@tryghost/app-sdk 0.1.0-alpha.11 → 0.1.0-alpha.12
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/README.md +31 -508
- package/build/index.d.ts +28 -27
- package/build/index.js +2 -2
- package/build/index.js.map +1 -1
- package/dist/app-sdk.js +2 -2
- package/dist/app-sdk.js.map +1 -1
- package/package.json +1 -1
package/build/index.d.ts
CHANGED
|
@@ -25,7 +25,7 @@ type StartContext = {
|
|
|
25
25
|
/**
|
|
26
26
|
* Who is using the app, by ID and role only. Name and email are left out on purpose: an
|
|
27
27
|
* app that needs more about a person reads it from the API, through `/users/?filter=id:…`,
|
|
28
|
-
* where app
|
|
28
|
+
* where the app's permissions will apply.
|
|
29
29
|
*/
|
|
30
30
|
user: {
|
|
31
31
|
id: string;
|
|
@@ -70,24 +70,24 @@ type Place = {
|
|
|
70
70
|
/**
|
|
71
71
|
* Why an SDK call failed:
|
|
72
72
|
*
|
|
73
|
-
* - `not_framed`:
|
|
74
|
-
* - `not_connected`: Admin
|
|
75
|
-
* - `duplicate_sdk`:
|
|
73
|
+
* - `not_framed`: The page isn't framed in Admin, so there's nothing to connect to.
|
|
74
|
+
* - `not_connected`: Admin didn't start the app in time.
|
|
75
|
+
* - `duplicate_sdk`: Another copy of the SDK in the page has already connected, or tried to,
|
|
76
76
|
* because the page loads the SDK more than once. Load a single copy for the whole page.
|
|
77
|
-
* - `invalid_context`: Admin started the app with a context this SDK
|
|
77
|
+
* - `invalid_context`: Admin started the app with a context this SDK can't read. Updating the
|
|
78
78
|
* SDK usually fixes it.
|
|
79
|
-
* - `session_ended`:
|
|
79
|
+
* - `session_ended`: This document has left the app session, usually because the page reloaded
|
|
80
80
|
* or navigated away, or the session has ended. Every call fails after that.
|
|
81
|
-
* - `invalid_argument`:
|
|
82
|
-
* - `invalid_path`:
|
|
81
|
+
* - `invalid_argument`: The app passed something that can't be sent.
|
|
82
|
+
* - `invalid_path`: A path that isn't an Admin API path or a route within the app, or
|
|
83
83
|
* one the Admin API only redirects, such as a path without its trailing `/`.
|
|
84
|
-
* - `unsupported`:
|
|
84
|
+
* - `unsupported`: This site's version of Ghost doesn't have the call the app made yet. The
|
|
85
85
|
* SDK knows this from the calls Admin listed when it connected.
|
|
86
86
|
* - `blocked`: Admin refused by policy, such as a request the allowlist doesn't allow.
|
|
87
|
-
* - `network_error`: Admin
|
|
88
|
-
* - `rejected`: Admin refused for
|
|
87
|
+
* - `network_error`: Admin couldn't reach its own API.
|
|
88
|
+
* - `rejected`: Admin refused for another reason. The message says why.
|
|
89
89
|
*
|
|
90
|
-
* `not_framed`, `not_connected`, `duplicate_sdk` and `unsupported` are the SDK's own codes
|
|
90
|
+
* `not_framed`, `not_connected`, `duplicate_sdk` and `unsupported` are the SDK's own codes. The
|
|
91
91
|
* rest are bridge codes, which cross the channel.
|
|
92
92
|
*/
|
|
93
93
|
type GhostAppErrorCode = 'not_framed' | 'not_connected' | 'duplicate_sdk' | 'unsupported' | BridgeErrorCode;
|
|
@@ -115,11 +115,11 @@ interface ConnectOptions {
|
|
|
115
115
|
type JsonBody = Record<string, unknown> | readonly unknown[];
|
|
116
116
|
/** Like `RequestInit`, for the requests Admin can make on the app's behalf. */
|
|
117
117
|
interface GhostFetchInit {
|
|
118
|
-
/** Any case
|
|
118
|
+
/** Any case, sent in uppercase. Defaults to `GET`. */
|
|
119
119
|
method?: string;
|
|
120
120
|
/**
|
|
121
|
-
* Anything `Headers` accepts, except the headers only Admin sets
|
|
122
|
-
* `cookie` and `content-type
|
|
121
|
+
* Anything `Headers` accepts, except the headers only Admin sets. The SDK refuses those,
|
|
122
|
+
* such as `authorization`, `cookie` and `content-type`.
|
|
123
123
|
*/
|
|
124
124
|
headers?: HeadersInit;
|
|
125
125
|
/** Always JSON: text is sent as it is, and an object or array is sent as JSON. */
|
|
@@ -133,7 +133,7 @@ interface GhostFetchInit {
|
|
|
133
133
|
interface GhostPath {
|
|
134
134
|
/**
|
|
135
135
|
* The app's route: the path, query and fragment of the page's URL, such as `/episodes/12`, in
|
|
136
|
-
* the URL parser's
|
|
136
|
+
* the URL parser's normalized form, as Admin stores it (`/search?q=a%20b`, `..` resolved).
|
|
137
137
|
*/
|
|
138
138
|
readonly current: string;
|
|
139
139
|
}
|
|
@@ -150,21 +150,22 @@ interface Ghost {
|
|
|
150
150
|
readonly session: Session;
|
|
151
151
|
/** The app's route, kept in step with Admin's URL. */
|
|
152
152
|
readonly path: GhostPath;
|
|
153
|
-
/** False once the session has ended
|
|
153
|
+
/** False once the session has ended. Every call then rejects with `session_ended`. */
|
|
154
154
|
readonly connected: boolean;
|
|
155
|
-
/**
|
|
155
|
+
/** Registers a callback that runs when the person using the app switches Admin's theme. */
|
|
156
156
|
onThemeChange(callback: (theme: Readonly<Theme>) => void): Unsubscribe;
|
|
157
157
|
/**
|
|
158
|
-
*
|
|
159
|
-
* history, or one of Admin's own links. The SDK has already put the
|
|
160
|
-
* dispatched `popstate`, which a router follows. A multi-page app, with
|
|
161
|
-
* the new address, loads it: `location.replace(path)`.
|
|
158
|
+
* Registers a callback that runs when Admin moves the app to another of its routes: Back or
|
|
159
|
+
* forward in Admin's history, or one of Admin's own links. The SDK has already put the
|
|
160
|
+
* page's URL there and dispatched `popstate`, which a router follows. A multi-page app, with
|
|
161
|
+
* no router to render the new address, loads it: `location.replace(path)`. It doesn't run for
|
|
162
|
+
* the app's own moves.
|
|
162
163
|
*/
|
|
163
164
|
onPathChange(callback: (path: string) => void): Unsubscribe;
|
|
164
165
|
/**
|
|
165
|
-
*
|
|
166
|
-
* form or follows a link, or when the app session itself ends.
|
|
167
|
-
* has already happened.
|
|
166
|
+
* Registers a callback that runs once when this document leaves the app session, because the
|
|
167
|
+
* page reloads, posts a form or follows a link, or when the app session itself ends. It runs
|
|
168
|
+
* straight away if that has already happened.
|
|
168
169
|
*/
|
|
169
170
|
onSessionEnd(callback: (error: GhostAppError) => void): Unsubscribe;
|
|
170
171
|
/**
|
|
@@ -173,7 +174,7 @@ interface Ghost {
|
|
|
173
174
|
* its status, and rejects only when Admin refuses to make the request.
|
|
174
175
|
*/
|
|
175
176
|
fetch(path: string, init?: GhostFetchInit): Promise<Response>;
|
|
176
|
-
/** Sends the
|
|
177
|
+
/** Sends the person using the app to a place in Admin, such as `{ post: { id } }`. */
|
|
177
178
|
open(place: Place): Promise<void>;
|
|
178
179
|
}
|
|
179
180
|
//#endregion
|
|
@@ -183,7 +184,7 @@ interface Ghost {
|
|
|
183
184
|
* app. Safe to call as soon as the page loads.
|
|
184
185
|
*
|
|
185
186
|
* Every call shares one connection, and the first call's options apply. Only one copy of the
|
|
186
|
-
* SDK in a page can connect
|
|
187
|
+
* SDK in a page can connect. Any other copy rejects with `duplicate_sdk`. Admin answers each
|
|
187
188
|
* document only once, so after it answers, that connection is the page's only one. Once it
|
|
188
189
|
* fails or its session ends, every call rejects with the error it ended with, and only a new
|
|
189
190
|
* document (after a reload, for example) can connect again. A failure before Admin answered,
|
package/build/index.js
CHANGED
|
@@ -490,7 +490,7 @@ var Channel = class {
|
|
|
490
490
|
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
491
491
|
* and doesn't read package.json.
|
|
492
492
|
*/
|
|
493
|
-
var SDK_VERSION = "0.1.0-alpha.
|
|
493
|
+
var SDK_VERSION = "0.1.0-alpha.12";
|
|
494
494
|
//#endregion
|
|
495
495
|
//#region src/connect.ts
|
|
496
496
|
/**
|
|
@@ -600,7 +600,7 @@ function forget(attempt) {
|
|
|
600
600
|
* app. Safe to call as soon as the page loads.
|
|
601
601
|
*
|
|
602
602
|
* Every call shares one connection, and the first call's options apply. Only one copy of the
|
|
603
|
-
* SDK in a page can connect
|
|
603
|
+
* SDK in a page can connect. Any other copy rejects with `duplicate_sdk`. Admin answers each
|
|
604
604
|
* document only once, so after it answers, that connection is the page's only one. Once it
|
|
605
605
|
* fails or its session ends, every call rejects with the error it ended with, and only a new
|
|
606
606
|
* document (after a reload, for example) can connect again. A failure before Admin answered,
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#port","#thread","#hostExports","#events","#themeListeners","#pathListeners","#endListeners","#start","#themeChanged","#pathChanged","#context","#theme","#history","#moved","#path","#stopWatchingTitle","#call","#assertStarted","#moves","#ended","#createGhost","#createPath","#onSessionEnd","#fetch","#open"],"sources":["../src/errors.ts","../src/fetch.ts","../src/history.ts","../src/title.ts","../src/session.ts","../src/version.ts","../src/connect.ts"],"sourcesContent":["import { HOST_ERROR_CODES, decodeBridgeError, type BridgeErrorCode } from '@tryghost/app-contracts';\n\n/**\n * Why an SDK call failed:\n *\n * - `not_framed`: the page is not framed in Admin, so there is nothing to connect to.\n * - `not_connected`: Admin did not start the app in time.\n * - `duplicate_sdk`: another copy of the SDK in the page has already connected, or tried to,\n * because the page loads the SDK more than once. Load a single copy for the whole page.\n * - `invalid_context`: Admin started the app with a context this SDK cannot read. Updating the\n * SDK usually fixes it.\n * - `session_ended`: this document has left the app session, usually because the page reloaded\n * or navigated away, or the session has ended. Every call fails after that.\n * - `invalid_argument`: the app passed something that cannot be sent.\n * - `invalid_path`: a path that is not an Admin API path, or not a route within the app; or\n * one the Admin API only redirects, such as a path without its trailing `/`.\n * - `unsupported`: this site's version of Ghost doesn't have the call the app made yet. The\n * SDK knows this from the calls Admin listed when it connected.\n * - `blocked`: Admin refused by policy, such as a request the allowlist doesn't allow.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: Admin refused for any other reason; the message says why.\n *\n * `not_framed`, `not_connected`, `duplicate_sdk` and `unsupported` are the SDK's own codes; the\n * rest are bridge codes, which cross the channel.\n */\nexport type GhostAppErrorCode =\n | 'not_framed'\n | 'not_connected'\n | 'duplicate_sdk'\n | 'unsupported'\n | BridgeErrorCode;\n\n/** The only error type the SDK rejects with, so an app can branch on `code`. */\nexport class GhostAppError extends Error {\n readonly code: GhostAppErrorCode;\n\n constructor(code: GhostAppErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'GhostAppError';\n this.code = code;\n }\n}\n\n/**\n * Converts whatever a call to Admin rejected with into a `GhostAppError`, with the code Admin\n * gave or, if there is none, `rejected` with Admin's message.\n */\nexport function fromHostError(error: unknown, operation: string): GhostAppError {\n const message =\n typeof error === 'object' && error !== null && 'message' in error\n ? String(error.message)\n : undefined;\n if (message === undefined) {\n return new GhostAppError('rejected', `Ghost refused ${operation}`, { cause: error });\n }\n // Only the codes Admin refuses with are parsed; any other prefix stays part of the message.\n const coded = decodeBridgeError(message, HOST_ERROR_CODES);\n if (coded) {\n return new GhostAppError(coded.code, coded.detail, { cause: error });\n }\n return new GhostAppError('rejected', message, { cause: error });\n}\n\nexport function invalidArgument(message: string): GhostAppError {\n return new GhostAppError('invalid_argument', message);\n}\n\nexport function invalidPath(message: string): GhostAppError {\n return new GhostAppError('invalid_path', message);\n}\n\nexport function unsupported(operation: string): GhostAppError {\n return new GhostAppError('unsupported', `This site's Ghost doesn't support ${operation} yet`);\n}\n\nexport function sessionEnded(): GhostAppError {\n return new GhostAppError('session_ended', 'The session with Ghost has ended');\n}\n","import {\n ARGUMENT_MESSAGES,\n FETCH_METHODS,\n isContainedPath,\n isFetchResponse,\n isRecord,\n isReservedRequestHeader,\n methodAllowsBody,\n type FetchMethod,\n type FetchRequest,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument, invalidPath } from './errors.ts';\nimport type { GhostFetchInit, JsonBody } from './types.ts';\n\nconst JSON_BODY = 'Expected a body that can be sent as JSON';\n\n// The statuses a `Response` must be built without a body for, or its constructor throws.\nconst NULL_BODY_STATUSES = new Set([204, 205, 304]);\n\nfunction isJsonBody(value: unknown): value is JsonBody {\n if (Array.isArray(value)) {\n return true;\n }\n if (!isRecord(value)) {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n// A cycle or a BigInt makes `JSON.stringify` throw, and a `toJSON` that returns `undefined`\n// makes it return `undefined`.\nfunction toJson(body: JsonBody): string {\n let json: string | undefined;\n try {\n json = JSON.stringify(body) as string | undefined;\n } catch (error) {\n throw new GhostAppError('invalid_argument', JSON_BODY, { cause: error });\n }\n if (json === undefined) {\n throw invalidArgument(JSON_BODY);\n }\n return json;\n}\n\nfunction toHeaders(init: HeadersInit | undefined): Record<string, string> {\n let headers: Headers;\n try {\n headers = new Headers(init);\n } catch (error) {\n throw new GhostAppError('invalid_argument', 'Expected headers with valid names and values', {\n cause: error,\n });\n }\n // `Headers` lowercases the names, so a reserved header the app set is found in any case.\n const entries = [...headers.entries()];\n const reserved = entries.find(([name]) => isReservedRequestHeader(name));\n if (reserved) {\n throw invalidArgument(ARGUMENT_MESSAGES.reservedHeader(reserved[0]));\n }\n return Object.fromEntries(entries);\n}\n\n/**\n * Converts `fetch(path, init)` into the plain request Admin accepts. Only obvious mistakes are\n * refused here, using the same rules Admin applies; Admin checks everything again.\n */\nexport function toFetchRequest(path: string, init: GhostFetchInit = {}): FetchRequest {\n if (!isContainedPath(path)) {\n throw invalidPath(ARGUMENT_MESSAGES.fetchPath);\n }\n // The types rule this out, but a page without TypeScript can pass anything.\n if (typeof init !== 'object' || init === null) {\n throw invalidArgument('Expected options such as { method, headers, body }');\n }\n\n const { method: given = 'GET' } = init as { method?: unknown };\n const method = (typeof given === 'string' ? given.toUpperCase() : given) as FetchMethod;\n if (!FETCH_METHODS.includes(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchMethod);\n }\n\n const headers = toHeaders(init.headers);\n const request: FetchRequest = { path, method };\n\n if (init.body !== undefined && init.body !== null) {\n if (!methodAllowsBody(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchBody);\n }\n if (typeof init.body === 'string') {\n request.body = init.body;\n } else if (isJsonBody(init.body)) {\n request.body = toJson(init.body);\n } else {\n // Binary and streamed bodies cannot cross the channel as text.\n throw invalidArgument('Expected the body as text, or as an object or array to send as JSON');\n }\n }\n\n if (Object.keys(headers).length > 0) {\n request.headers = headers;\n }\n return request;\n}\n\nconst UNREADABLE_ANSWER = \"Ghost answered with a response this SDK doesn't understand\";\n\n/** Rebuilds Admin's response as the `Response` the app would have got from `fetch`. */\nexport function toResponse(answer: unknown): Response {\n if (!isFetchResponse(answer)) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER);\n }\n // The `Response` constructor throws on a header name or status text it can't hold.\n try {\n return new Response(NULL_BODY_STATUSES.has(answer.status) ? null : answer.body, {\n status: answer.status,\n statusText: answer.statusText,\n headers: answer.headers,\n });\n } catch (error) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER, { cause: error });\n }\n}\n","import { isContainedPath, type PathMove } from '@tryghost/app-contracts';\n\n/**\n * A URL's route: its path, query and fragment. The URL parser has already put them in the\n * normalised form Admin stores app paths in. Resolving them again would read a path that starts\n * with `//` as a host, so a page at `//evil.example/x` would report `/x`; kept as it is, that\n * route fails `isContainedPath` and is never reported.\n */\nfunction routeOf({ pathname, search, hash }: { pathname: string; search: string; hash: string }) {\n return `${pathname}${search}${hash}`;\n}\n\n/** The page's route. */\nexport function currentRoute(): string {\n return routeOf(window.location);\n}\n\n/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */\nfunction isLink(node: EventTarget): node is Element {\n return (\n (node instanceof HTMLAnchorElement || (node instanceof SVGElement && node.localName === 'a')) &&\n node.hasAttribute('href')\n );\n}\n\nexport interface HistoryWatch {\n /**\n * Puts the page at `path` without adding a history entry, because Admin moved it there, and\n * dispatches `popstate` so the app's router shows it.\n */\n follow(path: string): void;\n /** Gives the page its own history methods and links back. */\n stop(): void;\n}\n\n/**\n * Whether a route is one Admin would take. Admin owns the app's address, so the page never\n * moves to a route Admin refuses: it would show a place that a reload, Back or a copied Admin\n * link doesn't lead to. `isContainedPath` refuses the same route every time, so the move is\n * dropped, with a warning for the app's developer.\n */\nfunction isContained(route: string): boolean {\n if (isContainedPath(route)) {\n return true;\n }\n // The only place the app's developer would learn why the move did nothing.\n // eslint-disable-next-line no-console\n console.warn(`Ghost Admin can't open the app at ${route}, so the page stays where it is.`);\n return false;\n}\n\n/**\n * Whether a `pushState` or `replaceState` URL leads to a route Admin refuses. One the URL\n * parser can't read is left to the browser, which throws as it would without the SDK.\n */\nfunction refuses(url: string | URL | null | undefined): boolean {\n if (url === undefined || url === null) {\n return false;\n }\n const next = URL.parse(url, window.location.href);\n return next !== null && next.origin === window.location.origin && !isContained(routeOf(next));\n}\n\n/**\n * Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,\n * and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's\n * entries, which left back steps that did nothing once the app's page opened again, and WebKit\n * applies Admin's replace after a frame's push to the entry before it. So the frame keeps a\n * single entry, and Admin keeps one for each of the app's moves.\n *\n * - `history.pushState` and `history.replaceState` replace the frame's entry, then report the\n * move to Admin as a push or a replace, which is how Admin records it. A move to the route the\n * page is already on isn't reported, so Admin never gets an entry that changes nothing.\n * - A click on a link to the app's own origin, which a router hasn't already handled, is reported\n * as a push, and the page then loads the link's address in place of its own entry. A link that\n * opens elsewhere (a `target`, `download`, or a modifier key) is left alone.\n * - Neither is made to a route Admin would refuse, one that isn't contained.\n * - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.\n *\n * Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the\n * fragment through `location.hash` and the Navigation API, which have added the entry before\n * any event says so.\n */\nexport function watchHistory(\n moved: (route: string, move: PathMove) => Promise<void>,\n // How the page loads a link's address in place of its own entry. Tests pass their own.\n load: (url: string) => void = (url) => window.location.replace(url),\n): HistoryWatch {\n const { history } = window;\n const { pushState, replaceState } = history;\n let route = currentRoute();\n // The state the app gave each route, so following Admin back to one gives it back.\n const states = new Map<string, unknown>([[route, history.state]]);\n\n const report = (move: PathMove) => {\n const next = currentRoute();\n states.set(next, history.state);\n if (next !== route) {\n route = next;\n void moved(next, move);\n }\n };\n\n const push: History['pushState'] = (data, unused, url) => {\n if (refuses(url)) {\n return;\n }\n replaceState.call(history, data, unused, url);\n report('push');\n };\n const replace: History['replaceState'] = (data, unused, url) => {\n if (refuses(url)) {\n return;\n }\n replaceState.call(history, data, unused, url);\n report('replace');\n };\n history.pushState = push;\n history.replaceState = replace;\n\n const onClick = (event: MouseEvent) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // Found through the event's path, which reaches into shadow roots, and read through its\n // attributes, because an SVG link has none of `HTMLAnchorElement`'s properties.\n const link = event.composedPath().find(isLink);\n const target = link?.getAttribute('target') ?? '';\n if (!link || link.hasAttribute('download') || (target !== '' && target !== '_self')) {\n return;\n }\n const url = new URL(link.getAttribute('href') as string, document.baseURI);\n if (url.origin !== window.location.origin) {\n return;\n }\n event.preventDefault();\n const go = () => load(url.href);\n const next = routeOf(url);\n if (!isContained(next)) {\n return;\n }\n if (next === route) {\n go();\n return;\n }\n route = next;\n // Admin records the move before the page leaves, so the next document starts where it is.\n moved(next, 'push').then(go, go);\n };\n document.addEventListener('click', onClick);\n\n return {\n follow(path) {\n route = path;\n const state = states.get(path) ?? null;\n replaceState.call(history, state, '', path);\n window.dispatchEvent(new PopStateEvent('popstate', { state }));\n },\n stop() {\n if (history.pushState === push) {\n history.pushState = pushState;\n }\n if (history.replaceState === replace) {\n history.replaceState = replaceState;\n }\n document.removeEventListener('click', onClick);\n },\n };\n}\n","import { TITLE_MAX_LENGTH, toPlainText } from '@tryghost/app-contracts';\n\n/**\n * Trims a title to what Admin accepts, without splitting a character in two. Admin refuses a\n * title containing a character that reorders or hides text, so the SDK drops those characters\n * rather than losing the whole title: a right-to-left title often contains a direction mark.\n */\nfunction clampTitle(title: string): string {\n const trimmed = toPlainText(title).trim();\n if (trimmed.length <= TITLE_MAX_LENGTH) {\n return trimmed;\n }\n const end = /[\\uD800-\\uDBFF]/.test(trimmed.charAt(TITLE_MAX_LENGTH - 1))\n ? TITLE_MAX_LENGTH - 1\n : TITLE_MAX_LENGTH;\n return trimmed.slice(0, end);\n}\n\n/**\n * Reports the page's title now and every time it changes, so Admin can show it as its own.\n * Returns a function that stops watching.\n *\n * A title can change in three ways, and frameworks use all three: its text is edited, its\n * element is replaced, or an element is added where there was none. Rather than distinguish\n * them, the SDK reads `document.title` after every batch of changes in `<head>` and reports it\n * only if it differs from the last one. A mutation observer already delivers each batch once,\n * in a microtask.\n */\nexport function watchTitle(report: (title: string) => void): () => void {\n let last: string | undefined;\n const check = () => {\n const title = clampTitle(document.title);\n if (title !== last) {\n last = title;\n report(title);\n }\n };\n\n check();\n const observer = new MutationObserver(check);\n observer.observe(document.head ?? document.documentElement, {\n subtree: true,\n childList: true,\n characterData: true,\n });\n return () => observer.disconnect();\n}\n","import { ThreadMessagePort } from '@quilted/threads';\nimport {\n ARGUMENT_MESSAGES,\n encodeBridgeError,\n type AppErrorCode,\n isContainedPath,\n isRecord,\n isStartContext,\n isTheme,\n type AppExports,\n type HostExports,\n type PathMove,\n type Place,\n type Theme,\n} from '@tryghost/app-contracts';\n\nimport {\n GhostAppError,\n fromHostError,\n invalidArgument,\n sessionEnded,\n unsupported,\n} from './errors.ts';\nimport { toFetchRequest, toResponse } from './fetch.ts';\nimport { currentRoute, watchHistory, type HistoryWatch } from './history.ts';\nimport { watchTitle } from './title.ts';\nimport type {\n Ghost,\n GhostFetchInit,\n GhostPath,\n Session,\n Site,\n Unsubscribe,\n User,\n} from './types.ts';\n\ntype HostCall<K extends keyof HostExports> = (\n ...args: Parameters<HostExports[K]>\n) => ReturnType<HostExports[K]>;\n\n/** Calls each listener the app registered, so that one that throws can't stop the others. */\nfunction notify<T>(listeners: ReadonlySet<(value: T) => void>, value: T) {\n for (const listener of [...listeners]) {\n try {\n listener(value);\n } catch (error) {\n // Rethrown outside the SDK, where the page's own error handling sees it.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n\n/**\n * An error that refuses one of Admin's calls. Only its message reaches Admin, so the message\n * starts with the code, as Admin's own refusals do.\n */\nfunction refusal(code: AppErrorCode, detail: string): Error {\n return new Error(encodeBridgeError(code, detail));\n}\n\n/**\n * Returns the copy of an argument that will cross the channel, or throws `invalid_argument`\n * with `message` if it can't cross. The structured clone that carries a call only refuses a\n * symbol or a DOM node once the call is in progress, and the channel would proxy a function,\n * though no argument in the bridge's calls is a function. Cloning first refuses all of these\n * before anything is sent to Admin.\n */\nfunction cloneArgument<T>(value: T, message: string): T {\n try {\n return structuredClone(value);\n } catch (error) {\n throw new GhostAppError('invalid_argument', message, { cause: error });\n }\n}\n\nfunction subscribe<T>(listeners: Set<T>, listener: T): Unsubscribe {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * The parts of Admin's start context that `start` keeps. The theme and path can change, so\n * they are stored separately.\n */\ninterface StartedContext {\n site: Site;\n user: User;\n session: Session;\n}\n\nexport interface ChannelEvents {\n /** Admin started the app, and the connection is ready for it to use. */\n started(ghost: Ghost): void;\n /** The channel ended, before or after the start. */\n ended(error: GhostAppError): void;\n}\n\n/**\n * The channel to Admin over the port Admin handed the page, and the `Ghost` object the app\n * gets once Admin has called `start`. The channel itself stays inside the SDK.\n *\n * The channel ends in three cases: when the port closes, which browsers that fire `close` on\n * a port (and Node) report when Admin closes its end or its document goes away; when a call\n * fails because the thread has closed; or when Admin rejects a call with `session_ended`.\n * After that, every call rejects with the same error.\n */\nexport class Channel {\n readonly #port: MessagePort;\n readonly #thread: ThreadMessagePort<HostExports, AppExports>;\n // What this Admin exports, from its connect message.\n readonly #hostExports: ReadonlySet<string>;\n readonly #events: ChannelEvents;\n readonly #themeListeners = new Set<(theme: Readonly<Theme>) => void>();\n readonly #pathListeners = new Set<(path: string) => void>();\n readonly #endListeners = new Set<(error: GhostAppError) => void>();\n #context: StartedContext | undefined;\n #theme: Readonly<Theme> | undefined;\n #path = '/';\n #ended: GhostAppError | undefined;\n #stopWatchingTitle: (() => void) | undefined;\n #history: HistoryWatch | undefined;\n // Counts the page's moves, so an answer to one the page has since moved on from is ignored.\n #moves = 0;\n\n constructor(port: MessagePort, hostExports: readonly string[], events: ChannelEvents) {\n this.#port = port;\n this.#hostExports = new Set(hostExports);\n this.#events = events;\n this.#thread = new ThreadMessagePort<HostExports, AppExports>(port, {\n exports: {\n start: async (context) => this.#start(context),\n themeChanged: async (theme) => this.#themeChanged(theme),\n pathChanged: async (path) => this.#pathChanged(path),\n },\n });\n port.addEventListener('close', () => this.end(sessionEnded()));\n // A message that could not be read is a call that will never be answered.\n port.addEventListener('messageerror', () => this.end(sessionEnded()));\n port.start();\n }\n\n #start(context: unknown) {\n if (this.#context) {\n return;\n }\n if (!isStartContext(context)) {\n const detail = \"Ghost started the app with a context this SDK doesn't understand\";\n // End the channel only after Admin has received the refusal, so Admin learns why instead\n // of waiting for its timeout.\n setTimeout(() => this.end(new GhostAppError('invalid_context', detail)), 0);\n throw refusal('invalid_context', detail);\n }\n this.#context = {\n site: Object.freeze({ ...context.site }),\n user: Object.freeze({ ...context.user }),\n session: Object.freeze({ ...context.session }),\n };\n this.#theme = Object.freeze({ ...context.theme });\n // Admin owns the history from here on. The page's own address is its route: Admin loads a\n // new frame at its own path, so the two differ only when the page's server redirected it or\n // a form or link loaded another page in place, and then Admin follows the page.\n this.#history = watchHistory((route, move) => this.#moved(route, move));\n const route = currentRoute();\n this.#path = context.path;\n if (route !== context.path) {\n void this.#moved(route, 'replace');\n }\n // Report the title before `start` returns, so Admin has it by the time it shows the page.\n // An older Admin without `titleChanged` keeps its own title.\n if (this.#hostExports.has('titleChanged')) {\n this.#stopWatchingTitle = watchTitle((title) => {\n this.#call('titleChanged', title).catch(() => {\n // If Admin refuses a title, it keeps showing its own.\n });\n });\n }\n this.#events.started(this.ghost);\n }\n\n #themeChanged(theme: unknown) {\n this.#assertStarted();\n if (!isTheme(theme)) {\n throw refusal('invalid_argument', \"Ghost sent a theme this SDK doesn't understand\");\n }\n this.#theme = Object.freeze({ ...theme });\n notify(this.#themeListeners, this.#theme);\n }\n\n #pathChanged(path: unknown) {\n this.#assertStarted();\n if (!isContainedPath(path)) {\n throw refusal('invalid_argument', \"Ghost sent a path this SDK doesn't understand\");\n }\n this.#path = path;\n this.#history?.follow(path);\n notify(this.#pathListeners, path);\n }\n\n /**\n * Reports a move the page made. Resolves once Admin has answered, with the path Admin now has\n * for the app, or has refused; a refused move leaves the page where it is.\n */\n async #moved(route: string, move: PathMove): Promise<void> {\n // A route that leaves the app once normalised, such as `/.//host/`, is one Admin refuses\n // and the SDK never hands out, so the app's path stays where it was.\n if (!isContainedPath(route)) {\n return;\n }\n this.#path = route;\n this.#moves += 1;\n const thisMove = this.#moves;\n try {\n const adminPath = await this.#call('pathChanged', route, move);\n // Admin's answer, rather than `route`: it's Admin's own path when Admin didn't follow\n // the move, such as when the publisher is leaving the app, and Admin then moves the page\n // back with `pathChanged`. An answer to an earlier move is out of date.\n if (thisMove === this.#moves && isContainedPath(adminPath)) {\n this.#path = adminPath;\n }\n } catch {\n // Refused, or the session ended: either way there's nothing for the page to do.\n }\n }\n\n #assertStarted() {\n if (!this.#context) {\n throw refusal('invalid_context', 'Ghost has not started the app yet');\n }\n }\n\n async #call<K extends keyof HostExports>(\n name: K,\n ...args: Parameters<HostExports[K]>\n ): Promise<Awaited<ReturnType<HostExports[K]>>> {\n if (this.#ended) {\n throw this.#ended;\n }\n if (!this.#hostExports.has(name)) {\n throw unsupported(name);\n }\n try {\n const call = this.#thread.imports[name] as HostCall<K>;\n return await call(...args);\n } catch (error) {\n if (this.#thread.closed) {\n throw this.end(sessionEnded());\n }\n const appError = fromHostError(error, name);\n if (appError.code === 'session_ended') {\n this.end(appError);\n }\n throw appError;\n }\n }\n\n /**\n * Ends the channel. Only the first call has an effect: pending and later calls reject with\n * its `error`. Returns the error the channel ended with.\n */\n end(error: GhostAppError): GhostAppError {\n if (this.#ended) {\n return this.#ended;\n }\n this.#ended = error;\n this.#stopWatchingTitle?.();\n this.#history?.stop();\n this.#thread.close();\n this.#port.close();\n this.#events.ended(error);\n notify(this.#endListeners, error);\n this.#endListeners.clear();\n return error;\n }\n\n /**\n * The `Ghost` object the app gets once `start` has set the context. It has only the members\n * its type declares, so no part of the channel, such as `end`, is reachable from the app.\n */\n readonly ghost: Ghost = this.#createGhost();\n\n #createGhost(): Ghost {\n const context = () => this.#context as StartedContext;\n const theme = () => this.#theme as Readonly<Theme>;\n const connected = () => this.#ended === undefined;\n return Object.freeze({\n get site(): Site {\n return context().site;\n },\n get user(): User {\n return context().user;\n },\n get theme(): Readonly<Theme> {\n return theme();\n },\n get session(): Session {\n return context().session;\n },\n get connected(): boolean {\n return connected();\n },\n path: this.#createPath(),\n onThemeChange: (callback: (theme: Readonly<Theme>) => void): Unsubscribe =>\n subscribe(this.#themeListeners, callback),\n onPathChange: (callback: (path: string) => void): Unsubscribe =>\n subscribe(this.#pathListeners, callback),\n onSessionEnd: (callback: (error: GhostAppError) => void): Unsubscribe =>\n this.#onSessionEnd(callback),\n fetch: (path: string, init?: GhostFetchInit): Promise<Response> => this.#fetch(path, init),\n open: (place: Place): Promise<void> => this.#open(place),\n });\n }\n\n #createPath(): GhostPath {\n const current = () => this.#path;\n return Object.freeze({\n get current(): string {\n return current();\n },\n });\n }\n\n #onSessionEnd(callback: (error: GhostAppError) => void): Unsubscribe {\n const ended = this.#ended;\n if (ended) {\n // Notify it in a microtask, as an earlier subscriber would be, unless it has\n // unsubscribed by then.\n let left = false;\n queueMicrotask(() => {\n if (!left) {\n callback(ended);\n }\n });\n return () => {\n left = true;\n };\n }\n return subscribe(this.#endListeners, callback);\n }\n\n async #fetch(path: string, init?: GhostFetchInit): Promise<Response> {\n const request = toFetchRequest(path, init);\n return toResponse(await this.#call('fetch', request));\n }\n\n async #open(place: Place): Promise<void> {\n if (!isRecord(place)) {\n throw invalidArgument(ARGUMENT_MESSAGES.place);\n }\n await this.#call('open', cloneArgument(place, ARGUMENT_MESSAGES.place));\n }\n}\n","declare const __SDK_VERSION__: string;\n\n/**\n * The SDK's version, sent in the hello for Admin's logs. The build and the tests replace\n * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`\n * and doesn't read package.json.\n */\nexport const SDK_VERSION: string = __SDK_VERSION__;\n","import {\n HELLO_MESSAGE_TYPE,\n START_TIMEOUT_MS,\n isConnectMessage,\n isRecord,\n type HelloMessage,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument } from './errors.ts';\nimport { Channel } from './session.ts';\nimport type { ConnectOptions, Ghost } from './types.ts';\nimport { SDK_VERSION } from './version.ts';\n\n/**\n * How often, in milliseconds, the SDK repeats the hello until Admin answers. Admin may only\n * start listening after the page has loaded and sent its first hello, so one hello is not\n * enough.\n */\nconst HELLO_INTERVAL = 250;\n\n/**\n * The target origin for the hello: the embedding page's origin where the browser exposes it\n * (`location.ancestorOrigins`, in Chromium and WebKit), and `'*'` elsewhere. The hello grants\n * nothing: the port goes the other way, and Admin addresses it to this page's origin only.\n * `document.referrer` doesn't work here: once the page has navigated within itself, it holds\n * the page's own origin.\n */\nfunction parentOrigin(): string {\n const origin = window.location.ancestorOrigins?.[0];\n return origin && origin !== 'null' ? origin : '*';\n}\n\n/**\n * The global key where the first copy of the SDK to connect claims the page. It is a symbol\n * from the global registry, so a second copy bundled into the same page finds the same key.\n */\nconst PAGE_CLAIM = Symbol.for('@tryghost/app-sdk');\n\n/**\n * The claim also holds the hello's `document` ID. It's made when the SDK loads, so every\n * `connect()` in a document sends the same ID, and a new document (after a reload, a form post\n * or a link) gets a new one. It's random rather than `performance.timeOrigin`, which some\n * privacy-focused browsers round to 16–100 ms, so two documents loaded in quick succession\n * could share it. `Math.random` is enough here, and unlike `crypto.randomUUID` it works on the\n * plain HTTP origins apps use in development.\n */\nconst thisCopy = Object.freeze({\n sdk: SDK_VERSION,\n document: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,\n});\n\n/** Claims the page for this copy of the SDK unless another copy has. Returns whether it did. */\nfunction claimPage(): boolean {\n const page = globalThis as unknown as Record<symbol, unknown>;\n page[PAGE_CLAIM] ??= thisCopy;\n return page[PAGE_CLAIM] === thisCopy;\n}\n\n/**\n * The longest delay `setTimeout` supports. It treats anything longer as 0, so the timeout\n * would fire immediately.\n */\nconst TIMEOUT_MAX = 2 ** 31 - 1;\n\nfunction handshake(\n options: ConnectOptions,\n onEnded: (error: GhostAppError) => void,\n): Promise<Ghost> {\n if (!isRecord(options)) {\n return Promise.reject(invalidArgument('Expected options such as { timeout: 10000 }'));\n }\n // By default, wait as long as Admin gives the page. Waiting longer would mean waiting on a\n // frame Admin has already given up on.\n const { timeout = START_TIMEOUT_MS } = options;\n if (typeof timeout !== 'number' || !(timeout > 0) || !(timeout <= TIMEOUT_MAX)) {\n return Promise.reject(\n invalidArgument(`Expected a timeout in milliseconds, above 0 and at most ${TIMEOUT_MAX}`),\n );\n }\n if (typeof window === 'undefined' || window.parent === window) {\n return Promise.reject(\n new GhostAppError('not_framed', 'This page is not open inside Ghost Admin'),\n );\n }\n\n const parent = window.parent;\n const targetOrigin = parentOrigin();\n\n return new Promise<Ghost>((resolve, reject) => {\n const stopWaiting = () => {\n clearInterval(helloTimer);\n clearTimeout(timeoutTimer);\n window.removeEventListener('message', onMessage);\n };\n\n // A promise ignores `reject` once it has settled, so a failure after `started` changes\n // nothing.\n const fail = (error: GhostAppError) => {\n stopWaiting();\n reject(error);\n };\n\n // The channel is bound to the first valid answer from the parent window. The listener is\n // removed as soon as that answer arrives, so later answers are ignored.\n const onMessage = (event: MessageEvent) => {\n const port = event.ports?.[0];\n if (\n event.source !== parent ||\n !isConnectMessage(event.data) ||\n !port ||\n (targetOrigin !== '*' && event.origin !== targetOrigin)\n ) {\n return;\n }\n clearInterval(helloTimer);\n window.removeEventListener('message', onMessage);\n channel = new Channel(port, event.data.exports, {\n started: (ghost) => {\n stopWaiting();\n resolve(ghost);\n },\n ended: (error) => {\n fail(error);\n onEnded(error);\n },\n });\n };\n\n const hello: HelloMessage = {\n type: HELLO_MESSAGE_TYPE,\n sdk: SDK_VERSION,\n document: thisCopy.document,\n };\n const sayHello = () => {\n parent.postMessage(hello, targetOrigin);\n };\n\n let channel: Channel | undefined;\n window.addEventListener('message', onMessage);\n sayHello();\n const helloTimer = setInterval(sayHello, HELLO_INTERVAL);\n const timeoutTimer = setTimeout(() => {\n const error = new GhostAppError('not_connected', 'Ghost Admin did not start the app in time');\n fail(error);\n channel?.end(error);\n }, timeout);\n });\n}\n\nlet connecting: Promise<Ghost> | undefined;\n// The error the page's connection ended with, after Admin answered it. Admin answers each\n// document only once, so this connection was the page's only one.\nlet spent: GhostAppError | undefined;\n\n// Forgets an attempt only if it is still the shared one: an attempt that ended may report\n// that after a newer attempt has started.\nfunction forget(attempt: Promise<Ghost>) {\n if (connecting === attempt) {\n connecting = undefined;\n }\n}\n\n/**\n * Connects to Ghost Admin, which must frame the page, and resolves once Admin has started the\n * app. Safe to call as soon as the page loads.\n *\n * Every call shares one connection, and the first call's options apply. Only one copy of the\n * SDK in a page can connect; any other copy rejects with `duplicate_sdk`. Admin answers each\n * document only once, so after it answers, that connection is the page's only one. Once it\n * fails or its session ends, every call rejects with the error it ended with, and only a new\n * document (after a reload, for example) can connect again. A failure before Admin answered,\n * such as a bad option or a timeout, can be retried.\n */\nexport function connect(options: ConnectOptions = {}): Promise<Ghost> {\n // Two copies would both send a hello for the same document, and Admin answers each document\n // only once.\n if (!claimPage()) {\n return Promise.reject(\n new GhostAppError(\n 'duplicate_sdk',\n 'This page loads the app SDK more than once; load one copy, which every part of the page shares',\n ),\n );\n }\n if (spent) {\n return Promise.reject(spent);\n }\n if (!connecting) {\n const attempt: Promise<Ghost> = handshake(options, (error) => {\n spent = error;\n forget(attempt);\n }).catch((error: unknown) => {\n forget(attempt);\n throw error;\n });\n connecting = attempt;\n }\n return connecting;\n}\n"],"mappings":";;;;AAiCA,IAAa,gBAAb,cAAmC,MAAM;CACvC;CAEA,YAAY,MAAyB,SAAiB,SAAwB;EAC5E,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;;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Q,IAAI,cAAc,iBAAiB,2CAA2C;GAC5F,KAAK,KAAK;GACV,SAAS,IAAI,KAAK;EACpB,GAAG,OAAO;CACZ,CAAC;AACH;AAEA,IAAI;AAGJ,IAAI;AAIJ,SAAS,OAAO,SAAyB;CACvC,IAAI,eAAe,SACjB,aAAa,KAAA;AAEjB;;;;;;;;;;;;AAaA,SAAgB,QAAQ,UAA0B,CAAC,GAAmB;CAGpE,IAAI,CAAC,UAAU,GACb,OAAO,QAAQ,OACb,IAAI,cACF,iBACA,gGACF,CACF;CAEF,IAAI,OACF,OAAO,QAAQ,OAAO,KAAK;CAE7B,IAAI,CAAC,YAAY;EACf,MAAM,UAA0B,UAAU,UAAU,UAAU;GAC5D,QAAQ;GACR,OAAO,OAAO;EAChB,CAAC,CAAC,CAAC,OAAO,UAAmB;GAC3B,OAAO,OAAO;GACd,MAAM;EACR,CAAC;EACD,aAAa;CACf;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#port","#thread","#hostExports","#events","#themeListeners","#pathListeners","#endListeners","#start","#themeChanged","#pathChanged","#context","#theme","#history","#moved","#path","#stopWatchingTitle","#call","#assertStarted","#moves","#ended","#createGhost","#createPath","#onSessionEnd","#fetch","#open"],"sources":["../src/errors.ts","../src/fetch.ts","../src/history.ts","../src/title.ts","../src/session.ts","../src/version.ts","../src/connect.ts"],"sourcesContent":["import { HOST_ERROR_CODES, decodeBridgeError, type BridgeErrorCode } from '@tryghost/app-contracts';\n\n/**\n * Why an SDK call failed:\n *\n * - `not_framed`: The page isn't framed in Admin, so there's nothing to connect to.\n * - `not_connected`: Admin didn't start the app in time.\n * - `duplicate_sdk`: Another copy of the SDK in the page has already connected, or tried to,\n * because the page loads the SDK more than once. Load a single copy for the whole page.\n * - `invalid_context`: Admin started the app with a context this SDK can't read. Updating the\n * SDK usually fixes it.\n * - `session_ended`: This document has left the app session, usually because the page reloaded\n * or navigated away, or the session has ended. Every call fails after that.\n * - `invalid_argument`: The app passed something that can't be sent.\n * - `invalid_path`: A path that isn't an Admin API path or a route within the app, or\n * one the Admin API only redirects, such as a path without its trailing `/`.\n * - `unsupported`: This site's version of Ghost doesn't have the call the app made yet. The\n * SDK knows this from the calls Admin listed when it connected.\n * - `blocked`: Admin refused by policy, such as a request the allowlist doesn't allow.\n * - `network_error`: Admin couldn't reach its own API.\n * - `rejected`: Admin refused for another reason. The message says why.\n *\n * `not_framed`, `not_connected`, `duplicate_sdk` and `unsupported` are the SDK's own codes. The\n * rest are bridge codes, which cross the channel.\n */\nexport type GhostAppErrorCode =\n | 'not_framed'\n | 'not_connected'\n | 'duplicate_sdk'\n | 'unsupported'\n | BridgeErrorCode;\n\n/** The only error type the SDK rejects with, so an app can branch on `code`. */\nexport class GhostAppError extends Error {\n readonly code: GhostAppErrorCode;\n\n constructor(code: GhostAppErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'GhostAppError';\n this.code = code;\n }\n}\n\n/**\n * Converts whatever a call to Admin rejected with into a `GhostAppError`, with the code Admin\n * gave or, if there is none, `rejected` with Admin's message.\n */\nexport function fromHostError(error: unknown, operation: string): GhostAppError {\n const message =\n typeof error === 'object' && error !== null && 'message' in error\n ? String(error.message)\n : undefined;\n if (message === undefined) {\n return new GhostAppError('rejected', `Ghost refused ${operation}`, { cause: error });\n }\n // Only the codes Admin refuses with are parsed; any other prefix stays part of the message.\n const coded = decodeBridgeError(message, HOST_ERROR_CODES);\n if (coded) {\n return new GhostAppError(coded.code, coded.detail, { cause: error });\n }\n return new GhostAppError('rejected', message, { cause: error });\n}\n\nexport function invalidArgument(message: string): GhostAppError {\n return new GhostAppError('invalid_argument', message);\n}\n\nexport function invalidPath(message: string): GhostAppError {\n return new GhostAppError('invalid_path', message);\n}\n\nexport function unsupported(operation: string): GhostAppError {\n return new GhostAppError('unsupported', `This site's Ghost doesn't support ${operation} yet`);\n}\n\nexport function sessionEnded(): GhostAppError {\n return new GhostAppError('session_ended', 'The session with Ghost has ended');\n}\n","import {\n ARGUMENT_MESSAGES,\n FETCH_METHODS,\n isContainedPath,\n isFetchResponse,\n isRecord,\n isReservedRequestHeader,\n methodAllowsBody,\n type FetchMethod,\n type FetchRequest,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument, invalidPath } from './errors.ts';\nimport type { GhostFetchInit, JsonBody } from './types.ts';\n\nconst JSON_BODY = 'Expected a body that can be sent as JSON';\n\n// The statuses a `Response` must be built without a body for, or its constructor throws.\nconst NULL_BODY_STATUSES = new Set([204, 205, 304]);\n\nfunction isJsonBody(value: unknown): value is JsonBody {\n if (Array.isArray(value)) {\n return true;\n }\n if (!isRecord(value)) {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n// A cycle or a BigInt makes `JSON.stringify` throw, and a `toJSON` that returns `undefined`\n// makes it return `undefined`.\nfunction toJson(body: JsonBody): string {\n let json: string | undefined;\n try {\n json = JSON.stringify(body) as string | undefined;\n } catch (error) {\n throw new GhostAppError('invalid_argument', JSON_BODY, { cause: error });\n }\n if (json === undefined) {\n throw invalidArgument(JSON_BODY);\n }\n return json;\n}\n\nfunction toHeaders(init: HeadersInit | undefined): Record<string, string> {\n let headers: Headers;\n try {\n headers = new Headers(init);\n } catch (error) {\n throw new GhostAppError('invalid_argument', 'Expected headers with valid names and values', {\n cause: error,\n });\n }\n // `Headers` lowercases the names, so a reserved header the app set is found in any case.\n const entries = [...headers.entries()];\n const reserved = entries.find(([name]) => isReservedRequestHeader(name));\n if (reserved) {\n throw invalidArgument(ARGUMENT_MESSAGES.reservedHeader(reserved[0]));\n }\n return Object.fromEntries(entries);\n}\n\n/**\n * Converts `fetch(path, init)` into the plain request Admin accepts. Only obvious mistakes are\n * refused here, using the same rules Admin applies; Admin checks everything again.\n */\nexport function toFetchRequest(path: string, init: GhostFetchInit = {}): FetchRequest {\n if (!isContainedPath(path)) {\n throw invalidPath(ARGUMENT_MESSAGES.fetchPath);\n }\n // The types rule this out, but a page without TypeScript can pass anything.\n if (typeof init !== 'object' || init === null) {\n throw invalidArgument('Expected options such as { method, headers, body }');\n }\n\n const { method: given = 'GET' } = init as { method?: unknown };\n const method = (typeof given === 'string' ? given.toUpperCase() : given) as FetchMethod;\n if (!FETCH_METHODS.includes(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchMethod);\n }\n\n const headers = toHeaders(init.headers);\n const request: FetchRequest = { path, method };\n\n if (init.body !== undefined && init.body !== null) {\n if (!methodAllowsBody(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchBody);\n }\n if (typeof init.body === 'string') {\n request.body = init.body;\n } else if (isJsonBody(init.body)) {\n request.body = toJson(init.body);\n } else {\n // Binary and streamed bodies cannot cross the channel as text.\n throw invalidArgument('Expected the body as text, or as an object or array to send as JSON');\n }\n }\n\n if (Object.keys(headers).length > 0) {\n request.headers = headers;\n }\n return request;\n}\n\nconst UNREADABLE_ANSWER = \"Ghost answered with a response this SDK doesn't understand\";\n\n/** Rebuilds Admin's response as the `Response` the app would have got from `fetch`. */\nexport function toResponse(answer: unknown): Response {\n if (!isFetchResponse(answer)) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER);\n }\n // The `Response` constructor throws on a header name or status text it can't hold.\n try {\n return new Response(NULL_BODY_STATUSES.has(answer.status) ? null : answer.body, {\n status: answer.status,\n statusText: answer.statusText,\n headers: answer.headers,\n });\n } catch (error) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER, { cause: error });\n }\n}\n","import { isContainedPath, type PathMove } from '@tryghost/app-contracts';\n\n/**\n * A URL's route: its path, query and fragment. The URL parser has already put them in the\n * normalised form Admin stores app paths in. Resolving them again would read a path that starts\n * with `//` as a host, so a page at `//evil.example/x` would report `/x`; kept as it is, that\n * route fails `isContainedPath` and is never reported.\n */\nfunction routeOf({ pathname, search, hash }: { pathname: string; search: string; hash: string }) {\n return `${pathname}${search}${hash}`;\n}\n\n/** The page's route. */\nexport function currentRoute(): string {\n return routeOf(window.location);\n}\n\n/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */\nfunction isLink(node: EventTarget): node is Element {\n return (\n (node instanceof HTMLAnchorElement || (node instanceof SVGElement && node.localName === 'a')) &&\n node.hasAttribute('href')\n );\n}\n\nexport interface HistoryWatch {\n /**\n * Puts the page at `path` without adding a history entry, because Admin moved it there, and\n * dispatches `popstate` so the app's router shows it.\n */\n follow(path: string): void;\n /** Gives the page its own history methods and links back. */\n stop(): void;\n}\n\n/**\n * Whether a route is one Admin would take. Admin owns the app's address, so the page never\n * moves to a route Admin refuses: it would show a place that a reload, Back or a copied Admin\n * link doesn't lead to. `isContainedPath` refuses the same route every time, so the move is\n * dropped, with a warning for the app's developer.\n */\nfunction isContained(route: string): boolean {\n if (isContainedPath(route)) {\n return true;\n }\n // The only place the app's developer would learn why the move did nothing.\n // eslint-disable-next-line no-console\n console.warn(`Ghost Admin can't open the app at ${route}, so the page stays where it is.`);\n return false;\n}\n\n/**\n * Whether a `pushState` or `replaceState` URL leads to a route Admin refuses. One the URL\n * parser can't read is left to the browser, which throws as it would without the SDK.\n */\nfunction refuses(url: string | URL | null | undefined): boolean {\n if (url === undefined || url === null) {\n return false;\n }\n const next = URL.parse(url, window.location.href);\n return next !== null && next.origin === window.location.origin && !isContained(routeOf(next));\n}\n\n/**\n * Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,\n * and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's\n * entries, which left back steps that did nothing once the app's page opened again, and WebKit\n * applies Admin's replace after a frame's push to the entry before it. So the frame keeps a\n * single entry, and Admin keeps one for each of the app's moves.\n *\n * - `history.pushState` and `history.replaceState` replace the frame's entry, then report the\n * move to Admin as a push or a replace, which is how Admin records it. A move to the route the\n * page is already on isn't reported, so Admin never gets an entry that changes nothing.\n * - A click on a link to the app's own origin, which a router hasn't already handled, is reported\n * as a push, and the page then loads the link's address in place of its own entry. A link that\n * opens elsewhere (a `target`, `download`, or a modifier key) is left alone.\n * - Neither is made to a route Admin would refuse, one that isn't contained.\n * - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.\n *\n * Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the\n * fragment through `location.hash` and the Navigation API, which have added the entry before\n * any event says so.\n */\nexport function watchHistory(\n moved: (route: string, move: PathMove) => Promise<void>,\n // How the page loads a link's address in place of its own entry. Tests pass their own.\n load: (url: string) => void = (url) => window.location.replace(url),\n): HistoryWatch {\n const { history } = window;\n const { pushState, replaceState } = history;\n let route = currentRoute();\n // The state the app gave each route, so following Admin back to one gives it back.\n const states = new Map<string, unknown>([[route, history.state]]);\n\n const report = (move: PathMove) => {\n const next = currentRoute();\n states.set(next, history.state);\n if (next !== route) {\n route = next;\n void moved(next, move);\n }\n };\n\n const push: History['pushState'] = (data, unused, url) => {\n if (refuses(url)) {\n return;\n }\n replaceState.call(history, data, unused, url);\n report('push');\n };\n const replace: History['replaceState'] = (data, unused, url) => {\n if (refuses(url)) {\n return;\n }\n replaceState.call(history, data, unused, url);\n report('replace');\n };\n history.pushState = push;\n history.replaceState = replace;\n\n const onClick = (event: MouseEvent) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // Found through the event's path, which reaches into shadow roots, and read through its\n // attributes, because an SVG link has none of `HTMLAnchorElement`'s properties.\n const link = event.composedPath().find(isLink);\n const target = link?.getAttribute('target') ?? '';\n if (!link || link.hasAttribute('download') || (target !== '' && target !== '_self')) {\n return;\n }\n const url = new URL(link.getAttribute('href') as string, document.baseURI);\n if (url.origin !== window.location.origin) {\n return;\n }\n event.preventDefault();\n const go = () => load(url.href);\n const next = routeOf(url);\n if (!isContained(next)) {\n return;\n }\n if (next === route) {\n go();\n return;\n }\n route = next;\n // Admin records the move before the page leaves, so the next document starts where it is.\n moved(next, 'push').then(go, go);\n };\n document.addEventListener('click', onClick);\n\n return {\n follow(path) {\n route = path;\n const state = states.get(path) ?? null;\n replaceState.call(history, state, '', path);\n window.dispatchEvent(new PopStateEvent('popstate', { state }));\n },\n stop() {\n if (history.pushState === push) {\n history.pushState = pushState;\n }\n if (history.replaceState === replace) {\n history.replaceState = replaceState;\n }\n document.removeEventListener('click', onClick);\n },\n };\n}\n","import { TITLE_MAX_LENGTH, toPlainText } from '@tryghost/app-contracts';\n\n/**\n * Trims a title to what Admin accepts, without splitting a character in two. Admin refuses a\n * title containing a character that reorders or hides text, so the SDK drops those characters\n * rather than losing the whole title: a right-to-left title often contains a direction mark.\n */\nfunction clampTitle(title: string): string {\n const trimmed = toPlainText(title).trim();\n if (trimmed.length <= TITLE_MAX_LENGTH) {\n return trimmed;\n }\n const end = /[\\uD800-\\uDBFF]/.test(trimmed.charAt(TITLE_MAX_LENGTH - 1))\n ? TITLE_MAX_LENGTH - 1\n : TITLE_MAX_LENGTH;\n return trimmed.slice(0, end);\n}\n\n/**\n * Reports the page's title now and every time it changes, so Admin can show it as its own.\n * Returns a function that stops watching.\n *\n * A title can change in three ways, and frameworks use all three: its text is edited, its\n * element is replaced, or an element is added where there was none. Rather than distinguish\n * them, the SDK reads `document.title` after every batch of changes in `<head>` and reports it\n * only if it differs from the last one. A mutation observer already delivers each batch once,\n * in a microtask.\n */\nexport function watchTitle(report: (title: string) => void): () => void {\n let last: string | undefined;\n const check = () => {\n const title = clampTitle(document.title);\n if (title !== last) {\n last = title;\n report(title);\n }\n };\n\n check();\n const observer = new MutationObserver(check);\n observer.observe(document.head ?? document.documentElement, {\n subtree: true,\n childList: true,\n characterData: true,\n });\n return () => observer.disconnect();\n}\n","import { ThreadMessagePort } from '@quilted/threads';\nimport {\n ARGUMENT_MESSAGES,\n encodeBridgeError,\n type AppErrorCode,\n isContainedPath,\n isRecord,\n isStartContext,\n isTheme,\n type AppExports,\n type HostExports,\n type PathMove,\n type Place,\n type Theme,\n} from '@tryghost/app-contracts';\n\nimport {\n GhostAppError,\n fromHostError,\n invalidArgument,\n sessionEnded,\n unsupported,\n} from './errors.ts';\nimport { toFetchRequest, toResponse } from './fetch.ts';\nimport { currentRoute, watchHistory, type HistoryWatch } from './history.ts';\nimport { watchTitle } from './title.ts';\nimport type {\n Ghost,\n GhostFetchInit,\n GhostPath,\n Session,\n Site,\n Unsubscribe,\n User,\n} from './types.ts';\n\ntype HostCall<K extends keyof HostExports> = (\n ...args: Parameters<HostExports[K]>\n) => ReturnType<HostExports[K]>;\n\n/** Calls each listener the app registered, so that one that throws can't stop the others. */\nfunction notify<T>(listeners: ReadonlySet<(value: T) => void>, value: T) {\n for (const listener of [...listeners]) {\n try {\n listener(value);\n } catch (error) {\n // Rethrown outside the SDK, where the page's own error handling sees it.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n\n/**\n * An error that refuses one of Admin's calls. Only its message reaches Admin, so the message\n * starts with the code, as Admin's own refusals do.\n */\nfunction refusal(code: AppErrorCode, detail: string): Error {\n return new Error(encodeBridgeError(code, detail));\n}\n\n/**\n * Returns the copy of an argument that will cross the channel, or throws `invalid_argument`\n * with `message` if it can't cross. The structured clone that carries a call only refuses a\n * symbol or a DOM node once the call is in progress, and the channel would proxy a function,\n * though no argument in the bridge's calls is a function. Cloning first refuses all of these\n * before anything is sent to Admin.\n */\nfunction cloneArgument<T>(value: T, message: string): T {\n try {\n return structuredClone(value);\n } catch (error) {\n throw new GhostAppError('invalid_argument', message, { cause: error });\n }\n}\n\nfunction subscribe<T>(listeners: Set<T>, listener: T): Unsubscribe {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * The parts of Admin's start context that `start` keeps. The theme and path can change, so\n * they are stored separately.\n */\ninterface StartedContext {\n site: Site;\n user: User;\n session: Session;\n}\n\nexport interface ChannelEvents {\n /** Admin started the app, and the connection is ready for it to use. */\n started(ghost: Ghost): void;\n /** The channel ended, before or after the start. */\n ended(error: GhostAppError): void;\n}\n\n/**\n * The channel to Admin over the port Admin handed the page, and the `Ghost` object the app\n * gets once Admin has called `start`. The channel itself stays inside the SDK.\n *\n * The channel ends in three cases: when the port closes, which browsers that fire `close` on\n * a port (and Node) report when Admin closes its end or its document goes away; when a call\n * fails because the thread has closed; or when Admin rejects a call with `session_ended`.\n * After that, every call rejects with the same error.\n */\nexport class Channel {\n readonly #port: MessagePort;\n readonly #thread: ThreadMessagePort<HostExports, AppExports>;\n // What this Admin exports, from its connect message.\n readonly #hostExports: ReadonlySet<string>;\n readonly #events: ChannelEvents;\n readonly #themeListeners = new Set<(theme: Readonly<Theme>) => void>();\n readonly #pathListeners = new Set<(path: string) => void>();\n readonly #endListeners = new Set<(error: GhostAppError) => void>();\n #context: StartedContext | undefined;\n #theme: Readonly<Theme> | undefined;\n #path = '/';\n #ended: GhostAppError | undefined;\n #stopWatchingTitle: (() => void) | undefined;\n #history: HistoryWatch | undefined;\n // Counts the page's moves, so an answer to one the page has since moved on from is ignored.\n #moves = 0;\n\n constructor(port: MessagePort, hostExports: readonly string[], events: ChannelEvents) {\n this.#port = port;\n this.#hostExports = new Set(hostExports);\n this.#events = events;\n this.#thread = new ThreadMessagePort<HostExports, AppExports>(port, {\n exports: {\n start: async (context) => this.#start(context),\n themeChanged: async (theme) => this.#themeChanged(theme),\n pathChanged: async (path) => this.#pathChanged(path),\n },\n });\n port.addEventListener('close', () => this.end(sessionEnded()));\n // A message that could not be read is a call that will never be answered.\n port.addEventListener('messageerror', () => this.end(sessionEnded()));\n port.start();\n }\n\n #start(context: unknown) {\n if (this.#context) {\n return;\n }\n if (!isStartContext(context)) {\n const detail = \"Ghost started the app with a context this SDK doesn't understand\";\n // End the channel only after Admin has received the refusal, so Admin learns why instead\n // of waiting for its timeout.\n setTimeout(() => this.end(new GhostAppError('invalid_context', detail)), 0);\n throw refusal('invalid_context', detail);\n }\n this.#context = {\n site: Object.freeze({ ...context.site }),\n user: Object.freeze({ ...context.user }),\n session: Object.freeze({ ...context.session }),\n };\n this.#theme = Object.freeze({ ...context.theme });\n // Admin owns the history from here on. The page's own address is its route: Admin loads a\n // new frame at its own path, so the two differ only when the page's server redirected it or\n // a form or link loaded another page in place, and then Admin follows the page.\n this.#history = watchHistory((route, move) => this.#moved(route, move));\n const route = currentRoute();\n this.#path = context.path;\n if (route !== context.path) {\n void this.#moved(route, 'replace');\n }\n // Report the title before `start` returns, so Admin has it by the time it shows the page.\n // An older Admin without `titleChanged` keeps its own title.\n if (this.#hostExports.has('titleChanged')) {\n this.#stopWatchingTitle = watchTitle((title) => {\n this.#call('titleChanged', title).catch(() => {\n // If Admin refuses a title, it keeps showing its own.\n });\n });\n }\n this.#events.started(this.ghost);\n }\n\n #themeChanged(theme: unknown) {\n this.#assertStarted();\n if (!isTheme(theme)) {\n throw refusal('invalid_argument', \"Ghost sent a theme this SDK doesn't understand\");\n }\n this.#theme = Object.freeze({ ...theme });\n notify(this.#themeListeners, this.#theme);\n }\n\n #pathChanged(path: unknown) {\n this.#assertStarted();\n if (!isContainedPath(path)) {\n throw refusal('invalid_argument', \"Ghost sent a path this SDK doesn't understand\");\n }\n this.#path = path;\n this.#history?.follow(path);\n notify(this.#pathListeners, path);\n }\n\n /**\n * Reports a move the page made. Resolves once Admin has answered, with the path Admin now has\n * for the app, or has refused; a refused move leaves the page where it is.\n */\n async #moved(route: string, move: PathMove): Promise<void> {\n // A route that leaves the app once normalised, such as `/.//host/`, is one Admin refuses\n // and the SDK never hands out, so the app's path stays where it was.\n if (!isContainedPath(route)) {\n return;\n }\n this.#path = route;\n this.#moves += 1;\n const thisMove = this.#moves;\n try {\n const adminPath = await this.#call('pathChanged', route, move);\n // Admin's answer, rather than `route`: it's Admin's own path when Admin didn't follow\n // the move, such as when the publisher is leaving the app, and Admin then moves the page\n // back with `pathChanged`. An answer to an earlier move is out of date.\n if (thisMove === this.#moves && isContainedPath(adminPath)) {\n this.#path = adminPath;\n }\n } catch {\n // Refused, or the session ended: either way there's nothing for the page to do.\n }\n }\n\n #assertStarted() {\n if (!this.#context) {\n throw refusal('invalid_context', 'Ghost has not started the app yet');\n }\n }\n\n async #call<K extends keyof HostExports>(\n name: K,\n ...args: Parameters<HostExports[K]>\n ): Promise<Awaited<ReturnType<HostExports[K]>>> {\n if (this.#ended) {\n throw this.#ended;\n }\n if (!this.#hostExports.has(name)) {\n throw unsupported(name);\n }\n try {\n const call = this.#thread.imports[name] as HostCall<K>;\n return await call(...args);\n } catch (error) {\n if (this.#thread.closed) {\n throw this.end(sessionEnded());\n }\n const appError = fromHostError(error, name);\n if (appError.code === 'session_ended') {\n this.end(appError);\n }\n throw appError;\n }\n }\n\n /**\n * Ends the channel. Only the first call has an effect: pending and later calls reject with\n * its `error`. Returns the error the channel ended with.\n */\n end(error: GhostAppError): GhostAppError {\n if (this.#ended) {\n return this.#ended;\n }\n this.#ended = error;\n this.#stopWatchingTitle?.();\n this.#history?.stop();\n this.#thread.close();\n this.#port.close();\n this.#events.ended(error);\n notify(this.#endListeners, error);\n this.#endListeners.clear();\n return error;\n }\n\n /**\n * The `Ghost` object the app gets once `start` has set the context. It has only the members\n * its type declares, so no part of the channel, such as `end`, is reachable from the app.\n */\n readonly ghost: Ghost = this.#createGhost();\n\n #createGhost(): Ghost {\n const context = () => this.#context as StartedContext;\n const theme = () => this.#theme as Readonly<Theme>;\n const connected = () => this.#ended === undefined;\n return Object.freeze({\n get site(): Site {\n return context().site;\n },\n get user(): User {\n return context().user;\n },\n get theme(): Readonly<Theme> {\n return theme();\n },\n get session(): Session {\n return context().session;\n },\n get connected(): boolean {\n return connected();\n },\n path: this.#createPath(),\n onThemeChange: (callback: (theme: Readonly<Theme>) => void): Unsubscribe =>\n subscribe(this.#themeListeners, callback),\n onPathChange: (callback: (path: string) => void): Unsubscribe =>\n subscribe(this.#pathListeners, callback),\n onSessionEnd: (callback: (error: GhostAppError) => void): Unsubscribe =>\n this.#onSessionEnd(callback),\n fetch: (path: string, init?: GhostFetchInit): Promise<Response> => this.#fetch(path, init),\n open: (place: Place): Promise<void> => this.#open(place),\n });\n }\n\n #createPath(): GhostPath {\n const current = () => this.#path;\n return Object.freeze({\n get current(): string {\n return current();\n },\n });\n }\n\n #onSessionEnd(callback: (error: GhostAppError) => void): Unsubscribe {\n const ended = this.#ended;\n if (ended) {\n // Notify it in a microtask, as an earlier subscriber would be, unless it has\n // unsubscribed by then.\n let left = false;\n queueMicrotask(() => {\n if (!left) {\n callback(ended);\n }\n });\n return () => {\n left = true;\n };\n }\n return subscribe(this.#endListeners, callback);\n }\n\n async #fetch(path: string, init?: GhostFetchInit): Promise<Response> {\n const request = toFetchRequest(path, init);\n return toResponse(await this.#call('fetch', request));\n }\n\n async #open(place: Place): Promise<void> {\n if (!isRecord(place)) {\n throw invalidArgument(ARGUMENT_MESSAGES.place);\n }\n await this.#call('open', cloneArgument(place, ARGUMENT_MESSAGES.place));\n }\n}\n","declare const __SDK_VERSION__: string;\n\n/**\n * The SDK's version, sent in the hello for Admin's logs. The build and the tests replace\n * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`\n * and doesn't read package.json.\n */\nexport const SDK_VERSION: string = __SDK_VERSION__;\n","import {\n HELLO_MESSAGE_TYPE,\n START_TIMEOUT_MS,\n isConnectMessage,\n isRecord,\n type HelloMessage,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument } from './errors.ts';\nimport { Channel } from './session.ts';\nimport type { ConnectOptions, Ghost } from './types.ts';\nimport { SDK_VERSION } from './version.ts';\n\n/**\n * How often, in milliseconds, the SDK repeats the hello until Admin answers. Admin may only\n * start listening after the page has loaded and sent its first hello, so one hello is not\n * enough.\n */\nconst HELLO_INTERVAL = 250;\n\n/**\n * The target origin for the hello: the embedding page's origin where the browser exposes it\n * (`location.ancestorOrigins`, in Chromium and WebKit), and `'*'` elsewhere. The hello grants\n * nothing: the port goes the other way, and Admin addresses it to this page's origin only.\n * `document.referrer` doesn't work here: once the page has navigated within itself, it holds\n * the page's own origin.\n */\nfunction parentOrigin(): string {\n const origin = window.location.ancestorOrigins?.[0];\n return origin && origin !== 'null' ? origin : '*';\n}\n\n/**\n * The global key where the first copy of the SDK to connect claims the page. It is a symbol\n * from the global registry, so a second copy bundled into the same page finds the same key.\n */\nconst PAGE_CLAIM = Symbol.for('@tryghost/app-sdk');\n\n/**\n * The claim also holds the hello's `document` ID. It's made when the SDK loads, so every\n * `connect()` in a document sends the same ID, and a new document (after a reload, a form post\n * or a link) gets a new one. It's random rather than `performance.timeOrigin`, which some\n * privacy-focused browsers round to 16–100 ms, so two documents loaded in quick succession\n * could share it. `Math.random` is enough here, and unlike `crypto.randomUUID` it works on the\n * plain HTTP origins apps use in development.\n */\nconst thisCopy = Object.freeze({\n sdk: SDK_VERSION,\n document: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,\n});\n\n/** Claims the page for this copy of the SDK unless another copy has. Returns whether it did. */\nfunction claimPage(): boolean {\n const page = globalThis as unknown as Record<symbol, unknown>;\n page[PAGE_CLAIM] ??= thisCopy;\n return page[PAGE_CLAIM] === thisCopy;\n}\n\n/**\n * The longest delay `setTimeout` supports. It treats anything longer as 0, so the timeout\n * would fire immediately.\n */\nconst TIMEOUT_MAX = 2 ** 31 - 1;\n\nfunction handshake(\n options: ConnectOptions,\n onEnded: (error: GhostAppError) => void,\n): Promise<Ghost> {\n if (!isRecord(options)) {\n return Promise.reject(invalidArgument('Expected options such as { timeout: 10000 }'));\n }\n // By default, wait as long as Admin gives the page. Waiting longer would mean waiting on a\n // frame Admin has already given up on.\n const { timeout = START_TIMEOUT_MS } = options;\n if (typeof timeout !== 'number' || !(timeout > 0) || !(timeout <= TIMEOUT_MAX)) {\n return Promise.reject(\n invalidArgument(`Expected a timeout in milliseconds, above 0 and at most ${TIMEOUT_MAX}`),\n );\n }\n if (typeof window === 'undefined' || window.parent === window) {\n return Promise.reject(\n new GhostAppError('not_framed', 'This page is not open inside Ghost Admin'),\n );\n }\n\n const parent = window.parent;\n const targetOrigin = parentOrigin();\n\n return new Promise<Ghost>((resolve, reject) => {\n const stopWaiting = () => {\n clearInterval(helloTimer);\n clearTimeout(timeoutTimer);\n window.removeEventListener('message', onMessage);\n };\n\n // A promise ignores `reject` once it has settled, so a failure after `started` changes\n // nothing.\n const fail = (error: GhostAppError) => {\n stopWaiting();\n reject(error);\n };\n\n // The channel is bound to the first valid answer from the parent window. The listener is\n // removed as soon as that answer arrives, so later answers are ignored.\n const onMessage = (event: MessageEvent) => {\n const port = event.ports?.[0];\n if (\n event.source !== parent ||\n !isConnectMessage(event.data) ||\n !port ||\n (targetOrigin !== '*' && event.origin !== targetOrigin)\n ) {\n return;\n }\n clearInterval(helloTimer);\n window.removeEventListener('message', onMessage);\n channel = new Channel(port, event.data.exports, {\n started: (ghost) => {\n stopWaiting();\n resolve(ghost);\n },\n ended: (error) => {\n fail(error);\n onEnded(error);\n },\n });\n };\n\n const hello: HelloMessage = {\n type: HELLO_MESSAGE_TYPE,\n sdk: SDK_VERSION,\n document: thisCopy.document,\n };\n const sayHello = () => {\n parent.postMessage(hello, targetOrigin);\n };\n\n let channel: Channel | undefined;\n window.addEventListener('message', onMessage);\n sayHello();\n const helloTimer = setInterval(sayHello, HELLO_INTERVAL);\n const timeoutTimer = setTimeout(() => {\n const error = new GhostAppError('not_connected', 'Ghost Admin did not start the app in time');\n fail(error);\n channel?.end(error);\n }, timeout);\n });\n}\n\nlet connecting: Promise<Ghost> | undefined;\n// The error the page's connection ended with, after Admin answered it. Admin answers each\n// document only once, so this connection was the page's only one.\nlet spent: GhostAppError | undefined;\n\n// Forgets an attempt only if it is still the shared one: an attempt that ended may report\n// that after a newer attempt has started.\nfunction forget(attempt: Promise<Ghost>) {\n if (connecting === attempt) {\n connecting = undefined;\n }\n}\n\n/**\n * Connects to Ghost Admin, which must frame the page, and resolves once Admin has started the\n * app. Safe to call as soon as the page loads.\n *\n * Every call shares one connection, and the first call's options apply. Only one copy of the\n * SDK in a page can connect. Any other copy rejects with `duplicate_sdk`. Admin answers each\n * document only once, so after it answers, that connection is the page's only one. Once it\n * fails or its session ends, every call rejects with the error it ended with, and only a new\n * document (after a reload, for example) can connect again. A failure before Admin answered,\n * such as a bad option or a timeout, can be retried.\n */\nexport function connect(options: ConnectOptions = {}): Promise<Ghost> {\n // Two copies would both send a hello for the same document, and Admin answers each document\n // only once.\n if (!claimPage()) {\n return Promise.reject(\n new GhostAppError(\n 'duplicate_sdk',\n 'This page loads the app SDK more than once; load one copy, which every part of the page shares',\n ),\n );\n }\n if (spent) {\n return Promise.reject(spent);\n }\n if (!connecting) {\n const attempt: Promise<Ghost> = handshake(options, (error) => {\n spent = error;\n forget(attempt);\n }).catch((error: unknown) => {\n forget(attempt);\n throw error;\n });\n connecting = attempt;\n }\n return connecting;\n}\n"],"mappings":";;;;AAiCA,IAAa,gBAAb,cAAmC,MAAM;CACvC;CAEA,YAAY,MAAyB,SAAiB,SAAwB;EAC5E,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;;;AAMA,SAAgB,cAAc,OAAgB,WAAkC;CAC9E,MAAM,UACJ,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,QACxD,OAAO,MAAM,OAAO,IACpB,KAAA;CACN,IAAI,YAAY,KAAA,GACd,OAAO,IAAI,cAAc,YAAY,iBAAiB,aAAa,EAAE,OAAO,MAAM,CAAC;CAGrF,MAAM,QAAQ,kBAAkB,SAAS,gBAAgB;CACzD,IAAI,OACF,OAAO,IAAI,cAAc,MAAM,MAAM,MAAM,QAAQ,EAAE,OAAO,MAAM,CAAC;CAErE,OAAO,IAAI,cAAc,YAAY,SAAS,EAAE,OAAO,MAAM,CAAC;AAChE;AAEA,SAAgB,gBAAgB,SAAgC;CAC9D,OAAO,IAAI,cAAc,oBAAoB,OAAO;AACtD;AAEA,SAAgB,YAAY,SAAgC;CAC1D,OAAO,IAAI,cAAc,gBAAgB,OAAO;AAClD;AAEA,SAAgB,YAAY,WAAkC;CAC5D,OAAO,IAAI,cAAc,eAAe,qCAAqC,UAAU,KAAK;AAC9F;AAEA,SAAgB,eAA8B;CAC5C,OAAO,IAAI,cAAc,iBAA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AC5B,CAAC,QACA,iBAAiB,OAAO,MAAM,WAAW,cAE1C;GAEF,cAAc,UAAU;GACxB,OAAO,oBAAoB,WAAW,SAAS;GAC/C,UAAU,IAAI,QAAQ,MAAM,MAAM,KAAK,SAAS;IAC9C,UAAU,UAAU;KAClB,YAAY;KACZ,QAAQ,KAAK;IACf;IACA,QAAQ,UAAU;KAChB,KAAK,KAAK;KACV,QAAQ,KAAK;IACf;GACF,CAAC;EACH;EAEA,MAAM,QAAsB;GAC1B,MAAM;GACN,KAAK;GACL,UAAU,SAAS;EACrB;EACA,MAAM,iBAAiB;GACrB,OAAO,YAAY,OAAO,YAAY;EACxC;EAEA,IAAI;EACJ,OAAO,iBAAiB,WAAW,SAAS;EAC5C,SAAS;EACT,MAAM,aAAa,YAAY,UAAU,cAAc;EACvD,MAAM,eAAe,iBAAiB;GACpC,MAAM,QAAQ,IAAI,cAAc,iBAAiB,2CAA2C;GAC5F,KAAK,KAAK;GACV,SAAS,IAAI,KAAK;EACpB,GAAG,OAAO;CACZ,CAAC;AACH;AAEA,IAAI;AAGJ,IAAI;AAIJ,SAAS,OAAO,SAAyB;CACvC,IAAI,eAAe,SACjB,aAAa,KAAA;AAEjB;;;;;;;;;;;;AAaA,SAAgB,QAAQ,UAA0B,CAAC,GAAmB;CAGpE,IAAI,CAAC,UAAU,GACb,OAAO,QAAQ,OACb,IAAI,cACF,iBACA,gGACF,CACF;CAEF,IAAI,OACF,OAAO,QAAQ,OAAO,KAAK;CAE7B,IAAI,CAAC,YAAY;EACf,MAAM,UAA0B,UAAU,UAAU,UAAU;GAC5D,QAAQ;GACR,OAAO,OAAO;EAChB,CAAC,CAAC,CAAC,OAAO,UAAmB;GAC3B,OAAO,OAAO;GACd,MAAM;EACR,CAAC;EACD,aAAa;CACf;CACA,OAAO;AACT"}
|
package/dist/app-sdk.js
CHANGED
|
@@ -1218,7 +1218,7 @@ var Channel = class {
|
|
|
1218
1218
|
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
1219
1219
|
* and doesn't read package.json.
|
|
1220
1220
|
*/
|
|
1221
|
-
var SDK_VERSION = "0.1.0-alpha.
|
|
1221
|
+
var SDK_VERSION = "0.1.0-alpha.12";
|
|
1222
1222
|
//#endregion
|
|
1223
1223
|
//#region src/connect.ts
|
|
1224
1224
|
/**
|
|
@@ -1328,7 +1328,7 @@ function forget(attempt) {
|
|
|
1328
1328
|
* app. Safe to call as soon as the page loads.
|
|
1329
1329
|
*
|
|
1330
1330
|
* Every call shares one connection, and the first call's options apply. Only one copy of the
|
|
1331
|
-
* SDK in a page can connect
|
|
1331
|
+
* SDK in a page can connect. Any other copy rejects with `duplicate_sdk`. Admin answers each
|
|
1332
1332
|
* document only once, so after it answers, that connection is the page's only one. Once it
|
|
1333
1333
|
* fails or its session ends, every call rejects with the error it ended with, and only a new
|
|
1334
1334
|
* document (after a reload, for example) can connect again. A failure before Admin answered,
|