standalone-shell.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. (() => {
  2. const frame = document.getElementById("zcode-visualization");
  3. if (!(frame instanceof HTMLIFrameElement)) {
  4. return;
  5. }
  6. let viewportHeight = globalThis.innerHeight;
  7. const storageKey = `zcode:visualization-widget-state-v2:${JSON.stringify([
  8. globalThis.location.pathname,
  9. globalThis.location.search,
  10. ])}`;
  11. const parseState = (serializedState) => {
  12. if (
  13. typeof serializedState !== "string" ||
  14. new TextEncoder().encode(serializedState).length > 16 * 1024
  15. ) {
  16. throw new TypeError("Widget state must be a JSON object of at most 16 KiB");
  17. }
  18. /** @type {unknown} */
  19. const state = JSON.parse(serializedState);
  20. if (
  21. state == null ||
  22. typeof state !== "object" ||
  23. Array.isArray(state) ||
  24. ("imageIds" in state && (!Array.isArray(state.imageIds) || state.imageIds.length > 0))
  25. ) {
  26. throw new TypeError("Widget state must be a JSON object");
  27. }
  28. const storedState = { modelContent: null, privateContent: null, ...state };
  29. const canonicalState = JSON.stringify(storedState, (_key, /** @type {unknown} */ value) => {
  30. if (typeof value === "number" && !Number.isFinite(value)) {
  31. throw new TypeError("Widget state must contain finite numbers");
  32. }
  33. return value;
  34. });
  35. if (new TextEncoder().encode(canonicalState).length > 16 * 1024) {
  36. throw new TypeError("Widget state must be a JSON object of at most 16 KiB");
  37. }
  38. return storedState;
  39. };
  40. let storage = null;
  41. let state = null;
  42. try {
  43. const localStorage = globalThis.localStorage;
  44. const probeKey = `${storageKey}:probe`;
  45. localStorage.setItem(probeKey, "1");
  46. localStorage.removeItem(probeKey);
  47. storage = localStorage;
  48. const savedState = storage.getItem(storageKey);
  49. if (savedState != null) {
  50. try {
  51. state = parseState(savedState);
  52. } catch {
  53. // Invalid saved state does not disable future writes.
  54. }
  55. }
  56. } catch {
  57. storage = null;
  58. }
  59. const initialGlobals = {
  60. widgetState: state,
  61. statePersistence: storage == null ? "none" : "local",
  62. };
  63. const channel = new MessageChannel();
  64. channel.port1.addEventListener("message", (event) => {
  65. const data = event.data;
  66. if (typeof data !== "object" || data == null) {
  67. return;
  68. }
  69. if (data.type === "widget-state-write") {
  70. if (!Number.isSafeInteger(data.id) || data.id <= 0) {
  71. return;
  72. }
  73. let ok = false;
  74. try {
  75. if (storage != null) {
  76. const state = parseState(data.state);
  77. storage.setItem(storageKey, JSON.stringify(state));
  78. ok = true;
  79. }
  80. } catch {
  81. // Storage denial, quota limits, and invalid state return a failed receipt.
  82. }
  83. channel.port1.postMessage({
  84. type: "widget-state-result",
  85. id: data.id,
  86. ok,
  87. });
  88. return;
  89. }
  90. if (data.type === "height") {
  91. const height = data.height;
  92. if (
  93. typeof height === "number" &&
  94. Number.isFinite(height) &&
  95. height >= 0 &&
  96. height <= 10_000
  97. ) {
  98. frame.style.height = Math.ceil(height) + "px";
  99. }
  100. return;
  101. }
  102. if (data.type === "scroll-to") {
  103. const top = data.top;
  104. if (
  105. typeof top === "number" &&
  106. Number.isFinite(top) &&
  107. top >= 0 &&
  108. globalThis.navigator.userActivation?.isActive === true
  109. ) {
  110. globalThis.scrollTo({
  111. top: Math.ceil(globalThis.scrollY + frame.getBoundingClientRect().top + top),
  112. });
  113. }
  114. return;
  115. }
  116. if (data.type === "open-external") {
  117. const rawHref = data.href;
  118. if (typeof rawHref !== "string") {
  119. return;
  120. }
  121. let href;
  122. try {
  123. const url = new URL(rawHref, document.baseURI);
  124. if (url.protocol !== "https:") {
  125. return;
  126. }
  127. href = url.href;
  128. } catch {
  129. return;
  130. }
  131. if (globalThis.navigator.userActivation?.isActive === true) {
  132. const anchor = document.createElement("a");
  133. anchor.href = href;
  134. anchor.rel = "noopener noreferrer";
  135. anchor.target = "_blank";
  136. document.body.appendChild(anchor);
  137. anchor.click();
  138. anchor.remove();
  139. }
  140. return;
  141. }
  142. if (data.type === "follow-up") {
  143. const prompt = data.prompt;
  144. if (typeof prompt !== "string" || globalThis.navigator.userActivation?.isActive !== true) {
  145. return;
  146. }
  147. const title = data.title;
  148. globalThis.prompt(typeof title === "string" ? title : prompt, prompt);
  149. }
  150. });
  151. channel.port1.start();
  152. const srcdoc = frame.dataset.srcdoc;
  153. if (srcdoc == null) {
  154. return;
  155. }
  156. globalThis.addEventListener("resize", () => {
  157. const height = Number.parseFloat(frame.style.height);
  158. if (!Number.isFinite(height) || height <= viewportHeight) {
  159. frame.style.removeProperty("height");
  160. }
  161. viewportHeight = globalThis.innerHeight;
  162. channel.port1.postMessage({ type: "measure" });
  163. });
  164. frame.addEventListener(
  165. "load",
  166. () => {
  167. frame.contentWindow?.postMessage({ type: "zcode-visualization-initialize" }, "*", [
  168. channel.port2,
  169. ]);
  170. },
  171. { once: true },
  172. );
  173. // Match the trusted bootstrap element, not the same text in an authored title.
  174. frame.srcdoc = srcdoc.replace(
  175. '<script type="application/json" id="zcode-visualization-widget-state">__ZCODE_VISUALIZATION_WIDGET_STATE__</script>',
  176. () =>
  177. '<script type="application/json" id="zcode-visualization-widget-state">' +
  178. JSON.stringify(initialGlobals).replaceAll("<", "\\u003c") +
  179. "</script>",
  180. );
  181. delete frame.dataset.srcdoc;
  182. })();