@tryghost/app-sdk 0.0.0-stage → 0.1.0-alpha.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/LICENSE +22 -0
- package/README.md +310 -2
- package/build/index.d.ts +180 -0
- package/build/index.js +763 -0
- package/build/index.js.map +1 -0
- package/dist/app-sdk.js +1339 -0
- package/dist/app-sdk.js.map +1 -0
- package/package.json +34 -3
package/build/index.js
ADDED
|
@@ -0,0 +1,763 @@
|
|
|
1
|
+
import { ThreadMessagePort } from "@quilted/threads";
|
|
2
|
+
//#region ../app-contracts/build/plain-text.js
|
|
3
|
+
var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
|
|
4
|
+
new RegExp(`^[${ALLOWED}]*$`, "u");
|
|
5
|
+
var NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, "gu");
|
|
6
|
+
/** Returns the text with the characters `isPlainText` refuses removed. */
|
|
7
|
+
function toPlainText(value) {
|
|
8
|
+
return value.replace(NOT_PLAIN_TEXT, "");
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region ../app-contracts/build/bridge/rules.js
|
|
12
|
+
/**
|
|
13
|
+
* The bridge's rules that have no dependencies. The root entry point exports them so the SDK
|
|
14
|
+
* can use them without zod. The schemas in this folder build on them, so the SDK and Admin
|
|
15
|
+
* read a path or a refusal the same way.
|
|
16
|
+
*
|
|
17
|
+
* What Admin sends the page has no schema, because Admin builds it and never parses it. Its
|
|
18
|
+
* types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so
|
|
19
|
+
* the guards only check shape and path containment. They turn a mismatch into a clear error
|
|
20
|
+
* rather than `undefined` somewhere in the app. Only the schemas check limits.
|
|
21
|
+
*/
|
|
22
|
+
/** Posted by the app's page to `window.parent` once the SDK has loaded. */
|
|
23
|
+
var HELLO_MESSAGE_TYPE = "ghost-app:hello";
|
|
24
|
+
/**
|
|
25
|
+
* How long an app's page has to start, in milliseconds. Admin gives up on a frame this long
|
|
26
|
+
* after mounting it, and the SDK waits this long for Admin to start the app unless the app
|
|
27
|
+
* passes its own `timeout`. Long enough for a slow page on a slow connection to load and send
|
|
28
|
+
* its hello.
|
|
29
|
+
*/
|
|
30
|
+
var START_TIMEOUT_MS = 1e4;
|
|
31
|
+
/**
|
|
32
|
+
* The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK
|
|
33
|
+
* uppercases what apps pass.
|
|
34
|
+
*/
|
|
35
|
+
var FETCH_METHODS = [
|
|
36
|
+
"GET",
|
|
37
|
+
"POST",
|
|
38
|
+
"PUT",
|
|
39
|
+
"DELETE"
|
|
40
|
+
];
|
|
41
|
+
/**
|
|
42
|
+
* Whether a request with this method may carry a body. Expects an uppercase method from
|
|
43
|
+
* `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.
|
|
44
|
+
*/
|
|
45
|
+
function methodAllowsBody(method) {
|
|
46
|
+
return method !== "GET";
|
|
47
|
+
}
|
|
48
|
+
var RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;
|
|
49
|
+
/**
|
|
50
|
+
* Whether a request header is one that apps may not set, in any case. Admin refuses a request
|
|
51
|
+
* that sets one rather than dropping the header, so the app gets an error instead of wondering
|
|
52
|
+
* why the header never arrived. The browser refuses some of these anyway; they are listed here
|
|
53
|
+
* so that none of them relies on the browser.
|
|
54
|
+
*/
|
|
55
|
+
function isReservedRequestHeader(name) {
|
|
56
|
+
return RESERVED_REQUEST_HEADER.test(name);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The messages Admin and the SDK use when they refuse an argument for the same reason, so an
|
|
60
|
+
* app gets the same message whichever side catches the problem. The SDK checks only for obvious
|
|
61
|
+
* mistakes, before anything crosses the channel; Admin's schemas check everything again.
|
|
62
|
+
*/
|
|
63
|
+
var ARGUMENT_MESSAGES = {
|
|
64
|
+
fetchPath: "Expected an Admin API path such as /posts/, not a URL",
|
|
65
|
+
fetchMethod: `Expected a method of: ${FETCH_METHODS.join(", ")}`,
|
|
66
|
+
fetchBody: "Expected no body on a GET request",
|
|
67
|
+
reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,
|
|
68
|
+
jsonBody: "Expected the body as JSON text",
|
|
69
|
+
appPath: "Expected a path within the app, starting with a single /",
|
|
70
|
+
pathMove: "Expected a move of push or replace",
|
|
71
|
+
place: "Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }"
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* The codes a refused call carries across the channel. The structured clone that carries an
|
|
75
|
+
* error keeps only its message, so the refusing side puts the code at the start of the
|
|
76
|
+
* message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes
|
|
77
|
+
* are only ever added: an SDK that doesn't know a code treats the whole message as a generic
|
|
78
|
+
* refusal.
|
|
79
|
+
*
|
|
80
|
+
* The host codes, which Admin refuses the page's calls with:
|
|
81
|
+
*
|
|
82
|
+
* - `session_ended`: the session is over; the page is about to be replaced.
|
|
83
|
+
* - `invalid_argument`: an argument Admin does not take.
|
|
84
|
+
* - `invalid_path`: a path that is not an Admin API path or a route within the app, or one
|
|
85
|
+
* the Admin API only responds to with a redirect, such as a path without its trailing `/`.
|
|
86
|
+
* - `blocked`: a request the allowlist doesn't allow, or a write it refuses.
|
|
87
|
+
* - `network_error`: Admin could not reach its own API.
|
|
88
|
+
* - `rejected`: anything else; the detail says why.
|
|
89
|
+
*/
|
|
90
|
+
var HOST_ERROR_CODES = [
|
|
91
|
+
"session_ended",
|
|
92
|
+
"invalid_argument",
|
|
93
|
+
"invalid_path",
|
|
94
|
+
"blocked",
|
|
95
|
+
"network_error",
|
|
96
|
+
"rejected"
|
|
97
|
+
];
|
|
98
|
+
[...HOST_ERROR_CODES];
|
|
99
|
+
var CODED_MESSAGE = /^([a-z_]+): ([\s\S]*)$/;
|
|
100
|
+
/**
|
|
101
|
+
* Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass
|
|
102
|
+
* only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.
|
|
103
|
+
*/
|
|
104
|
+
function encodeBridgeError(code, detail) {
|
|
105
|
+
return `${code}: ${detail}`;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the
|
|
109
|
+
* other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for
|
|
110
|
+
* one from the page. Returns `undefined` for a message that doesn't start with one of them.
|
|
111
|
+
*/
|
|
112
|
+
function decodeBridgeError(message, codes) {
|
|
113
|
+
const [, code = "", detail = ""] = CODED_MESSAGE.exec(message) ?? [];
|
|
114
|
+
return codes.includes(code) ? {
|
|
115
|
+
code,
|
|
116
|
+
detail
|
|
117
|
+
} : void 0;
|
|
118
|
+
}
|
|
119
|
+
var THEME_MODES = ["light", "dark"];
|
|
120
|
+
var CONTROL_CHARACTER = /\p{Cc}/u;
|
|
121
|
+
/**
|
|
122
|
+
* Whether a value is a path that stays within the base it is resolved against, rather than
|
|
123
|
+
* escaping it. It must start with a single `/`, so it can't carry a scheme or be read as
|
|
124
|
+
* `//host`. It must not contain `\`, which URL parsers read as `/`, or any control character.
|
|
125
|
+
*/
|
|
126
|
+
function isContainedPath(value) {
|
|
127
|
+
return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\") && !CONTROL_CHARACTER.test(value);
|
|
128
|
+
}
|
|
129
|
+
var APP_PATH_BASE = "https://app.invalid";
|
|
130
|
+
/**
|
|
131
|
+
* Returns an app path in the URL parser's normalised form, the one form Admin and the SDK
|
|
132
|
+
* store it in. `.` and `..` are resolved within the app, so a path can never climb out of it.
|
|
133
|
+
* Characters that need escaping are escaped once, so a path the app reported compares equal to
|
|
134
|
+
* the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and
|
|
135
|
+
* `/x/../episodes/1` becomes `/episodes/1`.
|
|
136
|
+
*
|
|
137
|
+
* Expects a path that `isContainedPath` accepts; anything else may not be a path within the
|
|
138
|
+
* app at all. `AppPathSchema` already returns this form, so Admin never calls this directly.
|
|
139
|
+
* The SDK, which doesn't load zod, does.
|
|
140
|
+
*/
|
|
141
|
+
function normaliseAppPath(path) {
|
|
142
|
+
const url = new URL(path, APP_PATH_BASE);
|
|
143
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
144
|
+
}
|
|
145
|
+
/** An object, or an array: anything whose fields can be read. */
|
|
146
|
+
function isRecord(value) {
|
|
147
|
+
return typeof value === "object" && value !== null;
|
|
148
|
+
}
|
|
149
|
+
function hasStrings(value, keys) {
|
|
150
|
+
return isRecord(value) && keys.every((key) => typeof value[key] === "string");
|
|
151
|
+
}
|
|
152
|
+
function isTheme(value) {
|
|
153
|
+
return hasStrings(value, ["accent_color"]) && THEME_MODES.includes(value.mode);
|
|
154
|
+
}
|
|
155
|
+
function isStartContext(value) {
|
|
156
|
+
return isRecord(value) && hasStrings(value.site, [
|
|
157
|
+
"url",
|
|
158
|
+
"title",
|
|
159
|
+
"timezone",
|
|
160
|
+
"locale"
|
|
161
|
+
]) && hasStrings(value.user, ["id", "role"]) && isTheme(value.theme) && isRecord(value.session) && Number.isSafeInteger(value.session.revision) && value.session.revision >= 0 && isContainedPath(value.path);
|
|
162
|
+
}
|
|
163
|
+
function isConnectMessage(value) {
|
|
164
|
+
return isRecord(value) && value.type === "ghost-app:connect" && Array.isArray(value.exports) && value.exports.every((name) => typeof name === "string");
|
|
165
|
+
}
|
|
166
|
+
function isFetchResponse(value) {
|
|
167
|
+
return isRecord(value) && Number.isSafeInteger(value.status) && value.status >= 200 && value.status <= 599 && typeof value.statusText === "string" && isRecord(value.headers) && !Array.isArray(value.headers) && Object.values(value.headers).every((header) => typeof header === "string") && typeof value.body === "string";
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/errors.ts
|
|
171
|
+
/** The only error type the SDK rejects with, so an app can branch on `code`. */
|
|
172
|
+
var GhostAppError = class extends Error {
|
|
173
|
+
code;
|
|
174
|
+
constructor(code, message, options) {
|
|
175
|
+
super(message, options);
|
|
176
|
+
this.name = "GhostAppError";
|
|
177
|
+
this.code = code;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
/**
|
|
181
|
+
* Converts whatever a call to Admin rejected with into a `GhostAppError`, with the code Admin
|
|
182
|
+
* gave or, if there is none, `rejected` with Admin's message.
|
|
183
|
+
*/
|
|
184
|
+
function fromHostError(error, operation) {
|
|
185
|
+
const message = typeof error === "object" && error !== null && "message" in error ? String(error.message) : void 0;
|
|
186
|
+
if (message === void 0) return new GhostAppError("rejected", `Ghost refused ${operation}`, { cause: error });
|
|
187
|
+
const coded = decodeBridgeError(message, HOST_ERROR_CODES);
|
|
188
|
+
if (coded) return new GhostAppError(coded.code, coded.detail, { cause: error });
|
|
189
|
+
return new GhostAppError("rejected", message, { cause: error });
|
|
190
|
+
}
|
|
191
|
+
function invalidArgument(message) {
|
|
192
|
+
return new GhostAppError("invalid_argument", message);
|
|
193
|
+
}
|
|
194
|
+
function invalidPath(message) {
|
|
195
|
+
return new GhostAppError("invalid_path", message);
|
|
196
|
+
}
|
|
197
|
+
function unsupported(operation) {
|
|
198
|
+
return new GhostAppError("unsupported", `This site's Ghost doesn't support ${operation} yet`);
|
|
199
|
+
}
|
|
200
|
+
function sessionEnded() {
|
|
201
|
+
return new GhostAppError("session_ended", "The session with Ghost has ended");
|
|
202
|
+
}
|
|
203
|
+
//#endregion
|
|
204
|
+
//#region src/fetch.ts
|
|
205
|
+
var JSON_BODY = "Expected a body that can be sent as JSON";
|
|
206
|
+
var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
|
|
207
|
+
204,
|
|
208
|
+
205,
|
|
209
|
+
304
|
|
210
|
+
]);
|
|
211
|
+
function isJsonBody(value) {
|
|
212
|
+
if (Array.isArray(value)) return true;
|
|
213
|
+
if (!isRecord(value)) return false;
|
|
214
|
+
const prototype = Object.getPrototypeOf(value);
|
|
215
|
+
return prototype === Object.prototype || prototype === null;
|
|
216
|
+
}
|
|
217
|
+
function toJson(body) {
|
|
218
|
+
let json;
|
|
219
|
+
try {
|
|
220
|
+
json = JSON.stringify(body);
|
|
221
|
+
} catch (error) {
|
|
222
|
+
throw new GhostAppError("invalid_argument", JSON_BODY, { cause: error });
|
|
223
|
+
}
|
|
224
|
+
if (json === void 0) throw invalidArgument(JSON_BODY);
|
|
225
|
+
return json;
|
|
226
|
+
}
|
|
227
|
+
function toHeaders(init) {
|
|
228
|
+
let headers;
|
|
229
|
+
try {
|
|
230
|
+
headers = new Headers(init);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
throw new GhostAppError("invalid_argument", "Expected headers with valid names and values", { cause: error });
|
|
233
|
+
}
|
|
234
|
+
const entries = [...headers.entries()];
|
|
235
|
+
const reserved = entries.find(([name]) => isReservedRequestHeader(name));
|
|
236
|
+
if (reserved) throw invalidArgument(ARGUMENT_MESSAGES.reservedHeader(reserved[0]));
|
|
237
|
+
return Object.fromEntries(entries);
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Converts `fetch(path, init)` into the plain request Admin accepts. Only obvious mistakes are
|
|
241
|
+
* refused here, using the same rules Admin applies; Admin checks everything again.
|
|
242
|
+
*/
|
|
243
|
+
function toFetchRequest(path, init = {}) {
|
|
244
|
+
if (!isContainedPath(path)) throw invalidPath(ARGUMENT_MESSAGES.fetchPath);
|
|
245
|
+
if (typeof init !== "object" || init === null) throw invalidArgument("Expected options such as { method, headers, body }");
|
|
246
|
+
const { method: given = "GET" } = init;
|
|
247
|
+
const method = typeof given === "string" ? given.toUpperCase() : given;
|
|
248
|
+
if (!FETCH_METHODS.includes(method)) throw invalidArgument(ARGUMENT_MESSAGES.fetchMethod);
|
|
249
|
+
const headers = toHeaders(init.headers);
|
|
250
|
+
const request = {
|
|
251
|
+
path,
|
|
252
|
+
method
|
|
253
|
+
};
|
|
254
|
+
if (init.body !== void 0 && init.body !== null) {
|
|
255
|
+
if (!methodAllowsBody(method)) throw invalidArgument(ARGUMENT_MESSAGES.fetchBody);
|
|
256
|
+
if (typeof init.body === "string") request.body = init.body;
|
|
257
|
+
else if (isJsonBody(init.body)) request.body = toJson(init.body);
|
|
258
|
+
else throw invalidArgument("Expected the body as text, or as an object or array to send as JSON");
|
|
259
|
+
}
|
|
260
|
+
if (Object.keys(headers).length > 0) request.headers = headers;
|
|
261
|
+
return request;
|
|
262
|
+
}
|
|
263
|
+
var UNREADABLE_ANSWER = "Ghost answered with a response this SDK doesn't understand";
|
|
264
|
+
/** Rebuilds Admin's response as the `Response` the app would have got from `fetch`. */
|
|
265
|
+
function toResponse(answer) {
|
|
266
|
+
if (!isFetchResponse(answer)) throw new GhostAppError("rejected", UNREADABLE_ANSWER);
|
|
267
|
+
try {
|
|
268
|
+
return new Response(NULL_BODY_STATUSES.has(answer.status) ? null : answer.body, {
|
|
269
|
+
status: answer.status,
|
|
270
|
+
statusText: answer.statusText,
|
|
271
|
+
headers: answer.headers
|
|
272
|
+
});
|
|
273
|
+
} catch (error) {
|
|
274
|
+
throw new GhostAppError("rejected", UNREADABLE_ANSWER, { cause: error });
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/history.ts
|
|
279
|
+
/**
|
|
280
|
+
* The page's route: the path, query and fragment of its URL, in the normalised form Admin
|
|
281
|
+
* stores app paths in.
|
|
282
|
+
*/
|
|
283
|
+
function currentRoute() {
|
|
284
|
+
const { pathname, search, hash } = window.location;
|
|
285
|
+
return normaliseAppPath(`${pathname}${search}${hash}`);
|
|
286
|
+
}
|
|
287
|
+
/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */
|
|
288
|
+
function isLink(node) {
|
|
289
|
+
return (node instanceof HTMLAnchorElement || node instanceof SVGElement && node.localName === "a") && node.hasAttribute("href");
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,
|
|
293
|
+
* and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's
|
|
294
|
+
* entries, which left back steps that did nothing once the app's page opened again, and WebKit
|
|
295
|
+
* applies Admin's replace after a frame's push to the entry before it. So the frame keeps a
|
|
296
|
+
* single entry, and Admin keeps one for each of the app's moves.
|
|
297
|
+
*
|
|
298
|
+
* - `history.pushState` and `history.replaceState` replace the frame's entry, then report the
|
|
299
|
+
* move to Admin as a push or a replace, which is how Admin records it. A move to the route the
|
|
300
|
+
* page is already on isn't reported, so Admin never gets an entry that changes nothing.
|
|
301
|
+
* - A click on a link to the app's own origin, which a router hasn't already handled, is reported
|
|
302
|
+
* as a push, and the page then loads the link's address in place of its own entry. A link that
|
|
303
|
+
* opens elsewhere (a `target`, `download`, or a modifier key) is left alone.
|
|
304
|
+
* - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.
|
|
305
|
+
*
|
|
306
|
+
* Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the
|
|
307
|
+
* fragment through `location.hash` and the Navigation API, which have added the entry before
|
|
308
|
+
* any event says so.
|
|
309
|
+
*/
|
|
310
|
+
function watchHistory(moved, load = (url) => window.location.replace(url)) {
|
|
311
|
+
const { history } = window;
|
|
312
|
+
const { pushState, replaceState } = history;
|
|
313
|
+
let route = currentRoute();
|
|
314
|
+
const states = /* @__PURE__ */ new Map([[route, history.state]]);
|
|
315
|
+
const report = (move) => {
|
|
316
|
+
const next = currentRoute();
|
|
317
|
+
states.set(next, history.state);
|
|
318
|
+
if (next !== route) {
|
|
319
|
+
route = next;
|
|
320
|
+
moved(next, move);
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
const push = (data, unused, url) => {
|
|
324
|
+
replaceState.call(history, data, unused, url);
|
|
325
|
+
report("push");
|
|
326
|
+
};
|
|
327
|
+
const replace = (data, unused, url) => {
|
|
328
|
+
replaceState.call(history, data, unused, url);
|
|
329
|
+
report("replace");
|
|
330
|
+
};
|
|
331
|
+
history.pushState = push;
|
|
332
|
+
history.replaceState = replace;
|
|
333
|
+
const onClick = (event) => {
|
|
334
|
+
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
335
|
+
const link = event.composedPath().find(isLink);
|
|
336
|
+
const target = link?.getAttribute("target") ?? "";
|
|
337
|
+
if (!link || link.hasAttribute("download") || target !== "" && target !== "_self") return;
|
|
338
|
+
const url = new URL(link.getAttribute("href"), document.baseURI);
|
|
339
|
+
if (url.origin !== window.location.origin) return;
|
|
340
|
+
event.preventDefault();
|
|
341
|
+
const go = () => load(url.href);
|
|
342
|
+
const next = normaliseAppPath(`${url.pathname}${url.search}${url.hash}`);
|
|
343
|
+
if (next === route) {
|
|
344
|
+
go();
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
route = next;
|
|
348
|
+
moved(next, "push").then(go, go);
|
|
349
|
+
};
|
|
350
|
+
document.addEventListener("click", onClick);
|
|
351
|
+
return {
|
|
352
|
+
follow(path) {
|
|
353
|
+
route = path;
|
|
354
|
+
const state = states.get(path) ?? null;
|
|
355
|
+
replaceState.call(history, state, "", path);
|
|
356
|
+
window.dispatchEvent(new PopStateEvent("popstate", { state }));
|
|
357
|
+
},
|
|
358
|
+
stop() {
|
|
359
|
+
if (history.pushState === push) history.pushState = pushState;
|
|
360
|
+
if (history.replaceState === replace) history.replaceState = replaceState;
|
|
361
|
+
document.removeEventListener("click", onClick);
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
//#endregion
|
|
366
|
+
//#region src/title.ts
|
|
367
|
+
/**
|
|
368
|
+
* Trims a title to what Admin accepts, without splitting a character in two. Admin refuses a
|
|
369
|
+
* title containing a character that reorders or hides text, so the SDK drops those characters
|
|
370
|
+
* rather than losing the whole title: a right-to-left title often contains a direction mark.
|
|
371
|
+
*/
|
|
372
|
+
function clampTitle(title) {
|
|
373
|
+
const trimmed = toPlainText(title).trim();
|
|
374
|
+
if (trimmed.length <= 200) return trimmed;
|
|
375
|
+
const end = /[\uD800-\uDBFF]/.test(trimmed.charAt(199)) ? 199 : 200;
|
|
376
|
+
return trimmed.slice(0, end);
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Reports the page's title now and every time it changes, so Admin can show it as its own.
|
|
380
|
+
* Returns a function that stops watching.
|
|
381
|
+
*
|
|
382
|
+
* A title can change in three ways, and frameworks use all three: its text is edited, its
|
|
383
|
+
* element is replaced, or an element is added where there was none. Rather than distinguish
|
|
384
|
+
* them, the SDK reads `document.title` after every batch of changes in `<head>` and reports it
|
|
385
|
+
* only if it differs from the last one. A mutation observer already delivers each batch once,
|
|
386
|
+
* in a microtask.
|
|
387
|
+
*/
|
|
388
|
+
function watchTitle(report) {
|
|
389
|
+
let last;
|
|
390
|
+
const check = () => {
|
|
391
|
+
const title = clampTitle(document.title);
|
|
392
|
+
if (title !== last) {
|
|
393
|
+
last = title;
|
|
394
|
+
report(title);
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
check();
|
|
398
|
+
const observer = new MutationObserver(check);
|
|
399
|
+
observer.observe(document.head ?? document.documentElement, {
|
|
400
|
+
subtree: true,
|
|
401
|
+
childList: true,
|
|
402
|
+
characterData: true
|
|
403
|
+
});
|
|
404
|
+
return () => observer.disconnect();
|
|
405
|
+
}
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region src/session.ts
|
|
408
|
+
/** Calls each listener the app registered, so that one that throws can't stop the others. */
|
|
409
|
+
function notify(listeners, value) {
|
|
410
|
+
for (const listener of [...listeners]) try {
|
|
411
|
+
listener(value);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
queueMicrotask(() => {
|
|
414
|
+
throw error;
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* An error that refuses one of Admin's calls. Only its message reaches Admin, so the message
|
|
420
|
+
* starts with the code, as Admin's own refusals do.
|
|
421
|
+
*/
|
|
422
|
+
function refusal(code, detail) {
|
|
423
|
+
return new Error(encodeBridgeError(code, detail));
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Returns the copy of an argument that will cross the channel, or throws `invalid_argument`
|
|
427
|
+
* with `message` if it can't cross. The structured clone that carries a call only refuses a
|
|
428
|
+
* symbol or a DOM node once the call is in progress, and the channel would proxy a function,
|
|
429
|
+
* though no argument in the bridge's calls is a function. Cloning first refuses all of these
|
|
430
|
+
* before anything is sent to Admin.
|
|
431
|
+
*/
|
|
432
|
+
function cloneArgument(value, message) {
|
|
433
|
+
try {
|
|
434
|
+
return structuredClone(value);
|
|
435
|
+
} catch (error) {
|
|
436
|
+
throw new GhostAppError("invalid_argument", message, { cause: error });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
function subscribe(listeners, listener) {
|
|
440
|
+
listeners.add(listener);
|
|
441
|
+
return () => {
|
|
442
|
+
listeners.delete(listener);
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* The channel to Admin over the port Admin handed the page, and the `Ghost` object the app
|
|
447
|
+
* gets once Admin has called `start`. The channel itself stays inside the SDK.
|
|
448
|
+
*
|
|
449
|
+
* The channel ends in three cases: when the port closes, which browsers that fire `close` on
|
|
450
|
+
* a port (and Node) report when Admin closes its end or its document goes away; when a call
|
|
451
|
+
* fails because the thread has closed; or when Admin rejects a call with `session_ended`.
|
|
452
|
+
* After that, every call rejects with the same error.
|
|
453
|
+
*/
|
|
454
|
+
var Channel = class {
|
|
455
|
+
#port;
|
|
456
|
+
#thread;
|
|
457
|
+
#hostExports;
|
|
458
|
+
#events;
|
|
459
|
+
#themeListeners = /* @__PURE__ */ new Set();
|
|
460
|
+
#pathListeners = /* @__PURE__ */ new Set();
|
|
461
|
+
#endListeners = /* @__PURE__ */ new Set();
|
|
462
|
+
#context;
|
|
463
|
+
#theme;
|
|
464
|
+
#path = "/";
|
|
465
|
+
#ended;
|
|
466
|
+
#stopWatchingTitle;
|
|
467
|
+
#history;
|
|
468
|
+
#moves = 0;
|
|
469
|
+
constructor(port, hostExports, events) {
|
|
470
|
+
this.#port = port;
|
|
471
|
+
this.#hostExports = new Set(hostExports);
|
|
472
|
+
this.#events = events;
|
|
473
|
+
this.#thread = new ThreadMessagePort(port, { exports: {
|
|
474
|
+
start: async (context) => this.#start(context),
|
|
475
|
+
themeChanged: async (theme) => this.#themeChanged(theme),
|
|
476
|
+
pathChanged: async (path) => this.#pathChanged(path)
|
|
477
|
+
} });
|
|
478
|
+
port.addEventListener("close", () => this.end(sessionEnded()));
|
|
479
|
+
port.addEventListener("messageerror", () => this.end(sessionEnded()));
|
|
480
|
+
port.start();
|
|
481
|
+
}
|
|
482
|
+
#start(context) {
|
|
483
|
+
if (this.#context) return;
|
|
484
|
+
if (!isStartContext(context)) {
|
|
485
|
+
const detail = "Ghost started the app with a context this SDK doesn't understand";
|
|
486
|
+
setTimeout(() => this.end(new GhostAppError("invalid_context", detail)), 0);
|
|
487
|
+
throw refusal("invalid_context", detail);
|
|
488
|
+
}
|
|
489
|
+
this.#context = {
|
|
490
|
+
site: Object.freeze({ ...context.site }),
|
|
491
|
+
user: Object.freeze({ ...context.user }),
|
|
492
|
+
session: Object.freeze({ ...context.session })
|
|
493
|
+
};
|
|
494
|
+
this.#theme = Object.freeze({ ...context.theme });
|
|
495
|
+
this.#history = watchHistory((route, move) => this.#moved(route, move));
|
|
496
|
+
this.#path = currentRoute();
|
|
497
|
+
if (this.#path !== context.path) this.#moved(this.#path, "replace");
|
|
498
|
+
if (this.#hostExports.has("titleChanged")) this.#stopWatchingTitle = watchTitle((title) => {
|
|
499
|
+
this.#call("titleChanged", title).catch(() => {});
|
|
500
|
+
});
|
|
501
|
+
this.#events.started(this.ghost);
|
|
502
|
+
}
|
|
503
|
+
#themeChanged(theme) {
|
|
504
|
+
this.#assertStarted();
|
|
505
|
+
if (!isTheme(theme)) throw refusal("invalid_argument", "Ghost sent a theme this SDK doesn't understand");
|
|
506
|
+
this.#theme = Object.freeze({ ...theme });
|
|
507
|
+
notify(this.#themeListeners, this.#theme);
|
|
508
|
+
}
|
|
509
|
+
#pathChanged(path) {
|
|
510
|
+
this.#assertStarted();
|
|
511
|
+
if (!isContainedPath(path)) throw refusal("invalid_argument", "Ghost sent a path this SDK doesn't understand");
|
|
512
|
+
this.#path = path;
|
|
513
|
+
this.#history?.follow(path);
|
|
514
|
+
notify(this.#pathListeners, path);
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Reports a move the page made. Resolves once Admin has answered, with the path Admin now has
|
|
518
|
+
* for the app, or has refused; a refused move leaves the page where it is.
|
|
519
|
+
*/
|
|
520
|
+
async #moved(route, move) {
|
|
521
|
+
this.#path = route;
|
|
522
|
+
this.#moves += 1;
|
|
523
|
+
const thisMove = this.#moves;
|
|
524
|
+
try {
|
|
525
|
+
const adminPath = await this.#call("pathChanged", route, move);
|
|
526
|
+
if (thisMove === this.#moves && isContainedPath(adminPath)) this.#path = adminPath;
|
|
527
|
+
} catch {}
|
|
528
|
+
}
|
|
529
|
+
#assertStarted() {
|
|
530
|
+
if (!this.#context) throw refusal("invalid_context", "Ghost has not started the app yet");
|
|
531
|
+
}
|
|
532
|
+
async #call(name, ...args) {
|
|
533
|
+
if (this.#ended) throw this.#ended;
|
|
534
|
+
if (!this.#hostExports.has(name)) throw unsupported(name);
|
|
535
|
+
try {
|
|
536
|
+
const call = this.#thread.imports[name];
|
|
537
|
+
return await call(...args);
|
|
538
|
+
} catch (error) {
|
|
539
|
+
if (this.#thread.closed) throw this.end(sessionEnded());
|
|
540
|
+
const appError = fromHostError(error, name);
|
|
541
|
+
if (appError.code === "session_ended") this.end(appError);
|
|
542
|
+
throw appError;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Ends the channel. Only the first call has an effect: pending and later calls reject with
|
|
547
|
+
* its `error`. Returns the error the channel ended with.
|
|
548
|
+
*/
|
|
549
|
+
end(error) {
|
|
550
|
+
if (this.#ended) return this.#ended;
|
|
551
|
+
this.#ended = error;
|
|
552
|
+
this.#stopWatchingTitle?.();
|
|
553
|
+
this.#history?.stop();
|
|
554
|
+
this.#thread.close();
|
|
555
|
+
this.#port.close();
|
|
556
|
+
this.#events.ended(error);
|
|
557
|
+
notify(this.#endListeners, error);
|
|
558
|
+
this.#endListeners.clear();
|
|
559
|
+
return error;
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* The `Ghost` object the app gets once `start` has set the context. It has only the members
|
|
563
|
+
* its type declares, so no part of the channel, such as `end`, is reachable from the app.
|
|
564
|
+
*/
|
|
565
|
+
ghost = this.#createGhost();
|
|
566
|
+
#createGhost() {
|
|
567
|
+
const context = () => this.#context;
|
|
568
|
+
const theme = () => this.#theme;
|
|
569
|
+
const connected = () => this.#ended === void 0;
|
|
570
|
+
return Object.freeze({
|
|
571
|
+
get site() {
|
|
572
|
+
return context().site;
|
|
573
|
+
},
|
|
574
|
+
get user() {
|
|
575
|
+
return context().user;
|
|
576
|
+
},
|
|
577
|
+
get theme() {
|
|
578
|
+
return theme();
|
|
579
|
+
},
|
|
580
|
+
get session() {
|
|
581
|
+
return context().session;
|
|
582
|
+
},
|
|
583
|
+
get connected() {
|
|
584
|
+
return connected();
|
|
585
|
+
},
|
|
586
|
+
path: this.#createPath(),
|
|
587
|
+
onThemeChange: (callback) => subscribe(this.#themeListeners, callback),
|
|
588
|
+
onPathChange: (callback) => subscribe(this.#pathListeners, callback),
|
|
589
|
+
onSessionEnd: (callback) => this.#onSessionEnd(callback),
|
|
590
|
+
fetch: (path, init) => this.#fetch(path, init),
|
|
591
|
+
open: (place) => this.#open(place)
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
#createPath() {
|
|
595
|
+
const current = () => this.#path;
|
|
596
|
+
return Object.freeze({ get current() {
|
|
597
|
+
return current();
|
|
598
|
+
} });
|
|
599
|
+
}
|
|
600
|
+
#onSessionEnd(callback) {
|
|
601
|
+
const ended = this.#ended;
|
|
602
|
+
if (ended) {
|
|
603
|
+
let left = false;
|
|
604
|
+
queueMicrotask(() => {
|
|
605
|
+
if (!left) callback(ended);
|
|
606
|
+
});
|
|
607
|
+
return () => {
|
|
608
|
+
left = true;
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
return subscribe(this.#endListeners, callback);
|
|
612
|
+
}
|
|
613
|
+
async #fetch(path, init) {
|
|
614
|
+
const request = toFetchRequest(path, init);
|
|
615
|
+
return toResponse(await this.#call("fetch", request));
|
|
616
|
+
}
|
|
617
|
+
async #open(place) {
|
|
618
|
+
if (!isRecord(place)) throw invalidArgument(ARGUMENT_MESSAGES.place);
|
|
619
|
+
await this.#call("open", cloneArgument(place, ARGUMENT_MESSAGES.place));
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
//#endregion
|
|
623
|
+
//#region src/version.ts
|
|
624
|
+
/**
|
|
625
|
+
* The SDK's version, sent in the hello for Admin's logs. The build and the tests replace
|
|
626
|
+
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
627
|
+
* and doesn't read package.json.
|
|
628
|
+
*/
|
|
629
|
+
var SDK_VERSION = "0.1.0-alpha.1";
|
|
630
|
+
//#endregion
|
|
631
|
+
//#region src/connect.ts
|
|
632
|
+
/**
|
|
633
|
+
* How often, in milliseconds, the SDK repeats the hello until Admin answers. Admin may only
|
|
634
|
+
* start listening after the page has loaded and sent its first hello, so one hello is not
|
|
635
|
+
* enough.
|
|
636
|
+
*/
|
|
637
|
+
var HELLO_INTERVAL = 250;
|
|
638
|
+
/**
|
|
639
|
+
* The target origin for the hello: the embedding page's origin where the browser exposes it
|
|
640
|
+
* (`location.ancestorOrigins`, in Chromium and WebKit), and `'*'` elsewhere. The hello grants
|
|
641
|
+
* nothing: the port goes the other way, and Admin addresses it to this page's origin only.
|
|
642
|
+
* `document.referrer` doesn't work here: once the page has navigated within itself, it holds
|
|
643
|
+
* the page's own origin.
|
|
644
|
+
*/
|
|
645
|
+
function parentOrigin() {
|
|
646
|
+
const origin = window.location.ancestorOrigins?.[0];
|
|
647
|
+
return origin && origin !== "null" ? origin : "*";
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* The global key where the first copy of the SDK to connect claims the page. It is a symbol
|
|
651
|
+
* from the global registry, so a second copy bundled into the same page finds the same key.
|
|
652
|
+
*/
|
|
653
|
+
var PAGE_CLAIM = Symbol.for("@tryghost/app-sdk");
|
|
654
|
+
/**
|
|
655
|
+
* The claim also holds the hello's `document` ID. It's made when the SDK loads, so every
|
|
656
|
+
* `connect()` in a document sends the same ID, and a new document (after a reload, a form post
|
|
657
|
+
* or a link) gets a new one. It's random rather than `performance.timeOrigin`, which some
|
|
658
|
+
* privacy-focused browsers round to 16–100 ms, so two documents loaded in quick succession
|
|
659
|
+
* could share it. `Math.random` is enough here, and unlike `crypto.randomUUID` it works on the
|
|
660
|
+
* plain HTTP origins apps use in development.
|
|
661
|
+
*/
|
|
662
|
+
var thisCopy = Object.freeze({
|
|
663
|
+
sdk: SDK_VERSION,
|
|
664
|
+
document: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
|
|
665
|
+
});
|
|
666
|
+
/** Claims the page for this copy of the SDK unless another copy has. Returns whether it did. */
|
|
667
|
+
function claimPage() {
|
|
668
|
+
const page = globalThis;
|
|
669
|
+
page[PAGE_CLAIM] ??= thisCopy;
|
|
670
|
+
return page[PAGE_CLAIM] === thisCopy;
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* The longest delay `setTimeout` supports. It treats anything longer as 0, so the timeout
|
|
674
|
+
* would fire immediately.
|
|
675
|
+
*/
|
|
676
|
+
var TIMEOUT_MAX = 2 ** 31 - 1;
|
|
677
|
+
function handshake(options, onEnded) {
|
|
678
|
+
if (!isRecord(options)) return Promise.reject(invalidArgument("Expected options such as { timeout: 10000 }"));
|
|
679
|
+
const { timeout = START_TIMEOUT_MS } = options;
|
|
680
|
+
if (typeof timeout !== "number" || !(timeout > 0) || !(timeout <= TIMEOUT_MAX)) return Promise.reject(invalidArgument(`Expected a timeout in milliseconds, above 0 and at most ${TIMEOUT_MAX}`));
|
|
681
|
+
if (typeof window === "undefined" || window.parent === window) return Promise.reject(new GhostAppError("not_framed", "This page is not open inside Ghost Admin"));
|
|
682
|
+
const parent = window.parent;
|
|
683
|
+
const targetOrigin = parentOrigin();
|
|
684
|
+
return new Promise((resolve, reject) => {
|
|
685
|
+
const stopWaiting = () => {
|
|
686
|
+
clearInterval(helloTimer);
|
|
687
|
+
clearTimeout(timeoutTimer);
|
|
688
|
+
window.removeEventListener("message", onMessage);
|
|
689
|
+
};
|
|
690
|
+
const fail = (error) => {
|
|
691
|
+
stopWaiting();
|
|
692
|
+
reject(error);
|
|
693
|
+
};
|
|
694
|
+
const onMessage = (event) => {
|
|
695
|
+
const port = event.ports?.[0];
|
|
696
|
+
if (event.source !== parent || !isConnectMessage(event.data) || !port || targetOrigin !== "*" && event.origin !== targetOrigin) return;
|
|
697
|
+
clearInterval(helloTimer);
|
|
698
|
+
window.removeEventListener("message", onMessage);
|
|
699
|
+
channel = new Channel(port, event.data.exports, {
|
|
700
|
+
started: (ghost) => {
|
|
701
|
+
stopWaiting();
|
|
702
|
+
resolve(ghost);
|
|
703
|
+
},
|
|
704
|
+
ended: (error) => {
|
|
705
|
+
fail(error);
|
|
706
|
+
onEnded(error);
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
};
|
|
710
|
+
const hello = {
|
|
711
|
+
type: HELLO_MESSAGE_TYPE,
|
|
712
|
+
sdk: SDK_VERSION,
|
|
713
|
+
document: thisCopy.document
|
|
714
|
+
};
|
|
715
|
+
const sayHello = () => {
|
|
716
|
+
parent.postMessage(hello, targetOrigin);
|
|
717
|
+
};
|
|
718
|
+
let channel;
|
|
719
|
+
window.addEventListener("message", onMessage);
|
|
720
|
+
sayHello();
|
|
721
|
+
const helloTimer = setInterval(sayHello, HELLO_INTERVAL);
|
|
722
|
+
const timeoutTimer = setTimeout(() => {
|
|
723
|
+
const error = new GhostAppError("not_connected", "Ghost Admin did not start the app in time");
|
|
724
|
+
fail(error);
|
|
725
|
+
channel?.end(error);
|
|
726
|
+
}, timeout);
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
var connecting;
|
|
730
|
+
var spent;
|
|
731
|
+
function forget(attempt) {
|
|
732
|
+
if (connecting === attempt) connecting = void 0;
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Connects to Ghost Admin, which must frame the page, and resolves once Admin has started the
|
|
736
|
+
* app. Safe to call as soon as the page loads.
|
|
737
|
+
*
|
|
738
|
+
* Every call shares one connection, and the first call's options apply. Only one copy of the
|
|
739
|
+
* SDK in a page can connect; any other copy rejects with `duplicate_sdk`. Admin answers each
|
|
740
|
+
* document only once, so after it answers, that connection is the page's only one. Once it
|
|
741
|
+
* fails or its session ends, every call rejects with the error it ended with, and only a new
|
|
742
|
+
* document (after a reload, for example) can connect again. A failure before Admin answered,
|
|
743
|
+
* such as a bad option or a timeout, can be retried.
|
|
744
|
+
*/
|
|
745
|
+
function connect(options = {}) {
|
|
746
|
+
if (!claimPage()) return Promise.reject(new GhostAppError("duplicate_sdk", "This page loads the app SDK more than once; load one copy, which every part of the page shares"));
|
|
747
|
+
if (spent) return Promise.reject(spent);
|
|
748
|
+
if (!connecting) {
|
|
749
|
+
const attempt = handshake(options, (error) => {
|
|
750
|
+
spent = error;
|
|
751
|
+
forget(attempt);
|
|
752
|
+
}).catch((error) => {
|
|
753
|
+
forget(attempt);
|
|
754
|
+
throw error;
|
|
755
|
+
});
|
|
756
|
+
connecting = attempt;
|
|
757
|
+
}
|
|
758
|
+
return connecting;
|
|
759
|
+
}
|
|
760
|
+
//#endregion
|
|
761
|
+
export { GhostAppError, connect };
|
|
762
|
+
|
|
763
|
+
//# sourceMappingURL=index.js.map
|