@mittwald/flow-remote-core 1.5.62 → 1.5.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/js/index-node.mjs +4 -1
  2. package/dist/js/index-node.mjs.map +1 -1
  3. package/dist/js/index.mjs +4 -1
  4. package/dist/js/index.mjs.map +1 -1
  5. package/dist/js/packages/remote-core/src/connection/allowedHostOrigins.mjs +6 -0
  6. package/dist/js/packages/remote-core/src/connection/allowedHostOrigins.mjs.map +1 -0
  7. package/dist/js/packages/remote-core/src/connection/connectHostRenderRoot.mjs +8 -5
  8. package/dist/js/packages/remote-core/src/connection/connectHostRenderRoot.mjs.map +1 -1
  9. package/dist/js/packages/remote-core/src/connection/connectRemoteIframe.mjs +51 -25
  10. package/dist/js/packages/remote-core/src/connection/connectRemoteIframe.mjs.map +1 -1
  11. package/dist/js/packages/remote-core/src/connection/hostOriginPatterns.mjs +69 -0
  12. package/dist/js/packages/remote-core/src/connection/hostOriginPatterns.mjs.map +1 -0
  13. package/dist/js/packages/remote-core/src/connection/index.mjs +4 -1
  14. package/dist/js/packages/remote-core/src/connection/originThreads.mjs +168 -0
  15. package/dist/js/packages/remote-core/src/connection/originThreads.mjs.map +1 -0
  16. package/dist/js/packages/remote-core/src/connection/toRelativePathname.mjs +20 -0
  17. package/dist/js/packages/remote-core/src/connection/toRelativePathname.mjs.map +1 -0
  18. package/dist/js/packages/remote-core/src/connection/types.mjs +2 -0
  19. package/dist/js/packages/remote-core/src/connection/types.mjs.map +1 -1
  20. package/dist/types/connection/allowedHostOrigins.d.ts +2 -0
  21. package/dist/types/connection/connectHostRenderRoot.d.ts +5 -4
  22. package/dist/types/connection/connectRemoteIframe.d.ts +8 -5
  23. package/dist/types/connection/hostOriginPatterns.d.ts +4 -0
  24. package/dist/types/connection/index.d.ts +3 -0
  25. package/dist/types/connection/originThreads.d.ts +21 -0
  26. package/dist/types/connection/toRelativePathname.d.ts +2 -0
  27. package/dist/types/connection/types.d.ts +10 -4
  28. package/package.json +8 -8
  29. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/ThreadIframe.mjs +0 -153
  30. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/ThreadIframe.mjs.map +0 -1
  31. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/ThreadNestedIframe.mjs +0 -77
  32. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/ThreadNestedIframe.mjs.map +0 -1
  33. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/window/ThreadNestedWindow.mjs +0 -119
  34. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/window/ThreadNestedWindow.mjs.map +0 -1
  35. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/window/ThreadWindow.mjs +0 -191
  36. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/window/ThreadWindow.mjs.map +0 -1
  37. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/window/shared.mjs +0 -6
  38. package/dist/js/node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/window/shared.mjs.map +0 -1
@@ -7,14 +7,17 @@ import { dataTransferTextSerializer } from "./packages/remote-core/src/serializa
7
7
  import { formDataSerializer } from "./packages/remote-core/src/serialization/serializers/formData.mjs";
8
8
  import { passwordPolicySerializer } from "./packages/remote-core/src/serialization/serializers/passwordPolicy.mjs";
9
9
  import { FlowThreadSerialization } from "./packages/remote-core/src/serialization/FlowThreadSerialization.mjs";
10
+ import { DEFAULT_ALLOWED_HOST_ORIGINS } from "./packages/remote-core/src/connection/allowedHostOrigins.mjs";
10
11
  import { Version } from "./packages/remote-core/src/connection/types.mjs";
12
+ import { createAllowedHostOriginMatcher } from "./packages/remote-core/src/connection/hostOriginPatterns.mjs";
11
13
  import { RemoteError } from "./packages/remote-core/src/error.mjs";
14
+ import { toRelativePathname } from "./packages/remote-core/src/connection/toRelativePathname.mjs";
12
15
  import { connectHostRenderRoot, connectHostRenderRootRef, connectRemoteReceiver } from "./packages/remote-core/src/connection/connectHostRenderRoot.mjs";
13
16
  import { componentRenderedEventSchema, parseReportedEvent, reportedEventSchema } from "./packages/remote-core/src/events/remoteEvents.mjs";
14
17
  import { connectRemoteIframe, connectRemoteIframeRef } from "./packages/remote-core/src/connection/connectRemoteIframe.mjs";
15
18
  import { RemoteElement, RemoteEvent, RemoteReceiver } from "./index.mjs";
16
19
  // src/index-node.ts
17
20
  if (!domShimApplied) throw new Error("remote-core DOM shim failed to initialize");
18
- export { FlowThreadSerialization, RemoteElement, RemoteError, RemoteEvent, RemoteReceiver, Serializer, Version, calendarDateSerializer, componentRenderedEventSchema, connectHostRenderRoot, connectHostRenderRootRef, connectRemoteIframe, connectRemoteIframeRef, connectRemoteReceiver, dataTransferTextSerializer, fileDeSerialize, fileListSerializer, fileSerialize, fileSerializer, formDataSerializer, isSerializedFile, parseReportedEvent, passwordPolicySerializer, reportedEventSchema };
21
+ export { DEFAULT_ALLOWED_HOST_ORIGINS, FlowThreadSerialization, RemoteElement, RemoteError, RemoteEvent, RemoteReceiver, Serializer, Version, calendarDateSerializer, componentRenderedEventSchema, connectHostRenderRoot, connectHostRenderRootRef, connectRemoteIframe, connectRemoteIframeRef, connectRemoteReceiver, createAllowedHostOriginMatcher, dataTransferTextSerializer, fileDeSerialize, fileListSerializer, fileSerialize, fileSerializer, formDataSerializer, isSerializedFile, parseReportedEvent, passwordPolicySerializer, reportedEventSchema, toRelativePathname };
19
22
 
20
23
  //# sourceMappingURL=index-node.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index-node.mjs","names":[],"sources":["../../src/index-node.ts"],"sourcesContent":["// The `node` export condition resolves here. The shim must be the very first\n// import so the DOM globals exist before any sibling module transitively pulls\n// in RemoteElement (which subclasses HTMLElement). Do NOT simplify this to a\n// bare `import \"./shim\"` or a plain `export * from \"./index\"`: Rollup then hoists\n// the remote-dom import ahead of the shim and SSR breaks with \"HTMLElement is\n// not defined\". Importing the shim as a used binding keeps it first.\nimport { domShimApplied } from \"./shim\";\nif (!domShimApplied) {\n throw new Error(\"remote-core DOM shim failed to initialize\");\n}\nexport * from \"./index\";\n"],"mappings":";;;;;;;;;;;;;;;;AAOA,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,2CAA2C"}
