@proteos/component-sdk 0.49.0 → 0.51.0
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/dist/{chunk-P4MKRWPA.cjs → chunk-IPYKNCDU.cjs} +2 -2
- package/dist/{chunk-P4MKRWPA.cjs.map → chunk-IPYKNCDU.cjs.map} +1 -1
- package/dist/{chunk-2EAOQNQB.js → chunk-RTYCYWKC.js} +2 -2
- package/dist/{chunk-2EAOQNQB.js.map → chunk-RTYCYWKC.js.map} +1 -1
- package/dist/index.cjs +26 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -2
- package/dist/index.d.ts +11 -2
- package/dist/index.js +18 -4
- package/dist/index.js.map +1 -1
- package/dist/protocol.cjs +5 -5
- package/dist/protocol.d.cts +10 -2
- package/dist/protocol.d.ts +10 -2
- package/dist/protocol.js +1 -1
- package/package.json +2 -2
- package/src/context.tsx +18 -1
- package/src/hooks.ts +9 -0
- package/src/index.ts +2 -0
- package/src/protocol.ts +10 -0
|
@@ -14,5 +14,5 @@ exports.COMPONENT_OVERLAY_Z_INDEX = COMPONENT_OVERLAY_Z_INDEX;
|
|
|
14
14
|
exports.MESSAGE_SOURCE = MESSAGE_SOURCE;
|
|
15
15
|
exports.isHostMessage = isHostMessage;
|
|
16
16
|
exports.isRuntimeMessage = isRuntimeMessage;
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
18
|
-
//# sourceMappingURL=chunk-
|
|
17
|
+
//# sourceMappingURL=chunk-IPYKNCDU.cjs.map
|
|
18
|
+
//# sourceMappingURL=chunk-IPYKNCDU.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocol.ts"],"names":[],"mappings":";;;AAUO,IAAM,cAAA,GAAiB;AAuBvB,IAAM,yBAAA,GAA4B;
|
|
1
|
+
{"version":3,"sources":["../src/protocol.ts"],"names":[],"mappings":";;;AAUO,IAAM,cAAA,GAAiB;AAuBvB,IAAM,yBAAA,GAA4B;AA0LlC,SAAS,cAAc,IAAA,EAA8C;AAC1E,EAAA,OACE,OAAO,IAAA,KAAS,QAAA,IAChB,IAAA,KAAS,IAAA,IACR,KAA8B,MAAA,KAAW,cAAA,IAC1C,OAAQ,IAAA,CAA4B,IAAA,KAAS,QAAA;AAEjD;AAEO,SAAS,iBAAiB,IAAA,EAAiD;AAChF,EAAA,OACE,OAAO,IAAA,KAAS,QAAA,IAChB,IAAA,KAAS,IAAA,IACR,KAA8B,MAAA,KAAW,cAAA,IAC1C,OAAQ,IAAA,CAA4B,IAAA,KAAS,QAAA;AAEjD","file":"chunk-IPYKNCDU.cjs","sourcesContent":["// postMessage protocol between the host page and the component-runtime iframe.\n// This is the single source of truth for the wire contract: the host renderer\n// (clients/web .../component-frame.tsx), the runtime shell\n// (clients/web/component-runtime/shell.tsx), and the author-facing hooks\n// (this package's RuntimeProvider / useNavigate) all import these same types so\n// every end stays in lockstep.\n//\n// Every message carries `source: MESSAGE_SOURCE` so we can ignore the unrelated\n// postMessage traffic that shares the window (OIDC silent-renew, Vite HMR, …).\n\nexport const MESSAGE_SOURCE = 'proteos-component-runtime' as const\n\n/**\n * z-index the component iframe is promoted to while one of its own overlays\n * (modal, popover, menu, select, tooltip) is open. The iframe goes\n * `position: fixed; inset: 0` at this z so the overlay — which portals to the\n * IFRAME's body and would otherwise clip at the frame's box — can paint over\n * the rest of the page.\n *\n * Host z ladder this slots into:\n * 50 @proteos/ui Modal / Tooltip / ImageLightbox (default tier)\n * 1000+ full-page panel stack (scrim 1000, panels 1001+n)\n * 1090 peek scrim 1100 peek panel, ask-proteos window\n * 1150 ← THIS\n * 1200 menu popover, command palette, action dialog, component modal\n * 1300 select popover\n *\n * Above the peek/full-page surfaces a component can live on, below the global\n * host chrome. Note the cap: inside a peek (a `fixed` + z-index ancestor) the\n * promoted iframe paints within that 1100 stacking context — it covers the\n * peek's own content and everything under it, but host chrome at 1200+ still\n * wins. That is the intended layering, not a bug.\n */\nexport const COMPONENT_OVERLAY_Z_INDEX = 1150\n\n/** Viewport-relative box of the iframe's in-flow placeholder, in CSS px. */\nexport interface OverlayRect {\n top: number\n left: number\n width: number\n height: number\n}\n\nexport interface PageContext {\n record?: Record<string, unknown>\n entity?: { slug: string; [key: string]: unknown }\n params?: Record<string, unknown>\n [key: string]: unknown\n}\n\n// ── Host → runtime ──────────────────────────────────────────────────────────\n\nexport interface InitMessage {\n type: 'INIT'\n /** Raw bearer token (the OIDC `id_token`). The runtime's ProteosClient\n * prepends `Bearer ` when building the Authorization header, so the host\n * sends the token verbatim — NOT a full `Bearer …` header value.\n * Empty string in public mode (`isPublic: true`). */\n authToken: string\n /** API origin the bundle endpoint + SDK calls resolve against. */\n apiBaseUrl: string\n /** Resolved props for the component (Liquid templating happens host-side). */\n props: Record<string, unknown>\n pageCtx: PageContext\n /** PUBLIC mode: the component renders on an unauthenticated public page.\n * The shell fetches the bundle from the public endpoint (no bearer) and\n * injects a restricted sdk — only `functions.actions.invokePublic` reaches\n * the platform. Requires `orgId`. */\n isPublic?: boolean\n /** Org id for public mode — public endpoints carry the org in the path\n * because there is no token to scope from. */\n orgId?: string\n /** Set when this frame is the CONTENT of a host component modal (opened by\n * another component via OPEN_MODAL). The component reads it through\n * `useModalHost()` and closes with a result by posting MODAL_RESULT with\n * this id. Absent on ordinary page-hosted frames. */\n modalRequestId?: string\n}\n\nexport interface AuthRefreshMessage {\n type: 'AUTH_REFRESH'\n token: string\n}\n\nexport interface DataInvalidateMessage {\n type: 'DATA_INVALIDATE'\n queryKey?: unknown[]\n}\n\n/** Where the iframe's in-flow box sits in the host viewport. Sent while the\n * frame is promoted (OVERLAY_STATE open) so the runtime can keep its content\n * parked at the original rect while the iframe itself covers the viewport —\n * and re-sent when the host window resizes under an open overlay. */\nexport interface OverlayRectMessage {\n type: 'OVERLAY_RECT'\n rect: OverlayRect\n}\n\n/** Resolution of an OPEN_MODAL request: the host modal closed. `result` is the\n * value the modal's component passed to MODAL_RESULT, and is absent when the\n * modal was dismissed (backdrop / Esc / ×). */\nexport interface ModalClosedMessage {\n type: 'MODAL_CLOSED'\n requestId: string\n result?: unknown\n}\n\nexport type HostMessage =\n | InitMessage\n | AuthRefreshMessage\n | DataInvalidateMessage\n | OverlayRectMessage\n | ModalClosedMessage\n\n// ── Runtime → host ──────────────────────────────────────────────────────────\n\nexport interface ReadyMessage {\n type: 'READY'\n}\n\nexport interface ResizeMessage {\n type: 'RESIZE'\n height: number\n}\n\nexport interface NavigateMessage {\n type: 'NAVIGATE'\n to: string\n}\n\n/** Open an in-app path in a peek (slide-over) panel instead of full-page\n * navigation. Same `/…` in-app path grammar as NAVIGATE; the host decides\n * what can peek (today: platform pages) and falls back to NAVIGATE otherwise. */\nexport interface OpenPeekMessage {\n type: 'OPEN_PEEK'\n to: string\n}\n\n/** Ask the host to open a prepared call: the host shows the conversation brief's\n * preview (its softphone owns the dial) and lets the user place the call.\n * Ignored on public pages and on hosts without a softphone. */\nexport interface OpenCallMessage {\n type: 'OPEN_CALL'\n /** The conversation brief to preview and dial from. */\n conversationBriefId: string\n}\n\n/** The runtime has (or no longer has) an overlay open and needs the host to\n * promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.\n *\n * Same-origin today, so the runtime applies the promotion styles to its own\n * `window.frameElement` synchronously (pre-paint, no flicker) and this message\n * is the host's cue to MIRROR that state into React — gate RESIZE, hold the\n * placeholder height, start posting OVERLAY_RECT. When components move to a\n * dedicated origin the runtime can no longer touch the frame and this message\n * becomes the actuation instead; the runtime hides its overlay until the\n * answering OVERLAY_RECT arrives. */\nexport interface OverlayStateMessage {\n type: 'OVERLAY_STATE'\n open: boolean\n}\n\n/** Ask the host to open ANOTHER component in a central modal, above everything\n * this frame could reach on its own. The host answers with MODAL_CLOSED\n * carrying the same `requestId`. */\nexport interface OpenModalMessage {\n type: 'OPEN_MODAL'\n /** Correlates the eventual MODAL_CLOSED. Generated by the opener. */\n requestId: string\n /** Slug of the component to mount inside the modal. */\n componentSlug: string\n /** Props for that component (already literal values — no Liquid). */\n props?: Record<string, unknown>\n /** Optional modal heading. */\n title?: string\n}\n\n/** Escape was pressed with focus inside the iframe, and nothing in the runtime\n * consumed it.\n *\n * Keyboard events don't cross the iframe boundary, and react-aria binds its\n * Escape handling to the overlay element in its own React tree — so a\n * host-rendered dialog CANNOT see Escape once the user has clicked into a\n * component. The runtime forwards it so the host can dismiss on the user's\n * behalf. Not sent while the runtime has its own overlay open: that overlay\n * owns Escape. */\nexport interface EscapePressedMessage {\n type: 'ESCAPE_PRESSED'\n}\n\n/** Posted by the component INSIDE a host modal to close it with a value. The\n * `requestId` is the one INIT carried as `modalRequestId`. */\nexport interface ModalResultMessage {\n type: 'MODAL_RESULT'\n requestId: string\n result?: unknown\n}\n\nexport interface ErrorMessage {\n type: 'ERROR'\n message: string\n stack?: string\n}\n\nexport type RuntimeMessage =\n | ReadyMessage\n | ResizeMessage\n | NavigateMessage\n | OpenPeekMessage\n | OpenCallMessage\n | OverlayStateMessage\n | OpenModalMessage\n | ModalResultMessage\n | EscapePressedMessage\n | ErrorMessage\n\n// Wire envelope: the message plus the source discriminator.\nexport type Envelope<T> = T & { source: typeof MESSAGE_SOURCE }\n\nexport function isHostMessage(data: unknown): data is Envelope<HostMessage> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { source?: unknown }).source === MESSAGE_SOURCE &&\n typeof (data as { type?: unknown }).type === 'string'\n )\n}\n\nexport function isRuntimeMessage(data: unknown): data is Envelope<RuntimeMessage> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { source?: unknown }).source === MESSAGE_SOURCE &&\n typeof (data as { type?: unknown }).type === 'string'\n )\n}\n"]}
|
|
@@ -9,5 +9,5 @@ function isRuntimeMessage(data) {
|
|
|
9
9
|
}
|
|
10
10
|
|
|
11
11
|
export { COMPONENT_OVERLAY_Z_INDEX, MESSAGE_SOURCE, isHostMessage, isRuntimeMessage };
|
|
12
|
-
//# sourceMappingURL=chunk-
|
|
13
|
-
//# sourceMappingURL=chunk-
|
|
12
|
+
//# sourceMappingURL=chunk-RTYCYWKC.js.map
|
|
13
|
+
//# sourceMappingURL=chunk-RTYCYWKC.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocol.ts"],"names":[],"mappings":";AAUO,IAAM,cAAA,GAAiB;AAuBvB,IAAM,yBAAA,GAA4B;
|
|
1
|
+
{"version":3,"sources":["../src/protocol.ts"],"names":[],"mappings":";AAUO,IAAM,cAAA,GAAiB;AAuBvB,IAAM,yBAAA,GAA4B;AA0LlC,SAAS,cAAc,IAAA,EAA8C;AAC1E,EAAA,OACE,OAAO,IAAA,KAAS,QAAA,IAChB,IAAA,KAAS,IAAA,IACR,KAA8B,MAAA,KAAW,cAAA,IAC1C,OAAQ,IAAA,CAA4B,IAAA,KAAS,QAAA;AAEjD;AAEO,SAAS,iBAAiB,IAAA,EAAiD;AAChF,EAAA,OACE,OAAO,IAAA,KAAS,QAAA,IAChB,IAAA,KAAS,IAAA,IACR,KAA8B,MAAA,KAAW,cAAA,IAC1C,OAAQ,IAAA,CAA4B,IAAA,KAAS,QAAA;AAEjD","file":"chunk-RTYCYWKC.js","sourcesContent":["// postMessage protocol between the host page and the component-runtime iframe.\n// This is the single source of truth for the wire contract: the host renderer\n// (clients/web .../component-frame.tsx), the runtime shell\n// (clients/web/component-runtime/shell.tsx), and the author-facing hooks\n// (this package's RuntimeProvider / useNavigate) all import these same types so\n// every end stays in lockstep.\n//\n// Every message carries `source: MESSAGE_SOURCE` so we can ignore the unrelated\n// postMessage traffic that shares the window (OIDC silent-renew, Vite HMR, …).\n\nexport const MESSAGE_SOURCE = 'proteos-component-runtime' as const\n\n/**\n * z-index the component iframe is promoted to while one of its own overlays\n * (modal, popover, menu, select, tooltip) is open. The iframe goes\n * `position: fixed; inset: 0` at this z so the overlay — which portals to the\n * IFRAME's body and would otherwise clip at the frame's box — can paint over\n * the rest of the page.\n *\n * Host z ladder this slots into:\n * 50 @proteos/ui Modal / Tooltip / ImageLightbox (default tier)\n * 1000+ full-page panel stack (scrim 1000, panels 1001+n)\n * 1090 peek scrim 1100 peek panel, ask-proteos window\n * 1150 ← THIS\n * 1200 menu popover, command palette, action dialog, component modal\n * 1300 select popover\n *\n * Above the peek/full-page surfaces a component can live on, below the global\n * host chrome. Note the cap: inside a peek (a `fixed` + z-index ancestor) the\n * promoted iframe paints within that 1100 stacking context — it covers the\n * peek's own content and everything under it, but host chrome at 1200+ still\n * wins. That is the intended layering, not a bug.\n */\nexport const COMPONENT_OVERLAY_Z_INDEX = 1150\n\n/** Viewport-relative box of the iframe's in-flow placeholder, in CSS px. */\nexport interface OverlayRect {\n top: number\n left: number\n width: number\n height: number\n}\n\nexport interface PageContext {\n record?: Record<string, unknown>\n entity?: { slug: string; [key: string]: unknown }\n params?: Record<string, unknown>\n [key: string]: unknown\n}\n\n// ── Host → runtime ──────────────────────────────────────────────────────────\n\nexport interface InitMessage {\n type: 'INIT'\n /** Raw bearer token (the OIDC `id_token`). The runtime's ProteosClient\n * prepends `Bearer ` when building the Authorization header, so the host\n * sends the token verbatim — NOT a full `Bearer …` header value.\n * Empty string in public mode (`isPublic: true`). */\n authToken: string\n /** API origin the bundle endpoint + SDK calls resolve against. */\n apiBaseUrl: string\n /** Resolved props for the component (Liquid templating happens host-side). */\n props: Record<string, unknown>\n pageCtx: PageContext\n /** PUBLIC mode: the component renders on an unauthenticated public page.\n * The shell fetches the bundle from the public endpoint (no bearer) and\n * injects a restricted sdk — only `functions.actions.invokePublic` reaches\n * the platform. Requires `orgId`. */\n isPublic?: boolean\n /** Org id for public mode — public endpoints carry the org in the path\n * because there is no token to scope from. */\n orgId?: string\n /** Set when this frame is the CONTENT of a host component modal (opened by\n * another component via OPEN_MODAL). The component reads it through\n * `useModalHost()` and closes with a result by posting MODAL_RESULT with\n * this id. Absent on ordinary page-hosted frames. */\n modalRequestId?: string\n}\n\nexport interface AuthRefreshMessage {\n type: 'AUTH_REFRESH'\n token: string\n}\n\nexport interface DataInvalidateMessage {\n type: 'DATA_INVALIDATE'\n queryKey?: unknown[]\n}\n\n/** Where the iframe's in-flow box sits in the host viewport. Sent while the\n * frame is promoted (OVERLAY_STATE open) so the runtime can keep its content\n * parked at the original rect while the iframe itself covers the viewport —\n * and re-sent when the host window resizes under an open overlay. */\nexport interface OverlayRectMessage {\n type: 'OVERLAY_RECT'\n rect: OverlayRect\n}\n\n/** Resolution of an OPEN_MODAL request: the host modal closed. `result` is the\n * value the modal's component passed to MODAL_RESULT, and is absent when the\n * modal was dismissed (backdrop / Esc / ×). */\nexport interface ModalClosedMessage {\n type: 'MODAL_CLOSED'\n requestId: string\n result?: unknown\n}\n\nexport type HostMessage =\n | InitMessage\n | AuthRefreshMessage\n | DataInvalidateMessage\n | OverlayRectMessage\n | ModalClosedMessage\n\n// ── Runtime → host ──────────────────────────────────────────────────────────\n\nexport interface ReadyMessage {\n type: 'READY'\n}\n\nexport interface ResizeMessage {\n type: 'RESIZE'\n height: number\n}\n\nexport interface NavigateMessage {\n type: 'NAVIGATE'\n to: string\n}\n\n/** Open an in-app path in a peek (slide-over) panel instead of full-page\n * navigation. Same `/…` in-app path grammar as NAVIGATE; the host decides\n * what can peek (today: platform pages) and falls back to NAVIGATE otherwise. */\nexport interface OpenPeekMessage {\n type: 'OPEN_PEEK'\n to: string\n}\n\n/** Ask the host to open a prepared call: the host shows the conversation brief's\n * preview (its softphone owns the dial) and lets the user place the call.\n * Ignored on public pages and on hosts without a softphone. */\nexport interface OpenCallMessage {\n type: 'OPEN_CALL'\n /** The conversation brief to preview and dial from. */\n conversationBriefId: string\n}\n\n/** The runtime has (or no longer has) an overlay open and needs the host to\n * promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.\n *\n * Same-origin today, so the runtime applies the promotion styles to its own\n * `window.frameElement` synchronously (pre-paint, no flicker) and this message\n * is the host's cue to MIRROR that state into React — gate RESIZE, hold the\n * placeholder height, start posting OVERLAY_RECT. When components move to a\n * dedicated origin the runtime can no longer touch the frame and this message\n * becomes the actuation instead; the runtime hides its overlay until the\n * answering OVERLAY_RECT arrives. */\nexport interface OverlayStateMessage {\n type: 'OVERLAY_STATE'\n open: boolean\n}\n\n/** Ask the host to open ANOTHER component in a central modal, above everything\n * this frame could reach on its own. The host answers with MODAL_CLOSED\n * carrying the same `requestId`. */\nexport interface OpenModalMessage {\n type: 'OPEN_MODAL'\n /** Correlates the eventual MODAL_CLOSED. Generated by the opener. */\n requestId: string\n /** Slug of the component to mount inside the modal. */\n componentSlug: string\n /** Props for that component (already literal values — no Liquid). */\n props?: Record<string, unknown>\n /** Optional modal heading. */\n title?: string\n}\n\n/** Escape was pressed with focus inside the iframe, and nothing in the runtime\n * consumed it.\n *\n * Keyboard events don't cross the iframe boundary, and react-aria binds its\n * Escape handling to the overlay element in its own React tree — so a\n * host-rendered dialog CANNOT see Escape once the user has clicked into a\n * component. The runtime forwards it so the host can dismiss on the user's\n * behalf. Not sent while the runtime has its own overlay open: that overlay\n * owns Escape. */\nexport interface EscapePressedMessage {\n type: 'ESCAPE_PRESSED'\n}\n\n/** Posted by the component INSIDE a host modal to close it with a value. The\n * `requestId` is the one INIT carried as `modalRequestId`. */\nexport interface ModalResultMessage {\n type: 'MODAL_RESULT'\n requestId: string\n result?: unknown\n}\n\nexport interface ErrorMessage {\n type: 'ERROR'\n message: string\n stack?: string\n}\n\nexport type RuntimeMessage =\n | ReadyMessage\n | ResizeMessage\n | NavigateMessage\n | OpenPeekMessage\n | OpenCallMessage\n | OverlayStateMessage\n | OpenModalMessage\n | ModalResultMessage\n | EscapePressedMessage\n | ErrorMessage\n\n// Wire envelope: the message plus the source discriminator.\nexport type Envelope<T> = T & { source: typeof MESSAGE_SOURCE }\n\nexport function isHostMessage(data: unknown): data is Envelope<HostMessage> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { source?: unknown }).source === MESSAGE_SOURCE &&\n typeof (data as { type?: unknown }).type === 'string'\n )\n}\n\nexport function isRuntimeMessage(data: unknown): data is Envelope<RuntimeMessage> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { source?: unknown }).source === MESSAGE_SOURCE &&\n typeof (data as { type?: unknown }).type === 'string'\n )\n}\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,16 +1,24 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkIPYKNCDU_cjs = require('./chunk-IPYKNCDU.cjs');
|
|
4
4
|
var react = require('react');
|
|
5
5
|
var jsxRuntime = require('react/jsx-runtime');
|
|
6
6
|
|
|
7
7
|
var RuntimeContext = react.createContext(null);
|
|
8
8
|
function postNavigate(to) {
|
|
9
|
-
const envelope = { source:
|
|
9
|
+
const envelope = { source: chunkIPYKNCDU_cjs.MESSAGE_SOURCE, type: "NAVIGATE", to };
|
|
10
10
|
window.parent?.postMessage(envelope, "*");
|
|
11
11
|
}
|
|
12
12
|
function postOpenPeek(to) {
|
|
13
|
-
const envelope = { source:
|
|
13
|
+
const envelope = { source: chunkIPYKNCDU_cjs.MESSAGE_SOURCE, type: "OPEN_PEEK", to };
|
|
14
|
+
window.parent?.postMessage(envelope, "*");
|
|
15
|
+
}
|
|
16
|
+
function openCall(conversationBriefId) {
|
|
17
|
+
const envelope = {
|
|
18
|
+
source: chunkIPYKNCDU_cjs.MESSAGE_SOURCE,
|
|
19
|
+
type: "OPEN_CALL",
|
|
20
|
+
conversationBriefId
|
|
21
|
+
};
|
|
14
22
|
window.parent?.postMessage(envelope, "*");
|
|
15
23
|
}
|
|
16
24
|
function navigate(to, options) {
|
|
@@ -24,7 +32,7 @@ function ensureModalListener() {
|
|
|
24
32
|
modalListenerAttached = true;
|
|
25
33
|
window.addEventListener("message", (event) => {
|
|
26
34
|
const data = event.data;
|
|
27
|
-
if (!
|
|
35
|
+
if (!chunkIPYKNCDU_cjs.isHostMessage(data) || data.type !== "MODAL_CLOSED") return;
|
|
28
36
|
const resolve = pendingModals.get(data.requestId);
|
|
29
37
|
if (!resolve) return;
|
|
30
38
|
pendingModals.delete(data.requestId);
|
|
@@ -41,7 +49,7 @@ function openModal(componentSlug, props, options) {
|
|
|
41
49
|
ensureModalListener();
|
|
42
50
|
const requestId = newRequestId();
|
|
43
51
|
const envelope = {
|
|
44
|
-
source:
|
|
52
|
+
source: chunkIPYKNCDU_cjs.MESSAGE_SOURCE,
|
|
45
53
|
type: "OPEN_MODAL",
|
|
46
54
|
requestId,
|
|
47
55
|
componentSlug,
|
|
@@ -55,7 +63,7 @@ function openModal(componentSlug, props, options) {
|
|
|
55
63
|
}
|
|
56
64
|
function postModalResult(requestId, result) {
|
|
57
65
|
const envelope = {
|
|
58
|
-
source:
|
|
66
|
+
source: chunkIPYKNCDU_cjs.MESSAGE_SOURCE,
|
|
59
67
|
type: "MODAL_RESULT",
|
|
60
68
|
requestId,
|
|
61
69
|
...result !== void 0 ? { result } : {}
|
|
@@ -63,7 +71,10 @@ function postModalResult(requestId, result) {
|
|
|
63
71
|
window.parent?.postMessage(envelope, "*");
|
|
64
72
|
}
|
|
65
73
|
function RuntimeProvider({ value, children }) {
|
|
66
|
-
const ctx = react.useMemo(
|
|
74
|
+
const ctx = react.useMemo(
|
|
75
|
+
() => ({ ...value, navigate, openCall, openModal }),
|
|
76
|
+
[value]
|
|
77
|
+
);
|
|
67
78
|
return /* @__PURE__ */ jsxRuntime.jsx(RuntimeContext.Provider, { value: ctx, children });
|
|
68
79
|
}
|
|
69
80
|
function useRuntime() {
|
|
@@ -87,6 +98,9 @@ function usePageContext() {
|
|
|
87
98
|
function useNavigate() {
|
|
88
99
|
return useRuntime().navigate;
|
|
89
100
|
}
|
|
101
|
+
function useOpenCall() {
|
|
102
|
+
return useRuntime().openCall;
|
|
103
|
+
}
|
|
90
104
|
function useApiBaseUrl() {
|
|
91
105
|
return useRuntime().apiBaseUrl;
|
|
92
106
|
}
|
|
@@ -169,19 +183,19 @@ function useFillViewportHeight(options = {}) {
|
|
|
169
183
|
|
|
170
184
|
Object.defineProperty(exports, "COMPONENT_OVERLAY_Z_INDEX", {
|
|
171
185
|
enumerable: true,
|
|
172
|
-
get: function () { return
|
|
186
|
+
get: function () { return chunkIPYKNCDU_cjs.COMPONENT_OVERLAY_Z_INDEX; }
|
|
173
187
|
});
|
|
174
188
|
Object.defineProperty(exports, "MESSAGE_SOURCE", {
|
|
175
189
|
enumerable: true,
|
|
176
|
-
get: function () { return
|
|
190
|
+
get: function () { return chunkIPYKNCDU_cjs.MESSAGE_SOURCE; }
|
|
177
191
|
});
|
|
178
192
|
Object.defineProperty(exports, "isHostMessage", {
|
|
179
193
|
enumerable: true,
|
|
180
|
-
get: function () { return
|
|
194
|
+
get: function () { return chunkIPYKNCDU_cjs.isHostMessage; }
|
|
181
195
|
});
|
|
182
196
|
Object.defineProperty(exports, "isRuntimeMessage", {
|
|
183
197
|
enumerable: true,
|
|
184
|
-
get: function () { return
|
|
198
|
+
get: function () { return chunkIPYKNCDU_cjs.isRuntimeMessage; }
|
|
185
199
|
});
|
|
186
200
|
exports.RuntimeProvider = RuntimeProvider;
|
|
187
201
|
exports.useApiBaseUrl = useApiBaseUrl;
|
|
@@ -191,6 +205,7 @@ exports.useFillViewportHeight = useFillViewportHeight;
|
|
|
191
205
|
exports.useHostLocation = useHostLocation;
|
|
192
206
|
exports.useModalHost = useModalHost;
|
|
193
207
|
exports.useNavigate = useNavigate;
|
|
208
|
+
exports.useOpenCall = useOpenCall;
|
|
194
209
|
exports.useOverlayExpansion = useOverlayExpansion;
|
|
195
210
|
exports.usePageContext = usePageContext;
|
|
196
211
|
exports.useProps = useProps;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context.tsx","../src/hooks.ts"],"names":["createContext","MESSAGE_SOURCE","isHostMessage","useMemo","useContext","useCallback","useState","useEffect"],"mappings":";;;;;;AAuHO,IAAM,cAAA,GAAiBA,oBAA0C,IAAI,CAAA;AAI5E,SAAS,aAAa,EAAA,EAAkB;AACtC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AACT;AAgBO,SAAS,qBAAA,CAAsB,OAAA,GAA+B,EAAC,EAAkB;AACtF,EAAA,MAAM,EAAE,YAAA,GAAe,EAAA,EAAI,SAAA,GAAY,KAAI,GAAI,OAAA;AAC/C,EAAA,MAAM,CAAC,MAAA,EAAQ,SAAS,CAAA,GAAIA,eAAwB,IAAI,CAAA;AAExD,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,SAAS,OAAA,GAAgB;AACvB,MAAA,IAAI;AACF,QAAA,MAAM,QAAQ,MAAA,CAAO,YAAA;AACrB,QAAA,MAAM,eAAe,MAAA,CAAO,MAAA;AAC5B,QAAA,IAAI,CAAC,KAAA,IAAS,CAAC,YAAA,IAAgB,iBAAiB,MAAA,EAAQ;AACxD,QAAA,MAAM,YACJ,YAAA,CAAa,WAAA,GAAc,KAAA,CAAM,qBAAA,GAAwB,GAAA,GAAM,YAAA;AACjE,QAAA,SAAA,CAAU,IAAA,CAAK,GAAA,CAAI,SAAA,EAAW,SAAS,CAAC,CAAA;AAAA,MAC1C,CAAA,CAAA,MAAQ;AACN,QAAA,SAAA,CAAU,IAAI,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,MAAA,CAAO,gBAAA,CAAiB,QAAA,EAAU,OAAO,CAAA;AAChD,MAAA,OAAO,MAAM,MAAA,CAAO,MAAA,CAAO,mBAAA,CAAoB,UAAU,OAAO,CAAA;AAAA,IAClE,CAAA,CAAA,MAAQ;AACN,MAAA;AAAA,IACF;AAAA,EACF,CAAA,EAAG,CAAC,YAAA,EAAc,SAAS,CAAC,CAAA;AAE5B,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["import type {\n AccountClient,\n AgentClient,\n ConversationClient,\n DataClient,\n FunctionsClient,\n KnowledgeClient,\n MetaClient,\n StorageClient,\n} from '@proteos/sdk'\nimport { createContext, type ReactNode, useMemo } from 'react'\n\nimport {\n type Envelope,\n isHostMessage,\n MESSAGE_SOURCE,\n type ModalResultMessage,\n type NavigateMessage,\n type OpenModalMessage,\n type OpenPeekMessage,\n type PageContext,\n} from './protocol'\n\n/** Options for {@link RuntimeContextValue.navigate}. */\nexport interface NavigateOptions {\n /** Open the target in a peek (slide-over) panel instead of full-page. */\n peek?: boolean\n}\n\n/** Options for {@link RuntimeContextValue.openModal}. */\nexport interface OpenModalOptions {\n /** Heading rendered in the modal chrome. */\n title?: string\n}\n\n/**\n * Manual control over iframe overlay promotion. The runtime already detects\n * overlays automatically (anything portaled to the iframe's `document.body` —\n * every `@proteos/ui` overlay qualifies), so components need this only for\n * custom portal targets, or to promote a frame *before* opening an overlay.\n * Calls are reference-counted: every `expand()` needs its `collapse()`.\n */\nexport interface OverlayController {\n expand: () => void\n collapse: () => void\n isExpanded: () => boolean\n}\n\n/**\n * The authenticated `@proteos/sdk` clients the runtime injects. Same instances\n * the host app uses — pre-wired with a refreshing bearer token, so a component\n * never touches auth headers.\n */\nexport interface ComponentSdk {\n account: AccountClient\n agents: AgentClient\n /**\n * Conversations, messages, contacts, connections (conversation-service) —\n * e.g. the DraftMessageComposer review surface. Plural per the platform's\n * resource-naming rule; the web app's own `useSdk().conversation` predates\n * it (documented asymmetry).\n */\n conversations: ConversationClient\n data: DataClient\n functions: FunctionsClient\n knowledge: KnowledgeClient\n meta: MetaClient\n storage: StorageClient\n}\n\n/**\n * The raw runtime payload the shell hands a component at INIT. The shell builds\n * this; component authors read it through the hooks.\n */\nexport interface RuntimeValue {\n /**\n * The injected sdk clients. On an authenticated page these are the full,\n * bearer-wired clients. On a PUBLIC page (`isPublic: true`) only\n * `functions.actions.invokePublic` reaches the platform — every other\n * client throws on use (there is no token, and the server rejects\n * unauthenticated calls anyway).\n */\n sdk: ComponentSdk\n /** Liquid-resolved props (a snapshot — not a live binding). */\n props: Record<string, unknown>\n /** Page context snapshot: the host record, entity, and URL params. */\n pageCtx: PageContext\n /** API origin SDK calls + asset URLs resolve against. */\n apiBaseUrl: string\n /** Current bearer token getter (escape hatch for raw fetches). Returns ''\n * on public pages. */\n getToken: () => string\n /** True when rendering on an unauthenticated public page. */\n isPublic?: boolean\n /** Org id, set in public mode (public API routes carry it in the path). */\n orgId?: string\n /** Set when this component is the content of a host component modal — the\n * correlation id it closes with. See `useModalHost()`. */\n modalRequestId?: string\n /** Overlay promotion controller, provided by the shell. Absent on older\n * shells / non-promoting hosts, in which case `useOverlayExpansion()`\n * no-ops. */\n overlay?: OverlayController\n}\n\n/** Runtime value plus the derived helpers the hooks expose. */\nexport interface RuntimeContextValue extends RuntimeValue {\n /** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or\n * open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */\n navigate: (to: string, options?: NavigateOptions) => void\n /** Open another component in a host-rendered modal; resolves with the value\n * that component closed with (`undefined` if dismissed). */\n openModal: (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n ) => Promise<unknown>\n}\n\nexport const RuntimeContext = createContext<RuntimeContextValue | null>(null)\n\n/** Post a NAVIGATE envelope to the host. The host only honours relative,\n * in-app targets (it ignores absolute/external URLs). */\nfunction postNavigate(to: string): void {\n const envelope: Envelope<NavigateMessage> = { source: MESSAGE_SOURCE, type: 'NAVIGATE', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Post an OPEN_PEEK envelope to the host — open the in-app path in a peek\n * panel. Same relative-path contract as {@link postNavigate}. */\nfunction postOpenPeek(to: string): void {\n const envelope: Envelope<OpenPeekMessage> = { source: MESSAGE_SOURCE, type: 'OPEN_PEEK', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Navigate full-page (default) or into a peek panel (`{ peek: true }`). */\nfunction navigate(to: string, options?: NavigateOptions): void {\n if (options?.peek) postOpenPeek(to)\n else postNavigate(to)\n}\n\n// ── Component modals ────────────────────────────────────────────────────────\n// One module-level listener + a pending map, rather than a listener per call:\n// the SDK is an import-mapped singleton, so this is per-iframe state.\n\nconst pendingModals = new Map<string, (result: unknown) => void>()\nlet modalListenerAttached = false\n\nfunction ensureModalListener(): void {\n if (modalListenerAttached) return\n modalListenerAttached = true\n window.addEventListener('message', (event: MessageEvent) => {\n const data: unknown = event.data\n if (!isHostMessage(data) || data.type !== 'MODAL_CLOSED') return\n const resolve = pendingModals.get(data.requestId)\n // An unknown requestId is someone else's modal (or a stale reply) — drop it.\n if (!resolve) return\n pendingModals.delete(data.requestId)\n resolve(data.result)\n })\n}\n\nfunction newRequestId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n return `modal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** Post OPEN_MODAL and resolve when the host answers MODAL_CLOSED. */\nfunction openModal(\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n): Promise<unknown> {\n ensureModalListener()\n const requestId = newRequestId()\n const envelope: Envelope<OpenModalMessage> = {\n source: MESSAGE_SOURCE,\n type: 'OPEN_MODAL',\n requestId,\n componentSlug,\n ...(props !== undefined ? { props } : {}),\n ...(options?.title !== undefined ? { title: options.title } : {}),\n }\n return new Promise<unknown>((resolve) => {\n pendingModals.set(requestId, resolve)\n window.parent?.postMessage(envelope, '*')\n })\n}\n\n/** Post MODAL_RESULT — the component inside a host modal closing with a value. */\nexport function postModalResult(requestId: string, result?: unknown): void {\n const envelope: Envelope<ModalResultMessage> = {\n source: MESSAGE_SOURCE,\n type: 'MODAL_RESULT',\n requestId,\n ...(result !== undefined ? { result } : {}),\n }\n window.parent?.postMessage(envelope, '*')\n}\n\n/**\n * Provides the runtime value + derived helpers to a component subtree. Mounted\n * by the component-runtime shell around the loaded component — authors never\n * render this themselves. Lives in `@proteos/component-sdk` (a shared,\n * import-mapped singleton) so the context the shell provides is the very same\n * context the component's hooks read, across the bundle boundary.\n */\nexport function RuntimeProvider({ value, children }: { value: RuntimeValue; children: ReactNode }) {\n // The shell builds `value` once at INIT (a stable state object — clients,\n // props and pageCtx are all set once), so memoizing on its identity recreates\n // the context only when the runtime genuinely re-inits.\n const ctx = useMemo<RuntimeContextValue>(() => ({ ...value, navigate, openModal }), [value])\n return <RuntimeContext.Provider value={ctx}>{children}</RuntimeContext.Provider>\n}\n","import { useCallback, useContext, useEffect, useMemo, useState } from 'react'\n\nimport {\n type ComponentSdk,\n type NavigateOptions,\n type OpenModalOptions,\n type OverlayController,\n postModalResult,\n RuntimeContext,\n type RuntimeContextValue,\n} from './context'\nimport type { PageContext } from './protocol'\n\n/**\n * Low-level escape hatch: the whole runtime context (sdk, props, pageCtx,\n * apiBaseUrl, getToken, navigate). Prefer the focused hooks below. Throws a\n * clear error if used outside the component runtime.\n */\nexport function useRuntime(): RuntimeContextValue {\n const ctx = useContext(RuntimeContext)\n if (!ctx) {\n throw new Error(\n '@proteos/component-sdk: hooks must run inside the Proteos component runtime. ' +\n 'This usually means the component is rendered outside its iframe, or a ' +\n 'second copy of @proteos/component-sdk was bundled instead of using the ' +\n 'runtime-provided one (keep it external).',\n )\n }\n return ctx\n}\n\n/** The authenticated SDK clients (account / agents / conversations / data / functions / knowledge / meta / storage). */\nexport function useSdk(): ComponentSdk {\n return useRuntime().sdk\n}\n\n/** The component's Liquid-resolved props (a snapshot, not a live binding). */\nexport function useProps<T extends Record<string, unknown> = Record<string, unknown>>(): T {\n return useRuntime().props as T\n}\n\n/**\n * The full page context: host `record`, `entity`, and URL `params`. The\n * `record` is a snapshot taken at mount (`undefined` on record-less platform\n * pages) — fetch via `useSdk().data` for anything that must stay fresh.\n */\nexport function usePageContext(): PageContext {\n return useRuntime().pageCtx\n}\n\n/**\n * Navigate the host SPA to an in-app path, e.g.\n * `navigate('/org/acme/record/task/123')`. The host ignores absolute/external\n * URLs. Build org/app-prefixed paths with `useHostLocation().appBasePath`.\n *\n * Pass `{ peek: true }` to open the path in a peek (slide-over) panel instead\n * of full-page navigation — e.g. `navigate(path, { peek: true })`. The host\n * peeks what it can (today: platform pages) and falls back to full navigation.\n */\nexport function useNavigate(): (to: string, options?: NavigateOptions) => void {\n return useRuntime().navigate\n}\n\n/** The API origin SDK calls resolve against (for building raw asset URLs). */\nexport function useApiBaseUrl(): string {\n return useRuntime().apiBaseUrl\n}\n\nconst NOOP_OVERLAY: OverlayController = {\n expand: () => {\n console.warn(\n '@proteos/component-sdk: useOverlayExpansion() has no effect — this runtime ' +\n 'does not support overlay promotion (older shell or non-promoting host).',\n )\n },\n collapse: () => {},\n isExpanded: () => false,\n}\n\n/**\n * Manual overlay promotion — lifts the whole component iframe over the rest of\n * the page so an overlay can escape the frame's box.\n *\n * You rarely need this. Every `@proteos/ui` overlay (Modal, Popover, Menu,\n * Select, Tooltip, …) portals to the iframe document's `<body>`, which the\n * runtime watches — those promote automatically, with no code. Reach for this\n * hook only when you portal somewhere else yourself, or want the frame lifted\n * *before* the overlay mounts. Reference-counted: pair every `expand()` with a\n * `collapse()`.\n */\nexport function useOverlayExpansion(): OverlayController {\n return useRuntime().overlay ?? NOOP_OVERLAY\n}\n\n/**\n * Open ANOTHER component in a modal the host renders above everything — the\n * cross-component flow (a picker, a wizard step, a confirm dialog shared by\n * several components). Resolves with whatever that component closed with, or\n * `undefined` if the user dismissed it.\n *\n * ```ts\n * const openModal = useComponentModal()\n * const picked = await openModal('contact-picker', { entity: 'contact' }, { title: 'Pick a contact' })\n * ```\n *\n * For an overlay that is part of THIS component, just render a `<Modal>` from\n * `@proteos/ui` — it promotes automatically.\n */\nexport function useComponentModal(): (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n) => Promise<unknown> {\n return useRuntime().openModal\n}\n\nexport interface ModalHost {\n /** True when this component is rendered as the content of a host modal. */\n isInModal: boolean\n /** Close the host modal, resolving the opener's promise with `result`.\n * No-op outside a modal. */\n close: (result?: unknown) => void\n}\n\n/**\n * For a component that is being shown INSIDE a host modal (opened by another\n * component's `useComponentModal()`): close it and hand a value back.\n * `isInModal` is false on ordinary page-hosted mounts, so one component can\n * serve both roles.\n */\nexport function useModalHost(): ModalHost {\n const requestId = useRuntime().modalRequestId\n const close = useCallback(\n (result?: unknown) => {\n if (requestId === undefined) return\n postModalResult(requestId, result)\n },\n [requestId],\n )\n return useMemo(() => ({ isInModal: requestId !== undefined, close }), [requestId, close])\n}\n\n/**\n * A getter for the current bearer token. Returns a function (not the token)\n * because the token is refreshed in place — read it at call time for a raw\n * `fetch`. Most components never need this; prefer `useSdk()`.\n */\nexport function useAuthToken(): () => string {\n return useRuntime().getToken\n}\n\nexport interface HostLocation {\n /** The host tab's pathname (same-origin read), or null if unavailable. */\n pathname: string | null\n /** The org id parsed from `/org/<orgId>/…`, or null. */\n orgId: string | null\n /** The `/org/<orgId>/app/<appId>` prefix, or null when not on an app page. */\n appBasePath: string | null\n}\n\nfunction readHostLocation(): HostLocation {\n const empty: HostLocation = { pathname: null, orgId: null, appBasePath: null }\n try {\n const parentWindow = window.parent\n if (!parentWindow || parentWindow === window) return empty\n const pathname = parentWindow.location.pathname\n const appMatch = pathname.match(/^\\/org\\/[^/]+\\/app\\/[^/]+/)\n const orgMatch = pathname.match(/^\\/org\\/([^/]+)\\//)\n return {\n pathname,\n orgId: orgMatch ? (orgMatch[1] ?? null) : null,\n appBasePath: appMatch ? appMatch[0] : null,\n }\n } catch {\n // Cross-origin (untrusted-component future) or detached — fall back to null.\n return empty\n }\n}\n\n/**\n * Read the host tab's location (same-origin) — the org id and `/org/.../app/...`\n * prefix needed to build navigation targets on platform pages. Read once on\n * mount (the iframe re-inits when the host route changes).\n */\nexport function useHostLocation(): HostLocation {\n const [loc] = useState(readHostLocation)\n return loc\n}\n\nexport interface FillViewportOptions {\n /** Gap left below the component (px). Default 24. */\n bottomMargin?: number\n /** Floor for the computed height (px). Default 320. */\n minHeight?: number\n}\n\n/**\n * Compute a \"fill the rest of the viewport\" height for full-bleed layouts\n * (boards, canvases). The runtime auto-sizes the iframe to its content, so a\n * component can't use its own `vh` units (circular). The iframe is same-origin,\n * so this measures the parent viewport minus the iframe's offset instead.\n * Returns `null` when it can't measure (fall back to natural height).\n */\nexport function useFillViewportHeight(options: FillViewportOptions = {}): number | null {\n const { bottomMargin = 24, minHeight = 320 } = options\n const [height, setHeight] = useState<number | null>(null)\n\n useEffect(() => {\n function compute(): void {\n try {\n const frame = window.frameElement\n const parentWindow = window.parent\n if (!frame || !parentWindow || parentWindow === window) return\n const available =\n parentWindow.innerHeight - frame.getBoundingClientRect().top - bottomMargin\n setHeight(Math.max(available, minHeight))\n } catch {\n setHeight(null) // cross-origin or detached — fall back to natural height\n }\n }\n compute()\n try {\n window.parent.addEventListener('resize', compute)\n return () => window.parent.removeEventListener('resize', compute)\n } catch {\n return\n }\n }, [bottomMargin, minHeight])\n\n return height\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/context.tsx","../src/hooks.ts"],"names":["createContext","MESSAGE_SOURCE","isHostMessage","useMemo","useContext","useCallback","useState","useEffect"],"mappings":";;;;;;AA2HO,IAAM,cAAA,GAAiBA,oBAA0C,IAAI,CAAA;AAI5E,SAAS,aAAa,EAAA,EAAkB;AACtC,EAAA,MAAM,WAAsC,EAAE,MAAA,EAAQC,gCAAA,EAAgB,IAAA,EAAM,YAAY,EAAA,EAAG;AAC3F,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,EAAU,GAAG,CAAA;AAC1C;AAIA,SAAS,aAAa,EAAA,EAAkB;AACtC,EAAA,MAAM,WAAsC,EAAE,MAAA,EAAQA,gCAAA,EAAgB,IAAA,EAAM,aAAa,EAAA,EAAG;AAC5F,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,EAAU,GAAG,CAAA;AAC1C;AAGA,SAAS,SAAS,mBAAA,EAAmC;AACnD,EAAA,MAAM,QAAA,GAAsC;AAAA,IAC1C,MAAA,EAAQA,gCAAA;AAAA,IACR,IAAA,EAAM,WAAA;AAAA,IACN;AAAA,GACF;AACA,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,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AAA,GAAgB;AACvB,MAAA,IAAI;AACF,QAAA,MAAM,QAAQ,MAAA,CAAO,YAAA;AACrB,QAAA,MAAM,eAAe,MAAA,CAAO,MAAA;AAC5B,QAAA,IAAI,CAAC,KAAA,IAAS,CAAC,YAAA,IAAgB,iBAAiB,MAAA,EAAQ;AACxD,QAAA,MAAM,YACJ,YAAA,CAAa,WAAA,GAAc,KAAA,CAAM,qBAAA,GAAwB,GAAA,GAAM,YAAA;AACjE,QAAA,SAAA,CAAU,IAAA,CAAK,GAAA,CAAI,SAAA,EAAW,SAAS,CAAC,CAAA;AAAA,MAC1C,CAAA,CAAA,MAAQ;AACN,QAAA,SAAA,CAAU,IAAI,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,MAAA,CAAO,gBAAA,CAAiB,QAAA,EAAU,OAAO,CAAA;AAChD,MAAA,OAAO,MAAM,MAAA,CAAO,MAAA,CAAO,mBAAA,CAAoB,UAAU,OAAO,CAAA;AAAA,IAClE,CAAA,CAAA,MAAQ;AACN,MAAA;AAAA,IACF;AAAA,EACF,CAAA,EAAG,CAAC,YAAA,EAAc,SAAS,CAAC,CAAA;AAE5B,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["import type {\n AccountClient,\n AgentClient,\n ConversationClient,\n DataClient,\n FunctionsClient,\n KnowledgeClient,\n MetaClient,\n StorageClient,\n} from '@proteos/sdk'\nimport { createContext, type ReactNode, useMemo } from 'react'\n\nimport {\n type Envelope,\n isHostMessage,\n MESSAGE_SOURCE,\n type ModalResultMessage,\n type NavigateMessage,\n type OpenCallMessage,\n type OpenModalMessage,\n type OpenPeekMessage,\n type PageContext,\n} from './protocol'\n\n/** Options for {@link RuntimeContextValue.navigate}. */\nexport interface NavigateOptions {\n /** Open the target in a peek (slide-over) panel instead of full-page. */\n peek?: boolean\n}\n\n/** Options for {@link RuntimeContextValue.openModal}. */\nexport interface OpenModalOptions {\n /** Heading rendered in the modal chrome. */\n title?: string\n}\n\n/**\n * Manual control over iframe overlay promotion. The runtime already detects\n * overlays automatically (anything portaled to the iframe's `document.body` —\n * every `@proteos/ui` overlay qualifies), so components need this only for\n * custom portal targets, or to promote a frame *before* opening an overlay.\n * Calls are reference-counted: every `expand()` needs its `collapse()`.\n */\nexport interface OverlayController {\n expand: () => void\n collapse: () => void\n isExpanded: () => boolean\n}\n\n/**\n * The authenticated `@proteos/sdk` clients the runtime injects. Same instances\n * the host app uses — pre-wired with a refreshing bearer token, so a component\n * never touches auth headers.\n */\nexport interface ComponentSdk {\n account: AccountClient\n agents: AgentClient\n /**\n * Conversations, messages, contacts, connections (conversation-service) —\n * e.g. the DraftMessageComposer review surface. Plural per the platform's\n * resource-naming rule; the web app's own `useSdk().conversation` predates\n * it (documented asymmetry).\n */\n conversations: ConversationClient\n data: DataClient\n functions: FunctionsClient\n knowledge: KnowledgeClient\n meta: MetaClient\n storage: StorageClient\n}\n\n/**\n * The raw runtime payload the shell hands a component at INIT. The shell builds\n * this; component authors read it through the hooks.\n */\nexport interface RuntimeValue {\n /**\n * The injected sdk clients. On an authenticated page these are the full,\n * bearer-wired clients. On a PUBLIC page (`isPublic: true`) only\n * `functions.actions.invokePublic` reaches the platform — every other\n * client throws on use (there is no token, and the server rejects\n * unauthenticated calls anyway).\n */\n sdk: ComponentSdk\n /** Liquid-resolved props (a snapshot — not a live binding). */\n props: Record<string, unknown>\n /** Page context snapshot: the host record, entity, and URL params. */\n pageCtx: PageContext\n /** API origin SDK calls + asset URLs resolve against. */\n apiBaseUrl: string\n /** Current bearer token getter (escape hatch for raw fetches). Returns ''\n * on public pages. */\n getToken: () => string\n /** True when rendering on an unauthenticated public page. */\n isPublic?: boolean\n /** Org id, set in public mode (public API routes carry it in the path). */\n orgId?: string\n /** Set when this component is the content of a host component modal — the\n * correlation id it closes with. See `useModalHost()`. */\n modalRequestId?: string\n /** Overlay promotion controller, provided by the shell. Absent on older\n * shells / non-promoting hosts, in which case `useOverlayExpansion()`\n * no-ops. */\n overlay?: OverlayController\n}\n\n/** Runtime value plus the derived helpers the hooks expose. */\nexport interface RuntimeContextValue extends RuntimeValue {\n /** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or\n * open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */\n navigate: (to: string, options?: NavigateOptions) => void\n /** Ask the host to open a prepared call from a conversation brief (posts\n * OPEN_CALL): the host previews the brief and dials through its softphone. */\n openCall: (conversationBriefId: string) => void\n /** Open another component in a host-rendered modal; resolves with the value\n * that component closed with (`undefined` if dismissed). */\n openModal: (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n ) => Promise<unknown>\n}\n\nexport const RuntimeContext = createContext<RuntimeContextValue | null>(null)\n\n/** Post a NAVIGATE envelope to the host. The host only honours relative,\n * in-app targets (it ignores absolute/external URLs). */\nfunction postNavigate(to: string): void {\n const envelope: Envelope<NavigateMessage> = { source: MESSAGE_SOURCE, type: 'NAVIGATE', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Post an OPEN_PEEK envelope to the host — open the in-app path in a peek\n * panel. Same relative-path contract as {@link postNavigate}. */\nfunction postOpenPeek(to: string): void {\n const envelope: Envelope<OpenPeekMessage> = { source: MESSAGE_SOURCE, type: 'OPEN_PEEK', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Post OPEN_CALL — the host previews the conversation brief and owns the dial. */\nfunction openCall(conversationBriefId: string): void {\n const envelope: Envelope<OpenCallMessage> = {\n source: MESSAGE_SOURCE,\n type: 'OPEN_CALL',\n conversationBriefId,\n }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Navigate full-page (default) or into a peek panel (`{ peek: true }`). */\nfunction navigate(to: string, options?: NavigateOptions): void {\n if (options?.peek) postOpenPeek(to)\n else postNavigate(to)\n}\n\n// ── Component modals ────────────────────────────────────────────────────────\n// One module-level listener + a pending map, rather than a listener per call:\n// the SDK is an import-mapped singleton, so this is per-iframe state.\n\nconst pendingModals = new Map<string, (result: unknown) => void>()\nlet modalListenerAttached = false\n\nfunction ensureModalListener(): void {\n if (modalListenerAttached) return\n modalListenerAttached = true\n window.addEventListener('message', (event: MessageEvent) => {\n const data: unknown = event.data\n if (!isHostMessage(data) || data.type !== 'MODAL_CLOSED') return\n const resolve = pendingModals.get(data.requestId)\n // An unknown requestId is someone else's modal (or a stale reply) — drop it.\n if (!resolve) return\n pendingModals.delete(data.requestId)\n resolve(data.result)\n })\n}\n\nfunction newRequestId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n return `modal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** Post OPEN_MODAL and resolve when the host answers MODAL_CLOSED. */\nfunction openModal(\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n): Promise<unknown> {\n ensureModalListener()\n const requestId = newRequestId()\n const envelope: Envelope<OpenModalMessage> = {\n source: MESSAGE_SOURCE,\n type: 'OPEN_MODAL',\n requestId,\n componentSlug,\n ...(props !== undefined ? { props } : {}),\n ...(options?.title !== undefined ? { title: options.title } : {}),\n }\n return new Promise<unknown>((resolve) => {\n pendingModals.set(requestId, resolve)\n window.parent?.postMessage(envelope, '*')\n })\n}\n\n/** Post MODAL_RESULT — the component inside a host modal closing with a value. */\nexport function postModalResult(requestId: string, result?: unknown): void {\n const envelope: Envelope<ModalResultMessage> = {\n source: MESSAGE_SOURCE,\n type: 'MODAL_RESULT',\n requestId,\n ...(result !== undefined ? { result } : {}),\n }\n window.parent?.postMessage(envelope, '*')\n}\n\n/**\n * Provides the runtime value + derived helpers to a component subtree. Mounted\n * by the component-runtime shell around the loaded component — authors never\n * render this themselves. Lives in `@proteos/component-sdk` (a shared,\n * import-mapped singleton) so the context the shell provides is the very same\n * context the component's hooks read, across the bundle boundary.\n */\nexport function RuntimeProvider({ value, children }: { value: RuntimeValue; children: ReactNode }) {\n // The shell builds `value` once at INIT (a stable state object — clients,\n // props and pageCtx are all set once), so memoizing on its identity recreates\n // the context only when the runtime genuinely re-inits.\n const ctx = useMemo<RuntimeContextValue>(\n () => ({ ...value, navigate, openCall, openModal }),\n [value],\n )\n return <RuntimeContext.Provider value={ctx}>{children}</RuntimeContext.Provider>\n}\n","import { useCallback, useContext, useEffect, useMemo, useState } from 'react'\n\nimport {\n type ComponentSdk,\n type NavigateOptions,\n type OpenModalOptions,\n type OverlayController,\n postModalResult,\n RuntimeContext,\n type RuntimeContextValue,\n} from './context'\nimport type { PageContext } from './protocol'\n\n/**\n * Low-level escape hatch: the whole runtime context (sdk, props, pageCtx,\n * apiBaseUrl, getToken, navigate). Prefer the focused hooks below. Throws a\n * clear error if used outside the component runtime.\n */\nexport function useRuntime(): RuntimeContextValue {\n const ctx = useContext(RuntimeContext)\n if (!ctx) {\n throw new Error(\n '@proteos/component-sdk: hooks must run inside the Proteos component runtime. ' +\n 'This usually means the component is rendered outside its iframe, or a ' +\n 'second copy of @proteos/component-sdk was bundled instead of using the ' +\n 'runtime-provided one (keep it external).',\n )\n }\n return ctx\n}\n\n/** The authenticated SDK clients (account / agents / conversations / data / functions / knowledge / meta / storage). */\nexport function useSdk(): ComponentSdk {\n return useRuntime().sdk\n}\n\n/** The component's Liquid-resolved props (a snapshot, not a live binding). */\nexport function useProps<T extends Record<string, unknown> = Record<string, unknown>>(): T {\n return useRuntime().props as T\n}\n\n/**\n * The full page context: host `record`, `entity`, and URL `params`. The\n * `record` is a snapshot taken at mount (`undefined` on record-less platform\n * pages) — fetch via `useSdk().data` for anything that must stay fresh.\n */\nexport function usePageContext(): PageContext {\n return useRuntime().pageCtx\n}\n\n/**\n * Navigate the host SPA to an in-app path, e.g.\n * `navigate('/org/acme/record/task/123')`. The host ignores absolute/external\n * URLs. Build org/app-prefixed paths with `useHostLocation().appBasePath`.\n *\n * Pass `{ peek: true }` to open the path in a peek (slide-over) panel instead\n * of full-page navigation — e.g. `navigate(path, { peek: true })`. The host\n * peeks what it can (today: platform pages) and falls back to full navigation.\n */\nexport function useNavigate(): (to: string, options?: NavigateOptions) => void {\n return useRuntime().navigate\n}\n\n/**\n * Open a prepared call from a conversation brief id: the HOST previews the brief and\n * places the call through its softphone (an iframe cannot dial). Pair it with\n * `ConversationBriefReview`'s `onOpenCall` from `@proteos/ui`.\n */\nexport function useOpenCall(): (conversationBriefId: string) => void {\n return useRuntime().openCall\n}\n\n/** The API origin SDK calls resolve against (for building raw asset URLs). */\nexport function useApiBaseUrl(): string {\n return useRuntime().apiBaseUrl\n}\n\nconst NOOP_OVERLAY: OverlayController = {\n expand: () => {\n console.warn(\n '@proteos/component-sdk: useOverlayExpansion() has no effect — this runtime ' +\n 'does not support overlay promotion (older shell or non-promoting host).',\n )\n },\n collapse: () => {},\n isExpanded: () => false,\n}\n\n/**\n * Manual overlay promotion — lifts the whole component iframe over the rest of\n * the page so an overlay can escape the frame's box.\n *\n * You rarely need this. Every `@proteos/ui` overlay (Modal, Popover, Menu,\n * Select, Tooltip, …) portals to the iframe document's `<body>`, which the\n * runtime watches — those promote automatically, with no code. Reach for this\n * hook only when you portal somewhere else yourself, or want the frame lifted\n * *before* the overlay mounts. Reference-counted: pair every `expand()` with a\n * `collapse()`.\n */\nexport function useOverlayExpansion(): OverlayController {\n return useRuntime().overlay ?? NOOP_OVERLAY\n}\n\n/**\n * Open ANOTHER component in a modal the host renders above everything — the\n * cross-component flow (a picker, a wizard step, a confirm dialog shared by\n * several components). Resolves with whatever that component closed with, or\n * `undefined` if the user dismissed it.\n *\n * ```ts\n * const openModal = useComponentModal()\n * const picked = await openModal('contact-picker', { entity: 'contact' }, { title: 'Pick a contact' })\n * ```\n *\n * For an overlay that is part of THIS component, just render a `<Modal>` from\n * `@proteos/ui` — it promotes automatically.\n */\nexport function useComponentModal(): (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n) => Promise<unknown> {\n return useRuntime().openModal\n}\n\nexport interface ModalHost {\n /** True when this component is rendered as the content of a host modal. */\n isInModal: boolean\n /** Close the host modal, resolving the opener's promise with `result`.\n * No-op outside a modal. */\n close: (result?: unknown) => void\n}\n\n/**\n * For a component that is being shown INSIDE a host modal (opened by another\n * component's `useComponentModal()`): close it and hand a value back.\n * `isInModal` is false on ordinary page-hosted mounts, so one component can\n * serve both roles.\n */\nexport function useModalHost(): ModalHost {\n const requestId = useRuntime().modalRequestId\n const close = useCallback(\n (result?: unknown) => {\n if (requestId === undefined) return\n postModalResult(requestId, result)\n },\n [requestId],\n )\n return useMemo(() => ({ isInModal: requestId !== undefined, close }), [requestId, close])\n}\n\n/**\n * A getter for the current bearer token. Returns a function (not the token)\n * because the token is refreshed in place — read it at call time for a raw\n * `fetch`. Most components never need this; prefer `useSdk()`.\n */\nexport function useAuthToken(): () => string {\n return useRuntime().getToken\n}\n\nexport interface HostLocation {\n /** The host tab's pathname (same-origin read), or null if unavailable. */\n pathname: string | null\n /** The org id parsed from `/org/<orgId>/…`, or null. */\n orgId: string | null\n /** The `/org/<orgId>/app/<appId>` prefix, or null when not on an app page. */\n appBasePath: string | null\n}\n\nfunction readHostLocation(): HostLocation {\n const empty: HostLocation = { pathname: null, orgId: null, appBasePath: null }\n try {\n const parentWindow = window.parent\n if (!parentWindow || parentWindow === window) return empty\n const pathname = parentWindow.location.pathname\n const appMatch = pathname.match(/^\\/org\\/[^/]+\\/app\\/[^/]+/)\n const orgMatch = pathname.match(/^\\/org\\/([^/]+)\\//)\n return {\n pathname,\n orgId: orgMatch ? (orgMatch[1] ?? null) : null,\n appBasePath: appMatch ? appMatch[0] : null,\n }\n } catch {\n // Cross-origin (untrusted-component future) or detached — fall back to null.\n return empty\n }\n}\n\n/**\n * Read the host tab's location (same-origin) — the org id and `/org/.../app/...`\n * prefix needed to build navigation targets on platform pages. Read once on\n * mount (the iframe re-inits when the host route changes).\n */\nexport function useHostLocation(): HostLocation {\n const [loc] = useState(readHostLocation)\n return loc\n}\n\nexport interface FillViewportOptions {\n /** Gap left below the component (px). Default 24. */\n bottomMargin?: number\n /** Floor for the computed height (px). Default 320. */\n minHeight?: number\n}\n\n/**\n * Compute a \"fill the rest of the viewport\" height for full-bleed layouts\n * (boards, canvases). The runtime auto-sizes the iframe to its content, so a\n * component can't use its own `vh` units (circular). The iframe is same-origin,\n * so this measures the parent viewport minus the iframe's offset instead.\n * Returns `null` when it can't measure (fall back to natural height).\n */\nexport function useFillViewportHeight(options: FillViewportOptions = {}): number | null {\n const { bottomMargin = 24, minHeight = 320 } = options\n const [height, setHeight] = useState<number | null>(null)\n\n useEffect(() => {\n function compute(): void {\n try {\n const frame = window.frameElement\n const parentWindow = window.parent\n if (!frame || !parentWindow || parentWindow === window) return\n const available =\n parentWindow.innerHeight - frame.getBoundingClientRect().top - bottomMargin\n setHeight(Math.max(available, minHeight))\n } catch {\n setHeight(null) // cross-origin or detached — fall back to natural height\n }\n }\n compute()\n try {\n window.parent.addEventListener('resize', compute)\n return () => window.parent.removeEventListener('resize', compute)\n } catch {\n return\n }\n }, [bottomMargin, minHeight])\n\n return height\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { AccountClient, AgentClient, ConversationClient, DataClient, FunctionsClient, KnowledgeClient, MetaClient, StorageClient } from '@proteos/sdk';
|
|
4
4
|
import { PageContext } from './protocol.cjs';
|
|
5
|
-
export { AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, DataInvalidateMessage, Envelope, ErrorMessage, EscapePressedMessage, HostMessage, InitMessage, MESSAGE_SOURCE, ModalClosedMessage, ModalResultMessage, NavigateMessage, OpenModalMessage, OpenPeekMessage, OverlayRect, OverlayRectMessage, OverlayStateMessage, ReadyMessage, ResizeMessage, RuntimeMessage, isHostMessage, isRuntimeMessage } from './protocol.cjs';
|
|
5
|
+
export { AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, DataInvalidateMessage, Envelope, ErrorMessage, EscapePressedMessage, HostMessage, InitMessage, MESSAGE_SOURCE, ModalClosedMessage, ModalResultMessage, NavigateMessage, OpenCallMessage, OpenModalMessage, OpenPeekMessage, OverlayRect, OverlayRectMessage, OverlayStateMessage, ReadyMessage, ResizeMessage, RuntimeMessage, isHostMessage, isRuntimeMessage } from './protocol.cjs';
|
|
6
6
|
|
|
7
7
|
/** Options for {@link RuntimeContextValue.navigate}. */
|
|
8
8
|
interface NavigateOptions {
|
|
@@ -86,6 +86,9 @@ interface RuntimeContextValue extends RuntimeValue {
|
|
|
86
86
|
/** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or
|
|
87
87
|
* open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */
|
|
88
88
|
navigate: (to: string, options?: NavigateOptions) => void;
|
|
89
|
+
/** Ask the host to open a prepared call from a conversation brief (posts
|
|
90
|
+
* OPEN_CALL): the host previews the brief and dials through its softphone. */
|
|
91
|
+
openCall: (conversationBriefId: string) => void;
|
|
89
92
|
/** Open another component in a host-rendered modal; resolves with the value
|
|
90
93
|
* that component closed with (`undefined` if dismissed). */
|
|
91
94
|
openModal: (componentSlug: string, props?: Record<string, unknown>, options?: OpenModalOptions) => Promise<unknown>;
|
|
@@ -140,6 +143,12 @@ declare function usePageContext(): PageContext;
|
|
|
140
143
|
* peeks what it can (today: platform pages) and falls back to full navigation.
|
|
141
144
|
*/
|
|
142
145
|
declare function useNavigate(): (to: string, options?: NavigateOptions) => void;
|
|
146
|
+
/**
|
|
147
|
+
* Open a prepared call from a conversation brief id: the HOST previews the brief and
|
|
148
|
+
* places the call through its softphone (an iframe cannot dial). Pair it with
|
|
149
|
+
* `ConversationBriefReview`'s `onOpenCall` from `@proteos/ui`.
|
|
150
|
+
*/
|
|
151
|
+
declare function useOpenCall(): (conversationBriefId: string) => void;
|
|
143
152
|
/** The API origin SDK calls resolve against (for building raw asset URLs). */
|
|
144
153
|
declare function useApiBaseUrl(): string;
|
|
145
154
|
/**
|
|
@@ -218,4 +227,4 @@ interface FillViewportOptions {
|
|
|
218
227
|
*/
|
|
219
228
|
declare function useFillViewportHeight(options?: FillViewportOptions): number | null;
|
|
220
229
|
|
|
221
|
-
export { type ComponentSdk, type FillViewportOptions, type HostLocation, type ModalHost, type NavigateOptions, type OpenModalOptions, type OverlayController, PageContext, type RuntimeContextValue, RuntimeProvider, type RuntimeValue, useApiBaseUrl, useAuthToken, useComponentModal, useFillViewportHeight, useHostLocation, useModalHost, useNavigate, useOverlayExpansion, usePageContext, useProps, useRuntime, useSdk };
|
|
230
|
+
export { type ComponentSdk, type FillViewportOptions, type HostLocation, type ModalHost, type NavigateOptions, type OpenModalOptions, type OverlayController, PageContext, type RuntimeContextValue, RuntimeProvider, type RuntimeValue, useApiBaseUrl, useAuthToken, useComponentModal, useFillViewportHeight, useHostLocation, useModalHost, useNavigate, useOpenCall, useOverlayExpansion, usePageContext, useProps, useRuntime, useSdk };
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { AccountClient, AgentClient, ConversationClient, DataClient, FunctionsClient, KnowledgeClient, MetaClient, StorageClient } from '@proteos/sdk';
|
|
4
4
|
import { PageContext } from './protocol.js';
|
|
5
|
-
export { AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, DataInvalidateMessage, Envelope, ErrorMessage, EscapePressedMessage, HostMessage, InitMessage, MESSAGE_SOURCE, ModalClosedMessage, ModalResultMessage, NavigateMessage, OpenModalMessage, OpenPeekMessage, OverlayRect, OverlayRectMessage, OverlayStateMessage, ReadyMessage, ResizeMessage, RuntimeMessage, isHostMessage, isRuntimeMessage } from './protocol.js';
|
|
5
|
+
export { AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, DataInvalidateMessage, Envelope, ErrorMessage, EscapePressedMessage, HostMessage, InitMessage, MESSAGE_SOURCE, ModalClosedMessage, ModalResultMessage, NavigateMessage, OpenCallMessage, OpenModalMessage, OpenPeekMessage, OverlayRect, OverlayRectMessage, OverlayStateMessage, ReadyMessage, ResizeMessage, RuntimeMessage, isHostMessage, isRuntimeMessage } from './protocol.js';
|
|
6
6
|
|
|
7
7
|
/** Options for {@link RuntimeContextValue.navigate}. */
|
|
8
8
|
interface NavigateOptions {
|
|
@@ -86,6 +86,9 @@ interface RuntimeContextValue extends RuntimeValue {
|
|
|
86
86
|
/** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or
|
|
87
87
|
* open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */
|
|
88
88
|
navigate: (to: string, options?: NavigateOptions) => void;
|
|
89
|
+
/** Ask the host to open a prepared call from a conversation brief (posts
|
|
90
|
+
* OPEN_CALL): the host previews the brief and dials through its softphone. */
|
|
91
|
+
openCall: (conversationBriefId: string) => void;
|
|
89
92
|
/** Open another component in a host-rendered modal; resolves with the value
|
|
90
93
|
* that component closed with (`undefined` if dismissed). */
|
|
91
94
|
openModal: (componentSlug: string, props?: Record<string, unknown>, options?: OpenModalOptions) => Promise<unknown>;
|
|
@@ -140,6 +143,12 @@ declare function usePageContext(): PageContext;
|
|
|
140
143
|
* peeks what it can (today: platform pages) and falls back to full navigation.
|
|
141
144
|
*/
|
|
142
145
|
declare function useNavigate(): (to: string, options?: NavigateOptions) => void;
|
|
146
|
+
/**
|
|
147
|
+
* Open a prepared call from a conversation brief id: the HOST previews the brief and
|
|
148
|
+
* places the call through its softphone (an iframe cannot dial). Pair it with
|
|
149
|
+
* `ConversationBriefReview`'s `onOpenCall` from `@proteos/ui`.
|
|
150
|
+
*/
|
|
151
|
+
declare function useOpenCall(): (conversationBriefId: string) => void;
|
|
143
152
|
/** The API origin SDK calls resolve against (for building raw asset URLs). */
|
|
144
153
|
declare function useApiBaseUrl(): string;
|
|
145
154
|
/**
|
|
@@ -218,4 +227,4 @@ interface FillViewportOptions {
|
|
|
218
227
|
*/
|
|
219
228
|
declare function useFillViewportHeight(options?: FillViewportOptions): number | null;
|
|
220
229
|
|
|
221
|
-
export { type ComponentSdk, type FillViewportOptions, type HostLocation, type ModalHost, type NavigateOptions, type OpenModalOptions, type OverlayController, PageContext, type RuntimeContextValue, RuntimeProvider, type RuntimeValue, useApiBaseUrl, useAuthToken, useComponentModal, useFillViewportHeight, useHostLocation, useModalHost, useNavigate, useOverlayExpansion, usePageContext, useProps, useRuntime, useSdk };
|
|
230
|
+
export { type ComponentSdk, type FillViewportOptions, type HostLocation, type ModalHost, type NavigateOptions, type OpenModalOptions, type OverlayController, PageContext, type RuntimeContextValue, RuntimeProvider, type RuntimeValue, useApiBaseUrl, useAuthToken, useComponentModal, useFillViewportHeight, useHostLocation, useModalHost, useNavigate, useOpenCall, useOverlayExpansion, usePageContext, useProps, useRuntime, useSdk };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { MESSAGE_SOURCE, isHostMessage } from './chunk-
|
|
2
|
-
export { COMPONENT_OVERLAY_Z_INDEX, MESSAGE_SOURCE, isHostMessage, isRuntimeMessage } from './chunk-
|
|
1
|
+
import { MESSAGE_SOURCE, isHostMessage } from './chunk-RTYCYWKC.js';
|
|
2
|
+
export { COMPONENT_OVERLAY_Z_INDEX, MESSAGE_SOURCE, isHostMessage, isRuntimeMessage } from './chunk-RTYCYWKC.js';
|
|
3
3
|
import { createContext, useMemo, useContext, useCallback, useState, useEffect } from 'react';
|
|
4
4
|
import { jsx } from 'react/jsx-runtime';
|
|
5
5
|
|
|
@@ -12,6 +12,14 @@ function postOpenPeek(to) {
|
|
|
12
12
|
const envelope = { source: MESSAGE_SOURCE, type: "OPEN_PEEK", to };
|
|
13
13
|
window.parent?.postMessage(envelope, "*");
|
|
14
14
|
}
|
|
15
|
+
function openCall(conversationBriefId) {
|
|
16
|
+
const envelope = {
|
|
17
|
+
source: MESSAGE_SOURCE,
|
|
18
|
+
type: "OPEN_CALL",
|
|
19
|
+
conversationBriefId
|
|
20
|
+
};
|
|
21
|
+
window.parent?.postMessage(envelope, "*");
|
|
22
|
+
}
|
|
15
23
|
function navigate(to, options) {
|
|
16
24
|
if (options?.peek) postOpenPeek(to);
|
|
17
25
|
else postNavigate(to);
|
|
@@ -62,7 +70,10 @@ function postModalResult(requestId, result) {
|
|
|
62
70
|
window.parent?.postMessage(envelope, "*");
|
|
63
71
|
}
|
|
64
72
|
function RuntimeProvider({ value, children }) {
|
|
65
|
-
const ctx = useMemo(
|
|
73
|
+
const ctx = useMemo(
|
|
74
|
+
() => ({ ...value, navigate, openCall, openModal }),
|
|
75
|
+
[value]
|
|
76
|
+
);
|
|
66
77
|
return /* @__PURE__ */ jsx(RuntimeContext.Provider, { value: ctx, children });
|
|
67
78
|
}
|
|
68
79
|
function useRuntime() {
|
|
@@ -86,6 +97,9 @@ function usePageContext() {
|
|
|
86
97
|
function useNavigate() {
|
|
87
98
|
return useRuntime().navigate;
|
|
88
99
|
}
|
|
100
|
+
function useOpenCall() {
|
|
101
|
+
return useRuntime().openCall;
|
|
102
|
+
}
|
|
89
103
|
function useApiBaseUrl() {
|
|
90
104
|
return useRuntime().apiBaseUrl;
|
|
91
105
|
}
|
|
@@ -166,6 +180,6 @@ function useFillViewportHeight(options = {}) {
|
|
|
166
180
|
return height;
|
|
167
181
|
}
|
|
168
182
|
|
|
169
|
-
export { RuntimeProvider, useApiBaseUrl, useAuthToken, useComponentModal, useFillViewportHeight, useHostLocation, useModalHost, useNavigate, useOverlayExpansion, usePageContext, useProps, useRuntime, useSdk };
|
|
183
|
+
export { RuntimeProvider, useApiBaseUrl, useAuthToken, useComponentModal, useFillViewportHeight, useHostLocation, useModalHost, useNavigate, useOpenCall, useOverlayExpansion, usePageContext, useProps, useRuntime, useSdk };
|
|
170
184
|
//# sourceMappingURL=index.js.map
|
|
171
185
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context.tsx","../src/hooks.ts"],"names":["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C9C,EAAA,MAAM,CAAC,GAAG,CAAA,GAAI,QAAA,CAAS,gBAAgB,CAAA;AACvC,EAAA,OAAO,GAAA;AACT;AAgBO,SAAS,qBAAA,CAAsB,OAAA,GAA+B,EAAC,EAAkB;AACtF,EAAA,MAAM,EAAE,YAAA,GAAe,EAAA,EAAI,SAAA,GAAY,KAAI,GAAI,OAAA;AAC/C,EAAA,MAAM,CAAC,MAAA,EAAQ,SAAS,CAAA,GAAI,SAAwB,IAAI,CAAA;AAExD,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,SAAS,OAAA,GAAgB;AACvB,MAAA,IAAI;AACF,QAAA,MAAM,QAAQ,MAAA,CAAO,YAAA;AACrB,QAAA,MAAM,eAAe,MAAA,CAAO,MAAA;AAC5B,QAAA,IAAI,CAAC,KAAA,IAAS,CAAC,YAAA,IAAgB,iBAAiB,MAAA,EAAQ;AACxD,QAAA,MAAM,YACJ,YAAA,CAAa,WAAA,GAAc,KAAA,CAAM,qBAAA,GAAwB,GAAA,GAAM,YAAA;AACjE,QAAA,SAAA,CAAU,IAAA,CAAK,GAAA,CAAI,SAAA,EAAW,SAAS,CAAC,CAAA;AAAA,MAC1C,CAAA,CAAA,MAAQ;AACN,QAAA,SAAA,CAAU,IAAI,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,MAAA,CAAO,gBAAA,CAAiB,QAAA,EAAU,OAAO,CAAA;AAChD,MAAA,OAAO,MAAM,MAAA,CAAO,MAAA,CAAO,mBAAA,CAAoB,UAAU,OAAO,CAAA;AAAA,IAClE,CAAA,CAAA,MAAQ;AACN,MAAA;AAAA,IACF;AAAA,EACF,CAAA,EAAG,CAAC,YAAA,EAAc,SAAS,CAAC,CAAA;AAE5B,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import type {\n AccountClient,\n AgentClient,\n ConversationClient,\n DataClient,\n FunctionsClient,\n KnowledgeClient,\n MetaClient,\n StorageClient,\n} from '@proteos/sdk'\nimport { createContext, type ReactNode, useMemo } from 'react'\n\nimport {\n type Envelope,\n isHostMessage,\n MESSAGE_SOURCE,\n type ModalResultMessage,\n type NavigateMessage,\n type OpenModalMessage,\n type OpenPeekMessage,\n type PageContext,\n} from './protocol'\n\n/** Options for {@link RuntimeContextValue.navigate}. */\nexport interface NavigateOptions {\n /** Open the target in a peek (slide-over) panel instead of full-page. */\n peek?: boolean\n}\n\n/** Options for {@link RuntimeContextValue.openModal}. */\nexport interface OpenModalOptions {\n /** Heading rendered in the modal chrome. */\n title?: string\n}\n\n/**\n * Manual control over iframe overlay promotion. The runtime already detects\n * overlays automatically (anything portaled to the iframe's `document.body` —\n * every `@proteos/ui` overlay qualifies), so components need this only for\n * custom portal targets, or to promote a frame *before* opening an overlay.\n * Calls are reference-counted: every `expand()` needs its `collapse()`.\n */\nexport interface OverlayController {\n expand: () => void\n collapse: () => void\n isExpanded: () => boolean\n}\n\n/**\n * The authenticated `@proteos/sdk` clients the runtime injects. Same instances\n * the host app uses — pre-wired with a refreshing bearer token, so a component\n * never touches auth headers.\n */\nexport interface ComponentSdk {\n account: AccountClient\n agents: AgentClient\n /**\n * Conversations, messages, contacts, connections (conversation-service) —\n * e.g. the DraftMessageComposer review surface. Plural per the platform's\n * resource-naming rule; the web app's own `useSdk().conversation` predates\n * it (documented asymmetry).\n */\n conversations: ConversationClient\n data: DataClient\n functions: FunctionsClient\n knowledge: KnowledgeClient\n meta: MetaClient\n storage: StorageClient\n}\n\n/**\n * The raw runtime payload the shell hands a component at INIT. The shell builds\n * this; component authors read it through the hooks.\n */\nexport interface RuntimeValue {\n /**\n * The injected sdk clients. On an authenticated page these are the full,\n * bearer-wired clients. On a PUBLIC page (`isPublic: true`) only\n * `functions.actions.invokePublic` reaches the platform — every other\n * client throws on use (there is no token, and the server rejects\n * unauthenticated calls anyway).\n */\n sdk: ComponentSdk\n /** Liquid-resolved props (a snapshot — not a live binding). */\n props: Record<string, unknown>\n /** Page context snapshot: the host record, entity, and URL params. */\n pageCtx: PageContext\n /** API origin SDK calls + asset URLs resolve against. */\n apiBaseUrl: string\n /** Current bearer token getter (escape hatch for raw fetches). Returns ''\n * on public pages. */\n getToken: () => string\n /** True when rendering on an unauthenticated public page. */\n isPublic?: boolean\n /** Org id, set in public mode (public API routes carry it in the path). */\n orgId?: string\n /** Set when this component is the content of a host component modal — the\n * correlation id it closes with. See `useModalHost()`. */\n modalRequestId?: string\n /** Overlay promotion controller, provided by the shell. Absent on older\n * shells / non-promoting hosts, in which case `useOverlayExpansion()`\n * no-ops. */\n overlay?: OverlayController\n}\n\n/** Runtime value plus the derived helpers the hooks expose. */\nexport interface RuntimeContextValue extends RuntimeValue {\n /** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or\n * open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */\n navigate: (to: string, options?: NavigateOptions) => void\n /** Open another component in a host-rendered modal; resolves with the value\n * that component closed with (`undefined` if dismissed). */\n openModal: (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n ) => Promise<unknown>\n}\n\nexport const RuntimeContext = createContext<RuntimeContextValue | null>(null)\n\n/** Post a NAVIGATE envelope to the host. The host only honours relative,\n * in-app targets (it ignores absolute/external URLs). */\nfunction postNavigate(to: string): void {\n const envelope: Envelope<NavigateMessage> = { source: MESSAGE_SOURCE, type: 'NAVIGATE', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Post an OPEN_PEEK envelope to the host — open the in-app path in a peek\n * panel. Same relative-path contract as {@link postNavigate}. */\nfunction postOpenPeek(to: string): void {\n const envelope: Envelope<OpenPeekMessage> = { source: MESSAGE_SOURCE, type: 'OPEN_PEEK', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Navigate full-page (default) or into a peek panel (`{ peek: true }`). */\nfunction navigate(to: string, options?: NavigateOptions): void {\n if (options?.peek) postOpenPeek(to)\n else postNavigate(to)\n}\n\n// ── Component modals ────────────────────────────────────────────────────────\n// One module-level listener + a pending map, rather than a listener per call:\n// the SDK is an import-mapped singleton, so this is per-iframe state.\n\nconst pendingModals = new Map<string, (result: unknown) => void>()\nlet modalListenerAttached = false\n\nfunction ensureModalListener(): void {\n if (modalListenerAttached) return\n modalListenerAttached = true\n window.addEventListener('message', (event: MessageEvent) => {\n const data: unknown = event.data\n if (!isHostMessage(data) || data.type !== 'MODAL_CLOSED') return\n const resolve = pendingModals.get(data.requestId)\n // An unknown requestId is someone else's modal (or a stale reply) — drop it.\n if (!resolve) return\n pendingModals.delete(data.requestId)\n resolve(data.result)\n })\n}\n\nfunction newRequestId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n return `modal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** Post OPEN_MODAL and resolve when the host answers MODAL_CLOSED. */\nfunction openModal(\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n): Promise<unknown> {\n ensureModalListener()\n const requestId = newRequestId()\n const envelope: Envelope<OpenModalMessage> = {\n source: MESSAGE_SOURCE,\n type: 'OPEN_MODAL',\n requestId,\n componentSlug,\n ...(props !== undefined ? { props } : {}),\n ...(options?.title !== undefined ? { title: options.title } : {}),\n }\n return new Promise<unknown>((resolve) => {\n pendingModals.set(requestId, resolve)\n window.parent?.postMessage(envelope, '*')\n })\n}\n\n/** Post MODAL_RESULT — the component inside a host modal closing with a value. */\nexport function postModalResult(requestId: string, result?: unknown): void {\n const envelope: Envelope<ModalResultMessage> = {\n source: MESSAGE_SOURCE,\n type: 'MODAL_RESULT',\n requestId,\n ...(result !== undefined ? { result } : {}),\n }\n window.parent?.postMessage(envelope, '*')\n}\n\n/**\n * Provides the runtime value + derived helpers to a component subtree. Mounted\n * by the component-runtime shell around the loaded component — authors never\n * render this themselves. Lives in `@proteos/component-sdk` (a shared,\n * import-mapped singleton) so the context the shell provides is the very same\n * context the component's hooks read, across the bundle boundary.\n */\nexport function RuntimeProvider({ value, children }: { value: RuntimeValue; children: ReactNode }) {\n // The shell builds `value` once at INIT (a stable state object — clients,\n // props and pageCtx are all set once), so memoizing on its identity recreates\n // the context only when the runtime genuinely re-inits.\n const ctx = useMemo<RuntimeContextValue>(() => ({ ...value, navigate, openModal }), [value])\n return <RuntimeContext.Provider value={ctx}>{children}</RuntimeContext.Provider>\n}\n","import { useCallback, useContext, useEffect, useMemo, useState } from 'react'\n\nimport {\n type ComponentSdk,\n type NavigateOptions,\n type OpenModalOptions,\n type OverlayController,\n postModalResult,\n RuntimeContext,\n type RuntimeContextValue,\n} from './context'\nimport type { PageContext } from './protocol'\n\n/**\n * Low-level escape hatch: the whole runtime context (sdk, props, pageCtx,\n * apiBaseUrl, getToken, navigate). Prefer the focused hooks below. Throws a\n * clear error if used outside the component runtime.\n */\nexport function useRuntime(): RuntimeContextValue {\n const ctx = useContext(RuntimeContext)\n if (!ctx) {\n throw new Error(\n '@proteos/component-sdk: hooks must run inside the Proteos component runtime. ' +\n 'This usually means the component is rendered outside its iframe, or a ' +\n 'second copy of @proteos/component-sdk was bundled instead of using the ' +\n 'runtime-provided one (keep it external).',\n )\n }\n return ctx\n}\n\n/** The authenticated SDK clients (account / agents / conversations / data / functions / knowledge / meta / storage). */\nexport function useSdk(): ComponentSdk {\n return useRuntime().sdk\n}\n\n/** The component's Liquid-resolved props (a snapshot, not a live binding). */\nexport function useProps<T extends Record<string, unknown> = Record<string, unknown>>(): T {\n return useRuntime().props as T\n}\n\n/**\n * The full page context: host `record`, `entity`, and URL `params`. The\n * `record` is a snapshot taken at mount (`undefined` on record-less platform\n * pages) — fetch via `useSdk().data` for anything that must stay fresh.\n */\nexport function usePageContext(): PageContext {\n return useRuntime().pageCtx\n}\n\n/**\n * Navigate the host SPA to an in-app path, e.g.\n * `navigate('/org/acme/record/task/123')`. The host ignores absolute/external\n * URLs. Build org/app-prefixed paths with `useHostLocation().appBasePath`.\n *\n * Pass `{ peek: true }` to open the path in a peek (slide-over) panel instead\n * of full-page navigation — e.g. `navigate(path, { peek: true })`. The host\n * peeks what it can (today: platform pages) and falls back to full navigation.\n */\nexport function useNavigate(): (to: string, options?: NavigateOptions) => void {\n return useRuntime().navigate\n}\n\n/** The API origin SDK calls resolve against (for building raw asset URLs). */\nexport function useApiBaseUrl(): string {\n return useRuntime().apiBaseUrl\n}\n\nconst NOOP_OVERLAY: OverlayController = {\n expand: () => {\n console.warn(\n '@proteos/component-sdk: useOverlayExpansion() has no effect — this runtime ' +\n 'does not support overlay promotion (older shell or non-promoting host).',\n )\n },\n collapse: () => {},\n isExpanded: () => false,\n}\n\n/**\n * Manual overlay promotion — lifts the whole component iframe over the rest of\n * the page so an overlay can escape the frame's box.\n *\n * You rarely need this. Every `@proteos/ui` overlay (Modal, Popover, Menu,\n * Select, Tooltip, …) portals to the iframe document's `<body>`, which the\n * runtime watches — those promote automatically, with no code. Reach for this\n * hook only when you portal somewhere else yourself, or want the frame lifted\n * *before* the overlay mounts. Reference-counted: pair every `expand()` with a\n * `collapse()`.\n */\nexport function useOverlayExpansion(): OverlayController {\n return useRuntime().overlay ?? NOOP_OVERLAY\n}\n\n/**\n * Open ANOTHER component in a modal the host renders above everything — the\n * cross-component flow (a picker, a wizard step, a confirm dialog shared by\n * several components). Resolves with whatever that component closed with, or\n * `undefined` if the user dismissed it.\n *\n * ```ts\n * const openModal = useComponentModal()\n * const picked = await openModal('contact-picker', { entity: 'contact' }, { title: 'Pick a contact' })\n * ```\n *\n * For an overlay that is part of THIS component, just render a `<Modal>` from\n * `@proteos/ui` — it promotes automatically.\n */\nexport function useComponentModal(): (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n) => Promise<unknown> {\n return useRuntime().openModal\n}\n\nexport interface ModalHost {\n /** True when this component is rendered as the content of a host modal. */\n isInModal: boolean\n /** Close the host modal, resolving the opener's promise with `result`.\n * No-op outside a modal. */\n close: (result?: unknown) => void\n}\n\n/**\n * For a component that is being shown INSIDE a host modal (opened by another\n * component's `useComponentModal()`): close it and hand a value back.\n * `isInModal` is false on ordinary page-hosted mounts, so one component can\n * serve both roles.\n */\nexport function useModalHost(): ModalHost {\n const requestId = useRuntime().modalRequestId\n const close = useCallback(\n (result?: unknown) => {\n if (requestId === undefined) return\n postModalResult(requestId, result)\n },\n [requestId],\n )\n return useMemo(() => ({ isInModal: requestId !== undefined, close }), [requestId, close])\n}\n\n/**\n * A getter for the current bearer token. Returns a function (not the token)\n * because the token is refreshed in place — read it at call time for a raw\n * `fetch`. Most components never need this; prefer `useSdk()`.\n */\nexport function useAuthToken(): () => string {\n return useRuntime().getToken\n}\n\nexport interface HostLocation {\n /** The host tab's pathname (same-origin read), or null if unavailable. */\n pathname: string | null\n /** The org id parsed from `/org/<orgId>/…`, or null. */\n orgId: string | null\n /** The `/org/<orgId>/app/<appId>` prefix, or null when not on an app page. */\n appBasePath: string | null\n}\n\nfunction readHostLocation(): HostLocation {\n const empty: HostLocation = { pathname: null, orgId: null, appBasePath: null }\n try {\n const parentWindow = window.parent\n if (!parentWindow || parentWindow === window) return empty\n const pathname = parentWindow.location.pathname\n const appMatch = pathname.match(/^\\/org\\/[^/]+\\/app\\/[^/]+/)\n const orgMatch = pathname.match(/^\\/org\\/([^/]+)\\//)\n return {\n pathname,\n orgId: orgMatch ? (orgMatch[1] ?? null) : null,\n appBasePath: appMatch ? appMatch[0] : null,\n }\n } catch {\n // Cross-origin (untrusted-component future) or detached — fall back to null.\n return empty\n }\n}\n\n/**\n * Read the host tab's location (same-origin) — the org id and `/org/.../app/...`\n * prefix needed to build navigation targets on platform pages. Read once on\n * mount (the iframe re-inits when the host route changes).\n */\nexport function useHostLocation(): HostLocation {\n const [loc] = useState(readHostLocation)\n return loc\n}\n\nexport interface FillViewportOptions {\n /** Gap left below the component (px). Default 24. */\n bottomMargin?: number\n /** Floor for the computed height (px). Default 320. */\n minHeight?: number\n}\n\n/**\n * Compute a \"fill the rest of the viewport\" height for full-bleed layouts\n * (boards, canvases). The runtime auto-sizes the iframe to its content, so a\n * component can't use its own `vh` units (circular). The iframe is same-origin,\n * so this measures the parent viewport minus the iframe's offset instead.\n * Returns `null` when it can't measure (fall back to natural height).\n */\nexport function useFillViewportHeight(options: FillViewportOptions = {}): number | null {\n const { bottomMargin = 24, minHeight = 320 } = options\n const [height, setHeight] = useState<number | null>(null)\n\n useEffect(() => {\n function compute(): void {\n try {\n const frame = window.frameElement\n const parentWindow = window.parent\n if (!frame || !parentWindow || parentWindow === window) return\n const available =\n parentWindow.innerHeight - frame.getBoundingClientRect().top - bottomMargin\n setHeight(Math.max(available, minHeight))\n } catch {\n setHeight(null) // cross-origin or detached — fall back to natural height\n }\n }\n compute()\n try {\n window.parent.addEventListener('resize', compute)\n return () => window.parent.removeEventListener('resize', compute)\n } catch {\n return\n }\n }, [bottomMargin, minHeight])\n\n return height\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/context.tsx","../src/hooks.ts"],"names":["useMemo"],"mappings":";;;;;AA2HO,IAAM,cAAA,GAAiB,cAA0C,IAAI,CAAA;AAI5E,SAAS,aAAa,EAAA,EAAkB;AACtC,EAAA,MAAM,WAAsC,EAAE,MAAA,EAAQ,cAAA,EAAgB,IAAA,EAAM,YAAY,EAAA,EAAG;AAC3F,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,EAAU,GAAG,CAAA;AAC1C;AAIA,SAAS,aAAa,EAAA,EAAkB;AACtC,EAAA,MAAM,WAAsC,EAAE,MAAA,EAAQ,cAAA,EAAgB,IAAA,EAAM,aAAa,EAAA,EAAG;AAC5F,EAAA,MAAA,CAAO,MAAA,EAAQ,WAAA,CAAY,QAAA,EAAU,GAAG,CAAA;AAC1C;AAGA,SAAS,SAAS,mBAAA,EAAmC;AACnD,EAAA,MAAM,QAAA,GAAsC;AAAA,IAC1C,MAAA,EAAQ,cAAA;AAAA,IACR,IAAA,EAAM,WAAA;AAAA,IACN;AAAA,GACF;AACA,EAAA,MAAA,CAAO,M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;AACd,IAAA,SAAS,OAAA,GAAgB;AACvB,MAAA,IAAI;AACF,QAAA,MAAM,QAAQ,MAAA,CAAO,YAAA;AACrB,QAAA,MAAM,eAAe,MAAA,CAAO,MAAA;AAC5B,QAAA,IAAI,CAAC,KAAA,IAAS,CAAC,YAAA,IAAgB,iBAAiB,MAAA,EAAQ;AACxD,QAAA,MAAM,YACJ,YAAA,CAAa,WAAA,GAAc,KAAA,CAAM,qBAAA,GAAwB,GAAA,GAAM,YAAA;AACjE,QAAA,SAAA,CAAU,IAAA,CAAK,GAAA,CAAI,SAAA,EAAW,SAAS,CAAC,CAAA;AAAA,MAC1C,CAAA,CAAA,MAAQ;AACN,QAAA,SAAA,CAAU,IAAI,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,MAAA,CAAO,gBAAA,CAAiB,QAAA,EAAU,OAAO,CAAA;AAChD,MAAA,OAAO,MAAM,MAAA,CAAO,MAAA,CAAO,mBAAA,CAAoB,UAAU,OAAO,CAAA;AAAA,IAClE,CAAA,CAAA,MAAQ;AACN,MAAA;AAAA,IACF;AAAA,EACF,CAAA,EAAG,CAAC,YAAA,EAAc,SAAS,CAAC,CAAA;AAE5B,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import type {\n AccountClient,\n AgentClient,\n ConversationClient,\n DataClient,\n FunctionsClient,\n KnowledgeClient,\n MetaClient,\n StorageClient,\n} from '@proteos/sdk'\nimport { createContext, type ReactNode, useMemo } from 'react'\n\nimport {\n type Envelope,\n isHostMessage,\n MESSAGE_SOURCE,\n type ModalResultMessage,\n type NavigateMessage,\n type OpenCallMessage,\n type OpenModalMessage,\n type OpenPeekMessage,\n type PageContext,\n} from './protocol'\n\n/** Options for {@link RuntimeContextValue.navigate}. */\nexport interface NavigateOptions {\n /** Open the target in a peek (slide-over) panel instead of full-page. */\n peek?: boolean\n}\n\n/** Options for {@link RuntimeContextValue.openModal}. */\nexport interface OpenModalOptions {\n /** Heading rendered in the modal chrome. */\n title?: string\n}\n\n/**\n * Manual control over iframe overlay promotion. The runtime already detects\n * overlays automatically (anything portaled to the iframe's `document.body` —\n * every `@proteos/ui` overlay qualifies), so components need this only for\n * custom portal targets, or to promote a frame *before* opening an overlay.\n * Calls are reference-counted: every `expand()` needs its `collapse()`.\n */\nexport interface OverlayController {\n expand: () => void\n collapse: () => void\n isExpanded: () => boolean\n}\n\n/**\n * The authenticated `@proteos/sdk` clients the runtime injects. Same instances\n * the host app uses — pre-wired with a refreshing bearer token, so a component\n * never touches auth headers.\n */\nexport interface ComponentSdk {\n account: AccountClient\n agents: AgentClient\n /**\n * Conversations, messages, contacts, connections (conversation-service) —\n * e.g. the DraftMessageComposer review surface. Plural per the platform's\n * resource-naming rule; the web app's own `useSdk().conversation` predates\n * it (documented asymmetry).\n */\n conversations: ConversationClient\n data: DataClient\n functions: FunctionsClient\n knowledge: KnowledgeClient\n meta: MetaClient\n storage: StorageClient\n}\n\n/**\n * The raw runtime payload the shell hands a component at INIT. The shell builds\n * this; component authors read it through the hooks.\n */\nexport interface RuntimeValue {\n /**\n * The injected sdk clients. On an authenticated page these are the full,\n * bearer-wired clients. On a PUBLIC page (`isPublic: true`) only\n * `functions.actions.invokePublic` reaches the platform — every other\n * client throws on use (there is no token, and the server rejects\n * unauthenticated calls anyway).\n */\n sdk: ComponentSdk\n /** Liquid-resolved props (a snapshot — not a live binding). */\n props: Record<string, unknown>\n /** Page context snapshot: the host record, entity, and URL params. */\n pageCtx: PageContext\n /** API origin SDK calls + asset URLs resolve against. */\n apiBaseUrl: string\n /** Current bearer token getter (escape hatch for raw fetches). Returns ''\n * on public pages. */\n getToken: () => string\n /** True when rendering on an unauthenticated public page. */\n isPublic?: boolean\n /** Org id, set in public mode (public API routes carry it in the path). */\n orgId?: string\n /** Set when this component is the content of a host component modal — the\n * correlation id it closes with. See `useModalHost()`. */\n modalRequestId?: string\n /** Overlay promotion controller, provided by the shell. Absent on older\n * shells / non-promoting hosts, in which case `useOverlayExpansion()`\n * no-ops. */\n overlay?: OverlayController\n}\n\n/** Runtime value plus the derived helpers the hooks expose. */\nexport interface RuntimeContextValue extends RuntimeValue {\n /** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or\n * open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */\n navigate: (to: string, options?: NavigateOptions) => void\n /** Ask the host to open a prepared call from a conversation brief (posts\n * OPEN_CALL): the host previews the brief and dials through its softphone. */\n openCall: (conversationBriefId: string) => void\n /** Open another component in a host-rendered modal; resolves with the value\n * that component closed with (`undefined` if dismissed). */\n openModal: (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n ) => Promise<unknown>\n}\n\nexport const RuntimeContext = createContext<RuntimeContextValue | null>(null)\n\n/** Post a NAVIGATE envelope to the host. The host only honours relative,\n * in-app targets (it ignores absolute/external URLs). */\nfunction postNavigate(to: string): void {\n const envelope: Envelope<NavigateMessage> = { source: MESSAGE_SOURCE, type: 'NAVIGATE', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Post an OPEN_PEEK envelope to the host — open the in-app path in a peek\n * panel. Same relative-path contract as {@link postNavigate}. */\nfunction postOpenPeek(to: string): void {\n const envelope: Envelope<OpenPeekMessage> = { source: MESSAGE_SOURCE, type: 'OPEN_PEEK', to }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Post OPEN_CALL — the host previews the conversation brief and owns the dial. */\nfunction openCall(conversationBriefId: string): void {\n const envelope: Envelope<OpenCallMessage> = {\n source: MESSAGE_SOURCE,\n type: 'OPEN_CALL',\n conversationBriefId,\n }\n window.parent?.postMessage(envelope, '*')\n}\n\n/** Navigate full-page (default) or into a peek panel (`{ peek: true }`). */\nfunction navigate(to: string, options?: NavigateOptions): void {\n if (options?.peek) postOpenPeek(to)\n else postNavigate(to)\n}\n\n// ── Component modals ────────────────────────────────────────────────────────\n// One module-level listener + a pending map, rather than a listener per call:\n// the SDK is an import-mapped singleton, so this is per-iframe state.\n\nconst pendingModals = new Map<string, (result: unknown) => void>()\nlet modalListenerAttached = false\n\nfunction ensureModalListener(): void {\n if (modalListenerAttached) return\n modalListenerAttached = true\n window.addEventListener('message', (event: MessageEvent) => {\n const data: unknown = event.data\n if (!isHostMessage(data) || data.type !== 'MODAL_CLOSED') return\n const resolve = pendingModals.get(data.requestId)\n // An unknown requestId is someone else's modal (or a stale reply) — drop it.\n if (!resolve) return\n pendingModals.delete(data.requestId)\n resolve(data.result)\n })\n}\n\nfunction newRequestId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n return `modal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** Post OPEN_MODAL and resolve when the host answers MODAL_CLOSED. */\nfunction openModal(\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n): Promise<unknown> {\n ensureModalListener()\n const requestId = newRequestId()\n const envelope: Envelope<OpenModalMessage> = {\n source: MESSAGE_SOURCE,\n type: 'OPEN_MODAL',\n requestId,\n componentSlug,\n ...(props !== undefined ? { props } : {}),\n ...(options?.title !== undefined ? { title: options.title } : {}),\n }\n return new Promise<unknown>((resolve) => {\n pendingModals.set(requestId, resolve)\n window.parent?.postMessage(envelope, '*')\n })\n}\n\n/** Post MODAL_RESULT — the component inside a host modal closing with a value. */\nexport function postModalResult(requestId: string, result?: unknown): void {\n const envelope: Envelope<ModalResultMessage> = {\n source: MESSAGE_SOURCE,\n type: 'MODAL_RESULT',\n requestId,\n ...(result !== undefined ? { result } : {}),\n }\n window.parent?.postMessage(envelope, '*')\n}\n\n/**\n * Provides the runtime value + derived helpers to a component subtree. Mounted\n * by the component-runtime shell around the loaded component — authors never\n * render this themselves. Lives in `@proteos/component-sdk` (a shared,\n * import-mapped singleton) so the context the shell provides is the very same\n * context the component's hooks read, across the bundle boundary.\n */\nexport function RuntimeProvider({ value, children }: { value: RuntimeValue; children: ReactNode }) {\n // The shell builds `value` once at INIT (a stable state object — clients,\n // props and pageCtx are all set once), so memoizing on its identity recreates\n // the context only when the runtime genuinely re-inits.\n const ctx = useMemo<RuntimeContextValue>(\n () => ({ ...value, navigate, openCall, openModal }),\n [value],\n )\n return <RuntimeContext.Provider value={ctx}>{children}</RuntimeContext.Provider>\n}\n","import { useCallback, useContext, useEffect, useMemo, useState } from 'react'\n\nimport {\n type ComponentSdk,\n type NavigateOptions,\n type OpenModalOptions,\n type OverlayController,\n postModalResult,\n RuntimeContext,\n type RuntimeContextValue,\n} from './context'\nimport type { PageContext } from './protocol'\n\n/**\n * Low-level escape hatch: the whole runtime context (sdk, props, pageCtx,\n * apiBaseUrl, getToken, navigate). Prefer the focused hooks below. Throws a\n * clear error if used outside the component runtime.\n */\nexport function useRuntime(): RuntimeContextValue {\n const ctx = useContext(RuntimeContext)\n if (!ctx) {\n throw new Error(\n '@proteos/component-sdk: hooks must run inside the Proteos component runtime. ' +\n 'This usually means the component is rendered outside its iframe, or a ' +\n 'second copy of @proteos/component-sdk was bundled instead of using the ' +\n 'runtime-provided one (keep it external).',\n )\n }\n return ctx\n}\n\n/** The authenticated SDK clients (account / agents / conversations / data / functions / knowledge / meta / storage). */\nexport function useSdk(): ComponentSdk {\n return useRuntime().sdk\n}\n\n/** The component's Liquid-resolved props (a snapshot, not a live binding). */\nexport function useProps<T extends Record<string, unknown> = Record<string, unknown>>(): T {\n return useRuntime().props as T\n}\n\n/**\n * The full page context: host `record`, `entity`, and URL `params`. The\n * `record` is a snapshot taken at mount (`undefined` on record-less platform\n * pages) — fetch via `useSdk().data` for anything that must stay fresh.\n */\nexport function usePageContext(): PageContext {\n return useRuntime().pageCtx\n}\n\n/**\n * Navigate the host SPA to an in-app path, e.g.\n * `navigate('/org/acme/record/task/123')`. The host ignores absolute/external\n * URLs. Build org/app-prefixed paths with `useHostLocation().appBasePath`.\n *\n * Pass `{ peek: true }` to open the path in a peek (slide-over) panel instead\n * of full-page navigation — e.g. `navigate(path, { peek: true })`. The host\n * peeks what it can (today: platform pages) and falls back to full navigation.\n */\nexport function useNavigate(): (to: string, options?: NavigateOptions) => void {\n return useRuntime().navigate\n}\n\n/**\n * Open a prepared call from a conversation brief id: the HOST previews the brief and\n * places the call through its softphone (an iframe cannot dial). Pair it with\n * `ConversationBriefReview`'s `onOpenCall` from `@proteos/ui`.\n */\nexport function useOpenCall(): (conversationBriefId: string) => void {\n return useRuntime().openCall\n}\n\n/** The API origin SDK calls resolve against (for building raw asset URLs). */\nexport function useApiBaseUrl(): string {\n return useRuntime().apiBaseUrl\n}\n\nconst NOOP_OVERLAY: OverlayController = {\n expand: () => {\n console.warn(\n '@proteos/component-sdk: useOverlayExpansion() has no effect — this runtime ' +\n 'does not support overlay promotion (older shell or non-promoting host).',\n )\n },\n collapse: () => {},\n isExpanded: () => false,\n}\n\n/**\n * Manual overlay promotion — lifts the whole component iframe over the rest of\n * the page so an overlay can escape the frame's box.\n *\n * You rarely need this. Every `@proteos/ui` overlay (Modal, Popover, Menu,\n * Select, Tooltip, …) portals to the iframe document's `<body>`, which the\n * runtime watches — those promote automatically, with no code. Reach for this\n * hook only when you portal somewhere else yourself, or want the frame lifted\n * *before* the overlay mounts. Reference-counted: pair every `expand()` with a\n * `collapse()`.\n */\nexport function useOverlayExpansion(): OverlayController {\n return useRuntime().overlay ?? NOOP_OVERLAY\n}\n\n/**\n * Open ANOTHER component in a modal the host renders above everything — the\n * cross-component flow (a picker, a wizard step, a confirm dialog shared by\n * several components). Resolves with whatever that component closed with, or\n * `undefined` if the user dismissed it.\n *\n * ```ts\n * const openModal = useComponentModal()\n * const picked = await openModal('contact-picker', { entity: 'contact' }, { title: 'Pick a contact' })\n * ```\n *\n * For an overlay that is part of THIS component, just render a `<Modal>` from\n * `@proteos/ui` — it promotes automatically.\n */\nexport function useComponentModal(): (\n componentSlug: string,\n props?: Record<string, unknown>,\n options?: OpenModalOptions,\n) => Promise<unknown> {\n return useRuntime().openModal\n}\n\nexport interface ModalHost {\n /** True when this component is rendered as the content of a host modal. */\n isInModal: boolean\n /** Close the host modal, resolving the opener's promise with `result`.\n * No-op outside a modal. */\n close: (result?: unknown) => void\n}\n\n/**\n * For a component that is being shown INSIDE a host modal (opened by another\n * component's `useComponentModal()`): close it and hand a value back.\n * `isInModal` is false on ordinary page-hosted mounts, so one component can\n * serve both roles.\n */\nexport function useModalHost(): ModalHost {\n const requestId = useRuntime().modalRequestId\n const close = useCallback(\n (result?: unknown) => {\n if (requestId === undefined) return\n postModalResult(requestId, result)\n },\n [requestId],\n )\n return useMemo(() => ({ isInModal: requestId !== undefined, close }), [requestId, close])\n}\n\n/**\n * A getter for the current bearer token. Returns a function (not the token)\n * because the token is refreshed in place — read it at call time for a raw\n * `fetch`. Most components never need this; prefer `useSdk()`.\n */\nexport function useAuthToken(): () => string {\n return useRuntime().getToken\n}\n\nexport interface HostLocation {\n /** The host tab's pathname (same-origin read), or null if unavailable. */\n pathname: string | null\n /** The org id parsed from `/org/<orgId>/…`, or null. */\n orgId: string | null\n /** The `/org/<orgId>/app/<appId>` prefix, or null when not on an app page. */\n appBasePath: string | null\n}\n\nfunction readHostLocation(): HostLocation {\n const empty: HostLocation = { pathname: null, orgId: null, appBasePath: null }\n try {\n const parentWindow = window.parent\n if (!parentWindow || parentWindow === window) return empty\n const pathname = parentWindow.location.pathname\n const appMatch = pathname.match(/^\\/org\\/[^/]+\\/app\\/[^/]+/)\n const orgMatch = pathname.match(/^\\/org\\/([^/]+)\\//)\n return {\n pathname,\n orgId: orgMatch ? (orgMatch[1] ?? null) : null,\n appBasePath: appMatch ? appMatch[0] : null,\n }\n } catch {\n // Cross-origin (untrusted-component future) or detached — fall back to null.\n return empty\n }\n}\n\n/**\n * Read the host tab's location (same-origin) — the org id and `/org/.../app/...`\n * prefix needed to build navigation targets on platform pages. Read once on\n * mount (the iframe re-inits when the host route changes).\n */\nexport function useHostLocation(): HostLocation {\n const [loc] = useState(readHostLocation)\n return loc\n}\n\nexport interface FillViewportOptions {\n /** Gap left below the component (px). Default 24. */\n bottomMargin?: number\n /** Floor for the computed height (px). Default 320. */\n minHeight?: number\n}\n\n/**\n * Compute a \"fill the rest of the viewport\" height for full-bleed layouts\n * (boards, canvases). The runtime auto-sizes the iframe to its content, so a\n * component can't use its own `vh` units (circular). The iframe is same-origin,\n * so this measures the parent viewport minus the iframe's offset instead.\n * Returns `null` when it can't measure (fall back to natural height).\n */\nexport function useFillViewportHeight(options: FillViewportOptions = {}): number | null {\n const { bottomMargin = 24, minHeight = 320 } = options\n const [height, setHeight] = useState<number | null>(null)\n\n useEffect(() => {\n function compute(): void {\n try {\n const frame = window.frameElement\n const parentWindow = window.parent\n if (!frame || !parentWindow || parentWindow === window) return\n const available =\n parentWindow.innerHeight - frame.getBoundingClientRect().top - bottomMargin\n setHeight(Math.max(available, minHeight))\n } catch {\n setHeight(null) // cross-origin or detached — fall back to natural height\n }\n }\n compute()\n try {\n window.parent.addEventListener('resize', compute)\n return () => window.parent.removeEventListener('resize', compute)\n } catch {\n return\n }\n }, [bottomMargin, minHeight])\n\n return height\n}\n"]}
|
package/dist/protocol.cjs
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkIPYKNCDU_cjs = require('./chunk-IPYKNCDU.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
Object.defineProperty(exports, "COMPONENT_OVERLAY_Z_INDEX", {
|
|
8
8
|
enumerable: true,
|
|
9
|
-
get: function () { return
|
|
9
|
+
get: function () { return chunkIPYKNCDU_cjs.COMPONENT_OVERLAY_Z_INDEX; }
|
|
10
10
|
});
|
|
11
11
|
Object.defineProperty(exports, "MESSAGE_SOURCE", {
|
|
12
12
|
enumerable: true,
|
|
13
|
-
get: function () { return
|
|
13
|
+
get: function () { return chunkIPYKNCDU_cjs.MESSAGE_SOURCE; }
|
|
14
14
|
});
|
|
15
15
|
Object.defineProperty(exports, "isHostMessage", {
|
|
16
16
|
enumerable: true,
|
|
17
|
-
get: function () { return
|
|
17
|
+
get: function () { return chunkIPYKNCDU_cjs.isHostMessage; }
|
|
18
18
|
});
|
|
19
19
|
Object.defineProperty(exports, "isRuntimeMessage", {
|
|
20
20
|
enumerable: true,
|
|
21
|
-
get: function () { return
|
|
21
|
+
get: function () { return chunkIPYKNCDU_cjs.isRuntimeMessage; }
|
|
22
22
|
});
|
|
23
23
|
//# sourceMappingURL=protocol.cjs.map
|
|
24
24
|
//# sourceMappingURL=protocol.cjs.map
|
package/dist/protocol.d.cts
CHANGED
|
@@ -106,6 +106,14 @@ interface OpenPeekMessage {
|
|
|
106
106
|
type: 'OPEN_PEEK';
|
|
107
107
|
to: string;
|
|
108
108
|
}
|
|
109
|
+
/** Ask the host to open a prepared call: the host shows the conversation brief's
|
|
110
|
+
* preview (its softphone owns the dial) and lets the user place the call.
|
|
111
|
+
* Ignored on public pages and on hosts without a softphone. */
|
|
112
|
+
interface OpenCallMessage {
|
|
113
|
+
type: 'OPEN_CALL';
|
|
114
|
+
/** The conversation brief to preview and dial from. */
|
|
115
|
+
conversationBriefId: string;
|
|
116
|
+
}
|
|
109
117
|
/** The runtime has (or no longer has) an overlay open and needs the host to
|
|
110
118
|
* promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.
|
|
111
119
|
*
|
|
@@ -158,11 +166,11 @@ interface ErrorMessage {
|
|
|
158
166
|
message: string;
|
|
159
167
|
stack?: string;
|
|
160
168
|
}
|
|
161
|
-
type RuntimeMessage = ReadyMessage | ResizeMessage | NavigateMessage | OpenPeekMessage | OverlayStateMessage | OpenModalMessage | ModalResultMessage | EscapePressedMessage | ErrorMessage;
|
|
169
|
+
type RuntimeMessage = ReadyMessage | ResizeMessage | NavigateMessage | OpenPeekMessage | OpenCallMessage | OverlayStateMessage | OpenModalMessage | ModalResultMessage | EscapePressedMessage | ErrorMessage;
|
|
162
170
|
type Envelope<T> = T & {
|
|
163
171
|
source: typeof MESSAGE_SOURCE;
|
|
164
172
|
};
|
|
165
173
|
declare function isHostMessage(data: unknown): data is Envelope<HostMessage>;
|
|
166
174
|
declare function isRuntimeMessage(data: unknown): data is Envelope<RuntimeMessage>;
|
|
167
175
|
|
|
168
|
-
export { type AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, type DataInvalidateMessage, type Envelope, type ErrorMessage, type EscapePressedMessage, type HostMessage, type InitMessage, MESSAGE_SOURCE, type ModalClosedMessage, type ModalResultMessage, type NavigateMessage, type OpenModalMessage, type OpenPeekMessage, type OverlayRect, type OverlayRectMessage, type OverlayStateMessage, type PageContext, type ReadyMessage, type ResizeMessage, type RuntimeMessage, isHostMessage, isRuntimeMessage };
|
|
176
|
+
export { type AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, type DataInvalidateMessage, type Envelope, type ErrorMessage, type EscapePressedMessage, type HostMessage, type InitMessage, MESSAGE_SOURCE, type ModalClosedMessage, type ModalResultMessage, type NavigateMessage, type OpenCallMessage, type OpenModalMessage, type OpenPeekMessage, type OverlayRect, type OverlayRectMessage, type OverlayStateMessage, type PageContext, type ReadyMessage, type ResizeMessage, type RuntimeMessage, isHostMessage, isRuntimeMessage };
|
package/dist/protocol.d.ts
CHANGED
|
@@ -106,6 +106,14 @@ interface OpenPeekMessage {
|
|
|
106
106
|
type: 'OPEN_PEEK';
|
|
107
107
|
to: string;
|
|
108
108
|
}
|
|
109
|
+
/** Ask the host to open a prepared call: the host shows the conversation brief's
|
|
110
|
+
* preview (its softphone owns the dial) and lets the user place the call.
|
|
111
|
+
* Ignored on public pages and on hosts without a softphone. */
|
|
112
|
+
interface OpenCallMessage {
|
|
113
|
+
type: 'OPEN_CALL';
|
|
114
|
+
/** The conversation brief to preview and dial from. */
|
|
115
|
+
conversationBriefId: string;
|
|
116
|
+
}
|
|
109
117
|
/** The runtime has (or no longer has) an overlay open and needs the host to
|
|
110
118
|
* promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.
|
|
111
119
|
*
|
|
@@ -158,11 +166,11 @@ interface ErrorMessage {
|
|
|
158
166
|
message: string;
|
|
159
167
|
stack?: string;
|
|
160
168
|
}
|
|
161
|
-
type RuntimeMessage = ReadyMessage | ResizeMessage | NavigateMessage | OpenPeekMessage | OverlayStateMessage | OpenModalMessage | ModalResultMessage | EscapePressedMessage | ErrorMessage;
|
|
169
|
+
type RuntimeMessage = ReadyMessage | ResizeMessage | NavigateMessage | OpenPeekMessage | OpenCallMessage | OverlayStateMessage | OpenModalMessage | ModalResultMessage | EscapePressedMessage | ErrorMessage;
|
|
162
170
|
type Envelope<T> = T & {
|
|
163
171
|
source: typeof MESSAGE_SOURCE;
|
|
164
172
|
};
|
|
165
173
|
declare function isHostMessage(data: unknown): data is Envelope<HostMessage>;
|
|
166
174
|
declare function isRuntimeMessage(data: unknown): data is Envelope<RuntimeMessage>;
|
|
167
175
|
|
|
168
|
-
export { type AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, type DataInvalidateMessage, type Envelope, type ErrorMessage, type EscapePressedMessage, type HostMessage, type InitMessage, MESSAGE_SOURCE, type ModalClosedMessage, type ModalResultMessage, type NavigateMessage, type OpenModalMessage, type OpenPeekMessage, type OverlayRect, type OverlayRectMessage, type OverlayStateMessage, type PageContext, type ReadyMessage, type ResizeMessage, type RuntimeMessage, isHostMessage, isRuntimeMessage };
|
|
176
|
+
export { type AuthRefreshMessage, COMPONENT_OVERLAY_Z_INDEX, type DataInvalidateMessage, type Envelope, type ErrorMessage, type EscapePressedMessage, type HostMessage, type InitMessage, MESSAGE_SOURCE, type ModalClosedMessage, type ModalResultMessage, type NavigateMessage, type OpenCallMessage, type OpenModalMessage, type OpenPeekMessage, type OverlayRect, type OverlayRectMessage, type OverlayStateMessage, type PageContext, type ReadyMessage, type ResizeMessage, type RuntimeMessage, isHostMessage, isRuntimeMessage };
|
package/dist/protocol.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { COMPONENT_OVERLAY_Z_INDEX, MESSAGE_SOURCE, isHostMessage, isRuntimeMessage } from './chunk-
|
|
1
|
+
export { COMPONENT_OVERLAY_Z_INDEX, MESSAGE_SOURCE, isHostMessage, isRuntimeMessage } from './chunk-RTYCYWKC.js';
|
|
2
2
|
//# sourceMappingURL=protocol.js.map
|
|
3
3
|
//# sourceMappingURL=protocol.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@proteos/component-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.51.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "Typed runtime hooks for authoring Proteos custom components — the SDK you import inside a component bundle.",
|
|
6
6
|
"repository": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"src"
|
|
43
43
|
],
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@proteos/sdk": "^0.
|
|
45
|
+
"@proteos/sdk": "^0.51.0"
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
48
|
"@tanstack/react-query": ">=5.0.0",
|
package/src/context.tsx
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
MESSAGE_SOURCE,
|
|
17
17
|
type ModalResultMessage,
|
|
18
18
|
type NavigateMessage,
|
|
19
|
+
type OpenCallMessage,
|
|
19
20
|
type OpenModalMessage,
|
|
20
21
|
type OpenPeekMessage,
|
|
21
22
|
type PageContext,
|
|
@@ -108,6 +109,9 @@ export interface RuntimeContextValue extends RuntimeValue {
|
|
|
108
109
|
/** Navigate the host SPA to an in-app path (posts a NAVIGATE message), or
|
|
109
110
|
* open it in a peek panel with `{ peek: true }` (posts OPEN_PEEK). */
|
|
110
111
|
navigate: (to: string, options?: NavigateOptions) => void
|
|
112
|
+
/** Ask the host to open a prepared call from a conversation brief (posts
|
|
113
|
+
* OPEN_CALL): the host previews the brief and dials through its softphone. */
|
|
114
|
+
openCall: (conversationBriefId: string) => void
|
|
111
115
|
/** Open another component in a host-rendered modal; resolves with the value
|
|
112
116
|
* that component closed with (`undefined` if dismissed). */
|
|
113
117
|
openModal: (
|
|
@@ -133,6 +137,16 @@ function postOpenPeek(to: string): void {
|
|
|
133
137
|
window.parent?.postMessage(envelope, '*')
|
|
134
138
|
}
|
|
135
139
|
|
|
140
|
+
/** Post OPEN_CALL — the host previews the conversation brief and owns the dial. */
|
|
141
|
+
function openCall(conversationBriefId: string): void {
|
|
142
|
+
const envelope: Envelope<OpenCallMessage> = {
|
|
143
|
+
source: MESSAGE_SOURCE,
|
|
144
|
+
type: 'OPEN_CALL',
|
|
145
|
+
conversationBriefId,
|
|
146
|
+
}
|
|
147
|
+
window.parent?.postMessage(envelope, '*')
|
|
148
|
+
}
|
|
149
|
+
|
|
136
150
|
/** Navigate full-page (default) or into a peek panel (`{ peek: true }`). */
|
|
137
151
|
function navigate(to: string, options?: NavigateOptions): void {
|
|
138
152
|
if (options?.peek) postOpenPeek(to)
|
|
@@ -211,6 +225,9 @@ export function RuntimeProvider({ value, children }: { value: RuntimeValue; chil
|
|
|
211
225
|
// The shell builds `value` once at INIT (a stable state object — clients,
|
|
212
226
|
// props and pageCtx are all set once), so memoizing on its identity recreates
|
|
213
227
|
// the context only when the runtime genuinely re-inits.
|
|
214
|
-
const ctx = useMemo<RuntimeContextValue>(
|
|
228
|
+
const ctx = useMemo<RuntimeContextValue>(
|
|
229
|
+
() => ({ ...value, navigate, openCall, openModal }),
|
|
230
|
+
[value],
|
|
231
|
+
)
|
|
215
232
|
return <RuntimeContext.Provider value={ctx}>{children}</RuntimeContext.Provider>
|
|
216
233
|
}
|
package/src/hooks.ts
CHANGED
|
@@ -61,6 +61,15 @@ export function useNavigate(): (to: string, options?: NavigateOptions) => void {
|
|
|
61
61
|
return useRuntime().navigate
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
/**
|
|
65
|
+
* Open a prepared call from a conversation brief id: the HOST previews the brief and
|
|
66
|
+
* places the call through its softphone (an iframe cannot dial). Pair it with
|
|
67
|
+
* `ConversationBriefReview`'s `onOpenCall` from `@proteos/ui`.
|
|
68
|
+
*/
|
|
69
|
+
export function useOpenCall(): (conversationBriefId: string) => void {
|
|
70
|
+
return useRuntime().openCall
|
|
71
|
+
}
|
|
72
|
+
|
|
64
73
|
/** The API origin SDK calls resolve against (for building raw asset URLs). */
|
|
65
74
|
export function useApiBaseUrl(): string {
|
|
66
75
|
return useRuntime().apiBaseUrl
|
package/src/index.ts
CHANGED
|
@@ -25,6 +25,7 @@ export {
|
|
|
25
25
|
useHostLocation,
|
|
26
26
|
useModalHost,
|
|
27
27
|
useNavigate,
|
|
28
|
+
useOpenCall,
|
|
28
29
|
useOverlayExpansion,
|
|
29
30
|
usePageContext,
|
|
30
31
|
useProps,
|
|
@@ -46,6 +47,7 @@ export {
|
|
|
46
47
|
type ModalClosedMessage,
|
|
47
48
|
type ModalResultMessage,
|
|
48
49
|
type NavigateMessage,
|
|
50
|
+
type OpenCallMessage,
|
|
49
51
|
type OpenModalMessage,
|
|
50
52
|
type OpenPeekMessage,
|
|
51
53
|
type OverlayRect,
|
package/src/protocol.ts
CHANGED
|
@@ -136,6 +136,15 @@ export interface OpenPeekMessage {
|
|
|
136
136
|
to: string
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
/** Ask the host to open a prepared call: the host shows the conversation brief's
|
|
140
|
+
* preview (its softphone owns the dial) and lets the user place the call.
|
|
141
|
+
* Ignored on public pages and on hosts without a softphone. */
|
|
142
|
+
export interface OpenCallMessage {
|
|
143
|
+
type: 'OPEN_CALL'
|
|
144
|
+
/** The conversation brief to preview and dial from. */
|
|
145
|
+
conversationBriefId: string
|
|
146
|
+
}
|
|
147
|
+
|
|
139
148
|
/** The runtime has (or no longer has) an overlay open and needs the host to
|
|
140
149
|
* promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.
|
|
141
150
|
*
|
|
@@ -198,6 +207,7 @@ export type RuntimeMessage =
|
|
|
198
207
|
| ResizeMessage
|
|
199
208
|
| NavigateMessage
|
|
200
209
|
| OpenPeekMessage
|
|
210
|
+
| OpenCallMessage
|
|
201
211
|
| OverlayStateMessage
|
|
202
212
|
| OpenModalMessage
|
|
203
213
|
| ModalResultMessage
|