@immediately-run/sdk 0.61.0 → 0.64.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/agentChatClient.d.cts +1 -0
- package/dist/agentChatClient.d.ts +1 -0
- package/dist/agentLoop.cjs +7 -1
- package/dist/agentLoop.cjs.map +1 -1
- package/dist/agentLoop.d.cts +21 -0
- package/dist/agentLoop.d.ts +21 -0
- package/dist/agentLoop.js +7 -1
- package/dist/agentLoop.js.map +1 -1
- package/dist/agentPause.cjs +68 -0
- package/dist/agentPause.cjs.map +1 -0
- package/dist/agentPause.d.cts +37 -0
- package/dist/agentPause.d.ts +37 -0
- package/dist/agentPause.js +45 -0
- package/dist/agentPause.js.map +1 -0
- package/dist/anchorClick.cjs +40 -0
- package/dist/anchorClick.cjs.map +1 -0
- package/dist/anchorClick.d.cts +23 -0
- package/dist/anchorClick.d.ts +23 -0
- package/dist/anchorClick.js +16 -0
- package/dist/anchorClick.js.map +1 -0
- package/dist/components/Link.cjs +4 -11
- package/dist/components/Link.cjs.map +1 -1
- package/dist/components/Link.d.cts +1 -1
- package/dist/components/Link.d.ts +1 -1
- package/dist/components/Link.js +3 -10
- package/dist/components/Link.js.map +1 -1
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/mounts.cjs +16 -0
- package/dist/mounts.cjs.map +1 -1
- package/dist/mounts.d.cts +18 -1
- package/dist/mounts.d.ts +18 -1
- package/dist/mounts.js +16 -0
- package/dist/mounts.js.map +1 -1
- package/dist/openRepository.cjs +44 -0
- package/dist/openRepository.cjs.map +1 -0
- package/dist/openRepository.d.cts +36 -0
- package/dist/openRepository.d.ts +36 -0
- package/dist/openRepository.js +21 -0
- package/dist/openRepository.js.map +1 -0
- package/dist/platformLink.cjs +18 -3
- package/dist/platformLink.cjs.map +1 -1
- package/dist/platformLink.d.cts +33 -10
- package/dist/platformLink.d.ts +33 -10
- package/dist/platformLink.js +18 -3
- package/dist/platformLink.js.map +1 -1
- package/dist/protocolSchemes.cjs +2 -0
- package/dist/protocolSchemes.cjs.map +1 -1
- package/dist/protocolSchemes.d.cts +2 -0
- package/dist/protocolSchemes.d.ts +2 -0
- package/dist/protocolSchemes.js +4 -0
- package/dist/protocolSchemes.js.map +1 -1
- package/dist/region.cjs +22 -2
- package/dist/region.cjs.map +1 -1
- package/dist/region.d.cts +20 -1
- package/dist/region.d.ts +20 -1
- package/dist/region.js +18 -1
- package/dist/region.js.map +1 -1
- package/dist/urlUtils.cjs.map +1 -1
- package/dist/urlUtils.d.cts +6 -2
- package/dist/urlUtils.d.ts +6 -2
- package/dist/urlUtils.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 +3 -3
package/dist/mounts.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { APP_ROOT } from '@immediately-run/platform-constants';\n\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// R3-166 — the `spaces:*` family is GENERATED from the capability descriptor set\n// (`scripts/codegen-prototype/descriptors.spaces.mjs`) rather than hand-written here.\n// Re-exported from this module so every existing import path keeps working: the\n// swap is a no-op to consumers (SDK_SIMPLIFICATION_SPEC §7 step 3), which is\n// asserted by the emitted-`.d.ts` before/after comparison, not assumed.\n//\n// `Role` is imported (not only re-exported) because `Invite` below still uses it —\n// the invite methods are the same `spaces:` scheme but are NOT yet described, so\n// they remain hand-written. That split is the next migration increment.\nimport type { Role } from './generated/spaces';\nexport type { Role, SpaceInfo, Member, ResolvedUser, GrantRecord } from './generated/spaces';\nexport {\n listSpaces,\n listAllSpaces,\n getSpaceMembers,\n inviteToSpace,\n unshareSpace,\n setSpaceRole,\n lookupUser,\n listGrants,\n revokeGrant,\n} from './generated/spaces';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\nimport {\n INVITATIONS,\n MOUNT_ADD,\n MOUNT_REMOVE,\n PROTOCOL_SETTINGS,\n PROTOCOL_SPACES,\n REQUEST_INVITATIONS,\n REQUEST_MOUNTS,\n REQUEST_SESSION_MOUNTS,\n SESSION_MOUNTS,\n} from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? APP_ROOT;\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: 'ro' | 'rw';\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason = 'revoked' | 'unshared' | 'signed-out' | 'unmounted' | 'deleted';\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value) ? (value as MountRemoveReason) : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\n/** @deprecated-path The injected `bundler.mounts` read — window opened 2026-08-25\n * (R3-278). The protocol equivalent is `transportMountService()` below (the\n * `mount-add`/`mount-remove` mirror + `request-mounts` replay), which the dual-mode\n * chooser already falls back to. Injection stays preferred for byte-compat through\n * the window; see DEPRECATION_CANDIDATES.md.\n */\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener(MOUNT_ADD, (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener(MOUNT_REMOVE, (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage(REQUEST_MOUNTS);\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean => mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined => getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n *\n * `timeoutMs` (optional, additive) rejects with a `timeout`-coded error instead of\n * waiting forever. Omit it to keep the original unbounded behaviour — but prefer\n * setting it on any path whose caller would otherwise hang silently: a mount that\n * never arrives is indistinguishable from one that is merely slow, and an awaited\n * promise that never settles surfaces to the user as a feature that quietly does\n * nothing.\n *\n * **Hazard — `onMountsChange` calls its listener SYNCHRONOUSLY on subscribe** (the\n * documented initial replay). So when the mount is already present — the common\n * case, since callers typically `await` the host request that creates it first —\n * the callback below runs *during* the `onMountsChange(...)` call, before the\n * assignment to `unsubscribe` completes. `unsubscribe` is therefore declared with\n * `let` ABOVE the subscription and read only inside a deferred closure: writing\n * `const unsubscribe = onMountsChange(...)` and referencing it in the callback\n * throws `ReferenceError: Cannot access 'unsubscribe' before initialization` (a\n * temporal-dead-zone read) on exactly that path. That bug silently broke\n * `openSettings()` — and with it the agent's conversation memory.\n */\nexport const waitForMount = (query: MountQuery, timeoutMs?: number): Promise<SandboxMount> =>\n awaitMatchingMount(onMountsChange, query, timeoutMs);\n\n/** The framework-free core of {@link waitForMount}, with the subscription injected\n * so a test can drive the synchronous-initial-replay case that broke it. */\nexport const awaitMatchingMount = (\n subscribe: (listener: (mounts: SandboxMount[]) => void) => () => void,\n query: MountQuery,\n timeoutMs?: number,\n): Promise<SandboxMount> =>\n new Promise((resolve, reject) => {\n // `let`, declared BEFORE `subscribe(...)` — see the hazard note above. A\n // `const` bound to the subscribe call is in its temporal dead zone while the\n // synchronous initial replay runs, and any read of it from the listener\n // throws.\n let unsubscribe: (() => void) | undefined;\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n // Deferred so we never dispose the subscription from inside its own initial\n // replay, and late enough that `unsubscribe` is always assigned.\n const stop = (): void => {\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n void Promise.resolve().then(() => unsubscribe?.());\n };\n unsubscribe = subscribe((mounts) => {\n if (settled) return;\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n stop();\n resolve(found);\n }\n });\n // The initial replay may have settled us above, before `unsubscribe` existed;\n // `stop()`'s deferred read picks it up, so nothing more is needed here.\n if (!settled && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (settled) return;\n stop();\n const err = new Error(\n `waitForMount timed out after ${timeoutMs}ms waiting for ${JSON.stringify(query)}`,\n ) as SpaceError;\n err.code = 'timeout';\n reject(err);\n }, timeoutMs);\n }\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: SESSION_MOUNTS,\n requestType: REQUEST_SESSION_MOUNTS,\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (listener: (mounts: SessionMount[]) => void): (() => void) =>\n sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** An error from a space operation, carrying a machine-readable `code`. */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n // Client-side, never from the host: a bounded `waitForMount` gave up.\n | 'timeout'\n | 'unknown';\n}\n\ntype SpaceResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and\n// throwing a typed SpaceError on failure.\nconst request = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES], method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'space request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (method: string, query: Record<string, unknown>): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> => requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> => mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> => requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n *\n * The body repeats {@link capFile} rather than calling it, and that is deliberate:\n * `tasks.ts` registers a host listener at module load, so a VALUE import of it here\n * would run that side effect in every importer of `mounts` (which is why the\n * `FileCap` import above is type-only). The shape the two share is the spec's, and\n * the `FileCap` type is what holds them to it.\n */\nexport const makeContentRef = (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/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `request` for the spaces surface).\nconst settingsRequest = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SETTINGS], method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'settings request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n *\n * **Which filesystem you get, and when that can change** (R3-413): for an\n * ordinary app — including one holding space grants, powerbox-picked or\n * declared — this is ALWAYS the app-level store (same mount id every call, so\n * \"which space did I pick\" style state survives later grants; no need to open\n * early and keep the handle). The one exception: an instance the host has\n * **floored** below its app tier (the generic-viewer containment,\n * `TRUST_MODES_SPEC` §5) gets a per-origin partition instead — a DIFFERENT\n * filesystem, chosen by the host, that changes when the loaded origin changes\n * and refuses (`forbidden`) when the floor forbids the write. If your app can\n * run floored and needs continuity across origins, keep state per-mount (the\n * returned `SandboxMount.id` tells you which partition you are in).\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway: an unbounded wait\n // here turns any delivery failure into a promise that never settles, and every\n // caller of `openSettings()` is doing it to reach durable state — so the app\n // just quietly loses that state with nothing to report.\n return waitForMount({ id: mount.id ?? mount.path }, SETTINGS_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openSettings()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst SETTINGS_MOUNT_TIMEOUT_MS = 15_000;\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> => settingsRequest<string[]>('list');\n\n/** Create a brand-new, empty platform-hosted space, granted to THIS app in full\n * (read-write) — the user's create consent is consent for the app to create\n * storage for itself, and the host records the same durable grant the\n * {@link requestMount} powerbox would. So the returned mount can be re-opened\n * later with {@link mountSpace} / {@link mount} (`space:<id>`) with no prompt —\n * on the next load, in another tab, after sign-out/sign-in — until the user\n * revokes the grant in their grants surface, after which `mount` answers\n * `forbidden`. Other apps get nothing: they still reach the space only through\n * the powerbox. (Before site-main R3-406 no grant was recorded and the space\n * could only be re-found via the powerbox.) */\nexport const createSpace = (opts: { name?: string } = {}): Promise<SandboxMount> =>\n requestMountInternal('create', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n// ---------------------------------------------------------------------------\n\n/** A pending invitation to a space (pull-based sharing, FILE_SHARING_SPEC §6.4).\n * It grants NO access until accepted — the recipient accepts it from their inbox\n * ({@link listMyInvites} → {@link acceptInvite}), materializing membership. The\n * display fields (`name`/`login`/`avatarUrl`) are untrusted for rendering. */\nexport interface Invite {\n spaceId: string;\n /** The invitee's uid — carried so the owner's pending list can\n * {@link revokeInvite}(spaceId, uid). */\n uid: string;\n role: Role;\n owner: string;\n name?: string;\n invitedBy: string;\n /** epoch ms (server-stamped); absent until the write settles. */\n invitedAt?: number;\n login?: string;\n avatarUrl?: string;\n}\n\n/** The owner's outstanding invitations for a space — `spaces:admin`. */\nexport const listPendingInvites = (spaceId: string): Promise<Invite[]> =>\n request<Invite[]>('pendingInvites', { spaceId });\n\n/** Withdraw a pending invitation (distinct from {@link unshareSpace}, which removes\n * an ACCEPTED member) — `spaces:admin`. */\nexport const revokeInvite = async (spaceId: string, uid: string): Promise<void> => {\n await request('revokeInvite', { spaceId, uid });\n};\n\n/** The caller's OWN invitation inbox — `spaces:user`. */\nexport const listMyInvites = (): Promise<Invite[]> => request<Invite[]>('listInvites', {});\n\n/** Accept an invitation: materialize your membership at the invited role and clear\n * the invite — `spaces:user`. An invitation the caller doesn't hold rejects with\n * `forbidden` (indistinguishable from a nonexistent space; no existence oracle). */\nexport const acceptInvite = async (spaceId: string): Promise<void> => {\n await request('acceptInvite', { spaceId });\n};\n\n/** Decline (dismiss) an invitation from your inbox; writes no membership —\n * `spaces:user`. */\nexport const declineInvite = async (spaceId: string): Promise<void> => {\n await request('declineInvite', { spaceId });\n};\n\n// The live invitations inbox (FILE_SHARING §6.4/§9.8): the host pushes the caller's\n// current invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects within one\n// snapshot — no poll. Mirrors the host's `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: INVITATIONS,\n requestType: REQUEST_INVITATIONS,\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n"],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,yBAAyB;AAClC,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAY7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAIP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AAUjB,MAAM,kBAAkB,MAAc,eAAe,GAAG,gBAAgB;AA6E/E,MAAM,WAAW,CAAC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,MAAM,gBAA8B,UAAU,EAAE,OAAO,CAAC;AACtE,SAAO,aAAa,EAAE,IAAIA,OAAM,MAAMA,OAAM,KAAK,CAAC;AACpD;AAOO,MAAM,mBAAmB,MAAyB,gBAA0B,MAAM;AAYlF,MAAM,cAAc,CAAC,OAA0B,CAAC,MACrD,qBAAqB,UAAU,IAAI;AAG9B,MAAM,eAAe,OAAO,UAA8C;AAC/E,QAAM,QAAQ,WAAW,KAAK;AAChC;AA+BO,MAAM,qBAAqB,CAAC,YACjC,QAAkB,kBAAkB,EAAE,QAAQ,CAAC;AAI1C,MAAM,eAAe,OAAO,SAAiB,QAA+B;AACjF,QAAM,QAAQ,gBAAgB,EAAE,SAAS,IAAI,CAAC;AAChD;AAGO,MAAM,gBAAgB,MAAyB,QAAkB,eAAe,CAAC,CAAC;AAKlF,MAAM,eAAe,OAAO,YAAmC;AACpE,QAAM,QAAQ,gBAAgB,EAAE,QAAQ,CAAC;AAC3C;AAIO,MAAM,gBAAgB,OAAO,YAAmC;AACrE,QAAM,QAAQ,iBAAiB,EAAE,QAAQ,CAAC;AAC5C;AAMA,MAAM,iBAAiB,kBAA4B;AAAA,EACjD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS,CAAC;AAAA,EACV,OAAO,CAAC,QAAS,MAAM,QAAQ,IAAI,OAAO,IAAK,IAAI,UAAuB;AAC5E,CAAC;AAIM,MAAM,aAAa,MAAgB,eAAe,IAAI;AAItD,MAAM,kBAAkB,CAAC,aAC9B,eAAe,SAAS,QAAQ;AAI3B,MAAM,aAAa,MAAgB,eAAe,IAAI;","names":["mount"]}
|
|
1
|
+
{"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { APP_ROOT } from '@immediately-run/platform-constants';\n\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// R3-166 — the `spaces:*` family is GENERATED from the capability descriptor set\n// (`scripts/codegen-prototype/descriptors.spaces.mjs`) rather than hand-written here.\n// Re-exported from this module so every existing import path keeps working: the\n// swap is a no-op to consumers (SDK_SIMPLIFICATION_SPEC §7 step 3), which is\n// asserted by the emitted-`.d.ts` before/after comparison, not assumed.\n//\n// `Role` is imported (not only re-exported) because `Invite` below still uses it —\n// the invite methods are the same `spaces:` scheme but are NOT yet described, so\n// they remain hand-written. That split is the next migration increment.\nimport type { Role } from './generated/spaces';\nexport type { Role, SpaceInfo, Member, ResolvedUser, GrantRecord } from './generated/spaces';\nexport {\n listSpaces,\n listAllSpaces,\n getSpaceMembers,\n inviteToSpace,\n unshareSpace,\n setSpaceRole,\n lookupUser,\n listGrants,\n revokeGrant,\n} from './generated/spaces';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\nimport {\n INVITATIONS,\n MOUNT_ADD,\n MOUNT_REMOVE,\n PROTOCOL_LOCALSTORE,\n PROTOCOL_SETTINGS,\n PROTOCOL_SPACES,\n REQUEST_INVITATIONS,\n REQUEST_MOUNTS,\n REQUEST_SESSION_MOUNTS,\n SESSION_MOUNTS,\n} from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? APP_ROOT;\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: 'ro' | 'rw';\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason = 'revoked' | 'unshared' | 'signed-out' | 'unmounted' | 'deleted';\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value) ? (value as MountRemoveReason) : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\n/** @deprecated-path The injected `bundler.mounts` read — window opened 2026-08-25\n * (R3-278). The protocol equivalent is `transportMountService()` below (the\n * `mount-add`/`mount-remove` mirror + `request-mounts` replay), which the dual-mode\n * chooser already falls back to. Injection stays preferred for byte-compat through\n * the window; see DEPRECATION_CANDIDATES.md.\n */\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener(MOUNT_ADD, (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener(MOUNT_REMOVE, (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage(REQUEST_MOUNTS);\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean => mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined => getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n *\n * `timeoutMs` (optional, additive) rejects with a `timeout`-coded error instead of\n * waiting forever. Omit it to keep the original unbounded behaviour — but prefer\n * setting it on any path whose caller would otherwise hang silently: a mount that\n * never arrives is indistinguishable from one that is merely slow, and an awaited\n * promise that never settles surfaces to the user as a feature that quietly does\n * nothing.\n *\n * **Hazard — `onMountsChange` calls its listener SYNCHRONOUSLY on subscribe** (the\n * documented initial replay). So when the mount is already present — the common\n * case, since callers typically `await` the host request that creates it first —\n * the callback below runs *during* the `onMountsChange(...)` call, before the\n * assignment to `unsubscribe` completes. `unsubscribe` is therefore declared with\n * `let` ABOVE the subscription and read only inside a deferred closure: writing\n * `const unsubscribe = onMountsChange(...)` and referencing it in the callback\n * throws `ReferenceError: Cannot access 'unsubscribe' before initialization` (a\n * temporal-dead-zone read) on exactly that path. That bug silently broke\n * `openSettings()` — and with it the agent's conversation memory.\n */\nexport const waitForMount = (query: MountQuery, timeoutMs?: number): Promise<SandboxMount> =>\n awaitMatchingMount(onMountsChange, query, timeoutMs);\n\n/** The framework-free core of {@link waitForMount}, with the subscription injected\n * so a test can drive the synchronous-initial-replay case that broke it. */\nexport const awaitMatchingMount = (\n subscribe: (listener: (mounts: SandboxMount[]) => void) => () => void,\n query: MountQuery,\n timeoutMs?: number,\n): Promise<SandboxMount> =>\n new Promise((resolve, reject) => {\n // `let`, declared BEFORE `subscribe(...)` — see the hazard note above. A\n // `const` bound to the subscribe call is in its temporal dead zone while the\n // synchronous initial replay runs, and any read of it from the listener\n // throws.\n let unsubscribe: (() => void) | undefined;\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n // Deferred so we never dispose the subscription from inside its own initial\n // replay, and late enough that `unsubscribe` is always assigned.\n const stop = (): void => {\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n void Promise.resolve().then(() => unsubscribe?.());\n };\n unsubscribe = subscribe((mounts) => {\n if (settled) return;\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n stop();\n resolve(found);\n }\n });\n // The initial replay may have settled us above, before `unsubscribe` existed;\n // `stop()`'s deferred read picks it up, so nothing more is needed here.\n if (!settled && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (settled) return;\n stop();\n const err = new Error(\n `waitForMount timed out after ${timeoutMs}ms waiting for ${JSON.stringify(query)}`,\n ) as SpaceError;\n err.code = 'timeout';\n reject(err);\n }, timeoutMs);\n }\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: SESSION_MOUNTS,\n requestType: REQUEST_SESSION_MOUNTS,\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (listener: (mounts: SessionMount[]) => void): (() => void) =>\n sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** An error from a space operation, carrying a machine-readable `code`. */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n // Client-side, never from the host: a bounded `waitForMount` gave up.\n | 'timeout'\n | 'unknown';\n}\n\ntype SpaceResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and\n// throwing a typed SpaceError on failure.\nconst request = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES], method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'space request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (method: string, query: Record<string, unknown>): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> => requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> => mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> => requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n *\n * The body repeats {@link capFile} rather than calling it, and that is deliberate:\n * `tasks.ts` registers a host listener at module load, so a VALUE import of it here\n * would run that side effect in every importer of `mounts` (which is why the\n * `FileCap` import above is type-only). The shape the two share is the spec's, and\n * the `FileCap` type is what holds them to it.\n */\nexport const makeContentRef = (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/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `request` for the spaces surface).\nconst settingsRequest = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SETTINGS], method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'settings request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n *\n * **Which filesystem you get, and when that can change** (R3-413): for an\n * ordinary app — including one holding space grants, powerbox-picked or\n * declared — this is ALWAYS the app-level store (same mount id every call, so\n * \"which space did I pick\" style state survives later grants; no need to open\n * early and keep the handle). The one exception: an instance the host has\n * **floored** below its app tier (the generic-viewer containment,\n * `TRUST_MODES_SPEC` §5) gets a per-origin partition instead — a DIFFERENT\n * filesystem, chosen by the host, that changes when the loaded origin changes\n * and refuses (`forbidden`) when the floor forbids the write. If your app can\n * run floored and needs continuity across origins, keep state per-mount (the\n * returned `SandboxMount.id` tells you which partition you are in).\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway: an unbounded wait\n // here turns any delivery failure into a promise that never settles, and every\n // caller of `openSettings()` is doing it to reach durable state — so the app\n // just quietly loses that state with nothing to report.\n return waitForMount({ id: mount.id ?? mount.path }, SETTINGS_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openSettings()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst SETTINGS_MOUNT_TIMEOUT_MS = 15_000;\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> => settingsRequest<string[]>('list');\n\n// ---------------------------------------------------------------------------\n// Device-local store — the per-app, device-local, IndexedDB-backed filesystem\n// (FILESYSTEM_SPEC §2.8). The distinction from `settings:` is durability, stated\n// to the app via the mount's `type: 'localstore'`, never a guess.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-localstore` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `settingsRequest`).\nconst localStoreRequest = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_LOCALSTORE], method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'localstore request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's **device-local** store — a private, per-device, IndexedDB-backed\n * filesystem, NOT synced (unlike {@link openSettings}). The cheap, throwaway-able\n * home for a cache, a draft, a scroll position, a checkpoint; the wrong home for\n * anything the user would mourn (the browser may evict it under storage pressure,\n * and the docs say so). Read/write it through `fs` at the returned mount's `path`,\n * with `type: 'localstore'`.\n *\n * Isolation is the store itself, keyed on the app's `appKey` — an app can never\n * name another app's local store, there is deliberately no `openOf` sibling, and\n * nothing written here is synced. Capability: baseline `storage:local` (no consent\n * prompt). Rejects with a {@link SpaceError}: `auth-required` when signed out,\n * `forbidden` when the capability is absent. A quota/external failure surfaces the\n * underlying error unchanged, so an app can tell \"the browser evicted me\" from\n * \"I never wrote anything\".\n */\nexport const openLocalStore = async (): Promise<SandboxMount> => {\n const mount = await localStoreRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway, for the same reason\n // `openSettings()` bounds its wait: an unbounded wait turns any delivery failure\n // into a promise that never settles, and the caller reached for durable state.\n return waitForMount({ id: mount.id ?? mount.path }, LOCALSTORE_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openLocalStore()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst LOCALSTORE_MOUNT_TIMEOUT_MS = 15_000;\n\n/** Create a brand-new, empty platform-hosted space, granted to THIS app in full\n * (read-write) — the user's create consent is consent for the app to create\n * storage for itself, and the host records the same durable grant the\n * {@link requestMount} powerbox would. So the returned mount can be re-opened\n * later with {@link mountSpace} / {@link mount} (`space:<id>`) with no prompt —\n * on the next load, in another tab, after sign-out/sign-in — until the user\n * revokes the grant in their grants surface, after which `mount` answers\n * `forbidden`. Other apps get nothing: they still reach the space only through\n * the powerbox. (Before site-main R3-406 no grant was recorded and the space\n * could only be re-found via the powerbox.) */\nexport const createSpace = (opts: { name?: string } = {}): Promise<SandboxMount> =>\n requestMountInternal('create', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n// ---------------------------------------------------------------------------\n\n/** A pending invitation to a space (pull-based sharing, FILE_SHARING_SPEC §6.4).\n * It grants NO access until accepted — the recipient accepts it from their inbox\n * ({@link listMyInvites} → {@link acceptInvite}), materializing membership. The\n * display fields (`name`/`login`/`avatarUrl`) are untrusted for rendering. */\nexport interface Invite {\n spaceId: string;\n /** The invitee's uid — carried so the owner's pending list can\n * {@link revokeInvite}(spaceId, uid). */\n uid: string;\n role: Role;\n owner: string;\n name?: string;\n invitedBy: string;\n /** epoch ms (server-stamped); absent until the write settles. */\n invitedAt?: number;\n login?: string;\n avatarUrl?: string;\n}\n\n/** The owner's outstanding invitations for a space — `spaces:admin`. */\nexport const listPendingInvites = (spaceId: string): Promise<Invite[]> =>\n request<Invite[]>('pendingInvites', { spaceId });\n\n/** Withdraw a pending invitation (distinct from {@link unshareSpace}, which removes\n * an ACCEPTED member) — `spaces:admin`. */\nexport const revokeInvite = async (spaceId: string, uid: string): Promise<void> => {\n await request('revokeInvite', { spaceId, uid });\n};\n\n/** The caller's OWN invitation inbox — `spaces:user`. */\nexport const listMyInvites = (): Promise<Invite[]> => request<Invite[]>('listInvites', {});\n\n/** Accept an invitation: materialize your membership at the invited role and clear\n * the invite — `spaces:user`. An invitation the caller doesn't hold rejects with\n * `forbidden` (indistinguishable from a nonexistent space; no existence oracle). */\nexport const acceptInvite = async (spaceId: string): Promise<void> => {\n await request('acceptInvite', { spaceId });\n};\n\n/** Decline (dismiss) an invitation from your inbox; writes no membership —\n * `spaces:user`. */\nexport const declineInvite = async (spaceId: string): Promise<void> => {\n await request('declineInvite', { spaceId });\n};\n\n// The live invitations inbox (FILE_SHARING §6.4/§9.8): the host pushes the caller's\n// current invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects within one\n// snapshot — no poll. Mirrors the host's `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: INVITATIONS,\n requestType: REQUEST_INVITATIONS,\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n"],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,WAAW,gBAAgB;AACpC,SAAS,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AE,QAAQ,CAAC;AAI1C,MAAM,eAAe,OAAO,SAAiB,QAA+B;AACjF,QAAM,QAAQ,gBAAgB,EAAE,SAAS,IAAI,CAAC;AAChD;AAGO,MAAM,gBAAgB,MAAyB,QAAkB,eAAe,CAAC,CAAC;AAKlF,MAAM,eAAe,OAAO,YAAmC;AACpE,QAAM,QAAQ,gBAAgB,EAAE,QAAQ,CAAC;AAC3C;AAIO,MAAM,gBAAgB,OAAO,YAAmC;AACrE,QAAM,QAAQ,iBAAiB,EAAE,QAAQ,CAAC;AAC5C;AAMA,MAAM,iBAAiB,kBAA4B;AAAA,EACjD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS,CAAC;AAAA,EACV,OAAO,CAAC,QAAS,MAAM,QAAQ,IAAI,OAAO,IAAK,IAAI,UAAuB;AAC5E,CAAC;AAIM,MAAM,aAAa,MAAgB,eAAe,IAAI;AAItD,MAAM,kBAAkB,CAAC,aAC9B,eAAe,SAAS,QAAQ;AAI3B,MAAM,aAAa,MAAgB,eAAe,IAAI;","names":["mount"]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var openRepository_exports = {};
|
|
20
|
+
__export(openRepository_exports, {
|
|
21
|
+
openRepository: () => openRepository
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(openRepository_exports);
|
|
24
|
+
var import_sandboxUtils = require("./sandboxUtils");
|
|
25
|
+
var import_protocol = require("./generated/protocol");
|
|
26
|
+
var import_protocolSchemes = require("./protocolSchemes");
|
|
27
|
+
async function openRepository(coordinates) {
|
|
28
|
+
const { provider, namespace, repository } = coordinates;
|
|
29
|
+
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_OPENREPO], "open", [
|
|
30
|
+
{ provider, namespace, repository }
|
|
31
|
+
]);
|
|
32
|
+
if (!res || res.ok !== true) {
|
|
33
|
+
const err = new Error(
|
|
34
|
+
(res && "message" in res ? res.message : void 0) ?? "repository open refused"
|
|
35
|
+
);
|
|
36
|
+
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
|
37
|
+
throw err;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
41
|
+
0 && (module.exports = {
|
|
42
|
+
openRepository
|
|
43
|
+
});
|
|
44
|
+
//# sourceMappingURL=openRepository.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code. */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [\n { provider, namespace, repository },\n ])) as OpenRepositoryReply;\n // The refusal resolves inside the reply, so `res.ok !== true` is the only failure test\n // there is — a bare-promise shape here would swallow every coded refusal as a success.\n if (!res || res.ok !== true) {\n const err = new Error(\n (res && 'message' in res ? res.message : undefined) ?? 'repository open refused',\n ) as OpenRepositoryError;\n err.code = ((res && 'code' in res ? res.code : undefined) as OpenRepositoryErrorCode) ?? 'unknown';\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,0BAAgC;AAChC,sBAAkC;AAClC,6BAAwB;AA0CxB,eAAsB,eAAe,aAAmD;AACtF,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAC5C,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,iCAAiB,GAAG,QAAQ;AAAA,IACrE,EAAE,UAAU,WAAW,WAAW;AAAA,EACpC,CAAC;AAGD,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI;AAAA,OACb,OAAO,aAAa,MAAM,IAAI,UAAU,WAAc;AAAA,IACzD;AACA,QAAI,QAAS,OAAO,UAAU,MAAM,IAAI,OAAO,WAA0C;AACzF,UAAM;AAAA,EACR;AACF;","names":[]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Where a repository lives. The same three fields a `RecentProject` carries — this is a
|
|
2
|
+
* location the user may already have navigated to under their own authority. */
|
|
3
|
+
interface RepositoryCoordinates {
|
|
4
|
+
provider: string;
|
|
5
|
+
namespace: string;
|
|
6
|
+
repository: string;
|
|
7
|
+
}
|
|
8
|
+
/** Why the host refused to open a tab.
|
|
9
|
+
*
|
|
10
|
+
* - `invalid` — the coordinates are not three clean path segments.
|
|
11
|
+
* - `no-activation` — no live user gesture on the host document. Call this from a click
|
|
12
|
+
* handler; a timer or a boot path will always get this. A SECOND call inside one gesture
|
|
13
|
+
* also lands here: `window.open` consumes the host's transient activation, so one click
|
|
14
|
+
* buys exactly one tab and the next needs a real second click.
|
|
15
|
+
* - `forbidden` — the app does not hold the baseline `route:read` capability.
|
|
16
|
+
* - `unsupported` — this host has no repository-open surface wired.
|
|
17
|
+
* - `unknown` — the host refused without naming a code. */
|
|
18
|
+
type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';
|
|
19
|
+
interface OpenRepositoryError extends Error {
|
|
20
|
+
code: OpenRepositoryErrorCode;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Ask the host to open a repository in a new browser tab.
|
|
24
|
+
*
|
|
25
|
+
* Resolves once the host has performed the open; it does not wait for — and cannot observe —
|
|
26
|
+
* the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`
|
|
27
|
+
* when the host refuses.
|
|
28
|
+
*
|
|
29
|
+
* Call it directly from a user gesture. The host samples its own transient activation when
|
|
30
|
+
* the request arrives, so anything that defers the call past the gesture (an `await` before
|
|
31
|
+
* it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
|
|
32
|
+
* worth retrying: each names a condition a retry cannot change.
|
|
33
|
+
*/
|
|
34
|
+
declare function openRepository(coordinates: RepositoryCoordinates): Promise<void>;
|
|
35
|
+
|
|
36
|
+
export { type OpenRepositoryError, type OpenRepositoryErrorCode, type RepositoryCoordinates, openRepository };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Where a repository lives. The same three fields a `RecentProject` carries — this is a
|
|
2
|
+
* location the user may already have navigated to under their own authority. */
|
|
3
|
+
interface RepositoryCoordinates {
|
|
4
|
+
provider: string;
|
|
5
|
+
namespace: string;
|
|
6
|
+
repository: string;
|
|
7
|
+
}
|
|
8
|
+
/** Why the host refused to open a tab.
|
|
9
|
+
*
|
|
10
|
+
* - `invalid` — the coordinates are not three clean path segments.
|
|
11
|
+
* - `no-activation` — no live user gesture on the host document. Call this from a click
|
|
12
|
+
* handler; a timer or a boot path will always get this. A SECOND call inside one gesture
|
|
13
|
+
* also lands here: `window.open` consumes the host's transient activation, so one click
|
|
14
|
+
* buys exactly one tab and the next needs a real second click.
|
|
15
|
+
* - `forbidden` — the app does not hold the baseline `route:read` capability.
|
|
16
|
+
* - `unsupported` — this host has no repository-open surface wired.
|
|
17
|
+
* - `unknown` — the host refused without naming a code. */
|
|
18
|
+
type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';
|
|
19
|
+
interface OpenRepositoryError extends Error {
|
|
20
|
+
code: OpenRepositoryErrorCode;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Ask the host to open a repository in a new browser tab.
|
|
24
|
+
*
|
|
25
|
+
* Resolves once the host has performed the open; it does not wait for — and cannot observe —
|
|
26
|
+
* the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`
|
|
27
|
+
* when the host refuses.
|
|
28
|
+
*
|
|
29
|
+
* Call it directly from a user gesture. The host samples its own transient activation when
|
|
30
|
+
* the request arrives, so anything that defers the call past the gesture (an `await` before
|
|
31
|
+
* it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
|
|
32
|
+
* worth retrying: each names a condition a retry cannot change.
|
|
33
|
+
*/
|
|
34
|
+
declare function openRepository(coordinates: RepositoryCoordinates): Promise<void>;
|
|
35
|
+
|
|
36
|
+
export { type OpenRepositoryError, type OpenRepositoryErrorCode, type RepositoryCoordinates, openRepository };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import "./chunk-VHAA22YE.js";
|
|
2
|
+
import { protocolRequest } from "./sandboxUtils";
|
|
3
|
+
import { PROTOCOL_OPENREPO } from "./generated/protocol";
|
|
4
|
+
import { SCHEMES } from "./protocolSchemes";
|
|
5
|
+
async function openRepository(coordinates) {
|
|
6
|
+
const { provider, namespace, repository } = coordinates;
|
|
7
|
+
const res = await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], "open", [
|
|
8
|
+
{ provider, namespace, repository }
|
|
9
|
+
]);
|
|
10
|
+
if (!res || res.ok !== true) {
|
|
11
|
+
const err = new Error(
|
|
12
|
+
(res && "message" in res ? res.message : void 0) ?? "repository open refused"
|
|
13
|
+
);
|
|
14
|
+
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
|
15
|
+
throw err;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export {
|
|
19
|
+
openRepository
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=openRepository.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code. */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [\n { provider, namespace, repository },\n ])) as OpenRepositoryReply;\n // The refusal resolves inside the reply, so `res.ok !== true` is the only failure test\n // there is — a bare-promise shape here would swallow every coded refusal as a success.\n if (!res || res.ok !== true) {\n const err = new Error(\n (res && 'message' in res ? res.message : undefined) ?? 'repository open refused',\n ) as OpenRepositoryError;\n err.code = ((res && 'code' in res ? res.code : undefined) as OpenRepositoryErrorCode) ?? 'unknown';\n throw err;\n }\n}\n"],"mappings":";AAgBA,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,eAAe;AA0CxB,eAAsB,eAAe,aAAmD;AACtF,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAC5C,QAAM,MAAO,MAAM,gBAAgB,QAAQ,iBAAiB,GAAG,QAAQ;AAAA,IACrE,EAAE,UAAU,WAAW,WAAW;AAAA,EACpC,CAAC;AAGD,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI;AAAA,OACb,OAAO,aAAa,MAAM,IAAI,UAAU,WAAc;AAAA,IACzD;AACA,QAAI,QAAS,OAAO,UAAU,MAAM,IAAI,OAAO,WAA0C;AACzF,UAAM;AAAA,EACR;AACF;","names":[]}
|
package/dist/platformLink.cjs
CHANGED
|
@@ -24,15 +24,30 @@ __export(platformLink_exports, {
|
|
|
24
24
|
module.exports = __toCommonJS(platformLink_exports);
|
|
25
25
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
26
26
|
var import_react = require("react");
|
|
27
|
+
var import_anchorClick = require("./anchorClick");
|
|
28
|
+
var import_routing = require("./routing");
|
|
27
29
|
var import_TinkerableContext = require("./TinkerableContext");
|
|
28
30
|
var import_urlUtils = require("./urlUtils");
|
|
29
31
|
const usePlatformHref = () => {
|
|
30
32
|
const { outerHref } = (0, import_react.use)(import_TinkerableContext.TinkerableContext);
|
|
31
33
|
return (path) => (0, import_urlUtils.platformHref)(outerHref, path);
|
|
32
34
|
};
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
35
|
+
const SAME_CONTEXT_TARGETS = /* @__PURE__ */ new Set(["_top", "_self", "_parent"]);
|
|
36
|
+
function PlatformLink({ path, children, onClick, target = "_top", ...rest }) {
|
|
37
|
+
const { outerHref } = (0, import_react.use)(import_TinkerableContext.TinkerableContext);
|
|
38
|
+
const href = (0, import_urlUtils.platformHref)(outerHref, path);
|
|
39
|
+
const clickHandler = (0, import_anchorClick.useComposedAnchorClick)(
|
|
40
|
+
onClick,
|
|
41
|
+
(event) => {
|
|
42
|
+
if ((0, import_anchorClick.isBrowserGestureClick)(event)) return;
|
|
43
|
+
if (!SAME_CONTEXT_TARGETS.has(target)) return;
|
|
44
|
+
if (!outerHref) return;
|
|
45
|
+
event.preventDefault();
|
|
46
|
+
(0, import_routing.navigate)(href);
|
|
47
|
+
},
|
|
48
|
+
[href, outerHref, target]
|
|
49
|
+
);
|
|
50
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", { ...rest, href, target, onClick: clickHandler, children });
|
|
36
51
|
}
|
|
37
52
|
// Annotate the CommonJS export names for ESM import in node:
|
|
38
53
|
0 && (module.exports = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/platformLink.tsx"],"sourcesContent":["import type { AnchorHTMLAttributes, ReactNode } from 'react';\nimport { use } from 'react';\n\nimport { TinkerableContext } from './TinkerableContext';\nimport { platformHref } from './urlUtils';\n\n/**\n * Build a PLATFORM-space href (`/present/…`, `/edit/github/…`, `/home`) in the host's URL\n * space, reading `outerHref` from {@link TinkerableContext} the way `useTinkerableLink` does.\n * The returned closure is fresh each render (its output is pure, so identity churn is\n * harmless); an empty context (no host, `vite dev`) yields the path unchanged.\n *\n *
|
|
1
|
+
{"version":3,"sources":["../src/platformLink.tsx"],"sourcesContent":["import type { AnchorHTMLAttributes, ReactNode } from 'react';\nimport { use } from 'react';\n\nimport { isBrowserGestureClick, useComposedAnchorClick } from './anchorClick';\nimport { navigate } from './routing';\nimport { TinkerableContext } from './TinkerableContext';\nimport { platformHref } from './urlUtils';\n\n/**\n * Build a PLATFORM-space href (`/present/…`, `/edit/github/…`, `/home`) in the host's URL\n * space, reading `outerHref` from {@link TinkerableContext} the way `useTinkerableLink` does.\n * The returned closure is fresh each render (its output is pure, so identity churn is\n * harmless); an empty context (no host, `vite dev`) yields the path unchanged.\n *\n * Prefer {@link PlatformLink} over calling this directly. An href alone does not reach a\n * platform route from inside the app frame (see that component), so a consumer that renders\n * its own anchor from this string must ask the host itself — otherwise it ships a link that\n * copies and opens-in-new-tab correctly and does nothing at all on a plain click. It is kept\n * exported because the wire and the module surface are additive-only\n * (`SDK_PACKAGING_SPEC` §9): an app pinned to an older SDK may already import it.\n */\nexport const usePlatformHref = (): ((path: string) => string) => {\n const { outerHref } = use(TinkerableContext);\n return (path: string) => platformHref(outerHref, path);\n};\n\n/**\n * Targets that reuse an existing browsing context. All three are unreachable from inside the\n * sandboxed app frame by the anchor alone — `_top`/`_parent` are refused outright, `_self`\n * merely moves the frame — so all three are asked of the host instead. Anything else opens a\n * new context, which the sandbox allows.\n */\nconst SAME_CONTEXT_TARGETS = new Set(['_top', '_self', '_parent']);\n\nexport interface PlatformLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {\n /** A root-relative platform path, e.g. `/present/github/acme/todo`. */\n path: string;\n children?: ReactNode;\n}\n\n/**\n * The ONE way to render an anchor to a PLATFORM route.\n *\n * It builds the href with {@link platformHref} (resolving against the host's outer origin)\n * and, on a plain left-click, asks the HOST to perform the navigation.\n *\n * **Why the anchor alone does not work (R3-568).** Until R3-568 this component relied solely\n * on `target=\"_top\"`. The app frame's sandbox omits `allow-top-navigation-by-user-activation`\n * deliberately — an app that can move the top-level window on its own schedule is a phishing\n * primitive — so the browser refuses outright and logs *\"Unsafe attempt to initiate\n * navigation…\"*. Every platform link in every app was inert on the host: measured on\n * production, no Open, no Fork, no Run, and no way to sign in.\n *\n * The host is therefore the only thing that can perform this navigation, and it is asked the\n * same way in-app routing asks — {@link navigate}. The host decides: it accepts a target\n * outside the app's own path prefix only when the target is same-origin, is a recognised\n * platform route, and the HOST's own `navigator.userActivation` says a person just acted.\n * Nothing the app asserts substitutes for that gesture, and a refusal is the host's to report.\n *\n * **The `href` and `target` stay.** They are what make copy-link, middle-click and\n * open-in-new-tab produce something that resolves for another reader — gestures the sandbox\n * does allow (`allow-popups`), which the handler below deliberately declines to intercept.\n * The href is also the correct behaviour with no host at all (`vite dev`), where there is\n * nobody to ask.\n *\n * External URLs (`https://…`) are not platform routes and should stay plain\n * `<a target=\"_blank\">` anchors.\n */\nexport function PlatformLink({ path, children, onClick, target = '_top', ...rest }: PlatformLinkProps) {\n const { outerHref } = use(TinkerableContext);\n const href = platformHref(outerHref, path);\n\n const clickHandler = useComposedAnchorClick(\n onClick,\n (event) => {\n // Open-in-new-tab gestures are the browser's — the sandbox allows those.\n if (isBrowserGestureClick(event)) return;\n // Intercept every target that stays in an EXISTING browsing context, not just the\n // default. `_top` and `_parent` both address the host document from inside the app\n // frame and are refused by the same missing sandbox flag; `_self` would navigate the\n // app frame itself to a host URL, framing the host inside its own sandbox — the\n // regression `components/Link.tsx` documents. Only a NEW context (`_blank`, a named\n // window) is genuinely the browser's, because that is what `allow-popups` permits.\n if (!SAME_CONTEXT_TARGETS.has(target)) return;\n // No host (`vite dev`): there is nobody to ask, and the anchor's own href is right.\n if (!outerHref) return;\n event.preventDefault();\n navigate(href);\n },\n [href, outerHref, target],\n );\n\n return (\n <a {...rest} href={href} target={target} onClick={clickHandler}>\n {children}\n </a>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6FI;AA5FJ,mBAAoB;AAEpB,yBAA8D;AAC9D,qBAAyB;AACzB,+BAAkC;AAClC,sBAA6B;AAetB,MAAM,kBAAkB,MAAkC;AAC/D,QAAM,EAAE,UAAU,QAAI,kBAAI,0CAAiB;AAC3C,SAAO,CAAC,aAAiB,8BAAa,WAAW,IAAI;AACvD;AAQA,MAAM,uBAAuB,oBAAI,IAAI,CAAC,QAAQ,SAAS,SAAS,CAAC;AAoC1D,SAAS,aAAa,EAAE,MAAM,UAAU,SAAS,SAAS,QAAQ,GAAG,KAAK,GAAsB;AACrG,QAAM,EAAE,UAAU,QAAI,kBAAI,0CAAiB;AAC3C,QAAM,WAAO,8BAAa,WAAW,IAAI;AAEzC,QAAM,mBAAe;AAAA,IACnB;AAAA,IACA,CAAC,UAAU;AAET,cAAI,0CAAsB,KAAK,EAAG;AAOlC,UAAI,CAAC,qBAAqB,IAAI,MAAM,EAAG;AAEvC,UAAI,CAAC,UAAW;AAChB,YAAM,eAAe;AACrB,mCAAS,IAAI;AAAA,IACf;AAAA,IACA,CAAC,MAAM,WAAW,MAAM;AAAA,EAC1B;AAEA,SACE,4CAAC,OAAG,GAAG,MAAM,MAAY,QAAgB,SAAS,cAC/C,UACH;AAEJ;","names":[]}
|
package/dist/platformLink.d.cts
CHANGED
|
@@ -7,10 +7,12 @@ import { AnchorHTMLAttributes, ReactNode } from 'react';
|
|
|
7
7
|
* The returned closure is fresh each render (its output is pure, so identity churn is
|
|
8
8
|
* harmless); an empty context (no host, `vite dev`) yields the path unchanged.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* Prefer {@link PlatformLink} over calling this directly. An href alone does not reach a
|
|
11
|
+
* platform route from inside the app frame (see that component), so a consumer that renders
|
|
12
|
+
* its own anchor from this string must ask the host itself — otherwise it ships a link that
|
|
13
|
+
* copies and opens-in-new-tab correctly and does nothing at all on a plain click. It is kept
|
|
14
|
+
* exported because the wire and the module surface are additive-only
|
|
15
|
+
* (`SDK_PACKAGING_SPEC` §9): an app pinned to an older SDK may already import it.
|
|
14
16
|
*/
|
|
15
17
|
declare const usePlatformHref: () => ((path: string) => string);
|
|
16
18
|
interface PlatformLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
|
|
@@ -19,12 +21,33 @@ interface PlatformLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>
|
|
|
19
21
|
children?: ReactNode;
|
|
20
22
|
}
|
|
21
23
|
/**
|
|
22
|
-
* The ONE way to render an anchor to a PLATFORM route
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
24
|
+
* The ONE way to render an anchor to a PLATFORM route.
|
|
25
|
+
*
|
|
26
|
+
* It builds the href with {@link platformHref} (resolving against the host's outer origin)
|
|
27
|
+
* and, on a plain left-click, asks the HOST to perform the navigation.
|
|
28
|
+
*
|
|
29
|
+
* **Why the anchor alone does not work (R3-568).** Until R3-568 this component relied solely
|
|
30
|
+
* on `target="_top"`. The app frame's sandbox omits `allow-top-navigation-by-user-activation`
|
|
31
|
+
* deliberately — an app that can move the top-level window on its own schedule is a phishing
|
|
32
|
+
* primitive — so the browser refuses outright and logs *"Unsafe attempt to initiate
|
|
33
|
+
* navigation…"*. Every platform link in every app was inert on the host: measured on
|
|
34
|
+
* production, no Open, no Fork, no Run, and no way to sign in.
|
|
35
|
+
*
|
|
36
|
+
* The host is therefore the only thing that can perform this navigation, and it is asked the
|
|
37
|
+
* same way in-app routing asks — {@link navigate}. The host decides: it accepts a target
|
|
38
|
+
* outside the app's own path prefix only when the target is same-origin, is a recognised
|
|
39
|
+
* platform route, and the HOST's own `navigator.userActivation` says a person just acted.
|
|
40
|
+
* Nothing the app asserts substitutes for that gesture, and a refusal is the host's to report.
|
|
41
|
+
*
|
|
42
|
+
* **The `href` and `target` stay.** They are what make copy-link, middle-click and
|
|
43
|
+
* open-in-new-tab produce something that resolves for another reader — gestures the sandbox
|
|
44
|
+
* does allow (`allow-popups`), which the handler below deliberately declines to intercept.
|
|
45
|
+
* The href is also the correct behaviour with no host at all (`vite dev`), where there is
|
|
46
|
+
* nobody to ask.
|
|
47
|
+
*
|
|
48
|
+
* External URLs (`https://…`) are not platform routes and should stay plain
|
|
49
|
+
* `<a target="_blank">` anchors.
|
|
27
50
|
*/
|
|
28
|
-
declare function PlatformLink({ path, children, ...rest }: PlatformLinkProps): react.JSX.Element;
|
|
51
|
+
declare function PlatformLink({ path, children, onClick, target, ...rest }: PlatformLinkProps): react.JSX.Element;
|
|
29
52
|
|
|
30
53
|
export { PlatformLink, type PlatformLinkProps, usePlatformHref };
|
package/dist/platformLink.d.ts
CHANGED
|
@@ -7,10 +7,12 @@ import { AnchorHTMLAttributes, ReactNode } from 'react';
|
|
|
7
7
|
* The returned closure is fresh each render (its output is pure, so identity churn is
|
|
8
8
|
* harmless); an empty context (no host, `vite dev`) yields the path unchanged.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* Prefer {@link PlatformLink} over calling this directly. An href alone does not reach a
|
|
11
|
+
* platform route from inside the app frame (see that component), so a consumer that renders
|
|
12
|
+
* its own anchor from this string must ask the host itself — otherwise it ships a link that
|
|
13
|
+
* copies and opens-in-new-tab correctly and does nothing at all on a plain click. It is kept
|
|
14
|
+
* exported because the wire and the module surface are additive-only
|
|
15
|
+
* (`SDK_PACKAGING_SPEC` §9): an app pinned to an older SDK may already import it.
|
|
14
16
|
*/
|
|
15
17
|
declare const usePlatformHref: () => ((path: string) => string);
|
|
16
18
|
interface PlatformLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
|
|
@@ -19,12 +21,33 @@ interface PlatformLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>
|
|
|
19
21
|
children?: ReactNode;
|
|
20
22
|
}
|
|
21
23
|
/**
|
|
22
|
-
* The ONE way to render an anchor to a PLATFORM route
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
24
|
+
* The ONE way to render an anchor to a PLATFORM route.
|
|
25
|
+
*
|
|
26
|
+
* It builds the href with {@link platformHref} (resolving against the host's outer origin)
|
|
27
|
+
* and, on a plain left-click, asks the HOST to perform the navigation.
|
|
28
|
+
*
|
|
29
|
+
* **Why the anchor alone does not work (R3-568).** Until R3-568 this component relied solely
|
|
30
|
+
* on `target="_top"`. The app frame's sandbox omits `allow-top-navigation-by-user-activation`
|
|
31
|
+
* deliberately — an app that can move the top-level window on its own schedule is a phishing
|
|
32
|
+
* primitive — so the browser refuses outright and logs *"Unsafe attempt to initiate
|
|
33
|
+
* navigation…"*. Every platform link in every app was inert on the host: measured on
|
|
34
|
+
* production, no Open, no Fork, no Run, and no way to sign in.
|
|
35
|
+
*
|
|
36
|
+
* The host is therefore the only thing that can perform this navigation, and it is asked the
|
|
37
|
+
* same way in-app routing asks — {@link navigate}. The host decides: it accepts a target
|
|
38
|
+
* outside the app's own path prefix only when the target is same-origin, is a recognised
|
|
39
|
+
* platform route, and the HOST's own `navigator.userActivation` says a person just acted.
|
|
40
|
+
* Nothing the app asserts substitutes for that gesture, and a refusal is the host's to report.
|
|
41
|
+
*
|
|
42
|
+
* **The `href` and `target` stay.** They are what make copy-link, middle-click and
|
|
43
|
+
* open-in-new-tab produce something that resolves for another reader — gestures the sandbox
|
|
44
|
+
* does allow (`allow-popups`), which the handler below deliberately declines to intercept.
|
|
45
|
+
* The href is also the correct behaviour with no host at all (`vite dev`), where there is
|
|
46
|
+
* nobody to ask.
|
|
47
|
+
*
|
|
48
|
+
* External URLs (`https://…`) are not platform routes and should stay plain
|
|
49
|
+
* `<a target="_blank">` anchors.
|
|
27
50
|
*/
|
|
28
|
-
declare function PlatformLink({ path, children, ...rest }: PlatformLinkProps): react.JSX.Element;
|
|
51
|
+
declare function PlatformLink({ path, children, onClick, target, ...rest }: PlatformLinkProps): react.JSX.Element;
|
|
29
52
|
|
|
30
53
|
export { PlatformLink, type PlatformLinkProps, usePlatformHref };
|
package/dist/platformLink.js
CHANGED
|
@@ -1,15 +1,30 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
3
|
import { use } from "react";
|
|
4
|
+
import { isBrowserGestureClick, useComposedAnchorClick } from "./anchorClick";
|
|
5
|
+
import { navigate } from "./routing";
|
|
4
6
|
import { TinkerableContext } from "./TinkerableContext";
|
|
5
7
|
import { platformHref } from "./urlUtils";
|
|
6
8
|
const usePlatformHref = () => {
|
|
7
9
|
const { outerHref } = use(TinkerableContext);
|
|
8
10
|
return (path) => platformHref(outerHref, path);
|
|
9
11
|
};
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
const SAME_CONTEXT_TARGETS = /* @__PURE__ */ new Set(["_top", "_self", "_parent"]);
|
|
13
|
+
function PlatformLink({ path, children, onClick, target = "_top", ...rest }) {
|
|
14
|
+
const { outerHref } = use(TinkerableContext);
|
|
15
|
+
const href = platformHref(outerHref, path);
|
|
16
|
+
const clickHandler = useComposedAnchorClick(
|
|
17
|
+
onClick,
|
|
18
|
+
(event) => {
|
|
19
|
+
if (isBrowserGestureClick(event)) return;
|
|
20
|
+
if (!SAME_CONTEXT_TARGETS.has(target)) return;
|
|
21
|
+
if (!outerHref) return;
|
|
22
|
+
event.preventDefault();
|
|
23
|
+
navigate(href);
|
|
24
|
+
},
|
|
25
|
+
[href, outerHref, target]
|
|
26
|
+
);
|
|
27
|
+
return /* @__PURE__ */ jsx("a", { ...rest, href, target, onClick: clickHandler, children });
|
|
13
28
|
}
|
|
14
29
|
export {
|
|
15
30
|
PlatformLink,
|