@immediately-run/sdk 0.85.0 → 0.87.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/protocolRefusal.cjs.map +1 -1
- package/dist/protocolRefusal.d.cts +15 -21
- package/dist/protocolRefusal.d.ts +15 -21
- package/dist/protocolRefusal.js.map +1 -1
- package/dist/recents.cjs +2 -5
- package/dist/recents.cjs.map +1 -1
- package/dist/recents.js +2 -5
- package/dist/recents.js.map +1 -1
- package/dist/routing.cjs +2 -1
- package/dist/routing.cjs.map +1 -1
- package/dist/routing.d.cts +1 -0
- package/dist/routing.d.ts +1 -0
- package/dist/routing.js +2 -1
- package/dist/routing.js.map +1 -1
- package/dist/tasks.cjs +2 -5
- package/dist/tasks.cjs.map +1 -1
- package/dist/tasks.js +2 -5
- package/dist/tasks.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 +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. The count is:\n//\n// **eighteen CALL SITES across thirteen FILES** — `grep -n 'throwOnRefusal(' src/*.ts`,\n// minus the declaration here and minus `*.test.*`:\n//\n// dnd.ts · editor.ts · feed.ts · ipc.ts (×2) · mounts.ts (×3) · netFetch.ts ·\n// openBundle.ts · openExternal.ts · openRepository.ts · secrets.ts · spacesMode.ts · theme.ts (×3) ·\n// vcs.ts\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// Not folded, deliberately, and the reason is NOT that they are all unalike — that was the\n// previous excuse and it was false for three of them:\n//\n// · `catalog.ts`, `recents.ts`, `tasks.ts` are pure copies of the shape `ipc.ts` had\n// until R3-780 folded it — untyped `Error & { code?: string }`, `res?.code ??\n// 'unknown'`. (`recents.ts` casts `code` as required rather than optional; immaterial,\n// the cast erases.) They are foldable and nothing here argues otherwise;\n// · `feed.ts`, `netFetch.ts` and `theme.ts` (×3) read `res && 'code' in res`, which\n// THREW `TypeError: Cannot use 'in' operator` on a string reply — FOLDED in R3-817\n// (0.74.3), a behaviour change reviewed as its own item, exactly as this bullet\n// prescribed;\n// · `launch.ts` folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// So the remaining work is two items, not one, and they are not the same size.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL EIGHTEEN SITES\n// ---------------------------------------------------------------------------\n//\n// Measured: changing the guard to `r.ok !== false` compiles clean and leaves **ten of the\n// eighteen SITES** green — seven of the thirteen files: `dnd`, `editor`, `ipc`, `mounts`,\n// `secrets`, `spacesMode` and `vcs`. Every one of them stubs an explicit `{ ok: false }`,\n// so they pin \"throws on a refusal envelope\" and nothing about a malformed or absent\n// reply. The catchers: `openBundle`, `openExternal`, `openRepository`, the five R3-817 sites (whose\n// string-reply tests reject on a non-envelope — the mutation never throws), plus\n// `protocolRefusal.test.ts`. (Re-run 2026-09-30 on the post-fold tree: suites red —\n// feed, netFetch, theme, openExternal, openRepository, protocolRefusal; the seven\n// families green. `openBundle`, the eighteenth site, was added 2026-10-05 and re-run alone\n// under the same mutation: red.)\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and eighteen near-duplicate malformed\n// -reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Eighteen sites call this;\n * **sixteen** had an inline copy it replaced (`spacesMode.ts` was written against the\n * helper in R3-708 and replaced nothing). All sixteen tested for PRESENCE, in **three**\n * shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **seven** used the `in` operator — `openExternal`, `openRepository` (with the cast;\n * folded in R3-708) and `feed`, `netFetch`, `theme` ×3 (without it; folded in R3-817,\n * the TypeError fix disclosed above);\n * - **two** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc.ts`.\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply.\n *\n * ONE revision of this paragraph got that backwards, and this is the fourth attempt to\n * describe it accurately. The original text was right FOR ITS REFERENT — it named\n * `'code' in res` as a shape replaced, without saying which sites, and at the time the\n * sites it referred to were R3-708's four, two of which used that form. R3-780 then folded\n * five DIFFERENT files and inherited the sentence unchanged, so it became false in place\n * without anyone editing it. That silent shift is the likeliest reason the next revision\n * \"corrected\" it to say NO replaced site used it — which is false the other way:\n * `openExternal` and `openRepository` did.\n *\n * The mechanism is worth more than the correction, because it is repeatable. `'code' in\n * res` is **gone from `main`** since R3-817 (0.74.3) folded the last five — a reviewer who\n * greps `main` finds nothing, and this paragraph is the record of where it lived and why\n * it misread twice before. What a grep of `main` cannot show is that the\n * form was ALSO at two sites R3-708 folded. The tree that answers the question is the one\n * before the fold, `d4b07cc1^`. Read that before rewriting this paragraph again.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n *\n * R3-817 (0.74.3): the five remaining inline copies (`feed.ts`, `netFetch.ts`,\n * `theme.ts` ×3) folded onto this — removing a latent defect with them: their\n * `res && 'code' in res` guard threw `TypeError: Cannot use 'in' operator` on a\n * bare-STRING reply (a proxy error page, a relay), escaping past every `err.code`\n * branch an app wrote. This function reads `typeof r?.code === 'string'` and\n * cannot throw on any input; the TypeError path no longer exists.\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiLO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. After R3-816 folded the pure copies, the count is:\n//\n// **twenty CALL SITES across fifteen FILES** — `grep -n 'throwOnRefusal(' src/*.ts`, minus\n// the declaration here, minus `*.test.*`, and minus this census's own mention of the\n// pattern (the recipe's literal matches it):\n//\n// dnd.ts · editor.ts · feed.ts · ipc.ts (×2) · mounts.ts (×3) · netFetch.ts ·\n// openBundle.ts · openExternal.ts · openRepository.ts · recents.ts · secrets.ts ·\n// spacesMode.ts · tasks.ts · theme.ts (×3) · vcs.ts\n//\n// `catalog.ts` is the one named NOT-folded site: its refusal copy is no longer pure —\n// R3-954 gave `invoke`'s error a `retryAfter` field this helper does not build, so the\n// fold's premise (a byte-identical copy) stopped holding for it between this branch's\n// review and its landing. `recents` and `tasks` folded as prescribed.\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// R3-816 folded the pure copies of the shape `ipc.ts` had until R3-780 — `recents` and\n// `tasks` here (two of the three the item named; the third, `catalog`, is the exemption\n// above) — and the fold changed nothing observable. R3-817 (merged as #192, 0.74.3) then\n// folded the `res && 'code' in res` family — `openExternal`, `openRepository`, `feed`,\n// `netFetch` and `theme` (×3) — fixing the `TypeError: Cannot use 'in' operator` a string\n// reply used to throw there. That form is gone from main; nothing remains to fold in\n// either family.\n//\n// Still deliberately NOT folded:\n//\n// · `catalog.ts` — the exemption above (R3-954's `retryAfter`, a field this helper\n// does not build);\n// · `launch.ts` — it folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL TWENTY SITES\n// ---------------------------------------------------------------------------\n//\n// Measured on this tree (2026-10-07, the take-over's re-run — the recipe, not the\n// history: apply the injection in a scratch copy and run the suite):\n//\n// - guard weakened to `r.ok === false` (a REFUSAL stops throwing and a success starts\n// throwing; an absent reply still throws through the `r &&` short-circuit):\n// **120 of 1002** tests redden, across **17 suites**;\n// - the FULL no-op neuter (the helper's body replaced by a bare return): **90 tests**\n// redden across **17 failed suites** — the sharper probe, and the one the\n// absent-reply cases redden under (they stay green under the guard-weakening,\n// which is the reason they exist).\n//\n// (An earlier take-over draft recorded 86 across 42 — a broken probe whose import\n// errors failed suites before their tests ran; the 90/17 pair is the stable re-run,\n// twice.)\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and fifteen near-duplicate\n// malformed-reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Twenty sites call this; **eighteen**\n * had an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708\n * and `openBundle.ts` against it in R3-808, so neither replaced anything; `catalog.ts`'s\n * copy returned inline in R3-954 — its error carries a `retryAfter` this helper does not\n * build, the one named not-folded site). They tested for PRESENCE, in **three** shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **seven** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as\n * Code) ?? 'unknown'` — `openExternal` and `openRepository` (folded in R3-708) and\n * `feed`, `netFetch` and `theme` (×3) (folded in R3-817, #192);\n * - **four** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc` (×2), `recents`, `tasks` (folded in R3-816).\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply.\n *\n * ONE revision of this paragraph got that backwards, and this is the fourth attempt to\n * describe it accurately. The original text was right FOR ITS REFERENT — it named\n * `'code' in res` as a shape replaced, without saying which sites, and at the time the\n * sites it referred to were R3-708's four, two of which used that form. R3-780 then folded\n * five DIFFERENT files and inherited the sentence unchanged, so it became false in place\n * without anyone editing it. That silent shift is the likeliest reason the next revision\n * \"corrected\" it to say NO replaced site used it — which is false the other way:\n * `openExternal` and `openRepository` did.\n *\n * The mechanism is worth more than the correction, because it is repeatable. `'code' in\n * res` is GONE from `main` — R3-817 (merged as #192, 0.74.3) folded the five sites that\n * carried it (`feed`, `netFetch`, `theme` ×3), beside R3-708's two (`openExternal`,\n * `openRepository`). A grep of `main` today finds the form only in this file's comments\n * and in test files. The tree that shows the form at the sites is the one before the\n * folds, `d4b07cc1^`. Read that before rewriting this paragraph again.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoLO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
|
|
@@ -9,18 +9,19 @@ interface CodedRefusalError<C extends string = string> extends Error {
|
|
|
9
9
|
* the code when it refused without one — a refusal is never reported as a success just
|
|
10
10
|
* because it arrived under-specified.
|
|
11
11
|
*
|
|
12
|
-
* `code` and `message` must be STRINGS to be used.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
12
|
+
* `code` and `message` must be STRINGS to be used. Twenty sites call this; **eighteen**
|
|
13
|
+
* had an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708
|
|
14
|
+
* and `openBundle.ts` against it in R3-808, so neither replaced anything; `catalog.ts`'s
|
|
15
|
+
* copy returned inline in R3-954 — its error carries a `retryAfter` this helper does not
|
|
16
|
+
* build, the one named not-folded site). They tested for PRESENCE, in **three** shapes:
|
|
16
17
|
*
|
|
17
18
|
* - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —
|
|
18
19
|
* `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;
|
|
19
|
-
* - **seven** used the `in` operator
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* - **
|
|
23
|
-
* `ipc.
|
|
20
|
+
* - **seven** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as
|
|
21
|
+
* Code) ?? 'unknown'` — `openExternal` and `openRepository` (folded in R3-708) and
|
|
22
|
+
* `feed`, `netFetch` and `theme` (×3) (folded in R3-817, #192);
|
|
23
|
+
* - **four** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —
|
|
24
|
+
* `ipc` (×2), `recents`, `tasks` (folded in R3-816).
|
|
24
25
|
*
|
|
25
26
|
* Every one of them let a host sending `code: 42` surface `err.code === 42` on a field
|
|
26
27
|
* declared `string`, and turned `message: 42` into the string `"42"`. Both now fall back,
|
|
@@ -47,11 +48,11 @@ interface CodedRefusalError<C extends string = string> extends Error {
|
|
|
47
48
|
* `openExternal` and `openRepository` did.
|
|
48
49
|
*
|
|
49
50
|
* The mechanism is worth more than the correction, because it is repeatable. `'code' in
|
|
50
|
-
* res` is
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
51
|
+
* res` is GONE from `main` — R3-817 (merged as #192, 0.74.3) folded the five sites that
|
|
52
|
+
* carried it (`feed`, `netFetch`, `theme` ×3), beside R3-708's two (`openExternal`,
|
|
53
|
+
* `openRepository`). A grep of `main` today finds the form only in this file's comments
|
|
54
|
+
* and in test files. The tree that shows the form at the sites is the one before the
|
|
55
|
+
* folds, `d4b07cc1^`. Read that before rewriting this paragraph again.
|
|
55
56
|
*
|
|
56
57
|
* It is an ASSERTION function, not a `void` one, because the inline form it replaced
|
|
57
58
|
* narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read
|
|
@@ -59,13 +60,6 @@ interface CodedRefusalError<C extends string = string> extends Error {
|
|
|
59
60
|
* the throw can ignore the narrowing; one that reads the payload gets it for free. (TS
|
|
60
61
|
* requires the call target to be an explicitly-typed declared name — this is why it is a
|
|
61
62
|
* `function` declaration and not an arrow const.)
|
|
62
|
-
*
|
|
63
|
-
* R3-817 (0.74.3): the five remaining inline copies (`feed.ts`, `netFetch.ts`,
|
|
64
|
-
* `theme.ts` ×3) folded onto this — removing a latent defect with them: their
|
|
65
|
-
* `res && 'code' in res` guard threw `TypeError: Cannot use 'in' operator` on a
|
|
66
|
-
* bare-STRING reply (a proxy error page, a relay), escaping past every `err.code`
|
|
67
|
-
* branch an app wrote. This function reads `typeof r?.code === 'string'` and
|
|
68
|
-
* cannot throw on any input; the TypeError path no longer exists.
|
|
69
63
|
*/
|
|
70
64
|
declare function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is {
|
|
71
65
|
ok: true;
|
|
@@ -9,18 +9,19 @@ interface CodedRefusalError<C extends string = string> extends Error {
|
|
|
9
9
|
* the code when it refused without one — a refusal is never reported as a success just
|
|
10
10
|
* because it arrived under-specified.
|
|
11
11
|
*
|
|
12
|
-
* `code` and `message` must be STRINGS to be used.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
12
|
+
* `code` and `message` must be STRINGS to be used. Twenty sites call this; **eighteen**
|
|
13
|
+
* had an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708
|
|
14
|
+
* and `openBundle.ts` against it in R3-808, so neither replaced anything; `catalog.ts`'s
|
|
15
|
+
* copy returned inline in R3-954 — its error carries a `retryAfter` this helper does not
|
|
16
|
+
* build, the one named not-folded site). They tested for PRESENCE, in **three** shapes:
|
|
16
17
|
*
|
|
17
18
|
* - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —
|
|
18
19
|
* `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;
|
|
19
|
-
* - **seven** used the `in` operator
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* - **
|
|
23
|
-
* `ipc.
|
|
20
|
+
* - **seven** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as
|
|
21
|
+
* Code) ?? 'unknown'` — `openExternal` and `openRepository` (folded in R3-708) and
|
|
22
|
+
* `feed`, `netFetch` and `theme` (×3) (folded in R3-817, #192);
|
|
23
|
+
* - **four** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —
|
|
24
|
+
* `ipc` (×2), `recents`, `tasks` (folded in R3-816).
|
|
24
25
|
*
|
|
25
26
|
* Every one of them let a host sending `code: 42` surface `err.code === 42` on a field
|
|
26
27
|
* declared `string`, and turned `message: 42` into the string `"42"`. Both now fall back,
|
|
@@ -47,11 +48,11 @@ interface CodedRefusalError<C extends string = string> extends Error {
|
|
|
47
48
|
* `openExternal` and `openRepository` did.
|
|
48
49
|
*
|
|
49
50
|
* The mechanism is worth more than the correction, because it is repeatable. `'code' in
|
|
50
|
-
* res` is
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
51
|
+
* res` is GONE from `main` — R3-817 (merged as #192, 0.74.3) folded the five sites that
|
|
52
|
+
* carried it (`feed`, `netFetch`, `theme` ×3), beside R3-708's two (`openExternal`,
|
|
53
|
+
* `openRepository`). A grep of `main` today finds the form only in this file's comments
|
|
54
|
+
* and in test files. The tree that shows the form at the sites is the one before the
|
|
55
|
+
* folds, `d4b07cc1^`. Read that before rewriting this paragraph again.
|
|
55
56
|
*
|
|
56
57
|
* It is an ASSERTION function, not a `void` one, because the inline form it replaced
|
|
57
58
|
* narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read
|
|
@@ -59,13 +60,6 @@ interface CodedRefusalError<C extends string = string> extends Error {
|
|
|
59
60
|
* the throw can ignore the narrowing; one that reads the payload gets it for free. (TS
|
|
60
61
|
* requires the call target to be an explicitly-typed declared name — this is why it is a
|
|
61
62
|
* `function` declaration and not an arrow const.)
|
|
62
|
-
*
|
|
63
|
-
* R3-817 (0.74.3): the five remaining inline copies (`feed.ts`, `netFetch.ts`,
|
|
64
|
-
* `theme.ts` ×3) folded onto this — removing a latent defect with them: their
|
|
65
|
-
* `res && 'code' in res` guard threw `TypeError: Cannot use 'in' operator` on a
|
|
66
|
-
* bare-STRING reply (a proxy error page, a relay), escaping past every `err.code`
|
|
67
|
-
* branch an app wrote. This function reads `typeof r?.code === 'string'` and
|
|
68
|
-
* cannot throw on any input; the TypeError path no longer exists.
|
|
69
63
|
*/
|
|
70
64
|
declare function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is {
|
|
71
65
|
ok: true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. The count is:\n//\n// **eighteen CALL SITES across thirteen FILES** — `grep -n 'throwOnRefusal(' src/*.ts`,\n// minus the declaration here and minus `*.test.*`:\n//\n// dnd.ts · editor.ts · feed.ts · ipc.ts (×2) · mounts.ts (×3) · netFetch.ts ·\n// openBundle.ts · openExternal.ts · openRepository.ts · secrets.ts · spacesMode.ts · theme.ts (×3) ·\n// vcs.ts\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// Not folded, deliberately, and the reason is NOT that they are all unalike — that was the\n// previous excuse and it was false for three of them:\n//\n// · `catalog.ts`, `recents.ts`, `tasks.ts` are pure copies of the shape `ipc.ts` had\n// until R3-780 folded it — untyped `Error & { code?: string }`, `res?.code ??\n// 'unknown'`. (`recents.ts` casts `code` as required rather than optional; immaterial,\n// the cast erases.) They are foldable and nothing here argues otherwise;\n// · `feed.ts`, `netFetch.ts` and `theme.ts` (×3) read `res && 'code' in res`, which\n// THREW `TypeError: Cannot use 'in' operator` on a string reply — FOLDED in R3-817\n// (0.74.3), a behaviour change reviewed as its own item, exactly as this bullet\n// prescribed;\n// · `launch.ts` folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// So the remaining work is two items, not one, and they are not the same size.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL EIGHTEEN SITES\n// ---------------------------------------------------------------------------\n//\n// Measured: changing the guard to `r.ok !== false` compiles clean and leaves **ten of the\n// eighteen SITES** green — seven of the thirteen files: `dnd`, `editor`, `ipc`, `mounts`,\n// `secrets`, `spacesMode` and `vcs`. Every one of them stubs an explicit `{ ok: false }`,\n// so they pin \"throws on a refusal envelope\" and nothing about a malformed or absent\n// reply. The catchers: `openBundle`, `openExternal`, `openRepository`, the five R3-817 sites (whose\n// string-reply tests reject on a non-envelope — the mutation never throws), plus\n// `protocolRefusal.test.ts`. (Re-run 2026-09-30 on the post-fold tree: suites red —\n// feed, netFetch, theme, openExternal, openRepository, protocolRefusal; the seven\n// families green. `openBundle`, the eighteenth site, was added 2026-10-05 and re-run alone\n// under the same mutation: red.)\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and eighteen near-duplicate malformed\n// -reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Eighteen sites call this;\n * **sixteen** had an inline copy it replaced (`spacesMode.ts` was written against the\n * helper in R3-708 and replaced nothing). All sixteen tested for PRESENCE, in **three**\n * shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **seven** used the `in` operator — `openExternal`, `openRepository` (with the cast;\n * folded in R3-708) and `feed`, `netFetch`, `theme` ×3 (without it; folded in R3-817,\n * the TypeError fix disclosed above);\n * - **two** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc.ts`.\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply.\n *\n * ONE revision of this paragraph got that backwards, and this is the fourth attempt to\n * describe it accurately. The original text was right FOR ITS REFERENT — it named\n * `'code' in res` as a shape replaced, without saying which sites, and at the time the\n * sites it referred to were R3-708's four, two of which used that form. R3-780 then folded\n * five DIFFERENT files and inherited the sentence unchanged, so it became false in place\n * without anyone editing it. That silent shift is the likeliest reason the next revision\n * \"corrected\" it to say NO replaced site used it — which is false the other way:\n * `openExternal` and `openRepository` did.\n *\n * The mechanism is worth more than the correction, because it is repeatable. `'code' in\n * res` is **gone from `main`** since R3-817 (0.74.3) folded the last five — a reviewer who\n * greps `main` finds nothing, and this paragraph is the record of where it lived and why\n * it misread twice before. What a grep of `main` cannot show is that the\n * form was ALSO at two sites R3-708 folded. The tree that answers the question is the one\n * before the fold, `d4b07cc1^`. Read that before rewriting this paragraph again.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n *\n * R3-817 (0.74.3): the five remaining inline copies (`feed.ts`, `netFetch.ts`,\n * `theme.ts` ×3) folded onto this — removing a latent defect with them: their\n * `res && 'code' in res` guard threw `TypeError: Cannot use 'in' operator` on a\n * bare-STRING reply (a proxy error page, a relay), escaping past every `err.code`\n * branch an app wrote. This function reads `typeof r?.code === 'string'` and\n * cannot throw on any input; the TypeError path no longer exists.\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";AAiLO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. After R3-816 folded the pure copies, the count is:\n//\n// **twenty CALL SITES across fifteen FILES** — `grep -n 'throwOnRefusal(' src/*.ts`, minus\n// the declaration here, minus `*.test.*`, and minus this census's own mention of the\n// pattern (the recipe's literal matches it):\n//\n// dnd.ts · editor.ts · feed.ts · ipc.ts (×2) · mounts.ts (×3) · netFetch.ts ·\n// openBundle.ts · openExternal.ts · openRepository.ts · recents.ts · secrets.ts ·\n// spacesMode.ts · tasks.ts · theme.ts (×3) · vcs.ts\n//\n// `catalog.ts` is the one named NOT-folded site: its refusal copy is no longer pure —\n// R3-954 gave `invoke`'s error a `retryAfter` field this helper does not build, so the\n// fold's premise (a byte-identical copy) stopped holding for it between this branch's\n// review and its landing. `recents` and `tasks` folded as prescribed.\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// R3-816 folded the pure copies of the shape `ipc.ts` had until R3-780 — `recents` and\n// `tasks` here (two of the three the item named; the third, `catalog`, is the exemption\n// above) — and the fold changed nothing observable. R3-817 (merged as #192, 0.74.3) then\n// folded the `res && 'code' in res` family — `openExternal`, `openRepository`, `feed`,\n// `netFetch` and `theme` (×3) — fixing the `TypeError: Cannot use 'in' operator` a string\n// reply used to throw there. That form is gone from main; nothing remains to fold in\n// either family.\n//\n// Still deliberately NOT folded:\n//\n// · `catalog.ts` — the exemption above (R3-954's `retryAfter`, a field this helper\n// does not build);\n// · `launch.ts` — it folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL TWENTY SITES\n// ---------------------------------------------------------------------------\n//\n// Measured on this tree (2026-10-07, the take-over's re-run — the recipe, not the\n// history: apply the injection in a scratch copy and run the suite):\n//\n// - guard weakened to `r.ok === false` (a REFUSAL stops throwing and a success starts\n// throwing; an absent reply still throws through the `r &&` short-circuit):\n// **120 of 1002** tests redden, across **17 suites**;\n// - the FULL no-op neuter (the helper's body replaced by a bare return): **90 tests**\n// redden across **17 failed suites** — the sharper probe, and the one the\n// absent-reply cases redden under (they stay green under the guard-weakening,\n// which is the reason they exist).\n//\n// (An earlier take-over draft recorded 86 across 42 — a broken probe whose import\n// errors failed suites before their tests ran; the 90/17 pair is the stable re-run,\n// twice.)\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and fifteen near-duplicate\n// malformed-reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Twenty sites call this; **eighteen**\n * had an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708\n * and `openBundle.ts` against it in R3-808, so neither replaced anything; `catalog.ts`'s\n * copy returned inline in R3-954 — its error carries a `retryAfter` this helper does not\n * build, the one named not-folded site). They tested for PRESENCE, in **three** shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **seven** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as\n * Code) ?? 'unknown'` — `openExternal` and `openRepository` (folded in R3-708) and\n * `feed`, `netFetch` and `theme` (×3) (folded in R3-817, #192);\n * - **four** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc` (×2), `recents`, `tasks` (folded in R3-816).\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply.\n *\n * ONE revision of this paragraph got that backwards, and this is the fourth attempt to\n * describe it accurately. The original text was right FOR ITS REFERENT — it named\n * `'code' in res` as a shape replaced, without saying which sites, and at the time the\n * sites it referred to were R3-708's four, two of which used that form. R3-780 then folded\n * five DIFFERENT files and inherited the sentence unchanged, so it became false in place\n * without anyone editing it. That silent shift is the likeliest reason the next revision\n * \"corrected\" it to say NO replaced site used it — which is false the other way:\n * `openExternal` and `openRepository` did.\n *\n * The mechanism is worth more than the correction, because it is repeatable. `'code' in\n * res` is GONE from `main` — R3-817 (merged as #192, 0.74.3) folded the five sites that\n * carried it (`feed`, `netFetch`, `theme` ×3), beside R3-708's two (`openExternal`,\n * `openRepository`). A grep of `main` today finds the form only in this file's comments\n * and in test files. The tree that shows the form at the sites is the one before the\n * folds, `d4b07cc1^`. Read that before rewriting this paragraph again.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";AAoLO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
|
package/dist/recents.cjs
CHANGED
|
@@ -23,15 +23,12 @@ __export(recents_exports, {
|
|
|
23
23
|
});
|
|
24
24
|
module.exports = __toCommonJS(recents_exports);
|
|
25
25
|
var import_sandboxUtils = require("./sandboxUtils");
|
|
26
|
+
var import_protocolRefusal = require("./protocolRefusal");
|
|
26
27
|
var import_protocol = require("./generated/protocol");
|
|
27
28
|
var import_protocolSchemes = require("./protocolSchemes");
|
|
28
29
|
const recentsRequest = async (params) => {
|
|
29
30
|
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_RECENTS], "list", [params]);
|
|
30
|
-
|
|
31
|
-
const err = new Error(res?.message ?? "recents request failed");
|
|
32
|
-
err.code = res?.code ?? "unknown";
|
|
33
|
-
throw err;
|
|
34
|
-
}
|
|
31
|
+
(0, import_protocolRefusal.throwOnRefusal)(res, "recents request failed");
|
|
35
32
|
return res.data;
|
|
36
33
|
};
|
|
37
34
|
async function listRecentProjects() {
|
package/dist/recents.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/recents.ts"],"sourcesContent":["// The recent-projects record — app-facing surface (R3-485, OSO §4.3).\n//\n// `listRecentProjects()` reads the HOST-OWNED record through the one elevated,\n// app-scoped `recents:read` capability. Two gates stand between an app and the\n// record, and both must pass: the §8.4 capability grant (declared as\n// `requests: { 'recents:read': {} }` and consented per (app, principal)), and the\n// handler's structural binding — the read is granted only to the app bound at\n// `page.home`. For every other app the call resolves to a refusal, whatever it\n// declared.\n//\n// A project entry is COORDINATES (provider/namespace/repository/ref + when) — a\n// location the user already navigated to under their own authority, never an\n// in-repo path. Opening one runs the ordinary load path with the ordinary\n// consent: the record confers nothing (R-OSO-22).\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_RECENTS } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** One recently opened project — repository coordinates, never an in-repo path. */\nexport interface RecentProject {\n provider: string;\n namespace: string;\n repository: string;\n /** The ref the user opened (`main`, a sha). */\n ref: string;\n /** When the user last opened it (epoch ms). */\n ts: number;\n}\n\ninterface RecentsReply {\n /** Newest-first; `null` when the record is empty or the user cleared it. */\n projects: RecentProject[] | null;\n}\n\n/**\n * The host wraps every action result as `{ ok: true, data }` and every refusal\n * as `{ ok: false, code, message }` INSIDE the reply's `result` — refusals\n * resolve rather than reject, because the sandbox's protocolRequest rejects\n * with a bare `Error` and would drop the `code` (requestDispatcher's reply\n * contract). Unwrap here, like every other gated module, so callers see the\n * coded refusal and never a silent `null`.\n */\ntype RecentsResult = { ok: true; data: RecentsReply } | { ok: false; code: string; message?: string };\n\n/**\n * The one call shape the SDK speaks under `protocol-recents` — read, or clear\n * (same gated surface). A single typed call site keeps the wire contract exact:\n * the snapshot gate reads THIS shape, and the host handler accepts the same.\n */\nconst recentsRequest = async (params: { clear?: boolean }): Promise<RecentsReply> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_RECENTS], 'list', [params])) as RecentsResult;\n
|
|
1
|
+
{"version":3,"sources":["../src/recents.ts"],"sourcesContent":["// The recent-projects record — app-facing surface (R3-485, OSO §4.3).\n//\n// `listRecentProjects()` reads the HOST-OWNED record through the one elevated,\n// app-scoped `recents:read` capability. Two gates stand between an app and the\n// record, and both must pass: the §8.4 capability grant (declared as\n// `requests: { 'recents:read': {} }` and consented per (app, principal)), and the\n// handler's structural binding — the read is granted only to the app bound at\n// `page.home`. For every other app the call resolves to a refusal, whatever it\n// declared.\n//\n// A project entry is COORDINATES (provider/namespace/repository/ref + when) — a\n// location the user already navigated to under their own authority, never an\n// in-repo path. Opening one runs the ordinary load path with the ordinary\n// consent: the record confers nothing (R-OSO-22).\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_RECENTS } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** One recently opened project — repository coordinates, never an in-repo path. */\nexport interface RecentProject {\n provider: string;\n namespace: string;\n repository: string;\n /** The ref the user opened (`main`, a sha). */\n ref: string;\n /** When the user last opened it (epoch ms). */\n ts: number;\n}\n\ninterface RecentsReply {\n /** Newest-first; `null` when the record is empty or the user cleared it. */\n projects: RecentProject[] | null;\n}\n\n/**\n * The host wraps every action result as `{ ok: true, data }` and every refusal\n * as `{ ok: false, code, message }` INSIDE the reply's `result` — refusals\n * resolve rather than reject, because the sandbox's protocolRequest rejects\n * with a bare `Error` and would drop the `code` (requestDispatcher's reply\n * contract). Unwrap here, like every other gated module, so callers see the\n * coded refusal and never a silent `null`.\n */\ntype RecentsResult = { ok: true; data: RecentsReply } | { ok: false; code: string; message?: string };\n\n/**\n * The one call shape the SDK speaks under `protocol-recents` — read, or clear\n * (same gated surface). A single typed call site keeps the wire contract exact:\n * the snapshot gate reads THIS shape, and the host handler accepts the same.\n */\nconst recentsRequest = async (params: { clear?: boolean }): Promise<RecentsReply> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_RECENTS], 'list', [params])) as RecentsResult;\n // The one refusal unwrap (R6, R3-816) — same observable behaviour: the coded\n // refusal throws with its code; an absent reply throws as 'unknown'.\n throwOnRefusal(res, 'recents request failed');\n return res.data;\n};\n\n/**\n * The user's recently opened projects, newest-first, or `null` when the record is\n * absent (R-OSO-22: cleared is absent, never an empty list). Refuses for any app\n * that is not the `page.home` binding.\n *\n * @throws a coded error — `forbidden` without the grant or the binding, or the\n * host's own code; never a silent `null` for a refusal.\n */\nexport async function listRecentProjects(): Promise<RecentProject[] | null> {\n const res = await recentsRequest({});\n return res.projects ?? null;\n}\n\n/**\n * Clear the user's recent-projects record (the surface afterwards is absent, not\n * empty). Rides the same page.home binding gate as the read.\n *\n * @throws a coded error when the clear is refused — the caller must not treat\n * the record as cleared.\n */\nexport async function clearRecentProjects(): Promise<void> {\n await recentsRequest({ clear: true });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,0BAAgC;AAChC,6BAA+B;AAC/B,sBAAiC;AACjC,6BAAwB;AAiCxB,MAAM,iBAAiB,OAAO,WAAuD;AACnF,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,gCAAgB,GAAG,QAAQ,CAAC,MAAM,CAAC;AAG9E,6CAAe,KAAK,wBAAwB;AAC5C,SAAO,IAAI;AACb;AAUA,eAAsB,qBAAsD;AAC1E,QAAM,MAAM,MAAM,eAAe,CAAC,CAAC;AACnC,SAAO,IAAI,YAAY;AACzB;AASA,eAAsB,sBAAqC;AACzD,QAAM,eAAe,EAAE,OAAO,KAAK,CAAC;AACtC;","names":[]}
|
package/dist/recents.js
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
2
|
import { protocolRequest } from "./sandboxUtils.js";
|
|
3
|
+
import { throwOnRefusal } from "./protocolRefusal.js";
|
|
3
4
|
import { PROTOCOL_RECENTS } from "./generated/protocol.js";
|
|
4
5
|
import { SCHEMES } from "./protocolSchemes.js";
|
|
5
6
|
const recentsRequest = async (params) => {
|
|
6
7
|
const res = await protocolRequest(SCHEMES[PROTOCOL_RECENTS], "list", [params]);
|
|
7
|
-
|
|
8
|
-
const err = new Error(res?.message ?? "recents request failed");
|
|
9
|
-
err.code = res?.code ?? "unknown";
|
|
10
|
-
throw err;
|
|
11
|
-
}
|
|
8
|
+
throwOnRefusal(res, "recents request failed");
|
|
12
9
|
return res.data;
|
|
13
10
|
};
|
|
14
11
|
async function listRecentProjects() {
|
package/dist/recents.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/recents.ts"],"sourcesContent":["// The recent-projects record — app-facing surface (R3-485, OSO §4.3).\n//\n// `listRecentProjects()` reads the HOST-OWNED record through the one elevated,\n// app-scoped `recents:read` capability. Two gates stand between an app and the\n// record, and both must pass: the §8.4 capability grant (declared as\n// `requests: { 'recents:read': {} }` and consented per (app, principal)), and the\n// handler's structural binding — the read is granted only to the app bound at\n// `page.home`. For every other app the call resolves to a refusal, whatever it\n// declared.\n//\n// A project entry is COORDINATES (provider/namespace/repository/ref + when) — a\n// location the user already navigated to under their own authority, never an\n// in-repo path. Opening one runs the ordinary load path with the ordinary\n// consent: the record confers nothing (R-OSO-22).\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_RECENTS } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** One recently opened project — repository coordinates, never an in-repo path. */\nexport interface RecentProject {\n provider: string;\n namespace: string;\n repository: string;\n /** The ref the user opened (`main`, a sha). */\n ref: string;\n /** When the user last opened it (epoch ms). */\n ts: number;\n}\n\ninterface RecentsReply {\n /** Newest-first; `null` when the record is empty or the user cleared it. */\n projects: RecentProject[] | null;\n}\n\n/**\n * The host wraps every action result as `{ ok: true, data }` and every refusal\n * as `{ ok: false, code, message }` INSIDE the reply's `result` — refusals\n * resolve rather than reject, because the sandbox's protocolRequest rejects\n * with a bare `Error` and would drop the `code` (requestDispatcher's reply\n * contract). Unwrap here, like every other gated module, so callers see the\n * coded refusal and never a silent `null`.\n */\ntype RecentsResult = { ok: true; data: RecentsReply } | { ok: false; code: string; message?: string };\n\n/**\n * The one call shape the SDK speaks under `protocol-recents` — read, or clear\n * (same gated surface). A single typed call site keeps the wire contract exact:\n * the snapshot gate reads THIS shape, and the host handler accepts the same.\n */\nconst recentsRequest = async (params: { clear?: boolean }): Promise<RecentsReply> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_RECENTS], 'list', [params])) as RecentsResult;\n
|
|
1
|
+
{"version":3,"sources":["../src/recents.ts"],"sourcesContent":["// The recent-projects record — app-facing surface (R3-485, OSO §4.3).\n//\n// `listRecentProjects()` reads the HOST-OWNED record through the one elevated,\n// app-scoped `recents:read` capability. Two gates stand between an app and the\n// record, and both must pass: the §8.4 capability grant (declared as\n// `requests: { 'recents:read': {} }` and consented per (app, principal)), and the\n// handler's structural binding — the read is granted only to the app bound at\n// `page.home`. For every other app the call resolves to a refusal, whatever it\n// declared.\n//\n// A project entry is COORDINATES (provider/namespace/repository/ref + when) — a\n// location the user already navigated to under their own authority, never an\n// in-repo path. Opening one runs the ordinary load path with the ordinary\n// consent: the record confers nothing (R-OSO-22).\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_RECENTS } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** One recently opened project — repository coordinates, never an in-repo path. */\nexport interface RecentProject {\n provider: string;\n namespace: string;\n repository: string;\n /** The ref the user opened (`main`, a sha). */\n ref: string;\n /** When the user last opened it (epoch ms). */\n ts: number;\n}\n\ninterface RecentsReply {\n /** Newest-first; `null` when the record is empty or the user cleared it. */\n projects: RecentProject[] | null;\n}\n\n/**\n * The host wraps every action result as `{ ok: true, data }` and every refusal\n * as `{ ok: false, code, message }` INSIDE the reply's `result` — refusals\n * resolve rather than reject, because the sandbox's protocolRequest rejects\n * with a bare `Error` and would drop the `code` (requestDispatcher's reply\n * contract). Unwrap here, like every other gated module, so callers see the\n * coded refusal and never a silent `null`.\n */\ntype RecentsResult = { ok: true; data: RecentsReply } | { ok: false; code: string; message?: string };\n\n/**\n * The one call shape the SDK speaks under `protocol-recents` — read, or clear\n * (same gated surface). A single typed call site keeps the wire contract exact:\n * the snapshot gate reads THIS shape, and the host handler accepts the same.\n */\nconst recentsRequest = async (params: { clear?: boolean }): Promise<RecentsReply> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_RECENTS], 'list', [params])) as RecentsResult;\n // The one refusal unwrap (R6, R3-816) — same observable behaviour: the coded\n // refusal throws with its code; an absent reply throws as 'unknown'.\n throwOnRefusal(res, 'recents request failed');\n return res.data;\n};\n\n/**\n * The user's recently opened projects, newest-first, or `null` when the record is\n * absent (R-OSO-22: cleared is absent, never an empty list). Refuses for any app\n * that is not the `page.home` binding.\n *\n * @throws a coded error — `forbidden` without the grant or the binding, or the\n * host's own code; never a silent `null` for a refusal.\n */\nexport async function listRecentProjects(): Promise<RecentProject[] | null> {\n const res = await recentsRequest({});\n return res.projects ?? null;\n}\n\n/**\n * Clear the user's recent-projects record (the surface afterwards is absent, not\n * empty). Rides the same page.home binding gate as the read.\n *\n * @throws a coded error when the clear is refused — the caller must not treat\n * the record as cleared.\n */\nexport async function clearRecentProjects(): Promise<void> {\n await recentsRequest({ clear: true });\n}\n"],"mappings":";AAcA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AACjC,SAAS,eAAe;AAiCxB,MAAM,iBAAiB,OAAO,WAAuD;AACnF,QAAM,MAAO,MAAM,gBAAgB,QAAQ,gBAAgB,GAAG,QAAQ,CAAC,MAAM,CAAC;AAG9E,iBAAe,KAAK,wBAAwB;AAC5C,SAAO,IAAI;AACb;AAUA,eAAsB,qBAAsD;AAC1E,QAAM,MAAM,MAAM,eAAe,CAAC,CAAC;AACnC,SAAO,IAAI,YAAY;AACzB;AASA,eAAsB,sBAAqC;AACzD,QAAM,eAAe,EAAE,OAAO,KAAK,CAAC;AACtC;","names":[]}
|
package/dist/routing.cjs
CHANGED
|
@@ -111,7 +111,8 @@ const navigate = (target, opts) => {
|
|
|
111
111
|
back: false,
|
|
112
112
|
forward: false,
|
|
113
113
|
...entryState ? { entryState } : {},
|
|
114
|
-
...declared
|
|
114
|
+
...declared,
|
|
115
|
+
...opts?.replace === true ? { replace: true } : {}
|
|
115
116
|
};
|
|
116
117
|
(0, import_sandboxUtils.sendMessage)(import_protocol.URLCHANGE, message);
|
|
117
118
|
};
|
package/dist/routing.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/routing.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { use, useContext } from 'react';\n\nimport { sendMessage } from './sandboxUtils';\nimport { NavigationState, TinkerableContext } from './TinkerableContext';\nimport { RouteParams, RoutingRule, RoutingSpec } from './RoutingSpec';\nimport { matchRoute } from './routeMatch';\nimport { constructUrl, isAbsolutePath, parseTarget } from './urlUtils';\nimport { joinPaths } from './pathUtils';\nimport { takeQueuedEntryState } from './entryState';\nimport { URLCHANGE, type UrlchangePayload } from './generated/protocol';\n\n/** The result of matching a path: the winning {@link RoutingRule} plus its captured params. */\nexport type AppliedRoutingRule = {\n routingRule: RoutingRule;\n pathParameters?: Record<string, string>;\n};\n\n/** Build the full outer href for an in-app target (absolute `sandboxPath` or a\n * path relative to the current route), e.g. for an `href` attribute. */\nexport const useTinkerableLink = (newSandboxLocation: string) => {\n const { outerHref, navigationState: navigation } = use(TinkerableContext);\n let newNavigationState = parseTarget(newSandboxLocation, navigation);\n if (!isAbsolutePath(newSandboxLocation)) {\n newNavigationState.sandboxPath = joinPaths(navigation.sandboxPath, newSandboxLocation);\n } else {\n newNavigationState.sandboxPath = newSandboxLocation;\n }\n return constructUrl(outerHref, newNavigationState);\n};\n\n/** Find the first rule in `routingSpec` whose pattern matches the current\n * `sandboxPath`, returning it with the captured params (or `undefined`). */\nexport const applyRoutingRule = (\n routingSpec: RoutingSpec,\n navigationState: NavigationState,\n): AppliedRoutingRule | undefined => {\n const { sandboxPath } = navigationState;\n for (const routingRule of routingSpec.routes) {\n const pathParameters = matchRoute(routingRule.pattern, sandboxPath);\n if (pathParameters) {\n return { routingRule, pathParameters };\n }\n }\n return undefined;\n};\n\n/** Render a matched rule, passing params to a `component` and falling back to `element`/`reactNode`. */\nexport const renderRoute = (routingRule: RoutingRule, params: RouteParams): ReactNode => {\n if (routingRule.component) {\n const Component = routingRule.component;\n return <Component params={params} />;\n }\n return routingRule.element ?? routingRule.reactNode ?? null;\n};\n\n/** Render the route matched for the current location (set up by `boot`'s route table). */\nexport const Router = () => {\n const context = useContext(TinkerableContext);\n const {\n navigationState: { routingRule, pathParameters },\n } = context;\n if (!routingRule) {\n // TODO: better error\n throw new Error(`No route registered for path ${context.navigationState.sandboxPath}!`);\n }\n\n return renderRoute(routingRule, pathParameters ?? {});\n};\n\n/** Read the current route's matched params (`:name` segments and the `*` wildcard). */\nexport const useRouteParams = <T extends RouteParams = RouteParams>(): T =>\n (use(TinkerableContext).navigationState.pathParameters ?? {}) as T;\n\n/**\n * Read the current route: the matched rule's `name`, its `params`, the app-owned\n * `sandboxPath`, and the read-only platform prefix fields (`mode`, `provider`,\n * `namespace`, `repository`, `ref`) — e.g. to tell `/edit` from `/present`.\n */\nexport const useRoute = () => {\n const { navigationState } = use(TinkerableContext);\n const { routingRule, pathParameters, sandboxPath, mode, provider, namespace, repository, ref } = navigationState;\n return {\n name: routingRule?.name,\n params: (pathParameters ?? {}) as RouteParams,\n sandboxPath,\n mode,\n provider,\n namespace,\n repository,\n ref,\n };\n};\n\n/**\n * Navigate within the app. Messages the host to update the URL; the host then\n * pushes the new href back, which drives the actual route change.\n *\n * `opts.viewedDocument` (R3-268) optionally declares which WORKING-TREE file\n * this destination renders — a tri-state rider on the navigation event:\n * - omit the option entirely → the host derives the hint from the URL's\n * `files/` suffix convention (the zero-SDK default);\n * - `null` → this view shows no file (clears the highlight — tag pages,\n * search, home views);\n * - a repo-relative path (the CORPUS path under dispatch — only the viewer\n * can map its own key space) → the file explorer highlights it.\n * The hint is highlight-only by contract (it never scrolls, never moves focus\n * or panes, never switches the editor) and is validated host-side for\n * existence — a wrong path degrades to \"no highlight\", never an error. The\n * host remembers declarations per URL, so back/forward reproduces them\n * without re-announcement.\n */\n// R3-268: an app-registered rule mapping a navigation TARGET to its viewed\n// document, consulted by `navigate()` whenever the caller did not declare one\n// explicitly. Registered ONCE (e.g. at boot) so an app whose links all flow\n// through `<Link>`/`navigate` gets correct declarations everywhere without\n// threading an option through every call site. Return `undefined` for \"no\n// declaration\" (the host falls back to the URL convention), `null` for \"this\n// view shows no file\", or a working-tree repo-relative path.\nlet viewedDocumentResolver: ((targetHref: string) => string | null | undefined) | null = null;\n\n/** Register the app's route→viewed-document rule (R3-268); pass `null` to clear. */\nexport const setViewedDocumentResolver = (\n resolver: ((targetHref: string) => string | null | undefined) | null,\n): void => {\n viewedDocumentResolver = resolver;\n};\n\nexport const navigate = (target: string, opts?: { viewedDocument?: string | null }) => {\n console.log(`[Sandbox] Navigating to ${target}`);\n // Explicit option first; else the registered resolver; else nothing on the\n // wire (the host derives from the URL convention). A resolver throw is\n // swallowed to \"no declaration\" — a mapping bug must never break navigation.\n let declared: { viewedDocument: string | null } | Record<string, never> = {};\n if (opts && 'viewedDocument' in opts) {\n declared = { viewedDocument: opts.viewedDocument ?? null };\n } else if (viewedDocumentResolver) {\n try {\n const v = viewedDocumentResolver(target);\n if (v !== undefined) declared = { viewedDocument: v };\n } catch {\n /* no declaration */\n }\n }\n // The scratch for the entry we are LEAVING, gathered synchronously here because\n // this call is the one moment the app knows a navigation is happening (R3-627).\n // The host stamps it on the current entry before pushing the target, and hands it\n // back if the reader ever returns; it never parses it.\n const entryState = takeQueuedEntryState();\n const message: UrlchangePayload = {\n url: target,\n back: false,\n forward: false,\n ...(entryState ? { entryState } : {}),\n ...declared,\n };\n sendMessage(URLCHANGE, message);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDW;AAlDX,mBAAgC;AAEhC,0BAA4B;AAC5B,+BAAmD;AAEnD,wBAA2B;AAC3B,sBAA0D;AAC1D,uBAA0B;AAC1B,wBAAqC;AACrC,sBAAiD;AAU1C,MAAM,oBAAoB,CAAC,uBAA+B;AAC/D,QAAM,EAAE,WAAW,iBAAiB,WAAW,QAAI,kBAAI,0CAAiB;AACxE,MAAI,yBAAqB,6BAAY,oBAAoB,UAAU;AACnE,MAAI,KAAC,gCAAe,kBAAkB,GAAG;AACvC,uBAAmB,kBAAc,4BAAU,WAAW,aAAa,kBAAkB;AAAA,EACvF,OAAO;AACL,uBAAmB,cAAc;AAAA,EACnC;AACA,aAAO,8BAAa,WAAW,kBAAkB;AACnD;AAIO,MAAM,mBAAmB,CAC9B,aACA,oBACmC;AACnC,QAAM,EAAE,YAAY,IAAI;AACxB,aAAW,eAAe,YAAY,QAAQ;AAC5C,UAAM,qBAAiB,8BAAW,YAAY,SAAS,WAAW;AAClE,QAAI,gBAAgB;AAClB,aAAO,EAAE,aAAa,eAAe;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;AAGO,MAAM,c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AAKA,QAAM,iBAAa,wCAAqB;AACxC,QAAM,UAA4B;AAAA,IAChC,KAAK;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;AAAA,IACnC,GAAG;AAAA,EACL;AACA,uCAAY,2BAAW,OAAO;AAChC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/routing.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { use, useContext } from 'react';\n\nimport { sendMessage } from './sandboxUtils';\nimport { NavigationState, TinkerableContext } from './TinkerableContext';\nimport { RouteParams, RoutingRule, RoutingSpec } from './RoutingSpec';\nimport { matchRoute } from './routeMatch';\nimport { constructUrl, isAbsolutePath, parseTarget } from './urlUtils';\nimport { joinPaths } from './pathUtils';\nimport { takeQueuedEntryState } from './entryState';\nimport { URLCHANGE, type UrlchangePayload } from './generated/protocol';\n\n/** The result of matching a path: the winning {@link RoutingRule} plus its captured params. */\nexport type AppliedRoutingRule = {\n routingRule: RoutingRule;\n pathParameters?: Record<string, string>;\n};\n\n/** Build the full outer href for an in-app target (absolute `sandboxPath` or a\n * path relative to the current route), e.g. for an `href` attribute. */\nexport const useTinkerableLink = (newSandboxLocation: string) => {\n const { outerHref, navigationState: navigation } = use(TinkerableContext);\n let newNavigationState = parseTarget(newSandboxLocation, navigation);\n if (!isAbsolutePath(newSandboxLocation)) {\n newNavigationState.sandboxPath = joinPaths(navigation.sandboxPath, newSandboxLocation);\n } else {\n newNavigationState.sandboxPath = newSandboxLocation;\n }\n return constructUrl(outerHref, newNavigationState);\n};\n\n/** Find the first rule in `routingSpec` whose pattern matches the current\n * `sandboxPath`, returning it with the captured params (or `undefined`). */\nexport const applyRoutingRule = (\n routingSpec: RoutingSpec,\n navigationState: NavigationState,\n): AppliedRoutingRule | undefined => {\n const { sandboxPath } = navigationState;\n for (const routingRule of routingSpec.routes) {\n const pathParameters = matchRoute(routingRule.pattern, sandboxPath);\n if (pathParameters) {\n return { routingRule, pathParameters };\n }\n }\n return undefined;\n};\n\n/** Render a matched rule, passing params to a `component` and falling back to `element`/`reactNode`. */\nexport const renderRoute = (routingRule: RoutingRule, params: RouteParams): ReactNode => {\n if (routingRule.component) {\n const Component = routingRule.component;\n return <Component params={params} />;\n }\n return routingRule.element ?? routingRule.reactNode ?? null;\n};\n\n/** Render the route matched for the current location (set up by `boot`'s route table). */\nexport const Router = () => {\n const context = useContext(TinkerableContext);\n const {\n navigationState: { routingRule, pathParameters },\n } = context;\n if (!routingRule) {\n // TODO: better error\n throw new Error(`No route registered for path ${context.navigationState.sandboxPath}!`);\n }\n\n return renderRoute(routingRule, pathParameters ?? {});\n};\n\n/** Read the current route's matched params (`:name` segments and the `*` wildcard). */\nexport const useRouteParams = <T extends RouteParams = RouteParams>(): T =>\n (use(TinkerableContext).navigationState.pathParameters ?? {}) as T;\n\n/**\n * Read the current route: the matched rule's `name`, its `params`, the app-owned\n * `sandboxPath`, and the read-only platform prefix fields (`mode`, `provider`,\n * `namespace`, `repository`, `ref`) — e.g. to tell `/edit` from `/present`.\n */\nexport const useRoute = () => {\n const { navigationState } = use(TinkerableContext);\n const { routingRule, pathParameters, sandboxPath, mode, provider, namespace, repository, ref } = navigationState;\n return {\n name: routingRule?.name,\n params: (pathParameters ?? {}) as RouteParams,\n sandboxPath,\n mode,\n provider,\n namespace,\n repository,\n ref,\n };\n};\n\n/**\n * Navigate within the app. Messages the host to update the URL; the host then\n * pushes the new href back, which drives the actual route change.\n *\n * `opts.viewedDocument` (R3-268) optionally declares which WORKING-TREE file\n * this destination renders — a tri-state rider on the navigation event:\n * - omit the option entirely → the host derives the hint from the URL's\n * `files/` suffix convention (the zero-SDK default);\n * - `null` → this view shows no file (clears the highlight — tag pages,\n * search, home views);\n * - a repo-relative path (the CORPUS path under dispatch — only the viewer\n * can map its own key space) → the file explorer highlights it.\n * The hint is highlight-only by contract (it never scrolls, never moves focus\n * or panes, never switches the editor) and is validated host-side for\n * existence — a wrong path degrades to \"no highlight\", never an error. The\n * host remembers declarations per URL, so back/forward reproduces them\n * without re-announcement.\n *\n * `opts.replace` (R3-874, APP_CUSTOMIZATION_SPEC §5): `true` asks the host to\n * REPLACE the current history entry instead of pushing — for an app whose URL\n * encodes view state, so re-renders don't flood the reader's Back chain.\n * In-prefix targets only: the host ignores it for a navigation that leaves the\n * app (an app must not erase the entry the user would press Back to reach,\n * G-CUST-6). Absent or `false` keeps the field off the wire entirely.\n */\n// R3-268: an app-registered rule mapping a navigation TARGET to its viewed\n// document, consulted by `navigate()` whenever the caller did not declare one\n// explicitly. Registered ONCE (e.g. at boot) so an app whose links all flow\n// through `<Link>`/`navigate` gets correct declarations everywhere without\n// threading an option through every call site. Return `undefined` for \"no\n// declaration\" (the host falls back to the URL convention), `null` for \"this\n// view shows no file\", or a working-tree repo-relative path.\nlet viewedDocumentResolver: ((targetHref: string) => string | null | undefined) | null = null;\n\n/** Register the app's route→viewed-document rule (R3-268); pass `null` to clear. */\nexport const setViewedDocumentResolver = (\n resolver: ((targetHref: string) => string | null | undefined) | null,\n): void => {\n viewedDocumentResolver = resolver;\n};\n\nexport const navigate = (target: string, opts?: { viewedDocument?: string | null; replace?: boolean }) => {\n console.log(`[Sandbox] Navigating to ${target}`);\n // Explicit option first; else the registered resolver; else nothing on the\n // wire (the host derives from the URL convention). A resolver throw is\n // swallowed to \"no declaration\" — a mapping bug must never break navigation.\n let declared: { viewedDocument: string | null } | Record<string, never> = {};\n if (opts && 'viewedDocument' in opts) {\n declared = { viewedDocument: opts.viewedDocument ?? null };\n } else if (viewedDocumentResolver) {\n try {\n const v = viewedDocumentResolver(target);\n if (v !== undefined) declared = { viewedDocument: v };\n } catch {\n /* no declaration */\n }\n }\n // The scratch for the entry we are LEAVING, gathered synchronously here because\n // this call is the one moment the app knows a navigation is happening (R3-627).\n // The host stamps it on the current entry before pushing the target, and hands it\n // back if the reader ever returns; it never parses it.\n //\n // R3-874: `replace: true` asks the host to REPLACE the current entry instead of\n // pushing (an app whose URL encodes view state would otherwise flood history).\n // The host ignores it for out-of-prefix targets (an app must not erase the entry\n // the user would press Back to reach — G-CUST-6). The message is built as ONE\n // typed value — the wire-shape gate fingerprints the declared UrlchangePayload,\n // and a spread-built union would extract as 'any' and never match (protocol#38).\n const entryState = takeQueuedEntryState();\n const message: UrlchangePayload = {\n url: target,\n back: false,\n forward: false,\n ...(entryState ? { entryState } : {}),\n ...declared,\n ...(opts?.replace === true ? { replace: true as const } : {}),\n };\n sendMessage(URLCHANGE, message);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDW;AAlDX,mBAAgC;AAEhC,0BAA4B;AAC5B,+BAAmD;AAEnD,wBAA2B;AAC3B,sBAA0D;AAC1D,uBAA0B;AAC1B,wBAAqC;AACrC,sBAAiD;AAU1C,MAAM,oBAAoB,CAAC,uBAA+B;AAC/D,QAAM,EAAE,WAAW,iBAAiB,WAAW,QAAI,kBAAI,0CAAiB;AACxE,MAAI,yBAAqB,6BAAY,oBAAoB,UAAU;AACnE,MAAI,KAAC,gCAAe,kBAAkB,GAAG;AACvC,uBAAmB,kBAAc,4BAAU,WAAW,aAAa,kBAAkB;AAAA,EACvF,OAAO;AACL,uBAAmB,cAAc;AAAA,EACnC;AACA,aAAO,8BAAa,WAAW,kBAAkB;AACnD;AAIO,MAAM,mBAAmB,CAC9B,aACA,oBACmC;AACnC,QAAM,EAAE,YAAY,IAAI;AACxB,aAAW,eAAe,YAAY,QAAQ;AAC5C,UAAM,qBAAiB,8BAAW,YAAY,SAAS,WAAW;AAClE,QAAI,gBAAgB;AAClB,aAAO,EAAE,aAAa,eAAe;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;AAGO,MAAM,cAAc,CAAC,aAA0B,WAAmC;AACvF,MAAI,YAAY,WAAW;AACzB,UAAM,YAAY,YAAY;AAC9B,WAAO,4CAAC,aAAU,QAAgB;AAAA,EACpC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Aa,EAAE,WAAW,IAAI,CAAC;AAAA,IACnC,GAAG;AAAA,IACH,GAAI,MAAM,YAAY,OAAO,EAAE,SAAS,KAAc,IAAI,CAAC;AAAA,EAC7D;AACA,uCAAY,2BAAW,OAAO;AAChC;","names":[]}
|
package/dist/routing.d.cts
CHANGED
|
@@ -39,6 +39,7 @@ declare const useRoute: () => {
|
|
|
39
39
|
declare const setViewedDocumentResolver: (resolver: ((targetHref: string) => string | null | undefined) | null) => void;
|
|
40
40
|
declare const navigate: (target: string, opts?: {
|
|
41
41
|
viewedDocument?: string | null;
|
|
42
|
+
replace?: boolean;
|
|
42
43
|
}) => void;
|
|
43
44
|
|
|
44
45
|
export { type AppliedRoutingRule, Router, applyRoutingRule, navigate, renderRoute, setViewedDocumentResolver, useRoute, useRouteParams, useTinkerableLink };
|
package/dist/routing.d.ts
CHANGED
|
@@ -39,6 +39,7 @@ declare const useRoute: () => {
|
|
|
39
39
|
declare const setViewedDocumentResolver: (resolver: ((targetHref: string) => string | null | undefined) | null) => void;
|
|
40
40
|
declare const navigate: (target: string, opts?: {
|
|
41
41
|
viewedDocument?: string | null;
|
|
42
|
+
replace?: boolean;
|
|
42
43
|
}) => void;
|
|
43
44
|
|
|
44
45
|
export { type AppliedRoutingRule, Router, applyRoutingRule, navigate, renderRoute, setViewedDocumentResolver, useRoute, useRouteParams, useTinkerableLink };
|
package/dist/routing.js
CHANGED
package/dist/routing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/routing.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { use, useContext } from 'react';\n\nimport { sendMessage } from './sandboxUtils';\nimport { NavigationState, TinkerableContext } from './TinkerableContext';\nimport { RouteParams, RoutingRule, RoutingSpec } from './RoutingSpec';\nimport { matchRoute } from './routeMatch';\nimport { constructUrl, isAbsolutePath, parseTarget } from './urlUtils';\nimport { joinPaths } from './pathUtils';\nimport { takeQueuedEntryState } from './entryState';\nimport { URLCHANGE, type UrlchangePayload } from './generated/protocol';\n\n/** The result of matching a path: the winning {@link RoutingRule} plus its captured params. */\nexport type AppliedRoutingRule = {\n routingRule: RoutingRule;\n pathParameters?: Record<string, string>;\n};\n\n/** Build the full outer href for an in-app target (absolute `sandboxPath` or a\n * path relative to the current route), e.g. for an `href` attribute. */\nexport const useTinkerableLink = (newSandboxLocation: string) => {\n const { outerHref, navigationState: navigation } = use(TinkerableContext);\n let newNavigationState = parseTarget(newSandboxLocation, navigation);\n if (!isAbsolutePath(newSandboxLocation)) {\n newNavigationState.sandboxPath = joinPaths(navigation.sandboxPath, newSandboxLocation);\n } else {\n newNavigationState.sandboxPath = newSandboxLocation;\n }\n return constructUrl(outerHref, newNavigationState);\n};\n\n/** Find the first rule in `routingSpec` whose pattern matches the current\n * `sandboxPath`, returning it with the captured params (or `undefined`). */\nexport const applyRoutingRule = (\n routingSpec: RoutingSpec,\n navigationState: NavigationState,\n): AppliedRoutingRule | undefined => {\n const { sandboxPath } = navigationState;\n for (const routingRule of routingSpec.routes) {\n const pathParameters = matchRoute(routingRule.pattern, sandboxPath);\n if (pathParameters) {\n return { routingRule, pathParameters };\n }\n }\n return undefined;\n};\n\n/** Render a matched rule, passing params to a `component` and falling back to `element`/`reactNode`. */\nexport const renderRoute = (routingRule: RoutingRule, params: RouteParams): ReactNode => {\n if (routingRule.component) {\n const Component = routingRule.component;\n return <Component params={params} />;\n }\n return routingRule.element ?? routingRule.reactNode ?? null;\n};\n\n/** Render the route matched for the current location (set up by `boot`'s route table). */\nexport const Router = () => {\n const context = useContext(TinkerableContext);\n const {\n navigationState: { routingRule, pathParameters },\n } = context;\n if (!routingRule) {\n // TODO: better error\n throw new Error(`No route registered for path ${context.navigationState.sandboxPath}!`);\n }\n\n return renderRoute(routingRule, pathParameters ?? {});\n};\n\n/** Read the current route's matched params (`:name` segments and the `*` wildcard). */\nexport const useRouteParams = <T extends RouteParams = RouteParams>(): T =>\n (use(TinkerableContext).navigationState.pathParameters ?? {}) as T;\n\n/**\n * Read the current route: the matched rule's `name`, its `params`, the app-owned\n * `sandboxPath`, and the read-only platform prefix fields (`mode`, `provider`,\n * `namespace`, `repository`, `ref`) — e.g. to tell `/edit` from `/present`.\n */\nexport const useRoute = () => {\n const { navigationState } = use(TinkerableContext);\n const { routingRule, pathParameters, sandboxPath, mode, provider, namespace, repository, ref } = navigationState;\n return {\n name: routingRule?.name,\n params: (pathParameters ?? {}) as RouteParams,\n sandboxPath,\n mode,\n provider,\n namespace,\n repository,\n ref,\n };\n};\n\n/**\n * Navigate within the app. Messages the host to update the URL; the host then\n * pushes the new href back, which drives the actual route change.\n *\n * `opts.viewedDocument` (R3-268) optionally declares which WORKING-TREE file\n * this destination renders — a tri-state rider on the navigation event:\n * - omit the option entirely → the host derives the hint from the URL's\n * `files/` suffix convention (the zero-SDK default);\n * - `null` → this view shows no file (clears the highlight — tag pages,\n * search, home views);\n * - a repo-relative path (the CORPUS path under dispatch — only the viewer\n * can map its own key space) → the file explorer highlights it.\n * The hint is highlight-only by contract (it never scrolls, never moves focus\n * or panes, never switches the editor) and is validated host-side for\n * existence — a wrong path degrades to \"no highlight\", never an error. The\n * host remembers declarations per URL, so back/forward reproduces them\n * without re-announcement.\n */\n// R3-268: an app-registered rule mapping a navigation TARGET to its viewed\n// document, consulted by `navigate()` whenever the caller did not declare one\n// explicitly. Registered ONCE (e.g. at boot) so an app whose links all flow\n// through `<Link>`/`navigate` gets correct declarations everywhere without\n// threading an option through every call site. Return `undefined` for \"no\n// declaration\" (the host falls back to the URL convention), `null` for \"this\n// view shows no file\", or a working-tree repo-relative path.\nlet viewedDocumentResolver: ((targetHref: string) => string | null | undefined) | null = null;\n\n/** Register the app's route→viewed-document rule (R3-268); pass `null` to clear. */\nexport const setViewedDocumentResolver = (\n resolver: ((targetHref: string) => string | null | undefined) | null,\n): void => {\n viewedDocumentResolver = resolver;\n};\n\nexport const navigate = (target: string, opts?: { viewedDocument?: string | null }) => {\n console.log(`[Sandbox] Navigating to ${target}`);\n // Explicit option first; else the registered resolver; else nothing on the\n // wire (the host derives from the URL convention). A resolver throw is\n // swallowed to \"no declaration\" — a mapping bug must never break navigation.\n let declared: { viewedDocument: string | null } | Record<string, never> = {};\n if (opts && 'viewedDocument' in opts) {\n declared = { viewedDocument: opts.viewedDocument ?? null };\n } else if (viewedDocumentResolver) {\n try {\n const v = viewedDocumentResolver(target);\n if (v !== undefined) declared = { viewedDocument: v };\n } catch {\n /* no declaration */\n }\n }\n // The scratch for the entry we are LEAVING, gathered synchronously here because\n // this call is the one moment the app knows a navigation is happening (R3-627).\n // The host stamps it on the current entry before pushing the target, and hands it\n // back if the reader ever returns; it never parses it.\n const entryState = takeQueuedEntryState();\n const message: UrlchangePayload = {\n url: target,\n back: false,\n forward: false,\n ...(entryState ? { entryState } : {}),\n ...declared,\n };\n sendMessage(URLCHANGE, message);\n};\n"],"mappings":";AAmDW;AAlDX,SAAS,KAAK,kBAAkB;AAEhC,SAAS,mBAAmB;AAC5B,SAA0B,yBAAyB;AAEnD,SAAS,kBAAkB;AAC3B,SAAS,cAAc,gBAAgB,mBAAmB;AAC1D,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,iBAAwC;AAU1C,MAAM,oBAAoB,CAAC,uBAA+B;AAC/D,QAAM,EAAE,WAAW,iBAAiB,WAAW,IAAI,IAAI,iBAAiB;AACxE,MAAI,qBAAqB,YAAY,oBAAoB,UAAU;AACnE,MAAI,CAAC,eAAe,kBAAkB,GAAG;AACvC,uBAAmB,cAAc,UAAU,WAAW,aAAa,kBAAkB;AAAA,EACvF,OAAO;AACL,uBAAmB,cAAc;AAAA,EACnC;AACA,SAAO,aAAa,WAAW,kBAAkB;AACnD;AAIO,MAAM,mBAAmB,CAC9B,aACA,oBACmC;AACnC,QAAM,EAAE,YAAY,IAAI;AACxB,aAAW,eAAe,YAAY,QAAQ;AAC5C,UAAM,iBAAiB,WAAW,YAAY,SAAS,WAAW;AAClE,QAAI,gBAAgB;AAClB,aAAO,EAA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,EAAE,gBAAgB,EAAE;AAAA,IACtD,QAAQ;AAAA,IAER;AAAA,EACF;AAKA,QAAM,aAAa,qBAAqB;AACxC,QAAM,UAA4B;AAAA,IAChC,KAAK;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;AAAA,IACnC,GAAG;AAAA,EACL;AACA,cAAY,WAAW,OAAO;AAChC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/routing.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { use, useContext } from 'react';\n\nimport { sendMessage } from './sandboxUtils';\nimport { NavigationState, TinkerableContext } from './TinkerableContext';\nimport { RouteParams, RoutingRule, RoutingSpec } from './RoutingSpec';\nimport { matchRoute } from './routeMatch';\nimport { constructUrl, isAbsolutePath, parseTarget } from './urlUtils';\nimport { joinPaths } from './pathUtils';\nimport { takeQueuedEntryState } from './entryState';\nimport { URLCHANGE, type UrlchangePayload } from './generated/protocol';\n\n/** The result of matching a path: the winning {@link RoutingRule} plus its captured params. */\nexport type AppliedRoutingRule = {\n routingRule: RoutingRule;\n pathParameters?: Record<string, string>;\n};\n\n/** Build the full outer href for an in-app target (absolute `sandboxPath` or a\n * path relative to the current route), e.g. for an `href` attribute. */\nexport const useTinkerableLink = (newSandboxLocation: string) => {\n const { outerHref, navigationState: navigation } = use(TinkerableContext);\n let newNavigationState = parseTarget(newSandboxLocation, navigation);\n if (!isAbsolutePath(newSandboxLocation)) {\n newNavigationState.sandboxPath = joinPaths(navigation.sandboxPath, newSandboxLocation);\n } else {\n newNavigationState.sandboxPath = newSandboxLocation;\n }\n return constructUrl(outerHref, newNavigationState);\n};\n\n/** Find the first rule in `routingSpec` whose pattern matches the current\n * `sandboxPath`, returning it with the captured params (or `undefined`). */\nexport const applyRoutingRule = (\n routingSpec: RoutingSpec,\n navigationState: NavigationState,\n): AppliedRoutingRule | undefined => {\n const { sandboxPath } = navigationState;\n for (const routingRule of routingSpec.routes) {\n const pathParameters = matchRoute(routingRule.pattern, sandboxPath);\n if (pathParameters) {\n return { routingRule, pathParameters };\n }\n }\n return undefined;\n};\n\n/** Render a matched rule, passing params to a `component` and falling back to `element`/`reactNode`. */\nexport const renderRoute = (routingRule: RoutingRule, params: RouteParams): ReactNode => {\n if (routingRule.component) {\n const Component = routingRule.component;\n return <Component params={params} />;\n }\n return routingRule.element ?? routingRule.reactNode ?? null;\n};\n\n/** Render the route matched for the current location (set up by `boot`'s route table). */\nexport const Router = () => {\n const context = useContext(TinkerableContext);\n const {\n navigationState: { routingRule, pathParameters },\n } = context;\n if (!routingRule) {\n // TODO: better error\n throw new Error(`No route registered for path ${context.navigationState.sandboxPath}!`);\n }\n\n return renderRoute(routingRule, pathParameters ?? {});\n};\n\n/** Read the current route's matched params (`:name` segments and the `*` wildcard). */\nexport const useRouteParams = <T extends RouteParams = RouteParams>(): T =>\n (use(TinkerableContext).navigationState.pathParameters ?? {}) as T;\n\n/**\n * Read the current route: the matched rule's `name`, its `params`, the app-owned\n * `sandboxPath`, and the read-only platform prefix fields (`mode`, `provider`,\n * `namespace`, `repository`, `ref`) — e.g. to tell `/edit` from `/present`.\n */\nexport const useRoute = () => {\n const { navigationState } = use(TinkerableContext);\n const { routingRule, pathParameters, sandboxPath, mode, provider, namespace, repository, ref } = navigationState;\n return {\n name: routingRule?.name,\n params: (pathParameters ?? {}) as RouteParams,\n sandboxPath,\n mode,\n provider,\n namespace,\n repository,\n ref,\n };\n};\n\n/**\n * Navigate within the app. Messages the host to update the URL; the host then\n * pushes the new href back, which drives the actual route change.\n *\n * `opts.viewedDocument` (R3-268) optionally declares which WORKING-TREE file\n * this destination renders — a tri-state rider on the navigation event:\n * - omit the option entirely → the host derives the hint from the URL's\n * `files/` suffix convention (the zero-SDK default);\n * - `null` → this view shows no file (clears the highlight — tag pages,\n * search, home views);\n * - a repo-relative path (the CORPUS path under dispatch — only the viewer\n * can map its own key space) → the file explorer highlights it.\n * The hint is highlight-only by contract (it never scrolls, never moves focus\n * or panes, never switches the editor) and is validated host-side for\n * existence — a wrong path degrades to \"no highlight\", never an error. The\n * host remembers declarations per URL, so back/forward reproduces them\n * without re-announcement.\n *\n * `opts.replace` (R3-874, APP_CUSTOMIZATION_SPEC §5): `true` asks the host to\n * REPLACE the current history entry instead of pushing — for an app whose URL\n * encodes view state, so re-renders don't flood the reader's Back chain.\n * In-prefix targets only: the host ignores it for a navigation that leaves the\n * app (an app must not erase the entry the user would press Back to reach,\n * G-CUST-6). Absent or `false` keeps the field off the wire entirely.\n */\n// R3-268: an app-registered rule mapping a navigation TARGET to its viewed\n// document, consulted by `navigate()` whenever the caller did not declare one\n// explicitly. Registered ONCE (e.g. at boot) so an app whose links all flow\n// through `<Link>`/`navigate` gets correct declarations everywhere without\n// threading an option through every call site. Return `undefined` for \"no\n// declaration\" (the host falls back to the URL convention), `null` for \"this\n// view shows no file\", or a working-tree repo-relative path.\nlet viewedDocumentResolver: ((targetHref: string) => string | null | undefined) | null = null;\n\n/** Register the app's route→viewed-document rule (R3-268); pass `null` to clear. */\nexport const setViewedDocumentResolver = (\n resolver: ((targetHref: string) => string | null | undefined) | null,\n): void => {\n viewedDocumentResolver = resolver;\n};\n\nexport const navigate = (target: string, opts?: { viewedDocument?: string | null; replace?: boolean }) => {\n console.log(`[Sandbox] Navigating to ${target}`);\n // Explicit option first; else the registered resolver; else nothing on the\n // wire (the host derives from the URL convention). A resolver throw is\n // swallowed to \"no declaration\" — a mapping bug must never break navigation.\n let declared: { viewedDocument: string | null } | Record<string, never> = {};\n if (opts && 'viewedDocument' in opts) {\n declared = { viewedDocument: opts.viewedDocument ?? null };\n } else if (viewedDocumentResolver) {\n try {\n const v = viewedDocumentResolver(target);\n if (v !== undefined) declared = { viewedDocument: v };\n } catch {\n /* no declaration */\n }\n }\n // The scratch for the entry we are LEAVING, gathered synchronously here because\n // this call is the one moment the app knows a navigation is happening (R3-627).\n // The host stamps it on the current entry before pushing the target, and hands it\n // back if the reader ever returns; it never parses it.\n //\n // R3-874: `replace: true` asks the host to REPLACE the current entry instead of\n // pushing (an app whose URL encodes view state would otherwise flood history).\n // The host ignores it for out-of-prefix targets (an app must not erase the entry\n // the user would press Back to reach — G-CUST-6). The message is built as ONE\n // typed value — the wire-shape gate fingerprints the declared UrlchangePayload,\n // and a spread-built union would extract as 'any' and never match (protocol#38).\n const entryState = takeQueuedEntryState();\n const message: UrlchangePayload = {\n url: target,\n back: false,\n forward: false,\n ...(entryState ? { entryState } : {}),\n ...declared,\n ...(opts?.replace === true ? { replace: true as const } : {}),\n };\n sendMessage(URLCHANGE, message);\n};\n"],"mappings":";AAmDW;AAlDX,SAAS,KAAK,kBAAkB;AAEhC,SAAS,mBAAmB;AAC5B,SAA0B,yBAAyB;AAEnD,SAAS,kBAAkB;AAC3B,SAAS,cAAc,gBAAgB,mBAAmB;AAC1D,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,iBAAwC;AAU1C,MAAM,oBAAoB,CAAC,uBAA+B;AAC/D,QAAM,EAAE,WAAW,iBAAiB,WAAW,IAAI,IAAI,iBAAiB;AACxE,MAAI,qBAAqB,YAAY,oBAAoB,UAAU;AACnE,MAAI,CAAC,eAAe,kBAAkB,GAAG;AACvC,uBAAmB,cAAc,UAAU,WAAW,aAAa,kBAAkB;AAAA,EACvF,OAAO;AACL,uBAAmB,cAAc;AAAA,EACnC;AACA,SAAO,aAAa,WAAW,kBAAkB;AACnD;AAIO,MAAM,mBAAmB,CAC9B,aACA,oBACmC;AACnC,QAAM,EAAE,YAAY,IAAI;AACxB,aAAW,eAAe,YAAY,QAAQ;AAC5C,UAAM,iBAAiB,WAAW,YAAY,SAAS,WAAW;AAClE,QAAI,gBAAgB;AAClB,aAAO,EAAE,aAAa,eAAe;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;AAGO,MAAM,cAAc,CAAC,aAA0B,WAAmC;AACvF,MAAI,YAAY,WAAW;AACzB,UAAM,YAAY,YAAY;AAC9B,WAAO,oBA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AS;AAAA,IACT,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;AAAA,IACnC,GAAG;AAAA,IACH,GAAI,MAAM,YAAY,OAAO,EAAE,SAAS,KAAc,IAAI,CAAC;AAAA,EAC7D;AACA,cAAY,WAAW,OAAO;AAChC;","names":[]}
|
package/dist/tasks.cjs
CHANGED
|
@@ -31,6 +31,7 @@ __export(tasks_exports, {
|
|
|
31
31
|
module.exports = __toCommonJS(tasks_exports);
|
|
32
32
|
var import_react = require("react");
|
|
33
33
|
var import_sandboxUtils = require("./sandboxUtils");
|
|
34
|
+
var import_protocolRefusal = require("./protocolRefusal");
|
|
34
35
|
var import_hostTransport = require("./hostTransport");
|
|
35
36
|
var import_protocol = require("./generated/protocol");
|
|
36
37
|
var import_protocolSchemes = require("./protocolSchemes");
|
|
@@ -48,11 +49,7 @@ const capDir = (ref, opts) => ({
|
|
|
48
49
|
});
|
|
49
50
|
const invokeTask = async (task, params = {}) => {
|
|
50
51
|
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_TASK], "invoke", [{ task, params }]);
|
|
51
|
-
|
|
52
|
-
const err = new Error(res?.message ?? `task '${task}' failed`);
|
|
53
|
-
err.code = res?.code ?? "unknown";
|
|
54
|
-
throw err;
|
|
55
|
-
}
|
|
52
|
+
(0, import_protocolRefusal.throwOnRefusal)(res, `task '${task}' failed`);
|
|
56
53
|
return res.data;
|
|
57
54
|
};
|
|
58
55
|
const capturePhoto = (options = {}) => invokeTask("capture-photo", { ...options });
|
package/dist/tasks.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\n//\n// OFF-HOST (plain `vite dev`, node/jsdom tests — no sandbox, no host transport):\n// importing this module is always safe (R3-421 — no subpath may throw at import\n// time), and the surface degrades instead of crashing: `getTaskInput()` /\n// `useTaskInput()` stay `null` forever (you are never a task callee without a\n// host), `completeTask` / `cancelTask` are no-ops, and `invokeTask` rejects with\n// a \"no host transport\" error. Under the @immediately-run/dev-fs substrate the\n// transport resolves but no task ever arrives — same observable behaviour.\n// The no-op is scoped to the ABSENCE of a host: when there IS one, a failed send\n// throws instead of leaving the caller to hang out its deadline.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { transport } from './hostTransport';\nimport { PROTOCOL_TASK, REQUEST_TASK_INPUT, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): FileCap => ({\n $cap: 'file',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): DirCap => ({\n $cap: 'dir',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (missing `task:invoke`, or a\n * file delegation you don't hold), `not-declared` (the task is missing from your\n * `immediately.run.invokes`), `no-such-task` (no app is bound to that contract),\n * `task-cycle`/`task-depth-exceeded`/`task-version-mismatch`, or `invalid-params`\n * (result failed the contract schema). **Read `err.message`** — since R3-418 the host\n * says which capability, which declaration or which param was at fault; the code alone\n * does not distinguish them.\n *\n * Two things must BOTH be true before any invoke is admitted, and they are separate:\n * 1. your `package.json` `immediately.run.invokes` lists the task (else `not-declared`);\n * 2. your app holds the `task:invoke` capability — declare it in\n * `immediately.run.capabilities` so the user can grant it (else `forbidden`).\n * Declaring the invoke does not imply the capability.\n *\n * ── `pick-file`: `roots` is required (SPACES_UI_SPEC §4.1) ───────────────────\n * ```ts\n * import { invokeTask, capDir, requestMount } from '@immediately-run/sdk';\n *\n * const mount = await requestMount(); // the user picks a space\n * // `invokeTask` returns `unknown` — name the result type, or the destructuring\n * // below does not compile.\n * const { root, path } = await invokeTask<{ root: number; path: string }>('pick-file', {\n * // `SandboxMount.id` is optional (absent on the primary repo mount) — fall back to\n * // `path`, which is always present and is what the host resolves against.\n * roots: [capDir({ mountId: mount.id ?? mount.path, relPath: 'boards' }, { mode: 'ro' })],\n * });\n * ```\n * - `roots` is a NON-EMPTY `DirCap[]` of directories you **already hold**. The result\n * names its target as `{ root, path }` where `root` INDEXES `params.roots`, so\n * `invokeTask('pick-file', {})` can never produce a valid result and is rejected.\n * There is no rootless \"pick from any of my spaces\" mode by design: enumerating the\n * user's spaces is the host's powerbox (`requestMount()`), and composing the two —\n * as above — is that flow. See SPACES_UI_SPEC R-SPACES-5/R-SPACES-12.\n * - Each `capDir` is attenuated against your own grant. **`{ mode: 'rw' }` over a space\n * the user granted `ro` is refused `forbidden`** — the commonest failure, because the\n * mount *was* granted and the path *is* inside it. Pass the mode you actually hold;\n * `ro` is right for a plain pick.\n * - The `requestMount()` grant is DURABLE and survives a cancelled pick: the user\n * consented to the mount in host chrome, separately from the pick (SPACES_UI_SPEC §4.1).\n * Reuse it for later picks rather than re-requesting.\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to resolve the task binding.\n */\nexport const invokeTask = async <R = unknown>(task: string, params: Record<string, unknown> = {}): Promise<R> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }])) as\n | { ok: true; data: R }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `task '${task}' failed`) as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n// ── the host-provided CAPTURE contracts (R3-425) ────────────────────────────\n\n/** Bytes captured by the host, as `capturePhoto()` / `captureAudio()` return them.\n * `bytes` is a transferable `ArrayBuffer` — write it to a space, decode it, upload\n * it. You never receive a `MediaStream` or a `MediaStreamTrack`, and that is not an\n * omission: a track cannot be transferred into an app frame at all\n * (`DataCloneError`), and the frame's opaque origin cannot open a device itself\n * (`getUserMedia` throws `SecurityError: Invalid security origin`). */\nexport interface CaptureResult {\n bytes: ArrayBuffer;\n /** e.g. `image/jpeg`, `audio/webm`. Chosen by the HOST, not by you. */\n mimeType: string;\n /** How long the device was open, in ms. */\n durationMs: number;\n}\n\n/** Optional hints for a capture. They deliberately name NOTHING — no device id, no\n * camera index — because the host chooses everything about how the capture is\n * performed. That is what lets the grant be a plain on/off instead of a per-call\n * target list the way `net:fetch` needs. */\nexport interface CaptureOptions {\n /** Which way the camera should face, if the device has a choice. A HINT: the host\n * may ignore it. Ignored for audio. */\n facing?: 'user' | 'environment';\n}\n\n/**\n * Take one photo, or record one audio clip, through the HOST's capture UI\n * (`BROWSER_CAPABILITIES_SPEC` §3 grade 1).\n *\n * The host opens the device at its own origin, draws the viewfinder, and hands you\n * the bytes when the user presses Done. **You are never in the loop while the device\n * is live** — that is the point of the design, not a limitation of it:\n *\n * - The capture UI is drawn by the host, so a user can trust it the way they trust\n * the sign-in dialog. Do not build a lookalike; imitating host chrome is spoofing.\n * - While the device is open the host shows a persistent \"camera on\" / \"microphone\n * on\" indicator in its own chrome, for the whole session. You cannot hide it and\n * should not try to.\n * - If the user cancels, this rejects `cancelled` and **nothing was recorded**. There\n * is no partial result — do not write error handling that hopes for one.\n *\n * ```ts\n * import { capturePhoto, requestMount, openFs } from '@immediately-run/sdk';\n *\n * try {\n * const { bytes, mimeType } = await capturePhoto({ facing: 'environment' });\n * const mount = await requestMount(); // the user picks a space to save into\n * const fs = openFs(mount); // writeFile is a METHOD on the MountFs\n * await fs.mkdir('photos', { recursive: true }); // writeFile does not create parents\n * await fs.writeFile(`photos/latest.${mimeType === 'image/png' ? 'png' : 'jpg'}`, new Uint8Array(bytes));\n * } catch (e) {\n * if ((e as { code?: string }).code === 'cancelled') return; // the user said no\n * throw e;\n * }\n * ```\n * (The extension follows `mimeType` because the HOST chooses the format — do not assume\n * JPEG. `openAppFs()` is the variant that writes to your own app space with no pick.)\n *\n * Two things must BOTH be true, exactly as for any other task:\n * 1. `immediately.run.invokes` lists `capture-photo` (or `capture-audio`);\n * 2. your app holds `task:invoke` **and** `device:camera` (or `device:microphone`)\n * — declare them in `immediately.run.capabilities` so the user can grant them.\n *\n * Rejects with `.code`: `cancelled` (the user dismissed the capture — nothing was\n * recorded), `forbidden` (you lack the capability; `message: 'browser-denied'` means\n * the BROWSER refused immediately.run itself, which your consent cannot fix),\n * `unavailable` (no such device on this machine, or it would not start),\n * `unsupported` (this host cannot capture), `not-declared`, `timeout`.\n *\n * *Zero-platform alternative, still worth knowing:* `<input type=\"file\"\n * accept=\"image/*\" capture=\"environment\">` opens the OS camera from inside the\n * sandbox (file choosers are not permission-gated). It needs no capability and no\n * host support; it also gives you no indicator and no host-drawn surface.\n */\nexport const capturePhoto = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-photo', { ...options });\n\n/** Record one audio clip through the host's capture UI. See {@link capturePhoto} —\n * every rule there applies verbatim, with `device:microphone` and `capture-audio`. */\nexport const captureAudio = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-audio', { ...options });\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\nlet inputListenerRegistered = false;\n\n/**\n * Whether two deliveries carry the same input, compared by their JSON image. The host does\n * not check that params are JSON; the hosts' senders build them from strings and plain\n * objects, for which the image is faithful. A value JSON cannot serialise at all (it\n * throws) is treated as a change; a value JSON writes lossily (a `Map`, a `Blob`) is not\n * told apart, so two inputs differing only there compare equal.\n */\nconst sameTaskInput = (a: TaskInput, b: TaskInput): boolean => {\n if (a.task !== b.task) return false;\n try {\n return JSON.stringify(a.params) === JSON.stringify(b.params);\n } catch {\n return false;\n }\n};\n\n// Register the `task-input` listener IF a host transport is reachable; otherwise do\n// nothing (and let the next call retry — the same pattern as pushChannel's `start`).\n// Split out so both the module-eval attempt below and the first-use call sites share\n// one idempotent path.\n//\n// Registration then pulls the input once with `request-task-input`, the way `mounts`\n// pulls with `request-mounts`: the host answers a callee frame with its current\n// `task-input` and answers nothing to any other frame. So the input arrives whenever\n// this listener comes to exist, and a host send that landed before it is not lost.\n//\n// The poll has its own latch, set only once a send returns. The listener registering\n// proves there is a host, so a send that then throws is a real failure, not the off-host\n// case: it is reported once and tried again on the next read, because a poll that never\n// goes out leaves a callee looking exactly like an app that is not one.\nlet inputPolled = false;\nlet inputPollFailureReported = false;\nconst ensureInputListener = (): void => {\n if (!inputListenerRegistered) {\n try {\n addListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n const next: TaskInput = { task: m.task, params: m.params ?? {} };\n // The host sends the same input several times (at mount, past each compile, and\n // in answer to the poll). A repeat keeps the object the app already has, so an\n // effect keyed on the input does not run again for a value that did not change.\n if (latestInput && sameTaskInput(latestInput, next)) return;\n latestInput = next;\n inputListeners.forEach((l) => l(next));\n });\n } catch {\n return; // off-host: the transport resolver threw — no host to listen on\n }\n inputListenerRegistered = true;\n }\n if (inputPolled) return;\n try {\n sendMessage(REQUEST_TASK_INPUT);\n inputPolled = true;\n } catch (err) {\n if (!inputPollFailureReported) {\n inputPollFailureReported = true;\n console.warn('[immediately.run] the task-input poll could not be sent; it is retried on the next read.', err);\n }\n }\n};\n\n// Register eagerly when a host transport is already present at module evaluation, and\n// lazily on first use otherwise, so importing this module off-host (plain `vite dev`)\n// never throws. Either way the registration polls, so against a host that answers the\n// poll its timing no longer decides whether the input is seen; against an older host the\n// eager registration is still what catches the send made at mount.\nensureInputListener();\n\n/** The task params this app was invoked with, or null if it isn't a task callee.\n * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke\n * this app as a callee. The object changes only when the task or its params change:\n * the host may deliver the same input more than once, and a repeat returns the same\n * object. */\nexport const getTaskInput = (): TaskInput | null => {\n ensureInputListener();\n return latestInput;\n};\n\n/**\n * Is a host transport reachable from this realm at all?\n *\n * The R3-421 off-host no-op below must mean EXACTLY \"there is nobody to answer\" —\n * plain `vite dev`, node, jsdom. A blanket try/catch around the send meant it also\n * swallowed a genuine failure against a REAL host (`DataCloneError` because the\n * result holds a DOM node, a function or a live class instance, being the usual\n * one): the host was then never told the task finished, and the caller's\n * `invokeTask` hung to its deadline with no diagnostic anywhere. Absence is\n * therefore decided BEFORE the send, and the send itself is left to throw.\n */\nconst hostReachable = (): boolean => {\n try {\n transport();\n return true;\n } catch {\n return false; // no injected bundler bus and no §4 discovery global — off-host\n }\n};\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n *\n * `result` must be STRUCTURED-CLONEABLE — it crosses a frame boundary. A DOM node, a\n * function, a class instance with methods, a `MediaStreamTrack`: all `DataCloneError`.\n * **That throws**, deliberately and loudly: the alternative is a caller left hanging to\n * its `invokeTask` deadline while this app believes it answered.\n *\n * Off-host (plain `vite dev` — no host transport) this is a no-op: there is no caller\n * to answer. That case, and only that case, is silent.\n */\nexport const completeTask = (result: unknown): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n // On-host, a failure here is REAL and the caller is waiting on this exact message.\n sendMessage(TASK_COMPLETE, { result });\n};\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`.\n * Off-host (plain `vite dev` — no host transport) this is a no-op; on-host a failed\n * send throws rather than leaving the caller waiting, exactly as {@link completeTask}. */\nexport const cancelTask = (): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n sendMessage(TASK_CANCEL, {});\n};\n\n/** React hook: the task input for this callee, re-rendering when it arrives.\n * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee\n * state rather than waiting on it. A repeated delivery of the same input is not\n * announced: the value's identity changes only when the task or its params do. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete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CAAC;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\n//\n// OFF-HOST (plain `vite dev`, node/jsdom tests — no sandbox, no host transport):\n// importing this module is always safe (R3-421 — no subpath may throw at import\n// time), and the surface degrades instead of crashing: `getTaskInput()` /\n// `useTaskInput()` stay `null` forever (you are never a task callee without a\n// host), `completeTask` / `cancelTask` are no-ops, and `invokeTask` rejects with\n// a \"no host transport\" error. Under the @immediately-run/dev-fs substrate the\n// transport resolves but no task ever arrives — same observable behaviour.\n// The no-op is scoped to the ABSENCE of a host: when there IS one, a failed send\n// throws instead of leaving the caller to hang out its deadline.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { transport } from './hostTransport';\nimport { PROTOCOL_TASK, REQUEST_TASK_INPUT, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): FileCap => ({\n $cap: 'file',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): DirCap => ({\n $cap: 'dir',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (missing `task:invoke`, or a\n * file delegation you don't hold), `not-declared` (the task is missing from your\n * `immediately.run.invokes`), `no-such-task` (no app is bound to that contract),\n * `task-cycle`/`task-depth-exceeded`/`task-version-mismatch`, or `invalid-params`\n * (result failed the contract schema). **Read `err.message`** — since R3-418 the host\n * says which capability, which declaration or which param was at fault; the code alone\n * does not distinguish them.\n *\n * Two things must BOTH be true before any invoke is admitted, and they are separate:\n * 1. your `package.json` `immediately.run.invokes` lists the task (else `not-declared`);\n * 2. your app holds the `task:invoke` capability — declare it in\n * `immediately.run.capabilities` so the user can grant it (else `forbidden`).\n * Declaring the invoke does not imply the capability.\n *\n * ── `pick-file`: `roots` is required (SPACES_UI_SPEC §4.1) ───────────────────\n * ```ts\n * import { invokeTask, capDir, requestMount } from '@immediately-run/sdk';\n *\n * const mount = await requestMount(); // the user picks a space\n * // `invokeTask` returns `unknown` — name the result type, or the destructuring\n * // below does not compile.\n * const { root, path } = await invokeTask<{ root: number; path: string }>('pick-file', {\n * // `SandboxMount.id` is optional (absent on the primary repo mount) — fall back to\n * // `path`, which is always present and is what the host resolves against.\n * roots: [capDir({ mountId: mount.id ?? mount.path, relPath: 'boards' }, { mode: 'ro' })],\n * });\n * ```\n * - `roots` is a NON-EMPTY `DirCap[]` of directories you **already hold**. The result\n * names its target as `{ root, path }` where `root` INDEXES `params.roots`, so\n * `invokeTask('pick-file', {})` can never produce a valid result and is rejected.\n * There is no rootless \"pick from any of my spaces\" mode by design: enumerating the\n * user's spaces is the host's powerbox (`requestMount()`), and composing the two —\n * as above — is that flow. See SPACES_UI_SPEC R-SPACES-5/R-SPACES-12.\n * - Each `capDir` is attenuated against your own grant. **`{ mode: 'rw' }` over a space\n * the user granted `ro` is refused `forbidden`** — the commonest failure, because the\n * mount *was* granted and the path *is* inside it. Pass the mode you actually hold;\n * `ro` is right for a plain pick.\n * - The `requestMount()` grant is DURABLE and survives a cancelled pick: the user\n * consented to the mount in host chrome, separately from the pick (SPACES_UI_SPEC §4.1).\n * Reuse it for later picks rather than re-requesting.\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to resolve the task binding.\n */\nexport const invokeTask = async <R = unknown>(task: string, params: Record<string, unknown> = {}): Promise<R> => {\n const res = await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }]);\n // The one refusal unwrap (R6, R3-816): an absent/malformed reply and a coded\n // refusal both throw, the task named in the fallback message.\n throwOnRefusal(res, `task '${task}' failed`);\n return res.data as R;\n};\n\n// ── the host-provided CAPTURE contracts (R3-425) ────────────────────────────\n\n/** Bytes captured by the host, as `capturePhoto()` / `captureAudio()` return them.\n * `bytes` is a transferable `ArrayBuffer` — write it to a space, decode it, upload\n * it. You never receive a `MediaStream` or a `MediaStreamTrack`, and that is not an\n * omission: a track cannot be transferred into an app frame at all\n * (`DataCloneError`), and the frame's opaque origin cannot open a device itself\n * (`getUserMedia` throws `SecurityError: Invalid security origin`). */\nexport interface CaptureResult {\n bytes: ArrayBuffer;\n /** e.g. `image/jpeg`, `audio/webm`. Chosen by the HOST, not by you. */\n mimeType: string;\n /** How long the device was open, in ms. */\n durationMs: number;\n}\n\n/** Optional hints for a capture. They deliberately name NOTHING — no device id, no\n * camera index — because the host chooses everything about how the capture is\n * performed. That is what lets the grant be a plain on/off instead of a per-call\n * target list the way `net:fetch` needs. */\nexport interface CaptureOptions {\n /** Which way the camera should face, if the device has a choice. A HINT: the host\n * may ignore it. Ignored for audio. */\n facing?: 'user' | 'environment';\n}\n\n/**\n * Take one photo, or record one audio clip, through the HOST's capture UI\n * (`BROWSER_CAPABILITIES_SPEC` §3 grade 1).\n *\n * The host opens the device at its own origin, draws the viewfinder, and hands you\n * the bytes when the user presses Done. **You are never in the loop while the device\n * is live** — that is the point of the design, not a limitation of it:\n *\n * - The capture UI is drawn by the host, so a user can trust it the way they trust\n * the sign-in dialog. Do not build a lookalike; imitating host chrome is spoofing.\n * - While the device is open the host shows a persistent \"camera on\" / \"microphone\n * on\" indicator in its own chrome, for the whole session. You cannot hide it and\n * should not try to.\n * - If the user cancels, this rejects `cancelled` and **nothing was recorded**. There\n * is no partial result — do not write error handling that hopes for one.\n *\n * ```ts\n * import { capturePhoto, requestMount, openFs } from '@immediately-run/sdk';\n *\n * try {\n * const { bytes, mimeType } = await capturePhoto({ facing: 'environment' });\n * const mount = await requestMount(); // the user picks a space to save into\n * const fs = openFs(mount); // writeFile is a METHOD on the MountFs\n * await fs.mkdir('photos', { recursive: true }); // writeFile does not create parents\n * await fs.writeFile(`photos/latest.${mimeType === 'image/png' ? 'png' : 'jpg'}`, new Uint8Array(bytes));\n * } catch (e) {\n * if ((e as { code?: string }).code === 'cancelled') return; // the user said no\n * throw e;\n * }\n * ```\n * (The extension follows `mimeType` because the HOST chooses the format — do not assume\n * JPEG. `openAppFs()` is the variant that writes to your own app space with no pick.)\n *\n * Two things must BOTH be true, exactly as for any other task:\n * 1. `immediately.run.invokes` lists `capture-photo` (or `capture-audio`);\n * 2. your app holds `task:invoke` **and** `device:camera` (or `device:microphone`)\n * — declare them in `immediately.run.capabilities` so the user can grant them.\n *\n * Rejects with `.code`: `cancelled` (the user dismissed the capture — nothing was\n * recorded), `forbidden` (you lack the capability; `message: 'browser-denied'` means\n * the BROWSER refused immediately.run itself, which your consent cannot fix),\n * `unavailable` (no such device on this machine, or it would not start),\n * `unsupported` (this host cannot capture), `not-declared`, `timeout`.\n *\n * *Zero-platform alternative, still worth knowing:* `<input type=\"file\"\n * accept=\"image/*\" capture=\"environment\">` opens the OS camera from inside the\n * sandbox (file choosers are not permission-gated). It needs no capability and no\n * host support; it also gives you no indicator and no host-drawn surface.\n */\nexport const capturePhoto = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-photo', { ...options });\n\n/** Record one audio clip through the host's capture UI. See {@link capturePhoto} —\n * every rule there applies verbatim, with `device:microphone` and `capture-audio`. */\nexport const captureAudio = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-audio', { ...options });\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\nlet inputListenerRegistered = false;\n\n/**\n * Whether two deliveries carry the same input, compared by their JSON image. The host does\n * not check that params are JSON; the hosts' senders build them from strings and plain\n * objects, for which the image is faithful. A value JSON cannot serialise at all (it\n * throws) is treated as a change; a value JSON writes lossily (a `Map`, a `Blob`) is not\n * told apart, so two inputs differing only there compare equal.\n */\nconst sameTaskInput = (a: TaskInput, b: TaskInput): boolean => {\n if (a.task !== b.task) return false;\n try {\n return JSON.stringify(a.params) === JSON.stringify(b.params);\n } catch {\n return false;\n }\n};\n\n// Register the `task-input` listener IF a host transport is reachable; otherwise do\n// nothing (and let the next call retry — the same pattern as pushChannel's `start`).\n// Split out so both the module-eval attempt below and the first-use call sites share\n// one idempotent path.\n//\n// Registration then pulls the input once with `request-task-input`, the way `mounts`\n// pulls with `request-mounts`: the host answers a callee frame with its current\n// `task-input` and answers nothing to any other frame. So the input arrives whenever\n// this listener comes to exist, and a host send that landed before it is not lost.\n//\n// The poll has its own latch, set only once a send returns. The listener registering\n// proves there is a host, so a send that then throws is a real failure, not the off-host\n// case: it is reported once and tried again on the next read, because a poll that never\n// goes out leaves a callee looking exactly like an app that is not one.\nlet inputPolled = false;\nlet inputPollFailureReported = false;\nconst ensureInputListener = (): void => {\n if (!inputListenerRegistered) {\n try {\n addListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n const next: TaskInput = { task: m.task, params: m.params ?? {} };\n // The host sends the same input several times (at mount, past each compile, and\n // in answer to the poll). A repeat keeps the object the app already has, so an\n // effect keyed on the input does not run again for a value that did not change.\n if (latestInput && sameTaskInput(latestInput, next)) return;\n latestInput = next;\n inputListeners.forEach((l) => l(next));\n });\n } catch {\n return; // off-host: the transport resolver threw — no host to listen on\n }\n inputListenerRegistered = true;\n }\n if (inputPolled) return;\n try {\n sendMessage(REQUEST_TASK_INPUT);\n inputPolled = true;\n } catch (err) {\n if (!inputPollFailureReported) {\n inputPollFailureReported = true;\n console.warn('[immediately.run] the task-input poll could not be sent; it is retried on the next read.', err);\n }\n }\n};\n\n// Register eagerly when a host transport is already present at module evaluation, and\n// lazily on first use otherwise, so importing this module off-host (plain `vite dev`)\n// never throws. Either way the registration polls, so against a host that answers the\n// poll its timing no longer decides whether the input is seen; against an older host the\n// eager registration is still what catches the send made at mount.\nensureInputListener();\n\n/** The task params this app was invoked with, or null if it isn't a task callee.\n * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke\n * this app as a callee. The object changes only when the task or its params change:\n * the host may deliver the same input more than once, and a repeat returns the same\n * object. */\nexport const getTaskInput = (): TaskInput | null => {\n ensureInputListener();\n return latestInput;\n};\n\n/**\n * Is a host transport reachable from this realm at all?\n *\n * The R3-421 off-host no-op below must mean EXACTLY \"there is nobody to answer\" —\n * plain `vite dev`, node, jsdom. A blanket try/catch around the send meant it also\n * swallowed a genuine failure against a REAL host (`DataCloneError` because the\n * result holds a DOM node, a function or a live class instance, being the usual\n * one): the host was then never told the task finished, and the caller's\n * `invokeTask` hung to its deadline with no diagnostic anywhere. Absence is\n * therefore decided BEFORE the send, and the send itself is left to throw.\n */\nconst hostReachable = (): boolean => {\n try {\n transport();\n return true;\n } catch {\n return false; // no injected bundler bus and no §4 discovery global — off-host\n }\n};\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n *\n * `result` must be STRUCTURED-CLONEABLE — it crosses a frame boundary. A DOM node, a\n * function, a class instance with methods, a `MediaStreamTrack`: all `DataCloneError`.\n * **That throws**, deliberately and loudly: the alternative is a caller left hanging to\n * its `invokeTask` deadline while this app believes it answered.\n *\n * Off-host (plain `vite dev` — no host transport) this is a no-op: there is no caller\n * to answer. That case, and only that case, is silent.\n */\nexport const completeTask = (result: unknown): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n // On-host, a failure here is REAL and the caller is waiting on this exact message.\n sendMessage(TASK_COMPLETE, { result });\n};\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`.\n * Off-host (plain `vite dev` — no host transport) this is a no-op; on-host a failed\n * send throws rather than leaving the caller waiting, exactly as {@link completeTask}. */\nexport const cancelTask = (): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n sendMessage(TASK_CANCEL, {});\n};\n\n/** React hook: the task input for this callee, re-rendering when it arrives.\n * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee\n * state rather than waiting on it. A repeated delivery of the same input is not\n * announced: the value's identity changes only when the task or its params do. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete(l);\n };\n }, []);\n return input;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,mBAAoC;AACpC,0BAA0D;AAC1D,6BAA+B;AAC/B,2BAA0B;AAC1B,sBAA0F;AAC1F,6BAAwB;AAmBjB,MAAM,UAAU,CAAC,KAA2C,UAA0C;AAAA,EAC3G,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAoBO,MAAM,SAAS,CAAC,KAA2C,UAAyC;AAAA,EACzG,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAiDO,MAAM,aAAa,OAAoB,MAAc,SAAkC,CAAC,MAAkB;AAC/G,QAAM,MAAM,UAAM,qCAAgB,+BAAQ,6BAAa,GAAG,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,CAAC;AAGtF,6CAAe,KAAK,SAAS,IAAI,UAAU;AAC3C,SAAO,IAAI;AACb;AA6EO,MAAM,eAAe,CAAC,UAA0B,CAAC,MACtD,WAA0B,iBAAiB,EAAE,GAAG,QAAQ,CAAC;AAIpD,MAAM,eAAe,CAAC,UAA0B,CAAC,MACtD,WAA0B,iBAAiB,EAAE,GAAG,QAAQ,CAAC;AAU3D,IAAI,cAAgC;AACpC,MAAM,iBAAiB,oBAAI,IAA4B;AACvD,IAAI,0BAA0B;AA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,QAAI,uBAA2B,YAAY;AACjE,8BAAU,MAAM;AACd,UAAM,IAAI,CAAC,MAAiB,SAAS,CAAC;AACtC,mBAAe,IAAI,CAAC;AACpB,QAAI,YAAa,UAAS,WAAW;AACrC,WAAO,MAAM;AACX,qBAAe,OAAO,CAAC;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO;AACT;","names":[]}
|
package/dist/tasks.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
2
|
import { useEffect, useState } from "react";
|
|
3
3
|
import { protocolRequest, sendMessage, addListener } from "./sandboxUtils.js";
|
|
4
|
+
import { throwOnRefusal } from "./protocolRefusal.js";
|
|
4
5
|
import { transport } from "./hostTransport.js";
|
|
5
6
|
import { PROTOCOL_TASK, REQUEST_TASK_INPUT, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from "./generated/protocol.js";
|
|
6
7
|
import { SCHEMES } from "./protocolSchemes.js";
|
|
@@ -18,11 +19,7 @@ const capDir = (ref, opts) => ({
|
|
|
18
19
|
});
|
|
19
20
|
const invokeTask = async (task, params = {}) => {
|
|
20
21
|
const res = await protocolRequest(SCHEMES[PROTOCOL_TASK], "invoke", [{ task, params }]);
|
|
21
|
-
|
|
22
|
-
const err = new Error(res?.message ?? `task '${task}' failed`);
|
|
23
|
-
err.code = res?.code ?? "unknown";
|
|
24
|
-
throw err;
|
|
25
|
-
}
|
|
22
|
+
throwOnRefusal(res, `task '${task}' failed`);
|
|
26
23
|
return res.data;
|
|
27
24
|
};
|
|
28
25
|
const capturePhoto = (options = {}) => invokeTask("capture-photo", { ...options });
|
package/dist/tasks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\n//\n// OFF-HOST (plain `vite dev`, node/jsdom tests — no sandbox, no host transport):\n// importing this module is always safe (R3-421 — no subpath may throw at import\n// time), and the surface degrades instead of crashing: `getTaskInput()` /\n// `useTaskInput()` stay `null` forever (you are never a task callee without a\n// host), `completeTask` / `cancelTask` are no-ops, and `invokeTask` rejects with\n// a \"no host transport\" error. Under the @immediately-run/dev-fs substrate the\n// transport resolves but no task ever arrives — same observable behaviour.\n// The no-op is scoped to the ABSENCE of a host: when there IS one, a failed send\n// throws instead of leaving the caller to hang out its deadline.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { transport } from './hostTransport';\nimport { PROTOCOL_TASK, REQUEST_TASK_INPUT, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): FileCap => ({\n $cap: 'file',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): DirCap => ({\n $cap: 'dir',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (missing `task:invoke`, or a\n * file delegation you don't hold), `not-declared` (the task is missing from your\n * `immediately.run.invokes`), `no-such-task` (no app is bound to that contract),\n * `task-cycle`/`task-depth-exceeded`/`task-version-mismatch`, or `invalid-params`\n * (result failed the contract schema). **Read `err.message`** — since R3-418 the host\n * says which capability, which declaration or which param was at fault; the code alone\n * does not distinguish them.\n *\n * Two things must BOTH be true before any invoke is admitted, and they are separate:\n * 1. your `package.json` `immediately.run.invokes` lists the task (else `not-declared`);\n * 2. your app holds the `task:invoke` capability — declare it in\n * `immediately.run.capabilities` so the user can grant it (else `forbidden`).\n * Declaring the invoke does not imply the capability.\n *\n * ── `pick-file`: `roots` is required (SPACES_UI_SPEC §4.1) ───────────────────\n * ```ts\n * import { invokeTask, capDir, requestMount } from '@immediately-run/sdk';\n *\n * const mount = await requestMount(); // the user picks a space\n * // `invokeTask` returns `unknown` — name the result type, or the destructuring\n * // below does not compile.\n * const { root, path } = await invokeTask<{ root: number; path: string }>('pick-file', {\n * // `SandboxMount.id` is optional (absent on the primary repo mount) — fall back to\n * // `path`, which is always present and is what the host resolves against.\n * roots: [capDir({ mountId: mount.id ?? mount.path, relPath: 'boards' }, { mode: 'ro' })],\n * });\n * ```\n * - `roots` is a NON-EMPTY `DirCap[]` of directories you **already hold**. The result\n * names its target as `{ root, path }` where `root` INDEXES `params.roots`, so\n * `invokeTask('pick-file', {})` can never produce a valid result and is rejected.\n * There is no rootless \"pick from any of my spaces\" mode by design: enumerating the\n * user's spaces is the host's powerbox (`requestMount()`), and composing the two —\n * as above — is that flow. See SPACES_UI_SPEC R-SPACES-5/R-SPACES-12.\n * - Each `capDir` is attenuated against your own grant. **`{ mode: 'rw' }` over a space\n * the user granted `ro` is refused `forbidden`** — the commonest failure, because the\n * mount *was* granted and the path *is* inside it. Pass the mode you actually hold;\n * `ro` is right for a plain pick.\n * - The `requestMount()` grant is DURABLE and survives a cancelled pick: the user\n * consented to the mount in host chrome, separately from the pick (SPACES_UI_SPEC §4.1).\n * Reuse it for later picks rather than re-requesting.\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to resolve the task binding.\n */\nexport const invokeTask = async <R = unknown>(task: string, params: Record<string, unknown> = {}): Promise<R> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }])) as\n | { ok: true; data: R }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `task '${task}' failed`) as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n// ── the host-provided CAPTURE contracts (R3-425) ────────────────────────────\n\n/** Bytes captured by the host, as `capturePhoto()` / `captureAudio()` return them.\n * `bytes` is a transferable `ArrayBuffer` — write it to a space, decode it, upload\n * it. You never receive a `MediaStream` or a `MediaStreamTrack`, and that is not an\n * omission: a track cannot be transferred into an app frame at all\n * (`DataCloneError`), and the frame's opaque origin cannot open a device itself\n * (`getUserMedia` throws `SecurityError: Invalid security origin`). */\nexport interface CaptureResult {\n bytes: ArrayBuffer;\n /** e.g. `image/jpeg`, `audio/webm`. Chosen by the HOST, not by you. */\n mimeType: string;\n /** How long the device was open, in ms. */\n durationMs: number;\n}\n\n/** Optional hints for a capture. They deliberately name NOTHING — no device id, no\n * camera index — because the host chooses everything about how the capture is\n * performed. That is what lets the grant be a plain on/off instead of a per-call\n * target list the way `net:fetch` needs. */\nexport interface CaptureOptions {\n /** Which way the camera should face, if the device has a choice. A HINT: the host\n * may ignore it. Ignored for audio. */\n facing?: 'user' | 'environment';\n}\n\n/**\n * Take one photo, or record one audio clip, through the HOST's capture UI\n * (`BROWSER_CAPABILITIES_SPEC` §3 grade 1).\n *\n * The host opens the device at its own origin, draws the viewfinder, and hands you\n * the bytes when the user presses Done. **You are never in the loop while the device\n * is live** — that is the point of the design, not a limitation of it:\n *\n * - The capture UI is drawn by the host, so a user can trust it the way they trust\n * the sign-in dialog. Do not build a lookalike; imitating host chrome is spoofing.\n * - While the device is open the host shows a persistent \"camera on\" / \"microphone\n * on\" indicator in its own chrome, for the whole session. You cannot hide it and\n * should not try to.\n * - If the user cancels, this rejects `cancelled` and **nothing was recorded**. There\n * is no partial result — do not write error handling that hopes for one.\n *\n * ```ts\n * import { capturePhoto, requestMount, openFs } from '@immediately-run/sdk';\n *\n * try {\n * const { bytes, mimeType } = await capturePhoto({ facing: 'environment' });\n * const mount = await requestMount(); // the user picks a space to save into\n * const fs = openFs(mount); // writeFile is a METHOD on the MountFs\n * await fs.mkdir('photos', { recursive: true }); // writeFile does not create parents\n * await fs.writeFile(`photos/latest.${mimeType === 'image/png' ? 'png' : 'jpg'}`, new Uint8Array(bytes));\n * } catch (e) {\n * if ((e as { code?: string }).code === 'cancelled') return; // the user said no\n * throw e;\n * }\n * ```\n * (The extension follows `mimeType` because the HOST chooses the format — do not assume\n * JPEG. `openAppFs()` is the variant that writes to your own app space with no pick.)\n *\n * Two things must BOTH be true, exactly as for any other task:\n * 1. `immediately.run.invokes` lists `capture-photo` (or `capture-audio`);\n * 2. your app holds `task:invoke` **and** `device:camera` (or `device:microphone`)\n * — declare them in `immediately.run.capabilities` so the user can grant them.\n *\n * Rejects with `.code`: `cancelled` (the user dismissed the capture — nothing was\n * recorded), `forbidden` (you lack the capability; `message: 'browser-denied'` means\n * the BROWSER refused immediately.run itself, which your consent cannot fix),\n * `unavailable` (no such device on this machine, or it would not start),\n * `unsupported` (this host cannot capture), `not-declared`, `timeout`.\n *\n * *Zero-platform alternative, still worth knowing:* `<input type=\"file\"\n * accept=\"image/*\" capture=\"environment\">` opens the OS camera from inside the\n * sandbox (file choosers are not permission-gated). It needs no capability and no\n * host support; it also gives you no indicator and no host-drawn surface.\n */\nexport const capturePhoto = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-photo', { ...options });\n\n/** Record one audio clip through the host's capture UI. See {@link capturePhoto} —\n * every rule there applies verbatim, with `device:microphone` and `capture-audio`. */\nexport const captureAudio = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-audio', { ...options });\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\nlet inputListenerRegistered = false;\n\n/**\n * Whether two deliveries carry the same input, compared by their JSON image. The host does\n * not check that params are JSON; the hosts' senders build them from strings and plain\n * objects, for which the image is faithful. A value JSON cannot serialise at all (it\n * throws) is treated as a change; a value JSON writes lossily (a `Map`, a `Blob`) is not\n * told apart, so two inputs differing only there compare equal.\n */\nconst sameTaskInput = (a: TaskInput, b: TaskInput): boolean => {\n if (a.task !== b.task) return false;\n try {\n return JSON.stringify(a.params) === JSON.stringify(b.params);\n } catch {\n return false;\n }\n};\n\n// Register the `task-input` listener IF a host transport is reachable; otherwise do\n// nothing (and let the next call retry — the same pattern as pushChannel's `start`).\n// Split out so both the module-eval attempt below and the first-use call sites share\n// one idempotent path.\n//\n// Registration then pulls the input once with `request-task-input`, the way `mounts`\n// pulls with `request-mounts`: the host answers a callee frame with its current\n// `task-input` and answers nothing to any other frame. So the input arrives whenever\n// this listener comes to exist, and a host send that landed before it is not lost.\n//\n// The poll has its own latch, set only once a send returns. The listener registering\n// proves there is a host, so a send that then throws is a real failure, not the off-host\n// case: it is reported once and tried again on the next read, because a poll that never\n// goes out leaves a callee looking exactly like an app that is not one.\nlet inputPolled = false;\nlet inputPollFailureReported = false;\nconst ensureInputListener = (): void => {\n if (!inputListenerRegistered) {\n try {\n addListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n const next: TaskInput = { task: m.task, params: m.params ?? {} };\n // The host sends the same input several times (at mount, past each compile, and\n // in answer to the poll). A repeat keeps the object the app already has, so an\n // effect keyed on the input does not run again for a value that did not change.\n if (latestInput && sameTaskInput(latestInput, next)) return;\n latestInput = next;\n inputListeners.forEach((l) => l(next));\n });\n } catch {\n return; // off-host: the transport resolver threw — no host to listen on\n }\n inputListenerRegistered = true;\n }\n if (inputPolled) return;\n try {\n sendMessage(REQUEST_TASK_INPUT);\n inputPolled = true;\n } catch (err) {\n if (!inputPollFailureReported) {\n inputPollFailureReported = true;\n console.warn('[immediately.run] the task-input poll could not be sent; it is retried on the next read.', err);\n }\n }\n};\n\n// Register eagerly when a host transport is already present at module evaluation, and\n// lazily on first use otherwise, so importing this module off-host (plain `vite dev`)\n// never throws. Either way the registration polls, so against a host that answers the\n// poll its timing no longer decides whether the input is seen; against an older host the\n// eager registration is still what catches the send made at mount.\nensureInputListener();\n\n/** The task params this app was invoked with, or null if it isn't a task callee.\n * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke\n * this app as a callee. The object changes only when the task or its params change:\n * the host may deliver the same input more than once, and a repeat returns the same\n * object. */\nexport const getTaskInput = (): TaskInput | null => {\n ensureInputListener();\n return latestInput;\n};\n\n/**\n * Is a host transport reachable from this realm at all?\n *\n * The R3-421 off-host no-op below must mean EXACTLY \"there is nobody to answer\" —\n * plain `vite dev`, node, jsdom. A blanket try/catch around the send meant it also\n * swallowed a genuine failure against a REAL host (`DataCloneError` because the\n * result holds a DOM node, a function or a live class instance, being the usual\n * one): the host was then never told the task finished, and the caller's\n * `invokeTask` hung to its deadline with no diagnostic anywhere. Absence is\n * therefore decided BEFORE the send, and the send itself is left to throw.\n */\nconst hostReachable = (): boolean => {\n try {\n transport();\n return true;\n } catch {\n return false; // no injected bundler bus and no §4 discovery global — off-host\n }\n};\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n *\n * `result` must be STRUCTURED-CLONEABLE — it crosses a frame boundary. A DOM node, a\n * function, a class instance with methods, a `MediaStreamTrack`: all `DataCloneError`.\n * **That throws**, deliberately and loudly: the alternative is a caller left hanging to\n * its `invokeTask` deadline while this app believes it answered.\n *\n * Off-host (plain `vite dev` — no host transport) this is a no-op: there is no caller\n * to answer. That case, and only that case, is silent.\n */\nexport const completeTask = (result: unknown): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n // On-host, a failure here is REAL and the caller is waiting on this exact message.\n sendMessage(TASK_COMPLETE, { result });\n};\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`.\n * Off-host (plain `vite dev` — no host transport) this is a no-op; on-host a failed\n * send throws rather than leaving the caller waiting, exactly as {@link completeTask}. */\nexport const cancelTask = (): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n sendMessage(TASK_CANCEL, {});\n};\n\n/** React hook: the task input for this callee, re-rendering when it arrives.\n * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee\n * state rather than waiting on it. A repeated delivery of the same input is not\n * announced: the value's identity changes only when the task or its params do. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete(l);\n };\n }, []);\n return input;\n};\n"],"mappings":";AAqBA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,iBAAiB;AAC1B,SAAS,eAAe,oBAAoB,aAAa,eAAe,kBAAkB;AAC1F,SAAS,eAAe;AAmBjB,MAAM,UAAU,CAAC,KAA2C,UAA0C;AAAA,EAC3G,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAoBO,MAAM,SAAS,CAAC,KAA2C,UAAyC;AAAA,EACzG,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAiDO,MAAM,aAAa,OAAoB,MAAc,SAAkC,CAAC,MAAkB;AAC/G,QAAM,MAAO,MAAM,gBAAgB,QAAQ,aAAa,GAAG,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,CAAC;AAIvF,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,SAAS,IAAI,UAAU;AAC7D,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACA,SAAO,IAAI;AACb;AA6EO,MAAM,eAAe,CAAC,UAA0B,CAAC,MACtD,WAA0B,iBAAiB,EAAE,GAAG,QAAQ,CAAC;AAIpD,MAAM,eAAe,CAAC,UAA0B,CAAC,MACtD,WAA0B,iBAAiB,EAAE,GAAG,QAAQ,CAAC;AAU3D,IAAI,cAAgC;AACpC,MAAM,iBAAiB,oBAAI,IAA4B;AACvD,IAAI,0BAA0B;AAS9B,MAAM,gBAAgB,CAAC,GAAc,MAA0B;AAC7D,MAAI,EAAE,SAAS,EAAE,KAAM,QAAO;AAC9B,MAAI;AACF,WAAO,KAAK,UAAU,EAAE,MAAM,MA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C,WAAO,MAAM;AACX,qBAAe,OAAO,CAAC;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\n//\n// OFF-HOST (plain `vite dev`, node/jsdom tests — no sandbox, no host transport):\n// importing this module is always safe (R3-421 — no subpath may throw at import\n// time), and the surface degrades instead of crashing: `getTaskInput()` /\n// `useTaskInput()` stay `null` forever (you are never a task callee without a\n// host), `completeTask` / `cancelTask` are no-ops, and `invokeTask` rejects with\n// a \"no host transport\" error. Under the @immediately-run/dev-fs substrate the\n// transport resolves but no task ever arrives — same observable behaviour.\n// The no-op is scoped to the ABSENCE of a host: when there IS one, a failed send\n// throws instead of leaving the caller to hang out its deadline.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { transport } from './hostTransport';\nimport { PROTOCOL_TASK, REQUEST_TASK_INPUT, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): FileCap => ({\n $cap: 'file',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): DirCap => ({\n $cap: 'dir',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (missing `task:invoke`, or a\n * file delegation you don't hold), `not-declared` (the task is missing from your\n * `immediately.run.invokes`), `no-such-task` (no app is bound to that contract),\n * `task-cycle`/`task-depth-exceeded`/`task-version-mismatch`, or `invalid-params`\n * (result failed the contract schema). **Read `err.message`** — since R3-418 the host\n * says which capability, which declaration or which param was at fault; the code alone\n * does not distinguish them.\n *\n * Two things must BOTH be true before any invoke is admitted, and they are separate:\n * 1. your `package.json` `immediately.run.invokes` lists the task (else `not-declared`);\n * 2. your app holds the `task:invoke` capability — declare it in\n * `immediately.run.capabilities` so the user can grant it (else `forbidden`).\n * Declaring the invoke does not imply the capability.\n *\n * ── `pick-file`: `roots` is required (SPACES_UI_SPEC §4.1) ───────────────────\n * ```ts\n * import { invokeTask, capDir, requestMount } from '@immediately-run/sdk';\n *\n * const mount = await requestMount(); // the user picks a space\n * // `invokeTask` returns `unknown` — name the result type, or the destructuring\n * // below does not compile.\n * const { root, path } = await invokeTask<{ root: number; path: string }>('pick-file', {\n * // `SandboxMount.id` is optional (absent on the primary repo mount) — fall back to\n * // `path`, which is always present and is what the host resolves against.\n * roots: [capDir({ mountId: mount.id ?? mount.path, relPath: 'boards' }, { mode: 'ro' })],\n * });\n * ```\n * - `roots` is a NON-EMPTY `DirCap[]` of directories you **already hold**. The result\n * names its target as `{ root, path }` where `root` INDEXES `params.roots`, so\n * `invokeTask('pick-file', {})` can never produce a valid result and is rejected.\n * There is no rootless \"pick from any of my spaces\" mode by design: enumerating the\n * user's spaces is the host's powerbox (`requestMount()`), and composing the two —\n * as above — is that flow. See SPACES_UI_SPEC R-SPACES-5/R-SPACES-12.\n * - Each `capDir` is attenuated against your own grant. **`{ mode: 'rw' }` over a space\n * the user granted `ro` is refused `forbidden`** — the commonest failure, because the\n * mount *was* granted and the path *is* inside it. Pass the mode you actually hold;\n * `ro` is right for a plain pick.\n * - The `requestMount()` grant is DURABLE and survives a cancelled pick: the user\n * consented to the mount in host chrome, separately from the pick (SPACES_UI_SPEC §4.1).\n * Reuse it for later picks rather than re-requesting.\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to resolve the task binding.\n */\nexport const invokeTask = async <R = unknown>(task: string, params: Record<string, unknown> = {}): Promise<R> => {\n const res = await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }]);\n // The one refusal unwrap (R6, R3-816): an absent/malformed reply and a coded\n // refusal both throw, the task named in the fallback message.\n throwOnRefusal(res, `task '${task}' failed`);\n return res.data as R;\n};\n\n// ── the host-provided CAPTURE contracts (R3-425) ────────────────────────────\n\n/** Bytes captured by the host, as `capturePhoto()` / `captureAudio()` return them.\n * `bytes` is a transferable `ArrayBuffer` — write it to a space, decode it, upload\n * it. You never receive a `MediaStream` or a `MediaStreamTrack`, and that is not an\n * omission: a track cannot be transferred into an app frame at all\n * (`DataCloneError`), and the frame's opaque origin cannot open a device itself\n * (`getUserMedia` throws `SecurityError: Invalid security origin`). */\nexport interface CaptureResult {\n bytes: ArrayBuffer;\n /** e.g. `image/jpeg`, `audio/webm`. Chosen by the HOST, not by you. */\n mimeType: string;\n /** How long the device was open, in ms. */\n durationMs: number;\n}\n\n/** Optional hints for a capture. They deliberately name NOTHING — no device id, no\n * camera index — because the host chooses everything about how the capture is\n * performed. That is what lets the grant be a plain on/off instead of a per-call\n * target list the way `net:fetch` needs. */\nexport interface CaptureOptions {\n /** Which way the camera should face, if the device has a choice. A HINT: the host\n * may ignore it. Ignored for audio. */\n facing?: 'user' | 'environment';\n}\n\n/**\n * Take one photo, or record one audio clip, through the HOST's capture UI\n * (`BROWSER_CAPABILITIES_SPEC` §3 grade 1).\n *\n * The host opens the device at its own origin, draws the viewfinder, and hands you\n * the bytes when the user presses Done. **You are never in the loop while the device\n * is live** — that is the point of the design, not a limitation of it:\n *\n * - The capture UI is drawn by the host, so a user can trust it the way they trust\n * the sign-in dialog. Do not build a lookalike; imitating host chrome is spoofing.\n * - While the device is open the host shows a persistent \"camera on\" / \"microphone\n * on\" indicator in its own chrome, for the whole session. You cannot hide it and\n * should not try to.\n * - If the user cancels, this rejects `cancelled` and **nothing was recorded**. There\n * is no partial result — do not write error handling that hopes for one.\n *\n * ```ts\n * import { capturePhoto, requestMount, openFs } from '@immediately-run/sdk';\n *\n * try {\n * const { bytes, mimeType } = await capturePhoto({ facing: 'environment' });\n * const mount = await requestMount(); // the user picks a space to save into\n * const fs = openFs(mount); // writeFile is a METHOD on the MountFs\n * await fs.mkdir('photos', { recursive: true }); // writeFile does not create parents\n * await fs.writeFile(`photos/latest.${mimeType === 'image/png' ? 'png' : 'jpg'}`, new Uint8Array(bytes));\n * } catch (e) {\n * if ((e as { code?: string }).code === 'cancelled') return; // the user said no\n * throw e;\n * }\n * ```\n * (The extension follows `mimeType` because the HOST chooses the format — do not assume\n * JPEG. `openAppFs()` is the variant that writes to your own app space with no pick.)\n *\n * Two things must BOTH be true, exactly as for any other task:\n * 1. `immediately.run.invokes` lists `capture-photo` (or `capture-audio`);\n * 2. your app holds `task:invoke` **and** `device:camera` (or `device:microphone`)\n * — declare them in `immediately.run.capabilities` so the user can grant them.\n *\n * Rejects with `.code`: `cancelled` (the user dismissed the capture — nothing was\n * recorded), `forbidden` (you lack the capability; `message: 'browser-denied'` means\n * the BROWSER refused immediately.run itself, which your consent cannot fix),\n * `unavailable` (no such device on this machine, or it would not start),\n * `unsupported` (this host cannot capture), `not-declared`, `timeout`.\n *\n * *Zero-platform alternative, still worth knowing:* `<input type=\"file\"\n * accept=\"image/*\" capture=\"environment\">` opens the OS camera from inside the\n * sandbox (file choosers are not permission-gated). It needs no capability and no\n * host support; it also gives you no indicator and no host-drawn surface.\n */\nexport const capturePhoto = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-photo', { ...options });\n\n/** Record one audio clip through the host's capture UI. See {@link capturePhoto} —\n * every rule there applies verbatim, with `device:microphone` and `capture-audio`. */\nexport const captureAudio = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-audio', { ...options });\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\nlet inputListenerRegistered = false;\n\n/**\n * Whether two deliveries carry the same input, compared by their JSON image. The host does\n * not check that params are JSON; the hosts' senders build them from strings and plain\n * objects, for which the image is faithful. A value JSON cannot serialise at all (it\n * throws) is treated as a change; a value JSON writes lossily (a `Map`, a `Blob`) is not\n * told apart, so two inputs differing only there compare equal.\n */\nconst sameTaskInput = (a: TaskInput, b: TaskInput): boolean => {\n if (a.task !== b.task) return false;\n try {\n return JSON.stringify(a.params) === JSON.stringify(b.params);\n } catch {\n return false;\n }\n};\n\n// Register the `task-input` listener IF a host transport is reachable; otherwise do\n// nothing (and let the next call retry — the same pattern as pushChannel's `start`).\n// Split out so both the module-eval attempt below and the first-use call sites share\n// one idempotent path.\n//\n// Registration then pulls the input once with `request-task-input`, the way `mounts`\n// pulls with `request-mounts`: the host answers a callee frame with its current\n// `task-input` and answers nothing to any other frame. So the input arrives whenever\n// this listener comes to exist, and a host send that landed before it is not lost.\n//\n// The poll has its own latch, set only once a send returns. The listener registering\n// proves there is a host, so a send that then throws is a real failure, not the off-host\n// case: it is reported once and tried again on the next read, because a poll that never\n// goes out leaves a callee looking exactly like an app that is not one.\nlet inputPolled = false;\nlet inputPollFailureReported = false;\nconst ensureInputListener = (): void => {\n if (!inputListenerRegistered) {\n try {\n addListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n const next: TaskInput = { task: m.task, params: m.params ?? {} };\n // The host sends the same input several times (at mount, past each compile, and\n // in answer to the poll). A repeat keeps the object the app already has, so an\n // effect keyed on the input does not run again for a value that did not change.\n if (latestInput && sameTaskInput(latestInput, next)) return;\n latestInput = next;\n inputListeners.forEach((l) => l(next));\n });\n } catch {\n return; // off-host: the transport resolver threw — no host to listen on\n }\n inputListenerRegistered = true;\n }\n if (inputPolled) return;\n try {\n sendMessage(REQUEST_TASK_INPUT);\n inputPolled = true;\n } catch (err) {\n if (!inputPollFailureReported) {\n inputPollFailureReported = true;\n console.warn('[immediately.run] the task-input poll could not be sent; it is retried on the next read.', err);\n }\n }\n};\n\n// Register eagerly when a host transport is already present at module evaluation, and\n// lazily on first use otherwise, so importing this module off-host (plain `vite dev`)\n// never throws. Either way the registration polls, so against a host that answers the\n// poll its timing no longer decides whether the input is seen; against an older host the\n// eager registration is still what catches the send made at mount.\nensureInputListener();\n\n/** The task params this app was invoked with, or null if it isn't a task callee.\n * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke\n * this app as a callee. The object changes only when the task or its params change:\n * the host may deliver the same input more than once, and a repeat returns the same\n * object. */\nexport const getTaskInput = (): TaskInput | null => {\n ensureInputListener();\n return latestInput;\n};\n\n/**\n * Is a host transport reachable from this realm at all?\n *\n * The R3-421 off-host no-op below must mean EXACTLY \"there is nobody to answer\" —\n * plain `vite dev`, node, jsdom. A blanket try/catch around the send meant it also\n * swallowed a genuine failure against a REAL host (`DataCloneError` because the\n * result holds a DOM node, a function or a live class instance, being the usual\n * one): the host was then never told the task finished, and the caller's\n * `invokeTask` hung to its deadline with no diagnostic anywhere. Absence is\n * therefore decided BEFORE the send, and the send itself is left to throw.\n */\nconst hostReachable = (): boolean => {\n try {\n transport();\n return true;\n } catch {\n return false; // no injected bundler bus and no §4 discovery global — off-host\n }\n};\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n *\n * `result` must be STRUCTURED-CLONEABLE — it crosses a frame boundary. A DOM node, a\n * function, a class instance with methods, a `MediaStreamTrack`: all `DataCloneError`.\n * **That throws**, deliberately and loudly: the alternative is a caller left hanging to\n * its `invokeTask` deadline while this app believes it answered.\n *\n * Off-host (plain `vite dev` — no host transport) this is a no-op: there is no caller\n * to answer. That case, and only that case, is silent.\n */\nexport const completeTask = (result: unknown): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n // On-host, a failure here is REAL and the caller is waiting on this exact message.\n sendMessage(TASK_COMPLETE, { result });\n};\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`.\n * Off-host (plain `vite dev` — no host transport) this is a no-op; on-host a failed\n * send throws rather than leaving the caller waiting, exactly as {@link completeTask}. */\nexport const cancelTask = (): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n sendMessage(TASK_CANCEL, {});\n};\n\n/** React hook: the task input for this callee, re-rendering when it arrives.\n * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee\n * state rather than waiting on it. A repeated delivery of the same input is not\n * announced: the value's identity changes only when the task or its params do. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete(l);\n };\n }, []);\n return input;\n};\n"],"mappings":";AAqBA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,sBAAsB;AAC/B,SAAS,iBAAiB;AAC1B,SAAS,eAAe,oBAAoB,aAAa,eAAe,kBAAkB;AAC1F,SAAS,eAAe;AAmBjB,MAAM,UAAU,CAAC,KAA2C,UAA0C;AAAA,EAC3G,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAoBO,MAAM,SAAS,CAAC,KAA2C,UAAyC;AAAA,EACzG,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAiDO,MAAM,aAAa,OAAoB,MAAc,SAAkC,CAAC,MAAkB;AAC/G,QAAM,MAAM,MAAM,gBAAgB,QAAQ,aAAa,GAAG,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,CAAC;AAGtF,iBAAe,KAAK,SAAS,IAAI,UAAU;AAC3C,SAAO,IAAI;AACb;AA6EO,MAAM,eAAe,CAAC,UAA0B,CAAC,MACtD,WAA0B,iBAAiB,EAAE,GAAG,QAAQ,CAAC;AAIpD,MAAM,eAAe,CAAC,UAA0B,CAAC,MACtD,WAA0B,iBAAiB,EAAE,GAAG,QAAQ,CAAC;AAU3D,IAAI,cAAgC;AACpC,MAAM,iBAAiB,oBAAI,IAA4B;AACvD,IAAI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AAQ,IAAI,SAA2B,YAAY;AACjE,YAAU,MAAM;AACd,UAAM,IAAI,CAAC,MAAiB,SAAS,CAAC;AACtC,mBAAe,IAAI,CAAC;AACpB,QAAI,YAAa,UAAS,WAAW;AACrC,WAAO,MAAM;AACX,qBAAe,OAAO,CAAC;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO;AACT;","names":[]}
|
package/dist/version.cjs
CHANGED
|
@@ -21,7 +21,7 @@ __export(version_exports, {
|
|
|
21
21
|
SDK_VERSION: () => SDK_VERSION
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(version_exports);
|
|
24
|
-
const SDK_VERSION = "0.
|
|
24
|
+
const SDK_VERSION = "0.87.1";
|
|
25
25
|
// Annotate the CommonJS export names for ESM import in node:
|
|
26
26
|
0 && (module.exports = {
|
|
27
27
|
SDK_VERSION
|
package/dist/version.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.87.1';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,MAAM,cAAc;","names":[]}
|
package/dist/version.d.cts
CHANGED
package/dist/version.d.ts
CHANGED
package/dist/version.js
CHANGED
package/dist/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.87.1';\n"],"mappings":";AAIO,MAAM,cAAc;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@immediately-run/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.87.1",
|
|
4
4
|
"description": "Runtime SDK for code executing inside an immediately.run sandbox.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": "github:immediately-run/immediately-run-sdk",
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"@immediately-run/mdx-plugins": "0.7.1",
|
|
76
76
|
"@immediately-run/platform-constants": "0.2.0",
|
|
77
77
|
"@immediately-run/safe-content": "0.1.0",
|
|
78
|
-
"@immediately-run/sandbox-protocol": "^0.
|
|
78
|
+
"@immediately-run/sandbox-protocol": "^0.25.0",
|
|
79
79
|
"react-error-boundary": "^6.0.0"
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|