@immediately-run/sdk 0.74.1 → 0.75.0
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/dist/contribute.cjs.map +1 -1
- package/dist/contribute.d.cts +6 -1
- package/dist/contribute.d.ts +6 -1
- package/dist/contribute.js.map +1 -1
- package/dist/dnd.cjs.map +1 -1
- package/dist/dnd.d.cts +3 -3
- package/dist/dnd.d.ts +3 -3
- package/dist/dnd.js.map +1 -1
- package/dist/editor.cjs.map +1 -1
- package/dist/editor.d.cts +12 -12
- package/dist/editor.d.ts +12 -12
- package/dist/editor.js.map +1 -1
- package/dist/feed.cjs +2 -5
- package/dist/feed.cjs.map +1 -1
- package/dist/feed.js +2 -5
- package/dist/feed.js.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/mounts.cjs.map +1 -1
- package/dist/mounts.d.cts +3 -3
- package/dist/mounts.d.ts +3 -3
- package/dist/mounts.js.map +1 -1
- package/dist/netFetch.cjs +2 -5
- package/dist/netFetch.cjs.map +1 -1
- package/dist/netFetch.js +2 -5
- package/dist/netFetch.js.map +1 -1
- package/dist/openExternal.cjs.map +1 -1
- package/dist/openExternal.d.cts +9 -3
- package/dist/openExternal.d.ts +9 -3
- package/dist/openExternal.js.map +1 -1
- package/dist/openRepository.cjs.map +1 -1
- package/dist/openRepository.d.cts +9 -3
- package/dist/openRepository.d.ts +9 -3
- package/dist/openRepository.js.map +1 -1
- package/dist/protocolRefusal.cjs.map +1 -1
- package/dist/protocolRefusal.d.cts +31 -10
- package/dist/protocolRefusal.d.ts +31 -10
- package/dist/protocolRefusal.js.map +1 -1
- package/dist/secrets.cjs.map +1 -1
- package/dist/secrets.d.cts +3 -3
- package/dist/secrets.d.ts +3 -3
- package/dist/secrets.js.map +1 -1
- package/dist/spacesMode.cjs.map +1 -1
- package/dist/spacesMode.d.cts +9 -3
- package/dist/spacesMode.d.ts +9 -3
- package/dist/spacesMode.js.map +1 -1
- package/dist/theme.cjs +4 -15
- package/dist/theme.cjs.map +1 -1
- package/dist/theme.js +4 -15
- package/dist/theme.js.map +1 -1
- package/dist/vcs.cjs +18 -1
- package/dist/vcs.cjs.map +1 -1
- package/dist/vcs.d.cts +22 -4
- package/dist/vcs.d.ts +22 -4
- package/dist/vcs.js +18 -1
- package/dist/vcs.js.map +1 -1
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +5 -4
package/dist/spacesMode.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/spacesMode.ts"],"sourcesContent":["// The spaces mode's route channel and its one navigation verb (R3-708).\n//\n// The spaces mode runs ONE app across six frames — three activity pairs — and they must\n// agree on which space, activity and bundle is selected. A reload or a pasted link has to\n// land every frame on the same state, so the selection is a route the HOST owns and\n// deep-links to (`SPACES_BRIEF` §3), not something the frames negotiate between\n// themselves.\n//\n// Two halves, and the asymmetry is the point:\n//\n// read `useSpacesMode()` — the host's parsed route, pushed down.\n// write `navigateSpaces(target)` — a request to MOVE, taking coordinates.\n//\n// The write half never takes a path string, now or later. An app that could spell the\n// destination could open anything (`BUNDLE_EMBEDDING_SPEC` §6.1a), so the SDK offers no\n// string overload and the host builds every URL from its own grammar\n// (`SPACES_BRIEF` §7, \"the host spells the URL\"). That is also why an app reads\n// `space.root` for its files rather than assuming a mount path.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { SPACES_MODE, REQUEST_SPACES_MODE, PROTOCOL_SPACES_MODE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The spaces mode's four top-level activities. */\nexport type SpacesActivity = 'spaces' | 'inbox' | 'people' | 'settings';\n\n/**\n * Where the user is inside the spaces mode, as the host parsed it.\n *\n * `spaceId` is `null` on a route that names no space, which is TWO routes, not one: the\n * launcher (`activity: 'spaces'`) and the **cross-space inbox** (`activity: 'inbox'` —\n * `/spaces/-/inbox`, every room across every space). Branch on the pair, not on `spaceId`\n * alone.\n *\n * The `-` in that URL is the host's reserved segment and never reaches here: it is not an\n * id, and an app must not send `spaceId: '-'` hoping to mean \"all spaces\" — say\n * `{ spaceId: null, activity: 'inbox' }`. The host spells the URL (`SPACES_BRIEF` §7); the\n * SDK never sees that grammar.\n *\n * The optional fields are the per-activity tail: `path` a bundle-relative file, `roomId` a\n * conversation, `member` the uid of `/spaces/<id>/people/<uid>`, `section` a settings pane.\n */\nexport interface SpacesRoute {\n spaceId: string | null;\n activity: SpacesActivity;\n path?: string;\n roomId?: string;\n member?: string;\n section?: string;\n}\n\n/**\n * The selected space, as the host resolved it for THIS frame.\n *\n * `root` is the path the host mounted the space at in this frame, at the reader's role —\n * or `null` in every frame the host did not mount it into. Read files under `root`; never\n * assume a mount path.\n *\n * `name` is untrusted display text supplied by whoever named the space. React escapes it\n * on render and the SDK does not sanitise it — treat it as content, not markup.\n *\n * `kind` (not `mode`) matches site-main's `SpaceKind`: one noun for the personal/shared\n * axis (R-IX-6).\n *\n * **None of this is a grant.** The object describes what the host chose to tell this\n * frame; it confers nothing. `role` is a label for deciding which affordances to *show* —\n * it is not permission to act, and an app that branches on `role === 'owner'` to skip\n * asking has only skipped its own UI, not the check. What IS enforced host-side is the\n * mount: `root` is mounted at the reader's role, so a reader's frame cannot write through\n * it (`site-main` `filesystem/liveRevocation.ts` derives the mount mode from the role, and\n * `editor/spaceHandler.ts` re-checks `role` on the owner-only paths).\n *\n * What is NOT enforced, and must not be read into the above: per-APP authority.\n * `UI_AS_APPS_SPEC` §8's audited gap is explicit that `mount` \"accepts an arbitrary\n * `spaceId` and enforces only user membership … every app currently inherits the user's\n * full authority\". So the host answers \"may the USER do this\", not \"may this app\", and a\n * frame holding this object is no more constrained than the reader is. Treat it as a\n * description of the reader's position, never as a sandbox around the app.\n *\n * A frame the host does not push to reads `null` — an absence of information, not a\n * denial, and equally not a reason to assume access.\n */\nexport interface SpacesModeSpace {\n id: string;\n name: string;\n role: 'owner' | 'writer' | 'reader';\n kind: 'personal' | 'shared';\n root: string | null;\n}\n\n/** The host's view of this frame: where the user is, and which space that resolves to. */\nexport interface SpacesModeState {\n route: SpacesRoute;\n space: SpacesModeSpace | null;\n}\n\n/**\n * Where to move to.\n *\n * Either a route inside the mode, or the one host destination outside it —\n * `{ destination: 'notifications' }`, which the inventory panel's line pointing at pending\n * invitations uses so the app never spells a mode path itself.\n */\nexport type SpacesTarget = SpacesRoute | { destination: 'notifications' };\n\n/** Why the host refused to navigate.\n *\n * - `invalid` — the target is not a route this host can build. This is also the code for\n * a space the reader has no membership-granted view of, **deliberately**: P7 forbids an\n * existence oracle, and `SPACES_BRIEF` §7 says a doclink into a space the reader is not\n * a member of \"renders the same not-found as a link to nothing\". A distinct code here\n * would be exactly the oracle — an app could enumerate spaceIds and read membership off\n * the difference. Non-member and never-existed are one answer.\n * - `forbidden` — this frame lacks the CAPABILITY to navigate at all. It is a statement\n * about the caller, never about the target, so it discloses nothing about what exists.\n * - `unsupported` — this host has no spaces mode wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends; the union was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test. */\nexport type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface NavigateSpacesError extends Error {\n code: NavigateSpacesErrorCode;\n}\n\nconst ACTIVITIES: readonly string[] = ['spaces', 'inbox', 'people', 'settings'];\nconst ROLES: readonly string[] = ['owner', 'writer', 'reader'];\nconst KINDS: readonly string[] = ['personal', 'shared'];\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** A present field must be a string; an absent one is fine. Anything else fails. */\nconst optionalString = (v: unknown): boolean => v === undefined || typeof v === 'string';\n\nconst parseRoute = (v: unknown): SpacesRoute | undefined => {\n if (!isRecord(v)) return undefined;\n if (typeof v.activity !== 'string' || !ACTIVITIES.includes(v.activity)) return undefined;\n if (!(v.spaceId === null || typeof v.spaceId === 'string')) return undefined;\n if (!optionalString(v.path) || !optionalString(v.roomId)) return undefined;\n if (!optionalString(v.member) || !optionalString(v.section)) return undefined;\n const route: SpacesRoute = {\n spaceId: v.spaceId as string | null,\n activity: v.activity as SpacesActivity,\n };\n // Copied field by field rather than spread: a host that adds a field tomorrow must not\n // have it silently appear on an object apps treat as this version's shape.\n if (typeof v.path === 'string') route.path = v.path;\n if (typeof v.roomId === 'string') route.roomId = v.roomId;\n if (typeof v.member === 'string') route.member = v.member;\n if (typeof v.section === 'string') route.section = v.section;\n return route;\n};\n\nconst parseSpace = (v: unknown): SpacesModeSpace | null | undefined => {\n if (v === null) return null;\n if (!isRecord(v)) return undefined;\n if (typeof v.id !== 'string' || typeof v.name !== 'string') return undefined;\n if (typeof v.role !== 'string' || !ROLES.includes(v.role)) return undefined;\n if (typeof v.kind !== 'string' || !KINDS.includes(v.kind)) return undefined;\n if (!(v.root === null || typeof v.root === 'string')) return undefined;\n return {\n id: v.id,\n name: v.name,\n role: v.role as SpacesModeSpace['role'],\n kind: v.kind as SpacesModeSpace['kind'],\n root: v.root as string | null,\n };\n};\n\n// Tolerant parse. `undefined` means \"ignore this message\", so a malformed push from a\n// newer or older host leaves the LAST GOOD value standing instead of flipping every frame\n// to a route nobody sent. Nothing in here throws: a throw in the listener would take down\n// the push loop for every channel sharing it.\nconst parseState = (state: unknown): SpacesModeState | null | undefined => {\n // A pushed `null` is a RETRACTION, not a malformed message, and the wire says so: the\n // channel's declared value is `SpacesModeState | null` (sandbox-protocol 0.11.0,\n // `snapshots/sdk.json`, `spaces-mode.value`). Folding it into the `isRecord` guard below\n // made it mean \"ignore\", which left the host with no way to say \"this frame has left the\n // mode\" — the last route would stand forever, and an app would keep rendering a space it\n // is no longer in. `null` here is distinct from `undefined`: it SETS the value.\n if (state === null) return null;\n if (!isRecord(state)) return undefined;\n const route = parseRoute(state.route);\n if (!route) return undefined;\n const space = parseSpace(state.space);\n if (space === undefined) return undefined;\n return { route, space };\n};\n\n// `initial: null` is the whole compatibility story, and it is deliberately NOT a synthetic\n// `{ activity: 'spaces' }`: an app must be able to tell \"the host has not told me anything\"\n// from \"the host says I am on the launcher\". A frame outside the mode, a standalone tab,\n// `vite dev`, an older host, or a frame lacking the read capability all stay `null`, and an\n// app falls back to its pre-mode UI there.\nconst channel = createPushChannel<SpacesModeState | null>({\n pushType: SPACES_MODE,\n requestType: REQUEST_SPACES_MODE,\n initial: null,\n // Written inline, reading `msg.state` here rather than inside the helper: the snapshot\n // gate extracts a push channel's `reads` from THIS expression, and a bare function\n // reference tells it nothing — it falls back to the parameter type and the wire shape\n // reads `Record<string, unknown>` instead of `{reads:[\"state\"]}`.\n parse: (msg) => parseState(msg.state),\n});\n\n/**\n * The host's spaces-mode state for this frame, or `null` when this app is not running in\n * the spaces mode — a standalone tab, `vite dev`, an older host, or a frame the host does\n * not push this to.\n *\n * `null` is a real answer, not a placeholder: fall back to your own UI rather than\n * assuming a route.\n */\nexport const getSpacesMode = (): SpacesModeState | null => channel.get();\n\n/**\n * Subscribe to spaces-mode changes. The listener is invoked immediately with the current\n * value, then on every change. Returns an unsubscribe function.\n */\nexport const onSpacesModeChange = (listener: (state: SpacesModeState | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/**\n * React hook form of {@link getSpacesMode} — re-renders when the host's route changes.\n *\n * ```tsx\n * const mode = useSpacesMode();\n * if (!mode) return <MyStandaloneUI />; // not in the spaces mode\n * if (!mode.space) return <Launcher />; // no space selected\n * if (!mode.space.root) return <NotMountedHere />; // selected, but not mounted into THIS\n * return <Files root={mode.space.root} />; // never assume a mount path\n * ```\n *\n * The third guard is not defensive padding: `root` is `null` in every frame the host did\n * not mount the space into, which is every frame but the launcher's. Passing it through\n * unchecked is the mistake this example exists to prevent.\n */\nexport const useSpacesMode = (): SpacesModeState | null => channel.use();\n\n/** The host's reply ENVELOPE (site-main's `SpaceResult`). A refusal is a RESOLVED\n * `{ ok: false, code, message }` frame, not a transport-level rejection — see\n * `protocolRefusal.ts` for which `ok` this is and why a handler must THROW\n * `spaceError` rather than return `{ ok: false }`. R3-707's `navigate` handler must\n * throw. */\ntype NavigateReply = { ok: true; data?: unknown } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to move the spaces mode to `target`.\n *\n * Resolves once the host has navigated. Rejects with a typed {@link NavigateSpacesError}\n * carrying `code` when the host refuses.\n *\n * The target is always structured coordinates — there is no path-string form, because an\n * app that could spell the destination could open anything. To leave the mode for the one\n * host destination outside it, pass `{ destination: 'notifications' }`.\n *\n * ```ts\n * await navigateSpaces({ spaceId: 'abc', activity: 'spaces', path: 'notes/today.mdx' });\n * await navigateSpaces({ destination: 'notifications' });\n * ```\n */\nexport async function navigateSpaces(target: SpacesTarget): Promise<void> {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES_MODE], 'navigate', [target])) as NavigateReply;\n throwOnRefusal(res, 'spaces navigation refused');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,0BAAgC;AAChC,6BAA+B;AAC/B,yBAAkC;AAClC,sBAAuE;AACvE,6BAAwB;AA4GxB,MAAM,aAAgC,CAAC,UAAU,SAAS,UAAU,UAAU;AAC9E,MAAM,QAA2B,CAAC,SAAS,UAAU,QAAQ;AAC7D,MAAM,QAA2B,CAAC,YAAY,QAAQ;AAEtD,MAAM,WAAW,CAAC,MAA6C,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAGtH,MAAM,iBAAiB,CAAC,MAAwB,MAAM,UAAa,OAAO,MAAM;AAEhF,M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aAAa,CAAC,UAAuD;AAOzE,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,QAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,EAAE,OAAO,MAAM;AACxB;AAOA,MAAM,cAAU,sCAA0C;AAAA,EACxD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAKT,OAAO,CAAC,QAAQ,WAAW,IAAI,KAAK;AACtC,CAAC;AAUM,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAMhE,MAAM,qBAAqB,CAAC,aACjC,QAAQ,SAAS,QAAQ;AAiBpB,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAwBvE,eAAsB,eAAe,QAAqC;AACxE,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,oCAAoB,GAAG,YAAY,CAAC,MAAM,CAAC;AACtF,6CAAe,KAAK,2BAA2B;AACjD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/spacesMode.ts"],"sourcesContent":["// The spaces mode's route channel and its one navigation verb (R3-708).\n//\n// The spaces mode runs ONE app across six frames — three activity pairs — and they must\n// agree on which space, activity and bundle is selected. A reload or a pasted link has to\n// land every frame on the same state, so the selection is a route the HOST owns and\n// deep-links to (`SPACES_BRIEF` §3), not something the frames negotiate between\n// themselves.\n//\n// Two halves, and the asymmetry is the point:\n//\n// read `useSpacesMode()` — the host's parsed route, pushed down.\n// write `navigateSpaces(target)` — a request to MOVE, taking coordinates.\n//\n// The write half never takes a path string, now or later. An app that could spell the\n// destination could open anything (`BUNDLE_EMBEDDING_SPEC` §6.1a), so the SDK offers no\n// string overload and the host builds every URL from its own grammar\n// (`SPACES_BRIEF` §7, \"the host spells the URL\"). That is also why an app reads\n// `space.root` for its files rather than assuming a mount path.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { SPACES_MODE, REQUEST_SPACES_MODE, PROTOCOL_SPACES_MODE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The spaces mode's four top-level activities. */\nexport type SpacesActivity = 'spaces' | 'inbox' | 'people' | 'settings';\n\n/**\n * Where the user is inside the spaces mode, as the host parsed it.\n *\n * `spaceId` is `null` on a route that names no space, which is TWO routes, not one: the\n * launcher (`activity: 'spaces'`) and the **cross-space inbox** (`activity: 'inbox'` —\n * `/spaces/-/inbox`, every room across every space). Branch on the pair, not on `spaceId`\n * alone.\n *\n * The `-` in that URL is the host's reserved segment and never reaches here: it is not an\n * id, and an app must not send `spaceId: '-'` hoping to mean \"all spaces\" — say\n * `{ spaceId: null, activity: 'inbox' }`. The host spells the URL (`SPACES_BRIEF` §7); the\n * SDK never sees that grammar.\n *\n * The optional fields are the per-activity tail: `path` a bundle-relative file, `roomId` a\n * conversation, `member` the uid of `/spaces/<id>/people/<uid>`, `section` a settings pane.\n */\nexport interface SpacesRoute {\n spaceId: string | null;\n activity: SpacesActivity;\n path?: string;\n roomId?: string;\n member?: string;\n section?: string;\n}\n\n/**\n * The selected space, as the host resolved it for THIS frame.\n *\n * `root` is the path the host mounted the space at in this frame, at the reader's role —\n * or `null` in every frame the host did not mount it into. Read files under `root`; never\n * assume a mount path.\n *\n * `name` is untrusted display text supplied by whoever named the space. React escapes it\n * on render and the SDK does not sanitise it — treat it as content, not markup.\n *\n * `kind` (not `mode`) matches site-main's `SpaceKind`: one noun for the personal/shared\n * axis (R-IX-6).\n *\n * **None of this is a grant.** The object describes what the host chose to tell this\n * frame; it confers nothing. `role` is a label for deciding which affordances to *show* —\n * it is not permission to act, and an app that branches on `role === 'owner'` to skip\n * asking has only skipped its own UI, not the check. What IS enforced host-side is the\n * mount: `root` is mounted at the reader's role, so a reader's frame cannot write through\n * it (`site-main` `filesystem/liveRevocation.ts` derives the mount mode from the role, and\n * `editor/spaceHandler.ts` re-checks `role` on the owner-only paths).\n *\n * What is NOT enforced, and must not be read into the above: per-APP authority.\n * `UI_AS_APPS_SPEC` §8's audited gap is explicit that `mount` \"accepts an arbitrary\n * `spaceId` and enforces only user membership … every app currently inherits the user's\n * full authority\". So the host answers \"may the USER do this\", not \"may this app\", and a\n * frame holding this object is no more constrained than the reader is. Treat it as a\n * description of the reader's position, never as a sandbox around the app.\n *\n * A frame the host does not push to reads `null` — an absence of information, not a\n * denial, and equally not a reason to assume access.\n */\nexport interface SpacesModeSpace {\n id: string;\n name: string;\n role: 'owner' | 'writer' | 'reader';\n kind: 'personal' | 'shared';\n root: string | null;\n}\n\n/** The host's view of this frame: where the user is, and which space that resolves to. */\nexport interface SpacesModeState {\n route: SpacesRoute;\n space: SpacesModeSpace | null;\n}\n\n/**\n * Where to move to.\n *\n * Either a route inside the mode, or the one host destination outside it —\n * `{ destination: 'notifications' }`, which the inventory panel's line pointing at pending\n * invitations uses so the app never spells a mode path itself.\n */\nexport type SpacesTarget = SpacesRoute | { destination: 'notifications' };\n\n/** Why the host refused to navigate.\n *\n * - `invalid` — the target is not a route this host can build. This is also the code for\n * a space the reader has no membership-granted view of, **deliberately**: P7 forbids an\n * existence oracle, and `SPACES_BRIEF` §7 says a doclink into a space the reader is not\n * a member of \"renders the same not-found as a link to nothing\". A distinct code here\n * would be exactly the oracle — an app could enumerate spaceIds and read membership off\n * the difference. Non-member and never-existed are one answer.\n * - `forbidden` — this frame lacks the CAPABILITY to navigate at all. It is a statement\n * about the caller, never about the target, so it discloses nothing about what exists.\n * - `unsupported` — this host has no spaces mode wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends. Nothing enforces the union at runtime — `.code` is\n * whatever string arrived — so treat an unlisted code as possible and `instanceof Error`\n * as the only reliable test.\n *\n * (This note is on the code alias rather than on the interface because the alias is where\n * the codes are documented. Every doclink in this file names the INTERFACE, so a reader\n * following one lands a hop away from this — a wart, not a plan. Stated without a\n * direction on purpose: two earlier revisions of this sentence asserted a positional\n * claim, and both were wrong.) */\nexport type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface NavigateSpacesError extends Error {\n code: NavigateSpacesErrorCode;\n}\n\nconst ACTIVITIES: readonly string[] = ['spaces', 'inbox', 'people', 'settings'];\nconst ROLES: readonly string[] = ['owner', 'writer', 'reader'];\nconst KINDS: readonly string[] = ['personal', 'shared'];\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** A present field must be a string; an absent one is fine. Anything else fails. */\nconst optionalString = (v: unknown): boolean => v === undefined || typeof v === 'string';\n\nconst parseRoute = (v: unknown): SpacesRoute | undefined => {\n if (!isRecord(v)) return undefined;\n if (typeof v.activity !== 'string' || !ACTIVITIES.includes(v.activity)) return undefined;\n if (!(v.spaceId === null || typeof v.spaceId === 'string')) return undefined;\n if (!optionalString(v.path) || !optionalString(v.roomId)) return undefined;\n if (!optionalString(v.member) || !optionalString(v.section)) return undefined;\n const route: SpacesRoute = {\n spaceId: v.spaceId as string | null,\n activity: v.activity as SpacesActivity,\n };\n // Copied field by field rather than spread: a host that adds a field tomorrow must not\n // have it silently appear on an object apps treat as this version's shape.\n if (typeof v.path === 'string') route.path = v.path;\n if (typeof v.roomId === 'string') route.roomId = v.roomId;\n if (typeof v.member === 'string') route.member = v.member;\n if (typeof v.section === 'string') route.section = v.section;\n return route;\n};\n\nconst parseSpace = (v: unknown): SpacesModeSpace | null | undefined => {\n if (v === null) return null;\n if (!isRecord(v)) return undefined;\n if (typeof v.id !== 'string' || typeof v.name !== 'string') return undefined;\n if (typeof v.role !== 'string' || !ROLES.includes(v.role)) return undefined;\n if (typeof v.kind !== 'string' || !KINDS.includes(v.kind)) return undefined;\n if (!(v.root === null || typeof v.root === 'string')) return undefined;\n return {\n id: v.id,\n name: v.name,\n role: v.role as SpacesModeSpace['role'],\n kind: v.kind as SpacesModeSpace['kind'],\n root: v.root as string | null,\n };\n};\n\n// Tolerant parse. `undefined` means \"ignore this message\", so a malformed push from a\n// newer or older host leaves the LAST GOOD value standing instead of flipping every frame\n// to a route nobody sent. Nothing in here throws: a throw in the listener would take down\n// the push loop for every channel sharing it.\nconst parseState = (state: unknown): SpacesModeState | null | undefined => {\n // A pushed `null` is a RETRACTION, not a malformed message, and the wire says so: the\n // channel's declared value is `SpacesModeState | null` (sandbox-protocol 0.11.0,\n // `snapshots/sdk.json`, `spaces-mode.value`). Folding it into the `isRecord` guard below\n // made it mean \"ignore\", which left the host with no way to say \"this frame has left the\n // mode\" — the last route would stand forever, and an app would keep rendering a space it\n // is no longer in. `null` here is distinct from `undefined`: it SETS the value.\n if (state === null) return null;\n if (!isRecord(state)) return undefined;\n const route = parseRoute(state.route);\n if (!route) return undefined;\n const space = parseSpace(state.space);\n if (space === undefined) return undefined;\n return { route, space };\n};\n\n// `initial: null` is the whole compatibility story, and it is deliberately NOT a synthetic\n// `{ activity: 'spaces' }`: an app must be able to tell \"the host has not told me anything\"\n// from \"the host says I am on the launcher\". A frame outside the mode, a standalone tab,\n// `vite dev`, an older host, or a frame lacking the read capability all stay `null`, and an\n// app falls back to its pre-mode UI there.\nconst channel = createPushChannel<SpacesModeState | null>({\n pushType: SPACES_MODE,\n requestType: REQUEST_SPACES_MODE,\n initial: null,\n // Written inline, reading `msg.state` here rather than inside the helper: the snapshot\n // gate extracts a push channel's `reads` from THIS expression, and a bare function\n // reference tells it nothing — it falls back to the parameter type and the wire shape\n // reads `Record<string, unknown>` instead of `{reads:[\"state\"]}`.\n parse: (msg) => parseState(msg.state),\n});\n\n/**\n * The host's spaces-mode state for this frame, or `null` when this app is not running in\n * the spaces mode — a standalone tab, `vite dev`, an older host, or a frame the host does\n * not push this to.\n *\n * `null` is a real answer, not a placeholder: fall back to your own UI rather than\n * assuming a route.\n */\nexport const getSpacesMode = (): SpacesModeState | null => channel.get();\n\n/**\n * Subscribe to spaces-mode changes. The listener is invoked immediately with the current\n * value, then on every change. Returns an unsubscribe function.\n */\nexport const onSpacesModeChange = (listener: (state: SpacesModeState | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/**\n * React hook form of {@link getSpacesMode} — re-renders when the host's route changes.\n *\n * ```tsx\n * const mode = useSpacesMode();\n * if (!mode) return <MyStandaloneUI />; // not in the spaces mode\n * if (!mode.space) return <Launcher />; // no space selected\n * if (!mode.space.root) return <NotMountedHere />; // selected, but not mounted into THIS\n * return <Files root={mode.space.root} />; // never assume a mount path\n * ```\n *\n * The third guard is not defensive padding: `root` is `null` in every frame the host did\n * not mount the space into, which is every frame but the launcher's. Passing it through\n * unchecked is the mistake this example exists to prevent.\n */\nexport const useSpacesMode = (): SpacesModeState | null => channel.use();\n\n/** The host's reply ENVELOPE (site-main's `SpaceResult`). A refusal is a RESOLVED\n * `{ ok: false, code, message }` frame, not a transport-level rejection — see\n * `protocolRefusal.ts` for which `ok` this is and why a handler must THROW\n * `spaceError` rather than return `{ ok: false }`. R3-707's `navigate` handler must\n * throw. */\ntype NavigateReply = { ok: true; data?: unknown } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to move the spaces mode to `target`.\n *\n * Resolves once the host has navigated. Rejects with a typed {@link NavigateSpacesError}\n * carrying `code` when the host refuses.\n *\n * The target is always structured coordinates — there is no path-string form, because an\n * app that could spell the destination could open anything. To leave the mode for the one\n * host destination outside it, pass `{ destination: 'notifications' }`.\n *\n * ```ts\n * await navigateSpaces({ spaceId: 'abc', activity: 'spaces', path: 'notes/today.mdx' });\n * await navigateSpaces({ destination: 'notifications' });\n * ```\n */\nexport async function navigateSpaces(target: SpacesTarget): Promise<void> {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES_MODE], 'navigate', [target])) as NavigateReply;\n throwOnRefusal(res, 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 type SpacesTarget = SpacesRoute | {
|
|
|
92
92
|
*
|
|
93
93
|
* **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
|
|
94
94
|
* `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the
|
|
95
|
-
* `.code` VALUES the host sends
|
|
96
|
-
*
|
|
97
|
-
* reliable test.
|
|
95
|
+
* `.code` VALUES the host sends. Nothing enforces the union at runtime — `.code` is
|
|
96
|
+
* whatever string arrived — so treat an unlisted code as possible and `instanceof Error`
|
|
97
|
+
* as the only reliable test.
|
|
98
|
+
*
|
|
99
|
+
* (This note is on the code alias rather than on the interface because the alias is where
|
|
100
|
+
* the codes are documented. Every doclink in this file names the INTERFACE, so a reader
|
|
101
|
+
* following one lands a hop away from this — a wart, not a plan. Stated without a
|
|
102
|
+
* direction on purpose: two earlier revisions of this sentence asserted a positional
|
|
103
|
+
* claim, and both were wrong.) */
|
|
98
104
|
type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';
|
|
99
105
|
interface NavigateSpacesError extends Error {
|
|
100
106
|
code: NavigateSpacesErrorCode;
|
package/dist/spacesMode.d.ts
CHANGED
|
@@ -92,9 +92,15 @@ type SpacesTarget = SpacesRoute | {
|
|
|
92
92
|
*
|
|
93
93
|
* **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
|
|
94
94
|
* `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the
|
|
95
|
-
* `.code` VALUES the host sends
|
|
96
|
-
*
|
|
97
|
-
* reliable test.
|
|
95
|
+
* `.code` VALUES the host sends. Nothing enforces the union at runtime — `.code` is
|
|
96
|
+
* whatever string arrived — so treat an unlisted code as possible and `instanceof Error`
|
|
97
|
+
* as the only reliable test.
|
|
98
|
+
*
|
|
99
|
+
* (This note is on the code alias rather than on the interface because the alias is where
|
|
100
|
+
* the codes are documented. Every doclink in this file names the INTERFACE, so a reader
|
|
101
|
+
* following one lands a hop away from this — a wart, not a plan. Stated without a
|
|
102
|
+
* direction on purpose: two earlier revisions of this sentence asserted a positional
|
|
103
|
+
* claim, and both were wrong.) */
|
|
98
104
|
type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';
|
|
99
105
|
interface NavigateSpacesError extends Error {
|
|
100
106
|
code: NavigateSpacesErrorCode;
|
package/dist/spacesMode.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/spacesMode.ts"],"sourcesContent":["// The spaces mode's route channel and its one navigation verb (R3-708).\n//\n// The spaces mode runs ONE app across six frames — three activity pairs — and they must\n// agree on which space, activity and bundle is selected. A reload or a pasted link has to\n// land every frame on the same state, so the selection is a route the HOST owns and\n// deep-links to (`SPACES_BRIEF` §3), not something the frames negotiate between\n// themselves.\n//\n// Two halves, and the asymmetry is the point:\n//\n// read `useSpacesMode()` — the host's parsed route, pushed down.\n// write `navigateSpaces(target)` — a request to MOVE, taking coordinates.\n//\n// The write half never takes a path string, now or later. An app that could spell the\n// destination could open anything (`BUNDLE_EMBEDDING_SPEC` §6.1a), so the SDK offers no\n// string overload and the host builds every URL from its own grammar\n// (`SPACES_BRIEF` §7, \"the host spells the URL\"). That is also why an app reads\n// `space.root` for its files rather than assuming a mount path.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { SPACES_MODE, REQUEST_SPACES_MODE, PROTOCOL_SPACES_MODE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The spaces mode's four top-level activities. */\nexport type SpacesActivity = 'spaces' | 'inbox' | 'people' | 'settings';\n\n/**\n * Where the user is inside the spaces mode, as the host parsed it.\n *\n * `spaceId` is `null` on a route that names no space, which is TWO routes, not one: the\n * launcher (`activity: 'spaces'`) and the **cross-space inbox** (`activity: 'inbox'` —\n * `/spaces/-/inbox`, every room across every space). Branch on the pair, not on `spaceId`\n * alone.\n *\n * The `-` in that URL is the host's reserved segment and never reaches here: it is not an\n * id, and an app must not send `spaceId: '-'` hoping to mean \"all spaces\" — say\n * `{ spaceId: null, activity: 'inbox' }`. The host spells the URL (`SPACES_BRIEF` §7); the\n * SDK never sees that grammar.\n *\n * The optional fields are the per-activity tail: `path` a bundle-relative file, `roomId` a\n * conversation, `member` the uid of `/spaces/<id>/people/<uid>`, `section` a settings pane.\n */\nexport interface SpacesRoute {\n spaceId: string | null;\n activity: SpacesActivity;\n path?: string;\n roomId?: string;\n member?: string;\n section?: string;\n}\n\n/**\n * The selected space, as the host resolved it for THIS frame.\n *\n * `root` is the path the host mounted the space at in this frame, at the reader's role —\n * or `null` in every frame the host did not mount it into. Read files under `root`; never\n * assume a mount path.\n *\n * `name` is untrusted display text supplied by whoever named the space. React escapes it\n * on render and the SDK does not sanitise it — treat it as content, not markup.\n *\n * `kind` (not `mode`) matches site-main's `SpaceKind`: one noun for the personal/shared\n * axis (R-IX-6).\n *\n * **None of this is a grant.** The object describes what the host chose to tell this\n * frame; it confers nothing. `role` is a label for deciding which affordances to *show* —\n * it is not permission to act, and an app that branches on `role === 'owner'` to skip\n * asking has only skipped its own UI, not the check. What IS enforced host-side is the\n * mount: `root` is mounted at the reader's role, so a reader's frame cannot write through\n * it (`site-main` `filesystem/liveRevocation.ts` derives the mount mode from the role, and\n * `editor/spaceHandler.ts` re-checks `role` on the owner-only paths).\n *\n * What is NOT enforced, and must not be read into the above: per-APP authority.\n * `UI_AS_APPS_SPEC` §8's audited gap is explicit that `mount` \"accepts an arbitrary\n * `spaceId` and enforces only user membership … every app currently inherits the user's\n * full authority\". So the host answers \"may the USER do this\", not \"may this app\", and a\n * frame holding this object is no more constrained than the reader is. Treat it as a\n * description of the reader's position, never as a sandbox around the app.\n *\n * A frame the host does not push to reads `null` — an absence of information, not a\n * denial, and equally not a reason to assume access.\n */\nexport interface SpacesModeSpace {\n id: string;\n name: string;\n role: 'owner' | 'writer' | 'reader';\n kind: 'personal' | 'shared';\n root: string | null;\n}\n\n/** The host's view of this frame: where the user is, and which space that resolves to. */\nexport interface SpacesModeState {\n route: SpacesRoute;\n space: SpacesModeSpace | null;\n}\n\n/**\n * Where to move to.\n *\n * Either a route inside the mode, or the one host destination outside it —\n * `{ destination: 'notifications' }`, which the inventory panel's line pointing at pending\n * invitations uses so the app never spells a mode path itself.\n */\nexport type SpacesTarget = SpacesRoute | { destination: 'notifications' };\n\n/** Why the host refused to navigate.\n *\n * - `invalid` — the target is not a route this host can build. This is also the code for\n * a space the reader has no membership-granted view of, **deliberately**: P7 forbids an\n * existence oracle, and `SPACES_BRIEF` §7 says a doclink into a space the reader is not\n * a member of \"renders the same not-found as a link to nothing\". A distinct code here\n * would be exactly the oracle — an app could enumerate spaceIds and read membership off\n * the difference. Non-member and never-existed are one answer.\n * - `forbidden` — this frame lacks the CAPABILITY to navigate at all. It is a statement\n * about the caller, never about the target, so it discloses nothing about what exists.\n * - `unsupported` — this host has no spaces mode wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends; the union was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test. */\nexport type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface NavigateSpacesError extends Error {\n code: NavigateSpacesErrorCode;\n}\n\nconst ACTIVITIES: readonly string[] = ['spaces', 'inbox', 'people', 'settings'];\nconst ROLES: readonly string[] = ['owner', 'writer', 'reader'];\nconst KINDS: readonly string[] = ['personal', 'shared'];\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** A present field must be a string; an absent one is fine. Anything else fails. */\nconst optionalString = (v: unknown): boolean => v === undefined || typeof v === 'string';\n\nconst parseRoute = (v: unknown): SpacesRoute | undefined => {\n if (!isRecord(v)) return undefined;\n if (typeof v.activity !== 'string' || !ACTIVITIES.includes(v.activity)) return undefined;\n if (!(v.spaceId === null || typeof v.spaceId === 'string')) return undefined;\n if (!optionalString(v.path) || !optionalString(v.roomId)) return undefined;\n if (!optionalString(v.member) || !optionalString(v.section)) return undefined;\n const route: SpacesRoute = {\n spaceId: v.spaceId as string | null,\n activity: v.activity as SpacesActivity,\n };\n // Copied field by field rather than spread: a host that adds a field tomorrow must not\n // have it silently appear on an object apps treat as this version's shape.\n if (typeof v.path === 'string') route.path = v.path;\n if (typeof v.roomId === 'string') route.roomId = v.roomId;\n if (typeof v.member === 'string') route.member = v.member;\n if (typeof v.section === 'string') route.section = v.section;\n return route;\n};\n\nconst parseSpace = (v: unknown): SpacesModeSpace | null | undefined => {\n if (v === null) return null;\n if (!isRecord(v)) return undefined;\n if (typeof v.id !== 'string' || typeof v.name !== 'string') return undefined;\n if (typeof v.role !== 'string' || !ROLES.includes(v.role)) return undefined;\n if (typeof v.kind !== 'string' || !KINDS.includes(v.kind)) return undefined;\n if (!(v.root === null || typeof v.root === 'string')) return undefined;\n return {\n id: v.id,\n name: v.name,\n role: v.role as SpacesModeSpace['role'],\n kind: v.kind as SpacesModeSpace['kind'],\n root: v.root as string | null,\n };\n};\n\n// Tolerant parse. `undefined` means \"ignore this message\", so a malformed push from a\n// newer or older host leaves the LAST GOOD value standing instead of flipping every frame\n// to a route nobody sent. Nothing in here throws: a throw in the listener would take down\n// the push loop for every channel sharing it.\nconst parseState = (state: unknown): SpacesModeState | null | undefined => {\n // A pushed `null` is a RETRACTION, not a malformed message, and the wire says so: the\n // channel's declared value is `SpacesModeState | null` (sandbox-protocol 0.11.0,\n // `snapshots/sdk.json`, `spaces-mode.value`). Folding it into the `isRecord` guard below\n // made it mean \"ignore\", which left the host with no way to say \"this frame has left the\n // mode\" — the last route would stand forever, and an app would keep rendering a space it\n // is no longer in. `null` here is distinct from `undefined`: it SETS the value.\n if (state === null) return null;\n if (!isRecord(state)) return undefined;\n const route = parseRoute(state.route);\n if (!route) return undefined;\n const space = parseSpace(state.space);\n if (space === undefined) return undefined;\n return { route, space };\n};\n\n// `initial: null` is the whole compatibility story, and it is deliberately NOT a synthetic\n// `{ activity: 'spaces' }`: an app must be able to tell \"the host has not told me anything\"\n// from \"the host says I am on the launcher\". A frame outside the mode, a standalone tab,\n// `vite dev`, an older host, or a frame lacking the read capability all stay `null`, and an\n// app falls back to its pre-mode UI there.\nconst channel = createPushChannel<SpacesModeState | null>({\n pushType: SPACES_MODE,\n requestType: REQUEST_SPACES_MODE,\n initial: null,\n // Written inline, reading `msg.state` here rather than inside the helper: the snapshot\n // gate extracts a push channel's `reads` from THIS expression, and a bare function\n // reference tells it nothing — it falls back to the parameter type and the wire shape\n // reads `Record<string, unknown>` instead of `{reads:[\"state\"]}`.\n parse: (msg) => parseState(msg.state),\n});\n\n/**\n * The host's spaces-mode state for this frame, or `null` when this app is not running in\n * the spaces mode — a standalone tab, `vite dev`, an older host, or a frame the host does\n * not push this to.\n *\n * `null` is a real answer, not a placeholder: fall back to your own UI rather than\n * assuming a route.\n */\nexport const getSpacesMode = (): SpacesModeState | null => channel.get();\n\n/**\n * Subscribe to spaces-mode changes. The listener is invoked immediately with the current\n * value, then on every change. Returns an unsubscribe function.\n */\nexport const onSpacesModeChange = (listener: (state: SpacesModeState | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/**\n * React hook form of {@link getSpacesMode} — re-renders when the host's route changes.\n *\n * ```tsx\n * const mode = useSpacesMode();\n * if (!mode) return <MyStandaloneUI />; // not in the spaces mode\n * if (!mode.space) return <Launcher />; // no space selected\n * if (!mode.space.root) return <NotMountedHere />; // selected, but not mounted into THIS\n * return <Files root={mode.space.root} />; // never assume a mount path\n * ```\n *\n * The third guard is not defensive padding: `root` is `null` in every frame the host did\n * not mount the space into, which is every frame but the launcher's. Passing it through\n * unchecked is the mistake this example exists to prevent.\n */\nexport const useSpacesMode = (): SpacesModeState | null => channel.use();\n\n/** The host's reply ENVELOPE (site-main's `SpaceResult`). A refusal is a RESOLVED\n * `{ ok: false, code, message }` frame, not a transport-level rejection — see\n * `protocolRefusal.ts` for which `ok` this is and why a handler must THROW\n * `spaceError` rather than return `{ ok: false }`. R3-707's `navigate` handler must\n * throw. */\ntype NavigateReply = { ok: true; data?: unknown } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to move the spaces mode to `target`.\n *\n * Resolves once the host has navigated. Rejects with a typed {@link NavigateSpacesError}\n * carrying `code` when the host refuses.\n *\n * The target is always structured coordinates — there is no path-string form, because an\n * app that could spell the destination could open anything. To leave the mode for the one\n * host destination outside it, pass `{ destination: 'notifications' }`.\n *\n * ```ts\n * await navigateSpaces({ spaceId: 'abc', activity: 'spaces', path: 'notes/today.mdx' });\n * await navigateSpaces({ destination: 'notifications' });\n * ```\n */\nexport async function navigateSpaces(target: SpacesTarget): Promise<void> {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES_MODE], 'navigate', [target])) as NavigateReply;\n throwOnRefusal(res, 'spaces navigation refused');\n}\n"],"mappings":";AAkBA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,aAAa,qBAAqB,4BAA4B;AACvE,SAAS,eAAe;AA4GxB,MAAM,aAAgC,CAAC,UAAU,SAAS,UAAU,UAAU;AAC9E,MAAM,QAA2B,CAAC,SAAS,UAAU,QAAQ;AAC7D,MAAM,QAA2B,CAAC,YAAY,QAAQ;AAEtD,MAAM,WAAW,CAAC,MAA6C,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAGtH,MAAM,iBAAiB,CAAC,MAAwB,MAAM,UAAa,OAAO,MAAM;AAEhF,MAAM,aAAa,CAAC,MAAwC;AAC1D,MAAI,CAAC,SAAS,CAAC,EAAG,QAAO;AACzB,MAAI,OAAO,EAAE,aAAa,YAAY,CAAC,WAAW,SAAS,EAAE,QAAQ,EAAG,QAAO;AAC/E,MAAI,EAAE,EAAE,YAAY,QAAQ,OAAO,EAAE,Y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;AACpC,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,EAAE,OAAO,MAAM;AACxB;AAOA,MAAM,UAAU,kBAA0C;AAAA,EACxD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAKT,OAAO,CAAC,QAAQ,WAAW,IAAI,KAAK;AACtC,CAAC;AAUM,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAMhE,MAAM,qBAAqB,CAAC,aACjC,QAAQ,SAAS,QAAQ;AAiBpB,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAwBvE,eAAsB,eAAe,QAAqC;AACxE,QAAM,MAAO,MAAM,gBAAgB,QAAQ,oBAAoB,GAAG,YAAY,CAAC,MAAM,CAAC;AACtF,iBAAe,KAAK,2BAA2B;AACjD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/spacesMode.ts"],"sourcesContent":["// The spaces mode's route channel and its one navigation verb (R3-708).\n//\n// The spaces mode runs ONE app across six frames — three activity pairs — and they must\n// agree on which space, activity and bundle is selected. A reload or a pasted link has to\n// land every frame on the same state, so the selection is a route the HOST owns and\n// deep-links to (`SPACES_BRIEF` §3), not something the frames negotiate between\n// themselves.\n//\n// Two halves, and the asymmetry is the point:\n//\n// read `useSpacesMode()` — the host's parsed route, pushed down.\n// write `navigateSpaces(target)` — a request to MOVE, taking coordinates.\n//\n// The write half never takes a path string, now or later. An app that could spell the\n// destination could open anything (`BUNDLE_EMBEDDING_SPEC` §6.1a), so the SDK offers no\n// string overload and the host builds every URL from its own grammar\n// (`SPACES_BRIEF` §7, \"the host spells the URL\"). That is also why an app reads\n// `space.root` for its files rather than assuming a mount path.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { SPACES_MODE, REQUEST_SPACES_MODE, PROTOCOL_SPACES_MODE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The spaces mode's four top-level activities. */\nexport type SpacesActivity = 'spaces' | 'inbox' | 'people' | 'settings';\n\n/**\n * Where the user is inside the spaces mode, as the host parsed it.\n *\n * `spaceId` is `null` on a route that names no space, which is TWO routes, not one: the\n * launcher (`activity: 'spaces'`) and the **cross-space inbox** (`activity: 'inbox'` —\n * `/spaces/-/inbox`, every room across every space). Branch on the pair, not on `spaceId`\n * alone.\n *\n * The `-` in that URL is the host's reserved segment and never reaches here: it is not an\n * id, and an app must not send `spaceId: '-'` hoping to mean \"all spaces\" — say\n * `{ spaceId: null, activity: 'inbox' }`. The host spells the URL (`SPACES_BRIEF` §7); the\n * SDK never sees that grammar.\n *\n * The optional fields are the per-activity tail: `path` a bundle-relative file, `roomId` a\n * conversation, `member` the uid of `/spaces/<id>/people/<uid>`, `section` a settings pane.\n */\nexport interface SpacesRoute {\n spaceId: string | null;\n activity: SpacesActivity;\n path?: string;\n roomId?: string;\n member?: string;\n section?: string;\n}\n\n/**\n * The selected space, as the host resolved it for THIS frame.\n *\n * `root` is the path the host mounted the space at in this frame, at the reader's role —\n * or `null` in every frame the host did not mount it into. Read files under `root`; never\n * assume a mount path.\n *\n * `name` is untrusted display text supplied by whoever named the space. React escapes it\n * on render and the SDK does not sanitise it — treat it as content, not markup.\n *\n * `kind` (not `mode`) matches site-main's `SpaceKind`: one noun for the personal/shared\n * axis (R-IX-6).\n *\n * **None of this is a grant.** The object describes what the host chose to tell this\n * frame; it confers nothing. `role` is a label for deciding which affordances to *show* —\n * it is not permission to act, and an app that branches on `role === 'owner'` to skip\n * asking has only skipped its own UI, not the check. What IS enforced host-side is the\n * mount: `root` is mounted at the reader's role, so a reader's frame cannot write through\n * it (`site-main` `filesystem/liveRevocation.ts` derives the mount mode from the role, and\n * `editor/spaceHandler.ts` re-checks `role` on the owner-only paths).\n *\n * What is NOT enforced, and must not be read into the above: per-APP authority.\n * `UI_AS_APPS_SPEC` §8's audited gap is explicit that `mount` \"accepts an arbitrary\n * `spaceId` and enforces only user membership … every app currently inherits the user's\n * full authority\". So the host answers \"may the USER do this\", not \"may this app\", and a\n * frame holding this object is no more constrained than the reader is. Treat it as a\n * description of the reader's position, never as a sandbox around the app.\n *\n * A frame the host does not push to reads `null` — an absence of information, not a\n * denial, and equally not a reason to assume access.\n */\nexport interface SpacesModeSpace {\n id: string;\n name: string;\n role: 'owner' | 'writer' | 'reader';\n kind: 'personal' | 'shared';\n root: string | null;\n}\n\n/** The host's view of this frame: where the user is, and which space that resolves to. */\nexport interface SpacesModeState {\n route: SpacesRoute;\n space: SpacesModeSpace | null;\n}\n\n/**\n * Where to move to.\n *\n * Either a route inside the mode, or the one host destination outside it —\n * `{ destination: 'notifications' }`, which the inventory panel's line pointing at pending\n * invitations uses so the app never spells a mode path itself.\n */\nexport type SpacesTarget = SpacesRoute | { destination: 'notifications' };\n\n/** Why the host refused to navigate.\n *\n * - `invalid` — the target is not a route this host can build. This is also the code for\n * a space the reader has no membership-granted view of, **deliberately**: P7 forbids an\n * existence oracle, and `SPACES_BRIEF` §7 says a doclink into a space the reader is not\n * a member of \"renders the same not-found as a link to nothing\". A distinct code here\n * would be exactly the oracle — an app could enumerate spaceIds and read membership off\n * the difference. Non-member and never-existed are one answer.\n * - `forbidden` — this frame lacks the CAPABILITY to navigate at all. It is a statement\n * about the caller, never about the target, so it discloses nothing about what exists.\n * - `unsupported` — this host has no spaces mode wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends. Nothing enforces the union at runtime — `.code` is\n * whatever string arrived — so treat an unlisted code as possible and `instanceof Error`\n * as the only reliable test.\n *\n * (This note is on the code alias rather than on the interface because the alias is where\n * the codes are documented. Every doclink in this file names the INTERFACE, so a reader\n * following one lands a hop away from this — a wart, not a plan. Stated without a\n * direction on purpose: two earlier revisions of this sentence asserted a positional\n * claim, and both were wrong.) */\nexport type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface NavigateSpacesError extends Error {\n code: NavigateSpacesErrorCode;\n}\n\nconst ACTIVITIES: readonly string[] = ['spaces', 'inbox', 'people', 'settings'];\nconst ROLES: readonly string[] = ['owner', 'writer', 'reader'];\nconst KINDS: readonly string[] = ['personal', 'shared'];\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** A present field must be a string; an absent one is fine. Anything else fails. */\nconst optionalString = (v: unknown): boolean => v === undefined || typeof v === 'string';\n\nconst parseRoute = (v: unknown): SpacesRoute | undefined => {\n if (!isRecord(v)) return undefined;\n if (typeof v.activity !== 'string' || !ACTIVITIES.includes(v.activity)) return undefined;\n if (!(v.spaceId === null || typeof v.spaceId === 'string')) return undefined;\n if (!optionalString(v.path) || !optionalString(v.roomId)) return undefined;\n if (!optionalString(v.member) || !optionalString(v.section)) return undefined;\n const route: SpacesRoute = {\n spaceId: v.spaceId as string | null,\n activity: v.activity as SpacesActivity,\n };\n // Copied field by field rather than spread: a host that adds a field tomorrow must not\n // have it silently appear on an object apps treat as this version's shape.\n if (typeof v.path === 'string') route.path = v.path;\n if (typeof v.roomId === 'string') route.roomId = v.roomId;\n if (typeof v.member === 'string') route.member = v.member;\n if (typeof v.section === 'string') route.section = v.section;\n return route;\n};\n\nconst parseSpace = (v: unknown): SpacesModeSpace | null | undefined => {\n if (v === null) return null;\n if (!isRecord(v)) return undefined;\n if (typeof v.id !== 'string' || typeof v.name !== 'string') return undefined;\n if (typeof v.role !== 'string' || !ROLES.includes(v.role)) return undefined;\n if (typeof v.kind !== 'string' || !KINDS.includes(v.kind)) return undefined;\n if (!(v.root === null || typeof v.root === 'string')) return undefined;\n return {\n id: v.id,\n name: v.name,\n role: v.role as SpacesModeSpace['role'],\n kind: v.kind as SpacesModeSpace['kind'],\n root: v.root as string | null,\n };\n};\n\n// Tolerant parse. `undefined` means \"ignore this message\", so a malformed push from a\n// newer or older host leaves the LAST GOOD value standing instead of flipping every frame\n// to a route nobody sent. Nothing in here throws: a throw in the listener would take down\n// the push loop for every channel sharing it.\nconst parseState = (state: unknown): SpacesModeState | null | undefined => {\n // A pushed `null` is a RETRACTION, not a malformed message, and the wire says so: the\n // channel's declared value is `SpacesModeState | null` (sandbox-protocol 0.11.0,\n // `snapshots/sdk.json`, `spaces-mode.value`). Folding it into the `isRecord` guard below\n // made it mean \"ignore\", which left the host with no way to say \"this frame has left the\n // mode\" — the last route would stand forever, and an app would keep rendering a space it\n // is no longer in. `null` here is distinct from `undefined`: it SETS the value.\n if (state === null) return null;\n if (!isRecord(state)) return undefined;\n const route = parseRoute(state.route);\n if (!route) return undefined;\n const space = parseSpace(state.space);\n if (space === undefined) return undefined;\n return { route, space };\n};\n\n// `initial: null` is the whole compatibility story, and it is deliberately NOT a synthetic\n// `{ activity: 'spaces' }`: an app must be able to tell \"the host has not told me anything\"\n// from \"the host says I am on the launcher\". A frame outside the mode, a standalone tab,\n// `vite dev`, an older host, or a frame lacking the read capability all stay `null`, and an\n// app falls back to its pre-mode UI there.\nconst channel = createPushChannel<SpacesModeState | null>({\n pushType: SPACES_MODE,\n requestType: REQUEST_SPACES_MODE,\n initial: null,\n // Written inline, reading `msg.state` here rather than inside the helper: the snapshot\n // gate extracts a push channel's `reads` from THIS expression, and a bare function\n // reference tells it nothing — it falls back to the parameter type and the wire shape\n // reads `Record<string, unknown>` instead of `{reads:[\"state\"]}`.\n parse: (msg) => parseState(msg.state),\n});\n\n/**\n * The host's spaces-mode state for this frame, or `null` when this app is not running in\n * the spaces mode — a standalone tab, `vite dev`, an older host, or a frame the host does\n * not push this to.\n *\n * `null` is a real answer, not a placeholder: fall back to your own UI rather than\n * assuming a route.\n */\nexport const getSpacesMode = (): SpacesModeState | null => channel.get();\n\n/**\n * Subscribe to spaces-mode changes. The listener is invoked immediately with the current\n * value, then on every change. Returns an unsubscribe function.\n */\nexport const onSpacesModeChange = (listener: (state: SpacesModeState | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/**\n * React hook form of {@link getSpacesMode} — re-renders when the host's route changes.\n *\n * ```tsx\n * const mode = useSpacesMode();\n * if (!mode) return <MyStandaloneUI />; // not in the spaces mode\n * if (!mode.space) return <Launcher />; // no space selected\n * if (!mode.space.root) return <NotMountedHere />; // selected, but not mounted into THIS\n * return <Files root={mode.space.root} />; // never assume a mount path\n * ```\n *\n * The third guard is not defensive padding: `root` is `null` in every frame the host did\n * not mount the space into, which is every frame but the launcher's. Passing it through\n * unchecked is the mistake this example exists to prevent.\n */\nexport const useSpacesMode = (): SpacesModeState | null => channel.use();\n\n/** The host's reply ENVELOPE (site-main's `SpaceResult`). A refusal is a RESOLVED\n * `{ ok: false, code, message }` frame, not a transport-level rejection — see\n * `protocolRefusal.ts` for which `ok` this is and why a handler must THROW\n * `spaceError` rather than return `{ ok: false }`. R3-707's `navigate` handler must\n * throw. */\ntype NavigateReply = { ok: true; data?: unknown } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to move the spaces mode to `target`.\n *\n * Resolves once the host has navigated. Rejects with a typed {@link NavigateSpacesError}\n * carrying `code` when the host refuses.\n *\n * The target is always structured coordinates — there is no path-string form, because an\n * app that could spell the destination could open anything. To leave the mode for the one\n * host destination outside it, pass `{ destination: 'notifications' }`.\n *\n * ```ts\n * await navigateSpaces({ spaceId: 'abc', activity: 'spaces', path: 'notes/today.mdx' });\n * await navigateSpaces({ destination: 'notifications' });\n * ```\n */\nexport async function navigateSpaces(target: SpacesTarget): Promise<void> {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES_MODE], 'navigate', [target])) as NavigateReply;\n throwOnRefusal(res, 'spaces navigation refused');\n}\n"],"mappings":";AAkBA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,aAAa,qBAAqB,4BAA4B;AACvE,SAAS,eAAe;AAkHxB,MAAM,aAAgC,CAAC,UAAU,SAAS,UAAU,UAAU;AAC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AI,EAAG,QAAO;AAClE,MAAI,EAAE,EAAE,SAAS,QAAQ,OAAO,EAAE,SAAS,UAAW,QAAO;AAC7D,SAAO;AAAA,IACL,IAAI,EAAE;AAAA,IACN,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,EACV;AACF;AAMA,MAAM,aAAa,CAAC,UAAuD;AAOzE,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,QAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,EAAE,OAAO,MAAM;AACxB;AAOA,MAAM,UAAU,kBAA0C;AAAA,EACxD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAKT,OAAO,CAAC,QAAQ,WAAW,IAAI,KAAK;AACtC,CAAC;AAUM,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAMhE,MAAM,qBAAqB,CAAC,aACjC,QAAQ,SAAS,QAAQ;AAiBpB,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAwBvE,eAAsB,eAAe,QAAqC;AACxE,QAAM,MAAO,MAAM,gBAAgB,QAAQ,oBAAoB,GAAG,YAAY,CAAC,MAAM,CAAC;AACtF,iBAAe,KAAK,2BAA2B;AACjD;","names":[]}
|
package/dist/theme.cjs
CHANGED
|
@@ -35,6 +35,7 @@ __export(theme_exports, {
|
|
|
35
35
|
module.exports = __toCommonJS(theme_exports);
|
|
36
36
|
var import_pushChannel = require("./pushChannel");
|
|
37
37
|
var import_sandboxUtils = require("./sandboxUtils");
|
|
38
|
+
var import_protocolRefusal = require("./protocolRefusal");
|
|
38
39
|
var import_protocol = require("./generated/protocol");
|
|
39
40
|
var import_protocolSchemes = require("./protocolSchemes");
|
|
40
41
|
const DEFAULT_SELECTION = {
|
|
@@ -92,11 +93,7 @@ const onThemeCatalogChange = (listener) => catalogChannel.onChange(listener);
|
|
|
92
93
|
const useThemeCatalog = () => catalogChannel.use();
|
|
93
94
|
const setTheme = async (params) => {
|
|
94
95
|
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_THEME], "set", [params]);
|
|
95
|
-
|
|
96
|
-
const err = new Error(res?.message ?? "setHostTheme failed");
|
|
97
|
-
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
|
98
|
-
throw err;
|
|
99
|
-
}
|
|
96
|
+
(0, import_protocolRefusal.throwOnRefusal)(res, "setHostTheme failed");
|
|
100
97
|
};
|
|
101
98
|
const setHostThemeSelection = async (selection) => {
|
|
102
99
|
await setTheme(selection);
|
|
@@ -106,19 +103,11 @@ const setHostTheme = async (theme) => {
|
|
|
106
103
|
};
|
|
107
104
|
const addThemeSource = async (location) => {
|
|
108
105
|
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_THEME], "add-source", [{ location }]);
|
|
109
|
-
|
|
110
|
-
const err = new Error(res?.message ?? "addThemeSource failed");
|
|
111
|
-
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
|
112
|
-
throw err;
|
|
113
|
-
}
|
|
106
|
+
(0, import_protocolRefusal.throwOnRefusal)(res, "addThemeSource failed");
|
|
114
107
|
};
|
|
115
108
|
const removeThemeSource = async (themeKey) => {
|
|
116
109
|
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_THEME], "remove-source", [{ themeKey }]);
|
|
117
|
-
|
|
118
|
-
const err = new Error(res?.message ?? "removeThemeSource failed");
|
|
119
|
-
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
|
120
|
-
throw err;
|
|
121
|
-
}
|
|
110
|
+
(0, import_protocolRefusal.throwOnRefusal)(res, "removeThemeSource failed");
|
|
122
111
|
};
|
|
123
112
|
// Annotate the CommonJS export names for ESM import in node:
|
|
124
113
|
0 && (module.exports = {
|
package/dist/theme.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme polarity, mirrored from the immediately.run host window into\n * the sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n *\n * `HostTheme` is the RESOLVED POLARITY only. The full selection — which theme is\n * active and which of its modes — is {@link HostThemeSelection}.\n */\nexport type HostTheme = 'light' | 'dark';\n\n/**\n * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity\n * plus the active theme's registry key and resolved mode. Carried on the widened\n * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —\n * an app wants to know what is on screen).\n */\nexport interface HostThemeSelection {\n /** Resolved polarity — the same value the legacy `theme` field carried. */\n theme: HostTheme;\n /** The host-minted registry key of the active theme. */\n themeKey: string;\n /** The resolved active mode id of the active theme. */\n modeId: string;\n}\n\n/**\n * The selection assumed before the host reports. The platform default theme is\n * `immediately-run-default` (dark polarity first-paint, matching the shipped\n * provider default — HOST_THEMING_SPEC §3 build-time correction).\n */\nconst DEFAULT_SELECTION: HostThemeSelection = {\n theme: 'dark',\n themeKey: 'immediately-run-default',\n modeId: 'dark',\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The parse\n// reads ALL THREE fields so the full selection survives the transport; the\n// polarity-only surface derives from it.\nconst channel = createPushChannel<HostThemeSelection>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: DEFAULT_SELECTION,\n parse: (msg) => {\n if (msg.theme !== 'light' && msg.theme !== 'dark') return undefined;\n if (typeof msg.themeKey !== 'string' || typeof msg.modeId !== 'string') return undefined;\n return { theme: msg.theme, themeKey: msg.themeKey, modeId: msg.modeId };\n },\n});\n\n/**\n * Returns the current host theme polarity. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get().theme;\n\n/**\n * Subscribe to host theme polarity changes. The listener is invoked immediately\n * with the current polarity, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange((sel) => listener(sel.theme));\n\n/**\n * React hook returning the current host theme polarity, re-rendering when it\n * changes. The recommended way to implement an app's own `useTheme`: follow the\n * host, allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use().theme;\n\n/**\n * Returns the current full host theme selection — polarity, active theme key, and\n * resolved mode. Use {@link useHostThemeSelection} to react to changes.\n */\nexport const getHostThemeSelection = (): HostThemeSelection => channel.get();\n\n/**\n * Subscribe to full host theme selection changes. The listener is invoked\n * immediately with the current selection, then again on every change. Returns an\n * unsubscribe fn.\n */\nexport const onHostThemeSelectionChange = (listener: (selection: HostThemeSelection) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current full host theme selection. */\nexport const useHostThemeSelection = (): HostThemeSelection => channel.use();\n\n/**\n * One entry of the theme catalogue: a selectable theme and its modes. The\n * catalogue is projected per grant — the baseline `theme:read` projection carries\n * NO source identities (no repo coordinates, no spaceIds), and labels are bounded.\n */\nexport interface ThemeCatalogEntry {\n themeKey: string;\n label: string;\n modes: { id: string; polarity: 'light' | 'dark' }[];\n}\n\n/**\n * The loaded-theme catalogue (HOST_THEMING_SPEC §9.2): every selectable theme, so\n * a theme-aware app can render a picker and match chrome. Pushed on\n * `theme-catalog` / polled with `request-theme-catalog`.\n */\nexport interface ThemeCatalog {\n themes: ThemeCatalogEntry[];\n}\n\nconst DEFAULT_CATALOG: ThemeCatalog = { themes: [] };\n\nconst catalogChannel = createPushChannel<ThemeCatalog>({\n pushType: THEME_CATALOG,\n requestType: REQUEST_THEME_CATALOG,\n initial: DEFAULT_CATALOG,\n parse: (msg) => {\n const themes = msg.themes;\n if (!Array.isArray(themes)) return undefined;\n const out: ThemeCatalogEntry[] = [];\n for (const t of themes as unknown[]) {\n if (!t || typeof t !== 'object') return undefined;\n const entry = t as { themeKey?: unknown; label?: unknown; modes?: unknown };\n if (typeof entry.themeKey !== 'string' || typeof entry.label !== 'string' || !Array.isArray(entry.modes)) {\n return undefined;\n }\n const modes: ThemeCatalogEntry['modes'] = [];\n for (const m of entry.modes) {\n if (!m || typeof m !== 'object') return undefined;\n const mode = m as { id?: unknown; polarity?: unknown };\n if (typeof mode.id !== 'string' || (mode.polarity !== 'light' && mode.polarity !== 'dark')) {\n return undefined;\n }\n modes.push({ id: mode.id, polarity: mode.polarity });\n }\n out.push({ themeKey: entry.themeKey, label: entry.label, modes });\n }\n return { themes: out };\n },\n});\n\n/**\n * Returns the current theme catalogue (themes + their modes). Use\n * {@link useThemeCatalog} to react to changes.\n */\nexport const getThemeCatalog = (): ThemeCatalog => catalogChannel.get();\n\n/**\n * Subscribe to theme catalogue changes. The listener is invoked immediately with\n * the current catalogue, then again on every change. Returns an unsubscribe fn.\n */\nexport const onThemeCatalogChange = (listener: (catalog: ThemeCatalog) => void): (() => void) =>\n catalogChannel.onChange(listener);\n\n/** React hook returning the current theme catalogue. */\nexport const useThemeCatalog = (): ThemeCatalog => catalogChannel.use();\n\n/**\n * A location the open-bundle picker returned — a repo or a space, with a\n * confined in-bundle path (OPEN_BUNDLE_SPEC §2). Carried to the host's\n * `theme:sources` `add-source` verb.\n */\nexport type ThemeBundleLocation =\n | { kind: 'repo'; repo: string; ref?: string; path: string }\n | { kind: 'space'; spaceId: string; path: string };\n\n/**\n * The canonical `theme:set` params (HOST_THEMING_SPEC §9.3). `theme` is the\n * registry key of the theme to select (or the legacy `'light' | 'dark'` polarity —\n * the host disambiguates by the reserved-id rule: legacy iff the value is\n * light/dark AND `mode` is absent). `mode` is one of that theme's modes or\n * `'system'`.\n */\nexport interface SetHostThemeSelectionParams {\n theme: string;\n mode?: string;\n}\n\n/** The one `set` call site, so the wire shape is fingerprint-stable. */\nconst setTheme = async (params: SetHostThemeSelectionParams): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [params])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'setHostTheme failed') as Error & {\n code?: string;\n };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n};\n\n/**\n * Set the host theme selection — the ELEVATED `theme:set` action\n * (HOST_THEMING_SPEC §9.3). `theme` is the registry key of the theme to select,\n * `mode` is one of that theme's modes or `'system'`. The host applies it and\n * re-pushes the new selection to every `theme:read` iframe, so your own\n * {@link useHostThemeSelection} confirms the change (the loop closes with no\n * special case). Only a grant holding `theme:set` (e.g. the theme-toggle system\n * app) may call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims.\n */\nexport const setHostThemeSelection = async (selection: { theme: string; mode: string }): Promise<void> => {\n await setTheme(selection);\n};\n\n/**\n * Set the host UI theme polarity — the LEGACY form of `theme:set` (§9.3). The host\n * applies that polarity to the CURRENT theme (never resets to the default), then\n * re-pushes. Keep this alias for old-SDK callers; new code should prefer\n * {@link setHostThemeSelection}.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n await setTheme({ theme });\n};\n\n/**\n * Add a theme source — the ELEVATED `theme:sources` `add-source` verb\n * (HOST_THEMING_SPEC §9.3). `location` must be a location the host journal saw a\n * RECENT open-bundle invocation OF THIS APP return (the picker-provenance rule —\n * \"the pick is the consent\", machine-checked); anything else is rejected with a\n * readable reason. The host fetches, gates, and registers the theme before\n * returning, so a rejected pick surfaces inline in the switcher. Only a grant\n * holding `theme:sources` (the theme switcher) may call this.\n */\nexport const addThemeSource = async (location: ThemeBundleLocation): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'add-source', [{ location }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'addThemeSource failed') as Error & {\n code?: string;\n };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n};\n\n/**\n * Remove a theme source — the `theme:sources` `remove-source` verb (§9.3). If the\n * removed theme is the current selection, the host falls back to the default theme\n * (keeping the mode selection where it exists). The default theme is never\n * removable. Only a grant holding `theme:sources` may call this.\n */\nexport const removeThemeSource = async (themeKey: string): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'remove-source', [{ themeKey }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'removeThemeSource failed') as Error & {\n code?: string;\n };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAkC;AAClC,0BAAgC;AAChC,sBAA2F;AAC3F,6BAAwB;AAoCxB,MAAM,oBAAwC;AAAA,EAC5C,OAAO;AAAA,EACP,UAAU;AAAA,EACV,QAAQ;AACV;AAMA,MAAM,cAAU,sCAAsC;AAAA,EACpD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,IAAI,UAAU,WAAW,IAAI,UAAU,O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,KAAK,WAAW,0BAA0B;AAGhE,QAAI,QAAQ,OAAO,UAAU,MAAM,IAAI,OAAO,WAAc;AAC5D,UAAM;AAAA,EACR;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme polarity, mirrored from the immediately.run host window into\n * the sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n *\n * `HostTheme` is the RESOLVED POLARITY only. The full selection — which theme is\n * active and which of its modes — is {@link HostThemeSelection}.\n */\nexport type HostTheme = 'light' | 'dark';\n\n/**\n * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity\n * plus the active theme's registry key and resolved mode. Carried on the widened\n * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —\n * an app wants to know what is on screen).\n */\nexport interface HostThemeSelection {\n /** Resolved polarity — the same value the legacy `theme` field carried. */\n theme: HostTheme;\n /** The host-minted registry key of the active theme. */\n themeKey: string;\n /** The resolved active mode id of the active theme. */\n modeId: string;\n}\n\n/**\n * The selection assumed before the host reports. The platform default theme is\n * `immediately-run-default` (dark polarity first-paint, matching the shipped\n * provider default — HOST_THEMING_SPEC §3 build-time correction).\n */\nconst DEFAULT_SELECTION: HostThemeSelection = {\n theme: 'dark',\n themeKey: 'immediately-run-default',\n modeId: 'dark',\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The parse\n// reads ALL THREE fields so the full selection survives the transport; the\n// polarity-only surface derives from it.\nconst channel = createPushChannel<HostThemeSelection>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: DEFAULT_SELECTION,\n parse: (msg) => {\n if (msg.theme !== 'light' && msg.theme !== 'dark') return undefined;\n if (typeof msg.themeKey !== 'string' || typeof msg.modeId !== 'string') return undefined;\n return { theme: msg.theme, themeKey: msg.themeKey, modeId: msg.modeId };\n },\n});\n\n/**\n * Returns the current host theme polarity. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get().theme;\n\n/**\n * Subscribe to host theme polarity changes. The listener is invoked immediately\n * with the current polarity, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange((sel) => listener(sel.theme));\n\n/**\n * React hook returning the current host theme polarity, re-rendering when it\n * changes. The recommended way to implement an app's own `useTheme`: follow the\n * host, allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use().theme;\n\n/**\n * Returns the current full host theme selection — polarity, active theme key, and\n * resolved mode. Use {@link useHostThemeSelection} to react to changes.\n */\nexport const getHostThemeSelection = (): HostThemeSelection => channel.get();\n\n/**\n * Subscribe to full host theme selection changes. The listener is invoked\n * immediately with the current selection, then again on every change. Returns an\n * unsubscribe fn.\n */\nexport const onHostThemeSelectionChange = (listener: (selection: HostThemeSelection) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current full host theme selection. */\nexport const useHostThemeSelection = (): HostThemeSelection => channel.use();\n\n/**\n * One entry of the theme catalogue: a selectable theme and its modes. The\n * catalogue is projected per grant — the baseline `theme:read` projection carries\n * NO source identities (no repo coordinates, no spaceIds), and labels are bounded.\n */\nexport interface ThemeCatalogEntry {\n themeKey: string;\n label: string;\n modes: { id: string; polarity: 'light' | 'dark' }[];\n}\n\n/**\n * The loaded-theme catalogue (HOST_THEMING_SPEC §9.2): every selectable theme, so\n * a theme-aware app can render a picker and match chrome. Pushed on\n * `theme-catalog` / polled with `request-theme-catalog`.\n */\nexport interface ThemeCatalog {\n themes: ThemeCatalogEntry[];\n}\n\nconst DEFAULT_CATALOG: ThemeCatalog = { themes: [] };\n\nconst catalogChannel = createPushChannel<ThemeCatalog>({\n pushType: THEME_CATALOG,\n requestType: REQUEST_THEME_CATALOG,\n initial: DEFAULT_CATALOG,\n parse: (msg) => {\n const themes = msg.themes;\n if (!Array.isArray(themes)) return undefined;\n const out: ThemeCatalogEntry[] = [];\n for (const t of themes as unknown[]) {\n if (!t || typeof t !== 'object') return undefined;\n const entry = t as { themeKey?: unknown; label?: unknown; modes?: unknown };\n if (typeof entry.themeKey !== 'string' || typeof entry.label !== 'string' || !Array.isArray(entry.modes)) {\n return undefined;\n }\n const modes: ThemeCatalogEntry['modes'] = [];\n for (const m of entry.modes) {\n if (!m || typeof m !== 'object') return undefined;\n const mode = m as { id?: unknown; polarity?: unknown };\n if (typeof mode.id !== 'string' || (mode.polarity !== 'light' && mode.polarity !== 'dark')) {\n return undefined;\n }\n modes.push({ id: mode.id, polarity: mode.polarity });\n }\n out.push({ themeKey: entry.themeKey, label: entry.label, modes });\n }\n return { themes: out };\n },\n});\n\n/**\n * Returns the current theme catalogue (themes + their modes). Use\n * {@link useThemeCatalog} to react to changes.\n */\nexport const getThemeCatalog = (): ThemeCatalog => catalogChannel.get();\n\n/**\n * Subscribe to theme catalogue changes. The listener is invoked immediately with\n * the current catalogue, then again on every change. Returns an unsubscribe fn.\n */\nexport const onThemeCatalogChange = (listener: (catalog: ThemeCatalog) => void): (() => void) =>\n catalogChannel.onChange(listener);\n\n/** React hook returning the current theme catalogue. */\nexport const useThemeCatalog = (): ThemeCatalog => catalogChannel.use();\n\n/**\n * A location the open-bundle picker returned — a repo or a space, with a\n * confined in-bundle path (OPEN_BUNDLE_SPEC §2). Carried to the host's\n * `theme:sources` `add-source` verb.\n */\nexport type ThemeBundleLocation =\n | { kind: 'repo'; repo: string; ref?: string; path: string }\n | { kind: 'space'; spaceId: string; path: string };\n\n/**\n * The canonical `theme:set` params (HOST_THEMING_SPEC §9.3). `theme` is the\n * registry key of the theme to select (or the legacy `'light' | 'dark'` polarity —\n * the host disambiguates by the reserved-id rule: legacy iff the value is\n * light/dark AND `mode` is absent). `mode` is one of that theme's modes or\n * `'system'`.\n */\nexport interface SetHostThemeSelectionParams {\n theme: string;\n mode?: string;\n}\n\n/** The one `set` call site, so the wire shape is fingerprint-stable. */\nconst setTheme = async (params: SetHostThemeSelectionParams): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [params])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'setHostTheme failed');\n};\n\n/**\n * Set the host theme selection — the ELEVATED `theme:set` action\n * (HOST_THEMING_SPEC §9.3). `theme` is the registry key of the theme to select,\n * `mode` is one of that theme's modes or `'system'`. The host applies it and\n * re-pushes the new selection to every `theme:read` iframe, so your own\n * {@link useHostThemeSelection} confirms the change (the loop closes with no\n * special case). Only a grant holding `theme:set` (e.g. the theme-toggle system\n * app) may call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims.\n */\nexport const setHostThemeSelection = async (selection: { theme: string; mode: string }): Promise<void> => {\n await setTheme(selection);\n};\n\n/**\n * Set the host UI theme polarity — the LEGACY form of `theme:set` (§9.3). The host\n * applies that polarity to the CURRENT theme (never resets to the default), then\n * re-pushes. Keep this alias for old-SDK callers; new code should prefer\n * {@link setHostThemeSelection}.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n await setTheme({ theme });\n};\n\n/**\n * Add a theme source — the ELEVATED `theme:sources` `add-source` verb\n * (HOST_THEMING_SPEC §9.3). `location` must be a location the host journal saw a\n * RECENT open-bundle invocation OF THIS APP return (the picker-provenance rule —\n * \"the pick is the consent\", machine-checked); anything else is rejected with a\n * readable reason. The host fetches, gates, and registers the theme before\n * returning, so a rejected pick surfaces inline in the switcher. Only a grant\n * holding `theme:sources` (the theme switcher) may call this.\n */\nexport const addThemeSource = async (location: ThemeBundleLocation): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'add-source', [{ location }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'addThemeSource failed');\n};\n\n/**\n * Remove a theme source — the `theme:sources` `remove-source` verb (§9.3). If the\n * removed theme is the current selection, the host falls back to the default theme\n * (keeping the mode selection where it exists). The default theme is never\n * removable. Only a grant holding `theme:sources` may call this.\n */\nexport const removeThemeSource = async (themeKey: string): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'remove-source', [{ themeKey }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'removeThemeSource failed');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAkC;AAClC,0BAAgC;AAChC,6BAA+B;AAC/B,sBAA2F;AAC3F,6BAAwB;AAoCxB,MAAM,oBAAwC;AAAA,EAC5C,OAAO;AAAA,EACP,UAAU;AAAA,EACV,QAAQ;AACV;AAMA,MAAM,cAAU,sCAAsC;AAAA,EACpD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,IAAI,UAAU,WAAW,IAAI,UAAU,OAAQ,QAAO;AAC1D,QAAI,OAAO,IAAI,aAAa,YAAY,OAAO,IAAI,WAAW,SAAU,QAAO;AAC/E,WAAO,EAAE,OAAO,IAAI,OAAO,UAAU,IAAI,UAAU,QAAQ,IAAI,OAAO;AAAA,EACxE;AACF,CAAC;AAMM,MAAM,eAAe,MAAiB,QAAQ,IAAI,EAAE;AAMpD,MAAM,oBAAoB,CAAC,aAChC,QAAQ,SAAS,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AAkB,MAAoB,eAAe,IAAI;AAwBtE,MAAM,WAAW,OAAO,WAAuD;AAC7E,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,8BAAc,GAAG,OAAO,CAAC,MAAM,CAAC;AAI3E,6CAAe,KAAK,qBAAqB;AAC3C;AAYO,MAAM,wBAAwB,OAAO,cAA8D;AACxG,QAAM,SAAS,SAAS;AAC1B;AAQO,MAAM,eAAe,OAAO,UAAoC;AACrE,QAAM,SAAS,EAAE,MAAM,CAAC;AAC1B;AAWO,MAAM,iBAAiB,OAAO,aAAiD;AACpF,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,8BAAc,GAAG,cAAc,CAAC,EAAE,SAAS,CAAC,CAAC;AAIxF,6CAAe,KAAK,uBAAuB;AAC7C;AAQO,MAAM,oBAAoB,OAAO,aAAoC;AAC1E,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,8BAAc,GAAG,iBAAiB,CAAC,EAAE,SAAS,CAAC,CAAC;AAI3F,6CAAe,KAAK,0BAA0B;AAChD;","names":[]}
|
package/dist/theme.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
2
|
import { createPushChannel } from "./pushChannel.js";
|
|
3
3
|
import { protocolRequest } from "./sandboxUtils.js";
|
|
4
|
+
import { throwOnRefusal } from "./protocolRefusal.js";
|
|
4
5
|
import { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from "./generated/protocol.js";
|
|
5
6
|
import { SCHEMES } from "./protocolSchemes.js";
|
|
6
7
|
const DEFAULT_SELECTION = {
|
|
@@ -58,11 +59,7 @@ const onThemeCatalogChange = (listener) => catalogChannel.onChange(listener);
|
|
|
58
59
|
const useThemeCatalog = () => catalogChannel.use();
|
|
59
60
|
const setTheme = async (params) => {
|
|
60
61
|
const res = await protocolRequest(SCHEMES[PROTOCOL_THEME], "set", [params]);
|
|
61
|
-
|
|
62
|
-
const err = new Error(res?.message ?? "setHostTheme failed");
|
|
63
|
-
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
|
64
|
-
throw err;
|
|
65
|
-
}
|
|
62
|
+
throwOnRefusal(res, "setHostTheme failed");
|
|
66
63
|
};
|
|
67
64
|
const setHostThemeSelection = async (selection) => {
|
|
68
65
|
await setTheme(selection);
|
|
@@ -72,19 +69,11 @@ const setHostTheme = async (theme) => {
|
|
|
72
69
|
};
|
|
73
70
|
const addThemeSource = async (location) => {
|
|
74
71
|
const res = await protocolRequest(SCHEMES[PROTOCOL_THEME], "add-source", [{ location }]);
|
|
75
|
-
|
|
76
|
-
const err = new Error(res?.message ?? "addThemeSource failed");
|
|
77
|
-
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
|
78
|
-
throw err;
|
|
79
|
-
}
|
|
72
|
+
throwOnRefusal(res, "addThemeSource failed");
|
|
80
73
|
};
|
|
81
74
|
const removeThemeSource = async (themeKey) => {
|
|
82
75
|
const res = await protocolRequest(SCHEMES[PROTOCOL_THEME], "remove-source", [{ themeKey }]);
|
|
83
|
-
|
|
84
|
-
const err = new Error(res?.message ?? "removeThemeSource failed");
|
|
85
|
-
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
|
86
|
-
throw err;
|
|
87
|
-
}
|
|
76
|
+
throwOnRefusal(res, "removeThemeSource failed");
|
|
88
77
|
};
|
|
89
78
|
export {
|
|
90
79
|
addThemeSource,
|
package/dist/theme.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme polarity, mirrored from the immediately.run host window into\n * the sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n *\n * `HostTheme` is the RESOLVED POLARITY only. The full selection — which theme is\n * active and which of its modes — is {@link HostThemeSelection}.\n */\nexport type HostTheme = 'light' | 'dark';\n\n/**\n * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity\n * plus the active theme's registry key and resolved mode. Carried on the widened\n * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —\n * an app wants to know what is on screen).\n */\nexport interface HostThemeSelection {\n /** Resolved polarity — the same value the legacy `theme` field carried. */\n theme: HostTheme;\n /** The host-minted registry key of the active theme. */\n themeKey: string;\n /** The resolved active mode id of the active theme. */\n modeId: string;\n}\n\n/**\n * The selection assumed before the host reports. The platform default theme is\n * `immediately-run-default` (dark polarity first-paint, matching the shipped\n * provider default — HOST_THEMING_SPEC §3 build-time correction).\n */\nconst DEFAULT_SELECTION: HostThemeSelection = {\n theme: 'dark',\n themeKey: 'immediately-run-default',\n modeId: 'dark',\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The parse\n// reads ALL THREE fields so the full selection survives the transport; the\n// polarity-only surface derives from it.\nconst channel = createPushChannel<HostThemeSelection>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: DEFAULT_SELECTION,\n parse: (msg) => {\n if (msg.theme !== 'light' && msg.theme !== 'dark') return undefined;\n if (typeof msg.themeKey !== 'string' || typeof msg.modeId !== 'string') return undefined;\n return { theme: msg.theme, themeKey: msg.themeKey, modeId: msg.modeId };\n },\n});\n\n/**\n * Returns the current host theme polarity. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get().theme;\n\n/**\n * Subscribe to host theme polarity changes. The listener is invoked immediately\n * with the current polarity, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange((sel) => listener(sel.theme));\n\n/**\n * React hook returning the current host theme polarity, re-rendering when it\n * changes. The recommended way to implement an app's own `useTheme`: follow the\n * host, allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use().theme;\n\n/**\n * Returns the current full host theme selection — polarity, active theme key, and\n * resolved mode. Use {@link useHostThemeSelection} to react to changes.\n */\nexport const getHostThemeSelection = (): HostThemeSelection => channel.get();\n\n/**\n * Subscribe to full host theme selection changes. The listener is invoked\n * immediately with the current selection, then again on every change. Returns an\n * unsubscribe fn.\n */\nexport const onHostThemeSelectionChange = (listener: (selection: HostThemeSelection) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current full host theme selection. */\nexport const useHostThemeSelection = (): HostThemeSelection => channel.use();\n\n/**\n * One entry of the theme catalogue: a selectable theme and its modes. The\n * catalogue is projected per grant — the baseline `theme:read` projection carries\n * NO source identities (no repo coordinates, no spaceIds), and labels are bounded.\n */\nexport interface ThemeCatalogEntry {\n themeKey: string;\n label: string;\n modes: { id: string; polarity: 'light' | 'dark' }[];\n}\n\n/**\n * The loaded-theme catalogue (HOST_THEMING_SPEC §9.2): every selectable theme, so\n * a theme-aware app can render a picker and match chrome. Pushed on\n * `theme-catalog` / polled with `request-theme-catalog`.\n */\nexport interface ThemeCatalog {\n themes: ThemeCatalogEntry[];\n}\n\nconst DEFAULT_CATALOG: ThemeCatalog = { themes: [] };\n\nconst catalogChannel = createPushChannel<ThemeCatalog>({\n pushType: THEME_CATALOG,\n requestType: REQUEST_THEME_CATALOG,\n initial: DEFAULT_CATALOG,\n parse: (msg) => {\n const themes = msg.themes;\n if (!Array.isArray(themes)) return undefined;\n const out: ThemeCatalogEntry[] = [];\n for (const t of themes as unknown[]) {\n if (!t || typeof t !== 'object') return undefined;\n const entry = t as { themeKey?: unknown; label?: unknown; modes?: unknown };\n if (typeof entry.themeKey !== 'string' || typeof entry.label !== 'string' || !Array.isArray(entry.modes)) {\n return undefined;\n }\n const modes: ThemeCatalogEntry['modes'] = [];\n for (const m of entry.modes) {\n if (!m || typeof m !== 'object') return undefined;\n const mode = m as { id?: unknown; polarity?: unknown };\n if (typeof mode.id !== 'string' || (mode.polarity !== 'light' && mode.polarity !== 'dark')) {\n return undefined;\n }\n modes.push({ id: mode.id, polarity: mode.polarity });\n }\n out.push({ themeKey: entry.themeKey, label: entry.label, modes });\n }\n return { themes: out };\n },\n});\n\n/**\n * Returns the current theme catalogue (themes + their modes). Use\n * {@link useThemeCatalog} to react to changes.\n */\nexport const getThemeCatalog = (): ThemeCatalog => catalogChannel.get();\n\n/**\n * Subscribe to theme catalogue changes. The listener is invoked immediately with\n * the current catalogue, then again on every change. Returns an unsubscribe fn.\n */\nexport const onThemeCatalogChange = (listener: (catalog: ThemeCatalog) => void): (() => void) =>\n catalogChannel.onChange(listener);\n\n/** React hook returning the current theme catalogue. */\nexport const useThemeCatalog = (): ThemeCatalog => catalogChannel.use();\n\n/**\n * A location the open-bundle picker returned — a repo or a space, with a\n * confined in-bundle path (OPEN_BUNDLE_SPEC §2). Carried to the host's\n * `theme:sources` `add-source` verb.\n */\nexport type ThemeBundleLocation =\n | { kind: 'repo'; repo: string; ref?: string; path: string }\n | { kind: 'space'; spaceId: string; path: string };\n\n/**\n * The canonical `theme:set` params (HOST_THEMING_SPEC §9.3). `theme` is the\n * registry key of the theme to select (or the legacy `'light' | 'dark'` polarity —\n * the host disambiguates by the reserved-id rule: legacy iff the value is\n * light/dark AND `mode` is absent). `mode` is one of that theme's modes or\n * `'system'`.\n */\nexport interface SetHostThemeSelectionParams {\n theme: string;\n mode?: string;\n}\n\n/** The one `set` call site, so the wire shape is fingerprint-stable. */\nconst setTheme = async (params: SetHostThemeSelectionParams): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [params])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'setHostTheme failed') as Error & {\n code?: string;\n };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n};\n\n/**\n * Set the host theme selection — the ELEVATED `theme:set` action\n * (HOST_THEMING_SPEC §9.3). `theme` is the registry key of the theme to select,\n * `mode` is one of that theme's modes or `'system'`. The host applies it and\n * re-pushes the new selection to every `theme:read` iframe, so your own\n * {@link useHostThemeSelection} confirms the change (the loop closes with no\n * special case). Only a grant holding `theme:set` (e.g. the theme-toggle system\n * app) may call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims.\n */\nexport const setHostThemeSelection = async (selection: { theme: string; mode: string }): Promise<void> => {\n await setTheme(selection);\n};\n\n/**\n * Set the host UI theme polarity — the LEGACY form of `theme:set` (§9.3). The host\n * applies that polarity to the CURRENT theme (never resets to the default), then\n * re-pushes. Keep this alias for old-SDK callers; new code should prefer\n * {@link setHostThemeSelection}.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n await setTheme({ theme });\n};\n\n/**\n * Add a theme source — the ELEVATED `theme:sources` `add-source` verb\n * (HOST_THEMING_SPEC §9.3). `location` must be a location the host journal saw a\n * RECENT open-bundle invocation OF THIS APP return (the picker-provenance rule —\n * \"the pick is the consent\", machine-checked); anything else is rejected with a\n * readable reason. The host fetches, gates, and registers the theme before\n * returning, so a rejected pick surfaces inline in the switcher. Only a grant\n * holding `theme:sources` (the theme switcher) may call this.\n */\nexport const addThemeSource = async (location: ThemeBundleLocation): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'add-source', [{ location }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'addThemeSource failed') as Error & {\n code?: string;\n };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n};\n\n/**\n * Remove a theme source — the `theme:sources` `remove-source` verb (§9.3). If the\n * removed theme is the current selection, the host falls back to the default theme\n * (keeping the mode selection where it exists). The default theme is never\n * removable. Only a grant holding `theme:sources` may call this.\n */\nexport const removeThemeSource = async (themeKey: string): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'remove-source', [{ themeKey }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'removeThemeSource failed') as Error & {\n code?: string;\n };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n};\n"],"mappings":";AAAA,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,gBAAgB,eAAe,uBAAuB,OAAO,qBAAqB;AAC3F,SAAS,eAAe;AAoCxB,MAAM,oBAAwC;AAAA,EAC5C,OAAO;AAAA,EACP,UAAU;AAAA,EACV,QAAQ;AACV;AAMA,MAAM,UAAU,kBAAsC;AAAA,EACpD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,IAAI,UAAU,WAAW,IAAI,UAAU,OAAQ,QAAO;AAC1D,QAAI,OAAO,IAAI,aAAa,YAAY,OAAO,IAAI,WAAW,SAAU,QAAO;AAC/E,WAAO,EAAE,OAAO,IAAI,OAAO,UAAU,IAAI,UAAU,QAAQ,IAAI,OAAO;AAAA,EACxE;AACF,CAAC;AAMM,MAAM,eAAe,MAAiB,QAAQ,IAAI,EAAE;AAMpD,MAAM,oBAAoB,CAAC,aAChC,QAAQ,SAAS,CAAC,QAAQ,SAAS,IAAI,KAAK,CAAC;AAOxC,MAAM,eAAe,MAAiB,QAAQ,IAAI,EAAE;AAMpD,MAAM,wBAAwB,MAA0B,QAAQ,IAAI;AAOpE,MAAM,6BAA6B,CAAC,aACzC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,wBAAwB,MAA0B,QAAQ,IAAI;AAsB3E,MAAM,kBAAgC,EAAE,QAAQ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,UAAU,MAAM,IAAI,OAAO,WAAc;AAC5D,UAAM;AAAA,EACR;AACF;AAYO,MAAM,wBAAwB,OAAO,cAA8D;AACxG,QAAM,SAAS,SAAS;AAC1B;AAQO,MAAM,eAAe,OAAO,UAAoC;AACrE,QAAM,SAAS,EAAE,MAAM,CAAC;AAC1B;AAWO,MAAM,iBAAiB,OAAO,aAAiD;AACpF,QAAM,MAAO,MAAM,gBAAgB,QAAQ,cAAc,GAAG,cAAc,CAAC,EAAE,SAAS,CAAC,CAAC;AAIxF,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,uBAAuB;AAG7D,QAAI,QAAQ,OAAO,UAAU,MAAM,IAAI,OAAO,WAAc;AAC5D,UAAM;AAAA,EACR;AACF;AAQO,MAAM,oBAAoB,OAAO,aAAoC;AAC1E,QAAM,MAAO,MAAM,gBAAgB,QAAQ,cAAc,GAAG,iBAAiB,CAAC,EAAE,SAAS,CAAC,CAAC;AAI3F,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,0BAA0B;AAGhE,QAAI,QAAQ,OAAO,UAAU,MAAM,IAAI,OAAO,WAAc;AAC5D,UAAM;AAAA,EACR;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme polarity, mirrored from the immediately.run host window into\n * the sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n *\n * `HostTheme` is the RESOLVED POLARITY only. The full selection — which theme is\n * active and which of its modes — is {@link HostThemeSelection}.\n */\nexport type HostTheme = 'light' | 'dark';\n\n/**\n * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity\n * plus the active theme's registry key and resolved mode. Carried on the widened\n * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —\n * an app wants to know what is on screen).\n */\nexport interface HostThemeSelection {\n /** Resolved polarity — the same value the legacy `theme` field carried. */\n theme: HostTheme;\n /** The host-minted registry key of the active theme. */\n themeKey: string;\n /** The resolved active mode id of the active theme. */\n modeId: string;\n}\n\n/**\n * The selection assumed before the host reports. The platform default theme is\n * `immediately-run-default` (dark polarity first-paint, matching the shipped\n * provider default — HOST_THEMING_SPEC §3 build-time correction).\n */\nconst DEFAULT_SELECTION: HostThemeSelection = {\n theme: 'dark',\n themeKey: 'immediately-run-default',\n modeId: 'dark',\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The parse\n// reads ALL THREE fields so the full selection survives the transport; the\n// polarity-only surface derives from it.\nconst channel = createPushChannel<HostThemeSelection>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: DEFAULT_SELECTION,\n parse: (msg) => {\n if (msg.theme !== 'light' && msg.theme !== 'dark') return undefined;\n if (typeof msg.themeKey !== 'string' || typeof msg.modeId !== 'string') return undefined;\n return { theme: msg.theme, themeKey: msg.themeKey, modeId: msg.modeId };\n },\n});\n\n/**\n * Returns the current host theme polarity. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get().theme;\n\n/**\n * Subscribe to host theme polarity changes. The listener is invoked immediately\n * with the current polarity, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange((sel) => listener(sel.theme));\n\n/**\n * React hook returning the current host theme polarity, re-rendering when it\n * changes. The recommended way to implement an app's own `useTheme`: follow the\n * host, allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use().theme;\n\n/**\n * Returns the current full host theme selection — polarity, active theme key, and\n * resolved mode. Use {@link useHostThemeSelection} to react to changes.\n */\nexport const getHostThemeSelection = (): HostThemeSelection => channel.get();\n\n/**\n * Subscribe to full host theme selection changes. The listener is invoked\n * immediately with the current selection, then again on every change. Returns an\n * unsubscribe fn.\n */\nexport const onHostThemeSelectionChange = (listener: (selection: HostThemeSelection) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current full host theme selection. */\nexport const useHostThemeSelection = (): HostThemeSelection => channel.use();\n\n/**\n * One entry of the theme catalogue: a selectable theme and its modes. The\n * catalogue is projected per grant — the baseline `theme:read` projection carries\n * NO source identities (no repo coordinates, no spaceIds), and labels are bounded.\n */\nexport interface ThemeCatalogEntry {\n themeKey: string;\n label: string;\n modes: { id: string; polarity: 'light' | 'dark' }[];\n}\n\n/**\n * The loaded-theme catalogue (HOST_THEMING_SPEC §9.2): every selectable theme, so\n * a theme-aware app can render a picker and match chrome. Pushed on\n * `theme-catalog` / polled with `request-theme-catalog`.\n */\nexport interface ThemeCatalog {\n themes: ThemeCatalogEntry[];\n}\n\nconst DEFAULT_CATALOG: ThemeCatalog = { themes: [] };\n\nconst catalogChannel = createPushChannel<ThemeCatalog>({\n pushType: THEME_CATALOG,\n requestType: REQUEST_THEME_CATALOG,\n initial: DEFAULT_CATALOG,\n parse: (msg) => {\n const themes = msg.themes;\n if (!Array.isArray(themes)) return undefined;\n const out: ThemeCatalogEntry[] = [];\n for (const t of themes as unknown[]) {\n if (!t || typeof t !== 'object') return undefined;\n const entry = t as { themeKey?: unknown; label?: unknown; modes?: unknown };\n if (typeof entry.themeKey !== 'string' || typeof entry.label !== 'string' || !Array.isArray(entry.modes)) {\n return undefined;\n }\n const modes: ThemeCatalogEntry['modes'] = [];\n for (const m of entry.modes) {\n if (!m || typeof m !== 'object') return undefined;\n const mode = m as { id?: unknown; polarity?: unknown };\n if (typeof mode.id !== 'string' || (mode.polarity !== 'light' && mode.polarity !== 'dark')) {\n return undefined;\n }\n modes.push({ id: mode.id, polarity: mode.polarity });\n }\n out.push({ themeKey: entry.themeKey, label: entry.label, modes });\n }\n return { themes: out };\n },\n});\n\n/**\n * Returns the current theme catalogue (themes + their modes). Use\n * {@link useThemeCatalog} to react to changes.\n */\nexport const getThemeCatalog = (): ThemeCatalog => catalogChannel.get();\n\n/**\n * Subscribe to theme catalogue changes. The listener is invoked immediately with\n * the current catalogue, then again on every change. Returns an unsubscribe fn.\n */\nexport const onThemeCatalogChange = (listener: (catalog: ThemeCatalog) => void): (() => void) =>\n catalogChannel.onChange(listener);\n\n/** React hook returning the current theme catalogue. */\nexport const useThemeCatalog = (): ThemeCatalog => catalogChannel.use();\n\n/**\n * A location the open-bundle picker returned — a repo or a space, with a\n * confined in-bundle path (OPEN_BUNDLE_SPEC §2). Carried to the host's\n * `theme:sources` `add-source` verb.\n */\nexport type ThemeBundleLocation =\n | { kind: 'repo'; repo: string; ref?: string; path: string }\n | { kind: 'space'; spaceId: string; path: string };\n\n/**\n * The canonical `theme:set` params (HOST_THEMING_SPEC §9.3). `theme` is the\n * registry key of the theme to select (or the legacy `'light' | 'dark'` polarity —\n * the host disambiguates by the reserved-id rule: legacy iff the value is\n * light/dark AND `mode` is absent). `mode` is one of that theme's modes or\n * `'system'`.\n */\nexport interface SetHostThemeSelectionParams {\n theme: string;\n mode?: string;\n}\n\n/** The one `set` call site, so the wire shape is fingerprint-stable. */\nconst setTheme = async (params: SetHostThemeSelectionParams): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [params])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'setHostTheme failed');\n};\n\n/**\n * Set the host theme selection — the ELEVATED `theme:set` action\n * (HOST_THEMING_SPEC §9.3). `theme` is the registry key of the theme to select,\n * `mode` is one of that theme's modes or `'system'`. The host applies it and\n * re-pushes the new selection to every `theme:read` iframe, so your own\n * {@link useHostThemeSelection} confirms the change (the loop closes with no\n * special case). Only a grant holding `theme:set` (e.g. the theme-toggle system\n * app) may call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims.\n */\nexport const setHostThemeSelection = async (selection: { theme: string; mode: string }): Promise<void> => {\n await setTheme(selection);\n};\n\n/**\n * Set the host UI theme polarity — the LEGACY form of `theme:set` (§9.3). The host\n * applies that polarity to the CURRENT theme (never resets to the default), then\n * re-pushes. Keep this alias for old-SDK callers; new code should prefer\n * {@link setHostThemeSelection}.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n await setTheme({ theme });\n};\n\n/**\n * Add a theme source — the ELEVATED `theme:sources` `add-source` verb\n * (HOST_THEMING_SPEC §9.3). `location` must be a location the host journal saw a\n * RECENT open-bundle invocation OF THIS APP return (the picker-provenance rule —\n * \"the pick is the consent\", machine-checked); anything else is rejected with a\n * readable reason. The host fetches, gates, and registers the theme before\n * returning, so a rejected pick surfaces inline in the switcher. Only a grant\n * holding `theme:sources` (the theme switcher) may call this.\n */\nexport const addThemeSource = async (location: ThemeBundleLocation): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'add-source', [{ location }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'addThemeSource failed');\n};\n\n/**\n * Remove a theme source — the `theme:sources` `remove-source` verb (§9.3). If the\n * removed theme is the current selection, the host falls back to the default theme\n * (keeping the mode selection where it exists). The default theme is never\n * removable. Only a grant holding `theme:sources` may call this.\n */\nexport const removeThemeSource = async (themeKey: string): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'remove-source', [{ themeKey }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'removeThemeSource failed');\n};\n"],"mappings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3F,iBAAe,KAAK,0BAA0B;AAChD;","names":[]}
|
package/dist/vcs.cjs
CHANGED
|
@@ -33,6 +33,21 @@ var import_protocol = require("./generated/protocol");
|
|
|
33
33
|
var import_protocolSchemes = require("./protocolSchemes");
|
|
34
34
|
const EMPTY = { changes: [], branch: null, prs: [], diffLoading: false };
|
|
35
35
|
const isChangeArray = (v) => Array.isArray(v) && v.every((c) => !!c && typeof c.path === "string" && typeof c.status === "string");
|
|
36
|
+
const parseAgentSession = (v) => {
|
|
37
|
+
if (v === void 0 || v === null) return void 0;
|
|
38
|
+
if (typeof v !== "object") return void 0;
|
|
39
|
+
const s = v;
|
|
40
|
+
if (typeof s.repo !== "string" || typeof s.conversationId !== "string" || typeof s.messageCount !== "number" || !Number.isFinite(s.messageCount) || typeof s.running !== "boolean" || s.updatedAt !== void 0 && (typeof s.updatedAt !== "number" || !Number.isFinite(s.updatedAt))) {
|
|
41
|
+
return void 0;
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
repo: s.repo,
|
|
45
|
+
conversationId: s.conversationId,
|
|
46
|
+
messageCount: s.messageCount,
|
|
47
|
+
running: s.running,
|
|
48
|
+
...s.updatedAt !== void 0 ? { updatedAt: s.updatedAt } : {}
|
|
49
|
+
};
|
|
50
|
+
};
|
|
36
51
|
const channel = (0, import_pushChannel.createPushChannel)({
|
|
37
52
|
pushType: import_protocol.VCS_STATE,
|
|
38
53
|
requestType: import_protocol.REQUEST_VCS_STATE,
|
|
@@ -41,11 +56,13 @@ const channel = (0, import_pushChannel.createPushChannel)({
|
|
|
41
56
|
if (!isChangeArray(msg.changes)) return void 0;
|
|
42
57
|
const branch = msg.branch && typeof msg.branch === "object" ? msg.branch : null;
|
|
43
58
|
const prs = Array.isArray(msg.prs) ? msg.prs : [];
|
|
59
|
+
const agentSession = parseAgentSession(msg.agentSession);
|
|
44
60
|
return {
|
|
45
61
|
changes: msg.changes,
|
|
46
62
|
branch,
|
|
47
63
|
prs,
|
|
48
|
-
diffLoading: msg.diffLoading === true
|
|
64
|
+
diffLoading: msg.diffLoading === true,
|
|
65
|
+
...agentSession ? { agentSession } : {}
|
|
49
66
|
};
|
|
50
67
|
}
|
|
51
68
|
});
|
package/dist/vcs.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vcs.ts"],"sourcesContent":["// The `vcs:read` / `vcs:reset` source-control surface — app-facing wrappers\n// (UI_AS_APPS_SPEC §5.3 Recipe A read channel + §8.4 Recipe B actions;\n// migrate-sidebars-to-apps Phase 05; roadmap R3-52).\n//\n// A first-party contribute panel (the `panel.contribute` app, Phase 06) reads the\n// live source-control state the native `SourceControlPanel` shows — the working-tree\n// diff summary, the branch lineage, and the open-PR list — and can trigger a\n// refresh/reset. The host derives all of it from authenticated GitHub calls +\n// the COW layers; NONE of the underlying `DiffResult` / `FileSystem` / OAuth token\n// ever crosses the boundary (§8.10) — the wire carries only the plain-JSON\n// {@link VcsState} the host projects.\n//\n// Read side: a Recipe-A push channel, the same get/onChange/use trio as\n// `editorContext` / `diagnostics`. Inert until the host wires the channel\n// (site-main `channelBridge`); an app without `vcs:read` simply sees the empty\n// initial. Action side: `protocol-vcs` requests gated host-side — `refreshDiff` /\n// `refreshPRs` by `vcs:read`, `resetWorkingTree` by first-party-only `vcs:reset`.\nimport { createPushChannel } from './pushChannel';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_VCS, REQUEST_VCS_STATE, VCS_STATE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** One changed path in the working tree (vs. the loaded ref). `status` mirrors the\n * host `DiffResult` change kinds; `path` is repo-relative. Contents are NOT\n * carried — the native panel showed path + status, and a per-file content diff is\n * a deferred follow-up (plan step 6). */\nexport interface VcsChange {\n path: string;\n status: 'created' | 'modified' | 'deleted';\n}\n\n/** The branch the working tree sits on and the upstream it diverged from\n * (host `BranchInfo`, §15.1). `null` until the user is on a immediately.run-created\n * branch. `upstreamPushable` is `null` while push access is still being probed. */\nexport interface VcsBranch {\n name: string;\n parentRepo: string;\n parentRef: string;\n parentCommitSha: string;\n upstreamPushable: boolean | null;\n}\n\n/** One pull request open from the current branch (host `BranchPR`). */\nexport interface VcsPR {\n number: number;\n url: string;\n title: string;\n state: 'open' | 'closed' | 'merged';\n draft: boolean;\n}\n\n/** The whole source-control snapshot the host projects to a `vcs:read` frame.\n * Plain JSON — never a `DiffResult` / `FileSystem` / `Journal`. */\nexport interface VcsState {\n changes: VcsChange[];\n branch: VcsBranch | null;\n prs: VcsPR[];\n /** True while the host is recomputing the diff — the panel shows a spinner\n * without a separate request (plan gotcha). */\n diffLoading: boolean;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `vcs:read`): an empty, branch-less snapshot. */\nconst EMPTY: VcsState = { changes: [], branch: null, prs: [], diffLoading: false };\n\nconst isChangeArray = (v: unknown): v is VcsChange[] =>\n Array.isArray(v) &&\n v.every((c) => !!c && typeof (c as VcsChange).path === 'string' && typeof (c as VcsChange).status === 'string');\n\nconst channel = createPushChannel<VcsState>({\n pushType: VCS_STATE,\n requestType: REQUEST_VCS_STATE,\n initial: EMPTY,\n parse: (msg) => {\n // Require a well-formed `changes` array; tolerate an absent branch/prs. A\n // malformed push is ignored (returns undefined) so the last good state stands.\n if (!isChangeArray(msg.changes)) return undefined;\n const branch = msg.branch && typeof msg.branch === 'object' ? (msg.branch as VcsBranch) : null;\n const prs = Array.isArray(msg.prs) ? (msg.prs as VcsPR[]) : [];\n return {\n changes: msg.changes,\n branch,\n prs,\n diffLoading: msg.diffLoading === true,\n };\n },\n});\n\n/** One-off read of the current source-control state. Returns the empty snapshot\n * until the host answers (or if the app lacks `vcs:read`). Use\n * {@link onVcsStateChange} / {@link useVcsState} to react to live updates. */\nexport const getVcsState = (): VcsState => channel.get();\n\n/** Subscribe to source-control changes. Invoked immediately with the current\n * value, then on every host push (diff refresh, PR poll, branch change). Returns\n * an unsubscribe. */\nexport const onVcsStateChange = (listener: (state: VcsState) => void): (() => void) => channel.onChange(listener);\n\n/** React hook: the current source-control state, re-rendering on every change. */\nexport const useVcsState = (): VcsState => channel.use();\n\n// ---------------------------------------------------------------------------\n// Actions (Recipe B, §8.4). The app NAMES an intent and the HOST performs it —\n// the COW/journal stays in the kernel (§2/§4). `refreshDiff`/`refreshPRs` only\n// cause a host-side recompute + a fresh push (gated `vcs:read`, no new authority);\n// `resetWorkingTree` DISCARDS the user's unsaved work, gated by the first-party-only\n// `vcs:reset` — a fork can never hold it. The arm-then-confirm UX stays in the app;\n// the authority is gated host-side (§8.9), and the host requires `confirm:true` as\n// belt-and-braces (T22).\n// ---------------------------------------------------------------------------\n\n/** An error from a `vcs` action, carrying a machine-readable `.code`.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface\n * documents the `.code` VALUES the host sends; it was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test.\n */\nexport interface VcsActionError extends Error {\n code:\n | 'forbidden' // the frame lacks the required capability (`vcs:read` / `vcs:reset`)\n | 'invalid-params' // reset called without `confirm: true`\n | 'no-target' // there is no host contribute session (not in edit mode)\n | 'unknown';\n}\n\ntype VcsResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\nconst vcsRequest = async (method: string, arg: Record<string, unknown> = {}): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_VCS], method, [arg])) as VcsResult;\n throwOnRefusal(res, `vcs ${method} failed`);\n};\n\n/** Ask the host to recompute the working-tree diff and push a fresh {@link VcsState}.\n * Gated `vcs:read`. Rejects with a {@link VcsActionError} (`.code`). */\nexport const refreshDiff = (): Promise<void> => vcsRequest('refreshDiff');\n\n/** Ask the host to re-poll the open PRs and push a fresh {@link VcsState}. Gated\n * `vcs:read`. Rejects with a {@link VcsActionError} (`.code`). */\nexport const refreshPRs = (): Promise<void> => vcsRequest('refreshPRs');\n\n/** Ask the host to DISCARD the working tree (COW writable wipe + journal clear) —\n * irreversible. First-party-only (`vcs:reset`); a fork/preview is refused at the\n * gate. Requires `confirm: true` (host belt-and-braces). Rejects with a\n * {@link VcsActionError} (`.code`). */\nexport const resetWorkingTree = (): Promise<void> => vcsRequest('reset', { confirm: true });\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,yBAAkC;AAClC,6BAA+B;AAC/B,0BAAgC;AAChC,sBAA2D;AAC3D,6BAAwB;AA4CxB,MAAM,QAAkB,EAAE,SAAS,CAAC,GAAG,QAAQ,MAAM,KAAK,CAAC,GAAG,aAAa,MAAM;AAEjF,MAAM,gBAAgB,CAAC,MACrB,MAAM,QAAQ,CAAC,KACf,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,OAAQ,EAAgB,SAAS,YAAY,OAAQ,EAAgB,WAAW,QAAQ;AAEhH,MAAM,cAAU,sCAA4B;AAAA,EAC1C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AAGd,QAAI,CAAC,cAAc,IAAI,OAAO,EAAG,QAAO;AACxC,UAAM,SAAS,IAAI,UAAU,OAAO,IAAI,WAAW,WAAY,IAAI,SAAuB;AAC1F,UAAM,MAAM,MAAM,QAAQ,IAAI,GAAG,IAAK,IAAI,MAAkB,CAAC;AAC7D,WAAO;AAAA,MACL,SAAS,IAAI;AAAA,MACb;AAAA,MACA;AAAA,MACA,aAAa,IAAI,gBAAgB;AAAA,IACnC;AAAA,EACF;AACF,CAAC;AAKM,MAAM,cAAc,MAAgB,QAAQ,IAAI;AAKhD,MAAM,mBAAmB,CAAC,aAAsD,QAAQ,SAAS,QAAQ;AAGzG,MAAM,cAAc,MAAgB,QAAQ,IAAI;AA8BvD,MAAM,aAAa,OAAO,QAAgB,MAA+B,CAAC,MAAqB;AAC7F,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,4BAAY,GAAG,QAAQ,CAAC,GAAG,CAAC;AACvE,6CAAe,KAAK,OAAO,MAAM,SAAS;AAC5C;AAIO,MAAM,cAAc,MAAqB,WAAW,aAAa;AAIjE,MAAM,aAAa,MAAqB,WAAW,YAAY;AAM/D,MAAM,mBAAmB,MAAqB,WAAW,SAAS,EAAE,SAAS,KAAK,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/vcs.ts"],"sourcesContent":["// The `vcs:read` / `vcs:reset` source-control surface — app-facing wrappers\n// (UI_AS_APPS_SPEC §5.3 Recipe A read channel + §8.4 Recipe B actions;\n// migrate-sidebars-to-apps Phase 05; roadmap R3-52).\n//\n// A first-party contribute panel (the `panel.contribute` app, Phase 06) reads the\n// live source-control state the native `SourceControlPanel` shows — the working-tree\n// diff summary, the branch lineage, and the open-PR list — and can trigger a\n// refresh/reset. The host derives all of it from authenticated GitHub calls +\n// the COW layers; NONE of the underlying `DiffResult` / `FileSystem` / OAuth token\n// ever crosses the boundary (§8.10) — the wire carries only the plain-JSON\n// {@link VcsState} the host projects.\n//\n// Read side: a Recipe-A push channel, the same get/onChange/use trio as\n// `editorContext` / `diagnostics`. Inert until the host wires the channel\n// (site-main `channelBridge`); an app without `vcs:read` simply sees the empty\n// initial. Action side: `protocol-vcs` requests gated host-side — `refreshDiff` /\n// `refreshPRs` by `vcs:read`, `resetWorkingTree` by first-party-only `vcs:reset`.\nimport { createPushChannel } from './pushChannel';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_VCS, REQUEST_VCS_STATE, VCS_STATE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** One changed path in the working tree (vs. the loaded ref). `status` mirrors the\n * host `DiffResult` change kinds; `path` is repo-relative. Contents are NOT\n * carried — the native panel showed path + status, and a per-file content diff is\n * a deferred follow-up (plan step 6). */\nexport interface VcsChange {\n path: string;\n status: 'created' | 'modified' | 'deleted';\n}\n\n/** The branch the working tree sits on and the upstream it diverged from\n * (host `BranchInfo`, §15.1). `null` until the user is on a immediately.run-created\n * branch. `upstreamPushable` is `null` while push access is still being probed. */\nexport interface VcsBranch {\n name: string;\n parentRepo: string;\n parentRef: string;\n parentCommitSha: string;\n upstreamPushable: boolean | null;\n}\n\n/** One pull request open from the current branch (host `BranchPR`). */\nexport interface VcsPR {\n number: number;\n url: string;\n title: string;\n state: 'open' | 'closed' | 'merged';\n draft: boolean;\n}\n\n/** The gate facts the host projects about an active agent session on the\n * target repo (CONTRIBUTE_TRANSCRIPT_SPEC §3/§4, R3-632/R3-659): enough for a\n * contribute app to render the \"Commit session transcript\" checkbox — never\n * transcript bytes, a title, or message content. Absent (undefined) unless a\n * qualifying session exists — R-CT-3: no session ⇒ no fact, not a disabled\n * rendering of one. */\nexport interface VcsAgentSession {\n repo: string;\n conversationId: string;\n messageCount: number;\n updatedAt?: number | undefined;\n running: boolean;\n}\n\n/** The whole source-control snapshot the host projects to a `vcs:read` frame.\n * Plain JSON — never a `DiffResult` / `FileSystem` / `Journal`. */\nexport interface VcsState {\n changes: VcsChange[];\n branch: VcsBranch | null;\n prs: VcsPR[];\n /** True while the host is recomputing the diff — the panel shows a spinner\n * without a separate request (plan gotcha). */\n diffLoading: boolean;\n /** See {@link VcsAgentSession}. Present only while a qualifying agent\n * session exists on the target repo. The explicit `| undefined` mirrors\n * the wire contract exactly (the wire-shape extractor reads union members\n * literally). */\n agentSession?: VcsAgentSession | null | undefined;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `vcs:read`): an empty, branch-less snapshot. */\nconst EMPTY: VcsState = { changes: [], branch: null, prs: [], diffLoading: false };\n\nconst isChangeArray = (v: unknown): v is VcsChange[] =>\n Array.isArray(v) &&\n v.every((c) => !!c && typeof (c as VcsChange).path === 'string' && typeof (c as VcsChange).status === 'string');\n\n// The agentSession fact is fail-closed for the transcript feature (R-CT-1): a\n// malformed one reads as NO session — dropped, never thrown into the vcs\n// channel, so a fault can never conjure a checkbox (and the rest of the\n// snapshot still lands).\nconst parseAgentSession = (v: unknown): VcsAgentSession | undefined => {\n if (v === undefined || v === null) return undefined;\n if (typeof v !== 'object') return undefined;\n const s = v as Record<string, unknown>;\n // Number.isFinite, not typeof: structured clone (the postMessage transport)\n // carries NaN/Infinity intact, and a non-finite count must not conjure the\n // fact — the producer's parser (site-main agentSessionState.ts) rejects the\n // same way.\n if (\n typeof s.repo !== 'string' ||\n typeof s.conversationId !== 'string' ||\n typeof s.messageCount !== 'number' ||\n !Number.isFinite(s.messageCount) ||\n typeof s.running !== 'boolean' ||\n (s.updatedAt !== undefined && (typeof s.updatedAt !== 'number' || !Number.isFinite(s.updatedAt)))\n ) {\n return undefined;\n }\n return {\n repo: s.repo,\n conversationId: s.conversationId,\n messageCount: s.messageCount,\n running: s.running,\n ...(s.updatedAt !== undefined ? { updatedAt: s.updatedAt } : {}),\n };\n};\n\nconst channel = createPushChannel<VcsState>({\n pushType: VCS_STATE,\n requestType: REQUEST_VCS_STATE,\n initial: EMPTY,\n parse: (msg) => {\n // Require a well-formed `changes` array; tolerate an absent branch/prs. A\n // malformed push is ignored (returns undefined) so the last good state stands.\n if (!isChangeArray(msg.changes)) return undefined;\n const branch = msg.branch && typeof msg.branch === 'object' ? (msg.branch as VcsBranch) : null;\n const prs = Array.isArray(msg.prs) ? (msg.prs as VcsPR[]) : [];\n const agentSession = parseAgentSession(msg.agentSession);\n return {\n changes: msg.changes,\n branch,\n prs,\n diffLoading: msg.diffLoading === true,\n ...(agentSession ? { agentSession } : {}),\n };\n },\n});\n\n/** One-off read of the current source-control state. Returns the empty snapshot\n * until the host answers (or if the app lacks `vcs:read`). Use\n * {@link onVcsStateChange} / {@link useVcsState} to react to live updates. */\nexport const getVcsState = (): VcsState => channel.get();\n\n/** Subscribe to source-control changes. Invoked immediately with the current\n * value, then on every host push (diff refresh, PR poll, branch change). Returns\n * an unsubscribe. */\nexport const onVcsStateChange = (listener: (state: VcsState) => void): (() => void) => channel.onChange(listener);\n\n/** React hook: the current source-control state, re-rendering on every change. */\nexport const useVcsState = (): VcsState => channel.use();\n\n// ---------------------------------------------------------------------------\n// Actions (Recipe B, §8.4). The app NAMES an intent and the HOST performs it —\n// the COW/journal stays in the kernel (§2/§4). `refreshDiff`/`refreshPRs` only\n// cause a host-side recompute + a fresh push (gated `vcs:read`, no new authority);\n// `resetWorkingTree` DISCARDS the user's unsaved work, gated by the first-party-only\n// `vcs:reset` — a fork can never hold it. The arm-then-confirm UX stays in the app;\n// the authority is gated host-side (§8.9), and the host requires `confirm:true` as\n// belt-and-braces (T22).\n// ---------------------------------------------------------------------------\n\n/** An error from a `vcs` action, carrying a machine-readable `.code`.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface\n * documents the `.code` VALUES the host sends. Nothing enforces the union at runtime —\n * `.code` is whatever string arrived — so treat an unlisted code as possible and\n * `instanceof Error` as the only reliable test.\n */\nexport interface VcsActionError extends Error {\n code:\n | 'forbidden' // the frame lacks the required capability (`vcs:read` / `vcs:reset`)\n | 'invalid-params' // reset called without `confirm: true`\n | 'no-target' // there is no host contribute session (not in edit mode)\n | 'unknown';\n}\n\ntype VcsResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\nconst vcsRequest = async (method: string, arg: Record<string, unknown> = {}): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_VCS], method, [arg])) as VcsResult;\n throwOnRefusal(res, `vcs ${method} failed`);\n};\n\n/** Ask the host to recompute the working-tree diff and push a fresh {@link VcsState}.\n * Gated `vcs:read`. Rejects with a {@link VcsActionError} (`.code`). */\nexport const refreshDiff = (): Promise<void> => vcsRequest('refreshDiff');\n\n/** Ask the host to re-poll the open PRs and push a fresh {@link VcsState}. Gated\n * `vcs:read`. Rejects with a {@link VcsActionError} (`.code`). */\nexport const refreshPRs = (): Promise<void> => vcsRequest('refreshPRs');\n\n/** Ask the host to DISCARD the working tree (COW writable wipe + journal clear) —\n * irreversible. First-party-only (`vcs:reset`); a fork/preview is refused at the\n * gate. Requires `confirm: true` (host belt-and-braces). Rejects with a\n * {@link VcsActionError} (`.code`). */\nexport const resetWorkingTree = (): Promise<void> => vcsRequest('reset', { confirm: true });\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,yBAAkC;AAClC,6BAA+B;AAC/B,0BAAgC;AAChC,sBAA2D;AAC3D,6BAAwB;AA+DxB,MAAM,QAAkB,EAAE,SAAS,CAAC,GAAG,QAAQ,MAAM,KAAK,CAAC,GAAG,aAAa,MAAM;AAEjF,MAAM,gBAAgB,CAAC,MACrB,MAAM,QAAQ,CAAC,KACf,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,OAAQ,EAAgB,SAAS,YAAY,OAAQ,EAAgB,WAAW,QAAQ;AAMhH,MAAM,oBAAoB,CAAC,MAA4C;AACrE,MAAI,MAAM,UAAa,MAAM,KAAM,QAAO;AAC1C,MAAI,OAAO,MAAM,SAAU,QAAO;AAClC,QAAM,IAAI;AAKV,MACE,OAAO,EAAE,SAAS,YAClB,OAAO,EAAE,mBAAmB,YAC5B,OAAO,EAAE,iBAAiB,YAC1B,CAAC,OAAO,SAAS,EAAE,YAAY,KAC/B,OAAO,EAAE,YAAY,aACpB,EAAE,cAAc,WAAc,OAAO,EAAE,cAAc,YAAY,CAAC,OAAO,SAAS,EAAE,SAAS,IAC9F;AACA,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,MAAM,EAAE;AAAA,IACR,gBAAgB,EAAE;AAAA,IAClB,cAAc,EAAE;AAAA,IAChB,SAAS,EAAE;AAAA,IACX,GAAI,EAAE,cAAc,SAAY,EAAE,WAAW,EAAE,UAAU,IAAI,CAAC;AAAA,EAChE;AACF;AAEA,MAAM,cAAU,sCAA4B;AAAA,EAC1C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AAGd,QAAI,CAAC,cAAc,IAAI,OAAO,EAAG,QAAO;AACxC,UAAM,SAAS,IAAI,UAAU,OAAO,IAAI,WAAW,WAAY,IAAI,SAAuB;AAC1F,UAAM,MAAM,MAAM,QAAQ,IAAI,GAAG,IAAK,IAAI,MAAkB,CAAC;AAC7D,UAAM,eAAe,kBAAkB,IAAI,YAAY;AACvD,WAAO;AAAA,MACL,SAAS,IAAI;AAAA,MACb;AAAA,MACA;AAAA,MACA,aAAa,IAAI,gBAAgB;AAAA,MACjC,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;AAAA,IACzC;AAAA,EACF;AACF,CAAC;AAKM,MAAM,cAAc,MAAgB,QAAQ,IAAI;AAKhD,MAAM,mBAAmB,CAAC,aAAsD,QAAQ,SAAS,QAAQ;AAGzG,MAAM,cAAc,MAAgB,QAAQ,IAAI;AA8BvD,MAAM,aAAa,OAAO,QAAgB,MAA+B,CAAC,MAAqB;AAC7F,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,4BAAY,GAAG,QAAQ,CAAC,GAAG,CAAC;AACvE,6CAAe,KAAK,OAAO,MAAM,SAAS;AAC5C;AAIO,MAAM,cAAc,MAAqB,WAAW,aAAa;AAIjE,MAAM,aAAa,MAAqB,WAAW,YAAY;AAM/D,MAAM,mBAAmB,MAAqB,WAAW,SAAS,EAAE,SAAS,KAAK,CAAC;","names":[]}
|
package/dist/vcs.d.cts
CHANGED
|
@@ -24,6 +24,19 @@ interface VcsPR {
|
|
|
24
24
|
state: 'open' | 'closed' | 'merged';
|
|
25
25
|
draft: boolean;
|
|
26
26
|
}
|
|
27
|
+
/** The gate facts the host projects about an active agent session on the
|
|
28
|
+
* target repo (CONTRIBUTE_TRANSCRIPT_SPEC §3/§4, R3-632/R3-659): enough for a
|
|
29
|
+
* contribute app to render the "Commit session transcript" checkbox — never
|
|
30
|
+
* transcript bytes, a title, or message content. Absent (undefined) unless a
|
|
31
|
+
* qualifying session exists — R-CT-3: no session ⇒ no fact, not a disabled
|
|
32
|
+
* rendering of one. */
|
|
33
|
+
interface VcsAgentSession {
|
|
34
|
+
repo: string;
|
|
35
|
+
conversationId: string;
|
|
36
|
+
messageCount: number;
|
|
37
|
+
updatedAt?: number | undefined;
|
|
38
|
+
running: boolean;
|
|
39
|
+
}
|
|
27
40
|
/** The whole source-control snapshot the host projects to a `vcs:read` frame.
|
|
28
41
|
* Plain JSON — never a `DiffResult` / `FileSystem` / `Journal`. */
|
|
29
42
|
interface VcsState {
|
|
@@ -33,6 +46,11 @@ interface VcsState {
|
|
|
33
46
|
/** True while the host is recomputing the diff — the panel shows a spinner
|
|
34
47
|
* without a separate request (plan gotcha). */
|
|
35
48
|
diffLoading: boolean;
|
|
49
|
+
/** See {@link VcsAgentSession}. Present only while a qualifying agent
|
|
50
|
+
* session exists on the target repo. The explicit `| undefined` mirrors
|
|
51
|
+
* the wire contract exactly (the wire-shape extractor reads union members
|
|
52
|
+
* literally). */
|
|
53
|
+
agentSession?: VcsAgentSession | null | undefined;
|
|
36
54
|
}
|
|
37
55
|
/** One-off read of the current source-control state. Returns the empty snapshot
|
|
38
56
|
* until the host answers (or if the app lacks `vcs:read`). Use
|
|
@@ -48,9 +66,9 @@ declare const useVcsState: () => VcsState;
|
|
|
48
66
|
*
|
|
49
67
|
* **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
|
|
50
68
|
* `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface
|
|
51
|
-
* documents the `.code` VALUES the host sends
|
|
52
|
-
*
|
|
53
|
-
* reliable test.
|
|
69
|
+
* documents the `.code` VALUES the host sends. Nothing enforces the union at runtime —
|
|
70
|
+
* `.code` is whatever string arrived — so treat an unlisted code as possible and
|
|
71
|
+
* `instanceof Error` as the only reliable test.
|
|
54
72
|
*/
|
|
55
73
|
interface VcsActionError extends Error {
|
|
56
74
|
code: 'forbidden' | 'invalid-params' | 'no-target' | 'unknown';
|
|
@@ -67,4 +85,4 @@ declare const refreshPRs: () => Promise<void>;
|
|
|
67
85
|
* {@link VcsActionError} (`.code`). */
|
|
68
86
|
declare const resetWorkingTree: () => Promise<void>;
|
|
69
87
|
|
|
70
|
-
export { type VcsActionError, type VcsBranch, type VcsChange, type VcsPR, type VcsState, getVcsState, onVcsStateChange, refreshDiff, refreshPRs, resetWorkingTree, useVcsState };
|
|
88
|
+
export { type VcsActionError, type VcsAgentSession, type VcsBranch, type VcsChange, type VcsPR, type VcsState, getVcsState, onVcsStateChange, refreshDiff, refreshPRs, resetWorkingTree, useVcsState };
|