@milofly/app-bridge 0.0.0-stage → 0.1.1

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/contract.js ADDED
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Milofly App Bridge — host ↔ embedded app message contract (single source).
3
+ *
4
+ * Both ends consume this file: the Milofly store panel (host, via `@milofly/app-bridge/host`)
5
+ * and every embedded app (via `createApp` from `@milofly/app-bridge`). A message that is not
6
+ * described here does not exist; a field that is not validated here is not accepted.
7
+ *
8
+ * Versioning: v1 messages (`ready`, `init`, `resize`, `token-request`, `token`, `token-error`)
9
+ * keep their shape, so apps written against v1 keep working. v2 adds host actions
10
+ * (`toast`, `title`, `navigate`, `redirect`, `open`, `confirm`, `loading`) answered with
11
+ * `result`, plus extra `init` fields. A breaking change bumps {@link CONTRACT_VERSION}.
12
+ */
13
+ /** Current contract version, sent by the host in `milofly:init.contractVersion`. */
14
+ export const CONTRACT_VERSION = 2;
15
+ /** Every message type on the wire. */
16
+ export const MessageType = {
17
+ /** app → host: the app is listening; host answers with `init` (every time). */
18
+ Ready: "milofly:ready",
19
+ /** host → app: context of this frame. */
20
+ Init: "milofly:init",
21
+ /** app → host: content height in CSS px (ignored on full-page surfaces). */
22
+ Resize: "milofly:resize",
23
+ /** app → host: ask for a fresh session token. */
24
+ TokenRequest: "milofly:token-request",
25
+ /** host → app: fresh session token for a `token-request`. */
26
+ Token: "milofly:token",
27
+ /** host → app: no token could be issued for a `token-request` (`reason` is an access reason code). */
28
+ TokenError: "milofly:token-error",
29
+ /** app → host (v2): show a toast in the panel. */
30
+ Toast: "milofly:toast",
31
+ /** app → host (v2): set the page title shown by the panel. */
32
+ Title: "milofly:title",
33
+ /** app → host (v2): the app moved to another in-app path; the panel mirrors it in its own URL. */
34
+ Navigate: "milofly:navigate",
35
+ /** app → host (v2): open a panel resource (order/product/customer detail). */
36
+ Redirect: "milofly:redirect",
37
+ /** app → host (v2): open an external https URL in a new tab. */
38
+ Open: "milofly:open",
39
+ /** app → host (v2): ask the merchant to confirm; answered with `{ confirmed }`. */
40
+ Confirm: "milofly:confirm",
41
+ /** app → host (v2): show/hide the panel progress indicator. */
42
+ Loading: "milofly:loading",
43
+ /** host → app (v2): answer to a v2 request. */
44
+ Result: "milofly:result",
45
+ };
46
+ /** Panel surfaces where an app frame can be rendered. */
47
+ export const Surface = {
48
+ Fullpage: "fullpage",
49
+ OrderDetail: "order-detail",
50
+ CustomerDetail: "customer-detail",
51
+ ProductDetail: "product-detail",
52
+ };
53
+ export const SURFACES = Object.freeze(Object.values(Surface));
54
+ export function isSurface(value) {
55
+ return typeof value === "string" && SURFACES.includes(value);
56
+ }
57
+ /** Panel resources an app may point to (`redirect`) and detail surfaces show. */
58
+ export const Resource = {
59
+ Order: "order",
60
+ Customer: "customer",
61
+ Product: "product",
62
+ };
63
+ export const RESOURCES = Object.freeze(Object.values(Resource));
64
+ export function isResource(value) {
65
+ return typeof value === "string" && RESOURCES.includes(value);
66
+ }
67
+ /** Which resource a surface is about (`null` = the surface is not bound to one record). */
68
+ export const SURFACE_RESOURCE = Object.freeze({
69
+ [Surface.Fullpage]: null,
70
+ [Surface.OrderDetail]: Resource.Order,
71
+ [Surface.CustomerDetail]: Resource.Customer,
72
+ [Surface.ProductDetail]: Resource.Product,
73
+ });
74
+ /** Host actions (v2). A host lists the ones it implements in `init.hostCapabilities`. */
75
+ export const HostCapability = {
76
+ Toast: "toast",
77
+ Title: "title",
78
+ Navigate: "navigate",
79
+ Redirect: "redirect",
80
+ Open: "open",
81
+ Confirm: "confirm",
82
+ Loading: "loading",
83
+ };
84
+ export const HOST_CAPABILITIES = Object.freeze(Object.values(HostCapability));
85
+ /** Request message type of each host action. */
86
+ export const CAPABILITY_MESSAGE = Object.freeze({
87
+ toast: MessageType.Toast,
88
+ title: MessageType.Title,
89
+ navigate: MessageType.Navigate,
90
+ redirect: MessageType.Redirect,
91
+ open: MessageType.Open,
92
+ confirm: MessageType.Confirm,
93
+ loading: MessageType.Loading,
94
+ });
95
+ export const TOAST_TONES = Object.freeze(["info", "success", "warning", "critical"]);
96
+ export const CONFIRM_TONES = Object.freeze(["default", "critical"]);
97
+ /** Length limits enforced by the host (characters). */
98
+ export const LIMITS = Object.freeze({
99
+ requestId: 128,
100
+ toastMessage: 300,
101
+ title: 120,
102
+ confirmTitle: 120,
103
+ confirmMessage: 1000,
104
+ confirmLabel: 40,
105
+ path: 2048,
106
+ url: 2048,
107
+ resourceId: 19,
108
+ });
109
+ /** Query parameters the host adds to the frame URL. */
110
+ export const UrlParam = {
111
+ /** Short-lived signed session token (the app strips it from its address bar). */
112
+ EmbedToken: "embed_token",
113
+ /** Origin of the host panel. The app talks only to this origin. */
114
+ HostOrigin: "mf_host",
115
+ /** In-app path to open (set when the merchant reloads or deep-links a full-page app). */
116
+ Path: "mf_path",
117
+ };
118
+ /** `result.error` codes. */
119
+ export const ResultError = {
120
+ /** The host does not implement this action. */
121
+ Unsupported: "unsupported",
122
+ /** The request failed validation (see {@link LIMITS} and the per-action rules). */
123
+ Invalid: "invalid",
124
+ /** The host refused (e.g. the merchant is not allowed to open the resource). */
125
+ Denied: "denied",
126
+ /** The host tried and failed. */
127
+ Failed: "failed",
128
+ };
129
+ /** Timings of the handshake and token refresh. */
130
+ export const TIMING = Object.freeze({
131
+ /** Host: if the app never sends `ready`, `init` is sent this long after the frame loads. */
132
+ initFallbackMs: 1200,
133
+ /** App: how long `createApp` waits for `init`. */
134
+ handshakeTimeoutMs: 10000,
135
+ /** App: how long a token request waits for the host. */
136
+ tokenRequestTimeoutMs: 10000,
137
+ /** App: a cached token is refreshed when it expires within this many seconds. */
138
+ tokenRefreshMarginSeconds: 30,
139
+ /** App: how long a v2 request (except `confirm`) waits for `result`. */
140
+ requestTimeoutMs: 10000,
141
+ /** Host: identical token requests within this window share one issued token. */
142
+ hostTokenCacheMs: 5000,
143
+ });
144
+ // ─────────────────────────────────────────────────────────────────────────────
145
+ // Validation (used by both ends; never trust the other side)
146
+ // ─────────────────────────────────────────────────────────────────────────────
147
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
148
+ function asRecord(value) {
149
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
150
+ }
151
+ function text(value, max, allowEmpty = false) {
152
+ if (typeof value !== "string")
153
+ return null;
154
+ const trimmed = value.trim();
155
+ if (!allowEmpty && trimmed.length === 0)
156
+ return null;
157
+ if (trimmed.length > max)
158
+ return null;
159
+ return trimmed;
160
+ }
161
+ export function isRequestId(value) {
162
+ return typeof value === "string" && value.length > 0 && value.length <= LIMITS.requestId && !CONTROL_CHARS.test(value);
163
+ }
164
+ /** In-app path: starts with a single `/`, no backslash, no control characters. */
165
+ export function isAppPath(value) {
166
+ return (typeof value === "string" &&
167
+ value.length > 0 &&
168
+ value.length <= LIMITS.path &&
169
+ value.startsWith("/") &&
170
+ !value.startsWith("//") &&
171
+ !value.includes("\\") &&
172
+ !CONTROL_CHARS.test(value));
173
+ }
174
+ /** Positive integer record id (as string). */
175
+ export function isResourceId(value) {
176
+ return typeof value === "string" && /^[1-9][0-9]*$/.test(value) && value.length <= LIMITS.resourceId;
177
+ }
178
+ /** External URL the host may open: absolute https only. */
179
+ export function isOpenableUrl(value) {
180
+ if (typeof value !== "string" || value.length > LIMITS.url || CONTROL_CHARS.test(value))
181
+ return false;
182
+ try {
183
+ return new URL(value).protocol === "https:";
184
+ }
185
+ catch {
186
+ return false;
187
+ }
188
+ }
189
+ /** Loopback hosts allowed over plain http (local development only). */
190
+ export const LOOPBACK_HOSTNAMES = Object.freeze(["localhost", "127.0.0.1", "[::1]"]);
191
+ /** Origin allowed for a host panel or an app frame: https, or http on loopback. */
192
+ export function isSecureOrigin(origin) {
193
+ let url;
194
+ try {
195
+ url = new URL(origin);
196
+ }
197
+ catch {
198
+ return false;
199
+ }
200
+ if (url.origin !== origin)
201
+ return false;
202
+ if (url.protocol === "https:")
203
+ return true;
204
+ return url.protocol === "http:" && LOOPBACK_HOSTNAMES.includes(url.hostname);
205
+ }
206
+ function parseRequestPayload(capability, msg) {
207
+ const done = (payload) => ({ ok: true, payload: payload });
208
+ switch (capability) {
209
+ case "toast": {
210
+ const message = text(msg.message, LIMITS.toastMessage);
211
+ const tone = msg.tone;
212
+ if (message === null || !TOAST_TONES.includes(tone))
213
+ return { ok: false };
214
+ return done({ message, tone: tone });
215
+ }
216
+ case "title": {
217
+ const title = text(msg.title, LIMITS.title, true);
218
+ return title === null ? { ok: false } : done({ title });
219
+ }
220
+ case "navigate":
221
+ return isAppPath(msg.path) ? done({ path: msg.path }) : { ok: false };
222
+ case "redirect": {
223
+ const id = typeof msg.id === "number" && Number.isSafeInteger(msg.id) ? String(msg.id) : msg.id;
224
+ return isResource(msg.resource) && isResourceId(id) ? done({ resource: msg.resource, id }) : { ok: false };
225
+ }
226
+ case "open":
227
+ return isOpenableUrl(msg.url) ? done({ url: msg.url }) : { ok: false };
228
+ case "confirm": {
229
+ const title = text(msg.title, LIMITS.confirmTitle);
230
+ const message = text(msg.message, LIMITS.confirmMessage);
231
+ const confirmLabel = msg.confirmLabel == null ? null : text(msg.confirmLabel, LIMITS.confirmLabel);
232
+ const tone = msg.tone;
233
+ if (title === null || message === null || (msg.confirmLabel != null && confirmLabel === null))
234
+ return { ok: false };
235
+ if (!CONFIRM_TONES.includes(tone))
236
+ return { ok: false };
237
+ return done({ title, message, confirmLabel, tone: tone });
238
+ }
239
+ case "loading":
240
+ return typeof msg.active === "boolean" ? done({ active: msg.active }) : { ok: false };
241
+ default:
242
+ return { ok: false };
243
+ }
244
+ }
245
+ const CAPABILITY_BY_MESSAGE = new Map(HOST_CAPABILITIES.map((cap) => [CAPABILITY_MESSAGE[cap], cap]));
246
+ export function parseAppMessage(data) {
247
+ const msg = asRecord(data);
248
+ if (!msg || typeof msg.type !== "string" || !msg.type.startsWith("milofly:"))
249
+ return null;
250
+ const type = msg.type;
251
+ const requestId = isRequestId(msg.requestId) ? msg.requestId : null;
252
+ if (type === MessageType.Ready)
253
+ return { ok: true, message: { type } };
254
+ if (type === MessageType.Resize) {
255
+ const h = msg.height;
256
+ return typeof h === "number" && Number.isFinite(h) && h > 0
257
+ ? { ok: true, message: { type, height: h } }
258
+ : { ok: false, type, requestId: null, error: ResultError.Invalid };
259
+ }
260
+ if (type === MessageType.TokenRequest) {
261
+ return requestId ? { ok: true, message: { type, requestId } } : { ok: false, type, requestId: null, error: ResultError.Invalid };
262
+ }
263
+ const capability = CAPABILITY_BY_MESSAGE.get(type);
264
+ if (!capability)
265
+ return { ok: false, type, requestId, error: ResultError.Unsupported };
266
+ if (!requestId)
267
+ return { ok: false, type, requestId: null, error: ResultError.Invalid };
268
+ const parsed = parseRequestPayload(capability, msg);
269
+ if (!parsed.ok)
270
+ return { ok: false, type, requestId, error: ResultError.Invalid };
271
+ return {
272
+ ok: true,
273
+ message: { type: CAPABILITY_MESSAGE[capability], capability, requestId, payload: parsed.payload },
274
+ };
275
+ }
276
+ function positiveInt(value) {
277
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
278
+ }
279
+ /**
280
+ * Validates an `init` message. Only contract v2+ is accepted: every field is required and nothing is
281
+ * filled in on the app's behalf (a v1 host never sends `contractVersion`; the SDK does not guess one).
282
+ * Returns the reason when the message is rejected so the app can report it.
283
+ */
284
+ export function parseInitMessage(data) {
285
+ const msg = asRecord(data);
286
+ if (!msg || msg.type !== MessageType.Init)
287
+ return { ok: false, reason: "not_init" };
288
+ if (typeof msg.contractVersion !== "number" || msg.contractVersion < 2)
289
+ return { ok: false, reason: "contract_version_unsupported" };
290
+ const store = asRecord(msg.storeContext);
291
+ const storeId = positiveInt(store?.storeId);
292
+ const regionId = positiveInt(store?.regionId);
293
+ if (!store || storeId === null || regionId === null || typeof store.currencyCode !== "string" || store.currencyCode.length === 0)
294
+ return { ok: false, reason: "store_context_invalid" };
295
+ if (typeof msg.pluginKey !== "string" || msg.pluginKey.length === 0)
296
+ return { ok: false, reason: "plugin_key_invalid" };
297
+ if (typeof msg.uiLocale !== "string" || msg.uiLocale.length === 0)
298
+ return { ok: false, reason: "ui_locale_invalid" };
299
+ if (typeof msg.contentLocale !== "string" || msg.contentLocale.length === 0)
300
+ return { ok: false, reason: "content_locale_invalid" };
301
+ if (!isSurface(msg.surface))
302
+ return { ok: false, reason: "surface_invalid" };
303
+ if (typeof msg.hostOrigin !== "string" || !isSecureOrigin(msg.hostOrigin))
304
+ return { ok: false, reason: "host_origin_invalid" };
305
+ if (!Array.isArray(msg.hostCapabilities))
306
+ return { ok: false, reason: "host_capabilities_invalid" };
307
+ let entity = null;
308
+ const expected = SURFACE_RESOURCE[msg.surface];
309
+ if (expected !== null) {
310
+ const rec = asRecord(msg.entity);
311
+ const id = rec ? (typeof rec.id === "number" ? String(rec.id) : rec.id) : null;
312
+ if (!rec || rec.type !== expected || !isResourceId(id))
313
+ return { ok: false, reason: "entity_invalid" };
314
+ entity = { type: expected, id };
315
+ }
316
+ else if (msg.entity != null) {
317
+ return { ok: false, reason: "entity_invalid" };
318
+ }
319
+ if (msg.path != null && !isAppPath(msg.path))
320
+ return { ok: false, reason: "path_invalid" };
321
+ return {
322
+ ok: true,
323
+ message: {
324
+ type: MessageType.Init,
325
+ contractVersion: msg.contractVersion,
326
+ pluginKey: msg.pluginKey,
327
+ locale: msg.uiLocale,
328
+ uiLocale: msg.uiLocale,
329
+ contentLocale: msg.contentLocale,
330
+ surface: msg.surface,
331
+ entity,
332
+ storeContext: { storeId, regionId, currencyCode: store.currencyCode },
333
+ hostOrigin: msg.hostOrigin,
334
+ // Unknown capability names from a newer host are dropped: the app cannot call what it does not know.
335
+ hostCapabilities: msg.hostCapabilities.filter((c) => HOST_CAPABILITIES.includes(c)),
336
+ path: typeof msg.path === "string" ? msg.path : null,
337
+ },
338
+ };
339
+ }
340
+ /** Parses a `token`, `token-error` or `result` message received by the app. `null` = not one of them / invalid. */
341
+ export function parseHostReply(data) {
342
+ const msg = asRecord(data);
343
+ if (!msg || !isRequestId(msg.requestId))
344
+ return null;
345
+ switch (msg.type) {
346
+ case MessageType.Token:
347
+ return typeof msg.token === "string" && msg.token.length > 0
348
+ ? { type: MessageType.Token, requestId: msg.requestId, token: msg.token }
349
+ : null;
350
+ case MessageType.TokenError:
351
+ return typeof msg.reason === "string" && msg.reason.length > 0
352
+ ? { type: MessageType.TokenError, requestId: msg.requestId, reason: msg.reason }
353
+ : null;
354
+ case MessageType.Result: {
355
+ if (typeof msg.ok !== "boolean")
356
+ return null;
357
+ if (msg.ok)
358
+ return { type: MessageType.Result, requestId: msg.requestId, ok: true, data: msg.data };
359
+ const error = Object.values(ResultError).includes(msg.error) ? msg.error : null;
360
+ return error === null ? null : { type: MessageType.Result, requestId: msg.requestId, ok: false, error };
361
+ }
362
+ default:
363
+ return null;
364
+ }
365
+ }
package/host.d.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Milofly App Bridge — host engine.
3
+ *
4
+ * Used by the Milofly store panel to run one embedded app frame. Framework-free: the panel's React
5
+ * component owns rendering (overlay, toasts, dialogs) and hands the engine plain callbacks.
6
+ *
7
+ * Security rules (unchanged from v1, now in one place):
8
+ * - Messages are accepted only from the app origin AND from this frame's window. Another frame of
9
+ * the same origin on the same page (detail widgets) cannot answer or trigger this frame's turn.
10
+ * - Messages are posted only to the app origin, never to `"*"`.
11
+ * - The app key used for token requests is the host's own value, never read from a message.
12
+ */
13
+ import { type EntityRef, type HostActionPayloads, type HostActionResults, type HostCapabilityKey, type ResultErrorCode, type StoreContext, type SurfaceKey } from "@milofly/app-bridge/contract";
14
+ export * from "@milofly/app-bridge/contract";
15
+ /** Why an app URL cannot be framed. */
16
+ export type AppUrlRejection = "invalid" | "opaque" | "same_origin" | "insecure";
17
+ export type AppUrlCheck = {
18
+ ok: true;
19
+ url: URL;
20
+ origin: string;
21
+ } | {
22
+ ok: false;
23
+ reason: AppUrlRejection;
24
+ };
25
+ /**
26
+ * Decides whether `appUrl` may be framed by a host at `hostOrigin`.
27
+ * - The app must have its own origin: a same-origin frame with `allow-same-origin` escapes the sandbox.
28
+ * - https only; plain http only on loopback (local development).
29
+ * - Opaque origins (`data:`, `blob:`, `javascript:`) are refused: origin checks cannot hold for them.
30
+ */
31
+ export declare function checkAppUrl(appUrl: string, hostOrigin: string): AppUrlCheck;
32
+ /**
33
+ * Adds the bridge parameters to the frame URL. The session token is optional: detail widgets fetch
34
+ * it over the bridge instead (their URL stays token-free).
35
+ */
36
+ export declare function buildFrameUrl(baseUrl: string, params: {
37
+ hostOrigin: string;
38
+ embedToken?: string | null;
39
+ path?: string | null;
40
+ }): string;
41
+ /** Outcome of the host's token provider. `reason` is the access gate's reason code. */
42
+ export type TokenResult = {
43
+ ok: true;
44
+ token: string;
45
+ } | {
46
+ ok: false;
47
+ reason: string;
48
+ };
49
+ /** Host action handlers. A missing handler means the host does not offer that capability. */
50
+ export type HostHandlers = {
51
+ [K in HostCapabilityKey]?: (payload: HostActionPayloads[K]) => Promise<HostActionResults[K]> | HostActionResults[K];
52
+ };
53
+ export interface ResizePolicy {
54
+ min: number;
55
+ max: number;
56
+ /** Changes smaller than this are ignored: breaks the "frame resizes → content reflows → new height" loop. */
57
+ epsilon: number;
58
+ }
59
+ export interface HostOptions {
60
+ iframe: HTMLIFrameElement;
61
+ /** Origin returned by {@link checkAppUrl}. */
62
+ appOrigin: string;
63
+ pluginKey: string;
64
+ surface: SurfaceKey;
65
+ uiLocale: string;
66
+ contentLocale: string;
67
+ entity: EntityRef | null;
68
+ storeContext: StoreContext;
69
+ /** In-app path opened first (full-page surface), else `null`. */
70
+ path: string | null;
71
+ /** Issues a fresh session token for this app on this surface. */
72
+ getSessionToken: () => Promise<TokenResult>;
73
+ handlers: HostHandlers;
74
+ /** Starting height of the frame; `resize` messages are compared with it. */
75
+ initialHeight: number;
76
+ /** `null`: the frame fills its container and `resize` is ignored (full-page apps). */
77
+ resizePolicy: ResizePolicy | null;
78
+ onHeight?: (height: number) => void;
79
+ /** First `ready` from the app, or the load fallback fired. */
80
+ onReady?: () => void;
81
+ /** Invalid or unsupported messages from the app (for the host's own diagnostics). */
82
+ onProtocolError?: (detail: {
83
+ type: string;
84
+ error: ResultErrorCode;
85
+ }) => void;
86
+ }
87
+ export interface HostHandle {
88
+ /** Call from the iframe's `load` event: starts the `init` fallback for apps that never send `ready`. */
89
+ frameLoaded(): void;
90
+ /** Capabilities announced in `init`. */
91
+ readonly capabilities: readonly HostCapabilityKey[];
92
+ destroy(): void;
93
+ }
94
+ /** Starts the bridge for one frame. Call {@link HostHandle.destroy} when the frame is removed. */
95
+ export declare function createHost(options: HostOptions): HostHandle;
96
+ /** Throw from a handler when the host refuses the action (answered as `denied`, not `failed`). */
97
+ export declare class HostActionDenied extends Error {
98
+ constructor(message?: string);
99
+ }
package/host.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Milofly App Bridge — host engine.
3
+ *
4
+ * Used by the Milofly store panel to run one embedded app frame. Framework-free: the panel's React
5
+ * component owns rendering (overlay, toasts, dialogs) and hands the engine plain callbacks.
6
+ *
7
+ * Security rules (unchanged from v1, now in one place):
8
+ * - Messages are accepted only from the app origin AND from this frame's window. Another frame of
9
+ * the same origin on the same page (detail widgets) cannot answer or trigger this frame's turn.
10
+ * - Messages are posted only to the app origin, never to `"*"`.
11
+ * - The app key used for token requests is the host's own value, never read from a message.
12
+ */
13
+ import { CONTRACT_VERSION, HOST_CAPABILITIES, MessageType, ResultError, TIMING, UrlParam, isSecureOrigin, parseAppMessage, } from "@milofly/app-bridge/contract";
14
+ export * from "@milofly/app-bridge/contract";
15
+ /**
16
+ * Decides whether `appUrl` may be framed by a host at `hostOrigin`.
17
+ * - The app must have its own origin: a same-origin frame with `allow-same-origin` escapes the sandbox.
18
+ * - https only; plain http only on loopback (local development).
19
+ * - Opaque origins (`data:`, `blob:`, `javascript:`) are refused: origin checks cannot hold for them.
20
+ */
21
+ export function checkAppUrl(appUrl, hostOrigin) {
22
+ let url;
23
+ try {
24
+ url = new URL(appUrl);
25
+ }
26
+ catch {
27
+ return { ok: false, reason: "invalid" };
28
+ }
29
+ if (url.origin === "null")
30
+ return { ok: false, reason: "opaque" };
31
+ if (url.origin === hostOrigin)
32
+ return { ok: false, reason: "same_origin" };
33
+ if (!isSecureOrigin(url.origin))
34
+ return { ok: false, reason: "insecure" };
35
+ return { ok: true, url, origin: url.origin };
36
+ }
37
+ /**
38
+ * Adds the bridge parameters to the frame URL. The session token is optional: detail widgets fetch
39
+ * it over the bridge instead (their URL stays token-free).
40
+ */
41
+ export function buildFrameUrl(baseUrl, params) {
42
+ const url = new URL(baseUrl);
43
+ url.searchParams.set(UrlParam.HostOrigin, params.hostOrigin);
44
+ if (params.path)
45
+ url.searchParams.set(UrlParam.Path, params.path);
46
+ if (params.embedToken)
47
+ url.searchParams.set(UrlParam.EmbedToken, params.embedToken);
48
+ return url.toString();
49
+ }
50
+ /** Starts the bridge for one frame. Call {@link HostHandle.destroy} when the frame is removed. */
51
+ export function createHost(options) {
52
+ const { iframe, appOrigin } = options;
53
+ const hostOrigin = window.location.origin;
54
+ const capabilities = HOST_CAPABILITIES.filter((cap) => typeof options.handlers[cap] === "function");
55
+ let destroyed = false;
56
+ let initSent = false;
57
+ let readySignalled = false;
58
+ let height = options.initialHeight;
59
+ let fallbackTimer = null;
60
+ let tokenCache = null;
61
+ let tokenInFlight = null;
62
+ const post = (message) => {
63
+ if (destroyed)
64
+ return;
65
+ iframe.contentWindow?.postMessage(message, appOrigin);
66
+ };
67
+ const signalReady = () => {
68
+ if (readySignalled)
69
+ return;
70
+ readySignalled = true;
71
+ options.onReady?.();
72
+ };
73
+ const initMessage = () => ({
74
+ type: MessageType.Init,
75
+ contractVersion: CONTRACT_VERSION,
76
+ pluginKey: options.pluginKey,
77
+ locale: options.uiLocale,
78
+ uiLocale: options.uiLocale,
79
+ contentLocale: options.contentLocale,
80
+ surface: options.surface,
81
+ entity: options.entity,
82
+ storeContext: options.storeContext,
83
+ hostOrigin,
84
+ hostCapabilities: [...capabilities],
85
+ path: options.path,
86
+ });
87
+ // `init` is answered to EVERY `ready`: an app whose script started after the load fallback fired
88
+ // would otherwise wait forever (v1 sent `init` once).
89
+ const sendInit = () => {
90
+ initSent = true;
91
+ post(initMessage());
92
+ };
93
+ const freshToken = () => {
94
+ if (tokenCache && Date.now() - tokenCache.at < TIMING.hostTokenCacheMs)
95
+ return Promise.resolve({ ok: true, token: tokenCache.token });
96
+ if (tokenInFlight)
97
+ return tokenInFlight;
98
+ const flight = options
99
+ .getSessionToken()
100
+ .then((result) => {
101
+ if (result.ok)
102
+ tokenCache = { token: result.token, at: Date.now() };
103
+ return result;
104
+ })
105
+ .finally(() => {
106
+ if (tokenInFlight === flight)
107
+ tokenInFlight = null;
108
+ });
109
+ tokenInFlight = flight;
110
+ return flight;
111
+ };
112
+ const reply = (requestId, ok, data, error) => post(ok ? { type: MessageType.Result, requestId, ok: true, data } : { type: MessageType.Result, requestId, ok: false, error });
113
+ const runAction = (capability, requestId, payload) => {
114
+ const handler = options.handlers[capability];
115
+ if (!handler) {
116
+ reply(requestId, false, undefined, ResultError.Unsupported);
117
+ return;
118
+ }
119
+ Promise.resolve()
120
+ .then(() => handler(payload))
121
+ .then((data) => reply(requestId, true, data ?? null), (err) => {
122
+ const code = err instanceof HostActionDenied ? ResultError.Denied : ResultError.Failed;
123
+ if (code === ResultError.Failed)
124
+ console.error(`[milofly-app-bridge] ${options.pluginKey}: '${capability}' failed`, err);
125
+ reply(requestId, false, undefined, code);
126
+ });
127
+ };
128
+ const onMessage = (event) => {
129
+ if (destroyed || event.origin !== appOrigin || event.source !== iframe.contentWindow)
130
+ return;
131
+ const parsed = parseAppMessage(event.data);
132
+ if (!parsed)
133
+ return;
134
+ if (!parsed.ok) {
135
+ options.onProtocolError?.({ type: parsed.type, error: parsed.error });
136
+ if (parsed.requestId)
137
+ reply(parsed.requestId, false, undefined, parsed.error);
138
+ return;
139
+ }
140
+ const msg = parsed.message;
141
+ switch (msg.type) {
142
+ case MessageType.Ready:
143
+ sendInit();
144
+ signalReady();
145
+ return;
146
+ case MessageType.Resize: {
147
+ const policy = options.resizePolicy;
148
+ if (!policy)
149
+ return;
150
+ const next = Math.min(policy.max, Math.max(policy.min, Math.round(msg.height)));
151
+ if (Math.abs(next - height) < policy.epsilon)
152
+ return;
153
+ height = next;
154
+ options.onHeight?.(next);
155
+ return;
156
+ }
157
+ case MessageType.TokenRequest: {
158
+ const { requestId } = msg;
159
+ void freshToken().then((result) => post(result.ok
160
+ ? { type: MessageType.Token, requestId, token: result.token }
161
+ : { type: MessageType.TokenError, requestId, reason: result.reason }), (err) => {
162
+ console.error(`[milofly-app-bridge] ${options.pluginKey}: token provider failed`, err);
163
+ post({ type: MessageType.TokenError, requestId, reason: "token_unavailable" });
164
+ });
165
+ return;
166
+ }
167
+ default:
168
+ runAction(msg.capability, msg.requestId, msg.payload);
169
+ }
170
+ };
171
+ window.addEventListener("message", onMessage);
172
+ return {
173
+ capabilities,
174
+ frameLoaded() {
175
+ if (destroyed)
176
+ return;
177
+ if (fallbackTimer !== null)
178
+ clearTimeout(fallbackTimer);
179
+ fallbackTimer = setTimeout(() => {
180
+ fallbackTimer = null;
181
+ if (!initSent)
182
+ sendInit();
183
+ signalReady();
184
+ }, TIMING.initFallbackMs);
185
+ },
186
+ destroy() {
187
+ destroyed = true;
188
+ window.removeEventListener("message", onMessage);
189
+ if (fallbackTimer !== null)
190
+ clearTimeout(fallbackTimer);
191
+ fallbackTimer = null;
192
+ },
193
+ };
194
+ }
195
+ /** Throw from a handler when the host refuses the action (answered as `denied`, not `failed`). */
196
+ export class HostActionDenied extends Error {
197
+ constructor(message = "denied") {
198
+ super(message);
199
+ this.name = "HostActionDenied";
200
+ }
201
+ }