@tryghost/app-sdk 0.1.0-alpha.16 → 0.1.0-alpha.17
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/build/chunks/sign-kHwo5gGW.js.map +1 -1
- package/build/index.js +1 -1
- package/dist/app-sdk.js +53 -1
- package/dist/app-sdk.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sign-kHwo5gGW.js","names":[],"sources":["../../../app-contracts/build/manifest/localhost.js","../../../app-contracts/build/manifest/ghost-host.js","../../../app-contracts/build/manifest/id.js","../../../app-contracts/build/manifest/limits.js","../../../app-contracts/build/identity/loading.js","../../../app-contracts/build/identity/signed-manifest.js","../../src/tooling/git.ts","../../src/tooling/keys.ts","../../../app-contracts/build/manifest/icon.js","../../../app-contracts/build/manifest/keys.js","../../../app-contracts/build/manifest/surfaces.js","../../../app-contracts/build/manifest/text.js","../../../app-contracts/build/manifest/url.js","../../../app-contracts/build/manifest/schema.js","../../../app-contracts/build/manifest/parse.js","../../src/tooling/sign.ts"],"sourcesContent":["// `URL` has already normalised the host by the time these run: every spelling of an IPv4\n// address is dotted decimal, and an IPv4-mapped IPv6 address is two hex groups.\nconst LOOPBACK_HOSTS = [\n /^localhost$/,\n /\\.localhost$/,\n /^127\\.\\d+\\.\\d+\\.\\d+$/,\n /^0\\.0\\.0\\.0$/,\n /^\\[::1?\\]$/,\n /^\\[::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}\\]$/,\n /^\\[::ffff:0:0\\]$/,\n];\n/**\n * A hostname without its trailing dots, which the URL parser keeps, every one of them:\n * `localhost..` is `localhost`. A loop rather than a regular expression, which would take\n * time quadratic in the number of dots on a hostname with many dots before its end.\n */\nexport function withoutTrailingDots(hostname) {\n let end = hostname.length;\n while (end > 0 && hostname[end - 1] === '.') {\n end -= 1;\n }\n return hostname.slice(0, end);\n}\n/**\n * Whether a host is the machine itself: `localhost`, or a loopback or unspecified address.\n * Pass `URL.hostname`, so the host is already normalised. Trailing dots are dropped, as\n * `isGhostHost` drops them.\n */\nexport function isLocalhost(hostname) {\n const host = withoutTrailingDots(hostname);\n return LOOPBACK_HOSTS.some((pattern) => pattern.test(host));\n}\n//# sourceMappingURL=localhost.js.map","import { withoutTrailingDots } from './localhost.js';\n/**\n * Whether a URL is on a host Ghost itself is served from: the site's, or Admin's, on any\n * port and over either scheme. A page on Ghost's origin would be Ghost, not the app,\n * whatever a frame's sandbox says. On another port it would be the app's, but browsers send\n * a host's cookies to every port on it, so the app's server would be sent the staff user's\n * session. So Ghost refuses a manifest URL on such a host, and Admin asks again where it\n * frames the page, since the site's or Admin's address can change after an app is\n * installed.\n *\n * Hosts are compared as the URL parser reads them, so case and IDN spellings agree, and\n * without a trailing dot. A sibling host, such as another subdomain of the site's, is not\n * Ghost's: the cookies Ghost sets are host-only. Nor is a name under Ghost's, such as\n * `my-app.localhost` next to `localhost`, or another name for the same machine, such as\n * `127.0.0.1`, which browsers treat as other hosts too.\n *\n * Any doubt counts as Ghost's: a URL that isn't http or https, a Ghost URL like that, or no\n * Ghost URLs at all. Either way the URL is refused.\n */\nexport function isGhostHost(url, ghostUrls) {\n const host = hostOf(url);\n if (host === null) {\n return true;\n }\n let known = false;\n for (const ghostUrl of ghostUrls) {\n const ghostHost = hostOf(ghostUrl);\n if (ghostHost === null || ghostHost === host) {\n return true;\n }\n known = true;\n }\n return !known;\n}\n/** An http or https URL's host as `isGhostHost` compares it, or null for any other. */\nexport function hostOf(value) {\n let url;\n // Admin runs this, and `URL.parse` is newer than the browsers Admin supports.\n try {\n url = new URL(value);\n }\n catch {\n return null;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return null;\n }\n return withoutTrailingDots(url.hostname) || null;\n}\n//# sourceMappingURL=ghost-host.js.map","/** Matches the limit of the index that ties saved cards to an app. */\nexport const APP_ID_MAX_LENGTH = 191;\nconst ID_SEGMENT = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n/**\n * An app ID is reverse-domain style: at least two dot-separated segments of lowercase\n * letters, digits and hyphens, starting with a letter so that an IP address or a version\n * number is not an ID. IDs are compared exactly, so an uppercase ID is invalid rather than\n * lowercased.\n */\nexport function isValidAppId(value) {\n if (typeof value !== 'string' || value.length > APP_ID_MAX_LENGTH) {\n return false;\n }\n const segments = value.split('.');\n return (segments.length >= 2 &&\n /^[a-z]/.test(value) &&\n segments.every((segment) => ID_SEGMENT.test(segment)));\n}\n//# sourceMappingURL=id.js.map","/**\n * The longest URL a manifest may hold, measured once resolved. Ghost stores every one of\n * them, the manifest's own URL included, so its columns are exactly this wide.\n */\nexport const URL_MAX_LENGTH = 2000;\n//# sourceMappingURL=limits.js.map","// How Ghost reads the signed manifest an app serves. Ghost core reads it by these, and the app\n// SDK signs by them, so a manifest it signs is one Ghost reads.\n/** The largest manifest Ghost stores, which it keeps in a TEXT column. */\nexport const MANIFEST_MAX_BYTES = 64 * 1024;\n/**\n * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and\n * the header and signature are well under a kilobyte, so a manifest of the largest size\n * still fits.\n */\nexport const SIGNED_MANIFEST_MAX_BYTES = Math.ceil((MANIFEST_MAX_BYTES * 4) / 3) + 1024;\n/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */\nexport function parseJsonText(text) {\n return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n}\n//# sourceMappingURL=loading.js.map","import { FlattenedSign, flattenedVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeText } from './keys.js';\n/** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */\nexport const SIGNED_MANIFEST_TYPE = 'ghost-app-manifest';\nconst SignedManifestShape = z.strictObject({\n protected: z.string(),\n payload: z.string(),\n signature: z.string(),\n});\nconst ProtectedHeader = z.strictObject({\n alg: z.literal(ALGORITHM),\n typ: z.literal(SIGNED_MANIFEST_TYPE),\n});\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE });\n/**\n * Signs a manifest with an app's identity key. A string is signed as the exact text it is;\n * anything else is signed as its JSON.\n */\nexport async function signManifest(manifest, identityKey) {\n const text = typeof manifest === 'string' ? manifest : JSON.stringify(manifest);\n const signed = await new FlattenedSign(new TextEncoder().encode(text))\n .setProtectedHeader({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE })\n .sign(identityKey);\n return { protected: signed.protected, payload: signed.payload, signature: signed.signature };\n}\n/**\n * Reads the manifest out of a signed manifest, without verifying it. The key to verify it\n * with is named inside the manifest, so the manifest has to be read and checked first;\n * nothing in it may be used until `verifySignedManifest` has passed.\n */\nexport function readSignedManifest(body) {\n const shape = SignedManifestShape.safeParse(body);\n if (!shape.success) {\n return {\n success: false,\n error: 'Expected a signed manifest: flattened JWS JSON with protected, payload and signature',\n };\n }\n const signed = shape.data;\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n const payload = decodeText(signed.payload);\n if (payload === undefined) {\n return { success: false, error: 'Expected a payload of UTF-8 text in base64url' };\n }\n return { success: true, signed, payload };\n}\n/**\n * Checks a signed manifest was signed with the identity key the manifest names, under\n * exactly the protected header `readSignedManifest` accepts.\n */\nexport async function verifySignedManifest(signed, identityKey) {\n let key;\n try {\n key = await importJWK(identityKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'identity_key is not a usable Ed25519 key' };\n }\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n try {\n await flattenedVerify(signed, key, { algorithms: [ALGORITHM] });\n }\n catch {\n return { success: false, error: 'The signature was not made with identity_key' };\n }\n return { success: true };\n}\n//# sourceMappingURL=signed-manifest.js.map","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\n\nimport { ignoreError } from '../shared/ignore.ts';\n\nexport type IgnoredResult = { ignored: true } | { ignored: false; reason: string };\n\nfunction git(args: string[], cwd: string, input?: string) {\n return new Promise<{ code: number | string | null; stdout: string; stderr: string }>((done) => {\n const child = execFile('git', args, { cwd }, (error, stdout, stderr) => {\n done({ code: error ? ((error as { code?: number | string }).code ?? 1) : 0, stdout, stderr });\n });\n // A git that couldn't start has no stdin to write to; its error arrives above.\n child.stdin?.on('error', ignoreError);\n child.stdin?.end(input);\n });\n}\n\nfunction insideRepository(directory: string): boolean {\n for (let current = resolve(directory); ; current = dirname(current)) {\n if (existsSync(join(current, '.git'))) {\n return true;\n }\n if (dirname(current) === current) {\n return false;\n }\n }\n}\n\n/**\n * The directory itself, or the nearest one above it that exists, to run git in: a project's\n * directory may not exist before its keys are written, and git can't start in one that doesn't.\n */\nfunction existingDirectory(directory: string): string {\n let current = resolve(directory);\n while (!existsSync(current) && dirname(current) !== current) {\n current = dirname(current);\n }\n return current;\n}\n\n/**\n * Whether git ignores every one of `files`, which needn't exist yet, so none can be committed by\n * accident. A file outside any repository counts as ignored.\n */\nexport async function isGitIgnored(\n root: string,\n files: string | readonly string[],\n): Promise<IgnoredResult> {\n // git can't start in a directory that doesn't exist, and a project's may not exist yet.\n const cwd = existingDirectory(root);\n const paths = (typeof files === 'string' ? [files] : files).map((file) => ({\n // As the developer named it, for messages, and as git is asked about it, from `cwd`.\n shown: relative(root, resolve(root, file)),\n asked: relative(cwd, resolve(root, file)),\n }));\n const named = `${paths.map(({ shown }) => shown).join(' and ')} ${paths.length > 1 ? 'are' : 'is'}`;\n\n const repository = await findRepository(cwd, named);\n if (repository !== 'inside') {\n return repository === 'outside' ? { ignored: true } : repository;\n }\n return askWhichAreIgnored(cwd, paths, named);\n}\n\n/** Whether `cwd` is in a repository, or why git can't say when it seems to be. */\nasync function findRepository(\n cwd: string,\n named: string,\n): Promise<'inside' | 'outside' | { ignored: false; reason: string }> {\n // Read from what git exits with, never from what it says, which is in the developer's\n // language. A `.git` that git can't read is still a repository, so it isn't taken as outside.\n const inside = await git(['rev-parse', '--is-inside-work-tree'], cwd);\n if (inside.code === 0) {\n return 'inside';\n }\n if (!insideRepository(cwd)) {\n return 'outside';\n }\n return {\n ignored: false,\n reason:\n inside.code === 'ENOENT'\n ? `git isn't installed, so it can't check ${named} ignored`\n : `git couldn't read the repository: ${inside.stderr.trim()}`,\n };\n}\n\nasync function askWhichAreIgnored(\n cwd: string,\n paths: { shown: string; asked: string }[],\n named: string,\n): Promise<IgnoredResult> {\n // One call for every path. It lists the ones it ignores, and exits with 1 when it ignores none.\n // Paths go in and out separated by NUL, as git would otherwise quote one with any byte outside\n // ASCII. A file git tracks isn't ignored, even if a `.gitignore` names it.\n const { code, stdout, stderr } = await git(\n ['check-ignore', '--stdin', '-z'],\n cwd,\n paths.map(({ asked }) => `${asked}\\0`).join(''),\n );\n if (code !== 0 && code !== 1) {\n return { ignored: false, reason: `git couldn't check ${named} ignored: ${stderr.trim()}` };\n }\n const ignored = new Set(stdout.split('\\0'));\n const notIgnored = paths.find(({ asked }) => !ignored.has(asked));\n return notIgnored\n ? { ignored: false, reason: `git doesn't ignore ${notIgnored.shown}` }\n : { ignored: true };\n}\n","import { generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { chmod, link, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nimport { publicHalfOf } from '../shared/keys.ts';\nimport { isGitIgnored } from './git.ts';\n\n/**\n * Which keys to use. Development and production have separate identity keys, so an app\n * installed from the developer's machine is a different app from the deployed one.\n */\nexport type Mode = 'development' | 'production';\n\n/** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */\nexport const KEYS_DIRECTORY = '.ghost-app';\n\n/**\n * - `identity`: signs the manifest. It says who made the app, so it stays with the developer\n * (or their CI) and never reaches the backend or a bundle.\n * - `backend`: answers Ghost's challenge, so the backend holds it.\n */\nexport type KeyName = 'identity' | 'backend';\n\nexport const KEY_NAMES: readonly KeyName[] = ['identity', 'backend'];\n\n/** A private Ed25519 key as a JWK. */\nexport interface PrivateKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n d: string;\n}\n\n/** A public Ed25519 key as a JWK, as a manifest names it. */\nexport interface PublicKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n}\n\n/** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */\nexport const IDENTITY_KEY_VARIABLE = 'GHOST_APP_IDENTITY_KEY';\n\n/**\n * The backend key, as the backend reads it, and as CI may provide it to sign a production\n * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.\n */\nexport const BACKEND_KEY_VARIABLE = 'GHOST_APP_BACKEND_KEY';\n\nexport interface KeyOptions {\n /** The project's directory, which holds `.ghost-app/`. */\n root: string;\n mode: Mode;\n}\n\n/** The file a key is kept in, relative to the project. */\nexport function keyFile(mode: Mode, name: KeyName): string {\n return join(KEYS_DIRECTORY, mode, `${name}.json`);\n}\n\n/** A new private Ed25519 key. */\nexport function generateKey(): PrivateKeyJwk {\n const { x, d } = generateKeyPairSync('ed25519').privateKey.export({ format: 'jwk' });\n return { kty: 'OKP', crv: 'Ed25519', x: x!, d: d! };\n}\n\n/** A key's public half, with only `kty`, `crv` and `x`. */\nexport function publicKeyOf(key: PrivateKeyJwk | PublicKeyJwk): PublicKeyJwk {\n return { kty: 'OKP', crv: 'Ed25519', x: key.x };\n}\n\n/**\n * Reads a private key from JSON. `source` names where it came from, for the error: the key\n * itself is never in one.\n */\nexport async function readKey(text: string, source: string): Promise<PrivateKeyJwk> {\n const key = await readAnyKey(text, source);\n if (!('d' in key)) {\n throw new Error(`${source} is a public key; expected the private key, with d`);\n }\n return key;\n}\n\n/** Reads a key from JSON, private or public. */\nasync function readAnyKey(text: string, source: string): Promise<PrivateKeyJwk | PublicKeyJwk> {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new Error(`${source} isn't a key: it isn't JSON`);\n }\n if (!isEd25519(value)) {\n throw new Error(`${source} isn't an Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\" and x`);\n }\n const { d } = value as { d?: unknown };\n if (d === undefined) {\n return publicKeyOf(value);\n }\n // A key with a private part that doesn't read isn't a public key either.\n if (typeof d !== 'string') {\n throw new Error(`${source} isn't a usable Ed25519 key: its d isn't a string`);\n }\n // A JWK carries both halves, so a hand-edited or pasted one could pair a private half with\n // someone else's public half, and sign for a key the manifest doesn't name.\n const bytes = Buffer.from(d, 'base64url');\n if (bytes.length !== 32) {\n throw new Error(`${source} isn't a usable Ed25519 key`);\n }\n if ((await publicHalfOf(bytes)) !== value.x) {\n throw new Error(`${source} isn't a usable Ed25519 key: its x doesn't match its d`);\n }\n return { kty: 'OKP', crv: 'Ed25519', x: value.x, d } satisfies PrivateKeyJwk;\n}\n\nfunction isEd25519(value: unknown): value is { kty: 'OKP'; crv: 'Ed25519'; x: string } {\n const { kty, crv, x } = (typeof value === 'object' && value !== null ? value : {}) as Record<\n string,\n unknown\n >;\n return kty === 'OKP' && crv === 'Ed25519' && typeof x === 'string';\n}\n\nasync function readKeyFile(root: string, mode: Mode, name: KeyName): Promise<PrivateKeyJwk> {\n const file = keyFile(mode, name);\n let text: string;\n try {\n text = await readFile(join(root, file), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n throw new Error(missingKeyMessage(mode, name, file), { cause: error });\n }\n return readKey(text, file);\n}\n\n/** Says how to create a missing key, as nothing that reads keys creates one. */\nfunction missingKeyMessage(mode: Mode, name: KeyName, file: string): string {\n if (mode === 'development') {\n return `There's no development ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys\\`.`;\n }\n // In production, CI may provide the key as a variable instead.\n return `There's no production ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys --production\\`, or set ${variableFor(name)}.`;\n}\n\nconst variableFor = (name: KeyName) =>\n name === 'identity' ? IDENTITY_KEY_VARIABLE : BACKEND_KEY_VARIABLE;\n\nexport interface CreateKeysResult {\n /** The keys this call created. */\n created: KeyName[];\n /** The keys that already existed, which are never replaced. */\n kept: KeyName[];\n}\n\n/**\n * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only\n * their owner can read, and keeps any that exist.\n */\nexport async function createKeys({ root, mode }: KeyOptions): Promise<CreateKeysResult> {\n // Each key is written whole to a temporary file beside it first, then linked to its name.\n const keys = KEY_NAMES.map((name) => {\n const file = keyFile(mode, name);\n const pending = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);\n return { name, file, pending };\n });\n // So a private key can't be committed by accident, git must ignore every file a key is\n // written to, the temporary ones included.\n await refuseUnlessGitIgnores(root, [\n ...keys.map(({ file }) => file),\n ...keys.map(({ pending }) => pending),\n ]);\n await mkdir(join(root, KEYS_DIRECTORY, mode), { recursive: true, mode: 0o700 });\n const result: CreateKeysResult = { created: [], kept: [] };\n for (const { name, file, pending } of keys) {\n // An existing key is kept: a new identity key would make the app a different app on every\n // site that installed it.\n const created = await publishKey(join(root, file), join(root, pending));\n result[created ? 'created' : 'kept'].push(name);\n }\n return result;\n}\n\nasync function refuseUnlessGitIgnores(root: string, files: string[]) {\n const ignored = await isGitIgnored(root, files);\n if (!ignored.ignored) {\n throw new Error(\n `Refusing to write private keys where git could commit them: ${ignored.reason}. Add ${KEYS_DIRECTORY}/ to .gitignore.`,\n );\n }\n}\n\n/** Writes a new key to `file` unless one is there, by way of `pending`, and says whether it did. */\nasync function publishKey(file: string, pending: string): Promise<boolean> {\n try {\n await writeFile(pending, `${JSON.stringify(generateKey(), null, 2)}\\n`, {\n flag: 'wx',\n // Only for its owner on macOS and Linux. Windows ignores the mode, and the key gets the\n // folder's inherited permissions, which the README tells developers to keep private.\n mode: 0o600,\n });\n // A link fails if the name is taken, so a key is never replaced, even by a concurrent run,\n // and an interrupted write never leaves part of a key where a key belongs.\n await link(pending, file);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n // Kept, but only for its owner, as a key written by hand or copied in may not be.\n if (process.platform !== 'win32' && ((await stat(file)).mode & 0o077) !== 0) {\n await chmod(file, 0o600);\n }\n return false;\n } finally {\n await rm(pending, { force: true });\n }\n}\n\nexport interface SigningKeys {\n identityKey: PrivateKeyJwk;\n /** The backend key's public half: all signing needs. */\n backendKey: PublicKeyJwk;\n}\n\nexport interface ReadKeysOptions extends KeyOptions {\n /** Where to read `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY` from, in production. */\n env?: Record<string, string | undefined>;\n}\n\n/**\n * Where `readSigningKeys` reads a mode's key from: the variable, in production when it's set to\n * anything but blanks, or else the key's file.\n */\nexport function signingKeySource(\n mode: Mode,\n name: KeyName,\n env: Record<string, string | undefined> = process.env,\n): string {\n const variable = variableFor(name);\n return mode === 'production' && env[variable]?.trim() ? variable : keyFile(mode, name);\n}\n\n/**\n * The keys to sign a mode's manifest with, from the key files, or in production from\n * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.\n */\nexport async function readSigningKeys({\n root,\n mode,\n env = process.env,\n}: ReadKeysOptions): Promise<SigningKeys> {\n const fromVariable = (name: KeyName) =>\n signingKeySource(mode, name, env) === variableFor(name)\n ? env[variableFor(name)]!.trim()\n : undefined;\n\n const identityText = fromVariable('identity');\n const identityKey = identityText\n ? await sameAsFile(root, mode, 'identity', await readKey(identityText, IDENTITY_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'identity');\n\n // CI may provide only the backend key's public half, as signing needs nothing more.\n const backendText = fromVariable('backend');\n const backendKey = publicKeyOf(\n backendText\n ? await sameAsFile(root, mode, 'backend', await readAnyKey(backendText, BACKEND_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'backend'),\n );\n\n if (identityKey.x === backendKey.x) {\n throw new Error('The identity key and the backend key are the same key; they must be two keys');\n }\n return { identityKey, backendKey };\n}\n\n/**\n * A key from a variable, after checking it's the same key as the file, where there's one. A\n * variable left set, such as a development key exported for every shell, would otherwise win over\n * the file unnoticed, and a manifest naming the wrong backend key retires the right one on every\n * site.\n */\nasync function sameAsFile<Key extends PublicKeyJwk>(\n root: string,\n mode: Mode,\n name: KeyName,\n key: Key,\n): Promise<Key> {\n const file = keyFile(mode, name);\n if (existsSync(join(root, file)) && (await readKeyFile(root, mode, name)).x !== key.x) {\n const variable = variableFor(name);\n throw new Error(\n `${variable} and ${file} are different ${name} keys. Unset ${variable} to sign with the file, or remove ${file} to sign with the variable.`,\n );\n }\n return key;\n}\n\n/** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */\nexport function readBackendKey({ root, mode }: KeyOptions): Promise<PrivateKeyJwk> {\n return readKeyFile(root, mode, 'backend');\n}\n","import { z } from 'zod';\nconst ICON_NAME_MAX_LENGTH = 64;\nconst ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst EITHER = 'Expected an icon with either a name or a url';\n/**\n * Ghost draws the icon on the app's accent colour: a named Admin icon or an image the app\n * serves. Ghost keeps a copy of the image with each manifest version it stores, and only\n * shows that copy. Unknown names aren't rejected, since they depend on the Admin build;\n * Admin falls back to a default icon.\n */\nexport function iconField(url) {\n return (z\n .strictObject({\n name: z\n .string('Expected an icon name')\n .max(ICON_NAME_MAX_LENGTH, `Expected at most ${ICON_NAME_MAX_LENGTH} characters`)\n .regex(ICON_NAME, 'Expected an icon name such as audio-lines')\n .optional(),\n url: url().optional(),\n }, EITHER)\n .refine(({ name, url: iconUrl }) => (name === undefined) !== (iconUrl === undefined), EITHER)\n // Only the type narrows: the value already is one or the other. A transform would\n // narrow it too, but one-way, and a stored manifest has to encode back through here.\n .pipe(z.custom()));\n}\n//# sourceMappingURL=icon.js.map","import { z } from 'zod';\n// 32 bytes in base64url without padding. The last character carries the final 4 bits and\n// 2 zero bits, so only 16 of the 64 characters can end it, which keeps the spelling of a key\n// unique.\nconst ED25519_X = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;\nconst EXPECTED = 'Expected a public Ed25519 key as a JWK with kty, crv and x';\nconst PRIVATE = 'Expected a public key, but this includes its private part (d)';\n/**\n * A key a manifest names. A manifest is public, so a key that includes its private part\n * is refused with a message of its own: it has to be replaced, not just removed. Other\n * members are refused by name, as key tools often add some, such as `kid` or `alg`.\n */\nexport const publicKeyField = z.strictObject({\n kty: z.literal('OKP', EXPECTED),\n crv: z.literal('Ed25519', EXPECTED),\n x: z.string(EXPECTED).regex(ED25519_X, 'Expected 32 bytes in base64url, without padding'),\n}, {\n error: (issue) => {\n if (issue.code !== 'unrecognized_keys') {\n return EXPECTED;\n }\n return issue.keys.includes('d')\n ? PRIVATE\n : `Expected only kty, crv and x; remove ${issue.keys.join(', ')}`;\n },\n});\n//# sourceMappingURL=keys.js.map","import { z } from 'zod';\n/**\n * What an app asks for: the places in Ghost it wants to appear. Each surface type is one\n * entry in a union, so a new one is added here and nowhere else.\n */\nexport function surfacesField(url) {\n const adminPage = z.strictObject({\n type: z.literal('admin_page'),\n url: url(),\n });\n const surfaceTypes = [adminPage];\n const surface = z.discriminatedUnion('type', surfaceTypes, {\n error: `Expected a surface with a type of: ${surfaceTypes.map((entry) => entry.shape.type.value).join(', ')}`,\n });\n return z\n .array(surface, 'Expected a list of surfaces')\n .min(1, 'Expected at least one surface')\n .superRefine((surfaces, ctx) => {\n const seen = new Set();\n surfaces.forEach((entry, index) => {\n if (seen.has(entry.type)) {\n ctx.addIssue({\n code: 'custom',\n message: `Expected at most one ${entry.type} surface`,\n path: [index],\n });\n }\n seen.add(entry.type);\n });\n });\n}\n//# sourceMappingURL=surfaces.js.map","import { z } from 'zod';\nimport { isPlainText } from '../plain-text.js';\n// A character that shows something on its own: a letter, digit, punctuation or symbol, but not\n// the blank Braille pattern or one Unicode says to draw as nothing, such as a joiner or a Hangul\n// filler. Whitespace and marks aren't any of those.\nconst VISIBLE_CHARACTER = new RegExp('(?![\\\\u2800\\\\p{Default_Ignorable_Code_Point}])[\\\\p{L}\\\\p{N}\\\\p{P}\\\\p{S}]', 'u');\nconst shows = (text) => VISIBLE_CHARACTER.test(text);\n// Shows nothing, and holds nothing plain text refuses other than whitespace, so trimming never\n// takes off a character, such as one that reorders text, that should get the text refused.\nconst blank = (character) => !shows(character) && isPlainText(character.replace(/\\s/gu, ''));\n// Made on first use, so loading the contract doesn't set one up.\nlet graphemes;\n/**\n * Takes off each end the characters, as a reader sees them, that show nothing: a space with a\n * mark on it goes, an emoji with its variation selector stays, and so does anything invisible\n * that joins onto a visible character. Walks in from each end, so a long run of spaces costs no\n * more than its length.\n */\nfunction trimEdges(value) {\n graphemes ??= new Intl.Segmenter();\n const characters = graphemes.segment(value);\n let start = value.length;\n for (const { segment, index } of characters) {\n if (!blank(segment)) {\n start = index;\n break;\n }\n }\n let end = value.length;\n while (end > start) {\n const { segment, index } = characters.containing(end - 1);\n if (!blank(segment)) {\n break;\n }\n end = index;\n }\n return value.slice(start, end);\n}\n/**\n * One line of plain text, as an app serves it. What shows nothing is taken off both ends, and\n * text with nothing visible left, such as a name of Hangul fillers, is refused.\n */\nexport function plainText(maxLength) {\n return (z\n .string('Expected text')\n // Whitespace first, as a character that joins onto a space, such as a skin tone, would keep it.\n .trim()\n .overwrite(trimEdges)\n .refine(shows, 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line'));\n}\n// Any letter, digit, punctuation or symbol, fillers included: the rule manifests were stored under\n// before blank names were refused.\nconst ANY_CHARACTER = /[\\p{L}\\p{N}\\p{P}\\p{S}]/u;\n/**\n * One line of plain text, as Ghost stored it. Laxer than `plainText`, so a manifest stored before\n * blank names were refused still reads, and the app can still be listed and uninstalled.\n */\nexport function storedText(maxLength) {\n return z\n .string('Expected text')\n .trim()\n .refine((value) => ANY_CHARACTER.test(value), 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line');\n}\n//# sourceMappingURL=text.js.map","import { z } from 'zod';\nimport { isContainedPath } from '../bridge/rules.js';\nimport { URL_MAX_LENGTH } from './limits.js';\nimport { isLocalhost } from './localhost.js';\nexport const FRAGMENT_PROBLEM = 'Expected a URL without a fragment';\n/**\n * Whether an address carries a fragment, even an empty one, which the parsed URL's `hash`\n * hides. A fragment never reaches the server, so a manifest address with one is a mistake or\n * a second spelling of the same address.\n */\nexport const hasFragment = (address) => address.includes('#');\n/**\n * Checks a URL once the URL parser has read it, so the rules apply to the URL Ghost would\n * use. The length is measured on the parsed URL for the same reason, as that is what is\n * stored and checked again later.\n */\nexport function checkResolvedUrl(url, allowLocalhost) {\n if (url.href.length > URL_MAX_LENGTH) {\n return `Expected at most ${URL_MAX_LENGTH} characters`;\n }\n if (url.username || url.password) {\n return 'Expected a URL without a username or password';\n }\n if (isLocalhost(url.hostname)) {\n if (!allowLocalhost) {\n return 'Expected a public address; localhost is only allowed when Ghost runs in development';\n }\n return url.protocol === 'https:' || url.protocol === 'http:'\n ? null\n : 'Expected an http or https URL';\n }\n return url.protocol === 'https:' ? null : 'Expected an https URL';\n}\nconst ROUTE_PROBLEM = 'Expected a URL that resolves to a path starting with a single /, with no \\\\ in its query or fragment';\nconst PATH_PROBLEM = 'Expected a path on the manifest’s own origin, such as /admin';\n// Two, so a reference that names one of them still names a host other than the other's.\nconst PLACEHOLDER_HOSTS = ['manifest-a.invalid', 'manifest-b.invalid'];\n/** Whether a reference names a host, in any of the URL parser's spellings of one. */\nconst namesHost = (value) => PLACEHOLDER_HOSTS.some((host) => URL.parse(value, `https://${host}/`)?.host !== host);\nfunction isManifestItself(url, base) {\n return url.pathname === new URL(base).pathname;\n}\n/**\n * A URL in the manifest. What Ghost loads is written as a path, resolved against the\n * address the manifest was fetched from, so an app is one origin: the one Ghost fetches\n * the manifest from and challenges is the one every surface runs on. The manifest names\n * that address as its signed `manifest_url`, so the resolved URLs are as fixed as if they\n * were written out. `parseManifestUrl` keeps that origin off Ghost's hosts.\n *\n * `linkOnly` marks a URL that is only ever linked to, never loaded, which is absolute and\n * may be anywhere, the publisher's own site included.\n *\n * A loaded URL's path, query and fragment must also make a path `isContainedPath` accepts.\n * Admin opens the app there, as its entry route, and the SDK refuses a route that isn't one.\n * Resolving can still give one that isn't: `/.//admin` resolves to the path `//admin`, which\n * names a host, and a `\\` in the query or fragment is left as it is. Only the page is opened\n * as a route, but every URL Ghost loads is held to the one rule.\n */\nexport function urlField({ allowLocalhost, base }, linkOnly = false) {\n if (linkOnly) {\n return z.string('Expected an absolute URL').transform((value, ctx) => {\n const url = URL.parse(value);\n const problem = url ? checkResolvedUrl(url, allowLocalhost) : 'Expected an absolute URL';\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n return url.href;\n });\n }\n const origin = new URL(base).origin;\n return z.string(PATH_PROBLEM).transform((value, ctx) => {\n // A path, or a path-relative reference. A URL with a scheme, or a `//host` one, names\n // its own origin, which the manifest's would then not be, even when it's the same one\n // today. An empty one, or one that's only a query or fragment, would be the manifest\n // itself.\n const url = URL.canParse(value) || namesHost(value) ? null : URL.parse(value, base);\n if (!url || url.origin !== origin || isManifestItself(url, base)) {\n ctx.addIssue({ code: 'custom', message: PATH_PROBLEM });\n return z.NEVER;\n }\n const problem = checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n if (!isContainedPath(`${url.pathname}${url.search}${url.hash}`)) {\n ctx.addIssue({ code: 'custom', message: ROUTE_PROBLEM });\n return z.NEVER;\n }\n return url.href;\n });\n}\n/**\n * A URL as a manifest holds it once `parseManifest` has accepted it: absolute, and\n * already checked. Nothing is resolved or checked again, so a manifest accepted before the\n * site's URL changed still reads back.\n */\nexport const absoluteUrl = () => z.url('Expected an absolute URL');\n//# sourceMappingURL=url.js.map","import { z } from 'zod';\nimport { iconField } from './icon.js';\nimport { APP_ID_MAX_LENGTH, isValidAppId } from './id.js';\nimport { publicKeyField } from './keys.js';\nimport { isLocalhost } from './localhost.js';\nimport { surfacesField } from './surfaces.js';\nimport { plainText, storedText } from './text.js';\nimport { absoluteUrl, FRAGMENT_PROBLEM, hasFragment, urlField, } from './url.js';\nconst NAME_MAX_LENGTH = 50;\nconst DESCRIPTION_MAX_LENGTH = 200;\nconst AUTHOR_NAME_MAX_LENGTH = 50;\nconst HEX_COLOR = /^#[0-9a-f]{6}$/i;\nconst KEY_FIELDS = new Set(['identity_key', 'backend_key']);\nconst URL_FIELDS = new Set([\n 'author',\n 'icon',\n 'surfaces',\n 'manifest_url',\n 'development',\n]);\n/** Passes a refinement only once the fields it reads parsed, and the manifest is an object. */\nconst parsedFields = (fields) => ({ issues }) => issues.every(({ path = [] }) => path.length > 0 && !fields.has(path[0]));\n/**\n * The manifest as a whole. Unknown fields are rejected at every level, so an app cannot\n * claim something Ghost has not designed, and adding a field is always a deliberate change\n * here.\n *\n * Defined once, with the URL and text rules left open. What a valid URL is depends on whether\n * the manifest is being parsed, when where Ghost is served from matters, or read back after it\n * was, when it doesn't. Text is held to today's rules when parsed, and read back under the\n * rules it was stored under.\n */\nfunction manifestShape(url, text) {\n return (z\n .strictObject({\n id: z.custom(isValidAppId, {\n error: `Expected a lowercase reverse-domain ID such as com.example.app, at most ${APP_ID_MAX_LENGTH} characters`,\n }),\n name: text(NAME_MAX_LENGTH),\n description: text(DESCRIPTION_MAX_LENGTH),\n author: z.strictObject({\n name: text(AUTHOR_NAME_MAX_LENGTH),\n // Only ever linked to, so it may point at the publisher's own site.\n url: url(true),\n }, 'Expected an author with a name and a url'),\n accent_color: z\n .string('Expected a hex colour such as #ff5500')\n .regex(HEX_COLOR, 'Expected a hex colour such as #ff5500')\n .toLowerCase(),\n icon: iconField(url),\n surfaces: surfacesField(url),\n // Where the signed manifest is served from: the app's one origin, which every path\n // in it resolves against. Ghost fetches it server-side and never loads it as a page.\n manifest_url: url(true).refine((address) => !hasFragment(address), FRAGMENT_PROBLEM),\n identity_key: publicKeyField,\n backend_key: publicKeyField,\n // Lets Admin label a development build. Production sites may run one to test it.\n development: z.boolean('Expected true or false'),\n })\n // A backend holds its key online. If it also signed manifests, whoever took over the\n // backend could publish any manifest as the app.\n .refine((manifest) => manifest.identity_key.x !== manifest.backend_key.x, {\n message: 'Expected a different key from identity_key',\n path: ['backend_key'],\n // Only once both keys are known to be keys. An issue without a path is about the\n // manifest as a whole, which may not be an object at all.\n when: parsedFields(KEY_FIELDS),\n })\n // An app on the developer's machine is always labelled as a development build.\n .refine((manifest) => manifest.development ||\n ![\n manifest.author.url,\n 'url' in manifest.icon ? manifest.icon.url : undefined,\n ...manifest.surfaces.map((surface) => surface.url),\n manifest.manifest_url,\n ].some((address) => address !== undefined && isLocalhost(new URL(address).hostname)), {\n message: 'Expected true, as the app is on localhost',\n path: ['development'],\n when: parsedFields(URL_FIELDS),\n }));\n}\n/** The manifest as an app serves it. Built per parse, as its URL rule depends on the parse. */\nexport function manifestSchema(rules) {\n return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);\n}\n/**\n * The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to\n * resolve or check. This is the schema to read a stored manifest with, as it holds\n * whatever the site's URL has become since, and it encodes a manifest back to the same\n * shape, so what is stored is what will be read.\n */\nexport const AppManifestSchema = manifestShape(absoluteUrl, storedText);\n//# sourceMappingURL=schema.js.map","import { hostOf, isGhostHost } from './ghost-host.js';\nimport { isLocalhost } from './localhost.js';\nimport { manifestSchema } from './schema.js';\nimport { checkResolvedUrl, FRAGMENT_PROBLEM, hasFragment } from './url.js';\nfunction formatPath(path) {\n return path.reduce((result, part) => {\n if (typeof part === 'number') {\n return `${result}[${part}]`;\n }\n return result ? `${result}.${String(part)}` : String(part);\n }, '');\n}\nconst GHOST_URLS_PROBLEM = 'Expected the URLs Ghost itself is served from';\nconst ON_GHOST_HOST = 'Expected the manifest on a host other than the one Ghost itself is served from, on any port, as browsers send Ghost’s cookies to every port on its host';\nconst ON_GHOST_HOST_LOCALLY = `${ON_GHOST_HOST}. To run the app on this machine too, serve it from a name of its own under .localhost, such as my-app.localhost`;\n/**\n * Why a manifest on one of Ghost's hosts is refused, with a hint for when that's most\n * likely: an app run next to Ghost on the developer's machine. A name under `.localhost`\n * is a host of its own, which browsers send to the machine itself, and so does Ghost in\n * development, whatever the system's resolver knows.\n */\nfunction onGhostHost(url) {\n return isLocalhost(url.hostname) ? ON_GHOST_HOST_LOCALLY : ON_GHOST_HOST;\n}\n/**\n * Reads the address a manifest is to be read from, by the same rules as the URLs inside\n * it, and checks it is on none of Ghost's hosts. Run it before fetching, so the first\n * request never goes to an address Ghost would refuse (plain HTTP, one carrying\n * credentials, or one on Ghost's host). It cannot judge where that address redirects,\n * which is for whatever fetches it to limit.\n *\n * The address it hands back is the one to store, to compare with a later one, and that the\n * manifest must name as its `manifest_url`. The URL parser settles most differences in\n * spelling, but not a trailing dot on the host or the case of a percent-encoding: an address spelled that way reads as a\n * change of manifest URL, which needs the publisher's approval, the safe way to be wrong.\n */\nexport function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {\n if (ghostUrls.length === 0 || !ghostUrls.every((ghostUrl) => hostOf(ghostUrl) !== null)) {\n return { success: false, error: GHOST_URLS_PROBLEM };\n }\n const url = URL.parse(input);\n if (!url) {\n return { success: false, error: 'Expected the manifest at a URL' };\n }\n const problem = hasFragment(input) ? FRAGMENT_PROBLEM : checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n return { success: false, error: `${problem} for the manifest itself` };\n }\n if (isGhostHost(url, ghostUrls)) {\n return { success: false, error: onGhostHost(url) };\n }\n return { success: true, manifestUrl: url.href };\n}\n/** A manifest's problems as `path: message`, joined by `separator`, as Ghost reports them. */\nexport function formatManifestErrors(errors, separator) {\n return errors\n .map(({ path, message }) => (path ? `${path}: ${message}` : message))\n .join(separator);\n}\nfunction invalid(errors) {\n return { success: false, reason: 'invalid', errors };\n}\n/**\n * Validates a manifest, and checks it names the address it was fetched from as its\n * `manifest_url`. A copy served from anywhere else is refused, so the signature binds the\n * manifest to its address as well as to every URL in it.\n *\n * Returns either the manifest, or every problem found. It does not fetch anything and it\n * never throws. Without the URLs Ghost is served from it rejects every manifest, since the\n * rule that keeps apps off Ghost's hosts could not be checked.\n */\nexport function parseManifest(input, options) {\n const allowLocalhost = options.allowLocalhost ?? false;\n const address = parseManifestUrl(options.manifestUrl, options);\n if (!address.success) {\n return invalid([{ path: '', message: address.error }]);\n }\n const result = manifestSchema({ allowLocalhost, base: address.manifestUrl }).safeParse(input);\n if (!result.success) {\n return invalid(result.error.issues.map((issue) => ({\n path: formatPath(issue.path),\n message: issue.message,\n })));\n }\n if (result.data.manifest_url !== address.manifestUrl) {\n return {\n success: false,\n reason: 'manifest_url_mismatch',\n errors: [\n {\n path: 'manifest_url',\n message: `Expected ${address.manifestUrl}, the address the manifest was read from`,\n },\n ],\n };\n }\n return { success: true, manifest: result.data };\n}\n//# sourceMappingURL=parse.js.map","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport {\n SIGNED_MANIFEST_MAX_BYTES,\n parseJsonText,\n signManifest,\n} from '@tryghost/app-contracts/identity';\nimport {\n formatManifestErrors,\n parseManifest,\n parseManifestUrl,\n} from '@tryghost/app-contracts/manifest';\n\nimport {\n publicKeyOf,\n readKey,\n readSigningKeys,\n type PrivateKeyJwk,\n type PublicKeyJwk,\n type ReadKeysOptions,\n} from './keys.ts';\nimport { UNKNOWN_GHOST_URL } from '../shared/manifest.ts';\nimport type { ManifestError, SignedManifest } from './types.ts';\n\n/** The readable manifest a project keeps, which the tooling signs. */\nexport const MANIFEST_FILE = 'ghost-app.json';\n\n/** The fields the tooling adds, which `ghost-app.json` mustn't set. */\nconst ADDED_FIELDS = ['manifest_url', 'identity_key', 'backend_key', 'development'] as const;\n\nexport interface SignOptions {\n /** The address the signed manifest will be served from, which it names as its own. */\n manifestUrl: string;\n identityKey: PrivateKeyJwk;\n /** Only its public half goes in the manifest. */\n backendKey: PrivateKeyJwk | PublicKeyJwk;\n /** Whether this is a development build, as it must be when any URL is on localhost. */\n development: boolean;\n}\n\nexport type SignResult =\n | {\n success: true;\n signed: SignedManifest;\n /** The manifest as signed, with the fields the tooling added. */\n manifest: Record<string, unknown>;\n }\n | {\n success: false;\n /**\n * As Ghost would refuse it: `APP_MANIFEST_INVALID`, `APP_MANIFEST_URL_INVALID`, or\n * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost fetches.\n */\n code: 'APP_MANIFEST_INVALID' | 'APP_MANIFEST_URL_INVALID' | 'APP_MANIFEST_TOO_LARGE';\n errors: ManifestError[];\n };\n\ntype Refusal = Extract<SignResult, { success: false }>;\n\nconst refuse = (code: Refusal['code'], message: string, path = ''): Refusal => ({\n success: false,\n code,\n errors: [{ path, message }],\n});\n\n/**\n * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it\n * with the identity key, unless Ghost would refuse it.\n */\nexport async function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult> {\n // A JWK carries both halves, so one passed in, rather than read from a file, could pair a\n // private half with another key's public half. The manifest would name a key that didn't sign\n // it, or one the backend can't answer for, and Ghost would refuse it. That's the caller's\n // mistake, so it throws.\n await readKey(JSON.stringify(options.identityKey), 'identityKey');\n if ('d' in options.backendKey) {\n await readKey(JSON.stringify(options.backendKey), 'backendKey');\n }\n // Ghost's own hosts are the one rule only a site knows, so a name no site has stands in.\n const address = parseManifestUrl(options.manifestUrl, {\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!address.success) {\n return refuse('APP_MANIFEST_URL_INVALID', address.error);\n }\n if (typeof source !== 'object' || source === null || Array.isArray(source)) {\n return refuse('APP_MANIFEST_INVALID', 'Expected the manifest as a JSON object');\n }\n // The fields signing adds can't come from the file, or the file could name other keys.\n const added = ADDED_FIELDS.filter((field) => field in source);\n if (added.length > 0) {\n return {\n success: false,\n code: 'APP_MANIFEST_INVALID',\n errors: added.map((field) => ({\n path: field,\n message: `Leave ${field} out: it's added when the manifest is signed`,\n })),\n };\n }\n\n const manifest = {\n ...source,\n manifest_url: address.manifestUrl,\n identity_key: publicKeyOf(options.identityKey),\n backend_key: publicKeyOf(options.backendKey),\n development: options.development,\n };\n // Checked by the rules Ghost applies, so a manifest Ghost would refuse is never signed, and\n // the result lists every problem by the path to its field.\n const parsed = parseManifest(manifest, {\n manifestUrl: address.manifestUrl,\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!parsed.success) {\n // A mismatch can't happen, as the manifest URL was just set; any failure is invalid.\n return { success: false, code: 'APP_MANIFEST_INVALID', errors: parsed.errors };\n }\n\n const signed = await signManifest(JSON.stringify(manifest), options.identityKey);\n // A valid manifest is far smaller than Ghost stores, but the payload keeps whatever the file\n // had, such as text Ghost trims, so it can still be larger than Ghost fetches.\n if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) {\n return refuse(\n 'APP_MANIFEST_TOO_LARGE',\n `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB`,\n );\n }\n return { success: true, signed, manifest };\n}\n\n/** A manifest's problems, one per line, as `path: message`, as Ghost lists them. */\nexport function formatErrors(errors: readonly ManifestError[]): string {\n return formatManifestErrors(errors, '\\n');\n}\n\n/** A signed manifest as the CLI and the Vite plugin write it to a file. */\nexport function serialiseSigned(signed: SignedManifest): string {\n return `${JSON.stringify(signed, null, 2)}\\n`;\n}\n\n/** Reads `ghost-app.json`, or another readable manifest, as JSON. */\nexport async function readManifestSource(file: string): Promise<unknown> {\n const text = await readFile(file, 'utf8');\n try {\n return parseJsonText(text);\n } catch (error) {\n throw new Error(`${file} isn't JSON: ${(error as Error).message}`, { cause: error });\n }\n}\n\nexport interface SignProjectOptions extends ReadKeysOptions {\n manifestUrl: string;\n /** The readable manifest, relative to `root`. `ghost-app.json` by default. */\n manifestFile?: string;\n}\n\n/** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */\nexport async function signProject({\n root,\n mode,\n env,\n manifestUrl,\n manifestFile = MANIFEST_FILE,\n}: SignProjectOptions): Promise<SignResult> {\n // Resolved, so an absolute path is taken as it is.\n const source = await readManifestSource(resolve(root, manifestFile));\n // Keys are read, never created: a missing one throws with how to create it.\n const keys = await readSigningKeys({ root, mode, env });\n return signAppManifest(source, { manifestUrl, ...keys, development: mode === 'development' });\n}\n"],"mappings":";;;;;;;;;;AAEA,IAAM,iBAAiB;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;AAMA,SAAgB,oBAAoB,UAAU;CAC1C,IAAI,MAAM,SAAS;CACnB,OAAO,MAAM,KAAK,SAAS,MAAM,OAAO,KACpC,OAAO;CAEX,OAAO,SAAS,MAAM,GAAG,GAAG;AAChC;;;;;;AAMA,SAAgB,YAAY,UAAU;CAClC,MAAM,OAAO,oBAAoB,QAAQ;CACzC,OAAO,eAAe,MAAM,YAAY,QAAQ,KAAK,IAAI,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;ACZA,SAAgB,YAAY,KAAK,WAAW;CACxC,MAAM,OAAO,OAAO,GAAG;CACvB,IAAI,SAAS,MACT,OAAO;CAEX,IAAI,QAAQ;CACZ,KAAK,MAAM,YAAY,WAAW;EAC9B,MAAM,YAAY,OAAO,QAAQ;EACjC,IAAI,cAAc,QAAQ,cAAc,MACpC,OAAO;EAEX,QAAQ;CACZ;CACA,OAAO,CAAC;AACZ;;AAEA,SAAgB,OAAO,OAAO;CAC1B,IAAI;CAEJ,IAAI;EACA,MAAM,IAAI,IAAI,KAAK;CACvB,QACM;EACF,OAAO;CACX;CACA,IAAI,IAAI,aAAa,WAAW,IAAI,aAAa,UAC7C,OAAO;CAEX,OAAO,oBAAoB,IAAI,QAAQ,KAAK;AAChD;AC9CA,IAAM,aAAa;;;;;;;AAOnB,SAAgB,aAAa,OAAO;CAChC,IAAI,OAAO,UAAU,YAAY,MAAM,SAAA,KACnC,OAAO;CAEX,MAAM,WAAW,MAAM,MAAM,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EAC3C,aAAa,QAAQ;CACvB;CAGA,MAAM,SAAS,cAAc,UAAU;EACrC,aAAa,QAAQ;EACrB,WAAW,CAAC,iBAAiB;EAC7B,gBAAgB;CAClB,CAAC;CACD,IAAI,CAAC,OAAO,SAEV,OAAO;EAAE,SAAS;EAAO,MAAM;EAAwB,QAAQ,OAAO;CAAO;CAG/E,MAAM,SAAS,MAAM,aAAa,KAAK,UAAU,QAAQ,GAAG,QAAQ,WAAW;CAG/E,IAAI,IAAI,YAAY,CAAC,CAAC,OAAO,gBAAgB,MAAM,CAAC,CAAC,CAAC,aAAa,2BACjE,OAAO,OACL,0BACA,yCAAyC,KAAK,MAAM,4BAA4B,IAAI,EAAE,IACxF;CAEF,OAAO;EAAE,SAAS;EAAM;EAAQ;CAAS;AAC3C;;AAGA,SAAgB,aAAa,QAA0C;CACrE,OAAO,qBAAqB,QAAQ,IAAI;AAC1C;;AAGA,SAAgB,gBAAgB,QAAgC;CAC9D,OAAO,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE;AAC5C;;AAGA,eAAsB,mBAAmB,MAAgC;CACvE,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM;CACxC,IAAI;EACF,OAAO,cAAc,IAAI;CAC3B,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,KAAK,eAAgB,MAAgB,WAAW,EAAE,OAAO,MAAM,CAAC;CACrF;AACF;;AASA,eAAsB,YAAY,EAChC,MACA,MACA,KACA,aACA,eAAe,iBAC2B;CAK1C,OAAO,gBAAgB,MAHF,mBAAmB,QAAQ,MAAM,YAAY,CAAC,GAGpC;EAAE;EAAa,GAAG,MAD9B,gBAAgB;GAAE;GAAM;GAAM;EAAI,CAAC;EACC,aAAa,SAAS;CAAc,CAAC;AAC9F"}
|
|
1
|
+
{"version":3,"file":"sign-kHwo5gGW.js","names":[],"sources":["../../../app-contracts/build/manifest/localhost.js","../../../app-contracts/build/manifest/ghost-host.js","../../../app-contracts/build/manifest/id.js","../../../app-contracts/build/manifest/limits.js","../../../app-contracts/build/identity/loading.js","../../../app-contracts/build/identity/signed-manifest.js","../../src/tooling/git.ts","../../src/tooling/keys.ts","../../../app-contracts/build/manifest/icon.js","../../../app-contracts/build/manifest/keys.js","../../../app-contracts/build/manifest/surfaces.js","../../../app-contracts/build/manifest/text.js","../../../app-contracts/build/manifest/url.js","../../../app-contracts/build/manifest/schema.js","../../../app-contracts/build/manifest/parse.js","../../src/tooling/sign.ts"],"sourcesContent":["// `URL` has already normalised the host by the time these run: every spelling of an IPv4\n// address is dotted decimal, and an IPv4-mapped IPv6 address is two hex groups.\nconst LOOPBACK_HOSTS = [\n /^localhost$/,\n /\\.localhost$/,\n /^127\\.\\d+\\.\\d+\\.\\d+$/,\n /^0\\.0\\.0\\.0$/,\n /^\\[::1?\\]$/,\n /^\\[::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}\\]$/,\n /^\\[::ffff:0:0\\]$/,\n];\n/**\n * A hostname without its trailing dots, which the URL parser keeps, every one of them:\n * `localhost..` is `localhost`. A loop rather than a regular expression, which would take\n * time quadratic in the number of dots on a hostname with many dots before its end.\n */\nexport function withoutTrailingDots(hostname) {\n let end = hostname.length;\n while (end > 0 && hostname[end - 1] === '.') {\n end -= 1;\n }\n return hostname.slice(0, end);\n}\n/**\n * Whether a host is the machine itself: `localhost`, or a loopback or unspecified address.\n * Pass `URL.hostname`, so the host is already normalised. Trailing dots are dropped, as\n * `isGhostHost` drops them.\n */\nexport function isLocalhost(hostname) {\n const host = withoutTrailingDots(hostname);\n return LOOPBACK_HOSTS.some((pattern) => pattern.test(host));\n}\n//# sourceMappingURL=localhost.js.map","import { withoutTrailingDots } from './localhost.js';\n/**\n * Whether a URL is on a host Ghost itself is served from: the site's, or Admin's, on any\n * port and over either scheme. A page on Ghost's origin would be Ghost, not the app,\n * whatever a frame's sandbox says. On another port it would be the app's, but browsers send\n * a host's cookies to every port on it, so the app's server would be sent the staff user's\n * session. So Ghost refuses a manifest URL on such a host, and Admin asks again where it\n * frames the page, since the site's or Admin's address can change after an app is\n * installed.\n *\n * Hosts are compared as the URL parser reads them, so case and IDN spellings agree, and\n * without a trailing dot. A sibling host, such as another subdomain of the site's, is not\n * Ghost's: the cookies Ghost sets are host-only. Nor is a name under Ghost's, such as\n * `my-app.localhost` next to `localhost`, or another name for the same machine, such as\n * `127.0.0.1`, which browsers treat as other hosts too.\n *\n * Any doubt counts as Ghost's: a URL that isn't http or https, a Ghost URL like that, or no\n * Ghost URLs at all. Either way the URL is refused.\n */\nexport function isGhostHost(url, ghostUrls) {\n const host = hostOf(url);\n if (host === null) {\n return true;\n }\n let known = false;\n for (const ghostUrl of ghostUrls) {\n const ghostHost = hostOf(ghostUrl);\n if (ghostHost === null || ghostHost === host) {\n return true;\n }\n known = true;\n }\n return !known;\n}\n/** An http or https URL's host as `isGhostHost` compares it, or null for any other. */\nexport function hostOf(value) {\n let url;\n // Admin runs this, and `URL.parse` is newer than the browsers Admin supports.\n try {\n url = new URL(value);\n }\n catch {\n return null;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return null;\n }\n return withoutTrailingDots(url.hostname) || null;\n}\n//# sourceMappingURL=ghost-host.js.map","/** Matches the limit of the index that ties saved cards to an app. */\nexport const APP_ID_MAX_LENGTH = 191;\nconst ID_SEGMENT = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n/**\n * An app ID is reverse-domain style: at least two dot-separated segments of lowercase\n * letters, digits and hyphens, starting with a letter so that an IP address or a version\n * number is not an ID. IDs are compared exactly, so an uppercase ID is invalid rather than\n * lowercased.\n */\nexport function isValidAppId(value) {\n if (typeof value !== 'string' || value.length > APP_ID_MAX_LENGTH) {\n return false;\n }\n const segments = value.split('.');\n return (segments.length >= 2 &&\n /^[a-z]/.test(value) &&\n segments.every((segment) => ID_SEGMENT.test(segment)));\n}\n//# sourceMappingURL=id.js.map","/**\n * The longest URL a manifest may hold, measured once resolved. Ghost stores every one of\n * them, the manifest's own URL included, so its columns are exactly this wide.\n */\nexport const URL_MAX_LENGTH = 2000;\n//# sourceMappingURL=limits.js.map","// How Ghost reads the signed manifest an app serves. Ghost core reads it by these, and the app\n// SDK signs by them, so a manifest it signs is one Ghost reads.\n/** The largest manifest Ghost stores, which it keeps in a TEXT column. */\nexport const MANIFEST_MAX_BYTES = 64 * 1024;\n/**\n * The largest signed manifest Ghost reads: the manifest in base64url is a third larger, and\n * the header and signature are well under a kilobyte, so a manifest of the largest size\n * still fits.\n */\nexport const SIGNED_MANIFEST_MAX_BYTES = Math.ceil((MANIFEST_MAX_BYTES * 4) / 3) + 1024;\n/** JSON text as Ghost reads it: a byte order mark is valid at its start, but JSON.parse refuses it. */\nexport function parseJsonText(text) {\n return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n}\n//# sourceMappingURL=loading.js.map","import { FlattenedSign, flattenedVerify, importJWK } from 'jose';\nimport { z } from 'zod';\nimport { ALGORITHM, readExactHeader } from './jws.js';\nimport { decodeText } from './keys.js';\n/** The `typ` a signed manifest's protected header carries, so no other signature passes as one. */\nexport const SIGNED_MANIFEST_TYPE = 'ghost-app-manifest';\nconst SignedManifestShape = z.strictObject({\n protected: z.string(),\n payload: z.string(),\n signature: z.string(),\n});\nconst ProtectedHeader = z.strictObject({\n alg: z.literal(ALGORITHM),\n typ: z.literal(SIGNED_MANIFEST_TYPE),\n});\nconst EXPECTED_HEADER = JSON.stringify({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE });\n/**\n * Signs a manifest with an app's identity key. A string is signed as the exact text it is;\n * anything else is signed as its JSON.\n */\nexport async function signManifest(manifest, identityKey) {\n const text = typeof manifest === 'string' ? manifest : JSON.stringify(manifest);\n const signed = await new FlattenedSign(new TextEncoder().encode(text))\n .setProtectedHeader({ alg: ALGORITHM, typ: SIGNED_MANIFEST_TYPE })\n .sign(identityKey);\n return { protected: signed.protected, payload: signed.payload, signature: signed.signature };\n}\n/**\n * Reads the manifest out of a signed manifest, without verifying it. The key to verify it\n * with is named inside the manifest, so the manifest has to be read and checked first;\n * nothing in it may be used until `verifySignedManifest` has passed.\n */\nexport function readSignedManifest(body) {\n const shape = SignedManifestShape.safeParse(body);\n if (!shape.success) {\n return {\n success: false,\n error: 'Expected a signed manifest: flattened JWS JSON with protected, payload and signature',\n };\n }\n const signed = shape.data;\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n const payload = decodeText(signed.payload);\n if (payload === undefined) {\n return { success: false, error: 'Expected a payload of UTF-8 text in base64url' };\n }\n return { success: true, signed, payload };\n}\n/**\n * Checks a signed manifest was signed with the identity key the manifest names, under\n * exactly the protected header `readSignedManifest` accepts.\n */\nexport async function verifySignedManifest(signed, identityKey) {\n let key;\n try {\n key = await importJWK(identityKey, ALGORITHM);\n }\n catch {\n return { success: false, error: 'identity_key is not a usable Ed25519 key' };\n }\n if (!readExactHeader(signed.protected, ProtectedHeader)) {\n return { success: false, error: `Expected a protected header of ${EXPECTED_HEADER}` };\n }\n try {\n await flattenedVerify(signed, key, { algorithms: [ALGORITHM] });\n }\n catch {\n return { success: false, error: 'The signature was not made with identity_key' };\n }\n return { success: true };\n}\n//# sourceMappingURL=signed-manifest.js.map","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\n\nimport { ignoreError } from '../shared/ignore.ts';\n\nexport type IgnoredResult = { ignored: true } | { ignored: false; reason: string };\n\nfunction git(args: string[], cwd: string, input?: string) {\n return new Promise<{ code: number | string | null; stdout: string; stderr: string }>((done) => {\n const child = execFile('git', args, { cwd }, (error, stdout, stderr) => {\n done({ code: error ? ((error as { code?: number | string }).code ?? 1) : 0, stdout, stderr });\n });\n // A git that couldn't start has no stdin to write to; its error arrives above.\n child.stdin?.on('error', ignoreError);\n child.stdin?.end(input);\n });\n}\n\nfunction insideRepository(directory: string): boolean {\n for (let current = resolve(directory); ; current = dirname(current)) {\n if (existsSync(join(current, '.git'))) {\n return true;\n }\n if (dirname(current) === current) {\n return false;\n }\n }\n}\n\n/**\n * The directory itself, or the nearest one above it that exists, to run git in: a project's\n * directory may not exist before its keys are written, and git can't start in one that doesn't.\n */\nfunction existingDirectory(directory: string): string {\n let current = resolve(directory);\n while (!existsSync(current) && dirname(current) !== current) {\n current = dirname(current);\n }\n return current;\n}\n\n/**\n * Whether git ignores every one of `files`, which needn't exist yet, so none can be committed by\n * accident. A file outside any repository counts as ignored.\n */\nexport async function isGitIgnored(\n root: string,\n files: string | readonly string[],\n): Promise<IgnoredResult> {\n // git can't start in a directory that doesn't exist, and a project's may not exist yet.\n const cwd = existingDirectory(root);\n const paths = (typeof files === 'string' ? [files] : files).map((file) => ({\n // As the developer named it, for messages, and as git is asked about it, from `cwd`.\n shown: relative(root, resolve(root, file)),\n asked: relative(cwd, resolve(root, file)),\n }));\n const named = `${paths.map(({ shown }) => shown).join(' and ')} ${paths.length > 1 ? 'are' : 'is'}`;\n\n const repository = await findRepository(cwd, named);\n if (repository !== 'inside') {\n return repository === 'outside' ? { ignored: true } : repository;\n }\n return askWhichAreIgnored(cwd, paths, named);\n}\n\n/** Whether `cwd` is in a repository, or why git can't say when it seems to be. */\nasync function findRepository(\n cwd: string,\n named: string,\n): Promise<'inside' | 'outside' | { ignored: false; reason: string }> {\n // Read from what git exits with, never from what it says, which is in the developer's\n // language. A `.git` that git can't read is still a repository, so it isn't taken as outside.\n const inside = await git(['rev-parse', '--is-inside-work-tree'], cwd);\n if (inside.code === 0) {\n return 'inside';\n }\n if (!insideRepository(cwd)) {\n return 'outside';\n }\n return {\n ignored: false,\n reason:\n inside.code === 'ENOENT'\n ? `git isn't installed, so it can't check ${named} ignored`\n : `git couldn't read the repository: ${inside.stderr.trim()}`,\n };\n}\n\nasync function askWhichAreIgnored(\n cwd: string,\n paths: { shown: string; asked: string }[],\n named: string,\n): Promise<IgnoredResult> {\n // One call for every path. It lists the ones it ignores, and exits with 1 when it ignores none.\n // Paths go in and out separated by NUL, as git would otherwise quote one with any byte outside\n // ASCII. A file git tracks isn't ignored, even if a `.gitignore` names it.\n const { code, stdout, stderr } = await git(\n ['check-ignore', '--stdin', '-z'],\n cwd,\n paths.map(({ asked }) => `${asked}\\0`).join(''),\n );\n if (code !== 0 && code !== 1) {\n return { ignored: false, reason: `git couldn't check ${named} ignored: ${stderr.trim()}` };\n }\n const ignored = new Set(stdout.split('\\0'));\n const notIgnored = paths.find(({ asked }) => !ignored.has(asked));\n return notIgnored\n ? { ignored: false, reason: `git doesn't ignore ${notIgnored.shown}` }\n : { ignored: true };\n}\n","import { generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { chmod, link, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nimport { publicHalfOf } from '../shared/keys.ts';\nimport { isGitIgnored } from './git.ts';\n\n/**\n * Which keys to use. Development and production have separate identity keys, so an app\n * installed from the developer's machine is a different app from the deployed one.\n */\nexport type Mode = 'development' | 'production';\n\n/** Where keys are kept, relative to the project: `.ghost-app/<mode>/<name>.json`. */\nexport const KEYS_DIRECTORY = '.ghost-app';\n\n/**\n * - `identity`: signs the manifest. It says who made the app, so it stays with the developer\n * (or their CI) and never reaches the backend or a bundle.\n * - `backend`: answers Ghost's challenge, so the backend holds it.\n */\nexport type KeyName = 'identity' | 'backend';\n\nexport const KEY_NAMES: readonly KeyName[] = ['identity', 'backend'];\n\n/** A private Ed25519 key as a JWK. */\nexport interface PrivateKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n d: string;\n}\n\n/** A public Ed25519 key as a JWK, as a manifest names it. */\nexport interface PublicKeyJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n}\n\n/** The production identity key, as CI provides it, instead of `.ghost-app/production/identity.json`. */\nexport const IDENTITY_KEY_VARIABLE = 'GHOST_APP_IDENTITY_KEY';\n\n/**\n * The backend key, as the backend reads it, and as CI may provide it to sign a production\n * manifest instead of `.ghost-app/production/backend.json`. Signing only needs its public half.\n */\nexport const BACKEND_KEY_VARIABLE = 'GHOST_APP_BACKEND_KEY';\n\nexport interface KeyOptions {\n /** The project's directory, which holds `.ghost-app/`. */\n root: string;\n mode: Mode;\n}\n\n/** The file a key is kept in, relative to the project. */\nexport function keyFile(mode: Mode, name: KeyName): string {\n return join(KEYS_DIRECTORY, mode, `${name}.json`);\n}\n\n/** A new private Ed25519 key. */\nexport function generateKey(): PrivateKeyJwk {\n const { x, d } = generateKeyPairSync('ed25519').privateKey.export({ format: 'jwk' });\n return { kty: 'OKP', crv: 'Ed25519', x: x!, d: d! };\n}\n\n/** A key's public half, with only `kty`, `crv` and `x`. */\nexport function publicKeyOf(key: PrivateKeyJwk | PublicKeyJwk): PublicKeyJwk {\n return { kty: 'OKP', crv: 'Ed25519', x: key.x };\n}\n\n/**\n * Reads a private key from JSON. `source` names where it came from, for the error: the key\n * itself is never in one.\n */\nexport async function readKey(text: string, source: string): Promise<PrivateKeyJwk> {\n const key = await readAnyKey(text, source);\n if (!('d' in key)) {\n throw new Error(`${source} is a public key; expected the private key, with d`);\n }\n return key;\n}\n\n/** Reads a key from JSON, private or public. */\nasync function readAnyKey(text: string, source: string): Promise<PrivateKeyJwk | PublicKeyJwk> {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new Error(`${source} isn't a key: it isn't JSON`);\n }\n if (!isEd25519(value)) {\n throw new Error(`${source} isn't an Ed25519 key as a JWK, with kty \"OKP\", crv \"Ed25519\" and x`);\n }\n const { d } = value as { d?: unknown };\n if (d === undefined) {\n return publicKeyOf(value);\n }\n // A key with a private part that doesn't read isn't a public key either.\n if (typeof d !== 'string') {\n throw new Error(`${source} isn't a usable Ed25519 key: its d isn't a string`);\n }\n // A JWK carries both halves, so a hand-edited or pasted one could pair a private half with\n // someone else's public half, and sign for a key the manifest doesn't name.\n const bytes = Buffer.from(d, 'base64url');\n if (bytes.length !== 32) {\n throw new Error(`${source} isn't a usable Ed25519 key`);\n }\n if ((await publicHalfOf(bytes)) !== value.x) {\n throw new Error(`${source} isn't a usable Ed25519 key: its x doesn't match its d`);\n }\n return { kty: 'OKP', crv: 'Ed25519', x: value.x, d } satisfies PrivateKeyJwk;\n}\n\nfunction isEd25519(value: unknown): value is { kty: 'OKP'; crv: 'Ed25519'; x: string } {\n const { kty, crv, x } = (typeof value === 'object' && value !== null ? value : {}) as Record<\n string,\n unknown\n >;\n return kty === 'OKP' && crv === 'Ed25519' && typeof x === 'string';\n}\n\nasync function readKeyFile(root: string, mode: Mode, name: KeyName): Promise<PrivateKeyJwk> {\n const file = keyFile(mode, name);\n let text: string;\n try {\n text = await readFile(join(root, file), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n throw new Error(missingKeyMessage(mode, name, file), { cause: error });\n }\n return readKey(text, file);\n}\n\n/** Says how to create a missing key, as nothing that reads keys creates one. */\nfunction missingKeyMessage(mode: Mode, name: KeyName, file: string): string {\n if (mode === 'development') {\n return `There's no development ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys\\`.`;\n }\n // In production, CI may provide the key as a variable instead.\n return `There's no production ${name} key: ${file} doesn't exist. Create one with \\`ghost-app keys --production\\`, or set ${variableFor(name)}.`;\n}\n\nconst variableFor = (name: KeyName) =>\n name === 'identity' ? IDENTITY_KEY_VARIABLE : BACKEND_KEY_VARIABLE;\n\nexport interface CreateKeysResult {\n /** The keys this call created. */\n created: KeyName[];\n /** The keys that already existed, which are never replaced. */\n kept: KeyName[];\n}\n\n/**\n * Creates a mode's missing identity and backend keys under `.ghost-app/<mode>/`, as files only\n * their owner can read, and keeps any that exist.\n */\nexport async function createKeys({ root, mode }: KeyOptions): Promise<CreateKeysResult> {\n // Each key is written whole to a temporary file beside it first, then linked to its name.\n const keys = KEY_NAMES.map((name) => {\n const file = keyFile(mode, name);\n const pending = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);\n return { name, file, pending };\n });\n // So a private key can't be committed by accident, git must ignore every file a key is\n // written to, the temporary ones included.\n await refuseUnlessGitIgnores(root, [\n ...keys.map(({ file }) => file),\n ...keys.map(({ pending }) => pending),\n ]);\n await mkdir(join(root, KEYS_DIRECTORY, mode), { recursive: true, mode: 0o700 });\n const result: CreateKeysResult = { created: [], kept: [] };\n for (const { name, file, pending } of keys) {\n // An existing key is kept: a new identity key would make the app a different app on every\n // site that installed it.\n const created = await publishKey(join(root, file), join(root, pending));\n result[created ? 'created' : 'kept'].push(name);\n }\n return result;\n}\n\nasync function refuseUnlessGitIgnores(root: string, files: string[]) {\n const ignored = await isGitIgnored(root, files);\n if (!ignored.ignored) {\n throw new Error(\n `Refusing to write private keys where git could commit them: ${ignored.reason}. Add ${KEYS_DIRECTORY}/ to .gitignore.`,\n );\n }\n}\n\n/** Writes a new key to `file` unless one is there, by way of `pending`, and says whether it did. */\nasync function publishKey(file: string, pending: string): Promise<boolean> {\n try {\n await writeFile(pending, `${JSON.stringify(generateKey(), null, 2)}\\n`, {\n flag: 'wx',\n // Only for its owner on macOS and Linux. Windows ignores the mode, and the key gets the\n // folder's inherited permissions, which the README tells developers to keep private.\n mode: 0o600,\n });\n // A link fails if the name is taken, so a key is never replaced, even by a concurrent run,\n // and an interrupted write never leaves part of a key where a key belongs.\n await link(pending, file);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n // Kept, but only for its owner, as a key written by hand or copied in may not be.\n if (process.platform !== 'win32' && ((await stat(file)).mode & 0o077) !== 0) {\n await chmod(file, 0o600);\n }\n return false;\n } finally {\n await rm(pending, { force: true });\n }\n}\n\nexport interface SigningKeys {\n identityKey: PrivateKeyJwk;\n /** The backend key's public half: all signing needs. */\n backendKey: PublicKeyJwk;\n}\n\nexport interface ReadKeysOptions extends KeyOptions {\n /** Where to read `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY` from, in production. */\n env?: Record<string, string | undefined>;\n}\n\n/**\n * Where `readSigningKeys` reads a mode's key from: the variable, in production when it's set to\n * anything but blanks, or else the key's file.\n */\nexport function signingKeySource(\n mode: Mode,\n name: KeyName,\n env: Record<string, string | undefined> = process.env,\n): string {\n const variable = variableFor(name);\n return mode === 'production' && env[variable]?.trim() ? variable : keyFile(mode, name);\n}\n\n/**\n * The keys to sign a mode's manifest with, from the key files, or in production from\n * `GHOST_APP_IDENTITY_KEY` and `GHOST_APP_BACKEND_KEY`, so CI can sign without the files.\n */\nexport async function readSigningKeys({\n root,\n mode,\n env = process.env,\n}: ReadKeysOptions): Promise<SigningKeys> {\n const fromVariable = (name: KeyName) =>\n signingKeySource(mode, name, env) === variableFor(name)\n ? env[variableFor(name)]!.trim()\n : undefined;\n\n const identityText = fromVariable('identity');\n const identityKey = identityText\n ? await sameAsFile(root, mode, 'identity', await readKey(identityText, IDENTITY_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'identity');\n\n // CI may provide only the backend key's public half, as signing needs nothing more.\n const backendText = fromVariable('backend');\n const backendKey = publicKeyOf(\n backendText\n ? await sameAsFile(root, mode, 'backend', await readAnyKey(backendText, BACKEND_KEY_VARIABLE))\n : await readKeyFile(root, mode, 'backend'),\n );\n\n if (identityKey.x === backendKey.x) {\n throw new Error('The identity key and the backend key are the same key; they must be two keys');\n }\n return { identityKey, backendKey };\n}\n\n/**\n * A key from a variable, after checking it's the same key as the file, where there's one. A\n * variable left set, such as a development key exported for every shell, would otherwise win over\n * the file unnoticed, and a manifest naming the wrong backend key retires the right one on every\n * site.\n */\nasync function sameAsFile<Key extends PublicKeyJwk>(\n root: string,\n mode: Mode,\n name: KeyName,\n key: Key,\n): Promise<Key> {\n const file = keyFile(mode, name);\n if (existsSync(join(root, file)) && (await readKeyFile(root, mode, name)).x !== key.x) {\n const variable = variableFor(name);\n throw new Error(\n `${variable} and ${file} are different ${name} keys. Unset ${variable} to sign with the file, or remove ${file} to sign with the variable.`,\n );\n }\n return key;\n}\n\n/** A mode's private backend key, from `.ghost-app/<mode>/backend.json`, for the backend to hold. */\nexport function readBackendKey({ root, mode }: KeyOptions): Promise<PrivateKeyJwk> {\n return readKeyFile(root, mode, 'backend');\n}\n","import { z } from 'zod';\nconst ICON_NAME_MAX_LENGTH = 64;\nconst ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst EITHER = 'Expected an icon with either a name or a url';\n/**\n * Ghost draws the icon on the app's accent colour: a named Admin icon or an image the app\n * serves. Ghost keeps a copy of the image with each manifest version it stores, and only\n * shows that copy. Unknown names aren't rejected, since they depend on the Admin build;\n * Admin falls back to a default icon.\n */\nexport function iconField(url) {\n return (z\n .strictObject({\n name: z\n .string('Expected an icon name')\n .max(ICON_NAME_MAX_LENGTH, `Expected at most ${ICON_NAME_MAX_LENGTH} characters`)\n .regex(ICON_NAME, 'Expected an icon name such as audio-lines')\n .optional(),\n url: url().optional(),\n }, EITHER)\n .refine(({ name, url: iconUrl }) => (name === undefined) !== (iconUrl === undefined), EITHER)\n // Only the type narrows: the value already is one or the other. A transform would\n // narrow it too, but one-way, and a stored manifest has to encode back through here.\n .pipe(z.custom()));\n}\n//# sourceMappingURL=icon.js.map","import { z } from 'zod';\n// 32 bytes in base64url without padding. The last character carries the final 4 bits and\n// 2 zero bits, so only 16 of the 64 characters can end it, which keeps the spelling of a key\n// unique.\nconst ED25519_X = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;\nconst EXPECTED = 'Expected a public Ed25519 key as a JWK with kty, crv and x';\nconst PRIVATE = 'Expected a public key, but this includes its private part (d)';\n/**\n * A key a manifest names. A manifest is public, so a key that includes its private part\n * is refused with a message of its own: it has to be replaced, not just removed. Other\n * members are refused by name, as key tools often add some, such as `kid` or `alg`.\n */\nexport const publicKeyField = z.strictObject({\n kty: z.literal('OKP', EXPECTED),\n crv: z.literal('Ed25519', EXPECTED),\n x: z.string(EXPECTED).regex(ED25519_X, 'Expected 32 bytes in base64url, without padding'),\n}, {\n error: (issue) => {\n if (issue.code !== 'unrecognized_keys') {\n return EXPECTED;\n }\n return issue.keys.includes('d')\n ? PRIVATE\n : `Expected only kty, crv and x; remove ${issue.keys.join(', ')}`;\n },\n});\n//# sourceMappingURL=keys.js.map","import { z } from 'zod';\n/**\n * What an app asks for: the places in Ghost it wants to appear. Each surface type is one\n * entry in a union, so a new one is added here and nowhere else.\n */\nexport function surfacesField(url) {\n const adminPage = z.strictObject({\n type: z.literal('admin_page'),\n url: url(),\n });\n const surfaceTypes = [adminPage];\n const surface = z.discriminatedUnion('type', surfaceTypes, {\n error: `Expected a surface with a type of: ${surfaceTypes.map((entry) => entry.shape.type.value).join(', ')}`,\n });\n return z\n .array(surface, 'Expected a list of surfaces')\n .min(1, 'Expected at least one surface')\n .superRefine((surfaces, ctx) => {\n const seen = new Set();\n surfaces.forEach((entry, index) => {\n if (seen.has(entry.type)) {\n ctx.addIssue({\n code: 'custom',\n message: `Expected at most one ${entry.type} surface`,\n path: [index],\n });\n }\n seen.add(entry.type);\n });\n });\n}\n//# sourceMappingURL=surfaces.js.map","import { z } from 'zod';\nimport { isPlainText } from '../plain-text.js';\n// A character that shows something on its own: a letter, digit, punctuation or symbol, but not\n// the blank Braille pattern or one Unicode says to draw as nothing, such as a joiner or a Hangul\n// filler. Whitespace and marks aren't any of those.\nconst VISIBLE_CHARACTER = new RegExp('(?![\\\\u2800\\\\p{Default_Ignorable_Code_Point}])[\\\\p{L}\\\\p{N}\\\\p{P}\\\\p{S}]', 'u');\nconst shows = (text) => VISIBLE_CHARACTER.test(text);\n// Shows nothing, and holds nothing plain text refuses other than whitespace, so trimming never\n// takes off a character, such as one that reorders text, that should get the text refused.\nconst blank = (character) => !shows(character) && isPlainText(character.replace(/\\s/gu, ''));\n// Made on first use, so loading the contract doesn't set one up.\nlet graphemes;\n/**\n * Takes off each end the characters, as a reader sees them, that show nothing: a space with a\n * mark on it goes, an emoji with its variation selector stays, and so does anything invisible\n * that joins onto a visible character. Walks in from each end, so a long run of spaces costs no\n * more than its length.\n */\nfunction trimEdges(value) {\n graphemes ??= new Intl.Segmenter();\n const characters = graphemes.segment(value);\n let start = value.length;\n for (const { segment, index } of characters) {\n if (!blank(segment)) {\n start = index;\n break;\n }\n }\n let end = value.length;\n while (end > start) {\n const { segment, index } = characters.containing(end - 1);\n if (!blank(segment)) {\n break;\n }\n end = index;\n }\n return value.slice(start, end);\n}\n/**\n * One line of plain text, as an app serves it. What shows nothing is taken off both ends, and\n * text with nothing visible left, such as a name of Hangul fillers, is refused.\n */\nexport function plainText(maxLength) {\n return (z\n .string('Expected text')\n // Whitespace first, as a character that joins onto a space, such as a skin tone, would keep it.\n .trim()\n .overwrite(trimEdges)\n .refine(shows, 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line'));\n}\n// Any letter, digit, punctuation or symbol, fillers included: the rule manifests were stored under\n// before blank names were refused.\nconst ANY_CHARACTER = /[\\p{L}\\p{N}\\p{P}\\p{S}]/u;\n/**\n * One line of plain text, as Ghost stored it. Laxer than `plainText`, so a manifest stored before\n * blank names were refused still reads, and the app can still be listed and uninstalled.\n */\nexport function storedText(maxLength) {\n return z\n .string('Expected text')\n .trim()\n .refine((value) => ANY_CHARACTER.test(value), 'Expected text')\n .max(maxLength, `Expected at most ${maxLength} characters`)\n .refine(isPlainText, 'Expected plain text on one line');\n}\n//# sourceMappingURL=text.js.map","import { z } from 'zod';\nimport { isContainedPath } from '../bridge/rules.js';\nimport { URL_MAX_LENGTH } from './limits.js';\nimport { isLocalhost } from './localhost.js';\nexport const FRAGMENT_PROBLEM = 'Expected a URL without a fragment';\n/**\n * Whether an address carries a fragment, even an empty one, which the parsed URL's `hash`\n * hides. A fragment never reaches the server, so a manifest address with one is a mistake or\n * a second spelling of the same address.\n */\nexport const hasFragment = (address) => address.includes('#');\n/**\n * Checks a URL once the URL parser has read it, so the rules apply to the URL Ghost would\n * use. The length is measured on the parsed URL for the same reason, as that is what is\n * stored and checked again later.\n */\nexport function checkResolvedUrl(url, allowLocalhost) {\n if (url.href.length > URL_MAX_LENGTH) {\n return `Expected at most ${URL_MAX_LENGTH} characters`;\n }\n if (url.username || url.password) {\n return 'Expected a URL without a username or password';\n }\n if (isLocalhost(url.hostname)) {\n if (!allowLocalhost) {\n return 'Expected a public address; localhost is only allowed when Ghost runs in development';\n }\n return url.protocol === 'https:' || url.protocol === 'http:'\n ? null\n : 'Expected an http or https URL';\n }\n return url.protocol === 'https:' ? null : 'Expected an https URL';\n}\nconst ROUTE_PROBLEM = 'Expected a URL that resolves to a path starting with a single /, with no \\\\ in its query or fragment';\nconst PATH_PROBLEM = 'Expected a path on the manifest’s own origin, such as /admin';\n// Two, so a reference that names one of them still names a host other than the other's.\nconst PLACEHOLDER_HOSTS = ['manifest-a.invalid', 'manifest-b.invalid'];\n/** Whether a reference names a host, in any of the URL parser's spellings of one. */\nconst namesHost = (value) => PLACEHOLDER_HOSTS.some((host) => URL.parse(value, `https://${host}/`)?.host !== host);\nfunction isManifestItself(url, base) {\n return url.pathname === new URL(base).pathname;\n}\n/**\n * A URL in the manifest. What Ghost loads is written as a path, resolved against the\n * address the manifest was fetched from, so an app is one origin: the one Ghost fetches\n * the manifest from and challenges is the one every surface runs on. The manifest names\n * that address as its signed `manifest_url`, so the resolved URLs are as fixed as if they\n * were written out. `parseManifestUrl` keeps that origin off Ghost's hosts.\n *\n * `linkOnly` marks a URL that is only ever linked to, never loaded, which is absolute and\n * may be anywhere, the publisher's own site included.\n *\n * A loaded URL's path, query and fragment must also make a path `isContainedPath` accepts.\n * Admin opens the app there, as its entry route, and the SDK refuses a route that isn't one.\n * Resolving can still give one that isn't: `/.//admin` resolves to the path `//admin`, which\n * names a host, and a `\\` in the query or fragment is left as it is. Only the page is opened\n * as a route, but every URL Ghost loads is held to the one rule.\n */\nexport function urlField({ allowLocalhost, base }, linkOnly = false) {\n if (linkOnly) {\n return z.string('Expected an absolute URL').transform((value, ctx) => {\n const url = URL.parse(value);\n const problem = url ? checkResolvedUrl(url, allowLocalhost) : 'Expected an absolute URL';\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n return url.href;\n });\n }\n const origin = new URL(base).origin;\n return z.string(PATH_PROBLEM).transform((value, ctx) => {\n // A path, or a path-relative reference. A URL with a scheme, or a `//host` one, names\n // its own origin, which the manifest's would then not be, even when it's the same one\n // today. An empty one, or one that's only a query or fragment, would be the manifest\n // itself.\n const url = URL.canParse(value) || namesHost(value) ? null : URL.parse(value, base);\n if (!url || url.origin !== origin || isManifestItself(url, base)) {\n ctx.addIssue({ code: 'custom', message: PATH_PROBLEM });\n return z.NEVER;\n }\n const problem = checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n ctx.addIssue({ code: 'custom', message: problem });\n return z.NEVER;\n }\n if (!isContainedPath(`${url.pathname}${url.search}${url.hash}`)) {\n ctx.addIssue({ code: 'custom', message: ROUTE_PROBLEM });\n return z.NEVER;\n }\n return url.href;\n });\n}\n/**\n * A URL as a manifest holds it once `parseManifest` has accepted it: absolute, and\n * already checked. Nothing is resolved or checked again, so a manifest accepted before the\n * site's URL changed still reads back.\n */\nexport const absoluteUrl = () => z.url('Expected an absolute URL');\n//# sourceMappingURL=url.js.map","import { z } from 'zod';\nimport { iconField } from './icon.js';\nimport { APP_ID_MAX_LENGTH, isValidAppId } from './id.js';\nimport { publicKeyField } from './keys.js';\nimport { isLocalhost } from './localhost.js';\nimport { surfacesField } from './surfaces.js';\nimport { plainText, storedText } from './text.js';\nimport { absoluteUrl, FRAGMENT_PROBLEM, hasFragment, urlField, } from './url.js';\nconst NAME_MAX_LENGTH = 50;\nconst DESCRIPTION_MAX_LENGTH = 200;\nconst AUTHOR_NAME_MAX_LENGTH = 50;\nconst HEX_COLOR = /^#[0-9a-f]{6}$/i;\nconst KEY_FIELDS = new Set(['identity_key', 'backend_key']);\nconst URL_FIELDS = new Set([\n 'author',\n 'icon',\n 'surfaces',\n 'manifest_url',\n 'development',\n]);\n/** Passes a refinement only once the fields it reads parsed, and the manifest is an object. */\nconst parsedFields = (fields) => ({ issues }) => issues.every(({ path = [] }) => path.length > 0 && !fields.has(path[0]));\n/**\n * The manifest as a whole. Unknown fields are rejected at every level, so an app cannot\n * claim something Ghost has not designed, and adding a field is always a deliberate change\n * here.\n *\n * Defined once, with the URL and text rules left open. What a valid URL is depends on whether\n * the manifest is being parsed, when where Ghost is served from matters, or read back after it\n * was, when it doesn't. Text is held to today's rules when parsed, and read back under the\n * rules it was stored under.\n */\nfunction manifestShape(url, text) {\n return (z\n .strictObject({\n id: z.custom(isValidAppId, {\n error: `Expected a lowercase reverse-domain ID such as com.example.app, at most ${APP_ID_MAX_LENGTH} characters`,\n }),\n name: text(NAME_MAX_LENGTH),\n description: text(DESCRIPTION_MAX_LENGTH),\n author: z.strictObject({\n name: text(AUTHOR_NAME_MAX_LENGTH),\n // Only ever linked to, so it may point at the publisher's own site.\n url: url(true),\n }, 'Expected an author with a name and a url'),\n accent_color: z\n .string('Expected a hex colour such as #ff5500')\n .regex(HEX_COLOR, 'Expected a hex colour such as #ff5500')\n .toLowerCase(),\n icon: iconField(url),\n surfaces: surfacesField(url),\n // Where the signed manifest is served from: the app's one origin, which every path\n // in it resolves against. Ghost fetches it server-side and never loads it as a page.\n manifest_url: url(true).refine((address) => !hasFragment(address), FRAGMENT_PROBLEM),\n identity_key: publicKeyField,\n backend_key: publicKeyField,\n // Lets Admin label a development build. Production sites may run one to test it.\n development: z.boolean('Expected true or false'),\n })\n // A backend holds its key online. If it also signed manifests, whoever took over the\n // backend could publish any manifest as the app.\n .refine((manifest) => manifest.identity_key.x !== manifest.backend_key.x, {\n message: 'Expected a different key from identity_key',\n path: ['backend_key'],\n // Only once both keys are known to be keys. An issue without a path is about the\n // manifest as a whole, which may not be an object at all.\n when: parsedFields(KEY_FIELDS),\n })\n // An app on the developer's machine is always labelled as a development build.\n .refine((manifest) => manifest.development ||\n ![\n manifest.author.url,\n 'url' in manifest.icon ? manifest.icon.url : undefined,\n ...manifest.surfaces.map((surface) => surface.url),\n manifest.manifest_url,\n ].some((address) => address !== undefined && isLocalhost(new URL(address).hostname)), {\n message: 'Expected true, as the app is on localhost',\n path: ['development'],\n when: parsedFields(URL_FIELDS),\n }));\n}\n/** The manifest as an app serves it. Built per parse, as its URL rule depends on the parse. */\nexport function manifestSchema(rules) {\n return manifestShape((linkOnly) => urlField(rules, linkOnly), plainText);\n}\n/**\n * The manifest as `parseManifest` hands it back: every URL absolute, and nothing left to\n * resolve or check. This is the schema to read a stored manifest with, as it holds\n * whatever the site's URL has become since, and it encodes a manifest back to the same\n * shape, so what is stored is what will be read.\n */\nexport const AppManifestSchema = manifestShape(absoluteUrl, storedText);\n//# sourceMappingURL=schema.js.map","import { hostOf, isGhostHost } from './ghost-host.js';\nimport { isLocalhost } from './localhost.js';\nimport { manifestSchema } from './schema.js';\nimport { checkResolvedUrl, FRAGMENT_PROBLEM, hasFragment } from './url.js';\nfunction formatPath(path) {\n return path.reduce((result, part) => {\n if (typeof part === 'number') {\n return `${result}[${part}]`;\n }\n return result ? `${result}.${String(part)}` : String(part);\n }, '');\n}\nconst GHOST_URLS_PROBLEM = 'Expected the URLs Ghost itself is served from';\nconst ON_GHOST_HOST = 'Expected the manifest on a host other than the one Ghost itself is served from, on any port, as browsers send Ghost’s cookies to every port on its host';\nconst ON_GHOST_HOST_LOCALLY = `${ON_GHOST_HOST}. To run the app on this machine too, serve it from a name of its own under .localhost, such as my-app.localhost`;\n/**\n * Why a manifest on one of Ghost's hosts is refused, with a hint for when that's most\n * likely: an app run next to Ghost on the developer's machine. A name under `.localhost`\n * is a host of its own, which browsers send to the machine itself, and so does Ghost in\n * development, whatever the system's resolver knows.\n */\nfunction onGhostHost(url) {\n return isLocalhost(url.hostname) ? ON_GHOST_HOST_LOCALLY : ON_GHOST_HOST;\n}\n/**\n * Reads the address a manifest is to be read from, by the same rules as the URLs inside\n * it, and checks it is on none of Ghost's hosts. Run it before fetching, so the first\n * request never goes to an address Ghost would refuse (plain HTTP, one carrying\n * credentials, or one on Ghost's host). It cannot judge where that address redirects,\n * which is for whatever fetches it to limit.\n *\n * The address it hands back is the one to store, to compare with a later one, and that the\n * manifest must name as its `manifest_url`. The URL parser settles most differences in\n * spelling, but not a trailing dot on the host or the case of a percent-encoding: an address spelled that way reads as a\n * change of manifest URL, which needs the publisher's approval, the safe way to be wrong.\n */\nexport function parseManifestUrl(input, { ghostUrls, allowLocalhost = false }) {\n if (ghostUrls.length === 0 || !ghostUrls.every((ghostUrl) => hostOf(ghostUrl) !== null)) {\n return { success: false, error: GHOST_URLS_PROBLEM };\n }\n const url = URL.parse(input);\n if (!url) {\n return { success: false, error: 'Expected the manifest at a URL' };\n }\n const problem = hasFragment(input) ? FRAGMENT_PROBLEM : checkResolvedUrl(url, allowLocalhost);\n if (problem) {\n return { success: false, error: `${problem} for the manifest itself` };\n }\n if (isGhostHost(url, ghostUrls)) {\n return { success: false, error: onGhostHost(url) };\n }\n return { success: true, manifestUrl: url.href };\n}\n/** A manifest's problems as `path: message`, joined by `separator`, as Ghost reports them. */\nexport function formatManifestErrors(errors, separator) {\n return errors\n .map(({ path, message }) => (path ? `${path}: ${message}` : message))\n .join(separator);\n}\nfunction invalid(errors) {\n return { success: false, reason: 'invalid', errors };\n}\n/**\n * Validates a manifest, and checks it names the address it was fetched from as its\n * `manifest_url`. A copy served from anywhere else is refused, so the signature binds the\n * manifest to its address as well as to every URL in it.\n *\n * Returns either the manifest, or every problem found. It does not fetch anything and it\n * never throws. Without the URLs Ghost is served from it rejects every manifest, since the\n * rule that keeps apps off Ghost's hosts could not be checked.\n */\nexport function parseManifest(input, options) {\n const allowLocalhost = options.allowLocalhost ?? false;\n const address = parseManifestUrl(options.manifestUrl, options);\n if (!address.success) {\n return invalid([{ path: '', message: address.error }]);\n }\n const result = manifestSchema({ allowLocalhost, base: address.manifestUrl }).safeParse(input);\n if (!result.success) {\n return invalid(result.error.issues.map((issue) => ({\n path: formatPath(issue.path),\n message: issue.message,\n })));\n }\n if (result.data.manifest_url !== address.manifestUrl) {\n return {\n success: false,\n reason: 'manifest_url_mismatch',\n errors: [\n {\n path: 'manifest_url',\n message: `Expected ${address.manifestUrl}, the address the manifest was read from`,\n },\n ],\n };\n }\n return { success: true, manifest: result.data };\n}\n//# sourceMappingURL=parse.js.map","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nimport type { AppFailureCode } from '@tryghost/app-contracts';\nimport {\n SIGNED_MANIFEST_MAX_BYTES,\n parseJsonText,\n signManifest,\n} from '@tryghost/app-contracts/identity';\nimport {\n formatManifestErrors,\n parseManifest,\n parseManifestUrl,\n} from '@tryghost/app-contracts/manifest';\n\nimport {\n publicKeyOf,\n readKey,\n readSigningKeys,\n type PrivateKeyJwk,\n type PublicKeyJwk,\n type ReadKeysOptions,\n} from './keys.ts';\nimport { UNKNOWN_GHOST_URL } from '../shared/manifest.ts';\nimport type { ManifestError, SignedManifest } from './types.ts';\n\n/** The readable manifest a project keeps, which the tooling signs. */\nexport const MANIFEST_FILE = 'ghost-app.json';\n\n/** The fields the tooling adds, which `ghost-app.json` mustn't set. */\nconst ADDED_FIELDS = ['manifest_url', 'identity_key', 'backend_key', 'development'] as const;\n\nexport interface SignOptions {\n /** The address the signed manifest will be served from, which it names as its own. */\n manifestUrl: string;\n identityKey: PrivateKeyJwk;\n /** Only its public half goes in the manifest. */\n backendKey: PrivateKeyJwk | PublicKeyJwk;\n /** Whether this is a development build, as it must be when any URL is on localhost. */\n development: boolean;\n}\n\nexport type SignResult =\n | {\n success: true;\n signed: SignedManifest;\n /** The manifest as signed, with the fields the tooling added. */\n manifest: Record<string, unknown>;\n }\n | {\n success: false;\n /**\n * As Ghost would refuse it: `APP_MANIFEST_INVALID`, `APP_MANIFEST_URL_INVALID`, or\n * `APP_MANIFEST_TOO_LARGE` for one larger than Ghost fetches.\n */\n code: 'APP_MANIFEST_INVALID' | 'APP_MANIFEST_URL_INVALID' | 'APP_MANIFEST_TOO_LARGE';\n errors: ManifestError[];\n };\n\n// Never if a code here stops being one Ghost answers with, so `refuse` stops compiling.\ntype Refusal = Extract<SignResult, { success: false; code: AppFailureCode }>;\n\nconst refuse = (code: Refusal['code'], message: string, path = ''): Refusal => ({\n success: false,\n code,\n errors: [{ path, message }],\n});\n\n/**\n * Adds the manifest URL, both public keys and the development flag to a manifest, and signs it\n * with the identity key, unless Ghost would refuse it.\n */\nexport async function signAppManifest(source: unknown, options: SignOptions): Promise<SignResult> {\n // A JWK carries both halves, so one passed in, rather than read from a file, could pair a\n // private half with another key's public half. The manifest would name a key that didn't sign\n // it, or one the backend can't answer for, and Ghost would refuse it. That's the caller's\n // mistake, so it throws.\n await readKey(JSON.stringify(options.identityKey), 'identityKey');\n if ('d' in options.backendKey) {\n await readKey(JSON.stringify(options.backendKey), 'backendKey');\n }\n // Ghost's own hosts are the one rule only a site knows, so a name no site has stands in.\n const address = parseManifestUrl(options.manifestUrl, {\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!address.success) {\n return refuse('APP_MANIFEST_URL_INVALID', address.error);\n }\n if (typeof source !== 'object' || source === null || Array.isArray(source)) {\n return refuse('APP_MANIFEST_INVALID', 'Expected the manifest as a JSON object');\n }\n // The fields signing adds can't come from the file, or the file could name other keys.\n const added = ADDED_FIELDS.filter((field) => field in source);\n if (added.length > 0) {\n return {\n success: false,\n code: 'APP_MANIFEST_INVALID',\n errors: added.map((field) => ({\n path: field,\n message: `Leave ${field} out: it's added when the manifest is signed`,\n })),\n };\n }\n\n const manifest = {\n ...source,\n manifest_url: address.manifestUrl,\n identity_key: publicKeyOf(options.identityKey),\n backend_key: publicKeyOf(options.backendKey),\n development: options.development,\n };\n // Checked by the rules Ghost applies, so a manifest Ghost would refuse is never signed, and\n // the result lists every problem by the path to its field.\n const parsed = parseManifest(manifest, {\n manifestUrl: address.manifestUrl,\n ghostUrls: [UNKNOWN_GHOST_URL],\n allowLocalhost: true,\n });\n if (!parsed.success) {\n // A mismatch can't happen, as the manifest URL was just set; any failure is invalid.\n return { success: false, code: 'APP_MANIFEST_INVALID', errors: parsed.errors };\n }\n\n const signed = await signManifest(JSON.stringify(manifest), options.identityKey);\n // A valid manifest is far smaller than Ghost stores, but the payload keeps whatever the file\n // had, such as text Ghost trims, so it can still be larger than Ghost fetches.\n if (new TextEncoder().encode(serialiseSigned(signed)).byteLength > SIGNED_MANIFEST_MAX_BYTES) {\n return refuse(\n 'APP_MANIFEST_TOO_LARGE',\n `Expected a signed manifest of at most ${Math.floor(SIGNED_MANIFEST_MAX_BYTES / 1024)} KB`,\n );\n }\n return { success: true, signed, manifest };\n}\n\n/** A manifest's problems, one per line, as `path: message`, as Ghost lists them. */\nexport function formatErrors(errors: readonly ManifestError[]): string {\n return formatManifestErrors(errors, '\\n');\n}\n\n/** A signed manifest as the CLI and the Vite plugin write it to a file. */\nexport function serialiseSigned(signed: SignedManifest): string {\n return `${JSON.stringify(signed, null, 2)}\\n`;\n}\n\n/** Reads `ghost-app.json`, or another readable manifest, as JSON. */\nexport async function readManifestSource(file: string): Promise<unknown> {\n const text = await readFile(file, 'utf8');\n try {\n return parseJsonText(text);\n } catch (error) {\n throw new Error(`${file} isn't JSON: ${(error as Error).message}`, { cause: error });\n }\n}\n\nexport interface SignProjectOptions extends ReadKeysOptions {\n manifestUrl: string;\n /** The readable manifest, relative to `root`. `ghost-app.json` by default. */\n manifestFile?: string;\n}\n\n/** Signs a project's `ghost-app.json` for a manifest URL with the mode's keys. */\nexport async function signProject({\n root,\n mode,\n env,\n manifestUrl,\n manifestFile = MANIFEST_FILE,\n}: SignProjectOptions): Promise<SignResult> {\n // Resolved, so an absolute path is taken as it is.\n const source = await readManifestSource(resolve(root, manifestFile));\n // Keys are read, never created: a missing one throws with how to create it.\n const keys = await readSigningKeys({ root, mode, env });\n return signAppManifest(source, { manifestUrl, ...keys, development: mode === 'development' });\n}\n"],"mappings":";;;;;;;;;;AAEA,IAAM,iBAAiB;CACnB;CACA;CACA;CACA;CACA;CACA;C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C,CAAC,OAAO,gBAAgB,MAAM,CAAC,CAAC,CAAC,aAAa,2BACjE,OAAO,OACL,0BACA,yCAAyC,KAAK,MAAM,4BAA4B,IAAI,EAAE,IACxF;CAEF,OAAO;EAAE,SAAS;EAAM;EAAQ;CAAS;AAC3C;;AAGA,SAAgB,aAAa,QAA0C;CACrE,OAAO,qBAAqB,QAAQ,IAAI;AAC1C;;AAGA,SAAgB,gBAAgB,QAAgC;CAC9D,OAAO,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE;AAC5C;;AAGA,eAAsB,mBAAmB,MAAgC;CACvE,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM;CACxC,IAAI;EACF,OAAO,cAAc,IAAI;CAC3B,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,KAAK,eAAgB,MAAgB,WAAW,EAAE,OAAO,MAAM,CAAC;CACrF;AACF;;AASA,eAAsB,YAAY,EAChC,MACA,MACA,KACA,aACA,eAAe,iBAC2B;CAK1C,OAAO,gBAAgB,MAHF,mBAAmB,QAAQ,MAAM,YAAY,CAAC,GAGpC;EAAE;EAAa,GAAG,MAD9B,gBAAgB;GAAE;GAAM;GAAM;EAAI,CAAC;EACC,aAAa,SAAS;CAAc,CAAC;AAC9F"}
|
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.17";
|
|
494
494
|
//#endregion
|
|
495
495
|
//#region src/connect.ts
|
|
496
496
|
/**
|
package/dist/app-sdk.js
CHANGED
|
@@ -1,3 +1,55 @@
|
|
|
1
|
+
//#region ../app-contracts/build/identity/codes.js
|
|
2
|
+
/**
|
|
3
|
+
* Ghost couldn't confirm the app is the one it says it is. Kept apart from an app that's down
|
|
4
|
+
* or broken because the publisher should hear something different: contact the developer, and
|
|
5
|
+
* don't install it again from a link, the one way a different developer's key gets pinned.
|
|
6
|
+
*/
|
|
7
|
+
var UNCONFIRMED_APP_CODES = [
|
|
8
|
+
"APP_MANIFEST_URL_MISMATCH",
|
|
9
|
+
"APP_MANIFEST_SIGNATURE_INVALID",
|
|
10
|
+
"APP_IDENTITY_MISMATCH",
|
|
11
|
+
"APP_BACKEND_KEY_RETIRED",
|
|
12
|
+
"APP_CHALLENGE_FAILED"
|
|
13
|
+
];
|
|
14
|
+
new Set(UNCONFIRMED_APP_CODES);
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region ../app-contracts/build/failure-codes.js
|
|
17
|
+
/** Trying again may work. */
|
|
18
|
+
var UNREACHABLE_APP_CODES = ["APP_MANIFEST_UNREACHABLE", "APP_CHALLENGE_UNREACHABLE"];
|
|
19
|
+
/** Only the app's developer can fix these. */
|
|
20
|
+
var UNUSABLE_MANIFEST_CODES = [
|
|
21
|
+
"APP_MANIFEST_URL_INVALID",
|
|
22
|
+
"APP_MANIFEST_REDIRECTED",
|
|
23
|
+
"APP_MANIFEST_TOO_LARGE",
|
|
24
|
+
"APP_MANIFEST_NOT_JSON",
|
|
25
|
+
"APP_MANIFEST_UNSIGNED",
|
|
26
|
+
"APP_MANIFEST_INVALID",
|
|
27
|
+
"APP_MANIFEST_OTHER_APP"
|
|
28
|
+
];
|
|
29
|
+
/**
|
|
30
|
+
* The publisher confirmed a review that's out of date. A changed manifest or installation
|
|
31
|
+
* carries the current review in the error's details when Ghost has one.
|
|
32
|
+
*/
|
|
33
|
+
var OUTDATED_REVIEW_CODES = [
|
|
34
|
+
"APP_MANIFEST_CHANGED",
|
|
35
|
+
"APP_INSTALLATION_CHANGED",
|
|
36
|
+
"APP_ALREADY_INSTALLED",
|
|
37
|
+
"APP_INSTALLATION_UNINSTALLED"
|
|
38
|
+
];
|
|
39
|
+
/**
|
|
40
|
+
* Admin can only explain a code listed here; any other shows as an unknown error. A Ghost
|
|
41
|
+
* core test checks the list against the codes the app installations service throws.
|
|
42
|
+
*/
|
|
43
|
+
var APP_FAILURE_CODES = [
|
|
44
|
+
...UNREACHABLE_APP_CODES,
|
|
45
|
+
...UNCONFIRMED_APP_CODES,
|
|
46
|
+
...UNUSABLE_MANIFEST_CODES,
|
|
47
|
+
...OUTDATED_REVIEW_CODES,
|
|
48
|
+
"APP_NOT_INSTALLED",
|
|
49
|
+
"APP_UNAVAILABLE"
|
|
50
|
+
];
|
|
51
|
+
new Set(APP_FAILURE_CODES);
|
|
52
|
+
new Set(OUTDATED_REVIEW_CODES);
|
|
1
53
|
//#endregion
|
|
2
54
|
//#region ../app-contracts/build/plain-text.js
|
|
3
55
|
var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
|
|
@@ -1218,7 +1270,7 @@ var Channel = class {
|
|
|
1218
1270
|
* `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
|
|
1219
1271
|
* and doesn't read package.json.
|
|
1220
1272
|
*/
|
|
1221
|
-
var SDK_VERSION = "0.1.0-alpha.
|
|
1273
|
+
var SDK_VERSION = "0.1.0-alpha.17";
|
|
1222
1274
|
//#endregion
|
|
1223
1275
|
//#region src/connect.ts
|
|
1224
1276
|
/**
|
package/dist/app-sdk.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-sdk.js","names":["#idsToFunction","#functionsToId","#idsToProxy","#finalizationRegistry","#finalization","#customSerializer","#customDeserializer","#serializeInternal","#deserializeInternal","#abort","#handlerForCall","#idsToResolver","#resolveCall","#callLocal","#waitForResult","#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":["../../app-contracts/build/identity/codes.js","../../app-contracts/build/plain-text.js","../../app-contracts/build/bridge/rules.js","../src/errors.ts","node_modules/@quilted/threads/build/esm/constants.mjs","node_modules/@quilted/events/build/esm/abort/NestedAbortController.mjs","node_modules/@quilted/threads/build/esm/errors.mjs","node_modules/@quilted/threads/build/esm/nanoid.mjs","node_modules/@quilted/threads/build/esm/functions/ThreadFunctionsAutomatic.mjs","node_modules/@quilted/threads/build/esm/serialization/shared.mjs","node_modules/@quilted/threads/build/esm/serialization/ThreadSerializationStructuredClone.mjs","node_modules/@quilted/threads/build/esm/Thread.mjs","node_modules/@quilted/threads/build/esm/threads/ThreadMessagePort.mjs","../src/fetch.ts","../src/history.ts","../src/title.ts","../src/session.ts","../src/version.ts","../src/connect.ts"],"sourcesContent":["/**\n * The codes Ghost fails with when it couldn't confirm an app is the one it says it is,\n * whether reviewing an install link or starting a session. They're kept apart from the\n * codes for an app that is down or broken, because the publisher should hear something\n * different: contact the developer, and don't install it again from a link, which is the\n * one way a different developer's key gets pinned.\n *\n * Free of jose and zod, so Admin reads it from the root entry point.\n */\nexport const UNCONFIRMED_APP_CODES = [\n /** The manifest names another address than the one it was fetched from. */\n 'APP_MANIFEST_URL_MISMATCH',\n /** The signature wasn't made with the identity key the manifest names. */\n 'APP_MANIFEST_SIGNATURE_INVALID',\n /** The manifest is signed with another key than the one the app was installed with. */\n 'APP_IDENTITY_MISMATCH',\n /** The manifest names a backend key a newer manifest from the same developer replaced. */\n 'APP_BACKEND_KEY_RETIRED',\n /** The app's origin didn't answer the challenge with the manifest's backend key. */\n 'APP_CHALLENGE_FAILED',\n];\nconst UNCONFIRMED = new Set(UNCONFIRMED_APP_CODES);\nexport function isUnconfirmedAppCode(code) {\n return UNCONFIRMED.has(code);\n}\n//# sourceMappingURL=codes.js.map","// What plain text may contain: letters, combining marks, digits, punctuation, symbols and\n// spaces, plus the two joiners that emoji sequences and scripts such as Persian need.\n// Everything else is refused by not being listed: control and formatting characters, line\n// breaks, the characters that reorder text, private-use and unassigned code points. Those can\n// make text display as something other than what it is, such as a title that reverses\n// whatever Admin shows after it.\nconst ALLOWED = '\\\\p{L}\\\\p{M}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\\\\u200C\\\\u200D';\nconst PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, 'u');\nconst NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, 'gu');\n/** Whether text is one line of plain text, as a name, a description or a title must be. */\nexport function isPlainText(value) {\n return PLAIN_TEXT.test(value);\n}\n/** Returns the text with the characters `isPlainText` refuses removed. */\nexport function toPlainText(value) {\n return value.replace(NOT_PLAIN_TEXT, '');\n}\n//# sourceMappingURL=plain-text.js.map","/**\n * The bridge's rules that have no dependencies. The root entry point exports them so the SDK\n * can use them without zod. The schemas in this folder build on them, so the SDK and Admin\n * read a path or a refusal the same way.\n *\n * What Admin sends the page has no schema, because Admin builds it and never parses it. Its\n * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so\n * the guards only check shape and path containment. They turn a mismatch into a clear error\n * rather than `undefined` somewhere in the app. Only the schemas check limits.\n */\n/** Posted by the app's page to `window.parent` once the SDK has loaded. */\nexport const HELLO_MESSAGE_TYPE = 'ghost-app:hello';\n/** Posted by Admin to the frame that sent the hello, with the channel's port attached. */\nexport const CONNECT_MESSAGE_TYPE = 'ghost-app:connect';\n/**\n * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long\n * after mounting it, and the SDK waits this long for Admin to start the app unless the app\n * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send\n * its hello.\n */\nexport const START_TIMEOUT_MS = 10_000;\n/** Long enough for any real page title, short enough that Admin's own name still shows. */\nexport const TITLE_MAX_LENGTH = 200;\n/**\n * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK\n * uppercases what apps pass.\n */\nexport const FETCH_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];\n/**\n * Whether a request with this method may carry a body. Expects an uppercase method from\n * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.\n */\nexport function methodAllowsBody(method) {\n return method !== 'GET';\n}\n// The headers Admin sets itself on a request it makes for an app: the credentials, which only\n// Admin may send; Admin's own markers, which Ghost core treats as coming from Admin; the headers\n// that describe the connection, or the proxies along the way, rather than the request; and the\n// ones that say how to read the body. A body is always JSON, which Admin labels itself: the Admin\n// API also reads forms and uploads, and decodes JSON in any charset it's told, so a content type\n// of the app's choosing could carry a write past the checks on what it contains.\nconst RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;\n/**\n * Whether a request header is one that apps may not set, in any case. Admin refuses a request\n * that sets one rather than dropping the header, so the app gets an error instead of wondering\n * why the header never arrived. The browser refuses some of these anyway; they are listed here\n * so that none of them relies on the browser.\n */\nexport function isReservedRequestHeader(name) {\n return RESERVED_REQUEST_HEADER.test(name);\n}\n/**\n * The messages Admin and the SDK use when they refuse an argument for the same reason, so an\n * app gets the same message whichever side catches the problem. The SDK checks only for obvious\n * mistakes, before anything crosses the channel; Admin's schemas check everything again.\n */\nexport const ARGUMENT_MESSAGES = {\n fetchPath: 'Expected an Admin API path such as /posts/, not a URL',\n fetchMethod: `Expected a method of: ${FETCH_METHODS.join(', ')}`,\n fetchBody: 'Expected no body on a GET request',\n // Header names are case-insensitive, and `Headers` lowercases them on the SDK's side, so the\n // name is lowercased here too and both sides produce the same message.\n reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,\n jsonBody: 'Expected the body as JSON text',\n appPath: 'Expected a path within the app, starting with a single /',\n pathMove: 'Expected a move of push or replace',\n place: 'Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }',\n};\n/**\n * The statuses a `fetch` response may have. The SDK turns the response back into a\n * `Response`, which only accepts statuses from 200 to 599. Fetch never returns an\n * informational (1xx) status to scripts anyway.\n */\nexport const FETCH_RESPONSE_STATUS_MIN = 200;\nexport const FETCH_RESPONSE_STATUS_MAX = 599;\n/**\n * The codes a refused call carries across the channel. The structured clone that carries an\n * error keeps only its message, so the refusing side puts the code at the start of the\n * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes\n * are only ever added: an SDK that doesn't know a code treats the whole message as a generic\n * refusal.\n *\n * The host codes, which Admin refuses the page's calls with:\n *\n * - `session_ended`: the session is over; the page is about to be replaced.\n * - `invalid_argument`: an argument Admin does not take.\n * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one\n * the Admin API only responds to with a redirect, such as a path without its trailing `/`.\n * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: anything else; the detail says why.\n */\nexport const HOST_ERROR_CODES = [\n 'session_ended',\n 'invalid_argument',\n 'invalid_path',\n 'blocked',\n 'network_error',\n 'rejected',\n];\n/**\n * The app codes, which the page refuses Admin's calls with:\n *\n * - `invalid_context`: a start context the SDK cannot read, or a call before the app has\n * started.\n * - `invalid_argument`: an argument the SDK does not take, such as a theme it cannot read.\n */\nexport const APP_ERROR_CODES = ['invalid_context', 'invalid_argument'];\n/** Every code a refusal can carry, in either direction. */\nexport const BRIDGE_ERROR_CODES = [...HOST_ERROR_CODES, 'invalid_context'];\nconst CODED_MESSAGE = /^([a-z_]+): ([\\s\\S]*)$/;\n/**\n * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass\n * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.\n */\nexport function encodeBridgeError(code, detail) {\n return `${code}: ${detail}`;\n}\n/**\n * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the\n * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for\n * one from the page. Returns `undefined` for a message that doesn't start with one of them.\n */\nexport function decodeBridgeError(message, codes) {\n const [, code = '', detail = ''] = CODED_MESSAGE.exec(message) ?? [];\n return codes.includes(code) ? { code: code, detail } : undefined;\n}\nconst THEME_MODES = ['light', 'dark'];\n// URL parsers and routers don't agree on whether to strip or refuse control characters, so a\n// path containing one can mean something different to each of them.\nconst CONTROL_CHARACTER = /\\p{Cc}/u;\n/**\n * Whether a value is a path that stays within the base it is resolved against, rather than\n * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as\n * `//host`. It must not contain `\\`, which URL parsers read as `/`, or any control character.\n */\nexport function isContainedPath(value) {\n return (typeof value === 'string' &&\n value.startsWith('/') &&\n !value.startsWith('//') &&\n !value.includes('\\\\') &&\n !CONTROL_CHARACTER.test(value));\n}\n// Used only as a base for parsing, never requested. Parsing against it gives a path the URL\n// parser's normalised form.\nconst APP_PATH_BASE = 'https://app.invalid';\n/**\n * Returns an app path in the URL parser's normalised form, the one form Admin and the SDK\n * store it in. `.` and `..` are resolved within the app, so `..` can never climb above its root.\n * Characters that need escaping are escaped once, so a path the app reported compares equal to\n * the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and\n * `/x/../episodes/1` becomes `/episodes/1`.\n *\n * Expects a path that `isContainedPath` accepts; anything else may not be a path within the\n * app at all. Even then, the result may not be: resolving `.` and `..` can leave `//` at the\n * start, so `/.//host` becomes `//host`, which resolves to another site. Check the result with\n * `isContainedPath` before resolving it against anything. `AppPathSchema` does both and returns\n * this form.\n */\nexport function normaliseAppPath(path) {\n const url = new URL(path, APP_PATH_BASE);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n/** An object, or an array: anything whose fields can be read. */\nexport function isRecord(value) {\n return typeof value === 'object' && value !== null;\n}\nfunction hasStrings(value, keys) {\n return isRecord(value) && keys.every((key) => typeof value[key] === 'string');\n}\nexport function isTheme(value) {\n return (hasStrings(value, ['accent_color']) && THEME_MODES.includes(value.mode));\n}\nexport function isStartContext(value) {\n return (isRecord(value) &&\n hasStrings(value.site, ['url', 'title', 'timezone', 'locale']) &&\n hasStrings(value.user, ['id', 'role']) &&\n isTheme(value.theme) &&\n isRecord(value.session) &&\n Number.isSafeInteger(value.session.revision) &&\n value.session.revision >= 0 &&\n isContainedPath(value.path));\n}\nexport function isConnectMessage(value) {\n return (isRecord(value) &&\n value.type === CONNECT_MESSAGE_TYPE &&\n Array.isArray(value.exports) &&\n value.exports.every((name) => typeof name === 'string'));\n}\nexport function isFetchResponse(value) {\n return (isRecord(value) &&\n Number.isSafeInteger(value.status) &&\n value.status >= FETCH_RESPONSE_STATUS_MIN &&\n value.status <= FETCH_RESPONSE_STATUS_MAX &&\n typeof value.statusText === 'string' &&\n isRecord(value.headers) &&\n !Array.isArray(value.headers) &&\n Object.values(value.headers).every((header) => typeof header === 'string') &&\n typeof value.body === 'string');\n}\n//# sourceMappingURL=rules.js.map","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","const MESSAGE_CALL = 1;\nconst MESSAGE_CALL_RESULT = 2;\nconst MESSAGE_FUNCTION_CALL = 3;\nconst MESSAGE_FUNCTION_RESULT = 4;\nconst MESSAGE_FUNCTION_RELEASE = 5;\nconst SERIALIZE_METHOD = Symbol.for('quilt.threads.serialize');\nconst TRANSFERABLE = Symbol.for('quilt.threads.transferable');\n\nexport { MESSAGE_CALL, MESSAGE_CALL_RESULT, MESSAGE_FUNCTION_CALL, MESSAGE_FUNCTION_RELEASE, MESSAGE_FUNCTION_RESULT, SERIALIZE_METHOD, TRANSFERABLE };\n","/**\n * An `AbortController` that will automatically abort when any of\n * its \"parent\" `AbortController`s abort. This is useful for when\n * you have nested asynchronous operations that may abort independently.\n * The `AbortController` can also be independently aborted.\n *\n * To associate the parent `AbortController`s, pass their signals\n * as arguments to the constructor.\n *\n * @example\n * import {NestedAbortController} from '@shopify/events';\n *\n * const parent = new AbortController();\n * const nested = new NestedAbortController(parent.signal);\n *\n * parent.abort();\n * nested.signal.aborted; // true\n */\nclass NestedAbortController extends AbortController {\n constructor(...parents) {\n super();\n const abortedSignal = parents.find(signal => signal.aborted);\n if (abortedSignal) {\n this.abort(abortedSignal.reason);\n } else {\n const abort = event => this.abort(event.target.reason);\n const options = {\n signal: this.signal\n };\n for (const signal of parents) {\n signal.addEventListener('abort', abort, options);\n }\n }\n }\n}\n\nexport { NestedAbortController };\n","class ThreadClosedError extends Error {\n constructor() {\n super('You attempted to call a function on a closed thread.');\n }\n}\n\nexport { ThreadClosedError };\n","// Copied from https://github.com/ai/nanoid/blob/main/nanoid.js\nlet a = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';\nfunction nanoid(e = 21) {\n let t = '',\n r = crypto.getRandomValues(new Uint8Array(e));\n for (let n = 0; n < e; n++) t += a[63 & r[n]];\n return t;\n}\n\nexport { nanoid };\n","import { MESSAGE_FUNCTION_CALL, MESSAGE_FUNCTION_RELEASE } from '../constants.mjs';\nimport { nanoid } from '../nanoid.mjs';\n\n/**\n * A strategy for managing functions across threads that automatically releases\n * functions when they are no longer needed. This is done by deserializing functions\n * into a proxy that can be called, and wrapping that proxy in a `FinalizationRegistry`,\n * which allows us to send a message to the parent thread when the function is no\n * longer used.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\nclass ThreadFunctionsAutomatic {\n #functionsToId = (() => new Map())();\n #idsToFunction = (() => new Map())();\n #idsToProxy = (() => new Map())();\n #finalization = (() => new WeakMap())();\n get(id) {\n return this.#idsToFunction.get(id);\n }\n release(id) {\n const func = this.#idsToFunction.get(id);\n if (func) {\n this.#idsToFunction.delete(id);\n this.#functionsToId.delete(func);\n }\n return Boolean(func);\n }\n serialize(func) {\n let id = this.#functionsToId.get(func);\n if (id == null) {\n id = nanoid();\n this.#functionsToId.set(func, id);\n this.#idsToFunction.set(id, func);\n }\n return id;\n }\n deserialize(id, thread) {\n let proxy = this.#idsToProxy.get(id)?.deref();\n if (proxy) return proxy;\n proxy = (...args) => {\n if (!this.#idsToProxy.has(id)) {\n throw new Error('You attempted to call a function that was already revoked.');\n }\n return thread.call((callID, args, transferable) => {\n thread.messages.send([MESSAGE_FUNCTION_CALL, callID, id, args], transferable);\n }, args);\n };\n this.#finalizationRegistry(thread)?.register(proxy, id);\n this.#idsToProxy.set(id, new WeakRef(proxy));\n return proxy;\n }\n #finalizationRegistry(thread) {\n let finalization = this.#finalization.get(thread);\n if (typeof FinalizationRegistry === 'undefined') {\n return undefined;\n }\n if (!finalization) {\n finalization = new FinalizationRegistry(id => {\n thread.messages.send([MESSAGE_FUNCTION_RELEASE, id]);\n });\n this.#finalization.set(thread, finalization);\n }\n return finalization;\n }\n}\n\nexport { ThreadFunctionsAutomatic };\n","function isIterator(value) {\n return value != null && (Symbol.asyncIterator in value || Symbol.iterator in value) && typeof value.next === 'function';\n}\nfunction isBasicObject(value) {\n if (value == null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype == null || prototype === Object.prototype;\n}\n\nexport { isBasicObject, isIterator };\n","import { TRANSFERABLE, SERIALIZE_METHOD } from '../constants.mjs';\nimport { isIterator, isBasicObject } from './shared.mjs';\n\nconst FUNCTION = '_@f';\nconst ASYNC_ITERATOR = '_@i';\n\n/**\n * A thread encoder that can transfer supports a wide variety of JavaScript types by\n * converting them to a format that the [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)\n * algorithm can process. This\n *\n * Additionally, this encoder will convert functions into a JSON-friendly representation.\n * These functions will use a manual memory management technique to ensure they can be\n * garbage collected by default, but can be configured to use a `WeakRef`-based automatic\n * memory management system by setting the `garbageCollection: 'weak-ref'` option.\n */\nclass ThreadSerializationStructuredClone {\n #customSerializer;\n #customDeserializer;\n constructor(options) {\n this.#customSerializer = options?.serialize;\n this.#customDeserializer = options?.deserialize;\n }\n\n /**\n * Serializes a value into a structured cloning-compatible format that can be transferred between threads.\n */\n serialize(value, thread, transferable) {\n return this.#serializeInternal(value, thread, transferable);\n }\n #serializeInternal(value, thread, transferable, seen = new Map(), isApplyingDefault = false) {\n if (value == null) return value;\n if (seen.has(value)) return seen.get(value);\n\n // Prevent circular references\n seen.set(value, undefined);\n if (typeof value === 'object') {\n if (this.#customSerializer && !isApplyingDefault) {\n const customValue = this.#customSerializer(value, value => this.#serializeInternal(value, thread, transferable, seen, true), thread, transferable);\n if (customValue !== undefined) {\n seen.set(value, customValue);\n return customValue;\n }\n }\n if (value[TRANSFERABLE]) {\n transferable?.push(value);\n seen.set(value, value);\n return value;\n }\n const serializeValue = value => {\n return this.#serializeInternal(value, thread, transferable, seen);\n };\n if (typeof value[SERIALIZE_METHOD] === 'function') {\n const result = value[SERIALIZE_METHOD]({\n serialize: serializeValue\n });\n seen.set(value, result);\n return result;\n }\n if (Array.isArray(value)) {\n const result = value.map(item => serializeValue(item));\n seen.set(value, result);\n return result;\n }\n if (value instanceof Map) {\n const entries = [...value.entries()].map(([key, value]) => {\n return [serializeValue(key), serializeValue(value)];\n });\n const result = new Map(entries);\n seen.set(value, result);\n return result;\n }\n if (value instanceof Set) {\n const entries = [...value].map(entry => serializeValue(entry));\n const result = new Set(entries);\n seen.set(value, result);\n return result;\n }\n const valueIsIterator = isIterator(value);\n if (isBasicObject(value) || valueIsIterator) {\n const result = {};\n for (const key of Object.keys(value)) {\n result[key] = serializeValue(value[key]);\n }\n if (valueIsIterator) {\n result.next ??= serializeValue(value.next.bind(value));\n result.return ??= serializeValue(value.return.bind(value));\n result.throw ??= serializeValue(value.throw.bind(value));\n result[ASYNC_ITERATOR] = true;\n }\n seen.set(value, result);\n return result;\n }\n }\n if (typeof value === 'function') {\n const serialized = thread.functions.serialize(value, thread, transferable);\n const result = {\n [FUNCTION]: serialized\n };\n seen.set(value, result);\n return result;\n }\n seen.set(value, value);\n return value;\n }\n\n /**\n * Deserializes a structured cloning-compatible value from another thread.\n */\n deserialize(value, thread) {\n return this.#deserializeInternal(value, thread);\n }\n #deserializeInternal(value, thread, isApplyingDefault = false) {\n if (value == null) return value;\n if (typeof value === 'object') {\n if (this.#customDeserializer && !isApplyingDefault) {\n const customValue = this.#customDeserializer(value, value => this.#deserializeInternal(value, thread, true), thread);\n if (customValue !== undefined) {\n return customValue;\n }\n }\n if (value == null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(value => this.#deserializeInternal(value, thread));\n }\n if (value instanceof Map) {\n return new Map([...value].map(([key, value]) => [this.#deserializeInternal(key, thread), this.#deserializeInternal(value, thread)]));\n }\n if (value instanceof Set) {\n return new Set([...value].map(entry => this.#deserializeInternal(entry, thread)));\n }\n if (FUNCTION in value) {\n const func = thread.functions.deserialize(value[FUNCTION], thread);\n return func;\n }\n if (!isBasicObject(value)) {\n return value;\n }\n const result = {};\n for (const key of Object.keys(value)) {\n if (key === ASYNC_ITERATOR) {\n result[Symbol.asyncIterator] = () => result;\n } else {\n result[key] = this.#deserializeInternal(value[key], thread);\n }\n }\n return result;\n }\n return value;\n }\n}\n\nexport { ThreadSerializationStructuredClone };\n","import { NestedAbortController } from '@quilted/events';\nimport { ThreadClosedError } from './errors.mjs';\nimport { nanoid } from './nanoid.mjs';\nimport { MESSAGE_FUNCTION_RELEASE, MESSAGE_FUNCTION_RESULT, MESSAGE_CALL_RESULT, MESSAGE_FUNCTION_CALL, MESSAGE_CALL } from './constants.mjs';\nimport { ThreadFunctionsAutomatic } from './functions/ThreadFunctionsAutomatic.mjs';\nimport { ThreadSerializationStructuredClone } from './serialization/ThreadSerializationStructuredClone.mjs';\n\n/**\n * An object that can serialize and deserialize values communicated between two threads.\n */\n\n/**\n * An object that can serialize and deserialize values communicated between two threads.\n */\n\n/**\n * Options to customize the creation of a `ThreadSerialization` instance.\n */\n\n/**\n * Options to customize the creation of a `Thread` instance.\n */\n\n/**\n * An object backing a `Thread` that provides the message-passing interface\n * that allows communication to flow between environments. This message-passing\n * interface is based on the [`postMessage` interface](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage),\n * which is easily adaptable to many JavaScript objects and environments.\n */\n\n/**\n * A map of messages that can be sent between threads.\n */\n\n/**\n * The possible data payloads that can be transferred between threads.\n */\n\n/**\n * A helper type that extracts all callable methods that can be safely proxied\n * between threads; that is, ones which return a promise or async iterator.\n */\n\n/**\n * A thread represents a target JavaScript environment that exposes a set\n * of callable, asynchronous methods. The thread takes care of automatically\n * encoding and decoding its arguments and return values, so you can interact\n * with it as if its methods were implemented in the same environment as your\n * own code.\n */\nclass Thread {\n /**\n * An object that exposes the methods that can be called on the paired thread.\n * This object will automatically encode and decode arguments and return values\n * as necessary.\n */\n\n /**\n * An object that exposes the methods that can be called on this thread by the\n * paired thread. To set these methods, pass the `exports` option when creating\n * a new `Thread`.\n */\n\n /**\n * An object that provides the message-passing interface that allows communication\n * to flow between environments.\n */\n\n /**\n * An object that manages how functions are proxied between threads.\n */\n\n /**\n * An object that manages how values are serialized and deserialized between threads.\n */\n\n /**\n * An `AbortSignal` that indicates whether the communication channel is still open.\n */\n get signal() {\n return this.#abort.signal;\n }\n\n /**\n * A boolean indicating whether the communication channel is still open.\n */\n get closed() {\n return this.#abort.signal.aborted;\n }\n #abort;\n #idsToResolver = (() => new Map())();\n constructor(messages, {\n imports,\n exports,\n functions = new ThreadFunctionsAutomatic(),\n serialization = new ThreadSerializationStructuredClone(),\n signal\n } = {}) {\n this.messages = messages;\n this.#abort = signal ? new NestedAbortController(signal) : new AbortController();\n this.exports = exports ?? {};\n this.imports = createThreadImports(this.#handlerForCall.bind(this), imports);\n this.functions = functions;\n this.serialization = serialization;\n this.functions.start?.(this);\n this.serialization.start?.(this);\n this.signal.addEventListener('abort', () => {\n for (const id of this.#idsToResolver.keys()) {\n this.#resolveCall(id, undefined, new ThreadClosedError());\n }\n this.#idsToResolver.clear();\n }, {\n once: true\n });\n messages.listen(async rawData => {\n const isThreadMessageData = Array.isArray(rawData) && typeof rawData[0] === 'number';\n if (!isThreadMessageData) {\n return;\n }\n const data = rawData;\n switch (data[0]) {\n case MESSAGE_CALL:\n {\n const [, id, property, args] = data;\n const func = this.exports[property] ?? (() => {\n throw new Error(`No '${property}' method is exported from this thread`);\n });\n await this.#callLocal(func, args, (value, error, transferable) => {\n this.messages.send([MESSAGE_CALL_RESULT, id, value, error], transferable);\n });\n break;\n }\n case MESSAGE_FUNCTION_CALL:\n {\n const [, callID, funcID, args] = data;\n const func = this.functions.get(funcID, this) ?? missingThreadFunction;\n await this.#callLocal(func, args, (value, error, transferable) => {\n this.messages.send([MESSAGE_FUNCTION_RESULT, callID, value, error], transferable);\n });\n break;\n }\n case MESSAGE_CALL_RESULT:\n case MESSAGE_FUNCTION_RESULT:\n {\n this.#resolveCall(...data.slice(1));\n break;\n }\n case MESSAGE_FUNCTION_RELEASE:\n {\n const id = data[1];\n this.functions.release(id, this);\n break;\n }\n }\n }, {\n signal: this.signal\n });\n }\n\n /**\n * Closes the communication channel between the two threads. This will prevent\n * any further communication between the threads, and will clean up any memory\n * associated with in-progress communication. It will also reject any inflight\n * function calls between threads with a `ThreadClosedError`.\n */\n close() {\n this.#abort.abort();\n }\n\n /**\n * Requests that the thread provide the context needed to make a function\n * call between threads. You provide this method a function to call and the\n * unserialized arguments you wish to call it with, and the thread will call\n * the function you provided with a serialized call ID, the serialized arguments,\n * and any transferable objects that need to be passed between threads.\n */\n call(func, args) {\n if (this.closed) {\n return Promise.reject(new ThreadClosedError());\n }\n const transferable = [];\n const serialized = this.serialization.serialize(args, this, transferable);\n const id = nanoid();\n const done = this.#waitForResult(id);\n func(id, serialized, transferable);\n return done;\n }\n async #callLocal(func, args, withResult) {\n try {\n const result = this.functions.call ? await this.functions.call(func, args, this) : await func(...this.serialization.deserialize(args, this));\n const transferable = [];\n const serialized = this.serialization.serialize(result, this, transferable);\n withResult(serialized, undefined, transferable);\n } catch (error) {\n withResult(undefined, this.serialization.serialize(error, this));\n }\n }\n #handlerForCall(property) {\n return (...args) => {\n try {\n if (typeof property !== 'string' && typeof property !== 'number') {\n throw new Error(`Can’t call a symbol method on a thread: ${property.toString()}`);\n }\n return this.call((id, serializedArgs, transferable) => {\n this.messages.send([MESSAGE_CALL, id, property, serializedArgs], transferable);\n }, args);\n } catch (error) {\n return Promise.reject(error);\n }\n };\n }\n #resolveCall(...args) {\n const callID = args[0];\n const resolver = this.#idsToResolver.get(callID);\n if (resolver) {\n resolver(...args);\n this.#idsToResolver.delete(callID);\n }\n }\n #waitForResult(id) {\n const promise = new Promise((resolve, reject) => {\n this.#idsToResolver.set(id, (_, value, error) => {\n if (error == null) {\n resolve(this.serialization.deserialize(value, this));\n } else {\n reject(this.serialization.deserialize(error, this));\n }\n });\n });\n Object.defineProperty(promise, Symbol.asyncIterator, {\n async *value() {\n const result = await promise;\n Object.defineProperty(result, Symbol.asyncIterator, {\n value: () => result\n });\n yield* result;\n }\n });\n return promise;\n }\n}\nfunction createThreadImports(handlerForImport, imported) {\n let call;\n if (imported == null) {\n if (typeof Proxy !== 'function') {\n throw new Error(`You must pass an array of callable methods in environments without Proxies.`);\n }\n const cache = new Map();\n call = new Proxy({}, {\n get(_target, property) {\n if (cache.has(property)) {\n return cache.get(property);\n }\n const handler = handlerForImport(property);\n cache.set(property, handler);\n return handler;\n }\n });\n } else {\n call = {};\n for (const method of imported) {\n Object.defineProperty(call, method, {\n value: handlerForImport(method),\n writable: false,\n configurable: true,\n enumerable: true\n });\n }\n }\n return call;\n}\nfunction missingThreadFunction() {\n throw new Error(`You attempted to call a function that is not stored. It may have already been released.`);\n}\n\nexport { Thread };\n","import { Thread } from '../Thread.mjs';\n\n/**\n * Creates a thread from a `MessagePort` instance in the browser.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MessagePort\n *\n * @example\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * const threadOne = new ThreadMessagePort(channel.port1);\n * const threadTwo = new ThreadMessagePort(channel.port2, {\n * exports: {\n * async sendMessage(message) {\n * console.log(message);\n * },\n * },\n * });\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * await threadOne.imports.sendMessage('Hello world!');\n */\nclass ThreadMessagePort extends Thread {\n /**\n * Starts a thread wrapped around a `MessagePort` object, and returns the imports\n * of the thread.\n *\n * @example\n * ```ts\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * ThreadMessagePort.export(channel.port1, {\n * async getMessage() {\n * return 'Hello, world!';\n * },\n * });\n *\n * const {getMessage} = ThreadMessagePort.import(channel.port2);\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * const message = await getMessage(); // 'Hello, world!'\n * ```\n */\n static import(port, options) {\n return new ThreadMessagePort(port, options).imports;\n }\n\n /**\n * Starts a thread wrapped around a `MessagePort` object, providing the second\n * argument as the exports of the thread.\n *\n * @example\n * ```ts\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * ThreadMessagePort.export(channel.port1, {\n * async getMessage() {\n * return 'Hello, world!';\n * },\n * });\n *\n * const {getMessage} = ThreadMessagePort.import(channel.port2);\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * const message = await getMessage(); // 'Hello, world!'\n * ```\n */\n static export(port, exports, options) {\n new ThreadMessagePort(port, {\n ...options,\n exports\n });\n }\n constructor(port, options) {\n super(portToMessageTarget(port), options);\n this.port = port;\n }\n}\nfunction portToMessageTarget(port) {\n return {\n send(...args) {\n port.postMessage(...args);\n },\n listen(listener, {\n signal\n }) {\n port.addEventListener('message', event => {\n listener(event.data);\n }, {\n signal\n });\n }\n };\n}\n\nexport { ThreadMessagePort, portToMessageTarget };\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"],"x_google_ignoreList":[4,5,6,7,8,9,10,11,12],"mappings":";;ACMA,IAAM,UAAU;AACG,IAAI,OAAO,KAAK,QAAQ,MAAM,GAAG;AACpD,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,IAAI,IAAI;;AAMvD,SAAgB,YAAY,OAAO;CAC/B,OAAO,MAAM,QAAQ,gBAAgB,EAAE;AAC3C;;;;;;;;;;;;;;ACLA,IAAa,qBAAqB;;;;;;;AASlC,IAAa,mBAAmB;;;;;AAOhC,IAAa,gBAAgB;CAAC;CAAO;CAAQ;CAAO;AAAQ;;;;;AAK5D,SAAgB,iBAAiB,QAAQ;CACrC,OAAO,WAAW;AACtB;AAOA,IAAM,0BAA0B;;;;;;;AAOhC,SAAgB,wBAAwB,MAAM;CAC1C,OAAO,wBAAwB,KAAK,IAAI;AAC5C;;;;;;AAMA,IAAa,oBAAoB;CAC7B,WAAW;CACX,aAAa,yBAAyB,cAAc,KAAK,IAAI;CAC7D,WAAW;CAGX,iBAAiB,SAAS,eAAe,KAAK,YAAY,EAAE;CAC5D,UAAU;CACV,SAAS;CACT,UAAU;CACV,OAAO;AACX;;;;;;;;;;;;;;;;;;AAyBA,IAAa,mBAAmB;CAC5B;CACA;CACA;CACA;CACA;CACA;AACJ;AAUkC,CAAC,GAAG,gBAAmC;AACzE,IAAM,gBAAgB;;;;;AAKtB,SAAgB,kBAAkB,MAAM,QAAQ;CAC5C,OAAO,GAAG,KAAK,IAAI;AACvB;;;;;;AAMA,SAAgB,kBAAkB,SAAS,OAAO;CAC9C,MAAM,GA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AI,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":"app-sdk.js","names":["#idsToFunction","#functionsToId","#idsToProxy","#finalizationRegistry","#finalization","#customSerializer","#customDeserializer","#serializeInternal","#deserializeInternal","#abort","#handlerForCall","#idsToResolver","#resolveCall","#callLocal","#waitForResult","#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":["../../app-contracts/build/identity/codes.js","../../app-contracts/build/failure-codes.js","../../app-contracts/build/plain-text.js","../../app-contracts/build/bridge/rules.js","../src/errors.ts","node_modules/@quilted/threads/build/esm/constants.mjs","node_modules/@quilted/events/build/esm/abort/NestedAbortController.mjs","node_modules/@quilted/threads/build/esm/errors.mjs","node_modules/@quilted/threads/build/esm/nanoid.mjs","node_modules/@quilted/threads/build/esm/functions/ThreadFunctionsAutomatic.mjs","node_modules/@quilted/threads/build/esm/serialization/shared.mjs","node_modules/@quilted/threads/build/esm/serialization/ThreadSerializationStructuredClone.mjs","node_modules/@quilted/threads/build/esm/Thread.mjs","node_modules/@quilted/threads/build/esm/threads/ThreadMessagePort.mjs","../src/fetch.ts","../src/history.ts","../src/title.ts","../src/session.ts","../src/version.ts","../src/connect.ts"],"sourcesContent":["/**\n * Ghost couldn't confirm the app is the one it says it is. Kept apart from an app that's down\n * or broken because the publisher should hear something different: contact the developer, and\n * don't install it again from a link, the one way a different developer's key gets pinned.\n */\nexport const UNCONFIRMED_APP_CODES = [\n /** The manifest names another address than the one it was fetched from. */\n 'APP_MANIFEST_URL_MISMATCH',\n /** The signature wasn't made with the identity key the manifest names. */\n 'APP_MANIFEST_SIGNATURE_INVALID',\n /** The manifest is signed with another key than the one the app was installed with. */\n 'APP_IDENTITY_MISMATCH',\n /** The manifest names a backend key a newer manifest from the same developer replaced. */\n 'APP_BACKEND_KEY_RETIRED',\n /** The app's origin didn't answer the challenge with the manifest's backend key. */\n 'APP_CHALLENGE_FAILED',\n];\nconst UNCONFIRMED = new Set(UNCONFIRMED_APP_CODES);\nexport function isUnconfirmedAppCode(code) {\n return UNCONFIRMED.has(code);\n}\n//# sourceMappingURL=codes.js.map","import { UNCONFIRMED_APP_CODES } from './identity/codes.js';\n/** Trying again may work. */\nconst UNREACHABLE_APP_CODES = [\n /** Also when the app answers with an error or a bad redirect. */\n 'APP_MANIFEST_UNREACHABLE',\n 'APP_CHALLENGE_UNREACHABLE',\n];\n/** Only the app's developer can fix these. */\nconst UNUSABLE_MANIFEST_CODES = [\n 'APP_MANIFEST_URL_INVALID',\n /** To another host. */\n 'APP_MANIFEST_REDIRECTED',\n /** The signed manifest is over what Ghost reads, or its manifest over what Ghost stores. */\n 'APP_MANIFEST_TOO_LARGE',\n 'APP_MANIFEST_NOT_JSON',\n 'APP_MANIFEST_UNSIGNED',\n /** Also for an invalid icon. The details list each problem. */\n 'APP_MANIFEST_INVALID',\n 'APP_MANIFEST_OTHER_APP',\n];\n/**\n * The publisher confirmed a review that's out of date. A changed manifest or installation\n * carries the current review in the error's details when Ghost has one.\n */\nexport const OUTDATED_REVIEW_CODES = [\n 'APP_MANIFEST_CHANGED',\n 'APP_INSTALLATION_CHANGED',\n 'APP_ALREADY_INSTALLED',\n 'APP_INSTALLATION_UNINSTALLED',\n];\n/**\n * Admin can only explain a code listed here; any other shows as an unknown error. A Ghost\n * core test checks the list against the codes the app installations service throws.\n */\nexport const APP_FAILURE_CODES = [\n ...UNREACHABLE_APP_CODES,\n ...UNCONFIRMED_APP_CODES,\n ...UNUSABLE_MANIFEST_CODES,\n ...OUTDATED_REVIEW_CODES,\n /** Also once uninstalled. */\n 'APP_NOT_INSTALLED',\n /** A session failed because of the app, for a reason with no code of its own. */\n 'APP_UNAVAILABLE',\n];\nconst FAILURE_CODES = new Set(APP_FAILURE_CODES);\n/** Unlike `code in table`, false for names every object has, such as `constructor`. */\nexport function isAppFailureCode(code) {\n return FAILURE_CODES.has(code);\n}\nconst OUTDATED_REVIEW = new Set(OUTDATED_REVIEW_CODES);\nexport function isOutdatedReviewCode(code) {\n return OUTDATED_REVIEW.has(code);\n}\n//# sourceMappingURL=failure-codes.js.map","// What plain text may contain: letters, combining marks, digits, punctuation, symbols and\n// spaces, plus the two joiners that emoji sequences and scripts such as Persian need.\n// Everything else is refused by not being listed: control and formatting characters, line\n// breaks, the characters that reorder text, private-use and unassigned code points. Those can\n// make text display as something other than what it is, such as a title that reverses\n// whatever Admin shows after it.\nconst ALLOWED = '\\\\p{L}\\\\p{M}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\\\\u200C\\\\u200D';\nconst PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, 'u');\nconst NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, 'gu');\n/** Whether text is one line of plain text, as a name, a description or a title must be. */\nexport function isPlainText(value) {\n return PLAIN_TEXT.test(value);\n}\n/** Returns the text with the characters `isPlainText` refuses removed. */\nexport function toPlainText(value) {\n return value.replace(NOT_PLAIN_TEXT, '');\n}\n//# sourceMappingURL=plain-text.js.map","/**\n * The bridge's rules that have no dependencies. The root entry point exports them so the SDK\n * can use them without zod. The schemas in this folder build on them, so the SDK and Admin\n * read a path or a refusal the same way.\n *\n * What Admin sends the page has no schema, because Admin builds it and never parses it. Its\n * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so\n * the guards only check shape and path containment. They turn a mismatch into a clear error\n * rather than `undefined` somewhere in the app. Only the schemas check limits.\n */\n/** Posted by the app's page to `window.parent` once the SDK has loaded. */\nexport const HELLO_MESSAGE_TYPE = 'ghost-app:hello';\n/** Posted by Admin to the frame that sent the hello, with the channel's port attached. */\nexport const CONNECT_MESSAGE_TYPE = 'ghost-app:connect';\n/**\n * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long\n * after mounting it, and the SDK waits this long for Admin to start the app unless the app\n * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send\n * its hello.\n */\nexport const START_TIMEOUT_MS = 10_000;\n/** Long enough for any real page title, short enough that Admin's own name still shows. */\nexport const TITLE_MAX_LENGTH = 200;\n/**\n * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK\n * uppercases what apps pass.\n */\nexport const FETCH_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];\n/**\n * Whether a request with this method may carry a body. Expects an uppercase method from\n * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.\n */\nexport function methodAllowsBody(method) {\n return method !== 'GET';\n}\n// The headers Admin sets itself on a request it makes for an app: the credentials, which only\n// Admin may send; Admin's own markers, which Ghost core treats as coming from Admin; the headers\n// that describe the connection, or the proxies along the way, rather than the request; and the\n// ones that say how to read the body. A body is always JSON, which Admin labels itself: the Admin\n// API also reads forms and uploads, and decodes JSON in any charset it's told, so a content type\n// of the app's choosing could carry a write past the checks on what it contains.\nconst RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;\n/**\n * Whether a request header is one that apps may not set, in any case. Admin refuses a request\n * that sets one rather than dropping the header, so the app gets an error instead of wondering\n * why the header never arrived. The browser refuses some of these anyway; they are listed here\n * so that none of them relies on the browser.\n */\nexport function isReservedRequestHeader(name) {\n return RESERVED_REQUEST_HEADER.test(name);\n}\n/**\n * The messages Admin and the SDK use when they refuse an argument for the same reason, so an\n * app gets the same message whichever side catches the problem. The SDK checks only for obvious\n * mistakes, before anything crosses the channel; Admin's schemas check everything again.\n */\nexport const ARGUMENT_MESSAGES = {\n fetchPath: 'Expected an Admin API path such as /posts/, not a URL',\n fetchMethod: `Expected a method of: ${FETCH_METHODS.join(', ')}`,\n fetchBody: 'Expected no body on a GET request',\n // Header names are case-insensitive, and `Headers` lowercases them on the SDK's side, so the\n // name is lowercased here too and both sides produce the same message.\n reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,\n jsonBody: 'Expected the body as JSON text',\n appPath: 'Expected a path within the app, starting with a single /',\n pathMove: 'Expected a move of push or replace',\n place: 'Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }',\n};\n/**\n * The statuses a `fetch` response may have. The SDK turns the response back into a\n * `Response`, which only accepts statuses from 200 to 599. Fetch never returns an\n * informational (1xx) status to scripts anyway.\n */\nexport const FETCH_RESPONSE_STATUS_MIN = 200;\nexport const FETCH_RESPONSE_STATUS_MAX = 599;\n/**\n * The codes a refused call carries across the channel. The structured clone that carries an\n * error keeps only its message, so the refusing side puts the code at the start of the\n * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes\n * are only ever added: an SDK that doesn't know a code treats the whole message as a generic\n * refusal.\n *\n * The host codes, which Admin refuses the page's calls with:\n *\n * - `session_ended`: the session is over; the page is about to be replaced.\n * - `invalid_argument`: an argument Admin does not take.\n * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one\n * the Admin API only responds to with a redirect, such as a path without its trailing `/`.\n * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: anything else; the detail says why.\n */\nexport const HOST_ERROR_CODES = [\n 'session_ended',\n 'invalid_argument',\n 'invalid_path',\n 'blocked',\n 'network_error',\n 'rejected',\n];\n/**\n * The app codes, which the page refuses Admin's calls with:\n *\n * - `invalid_context`: a start context the SDK cannot read, or a call before the app has\n * started.\n * - `invalid_argument`: an argument the SDK does not take, such as a theme it cannot read.\n */\nexport const APP_ERROR_CODES = ['invalid_context', 'invalid_argument'];\n/** Every code a refusal can carry, in either direction. */\nexport const BRIDGE_ERROR_CODES = [...HOST_ERROR_CODES, 'invalid_context'];\nconst CODED_MESSAGE = /^([a-z_]+): ([\\s\\S]*)$/;\n/**\n * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass\n * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.\n */\nexport function encodeBridgeError(code, detail) {\n return `${code}: ${detail}`;\n}\n/**\n * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the\n * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for\n * one from the page. Returns `undefined` for a message that doesn't start with one of them.\n */\nexport function decodeBridgeError(message, codes) {\n const [, code = '', detail = ''] = CODED_MESSAGE.exec(message) ?? [];\n return codes.includes(code) ? { code: code, detail } : undefined;\n}\nconst THEME_MODES = ['light', 'dark'];\n// URL parsers and routers don't agree on whether to strip or refuse control characters, so a\n// path containing one can mean something different to each of them.\nconst CONTROL_CHARACTER = /\\p{Cc}/u;\n/**\n * Whether a value is a path that stays within the base it is resolved against, rather than\n * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as\n * `//host`. It must not contain `\\`, which URL parsers read as `/`, or any control character.\n */\nexport function isContainedPath(value) {\n return (typeof value === 'string' &&\n value.startsWith('/') &&\n !value.startsWith('//') &&\n !value.includes('\\\\') &&\n !CONTROL_CHARACTER.test(value));\n}\n// Used only as a base for parsing, never requested. Parsing against it gives a path the URL\n// parser's normalised form.\nconst APP_PATH_BASE = 'https://app.invalid';\n/**\n * Returns an app path in the URL parser's normalised form, the one form Admin and the SDK\n * store it in. `.` and `..` are resolved within the app, so `..` can never climb above its root.\n * Characters that need escaping are escaped once, so a path the app reported compares equal to\n * the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and\n * `/x/../episodes/1` becomes `/episodes/1`.\n *\n * Expects a path that `isContainedPath` accepts; anything else may not be a path within the\n * app at all. Even then, the result may not be: resolving `.` and `..` can leave `//` at the\n * start, so `/.//host` becomes `//host`, which resolves to another site. Check the result with\n * `isContainedPath` before resolving it against anything. `AppPathSchema` does both and returns\n * this form.\n */\nexport function normaliseAppPath(path) {\n const url = new URL(path, APP_PATH_BASE);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n/** An object, or an array: anything whose fields can be read. */\nexport function isRecord(value) {\n return typeof value === 'object' && value !== null;\n}\nfunction hasStrings(value, keys) {\n return isRecord(value) && keys.every((key) => typeof value[key] === 'string');\n}\nexport function isTheme(value) {\n return (hasStrings(value, ['accent_color']) && THEME_MODES.includes(value.mode));\n}\nexport function isStartContext(value) {\n return (isRecord(value) &&\n hasStrings(value.site, ['url', 'title', 'timezone', 'locale']) &&\n hasStrings(value.user, ['id', 'role']) &&\n isTheme(value.theme) &&\n isRecord(value.session) &&\n Number.isSafeInteger(value.session.revision) &&\n value.session.revision >= 0 &&\n isContainedPath(value.path));\n}\nexport function isConnectMessage(value) {\n return (isRecord(value) &&\n value.type === CONNECT_MESSAGE_TYPE &&\n Array.isArray(value.exports) &&\n value.exports.every((name) => typeof name === 'string'));\n}\nexport function isFetchResponse(value) {\n return (isRecord(value) &&\n Number.isSafeInteger(value.status) &&\n value.status >= FETCH_RESPONSE_STATUS_MIN &&\n value.status <= FETCH_RESPONSE_STATUS_MAX &&\n typeof value.statusText === 'string' &&\n isRecord(value.headers) &&\n !Array.isArray(value.headers) &&\n Object.values(value.headers).every((header) => typeof header === 'string') &&\n typeof value.body === 'string');\n}\n//# sourceMappingURL=rules.js.map","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","const MESSAGE_CALL = 1;\nconst MESSAGE_CALL_RESULT = 2;\nconst MESSAGE_FUNCTION_CALL = 3;\nconst MESSAGE_FUNCTION_RESULT = 4;\nconst MESSAGE_FUNCTION_RELEASE = 5;\nconst SERIALIZE_METHOD = Symbol.for('quilt.threads.serialize');\nconst TRANSFERABLE = Symbol.for('quilt.threads.transferable');\n\nexport { MESSAGE_CALL, MESSAGE_CALL_RESULT, MESSAGE_FUNCTION_CALL, MESSAGE_FUNCTION_RELEASE, MESSAGE_FUNCTION_RESULT, SERIALIZE_METHOD, TRANSFERABLE };\n","/**\n * An `AbortController` that will automatically abort when any of\n * its \"parent\" `AbortController`s abort. This is useful for when\n * you have nested asynchronous operations that may abort independently.\n * The `AbortController` can also be independently aborted.\n *\n * To associate the parent `AbortController`s, pass their signals\n * as arguments to the constructor.\n *\n * @example\n * import {NestedAbortController} from '@shopify/events';\n *\n * const parent = new AbortController();\n * const nested = new NestedAbortController(parent.signal);\n *\n * parent.abort();\n * nested.signal.aborted; // true\n */\nclass NestedAbortController extends AbortController {\n constructor(...parents) {\n super();\n const abortedSignal = parents.find(signal => signal.aborted);\n if (abortedSignal) {\n this.abort(abortedSignal.reason);\n } else {\n const abort = event => this.abort(event.target.reason);\n const options = {\n signal: this.signal\n };\n for (const signal of parents) {\n signal.addEventListener('abort', abort, options);\n }\n }\n }\n}\n\nexport { NestedAbortController };\n","class ThreadClosedError extends Error {\n constructor() {\n super('You attempted to call a function on a closed thread.');\n }\n}\n\nexport { ThreadClosedError };\n","// Copied from https://github.com/ai/nanoid/blob/main/nanoid.js\nlet a = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';\nfunction nanoid(e = 21) {\n let t = '',\n r = crypto.getRandomValues(new Uint8Array(e));\n for (let n = 0; n < e; n++) t += a[63 & r[n]];\n return t;\n}\n\nexport { nanoid };\n","import { MESSAGE_FUNCTION_CALL, MESSAGE_FUNCTION_RELEASE } from '../constants.mjs';\nimport { nanoid } from '../nanoid.mjs';\n\n/**\n * A strategy for managing functions across threads that automatically releases\n * functions when they are no longer needed. This is done by deserializing functions\n * into a proxy that can be called, and wrapping that proxy in a `FinalizationRegistry`,\n * which allows us to send a message to the parent thread when the function is no\n * longer used.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\nclass ThreadFunctionsAutomatic {\n #functionsToId = (() => new Map())();\n #idsToFunction = (() => new Map())();\n #idsToProxy = (() => new Map())();\n #finalization = (() => new WeakMap())();\n get(id) {\n return this.#idsToFunction.get(id);\n }\n release(id) {\n const func = this.#idsToFunction.get(id);\n if (func) {\n this.#idsToFunction.delete(id);\n this.#functionsToId.delete(func);\n }\n return Boolean(func);\n }\n serialize(func) {\n let id = this.#functionsToId.get(func);\n if (id == null) {\n id = nanoid();\n this.#functionsToId.set(func, id);\n this.#idsToFunction.set(id, func);\n }\n return id;\n }\n deserialize(id, thread) {\n let proxy = this.#idsToProxy.get(id)?.deref();\n if (proxy) return proxy;\n proxy = (...args) => {\n if (!this.#idsToProxy.has(id)) {\n throw new Error('You attempted to call a function that was already revoked.');\n }\n return thread.call((callID, args, transferable) => {\n thread.messages.send([MESSAGE_FUNCTION_CALL, callID, id, args], transferable);\n }, args);\n };\n this.#finalizationRegistry(thread)?.register(proxy, id);\n this.#idsToProxy.set(id, new WeakRef(proxy));\n return proxy;\n }\n #finalizationRegistry(thread) {\n let finalization = this.#finalization.get(thread);\n if (typeof FinalizationRegistry === 'undefined') {\n return undefined;\n }\n if (!finalization) {\n finalization = new FinalizationRegistry(id => {\n thread.messages.send([MESSAGE_FUNCTION_RELEASE, id]);\n });\n this.#finalization.set(thread, finalization);\n }\n return finalization;\n }\n}\n\nexport { ThreadFunctionsAutomatic };\n","function isIterator(value) {\n return value != null && (Symbol.asyncIterator in value || Symbol.iterator in value) && typeof value.next === 'function';\n}\nfunction isBasicObject(value) {\n if (value == null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype == null || prototype === Object.prototype;\n}\n\nexport { isBasicObject, isIterator };\n","import { TRANSFERABLE, SERIALIZE_METHOD } from '../constants.mjs';\nimport { isIterator, isBasicObject } from './shared.mjs';\n\nconst FUNCTION = '_@f';\nconst ASYNC_ITERATOR = '_@i';\n\n/**\n * A thread encoder that can transfer supports a wide variety of JavaScript types by\n * converting them to a format that the [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)\n * algorithm can process. This\n *\n * Additionally, this encoder will convert functions into a JSON-friendly representation.\n * These functions will use a manual memory management technique to ensure they can be\n * garbage collected by default, but can be configured to use a `WeakRef`-based automatic\n * memory management system by setting the `garbageCollection: 'weak-ref'` option.\n */\nclass ThreadSerializationStructuredClone {\n #customSerializer;\n #customDeserializer;\n constructor(options) {\n this.#customSerializer = options?.serialize;\n this.#customDeserializer = options?.deserialize;\n }\n\n /**\n * Serializes a value into a structured cloning-compatible format that can be transferred between threads.\n */\n serialize(value, thread, transferable) {\n return this.#serializeInternal(value, thread, transferable);\n }\n #serializeInternal(value, thread, transferable, seen = new Map(), isApplyingDefault = false) {\n if (value == null) return value;\n if (seen.has(value)) return seen.get(value);\n\n // Prevent circular references\n seen.set(value, undefined);\n if (typeof value === 'object') {\n if (this.#customSerializer && !isApplyingDefault) {\n const customValue = this.#customSerializer(value, value => this.#serializeInternal(value, thread, transferable, seen, true), thread, transferable);\n if (customValue !== undefined) {\n seen.set(value, customValue);\n return customValue;\n }\n }\n if (value[TRANSFERABLE]) {\n transferable?.push(value);\n seen.set(value, value);\n return value;\n }\n const serializeValue = value => {\n return this.#serializeInternal(value, thread, transferable, seen);\n };\n if (typeof value[SERIALIZE_METHOD] === 'function') {\n const result = value[SERIALIZE_METHOD]({\n serialize: serializeValue\n });\n seen.set(value, result);\n return result;\n }\n if (Array.isArray(value)) {\n const result = value.map(item => serializeValue(item));\n seen.set(value, result);\n return result;\n }\n if (value instanceof Map) {\n const entries = [...value.entries()].map(([key, value]) => {\n return [serializeValue(key), serializeValue(value)];\n });\n const result = new Map(entries);\n seen.set(value, result);\n return result;\n }\n if (value instanceof Set) {\n const entries = [...value].map(entry => serializeValue(entry));\n const result = new Set(entries);\n seen.set(value, result);\n return result;\n }\n const valueIsIterator = isIterator(value);\n if (isBasicObject(value) || valueIsIterator) {\n const result = {};\n for (const key of Object.keys(value)) {\n result[key] = serializeValue(value[key]);\n }\n if (valueIsIterator) {\n result.next ??= serializeValue(value.next.bind(value));\n result.return ??= serializeValue(value.return.bind(value));\n result.throw ??= serializeValue(value.throw.bind(value));\n result[ASYNC_ITERATOR] = true;\n }\n seen.set(value, result);\n return result;\n }\n }\n if (typeof value === 'function') {\n const serialized = thread.functions.serialize(value, thread, transferable);\n const result = {\n [FUNCTION]: serialized\n };\n seen.set(value, result);\n return result;\n }\n seen.set(value, value);\n return value;\n }\n\n /**\n * Deserializes a structured cloning-compatible value from another thread.\n */\n deserialize(value, thread) {\n return this.#deserializeInternal(value, thread);\n }\n #deserializeInternal(value, thread, isApplyingDefault = false) {\n if (value == null) return value;\n if (typeof value === 'object') {\n if (this.#customDeserializer && !isApplyingDefault) {\n const customValue = this.#customDeserializer(value, value => this.#deserializeInternal(value, thread, true), thread);\n if (customValue !== undefined) {\n return customValue;\n }\n }\n if (value == null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(value => this.#deserializeInternal(value, thread));\n }\n if (value instanceof Map) {\n return new Map([...value].map(([key, value]) => [this.#deserializeInternal(key, thread), this.#deserializeInternal(value, thread)]));\n }\n if (value instanceof Set) {\n return new Set([...value].map(entry => this.#deserializeInternal(entry, thread)));\n }\n if (FUNCTION in value) {\n const func = thread.functions.deserialize(value[FUNCTION], thread);\n return func;\n }\n if (!isBasicObject(value)) {\n return value;\n }\n const result = {};\n for (const key of Object.keys(value)) {\n if (key === ASYNC_ITERATOR) {\n result[Symbol.asyncIterator] = () => result;\n } else {\n result[key] = this.#deserializeInternal(value[key], thread);\n }\n }\n return result;\n }\n return value;\n }\n}\n\nexport { ThreadSerializationStructuredClone };\n","import { NestedAbortController } from '@quilted/events';\nimport { ThreadClosedError } from './errors.mjs';\nimport { nanoid } from './nanoid.mjs';\nimport { MESSAGE_FUNCTION_RELEASE, MESSAGE_FUNCTION_RESULT, MESSAGE_CALL_RESULT, MESSAGE_FUNCTION_CALL, MESSAGE_CALL } from './constants.mjs';\nimport { ThreadFunctionsAutomatic } from './functions/ThreadFunctionsAutomatic.mjs';\nimport { ThreadSerializationStructuredClone } from './serialization/ThreadSerializationStructuredClone.mjs';\n\n/**\n * An object that can serialize and deserialize values communicated between two threads.\n */\n\n/**\n * An object that can serialize and deserialize values communicated between two threads.\n */\n\n/**\n * Options to customize the creation of a `ThreadSerialization` instance.\n */\n\n/**\n * Options to customize the creation of a `Thread` instance.\n */\n\n/**\n * An object backing a `Thread` that provides the message-passing interface\n * that allows communication to flow between environments. This message-passing\n * interface is based on the [`postMessage` interface](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage),\n * which is easily adaptable to many JavaScript objects and environments.\n */\n\n/**\n * A map of messages that can be sent between threads.\n */\n\n/**\n * The possible data payloads that can be transferred between threads.\n */\n\n/**\n * A helper type that extracts all callable methods that can be safely proxied\n * between threads; that is, ones which return a promise or async iterator.\n */\n\n/**\n * A thread represents a target JavaScript environment that exposes a set\n * of callable, asynchronous methods. The thread takes care of automatically\n * encoding and decoding its arguments and return values, so you can interact\n * with it as if its methods were implemented in the same environment as your\n * own code.\n */\nclass Thread {\n /**\n * An object that exposes the methods that can be called on the paired thread.\n * This object will automatically encode and decode arguments and return values\n * as necessary.\n */\n\n /**\n * An object that exposes the methods that can be called on this thread by the\n * paired thread. To set these methods, pass the `exports` option when creating\n * a new `Thread`.\n */\n\n /**\n * An object that provides the message-passing interface that allows communication\n * to flow between environments.\n */\n\n /**\n * An object that manages how functions are proxied between threads.\n */\n\n /**\n * An object that manages how values are serialized and deserialized between threads.\n */\n\n /**\n * An `AbortSignal` that indicates whether the communication channel is still open.\n */\n get signal() {\n return this.#abort.signal;\n }\n\n /**\n * A boolean indicating whether the communication channel is still open.\n */\n get closed() {\n return this.#abort.signal.aborted;\n }\n #abort;\n #idsToResolver = (() => new Map())();\n constructor(messages, {\n imports,\n exports,\n functions = new ThreadFunctionsAutomatic(),\n serialization = new ThreadSerializationStructuredClone(),\n signal\n } = {}) {\n this.messages = messages;\n this.#abort = signal ? new NestedAbortController(signal) : new AbortController();\n this.exports = exports ?? {};\n this.imports = createThreadImports(this.#handlerForCall.bind(this), imports);\n this.functions = functions;\n this.serialization = serialization;\n this.functions.start?.(this);\n this.serialization.start?.(this);\n this.signal.addEventListener('abort', () => {\n for (const id of this.#idsToResolver.keys()) {\n this.#resolveCall(id, undefined, new ThreadClosedError());\n }\n this.#idsToResolver.clear();\n }, {\n once: true\n });\n messages.listen(async rawData => {\n const isThreadMessageData = Array.isArray(rawData) && typeof rawData[0] === 'number';\n if (!isThreadMessageData) {\n return;\n }\n const data = rawData;\n switch (data[0]) {\n case MESSAGE_CALL:\n {\n const [, id, property, args] = data;\n const func = this.exports[property] ?? (() => {\n throw new Error(`No '${property}' method is exported from this thread`);\n });\n await this.#callLocal(func, args, (value, error, transferable) => {\n this.messages.send([MESSAGE_CALL_RESULT, id, value, error], transferable);\n });\n break;\n }\n case MESSAGE_FUNCTION_CALL:\n {\n const [, callID, funcID, args] = data;\n const func = this.functions.get(funcID, this) ?? missingThreadFunction;\n await this.#callLocal(func, args, (value, error, transferable) => {\n this.messages.send([MESSAGE_FUNCTION_RESULT, callID, value, error], transferable);\n });\n break;\n }\n case MESSAGE_CALL_RESULT:\n case MESSAGE_FUNCTION_RESULT:\n {\n this.#resolveCall(...data.slice(1));\n break;\n }\n case MESSAGE_FUNCTION_RELEASE:\n {\n const id = data[1];\n this.functions.release(id, this);\n break;\n }\n }\n }, {\n signal: this.signal\n });\n }\n\n /**\n * Closes the communication channel between the two threads. This will prevent\n * any further communication between the threads, and will clean up any memory\n * associated with in-progress communication. It will also reject any inflight\n * function calls between threads with a `ThreadClosedError`.\n */\n close() {\n this.#abort.abort();\n }\n\n /**\n * Requests that the thread provide the context needed to make a function\n * call between threads. You provide this method a function to call and the\n * unserialized arguments you wish to call it with, and the thread will call\n * the function you provided with a serialized call ID, the serialized arguments,\n * and any transferable objects that need to be passed between threads.\n */\n call(func, args) {\n if (this.closed) {\n return Promise.reject(new ThreadClosedError());\n }\n const transferable = [];\n const serialized = this.serialization.serialize(args, this, transferable);\n const id = nanoid();\n const done = this.#waitForResult(id);\n func(id, serialized, transferable);\n return done;\n }\n async #callLocal(func, args, withResult) {\n try {\n const result = this.functions.call ? await this.functions.call(func, args, this) : await func(...this.serialization.deserialize(args, this));\n const transferable = [];\n const serialized = this.serialization.serialize(result, this, transferable);\n withResult(serialized, undefined, transferable);\n } catch (error) {\n withResult(undefined, this.serialization.serialize(error, this));\n }\n }\n #handlerForCall(property) {\n return (...args) => {\n try {\n if (typeof property !== 'string' && typeof property !== 'number') {\n throw new Error(`Can’t call a symbol method on a thread: ${property.toString()}`);\n }\n return this.call((id, serializedArgs, transferable) => {\n this.messages.send([MESSAGE_CALL, id, property, serializedArgs], transferable);\n }, args);\n } catch (error) {\n return Promise.reject(error);\n }\n };\n }\n #resolveCall(...args) {\n const callID = args[0];\n const resolver = this.#idsToResolver.get(callID);\n if (resolver) {\n resolver(...args);\n this.#idsToResolver.delete(callID);\n }\n }\n #waitForResult(id) {\n const promise = new Promise((resolve, reject) => {\n this.#idsToResolver.set(id, (_, value, error) => {\n if (error == null) {\n resolve(this.serialization.deserialize(value, this));\n } else {\n reject(this.serialization.deserialize(error, this));\n }\n });\n });\n Object.defineProperty(promise, Symbol.asyncIterator, {\n async *value() {\n const result = await promise;\n Object.defineProperty(result, Symbol.asyncIterator, {\n value: () => result\n });\n yield* result;\n }\n });\n return promise;\n }\n}\nfunction createThreadImports(handlerForImport, imported) {\n let call;\n if (imported == null) {\n if (typeof Proxy !== 'function') {\n throw new Error(`You must pass an array of callable methods in environments without Proxies.`);\n }\n const cache = new Map();\n call = new Proxy({}, {\n get(_target, property) {\n if (cache.has(property)) {\n return cache.get(property);\n }\n const handler = handlerForImport(property);\n cache.set(property, handler);\n return handler;\n }\n });\n } else {\n call = {};\n for (const method of imported) {\n Object.defineProperty(call, method, {\n value: handlerForImport(method),\n writable: false,\n configurable: true,\n enumerable: true\n });\n }\n }\n return call;\n}\nfunction missingThreadFunction() {\n throw new Error(`You attempted to call a function that is not stored. It may have already been released.`);\n}\n\nexport { Thread };\n","import { Thread } from '../Thread.mjs';\n\n/**\n * Creates a thread from a `MessagePort` instance in the browser.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MessagePort\n *\n * @example\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * const threadOne = new ThreadMessagePort(channel.port1);\n * const threadTwo = new ThreadMessagePort(channel.port2, {\n * exports: {\n * async sendMessage(message) {\n * console.log(message);\n * },\n * },\n * });\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * await threadOne.imports.sendMessage('Hello world!');\n */\nclass ThreadMessagePort extends Thread {\n /**\n * Starts a thread wrapped around a `MessagePort` object, and returns the imports\n * of the thread.\n *\n * @example\n * ```ts\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * ThreadMessagePort.export(channel.port1, {\n * async getMessage() {\n * return 'Hello, world!';\n * },\n * });\n *\n * const {getMessage} = ThreadMessagePort.import(channel.port2);\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * const message = await getMessage(); // 'Hello, world!'\n * ```\n */\n static import(port, options) {\n return new ThreadMessagePort(port, options).imports;\n }\n\n /**\n * Starts a thread wrapped around a `MessagePort` object, providing the second\n * argument as the exports of the thread.\n *\n * @example\n * ```ts\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * ThreadMessagePort.export(channel.port1, {\n * async getMessage() {\n * return 'Hello, world!';\n * },\n * });\n *\n * const {getMessage} = ThreadMessagePort.import(channel.port2);\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * const message = await getMessage(); // 'Hello, world!'\n * ```\n */\n static export(port, exports, options) {\n new ThreadMessagePort(port, {\n ...options,\n exports\n });\n }\n constructor(port, options) {\n super(portToMessageTarget(port), options);\n this.port = port;\n }\n}\nfunction portToMessageTarget(port) {\n return {\n send(...args) {\n port.postMessage(...args);\n },\n listen(listener, {\n signal\n }) {\n port.addEventListener('message', event => {\n listener(event.data);\n }, {\n signal\n });\n }\n };\n}\n\nexport { ThreadMessagePort, portToMessageTarget };\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"],"x_google_ignoreList":[5,6,7,8,9,10,11,12,13],"mappings":";;;;;;AAKA,IAAa,wBAAwB;CAEjC;CAEA;CAEA;CAEA;CAEA;AACJ;AACoB,IAAI,IAAI,qBAAqB;;;;ACfjD,IAAM,wBAAwB,CAE1B,4BACA,2BACJ;;AAEA,IAAM,0BAA0B;CAC5B;CAEA;CAEA;CACA;CACA;CAEA;CACA;AACJ;;;;;AAKA,IAAa,wBAAwB;CACjC;CACA;CACA;CACA;AACJ;;;;;AAKA,IAAa,oBAAoB;CAC7B,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH;CAEA;AACJ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;CACA,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tryghost/app-sdk",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.17",
|
|
4
4
|
"description": "The SDK apps use to talk to Ghost: from their page inside Admin, from their backend, and from their tooling",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Ghost Foundation",
|