@immediately-run/sdk 0.57.1 → 0.57.4

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.
Files changed (125) hide show
  1. package/dist/agentChatClient.cjs +112 -0
  2. package/dist/agentChatClient.cjs.map +1 -0
  3. package/dist/agentChatClient.d.cts +9 -0
  4. package/dist/agentChatClient.d.ts +9 -0
  5. package/dist/agentChatClient.js +89 -0
  6. package/dist/agentChatClient.js.map +1 -0
  7. package/dist/agentContext.cjs +69 -0
  8. package/dist/agentContext.cjs.map +1 -0
  9. package/dist/agentContext.d.cts +45 -0
  10. package/dist/agentContext.d.ts +45 -0
  11. package/dist/agentContext.js +45 -0
  12. package/dist/agentContext.js.map +1 -0
  13. package/dist/agentLoop.cjs +301 -0
  14. package/dist/agentLoop.cjs.map +1 -0
  15. package/dist/agentLoop.d.cts +267 -0
  16. package/dist/agentLoop.d.ts +267 -0
  17. package/dist/agentLoop.js +271 -0
  18. package/dist/agentLoop.js.map +1 -0
  19. package/dist/agentSteering.cjs +127 -0
  20. package/dist/agentSteering.cjs.map +1 -0
  21. package/dist/agentSteering.d.cts +80 -0
  22. package/dist/agentSteering.d.ts +80 -0
  23. package/dist/agentSteering.js +98 -0
  24. package/dist/agentSteering.js.map +1 -0
  25. package/dist/auth.cjs.map +1 -1
  26. package/dist/auth.d.cts +33 -2
  27. package/dist/auth.d.ts +33 -2
  28. package/dist/auth.js.map +1 -1
  29. package/dist/bundle.cjs +91 -0
  30. package/dist/bundle.cjs.map +1 -0
  31. package/dist/bundle.d.cts +63 -0
  32. package/dist/bundle.d.ts +63 -0
  33. package/dist/bundle.js +62 -0
  34. package/dist/bundle.js.map +1 -0
  35. package/dist/collectHeadings.cjs +59 -0
  36. package/dist/collectHeadings.cjs.map +1 -0
  37. package/dist/collectHeadings.d.cts +16 -0
  38. package/dist/collectHeadings.d.ts +16 -0
  39. package/dist/collectHeadings.js +36 -0
  40. package/dist/collectHeadings.js.map +1 -0
  41. package/dist/corpus.cjs +9 -58
  42. package/dist/corpus.cjs.map +1 -1
  43. package/dist/corpus.d.cts +3 -63
  44. package/dist/corpus.d.ts +3 -63
  45. package/dist/corpus.js +15 -57
  46. package/dist/corpus.js.map +1 -1
  47. package/dist/debug.cjs +115 -0
  48. package/dist/debug.cjs.map +1 -1
  49. package/dist/debug.js +115 -0
  50. package/dist/debug.js.map +1 -1
  51. package/dist/fence.cjs +49 -0
  52. package/dist/fence.cjs.map +1 -0
  53. package/dist/fence.d.cts +4 -0
  54. package/dist/fence.d.ts +4 -0
  55. package/dist/fence.js +26 -0
  56. package/dist/fence.js.map +1 -0
  57. package/dist/formFactor.cjs.map +1 -1
  58. package/dist/formFactor.d.cts +11 -2
  59. package/dist/formFactor.d.ts +11 -2
  60. package/dist/formFactor.js.map +1 -1
  61. package/dist/fs.cjs.map +1 -1
  62. package/dist/fs.d.cts +16 -6
  63. package/dist/fs.d.ts +16 -6
  64. package/dist/fs.js.map +1 -1
  65. package/dist/hooks.cjs.map +1 -1
  66. package/dist/hooks.d.cts +7 -0
  67. package/dist/hooks.d.ts +7 -0
  68. package/dist/hooks.js.map +1 -1
  69. package/dist/index.cjs +19 -1
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.d.cts +11 -3
  72. package/dist/index.d.ts +11 -3
  73. package/dist/index.js +9 -0
  74. package/dist/index.js.map +1 -1
  75. package/dist/launch.cjs +45 -6
  76. package/dist/launch.cjs.map +1 -1
  77. package/dist/launch.d.cts +3 -0
  78. package/dist/launch.d.ts +3 -0
  79. package/dist/launch.js +45 -6
  80. package/dist/launch.js.map +1 -1
  81. package/dist/llm.cjs.map +1 -1
  82. package/dist/llm.d.cts +20 -3
  83. package/dist/llm.d.ts +20 -3
  84. package/dist/llm.js.map +1 -1
  85. package/dist/metadataQueryTool.cjs +271 -0
  86. package/dist/metadataQueryTool.cjs.map +1 -0
  87. package/dist/metadataQueryTool.d.cts +159 -0
  88. package/dist/metadataQueryTool.d.ts +159 -0
  89. package/dist/metadataQueryTool.js +241 -0
  90. package/dist/metadataQueryTool.js.map +1 -0
  91. package/dist/mounts.cjs.map +1 -1
  92. package/dist/mounts.d.cts +22 -3
  93. package/dist/mounts.d.ts +22 -3
  94. package/dist/mounts.js.map +1 -1
  95. package/dist/onFsChange.cjs +13 -1
  96. package/dist/onFsChange.cjs.map +1 -1
  97. package/dist/onFsChange.d.cts +21 -1
  98. package/dist/onFsChange.d.ts +21 -1
  99. package/dist/onFsChange.js +13 -1
  100. package/dist/onFsChange.js.map +1 -1
  101. package/dist/protocolSchemes.cjs +1 -0
  102. package/dist/protocolSchemes.cjs.map +1 -1
  103. package/dist/protocolSchemes.d.cts +1 -0
  104. package/dist/protocolSchemes.d.ts +1 -0
  105. package/dist/protocolSchemes.js +2 -0
  106. package/dist/protocolSchemes.js.map +1 -1
  107. package/dist/recents.cjs +41 -0
  108. package/dist/recents.cjs.map +1 -0
  109. package/dist/recents.d.cts +23 -0
  110. package/dist/recents.d.ts +23 -0
  111. package/dist/recents.js +17 -0
  112. package/dist/recents.js.map +1 -0
  113. package/dist/tasks.cjs +41 -7
  114. package/dist/tasks.cjs.map +1 -1
  115. package/dist/tasks.d.cts +136 -7
  116. package/dist/tasks.d.ts +136 -7
  117. package/dist/tasks.js +39 -7
  118. package/dist/tasks.js.map +1 -1
  119. package/dist/version.cjs +1 -1
  120. package/dist/version.cjs.map +1 -1
  121. package/dist/version.d.cts +1 -1
  122. package/dist/version.d.ts +1 -1
  123. package/dist/version.js +1 -1
  124. package/dist/version.js.map +1 -1
  125. package/package.json +6 -5
@@ -18,14 +18,23 @@ interface FormFactor {
18
18
  width: number;
19
19
  height: number;
20
20
  }
21
- /** Returns the current form factor. Poll for a one-off read. */
21
+ /** Returns the current form factor. Poll for a one-off read.
22
+ *
23
+ * Off-host (plain `vite dev` — no host to report the region's box) this stays at
24
+ * the default forever: `{ class: 'desktop', orientation: 'landscape', width: 1280,
25
+ * height: 800 }`. Don't mistake it for a measurement — locally, size your layout
26
+ * from the DOM if you need the real viewport. */
22
27
  declare const getFormFactor: () => FormFactor;
23
28
  /**
24
29
  * Subscribe to form-factor changes. The listener is invoked immediately with
25
30
  * the current value, then again on every change. Returns an unsubscribe fn.
26
31
  */
27
32
  declare const onFormFactorChange: (listener: (formFactor: FormFactor) => void) => (() => void);
28
- /** React hook returning the current form factor, re-rendering on change. */
33
+ /** React hook returning the current form factor, re-rendering on change.
34
+ *
35
+ * Off-host (plain `vite dev`) it returns the desktop default (`desktop`,
36
+ * `landscape`, 1280×800) forever — the host never reports, so no re-render ever
37
+ * arrives. See {@link getFormFactor}. */
29
38
  declare const useFormFactor: () => FormFactor;
30
39
 
