@tryghost/app-sdk 0.1.0-alpha.10 → 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/backend.d.ts +1 -1
- package/build/backend.js +2 -1
- package/build/backend.js.map +1 -1
- package/build/bin.js +1 -2
- package/build/bin.js.map +1 -1
- package/build/chunks/manifest-BO_hJDEK.js +21 -0
- package/build/chunks/manifest-BO_hJDEK.js.map +1 -0
- package/build/chunks/{manifest-DFLCKcwH.d.ts → manifest-CYA0krtI.d.ts} +1 -3
- package/build/chunks/parse-C6hK3wRD.js +17 -0
- package/build/chunks/parse-C6hK3wRD.js.map +1 -0
- package/build/chunks/{sign-Deg9TCUr.js → sign-3ysEUyYt.js} +25 -10
- package/build/chunks/sign-3ysEUyYt.js.map +1 -0
- package/build/index.d.ts +28 -27
- package/build/index.js +2 -2
- package/build/index.js.map +1 -1
- package/build/tooling.d.ts +3 -1
- package/build/tooling.js +1 -2
- package/build/vite.js +3 -2
- package/build/vite.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/chunks/manifest-B9vQoSfm.js +0 -43
- package/build/chunks/manifest-B9vQoSfm.js.map +0 -1
- package/build/chunks/sign-Deg9TCUr.js.map +0 -1
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(attemp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1B,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"}
|
|
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,c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O,OAAO;EAChB,CAAC,CAAC,CAAC,OAAO,UAAmB;GAC3B,OAAO,OAAO;GACd,MAAM;EACR,CAAC;EACD,aAAa;CACf;CACA,OAAO;AACT"}
|
package/build/tooling.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as ManifestError, r as SignedManifest } from "./chunks/manifest-CYA0krtI.js";
|
|
2
2
|
//#region src/tooling/keys.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Which keys to use. Development and production have separate identity keys, so an app
|
|
@@ -135,6 +135,8 @@ type SignResult = {
|
|
|
135
135
|
* with the identity key, unless Ghost would refuse it.
|
|
136
136
|
*/
|
|
137
137
|
declare function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult>;
|
|
138
|
+
/** A manifest's problems, one per line, as `path: message`, as Ghost lists them. */
|
|
139
|
+
declare function formatErrors(errors: readonly ManifestError[]): string;
|
|
138
140
|
/** Reads `ghost-app.json`, or another readable manifest, as JSON. */
|
|
139
141
|
declare function readManifestSource(file: string): Promise<unknown>;
|
|
140
142
|
interface SignProjectOptions extends ReadKeysOptions {
|
package/build/tooling.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { r as formatErrors } from "./chunks/manifest-B9vQoSfm.js";
|
|
1
|
+
import { a as signAppManifest, c as IDENTITY_KEY_VARIABLE, d as createKeys, f as generateKey, g as readSigningKeys, h as readBackendKey, l as KEYS_DIRECTORY, m as publicKeyOf, n as formatErrors, o as signProject, p as keyFile, r as readManifestSource, s as BACKEND_KEY_VARIABLE, t as MANIFEST_FILE } from "./chunks/sign-3ysEUyYt.js";
|
|
3
2
|
export { BACKEND_KEY_VARIABLE, IDENTITY_KEY_VARIABLE, KEYS_DIRECTORY, MANIFEST_FILE, createKeys, formatErrors, generateKey, keyFile, publicKeyOf, readBackendKey, readManifestSource, readSigningKeys, signAppManifest, signProject };
|
package/build/vite.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { _ as
|
|
2
|
-
import {
|
|
1
|
+
import { _ as signingKeySource, b as isLocalhost, c as IDENTITY_KEY_VARIABLE, d as createKeys, h as readBackendKey, i as serialiseSigned, l as KEYS_DIRECTORY, n as formatErrors, o as signProject, p as keyFile, s as BACKEND_KEY_VARIABLE, v as parseJsonText, y as isValidAppId } from "./chunks/sign-3ysEUyYt.js";
|
|
2
|
+
import { t as MANIFEST_PATH } from "./chunks/manifest-BO_hJDEK.js";
|
|
3
|
+
import { t as parseOrigin } from "./chunks/parse-C6hK3wRD.js";
|
|
3
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
4
5
|
import { appendFile, readFile } from "node:fs/promises";
|
|
5
6
|
import { join, resolve } from "node:path";
|
package/build/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite/deny.ts","../src/vite/dev-vars.ts","../src/vite/index.ts"],"sourcesContent":["// What Vite denies when a project names nothing to deny, as of Vite 8. A project's own list\n// replaces these rather than adding to them, and Vite compiles the list before any plugin sees\n// the resolved config, so the plugin adds them again alongside the keys. The tests compare it\n// with what the installed Vite resolves.\nexport const VITE_DEFAULT_DENY = [\n '.env',\n '.env.*',\n '*.{crt,pem,key,p12,pfx,cer,der}',\n '.npmrc',\n '.yarnrc.yml',\n '**/.git/**',\n];\n\n// The private keys, and `.dev.vars`, which holds the development backend key. Vite serves the\n// project's root, so without these anyone who can reach the dev server, through a tunnel too,\n// could read them as files, through `/@fs/` or as imports. `.env` files are denied even when a\n// project's own list leaves them out, as the plugin may tell a Workers project to put the\n// development backend key in one.\nexport const DENY = ['**/.ghost-app/**', '.dev.vars*', '.env', '.env.*'];\n","import { existsSync } from 'node:fs';\nimport { appendFile, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { BACKEND_KEY_VARIABLE, keyFile, readBackendKey } from '../tooling/keys.ts';\n\nconst WRANGLER_CONFIGS = ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'];\n\nconst DEV_VARS = '.dev.vars';\n\n/**\n * Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as\n * `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development\n * as it does in production. Returns what to tell the developer, if anything.\n */\nexport async function provideDevBackendKey(\n root: string,\n): Promise<{ level: 'info' | 'warn'; message: string } | undefined> {\n const there = (file: string) => existsSync(join(root, file));\n if (!WRANGLER_CONFIGS.some(there)) {\n return undefined;\n }\n const key = await readBackendKey({ root, mode: 'development' });\n // Wrangler reads `.env` and `.env.local` only when there's no `.dev.vars`, so creating one\n // would hide what they set.\n const read = there(DEV_VARS) ? [DEV_VARS] : ['.env.local', '.env'].filter(there);\n let last = '';\n for (const file of read) {\n last = await readFile(join(root, file), 'utf8');\n if (last.includes(BACKEND_KEY_VARIABLE)) {\n // The public half is enough to tell one key from another.\n return last.includes(key.x)\n ? undefined\n : {\n level: 'warn',\n message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile('development', 'backend')}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`,\n };\n }\n }\n if (read.length > 0 && read[0] !== DEV_VARS) {\n return {\n level: 'warn',\n message: `Wrangler reads ${read.join(' and ')} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \\`ghost-app backend-key\\`, so the Worker can answer Ghost's challenge.`,\n };\n }\n // Single quotes keep the JSON as it is.\n const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\\n`;\n await appendFile(join(root, DEV_VARS), `${last && !last.endsWith('\\n') ? '\\n' : ''}${line}`, {\n mode: 0o600,\n });\n return {\n level: 'info',\n message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`,\n };\n}\n","/**\n * A Vite plugin that serves and builds an app's signed manifest.\n *\n * ```ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { ghostApp } from '@tryghost/app-sdk/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({ plugins: [ghostApp(), cloudflare()] });\n * ```\n */\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { isLocalhost, isValidAppId } from '@tryghost/app-contracts';\nimport type { Plugin, ResolvedConfig } from 'vite';\n\nimport {\n BACKEND_KEY_VARIABLE,\n IDENTITY_KEY_VARIABLE,\n KEYS_DIRECTORY,\n createKeys,\n signingKeySource,\n} from '../tooling/keys.ts';\nimport { MANIFEST_PATH, formatErrors } from '../shared/manifest.ts';\nimport { parseJsonText, parseOrigin } from '../shared/parse.ts';\nimport { MANIFEST_FILE, serialiseSigned, signProject } from '../tooling/sign.ts';\nimport { DENY, VITE_DEFAULT_DENY } from './deny.ts';\nimport { provideDevBackendKey } from './dev-vars.ts';\n\nexport interface GhostAppOptions {\n /** The readable manifest, relative to Vite's root. `ghost-app.json` by default. */\n manifest?: string;\n /**\n * The public addresses of tunnels to the dev server, such as\n * `https://example.trycloudflare.com`, which `vite dev` also signs the manifest for. Read from\n * `GHOST_APP_TUNNEL_URL` (comma-separated) by default, in the environment or the mode's `.env`\n * files.\n */\n tunnelUrl?: string | readonly string[];\n}\n\nfunction readTunnels(input: string | readonly string[] | undefined): string[] {\n const entries = typeof input === 'string' ? input.split(',') : (input ?? []);\n return entries\n .map((entry) => entry.trim())\n .filter(Boolean)\n .map((entry) => {\n const origin = parseOrigin(entry);\n if (!origin) {\n throw new Error(\n `ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`,\n );\n }\n return origin;\n });\n}\n\n/**\n * The name `vite dev` prints the app at, such as `hello-world.localhost` for\n * `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.\n */\nfunction devHostname(manifestFile: string): string {\n try {\n const { id } = parseJsonText(readFileSync(manifestFile, 'utf8')) as { id?: unknown };\n if (isValidAppId(id)) {\n return `${id.slice(id.lastIndexOf('.') + 1)}.localhost`;\n }\n } catch {\n // Signing says what's wrong when the manifest is requested.\n }\n return 'app.localhost';\n}\n\n/**\n * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build\n * emits it:\n *\n * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves\n * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one\n * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development\n * backend key to `.dev.vars`.\n * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the\n * client build.\n *\n * List it before `cloudflare()`.\n */\nexport function ghostApp(options: GhostAppOptions = {}): Plugin {\n const manifestFile = options.manifest ?? MANIFEST_FILE;\n let tunnels: string[] = [];\n let appUrl: string | undefined;\n let ghostUrl: string | undefined;\n let config: ResolvedConfig;\n let pending: { level: 'info' | 'warn'; message: string } | undefined;\n // Whether this is `vite dev`, not a build, `vite preview` or Vitest loading the config.\n let dev = false;\n\n /** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */\n function manifestUrlFor(host: string | undefined): string | undefined {\n const url = URL.parse(`${config.server.https ? 'https' : 'http'}://${host ?? ''}`);\n const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);\n if (tunnel) {\n return `${tunnel}${MANIFEST_PATH}`;\n }\n // Signing for any other host would let anyone pass for the app.\n return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : undefined;\n }\n\n return {\n name: '@tryghost/app-sdk/vite',\n // Before Cloudflare's plugin, so the keys and `.dev.vars` exist before it starts the Worker,\n // and the manifest route comes before the Worker and Vite's own file serving.\n enforce: 'pre',\n\n async config(userConfig, { command, isPreview, mode }) {\n const root = resolve(userConfig.root ?? '');\n // Imported here, as Vite is an optional peer dependency. The environment wins over files.\n const { loadEnv } = await import('vite');\n const env =\n userConfig.envDir === false\n ? process.env\n : // By name, as every `GHOST_` variable would include the private keys CI signs with.\n loadEnv(mode, resolve(root, userConfig.envDir ?? ''), [\n 'GHOST_APP_URL',\n 'GHOST_APP_TUNNEL_URL',\n 'GHOST_URL',\n ]);\n appUrl = env.GHOST_APP_URL?.trim() || undefined;\n ghostUrl = env.GHOST_URL?.trim() || undefined;\n if (command !== 'serve' || isPreview) {\n return undefined;\n }\n tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);\n // Vitest loads the project's Vite config as a dev server, which shouldn't create keys.\n dev = !process.env.VITEST && mode !== 'test';\n if (dev) {\n await createKeys({ root, mode: 'development' });\n pending = await provideDevBackendKey(root);\n }\n return {\n server: {\n // A plugin's list replaces Vite's defaults when the project has none, so they're added.\n fs: { deny: [...(userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY), ...DENY] },\n ...(tunnels.length > 0 && userConfig.server?.allowedHosts !== true\n ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) }\n : {}),\n },\n };\n },\n\n configResolved(resolved) {\n config = resolved;\n // Vite gives client code every variable that starts with an env prefix.\n const exposed = [resolved.envPrefix ?? 'VITE_']\n .flat()\n .find((prefix) =>\n [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)),\n );\n if (exposed !== undefined) {\n throw new Error(\n `ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`,\n );\n }\n // Vite checks `server.fs.deny` only with `fs.strict` on.\n if (dev && !resolved.server.fs.strict) {\n throw new Error(\n `ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`,\n );\n }\n if (pending) {\n config.logger[pending.level](`ghost-app: ${pending.message}`);\n }\n },\n\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.split('?')[0] !== MANIFEST_PATH || !['GET', 'HEAD'].includes(req.method!)) {\n next();\n return;\n }\n // HTTP/2, which Vite serves with server.https, names the host in `:authority`.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined);\n const manifestUrl = manifestUrlFor(host);\n if (!manifestUrl) {\n const allowed = ['this machine', ...tunnels.map((origin) => new URL(origin).host)];\n res.statusCode = 421;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(\n `The dev server signs ghost-app.json only for ${allowed.join(', ')}, not ${host ?? 'a request without a Host'}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\\n`,\n );\n return;\n }\n signProject({ root: config.root, mode: 'development', manifestUrl, manifestFile })\n .then((result) => {\n if (!result.success) {\n throw new Error(`${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n }\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(req.method === 'HEAD' ? undefined : serialiseSigned(result.signed));\n })\n .catch((error: unknown) => {\n const message = `ghost-app: ${(error as Error).message}`;\n config.logger.error(message, { timestamp: true });\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(`${message}\\n`);\n });\n });\n\n const printUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n printUrls();\n const address = server.httpServer?.address();\n const port = typeof address === 'object' && address ? address.port : undefined;\n const scheme = config.server.https ? 'https' : 'http';\n const local = `${scheme}://${devHostname(resolve(config.root, manifestFile))}:${port}`;\n const ghost = (ghostUrl ?? 'http://localhost:2368').replace(/\\/+$/, '');\n const lines = [...(port ? [local] : []), ...tunnels].flatMap((origin) => [\n ` Ghost app: ${origin}${MANIFEST_PATH}`,\n ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`,\n ]);\n config.logger.info(`\\n${lines.join('\\n')}\\n`);\n };\n },\n\n async buildStart() {\n if (config.command !== 'build' || this.environment.config.consumer !== 'client') {\n return;\n }\n if (!appUrl) {\n config.logger.warn(\n `ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`,\n );\n return;\n }\n const base = URL.parse(appUrl.endsWith('/') ? appUrl : `${appUrl}/`);\n // A query or fragment would swallow the manifest's path.\n if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) {\n this.error(\n `ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`,\n );\n }\n const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;\n // So `vite build --watch` signs it again when it changes.\n this.addWatchFile(resolve(config.root, manifestFile));\n const result = await signProject({\n root: config.root,\n mode: 'production',\n manifestUrl,\n manifestFile,\n }).catch((error: unknown) => this.error(`ghost-app: ${(error as Error).message}`));\n if (!result.success) {\n this.error(\n `ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\\n${formatErrors(result.errors)}`,\n );\n }\n this.emitFile({\n type: 'asset',\n fileName: MANIFEST_PATH.slice(1),\n source: serialiseSigned(result.signed),\n });\n config.logger.info(\n `ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource('production', 'identity')}`,\n );\n },\n };\n}\n"],"mappings":";;;;;;AAIA,IAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;AACF;AAOA,IAAa,OAAO;CAAC;CAAoB;CAAc;CAAQ;AAAQ;;;ACZvE,IAAM,mBAAmB;CAAC;CAAiB;CAAkB;AAAe;AAE5E,IAAM,WAAW;;;;;;AAOjB,eAAsB,qBACpB,MACkE;CAClE,MAAM,SAAS,SAAiB,WAAW,KAAK,MAAM,IAAI,CAAC;CAC3D,IAAI,CAAC,iBAAiB,KAAK,KAAK,GAC9B;CAEF,MAAM,MAAM,MAAM,eAAe;EAAE;EAAM,MAAM;CAAc,CAAC;CAG9D,MAAM,OAAO,MAAM,QAAQ,IAAI,CAAC,QAAQ,IAAI,CAAC,cAAc,MAAM,CAAC,CAAC,OAAO,KAAK;CAC/E,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,MAAM;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,MAAM,OAAO,SAAS,GAAG,IAAI,SAAS,GAAG,OAAO,EAAE;GAEnE,IAAI,CAAC,QAAQ,CAAC,YAAY,KAAK,KAAK,QAAQ,KAAK,OAAO,KAAK,MAAM,GACjE,KAAK,MACH,mGAAmG,QACrG;GAEF,MAAM,cAAc,IAAI,IAAI,cAAc,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;GAE1D,KAAK,aAAa,QAAQ,OAAO,MAAM,YAAY,CAAC;GACpD,MAAM,SAAS,MAAM,YAAY;IAC/B,MAAM,OAAO;IACb,MAAM;IACN;IACA;GACF,CAAC,CAAC,CAAC,OAAO,UAAmB,KAAK,MAAM,cAAe,MAAgB,SAAS,CAAC;GACjF,IAAI,CAAC,OAAO,SACV,KAAK,MACH,cAAc,aAAa,uBAAuB,YAAY,KAAK,aAAa,OAAO,MAAM,GAC/F;GAEF,KAAK,SAAS;IACZ,MAAM;IACN,UAAU,cAAc,MAAM,CAAC;IAC/B,QAAQ,gBAAgB,OAAO,MAAM;GACvC,CAAC;GACD,OAAO,OAAO,KACZ,wCAAwC,YAAY,QAAQ,iBAAiB,cAAc,UAAU,GACvG;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite/deny.ts","../src/vite/dev-vars.ts","../src/vite/index.ts"],"sourcesContent":["// What Vite denies when a project names nothing to deny, as of Vite 8. A project's own list\n// replaces these rather than adding to them, and Vite compiles the list before any plugin sees\n// the resolved config, so the plugin adds them again alongside the keys. The tests compare it\n// with what the installed Vite resolves.\nexport const VITE_DEFAULT_DENY = [\n '.env',\n '.env.*',\n '*.{crt,pem,key,p12,pfx,cer,der}',\n '.npmrc',\n '.yarnrc.yml',\n '**/.git/**',\n];\n\n// The private keys, and `.dev.vars`, which holds the development backend key. Vite serves the\n// project's root, so without these anyone who can reach the dev server, through a tunnel too,\n// could read them as files, through `/@fs/` or as imports. `.env` files are denied even when a\n// project's own list leaves them out, as the plugin may tell a Workers project to put the\n// development backend key in one.\nexport const DENY = ['**/.ghost-app/**', '.dev.vars*', '.env', '.env.*'];\n","import { existsSync } from 'node:fs';\nimport { appendFile, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { BACKEND_KEY_VARIABLE, keyFile, readBackendKey } from '../tooling/keys.ts';\n\nconst WRANGLER_CONFIGS = ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'];\n\nconst DEV_VARS = '.dev.vars';\n\n/**\n * Gives a Cloudflare Workers project's backend the development backend key in `vite dev`, as\n * `GHOST_APP_BACKEND_KEY` in `.dev.vars`, so the Worker answers Ghost's challenge in development\n * as it does in production. Returns what to tell the developer, if anything.\n */\nexport async function provideDevBackendKey(\n root: string,\n): Promise<{ level: 'info' | 'warn'; message: string } | undefined> {\n const there = (file: string) => existsSync(join(root, file));\n if (!WRANGLER_CONFIGS.some(there)) {\n return undefined;\n }\n const key = await readBackendKey({ root, mode: 'development' });\n // Wrangler reads `.env` and `.env.local` only when there's no `.dev.vars`, so creating one\n // would hide what they set.\n const read = there(DEV_VARS) ? [DEV_VARS] : ['.env.local', '.env'].filter(there);\n let last = '';\n for (const file of read) {\n last = await readFile(join(root, file), 'utf8');\n if (last.includes(BACKEND_KEY_VARIABLE)) {\n // The public half is enough to tell one key from another.\n return last.includes(key.x)\n ? undefined\n : {\n level: 'warn',\n message: `${file} has a ${BACKEND_KEY_VARIABLE} that isn't the key in ${keyFile('development', 'backend')}, so the Worker's answers to Ghost's challenge won't match the manifest the dev server signs. Remove that line from ${file} and restart.`,\n };\n }\n }\n if (read.length > 0 && read[0] !== DEV_VARS) {\n return {\n level: 'warn',\n message: `Wrangler reads ${read.join(' and ')} when there's no ${DEV_VARS}, so add ${BACKEND_KEY_VARIABLE} to .env.local, set to the output of \\`ghost-app backend-key\\`, so the Worker can answer Ghost's challenge.`,\n };\n }\n // Single quotes keep the JSON as it is.\n const line = `${BACKEND_KEY_VARIABLE}='${JSON.stringify(key)}'\\n`;\n await appendFile(join(root, DEV_VARS), `${last && !last.endsWith('\\n') ? '\\n' : ''}${line}`, {\n mode: 0o600,\n });\n return {\n level: 'info',\n message: `Added ${BACKEND_KEY_VARIABLE} to ${DEV_VARS}, with the development backend key`,\n };\n}\n","/**\n * A Vite plugin that serves and builds an app's signed manifest.\n *\n * ```ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { ghostApp } from '@tryghost/app-sdk/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({ plugins: [ghostApp(), cloudflare()] });\n * ```\n */\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { isLocalhost, isValidAppId } from '@tryghost/app-contracts';\nimport { parseJsonText } from '@tryghost/app-contracts/identity';\nimport type { Plugin, ResolvedConfig } from 'vite';\n\nimport {\n BACKEND_KEY_VARIABLE,\n IDENTITY_KEY_VARIABLE,\n KEYS_DIRECTORY,\n createKeys,\n signingKeySource,\n} from '../tooling/keys.ts';\nimport { MANIFEST_PATH } from '../shared/manifest.ts';\nimport { parseOrigin } from '../shared/parse.ts';\nimport { MANIFEST_FILE, formatErrors, serialiseSigned, signProject } from '../tooling/sign.ts';\nimport { DENY, VITE_DEFAULT_DENY } from './deny.ts';\nimport { provideDevBackendKey } from './dev-vars.ts';\n\nexport interface GhostAppOptions {\n /** The readable manifest, relative to Vite's root. `ghost-app.json` by default. */\n manifest?: string;\n /**\n * The public addresses of tunnels to the dev server, such as\n * `https://example.trycloudflare.com`, which `vite dev` also signs the manifest for. Read from\n * `GHOST_APP_TUNNEL_URL` (comma-separated) by default, in the environment or the mode's `.env`\n * files.\n */\n tunnelUrl?: string | readonly string[];\n}\n\nfunction readTunnels(input: string | readonly string[] | undefined): string[] {\n const entries = typeof input === 'string' ? input.split(',') : (input ?? []);\n return entries\n .map((entry) => entry.trim())\n .filter(Boolean)\n .map((entry) => {\n const origin = parseOrigin(entry);\n if (!origin) {\n throw new Error(\n `ghost-app: expected a tunnel's address such as https://example.trycloudflare.com, not ${entry}`,\n );\n }\n return origin;\n });\n}\n\n/**\n * The name `vite dev` prints the app at, such as `hello-world.localhost` for\n * `org.ghost.hello-world`, as Ghost on `localhost` refuses an app on its own host.\n */\nfunction devHostname(manifestFile: string): string {\n try {\n const { id } = parseJsonText(readFileSync(manifestFile, 'utf8')) as { id?: unknown };\n if (isValidAppId(id)) {\n return `${id.slice(id.lastIndexOf('.') + 1)}.localhost`;\n }\n } catch {\n // Signing says what's wrong when the manifest is requested.\n }\n return 'app.localhost';\n}\n\n/**\n * Signs `ghost-app.json` with the app's keys, as the dev server serves it and as the build\n * emits it:\n *\n * - `vite dev` creates the development keys in `.ghost-app/` on its first run, and serves\n * `/ghost-app.json` signed for the address it's requested at: a name for this machine, or one\n * of the tunnels it's told about. In a Cloudflare Workers project, it adds the development\n * backend key to `.dev.vars`.\n * - `vite build` signs it for `GHOST_APP_URL` with the production keys, and emits it with the\n * client build.\n *\n * List it before `cloudflare()`.\n */\nexport function ghostApp(options: GhostAppOptions = {}): Plugin {\n const manifestFile = options.manifest ?? MANIFEST_FILE;\n let tunnels: string[] = [];\n let appUrl: string | undefined;\n let ghostUrl: string | undefined;\n let config: ResolvedConfig;\n let pending: { level: 'info' | 'warn'; message: string } | undefined;\n // Whether this is `vite dev`, not a build, `vite preview` or Vitest loading the config.\n let dev = false;\n\n /** The manifest URL to sign for a request's Host, or `undefined` if it isn't one of ours. */\n function manifestUrlFor(host: string | undefined): string | undefined {\n const url = URL.parse(`${config.server.https ? 'https' : 'http'}://${host ?? ''}`);\n const tunnel = tunnels.find((origin) => new URL(origin).host === url?.host);\n if (tunnel) {\n return `${tunnel}${MANIFEST_PATH}`;\n }\n // Signing for any other host would let anyone pass for the app.\n return url && isLocalhost(url.hostname) ? `${url.origin}${MANIFEST_PATH}` : undefined;\n }\n\n return {\n name: '@tryghost/app-sdk/vite',\n // Before Cloudflare's plugin, so the keys and `.dev.vars` exist before it starts the Worker,\n // and the manifest route comes before the Worker and Vite's own file serving.\n enforce: 'pre',\n\n async config(userConfig, { command, isPreview, mode }) {\n const root = resolve(userConfig.root ?? '');\n // Imported here, as Vite is an optional peer dependency. The environment wins over files.\n const { loadEnv } = await import('vite');\n const env =\n userConfig.envDir === false\n ? process.env\n : // By name, as every `GHOST_` variable would include the private keys CI signs with.\n loadEnv(mode, resolve(root, userConfig.envDir ?? ''), [\n 'GHOST_APP_URL',\n 'GHOST_APP_TUNNEL_URL',\n 'GHOST_URL',\n ]);\n appUrl = env.GHOST_APP_URL?.trim() || undefined;\n ghostUrl = env.GHOST_URL?.trim() || undefined;\n if (command !== 'serve' || isPreview) {\n return undefined;\n }\n tunnels = readTunnels(options.tunnelUrl ?? env.GHOST_APP_TUNNEL_URL);\n // Vitest loads the project's Vite config as a dev server, which shouldn't create keys.\n dev = !process.env.VITEST && mode !== 'test';\n if (dev) {\n await createKeys({ root, mode: 'development' });\n pending = await provideDevBackendKey(root);\n }\n return {\n server: {\n // A plugin's list replaces Vite's defaults when the project has none, so they're added.\n fs: { deny: [...(userConfig.server?.fs?.deny ? [] : VITE_DEFAULT_DENY), ...DENY] },\n ...(tunnels.length > 0 && userConfig.server?.allowedHosts !== true\n ? { allowedHosts: tunnels.map((origin) => new URL(origin).hostname) }\n : {}),\n },\n };\n },\n\n configResolved(resolved) {\n config = resolved;\n // Vite gives client code every variable that starts with an env prefix.\n const exposed = [resolved.envPrefix ?? 'VITE_']\n .flat()\n .find((prefix) =>\n [IDENTITY_KEY_VARIABLE, BACKEND_KEY_VARIABLE].some((name) => name.startsWith(prefix)),\n );\n if (exposed !== undefined) {\n throw new Error(\n `ghost-app: envPrefix ${JSON.stringify(exposed)} would expose ${IDENTITY_KEY_VARIABLE} and ${BACKEND_KEY_VARIABLE}, the app's private keys, to the client bundle. Use a prefix they don't start with, such as VITE_.`,\n );\n }\n // Vite checks `server.fs.deny` only with `fs.strict` on.\n if (dev && !resolved.server.fs.strict) {\n throw new Error(\n `ghost-app: server.fs.strict is false, so the dev server would serve ${KEYS_DIRECTORY}/ and .dev.vars, the private keys, to anyone who can reach it. Leave it on, and name other directories in server.fs.allow.`,\n );\n }\n if (pending) {\n config.logger[pending.level](`ghost-app: ${pending.message}`);\n }\n },\n\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.split('?')[0] !== MANIFEST_PATH || !['GET', 'HEAD'].includes(req.method!)) {\n next();\n return;\n }\n // HTTP/2, which Vite serves with server.https, names the host in `:authority`.\n const host = req.headers.host ?? (req.headers[':authority'] as string | undefined);\n const manifestUrl = manifestUrlFor(host);\n if (!manifestUrl) {\n const allowed = ['this machine', ...tunnels.map((origin) => new URL(origin).host)];\n res.statusCode = 421;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(\n `The dev server signs ghost-app.json only for ${allowed.join(', ')}, not ${host ?? 'a request without a Host'}. Name a tunnel's address with GHOST_APP_TUNNEL_URL.\\n`,\n );\n return;\n }\n signProject({ root: config.root, mode: 'development', manifestUrl, manifestFile })\n .then((result) => {\n if (!result.success) {\n throw new Error(`${manifestFile} can't be signed:\\n${formatErrors(result.errors)}`);\n }\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(req.method === 'HEAD' ? undefined : serialiseSigned(result.signed));\n })\n .catch((error: unknown) => {\n const message = `ghost-app: ${(error as Error).message}`;\n config.logger.error(message, { timestamp: true });\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain; charset=utf-8');\n res.end(`${message}\\n`);\n });\n });\n\n const printUrls = server.printUrls.bind(server);\n server.printUrls = () => {\n printUrls();\n const address = server.httpServer?.address();\n const port = typeof address === 'object' && address ? address.port : undefined;\n const scheme = config.server.https ? 'https' : 'http';\n const local = `${scheme}://${devHostname(resolve(config.root, manifestFile))}:${port}`;\n const ghost = (ghostUrl ?? 'http://localhost:2368').replace(/\\/+$/, '');\n const lines = [...(port ? [local] : []), ...tunnels].flatMap((origin) => [\n ` Ghost app: ${origin}${MANIFEST_PATH}`,\n ` Install: ${ghost}/ghost/#/apps/install?manifest=${encodeURIComponent(`${origin}${MANIFEST_PATH}`)}`,\n ]);\n config.logger.info(`\\n${lines.join('\\n')}\\n`);\n };\n },\n\n async buildStart() {\n if (config.command !== 'build' || this.environment.config.consumer !== 'client') {\n return;\n }\n if (!appUrl) {\n config.logger.warn(\n `ghost-app: GHOST_APP_URL isn't set, so this build emits no signed ghost-app.json, and deploying a build without one takes the app down wherever it's installed. Set GHOST_APP_URL to the app's public address, such as https://app.example.com, in .env.production or the environment.`,\n );\n return;\n }\n const base = URL.parse(appUrl.endsWith('/') ? appUrl : `${appUrl}/`);\n // A query or fragment would swallow the manifest's path.\n if (!base || !/^https?:$/.test(base.protocol) || /[?#]/.test(appUrl)) {\n this.error(\n `ghost-app: GHOST_APP_URL must be the app's public address, such as https://app.example.com, not ${appUrl}`,\n );\n }\n const manifestUrl = new URL(MANIFEST_PATH.slice(1), base).href;\n // So `vite build --watch` signs it again when it changes.\n this.addWatchFile(resolve(config.root, manifestFile));\n const result = await signProject({\n root: config.root,\n mode: 'production',\n manifestUrl,\n manifestFile,\n }).catch((error: unknown) => this.error(`ghost-app: ${(error as Error).message}`));\n if (!result.success) {\n this.error(\n `ghost-app: ${manifestFile} can't be signed for ${manifestUrl}:\\n${formatErrors(result.errors)}`,\n );\n }\n this.emitFile({\n type: 'asset',\n fileName: MANIFEST_PATH.slice(1),\n source: serialiseSigned(result.signed),\n });\n config.logger.info(\n `ghost-app: signed ghost-app.json for ${manifestUrl} with ${signingKeySource('production', 'identity')}`,\n );\n },\n };\n}\n"],"mappings":";;;;;;;AAIA,IAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;AACF;AAOA,IAAa,OAAO;CAAC;CAAoB;CAAc;CAAQ;AAAQ;;;ACZvE,IAAM,mBAAmB;CAAC;CAAiB;CAAkB;AAAe;AAE5E,IAAM,WAAW;;;;;;AAOjB,eAAsB,qBACpB,MACkE;CAClE,MAAM,SAAS,SAAiB,WAAW,KAAK,MAAM,IAAI,CAAC;CAC3D,IAAI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vG,CAAC;IACD,OAAO,OAAO,KAAK,KAAK,MAAM,KAAK,IAAI,EAAE,GAAG;GAC9C;EACF;EAEA,MAAM,aAAa;GACjB,IAAI,OAAO,YAAY,WAAW,KAAK,YAAY,OAAO,aAAa,UACrE;GAEF,IAAI,CAAC,QAAQ;IACX,OAAO,OAAO,KACZ,wRACF;IACA;GACF;GACA,MAAM,OAAO,IAAI,MAAM,OAAO,SAAS,GAAG,IAAI,SAAS,GAAG,OAAO,EAAE;GAEnE,IAAI,CAAC,QAAQ,CAAC,YAAY,KAAK,KAAK,QAAQ,KAAK,OAAO,KAAK,MAAM,GACjE,KAAK,MACH,mGAAmG,QACrG;GAEF,MAAM,cAAc,IAAI,IAAI,cAAc,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;GAE1D,KAAK,aAAa,QAAQ,OAAO,MAAM,YAAY,CAAC;GACpD,MAAM,SAAS,MAAM,YAAY;IAC/B,MAAM,OAAO;IACb,MAAM;IACN;IACA;GACF,CAAC,CAAC,CAAC,OAAO,UAAmB,KAAK,MAAM,cAAe,MAAgB,SAAS,CAAC;GACjF,IAAI,CAAC,OAAO,SACV,KAAK,MACH,cAAc,aAAa,uBAAuB,YAAY,KAAK,aAAa,OAAO,MAAM,GAC/F;GAEF,KAAK,SAAS;IACZ,MAAM;IACN,UAAU,cAAc,MAAM,CAAC;IAC/B,QAAQ,gBAAgB,OAAO,MAAM;GACvC,CAAC;GACD,OAAO,OAAO,KACZ,wCAAwC,YAAY,QAAQ,iBAAiB,cAAc,UAAU,GACvG;EACF;CACF;AACF"}
|
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,
|