@immediately-run/sdk 0.43.1 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ambient.d.ts +47 -0
- package/dist/auth.cjs +3 -2
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.js +3 -2
- package/dist/auth.js.map +1 -1
- package/dist/boot.cjs +3 -2
- package/dist/boot.cjs.map +1 -1
- package/dist/boot.js +3 -2
- package/dist/boot.js.map +1 -1
- package/dist/catalog.cjs +3 -2
- package/dist/catalog.cjs.map +1 -1
- package/dist/catalog.js +3 -2
- package/dist/catalog.js.map +1 -1
- package/dist/components/MDXComponents.cjs +14 -1
- package/dist/components/MDXComponents.cjs.map +1 -1
- package/dist/components/MDXComponents.js +14 -1
- package/dist/components/MDXComponents.js.map +1 -1
- package/dist/components/WikiLink.cjs +19 -17
- package/dist/components/WikiLink.cjs.map +1 -1
- package/dist/components/WikiLink.js +19 -17
- package/dist/components/WikiLink.js.map +1 -1
- package/dist/contribute.cjs +2 -1
- package/dist/contribute.cjs.map +1 -1
- package/dist/contribute.js +2 -1
- package/dist/contribute.js.map +1 -1
- package/dist/debug.cjs +6 -5
- package/dist/debug.cjs.map +1 -1
- package/dist/debug.js +12 -5
- package/dist/debug.js.map +1 -1
- package/dist/diagnostics.cjs +3 -2
- package/dist/diagnostics.cjs.map +1 -1
- package/dist/diagnostics.js +3 -2
- package/dist/diagnostics.js.map +1 -1
- package/dist/dnd.cjs +5 -3
- package/dist/dnd.cjs.map +1 -1
- package/dist/dnd.js +5 -3
- package/dist/dnd.js.map +1 -1
- package/dist/editor.cjs +3 -1
- package/dist/editor.cjs.map +1 -1
- package/dist/editor.js +3 -1
- package/dist/editor.js.map +1 -1
- package/dist/editorContext.cjs +3 -2
- package/dist/editorContext.cjs.map +1 -1
- package/dist/editorContext.js +3 -2
- package/dist/editorContext.js.map +1 -1
- package/dist/formFactor.cjs +3 -2
- package/dist/formFactor.cjs.map +1 -1
- package/dist/formFactor.js +3 -2
- package/dist/formFactor.js.map +1 -1
- package/dist/generated/protocol.cjs +23 -0
- package/dist/generated/protocol.cjs.map +1 -0
- package/dist/generated/protocol.d.cts +1 -0
- package/dist/generated/protocol.d.ts +1 -0
- package/dist/generated/protocol.js +2 -0
- package/dist/generated/protocol.js.map +1 -0
- package/dist/hooks.cjs +22 -14
- package/dist/hooks.cjs.map +1 -1
- package/dist/hooks.d.cts +26 -4
- package/dist/hooks.d.ts +26 -4
- package/dist/hooks.js +23 -15
- package/dist/hooks.js.map +1 -1
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/ipc.cjs +5 -3
- package/dist/ipc.cjs.map +1 -1
- package/dist/ipc.js +5 -3
- package/dist/ipc.js.map +1 -1
- package/dist/launch.cjs +5 -3
- package/dist/launch.cjs.map +1 -1
- package/dist/launch.js +5 -3
- package/dist/launch.js.map +1 -1
- package/dist/linkSpace.cjs +63 -0
- package/dist/linkSpace.cjs.map +1 -0
- package/dist/linkSpace.d.cts +44 -0
- package/dist/linkSpace.d.ts +44 -0
- package/dist/linkSpace.js +37 -0
- package/dist/linkSpace.js.map +1 -0
- package/dist/llm.cjs +3 -2
- package/dist/llm.cjs.map +1 -1
- package/dist/llm.js +3 -2
- package/dist/llm.js.map +1 -1
- package/dist/metadataSource.cjs +53 -0
- package/dist/metadataSource.cjs.map +1 -0
- package/dist/metadataSource.d.cts +51 -0
- package/dist/metadataSource.d.ts +51 -0
- package/dist/metadataSource.js +29 -0
- package/dist/metadataSource.js.map +1 -0
- package/dist/moduleCache.cjs +2 -1
- package/dist/moduleCache.cjs.map +1 -1
- package/dist/moduleCache.js +2 -1
- package/dist/moduleCache.js.map +1 -1
- package/dist/mounts.cjs +13 -10
- package/dist/mounts.cjs.map +1 -1
- package/dist/mounts.js +23 -10
- package/dist/mounts.js.map +1 -1
- package/dist/netFetch.cjs +4 -2
- package/dist/netFetch.cjs.map +1 -1
- package/dist/netFetch.js +4 -2
- package/dist/netFetch.js.map +1 -1
- package/dist/onFsChange.cjs +2 -1
- package/dist/onFsChange.cjs.map +1 -1
- package/dist/onFsChange.js +2 -1
- package/dist/onFsChange.js.map +1 -1
- package/dist/protocolSchemes.cjs +46 -0
- package/dist/protocolSchemes.cjs.map +1 -0
- package/dist/protocolSchemes.d.cts +18 -0
- package/dist/protocolSchemes.d.ts +18 -0
- package/dist/protocolSchemes.js +37 -0
- package/dist/protocolSchemes.js.map +1 -0
- package/dist/routing.cjs +2 -1
- package/dist/routing.cjs.map +1 -1
- package/dist/routing.js +2 -1
- package/dist/routing.js.map +1 -1
- package/dist/runtime.cjs +4 -2
- package/dist/runtime.cjs.map +1 -1
- package/dist/runtime.js +4 -2
- package/dist/runtime.js.map +1 -1
- package/dist/safeContent/renderMdast.cjs +2 -0
- package/dist/safeContent/renderMdast.cjs.map +1 -1
- package/dist/safeContent/renderMdast.js +2 -0
- package/dist/safeContent/renderMdast.js.map +1 -1
- package/dist/sandboxTypes.cjs.map +1 -1
- package/dist/sandboxTypes.d.cts +40 -6
- package/dist/sandboxTypes.d.ts +40 -6
- package/dist/secrets.cjs +5 -3
- package/dist/secrets.cjs.map +1 -1
- package/dist/secrets.js +5 -3
- package/dist/secrets.js.map +1 -1
- package/dist/tasks.cjs +6 -4
- package/dist/tasks.cjs.map +1 -1
- package/dist/tasks.js +6 -4
- package/dist/tasks.js.map +1 -1
- package/dist/theme.cjs +5 -3
- package/dist/theme.cjs.map +1 -1
- package/dist/theme.js +5 -3
- package/dist/theme.js.map +1 -1
- package/dist/urlUtils.cjs +3 -4
- package/dist/urlUtils.cjs.map +1 -1
- package/dist/urlUtils.d.cts +3 -10
- package/dist/urlUtils.d.ts +3 -10
- package/dist/urlUtils.js +1 -2
- package/dist/urlUtils.js.map +1 -1
- package/dist/vcs.cjs +5 -3
- package/dist/vcs.cjs.map +1 -1
- package/dist/vcs.js +5 -3
- package/dist/vcs.js.map +1 -1
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +11 -4
package/dist/tasks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): FileCap => ({ $cap: 'file', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): DirCap => ({ $cap: 'dir', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (undeclared task or a file\n * delegation you don't hold), `no-such-task`, `task-cycle`/`task-depth-exceeded`/\n * `task-version-mismatch`, or `invalid-params` (result failed the contract schema).\n */\nexport const invokeTask = async <R = unknown>(\n task: string,\n params: Record<string, unknown> = {},\n): Promise<R> => {\n const res = (await protocolRequest(
|
|
1
|
+
{"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { PROTOCOL_TASK, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): FileCap => ({ $cap: 'file', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): DirCap => ({ $cap: 'dir', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (undeclared task or a file\n * delegation you don't hold), `no-such-task`, `task-cycle`/`task-depth-exceeded`/\n * `task-version-mismatch`, or `invalid-params` (result failed the contract schema).\n */\nexport const invokeTask = async <R = unknown>(\n task: string,\n params: Record<string, unknown> = {},\n): Promise<R> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }])) as\n | { ok: true; data: R }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `task '${task}' failed`) as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\n\n// The host delivers a `task-input` message to the callee's iframe right after it\n// mounts the overlay (the §5.7 \"params via the region's mount event\").\naddListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n latestInput = { task: m.task, params: m.params ?? {} };\n inputListeners.forEach((l) => l(latestInput!));\n});\n\n/** The task params this app was invoked with, or null if it isn't a task callee. */\nexport const getTaskInput = (): TaskInput | null => latestInput;\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n */\nexport const completeTask = (result: unknown): void => sendMessage(TASK_COMPLETE, { result });\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`. */\nexport const cancelTask = (): void => sendMessage(TASK_CANCEL, {});\n\n/** React hook: the task input for this callee, re-rendering when it arrives. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete(l);\n };\n }, []);\n return input;\n};\n"],"mappings":";AAWA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,eAAe,aAAa,eAAe,kBAAkB;AACtE,SAAS,eAAe;AAmBjB,MAAM,UAAU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, {
|
|
|
26
26
|
module.exports = __toCommonJS(theme_exports);
|
|
27
27
|
var import_pushChannel = require("./pushChannel");
|
|
28
28
|
var import_sandboxUtils = require("./sandboxUtils");
|
|
29
|
+
var import_protocol = require("./generated/protocol");
|
|
30
|
+
var import_protocolSchemes = require("./protocolSchemes");
|
|
29
31
|
const channel = (0, import_pushChannel.createPushChannel)({
|
|
30
|
-
pushType:
|
|
31
|
-
requestType:
|
|
32
|
+
pushType: import_protocol.THEME,
|
|
33
|
+
requestType: import_protocol.REQUEST_THEME,
|
|
32
34
|
initial: "dark",
|
|
33
35
|
parse: (msg) => msg.theme === "light" || msg.theme === "dark" ? msg.theme : void 0
|
|
34
36
|
});
|
|
@@ -36,7 +38,7 @@ const getHostTheme = () => channel.get();
|
|
|
36
38
|
const onHostThemeChange = (listener) => channel.onChange(listener);
|
|
37
39
|
const useHostTheme = () => channel.use();
|
|
38
40
|
const setHostTheme = async (theme) => {
|
|
39
|
-
const res = await (0, import_sandboxUtils.protocolRequest)(
|
|
41
|
+
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_THEME], "set", [{ theme }]);
|
|
40
42
|
if (!res || res.ok !== true) {
|
|
41
43
|
const err = new Error(res?.message ?? "setHostTheme failed");
|
|
42
44
|
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
package/dist/theme.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\n\n/**\n * The host UI theme, mirrored from the immediately.run host window into the\n * sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n */\nexport type HostTheme = 'light' | 'dark';\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The host's\n// default before it reports is `dark` (sandbox themeState.DEFAULT_THEME).\nconst channel = createPushChannel<HostTheme>({\n pushType:
|
|
1
|
+
{"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_THEME, REQUEST_THEME, THEME } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme, mirrored from the immediately.run host window into the\n * sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n */\nexport type HostTheme = 'light' | 'dark';\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The host's\n// default before it reports is `dark` (sandbox themeState.DEFAULT_THEME).\nconst channel = createPushChannel<HostTheme>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: 'dark',\n parse: (msg) => (msg.theme === 'light' || msg.theme === 'dark' ? msg.theme : undefined),\n});\n\n/**\n * Returns the current host theme. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get();\n\n/**\n * Subscribe to host theme changes. The listener is invoked immediately with the\n * current theme, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange(listener);\n\n/**\n * React hook returning the current host theme, re-rendering when it changes.\n * The recommended way to implement an app's own `useTheme`: follow the host,\n * allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use();\n\n/**\n * Set the host UI theme — the ELEVATED `theme:set` action (§8.5). The host\n * applies it and re-pushes the new value to every `theme:read` iframe, so your\n * own {@link useHostTheme} confirms the change (the loop closes with no special\n * case). Only a grant holding `theme:set` (e.g. the theme-toggle system app) may\n * call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims. Update\n * optimistically and let the re-push confirm.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [{ theme }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'setHostTheme failed') as Error & {\n code?: string;\n };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAkC;AAClC,0BAAgC;AAChC,sBAAqD;AACrD,6BAAwB;AAgBxB,MAAM,cAAU,sCAA6B;AAAA,EAC3C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAS,IAAI,UAAU,WAAW,IAAI,UAAU,SAAS,IAAI,QAAQ;AAC/E,CAAC;AAMM,MAAM,eAAe,MAAiB,QAAQ,IAAI;AAMlD,MAAM,oBAAoB,CAAC,aAChC,QAAQ,SAAS,QAAQ;AAOpB,MAAM,eAAe,MAAiB,QAAQ,IAAI;AAWlD,MAAM,eAAe,OAAO,UAAoC;AACrE,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,8BAAc,GAAG,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC;AAI9E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,qBAAqB;AAG3D,QAAI,QAAQ,OAAO,UAAU,MAAM,IAAI,OAAO,WAAc;AAC5D,UAAM;AAAA,EACR;AACF;","names":[]}
|
package/dist/theme.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
2
|
import { createPushChannel } from "./pushChannel";
|
|
3
3
|
import { protocolRequest } from "./sandboxUtils";
|
|
4
|
+
import { PROTOCOL_THEME, REQUEST_THEME, THEME } from "./generated/protocol";
|
|
5
|
+
import { SCHEMES } from "./protocolSchemes";
|
|
4
6
|
const channel = createPushChannel({
|
|
5
|
-
pushType:
|
|
6
|
-
requestType:
|
|
7
|
+
pushType: THEME,
|
|
8
|
+
requestType: REQUEST_THEME,
|
|
7
9
|
initial: "dark",
|
|
8
10
|
parse: (msg) => msg.theme === "light" || msg.theme === "dark" ? msg.theme : void 0
|
|
9
11
|
});
|
|
@@ -11,7 +13,7 @@ const getHostTheme = () => channel.get();
|
|
|
11
13
|
const onHostThemeChange = (listener) => channel.onChange(listener);
|
|
12
14
|
const useHostTheme = () => channel.use();
|
|
13
15
|
const setHostTheme = async (theme) => {
|
|
14
|
-
const res = await protocolRequest(
|
|
16
|
+
const res = await protocolRequest(SCHEMES[PROTOCOL_THEME], "set", [{ theme }]);
|
|
15
17
|
if (!res || res.ok !== true) {
|
|
16
18
|
const err = new Error(res?.message ?? "setHostTheme failed");
|
|
17
19
|
err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
|
package/dist/theme.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\n\n/**\n * The host UI theme, mirrored from the immediately.run host window into the\n * sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n */\nexport type HostTheme = 'light' | 'dark';\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The host's\n// default before it reports is `dark` (sandbox themeState.DEFAULT_THEME).\nconst channel = createPushChannel<HostTheme>({\n pushType:
|
|
1
|
+
{"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_THEME, REQUEST_THEME, THEME } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme, mirrored from the immediately.run host window into the\n * sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n */\nexport type HostTheme = 'light' | 'dark';\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The host's\n// default before it reports is `dark` (sandbox themeState.DEFAULT_THEME).\nconst channel = createPushChannel<HostTheme>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: 'dark',\n parse: (msg) => (msg.theme === 'light' || msg.theme === 'dark' ? msg.theme : undefined),\n});\n\n/**\n * Returns the current host theme. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get();\n\n/**\n * Subscribe to host theme changes. The listener is invoked immediately with the\n * current theme, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange(listener);\n\n/**\n * React hook returning the current host theme, re-rendering when it changes.\n * The recommended way to implement an app's own `useTheme`: follow the host,\n * allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use();\n\n/**\n * Set the host UI theme — the ELEVATED `theme:set` action (§8.5). The host\n * applies it and re-pushes the new value to every `theme:read` iframe, so your\n * own {@link useHostTheme} confirms the change (the loop closes with no special\n * case). Only a grant holding `theme:set` (e.g. the theme-toggle system app) may\n * call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims. Update\n * optimistically and let the re-push confirm.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [{ theme }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'setHostTheme failed') as Error & {\n code?: string;\n };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n};\n"],"mappings":";AAAA,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,gBAAgB,eAAe,aAAa;AACrD,SAAS,eAAe;AAgBxB,MAAM,UAAU,kBAA6B;AAAA,EAC3C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAS,IAAI,UAAU,WAAW,IAAI,UAAU,SAAS,IAAI,QAAQ;AAC/E,CAAC;AAMM,MAAM,eAAe,MAAiB,QAAQ,IAAI;AAMlD,MAAM,oBAAoB,CAAC,aAChC,QAAQ,SAAS,QAAQ;AAOpB,MAAM,eAAe,MAAiB,QAAQ,IAAI;AAWlD,MAAM,eAAe,OAAO,UAAoC;AACrE,QAAM,MAAO,MAAM,gBAAgB,QAAQ,cAAc,GAAG,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC;AAI9E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,qBAAqB;AAG3D,QAAI,QAAQ,OAAO,UAAU,MAAM,IAAI,OAAO,WAAc;AAC5D,UAAM;AAAA,EACR;AACF;","names":[]}
|
package/dist/urlUtils.cjs
CHANGED
|
@@ -18,7 +18,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
var urlUtils_exports = {};
|
|
20
20
|
__export(urlUtils_exports, {
|
|
21
|
-
APP_ROOT: () => APP_ROOT,
|
|
21
|
+
APP_ROOT: () => import_platform_constants.APP_ROOT,
|
|
22
22
|
FILES_PREFIX: () => FILES_PREFIX,
|
|
23
23
|
constructOuterUrl: () => constructOuterUrl,
|
|
24
24
|
constructUrl: () => constructUrl,
|
|
@@ -32,13 +32,12 @@ __export(urlUtils_exports, {
|
|
|
32
32
|
parseTarget: () => parseTarget,
|
|
33
33
|
repositoryPrefixURL: () => repositoryPrefixURL,
|
|
34
34
|
splitHash: () => splitHash,
|
|
35
|
-
underAppRoot: () => underAppRoot
|
|
35
|
+
underAppRoot: () => import_platform_constants.underAppRoot
|
|
36
36
|
});
|
|
37
37
|
module.exports = __toCommonJS(urlUtils_exports);
|
|
38
|
+
var import_platform_constants = require("@immediately-run/platform-constants");
|
|
38
39
|
var import_pathUtils = require("./pathUtils");
|
|
39
40
|
const FILES_PREFIX = "/files";
|
|
40
|
-
const APP_ROOT = "/app";
|
|
41
|
-
const underAppRoot = (repoRelativePath) => (0, import_pathUtils.joinPaths)(APP_ROOT, repoRelativePath);
|
|
42
41
|
const getOuterHostname = (outerHref) => {
|
|
43
42
|
const url = new URL(outerHref);
|
|
44
43
|
return `${url.protocol}//${url.host}`;
|
package/dist/urlUtils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/urlUtils.ts"],"sourcesContent":["import { joinPaths } from \"./pathUtils\";\nimport { NavigationState, PathState } from \"./TinkerableContext\";\n\nexport const FILES_PREFIX = '/files';\n\n/**\n * Mount point of the Git repository inside the sandbox filesystem. The sandbox\n * fs is rooted at `/` (so apps can reach dynamic mounts like `/firestore`), with\n * the repo mounted here. URL subpaths are repo-relative, so the file router\n * resolves them under `APP_ROOT`.\n */\nexport const APP_ROOT = '/app';\n\n/** Resolve a repo-relative path (e.g. a URL subpath) to its absolute sandbox path. */\nexport const underAppRoot = (repoRelativePath: string): string =>\n joinPaths(APP_ROOT, repoRelativePath);\n\n/**\n * The origin every outer URL is rebuilt on — `protocol//host`, **port included**.\n *\n * `url.hostname` drops the port; `url.host` keeps it (and still omits it for the default\n * 80/443, so a production URL is byte-identical either way). Using `hostname` here was\n * invisible on `https://immediately.run` and broke every routed link under local dev on any\n * port but 80: `http://localhost:3100/edit/…` was rebuilt as `http://localhost/edit/…`.\n *\n * Worse than a wrong link, it silently changed link BEHAVIOUR. `repositoryPrefixURL` is\n * built from this, and `isInternalHref` decides by prefix-matching against it — so an\n * absolute in-app URL failed the match, was classified EXTERNAL, and rendered as a plain\n * `<a>`. Clicking it performed a real navigation out of the sandboxed frame instead of\n * routing: the app appeared to \"reload\" on an ordinary internal link.\n */\nexport const getOuterHostname = (outerHref:string) => {\n const url = new URL(outerHref);\n return `${url.protocol}//${url.host}`;\n}\n\nexport const getSearchParams = (search?: string): Record<string, string> => Object.fromEntries(\n [...(new URLSearchParams(search ?? window.location.search).entries())]);\n\n/**\n * Split a link target into its path part and its `#fragment` (the `#` dropped),\n * e.g. `\"FOO.mdx#sec-8-9\"` → `[\"FOO.mdx\", \"sec-8-9\"]`, `\"#sec-3\"` → `[\"\", \"sec-3\"]`,\n * `\"FOO.mdx\"` → `[\"FOO.mdx\", \"\"]`. Only the **first** `#` splits — a fragment never\n * contains another `#`. The seam between wiki-links (§13) and heading ids (§15):\n * existence is resolved on the path part, the fragment is threaded to navigation.\n * MARKDOWN_SYNTAX_SPEC §13.5.\n */\nexport const splitHash = (target: string): [string, string] => {\n const i = target.indexOf('#');\n return i === -1 ? [target, ''] : [target.slice(0, i), target.slice(i + 1)];\n};\n\n\nexport const parseTarget = (target: string, navigation: NavigationState): NavigationState => {\n const newNavigation = { ...navigation };\n let [prehash, hash] = target.split(\"#\")\n if (prehash) {\n let [path, search] = prehash.split(\"?\")\n if (path) {\n newNavigation.sandboxPath = path\n }\n newNavigation.search = search ? search : '';\n }\n newNavigation.hash = hash ? hash : '';\n return newNavigation\n}\n\n\nexport const maybeParseUrl = (str: string): URL | null => {\n try {\n return new URL(str);\n } catch (_) {\n return null;\n }\n}\n\nexport const isAbsolutePath = (sandboxPath: string) => sandboxPath.startsWith('/');\n\n/**\n * The origin+repo prefix every same-app URL starts with — used by {@link isInternalHref} to\n * decide whether an absolute href is \"this app\" or somewhere else.\n *\n * `hash` and `search` are cleared, not just `sandboxPath`. They belong to the CURRENT page,\n * and leaving them in put them on the end of a *prefix*: from a page carrying `#sec-8-9`,\n * the prefix became `…/main/#sec-8-9`, no same-app URL could start with it, every absolute\n * in-app link was classified EXTERNAL, and clicking one navigated the sandboxed frame away\n * instead of routing. A page with a fragment quietly broke its own links.\n */\nexport const repositoryPrefixURL = (outerHref:string, navigationState: NavigationState) => constructUrl(outerHref, {\n ...navigationState,\n sandboxPath: '',\n hash: '',\n search: '',\n });\n\nexport const constructOuterUrl = (previousOuterHref:string, sandboxTarget:string, navigationState: NavigationState, addFilesPrefix=true):string => {\n if (isAbsolutePath(sandboxTarget)) {\n // Split a trailing `#fragment` off before the target is folded into the\n // sandboxPath, and carry it in `hash` instead — a fragment addresses a section,\n // not a file, so it must not leak into the path (MARKDOWN_SYNTAX_SPEC §13.5). An\n // absolute target with no fragment clears any stale hash from the prior state.\n const [pathPart, hash] = splitHash(sandboxTarget);\n return constructUrl(\n previousOuterHref,\n {\n ...navigationState,\n sandboxPath: addFilesPrefix ? joinPaths(FILES_PREFIX, pathPart) : pathPart,\n hash,\n })\n }\n return (\n new URL(\n sandboxTarget,\n constructUrl(\n previousOuterHref,\n navigationState\n )\n )\n ).toString();\n}\n\nexport const isInternalHref = (outerHref:string, target: string, navigationState: NavigationState) => {\n const parsedUrl = maybeParseUrl(target);\n if (parsedUrl) {\n return target.startsWith(repositoryPrefixURL(outerHref, navigationState));\n }\n // if target is not a valid URL, then assume it's relative.\n return true;\n}\n\nexport type PathSegment = {\n name: string,\n pattern: string,\n transform?: (pathSegment: string) => string,\n // When true, the leading slash that delimits this segment is optional, so the\n // whole `/segment` group can be absent. Used for the trailing sandboxPath:\n // an outer href of `/mode/provider/namespace/repository/ref` (no trailing\n // slash, no sub-path) must still parse, otherwise the regex matches nothing\n // and every segment comes back empty.\n optionalLeadingSlash?: boolean\n}\n\nconst PATH_SEGMENTS: PathSegment[] = [\n { name: 'mode', pattern: '\\\\w+' },\n { name: 'provider', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'namespace', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'repository', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'ref', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'sandboxPath', pattern: '.*', transform: s => `/${s}`, optionalLeadingSlash: true }\n];\n\nconst OUTER_HREF_REGEXP = new RegExp(\n '^' +\n PATH_SEGMENTS.map(({ name, pattern, optionalLeadingSlash }) =>\n optionalLeadingSlash\n ? `(?:\\/(?<${name}>${pattern}))?`\n : `\\/(?<${name}>${pattern})`\n ).join('') +\n \"$\"\n);\n\n\nexport const parsePath = (pathname: string): PathState => {\n const matchResults = pathname.match(OUTER_HREF_REGEXP)?.groups ?? {};\n return PATH_SEGMENTS.reduce((acc: Partial<PathState>, { name, transform }: PathSegment) => {\n let value: string | undefined = undefined;\n if (name in matchResults) {\n value = matchResults[name];\n }\n if (!value) {\n // fall back to default value if var not present in\n value = '';\n }\n if (typeof value === 'string') {\n acc[name] = transform ? transform(value) : value;\n }\n return acc;\n }, {}) as PathState;\n}\n\nexport const parseHref = (href: string): NavigationState => {\n const parsedUrl = new URL(href);\n const pathnameState = parsePath(parsedUrl.pathname);\n return {\n ...pathnameState,\n search: parsedUrl.search.substring(1),\n hash: parsedUrl.hash.substring(1),\n } as NavigationState\n}\n\nconst stripSlashPrefix = (s: string): string => s.startsWith('/') ? s.substring(1) : s;\n\nexport const constructUrl = (outerHref:string, navigationState: NavigationState): string => {\n const path = PATH_SEGMENTS.map(({ name }) => {\n let value = navigationState[name];\n return stripSlashPrefix(value ?? '');\n }).join('/');\n const host = getOuterHostname(outerHref);\n let url = `${host}/${path}`\n if (navigationState.search) {\n url += '?' + navigationState.search\n }\n if (navigationState.hash) {\n url += '#' + navigationState.hash\n }\n return url;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA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AAe,SAAS,MAAM,iBAAiB,GAAG,UAAU,CAAC;AACnE,SAAO,cAAc,OAAO,CAAC,KAAyB,EAAE,MAAM,UAAU,MAAmB;AACzF,QAAI,QAA4B;AAChC,QAAI,QAAQ,cAAc;AACxB,cAAQ,aAAa,IAAI;AAAA,IAC3B;AACA,QAAI,CAAC,OAAO;AAEV,cAAQ;AAAA,IACV;AACA,QAAI,OAAO,UAAU,UAAU;AAC7B,UAAI,IAAI,IAAI,YAAY,UAAU,KAAK,IAAI;AAAA,IAC7C;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AACP;AAEO,MAAM,YAAY,CAAC,SAAkC;AAC1D,QAAM,YAAY,IAAI,IAAI,IAAI;AAC9B,QAAM,gBAAgB,UAAU,UAAU,QAAQ;AAClD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ,UAAU,OAAO,UAAU,CAAC;AAAA,IACpC,MAAM,UAAU,KAAK,UAAU,CAAC;AAAA,EAClC;AACF;AAEA,MAAM,mBAAmB,CAAC,MAAsB,EAAE,WAAW,GAAG,IAAI,EAAE,UAAU,CAAC,IAAI;AAE9E,MAAM,eAAe,CAAC,WAAkB,oBAA6C;AAC1F,QAAM,OAAO,cAAc,IAAI,CAAC,EAAE,KAAK,MAAM;AAC3C,QAAI,QAAQ,gBAAgB,IAAI;AAChC,WAAO,iBAAiB,SAAS,EAAE;AAAA,EACrC,CAAC,EAAE,KAAK,GAAG;AACX,QAAM,OAAO,iBAAiB,SAAS;AACvC,MAAI,MAAM,GAAG,IAAI,IAAI,IAAI;AACzB,MAAI,gBAAgB,QAAQ;AAC1B,WAAO,MAAM,gBAAgB;AAAA,EAC/B;AACA,MAAI,gBAAgB,MAAM;AACxB,WAAO,MAAM,gBAAgB;AAAA,EAC/B;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/urlUtils.ts"],"sourcesContent":["import { APP_ROOT, underAppRoot } from \"@immediately-run/platform-constants\";\n\nimport { joinPaths } from \"./pathUtils\";\nimport { NavigationState, PathState } from \"./TinkerableContext\";\n\nexport const FILES_PREFIX = '/files';\n\n/**\n * Mount point of the Git repository inside the sandbox filesystem, and the join\n * into it — both now defined ONCE in `@immediately-run/platform-constants` (R3-275)\n * and re-exported here so every import site is unchanged.\n *\n * They were declared here AND in `sandbox/src/fsLayout.ts`, with two different\n * implementations of the join (this one over `joinPaths`, the sandbox's hand-rolled).\n * The two agreed; nothing made them agree — and the metadata key space is derived\n * from this constant on both sides, so a drift would have split that key space\n * silently. The package's tests replicate BOTH implementations, quirks included.\n *\n * The sandbox fs is rooted at `/` (so apps can reach dynamic mounts like\n * `/firestore`), with the repo mounted at `APP_ROOT`. URL subpaths are\n * repo-relative, so the file router resolves them under it.\n */\nexport { APP_ROOT, underAppRoot };\n\n/**\n * The origin every outer URL is rebuilt on — `protocol//host`, **port included**.\n *\n * `url.hostname` drops the port; `url.host` keeps it (and still omits it for the default\n * 80/443, so a production URL is byte-identical either way). Using `hostname` here was\n * invisible on `https://immediately.run` and broke every routed link under local dev on any\n * port but 80: `http://localhost:3100/edit/…` was rebuilt as `http://localhost/edit/…`.\n *\n * Worse than a wrong link, it silently changed link BEHAVIOUR. `repositoryPrefixURL` is\n * built from this, and `isInternalHref` decides by prefix-matching against it — so an\n * absolute in-app URL failed the match, was classified EXTERNAL, and rendered as a plain\n * `<a>`. Clicking it performed a real navigation out of the sandboxed frame instead of\n * routing: the app appeared to \"reload\" on an ordinary internal link.\n */\nexport const getOuterHostname = (outerHref:string) => {\n const url = new URL(outerHref);\n return `${url.protocol}//${url.host}`;\n}\n\nexport const getSearchParams = (search?: string): Record<string, string> => Object.fromEntries(\n [...(new URLSearchParams(search ?? window.location.search).entries())]);\n\n/**\n * Split a link target into its path part and its `#fragment` (the `#` dropped),\n * e.g. `\"FOO.mdx#sec-8-9\"` → `[\"FOO.mdx\", \"sec-8-9\"]`, `\"#sec-3\"` → `[\"\", \"sec-3\"]`,\n * `\"FOO.mdx\"` → `[\"FOO.mdx\", \"\"]`. Only the **first** `#` splits — a fragment never\n * contains another `#`. The seam between wiki-links (§13) and heading ids (§15):\n * existence is resolved on the path part, the fragment is threaded to navigation.\n * MARKDOWN_SYNTAX_SPEC §13.5.\n */\nexport const splitHash = (target: string): [string, string] => {\n const i = target.indexOf('#');\n return i === -1 ? [target, ''] : [target.slice(0, i), target.slice(i + 1)];\n};\n\n\nexport const parseTarget = (target: string, navigation: NavigationState): NavigationState => {\n const newNavigation = { ...navigation };\n let [prehash, hash] = target.split(\"#\")\n if (prehash) {\n let [path, search] = prehash.split(\"?\")\n if (path) {\n newNavigation.sandboxPath = path\n }\n newNavigation.search = search ? search : '';\n }\n newNavigation.hash = hash ? hash : '';\n return newNavigation\n}\n\n\nexport const maybeParseUrl = (str: string): URL | null => {\n try {\n return new URL(str);\n } catch (_) {\n return null;\n }\n}\n\nexport const isAbsolutePath = (sandboxPath: string) => sandboxPath.startsWith('/');\n\n/**\n * The origin+repo prefix every same-app URL starts with — used by {@link isInternalHref} to\n * decide whether an absolute href is \"this app\" or somewhere else.\n *\n * `hash` and `search` are cleared, not just `sandboxPath`. They belong to the CURRENT page,\n * and leaving them in put them on the end of a *prefix*: from a page carrying `#sec-8-9`,\n * the prefix became `…/main/#sec-8-9`, no same-app URL could start with it, every absolute\n * in-app link was classified EXTERNAL, and clicking one navigated the sandboxed frame away\n * instead of routing. A page with a fragment quietly broke its own links.\n */\nexport const repositoryPrefixURL = (outerHref:string, navigationState: NavigationState) => constructUrl(outerHref, {\n ...navigationState,\n sandboxPath: '',\n hash: '',\n search: '',\n });\n\nexport const constructOuterUrl = (previousOuterHref:string, sandboxTarget:string, navigationState: NavigationState, addFilesPrefix=true):string => {\n if (isAbsolutePath(sandboxTarget)) {\n // Split a trailing `#fragment` off before the target is folded into the\n // sandboxPath, and carry it in `hash` instead — a fragment addresses a section,\n // not a file, so it must not leak into the path (MARKDOWN_SYNTAX_SPEC §13.5). An\n // absolute target with no fragment clears any stale hash from the prior state.\n const [pathPart, hash] = splitHash(sandboxTarget);\n return constructUrl(\n previousOuterHref,\n {\n ...navigationState,\n sandboxPath: addFilesPrefix ? joinPaths(FILES_PREFIX, pathPart) : pathPart,\n hash,\n })\n }\n return (\n new URL(\n sandboxTarget,\n constructUrl(\n previousOuterHref,\n navigationState\n )\n )\n ).toString();\n}\n\nexport const isInternalHref = (outerHref:string, target: string, navigationState: NavigationState) => {\n const parsedUrl = maybeParseUrl(target);\n if (parsedUrl) {\n return target.startsWith(repositoryPrefixURL(outerHref, navigationState));\n }\n // if target is not a valid URL, then assume it's relative.\n return true;\n}\n\nexport type PathSegment = {\n name: string,\n pattern: string,\n transform?: (pathSegment: string) => string,\n // When true, the leading slash that delimits this segment is optional, so the\n // whole `/segment` group can be absent. Used for the trailing sandboxPath:\n // an outer href of `/mode/provider/namespace/repository/ref` (no trailing\n // slash, no sub-path) must still parse, otherwise the regex matches nothing\n // and every segment comes back empty.\n optionalLeadingSlash?: boolean\n}\n\nconst PATH_SEGMENTS: PathSegment[] = [\n { name: 'mode', pattern: '\\\\w+' },\n { name: 'provider', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'namespace', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'repository', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'ref', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'sandboxPath', pattern: '.*', transform: s => `/${s}`, optionalLeadingSlash: true }\n];\n\nconst OUTER_HREF_REGEXP = new RegExp(\n '^' +\n PATH_SEGMENTS.map(({ name, pattern, optionalLeadingSlash }) =>\n optionalLeadingSlash\n ? `(?:\\/(?<${name}>${pattern}))?`\n : `\\/(?<${name}>${pattern})`\n ).join('') +\n \"$\"\n);\n\n\nexport const parsePath = (pathname: string): PathState => {\n const matchResults = pathname.match(OUTER_HREF_REGEXP)?.groups ?? {};\n return PATH_SEGMENTS.reduce((acc: Partial<PathState>, { name, transform }: PathSegment) => {\n let value: string | undefined = undefined;\n if (name in matchResults) {\n value = matchResults[name];\n }\n if (!value) {\n // fall back to default value if var not present in\n value = '';\n }\n if (typeof value === 'string') {\n acc[name] = transform ? transform(value) : value;\n }\n return acc;\n }, {}) as PathState;\n}\n\nexport const parseHref = (href: string): NavigationState => {\n const parsedUrl = new URL(href);\n const pathnameState = parsePath(parsedUrl.pathname);\n return {\n ...pathnameState,\n search: parsedUrl.search.substring(1),\n hash: parsedUrl.hash.substring(1),\n } as NavigationState\n}\n\nconst stripSlashPrefix = (s: string): string => s.startsWith('/') ? s.substring(1) : s;\n\nexport const constructUrl = (outerHref:string, navigationState: NavigationState): string => {\n const path = PATH_SEGMENTS.map(({ name }) => {\n let value = navigationState[name];\n return stripSlashPrefix(value ?? '');\n }).join('/');\n const host = getOuterHostname(outerHref);\n let url = `${host}/${path}`\n if (navigationState.search) {\n url += '?' + navigationState.search\n }\n if (navigationState.hash) {\n url += '#' + navigationState.hash\n }\n return url;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAuC;AAEvC,uBAA0B;AAGnB,MAAM,eAAe;AAiCrB,MAAM,mBAAmB,CAAC,cAAqB;AACpD,QAAM,MAAM,IAAI,IAAI,SAAS;AAC7B,SAAO,GAAG,IAAI,QAAQ,KAAK,IAAI,IAAI;AACrC;AAEO,MAAM,kBAAkB,CAAC,WAA4C,OAAO;AAAA,EACjF,CAAC,GAAI,IAAI,gBAAgB,UAAU,OAAO,SAAS,MAAM,EAAE,QAAQ,CAAE;AAAC;AAUjE,MAAM,YAAY,CAAC,WAAqC;AAC7D,QAAM,IAAI,OAAO,QAAQ,GAAG;AAC5B,SAAO,MAAM,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,OAAO,MAAM,GAAG,CAAC,GAAG,OAAO,MAAM,IAAI,CAAC,CAAC;AAC3E;AAGO,MAAM,cAAc,CAAC,QAA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U,CAAC,IAAI;AAE9E,MAAM,eAAe,CAAC,WAAkB,oBAA6C;AAC1F,QAAM,OAAO,cAAc,IAAI,CAAC,EAAE,KAAK,MAAM;AAC3C,QAAI,QAAQ,gBAAgB,IAAI;AAChC,WAAO,iBAAiB,SAAS,EAAE;AAAA,EACrC,CAAC,EAAE,KAAK,GAAG;AACX,QAAM,OAAO,iBAAiB,SAAS;AACvC,MAAI,MAAM,GAAG,IAAI,IAAI,IAAI;AACzB,MAAI,gBAAgB,QAAQ;AAC1B,WAAO,MAAM,gBAAgB;AAAA,EAC/B;AACA,MAAI,gBAAgB,MAAM;AACxB,WAAO,MAAM,gBAAgB;AAAA,EAC/B;AACA,SAAO;AACT;","names":[]}
|
package/dist/urlUtils.d.cts
CHANGED
|
@@ -1,18 +1,11 @@
|
|
|
1
|
+
export { APP_ROOT, underAppRoot } from '@immediately-run/platform-constants';
|
|
1
2
|
import { NavigationState, PathState } from './TinkerableContext.cjs';
|
|
2
3
|
import 'react';
|
|
3
4
|
import './RoutingSpec.cjs';
|
|
4
5
|
import './sandboxTypes.cjs';
|
|
5
6
|
|
|
6
7
|
declare const FILES_PREFIX = "/files";
|
|
7
|
-
|
|
8
|
-
* Mount point of the Git repository inside the sandbox filesystem. The sandbox
|
|
9
|
-
* fs is rooted at `/` (so apps can reach dynamic mounts like `/firestore`), with
|
|
10
|
-
* the repo mounted here. URL subpaths are repo-relative, so the file router
|
|
11
|
-
* resolves them under `APP_ROOT`.
|
|
12
|
-
*/
|
|
13
|
-
declare const APP_ROOT = "/app";
|
|
14
|
-
/** Resolve a repo-relative path (e.g. a URL subpath) to its absolute sandbox path. */
|
|
15
|
-
declare const underAppRoot: (repoRelativePath: string) => string;
|
|
8
|
+
|
|
16
9
|
/**
|
|
17
10
|
* The origin every outer URL is rebuilt on — `protocol//host`, **port included**.
|
|
18
11
|
*
|
|
@@ -64,4 +57,4 @@ declare const parsePath: (pathname: string) => PathState;
|
|
|
64
57
|
declare const parseHref: (href: string) => NavigationState;
|
|
65
58
|
declare const constructUrl: (outerHref: string, navigationState: NavigationState) => string;
|
|
66
59
|
|
|
67
|
-
export {
|
|
60
|
+
export { FILES_PREFIX, type PathSegment, constructOuterUrl, constructUrl, getOuterHostname, getSearchParams, isAbsolutePath, isInternalHref, maybeParseUrl, parseHref, parsePath, parseTarget, repositoryPrefixURL, splitHash };
|
package/dist/urlUtils.d.ts
CHANGED
|
@@ -1,18 +1,11 @@
|
|
|
1
|
+
export { APP_ROOT, underAppRoot } from '@immediately-run/platform-constants';
|
|
1
2
|
import { NavigationState, PathState } from './TinkerableContext.js';
|
|
2
3
|
import 'react';
|
|
3
4
|
import './RoutingSpec.js';
|
|
4
5
|
import './sandboxTypes.js';
|
|
5
6
|
|
|
6
7
|
declare const FILES_PREFIX = "/files";
|
|
7
|
-
|
|
8
|
-
* Mount point of the Git repository inside the sandbox filesystem. The sandbox
|
|
9
|
-
* fs is rooted at `/` (so apps can reach dynamic mounts like `/firestore`), with
|
|
10
|
-
* the repo mounted here. URL subpaths are repo-relative, so the file router
|
|
11
|
-
* resolves them under `APP_ROOT`.
|
|
12
|
-
*/
|
|
13
|
-
declare const APP_ROOT = "/app";
|
|
14
|
-
/** Resolve a repo-relative path (e.g. a URL subpath) to its absolute sandbox path. */
|
|
15
|
-
declare const underAppRoot: (repoRelativePath: string) => string;
|
|
8
|
+
|
|
16
9
|
/**
|
|
17
10
|
* The origin every outer URL is rebuilt on — `protocol//host`, **port included**.
|
|
18
11
|
*
|
|
@@ -64,4 +57,4 @@ declare const parsePath: (pathname: string) => PathState;
|
|
|
64
57
|
declare const parseHref: (href: string) => NavigationState;
|
|
65
58
|
declare const constructUrl: (outerHref: string, navigationState: NavigationState) => string;
|
|
66
59
|
|
|
67
|
-
export {
|
|
60
|
+
export { FILES_PREFIX, type PathSegment, constructOuterUrl, constructUrl, getOuterHostname, getSearchParams, isAbsolutePath, isInternalHref, maybeParseUrl, parseHref, parsePath, parseTarget, repositoryPrefixURL, splitHash };
|
package/dist/urlUtils.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
|
+
import { APP_ROOT, underAppRoot } from "@immediately-run/platform-constants";
|
|
2
3
|
import { joinPaths } from "./pathUtils";
|
|
3
4
|
const FILES_PREFIX = "/files";
|
|
4
|
-
const APP_ROOT = "/app";
|
|
5
|
-
const underAppRoot = (repoRelativePath) => joinPaths(APP_ROOT, repoRelativePath);
|
|
6
5
|
const getOuterHostname = (outerHref) => {
|
|
7
6
|
const url = new URL(outerHref);
|
|
8
7
|
return `${url.protocol}//${url.host}`;
|
package/dist/urlUtils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/urlUtils.ts"],"sourcesContent":["import { joinPaths } from \"./pathUtils\";\nimport { NavigationState, PathState } from \"./TinkerableContext\";\n\nexport const FILES_PREFIX = '/files';\n\n/**\n * Mount point of the Git repository inside the sandbox filesystem. The sandbox\n * fs is rooted at `/` (so apps can reach dynamic mounts like `/firestore`), with\n * the repo mounted here. URL subpaths are repo-relative, so the file router\n * resolves them under `APP_ROOT`.\n */\nexport const APP_ROOT = '/app';\n\n/** Resolve a repo-relative path (e.g. a URL subpath) to its absolute sandbox path. */\nexport const underAppRoot = (repoRelativePath: string): string =>\n joinPaths(APP_ROOT, repoRelativePath);\n\n/**\n * The origin every outer URL is rebuilt on — `protocol//host`, **port included**.\n *\n * `url.hostname` drops the port; `url.host` keeps it (and still omits it for the default\n * 80/443, so a production URL is byte-identical either way). Using `hostname` here was\n * invisible on `https://immediately.run` and broke every routed link under local dev on any\n * port but 80: `http://localhost:3100/edit/…` was rebuilt as `http://localhost/edit/…`.\n *\n * Worse than a wrong link, it silently changed link BEHAVIOUR. `repositoryPrefixURL` is\n * built from this, and `isInternalHref` decides by prefix-matching against it — so an\n * absolute in-app URL failed the match, was classified EXTERNAL, and rendered as a plain\n * `<a>`. Clicking it performed a real navigation out of the sandboxed frame instead of\n * routing: the app appeared to \"reload\" on an ordinary internal link.\n */\nexport const getOuterHostname = (outerHref:string) => {\n const url = new URL(outerHref);\n return `${url.protocol}//${url.host}`;\n}\n\nexport const getSearchParams = (search?: string): Record<string, string> => Object.fromEntries(\n [...(new URLSearchParams(search ?? window.location.search).entries())]);\n\n/**\n * Split a link target into its path part and its `#fragment` (the `#` dropped),\n * e.g. `\"FOO.mdx#sec-8-9\"` → `[\"FOO.mdx\", \"sec-8-9\"]`, `\"#sec-3\"` → `[\"\", \"sec-3\"]`,\n * `\"FOO.mdx\"` → `[\"FOO.mdx\", \"\"]`. Only the **first** `#` splits — a fragment never\n * contains another `#`. The seam between wiki-links (§13) and heading ids (§15):\n * existence is resolved on the path part, the fragment is threaded to navigation.\n * MARKDOWN_SYNTAX_SPEC §13.5.\n */\nexport const splitHash = (target: string): [string, string] => {\n const i = target.indexOf('#');\n return i === -1 ? [target, ''] : [target.slice(0, i), target.slice(i + 1)];\n};\n\n\nexport const parseTarget = (target: string, navigation: NavigationState): NavigationState => {\n const newNavigation = { ...navigation };\n let [prehash, hash] = target.split(\"#\")\n if (prehash) {\n let [path, search] = prehash.split(\"?\")\n if (path) {\n newNavigation.sandboxPath = path\n }\n newNavigation.search = search ? search : '';\n }\n newNavigation.hash = hash ? hash : '';\n return newNavigation\n}\n\n\nexport const maybeParseUrl = (str: string): URL | null => {\n try {\n return new URL(str);\n } catch (_) {\n return null;\n }\n}\n\nexport const isAbsolutePath = (sandboxPath: string) => sandboxPath.startsWith('/');\n\n/**\n * The origin+repo prefix every same-app URL starts with — used by {@link isInternalHref} to\n * decide whether an absolute href is \"this app\" or somewhere else.\n *\n * `hash` and `search` are cleared, not just `sandboxPath`. They belong to the CURRENT page,\n * and leaving them in put them on the end of a *prefix*: from a page carrying `#sec-8-9`,\n * the prefix became `…/main/#sec-8-9`, no same-app URL could start with it, every absolute\n * in-app link was classified EXTERNAL, and clicking one navigated the sandboxed frame away\n * instead of routing. A page with a fragment quietly broke its own links.\n */\nexport const repositoryPrefixURL = (outerHref:string, navigationState: NavigationState) => constructUrl(outerHref, {\n ...navigationState,\n sandboxPath: '',\n hash: '',\n search: '',\n });\n\nexport const constructOuterUrl = (previousOuterHref:string, sandboxTarget:string, navigationState: NavigationState, addFilesPrefix=true):string => {\n if (isAbsolutePath(sandboxTarget)) {\n // Split a trailing `#fragment` off before the target is folded into the\n // sandboxPath, and carry it in `hash` instead — a fragment addresses a section,\n // not a file, so it must not leak into the path (MARKDOWN_SYNTAX_SPEC §13.5). An\n // absolute target with no fragment clears any stale hash from the prior state.\n const [pathPart, hash] = splitHash(sandboxTarget);\n return constructUrl(\n previousOuterHref,\n {\n ...navigationState,\n sandboxPath: addFilesPrefix ? joinPaths(FILES_PREFIX, pathPart) : pathPart,\n hash,\n })\n }\n return (\n new URL(\n sandboxTarget,\n constructUrl(\n previousOuterHref,\n navigationState\n )\n )\n ).toString();\n}\n\nexport const isInternalHref = (outerHref:string, target: string, navigationState: NavigationState) => {\n const parsedUrl = maybeParseUrl(target);\n if (parsedUrl) {\n return target.startsWith(repositoryPrefixURL(outerHref, navigationState));\n }\n // if target is not a valid URL, then assume it's relative.\n return true;\n}\n\nexport type PathSegment = {\n name: string,\n pattern: string,\n transform?: (pathSegment: string) => string,\n // When true, the leading slash that delimits this segment is optional, so the\n // whole `/segment` group can be absent. Used for the trailing sandboxPath:\n // an outer href of `/mode/provider/namespace/repository/ref` (no trailing\n // slash, no sub-path) must still parse, otherwise the regex matches nothing\n // and every segment comes back empty.\n optionalLeadingSlash?: boolean\n}\n\nconst PATH_SEGMENTS: PathSegment[] = [\n { name: 'mode', pattern: '\\\\w+' },\n { name: 'provider', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'namespace', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'repository', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'ref', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'sandboxPath', pattern: '.*', transform: s => `/${s}`, optionalLeadingSlash: true }\n];\n\nconst OUTER_HREF_REGEXP = new RegExp(\n '^' +\n PATH_SEGMENTS.map(({ name, pattern, optionalLeadingSlash }) =>\n optionalLeadingSlash\n ? `(?:\\/(?<${name}>${pattern}))?`\n : `\\/(?<${name}>${pattern})`\n ).join('') +\n \"$\"\n);\n\n\nexport const parsePath = (pathname: string): PathState => {\n const matchResults = pathname.match(OUTER_HREF_REGEXP)?.groups ?? {};\n return PATH_SEGMENTS.reduce((acc: Partial<PathState>, { name, transform }: PathSegment) => {\n let value: string | undefined = undefined;\n if (name in matchResults) {\n value = matchResults[name];\n }\n if (!value) {\n // fall back to default value if var not present in\n value = '';\n }\n if (typeof value === 'string') {\n acc[name] = transform ? transform(value) : value;\n }\n return acc;\n }, {}) as PathState;\n}\n\nexport const parseHref = (href: string): NavigationState => {\n const parsedUrl = new URL(href);\n const pathnameState = parsePath(parsedUrl.pathname);\n return {\n ...pathnameState,\n search: parsedUrl.search.substring(1),\n hash: parsedUrl.hash.substring(1),\n } as NavigationState\n}\n\nconst stripSlashPrefix = (s: string): string => s.startsWith('/') ? s.substring(1) : s;\n\nexport const constructUrl = (outerHref:string, navigationState: NavigationState): string => {\n const path = PATH_SEGMENTS.map(({ name }) => {\n let value = navigationState[name];\n return stripSlashPrefix(value ?? '');\n }).join('/');\n const host = getOuterHostname(outerHref);\n let url = `${host}/${path}`\n if (navigationState.search) {\n url += '?' + navigationState.search\n }\n if (navigationState.hash) {\n url += '#' + navigationState.hash\n }\n return url;\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAGnB,MAAM,eAAe;AAQrB,MAAM,WAAW;AAGjB,MAAM,eAAe,CAAC,qBAC3B,UAAU,UAAU,gBAAgB;AAgB/B,MAAM,mBAAmB,CAAC,cAAqB;AACpD,QAAM,MAAM,IAAI,IAAI,SAAS;AAC7B,SAAO,GAAG,IAAI,QAAQ,KAAK,IAAI,IAAI;AACrC;AAEO,MAAM,kBAAkB,CAAC,WAA4C,OAAO;AAAA,EACjF,CAAC,GAAI,IAAI,gBAA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AC1D,QAAM,YAAY,IAAI,IAAI,IAAI;AAC9B,QAAM,gBAAgB,UAAU,UAAU,QAAQ;AAClD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ,UAAU,OAAO,UAAU,CAAC;AAAA,IACpC,MAAM,UAAU,KAAK,UAAU,CAAC;AAAA,EAClC;AACF;AAEA,MAAM,mBAAmB,CAAC,MAAsB,EAAE,WAAW,GAAG,IAAI,EAAE,UAAU,CAAC,IAAI;AAE9E,MAAM,eAAe,CAAC,WAAkB,oBAA6C;AAC1F,QAAM,OAAO,cAAc,IAAI,CAAC,EAAE,KAAK,MAAM;AAC3C,QAAI,QAAQ,gBAAgB,IAAI;AAChC,WAAO,iBAAiB,SAAS,EAAE;AAAA,EACrC,CAAC,EAAE,KAAK,GAAG;AACX,QAAM,OAAO,iBAAiB,SAAS;AACvC,MAAI,MAAM,GAAG,IAAI,IAAI,IAAI;AACzB,MAAI,gBAAgB,QAAQ;AAC1B,WAAO,MAAM,gBAAgB;AAAA,EAC/B;AACA,MAAI,gBAAgB,MAAM;AACxB,WAAO,MAAM,gBAAgB;AAAA,EAC/B;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/urlUtils.ts"],"sourcesContent":["import { APP_ROOT, underAppRoot } from \"@immediately-run/platform-constants\";\n\nimport { joinPaths } from \"./pathUtils\";\nimport { NavigationState, PathState } from \"./TinkerableContext\";\n\nexport const FILES_PREFIX = '/files';\n\n/**\n * Mount point of the Git repository inside the sandbox filesystem, and the join\n * into it — both now defined ONCE in `@immediately-run/platform-constants` (R3-275)\n * and re-exported here so every import site is unchanged.\n *\n * They were declared here AND in `sandbox/src/fsLayout.ts`, with two different\n * implementations of the join (this one over `joinPaths`, the sandbox's hand-rolled).\n * The two agreed; nothing made them agree — and the metadata key space is derived\n * from this constant on both sides, so a drift would have split that key space\n * silently. The package's tests replicate BOTH implementations, quirks included.\n *\n * The sandbox fs is rooted at `/` (so apps can reach dynamic mounts like\n * `/firestore`), with the repo mounted at `APP_ROOT`. URL subpaths are\n * repo-relative, so the file router resolves them under it.\n */\nexport { APP_ROOT, underAppRoot };\n\n/**\n * The origin every outer URL is rebuilt on — `protocol//host`, **port included**.\n *\n * `url.hostname` drops the port; `url.host` keeps it (and still omits it for the default\n * 80/443, so a production URL is byte-identical either way). Using `hostname` here was\n * invisible on `https://immediately.run` and broke every routed link under local dev on any\n * port but 80: `http://localhost:3100/edit/…` was rebuilt as `http://localhost/edit/…`.\n *\n * Worse than a wrong link, it silently changed link BEHAVIOUR. `repositoryPrefixURL` is\n * built from this, and `isInternalHref` decides by prefix-matching against it — so an\n * absolute in-app URL failed the match, was classified EXTERNAL, and rendered as a plain\n * `<a>`. Clicking it performed a real navigation out of the sandboxed frame instead of\n * routing: the app appeared to \"reload\" on an ordinary internal link.\n */\nexport const getOuterHostname = (outerHref:string) => {\n const url = new URL(outerHref);\n return `${url.protocol}//${url.host}`;\n}\n\nexport const getSearchParams = (search?: string): Record<string, string> => Object.fromEntries(\n [...(new URLSearchParams(search ?? window.location.search).entries())]);\n\n/**\n * Split a link target into its path part and its `#fragment` (the `#` dropped),\n * e.g. `\"FOO.mdx#sec-8-9\"` → `[\"FOO.mdx\", \"sec-8-9\"]`, `\"#sec-3\"` → `[\"\", \"sec-3\"]`,\n * `\"FOO.mdx\"` → `[\"FOO.mdx\", \"\"]`. Only the **first** `#` splits — a fragment never\n * contains another `#`. The seam between wiki-links (§13) and heading ids (§15):\n * existence is resolved on the path part, the fragment is threaded to navigation.\n * MARKDOWN_SYNTAX_SPEC §13.5.\n */\nexport const splitHash = (target: string): [string, string] => {\n const i = target.indexOf('#');\n return i === -1 ? [target, ''] : [target.slice(0, i), target.slice(i + 1)];\n};\n\n\nexport const parseTarget = (target: string, navigation: NavigationState): NavigationState => {\n const newNavigation = { ...navigation };\n let [prehash, hash] = target.split(\"#\")\n if (prehash) {\n let [path, search] = prehash.split(\"?\")\n if (path) {\n newNavigation.sandboxPath = path\n }\n newNavigation.search = search ? search : '';\n }\n newNavigation.hash = hash ? hash : '';\n return newNavigation\n}\n\n\nexport const maybeParseUrl = (str: string): URL | null => {\n try {\n return new URL(str);\n } catch (_) {\n return null;\n }\n}\n\nexport const isAbsolutePath = (sandboxPath: string) => sandboxPath.startsWith('/');\n\n/**\n * The origin+repo prefix every same-app URL starts with — used by {@link isInternalHref} to\n * decide whether an absolute href is \"this app\" or somewhere else.\n *\n * `hash` and `search` are cleared, not just `sandboxPath`. They belong to the CURRENT page,\n * and leaving them in put them on the end of a *prefix*: from a page carrying `#sec-8-9`,\n * the prefix became `…/main/#sec-8-9`, no same-app URL could start with it, every absolute\n * in-app link was classified EXTERNAL, and clicking one navigated the sandboxed frame away\n * instead of routing. A page with a fragment quietly broke its own links.\n */\nexport const repositoryPrefixURL = (outerHref:string, navigationState: NavigationState) => constructUrl(outerHref, {\n ...navigationState,\n sandboxPath: '',\n hash: '',\n search: '',\n });\n\nexport const constructOuterUrl = (previousOuterHref:string, sandboxTarget:string, navigationState: NavigationState, addFilesPrefix=true):string => {\n if (isAbsolutePath(sandboxTarget)) {\n // Split a trailing `#fragment` off before the target is folded into the\n // sandboxPath, and carry it in `hash` instead — a fragment addresses a section,\n // not a file, so it must not leak into the path (MARKDOWN_SYNTAX_SPEC §13.5). An\n // absolute target with no fragment clears any stale hash from the prior state.\n const [pathPart, hash] = splitHash(sandboxTarget);\n return constructUrl(\n previousOuterHref,\n {\n ...navigationState,\n sandboxPath: addFilesPrefix ? joinPaths(FILES_PREFIX, pathPart) : pathPart,\n hash,\n })\n }\n return (\n new URL(\n sandboxTarget,\n constructUrl(\n previousOuterHref,\n navigationState\n )\n )\n ).toString();\n}\n\nexport const isInternalHref = (outerHref:string, target: string, navigationState: NavigationState) => {\n const parsedUrl = maybeParseUrl(target);\n if (parsedUrl) {\n return target.startsWith(repositoryPrefixURL(outerHref, navigationState));\n }\n // if target is not a valid URL, then assume it's relative.\n return true;\n}\n\nexport type PathSegment = {\n name: string,\n pattern: string,\n transform?: (pathSegment: string) => string,\n // When true, the leading slash that delimits this segment is optional, so the\n // whole `/segment` group can be absent. Used for the trailing sandboxPath:\n // an outer href of `/mode/provider/namespace/repository/ref` (no trailing\n // slash, no sub-path) must still parse, otherwise the regex matches nothing\n // and every segment comes back empty.\n optionalLeadingSlash?: boolean\n}\n\nconst PATH_SEGMENTS: PathSegment[] = [\n { name: 'mode', pattern: '\\\\w+' },\n { name: 'provider', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'namespace', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'repository', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'ref', pattern: '[a-zA-Z0-9-_]+' },\n { name: 'sandboxPath', pattern: '.*', transform: s => `/${s}`, optionalLeadingSlash: true }\n];\n\nconst OUTER_HREF_REGEXP = new RegExp(\n '^' +\n PATH_SEGMENTS.map(({ name, pattern, optionalLeadingSlash }) =>\n optionalLeadingSlash\n ? `(?:\\/(?<${name}>${pattern}))?`\n : `\\/(?<${name}>${pattern})`\n ).join('') +\n \"$\"\n);\n\n\nexport const parsePath = (pathname: string): PathState => {\n const matchResults = pathname.match(OUTER_HREF_REGEXP)?.groups ?? {};\n return PATH_SEGMENTS.reduce((acc: Partial<PathState>, { name, transform }: PathSegment) => {\n let value: string | undefined = undefined;\n if (name in matchResults) {\n value = matchResults[name];\n }\n if (!value) {\n // fall back to default value if var not present in\n value = '';\n }\n if (typeof value === 'string') {\n acc[name] = transform ? transform(value) : value;\n }\n return acc;\n }, {}) as PathState;\n}\n\nexport const parseHref = (href: string): NavigationState => {\n const parsedUrl = new URL(href);\n const pathnameState = parsePath(parsedUrl.pathname);\n return {\n ...pathnameState,\n search: parsedUrl.search.substring(1),\n hash: parsedUrl.hash.substring(1),\n } as NavigationState\n}\n\nconst stripSlashPrefix = (s: string): string => s.startsWith('/') ? s.substring(1) : s;\n\nexport const constructUrl = (outerHref:string, navigationState: NavigationState): string => {\n const path = PATH_SEGMENTS.map(({ name }) => {\n let value = navigationState[name];\n return stripSlashPrefix(value ?? '');\n }).join('/');\n const host = getOuterHostname(outerHref);\n let url = `${host}/${path}`\n if (navigationState.search) {\n url += '?' + navigationState.search\n }\n if (navigationState.hash) {\n url += '#' + navigationState.hash\n }\n return url;\n}\n"],"mappings":";AAAA,SAAS,UAAU,oBAAoB;AAEvC,SAAS,iBAAiB;AAGnB,MAAM,eAAe;AAiCrB,MAAM,mBAAmB,CAAC,cAAqB;AACpD,QAAM,MAAM,IAAI,IAAI,SAAS;AAC7B,SAAO,GAAG,IAAI,QAAQ,KAAK,IAAI,IAAI;AACrC;AAEO,MAAM,kBAAkB,CAAC,WAA4C,OAAO;AAAA,EACjF,CAAC,GAAI,IAAI,gBAAgB,UAAU,OAAO,SAAS,MAAM,EAAE,QAAQ,CAAE;AAAC;AAUjE,MAAM,YAAY,CAAC,WAAqC;AAC7D,QAAM,IAAI,OAAO,QAAQ,GAAG;AAC5B,SAAO,MAAM,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,OAAO,MAAM,GAAG,CAAC,GAAG,OAAO,MAAM,IAAI,CAAC,CAAC;AAC3E;AAGO,MAAM,cAAc,CAAC,QAAgB,eAAiD;AAC3F,QAAM,gBAAgB,EAAE,GAAG,WAAW;AACtC,MAAI,CAAC,SAAS,IAAI,IAAI,OAAO,MAAM,GAAG;AACtC,MAAI,SAAS;AACX,QAAI,CAAC,MAAM,MAAM,IAAI,QAAQ,MAAM,GAAG;AACtC,QAAI,MAAM;AACR,oBAAc,cAAc;AAAA,IAC9B;AACA,kBAAc,SAAS,SAAS,SAAS;AAAA,EAC3C;AACA,gBAAc,OAAO,OAAO,OAAO;AACnC,SAAO;AACT;AAGO,MAAM,gBAAgB,CAAC,QAA4B;AACxD,MAAI;AACF,WAAO,IAAI,IAAI,GAAG;AAAA,EACpB,SAAS,GAAG;AACV,WAAO;AAAA,EACT;AACF;AAEO,MAAM,iBAAiB,CAAC,gBAAwB,YAAY,WAAW,GAAG;AAY1E,MAAM,sBAAsB,CAAC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.exports = __toCommonJS(vcs_exports);
|
|
29
29
|
var import_pushChannel = require("./pushChannel");
|
|
30
30
|
var import_sandboxUtils = require("./sandboxUtils");
|
|
31
|
+
var import_protocol = require("./generated/protocol");
|
|
32
|
+
var import_protocolSchemes = require("./protocolSchemes");
|
|
31
33
|
const EMPTY = { changes: [], branch: null, prs: [], diffLoading: false };
|
|
32
34
|
const isChangeArray = (v) => Array.isArray(v) && v.every(
|
|
33
35
|
(c) => !!c && typeof c.path === "string" && typeof c.status === "string"
|
|
34
36
|
);
|
|
35
37
|
const channel = (0, import_pushChannel.createPushChannel)({
|
|
36
|
-
pushType:
|
|
37
|
-
requestType:
|
|
38
|
+
pushType: import_protocol.VCS_STATE,
|
|
39
|
+
requestType: import_protocol.REQUEST_VCS_STATE,
|
|
38
40
|
initial: EMPTY,
|
|
39
41
|
parse: (msg) => {
|
|
40
42
|
if (!isChangeArray(msg.changes)) return void 0;
|
|
@@ -52,7 +54,7 @@ const getVcsState = () => channel.get();
|
|
|
52
54
|
const onVcsStateChange = (listener) => channel.onChange(listener);
|
|
53
55
|
const useVcsState = () => channel.use();
|
|
54
56
|
const vcsRequest = async (method, arg = {}) => {
|
|
55
|
-
const res = await (0, import_sandboxUtils.protocolRequest)(
|
|
57
|
+
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_VCS], method, [arg]);
|
|
56
58
|
if (!res || res.ok !== true) {
|
|
57
59
|
const err = new Error(res?.message ?? `vcs ${method} failed`);
|
|
58
60
|
err.code = res?.code ?? "unknown";
|
package/dist/vcs.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vcs.ts"],"sourcesContent":["// The `vcs:read` / `vcs:reset` source-control surface — app-facing wrappers\n// (UI_AS_APPS_SPEC §5.3 Recipe A read channel + §8.4 Recipe B actions;\n// migrate-sidebars-to-apps Phase 05; roadmap R3-52).\n//\n// A first-party contribute panel (the `panel.contribute` app, Phase 06) reads the\n// live source-control state the native `SourceControlPanel` shows — the working-tree\n// diff summary, the branch lineage, and the open-PR list — and can trigger a\n// refresh/reset. The host derives all of it from authenticated GitHub calls +\n// the COW layers; NONE of the underlying `DiffResult` / `FileSystem` / OAuth token\n// ever crosses the boundary (§8.10) — the wire carries only the plain-JSON\n// {@link VcsState} the host projects.\n//\n// Read side: a Recipe-A push channel, the same get/onChange/use trio as\n// `editorContext` / `diagnostics`. Inert until the host wires the channel\n// (site-main `channelBridge`); an app without `vcs:read` simply sees the empty\n// initial. Action side: `protocol-vcs` requests gated host-side — `refreshDiff` /\n// `refreshPRs` by `vcs:read`, `resetWorkingTree` by first-party-only `vcs:reset`.\nimport { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\n\n/** One changed path in the working tree (vs. the loaded ref). `status` mirrors the\n * host `DiffResult` change kinds; `path` is repo-relative. Contents are NOT\n * carried — the native panel showed path + status, and a per-file content diff is\n * a deferred follow-up (plan step 6). */\nexport interface VcsChange {\n path: string;\n status: 'created' | 'modified' | 'deleted';\n}\n\n/** The branch the working tree sits on and the upstream it diverged from\n * (host `BranchInfo`, §15.1). `null` until the user is on a immediately.run-created\n * branch. `upstreamPushable` is `null` while push access is still being probed. */\nexport interface VcsBranch {\n name: string;\n parentRepo: string;\n parentRef: string;\n parentCommitSha: string;\n upstreamPushable: boolean | null;\n}\n\n/** One pull request open from the current branch (host `BranchPR`). */\nexport interface VcsPR {\n number: number;\n url: string;\n title: string;\n state: 'open' | 'closed' | 'merged';\n draft: boolean;\n}\n\n/** The whole source-control snapshot the host projects to a `vcs:read` frame.\n * Plain JSON — never a `DiffResult` / `FileSystem` / `Journal`. */\nexport interface VcsState {\n changes: VcsChange[];\n branch: VcsBranch | null;\n prs: VcsPR[];\n /** True while the host is recomputing the diff — the panel shows a spinner\n * without a separate request (plan gotcha). */\n diffLoading: boolean;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `vcs:read`): an empty, branch-less snapshot. */\nconst EMPTY: VcsState = { changes: [], branch: null, prs: [], diffLoading: false };\n\nconst isChangeArray = (v: unknown): v is VcsChange[] =>\n Array.isArray(v) &&\n v.every(\n (c) =>\n !!c &&\n typeof (c as VcsChange).path === 'string' &&\n typeof (c as VcsChange).status === 'string',\n );\n\nconst channel = createPushChannel<VcsState>({\n pushType:
|
|
1
|
+
{"version":3,"sources":["../src/vcs.ts"],"sourcesContent":["// The `vcs:read` / `vcs:reset` source-control surface — app-facing wrappers\n// (UI_AS_APPS_SPEC §5.3 Recipe A read channel + §8.4 Recipe B actions;\n// migrate-sidebars-to-apps Phase 05; roadmap R3-52).\n//\n// A first-party contribute panel (the `panel.contribute` app, Phase 06) reads the\n// live source-control state the native `SourceControlPanel` shows — the working-tree\n// diff summary, the branch lineage, and the open-PR list — and can trigger a\n// refresh/reset. The host derives all of it from authenticated GitHub calls +\n// the COW layers; NONE of the underlying `DiffResult` / `FileSystem` / OAuth token\n// ever crosses the boundary (§8.10) — the wire carries only the plain-JSON\n// {@link VcsState} the host projects.\n//\n// Read side: a Recipe-A push channel, the same get/onChange/use trio as\n// `editorContext` / `diagnostics`. Inert until the host wires the channel\n// (site-main `channelBridge`); an app without `vcs:read` simply sees the empty\n// initial. Action side: `protocol-vcs` requests gated host-side — `refreshDiff` /\n// `refreshPRs` by `vcs:read`, `resetWorkingTree` by first-party-only `vcs:reset`.\nimport { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_VCS, REQUEST_VCS_STATE, VCS_STATE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** One changed path in the working tree (vs. the loaded ref). `status` mirrors the\n * host `DiffResult` change kinds; `path` is repo-relative. Contents are NOT\n * carried — the native panel showed path + status, and a per-file content diff is\n * a deferred follow-up (plan step 6). */\nexport interface VcsChange {\n path: string;\n status: 'created' | 'modified' | 'deleted';\n}\n\n/** The branch the working tree sits on and the upstream it diverged from\n * (host `BranchInfo`, §15.1). `null` until the user is on a immediately.run-created\n * branch. `upstreamPushable` is `null` while push access is still being probed. */\nexport interface VcsBranch {\n name: string;\n parentRepo: string;\n parentRef: string;\n parentCommitSha: string;\n upstreamPushable: boolean | null;\n}\n\n/** One pull request open from the current branch (host `BranchPR`). */\nexport interface VcsPR {\n number: number;\n url: string;\n title: string;\n state: 'open' | 'closed' | 'merged';\n draft: boolean;\n}\n\n/** The whole source-control snapshot the host projects to a `vcs:read` frame.\n * Plain JSON — never a `DiffResult` / `FileSystem` / `Journal`. */\nexport interface VcsState {\n changes: VcsChange[];\n branch: VcsBranch | null;\n prs: VcsPR[];\n /** True while the host is recomputing the diff — the panel shows a spinner\n * without a separate request (plan gotcha). */\n diffLoading: boolean;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `vcs:read`): an empty, branch-less snapshot. */\nconst EMPTY: VcsState = { changes: [], branch: null, prs: [], diffLoading: false };\n\nconst isChangeArray = (v: unknown): v is VcsChange[] =>\n Array.isArray(v) &&\n v.every(\n (c) =>\n !!c &&\n typeof (c as VcsChange).path === 'string' &&\n typeof (c as VcsChange).status === 'string',\n );\n\nconst channel = createPushChannel<VcsState>({\n pushType: VCS_STATE,\n requestType: REQUEST_VCS_STATE,\n initial: EMPTY,\n parse: (msg) => {\n // Require a well-formed `changes` array; tolerate an absent branch/prs. A\n // malformed push is ignored (returns undefined) so the last good state stands.\n if (!isChangeArray(msg.changes)) return undefined;\n const branch =\n msg.branch && typeof msg.branch === 'object' ? (msg.branch as VcsBranch) : null;\n const prs = Array.isArray(msg.prs) ? (msg.prs as VcsPR[]) : [];\n return {\n changes: msg.changes,\n branch,\n prs,\n diffLoading: msg.diffLoading === true,\n };\n },\n});\n\n/** One-off read of the current source-control state. Returns the empty snapshot\n * until the host answers (or if the app lacks `vcs:read`). Use\n * {@link onVcsStateChange} / {@link useVcsState} to react to live updates. */\nexport const getVcsState = (): VcsState => channel.get();\n\n/** Subscribe to source-control changes. Invoked immediately with the current\n * value, then on every host push (diff refresh, PR poll, branch change). Returns\n * an unsubscribe. */\nexport const onVcsStateChange = (listener: (state: VcsState) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook: the current source-control state, re-rendering on every change. */\nexport const useVcsState = (): VcsState => channel.use();\n\n// ---------------------------------------------------------------------------\n// Actions (Recipe B, §8.4). The app NAMES an intent and the HOST performs it —\n// the COW/journal stays in the kernel (§2/§4). `refreshDiff`/`refreshPRs` only\n// cause a host-side recompute + a fresh push (gated `vcs:read`, no new authority);\n// `resetWorkingTree` DISCARDS the user's unsaved work, gated by the first-party-only\n// `vcs:reset` — a fork can never hold it. The arm-then-confirm UX stays in the app;\n// the authority is gated host-side (§8.9), and the host requires `confirm:true` as\n// belt-and-braces (T22).\n// ---------------------------------------------------------------------------\n\n/** An error from a `vcs` action, carrying a machine-readable `.code`. */\nexport interface VcsActionError extends Error {\n code:\n | 'forbidden' // the frame lacks the required capability (`vcs:read` / `vcs:reset`)\n | 'invalid-params' // reset called without `confirm: true`\n | 'no-target' // there is no host contribute session (not in edit mode)\n | 'unknown';\n}\n\ntype VcsResult =\n | { ok: true; data: unknown }\n | { ok: false; code: string; message: string };\n\nconst vcsRequest = async (method: string, arg: Record<string, unknown> = {}): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_VCS], method, [arg])) as VcsResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `vcs ${method} failed`) as VcsActionError;\n err.code = (res?.code as VcsActionError['code']) ?? 'unknown';\n throw err;\n }\n};\n\n/** Ask the host to recompute the working-tree diff and push a fresh {@link VcsState}.\n * Gated `vcs:read`. Rejects with a {@link VcsActionError} (`.code`). */\nexport const refreshDiff = (): Promise<void> => vcsRequest('refreshDiff');\n\n/** Ask the host to re-poll the open PRs and push a fresh {@link VcsState}. Gated\n * `vcs:read`. Rejects with a {@link VcsActionError} (`.code`). */\nexport const refreshPRs = (): Promise<void> => vcsRequest('refreshPRs');\n\n/** Ask the host to DISCARD the working tree (COW writable wipe + journal clear) —\n * irreversible. First-party-only (`vcs:reset`); a fork/preview is refused at the\n * gate. Requires `confirm: true` (host belt-and-braces). Rejects with a\n * {@link VcsActionError} (`.code`). */\nexport const resetWorkingTree = (): Promise<void> => vcsRequest('reset', { confirm: true });\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,yBAAkC;AAClC,0BAAgC;AAChC,sBAA2D;AAC3D,6BAAwB;AA4CxB,MAAM,QAAkB,EAAE,SAAS,CAAC,GAAG,QAAQ,MAAM,KAAK,CAAC,GAAG,aAAa,MAAM;AAEjF,MAAM,gBAAgB,CAAC,MACrB,MAAM,QAAQ,CAAC,KACf,EAAE;AAAA,EACA,CAAC,MACC,CAAC,CAAC,KACF,OAAQ,EAAgB,SAAS,YACjC,OAAQ,EAAgB,WAAW;AACvC;AAEF,MAAM,cAAU,sCAA4B;AAAA,EAC1C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AAGd,QAAI,CAAC,cAAc,IAAI,OAAO,EAAG,QAAO;AACxC,UAAM,SACJ,IAAI,UAAU,OAAO,IAAI,WAAW,WAAY,IAAI,SAAuB;AAC7E,UAAM,MAAM,MAAM,QAAQ,IAAI,GAAG,IAAK,IAAI,MAAkB,CAAC;AAC7D,WAAO;AAAA,MACL,SAAS,IAAI;AAAA,MACb;AAAA,MACA;AAAA,MACA,aAAa,IAAI,gBAAgB;AAAA,IACnC;AAAA,EACF;AACF,CAAC;AAKM,MAAM,cAAc,MAAgB,QAAQ,IAAI;AAKhD,MAAM,mBAAmB,CAAC,aAC/B,QAAQ,SAAS,QAAQ;AAGpB,MAAM,cAAc,MAAgB,QAAQ,IAAI;AAyBvD,MAAM,aAAa,OAAO,QAAgB,MAA+B,CAAC,MAAqB;AAC7F,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,4BAAY,GAAG,QAAQ,CAAC,GAAG,CAAC;AACvE,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,OAAO,MAAM,SAAS;AAC5D,QAAI,OAAQ,KAAK,QAAmC;AACpD,UAAM;AAAA,EACR;AACF;AAIO,MAAM,cAAc,MAAqB,WAAW,aAAa;AAIjE,MAAM,aAAa,MAAqB,WAAW,YAAY;AAM/D,MAAM,mBAAmB,MAAqB,WAAW,SAAS,EAAE,SAAS,KAAK,CAAC;","names":[]}
|
package/dist/vcs.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
2
|
import { createPushChannel } from "./pushChannel";
|
|
3
3
|
import { protocolRequest } from "./sandboxUtils";
|
|
4
|
+
import { PROTOCOL_VCS, REQUEST_VCS_STATE, VCS_STATE } from "./generated/protocol";
|
|
5
|
+
import { SCHEMES } from "./protocolSchemes";
|
|
4
6
|
const EMPTY = { changes: [], branch: null, prs: [], diffLoading: false };
|
|
5
7
|
const isChangeArray = (v) => Array.isArray(v) && v.every(
|
|
6
8
|
(c) => !!c && typeof c.path === "string" && typeof c.status === "string"
|
|
7
9
|
);
|
|
8
10
|
const channel = createPushChannel({
|
|
9
|
-
pushType:
|
|
10
|
-
requestType:
|
|
11
|
+
pushType: VCS_STATE,
|
|
12
|
+
requestType: REQUEST_VCS_STATE,
|
|
11
13
|
initial: EMPTY,
|
|
12
14
|
parse: (msg) => {
|
|
13
15
|
if (!isChangeArray(msg.changes)) return void 0;
|
|
@@ -25,7 +27,7 @@ const getVcsState = () => channel.get();
|
|
|
25
27
|
const onVcsStateChange = (listener) => channel.onChange(listener);
|
|
26
28
|
const useVcsState = () => channel.use();
|
|
27
29
|
const vcsRequest = async (method, arg = {}) => {
|
|
28
|
-
const res = await protocolRequest(
|
|
30
|
+
const res = await protocolRequest(SCHEMES[PROTOCOL_VCS], method, [arg]);
|
|
29
31
|
if (!res || res.ok !== true) {
|
|
30
32
|
const err = new Error(res?.message ?? `vcs ${method} failed`);
|
|
31
33
|
err.code = res?.code ?? "unknown";
|
package/dist/vcs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vcs.ts"],"sourcesContent":["// The `vcs:read` / `vcs:reset` source-control surface — app-facing wrappers\n// (UI_AS_APPS_SPEC §5.3 Recipe A read channel + §8.4 Recipe B actions;\n// migrate-sidebars-to-apps Phase 05; roadmap R3-52).\n//\n// A first-party contribute panel (the `panel.contribute` app, Phase 06) reads the\n// live source-control state the native `SourceControlPanel` shows — the working-tree\n// diff summary, the branch lineage, and the open-PR list — and can trigger a\n// refresh/reset. The host derives all of it from authenticated GitHub calls +\n// the COW layers; NONE of the underlying `DiffResult` / `FileSystem` / OAuth token\n// ever crosses the boundary (§8.10) — the wire carries only the plain-JSON\n// {@link VcsState} the host projects.\n//\n// Read side: a Recipe-A push channel, the same get/onChange/use trio as\n// `editorContext` / `diagnostics`. Inert until the host wires the channel\n// (site-main `channelBridge`); an app without `vcs:read` simply sees the empty\n// initial. Action side: `protocol-vcs` requests gated host-side — `refreshDiff` /\n// `refreshPRs` by `vcs:read`, `resetWorkingTree` by first-party-only `vcs:reset`.\nimport { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\n\n/** One changed path in the working tree (vs. the loaded ref). `status` mirrors the\n * host `DiffResult` change kinds; `path` is repo-relative. Contents are NOT\n * carried — the native panel showed path + status, and a per-file content diff is\n * a deferred follow-up (plan step 6). */\nexport interface VcsChange {\n path: string;\n status: 'created' | 'modified' | 'deleted';\n}\n\n/** The branch the working tree sits on and the upstream it diverged from\n * (host `BranchInfo`, §15.1). `null` until the user is on a immediately.run-created\n * branch. `upstreamPushable` is `null` while push access is still being probed. */\nexport interface VcsBranch {\n name: string;\n parentRepo: string;\n parentRef: string;\n parentCommitSha: string;\n upstreamPushable: boolean | null;\n}\n\n/** One pull request open from the current branch (host `BranchPR`). */\nexport interface VcsPR {\n number: number;\n url: string;\n title: string;\n state: 'open' | 'closed' | 'merged';\n draft: boolean;\n}\n\n/** The whole source-control snapshot the host projects to a `vcs:read` frame.\n * Plain JSON — never a `DiffResult` / `FileSystem` / `Journal`. */\nexport interface VcsState {\n changes: VcsChange[];\n branch: VcsBranch | null;\n prs: VcsPR[];\n /** True while the host is recomputing the diff — the panel shows a spinner\n * without a separate request (plan gotcha). */\n diffLoading: boolean;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `vcs:read`): an empty, branch-less snapshot. */\nconst EMPTY: VcsState = { changes: [], branch: null, prs: [], diffLoading: false };\n\nconst isChangeArray = (v: unknown): v is VcsChange[] =>\n Array.isArray(v) &&\n v.every(\n (c) =>\n !!c &&\n typeof (c as VcsChange).path === 'string' &&\n typeof (c as VcsChange).status === 'string',\n );\n\nconst channel = createPushChannel<VcsState>({\n pushType:
|
|
1
|
+
{"version":3,"sources":["../src/vcs.ts"],"sourcesContent":["// The `vcs:read` / `vcs:reset` source-control surface — app-facing wrappers\n// (UI_AS_APPS_SPEC §5.3 Recipe A read channel + §8.4 Recipe B actions;\n// migrate-sidebars-to-apps Phase 05; roadmap R3-52).\n//\n// A first-party contribute panel (the `panel.contribute` app, Phase 06) reads the\n// live source-control state the native `SourceControlPanel` shows — the working-tree\n// diff summary, the branch lineage, and the open-PR list — and can trigger a\n// refresh/reset. The host derives all of it from authenticated GitHub calls +\n// the COW layers; NONE of the underlying `DiffResult` / `FileSystem` / OAuth token\n// ever crosses the boundary (§8.10) — the wire carries only the plain-JSON\n// {@link VcsState} the host projects.\n//\n// Read side: a Recipe-A push channel, the same get/onChange/use trio as\n// `editorContext` / `diagnostics`. Inert until the host wires the channel\n// (site-main `channelBridge`); an app without `vcs:read` simply sees the empty\n// initial. Action side: `protocol-vcs` requests gated host-side — `refreshDiff` /\n// `refreshPRs` by `vcs:read`, `resetWorkingTree` by first-party-only `vcs:reset`.\nimport { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_VCS, REQUEST_VCS_STATE, VCS_STATE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** One changed path in the working tree (vs. the loaded ref). `status` mirrors the\n * host `DiffResult` change kinds; `path` is repo-relative. Contents are NOT\n * carried — the native panel showed path + status, and a per-file content diff is\n * a deferred follow-up (plan step 6). */\nexport interface VcsChange {\n path: string;\n status: 'created' | 'modified' | 'deleted';\n}\n\n/** The branch the working tree sits on and the upstream it diverged from\n * (host `BranchInfo`, §15.1). `null` until the user is on a immediately.run-created\n * branch. `upstreamPushable` is `null` while push access is still being probed. */\nexport interface VcsBranch {\n name: string;\n parentRepo: string;\n parentRef: string;\n parentCommitSha: string;\n upstreamPushable: boolean | null;\n}\n\n/** One pull request open from the current branch (host `BranchPR`). */\nexport interface VcsPR {\n number: number;\n url: string;\n title: string;\n state: 'open' | 'closed' | 'merged';\n draft: boolean;\n}\n\n/** The whole source-control snapshot the host projects to a `vcs:read` frame.\n * Plain JSON — never a `DiffResult` / `FileSystem` / `Journal`. */\nexport interface VcsState {\n changes: VcsChange[];\n branch: VcsBranch | null;\n prs: VcsPR[];\n /** True while the host is recomputing the diff — the panel shows a spinner\n * without a separate request (plan gotcha). */\n diffLoading: boolean;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `vcs:read`): an empty, branch-less snapshot. */\nconst EMPTY: VcsState = { changes: [], branch: null, prs: [], diffLoading: false };\n\nconst isChangeArray = (v: unknown): v is VcsChange[] =>\n Array.isArray(v) &&\n v.every(\n (c) =>\n !!c &&\n typeof (c as VcsChange).path === 'string' &&\n typeof (c as VcsChange).status === 'string',\n );\n\nconst channel = createPushChannel<VcsState>({\n pushType: VCS_STATE,\n requestType: REQUEST_VCS_STATE,\n initial: EMPTY,\n parse: (msg) => {\n // Require a well-formed `changes` array; tolerate an absent branch/prs. A\n // malformed push is ignored (returns undefined) so the last good state stands.\n if (!isChangeArray(msg.changes)) return undefined;\n const branch =\n msg.branch && typeof msg.branch === 'object' ? (msg.branch as VcsBranch) : null;\n const prs = Array.isArray(msg.prs) ? (msg.prs as VcsPR[]) : [];\n return {\n changes: msg.changes,\n branch,\n prs,\n diffLoading: msg.diffLoading === true,\n };\n },\n});\n\n/** One-off read of the current source-control state. Returns the empty snapshot\n * until the host answers (or if the app lacks `vcs:read`). Use\n * {@link onVcsStateChange} / {@link useVcsState} to react to live updates. */\nexport const getVcsState = (): VcsState => channel.get();\n\n/** Subscribe to source-control changes. Invoked immediately with the current\n * value, then on every host push (diff refresh, PR poll, branch change). Returns\n * an unsubscribe. */\nexport const onVcsStateChange = (listener: (state: VcsState) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook: the current source-control state, re-rendering on every change. */\nexport const useVcsState = (): VcsState => channel.use();\n\n// ---------------------------------------------------------------------------\n// Actions (Recipe B, §8.4). The app NAMES an intent and the HOST performs it —\n// the COW/journal stays in the kernel (§2/§4). `refreshDiff`/`refreshPRs` only\n// cause a host-side recompute + a fresh push (gated `vcs:read`, no new authority);\n// `resetWorkingTree` DISCARDS the user's unsaved work, gated by the first-party-only\n// `vcs:reset` — a fork can never hold it. The arm-then-confirm UX stays in the app;\n// the authority is gated host-side (§8.9), and the host requires `confirm:true` as\n// belt-and-braces (T22).\n// ---------------------------------------------------------------------------\n\n/** An error from a `vcs` action, carrying a machine-readable `.code`. */\nexport interface VcsActionError extends Error {\n code:\n | 'forbidden' // the frame lacks the required capability (`vcs:read` / `vcs:reset`)\n | 'invalid-params' // reset called without `confirm: true`\n | 'no-target' // there is no host contribute session (not in edit mode)\n | 'unknown';\n}\n\ntype VcsResult =\n | { ok: true; data: unknown }\n | { ok: false; code: string; message: string };\n\nconst vcsRequest = async (method: string, arg: Record<string, unknown> = {}): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_VCS], method, [arg])) as VcsResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `vcs ${method} failed`) as VcsActionError;\n err.code = (res?.code as VcsActionError['code']) ?? 'unknown';\n throw err;\n }\n};\n\n/** Ask the host to recompute the working-tree diff and push a fresh {@link VcsState}.\n * Gated `vcs:read`. Rejects with a {@link VcsActionError} (`.code`). */\nexport const refreshDiff = (): Promise<void> => vcsRequest('refreshDiff');\n\n/** Ask the host to re-poll the open PRs and push a fresh {@link VcsState}. Gated\n * `vcs:read`. Rejects with a {@link VcsActionError} (`.code`). */\nexport const refreshPRs = (): Promise<void> => vcsRequest('refreshPRs');\n\n/** Ask the host to DISCARD the working tree (COW writable wipe + journal clear) —\n * irreversible. First-party-only (`vcs:reset`); a fork/preview is refused at the\n * gate. Requires `confirm: true` (host belt-and-braces). Rejects with a\n * {@link VcsActionError} (`.code`). */\nexport const resetWorkingTree = (): Promise<void> => vcsRequest('reset', { confirm: true });\n"],"mappings":";AAiBA,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,cAAc,mBAAmB,iBAAiB;AAC3D,SAAS,eAAe;AA4CxB,MAAM,QAAkB,EAAE,SAAS,CAAC,GAAG,QAAQ,MAAM,KAAK,CAAC,GAAG,aAAa,MAAM;AAEjF,MAAM,gBAAgB,CAAC,MACrB,MAAM,QAAQ,CAAC,KACf,EAAE;AAAA,EACA,CAAC,MACC,CAAC,CAAC,KACF,OAAQ,EAAgB,SAAS,YACjC,OAAQ,EAAgB,WAAW;AACvC;AAEF,MAAM,UAAU,kBAA4B;AAAA,EAC1C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AAGd,QAAI,CAAC,cAAc,IAAI,OAAO,EAAG,QAAO;AACxC,UAAM,SACJ,IAAI,UAAU,OAAO,IAAI,WAAW,WAAY,IAAI,SAAuB;AAC7E,UAAM,MAAM,MAAM,QAAQ,IAAI,GAAG,IAAK,IAAI,MAAkB,CAAC;AAC7D,WAAO;AAAA,MACL,SAAS,IAAI;AAAA,MACb;AAAA,MACA;AAAA,MACA,aAAa,IAAI,gBAAgB;AAAA,IACnC;AAAA,EACF;AACF,CAAC;AAKM,MAAM,cAAc,MAAgB,QAAQ,IAAI;AAKhD,MAAM,mBAAmB,CAAC,aAC/B,QAAQ,SAAS,QAAQ;AAGpB,MAAM,cAAc,MAAgB,QAAQ,IAAI;AAyBvD,MAAM,aAAa,OAAO,QAAgB,MAA+B,CAAC,MAAqB;AAC7F,QAAM,MAAO,MAAM,gBAAgB,QAAQ,YAAY,GAAG,QAAQ,CAAC,GAAG,CAAC;AACvE,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,OAAO,MAAM,SAAS;AAC5D,QAAI,OAAQ,KAAK,QAAmC;AACpD,UAAM;AAAA,EACR;AACF;AAIO,MAAM,cAAc,MAAqB,WAAW,aAAa;AAIjE,MAAM,aAAa,MAAqB,WAAW,YAAY;AAM/D,MAAM,mBAAmB,MAAqB,WAAW,SAAS,EAAE,SAAS,KAAK,CAAC;","names":[]}
|
package/dist/version.cjs
CHANGED
|
@@ -21,7 +21,7 @@ __export(version_exports, {
|
|
|
21
21
|
SDK_VERSION: () => SDK_VERSION
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(version_exports);
|
|
24
|
-
const SDK_VERSION = "0.
|
|
24
|
+
const SDK_VERSION = "0.45.0";
|
|
25
25
|
// Annotate the CommonJS export names for ESM import in node:
|
|
26
26
|
0 && (module.exports = {
|
|
27
27
|
SDK_VERSION
|
package/dist/version.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.45.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,MAAM,cAAc;","names":[]}
|
package/dist/version.d.cts
CHANGED
package/dist/version.d.ts
CHANGED
package/dist/version.js
CHANGED
package/dist/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.45.0';\n"],"mappings":";AAIO,MAAM,cAAc;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@immediately-run/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.0",
|
|
4
4
|
"description": "Runtime SDK for code executing inside an immediately.run sandbox.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": "github:immediately-run/immediately-run-sdk",
|
|
@@ -27,22 +27,29 @@
|
|
|
27
27
|
"scripts": {
|
|
28
28
|
"gen:version": "node scripts/gen-version.mjs",
|
|
29
29
|
"prebuild": "node scripts/gen-version.mjs",
|
|
30
|
-
"build": "tsup && node scripts/build-safecontent-deps.mjs",
|
|
30
|
+
"build": "tsup && node scripts/build-safecontent-deps.mjs && node scripts/copy-ambient-types.mjs",
|
|
31
31
|
"test": "jest",
|
|
32
32
|
"check:circular": "node scripts/check-circular.mjs",
|
|
33
33
|
"api:check": "node scripts/check-api-stability.mjs",
|
|
34
|
+
"protocol:check": "node scripts/check-protocol-snapshot.mjs",
|
|
34
35
|
"verify:codegen-parity": "node scripts/codegen-prototype/verify-drift.mjs --self-test && node scripts/codegen-prototype/verify-drift.mjs && node scripts/codegen-prototype/verify.streams.mjs --self-test && node scripts/codegen-prototype/verify.streams.mjs",
|
|
35
36
|
"api:update": "node scripts/check-api-stability.mjs --update",
|
|
36
|
-
"verify": "npm run check:circular && npm run build && npm test && npm run test:safe-content && npm run api:check && npm run verify:codegen-parity",
|
|
37
|
+
"verify": "npm run check:circular && npm run build && npm test && npm run test:safe-content && npm run test:metadata-e2e && npm run api:check && npm run compat:selftest && npm run compat:previous && npm run protocol:check && npm run protocol:selftest && npm run verify:codegen-parity",
|
|
37
38
|
"docs": "typedoc --json docs/api.json && node scripts/gen-llms.mjs",
|
|
38
39
|
"prepublishOnly": "npm run check:circular && npm run build && npm run api:check",
|
|
39
|
-
"test:safe-content": "node scripts/build-safecontent-e2e.mjs && node --test test/safeContent.e2e.mjs"
|
|
40
|
+
"test:safe-content": "node scripts/build-safecontent-e2e.mjs && node --test test/safeContent.e2e.mjs",
|
|
41
|
+
"test:metadata-e2e": "node --test test/metadataHooks.e2e.mjs",
|
|
42
|
+
"protocol:selftest": "node scripts/check-protocol-snapshot.mjs --self-test",
|
|
43
|
+
"compat:previous": "node scripts/check-previous-sdk-compat.mjs",
|
|
44
|
+
"compat:selftest": "node scripts/check-previous-sdk-compat.mjs --self-test"
|
|
40
45
|
},
|
|
41
46
|
"peerDependencies": {
|
|
42
47
|
"react": "^19.0.0",
|
|
43
48
|
"react-dom": "^19.0.0"
|
|
44
49
|
},
|
|
45
50
|
"dependencies": {
|
|
51
|
+
"@immediately-run/platform-constants": "0.2.0",
|
|
52
|
+
"@immediately-run/sandbox-protocol": "0.3.1",
|
|
46
53
|
"react-error-boundary": "^6.0.0"
|
|
47
54
|
},
|
|
48
55
|
"devDependencies": {
|