31
40
  export { type FormFactor, type FormFactorClass, type Orientation, getFormFactor, onFormFactorChange, useFormFactor };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/formFactor.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { FORM_FACTOR, REQUEST_FORM_FACTOR } from './generated/protocol';\n\n/**\n * The form factor of the surface your app is rendered into, mirrored from the\n * immediately.run host (UI_AS_APPS_SPEC §5.4.1). Read this to lay out\n * responsively — a narrow chrome panel, a full preview, or a mobile carousel\n * pane all report their box here. The host is the source of truth (it owns the\n * region); you cannot reliably measure your own viewport across the sandbox\n * boundary.\n *\n * Baseline capability `formFactor:read` — every app may read it.\n */\nexport type FormFactorClass = 'mobile' | 'tablet' | 'desktop';\n/** Whether the rendered surface is taller than wide (`portrait`) or wider (`landscape`). */\nexport type Orientation = 'portrait' | 'landscape';\n\n/** The host-reported size class, orientation, and pixel box of your app's surface. */\nexport interface FormFactor {\n class: FormFactorClass;\n orientation: Orientation;\n width: number;\n height: number;\n}\n\n/** Assumed before the host reports — a reasonable desktop default. */\nconst DEFAULT_FORM_FACTOR: FormFactor = {\n class: 'desktop',\n orientation: 'landscape',\n width: 1280,\n height: 800,\n};\n\nconst isFormFactor = (v: unknown): v is FormFactor => {\n const f = v as Partial<FormFactor> | null;\n return (\n !!f &&\n (f.class === 'mobile' || f.class === 'tablet' || f.class === 'desktop') &&\n (f.orientation === 'portrait' || f.orientation === 'landscape') &&\n typeof f.width === 'number' &&\n typeof f.height === 'number'\n );\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `form-factor`\n// and answers `request-form-factor` (wire format: site-main channelBridge.ts).\nconst channel = createPushChannel<FormFactor>({\n pushType: FORM_FACTOR,\n requestType: REQUEST_FORM_FACTOR,\n initial: DEFAULT_FORM_FACTOR,\n parse: (msg) => (isFormFactor(msg.formFactor) ? (msg.formFactor as FormFactor) : undefined),\n});\n\n/** Returns the current form factor. Poll for a one-off read. */\nexport const getFormFactor = (): FormFactor => channel.get();\n\n/**\n * Subscribe to form-factor changes. The listener is invoked immediately with\n * the current value, then again on every change. Returns an unsubscribe fn.\n */\nexport const onFormFactorChange = (listener: (formFactor: FormFactor) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current form factor, re-rendering on change. */\nexport const useFormFactor = (): FormFactor => channel.use();\n"],"mappings":";AAAA,SAAS,yBAAyB;AAClC,SAAS,aAAa,2BAA2B;AAyBjD,MAAM,sBAAkC;AAAA,EACtC,OAAO;AAAA,EACP,aAAa;AAAA,EACb,OAAO;AAAA,EACP,QAAQ;AACV;AAEA,MAAM,eAAe,CAAC,MAAgC;AACpD,QAAM,IAAI;AACV,SACE,CAAC,CAAC,MACD,EAAE,UAAU,YAAY,EAAE,UAAU,YAAY,EAAE,UAAU,eAC5D,EAAE,gBAAgB,cAAc,EAAE,gBAAgB,gBACnD,OAAO,EAAE,UAAU,YACnB,OAAO,EAAE,WAAW;AAExB;AAIA,MAAM,UAAU,kBAA8B;AAAA,EAC5C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAS,aAAa,IAAI,UAAU,IAAK,IAAI,aAA4B;AACnF,CAAC;AAGM,MAAM,gBAAgB,MAAkB,QAAQ,IAAI;AAMpD,MAAM,qBAAqB,CAAC,aACjC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,gBAAgB,MAAkB,QAAQ,IAAI;","names":[]}
1
+ {"version":3,"sources":["../src/formFactor.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { FORM_FACTOR, REQUEST_FORM_FACTOR } from './generated/protocol';\n\n/**\n * The form factor of the surface your app is rendered into, mirrored from the\n * immediately.run host (UI_AS_APPS_SPEC §5.4.1). Read this to lay out\n * responsively — a narrow chrome panel, a full preview, or a mobile carousel\n * pane all report their box here. The host is the source of truth (it owns the\n * region); you cannot reliably measure your own viewport across the sandbox\n * boundary.\n *\n * Baseline capability `formFactor:read` — every app may read it.\n */\nexport type FormFactorClass = 'mobile' | 'tablet' | 'desktop';\n/** Whether the rendered surface is taller than wide (`portrait`) or wider (`landscape`). */\nexport type Orientation = 'portrait' | 'landscape';\n\n/** The host-reported size class, orientation, and pixel box of your app's surface. */\nexport interface FormFactor {\n class: FormFactorClass;\n orientation: Orientation;\n width: number;\n height: number;\n}\n\n/** Assumed before the host reports — a reasonable desktop default. */\nconst DEFAULT_FORM_FACTOR: FormFactor = {\n class: 'desktop',\n orientation: 'landscape',\n width: 1280,\n height: 800,\n};\n\nconst isFormFactor = (v: unknown): v is FormFactor => {\n const f = v as Partial<FormFactor> | null;\n return (\n !!f &&\n (f.class === 'mobile' || f.class === 'tablet' || f.class === 'desktop') &&\n (f.orientation === 'portrait' || f.orientation === 'landscape') &&\n typeof f.width === 'number' &&\n typeof f.height === 'number'\n );\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `form-factor`\n// and answers `request-form-factor` (wire format: site-main channelBridge.ts).\nconst channel = createPushChannel<FormFactor>({\n pushType: FORM_FACTOR,\n requestType: REQUEST_FORM_FACTOR,\n initial: DEFAULT_FORM_FACTOR,\n parse: (msg) => (isFormFactor(msg.formFactor) ? (msg.formFactor as FormFactor) : undefined),\n});\n\n/** Returns the current form factor. Poll for a one-off read.\n *\n * Off-host (plain `vite dev` — no host to report the region's box) this stays at\n * the default forever: `{ class: 'desktop', orientation: 'landscape', width: 1280,\n * height: 800 }`. Don't mistake it for a measurement — locally, size your layout\n * from the DOM if you need the real viewport. */\nexport const getFormFactor = (): FormFactor => channel.get();\n\n/**\n * Subscribe to form-factor changes. The listener is invoked immediately with\n * the current value, then again on every change. Returns an unsubscribe fn.\n */\nexport const onFormFactorChange = (listener: (formFactor: FormFactor) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current form factor, re-rendering on change.\n *\n * Off-host (plain `vite dev`) it returns the desktop default (`desktop`,\n * `landscape`, 1280×800) forever — the host never reports, so no re-render ever\n * arrives. See {@link getFormFactor}. */\nexport const useFormFactor = (): FormFactor => channel.use();\n"],"mappings":";AAAA,SAAS,yBAAyB;AAClC,SAAS,aAAa,2BAA2B;AAyBjD,MAAM,sBAAkC;AAAA,EACtC,OAAO;AAAA,EACP,aAAa;AAAA,EACb,OAAO;AAAA,EACP,QAAQ;AACV;AAEA,MAAM,eAAe,CAAC,MAAgC;AACpD,QAAM,IAAI;AACV,SACE,CAAC,CAAC,MACD,EAAE,UAAU,YAAY,EAAE,UAAU,YAAY,EAAE,UAAU,eAC5D,EAAE,gBAAgB,cAAc,EAAE,gBAAgB,gBACnD,OAAO,EAAE,UAAU,YACnB,OAAO,EAAE,WAAW;AAExB;AAIA,MAAM,UAAU,kBAA8B;AAAA,EAC5C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAS,aAAa,IAAI,UAAU,IAAK,IAAI,aAA4B;AACnF,CAAC;AAQM,MAAM,gBAAgB,MAAkB,QAAQ,IAAI;AAMpD,MAAM,qBAAqB,CAAC,aACjC,QAAQ,SAAS,QAAQ;AAOpB,MAAM,gBAAgB,MAAkB,QAAQ,IAAI;","names":[]}
package/dist/fs.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/fs.ts"],"sourcesContent":["// Typed, discoverable filesystem access — the app-facing surface for the ZenFS\n// mount ports (SDK_FS_SURFACE_SPEC; FILESYSTEM_SPEC §2 the ZenFS-shaped contract).\n//\n// The single most important thing an app does — read/write files in its mounts —\n// previously had NO SDK surface: apps reached an ambient `globalThis.__sandpackSharedFs`\n// by hand-rolling the same accessor (editor/file-explorer `src/fs/mountFs.ts`, \"keep the\n// two in sync\"), with a documented footgun (`module.evaluation.module.bundler.fs` is the\n// WRONG object — it has no `promises`/`stat`). This module is that accessor's ONE home,\n// typed and documented.\n//\n// It adds NO authority: the ZenFS port is already minted and chroot/`ro`-enforced\n// host-side (FILESYSTEM_SPEC §2, UI_AS_APPS §8.7). This is typing + discoverability +\n// de-duplication only. `fs` is a Resource PORT (a byte channel), not a host-brokered RPC,\n// so — unlike the `invoke()` catalog surface — it is hand-written, not gate-table-derived.\nimport type { SandboxMount, MountRule } from './mounts';\nimport { getAppMountPath } from './mounts';\nimport { onFsChange } from './onFsChange';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** The node-compatible promises surface the sandbox ZenFS exposes (the subset we use). */\ninterface NodeFsPromises {\n readFile(path: string, encoding?: any): Promise<string | Uint8Array>;\n writeFile(path: string, data: string | Uint8Array): Promise<void>;\n readdir(path: string, opts?: any): Promise<any[]>;\n stat(path: string): Promise<any>;\n mkdir(path: string, opts?: any): Promise<unknown>;\n rm(path: string, opts?: any): Promise<void>;\n rename(from: string, to: string): Promise<void>;\n}\n\n/** The resolved sandbox ZenFS handle (node-compatible, `/`-rooted). Opaque to apps —\n * reach it through {@link openFs}; the raw handle is the {@link sandboxFs} escape hatch. */\nexport interface SandboxFsPort {\n promises?: NodeFsPromises;\n readFile?: NodeFsPromises['readFile'];\n}\n\nconst hasFs = (fs: any): boolean => typeof fs?.promises?.readFile === 'function' || typeof fs?.readFile === 'function';\n\n/**\n * The resolved sandbox ZenFS, or `null` when unavailable. The ONE home for the\n * resolution order previously duplicated in every app's `mountFs.ts`:\n *\n * 1. `globalThis.__sandpackSharedFs` — the `/`-rooted bound ZenFS the sandbox publishes.\n * 2. fallback: the first `module.evaluation.module.bundler.fs.layers[].boundContext.fs`\n * whose surface has `readFile` (the bundler ZenFS-layer bound context).\n * 3. else `null` (local `vite dev` / before boot).\n *\n * Prefer {@link openFs}; reach for this only when a system app spans mounts in absolute\n * `/mnt/{hash}` paths (the file explorer / editor).\n */\nexport function sandboxFs(): SandboxFsPort | null {\n try {\n const shared = (globalThis as any).__sandpackSharedFs;\n if (hasFs(shared)) return shared as SandboxFsPort;\n } catch {\n /* not in the sandbox */\n }\n try {\n // @ts-ignore - `module` is injected by the sandbox runtime (see sandboxUtils transport).\n // DEPRECATION WINDOW (opened 2026-08-25, R3-278): this `bundler.fs.layers` fallback\n // is injected-bundler API reading — the supported surface is the\n // `__sandpackSharedFs` discovery global above (and `openFs`/`sandboxFs` themselves).\n // Kept through the SDK_PACKAGING_SPEC §9 window; new code must not read bundler.*\n // (scripts/check-bundler-reads.mjs).\n const layers = module?.evaluation?.module?.bundler?.fs?.layers;\n if (Array.isArray(layers)) {\n for (const layer of layers) {\n const fs = layer?.boundContext?.fs;\n if (hasFs(fs)) return fs as SandboxFsPort;\n }\n }\n } catch {\n /* not in the sandbox */\n }\n return null;\n}\n\n/** Is the sandbox filesystem reachable at all? `false` in local `vite dev` and before\n * boot — gate file affordances on it so an app degrades instead of throwing. */\nexport function fsAvailable(): boolean {\n return sandboxFs() != null;\n}\n\n/** A directory entry from {@link MountFs.readdir}. */\nexport interface DirEntry {\n name: string;\n kind: 'file' | 'dir';\n}\n\n/** A stat result from {@link MountFs.stat}. */\nexport interface FileStat {\n kind: 'file' | 'dir';\n size: number;\n mtimeMs?: number;\n}\n\n/** An error from a {@link MountFs} operation, carrying a machine-readable `.code`\n * (mapped from the ZenFS errno) so an app branches on `.code`, never on a message. */\nexport interface FsError extends Error {\n code:\n | 'not-found' // ENOENT\n | 'read-only' // EROFS — a `ro` mount / downgraded role; NEVER surface as UX (gate with canWrite)\n | 'not-permitted' // EACCES\n | 'exists' // EEXIST\n | 'not-empty' // ENOTEMPTY\n | 'invalid-path' // a `..` segment / absolute escape was passed as a relPath\n | 'unavailable' // no sandbox fs (local dev / pre-boot)\n | 'unknown';\n}\n\nconst ERRNO: Record<string, FsError['code']> = {\n ENOENT: 'not-found',\n EROFS: 'read-only',\n EACCES: 'not-permitted',\n EPERM: 'not-permitted',\n EEXIST: 'exists',\n ENOTEMPTY: 'not-empty',\n};\n\nconst fsError = (code: FsError['code'], message: string): FsError => {\n const err = new Error(message) as FsError;\n err.code = code;\n return err;\n};\n\nconst mapError = (e: unknown): FsError => {\n const errno = (e as { code?: string } | null)?.code;\n const code: FsError['code'] = (errno ? ERRNO[errno] : undefined) ?? 'unknown';\n const err = new Error((e as Error)?.message ?? 'fs operation failed') as FsError;\n err.code = code;\n return err;\n};\n\n// Lazily constructed so merely *importing* this module doesn't touch the\n// TextEncoder/TextDecoder globals — some non-DOM test/build environments only\n// provide them on demand, and no image/URL path needs them at all.\nlet _decoder: TextDecoder | undefined;\nlet _encoder: TextEncoder | undefined;\nconst decoder = (): TextDecoder => (_decoder ??= new TextDecoder());\nconst encoder = (): TextEncoder => (_encoder ??= new TextEncoder());\n\n// Extension → MIME type for the kinds an app displays inline. Images first (the\n// common case — `<img src>` off a mount), plus a couple of adjacent binary kinds.\n// Deliberately small: `mimeTypeFor` returns undefined for anything not here and\n// callers fall back to `application/octet-stream`.\nconst MIME_BY_EXT: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n};\n\n/**\n * Best-effort MIME type from a filename's extension — mainly image kinds\n * (png/jpg/jpeg/gif/webp/avif/svg/bmp/ico). Returns `undefined` when the\n * extension isn't recognized (the caller falls back to `application/octet-stream`).\n * Used by {@link MountFs.readBlob} / {@link MountFs.readObjectUrl}; exported so an\n * app can label a Blob it builds itself.\n */\nexport function mimeTypeFor(path: string): string | undefined {\n const dot = path.lastIndexOf('.');\n if (dot < 0) return undefined;\n return MIME_BY_EXT[path.slice(dot + 1).toLowerCase()];\n}\n\n// Join a mount-RELATIVE path under the mount root, rejecting `..` escapes and absolute\n// paths (CLAUDE.md security rule 3 — don't probe for escapes). The host chroot is the\n// real enforcer; this keeps an honest app from accidentally naming outside its grant.\nconst resolveUnder = (root: string, relPath: string): string => {\n if (relPath.startsWith('/')) {\n throw fsError('invalid-path', `expected a mount-relative path, got absolute \"${relPath}\"`);\n }\n const parts: string[] = [];\n for (const seg of relPath.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') {\n throw fsError('invalid-path', `\"${relPath}\" escapes the mount root`);\n }\n parts.push(seg);\n }\n const base = root.endsWith('/') ? root.slice(0, -1) : root;\n return parts.length ? `${base}/${parts.join('/')}` : base;\n};\n\n// The longest matching `rules` subtree governs a path (mounts.ts MountRule); fall back to\n// the whole-mount `mode`. A CLIENT-SIDE hint mirroring the host rule — EROFS stays\n// authoritative (the host re-checks live policy on every write).\nconst writableAt = (mount: SandboxMount, relPath: string): boolean => {\n const path =\n '/' +\n relPath\n .split('/')\n .filter((s) => s && s !== '.')\n .join('/');\n const rules: MountRule[] | undefined = mount.rules;\n if (rules && rules.length) {\n let best: MountRule | undefined;\n for (const r of rules) {\n const sub = r.subtree.endsWith('/') ? r.subtree : r.subtree + '/';\n if (path === r.subtree || path.startsWith(sub) || r.subtree === '/') {\n if (!best || r.subtree.length > best.subtree.length) best = r;\n }\n }\n if (best) return best.mode === 'rw';\n }\n return (mount.mode ?? 'rw') === 'rw';\n};\n\n/** A mount-anchored, typed filesystem view. All paths are RELATIVE to the mount root;\n * the accessor resolves them under `mount.path`. Async-only (ZenFS rides a MessagePort).\n * Obtain one with {@link openFs}. */\nexport interface MountFs {\n /** The mount this view is anchored to (read `mode`/`rules` for writability). */\n readonly mount: SandboxMount;\n /** Read a file as UTF-8 text (`encoding: 'utf8'`) or raw bytes (omit encoding). */\n readFile(relPath: string, encoding: 'utf8'): Promise<string>;\n readFile(relPath: string): Promise<Uint8Array>;\n /** Read a file's bytes as a `Blob`, tagged with a MIME `type` inferred from the\n * extension ({@link mimeTypeFor}) or `opts.type` when given (falls back to\n * `application/octet-stream`). The building block for downloads and object URLs. */\n readBlob(relPath: string, opts?: { type?: string }): Promise<Blob>;\n /** Read a file into an **object URL** suitable for `<img src>` / `<a href>` — the\n * fix for \"an opaque-origin iframe can't fetch a mount path\". Returns the `url`\n * and a `revoke()` you MUST call when done (typically on unmount) or the URL\n * leaks. Prefer the `useObjectUrl` hook / `MountImage` component, which revoke\n * for you; reach for this directly only outside React. */\n readObjectUrl(relPath: string, opts?: { type?: string }): Promise<{ url: string; revoke: () => void }>;\n /** Write text or bytes, creating or truncating the file. Throws `read-only` on a `ro` mount. */\n writeFile(relPath: string, data: string | Uint8Array): Promise<void>;\n /** List a directory (the mount root when `relPath` is omitted). */\n readdir(relPath?: string): Promise<DirEntry[]>;\n /** Stat a path. Throws `not-found` if absent. */\n stat(relPath: string): Promise<FileStat>;\n /** Does `relPath` exist? Never throws on absence. */\n exists(relPath: string): Promise<boolean>;\n /** Create a directory (pass `{ recursive: true }` to make parents). */\n mkdir(relPath: string, opts?: { recursive?: boolean }): Promise<void>;\n /** Remove a file, or a directory with `{ recursive: true }`. */\n rm(relPath: string, opts?: { recursive?: boolean }): Promise<void>;\n /** Rename/move within the mount. */\n rename(fromRel: string, toRel: string): Promise<void>;\n /** Client-side writability hint for `relPath` (mount `mode` ∩ longest-matching `rule`),\n * so an app can hide an \"edit\" affordance instead of catching `read-only`\n * (EDITOR_FIRST_EDITING_SPEC §3). Re-evaluate on `onMountsChange` — a role downgrade\n * flips it. EROFS from the host stays authoritative. */\n canWrite(relPath?: string): boolean;\n /** Subscribe to changes to files in this mount — the mount-scoped projection of\n * the host working-tree change stream (`onFsChange`), so a viewer re-reads an\n * affected file instead of polling (SDK_FS_SURFACE_SPEC §5). The callback gets\n * the changed paths RELATIVE to this mount (feed them straight back into\n * `readFile`/`stat`/…). Returns an unsubscribe fn.\n *\n * **Working-tree-only in v1 (an honest gap, O2):** the host push channel carries\n * only working-tree changes, so `onChange` on a NON-working-tree mount (a space)\n * is an inert subscription that never fires until that channel lands. Like\n * `onFsChange`, origin-exclusion (ignoring the echo of your own write) is the\n * caller's responsibility. */\n onChange(cb: (changedRelPaths: string[]) => void): () => void;\n}\n\nconst promisesOf = (port: SandboxFsPort): NodeFsPromises => port.promises ?? (port as unknown as NodeFsPromises);\n\n/**\n * Open a typed, mount-anchored filesystem view (SDK_FS_SURFACE_SPEC §2.1). Pure-client:\n * resolves the ambient ZenFS once ({@link sandboxFs}) and binds it to `mount.path`, so you\n * read/write with paths RELATIVE to the mount root — you cannot accidentally name a path\n * outside your grant (a `..`/absolute path throws `invalid-path`; the host chroot is the\n * real enforcer).\n *\n * ```ts\n * import { mountSpace } from '@immediately-run/sdk';\n * import { openFs } from '@immediately-run/sdk/fs';\n * const fs = openFs(await mountSpace({ spaceId }));\n * const text = await fs.readFile('notes/idea.mdx', 'utf8');\n * if (fs.canWrite('notes/idea.mdx')) await fs.writeFile('notes/idea.mdx', text);\n * ```\n *\n * Throws {@link FsError} `unavailable` if the sandbox fs is not present (local `vite dev`\n * / before boot — gate with {@link fsAvailable}). Per-op failures throw {@link FsError}\n * with a mapped `.code` (`not-found`, `read-only`, …).\n */\nexport function openFs(mount: SandboxMount): MountFs {\n const root = mount.path;\n\n const port = (): NodeFsPromises => {\n const p = sandboxFs();\n if (!p) throw fsError('unavailable', 'immediately.run: sandbox filesystem unavailable');\n return promisesOf(p);\n };\n\n const api: MountFs = {\n mount,\n async readFile(relPath: string, encoding?: 'utf8'): Promise<any> {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const data = await p.readFile(abs);\n const bytes = typeof data === 'string' ? encoder().encode(data) : (data as Uint8Array);\n return encoding === 'utf8' ? decoder().decode(bytes) : bytes;\n } catch (e) {\n throw mapError(e);\n }\n },\n async readBlob(relPath, opts) {\n const bytes = await api.readFile(relPath);\n const type = opts?.type ?? mimeTypeFor(relPath) ?? 'application/octet-stream';\n return new Blob([bytes as BlobPart], { type });\n },\n async readObjectUrl(relPath, opts) {\n const blob = await api.readBlob(relPath, opts);\n const url = URL.createObjectURL(blob);\n return { url, revoke: () => URL.revokeObjectURL(url) };\n },\n async writeFile(relPath, data) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.writeFile(abs, typeof data === 'string' ? encoder().encode(data) : data);\n } catch (e) {\n throw mapError(e);\n }\n },\n async readdir(relPath = '') {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const entries = await p.readdir(abs, { withFileTypes: true });\n return entries.map((d: any) =>\n typeof d === 'string'\n ? ({ name: d, kind: 'file' } as DirEntry)\n : ({ name: d.name, kind: d.isDirectory?.() ? 'dir' : 'file' } as DirEntry),\n );\n } catch (e) {\n throw mapError(e);\n }\n },\n async stat(relPath) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const s: any = await p.stat(abs);\n return {\n kind: s.isDirectory?.() ? 'dir' : 'file',\n size: typeof s.size === 'number' ? s.size : 0,\n mtimeMs: typeof s.mtimeMs === 'number' ? s.mtimeMs : undefined,\n };\n } catch (e) {\n throw mapError(e);\n }\n },\n async exists(relPath) {\n try {\n await api.stat(relPath);\n return true;\n } catch (e) {\n if ((e as FsError).code === 'not-found') return false;\n if ((e as FsError).code === 'unavailable' || (e as FsError).code === 'invalid-path') {\n throw e;\n }\n return false;\n }\n },\n async mkdir(relPath, opts) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.mkdir(abs, { recursive: opts?.recursive ?? false });\n } catch (e) {\n throw mapError(e);\n }\n },\n async rm(relPath, opts) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.rm(abs, { recursive: opts?.recursive ?? false });\n } catch (e) {\n throw mapError(e);\n }\n },\n async rename(fromRel, toRel) {\n const p = port();\n const from = resolveUnder(root, fromRel);\n const to = resolveUnder(root, toRel);\n try {\n await p.rename(from, to);\n } catch (e) {\n throw mapError(e);\n }\n },\n canWrite(relPath = '') {\n return writableAt(mount, relPath);\n },\n onChange(cb) {\n // §5 — mount-scoped projection of the working-tree change channel\n // (`onFsChange`). v1 is WORKING-TREE-ONLY: the host pushes only working-tree\n // changes, so a non-working-tree mount (a space) has no channel yet (O2) and\n // gets an inert subscription rather than another mount's paths leaking in.\n if (root !== getAppMountPath()) {\n return () => {}; // no channel for this mount — inert (honest v1 gap)\n }\n return onFsChange((change) => {\n // Skip the empty pre-first-event initial batch; forward only real changes,\n // as mount-relative paths (drop the repo-relative leading slash) so they\n // feed straight back into readFile/stat/etc.\n if (change.paths.length === 0) return;\n cb(change.paths.map((p) => p.replace(/^\\/+/, '')));\n });\n },\n };\n return api;\n}\n\n/** Open a mount-anchored view of this app's OWN repository working tree — a convenience\n * over {@link openFs} using `getAppMountPath()` (FILE_SHARING_SPEC §11.2). */\nexport function openAppFs(): MountFs {\n return openFs({ path: getAppMountPath(), type: 'repo' } as SandboxMount);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,oBAAgC;AAChC,wBAA2B;AAsB3B,MAAM,QAAQ,CAAC,OAAqB,OAAO,IAAI,UAAU,aAAa,cAAc,OAAO,IAAI,aAAa;AAcrG,SAAS,YAAkC;AAChD,MAAI;AACF,UAAM,SAAU,WAAmB;AACnC,QAAI,MAAM,MAAM,EAAG,QAAO;AAAA,EAC5B,QAAQ;AAAA,EAER;AACA,MAAI;AAOF,UAAM,SAAS,QAAQ,YAAY,QAAQ,SAAS,IAAI;AACxD,QAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,iBAAW,SAAS,QAAQ;AAC1B,cAAM,KAAK,OAAO,cAAc;AAChC,YAAI,MAAM,EAAE,EAAG,QAAO;AAAA,MACxB;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT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,MAAM,KAAK;AACnC,UAAI;AACF,cAAM,EAAE,OAAO,MAAM,EAAE;AAAA,MACzB,SAAS,GAAG;AACV,cAAM,SAAS,CAAC;AAAA,MAClB;AAAA,IACF;AAAA,IACA,SAAS,UAAU,IAAI;AACrB,aAAO,WAAW,OAAO,OAAO;AAAA,IAClC;AAAA,IACA,SAAS,IAAI;AAKX,UAAI,aAAS,+BAAgB,GAAG;AAC9B,eAAO,MAAM;AAAA,QAAC;AAAA,MAChB;AACA,iBAAO,8BAAW,CAAC,WAAW;AAI5B,YAAI,OAAO,MAAM,WAAW,EAAG;AAC/B,WAAG,OAAO,MAAM,IAAI,CAAC,MAAM,EAAE,QAAQ,QAAQ,EAAE,CAAC,CAAC;AAAA,MACnD,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AAIO,SAAS,YAAqB;AACnC,SAAO,OAAO,EAAE,UAAM,+BAAgB,GAAG,MAAM,OAAO,CAAiB;AACzE;","names":[]}
1
+ {"version":3,"sources":["../src/fs.ts"],"sourcesContent":["// Typed, discoverable filesystem access — the app-facing surface for the ZenFS\n// mount ports (SDK_FS_SURFACE_SPEC; FILESYSTEM_SPEC §2 the ZenFS-shaped contract).\n//\n// The single most important thing an app does — read/write files in its mounts —\n// previously had NO SDK surface: apps reached an ambient `globalThis.__sandpackSharedFs`\n// by hand-rolling the same accessor (editor/file-explorer `src/fs/mountFs.ts`, \"keep the\n// two in sync\"), with a documented footgun (`module.evaluation.module.bundler.fs` is the\n// WRONG object — it has no `promises`/`stat`). This module is that accessor's ONE home,\n// typed and documented.\n//\n// It adds NO authority: the ZenFS port is already minted and chroot/`ro`-enforced\n// host-side (FILESYSTEM_SPEC §2, UI_AS_APPS §8.7). This is typing + discoverability +\n// de-duplication only. `fs` is a Resource PORT (a byte channel), not a host-brokered RPC,\n// so — unlike the `invoke()` catalog surface — it is hand-written, not gate-table-derived.\nimport type { SandboxMount, MountRule } from './mounts';\nimport { getAppMountPath } from './mounts';\nimport { onFsChange } from './onFsChange';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** The node-compatible promises surface the sandbox ZenFS exposes (the subset we use). */\ninterface NodeFsPromises {\n readFile(path: string, encoding?: any): Promise<string | Uint8Array>;\n writeFile(path: string, data: string | Uint8Array): Promise<void>;\n readdir(path: string, opts?: any): Promise<any[]>;\n stat(path: string): Promise<any>;\n mkdir(path: string, opts?: any): Promise<unknown>;\n rm(path: string, opts?: any): Promise<void>;\n rename(from: string, to: string): Promise<void>;\n}\n\n/** The resolved sandbox ZenFS handle (node-compatible, `/`-rooted). Opaque to apps —\n * reach it through {@link openFs}; the raw handle is the {@link sandboxFs} escape hatch. */\nexport interface SandboxFsPort {\n promises?: NodeFsPromises;\n readFile?: NodeFsPromises['readFile'];\n}\n\nconst hasFs = (fs: any): boolean => typeof fs?.promises?.readFile === 'function' || typeof fs?.readFile === 'function';\n\n/**\n * The resolved sandbox ZenFS, or `null` when unavailable. The ONE home for the\n * resolution order previously duplicated in every app's `mountFs.ts`:\n *\n * 1. `globalThis.__sandpackSharedFs` — the `/`-rooted bound ZenFS the sandbox publishes.\n * 2. fallback: the first `module.evaluation.module.bundler.fs.layers[].boundContext.fs`\n * whose surface has `readFile` (the bundler ZenFS-layer bound context).\n * 3. else `null` (plain local `vite dev` / before boot).\n *\n * Under `vite dev` WITH the `@immediately-run/dev-fs` plugin (>= 0.5.0), step 1\n * resolves: the plugin publishes its local-disk fs bridge at the same\n * `__sandpackSharedFs` global, so `openFs` / `readBlob` / `readObjectUrl` /\n * `useObjectUrl` work locally through this existing path with no special-casing.\n * Without the plugin they fail with `unavailable`.\n *\n * Prefer {@link openFs}; reach for this only when a system app spans mounts in absolute\n * `/mnt/{hash}` paths (the file explorer / editor).\n */\nexport function sandboxFs(): SandboxFsPort | null {\n try {\n const shared = (globalThis as any).__sandpackSharedFs;\n if (hasFs(shared)) return shared as SandboxFsPort;\n } catch {\n /* not in the sandbox */\n }\n try {\n // @ts-ignore - `module` is injected by the sandbox runtime (see sandboxUtils transport).\n // DEPRECATION WINDOW (opened 2026-08-25, R3-278): this `bundler.fs.layers` fallback\n // is injected-bundler API reading — the supported surface is the\n // `__sandpackSharedFs` discovery global above (and `openFs`/`sandboxFs` themselves).\n // Kept through the SDK_PACKAGING_SPEC §9 window; new code must not read bundler.*\n // (scripts/check-bundler-reads.mjs).\n const layers = module?.evaluation?.module?.bundler?.fs?.layers;\n if (Array.isArray(layers)) {\n for (const layer of layers) {\n const fs = layer?.boundContext?.fs;\n if (hasFs(fs)) return fs as SandboxFsPort;\n }\n }\n } catch {\n /* not in the sandbox */\n }\n return null;\n}\n\n/** Is the sandbox filesystem reachable at all? `false` in plain local `vite dev` and\n * before boot — gate file affordances on it so an app degrades instead of throwing.\n * `true` under `vite dev` with the `@immediately-run/dev-fs` plugin (>= 0.5.0),\n * which publishes its bridge where {@link sandboxFs} discovers it. */\nexport function fsAvailable(): boolean {\n return sandboxFs() != null;\n}\n\n/** A directory entry from {@link MountFs.readdir}. */\nexport interface DirEntry {\n name: string;\n kind: 'file' | 'dir';\n}\n\n/** A stat result from {@link MountFs.stat}. */\nexport interface FileStat {\n kind: 'file' | 'dir';\n size: number;\n mtimeMs?: number;\n}\n\n/** An error from a {@link MountFs} operation, carrying a machine-readable `.code`\n * (mapped from the ZenFS errno) so an app branches on `.code`, never on a message. */\nexport interface FsError extends Error {\n code:\n | 'not-found' // ENOENT\n | 'read-only' // EROFS — a `ro` mount / downgraded role; NEVER surface as UX (gate with canWrite)\n | 'not-permitted' // EACCES\n | 'exists' // EEXIST\n | 'not-empty' // ENOTEMPTY\n | 'invalid-path' // a `..` segment / absolute escape was passed as a relPath\n | 'unavailable' // no sandbox fs (local dev / pre-boot)\n | 'unknown';\n}\n\nconst ERRNO: Record<string, FsError['code']> = {\n ENOENT: 'not-found',\n EROFS: 'read-only',\n EACCES: 'not-permitted',\n EPERM: 'not-permitted',\n EEXIST: 'exists',\n ENOTEMPTY: 'not-empty',\n};\n\nconst fsError = (code: FsError['code'], message: string): FsError => {\n const err = new Error(message) as FsError;\n err.code = code;\n return err;\n};\n\nconst mapError = (e: unknown): FsError => {\n const errno = (e as { code?: string } | null)?.code;\n const code: FsError['code'] = (errno ? ERRNO[errno] : undefined) ?? 'unknown';\n const err = new Error((e as Error)?.message ?? 'fs operation failed') as FsError;\n err.code = code;\n return err;\n};\n\n// Lazily constructed so merely *importing* this module doesn't touch the\n// TextEncoder/TextDecoder globals — some non-DOM test/build environments only\n// provide them on demand, and no image/URL path needs them at all.\nlet _decoder: TextDecoder | undefined;\nlet _encoder: TextEncoder | undefined;\nconst decoder = (): TextDecoder => (_decoder ??= new TextDecoder());\nconst encoder = (): TextEncoder => (_encoder ??= new TextEncoder());\n\n// Extension → MIME type for the kinds an app displays inline. Images first (the\n// common case — `<img src>` off a mount), plus a couple of adjacent binary kinds.\n// Deliberately small: `mimeTypeFor` returns undefined for anything not here and\n// callers fall back to `application/octet-stream`.\nconst MIME_BY_EXT: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n};\n\n/**\n * Best-effort MIME type from a filename's extension — mainly image kinds\n * (png/jpg/jpeg/gif/webp/avif/svg/bmp/ico). Returns `undefined` when the\n * extension isn't recognized (the caller falls back to `application/octet-stream`).\n * Used by {@link MountFs.readBlob} / {@link MountFs.readObjectUrl}; exported so an\n * app can label a Blob it builds itself.\n */\nexport function mimeTypeFor(path: string): string | undefined {\n const dot = path.lastIndexOf('.');\n if (dot < 0) return undefined;\n return MIME_BY_EXT[path.slice(dot + 1).toLowerCase()];\n}\n\n// Join a mount-RELATIVE path under the mount root, rejecting `..` escapes and absolute\n// paths (CLAUDE.md security rule 3 — don't probe for escapes). The host chroot is the\n// real enforcer; this keeps an honest app from accidentally naming outside its grant.\nconst resolveUnder = (root: string, relPath: string): string => {\n if (relPath.startsWith('/')) {\n throw fsError('invalid-path', `expected a mount-relative path, got absolute \"${relPath}\"`);\n }\n const parts: string[] = [];\n for (const seg of relPath.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') {\n throw fsError('invalid-path', `\"${relPath}\" escapes the mount root`);\n }\n parts.push(seg);\n }\n const base = root.endsWith('/') ? root.slice(0, -1) : root;\n return parts.length ? `${base}/${parts.join('/')}` : base;\n};\n\n// The longest matching `rules` subtree governs a path (mounts.ts MountRule); fall back to\n// the whole-mount `mode`. A CLIENT-SIDE hint mirroring the host rule — EROFS stays\n// authoritative (the host re-checks live policy on every write).\nconst writableAt = (mount: SandboxMount, relPath: string): boolean => {\n const path =\n '/' +\n relPath\n .split('/')\n .filter((s) => s && s !== '.')\n .join('/');\n const rules: MountRule[] | undefined = mount.rules;\n if (rules && rules.length) {\n let best: MountRule | undefined;\n for (const r of rules) {\n const sub = r.subtree.endsWith('/') ? r.subtree : r.subtree + '/';\n if (path === r.subtree || path.startsWith(sub) || r.subtree === '/') {\n if (!best || r.subtree.length > best.subtree.length) best = r;\n }\n }\n if (best) return best.mode === 'rw';\n }\n return (mount.mode ?? 'rw') === 'rw';\n};\n\n/** A mount-anchored, typed filesystem view. All paths are RELATIVE to the mount root;\n * the accessor resolves them under `mount.path`. Async-only (ZenFS rides a MessagePort).\n * Obtain one with {@link openFs}. */\nexport interface MountFs {\n /** The mount this view is anchored to (read `mode`/`rules` for writability). */\n readonly mount: SandboxMount;\n /** Read a file as UTF-8 text (`encoding: 'utf8'`) or raw bytes (omit encoding). */\n readFile(relPath: string, encoding: 'utf8'): Promise<string>;\n readFile(relPath: string): Promise<Uint8Array>;\n /** Read a file's bytes as a `Blob`, tagged with a MIME `type` inferred from the\n * extension ({@link mimeTypeFor}) or `opts.type` when given (falls back to\n * `application/octet-stream`). The building block for downloads and object URLs. */\n readBlob(relPath: string, opts?: { type?: string }): Promise<Blob>;\n /** Read a file into an **object URL** suitable for `<img src>` / `<a href>` — the\n * fix for \"an opaque-origin iframe can't fetch a mount path\". Returns the `url`\n * and a `revoke()` you MUST call when done (typically on unmount) or the URL\n * leaks. Prefer the `useObjectUrl` hook / `MountImage` component, which revoke\n * for you; reach for this directly only outside React. */\n readObjectUrl(relPath: string, opts?: { type?: string }): Promise<{ url: string; revoke: () => void }>;\n /** Write text or bytes, creating or truncating the file. Throws `read-only` on a `ro` mount. */\n writeFile(relPath: string, data: string | Uint8Array): Promise<void>;\n /** List a directory (the mount root when `relPath` is omitted). */\n readdir(relPath?: string): Promise<DirEntry[]>;\n /** Stat a path. Throws `not-found` if absent. */\n stat(relPath: string): Promise<FileStat>;\n /** Does `relPath` exist? Never throws on absence. */\n exists(relPath: string): Promise<boolean>;\n /** Create a directory (pass `{ recursive: true }` to make parents). */\n mkdir(relPath: string, opts?: { recursive?: boolean }): Promise<void>;\n /** Remove a file, or a directory with `{ recursive: true }`. */\n rm(relPath: string, opts?: { recursive?: boolean }): Promise<void>;\n /** Rename/move within the mount. */\n rename(fromRel: string, toRel: string): Promise<void>;\n /** Client-side writability hint for `relPath` (mount `mode` ∩ longest-matching `rule`),\n * so an app can hide an \"edit\" affordance instead of catching `read-only`\n * (EDITOR_FIRST_EDITING_SPEC §3). Re-evaluate on `onMountsChange` — a role downgrade\n * flips it. EROFS from the host stays authoritative. */\n canWrite(relPath?: string): boolean;\n /** Subscribe to changes to files in this mount — the mount-scoped projection of\n * the host working-tree change stream (`onFsChange`), so a viewer re-reads an\n * affected file instead of polling (SDK_FS_SURFACE_SPEC §5). The callback gets\n * the changed paths RELATIVE to this mount (feed them straight back into\n * `readFile`/`stat`/…). Returns an unsubscribe fn.\n *\n * **Working-tree-only in v1 (an honest gap, O2):** the host push channel carries\n * only working-tree changes, so `onChange` on a NON-working-tree mount (a space)\n * is an inert subscription that never fires until that channel lands. Like\n * `onFsChange`, origin-exclusion (ignoring the echo of your own write) is the\n * caller's responsibility. */\n onChange(cb: (changedRelPaths: string[]) => void): () => void;\n}\n\nconst promisesOf = (port: SandboxFsPort): NodeFsPromises => port.promises ?? (port as unknown as NodeFsPromises);\n\n/**\n * Open a typed, mount-anchored filesystem view (SDK_FS_SURFACE_SPEC §2.1). Pure-client:\n * resolves the ambient ZenFS once ({@link sandboxFs}) and binds it to `mount.path`, so you\n * read/write with paths RELATIVE to the mount root — you cannot accidentally name a path\n * outside your grant (a `..`/absolute path throws `invalid-path`; the host chroot is the\n * real enforcer).\n *\n * ```ts\n * import { mountSpace } from '@immediately-run/sdk';\n * import { openFs } from '@immediately-run/sdk/fs';\n * const fs = openFs(await mountSpace({ spaceId }));\n * const text = await fs.readFile('notes/idea.mdx', 'utf8');\n * if (fs.canWrite('notes/idea.mdx')) await fs.writeFile('notes/idea.mdx', text);\n * ```\n *\n * Throws {@link FsError} `unavailable` if the sandbox fs is not present (plain local\n * `vite dev` / before boot — gate with {@link fsAvailable}; under `vite dev` the\n * `@immediately-run/dev-fs` plugin >= 0.5.0 provides it, see {@link sandboxFs}).\n * Per-op failures throw {@link FsError} with a mapped `.code` (`not-found`,\n * `read-only`, …).\n */\nexport function openFs(mount: SandboxMount): MountFs {\n const root = mount.path;\n\n const port = (): NodeFsPromises => {\n const p = sandboxFs();\n if (!p) throw fsError('unavailable', 'immediately.run: sandbox filesystem unavailable');\n return promisesOf(p);\n };\n\n const api: MountFs = {\n mount,\n async readFile(relPath: string, encoding?: 'utf8'): Promise<any> {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const data = await p.readFile(abs);\n const bytes = typeof data === 'string' ? encoder().encode(data) : (data as Uint8Array);\n return encoding === 'utf8' ? decoder().decode(bytes) : bytes;\n } catch (e) {\n throw mapError(e);\n }\n },\n async readBlob(relPath, opts) {\n const bytes = await api.readFile(relPath);\n const type = opts?.type ?? mimeTypeFor(relPath) ?? 'application/octet-stream';\n return new Blob([bytes as BlobPart], { type });\n },\n async readObjectUrl(relPath, opts) {\n const blob = await api.readBlob(relPath, opts);\n const url = URL.createObjectURL(blob);\n return { url, revoke: () => URL.revokeObjectURL(url) };\n },\n async writeFile(relPath, data) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.writeFile(abs, typeof data === 'string' ? encoder().encode(data) : data);\n } catch (e) {\n throw mapError(e);\n }\n },\n async readdir(relPath = '') {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const entries = await p.readdir(abs, { withFileTypes: true });\n return entries.map((d: any) =>\n typeof d === 'string'\n ? ({ name: d, kind: 'file' } as DirEntry)\n : ({ name: d.name, kind: d.isDirectory?.() ? 'dir' : 'file' } as DirEntry),\n );\n } catch (e) {\n throw mapError(e);\n }\n },\n async stat(relPath) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const s: any = await p.stat(abs);\n return {\n kind: s.isDirectory?.() ? 'dir' : 'file',\n size: typeof s.size === 'number' ? s.size : 0,\n mtimeMs: typeof s.mtimeMs === 'number' ? s.mtimeMs : undefined,\n };\n } catch (e) {\n throw mapError(e);\n }\n },\n async exists(relPath) {\n try {\n await api.stat(relPath);\n return true;\n } catch (e) {\n if ((e as FsError).code === 'not-found') return false;\n if ((e as FsError).code === 'unavailable' || (e as FsError).code === 'invalid-path') {\n throw e;\n }\n return false;\n }\n },\n async mkdir(relPath, opts) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.mkdir(abs, { recursive: opts?.recursive ?? false });\n } catch (e) {\n throw mapError(e);\n }\n },\n async rm(relPath, opts) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.rm(abs, { recursive: opts?.recursive ?? false });\n } catch (e) {\n throw mapError(e);\n }\n },\n async rename(fromRel, toRel) {\n const p = port();\n const from = resolveUnder(root, fromRel);\n const to = resolveUnder(root, toRel);\n try {\n await p.rename(from, to);\n } catch (e) {\n throw mapError(e);\n }\n },\n canWrite(relPath = '') {\n return writableAt(mount, relPath);\n },\n onChange(cb) {\n // §5 — mount-scoped projection of the working-tree change channel\n // (`onFsChange`). v1 is WORKING-TREE-ONLY: the host pushes only working-tree\n // changes, so a non-working-tree mount (a space) has no channel yet (O2) and\n // gets an inert subscription rather than another mount's paths leaking in.\n if (root !== getAppMountPath()) {\n return () => {}; // no channel for this mount — inert (honest v1 gap)\n }\n return onFsChange((change) => {\n // Skip the empty pre-first-event initial batch; forward only real changes,\n // as mount-relative paths (drop the repo-relative leading slash) so they\n // feed straight back into readFile/stat/etc.\n if (change.paths.length === 0) return;\n cb(change.paths.map((p) => p.replace(/^\\/+/, '')));\n });\n },\n };\n return api;\n}\n\n/** Open a mount-anchored view of this app's OWN repository working tree — a convenience\n * over {@link openFs} using `getAppMountPath()` (FILE_SHARING_SPEC §11.2). */\nexport function openAppFs(): MountFs {\n return openFs({ path: getAppMountPath(), type: 'repo' } as SandboxMount);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,oBAAgC;AAChC,wBAA2B;AAsB3B,MAAM,QAAQ,CAAC,OAAqB,OAAO,IAAI,UAAU,aAAa,cAAc,OAAO,IAAI,aAAa;AAoBrG,SAAS,YAAkC;AAChD,MAAI;AACF,UAAM,SAAU,WAAmB;AACnC,QAAI,MAAM,MAAM,EAAG,QAAO;AAAA,EAC5B,QAAQ;AAAA,EAER;AACA,MAAI;AAOF,UAAM,SAAS,QAAQ,YAAY,QAAQ,SAAS,IAAI;AACxD,QAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,iBAAW,SAAS,QAAQ;AAC1B,cAAM,KAAK,OAAO,cAAc;AAChC,YAAI,MAAM,EAAE,EAAG,QAAO;AAAA,MACxB;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAMO,SAAS,cAAuB;AACrC,SAAO,UAAU,KAAK;AACxB;AA6BA,MAAM,QAAyC;AAAA,EAC7C,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,WAAW;AACb;AAEA,MA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AA,IAClC;AAAA,IACA,SAAS,IAAI;AAKX,UAAI,aAAS,+BAAgB,GAAG;AAC9B,eAAO,MAAM;AAAA,QAAC;AAAA,MAChB;AACA,iBAAO,8BAAW,CAAC,WAAW;AAI5B,YAAI,OAAO,MAAM,WAAW,EAAG;AAC/B,WAAG,OAAO,MAAM,IAAI,CAAC,MAAM,EAAE,QAAQ,QAAQ,EAAE,CAAC,CAAC;AAAA,MACnD,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AAIO,SAAS,YAAqB;AACnC,SAAO,OAAO,EAAE,UAAM,+BAAgB,GAAG,MAAM,OAAO,CAAiB;AACzE;","names":[]}
package/dist/fs.d.cts CHANGED
@@ -25,14 +25,22 @@ interface SandboxFsPort {
25
25
  * 1. `globalThis.__sandpackSharedFs` — the `/`-rooted bound ZenFS the sandbox publishes.
26
26
  * 2. fallback: the first `module.evaluation.module.bundler.fs.layers[].boundContext.fs`
27
27
  * whose surface has `readFile` (the bundler ZenFS-layer bound context).
28
- * 3. else `null` (local `vite dev` / before boot).
28
+ * 3. else `null` (plain local `vite dev` / before boot).
29
+ *
30
+ * Under `vite dev` WITH the `@immediately-run/dev-fs` plugin (>= 0.5.0), step 1
31
+ * resolves: the plugin publishes its local-disk fs bridge at the same
32
+ * `__sandpackSharedFs` global, so `openFs` / `readBlob` / `readObjectUrl` /
33
+ * `useObjectUrl` work locally through this existing path with no special-casing.
34
+ * Without the plugin they fail with `unavailable`.
29
35
  *
30
36
  * Prefer {@link openFs}; reach for this only when a system app spans mounts in absolute
31
37
  * `/mnt/{hash}` paths (the file explorer / editor).
32
38
  */
33
39
  declare function sandboxFs(): SandboxFsPort | null;
34
- /** Is the sandbox filesystem reachable at all? `false` in local `vite dev` and before
35
- * boot — gate file affordances on it so an app degrades instead of throwing. */
40
+ /** Is the sandbox filesystem reachable at all? `false` in plain local `vite dev` and
41
+ * before boot — gate file affordances on it so an app degrades instead of throwing.
42
+ * `true` under `vite dev` with the `@immediately-run/dev-fs` plugin (>= 0.5.0),
43
+ * which publishes its bridge where {@link sandboxFs} discovers it. */
36
44
  declare function fsAvailable(): boolean;
37
45
  /** A directory entry from {@link MountFs.readdir}. */
38
46
  interface DirEntry {
@@ -135,9 +143,11 @@ interface MountFs {
135
143
  * if (fs.canWrite('notes/idea.mdx')) await fs.writeFile('notes/idea.mdx', text);
136
144
  * ```
137
145
  *
138
- * Throws {@link FsError} `unavailable` if the sandbox fs is not present (local `vite dev`
139
- * / before boot — gate with {@link fsAvailable}). Per-op failures throw {@link FsError}
140
- * with a mapped `.code` (`not-found`, `read-only`, …).
146
+ * Throws {@link FsError} `unavailable` if the sandbox fs is not present (plain local
147
+ * `vite dev` / before boot — gate with {@link fsAvailable}; under `vite dev` the
148
+ * `@immediately-run/dev-fs` plugin >= 0.5.0 provides it, see {@link sandboxFs}).
149
+ * Per-op failures throw {@link FsError} with a mapped `.code` (`not-found`,
150
+ * `read-only`, …).
141
151
  */
142
152
  declare function openFs(mount: SandboxMount): MountFs;
143
153
  /** Open a mount-anchored view of this app's OWN repository working tree — a convenience
package/dist/fs.d.ts CHANGED
@@ -25,14 +25,22 @@ interface SandboxFsPort {
25
25
  * 1. `globalThis.__sandpackSharedFs` — the `/`-rooted bound ZenFS the sandbox publishes.
26
26
  * 2. fallback: the first `module.evaluation.module.bundler.fs.layers[].boundContext.fs`
27
27
  * whose surface has `readFile` (the bundler ZenFS-layer bound context).
28
- * 3. else `null` (local `vite dev` / before boot).
28
+ * 3. else `null` (plain local `vite dev` / before boot).
29
+ *
30
+ * Under `vite dev` WITH the `@immediately-run/dev-fs` plugin (>= 0.5.0), step 1
31
+ * resolves: the plugin publishes its local-disk fs bridge at the same
32
+ * `__sandpackSharedFs` global, so `openFs` / `readBlob` / `readObjectUrl` /
33
+ * `useObjectUrl` work locally through this existing path with no special-casing.
34
+ * Without the plugin they fail with `unavailable`.
29
35
  *
30
36
  * Prefer {@link openFs}; reach for this only when a system app spans mounts in absolute
31
37
  * `/mnt/{hash}` paths (the file explorer / editor).
32
38
  */
33
39
  declare function sandboxFs(): SandboxFsPort | null;
34
- /** Is the sandbox filesystem reachable at all? `false` in local `vite dev` and before
35
- * boot — gate file affordances on it so an app degrades instead of throwing. */
40
+ /** Is the sandbox filesystem reachable at all? `false` in plain local `vite dev` and
41
+ * before boot — gate file affordances on it so an app degrades instead of throwing.
42
+ * `true` under `vite dev` with the `@immediately-run/dev-fs` plugin (>= 0.5.0),
43
+ * which publishes its bridge where {@link sandboxFs} discovers it. */
36
44
  declare function fsAvailable(): boolean;
37
45
  /** A directory entry from {@link MountFs.readdir}. */
38
46
  interface DirEntry {
@@ -135,9 +143,11 @@ interface MountFs {
135
143
  * if (fs.canWrite('notes/idea.mdx')) await fs.writeFile('notes/idea.mdx', text);
136
144
  * ```
137
145
  *
138
- * Throws {@link FsError} `unavailable` if the sandbox fs is not present (local `vite dev`
139
- * / before boot — gate with {@link fsAvailable}). Per-op failures throw {@link FsError}
140
- * with a mapped `.code` (`not-found`, `read-only`, …).
146
+ * Throws {@link FsError} `unavailable` if the sandbox fs is not present (plain local
147
+ * `vite dev` / before boot — gate with {@link fsAvailable}; under `vite dev` the
148
+ * `@immediately-run/dev-fs` plugin >= 0.5.0 provides it, see {@link sandboxFs}).
149
+ * Per-op failures throw {@link FsError} with a mapped `.code` (`not-found`,
150
+ * `read-only`, …).
141
151
  */
142
152
  declare function openFs(mount: SandboxMount): MountFs;
143
153
  /** Open a mount-anchored view of this app's OWN repository working tree — a convenience
package/dist/fs.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/fs.ts"],"sourcesContent":["// Typed, discoverable filesystem access — the app-facing surface for the ZenFS\n// mount ports (SDK_FS_SURFACE_SPEC; FILESYSTEM_SPEC §2 the ZenFS-shaped contract).\n//\n// The single most important thing an app does — read/write files in its mounts —\n// previously had NO SDK surface: apps reached an ambient `globalThis.__sandpackSharedFs`\n// by hand-rolling the same accessor (editor/file-explorer `src/fs/mountFs.ts`, \"keep the\n// two in sync\"), with a documented footgun (`module.evaluation.module.bundler.fs` is the\n// WRONG object — it has no `promises`/`stat`). This module is that accessor's ONE home,\n// typed and documented.\n//\n// It adds NO authority: the ZenFS port is already minted and chroot/`ro`-enforced\n// host-side (FILESYSTEM_SPEC §2, UI_AS_APPS §8.7). This is typing + discoverability +\n// de-duplication only. `fs` is a Resource PORT (a byte channel), not a host-brokered RPC,\n// so — unlike the `invoke()` catalog surface — it is hand-written, not gate-table-derived.\nimport type { SandboxMount, MountRule } from './mounts';\nimport { getAppMountPath } from './mounts';\nimport { onFsChange } from './onFsChange';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** The node-compatible promises surface the sandbox ZenFS exposes (the subset we use). */\ninterface NodeFsPromises {\n readFile(path: string, encoding?: any): Promise<string | Uint8Array>;\n writeFile(path: string, data: string | Uint8Array): Promise<void>;\n readdir(path: string, opts?: any): Promise<any[]>;\n stat(path: string): Promise<any>;\n mkdir(path: string, opts?: any): Promise<unknown>;\n rm(path: string, opts?: any): Promise<void>;\n rename(from: string, to: string): Promise<void>;\n}\n\n/** The resolved sandbox ZenFS handle (node-compatible, `/`-rooted). Opaque to apps —\n * reach it through {@link openFs}; the raw handle is the {@link sandboxFs} escape hatch. */\nexport interface SandboxFsPort {\n promises?: NodeFsPromises;\n readFile?: NodeFsPromises['readFile'];\n}\n\nconst hasFs = (fs: any): boolean => typeof fs?.promises?.readFile === 'function' || typeof fs?.readFile === 'function';\n\n/**\n * The resolved sandbox ZenFS, or `null` when unavailable. The ONE home for the\n * resolution order previously duplicated in every app's `mountFs.ts`:\n *\n * 1. `globalThis.__sandpackSharedFs` — the `/`-rooted bound ZenFS the sandbox publishes.\n * 2. fallback: the first `module.evaluation.module.bundler.fs.layers[].boundContext.fs`\n * whose surface has `readFile` (the bundler ZenFS-layer bound context).\n * 3. else `null` (local `vite dev` / before boot).\n *\n * Prefer {@link openFs}; reach for this only when a system app spans mounts in absolute\n * `/mnt/{hash}` paths (the file explorer / editor).\n */\nexport function sandboxFs(): SandboxFsPort | null {\n try {\n const shared = (globalThis as any).__sandpackSharedFs;\n if (hasFs(shared)) return shared as SandboxFsPort;\n } catch {\n /* not in the sandbox */\n }\n try {\n // @ts-ignore - `module` is injected by the sandbox runtime (see sandboxUtils transport).\n // DEPRECATION WINDOW (opened 2026-08-25, R3-278): this `bundler.fs.layers` fallback\n // is injected-bundler API reading — the supported surface is the\n // `__sandpackSharedFs` discovery global above (and `openFs`/`sandboxFs` themselves).\n // Kept through the SDK_PACKAGING_SPEC §9 window; new code must not read bundler.*\n // (scripts/check-bundler-reads.mjs).\n const layers = module?.evaluation?.module?.bundler?.fs?.layers;\n if (Array.isArray(layers)) {\n for (const layer of layers) {\n const fs = layer?.boundContext?.fs;\n if (hasFs(fs)) return fs as SandboxFsPort;\n }\n }\n } catch {\n /* not in the sandbox */\n }\n return null;\n}\n\n/** Is the sandbox filesystem reachable at all? `false` in local `vite dev` and before\n * boot — gate file affordances on it so an app degrades instead of throwing. */\nexport function fsAvailable(): boolean {\n return sandboxFs() != null;\n}\n\n/** A directory entry from {@link MountFs.readdir}. */\nexport interface DirEntry {\n name: string;\n kind: 'file' | 'dir';\n}\n\n/** A stat result from {@link MountFs.stat}. */\nexport interface FileStat {\n kind: 'file' | 'dir';\n size: number;\n mtimeMs?: number;\n}\n\n/** An error from a {@link MountFs} operation, carrying a machine-readable `.code`\n * (mapped from the ZenFS errno) so an app branches on `.code`, never on a message. */\nexport interface FsError extends Error {\n code:\n | 'not-found' // ENOENT\n | 'read-only' // EROFS — a `ro` mount / downgraded role; NEVER surface as UX (gate with canWrite)\n | 'not-permitted' // EACCES\n | 'exists' // EEXIST\n | 'not-empty' // ENOTEMPTY\n | 'invalid-path' // a `..` segment / absolute escape was passed as a relPath\n | 'unavailable' // no sandbox fs (local dev / pre-boot)\n | 'unknown';\n}\n\nconst ERRNO: Record<string, FsError['code']> = {\n ENOENT: 'not-found',\n EROFS: 'read-only',\n EACCES: 'not-permitted',\n EPERM: 'not-permitted',\n EEXIST: 'exists',\n ENOTEMPTY: 'not-empty',\n};\n\nconst fsError = (code: FsError['code'], message: string): FsError => {\n const err = new Error(message) as FsError;\n err.code = code;\n return err;\n};\n\nconst mapError = (e: unknown): FsError => {\n const errno = (e as { code?: string } | null)?.code;\n const code: FsError['code'] = (errno ? ERRNO[errno] : undefined) ?? 'unknown';\n const err = new Error((e as Error)?.message ?? 'fs operation failed') as FsError;\n err.code = code;\n return err;\n};\n\n// Lazily constructed so merely *importing* this module doesn't touch the\n// TextEncoder/TextDecoder globals — some non-DOM test/build environments only\n// provide them on demand, and no image/URL path needs them at all.\nlet _decoder: TextDecoder | undefined;\nlet _encoder: TextEncoder | undefined;\nconst decoder = (): TextDecoder => (_decoder ??= new TextDecoder());\nconst encoder = (): TextEncoder => (_encoder ??= new TextEncoder());\n\n// Extension → MIME type for the kinds an app displays inline. Images first (the\n// common case — `<img src>` off a mount), plus a couple of adjacent binary kinds.\n// Deliberately small: `mimeTypeFor` returns undefined for anything not here and\n// callers fall back to `application/octet-stream`.\nconst MIME_BY_EXT: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n};\n\n/**\n * Best-effort MIME type from a filename's extension — mainly image kinds\n * (png/jpg/jpeg/gif/webp/avif/svg/bmp/ico). Returns `undefined` when the\n * extension isn't recognized (the caller falls back to `application/octet-stream`).\n * Used by {@link MountFs.readBlob} / {@link MountFs.readObjectUrl}; exported so an\n * app can label a Blob it builds itself.\n */\nexport function mimeTypeFor(path: string): string | undefined {\n const dot = path.lastIndexOf('.');\n if (dot < 0) return undefined;\n return MIME_BY_EXT[path.slice(dot + 1).toLowerCase()];\n}\n\n// Join a mount-RELATIVE path under the mount root, rejecting `..` escapes and absolute\n// paths (CLAUDE.md security rule 3 — don't probe for escapes). The host chroot is the\n// real enforcer; this keeps an honest app from accidentally naming outside its grant.\nconst resolveUnder = (root: string, relPath: string): string => {\n if (relPath.startsWith('/')) {\n throw fsError('invalid-path', `expected a mount-relative path, got absolute \"${relPath}\"`);\n }\n const parts: string[] = [];\n for (const seg of relPath.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') {\n throw fsError('invalid-path', `\"${relPath}\" escapes the mount root`);\n }\n parts.push(seg);\n }\n const base = root.endsWith('/') ? root.slice(0, -1) : root;\n return parts.length ? `${base}/${parts.join('/')}` : base;\n};\n\n// The longest matching `rules` subtree governs a path (mounts.ts MountRule); fall back to\n// the whole-mount `mode`. A CLIENT-SIDE hint mirroring the host rule — EROFS stays\n// authoritative (the host re-checks live policy on every write).\nconst writableAt = (mount: SandboxMount, relPath: string): boolean => {\n const path =\n '/' +\n relPath\n .split('/')\n .filter((s) => s && s !== '.')\n .join('/');\n const rules: MountRule[] | undefined = mount.rules;\n if (rules && rules.length) {\n let best: MountRule | undefined;\n for (const r of rules) {\n const sub = r.subtree.endsWith('/') ? r.subtree : r.subtree + '/';\n if (path === r.subtree || path.startsWith(sub) || r.subtree === '/') {\n if (!best || r.subtree.length > best.subtree.length) best = r;\n }\n }\n if (best) return best.mode === 'rw';\n }\n return (mount.mode ?? 'rw') === 'rw';\n};\n\n/** A mount-anchored, typed filesystem view. All paths are RELATIVE to the mount root;\n * the accessor resolves them under `mount.path`. Async-only (ZenFS rides a MessagePort).\n * Obtain one with {@link openFs}. */\nexport interface MountFs {\n /** The mount this view is anchored to (read `mode`/`rules` for writability). */\n readonly mount: SandboxMount;\n /** Read a file as UTF-8 text (`encoding: 'utf8'`) or raw bytes (omit encoding). */\n readFile(relPath: string, encoding: 'utf8'): Promise<string>;\n readFile(relPath: string): Promise<Uint8Array>;\n /** Read a file's bytes as a `Blob`, tagged with a MIME `type` inferred from the\n * extension ({@link mimeTypeFor}) or `opts.type` when given (falls back to\n * `application/octet-stream`). The building block for downloads and object URLs. */\n readBlob(relPath: string, opts?: { type?: string }): Promise<Blob>;\n /** Read a file into an **object URL** suitable for `<img src>` / `<a href>` — the\n * fix for \"an opaque-origin iframe can't fetch a mount path\". Returns the `url`\n * and a `revoke()` you MUST call when done (typically on unmount) or the URL\n * leaks. Prefer the `useObjectUrl` hook / `MountImage` component, which revoke\n * for you; reach for this directly only outside React. */\n readObjectUrl(relPath: string, opts?: { type?: string }): Promise<{ url: string; revoke: () => void }>;\n /** Write text or bytes, creating or truncating the file. Throws `read-only` on a `ro` mount. */\n writeFile(relPath: string, data: string | Uint8Array): Promise<void>;\n /** List a directory (the mount root when `relPath` is omitted). */\n readdir(relPath?: string): Promise<DirEntry[]>;\n /** Stat a path. Throws `not-found` if absent. */\n stat(relPath: string): Promise<FileStat>;\n /** Does `relPath` exist? Never throws on absence. */\n exists(relPath: string): Promise<boolean>;\n /** Create a directory (pass `{ recursive: true }` to make parents). */\n mkdir(relPath: string, opts?: { recursive?: boolean }): Promise<void>;\n /** Remove a file, or a directory with `{ recursive: true }`. */\n rm(relPath: string, opts?: { recursive?: boolean }): Promise<void>;\n /** Rename/move within the mount. */\n rename(fromRel: string, toRel: string): Promise<void>;\n /** Client-side writability hint for `relPath` (mount `mode` ∩ longest-matching `rule`),\n * so an app can hide an \"edit\" affordance instead of catching `read-only`\n * (EDITOR_FIRST_EDITING_SPEC §3). Re-evaluate on `onMountsChange` — a role downgrade\n * flips it. EROFS from the host stays authoritative. */\n canWrite(relPath?: string): boolean;\n /** Subscribe to changes to files in this mount — the mount-scoped projection of\n * the host working-tree change stream (`onFsChange`), so a viewer re-reads an\n * affected file instead of polling (SDK_FS_SURFACE_SPEC §5). The callback gets\n * the changed paths RELATIVE to this mount (feed them straight back into\n * `readFile`/`stat`/…). Returns an unsubscribe fn.\n *\n * **Working-tree-only in v1 (an honest gap, O2):** the host push channel carries\n * only working-tree changes, so `onChange` on a NON-working-tree mount (a space)\n * is an inert subscription that never fires until that channel lands. Like\n * `onFsChange`, origin-exclusion (ignoring the echo of your own write) is the\n * caller's responsibility. */\n onChange(cb: (changedRelPaths: string[]) => void): () => void;\n}\n\nconst promisesOf = (port: SandboxFsPort): NodeFsPromises => port.promises ?? (port as unknown as NodeFsPromises);\n\n/**\n * Open a typed, mount-anchored filesystem view (SDK_FS_SURFACE_SPEC §2.1). Pure-client:\n * resolves the ambient ZenFS once ({@link sandboxFs}) and binds it to `mount.path`, so you\n * read/write with paths RELATIVE to the mount root — you cannot accidentally name a path\n * outside your grant (a `..`/absolute path throws `invalid-path`; the host chroot is the\n * real enforcer).\n *\n * ```ts\n * import { mountSpace } from '@immediately-run/sdk';\n * import { openFs } from '@immediately-run/sdk/fs';\n * const fs = openFs(await mountSpace({ spaceId }));\n * const text = await fs.readFile('notes/idea.mdx', 'utf8');\n * if (fs.canWrite('notes/idea.mdx')) await fs.writeFile('notes/idea.mdx', text);\n * ```\n *\n * Throws {@link FsError} `unavailable` if the sandbox fs is not present (local `vite dev`\n * / before boot — gate with {@link fsAvailable}). Per-op failures throw {@link FsError}\n * with a mapped `.code` (`not-found`, `read-only`, …).\n */\nexport function openFs(mount: SandboxMount): MountFs {\n const root = mount.path;\n\n const port = (): NodeFsPromises => {\n const p = sandboxFs();\n if (!p) throw fsError('unavailable', 'immediately.run: sandbox filesystem unavailable');\n return promisesOf(p);\n };\n\n const api: MountFs = {\n mount,\n async readFile(relPath: string, encoding?: 'utf8'): Promise<any> {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const data = await p.readFile(abs);\n const bytes = typeof data === 'string' ? encoder().encode(data) : (data as Uint8Array);\n return encoding === 'utf8' ? decoder().decode(bytes) : bytes;\n } catch (e) {\n throw mapError(e);\n }\n },\n async readBlob(relPath, opts) {\n const bytes = await api.readFile(relPath);\n const type = opts?.type ?? mimeTypeFor(relPath) ?? 'application/octet-stream';\n return new Blob([bytes as BlobPart], { type });\n },\n async readObjectUrl(relPath, opts) {\n const blob = await api.readBlob(relPath, opts);\n const url = URL.createObjectURL(blob);\n return { url, revoke: () => URL.revokeObjectURL(url) };\n },\n async writeFile(relPath, data) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.writeFile(abs, typeof data === 'string' ? encoder().encode(data) : data);\n } catch (e) {\n throw mapError(e);\n }\n },\n async readdir(relPath = '') {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const entries = await p.readdir(abs, { withFileTypes: true });\n return entries.map((d: any) =>\n typeof d === 'string'\n ? ({ name: d, kind: 'file' } as DirEntry)\n : ({ name: d.name, kind: d.isDirectory?.() ? 'dir' : 'file' } as DirEntry),\n );\n } catch (e) {\n throw mapError(e);\n }\n },\n async stat(relPath) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const s: any = await p.stat(abs);\n return {\n kind: s.isDirectory?.() ? 'dir' : 'file',\n size: typeof s.size === 'number' ? s.size : 0,\n mtimeMs: typeof s.mtimeMs === 'number' ? s.mtimeMs : undefined,\n };\n } catch (e) {\n throw mapError(e);\n }\n },\n async exists(relPath) {\n try {\n await api.stat(relPath);\n return true;\n } catch (e) {\n if ((e as FsError).code === 'not-found') return false;\n if ((e as FsError).code === 'unavailable' || (e as FsError).code === 'invalid-path') {\n throw e;\n }\n return false;\n }\n },\n async mkdir(relPath, opts) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.mkdir(abs, { recursive: opts?.recursive ?? false });\n } catch (e) {\n throw mapError(e);\n }\n },\n async rm(relPath, opts) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.rm(abs, { recursive: opts?.recursive ?? false });\n } catch (e) {\n throw mapError(e);\n }\n },\n async rename(fromRel, toRel) {\n const p = port();\n const from = resolveUnder(root, fromRel);\n const to = resolveUnder(root, toRel);\n try {\n await p.rename(from, to);\n } catch (e) {\n throw mapError(e);\n }\n },\n canWrite(relPath = '') {\n return writableAt(mount, relPath);\n },\n onChange(cb) {\n // §5 — mount-scoped projection of the working-tree change channel\n // (`onFsChange`). v1 is WORKING-TREE-ONLY: the host pushes only working-tree\n // changes, so a non-working-tree mount (a space) has no channel yet (O2) and\n // gets an inert subscription rather than another mount's paths leaking in.\n if (root !== getAppMountPath()) {\n return () => {}; // no channel for this mount — inert (honest v1 gap)\n }\n return onFsChange((change) => {\n // Skip the empty pre-first-event initial batch; forward only real changes,\n // as mount-relative paths (drop the repo-relative leading slash) so they\n // feed straight back into readFile/stat/etc.\n if (change.paths.length === 0) return;\n cb(change.paths.map((p) => p.replace(/^\\/+/, '')));\n });\n },\n };\n return api;\n}\n\n/** Open a mount-anchored view of this app's OWN repository working tree — a convenience\n * over {@link openFs} using `getAppMountPath()` (FILE_SHARING_SPEC §11.2). */\nexport function openAppFs(): MountFs {\n return openFs({ path: getAppMountPath(), type: 'repo' } as SandboxMount);\n}\n"],"mappings":";AAeA,SAAS,uBAAuB;AAChC,SAAS,kBAAkB;AAsB3B,MAAM,QAAQ,CAAC,OAAqB,OAAO,IAAI,UAAU,aAAa,cAAc,OAAO,IAAI,aAAa;AAcrG,SAAS,YAAkC;AAChD,MAAI;AACF,UAAM,SAAU,WAAmB;AACnC,QAAI,MAAM,MAAM,EAAG,QAAO;AAAA,EAC5B,QAAQ;AAAA,EAER;AACA,MAAI;AAOF,UAAM,SAAS,QAAQ,YAAY,QAAQ,SAAS,IAAI;AACxD,QAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,iBAAW,SAAS,QAAQ;AAC1B,cAAM,KAAK,OAAO,cAAc;AAChC,YAAI,MAAM,EAAE,EAAG,QAAO;AAAA,MACxB;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAIO,SAAS,cAAuB;AACrC,SAAO,UAAU,KAAK;AACxB;AA6BA,MAAM,QAAyC;AAAA,EAC7C,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,WAAW;AACb;AAEA,MAAM,UAAU,CAAC,MAAuB,YAA6B;AACnE,QAAM,MAAM,IAAI,MAAM,OAAO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AAC9B,eAAO,MAAM;AAAA,QAAC;AAAA,MAChB;AACA,aAAO,WAAW,CAAC,WAAW;AAI5B,YAAI,OAAO,MAAM,WAAW,EAAG;AAC/B,WAAG,OAAO,MAAM,IAAI,CAAC,MAAM,EAAE,QAAQ,QAAQ,EAAE,CAAC,CAAC;AAAA,MACnD,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AAIO,SAAS,YAAqB;AACnC,SAAO,OAAO,EAAE,MAAM,gBAAgB,GAAG,MAAM,OAAO,CAAiB;AACzE;","names":[]}
1
+ {"version":3,"sources":["../src/fs.ts"],"sourcesContent":["// Typed, discoverable filesystem access — the app-facing surface for the ZenFS\n// mount ports (SDK_FS_SURFACE_SPEC; FILESYSTEM_SPEC §2 the ZenFS-shaped contract).\n//\n// The single most important thing an app does — read/write files in its mounts —\n// previously had NO SDK surface: apps reached an ambient `globalThis.__sandpackSharedFs`\n// by hand-rolling the same accessor (editor/file-explorer `src/fs/mountFs.ts`, \"keep the\n// two in sync\"), with a documented footgun (`module.evaluation.module.bundler.fs` is the\n// WRONG object — it has no `promises`/`stat`). This module is that accessor's ONE home,\n// typed and documented.\n//\n// It adds NO authority: the ZenFS port is already minted and chroot/`ro`-enforced\n// host-side (FILESYSTEM_SPEC §2, UI_AS_APPS §8.7). This is typing + discoverability +\n// de-duplication only. `fs` is a Resource PORT (a byte channel), not a host-brokered RPC,\n// so — unlike the `invoke()` catalog surface — it is hand-written, not gate-table-derived.\nimport type { SandboxMount, MountRule } from './mounts';\nimport { getAppMountPath } from './mounts';\nimport { onFsChange } from './onFsChange';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** The node-compatible promises surface the sandbox ZenFS exposes (the subset we use). */\ninterface NodeFsPromises {\n readFile(path: string, encoding?: any): Promise<string | Uint8Array>;\n writeFile(path: string, data: string | Uint8Array): Promise<void>;\n readdir(path: string, opts?: any): Promise<any[]>;\n stat(path: string): Promise<any>;\n mkdir(path: string, opts?: any): Promise<unknown>;\n rm(path: string, opts?: any): Promise<void>;\n rename(from: string, to: string): Promise<void>;\n}\n\n/** The resolved sandbox ZenFS handle (node-compatible, `/`-rooted). Opaque to apps —\n * reach it through {@link openFs}; the raw handle is the {@link sandboxFs} escape hatch. */\nexport interface SandboxFsPort {\n promises?: NodeFsPromises;\n readFile?: NodeFsPromises['readFile'];\n}\n\nconst hasFs = (fs: any): boolean => typeof fs?.promises?.readFile === 'function' || typeof fs?.readFile === 'function';\n\n/**\n * The resolved sandbox ZenFS, or `null` when unavailable. The ONE home for the\n * resolution order previously duplicated in every app's `mountFs.ts`:\n *\n * 1. `globalThis.__sandpackSharedFs` — the `/`-rooted bound ZenFS the sandbox publishes.\n * 2. fallback: the first `module.evaluation.module.bundler.fs.layers[].boundContext.fs`\n * whose surface has `readFile` (the bundler ZenFS-layer bound context).\n * 3. else `null` (plain local `vite dev` / before boot).\n *\n * Under `vite dev` WITH the `@immediately-run/dev-fs` plugin (>= 0.5.0), step 1\n * resolves: the plugin publishes its local-disk fs bridge at the same\n * `__sandpackSharedFs` global, so `openFs` / `readBlob` / `readObjectUrl` /\n * `useObjectUrl` work locally through this existing path with no special-casing.\n * Without the plugin they fail with `unavailable`.\n *\n * Prefer {@link openFs}; reach for this only when a system app spans mounts in absolute\n * `/mnt/{hash}` paths (the file explorer / editor).\n */\nexport function sandboxFs(): SandboxFsPort | null {\n try {\n const shared = (globalThis as any).__sandpackSharedFs;\n if (hasFs(shared)) return shared as SandboxFsPort;\n } catch {\n /* not in the sandbox */\n }\n try {\n // @ts-ignore - `module` is injected by the sandbox runtime (see sandboxUtils transport).\n // DEPRECATION WINDOW (opened 2026-08-25, R3-278): this `bundler.fs.layers` fallback\n // is injected-bundler API reading — the supported surface is the\n // `__sandpackSharedFs` discovery global above (and `openFs`/`sandboxFs` themselves).\n // Kept through the SDK_PACKAGING_SPEC §9 window; new code must not read bundler.*\n // (scripts/check-bundler-reads.mjs).\n const layers = module?.evaluation?.module?.bundler?.fs?.layers;\n if (Array.isArray(layers)) {\n for (const layer of layers) {\n const fs = layer?.boundContext?.fs;\n if (hasFs(fs)) return fs as SandboxFsPort;\n }\n }\n } catch {\n /* not in the sandbox */\n }\n return null;\n}\n\n/** Is the sandbox filesystem reachable at all? `false` in plain local `vite dev` and\n * before boot — gate file affordances on it so an app degrades instead of throwing.\n * `true` under `vite dev` with the `@immediately-run/dev-fs` plugin (>= 0.5.0),\n * which publishes its bridge where {@link sandboxFs} discovers it. */\nexport function fsAvailable(): boolean {\n return sandboxFs() != null;\n}\n\n/** A directory entry from {@link MountFs.readdir}. */\nexport interface DirEntry {\n name: string;\n kind: 'file' | 'dir';\n}\n\n/** A stat result from {@link MountFs.stat}. */\nexport interface FileStat {\n kind: 'file' | 'dir';\n size: number;\n mtimeMs?: number;\n}\n\n/** An error from a {@link MountFs} operation, carrying a machine-readable `.code`\n * (mapped from the ZenFS errno) so an app branches on `.code`, never on a message. */\nexport interface FsError extends Error {\n code:\n | 'not-found' // ENOENT\n | 'read-only' // EROFS — a `ro` mount / downgraded role; NEVER surface as UX (gate with canWrite)\n | 'not-permitted' // EACCES\n | 'exists' // EEXIST\n | 'not-empty' // ENOTEMPTY\n | 'invalid-path' // a `..` segment / absolute escape was passed as a relPath\n | 'unavailable' // no sandbox fs (local dev / pre-boot)\n | 'unknown';\n}\n\nconst ERRNO: Record<string, FsError['code']> = {\n ENOENT: 'not-found',\n EROFS: 'read-only',\n EACCES: 'not-permitted',\n EPERM: 'not-permitted',\n EEXIST: 'exists',\n ENOTEMPTY: 'not-empty',\n};\n\nconst fsError = (code: FsError['code'], message: string): FsError => {\n const err = new Error(message) as FsError;\n err.code = code;\n return err;\n};\n\nconst mapError = (e: unknown): FsError => {\n const errno = (e as { code?: string } | null)?.code;\n const code: FsError['code'] = (errno ? ERRNO[errno] : undefined) ?? 'unknown';\n const err = new Error((e as Error)?.message ?? 'fs operation failed') as FsError;\n err.code = code;\n return err;\n};\n\n// Lazily constructed so merely *importing* this module doesn't touch the\n// TextEncoder/TextDecoder globals — some non-DOM test/build environments only\n// provide them on demand, and no image/URL path needs them at all.\nlet _decoder: TextDecoder | undefined;\nlet _encoder: TextEncoder | undefined;\nconst decoder = (): TextDecoder => (_decoder ??= new TextDecoder());\nconst encoder = (): TextEncoder => (_encoder ??= new TextEncoder());\n\n// Extension → MIME type for the kinds an app displays inline. Images first (the\n// common case — `<img src>` off a mount), plus a couple of adjacent binary kinds.\n// Deliberately small: `mimeTypeFor` returns undefined for anything not here and\n// callers fall back to `application/octet-stream`.\nconst MIME_BY_EXT: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n};\n\n/**\n * Best-effort MIME type from a filename's extension — mainly image kinds\n * (png/jpg/jpeg/gif/webp/avif/svg/bmp/ico). Returns `undefined` when the\n * extension isn't recognized (the caller falls back to `application/octet-stream`).\n * Used by {@link MountFs.readBlob} / {@link MountFs.readObjectUrl}; exported so an\n * app can label a Blob it builds itself.\n */\nexport function mimeTypeFor(path: string): string | undefined {\n const dot = path.lastIndexOf('.');\n if (dot < 0) return undefined;\n return MIME_BY_EXT[path.slice(dot + 1).toLowerCase()];\n}\n\n// Join a mount-RELATIVE path under the mount root, rejecting `..` escapes and absolute\n// paths (CLAUDE.md security rule 3 — don't probe for escapes). The host chroot is the\n// real enforcer; this keeps an honest app from accidentally naming outside its grant.\nconst resolveUnder = (root: string, relPath: string): string => {\n if (relPath.startsWith('/')) {\n throw fsError('invalid-path', `expected a mount-relative path, got absolute \"${relPath}\"`);\n }\n const parts: string[] = [];\n for (const seg of relPath.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') {\n throw fsError('invalid-path', `\"${relPath}\" escapes the mount root`);\n }\n parts.push(seg);\n }\n const base = root.endsWith('/') ? root.slice(0, -1) : root;\n return parts.length ? `${base}/${parts.join('/')}` : base;\n};\n\n// The longest matching `rules` subtree governs a path (mounts.ts MountRule); fall back to\n// the whole-mount `mode`. A CLIENT-SIDE hint mirroring the host rule — EROFS stays\n// authoritative (the host re-checks live policy on every write).\nconst writableAt = (mount: SandboxMount, relPath: string): boolean => {\n const path =\n '/' +\n relPath\n .split('/')\n .filter((s) => s && s !== '.')\n .join('/');\n const rules: MountRule[] | undefined = mount.rules;\n if (rules && rules.length) {\n let best: MountRule | undefined;\n for (const r of rules) {\n const sub = r.subtree.endsWith('/') ? r.subtree : r.subtree + '/';\n if (path === r.subtree || path.startsWith(sub) || r.subtree === '/') {\n if (!best || r.subtree.length > best.subtree.length) best = r;\n }\n }\n if (best) return best.mode === 'rw';\n }\n return (mount.mode ?? 'rw') === 'rw';\n};\n\n/** A mount-anchored, typed filesystem view. All paths are RELATIVE to the mount root;\n * the accessor resolves them under `mount.path`. Async-only (ZenFS rides a MessagePort).\n * Obtain one with {@link openFs}. */\nexport interface MountFs {\n /** The mount this view is anchored to (read `mode`/`rules` for writability). */\n readonly mount: SandboxMount;\n /** Read a file as UTF-8 text (`encoding: 'utf8'`) or raw bytes (omit encoding). */\n readFile(relPath: string, encoding: 'utf8'): Promise<string>;\n readFile(relPath: string): Promise<Uint8Array>;\n /** Read a file's bytes as a `Blob`, tagged with a MIME `type` inferred from the\n * extension ({@link mimeTypeFor}) or `opts.type` when given (falls back to\n * `application/octet-stream`). The building block for downloads and object URLs. */\n readBlob(relPath: string, opts?: { type?: string }): Promise<Blob>;\n /** Read a file into an **object URL** suitable for `<img src>` / `<a href>` — the\n * fix for \"an opaque-origin iframe can't fetch a mount path\". Returns the `url`\n * and a `revoke()` you MUST call when done (typically on unmount) or the URL\n * leaks. Prefer the `useObjectUrl` hook / `MountImage` component, which revoke\n * for you; reach for this directly only outside React. */\n readObjectUrl(relPath: string, opts?: { type?: string }): Promise<{ url: string; revoke: () => void }>;\n /** Write text or bytes, creating or truncating the file. Throws `read-only` on a `ro` mount. */\n writeFile(relPath: string, data: string | Uint8Array): Promise<void>;\n /** List a directory (the mount root when `relPath` is omitted). */\n readdir(relPath?: string): Promise<DirEntry[]>;\n /** Stat a path. Throws `not-found` if absent. */\n stat(relPath: string): Promise<FileStat>;\n /** Does `relPath` exist? Never throws on absence. */\n exists(relPath: string): Promise<boolean>;\n /** Create a directory (pass `{ recursive: true }` to make parents). */\n mkdir(relPath: string, opts?: { recursive?: boolean }): Promise<void>;\n /** Remove a file, or a directory with `{ recursive: true }`. */\n rm(relPath: string, opts?: { recursive?: boolean }): Promise<void>;\n /** Rename/move within the mount. */\n rename(fromRel: string, toRel: string): Promise<void>;\n /** Client-side writability hint for `relPath` (mount `mode` ∩ longest-matching `rule`),\n * so an app can hide an \"edit\" affordance instead of catching `read-only`\n * (EDITOR_FIRST_EDITING_SPEC §3). Re-evaluate on `onMountsChange` — a role downgrade\n * flips it. EROFS from the host stays authoritative. */\n canWrite(relPath?: string): boolean;\n /** Subscribe to changes to files in this mount — the mount-scoped projection of\n * the host working-tree change stream (`onFsChange`), so a viewer re-reads an\n * affected file instead of polling (SDK_FS_SURFACE_SPEC §5). The callback gets\n * the changed paths RELATIVE to this mount (feed them straight back into\n * `readFile`/`stat`/…). Returns an unsubscribe fn.\n *\n * **Working-tree-only in v1 (an honest gap, O2):** the host push channel carries\n * only working-tree changes, so `onChange` on a NON-working-tree mount (a space)\n * is an inert subscription that never fires until that channel lands. Like\n * `onFsChange`, origin-exclusion (ignoring the echo of your own write) is the\n * caller's responsibility. */\n onChange(cb: (changedRelPaths: string[]) => void): () => void;\n}\n\nconst promisesOf = (port: SandboxFsPort): NodeFsPromises => port.promises ?? (port as unknown as NodeFsPromises);\n\n/**\n * Open a typed, mount-anchored filesystem view (SDK_FS_SURFACE_SPEC §2.1). Pure-client:\n * resolves the ambient ZenFS once ({@link sandboxFs}) and binds it to `mount.path`, so you\n * read/write with paths RELATIVE to the mount root — you cannot accidentally name a path\n * outside your grant (a `..`/absolute path throws `invalid-path`; the host chroot is the\n * real enforcer).\n *\n * ```ts\n * import { mountSpace } from '@immediately-run/sdk';\n * import { openFs } from '@immediately-run/sdk/fs';\n * const fs = openFs(await mountSpace({ spaceId }));\n * const text = await fs.readFile('notes/idea.mdx', 'utf8');\n * if (fs.canWrite('notes/idea.mdx')) await fs.writeFile('notes/idea.mdx', text);\n * ```\n *\n * Throws {@link FsError} `unavailable` if the sandbox fs is not present (plain local\n * `vite dev` / before boot — gate with {@link fsAvailable}; under `vite dev` the\n * `@immediately-run/dev-fs` plugin >= 0.5.0 provides it, see {@link sandboxFs}).\n * Per-op failures throw {@link FsError} with a mapped `.code` (`not-found`,\n * `read-only`, …).\n */\nexport function openFs(mount: SandboxMount): MountFs {\n const root = mount.path;\n\n const port = (): NodeFsPromises => {\n const p = sandboxFs();\n if (!p) throw fsError('unavailable', 'immediately.run: sandbox filesystem unavailable');\n return promisesOf(p);\n };\n\n const api: MountFs = {\n mount,\n async readFile(relPath: string, encoding?: 'utf8'): Promise<any> {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const data = await p.readFile(abs);\n const bytes = typeof data === 'string' ? encoder().encode(data) : (data as Uint8Array);\n return encoding === 'utf8' ? decoder().decode(bytes) : bytes;\n } catch (e) {\n throw mapError(e);\n }\n },\n async readBlob(relPath, opts) {\n const bytes = await api.readFile(relPath);\n const type = opts?.type ?? mimeTypeFor(relPath) ?? 'application/octet-stream';\n return new Blob([bytes as BlobPart], { type });\n },\n async readObjectUrl(relPath, opts) {\n const blob = await api.readBlob(relPath, opts);\n const url = URL.createObjectURL(blob);\n return { url, revoke: () => URL.revokeObjectURL(url) };\n },\n async writeFile(relPath, data) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.writeFile(abs, typeof data === 'string' ? encoder().encode(data) : data);\n } catch (e) {\n throw mapError(e);\n }\n },\n async readdir(relPath = '') {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const entries = await p.readdir(abs, { withFileTypes: true });\n return entries.map((d: any) =>\n typeof d === 'string'\n ? ({ name: d, kind: 'file' } as DirEntry)\n : ({ name: d.name, kind: d.isDirectory?.() ? 'dir' : 'file' } as DirEntry),\n );\n } catch (e) {\n throw mapError(e);\n }\n },\n async stat(relPath) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n const s: any = await p.stat(abs);\n return {\n kind: s.isDirectory?.() ? 'dir' : 'file',\n size: typeof s.size === 'number' ? s.size : 0,\n mtimeMs: typeof s.mtimeMs === 'number' ? s.mtimeMs : undefined,\n };\n } catch (e) {\n throw mapError(e);\n }\n },\n async exists(relPath) {\n try {\n await api.stat(relPath);\n return true;\n } catch (e) {\n if ((e as FsError).code === 'not-found') return false;\n if ((e as FsError).code === 'unavailable' || (e as FsError).code === 'invalid-path') {\n throw e;\n }\n return false;\n }\n },\n async mkdir(relPath, opts) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.mkdir(abs, { recursive: opts?.recursive ?? false });\n } catch (e) {\n throw mapError(e);\n }\n },\n async rm(relPath, opts) {\n const p = port();\n const abs = resolveUnder(root, relPath);\n try {\n await p.rm(abs, { recursive: opts?.recursive ?? false });\n } catch (e) {\n throw mapError(e);\n }\n },\n async rename(fromRel, toRel) {\n const p = port();\n const from = resolveUnder(root, fromRel);\n const to = resolveUnder(root, toRel);\n try {\n await p.rename(from, to);\n } catch (e) {\n throw mapError(e);\n }\n },\n canWrite(relPath = '') {\n return writableAt(mount, relPath);\n },\n onChange(cb) {\n // §5 — mount-scoped projection of the working-tree change channel\n // (`onFsChange`). v1 is WORKING-TREE-ONLY: the host pushes only working-tree\n // changes, so a non-working-tree mount (a space) has no channel yet (O2) and\n // gets an inert subscription rather than another mount's paths leaking in.\n if (root !== getAppMountPath()) {\n return () => {}; // no channel for this mount — inert (honest v1 gap)\n }\n return onFsChange((change) => {\n // Skip the empty pre-first-event initial batch; forward only real changes,\n // as mount-relative paths (drop the repo-relative leading slash) so they\n // feed straight back into readFile/stat/etc.\n if (change.paths.length === 0) return;\n cb(change.paths.map((p) => p.replace(/^\\/+/, '')));\n });\n },\n };\n return api;\n}\n\n/** Open a mount-anchored view of this app's OWN repository working tree — a convenience\n * over {@link openFs} using `getAppMountPath()` (FILE_SHARING_SPEC §11.2). */\nexport function openAppFs(): MountFs {\n return openFs({ path: getAppMountPath(), type: 'repo' } as SandboxMount);\n}\n"],"mappings":";AAeA,SAAS,uBAAuB;AAChC,SAAS,kBAAkB;AAsB3B,MAAM,QAAQ,CAAC,OAAqB,OAAO,IAAI,UAAU,aAAa,cAAc,OAAO,IAAI,aAAa;AAoBrG,SAAS,YAAkC;AAChD,MAAI;AACF,UAAM,SAAU,WAAmB;AACnC,QAAI,MAAM,MAAM,EAAG,QAAO;AAAA,EAC5B,QAAQ;AAAA,EAER;AACA,MAAI;AAOF,UAAM,SAAS,QAAQ,YAAY,QAAQ,SAAS,IAAI;AACxD,QAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,iBAAW,SAAS,QAAQ;AAC1B,cAAM,KAAK,OAAO,cAAc;AAChC,YAAI,MAAM,EAAE,EAAG,QAAO;AAAA,MACxB;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAMO,SAAS,cAAuB;AACrC,SAAO,UAAU,KAAK;AACxB;AA6BA,MAAM,QAAyC;AAAA,EAC7C,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,WAAW;AACb;AAEA,MAAM,UAAU,CAAC,MAAuB,YAA6B;AACnE,QAAM,MAAM,IAAI,MAAM,OAAO;AAC7B,MAAI,OAAO;AACX,SAAO;AACT;AAEA,MAAM,WAAW,CAAC,MAAwB;AACxC,QAAM,QAAS,GAAgC;AAC/C,QAAM,QAAyB,QAAQ,MAAM,KAAK,IAAI,WAAc;AACpE,QAAM,MAAM,IAAI,MAAO,GAAa,WAAW,qBAAqB;AACpE,MAAI,OAAO;AACX,SAAO;AACT;AAKA,IAAI;AACJ,IAAI;AACJ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S,YAAqB;AACnC,SAAO,OAAO,EAAE,MAAM,gBAAgB,GAAG,MAAM,OAAO,CAAiB;AACzE;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks.ts"],"sourcesContent":["import { APP_ROOT, underAppRoot } from '@immediately-run/platform-constants';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { openFs, type FsError } from './fs';\nimport { useMetadataStore } from './metadataSource';\nimport type { SandboxMount } from './mounts';\nimport {\n FilesMetadata,\n Metadata,\n MetadataQueryEntry,\n MetadataQueryFunction,\n MetadataQueryResult,\n} from './sandboxTypes';\n\nconst entriesEqual = <T>(\n a: MetadataQueryEntry<T, Record<string, unknown>>[],\n b: MetadataQueryEntry<T, Record<string, unknown>>[],\n): boolean => {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n // Unchanged frontmatter keeps its object identity across `metadata-update`\n // merges, so an identity check on `meta` is a sound \"did this match change?\".\n if (a[i].path !== b[i].path || a[i].meta !== b[i].meta) {\n return false;\n }\n // Extra fields a record-returning query computed (R3-276) are part of the\n // result, so a change in them is a change in the result — compared by value,\n // one level, because they are derived scalars, not the store's shared objects.\n const ax = a[i] as Record<string, unknown>;\n const bx = b[i] as Record<string, unknown>;\n const keys = new Set([...Object.keys(ax), ...Object.keys(bx)]);\n for (const k of keys) {\n if (k === 'path' || k === 'meta') continue;\n if (ax[k] !== bx[k]) return false;\n }\n }\n return true;\n};\n\n/**\n * Query the file metadata store (MDX frontmatter) with a plain JS function.\n *\n * The query receives every file's frontmatter keyed by path and returns the paths\n * that match; the hook resolves each path back to its frontmatter and returns an\n * array of `{ path, meta }` entries — so a single call gives you everything you\n * filtered on, with no second lookup. A throwing query is reported as `{ error }`\n * rather than crashing the render.\n *\n * The query runs synchronously during render (no empty first frame), and the\n * returned array keeps its identity while the matches are unchanged, so it is safe\n * to use directly in downstream `useMemo`/`useEffect` dependency arrays.\n *\n * A query may return RECORDS instead of bare paths (R3-276) — `{ path, ...extra }`\n * — and the extra fields ride along on each entry, so something derived while\n * selecting does not have to be recomputed downstream:\n * ```ts\n * const posts = useMetadataQuery<PostMeta, { year: string }>((files) =>\n * Object.entries(files).map(([path, m]) => ({ path, year: m.date.slice(0, 4) })),\n * );\n * ```\n * The store it queries is the nearest {@link MetadataSource}, else the host's.\n *\n * Pass a type parameter to get typed frontmatter throughout:\n * ```ts\n * interface PostMeta { title: string; date: string; draft?: boolean }\n * const posts = useMetadataQuery<PostMeta>((files) =>\n * Object.entries(files)\n * .filter(([, m]) => !m.draft)\n * .sort(([, a], [, b]) => b.date.localeCompare(a.date))\n * .map(([path]) => path),\n * );\n * ```\n */\nexport const useMetadataQuery = <T = Metadata, E extends object = {}>(\n queryFunction: MetadataQueryFunction<T>,\n): MetadataQueryResult<T, E> => {\n const files = useMetadataStore<T>();\n const previous = useRef<MetadataQueryEntry<T, Record<string, unknown>>[]>([]);\n return useMemo<MetadataQueryResult<T, E>>(() => {\n let entries: MetadataQueryEntry<T, Record<string, unknown>>[];\n try {\n // `path` and `meta` are applied AFTER the record's own fields: a query cannot\n // shadow the two the hook is responsible for, whatever it happened to name.\n entries = queryFunction(files).map((selected) =>\n typeof selected === 'string'\n ? { path: selected, meta: files[selected] }\n : { ...selected, path: selected.path, meta: files[selected.path] },\n );\n } catch (error) {\n return { error };\n }\n // Preserve the prior array reference when nothing matched differently.\n if (entriesEqual(entries, previous.current)) {\n return previous.current as MetadataQueryEntry<T, E>[];\n }\n previous.current = entries;\n return entries as MetadataQueryEntry<T, E>[];\n }, [files, queryFunction]);\n};\n\n/**\n * Read one file's metadata (MDX frontmatter) by path. Returns `undefined` when the\n * path has no metadata. Pass a type parameter for typed field access.\n *\n * **The store is keyed by ABSOLUTE module path** — `/app/content/post.mdx`, the same\n * identifier `fs`, `module.dynamicImport` and `<Include>` use — not by the\n * repo-relative path this doc claimed until R3-276. Keeping metadata in the file\n * space is what lets an app read a file's metadata and render that same file by the\n * same path (`sandbox/src/bundler/metadataKey.test.ts` pins it).\n *\n * A repo-relative path (`/content/post.mdx`) is accepted as a fallback: if the path\n * is not a key, it is retried under the app root via the shared\n * `underAppRoot` helper (R3-275). That is additive — it only turns a previous\n * `undefined` into a value — and it exists because the old doc told people to pass\n * exactly that form. A path a {@link MetadataSource} provided in some other key\n * space is looked up as given, unchanged.\n */\nexport const useFileMetadata = <T = Metadata>(path: string): T | undefined => {\n const files = useMetadataStore<T>();\n return useMemo(() => {\n const direct = files[path];\n if (direct !== undefined) return direct;\n // The fallback is for a path in the REPO-RELATIVE space. An already-app-rooted\n // path that missed is simply a miss: retrying it would consult `/app/app/…`,\n // which is not a key space anything writes — it would only ever hit by accident.\n if (path === APP_ROOT || path.startsWith(`${APP_ROOT}/`)) return undefined;\n return files[underAppRoot(path)];\n }, [path, files]);\n};\n\n/**\n * The raw, reactive metadata store: a map from file path to frontmatter. The\n * escape hatch for apps that want to render their own index rather than express it\n * as a path-returning query. Pass a type parameter for typed frontmatter values.\n */\nexport const useAllMetadata = <T = Metadata>(): FilesMetadata<T> => useMetadataStore<T>();\n\n/** The reactive state returned by {@link useObjectUrl}. */\nexport interface ObjectUrlState {\n /** The object URL once the bytes have loaded; `null` while loading or on error. */\n url: string | null;\n /** True while the file is being read. */\n loading: boolean;\n /** The {@link FsError} if the read failed (`not-found`, `unavailable`, …), else `null`. */\n error: FsError | null;\n}\n\n/**\n * Read a file from a mount into an **object URL** for `<img src>`, revoking it\n * automatically on unmount or when `mount`/`relPath` changes. This is the React\n * answer to \"an opaque-origin iframe can't fetch a mount path\": it reads the bytes\n * off the sandbox ZenFS ({@link openFs}) and hands you a URL to drop into an\n * `<img>`, and it owns the create/revoke lifecycle so you never leak a URL.\n *\n * Pass `null`/`undefined` for `mount` or `relPath` to mean \"nothing to load yet\"\n * (idle state, no read). For a ready-made element use `MountImage`.\n *\n * ```tsx\n * const { url, loading, error } = useObjectUrl(mount, 'photos/cat.png');\n * if (loading) return <Spinner />;\n * if (error || !url) return <span>missing</span>;\n * return <img src={url} alt=\"cat\" />;\n * ```\n */\nexport const useObjectUrl = (\n mount: SandboxMount | null | undefined,\n relPath: string | null | undefined,\n opts?: { type?: string },\n): ObjectUrlState => {\n const [state, setState] = useState<ObjectUrlState>({\n url: null,\n loading: Boolean(mount && relPath),\n error: null,\n });\n const type = opts?.type;\n // Key the effect on the mount's stable `path` (its object identity churns as the\n // mount set re-announces) plus the relPath and the optional type override.\n const mountPath = mount?.path;\n useEffect(() => {\n if (!mount || !relPath) {\n setState({ url: null, loading: false, error: null });\n return;\n }\n let alive = true;\n let revoke: (() => void) | null = null;\n setState({ url: null, loading: true, error: null });\n openFs(mount)\n .readObjectUrl(relPath, type ? { type } : undefined)\n .then((res) => {\n // Lost the race (unmounted / prop changed): revoke immediately, don't set.\n if (!alive) {\n res.revoke();\n return;\n }\n revoke = res.revoke;\n setState({ url: res.url, loading: false, error: null });\n })\n .catch((e) => {\n if (alive) setState({ url: null, loading: false, error: e as FsError });\n });\n return () => {\n alive = false;\n if (revoke) revoke();\n };\n // `mount` is intentionally tracked via its stable `mountPath`.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mountPath, relPath, type]);\n return state;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAuC;AACvC,mBAAqD;AACrD,gBAAqC;AACrC,4BAAiC;AAUjC,MAAM,eAAe,CACnB,GACA,MACY;AACZ,MAAI,EAAE,WAAW,EAAE,QAAQ;AACzB,WAAO;AAAA,EACT;AACA,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AAGjC,QAAI,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM;AACtD,aAAO;AAAA,IACT;AAIA,UAAM,KAAK,EAAE,CAAC;AACd,UAAM,KAAK,EAAE,CAAC;AACd,UAAM,OAAO,oBAAI,IAAI,CAAC,G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KAAK;AAAA,IACL,SAAS,QAAQ,SAAS,OAAO;AAAA,IACjC,OAAO;AAAA,EACT,CAAC;AACD,QAAM,OAAO,MAAM;AAGnB,QAAM,YAAY,OAAO;AACzB,8BAAU,MAAM;AACd,QAAI,CAAC,SAAS,CAAC,SAAS;AACtB,eAAS,EAAE,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,CAAC;AACnD;AAAA,IACF;AACA,QAAI,QAAQ;AACZ,QAAI,SAA8B;AAClC,aAAS,EAAE,KAAK,MAAM,SAAS,MAAM,OAAO,KAAK,CAAC;AAClD,0BAAO,KAAK,EACT,cAAc,SAAS,OAAO,EAAE,KAAK,IAAI,MAAS,EAClD,KAAK,CAAC,QAAQ;AAEb,UAAI,CAAC,OAAO;AACV,YAAI,OAAO;AACX;AAAA,MACF;AACA,eAAS,IAAI;AACb,eAAS,EAAE,KAAK,IAAI,KAAK,SAAS,OAAO,OAAO,KAAK,CAAC;AAAA,IACxD,CAAC,EACA,MAAM,CAAC,MAAM;AACZ,UAAI,MAAO,UAAS,EAAE,KAAK,MAAM,SAAS,OAAO,OAAO,EAAa,CAAC;AAAA,IACxE,CAAC;AACH,WAAO,MAAM;AACX,cAAQ;AACR,UAAI,OAAQ,QAAO;AAAA,IACrB;AAAA,EAGF,GAAG,CAAC,WAAW,SAAS,IAAI,CAAC;AAC7B,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/hooks.ts"],"sourcesContent":["import { APP_ROOT, underAppRoot } from '@immediately-run/platform-constants';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { openFs, type FsError } from './fs';\nimport { useMetadataStore } from './metadataSource';\nimport type { SandboxMount } from './mounts';\nimport {\n FilesMetadata,\n Metadata,\n MetadataQueryEntry,\n MetadataQueryFunction,\n MetadataQueryResult,\n} from './sandboxTypes';\n\nconst entriesEqual = <T>(\n a: MetadataQueryEntry<T, Record<string, unknown>>[],\n b: MetadataQueryEntry<T, Record<string, unknown>>[],\n): boolean => {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n // Unchanged frontmatter keeps its object identity across `metadata-update`\n // merges, so an identity check on `meta` is a sound \"did this match change?\".\n if (a[i].path !== b[i].path || a[i].meta !== b[i].meta) {\n return false;\n }\n // Extra fields a record-returning query computed (R3-276) are part of the\n // result, so a change in them is a change in the result — compared by value,\n // one level, because they are derived scalars, not the store's shared objects.\n const ax = a[i] as Record<string, unknown>;\n const bx = b[i] as Record<string, unknown>;\n const keys = new Set([...Object.keys(ax), ...Object.keys(bx)]);\n for (const k of keys) {\n if (k === 'path' || k === 'meta') continue;\n if (ax[k] !== bx[k]) return false;\n }\n }\n return true;\n};\n\n/**\n * Query the file metadata store (MDX frontmatter) with a plain JS function.\n *\n * The query receives every file's frontmatter keyed by path and returns the paths\n * that match; the hook resolves each path back to its frontmatter and returns an\n * array of `{ path, meta }` entries — so a single call gives you everything you\n * filtered on, with no second lookup. A throwing query is reported as `{ error }`\n * rather than crashing the render.\n *\n * The query runs synchronously during render (no empty first frame), and the\n * returned array keeps its identity while the matches are unchanged, so it is safe\n * to use directly in downstream `useMemo`/`useEffect` dependency arrays.\n *\n * A query may return RECORDS instead of bare paths (R3-276) — `{ path, ...extra }`\n * — and the extra fields ride along on each entry, so something derived while\n * selecting does not have to be recomputed downstream:\n * ```ts\n * const posts = useMetadataQuery<PostMeta, { year: string }>((files) =>\n * Object.entries(files).map(([path, m]) => ({ path, year: m.date.slice(0, 4) })),\n * );\n * ```\n * The store it queries is the nearest {@link MetadataSource}, else the host's.\n *\n * Pass a type parameter to get typed frontmatter throughout:\n * ```ts\n * interface PostMeta { title: string; date: string; draft?: boolean }\n * const posts = useMetadataQuery<PostMeta>((files) =>\n * Object.entries(files)\n * .filter(([, m]) => !m.draft)\n * .sort(([, a], [, b]) => b.date.localeCompare(a.date))\n * .map(([path]) => path),\n * );\n * ```\n */\nexport const useMetadataQuery = <T = Metadata, E extends object = {}>(\n queryFunction: MetadataQueryFunction<T>,\n): MetadataQueryResult<T, E> => {\n const files = useMetadataStore<T>();\n const previous = useRef<MetadataQueryEntry<T, Record<string, unknown>>[]>([]);\n return useMemo<MetadataQueryResult<T, E>>(() => {\n let entries: MetadataQueryEntry<T, Record<string, unknown>>[];\n try {\n // `path` and `meta` are applied AFTER the record's own fields: a query cannot\n // shadow the two the hook is responsible for, whatever it happened to name.\n entries = queryFunction(files).map((selected) =>\n typeof selected === 'string'\n ? { path: selected, meta: files[selected] }\n : { ...selected, path: selected.path, meta: files[selected.path] },\n );\n } catch (error) {\n return { error };\n }\n // Preserve the prior array reference when nothing matched differently.\n if (entriesEqual(entries, previous.current)) {\n return previous.current as MetadataQueryEntry<T, E>[];\n }\n previous.current = entries;\n return entries as MetadataQueryEntry<T, E>[];\n }, [files, queryFunction]);\n};\n\n/**\n * Read one file's metadata (MDX frontmatter) by path. Returns `undefined` when the\n * path has no metadata. Pass a type parameter for typed field access.\n *\n * **The store is keyed by ABSOLUTE module path** — `/app/content/post.mdx`, the same\n * identifier `fs`, `module.dynamicImport` and `<Include>` use — not by the\n * repo-relative path this doc claimed until R3-276. Keeping metadata in the file\n * space is what lets an app read a file's metadata and render that same file by the\n * same path (`sandbox/src/bundler/metadataKey.test.ts` pins it).\n *\n * A repo-relative path (`/content/post.mdx`) is accepted as a fallback: if the path\n * is not a key, it is retried under the app root via the shared\n * `underAppRoot` helper (R3-275). That is additive — it only turns a previous\n * `undefined` into a value — and it exists because the old doc told people to pass\n * exactly that form. A path a {@link MetadataSource} provided in some other key\n * space is looked up as given, unchanged.\n */\nexport const useFileMetadata = <T = Metadata>(path: string): T | undefined => {\n const files = useMetadataStore<T>();\n return useMemo(() => {\n const direct = files[path];\n if (direct !== undefined) return direct;\n // The fallback is for a path in the REPO-RELATIVE space. An already-app-rooted\n // path that missed is simply a miss: retrying it would consult `/app/app/…`,\n // which is not a key space anything writes — it would only ever hit by accident.\n if (path === APP_ROOT || path.startsWith(`${APP_ROOT}/`)) return undefined;\n return files[underAppRoot(path)];\n }, [path, files]);\n};\n\n/**\n * The raw, reactive metadata store: a map from file path to frontmatter. The\n * escape hatch for apps that want to render their own index rather than express it\n * as a path-returning query. Pass a type parameter for typed frontmatter values.\n */\nexport const useAllMetadata = <T = Metadata>(): FilesMetadata<T> => useMetadataStore<T>();\n\n/** The reactive state returned by {@link useObjectUrl}. */\nexport interface ObjectUrlState {\n /** The object URL once the bytes have loaded; `null` while loading or on error. */\n url: string | null;\n /** True while the file is being read. */\n loading: boolean;\n /** The {@link FsError} if the read failed (`not-found`, `unavailable`, …), else `null`. */\n error: FsError | null;\n}\n\n/**\n * Read a file from a mount into an **object URL** for `<img src>`, revoking it\n * automatically on unmount or when `mount`/`relPath` changes. This is the React\n * answer to \"an opaque-origin iframe can't fetch a mount path\": it reads the bytes\n * off the sandbox ZenFS ({@link openFs}) and hands you a URL to drop into an\n * `<img>`, and it owns the create/revoke lifecycle so you never leak a URL.\n *\n * Pass `null`/`undefined` for `mount` or `relPath` to mean \"nothing to load yet\"\n * (idle state, no read). For a ready-made element use `MountImage`.\n *\n * ```tsx\n * const { url, loading, error } = useObjectUrl(mount, 'photos/cat.png');\n * if (loading) return <Spinner />;\n * if (error || !url) return <span>missing</span>;\n * return <img src={url} alt=\"cat\" />;\n * ```\n *\n * Off-host: under `vite dev` with the `@immediately-run/dev-fs` plugin (>= 0.5.0)\n * this works against your local disk — the plugin publishes its fs bridge where\n * the SDK discovers the sandbox fs (see `sandboxFs` in `fs.ts`). Under plain\n * `vite dev` (no plugin) there is no filesystem at all, and the hook settles to\n * `{ url: null, loading: false, error }` with `error.code === 'unavailable'` —\n * render the error/absent state, don't treat it as forever-loading.\n */\nexport const useObjectUrl = (\n mount: SandboxMount | null | undefined,\n relPath: string | null | undefined,\n opts?: { type?: string },\n): ObjectUrlState => {\n const [state, setState] = useState<ObjectUrlState>({\n url: null,\n loading: Boolean(mount && relPath),\n error: null,\n });\n const type = opts?.type;\n // Key the effect on the mount's stable `path` (its object identity churns as the\n // mount set re-announces) plus the relPath and the optional type override.\n const mountPath = mount?.path;\n useEffect(() => {\n if (!mount || !relPath) {\n setState({ url: null, loading: false, error: null });\n return;\n }\n let alive = true;\n let revoke: (() => void) | null = null;\n setState({ url: null, loading: true, error: null });\n openFs(mount)\n .readObjectUrl(relPath, type ? { type } : undefined)\n .then((res) => {\n // Lost the race (unmounted / prop changed): revoke immediately, don't set.\n if (!alive) {\n res.revoke();\n return;\n }\n revoke = res.revoke;\n setState({ url: res.url, loading: false, error: null });\n })\n .catch((e) => {\n if (alive) setState({ url: null, loading: false, error: e as FsError });\n });\n return () => {\n alive = false;\n if (revoke) revoke();\n };\n // `mount` is intentionally tracked via its stable `mountPath`.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mountPath, relPath, type]);\n return state;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAuC;AACvC,mBAAqD;AACrD,gBAAqC;AACrC,4BAAiC;AAUjC,MAAM,eAAe,CACnB,GACA,MACY;AACZ,MAAI,EAAE,WAAW,EAAE,QAAQ;AACzB,WAAO;AAAA,EACT;AACA,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AAGjC,QAAI,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM;AACtD,aAAO;AAAA,IACT;AAIA,UAAM,KAAK,EAAE,CAAC;AACd,UAAM,KAAK,EAAE,CAAC;AACd,UAAM,OAAO,oBAAI,IAAI,CAAC,GAAG,OAAO,KAAK,EAAE,GAAG,GAAG,OAAO,KAAK,EAAE,CAAC,CAAC;AAC7D,eAAW,KAAK,MAAM;AACpB,UAAI,MAAM,UAAU,MAAM,OAAQ;AAClC,UAAI,GAAG,CAAC,MAAM,GAAG,CAAC,EAAG,QAAO;AAAA,IAC9B;AAAA,EACF;AACA,SAAO;AACT;AAoCO,MAAM,mBA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;AACnD;AAAA,IACF;AACA,QAAI,QAAQ;AACZ,QAAI,SAA8B;AAClC,aAAS,EAAE,KAAK,MAAM,SAAS,MAAM,OAAO,KAAK,CAAC;AAClD,0BAAO,KAAK,EACT,cAAc,SAAS,OAAO,EAAE,KAAK,IAAI,MAAS,EAClD,KAAK,CAAC,QAAQ;AAEb,UAAI,CAAC,OAAO;AACV,YAAI,OAAO;AACX;AAAA,MACF;AACA,eAAS,IAAI;AACb,eAAS,EAAE,KAAK,IAAI,KAAK,SAAS,OAAO,OAAO,KAAK,CAAC;AAAA,IACxD,CAAC,EACA,MAAM,CAAC,MAAM;AACZ,UAAI,MAAO,UAAS,EAAE,KAAK,MAAM,SAAS,OAAO,OAAO,EAAa,CAAC;AAAA,IACxE,CAAC;AACH,WAAO,MAAM;AACX,cAAQ;AACR,UAAI,OAAQ,QAAO;AAAA,IACrB;AAAA,EAGF,GAAG,CAAC,WAAW,SAAS,IAAI,CAAC;AAC7B,SAAO;AACT;","names":[]}
package/dist/hooks.d.cts CHANGED
@@ -88,6 +88,13 @@ interface ObjectUrlState {
88
88
  * if (error || !url) return <span>missing</span>;
89
89
  * return <img src={url} alt="cat" />;
90
90
  * ```
91
+ *
92
+ * Off-host: under `vite dev` with the `@immediately-run/dev-fs` plugin (>= 0.5.0)
93
+ * this works against your local disk — the plugin publishes its fs bridge where
94
+ * the SDK discovers the sandbox fs (see `sandboxFs` in `fs.ts`). Under plain
95
+ * `vite dev` (no plugin) there is no filesystem at all, and the hook settles to
96
+ * `{ url: null, loading: false, error }` with `error.code === 'unavailable'` —
97
+ * render the error/absent state, don't treat it as forever-loading.
91
98
  */
92
99
  declare const useObjectUrl: (mount: SandboxMount | null | undefined, relPath: string | null | undefined, opts?: {
93
100
  type?: string;
package/dist/hooks.d.ts CHANGED
@@ -88,6 +88,13 @@ interface ObjectUrlState {
88
88
  * if (error || !url) return <span>missing</span>;
89
89
  * return <img src={url} alt="cat" />;
90
90
  * ```
91
+ *
92
+ * Off-host: under `vite dev` with the `@immediately-run/dev-fs` plugin (>= 0.5.0)
93
+ * this works against your local disk — the plugin publishes its fs bridge where
94
+ * the SDK discovers the sandbox fs (see `sandboxFs` in `fs.ts`). Under plain
95
+ * `vite dev` (no plugin) there is no filesystem at all, and the hook settles to
96
+ * `{ url: null, loading: false, error }` with `error.code === 'unavailable'` —
97
+ * render the error/absent state, don't treat it as forever-loading.
91
98
  */
92
99
  declare const useObjectUrl: (mount: SandboxMount | null | undefined, relPath: string | null | undefined, opts?: {
93
100
  type?: string;
package/dist/hooks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks.ts"],"sourcesContent":["import { APP_ROOT, underAppRoot } from '@immediately-run/platform-constants';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { openFs, type FsError } from './fs';\nimport { useMetadataStore } from './metadataSource';\nimport type { SandboxMount } from './mounts';\nimport {\n FilesMetadata,\n Metadata,\n MetadataQueryEntry,\n MetadataQueryFunction,\n MetadataQueryResult,\n} from './sandboxTypes';\n\nconst entriesEqual = <T>(\n a: MetadataQueryEntry<T, Record<string, unknown>>[],\n b: MetadataQueryEntry<T, Record<string, unknown>>[],\n): boolean => {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n // Unchanged frontmatter keeps its object identity across `metadata-update`\n // merges, so an identity check on `meta` is a sound \"did this match change?\".\n if (a[i].path !== b[i].path || a[i].meta !== b[i].meta) {\n return false;\n }\n // Extra fields a record-returning query computed (R3-276) are part of the\n // result, so a change in them is a change in the result — compared by value,\n // one level, because they are derived scalars, not the store's shared objects.\n const ax = a[i] as Record<string, unknown>;\n const bx = b[i] as Record<string, unknown>;\n const keys = new Set([...Object.keys(ax), ...Object.keys(bx)]);\n for (const k of keys) {\n if (k === 'path' || k === 'meta') continue;\n if (ax[k] !== bx[k]) return false;\n }\n }\n return true;\n};\n\n/**\n * Query the file metadata store (MDX frontmatter) with a plain JS function.\n *\n * The query receives every file's frontmatter keyed by path and returns the paths\n * that match; the hook resolves each path back to its frontmatter and returns an\n * array of `{ path, meta }` entries — so a single call gives you everything you\n * filtered on, with no second lookup. A throwing query is reported as `{ error }`\n * rather than crashing the render.\n *\n * The query runs synchronously during render (no empty first frame), and the\n * returned array keeps its identity while the matches are unchanged, so it is safe\n * to use directly in downstream `useMemo`/`useEffect` dependency arrays.\n *\n * A query may return RECORDS instead of bare paths (R3-276) — `{ path, ...extra }`\n * — and the extra fields ride along on each entry, so something derived while\n * selecting does not have to be recomputed downstream:\n * ```ts\n * const posts = useMetadataQuery<PostMeta, { year: string }>((files) =>\n * Object.entries(files).map(([path, m]) => ({ path, year: m.date.slice(0, 4) })),\n * );\n * ```\n * The store it queries is the nearest {@link MetadataSource}, else the host's.\n *\n * Pass a type parameter to get typed frontmatter throughout:\n * ```ts\n * interface PostMeta { title: string; date: string; draft?: boolean }\n * const posts = useMetadataQuery<PostMeta>((files) =>\n * Object.entries(files)\n * .filter(([, m]) => !m.draft)\n * .sort(([, a], [, b]) => b.date.localeCompare(a.date))\n * .map(([path]) => path),\n * );\n * ```\n */\nexport const useMetadataQuery = <T = Metadata, E extends object = {}>(\n queryFunction: MetadataQueryFunction<T>,\n): MetadataQueryResult<T, E> => {\n const files = useMetadataStore<T>();\n const previous = useRef<MetadataQueryEntry<T, Record<string, unknown>>[]>([]);\n return useMemo<MetadataQueryResult<T, E>>(() => {\n let entries: MetadataQueryEntry<T, Record<string, unknown>>[];\n try {\n // `path` and `meta` are applied AFTER the record's own fields: a query cannot\n // shadow the two the hook is responsible for, whatever it happened to name.\n entries = queryFunction(files).map((selected) =>\n typeof selected === 'string'\n ? { path: selected, meta: files[selected] }\n : { ...selected, path: selected.path, meta: files[selected.path] },\n );\n } catch (error) {\n return { error };\n }\n // Preserve the prior array reference when nothing matched differently.\n if (entriesEqual(entries, previous.current)) {\n return previous.current as MetadataQueryEntry<T, E>[];\n }\n previous.current = entries;\n return entries as MetadataQueryEntry<T, E>[];\n }, [files, queryFunction]);\n};\n\n/**\n * Read one file's metadata (MDX frontmatter) by path. Returns `undefined` when the\n * path has no metadata. Pass a type parameter for typed field access.\n *\n * **The store is keyed by ABSOLUTE module path** — `/app/content/post.mdx`, the same\n * identifier `fs`, `module.dynamicImport` and `<Include>` use — not by the\n * repo-relative path this doc claimed until R3-276. Keeping metadata in the file\n * space is what lets an app read a file's metadata and render that same file by the\n * same path (`sandbox/src/bundler/metadataKey.test.ts` pins it).\n *\n * A repo-relative path (`/content/post.mdx`) is accepted as a fallback: if the path\n * is not a key, it is retried under the app root via the shared\n * `underAppRoot` helper (R3-275). That is additive — it only turns a previous\n * `undefined` into a value — and it exists because the old doc told people to pass\n * exactly that form. A path a {@link MetadataSource} provided in some other key\n * space is looked up as given, unchanged.\n */\nexport const useFileMetadata = <T = Metadata>(path: string): T | undefined => {\n const files = useMetadataStore<T>();\n return useMemo(() => {\n const direct = files[path];\n if (direct !== undefined) return direct;\n // The fallback is for a path in the REPO-RELATIVE space. An already-app-rooted\n // path that missed is simply a miss: retrying it would consult `/app/app/…`,\n // which is not a key space anything writes — it would only ever hit by accident.\n if (path === APP_ROOT || path.startsWith(`${APP_ROOT}/`)) return undefined;\n return files[underAppRoot(path)];\n }, [path, files]);\n};\n\n/**\n * The raw, reactive metadata store: a map from file path to frontmatter. The\n * escape hatch for apps that want to render their own index rather than express it\n * as a path-returning query. Pass a type parameter for typed frontmatter values.\n */\nexport const useAllMetadata = <T = Metadata>(): FilesMetadata<T> => useMetadataStore<T>();\n\n/** The reactive state returned by {@link useObjectUrl}. */\nexport interface ObjectUrlState {\n /** The object URL once the bytes have loaded; `null` while loading or on error. */\n url: string | null;\n /** True while the file is being read. */\n loading: boolean;\n /** The {@link FsError} if the read failed (`not-found`, `unavailable`, …), else `null`. */\n error: FsError | null;\n}\n\n/**\n * Read a file from a mount into an **object URL** for `<img src>`, revoking it\n * automatically on unmount or when `mount`/`relPath` changes. This is the React\n * answer to \"an opaque-origin iframe can't fetch a mount path\": it reads the bytes\n * off the sandbox ZenFS ({@link openFs}) and hands you a URL to drop into an\n * `<img>`, and it owns the create/revoke lifecycle so you never leak a URL.\n *\n * Pass `null`/`undefined` for `mount` or `relPath` to mean \"nothing to load yet\"\n * (idle state, no read). For a ready-made element use `MountImage`.\n *\n * ```tsx\n * const { url, loading, error } = useObjectUrl(mount, 'photos/cat.png');\n * if (loading) return <Spinner />;\n * if (error || !url) return <span>missing</span>;\n * return <img src={url} alt=\"cat\" />;\n * ```\n */\nexport const useObjectUrl = (\n mount: SandboxMount | null | undefined,\n relPath: string | null | undefined,\n opts?: { type?: string },\n): ObjectUrlState => {\n const [state, setState] = useState<ObjectUrlState>({\n url: null,\n loading: Boolean(mount && relPath),\n error: null,\n });\n const type = opts?.type;\n // Key the effect on the mount's stable `path` (its object identity churns as the\n // mount set re-announces) plus the relPath and the optional type override.\n const mountPath = mount?.path;\n useEffect(() => {\n if (!mount || !relPath) {\n setState({ url: null, loading: false, error: null });\n return;\n }\n let alive = true;\n let revoke: (() => void) | null = null;\n setState({ url: null, loading: true, error: null });\n openFs(mount)\n .readObjectUrl(relPath, type ? { type } : undefined)\n .then((res) => {\n // Lost the race (unmounted / prop changed): revoke immediately, don't set.\n if (!alive) {\n res.revoke();\n return;\n }\n revoke = res.revoke;\n setState({ url: res.url, loading: false, error: null });\n })\n .catch((e) => {\n if (alive) setState({ url: null, loading: false, error: e as FsError });\n });\n return () => {\n alive = false;\n if (revoke) revoke();\n };\n // `mount` is intentionally tracked via its stable `mountPath`.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mountPath, relPath, type]);\n return state;\n};\n"],"mappings":";AAAA,SAAS,UAAU,oBAAoB;AACvC,SAAS,WAAW,SAAS,QAAQ,gBAAgB;AACrD,SAAS,cAA4B;AACrC,SAAS,wBAAwB;AAUjC,MAAM,eAAe,CACnB,GACA,MACY;AACZ,MAAI,EAAE,WAAW,EAAE,QAAQ;AACzB,WAAO;AAAA,EACT;AACA,WAAS,IAAI,GAAG,IAAI,EAAE,QA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EAAG,QAAO;AACjE,WAAO,MAAM,aAAa,IAAI,CAAC;AAAA,EACjC,GAAG,CAAC,MAAM,KAAK,CAAC;AAClB;AAOO,MAAM,iBAAiB,MAAsC,iBAAoB;AA6BjF,MAAM,eAAe,CAC1B,OACA,SACA,SACmB;AACnB,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAyB;AAAA,IACjD,KAAK;AAAA,IACL,SAAS,QAAQ,SAAS,OAAO;AAAA,IACjC,OAAO;AAAA,EACT,CAAC;AACD,QAAM,OAAO,MAAM;AAGnB,QAAM,YAAY,OAAO;AACzB,YAAU,MAAM;AACd,QAAI,CAAC,SAAS,CAAC,SAAS;AACtB,eAAS,EAAE,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,CAAC;AACnD;AAAA,IACF;AACA,QAAI,QAAQ;AACZ,QAAI,SAA8B;AAClC,aAAS,EAAE,KAAK,MAAM,SAAS,MAAM,OAAO,KAAK,CAAC;AAClD,WAAO,KAAK,EACT,cAAc,SAAS,OAAO,EAAE,KAAK,IAAI,MAAS,EAClD,KAAK,CAAC,QAAQ;AAEb,UAAI,CAAC,OAAO;AACV,YAAI,OAAO;AACX;AAAA,MACF;AACA,eAAS,IAAI;AACb,eAAS,EAAE,KAAK,IAAI,KAAK,SAAS,OAAO,OAAO,KAAK,CAAC;AAAA,IACxD,CAAC,EACA,MAAM,CAAC,MAAM;AACZ,UAAI,MAAO,UAAS,EAAE,KAAK,MAAM,SAAS,OAAO,OAAO,EAAa,CAAC;AAAA,IACxE,CAAC;AACH,WAAO,MAAM;AACX,cAAQ;AACR,UAAI,OAAQ,QAAO;AAAA,IACrB;AAAA,EAGF,GAAG,CAAC,WAAW,SAAS,IAAI,CAAC;AAC7B,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/hooks.ts"],"sourcesContent":["import { APP_ROOT, underAppRoot } from '@immediately-run/platform-constants';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { openFs, type FsError } from './fs';\nimport { useMetadataStore } from './metadataSource';\nimport type { SandboxMount } from './mounts';\nimport {\n FilesMetadata,\n Metadata,\n MetadataQueryEntry,\n MetadataQueryFunction,\n MetadataQueryResult,\n} from './sandboxTypes';\n\nconst entriesEqual = <T>(\n a: MetadataQueryEntry<T, Record<string, unknown>>[],\n b: MetadataQueryEntry<T, Record<string, unknown>>[],\n): boolean => {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n // Unchanged frontmatter keeps its object identity across `metadata-update`\n // merges, so an identity check on `meta` is a sound \"did this match change?\".\n if (a[i].path !== b[i].path || a[i].meta !== b[i].meta) {\n return false;\n }\n // Extra fields a record-returning query computed (R3-276) are part of the\n // result, so a change in them is a change in the result — compared by value,\n // one level, because they are derived scalars, not the store's shared objects.\n const ax = a[i] as Record<string, unknown>;\n const bx = b[i] as Record<string, unknown>;\n const keys = new Set([...Object.keys(ax), ...Object.keys(bx)]);\n for (const k of keys) {\n if (k === 'path' || k === 'meta') continue;\n if (ax[k] !== bx[k]) return false;\n }\n }\n return true;\n};\n\n/**\n * Query the file metadata store (MDX frontmatter) with a plain JS function.\n *\n * The query receives every file's frontmatter keyed by path and returns the paths\n * that match; the hook resolves each path back to its frontmatter and returns an\n * array of `{ path, meta }` entries — so a single call gives you everything you\n * filtered on, with no second lookup. A throwing query is reported as `{ error }`\n * rather than crashing the render.\n *\n * The query runs synchronously during render (no empty first frame), and the\n * returned array keeps its identity while the matches are unchanged, so it is safe\n * to use directly in downstream `useMemo`/`useEffect` dependency arrays.\n *\n * A query may return RECORDS instead of bare paths (R3-276) — `{ path, ...extra }`\n * — and the extra fields ride along on each entry, so something derived while\n * selecting does not have to be recomputed downstream:\n * ```ts\n * const posts = useMetadataQuery<PostMeta, { year: string }>((files) =>\n * Object.entries(files).map(([path, m]) => ({ path, year: m.date.slice(0, 4) })),\n * );\n * ```\n * The store it queries is the nearest {@link MetadataSource}, else the host's.\n *\n * Pass a type parameter to get typed frontmatter throughout:\n * ```ts\n * interface PostMeta { title: string; date: string; draft?: boolean }\n * const posts = useMetadataQuery<PostMeta>((files) =>\n * Object.entries(files)\n * .filter(([, m]) => !m.draft)\n * .sort(([, a], [, b]) => b.date.localeCompare(a.date))\n * .map(([path]) => path),\n * );\n * ```\n */\nexport const useMetadataQuery = <T = Metadata, E extends object = {}>(\n queryFunction: MetadataQueryFunction<T>,\n): MetadataQueryResult<T, E> => {\n const files = useMetadataStore<T>();\n const previous = useRef<MetadataQueryEntry<T, Record<string, unknown>>[]>([]);\n return useMemo<MetadataQueryResult<T, E>>(() => {\n let entries: MetadataQueryEntry<T, Record<string, unknown>>[];\n try {\n // `path` and `meta` are applied AFTER the record's own fields: a query cannot\n // shadow the two the hook is responsible for, whatever it happened to name.\n entries = queryFunction(files).map((selected) =>\n typeof selected === 'string'\n ? { path: selected, meta: files[selected] }\n : { ...selected, path: selected.path, meta: files[selected.path] },\n );\n } catch (error) {\n return { error };\n }\n // Preserve the prior array reference when nothing matched differently.\n if (entriesEqual(entries, previous.current)) {\n return previous.current as MetadataQueryEntry<T, E>[];\n }\n previous.current = entries;\n return entries as MetadataQueryEntry<T, E>[];\n }, [files, queryFunction]);\n};\n\n/**\n * Read one file's metadata (MDX frontmatter) by path. Returns `undefined` when the\n * path has no metadata. Pass a type parameter for typed field access.\n *\n * **The store is keyed by ABSOLUTE module path** — `/app/content/post.mdx`, the same\n * identifier `fs`, `module.dynamicImport` and `<Include>` use — not by the\n * repo-relative path this doc claimed until R3-276. Keeping metadata in the file\n * space is what lets an app read a file's metadata and render that same file by the\n * same path (`sandbox/src/bundler/metadataKey.test.ts` pins it).\n *\n * A repo-relative path (`/content/post.mdx`) is accepted as a fallback: if the path\n * is not a key, it is retried under the app root via the shared\n * `underAppRoot` helper (R3-275). That is additive — it only turns a previous\n * `undefined` into a value — and it exists because the old doc told people to pass\n * exactly that form. A path a {@link MetadataSource} provided in some other key\n * space is looked up as given, unchanged.\n */\nexport const useFileMetadata = <T = Metadata>(path: string): T | undefined => {\n const files = useMetadataStore<T>();\n return useMemo(() => {\n const direct = files[path];\n if (direct !== undefined) return direct;\n // The fallback is for a path in the REPO-RELATIVE space. An already-app-rooted\n // path that missed is simply a miss: retrying it would consult `/app/app/…`,\n // which is not a key space anything writes — it would only ever hit by accident.\n if (path === APP_ROOT || path.startsWith(`${APP_ROOT}/`)) return undefined;\n return files[underAppRoot(path)];\n }, [path, files]);\n};\n\n/**\n * The raw, reactive metadata store: a map from file path to frontmatter. The\n * escape hatch for apps that want to render their own index rather than express it\n * as a path-returning query. Pass a type parameter for typed frontmatter values.\n */\nexport const useAllMetadata = <T = Metadata>(): FilesMetadata<T> => useMetadataStore<T>();\n\n/** The reactive state returned by {@link useObjectUrl}. */\nexport interface ObjectUrlState {\n /** The object URL once the bytes have loaded; `null` while loading or on error. */\n url: string | null;\n /** True while the file is being read. */\n loading: boolean;\n /** The {@link FsError} if the read failed (`not-found`, `unavailable`, …), else `null`. */\n error: FsError | null;\n}\n\n/**\n * Read a file from a mount into an **object URL** for `<img src>`, revoking it\n * automatically on unmount or when `mount`/`relPath` changes. This is the React\n * answer to \"an opaque-origin iframe can't fetch a mount path\": it reads the bytes\n * off the sandbox ZenFS ({@link openFs}) and hands you a URL to drop into an\n * `<img>`, and it owns the create/revoke lifecycle so you never leak a URL.\n *\n * Pass `null`/`undefined` for `mount` or `relPath` to mean \"nothing to load yet\"\n * (idle state, no read). For a ready-made element use `MountImage`.\n *\n * ```tsx\n * const { url, loading, error } = useObjectUrl(mount, 'photos/cat.png');\n * if (loading) return <Spinner />;\n * if (error || !url) return <span>missing</span>;\n * return <img src={url} alt=\"cat\" />;\n * ```\n *\n * Off-host: under `vite dev` with the `@immediately-run/dev-fs` plugin (>= 0.5.0)\n * this works against your local disk — the plugin publishes its fs bridge where\n * the SDK discovers the sandbox fs (see `sandboxFs` in `fs.ts`). Under plain\n * `vite dev` (no plugin) there is no filesystem at all, and the hook settles to\n * `{ url: null, loading: false, error }` with `error.code === 'unavailable'` —\n * render the error/absent state, don't treat it as forever-loading.\n */\nexport const useObjectUrl = (\n mount: SandboxMount | null | undefined,\n relPath: string | null | undefined,\n opts?: { type?: string },\n): ObjectUrlState => {\n const [state, setState] = useState<ObjectUrlState>({\n url: null,\n loading: Boolean(mount && relPath),\n error: null,\n });\n const type = opts?.type;\n // Key the effect on the mount's stable `path` (its object identity churns as the\n // mount set re-announces) plus the relPath and the optional type override.\n const mountPath = mount?.path;\n useEffect(() => {\n if (!mount || !relPath) {\n setState({ url: null, loading: false, error: null });\n return;\n }\n let alive = true;\n let revoke: (() => void) | null = null;\n setState({ url: null, loading: true, error: null });\n openFs(mount)\n .readObjectUrl(relPath, type ? { type } : undefined)\n .then((res) => {\n // Lost the race (unmounted / prop changed): revoke immediately, don't set.\n if (!alive) {\n res.revoke();\n return;\n }\n revoke = res.revoke;\n setState({ url: res.url, loading: false, error: null });\n })\n .catch((e) => {\n if (alive) setState({ url: null, loading: false, error: e as FsError });\n });\n return () => {\n alive = false;\n if (revoke) revoke();\n };\n // `mount` is intentionally tracked via its stable `mountPath`.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [mountPath, relPath, type]);\n return state;\n};\n"],"mappings":";AAAA,SAAS,UAAU,oBAAoB;AACvC,SAAS,WAAW,SAAS,QAAQ,gBAAgB;AACrD,SAAS,cAA4B;AACrC,SAAS,wBAAwB;AAUjC,MAAM,eAAe,CACnB,GACA,MACY;AACZ,MAAI,EAAE,WAAW,EAAE,QAAQ;AACzB,WAAO;AAAA,EACT;AACA,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AAGjC,QAAI,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM;AACtD,aAAO;AAAA,IACT;AAIA,UAAM,KAAK,EAAE,CAAC;AACd,UAAM,KAAK,EAAE,CAAC;AACd,UAAM,OAAO,oBAAI,IAAI,CAAC,GAAG,OAAO,KAAK,EAAE,GAAG,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AAO;AAAA,IACjC,OAAO;AAAA,EACT,CAAC;AACD,QAAM,OAAO,MAAM;AAGnB,QAAM,YAAY,OAAO;AACzB,YAAU,MAAM;AACd,QAAI,CAAC,SAAS,CAAC,SAAS;AACtB,eAAS,EAAE,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,CAAC;AACnD;AAAA,IACF;AACA,QAAI,QAAQ;AACZ,QAAI,SAA8B;AAClC,aAAS,EAAE,KAAK,MAAM,SAAS,MAAM,OAAO,KAAK,CAAC;AAClD,WAAO,KAAK,EACT,cAAc,SAAS,OAAO,EAAE,KAAK,IAAI,MAAS,EAClD,KAAK,CAAC,QAAQ;AAEb,UAAI,CAAC,OAAO;AACV,YAAI,OAAO;AACX;AAAA,MACF;AACA,eAAS,IAAI;AACb,eAAS,EAAE,KAAK,IAAI,KAAK,SAAS,OAAO,OAAO,KAAK,CAAC;AAAA,IACxD,CAAC,EACA,MAAM,CAAC,MAAM;AACZ,UAAI,MAAO,UAAS,EAAE,KAAK,MAAM,SAAS,OAAO,OAAO,EAAa,CAAC;AAAA,IACxE,CAAC;AACH,WAAO,MAAM;AACX,cAAQ;AACR,UAAI,OAAQ,QAAO;AAAA,IACrB;AAAA,EAGF,GAAG,CAAC,WAAW,SAAS,IAAI,CAAC;AAC7B,SAAO;AACT;","names":[]}
package/dist/index.cjs CHANGED
@@ -32,6 +32,7 @@ var import_SafeInclude = require("./components/SafeInclude");
32
32
  __reExport(index_exports, require("./sourceCache"), module.exports);
33
33
  __reExport(index_exports, require("./components/MDXComponents"), module.exports);
34
34
  __reExport(index_exports, require("./linkSpace"), module.exports);
35
+ __reExport(index_exports, require("./bundle"), module.exports);
35
36
  __reExport(index_exports, require("./corpus"), module.exports);
36
37
  __reExport(index_exports, require("./components/MountImage"), module.exports);
37
38
  __reExport(index_exports, require("./components/Routes"), module.exports);
@@ -55,6 +56,7 @@ __reExport(index_exports, require("./dnd"), module.exports);
55
56
  __reExport(index_exports, require("./netFetch"), module.exports);
56
57
  __reExport(index_exports, require("./feed"), module.exports);
57
58
  __reExport(index_exports, require("./secrets"), module.exports);
59
+ __reExport(index_exports, require("./recents"), module.exports);
58
60
  __reExport(index_exports, require("./llm"), module.exports);
59
61
  __reExport(index_exports, require("./diagnostics"), module.exports);
60
62
  __reExport(index_exports, require("./vcs"), module.exports);
@@ -71,6 +73,13 @@ __reExport(index_exports, require("./protocolStream"), module.exports);
71
73
  __reExport(index_exports, require("./protocolDeadline"), module.exports);
72
74
  __reExport(index_exports, require("./sandboxTypes"), module.exports);
73
75
  __reExport(index_exports, require("./safeContent"), module.exports);
76
+ __reExport(index_exports, require("./agentLoop"), module.exports);
77
+ __reExport(index_exports, require("./agentSteering"), module.exports);
78
+ __reExport(index_exports, require("./agentChatClient"), module.exports);
79
+ __reExport(index_exports, require("./metadataQueryTool"), module.exports);
80
+ __reExport(index_exports, require("./collectHeadings"), module.exports);
81
+ __reExport(index_exports, require("./agentContext"), module.exports);
82
+ __reExport(index_exports, require("./fence"), module.exports);
74
83
  // Annotate the CommonJS export names for ESM import in node:
75
84
  0 && (module.exports = {
76
85
  SafeInclude,
@@ -83,6 +92,7 @@ __reExport(index_exports, require("./safeContent"), module.exports);
83
92
  ...require("./sourceCache"),
84
93
  ...require("./components/MDXComponents"),
85
94
  ...require("./linkSpace"),
95
+ ...require("./bundle"),
86
96
  ...require("./corpus"),
87
97
  ...require("./components/MountImage"),
88
98
  ...require("./components/Routes"),
@@ -105,6 +115,7 @@ __reExport(index_exports, require("./safeContent"), module.exports);
105
115
  ...require("./netFetch"),
106
116
  ...require("./feed"),
107
117
  ...require("./secrets"),
118
+ ...require("./recents"),
108
119
  ...require("./llm"),
109
120
  ...require("./diagnostics"),
110
121
  ...require("./vcs"),
@@ -120,6 +131,13 @@ __reExport(index_exports, require("./safeContent"), module.exports);
120
131
  ...require("./protocolStream"),
121
132
  ...require("./protocolDeadline"),
122
133
  ...require("./sandboxTypes"),
123
- ...require("./safeContent")
134
+ ...require("./safeContent"),
135
+ ...require("./agentLoop"),
136
+ ...require("./agentSteering"),
137
+ ...require("./agentChatClient"),
138
+ ...require("./metadataQueryTool"),
139
+ ...require("./collectHeadings"),
140
+ ...require("./agentContext"),
141
+ ...require("./fence")
124
142
  });
125
143
  //# sourceMappingURL=index.cjs.map