@stigmer/embed 3.1.8

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.
package/host.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Host-side embed controller — the loader half of the protocol, shared by the
3
+ * `<stigmer-agent>` element (and any future framework adapters) so the
4
+ * message-pinning rules live in exactly one place.
5
+ */
6
+ export interface EmbedHostHandlers {
7
+ /** The widget rendered inside the iframe and may be shown. */
8
+ readonly onReady?: () => void;
9
+ /** The platform refused this embed context; the caller should hide the widget. */
10
+ readonly onRefused?: () => void;
11
+ }
12
+ export interface EmbedHost {
13
+ /** Detaches listeners. Call when the iframe is removed. */
14
+ destroy(): void;
15
+ }
16
+ /**
17
+ * Wires the host side of the embed bridge onto an iframe.
18
+ *
19
+ * Security posture: every inbound message is pinned to both the iframe's
20
+ * `contentWindow` (source) and the expected frame origin, and `init` is only
21
+ * ever posted to that origin. `init` is sent once the iframe loads and again
22
+ * on every `hello` — the frame's script may attach its listener after the
23
+ * load-time send, so the handshake must be answerable at any time.
24
+ */
25
+ export declare function createEmbedHost(iframe: HTMLIFrameElement, frameOrigin: string, handlers?: EmbedHostHandlers): EmbedHost;
26
+ //# sourceMappingURL=host.d.ts.map
package/host.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,MAAM,WAAW,iBAAiB;IAChC,8DAA8D;IAC9D,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IAC9B,kFAAkF;IAClF,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;CACjC;AAED,MAAM,WAAW,SAAS;IACxB,2DAA2D;IAC3D,OAAO,IAAI,IAAI,CAAC;CACjB;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,iBAAiB,EACzB,WAAW,EAAE,MAAM,EACnB,QAAQ,GAAE,iBAAsB,GAC/B,SAAS,CAiCX"}
package/host.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Host-side embed controller — the loader half of the protocol, shared by the
3
+ * `<stigmer-agent>` element (and any future framework adapters) so the
4
+ * message-pinning rules live in exactly one place.
5
+ */
6
+ import { parseFrameMessage, toWire } from "./protocol.js";
7
+ /**
8
+ * Wires the host side of the embed bridge onto an iframe.
9
+ *
10
+ * Security posture: every inbound message is pinned to both the iframe's
11
+ * `contentWindow` (source) and the expected frame origin, and `init` is only
12
+ * ever posted to that origin. `init` is sent once the iframe loads and again
13
+ * on every `hello` — the frame's script may attach its listener after the
14
+ * load-time send, so the handshake must be answerable at any time.
15
+ */
16
+ export function createEmbedHost(iframe, frameOrigin, handlers = {}) {
17
+ const sendInit = () => {
18
+ iframe.contentWindow?.postMessage(toWire({ type: "init" }), frameOrigin);
19
+ };
20
+ const onMessage = (event) => {
21
+ if (event.source !== iframe.contentWindow)
22
+ return;
23
+ if (event.origin !== frameOrigin)
24
+ return;
25
+ const message = parseFrameMessage(event.data);
26
+ if (!message)
27
+ return;
28
+ switch (message.type) {
29
+ case "hello":
30
+ sendInit();
31
+ break;
32
+ case "ready":
33
+ handlers.onReady?.();
34
+ break;
35
+ case "refused":
36
+ handlers.onRefused?.();
37
+ break;
38
+ }
39
+ };
40
+ window.addEventListener("message", onMessage);
41
+ iframe.addEventListener("load", sendInit);
42
+ return {
43
+ destroy() {
44
+ window.removeEventListener("message", onMessage);
45
+ iframe.removeEventListener("load", sendInit);
46
+ },
47
+ };
48
+ }
49
+ //# sourceMappingURL=host.js.map
package/host.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAc1D;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAC7B,MAAyB,EACzB,WAAmB,EACnB,WAA8B,EAAE;IAEhC,MAAM,QAAQ,GAAG,GAAS,EAAE;QAC1B,MAAM,CAAC,aAAa,EAAE,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,WAAW,CAAC,CAAC;IAC3E,CAAC,CAAC;IAEF,MAAM,SAAS,GAAG,CAAC,KAAmB,EAAQ,EAAE;QAC9C,IAAI,KAAK,CAAC,MAAM,KAAK,MAAM,CAAC,aAAa;YAAE,OAAO;QAClD,IAAI,KAAK,CAAC,MAAM,KAAK,WAAW;YAAE,OAAO;QACzC,MAAM,OAAO,GAAG,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC9C,IAAI,CAAC,OAAO;YAAE,OAAO;QAErB,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;YACrB,KAAK,OAAO;gBACV,QAAQ,EAAE,CAAC;gBACX,MAAM;YACR,KAAK,OAAO;gBACV,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;gBACrB,MAAM;YACR,KAAK,SAAS;gBACZ,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC;gBACvB,MAAM;QACV,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IAC9C,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAE1C,OAAO;QACL,OAAO;YACL,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;YACjD,MAAM,CAAC,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAC/C,CAAC;KACF,CAAC;AACJ,CAAC"}
package/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @stigmer/embed — the one-line script embed for shared Stigmer agents.
3
+ *
4
+ * Three consumption forms:
5
+ * - `<script src=".../embed.js">` — the IIFE loader (`./loader` export),
6
+ * auto-registers `<stigmer-agent>` and derives the app origin from its URL.
7
+ * - `import "@stigmer/embed/define"` — bundler-side auto-registration.
8
+ * - `import { ... } from "@stigmer/embed"` — this side-effect-free API, also
9
+ * used by the hosted chat page itself for the frame half of the protocol.
10
+ */
11
+ export { EMBED_SOURCE, EMBED_PROTOCOL_VERSION, parseFrameMessage, parseHostMessage, toWire, type FrameToHostMessage, type HostToFrameMessage, } from "./protocol.js";
12
+ export { OPAQUE_ORIGIN, isEmbedded, notifyParent, resolveParentOrigin, } from "./frame.js";
13
+ export { createEmbedHost, type EmbedHost, type EmbedHostHandlers, } from "./host.js";
14
+ export { StigmerAgentElement, defineStigmerAgent, setDefaultAppOrigin, } from "./element.js";
15
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,YAAY,EACZ,sBAAsB,EACtB,iBAAiB,EACjB,gBAAgB,EAChB,MAAM,EACN,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,GACxB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,eAAe,EACf,KAAK,SAAS,EACd,KAAK,iBAAiB,GACvB,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,cAAc,CAAC"}
package/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @stigmer/embed — the one-line script embed for shared Stigmer agents.
3
+ *
4
+ * Three consumption forms:
5
+ * - `<script src=".../embed.js">` — the IIFE loader (`./loader` export),
6
+ * auto-registers `<stigmer-agent>` and derives the app origin from its URL.
7
+ * - `import "@stigmer/embed/define"` — bundler-side auto-registration.
8
+ * - `import { ... } from "@stigmer/embed"` — this side-effect-free API, also
9
+ * used by the hosted chat page itself for the frame half of the protocol.
10
+ */
11
+ export { EMBED_SOURCE, EMBED_PROTOCOL_VERSION, parseFrameMessage, parseHostMessage, toWire, } from "./protocol.js";
12
+ export { OPAQUE_ORIGIN, isEmbedded, notifyParent, resolveParentOrigin, } from "./frame.js";
13
+ export { createEmbedHost, } from "./host.js";
14
+ export { StigmerAgentElement, defineStigmerAgent, setDefaultAppOrigin, } from "./element.js";
15
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,YAAY,EACZ,sBAAsB,EACtB,iBAAiB,EACjB,gBAAgB,EAChB,MAAM,GAGP,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,eAAe,GAGhB,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,cAAc,CAAC"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@stigmer/embed",
3
+ "version": "3.1.8",
4
+ "description": "One-line script embed for shared Stigmer agents — a framework-free <stigmer-agent> web component that bootstraps the hosted chat page in an iframe",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": [
8
+ "./src/define.ts",
9
+ "./dist/define.js",
10
+ "./dist/embed.global.js"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/stigmer/stigmer.git",
15
+ "directory": "sdk/embed"
16
+ },
17
+ "engines": {
18
+ "node": ">=18"
19
+ },
20
+ "keywords": [
21
+ "stigmer",
22
+ "embed",
23
+ "iframe",
24
+ "web-component",
25
+ "chat-widget",
26
+ "ai-agents"
27
+ ],
28
+ "main": "./index.js",
29
+ "types": "./index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./index.d.ts",
33
+ "import": "./index.js"
34
+ },
35
+ "./define": {
36
+ "types": "./define.d.ts",
37
+ "import": "./define.js"
38
+ },
39
+ "./loader": "./embed.global.js"
40
+ }
41
+ }
package/protocol.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The postMessage wire contract between the embed loader (host page) and the
3
+ * hosted chat page (inside the iframe).
4
+ *
5
+ * This module is the single source of truth for the protocol: the loader
6
+ * (`element.ts` / `host.ts`) and the chat page (`frame.ts`, consumed by
7
+ * `client-apps/web`) both import these constants and parsers — nothing is
8
+ * redeclared elsewhere. Every message is stamped with {@link EMBED_SOURCE}
9
+ * and {@link EMBED_PROTOCOL_VERSION}; receivers must ignore anything that
10
+ * does not match, because the browser `message` channel is shared with the
11
+ * whole page.
12
+ *
13
+ * v1 messages:
14
+ * - host -> frame `init` — carries no payload; its value is the browser-set
15
+ * `event.origin`, which tells the framed page who embeds it (unforgeable).
16
+ * - frame -> host `hello` — asks the host to (re)send `init`, for the case
17
+ * where the frame's listener attaches after the host's load-time `init`.
18
+ * - frame -> host `ready` — the widget rendered and may be shown.
19
+ * - frame -> host `refused` — the platform refused this embed context (origin
20
+ * not allowed); the loader hides the element gracefully.
21
+ */
22
+ export declare const EMBED_SOURCE = "stigmer-embed";
23
+ export declare const EMBED_PROTOCOL_VERSION = 1;
24
+ /** Messages sent by the hosted chat page (frame) to the embedding page (host). */
25
+ export type FrameToHostMessage = {
26
+ readonly type: "hello";
27
+ } | {
28
+ readonly type: "ready";
29
+ } | {
30
+ readonly type: "refused";
31
+ };
32
+ /** Messages sent by the embedding page (host) to the hosted chat page (frame). */
33
+ export type HostToFrameMessage = {
34
+ readonly type: "init";
35
+ };
36
+ interface Envelope {
37
+ readonly source: typeof EMBED_SOURCE;
38
+ readonly v: typeof EMBED_PROTOCOL_VERSION;
39
+ readonly type: string;
40
+ }
41
+ /** Wraps a message in the versioned envelope for `postMessage`. */
42
+ export declare function toWire(message: FrameToHostMessage | HostToFrameMessage): Envelope;
43
+ /** Parses an inbound message on the host side; `null` for foreign messages. */
44
+ export declare function parseFrameMessage(data: unknown): FrameToHostMessage | null;
45
+ /** Parses an inbound message on the frame side; `null` for foreign messages. */
46
+ export declare function parseHostMessage(data: unknown): HostToFrameMessage | null;
47
+ export {};
48
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,eAAO,MAAM,YAAY,kBAAkB,CAAC;AAC5C,eAAO,MAAM,sBAAsB,IAAI,CAAC;AAExC,kFAAkF;AAClF,MAAM,MAAM,kBAAkB,GAC1B;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAC1B;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAC1B;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC;AAEjC,kFAAkF;AAClF,MAAM,MAAM,kBAAkB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAE3D,UAAU,QAAQ;IAChB,QAAQ,CAAC,MAAM,EAAE,OAAO,YAAY,CAAC;IACrC,QAAQ,CAAC,CAAC,EAAE,OAAO,sBAAsB,CAAC;IAC1C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,mEAAmE;AACnE,wBAAgB,MAAM,CACpB,OAAO,EAAE,kBAAkB,GAAG,kBAAkB,GAC/C,QAAQ,CAEV;AAWD,+EAA+E;AAC/E,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,kBAAkB,GAAG,IAAI,CAW1E;AAED,gFAAgF;AAChF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,OAAO,GAAG,kBAAkB,GAAG,IAAI,CAIzE"}
package/protocol.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The postMessage wire contract between the embed loader (host page) and the
3
+ * hosted chat page (inside the iframe).
4
+ *
5
+ * This module is the single source of truth for the protocol: the loader
6
+ * (`element.ts` / `host.ts`) and the chat page (`frame.ts`, consumed by
7
+ * `client-apps/web`) both import these constants and parsers — nothing is
8
+ * redeclared elsewhere. Every message is stamped with {@link EMBED_SOURCE}
9
+ * and {@link EMBED_PROTOCOL_VERSION}; receivers must ignore anything that
10
+ * does not match, because the browser `message` channel is shared with the
11
+ * whole page.
12
+ *
13
+ * v1 messages:
14
+ * - host -> frame `init` — carries no payload; its value is the browser-set
15
+ * `event.origin`, which tells the framed page who embeds it (unforgeable).
16
+ * - frame -> host `hello` — asks the host to (re)send `init`, for the case
17
+ * where the frame's listener attaches after the host's load-time `init`.
18
+ * - frame -> host `ready` — the widget rendered and may be shown.
19
+ * - frame -> host `refused` — the platform refused this embed context (origin
20
+ * not allowed); the loader hides the element gracefully.
21
+ */
22
+ export const EMBED_SOURCE = "stigmer-embed";
23
+ export const EMBED_PROTOCOL_VERSION = 1;
24
+ /** Wraps a message in the versioned envelope for `postMessage`. */
25
+ export function toWire(message) {
26
+ return { source: EMBED_SOURCE, v: EMBED_PROTOCOL_VERSION, ...message };
27
+ }
28
+ function parseEnvelope(data) {
29
+ if (typeof data !== "object" || data === null)
30
+ return null;
31
+ const candidate = data;
32
+ if (candidate.source !== EMBED_SOURCE)
33
+ return null;
34
+ if (candidate.v !== EMBED_PROTOCOL_VERSION)
35
+ return null;
36
+ if (typeof candidate.type !== "string")
37
+ return null;
38
+ return candidate;
39
+ }
40
+ /** Parses an inbound message on the host side; `null` for foreign messages. */
41
+ export function parseFrameMessage(data) {
42
+ const envelope = parseEnvelope(data);
43
+ if (!envelope)
44
+ return null;
45
+ switch (envelope.type) {
46
+ case "hello":
47
+ case "ready":
48
+ case "refused":
49
+ return { type: envelope.type };
50
+ default:
51
+ return null;
52
+ }
53
+ }
54
+ /** Parses an inbound message on the frame side; `null` for foreign messages. */
55
+ export function parseHostMessage(data) {
56
+ const envelope = parseEnvelope(data);
57
+ if (!envelope)
58
+ return null;
59
+ return envelope.type === "init" ? { type: "init" } : null;
60
+ }
61
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,MAAM,CAAC,MAAM,YAAY,GAAG,eAAe,CAAC;AAC5C,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AAiBxC,mEAAmE;AACnE,MAAM,UAAU,MAAM,CACpB,OAAgD;IAEhD,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC,EAAE,sBAAsB,EAAE,GAAG,OAAO,EAAE,CAAC;AACzE,CAAC;AAED,SAAS,aAAa,CAAC,IAAa;IAClC,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC3D,MAAM,SAAS,GAAG,IAA+B,CAAC;IAClD,IAAI,SAAS,CAAC,MAAM,KAAK,YAAY;QAAE,OAAO,IAAI,CAAC;IACnD,IAAI,SAAS,CAAC,CAAC,KAAK,sBAAsB;QAAE,OAAO,IAAI,CAAC;IACxD,IAAI,OAAO,SAAS,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpD,OAAO,SAAgC,CAAC;AAC1C,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,iBAAiB,CAAC,IAAa;IAC7C,MAAM,QAAQ,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;IACrC,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3B,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,OAAO,CAAC;QACb,KAAK,OAAO,CAAC;QACb,KAAK,SAAS;YACZ,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC;QACjC;YACE,OAAO,IAAI,CAAC;IAChB,CAAC;AACH,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,gBAAgB,CAAC,IAAa;IAC5C,MAAM,QAAQ,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;IACrC,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3B,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC5D,CAAC"}
@@ -0,0 +1,177 @@
1
+ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
2
+
3
+ import {
4
+ StigmerAgentElement,
5
+ defineStigmerAgent,
6
+ setDefaultAppOrigin,
7
+ } from "../element.js";
8
+ import { toWire } from "../protocol.js";
9
+
10
+ const APP_ORIGIN = "https://app.stigmer.example";
11
+
12
+ beforeAll(() => {
13
+ defineStigmerAgent();
14
+ });
15
+
16
+ afterEach(() => {
17
+ document.body.innerHTML = "";
18
+ setDefaultAppOrigin(APP_ORIGIN);
19
+ });
20
+
21
+ function mount(attributes: Record<string, string>): StigmerAgentElement {
22
+ const element = document.createElement("stigmer-agent") as StigmerAgentElement;
23
+ for (const [name, value] of Object.entries(attributes)) {
24
+ element.setAttribute(name, value);
25
+ }
26
+ document.body.appendChild(element);
27
+ return element;
28
+ }
29
+
30
+ function iframeOf(element: StigmerAgentElement): HTMLIFrameElement | null {
31
+ return element.querySelector("iframe");
32
+ }
33
+
34
+ describe("<stigmer-agent>", () => {
35
+ it("registers exactly once, tolerating repeat define calls", () => {
36
+ defineStigmerAgent();
37
+ expect(customElements.get("stigmer-agent")).toBe(StigmerAgentElement);
38
+ });
39
+
40
+ it("renders an iframe onto the hosted chat page for org/agent", () => {
41
+ setDefaultAppOrigin(APP_ORIGIN);
42
+ const element = mount({ org: "acme", agent: "support-bot" });
43
+
44
+ const iframe = iframeOf(element);
45
+ expect(iframe).not.toBeNull();
46
+ expect(iframe!.src).toBe(`${APP_ORIGIN}/chat/acme/support-bot`);
47
+ expect(element.style.width).toBe("400px");
48
+ expect(element.style.height).toBe("600px");
49
+ });
50
+
51
+ it("honors width/height (bare numbers become px) and explicit themes", () => {
52
+ setDefaultAppOrigin(APP_ORIGIN);
53
+ const element = mount({
54
+ org: "acme",
55
+ agent: "support-bot",
56
+ width: "320",
57
+ height: "80vh",
58
+ theme: "dark",
59
+ });
60
+
61
+ expect(element.style.width).toBe("320px");
62
+ expect(element.style.height).toBe("80vh");
63
+ expect(iframeOf(element)!.src).toBe(
64
+ `${APP_ORIGIN}/chat/acme/support-bot?theme=dark`,
65
+ );
66
+ });
67
+
68
+ it("forwards the token attribute as ?k= on the iframe URL (locked link)", () => {
69
+ setDefaultAppOrigin(APP_ORIGIN);
70
+ const element = mount({
71
+ org: "acme",
72
+ agent: "support-bot",
73
+ token: "tok123",
74
+ theme: "dark",
75
+ });
76
+
77
+ // The hosted page reads ?k= and forwards it on its guest mint; the
78
+ // token must ride BEFORE theme so the URL matches the SDK's shape.
79
+ expect(iframeOf(element)!.src).toBe(
80
+ `${APP_ORIGIN}/chat/acme/support-bot?k=tok123&theme=dark`,
81
+ );
82
+ });
83
+
84
+ it("prefers the app-origin attribute over the loader default", () => {
85
+ setDefaultAppOrigin(APP_ORIGIN);
86
+ const element = mount({
87
+ org: "acme",
88
+ agent: "support-bot",
89
+ "app-origin": "https://selfhosted.example",
90
+ });
91
+
92
+ expect(iframeOf(element)!.src).toBe(
93
+ "https://selfhosted.example/chat/acme/support-bot",
94
+ );
95
+ });
96
+
97
+ it("URL-encodes org and agent path segments", () => {
98
+ setDefaultAppOrigin(APP_ORIGIN);
99
+ const element = mount({ org: "acme co", agent: "bot/one" });
100
+
101
+ expect(iframeOf(element)!.src).toBe(
102
+ `${APP_ORIGIN}/chat/acme%20co/bot%2Fone`,
103
+ );
104
+ });
105
+
106
+ it("renders nothing (with a console error) when required config is missing", () => {
107
+ const consoleError = vi
108
+ .spyOn(console, "error")
109
+ .mockImplementation(() => undefined);
110
+
111
+ const missingAgent = mount({ org: "acme" });
112
+ expect(iframeOf(missingAgent)).toBeNull();
113
+
114
+ setDefaultAppOrigin("");
115
+ const missingOrigin = mount({ org: "acme", agent: "support-bot" });
116
+ expect(iframeOf(missingOrigin)).toBeNull();
117
+
118
+ expect(consoleError).toHaveBeenCalled();
119
+ consoleError.mockRestore();
120
+ });
121
+
122
+ it("hides itself and dispatches stigmer:refused when the frame reports refusal", () => {
123
+ setDefaultAppOrigin(APP_ORIGIN);
124
+ const element = mount({ org: "acme", agent: "support-bot" });
125
+ const refused = vi.fn();
126
+ element.addEventListener("stigmer:refused", refused);
127
+
128
+ window.dispatchEvent(
129
+ new MessageEvent("message", {
130
+ data: toWire({ type: "refused" }),
131
+ origin: APP_ORIGIN,
132
+ source: iframeOf(element)!.contentWindow,
133
+ }),
134
+ );
135
+
136
+ expect(element.style.display).toBe("none");
137
+ expect(refused).toHaveBeenCalledTimes(1);
138
+ });
139
+
140
+ it("dispatches stigmer:ready when the frame reports readiness", () => {
141
+ setDefaultAppOrigin(APP_ORIGIN);
142
+ const element = mount({ org: "acme", agent: "support-bot" });
143
+ const ready = vi.fn();
144
+ element.addEventListener("stigmer:ready", ready);
145
+
146
+ window.dispatchEvent(
147
+ new MessageEvent("message", {
148
+ data: toWire({ type: "ready" }),
149
+ origin: APP_ORIGIN,
150
+ source: iframeOf(element)!.contentWindow,
151
+ }),
152
+ );
153
+
154
+ expect(ready).toHaveBeenCalledTimes(1);
155
+ expect(element.style.display).toBe("inline-block");
156
+ });
157
+
158
+ it("tears down its iframe and bridge on disconnect", () => {
159
+ setDefaultAppOrigin(APP_ORIGIN);
160
+ const element = mount({ org: "acme", agent: "support-bot" });
161
+ const ready = vi.fn();
162
+ element.addEventListener("stigmer:ready", ready);
163
+ const frameWindow = iframeOf(element)!.contentWindow;
164
+
165
+ element.remove();
166
+
167
+ expect(iframeOf(element)).toBeNull();
168
+ window.dispatchEvent(
169
+ new MessageEvent("message", {
170
+ data: toWire({ type: "ready" }),
171
+ origin: APP_ORIGIN,
172
+ source: frameWindow,
173
+ }),
174
+ );
175
+ expect(ready).not.toHaveBeenCalled();
176
+ });
177
+ });
@@ -0,0 +1,141 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ import { OPAQUE_ORIGIN, notifyParent, resolveParentOrigin } from "../frame.js";
4
+ import { toWire } from "../protocol.js";
5
+
6
+ /**
7
+ * happy-dom runs the suite unframed (window.self === window.top), so framed
8
+ * behavior is exercised by stubbing the browser-owned discovery sources
9
+ * (ancestorOrigins, referrer, parent messaging) rather than real nesting —
10
+ * real cross-origin frames are e2e territory.
11
+ */
12
+
13
+ const PARENT_ORIGIN = "https://docs.example.com";
14
+
15
+ function stubAncestorOrigins(...origins: string[]): void {
16
+ vi.spyOn(window, "location", "get").mockReturnValue({
17
+ ...window.location,
18
+ ancestorOrigins: {
19
+ length: origins.length,
20
+ 0: origins[0],
21
+ item: (i: number) => origins[i] ?? null,
22
+ },
23
+ } as unknown as Location);
24
+ }
25
+
26
+ afterEach(() => {
27
+ vi.restoreAllMocks();
28
+ });
29
+
30
+ describe("resolveParentOrigin", () => {
31
+ it("prefers ancestorOrigins when the browser provides it", async () => {
32
+ stubAncestorOrigins(PARENT_ORIGIN);
33
+
34
+ await expect(resolveParentOrigin()).resolves.toBe(PARENT_ORIGIN);
35
+ });
36
+
37
+ it("falls back to the referrer origin when ancestorOrigins is unavailable", async () => {
38
+ vi.spyOn(document, "referrer", "get").mockReturnValue(
39
+ `${PARENT_ORIGIN}/pricing/page?x=1`,
40
+ );
41
+
42
+ await expect(resolveParentOrigin()).resolves.toBe(PARENT_ORIGIN);
43
+ });
44
+
45
+ it("skips an opaque ancestor entry and keeps descending the ladder", async () => {
46
+ stubAncestorOrigins(OPAQUE_ORIGIN);
47
+ vi.spyOn(document, "referrer", "get").mockReturnValue(`${PARENT_ORIGIN}/`);
48
+
49
+ await expect(resolveParentOrigin()).resolves.toBe(PARENT_ORIGIN);
50
+ });
51
+
52
+ it("uses the loader handshake's event.origin when nothing else is available", async () => {
53
+ vi.spyOn(document, "referrer", "get").mockReturnValue("");
54
+ // The hello goes to window.parent; unframed in happy-dom that is window
55
+ // itself, so the loader's reply is simulated with a parent-sourced event.
56
+ const helloSent = new Promise<void>((resolve) => {
57
+ vi.spyOn(window.parent, "postMessage").mockImplementation(() => {
58
+ resolve();
59
+ });
60
+ });
61
+
62
+ const pending = resolveParentOrigin(1_000);
63
+ await helloSent;
64
+ window.dispatchEvent(
65
+ new MessageEvent("message", {
66
+ data: toWire({ type: "init" }),
67
+ origin: PARENT_ORIGIN,
68
+ source: window.parent,
69
+ }),
70
+ );
71
+
72
+ await expect(pending).resolves.toBe(PARENT_ORIGIN);
73
+ });
74
+
75
+ it("ignores forged init messages that are not from the parent window", async () => {
76
+ vi.spyOn(document, "referrer", "get").mockReturnValue("");
77
+ vi.spyOn(window.parent, "postMessage").mockImplementation(() => undefined);
78
+ const iframe = document.createElement("iframe");
79
+ document.body.appendChild(iframe);
80
+
81
+ const pending = resolveParentOrigin(50);
82
+ window.dispatchEvent(
83
+ new MessageEvent("message", {
84
+ data: toWire({ type: "init" }),
85
+ origin: "https://evil.example.com",
86
+ source: iframe.contentWindow,
87
+ }),
88
+ );
89
+
90
+ // The forged message must not settle the ladder; the timeout resolves it
91
+ // to the opaque sentinel instead.
92
+ await expect(pending).resolves.toBe(OPAQUE_ORIGIN);
93
+ iframe.remove();
94
+ });
95
+
96
+ it("resolves to the opaque sentinel when the handshake times out", async () => {
97
+ vi.spyOn(document, "referrer", "get").mockReturnValue("");
98
+ vi.spyOn(window.parent, "postMessage").mockImplementation(() => undefined);
99
+
100
+ await expect(resolveParentOrigin(20)).resolves.toBe(OPAQUE_ORIGIN);
101
+ });
102
+ });
103
+
104
+ describe("notifyParent", () => {
105
+ it("targets the discovered parent origin", () => {
106
+ // notifyParent no-ops when unframed, so frame window.top to a distinct
107
+ // object for the duration of the call.
108
+ vi.spyOn(window, "top", "get").mockReturnValue({} as Window);
109
+ const postMessage = vi
110
+ .spyOn(window.parent, "postMessage")
111
+ .mockImplementation(() => undefined);
112
+
113
+ notifyParent({ type: "ready" }, PARENT_ORIGIN);
114
+
115
+ expect(postMessage).toHaveBeenCalledWith(
116
+ toWire({ type: "ready" }),
117
+ PARENT_ORIGIN,
118
+ );
119
+ });
120
+
121
+ it("falls back to a wildcard target for an opaque parent", () => {
122
+ vi.spyOn(window, "top", "get").mockReturnValue({} as Window);
123
+ const postMessage = vi
124
+ .spyOn(window.parent, "postMessage")
125
+ .mockImplementation(() => undefined);
126
+
127
+ notifyParent({ type: "refused" }, OPAQUE_ORIGIN);
128
+
129
+ expect(postMessage).toHaveBeenCalledWith(toWire({ type: "refused" }), "*");
130
+ });
131
+
132
+ it("no-ops when the page is not framed", () => {
133
+ const postMessage = vi
134
+ .spyOn(window.parent, "postMessage")
135
+ .mockImplementation(() => undefined);
136
+
137
+ notifyParent({ type: "ready" }, PARENT_ORIGIN);
138
+
139
+ expect(postMessage).not.toHaveBeenCalled();
140
+ });
141
+ });