@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/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +49 -2
- package/contract.d.ts +294 -0
- package/contract.js +365 -0
- package/host.d.ts +99 -0
- package/host.js +201 -0
- package/index.d.ts +76 -0
- package/index.js +251 -0
- package/package.json +32 -4
package/index.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milofly App Bridge — client for apps embedded in the Milofly store panel.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { createApp } from "@milofly/app-bridge";
|
|
6
|
+
*
|
|
7
|
+
* const app = await createApp();
|
|
8
|
+
* const token = await app.getSessionToken(); // send to YOUR server, verify it there
|
|
9
|
+
* await app.toast("Saved");
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* The context in `app` (store, locale, surface) is informational. Identity is what your server reads
|
|
13
|
+
* from the verified session token (`@milofly/app-server` → `verifySessionToken`).
|
|
14
|
+
*/
|
|
15
|
+
import { type ConfirmTone, type EntityRef, type HostCapabilityKey, type ResourceKey, type StoreContext, type SurfaceKey, type ToastTone } from "@milofly/app-bridge/contract";
|
|
16
|
+
export * from "@milofly/app-bridge/contract";
|
|
17
|
+
/** Error raised by the bridge. `code` is stable and safe to branch on. */
|
|
18
|
+
export declare class MiloflyBridgeError extends Error {
|
|
19
|
+
readonly code: string;
|
|
20
|
+
constructor(code: string, message?: string);
|
|
21
|
+
}
|
|
22
|
+
export interface CreateAppOptions {
|
|
23
|
+
/**
|
|
24
|
+
* Host origins this app accepts (e.g. `["https://app.milofly.com"]`). Recommended in production.
|
|
25
|
+
* When omitted, the origin given by the host in `mf_host` is used as long as it is https (or http
|
|
26
|
+
* on loopback). Your server must still verify the session token's `HostOrigin` claim.
|
|
27
|
+
*/
|
|
28
|
+
allowedHostOrigins?: readonly string[];
|
|
29
|
+
/** Report content height to the host (detail widgets grow with their content). Default `true`. */
|
|
30
|
+
autoResize?: boolean;
|
|
31
|
+
}
|
|
32
|
+
export interface MiloflyApp {
|
|
33
|
+
readonly contractVersion: number;
|
|
34
|
+
readonly pluginKey: string;
|
|
35
|
+
readonly surface: SurfaceKey;
|
|
36
|
+
readonly entity: EntityRef | null;
|
|
37
|
+
readonly uiLocale: string;
|
|
38
|
+
readonly contentLocale: string;
|
|
39
|
+
readonly storeContext: StoreContext;
|
|
40
|
+
readonly hostOrigin: string;
|
|
41
|
+
/** In-app path the merchant asked for (reload/deep link of a full-page app), else `null`. */
|
|
42
|
+
readonly initialPath: string | null;
|
|
43
|
+
readonly hostCapabilities: readonly HostCapabilityKey[];
|
|
44
|
+
supports(capability: HostCapabilityKey): boolean;
|
|
45
|
+
/** A session token valid for at least the refresh margin; fetched from the host when needed. */
|
|
46
|
+
getSessionToken(): Promise<string>;
|
|
47
|
+
toast(message: string, options?: {
|
|
48
|
+
tone?: ToastTone;
|
|
49
|
+
}): Promise<void>;
|
|
50
|
+
setTitle(title: string): Promise<void>;
|
|
51
|
+
/** Tell the host the app is now at `path` (in-app, starts with `/`). The panel URL follows it. */
|
|
52
|
+
navigate(path: string): Promise<void>;
|
|
53
|
+
/** Open an order/product/customer in the panel. */
|
|
54
|
+
redirect(resource: ResourceKey, id: string | number): Promise<void>;
|
|
55
|
+
/** Open an https URL in a new tab (call from a user gesture). */
|
|
56
|
+
open(url: string): Promise<void>;
|
|
57
|
+
confirm(options: {
|
|
58
|
+
title: string;
|
|
59
|
+
message: string;
|
|
60
|
+
confirmLabel?: string;
|
|
61
|
+
tone?: ConfirmTone;
|
|
62
|
+
}): Promise<boolean>;
|
|
63
|
+
setLoading(active: boolean): Promise<void>;
|
|
64
|
+
destroy(): void;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Reads `Exp` from a session token WITHOUT verifying it — only to decide when to refresh.
|
|
68
|
+
* Never use these claims for authorization; verify the token on your server.
|
|
69
|
+
*/
|
|
70
|
+
export declare function readSessionTokenExpiry(token: string): number | null;
|
|
71
|
+
/**
|
|
72
|
+
* Connects to the host panel: reads `mf_host`, sends `ready`, waits for `init`.
|
|
73
|
+
* Rejects with {@link MiloflyBridgeError} (`not_embedded`, `host_origin_missing`, `host_origin_not_allowed`,
|
|
74
|
+
* `handshake_timeout`, `init_invalid:<reason>`).
|
|
75
|
+
*/
|
|
76
|
+
export declare function createApp(options?: CreateAppOptions): Promise<MiloflyApp>;
|
package/index.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milofly App Bridge — client for apps embedded in the Milofly store panel.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { createApp } from "@milofly/app-bridge";
|
|
6
|
+
*
|
|
7
|
+
* const app = await createApp();
|
|
8
|
+
* const token = await app.getSessionToken(); // send to YOUR server, verify it there
|
|
9
|
+
* await app.toast("Saved");
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* The context in `app` (store, locale, surface) is informational. Identity is what your server reads
|
|
13
|
+
* from the verified session token (`@milofly/app-server` → `verifySessionToken`).
|
|
14
|
+
*/
|
|
15
|
+
import { CAPABILITY_MESSAGE, MessageType, TIMING, UrlParam, isSecureOrigin, parseHostReply, parseInitMessage, } from "@milofly/app-bridge/contract";
|
|
16
|
+
export * from "@milofly/app-bridge/contract";
|
|
17
|
+
/** Error raised by the bridge. `code` is stable and safe to branch on. */
|
|
18
|
+
export class MiloflyBridgeError extends Error {
|
|
19
|
+
constructor(code, message) {
|
|
20
|
+
super(message ?? code);
|
|
21
|
+
this.name = "MiloflyBridgeError";
|
|
22
|
+
this.code = code;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function newRequestId() {
|
|
26
|
+
const c = globalThis.crypto;
|
|
27
|
+
if (c && typeof c.randomUUID === "function")
|
|
28
|
+
return c.randomUUID();
|
|
29
|
+
if (c && typeof c.getRandomValues === "function") {
|
|
30
|
+
const bytes = c.getRandomValues(new Uint8Array(16));
|
|
31
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
32
|
+
}
|
|
33
|
+
throw new MiloflyBridgeError("crypto_unavailable", "Web Crypto is required to create request ids.");
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Reads `Exp` from a session token WITHOUT verifying it — only to decide when to refresh.
|
|
37
|
+
* Never use these claims for authorization; verify the token on your server.
|
|
38
|
+
*/
|
|
39
|
+
export function readSessionTokenExpiry(token) {
|
|
40
|
+
const dot = token.indexOf(".");
|
|
41
|
+
if (dot <= 0)
|
|
42
|
+
return null;
|
|
43
|
+
try {
|
|
44
|
+
const b64 = token.slice(0, dot).replace(/-/g, "+").replace(/_/g, "/");
|
|
45
|
+
const json = JSON.parse(atob(b64.padEnd(b64.length + ((4 - (b64.length % 4)) % 4), "=")));
|
|
46
|
+
return typeof json.Exp === "number" ? json.Exp : null;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function tokenState(token) {
|
|
53
|
+
const exp = readSessionTokenExpiry(token);
|
|
54
|
+
if (exp === null)
|
|
55
|
+
throw new MiloflyBridgeError("token_malformed", "The host returned a session token without an expiry.");
|
|
56
|
+
return { token, exp };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Connects to the host panel: reads `mf_host`, sends `ready`, waits for `init`.
|
|
60
|
+
* Rejects with {@link MiloflyBridgeError} (`not_embedded`, `host_origin_missing`, `host_origin_not_allowed`,
|
|
61
|
+
* `handshake_timeout`, `init_invalid:<reason>`).
|
|
62
|
+
*/
|
|
63
|
+
export function createApp(options = {}) {
|
|
64
|
+
if (typeof window === "undefined")
|
|
65
|
+
return Promise.reject(new MiloflyBridgeError("no_window"));
|
|
66
|
+
if (window.parent === window)
|
|
67
|
+
return Promise.reject(new MiloflyBridgeError("not_embedded", "The app is not inside the Milofly panel."));
|
|
68
|
+
const location = new URL(window.location.href);
|
|
69
|
+
const hostOriginParam = location.searchParams.get(UrlParam.HostOrigin);
|
|
70
|
+
if (!hostOriginParam)
|
|
71
|
+
return Promise.reject(new MiloflyBridgeError("host_origin_missing", `The frame URL has no '${UrlParam.HostOrigin}' parameter.`));
|
|
72
|
+
const hostOrigin = hostOriginParam;
|
|
73
|
+
if (!isSecureOrigin(hostOrigin))
|
|
74
|
+
return Promise.reject(new MiloflyBridgeError("host_origin_invalid"));
|
|
75
|
+
if (options.allowedHostOrigins && !options.allowedHostOrigins.includes(hostOrigin))
|
|
76
|
+
return Promise.reject(new MiloflyBridgeError("host_origin_not_allowed", `Host origin ${hostOrigin} is not in allowedHostOrigins.`));
|
|
77
|
+
// The URL token is a secret: take it and remove it from the address bar and history.
|
|
78
|
+
const urlToken = location.searchParams.get(UrlParam.EmbedToken);
|
|
79
|
+
if (urlToken !== null) {
|
|
80
|
+
location.searchParams.delete(UrlParam.EmbedToken);
|
|
81
|
+
window.history.replaceState(window.history.state, "", location.toString());
|
|
82
|
+
}
|
|
83
|
+
const parent = window.parent;
|
|
84
|
+
const post = (message) => parent.postMessage(message, hostOrigin);
|
|
85
|
+
const pending = new Map();
|
|
86
|
+
let init = null;
|
|
87
|
+
let onInit = null;
|
|
88
|
+
let onInitError = null;
|
|
89
|
+
let destroyed = false;
|
|
90
|
+
const onMessage = (event) => {
|
|
91
|
+
if (destroyed || event.origin !== hostOrigin || event.source !== parent)
|
|
92
|
+
return;
|
|
93
|
+
const data = event.data;
|
|
94
|
+
if (data && data.type === MessageType.Init) {
|
|
95
|
+
const parsed = parseInitMessage(data);
|
|
96
|
+
if (!parsed.ok) {
|
|
97
|
+
onInitError?.(new MiloflyBridgeError(`init_invalid:${parsed.reason}`));
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (parsed.message.hostOrigin !== hostOrigin) {
|
|
101
|
+
onInitError?.(new MiloflyBridgeError("init_invalid:host_origin_mismatch"));
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
init = parsed.message;
|
|
105
|
+
onInit?.(parsed.message);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const reply = parseHostReply(data);
|
|
109
|
+
if (!reply)
|
|
110
|
+
return;
|
|
111
|
+
const waiter = pending.get(reply.requestId);
|
|
112
|
+
if (!waiter)
|
|
113
|
+
return;
|
|
114
|
+
pending.delete(reply.requestId);
|
|
115
|
+
if (waiter.timer !== null)
|
|
116
|
+
clearTimeout(waiter.timer);
|
|
117
|
+
waiter.resolve(reply);
|
|
118
|
+
};
|
|
119
|
+
window.addEventListener("message", onMessage);
|
|
120
|
+
const awaitReply = (requestId, timeoutMs) => new Promise((resolve, reject) => {
|
|
121
|
+
const timer = timeoutMs === null
|
|
122
|
+
? null
|
|
123
|
+
: setTimeout(() => {
|
|
124
|
+
pending.delete(requestId);
|
|
125
|
+
reject(new MiloflyBridgeError("host_timeout", "The host did not answer in time."));
|
|
126
|
+
}, timeoutMs);
|
|
127
|
+
pending.set(requestId, { resolve, reject, timer });
|
|
128
|
+
});
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
const timer = setTimeout(() => {
|
|
131
|
+
cleanup();
|
|
132
|
+
reject(new MiloflyBridgeError("handshake_timeout", "The Milofly panel did not answer 'ready'."));
|
|
133
|
+
}, TIMING.handshakeTimeoutMs);
|
|
134
|
+
const cleanup = () => {
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
onInit = null;
|
|
137
|
+
onInitError = null;
|
|
138
|
+
};
|
|
139
|
+
onInitError = (err) => {
|
|
140
|
+
cleanup();
|
|
141
|
+
destroyed = true;
|
|
142
|
+
window.removeEventListener("message", onMessage);
|
|
143
|
+
reject(err);
|
|
144
|
+
};
|
|
145
|
+
onInit = (first) => {
|
|
146
|
+
cleanup();
|
|
147
|
+
try {
|
|
148
|
+
resolve(buildApp(first));
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
destroyed = true;
|
|
152
|
+
window.removeEventListener("message", onMessage);
|
|
153
|
+
reject(err instanceof MiloflyBridgeError ? err : new MiloflyBridgeError("init_failed", String(err)));
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
post({ type: MessageType.Ready });
|
|
157
|
+
});
|
|
158
|
+
function buildApp(first) {
|
|
159
|
+
let token = urlToken ? tokenState(urlToken) : null;
|
|
160
|
+
let tokenFlight = null;
|
|
161
|
+
let resizeObserver = null;
|
|
162
|
+
const current = () => init ?? first;
|
|
163
|
+
const requestToken = async () => {
|
|
164
|
+
const requestId = newRequestId();
|
|
165
|
+
const wait = awaitReply(requestId, TIMING.tokenRequestTimeoutMs);
|
|
166
|
+
post({ type: MessageType.TokenRequest, requestId });
|
|
167
|
+
const reply = await wait;
|
|
168
|
+
if (reply.type === MessageType.Token) {
|
|
169
|
+
token = tokenState(reply.token);
|
|
170
|
+
return reply.token;
|
|
171
|
+
}
|
|
172
|
+
if (reply.type === MessageType.TokenError)
|
|
173
|
+
throw new MiloflyBridgeError(reply.reason, `The host could not issue a session token (${reply.reason}).`);
|
|
174
|
+
throw new MiloflyBridgeError("host_reply_invalid");
|
|
175
|
+
};
|
|
176
|
+
const call = async (capability, payload, timeoutMs) => {
|
|
177
|
+
if (destroyed)
|
|
178
|
+
throw new MiloflyBridgeError("destroyed");
|
|
179
|
+
if (!current().hostCapabilities.includes(capability))
|
|
180
|
+
throw new MiloflyBridgeError("unsupported", `The host does not support '${capability}'.`);
|
|
181
|
+
const requestId = newRequestId();
|
|
182
|
+
const wait = awaitReply(requestId, timeoutMs);
|
|
183
|
+
post({ type: CAPABILITY_MESSAGE[capability], requestId, ...payload });
|
|
184
|
+
const reply = await wait;
|
|
185
|
+
if (reply.type !== MessageType.Result)
|
|
186
|
+
throw new MiloflyBridgeError("host_reply_invalid");
|
|
187
|
+
if (!reply.ok)
|
|
188
|
+
throw new MiloflyBridgeError(reply.error ?? "failed");
|
|
189
|
+
return (reply.data ?? null);
|
|
190
|
+
};
|
|
191
|
+
if (options.autoResize !== false && typeof ResizeObserver !== "undefined") {
|
|
192
|
+
let frame = 0;
|
|
193
|
+
let last = 0;
|
|
194
|
+
resizeObserver = new ResizeObserver(() => {
|
|
195
|
+
if (frame)
|
|
196
|
+
return;
|
|
197
|
+
frame = requestAnimationFrame(() => {
|
|
198
|
+
frame = 0;
|
|
199
|
+
const h = Math.ceil(document.documentElement.scrollHeight);
|
|
200
|
+
if (h > 0 && h !== last) {
|
|
201
|
+
last = h;
|
|
202
|
+
post({ type: MessageType.Resize, height: h });
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
resizeObserver.observe(document.documentElement);
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
get contractVersion() { return current().contractVersion; },
|
|
210
|
+
get pluginKey() { return current().pluginKey; },
|
|
211
|
+
get surface() { return current().surface; },
|
|
212
|
+
get entity() { return current().entity; },
|
|
213
|
+
get uiLocale() { return current().uiLocale; },
|
|
214
|
+
get contentLocale() { return current().contentLocale; },
|
|
215
|
+
get storeContext() { return current().storeContext; },
|
|
216
|
+
get hostOrigin() { return hostOrigin; },
|
|
217
|
+
get initialPath() { return first.path; },
|
|
218
|
+
get hostCapabilities() { return current().hostCapabilities; },
|
|
219
|
+
supports: (capability) => current().hostCapabilities.includes(capability),
|
|
220
|
+
getSessionToken() {
|
|
221
|
+
if (destroyed)
|
|
222
|
+
return Promise.reject(new MiloflyBridgeError("destroyed"));
|
|
223
|
+
const now = Math.floor(Date.now() / 1000);
|
|
224
|
+
if (token && token.exp - now > TIMING.tokenRefreshMarginSeconds)
|
|
225
|
+
return Promise.resolve(token.token);
|
|
226
|
+
if (!tokenFlight)
|
|
227
|
+
tokenFlight = requestToken().finally(() => (tokenFlight = null));
|
|
228
|
+
return tokenFlight;
|
|
229
|
+
},
|
|
230
|
+
toast: (message, opts) => call("toast", { message, tone: opts?.tone ?? "info" }, TIMING.requestTimeoutMs).then(() => undefined),
|
|
231
|
+
setTitle: (title) => call("title", { title }, TIMING.requestTimeoutMs).then(() => undefined),
|
|
232
|
+
navigate: (path) => call("navigate", { path }, TIMING.requestTimeoutMs).then(() => undefined),
|
|
233
|
+
redirect: (resource, id) => call("redirect", { resource, id: String(id) }, TIMING.requestTimeoutMs).then(() => undefined),
|
|
234
|
+
open: (url) => call("open", { url }, TIMING.requestTimeoutMs).then(() => undefined),
|
|
235
|
+
// The merchant decides at their own pace: no timeout.
|
|
236
|
+
confirm: (o) => call("confirm", { title: o.title, message: o.message, confirmLabel: o.confirmLabel ?? null, tone: o.tone ?? "default" }, null).then((r) => r.confirmed),
|
|
237
|
+
setLoading: (active) => call("loading", { active }, TIMING.requestTimeoutMs).then(() => undefined),
|
|
238
|
+
destroy() {
|
|
239
|
+
destroyed = true;
|
|
240
|
+
window.removeEventListener("message", onMessage);
|
|
241
|
+
resizeObserver?.disconnect();
|
|
242
|
+
for (const [id, w] of pending) {
|
|
243
|
+
if (w.timer !== null)
|
|
244
|
+
clearTimeout(w.timer);
|
|
245
|
+
pending.delete(id);
|
|
246
|
+
w.reject(new MiloflyBridgeError("destroyed"));
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@milofly/app-bridge",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Milofly App Bridge: embed an app in the Milofly store panel (client and host).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://developer.milofly.com",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Milofly/milofly-sdk.git",
|
|
10
|
+
"directory": "js/app-bridge"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/Milofly/milofly-sdk/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./index.d.ts",
|
|
20
|
+
"import": "./index.js"
|
|
21
|
+
},
|
|
22
|
+
"./host": {
|
|
23
|
+
"types": "./host.d.ts",
|
|
24
|
+
"import": "./host.js"
|
|
25
|
+
},
|
|
26
|
+
"./contract": {
|
|
27
|
+
"types": "./contract.d.ts",
|
|
28
|
+
"import": "./contract.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
}
|
|
34
|
+
}
|