1
+ {"version":3,"file":"index-node.mjs","names":[],"sources":["../../src/index-node.ts"],"sourcesContent":["// The `node` export condition resolves here. The shim must be the very first\n// import so the DOM globals exist before any sibling module transitively pulls\n// in RemoteElement (which subclasses HTMLElement). Do NOT simplify this to a\n// bare `import \"./shim\"` or a plain `export * from \"./index\"`: Rollup then hoists\n// the remote-dom import ahead of the shim and SSR breaks with \"HTMLElement is\n// not defined\". Importing the shim as a used binding keeps it first.\nimport { domShimApplied } from \"./shim\";\nif (!domShimApplied) {\n throw new Error(\"remote-core DOM shim failed to initialize\");\n}\nexport * from \"./index\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAOA,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,2CAA2C"}
package/dist/js/index.mjs CHANGED
@@ -8,8 +8,11 @@ import { formDataSerializer } from "./packages/remote-core/src/serialization/ser
8
8
  import { passwordPolicySerializer } from "./packages/remote-core/src/serialization/serializers/passwordPolicy.mjs";
9
9
  import { FlowThreadSerialization } from "./packages/remote-core/src/serialization/FlowThreadSerialization.mjs";
10
10
  import "./packages/remote-core/src/serialization/index.mjs";
11
+ import { DEFAULT_ALLOWED_HOST_ORIGINS } from "./packages/remote-core/src/connection/allowedHostOrigins.mjs";
11
12
  import { Version } from "./packages/remote-core/src/connection/types.mjs";
13
+ import { createAllowedHostOriginMatcher } from "./packages/remote-core/src/connection/hostOriginPatterns.mjs";
12
14
  import { RemoteError } from "./packages/remote-core/src/error.mjs";
15
+ import { toRelativePathname } from "./packages/remote-core/src/connection/toRelativePathname.mjs";
13
16
  import { connectHostRenderRoot, connectHostRenderRootRef, connectRemoteReceiver } from "./packages/remote-core/src/connection/connectHostRenderRoot.mjs";
14
17
  import { componentRenderedEventSchema, parseReportedEvent, reportedEventSchema } from "./packages/remote-core/src/events/remoteEvents.mjs";
15
18
  import { connectRemoteIframe, connectRemoteIframeRef } from "./packages/remote-core/src/connection/connectRemoteIframe.mjs";
@@ -18,6 +21,6 @@ import { RemoteReceiver } from "@mittwald/remote-dom-core/receivers";
18
21
  import { RemoteElement, RemoteEvent } from "@mittwald/remote-dom-core/elements";
19
22
  // src/index.ts
20
23
  if (!domShimApplied) throw new Error("remote-core DOM shim failed to initialize");
21
- export { FlowThreadSerialization, RemoteElement, RemoteError, RemoteEvent, RemoteReceiver, Serializer, Version, calendarDateSerializer, componentRenderedEventSchema, connectHostRenderRoot, connectHostRenderRootRef, connectRemoteIframe, connectRemoteIframeRef, connectRemoteReceiver, dataTransferTextSerializer, fileDeSerialize, fileListSerializer, fileSerialize, fileSerializer, formDataSerializer, isSerializedFile, parseReportedEvent, passwordPolicySerializer, reportedEventSchema };
24
+ export { DEFAULT_ALLOWED_HOST_ORIGINS, FlowThreadSerialization, RemoteElement, RemoteError, RemoteEvent, RemoteReceiver, Serializer, Version, calendarDateSerializer, componentRenderedEventSchema, connectHostRenderRoot, connectHostRenderRootRef, connectRemoteIframe, connectRemoteIframeRef, connectRemoteReceiver, createAllowedHostOriginMatcher, dataTransferTextSerializer, fileDeSerialize, fileListSerializer, fileSerialize, fileSerializer, formDataSerializer, isSerializedFile, parseReportedEvent, passwordPolicySerializer, reportedEventSchema, toRelativePathname };
22
25
 
23
26
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import { domShimApplied } from \"./shim\";\n\nexport { RemoteReceiver } from \"@mittwald/remote-dom-core/receivers\";\nexport {\n RemoteElement,\n RemoteEvent,\n type RemoteElementConstructor,\n} from \"@mittwald/remote-dom-core/elements\";\nexport * from \"./serialization\";\nexport * from \"./connection\";\nexport * from \"./error\";\nexport * from \"./events/remoteEvents\";\n\n// The DOM shim above must be evaluated before RemoteElement (which subclasses\n// HTMLElement) is imported. Referencing the binding keeps the import from being\n// tree-shaken or reordered after the remote-dom re-export.\nif (!domShimApplied) {\n throw new Error(\"remote-core DOM shim failed to initialize\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgBA,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,2CAA2C"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import { domShimApplied } from \"./shim\";\n\nexport { RemoteReceiver } from \"@mittwald/remote-dom-core/receivers\";\nexport {\n RemoteElement,\n RemoteEvent,\n type RemoteElementConstructor,\n} from \"@mittwald/remote-dom-core/elements\";\nexport * from \"./serialization\";\nexport * from \"./connection\";\nexport * from \"./error\";\nexport * from \"./events/remoteEvents\";\n\n// The DOM shim above must be evaluated before RemoteElement (which subclasses\n// HTMLElement) is imported. Referencing the binding keeps the import from being\n// tree-shaken or reordered after the remote-dom re-export.\nif (!domShimApplied) {\n throw new Error(\"remote-core DOM shim failed to initialize\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,2CAA2C"}
@@ -0,0 +1,6 @@
1
+ // src/connection/allowedHostOrigins.ts
2
+ /** Entries are exact origins or patterns in the form `https://*.<domain>`. */
3
+ var DEFAULT_ALLOWED_HOST_ORIGINS = ["https://*.mittwald.de", "https://*.mittwald.systems"];
4
+ export { DEFAULT_ALLOWED_HOST_ORIGINS };
5
+
6
+ //# sourceMappingURL=allowedHostOrigins.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allowedHostOrigins.mjs","names":[],"sources":["../../../../../../src/connection/allowedHostOrigins.ts"],"sourcesContent":["/** Entries are exact origins or patterns in the form `https://*.<domain>`. */\nexport const DEFAULT_ALLOWED_HOST_ORIGINS: readonly string[] = [\n \"https://*.mittwald.de\",\n \"https://*.mittwald.systems\",\n];\n"],"mappings":";;AACA,IAAa,+BAAkD,CAC7D,yBACA,4BACF"}
@@ -1,7 +1,8 @@
1
- import { ThreadNestedIframe } from "../../../../node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/ThreadNestedIframe.mjs";
2
1
  import { FlowThreadSerialization } from "../serialization/FlowThreadSerialization.mjs";
3
2
  import { Version } from "./types.mjs";
4
3
  import { RemoteError } from "../error.mjs";
4
+ import { HostOriginThread } from "./originThreads.mjs";
5
+ import { toRelativePathname } from "./toRelativePathname.mjs";
5
6
  import "@mittwald/remote-dom-core/elements";
6
7
  // src/connection/connectHostRenderRoot.ts
7
8
  var incompatibleParentFrameError = () => new RemoteError("Could not find any compatible parent frame");
@@ -9,13 +10,15 @@ var connectRemoteReceiver = (root, receiverConnection) => import("@mittwald/remo
9
10
  new RemoteMutationObserver(receiverConnection).observe(root);
10
11
  });
11
12
  var connectHostRenderRoot = async (options) => {
12
- const { root, onPathnameChanged, onHostError, packageVersion } = options;
13
- const connection = new ThreadNestedIframe({
13
+ const { root, onPathnameChanged, onHostError, packageVersion, allowedHostOrigins } = options;
14
+ const connection = new HostOriginThread({
15
+ allowedHostOrigins,
14
16
  serialization: new FlowThreadSerialization(),
15
17
  exports: {
16
18
  render: (connection) => connectRemoteReceiver(root, connection),
17
19
  setPathname: async (pathname) => {
18
- onPathnameChanged?.(pathname);
20
+ const relativePathname = toRelativePathname(pathname);
21
+ if (relativePathname !== void 0) onPathnameChanged?.(relativePathname);
19
22
  },
20
23
  setHostError: async (error) => {
21
24
  onHostError?.(error);
@@ -25,7 +28,7 @@ var connectHostRenderRoot = async (options) => {
25
28
  if (connection.parent === window) throw incompatibleParentFrameError();
26
29
  try {
27
30
  await connection.imports.setIsReady({
28
- version: Version.v5,
31
+ version: Version.v6,
29
32
  packageVersion
30
33
  });
31
34
  if (typeof mwExtBridge !== "undefined") {
@@ -1 +1 @@
1
- {"version":3,"file":"connectHostRenderRoot.mjs","names":[],"sources":["../../../../../../src/connection/connectHostRenderRoot.ts"],"sourcesContent":["import {\n Version,\n type HostExports,\n type RemoteExports,\n type RemoteToHostConnection,\n} from \"@/connection/types\";\nimport { RemoteError } from \"@/error\";\nimport { FlowThreadSerialization } from \"@/serialization/FlowThreadSerialization\";\nimport { type RemoteConnection } from \"@mittwald/remote-dom-core/elements\";\nimport { ThreadNestedIframe } from \"@quilted/threads\";\n\ninterface Options {\n root: HTMLDivElement;\n onPathnameChanged?: (pathname: string) => void;\n onHostError?: (error: string) => void;\n packageVersion?: string;\n}\n\nconst incompatibleParentFrameError = () =>\n new RemoteError(\"Could not find any compatible parent frame\");\n\nexport const connectRemoteReceiver = (\n root: HTMLDivElement,\n receiverConnection: RemoteConnection,\n) =>\n import(\"@mittwald/remote-dom-core/elements\").then(\n ({ RemoteMutationObserver }) => {\n const observer = new RemoteMutationObserver(receiverConnection);\n observer.observe(root);\n },\n );\n\nexport const connectHostRenderRoot = async (\n options: Options,\n): Promise<RemoteToHostConnection> => {\n const { root, onPathnameChanged, onHostError, packageVersion } = options;\n\n const connection = new ThreadNestedIframe<HostExports, RemoteExports>({\n serialization: new FlowThreadSerialization(),\n exports: {\n render: (connection: RemoteConnection) =>\n connectRemoteReceiver(root, connection),\n setPathname: async (pathname) => {\n onPathnameChanged?.(pathname);\n },\n setHostError: async (error) => {\n onHostError?.(error);\n },\n },\n });\n\n if (connection.parent === window) {\n throw incompatibleParentFrameError();\n }\n\n try {\n await connection.imports.setIsReady({\n version: Version.v5,\n packageVersion,\n });\n\n if (typeof mwExtBridge !== \"undefined\") {\n mwExtBridge.connection = connection.imports;\n await mwExtBridge.readiness.setIsReady();\n }\n\n return connection;\n } catch (error) {\n if (\n error instanceof Error &&\n /No '.*' method is exported from this thread/.test(error.message)\n ) {\n throw incompatibleParentFrameError();\n }\n throw error;\n }\n};\n\nexport const connectHostRenderRootRef =\n (opts: Omit<Options, \"root\">) => (ref: HTMLDivElement | null) => {\n if (ref === null) {\n return;\n }\n if (\"__remoteConnection\" in ref) {\n return ref[\"__remoteConnection\"] as Promise<RemoteToHostConnection>;\n }\n\n const connection = connectHostRenderRoot({\n root: ref,\n ...opts,\n });\n Object.assign(ref, { __remoteConnection: connection });\n return connection;\n };\n"],"mappings":";;;;;;AAkBA,IAAM,qCACJ,IAAI,YAAY,4CAA4C;AAE9D,IAAa,yBACX,MACA,uBAEA,OAAO,qCAAqC,CAAC,MAC1C,EAAE,6BAA6B;CAE9B,IADqB,uBAAuB,kBAC5C,CAAA,CAAS,QAAQ,IAAI;AACvB,CACF;AAEF,IAAa,wBAAwB,OACnC,YACoC;CACpC,MAAM,EAAE,MAAM,mBAAmB,aAAa,mBAAmB;CAEjE,MAAM,aAAa,IAAI,mBAA+C;EACpE,eAAe,IAAI,wBAAwB;EAC3C,SAAS;GACP,SAAS,eACP,sBAAsB,MAAM,UAAU;GACxC,aAAa,OAAO,aAAa;IAC/B,oBAAoB,QAAQ;GAC9B;GACA,cAAc,OAAO,UAAU;IAC7B,cAAc,KAAK;GACrB;EACF;CACF,CAAC;CAED,IAAI,WAAW,WAAW,QACxB,MAAM,6BAA6B;CAGrC,IAAI;EACF,MAAM,WAAW,QAAQ,WAAW;GAClC,SAAS,QAAQ;GACjB;EACF,CAAC;EAED,IAAI,OAAO,gBAAgB,aAAa;GACtC,YAAY,aAAa,WAAW;GACpC,MAAM,YAAY,UAAU,WAAW;EACzC;EAEA,OAAO;CACT,SAAS,OAAO;EACd,IACE,iBAAiB,SACjB,8CAA8C,KAAK,MAAM,OAAO,GAEhE,MAAM,6BAA6B;EAErC,MAAM;CACR;AACF;AAEA,IAAa,4BACV,UAAiC,QAA+B;CAC/D,IAAI,QAAQ,MACV;CAEF,IAAI,wBAAwB,KAC1B,OAAO,IAAI;CAGb,MAAM,aAAa,sBAAsB;EACvC,MAAM;EACN,GAAG;CACL,CAAC;CACD,OAAO,OAAO,KAAK,EAAE,oBAAoB,WAAW,CAAC;CACrD,OAAO;AACT"}
1
+ {"version":3,"file":"connectHostRenderRoot.mjs","names":[],"sources":["../../../../../../src/connection/connectHostRenderRoot.ts"],"sourcesContent":["import {\n Version,\n type HostExports,\n type RemoteExports,\n type RemoteToHostConnection,\n} from \"@/connection/types\";\nimport { HostOriginThread } from \"@/connection/originThreads\";\nimport { toRelativePathname } from \"@/connection/toRelativePathname\";\nimport { RemoteError } from \"@/error\";\nimport { FlowThreadSerialization } from \"@/serialization/FlowThreadSerialization\";\nimport { type RemoteConnection } from \"@mittwald/remote-dom-core/elements\";\n\nexport interface ConnectHostRenderRootOptions {\n root: HTMLDivElement;\n onPathnameChanged?: (pathname: string) => void;\n onHostError?: (error: string) => void;\n packageVersion?: string;\n /** Additional host origins accepted by the remote app. */\n allowedHostOrigins?: string[];\n}\n\nconst incompatibleParentFrameError = () =>\n new RemoteError(\"Could not find any compatible parent frame\");\n\nexport const connectRemoteReceiver = (\n root: HTMLDivElement,\n receiverConnection: RemoteConnection,\n) =>\n import(\"@mittwald/remote-dom-core/elements\").then(\n ({ RemoteMutationObserver }) => {\n const observer = new RemoteMutationObserver(receiverConnection);\n observer.observe(root);\n },\n );\n\nexport const connectHostRenderRoot = async (\n options: ConnectHostRenderRootOptions,\n): Promise<RemoteToHostConnection> => {\n const {\n root,\n onPathnameChanged,\n onHostError,\n packageVersion,\n allowedHostOrigins,\n } = options;\n\n const connection = new HostOriginThread<HostExports, RemoteExports>({\n allowedHostOrigins,\n serialization: new FlowThreadSerialization(),\n exports: {\n render: (connection: RemoteConnection) =>\n connectRemoteReceiver(root, connection),\n setPathname: async (pathname) => {\n const relativePathname = toRelativePathname(pathname);\n if (relativePathname !== undefined) {\n onPathnameChanged?.(relativePathname);\n }\n },\n setHostError: async (error) => {\n onHostError?.(error);\n },\n },\n });\n\n if (connection.parent === window) {\n throw incompatibleParentFrameError();\n }\n\n try {\n await connection.imports.setIsReady({\n version: Version.v6,\n packageVersion,\n });\n\n if (typeof mwExtBridge !== \"undefined\") {\n mwExtBridge.connection = connection.imports;\n await mwExtBridge.readiness.setIsReady();\n }\n\n return connection;\n } catch (error) {\n if (\n error instanceof Error &&\n /No '.*' method is exported from this thread/.test(error.message)\n ) {\n throw incompatibleParentFrameError();\n }\n throw error;\n }\n};\n\nexport const connectHostRenderRootRef =\n (opts: Omit<ConnectHostRenderRootOptions, \"root\">) =>\n (ref: HTMLDivElement | null) => {\n if (ref === null) {\n return;\n }\n if (\"__remoteConnection\" in ref) {\n return ref[\"__remoteConnection\"] as Promise<RemoteToHostConnection>;\n }\n\n const connection = connectHostRenderRoot({\n root: ref,\n ...opts,\n });\n Object.assign(ref, { __remoteConnection: connection });\n return connection;\n };\n"],"mappings":";;;;;;;AAqBA,IAAM,qCACJ,IAAI,YAAY,4CAA4C;AAE9D,IAAa,yBACX,MACA,uBAEA,OAAO,qCAAqC,CAAC,MAC1C,EAAE,6BAA6B;CAE9B,IADqB,uBAAuB,kBAC5C,CAAA,CAAS,QAAQ,IAAI;AACvB,CACF;AAEF,IAAa,wBAAwB,OACnC,YACoC;CACpC,MAAM,EACJ,MACA,mBACA,aACA,gBACA,uBACE;CAEJ,MAAM,aAAa,IAAI,iBAA6C;EAClE;EACA,eAAe,IAAI,wBAAwB;EAC3C,SAAS;GACP,SAAS,eACP,sBAAsB,MAAM,UAAU;GACxC,aAAa,OAAO,aAAa;IAC/B,MAAM,mBAAmB,mBAAmB,QAAQ;IACpD,IAAI,qBAAqB,KAAA,GACvB,oBAAoB,gBAAgB;GAExC;GACA,cAAc,OAAO,UAAU;IAC7B,cAAc,KAAK;GACrB;EACF;CACF,CAAC;CAED,IAAI,WAAW,WAAW,QACxB,MAAM,6BAA6B;CAGrC,IAAI;EACF,MAAM,WAAW,QAAQ,WAAW;GAClC,SAAS,QAAQ;GACjB;EACF,CAAC;EAED,IAAI,OAAO,gBAAgB,aAAa;GACtC,YAAY,aAAa,WAAW;GACpC,MAAM,YAAY,UAAU,WAAW;EACzC;EAEA,OAAO;CACT,SAAS,OAAO;EACd,IACE,iBAAiB,SACjB,8CAA8C,KAAK,MAAM,OAAO,GAEhE,MAAM,6BAA6B;EAErC,MAAM;CACR;AACF;AAEA,IAAa,4BACV,UACA,QAA+B;CAC9B,IAAI,QAAQ,MACV;CAEF,IAAI,wBAAwB,KAC1B,OAAO,IAAI;CAGb,MAAM,aAAa,sBAAsB;EACvC,MAAM;EACN,GAAG;CACL,CAAC;CACD,OAAO,OAAO,KAAK,EAAE,oBAAoB,WAAW,CAAC;CACrD,OAAO;AACT"}
@@ -1,6 +1,7 @@
1
- import { ThreadIframe } from "../../../../node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/threads/ThreadIframe.mjs";
2
1
  import { FlowThreadSerialization } from "../serialization/FlowThreadSerialization.mjs";
3
2
  import { Version } from "./types.mjs";
3
+ import { RemoteError } from "../error.mjs";
4
+ import { RemoteOriginThread } from "./originThreads.mjs";
4
5
  import { parseReportedEvent } from "../events/remoteEvents.mjs";
5
6
  import { getWithMergedHostConfig } from "../ext-bridge/getWithMergedHostConfig.mjs";
6
7
  import { emptyImplementation } from "../ext-bridge/implementation.mjs";
@@ -9,43 +10,65 @@ var normalizeReadyEvent = (event) => {
9
10
  if (typeof event === "number") return { version: event };
10
11
  return event ?? { version: Version.v1 };
11
12
  };
13
+ var guardedHostExports = (exports, isReady, minRemoteVersion) => new Proxy(exports, { get(target, property, receiver) {
14
+ const value = Reflect.get(target, property, receiver);
15
+ if (typeof value !== "function") return value;
16
+ return async (...args) => {
17
+ if (!isReady()) throw new RemoteError(`Remote has not reported the required version ${minRemoteVersion}`);
18
+ return Reflect.apply(value, target, args);
19
+ };
20
+ } });
12
21
  var connectRemoteIframe = (opts) => {
13
- const { connection, iframe, onReady, onLoadingChanged, onError, onNavigationStateChanged, onDeprecation, onEvent, extBridgeImplementation: extBridgeImplementationProp = emptyImplementation, hostConfig } = opts;
22
+ const { connection, iframe, onReady, onLoadingChanged, onError, onNavigationStateChanged, onDeprecation, onEvent, extBridgeImplementation: extBridgeImplementationProp = emptyImplementation, hostConfig, remoteOrigin, minRemoteVersion } = opts;
14
23
  const extBridgeImplementation = {
15
- ...extBridgeImplementationProp,
24
+ getSessionToken: () => extBridgeImplementationProp.getSessionToken(),
16
25
  getConfig: getWithMergedHostConfig(extBridgeImplementationProp, hostConfig)
17
26
  };
27
+ let isRequiredVersionReady = minRemoteVersion === void 0;
28
+ let hasRendered = false;
29
+ const hostExportsWithoutReady = {
30
+ ...extBridgeImplementation,
31
+ setIsLoading: async (isLoading) => {
32
+ onLoadingChanged?.(isLoading);
33
+ },
34
+ setError: async (error) => {
35
+ onError?.(error);
36
+ },
37
+ setNavigationState: async (state) => {
38
+ onNavigationStateChanged?.(state);
39
+ },
40
+ reportDeprecation: async (message) => {
41
+ onDeprecation?.(message);
42
+ },
43
+ reportEvent: async (event) => {
44
+ const parsed = parseReportedEvent(event);
45
+ if (parsed) onEvent?.(parsed);
46
+ },
47
+ getHostConfig: async () => hostConfig
48
+ };
49
+ const exportsWithVersionRequirement = minRemoteVersion === void 0 ? hostExportsWithoutReady : guardedHostExports(hostExportsWithoutReady, () => isRequiredVersionReady, minRemoteVersion);
18
50
  const result = {
19
- thread: new ThreadIframe(iframe, {
51
+ thread: new RemoteOriginThread(iframe, {
52
+ remoteOrigin,
20
53
  serialization: new FlowThreadSerialization(),
21
54
  exports: {
22
- ...extBridgeImplementation,
55
+ ...exportsWithVersionRequirement,
23
56
  setIsReady: async (event) => {
24
57
  const readyEvent = normalizeReadyEvent(event);
58
+ if (minRemoteVersion !== void 0 && readyEvent.version < minRemoteVersion) {
59
+ onError?.(`Remote version ${readyEvent.version} is lower than the required version ${minRemoteVersion}`);
60
+ return;
61
+ }
25
62
  result.version = readyEvent.version;
63
+ isRequiredVersionReady = true;
26
64
  onReady?.({
27
65
  connection: result,
28
66
  remoteReadyEvent: readyEvent
29
67
  });
30
- },
31
- setIsLoading: async (isLoading) => {
32
- onLoadingChanged?.(isLoading);
33
- },
34
- setError: async (error) => {
35
- onError?.(error);
36
- },
37
- setNavigationState: async (state) => {
38
- onNavigationStateChanged?.(state);
39
- },
40
- reportDeprecation: async (message) => {
41
- onDeprecation?.(message);
42
- },
43
- reportEvent: async (event) => {
44
- const parsed = parseReportedEvent(event);
45
- if (parsed) onEvent?.(parsed);
46
- },
47
- getHostConfig: async () => {
48
- return hostConfig;
68
+ if (minRemoteVersion !== void 0 && !hasRendered) {
69
+ hasRendered = true;
70
+ result.thread.imports.render(connection);
71
+ }
49
72
  }
50
73
  }
51
74
  }),
@@ -58,7 +81,10 @@ var connectRemoteIframe = (opts) => {
58
81
  },
59
82
  version: 0
60
83
  };
61
- result.thread.imports.render(connection);
84
+ if (minRemoteVersion === void 0) {
85
+ hasRendered = true;
86
+ result.thread.imports.render(connection);
87
+ }
62
88
  return result;
63
89
  };
64
90
  var connectRemoteIframeRef = (opts) => (ref) => {
@@ -1 +1 @@
1
- {"version":3,"file":"connectRemoteIframe.mjs","names":[],"sources":["../../../../../../src/connection/connectRemoteIframe.ts"],"sourcesContent":["import {\n Version,\n type HostExports,\n type HostToRemoteConnection,\n type HostToRemoteConnectionReadyEvent,\n type NavigationState,\n type RemoteExports,\n type RemoteExtBridgeConnectionApi,\n type RemoteReadyEvent,\n type RemoteReadyEventInput,\n} from \"@/connection/types\";\nimport { parseReportedEvent, type ReportedEvent } from \"@/events/remoteEvents\";\nimport { getWithMergedHostConfig } from \"@/ext-bridge/getWithMergedHostConfig\";\nimport { emptyImplementation } from \"@/ext-bridge/implementation\";\nimport { FlowThreadSerialization } from \"@/serialization/FlowThreadSerialization\";\nimport type { HostConfig } from \"@mittwald/ext-bridge\";\nimport type { RemoteConnection } from \"@mittwald/remote-dom-core/elements\";\nimport { ThreadIframe } from \"@quilted/threads\";\n\ninterface Options {\n connection: RemoteConnection;\n iframe: HTMLIFrameElement;\n hostConfig: HostConfig;\n onReady?: (event: HostToRemoteConnectionReadyEvent) => void;\n onLoadingChanged?: (isLoading: boolean) => void;\n onError?: (error: string) => void;\n onNavigationStateChanged?: (state: NavigationState) => void;\n onDeprecation?: (message: string) => void;\n onEvent?: (event: ReportedEvent) => void;\n extBridgeImplementation?: RemoteExtBridgeConnectionApi;\n}\n\nconst normalizeReadyEvent = (\n event?: RemoteReadyEventInput,\n): RemoteReadyEvent => {\n if (typeof event === \"number\") {\n return {\n version: event,\n };\n }\n\n return (\n event ?? {\n version: Version.v1,\n }\n );\n};\n\nexport const connectRemoteIframe = (opts: Options): HostToRemoteConnection => {\n const {\n connection,\n iframe,\n onReady,\n onLoadingChanged,\n onError,\n onNavigationStateChanged,\n onDeprecation,\n onEvent,\n extBridgeImplementation: extBridgeImplementationProp = emptyImplementation,\n hostConfig,\n } = opts;\n\n const extBridgeImplementation = {\n ...extBridgeImplementationProp,\n getConfig: getWithMergedHostConfig(extBridgeImplementationProp, hostConfig),\n };\n\n const result: HostToRemoteConnection = {\n thread: new ThreadIframe<RemoteExports, HostExports>(iframe, {\n serialization: new FlowThreadSerialization(),\n exports: {\n ...extBridgeImplementation,\n setIsReady: async (event) => {\n const readyEvent = normalizeReadyEvent(event);\n result.version = readyEvent.version;\n onReady?.({\n connection: result,\n remoteReadyEvent: readyEvent,\n });\n },\n setIsLoading: async (isLoading: boolean) => {\n onLoadingChanged?.(isLoading);\n },\n setError: async (error: string) => {\n onError?.(error);\n },\n setNavigationState: async (state) => {\n onNavigationStateChanged?.(state);\n },\n reportDeprecation: async (message: string) => {\n onDeprecation?.(message);\n },\n reportEvent: async (event) => {\n const parsed = parseReportedEvent(event);\n if (parsed) {\n onEvent?.(parsed);\n }\n },\n getHostConfig: async () => {\n return hostConfig;\n },\n },\n }),\n updateHostPathname: (hostPathname?: string) => {\n if (hostPathname === undefined) {\n return;\n }\n\n if (result.version >= Version.v2) {\n result.thread.imports.setPathname(hostPathname);\n }\n },\n reportHostError: async (error) => {\n if (result.version >= Version.v5) {\n await result.thread.imports.setHostError(error);\n }\n },\n version: 0,\n };\n\n result.thread.imports.render(connection);\n return result;\n};\n\nexport const connectRemoteIframeRef =\n (opts: Omit<Options, \"iframe\">) => (ref: HTMLIFrameElement | null) => {\n if (!ref) {\n return;\n }\n\n if (\"__remoteConnection\" in ref) {\n return ref[\"__remoteConnection\"] as HostToRemoteConnection;\n }\n\n const connection = connectRemoteIframe({\n iframe: ref,\n ...opts,\n });\n Object.assign(ref, { __remoteConnection: connection });\n return connection;\n };\n"],"mappings":";;;;;;;AAgCA,IAAM,uBACJ,UACqB;CACrB,IAAI,OAAO,UAAU,UACnB,OAAO,EACL,SAAS,MACX;CAGF,OACE,SAAS,EACP,SAAS,QAAQ,GACnB;AAEJ;AAEA,IAAa,uBAAuB,SAA0C;CAC5E,MAAM,EACJ,YACA,QACA,SACA,kBACA,SACA,0BACA,eACA,SACA,yBAAyB,8BAA8B,qBACvD,eACE;CAEJ,MAAM,0BAA0B;EAC9B,GAAG;EACH,WAAW,wBAAwB,6BAA6B,UAAU;CAC5E;CAEA,MAAM,SAAiC;EACrC,QAAQ,IAAI,aAAyC,QAAQ;GAC3D,eAAe,IAAI,wBAAwB;GAC3C,SAAS;IACP,GAAG;IACH,YAAY,OAAO,UAAU;KAC3B,MAAM,aAAa,oBAAoB,KAAK;KAC5C,OAAO,UAAU,WAAW;KAC5B,UAAU;MACR,YAAY;MACZ,kBAAkB;KACpB,CAAC;IACH;IACA,cAAc,OAAO,cAAuB;KAC1C,mBAAmB,SAAS;IAC9B;IACA,UAAU,OAAO,UAAkB;KACjC,UAAU,KAAK;IACjB;IACA,oBAAoB,OAAO,UAAU;KACnC,2BAA2B,KAAK;IAClC;IACA,mBAAmB,OAAO,YAAoB;KAC5C,gBAAgB,OAAO;IACzB;IACA,aAAa,OAAO,UAAU;KAC5B,MAAM,SAAS,mBAAmB,KAAK;KACvC,IAAI,QACF,UAAU,MAAM;IAEpB;IACA,eAAe,YAAY;KACzB,OAAO;IACT;GACF;EACF,CAAC;EACD,qBAAqB,iBAA0B;GAC7C,IAAI,iBAAiB,KAAA,GACnB;GAGF,IAAI,OAAO,WAAW,QAAQ,IAC5B,OAAO,OAAO,QAAQ,YAAY,YAAY;EAElD;EACA,iBAAiB,OAAO,UAAU;GAChC,IAAI,OAAO,WAAW,QAAQ,IAC5B,MAAM,OAAO,OAAO,QAAQ,aAAa,KAAK;EAElD;EACA,SAAS;CACX;CAEA,OAAO,OAAO,QAAQ,OAAO,UAAU;CACvC,OAAO;AACT;AAEA,IAAa,0BACV,UAAmC,QAAkC;CACpE,IAAI,CAAC,KACH;CAGF,IAAI,wBAAwB,KAC1B,OAAO,IAAI;CAGb,MAAM,aAAa,oBAAoB;EACrC,QAAQ;EACR,GAAG;CACL,CAAC;CACD,OAAO,OAAO,KAAK,EAAE,oBAAoB,WAAW,CAAC;CACrD,OAAO;AACT"}
1
+ {"version":3,"file":"connectRemoteIframe.mjs","names":[],"sources":["../../../../../../src/connection/connectRemoteIframe.ts"],"sourcesContent":["import {\n Version,\n type HostExports,\n type HostToRemoteConnection,\n type HostToRemoteConnectionReadyEvent,\n type NavigationState,\n type RemoteExports,\n type RemoteExtBridgeConnectionApi,\n type RemoteReadyEvent,\n type RemoteReadyEventInput,\n} from \"@/connection/types\";\nimport { RemoteOriginThread } from \"@/connection/originThreads\";\nimport { RemoteError } from \"@/error\";\nimport { parseReportedEvent, type ReportedEvent } from \"@/events/remoteEvents\";\nimport { getWithMergedHostConfig } from \"@/ext-bridge/getWithMergedHostConfig\";\nimport { emptyImplementation } from \"@/ext-bridge/implementation\";\nimport { FlowThreadSerialization } from \"@/serialization/FlowThreadSerialization\";\nimport type { HostConfig } from \"@mittwald/ext-bridge\";\nimport type { RemoteConnection } from \"@mittwald/remote-dom-core/elements\";\n\nexport interface ConnectRemoteIframeOptions {\n connection: RemoteConnection;\n iframe: HTMLIFrameElement;\n hostConfig: HostConfig;\n onReady?: (event: HostToRemoteConnectionReadyEvent) => void;\n onLoadingChanged?: (isLoading: boolean) => void;\n onError?: (error: string) => void;\n onNavigationStateChanged?: (state: NavigationState) => void;\n onDeprecation?: (message: string) => void;\n onEvent?: (event: ReportedEvent) => void;\n extBridgeImplementation?: RemoteExtBridgeConnectionApi;\n /** Expected origin of the remote iframe. Defaults to the iframe URL origin. */\n remoteOrigin?: string;\n /** Minimum communication version required before rendering the remote app. */\n minRemoteVersion?: Version;\n}\n\nconst normalizeReadyEvent = (\n event?: RemoteReadyEventInput,\n): RemoteReadyEvent => {\n if (typeof event === \"number\") {\n return {\n version: event,\n };\n }\n\n return (\n event ?? {\n version: Version.v1,\n }\n );\n};\n\nconst guardedHostExports = <Exports extends object>(\n exports: Exports,\n isReady: () => boolean,\n minRemoteVersion: Version,\n): Exports =>\n new Proxy(exports, {\n get(target, property, receiver) {\n const value = Reflect.get(target, property, receiver);\n\n if (typeof value !== \"function\") {\n return value;\n }\n\n return async (...args: unknown[]) => {\n if (!isReady()) {\n throw new RemoteError(\n `Remote has not reported the required version ${minRemoteVersion}`,\n );\n }\n\n return Reflect.apply(value, target, args);\n };\n },\n });\n\nexport const connectRemoteIframe = (\n opts: ConnectRemoteIframeOptions,\n): HostToRemoteConnection => {\n const {\n connection,\n iframe,\n onReady,\n onLoadingChanged,\n onError,\n onNavigationStateChanged,\n onDeprecation,\n onEvent,\n extBridgeImplementation: extBridgeImplementationProp = emptyImplementation,\n hostConfig,\n remoteOrigin,\n minRemoteVersion,\n } = opts;\n\n const extBridgeImplementation = {\n getSessionToken: () => extBridgeImplementationProp.getSessionToken(),\n getConfig: getWithMergedHostConfig(extBridgeImplementationProp, hostConfig),\n };\n\n let isRequiredVersionReady = minRemoteVersion === undefined;\n let hasRendered = false;\n\n const hostExportsWithoutReady = {\n ...extBridgeImplementation,\n setIsLoading: async (isLoading: boolean) => {\n onLoadingChanged?.(isLoading);\n },\n setError: async (error: string) => {\n onError?.(error);\n },\n setNavigationState: async (state: NavigationState) => {\n onNavigationStateChanged?.(state);\n },\n reportDeprecation: async (message: string) => {\n onDeprecation?.(message);\n },\n reportEvent: async (event: ReportedEvent) => {\n const parsed = parseReportedEvent(event);\n if (parsed) {\n onEvent?.(parsed);\n }\n },\n getHostConfig: async () => hostConfig,\n };\n\n const exportsWithVersionRequirement =\n minRemoteVersion === undefined\n ? hostExportsWithoutReady\n : guardedHostExports(\n hostExportsWithoutReady,\n () => isRequiredVersionReady,\n minRemoteVersion,\n );\n\n const result: HostToRemoteConnection = {\n thread: new RemoteOriginThread<RemoteExports, HostExports>(iframe, {\n remoteOrigin,\n serialization: new FlowThreadSerialization(),\n exports: {\n ...exportsWithVersionRequirement,\n setIsReady: async (event) => {\n const readyEvent = normalizeReadyEvent(event);\n\n if (\n minRemoteVersion !== undefined &&\n readyEvent.version < minRemoteVersion\n ) {\n onError?.(\n `Remote version ${readyEvent.version} is lower than the required version ${minRemoteVersion}`,\n );\n return;\n }\n\n result.version = readyEvent.version;\n isRequiredVersionReady = true;\n onReady?.({\n connection: result,\n remoteReadyEvent: readyEvent,\n });\n\n if (minRemoteVersion !== undefined && !hasRendered) {\n hasRendered = true;\n void result.thread.imports.render(connection);\n }\n },\n },\n }),\n updateHostPathname: (hostPathname?: string) => {\n if (hostPathname === undefined) {\n return;\n }\n\n if (result.version >= Version.v2) {\n result.thread.imports.setPathname(hostPathname);\n }\n },\n reportHostError: async (error) => {\n if (result.version >= Version.v5) {\n await result.thread.imports.setHostError(error);\n }\n },\n version: 0,\n };\n\n if (minRemoteVersion === undefined) {\n hasRendered = true;\n void result.thread.imports.render(connection);\n }\n return result;\n};\n\nexport const connectRemoteIframeRef =\n (opts: Omit<ConnectRemoteIframeOptions, \"iframe\">) =>\n (ref: HTMLIFrameElement | null) => {\n if (!ref) {\n return;\n }\n\n if (\"__remoteConnection\" in ref) {\n return ref[\"__remoteConnection\"] as HostToRemoteConnection;\n }\n\n const connection = connectRemoteIframe({\n iframe: ref,\n ...opts,\n });\n Object.assign(ref, { __remoteConnection: connection });\n return connection;\n };\n"],"mappings":";;;;;;;;AAqCA,IAAM,uBACJ,UACqB;CACrB,IAAI,OAAO,UAAU,UACnB,OAAO,EACL,SAAS,MACX;CAGF,OACE,SAAS,EACP,SAAS,QAAQ,GACnB;AAEJ;AAEA,IAAM,sBACJ,SACA,SACA,qBAEA,IAAI,MA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,WAAW,QAAQ,sCAAsC,kBAC7E;MACA;KACF;KAEA,OAAO,UAAU,WAAW;KAC5B,yBAAyB;KACzB,UAAU;MACR,YAAY;MACZ,kBAAkB;KACpB,CAAC;KAED,IAAI,qBAAqB,KAAA,KAAa,CAAC,aAAa;MAClD,cAAc;MACd,OAAY,OAAO,QAAQ,OAAO,UAAU;KAC9C;IACF;GACF;EACF,CAAC;EACD,qBAAqB,iBAA0B;GAC7C,IAAI,iBAAiB,KAAA,GACnB;GAGF,IAAI,OAAO,WAAW,QAAQ,IAC5B,OAAO,OAAO,QAAQ,YAAY,YAAY;EAElD;EACA,iBAAiB,OAAO,UAAU;GAChC,IAAI,OAAO,WAAW,QAAQ,IAC5B,MAAM,OAAO,OAAO,QAAQ,aAAa,KAAK;EAElD;EACA,SAAS;CACX;CAEA,IAAI,qBAAqB,KAAA,GAAW;EAClC,cAAc;EACd,OAAY,OAAO,QAAQ,OAAO,UAAU;CAC9C;CACA,OAAO;AACT;AAEA,IAAa,0BACV,UACA,QAAkC;CACjC,IAAI,CAAC,KACH;CAGF,IAAI,wBAAwB,KAC1B,OAAO,IAAI;CAGb,MAAM,aAAa,oBAAoB;EACrC,QAAQ;EACR,GAAG;CACL,CAAC;CACD,OAAO,OAAO,KAAK,EAAE,oBAAoB,WAAW,CAAC;CACrD,OAAO;AACT"}
@@ -0,0 +1,69 @@
1
+ // src/connection/hostOriginPatterns.ts
2
+ var WILDCARD_LABEL = "wildcard";
3
+ var WILDCARD_PATTERN = /^([a-zA-Z][a-zA-Z\d+.-]*):\/\/\*\.([^/:?#\\@]+)(?::(\d+))?$/;
4
+ var parseOrigin = (value) => {
5
+ try {
6
+ const url = new URL(value);
7
+ if (url.origin === "null") return;
8
+ return {
9
+ origin: url.origin,
10
+ protocol: url.protocol,
11
+ hostname: url.hostname.toLowerCase(),
12
+ port: url.port
13
+ };
14
+ } catch {
15
+ return;
16
+ }
17
+ };
18
+ var parseWildcardPattern = (value) => {
19
+ if (value !== value.trim()) return;
20
+ const match = WILDCARD_PATTERN.exec(value);
21
+ if (!match) return;
22
+ const [, scheme, domain, port] = match;
23
+ if (!scheme || !domain) return;
24
+ try {
25
+ const url = new URL(`${scheme}://${WILDCARD_LABEL}.${domain}${port ? `:${port}` : ""}`);
26
+ const hostnamePrefix = `${WILDCARD_LABEL}.`;
27
+ if (url.origin === "null" || url.username || url.password || !url.hostname.toLowerCase().startsWith(hostnamePrefix)) return;
28
+ const hostname = url.hostname.toLowerCase().slice(hostnamePrefix.length);
29
+ if (!hostname || hostname.includes("*")) return;
30
+ return {
31
+ protocol: url.protocol,
32
+ hostname,
33
+ port: url.port
34
+ };
35
+ } catch {
36
+ return;
37
+ }
38
+ };
39
+ var matchesWildcardPattern = (candidate, pattern) => {
40
+ if (candidate.protocol !== pattern.protocol || candidate.port !== pattern.port) return false;
41
+ const hostnameSuffix = `.${pattern.hostname}`;
42
+ if (!candidate.hostname.endsWith(hostnameSuffix)) return false;
43
+ return candidate.hostname.slice(0, -hostnameSuffix.length).split(".").every((label) => label.length > 0);
44
+ };
45
+ /** Normalizes a non-opaque host origin. */
46
+ var normalizeHostOrigin = (value) => parseOrigin(value)?.origin;
47
+ /** Creates a matcher for exact and wildcard allowed host origins. */
48
+ var createAllowedHostOriginMatcher = (allowedHostOrigins) => {
49
+ const exactOrigins = /* @__PURE__ */ new Set();
50
+ const wildcardPatterns = [];
51
+ for (const value of allowedHostOrigins) {
52
+ if (value.includes("*")) {
53
+ const pattern = parseWildcardPattern(value);
54
+ if (pattern) wildcardPatterns.push(pattern);
55
+ continue;
56
+ }
57
+ const origin = normalizeHostOrigin(value);
58
+ if (origin) exactOrigins.add(origin);
59
+ }
60
+ return (candidateOrigin) => {
61
+ const candidate = parseOrigin(candidateOrigin);
62
+ if (!candidate) return false;
63
+ if (exactOrigins.has(candidate.origin)) return true;
64
+ return wildcardPatterns.some((pattern) => matchesWildcardPattern(candidate, pattern));
65
+ };
66
+ };
67
+ export { createAllowedHostOriginMatcher, normalizeHostOrigin };
68
+
69
+ //# sourceMappingURL=hostOriginPatterns.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hostOriginPatterns.mjs","names":[],"sources":["../../../../../../src/connection/hostOriginPatterns.ts"],"sourcesContent":["interface ParsedOrigin {\n origin: string;\n protocol: string;\n hostname: string;\n port: string;\n}\n\ninterface WildcardOriginPattern {\n protocol: string;\n hostname: string;\n port: string;\n}\n\nconst WILDCARD_LABEL = \"wildcard\";\nconst WILDCARD_PATTERN =\n /^([a-zA-Z][a-zA-Z\\d+.-]*):\\/\\/\\*\\.([^/:?#\\\\@]+)(?::(\\d+))?$/;\n\nconst parseOrigin = (value: string): ParsedOrigin | undefined => {\n try {\n const url = new URL(value);\n if (url.origin === \"null\") {\n return undefined;\n }\n\n return {\n origin: url.origin,\n protocol: url.protocol,\n hostname: url.hostname.toLowerCase(),\n port: url.port,\n };\n } catch {\n return undefined;\n }\n};\n\nconst parseWildcardPattern = (\n value: string,\n): WildcardOriginPattern | undefined => {\n if (value !== value.trim()) {\n return undefined;\n }\n\n const match = WILDCARD_PATTERN.exec(value);\n if (!match) {\n return undefined;\n }\n\n const [, scheme, domain, port] = match;\n if (!scheme || !domain) {\n return undefined;\n }\n\n try {\n const url = new URL(\n `${scheme}://${WILDCARD_LABEL}.${domain}${port ? `:${port}` : \"\"}`,\n );\n const hostnamePrefix = `${WILDCARD_LABEL}.`;\n\n if (\n url.origin === \"null\" ||\n url.username ||\n url.password ||\n !url.hostname.toLowerCase().startsWith(hostnamePrefix)\n ) {\n return undefined;\n }\n\n const hostname = url.hostname.toLowerCase().slice(hostnamePrefix.length);\n if (!hostname || hostname.includes(\"*\")) {\n return undefined;\n }\n\n return {\n protocol: url.protocol,\n hostname,\n port: url.port,\n };\n } catch {\n return undefined;\n }\n};\n\nconst matchesWildcardPattern = (\n candidate: ParsedOrigin,\n pattern: WildcardOriginPattern,\n): boolean => {\n if (\n candidate.protocol !== pattern.protocol ||\n candidate.port !== pattern.port\n ) {\n return false;\n }\n\n const hostnameSuffix = `.${pattern.hostname}`;\n if (!candidate.hostname.endsWith(hostnameSuffix)) {\n return false;\n }\n\n const subdomain = candidate.hostname.slice(0, -hostnameSuffix.length);\n return subdomain.split(\".\").every((label) => label.length > 0);\n};\n\n/** Normalizes a non-opaque host origin. */\nexport const normalizeHostOrigin = (value: string): string | undefined =>\n parseOrigin(value)?.origin;\n\n/** Creates a matcher for exact and wildcard allowed host origins. */\nexport const createAllowedHostOriginMatcher = (\n allowedHostOrigins: readonly string[],\n) => {\n const exactOrigins = new Set<string>();\n const wildcardPatterns: WildcardOriginPattern[] = [];\n\n for (const value of allowedHostOrigins) {\n if (value.includes(\"*\")) {\n const pattern = parseWildcardPattern(value);\n if (pattern) {\n wildcardPatterns.push(pattern);\n }\n continue;\n }\n\n const origin = normalizeHostOrigin(value);\n if (origin) {\n exactOrigins.add(origin);\n }\n }\n\n return (candidateOrigin: string): boolean => {\n const candidate = parseOrigin(candidateOrigin);\n if (!candidate) {\n return false;\n }\n\n if (exactOrigins.has(candidate.origin)) {\n return true;\n }\n\n return wildcardPatterns.some((pattern) =>\n matchesWildcardPattern(candidate, pattern),\n );\n };\n};\n"],"mappings":";AAaA,IAAM,iBAAiB;AACvB,IAAM,mBACJ;AAEF,IAAM,eAAe,UAA4C;CAC/D,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,KAAK;EACzB,IAAI,IAAI,WAAW,QACjB;EAGF,OAAO;GACL,QAAQ,IAAI;GACZ,UAAU,IAAI;GACd,UAAU,IAAI,SAAS,YAAY;GACnC,MAAM,IAAI;EACZ;CACF,QAAQ;EACN;CACF;AACF;AAEA,IAAM,wBACJ,UACsC;CACtC,IAAI,UAAU,MAAM,KAAK,GACvB;CAGF,MAAM,QAAQ,iBAAiB,KAAK,KAAK;CACzC,IAAI,CAAC,OACH;CAGF,MAAM,GAAG,QAAQ,QAAQ,QAAQ;CACjC,IAAI,CAAC,UAAU,CAAC,QACd;CAGF,IAAI;EACF,MAAM,MAAM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AiB,MAAM,YAC5B,uBAAuB,WAAW,OAAO,CAC3C;CACF;AACF"}
@@ -1,4 +1,7 @@
1
+ import { DEFAULT_ALLOWED_HOST_ORIGINS } from "./allowedHostOrigins.mjs";
1
2
  import { Version } from "./types.mjs";
3
+ import { createAllowedHostOriginMatcher } from "./hostOriginPatterns.mjs";
4
+ import { toRelativePathname } from "./toRelativePathname.mjs";
2
5
  import { connectHostRenderRoot, connectHostRenderRootRef, connectRemoteReceiver } from "./connectHostRenderRoot.mjs";
3
6
  import { connectRemoteIframe, connectRemoteIframeRef } from "./connectRemoteIframe.mjs";
4
- export { Version, connectHostRenderRoot, connectHostRenderRootRef, connectRemoteIframe, connectRemoteIframeRef, connectRemoteReceiver };
7
+ export { DEFAULT_ALLOWED_HOST_ORIGINS, Version, connectHostRenderRoot, connectHostRenderRootRef, connectRemoteIframe, connectRemoteIframeRef, connectRemoteReceiver, createAllowedHostOriginMatcher, toRelativePathname };
@@ -0,0 +1,168 @@
1
+ import { Thread } from "../../../../node_modules/.pnpm/@quilted_threads@3.3.1_patch_hash_fa797cdfb8346ba050fd5d6367ccd451df47806c6ea34421e45e8_e52b779d86bc12aeba80f9d7805f6a15/node_modules/@quilted/threads/build/esm/Thread.mjs";
2
+ import { DEFAULT_ALLOWED_HOST_ORIGINS } from "./allowedHostOrigins.mjs";
3
+ import { createAllowedHostOriginMatcher, normalizeHostOrigin } from "./hostOriginPatterns.mjs";
4
+ import { RemoteError } from "../error.mjs";
5
+ // src/connection/originThreads.ts
6
+ var CHECK_MESSAGE = "quilt.threads.ping";
7
+ var RESPONSE_MESSAGE = "quilt.threads.pong";
8
+ var hostOriginMessageTarget = (parent, { allowedHostOrigins: additionalOrigins = [] } = {}) => {
9
+ const warnedOrigins = /* @__PURE__ */ new Set();
10
+ const isAllowedHostOrigin = createAllowedHostOriginMatcher([
11
+ ...DEFAULT_ALLOWED_HOST_ORIGINS,
12
+ window.location.origin,
13
+ ...additionalOrigins
14
+ ]);
15
+ const ancestorOriginValue = window.location.ancestorOrigins?.[0];
16
+ const ancestorOrigin = ancestorOriginValue ? normalizeHostOrigin(ancestorOriginValue) : void 0;
17
+ if (ancestorOriginValue && (!ancestorOrigin || !isAllowedHostOrigin(ancestorOrigin))) {
18
+ warnedOrigins.add(ancestorOriginValue);
19
+ console.warn(`Host origin ${ancestorOriginValue} is not an allowed host origin. Add it to allowedHostOrigins to connect.`);
20
+ throw new RemoteError("Host origin is not allowed");
21
+ }
22
+ let hostOrigin = ancestorOrigin;
23
+ const pendingMessages = [];
24
+ const post = (message, origin, transferables) => parent.postMessage(message, origin, transferables ?? []);
25
+ const flush = () => {
26
+ if (!hostOrigin) return;
27
+ for (const { message, transferables } of pendingMessages.splice(0)) post(message, hostOrigin, transferables);
28
+ };
29
+ const accept = (event) => {
30
+ if (event.source !== parent) return false;
31
+ if (!isAllowedHostOrigin(event.origin)) {
32
+ if (!warnedOrigins.has(event.origin)) {
33
+ warnedOrigins.add(event.origin);
34
+ console.warn(`Ignored a message from host origin ${event.origin}: it is not an allowed host origin. Add it to allowedHostOrigins to connect.`);
35
+ }
36
+ return false;
37
+ }
38
+ if (hostOrigin && event.origin !== hostOrigin) {
39
+ if (!warnedOrigins.has(event.origin)) {
40
+ warnedOrigins.add(event.origin);
41
+ console.warn(`Ignored a message from host origin ${event.origin}: the connection uses ${hostOrigin}.`);
42
+ }
43
+ return false;
44
+ }
45
+ hostOrigin ??= event.origin;
46
+ return true;
47
+ };
48
+ let hasAnnouncedReady = false;
49
+ const announceReady = () => {
50
+ if (hasAnnouncedReady) return;
51
+ hasAnnouncedReady = true;
52
+ post(RESPONSE_MESSAGE, hostOrigin ?? "*");
53
+ };
54
+ if (document.readyState === "complete") announceReady();
55
+ else document.addEventListener("readystatechange", () => {
56
+ if (document.readyState === "complete") announceReady();
57
+ });
58
+ return {
59
+ send(message, transferables) {
60
+ if (!hostOrigin) {
61
+ pendingMessages.push({
62
+ message,
63
+ transferables
64
+ });
65
+ return;
66
+ }
67
+ post(message, hostOrigin, transferables);
68
+ },
69
+ listen(listener, { signal }) {
70
+ window.addEventListener("message", (event) => {
71
+ if (!accept(event)) return;
72
+ if (event.data === CHECK_MESSAGE) {
73
+ post(RESPONSE_MESSAGE, event.origin);
74
+ flush();
75
+ return;
76
+ }
77
+ flush();
78
+ listener(event.data);
79
+ }, { signal });
80
+ }
81
+ };
82
+ };
83
+ var resolvedRemoteOrigin = (iframe, remoteOrigin) => {
84
+ const configuredOrigin = remoteOrigin?.trim();
85
+ const iframeSource = iframe.getAttribute("src")?.trim();
86
+ if (!configuredOrigin && !iframeSource) throw new RemoteError("Remote origin could not be determined");
87
+ try {
88
+ const origin = configuredOrigin ? new URL(configuredOrigin).origin : new URL(iframe.src, document.baseURI).origin;
89
+ if (origin === "null") throw new RemoteError("Remote origin could not be determined");
90
+ return origin;
91
+ } catch (error) {
92
+ if (error instanceof RemoteError) throw error;
93
+ throw new RemoteError("Remote origin could not be determined");
94
+ }
95
+ };
96
+ var remoteOriginMessageTarget = (iframe, remoteOrigin) => {
97
+ const expectedOrigin = resolvedRemoteOrigin(iframe, remoteOrigin);
98
+ const remoteWindow = iframe.contentWindow;
99
+ if (!remoteWindow) throw new RemoteError("Remote window could not be determined");
100
+ const warnedOrigins = /* @__PURE__ */ new Set();
101
+ let connected = false;
102
+ let shouldAnswerResponse = true;
103
+ const pendingMessages = [];
104
+ const post = (message, transferables) => remoteWindow.postMessage(message, expectedOrigin, transferables ?? []);
105
+ const accept = (event) => {
106
+ if (event.source !== remoteWindow) return false;
107
+ if (event.origin !== expectedOrigin) {
108
+ if (!warnedOrigins.has(event.origin)) {
109
+ warnedOrigins.add(event.origin);
110
+ console.warn(`Ignored a message from remote origin ${event.origin}: expected ${expectedOrigin}.`);
111
+ }
112
+ return false;
113
+ }
114
+ return true;
115
+ };
116
+ const responseController = new AbortController();
117
+ if (typeof iframe.addEventListener === "function") iframe.addEventListener("load", () => {
118
+ shouldAnswerResponse = true;
119
+ }, { signal: responseController.signal });
120
+ window.addEventListener("message", (event) => {
121
+ if (!accept(event) || event.data !== RESPONSE_MESSAGE) return;
122
+ if (shouldAnswerResponse) {
123
+ shouldAnswerResponse = false;
124
+ post(CHECK_MESSAGE);
125
+ }
126
+ if (connected) return;
127
+ connected = true;
128
+ for (const { message, transferables } of pendingMessages.splice(0)) post(message, transferables);
129
+ }, { signal: responseController.signal });
130
+ post(CHECK_MESSAGE);
131
+ return {
132
+ send(message, transferables) {
133
+ if (!connected) {
134
+ pendingMessages.push({
135
+ message,
136
+ transferables
137
+ });
138
+ return;
139
+ }
140
+ post(message, transferables);
141
+ },
142
+ listen(listener, { signal }) {
143
+ if (signal?.aborted) responseController.abort();
144
+ else signal?.addEventListener("abort", () => responseController.abort(), { once: true });
145
+ window.addEventListener("message", (event) => {
146
+ if (!accept(event) || event.data === RESPONSE_MESSAGE) return;
147
+ listener(event.data);
148
+ }, { signal });
149
+ }
150
+ };
151
+ };
152
+ var HostOriginThread = class extends Thread {
153
+ parent;
154
+ constructor({ parent = globalThis.parent, allowedHostOrigins, ...options } = {}) {
155
+ super(hostOriginMessageTarget(parent, { allowedHostOrigins }), options);
156
+ this.parent = parent;
157
+ }
158
+ };
159
+ var RemoteOriginThread = class extends Thread {
160
+ iframe;
161
+ constructor(iframe, { remoteOrigin, ...options }) {
162
+ super(remoteOriginMessageTarget(iframe, remoteOrigin), options);
163
+ this.iframe = iframe;
164
+ }
165
+ };
166
+ export { HostOriginThread, RemoteOriginThread, hostOriginMessageTarget, remoteOriginMessageTarget };
167
+
168
+ //# sourceMappingURL=originThreads.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"originThreads.mjs","names":[],"sources":["../../../../../../src/connection/originThreads.ts"],"sourcesContent":["import { DEFAULT_ALLOWED_HOST_ORIGINS } from \"@/connection/allowedHostOrigins\";\nimport {\n createAllowedHostOriginMatcher,\n normalizeHostOrigin,\n} from \"@/connection/hostOriginPatterns\";\nimport { RemoteError } from \"@/error\";\nimport {\n Thread,\n type ThreadMessageTarget,\n type ThreadOptions,\n} from \"@quilted/threads\";\n\nconst CHECK_MESSAGE = \"quilt.threads.ping\";\nconst RESPONSE_MESSAGE = \"quilt.threads.pong\";\n\ninterface HostOriginTargetOptions {\n allowedHostOrigins?: readonly string[];\n}\n\nexport const hostOriginMessageTarget = (\n parent: Window,\n { allowedHostOrigins: additionalOrigins = [] }: HostOriginTargetOptions = {},\n): ThreadMessageTarget => {\n const warnedOrigins = new Set<string>();\n const isAllowedHostOrigin = createAllowedHostOriginMatcher([\n ...DEFAULT_ALLOWED_HOST_ORIGINS,\n window.location.origin,\n ...additionalOrigins,\n ]);\n const ancestorOriginValue = window.location.ancestorOrigins?.[0];\n const ancestorOrigin = ancestorOriginValue\n ? normalizeHostOrigin(ancestorOriginValue)\n : undefined;\n\n if (\n ancestorOriginValue &&\n (!ancestorOrigin || !isAllowedHostOrigin(ancestorOrigin))\n ) {\n warnedOrigins.add(ancestorOriginValue);\n console.warn(\n `Host origin ${ancestorOriginValue} is not an allowed host origin. Add it to allowedHostOrigins to connect.`,\n );\n throw new RemoteError(\"Host origin is not allowed\");\n }\n\n let hostOrigin = ancestorOrigin;\n const pendingMessages: {\n message: unknown;\n transferables?: Transferable[];\n }[] = [];\n\n const post = (\n message: unknown,\n origin: string,\n transferables?: Transferable[],\n ) => parent.postMessage(message, origin, transferables ?? []);\n\n const flush = () => {\n if (!hostOrigin) {\n return;\n }\n\n for (const { message, transferables } of pendingMessages.splice(0)) {\n post(message, hostOrigin, transferables);\n }\n };\n\n const accept = (event: MessageEvent) => {\n if (event.source !== parent) {\n return false;\n }\n\n if (!isAllowedHostOrigin(event.origin)) {\n if (!warnedOrigins.has(event.origin)) {\n warnedOrigins.add(event.origin);\n console.warn(\n `Ignored a message from host origin ${event.origin}: it is not an allowed host origin. Add it to allowedHostOrigins to connect.`,\n );\n }\n return false;\n }\n\n if (hostOrigin && event.origin !== hostOrigin) {\n if (!warnedOrigins.has(event.origin)) {\n warnedOrigins.add(event.origin);\n console.warn(\n `Ignored a message from host origin ${event.origin}: the connection uses ${hostOrigin}.`,\n );\n }\n return false;\n }\n\n hostOrigin ??= event.origin;\n return true;\n };\n\n let hasAnnouncedReady = false;\n const announceReady = () => {\n if (hasAnnouncedReady) {\n return;\n }\n hasAnnouncedReady = true;\n\n post(RESPONSE_MESSAGE, hostOrigin ?? \"*\");\n };\n\n if (document.readyState === \"complete\") {\n announceReady();\n } else {\n document.addEventListener(\"readystatechange\", () => {\n if (document.readyState === \"complete\") {\n announceReady();\n }\n });\n }\n\n return {\n send(message, transferables) {\n if (!hostOrigin) {\n pendingMessages.push({ message, transferables });\n return;\n }\n\n post(message, hostOrigin, transferables);\n },\n listen(listener, { signal }) {\n window.addEventListener(\n \"message\",\n (event) => {\n if (!accept(event)) {\n return;\n }\n\n if (event.data === CHECK_MESSAGE) {\n post(RESPONSE_MESSAGE, event.origin);\n flush();\n return;\n }\n\n flush();\n listener(event.data);\n },\n { signal },\n );\n },\n };\n};\n\nconst resolvedRemoteOrigin = (\n iframe: HTMLIFrameElement,\n remoteOrigin?: string,\n) => {\n const configuredOrigin = remoteOrigin?.trim();\n const iframeSource = iframe.getAttribute(\"src\")?.trim();\n\n if (!configuredOrigin && !iframeSource) {\n throw new RemoteError(\"Remote origin could not be determined\");\n }\n\n try {\n const origin = configuredOrigin\n ? new URL(configuredOrigin).origin\n : new URL(iframe.src, document.baseURI).origin;\n\n if (origin === \"null\") {\n throw new RemoteError(\"Remote origin could not be determined\");\n }\n\n return origin;\n } catch (error) {\n if (error instanceof RemoteError) {\n throw error;\n }\n throw new RemoteError(\"Remote origin could not be determined\");\n }\n};\n\nexport const remoteOriginMessageTarget = (\n iframe: HTMLIFrameElement,\n remoteOrigin?: string,\n): ThreadMessageTarget => {\n const expectedOrigin = resolvedRemoteOrigin(iframe, remoteOrigin);\n const remoteWindow = iframe.contentWindow;\n\n if (!remoteWindow) {\n throw new RemoteError(\"Remote window could not be determined\");\n }\n\n const warnedOrigins = new Set<string>();\n let connected = false;\n let shouldAnswerResponse = true;\n const pendingMessages: {\n message: unknown;\n transferables?: Transferable[];\n }[] = [];\n\n const post = (message: unknown, transferables?: Transferable[]) =>\n remoteWindow.postMessage(message, expectedOrigin, transferables ?? []);\n\n const accept = (event: MessageEvent) => {\n if (event.source !== remoteWindow) {\n return false;\n }\n\n if (event.origin !== expectedOrigin) {\n if (!warnedOrigins.has(event.origin)) {\n warnedOrigins.add(event.origin);\n console.warn(\n `Ignored a message from remote origin ${event.origin}: expected ${expectedOrigin}.`,\n );\n }\n return false;\n }\n\n return true;\n };\n\n const responseController = new AbortController();\n if (typeof iframe.addEventListener === \"function\") {\n iframe.addEventListener(\n \"load\",\n () => {\n shouldAnswerResponse = true;\n },\n { signal: responseController.signal },\n );\n }\n window.addEventListener(\n \"message\",\n (event) => {\n if (!accept(event) || event.data !== RESPONSE_MESSAGE) {\n return;\n }\n\n if (shouldAnswerResponse) {\n shouldAnswerResponse = false;\n post(CHECK_MESSAGE);\n }\n if (connected) {\n return;\n }\n\n connected = true;\n for (const { message, transferables } of pendingMessages.splice(0)) {\n post(message, transferables);\n }\n },\n { signal: responseController.signal },\n );\n post(CHECK_MESSAGE);\n\n return {\n send(message, transferables) {\n if (!connected) {\n pendingMessages.push({ message, transferables });\n return;\n }\n\n post(message, transferables);\n },\n listen(listener, { signal }) {\n if (signal?.aborted) {\n responseController.abort();\n } else {\n signal?.addEventListener(\"abort\", () => responseController.abort(), {\n once: true,\n });\n }\n\n window.addEventListener(\n \"message\",\n (event) => {\n if (!accept(event) || event.data === RESPONSE_MESSAGE) {\n return;\n }\n\n listener(event.data);\n },\n { signal },\n );\n },\n };\n};\n\ninterface HostOriginThreadOptions<Imports, Exports>\n extends ThreadOptions<Imports, Exports>, HostOriginTargetOptions {\n parent?: Window;\n}\n\nexport class HostOriginThread<\n Imports = Record<string, never>,\n Exports = Record<string, never>,\n> extends Thread<Imports, Exports> {\n readonly parent: Window;\n\n constructor({\n parent = globalThis.parent,\n allowedHostOrigins,\n ...options\n }: HostOriginThreadOptions<Imports, Exports> = {}) {\n super(hostOriginMessageTarget(parent, { allowedHostOrigins }), options);\n this.parent = parent;\n }\n}\n\ninterface RemoteOriginThreadOptions<Imports, Exports> extends ThreadOptions<\n Imports,\n Exports\n> {\n remoteOrigin?: string;\n}\n\nexport class RemoteOriginThread<\n Imports = Record<string, never>,\n Exports = Record<string, never>,\n> extends Thread<Imports, Exports> {\n readonly iframe: HTMLIFrameElement;\n\n constructor(\n iframe: HTMLIFrameElement,\n { remoteOrigin, ...options }: RemoteOriginThreadOptions<Imports, Exports>,\n ) {\n super(remoteOriginMessageTarget(iframe, remoteOrigin), options);\n this.iframe = iframe;\n }\n}\n"],"mappings":";;;;;AAYA,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AAMzB,IAAa,2BACX,QACA,EAAE,oBAAoB,oBAAoB,CAAC,MAA+B,CAAC,MACnD;CACxB,MAAM,gCAAgB,IAAI,IAAY;CACtC,MAAM,sBAAsB,+BAA+B;EACzD,GAAG;EACH,OAAO,SAAS;EAChB,GAAG;CACL,CAAC;CACD,MAAM,sBAAsB,OAAO,SAAS,kBAAkB;CAC9D,MAAM,iBAAiB,sBACnB,oBAAoB,mBAAmB,IACvC,KAAA;CAEJ,IACE,wBACC,CAAC,kBAAkB,CAAC,oBAAoB,cAAc,IACvD;EACA,cAAc,IAAI,mBAAmB;EACrC,QAAQ,KACN,eAAe,oBAAoB,yEACrC;EACA,MAAM,IAAI,YAAY,4BAA4B;CACpD;CAEA,IAAI,aAAa;CACjB,MAAM,kBAGA,CAAC;CAEP,MAAM,QACJ,SACA,QACA,kBACG,OAAO,YAAY,SAAS,QAAQ,iBAAiB,CAAC,CAAC;CAE5D,MAAM,cAAc;EAClB,IAAI,CAAC,YACH;EAGF,KAAK,MAAM,EAAE,SAAS,mBAAmB,gBAAgB,OAAO,CAAC,GAC/D,KAAK,SAAS,YAAY,aAAa;CAE3C;CAEA,MAAM,UAAU,UAAwB;EACtC,IAAI,MAAM,WA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AAM,EAAE,SAAS,mBAAmB,gBAAgB,OAAO,CAAC,GAC/D,KAAK,SAAS,aAAa;CAE/B,GACA,EAAE,QAAQ,mBAAmB,OAAO,CACtC;CACA,KAAK,aAAa;CAElB,OAAO;EACL,KAAK,SAAS,eAAe;GAC3B,IAAI,CAAC,WAAW;IACd,gBAAgB,KAAK;KAAE;KAAS;IAAc,CAAC;IAC/C;GACF;GAEA,KAAK,SAAS,aAAa;EAC7B;EACA,OAAO,UAAU,EAAE,UAAU;GAC3B,IAAI,QAAQ,SACV,mBAAmB,MAAM;QAEzB,QAAQ,iBAAiB,eAAe,mBAAmB,MAAM,GAAG,EAClE,MAAM,KACR,CAAC;GAGH,OAAO,iBACL,YACC,UAAU;IACT,IAAI,CAAC,OAAO,KAAK,KAAK,MAAM,SAAS,kBACnC;IAGF,SAAS,MAAM,IAAI;GACrB,GACA,EAAE,OAAO,CACX;EACF;CACF;AACF;AAOA,IAAa,mBAAb,cAGU,OAAyB;CACjC;CAEA,YAAY,EACV,SAAS,WAAW,QACpB,oBACA,GAAG,YAC0C,CAAC,GAAG;EACjD,MAAM,wBAAwB,QAAQ,EAAE,mBAAmB,CAAC,GAAG,OAAO;EACtE,KAAK,SAAS;CAChB;AACF;AASA,IAAa,qBAAb,cAGU,OAAyB;CACjC;CAEA,YACE,QACA,EAAE,cAAc,GAAG,WACnB;EACA,MAAM,0BAA0B,QAAQ,YAAY,GAAG,OAAO;EAC9D,KAAK,SAAS;CAChB;AACF"}
@@ -0,0 +1,20 @@
1
+ // src/connection/toRelativePathname.ts
2
+ var RELATIVE_PATH_ORIGIN = "https://example.invalid";
3
+ var hasControlCharacter = (value) => [...value].some((character) => {
4
+ const code = character.charCodeAt(0);
5
+ return code <= 31 || code >= 127 && code <= 159;
6
+ });
7
+ /** Returns a normalized relative in-app path. */
8
+ var toRelativePathname = (value) => {
9
+ if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\") || value.includes("\\") || hasControlCharacter(value)) return;
10
+ try {
11
+ const url = new URL(value, RELATIVE_PATH_ORIGIN);
12
+ if (url.origin !== RELATIVE_PATH_ORIGIN) return;
13
+ return `${url.pathname}${url.search}${url.hash}`;
14
+ } catch {
15
+ return;
16
+ }
17
+ };
18
+ export { toRelativePathname };
19
+
20
+ //# sourceMappingURL=toRelativePathname.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toRelativePathname.mjs","names":[],"sources":["../../../../../../src/connection/toRelativePathname.ts"],"sourcesContent":["const RELATIVE_PATH_ORIGIN = \"https://example.invalid\";\nconst hasControlCharacter = (value: string) =>\n [...value].some((character) => {\n const code = character.charCodeAt(0);\n return code <= 0x1f || (code >= 0x7f && code <= 0x9f);\n });\n\n/** Returns a normalized relative in-app path. */\nexport const toRelativePathname = (value: unknown): string | undefined => {\n if (\n typeof value !== \"string\" ||\n !value.startsWith(\"/\") ||\n value.startsWith(\"//\") ||\n value.startsWith(\"/\\\\\") ||\n value.includes(\"\\\\\") ||\n hasControlCharacter(value)\n ) {\n return undefined;\n }\n\n try {\n const url = new URL(value, RELATIVE_PATH_ORIGIN);\n\n if (url.origin !== RELATIVE_PATH_ORIGIN) {\n return undefined;\n }\n\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return undefined;\n }\n};\n"],"mappings":";AAAA,IAAM,uBAAuB;AAC7B,IAAM,uBAAuB,UAC3B,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,cAAc;CAC7B,MAAM,OAAO,UAAU,WAAW,CAAC;CACnC,OAAO,QAAQ,MAAS,QAAQ,OAAQ,QAAQ;AAClD,CAAC;;AAGH,IAAa,sBAAsB,UAAuC;CACxE,IACE,OAAO,UAAU,YACjB,CAAC,MAAM,WAAW,GAAG,KACrB,MAAM,WAAW,IAAI,KACrB,MAAM,WAAW,KAAK,KACtB,MAAM,SAAS,IAAI,KACnB,oBAAoB,KAAK,GAEzB;CAGF,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,OAAO,oBAAoB;EAE/C,IAAI,IAAI,WAAW,sBACjB;EAGF,OAAO,GAAG,IAAI,WAAW,IAAI,SAAS,IAAI;CAC5C,QAAQ;EACN;CACF;AACF"}
@@ -6,6 +6,8 @@ var Version = /* @__PURE__ */ function(Version) {
6
6
  Version[Version["v3"] = 3] = "v3";
7
7
  Version[Version["v4"] = 4] = "v4";
8
8
  Version[Version["v5"] = 5] = "v5";
9
+ /** The remote only accepts messages from allowed host origins. */
10
+ Version[Version["v6"] = 6] = "v6";
9
11
  return Version;
10
12
  }({});
11
13
  export { Version };