@w6w/embed 0.2.30 → 0.2.31
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/{CreateFunctionModal-CCYi9deY.js → CreateFunctionModal-glk2zg1r.js} +28 -27
- package/dist/{CreateFunctionModal-CCYi9deY.js.map → CreateFunctionModal-glk2zg1r.js.map} +1 -1
- package/dist/{DocumentFormModal-B3VudaLb.js → DocumentFormModal-Cw85R4wk.js} +2 -2
- package/dist/{DocumentFormModal-B3VudaLb.js.map → DocumentFormModal-Cw85R4wk.js.map} +1 -1
- package/dist/{ImportSpecModal-C-B8Jwxk.js → ImportSpecModal-fU5RsVTa.js} +2 -2
- package/dist/{ImportSpecModal-C-B8Jwxk.js.map → ImportSpecModal-fU5RsVTa.js.map} +1 -1
- package/dist/{WorkflowEditor-8NAcpjO_.js → WorkflowEditor-B-Wc_r4X.js} +5 -5
- package/dist/{WorkflowEditor-8NAcpjO_.js.map → WorkflowEditor-B-Wc_r4X.js.map} +1 -1
- package/dist/callable-record-Bhxim8C1.js +14 -0
- package/dist/callable-record-Bhxim8C1.js.map +1 -0
- package/dist/callables-B49tS2vv.js +297 -0
- package/dist/callables-B49tS2vv.js.map +1 -0
- package/dist/{document-sources-DNmBojx6.js → document-sources-Khcw2zB5.js} +16 -16
- package/dist/document-sources-Khcw2zB5.js.map +1 -0
- package/dist/draft.mjs +1 -1
- package/dist/editor/WorkflowInputsModal.d.ts +12 -0
- package/dist/editor/WorkflowVariablesEditor.d.ts +1 -1
- package/dist/{editor-tools-BIAW-wzt.js → editor-tools-Ch1cAE4F.js} +423 -366
- package/dist/editor-tools-Ch1cAE4F.js.map +1 -0
- package/dist/editor.mjs +1 -1
- package/dist/editors.mjs +81 -80
- package/dist/editors.mjs.map +1 -1
- package/dist/endpoints-zOuwci2U.js +136 -0
- package/dist/endpoints-zOuwci2U.js.map +1 -0
- package/dist/fields-CXHRR5eK.js +28 -0
- package/dist/fields-CXHRR5eK.js.map +1 -0
- package/dist/forms.mjs +1 -1
- package/dist/index.mjs +91 -91
- package/dist/index.mjs.map +1 -1
- package/dist/lib/callable-duplicate.d.ts +26 -0
- package/dist/lib/variable-preview.d.ts +6 -0
- package/dist/lib.mjs +41 -40
- package/dist/lib.mjs.map +1 -1
- package/dist/lists/CallableKindList.d.ts +4 -1
- package/dist/lists/CallableRowParts.d.ts +5 -0
- package/dist/lists/CredentialDetail.d.ts +2 -0
- package/dist/lists/CredentialFields.d.ts +1 -1
- package/dist/lists/EndpointList.d.ts +2 -1
- package/dist/lists/WorkflowList.d.ts +2 -1
- package/dist/lists.mjs +1509 -1421
- package/dist/lists.mjs.map +1 -1
- package/dist/rail.mjs +1 -1
- package/dist/repos/callables.d.ts +23 -0
- package/dist/repos/fields.d.ts +4 -1
- package/dist/repos.mjs +242 -239
- package/dist/settings-rail-BjsTjg2u.js +22 -0
- package/dist/settings-rail-BjsTjg2u.js.map +1 -0
- package/dist/{spec-import-FygyV8sy.js → spec-import-CGPqUUjN.js} +2 -2
- package/dist/{spec-import-FygyV8sy.js.map → spec-import-CGPqUUjN.js.map} +1 -1
- package/dist/{use-callable-draft-DCauHt5o.js → use-callable-draft-DjW7_9qb.js} +8 -7
- package/dist/{use-callable-draft-DCauHt5o.js.map → use-callable-draft-DjW7_9qb.js.map} +1 -1
- package/package.json +3 -3
- package/src/styles.css +165 -10
- package/dist/callables-tOlflvbl.js +0 -151
- package/dist/callables-tOlflvbl.js.map +0 -1
- package/dist/document-sources-DNmBojx6.js.map +0 -1
- package/dist/editor-tools-BIAW-wzt.js.map +0 -1
- package/dist/endpoints-DArAqoLT.js +0 -233
- package/dist/endpoints-DArAqoLT.js.map +0 -1
- package/dist/fields-DvS8XZFc.js +0 -21
- package/dist/fields-DvS8XZFc.js.map +0 -1
- package/dist/settings-rail--GdRMusb.js +0 -33
- package/dist/settings-rail--GdRMusb.js.map +0 -1
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
function u(r) {
|
|
2
|
+
return r ? r.kind === "function" || r.kind === "endpoint" ? !0 : r.kind === "workflow" && typeof r.onPolicyChange == "function" : !1;
|
|
3
|
+
}
|
|
4
|
+
function f(r) {
|
|
5
|
+
const o = {};
|
|
6
|
+
return r.retry && (o.retry = r.retry), r.onError && r.onError !== "fail" && (o.onError = r.onError), r.reroute && (o.reroute = r.reroute), o;
|
|
7
|
+
}
|
|
8
|
+
function E(r, o) {
|
|
9
|
+
const { retry: e, onError: t, reroute: i, ...n } = r;
|
|
10
|
+
return {
|
|
11
|
+
...n,
|
|
12
|
+
...o.retry ? { retry: o.retry } : {},
|
|
13
|
+
...o.onError && o.onError !== "fail" ? { onError: o.onError } : {},
|
|
14
|
+
...o.reroute ? { reroute: o.reroute } : {}
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
export {
|
|
18
|
+
E as d,
|
|
19
|
+
u as i,
|
|
20
|
+
f as p
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=settings-rail-BjsTjg2u.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settings-rail-BjsTjg2u.js","sources":["../src/lib/settings-rail.ts"],"sourcesContent":["/**\n * Pure decisions behind the right rail's Error handling tool\n * (`src/ui/rail/SettingsTool.tsx`, D-10) — the third `railTools` entry,\n * rendering `@w6w/ui`'s `NodeConfigForm` for a Function or an Endpoint and\n * persisting `retry` / `onError` / `reroute` onto that resource's own\n * definition. Split out so `node --test` can gate them directly — mirrors\n * `code-rail.ts`'s own reason for existing: `node --test` throws\n * `ERR_UNKNOWN_FILE_EXTENSION` on any `@w6w/ui`-adjacent import, and\n * `src/ui/workspace.tsx` sits one hop from that barrel through `Layout.tsx`'s\n * import graph. So this module declares its own structural mirror of\n * `WorkspaceCallable` instead of importing it — `import type … from\n * \"@w6w/sdk/console\"` is safe and precedented (`src/lib/workflow-poll.ts:15`,\n * `src/lib/tenant-oauth-patch.ts:69`, both unit-tested today).\n */\nimport type { CallableOnError, ErrorReroute, RetryPolicy } from \"@w6w/sdk/console\";\n\n/** Structural mirror of `WorkspaceCallable` (`src/ui/workspace.tsx`) — only\n * the fields this module reads. `onPolicyChange` is the WORKFLOW arm's\n * injected writer (see {@link isAvailable}); the two callable arms have no\n * such member and never read it. */\nexport type SettingsCallable = {\n kind: string;\n id: string;\n onPolicyChange?: (policy: CallablePolicy) => void;\n} | null;\n\n/** The three fields this tool owns on a Function/Endpoint definition —\n * TC2's pinned shape, shared by both `Fn` and `Endpoint`. */\nexport interface CallablePolicy {\n retry?: RetryPolicy;\n onError?: CallableOnError;\n reroute?: ErrorReroute;\n}\n\n/** A definition carrying (at least) the three fields above, plus whatever\n * else `Fn`/`Endpoint` declares — `definitionWithPolicy` preserves every\n * field this type doesn't name. */\nexport type CallableDefinition = CallablePolicy;\n\n/**\n * Is the Error handling tool meaningful for this context?\n *\n * A Function and an Endpoint: always — the panel owns their whole\n * read-modify-write, because nothing else on the page is editing the same\n * definition at the same time.\n *\n * A Workflow: only when the publishing page injects `onPolicyChange` (core\n * Workflow RFC — *Amendment — 2026-08-21: the run-level error handler*). This\n * is not fussiness. The workflow canvas holds the definition as JSON TEXT it\n * owns, and auto-saves it (`settings.autoSave` defaults to ON), so a rail\n * panel doing its own read-modify-write against the server would be racing the\n * editor: whichever wrote last would silently drop the other's edit, and the\n * loser would most often be the rail, since the canvas re-sends its whole\n * buffer on the next keystroke. Injecting the writer instead means the rail\n * edits the SAME buffer the canvas is about to save. A page that does not own\n * that buffer (the run-detail page) publishes no writer, and the tool simply\n * does not appear there.\n *\n * A Connection has no run-level policy at all. `null` (no resource published)\n * fails closed, house style (mirrors `code-rail.ts`'s `isAvailable`).\n */\nexport function isAvailable(ctx: SettingsCallable): boolean {\n if (!ctx) return false;\n if (ctx.kind === \"function\" || ctx.kind === \"endpoint\") return true;\n return ctx.kind === \"workflow\" && typeof ctx.onPolicyChange === \"function\";\n}\n\n/**\n * Read a definition's `{retry, onError, reroute}` into the shape the panel's\n * local editing state starts from. Normalizes the same way\n * `definitionWithPolicy` writes: a stored `onError: \"fail\"` (never written by\n * this tool, but defensive against a hand-edited or older definition) reads\n * back as absent, matching how `NodeConfigForm` already treats `\"fail\"` as\n * its own default.\n */\nexport function policyFromDefinition(def: CallableDefinition): CallablePolicy {\n const policy: CallablePolicy = {};\n if (def.retry) policy.retry = def.retry;\n if (def.onError && def.onError !== \"fail\") policy.onError = def.onError;\n if (def.reroute) policy.reroute = def.reroute;\n return policy;\n}\n\n/**\n * Read-modify-write: apply `policy`'s `{retry, onError, reroute}` onto `def`,\n * preserving every OTHER field untouched (`impl`/`inputs`/`key` on a\n * Function, `target`/`input`/`key` on an Endpoint, …) — the save this tool\n * issues is never a bare `{retry, onError, reroute}` object. A field whose\n * value is the default is OMITTED entirely, not written as `undefined`:\n * `policy.onError === \"fail\"` (or absent) drops the key, matching\n * `NodeConfigForm`'s own \"fail\" -> absent convention for the field it edits\n * in place. Built by destructuring the three fields OUT of `def` and\n * conditionally re-spreading them, rather than `delete`, so the key is\n * genuinely absent from the returned object, not merely `undefined`-valued —\n * `node:assert/strict`'s deep-equal distinguishes the two (this module's own\n * test pins it).\n */\nexport function definitionWithPolicy<T extends CallableDefinition>(\n def: T,\n policy: CallablePolicy,\n): T {\n const { retry: _retry, onError: _onError, reroute: _reroute, ...rest } = def;\n return {\n ...rest,\n ...(policy.retry ? { retry: policy.retry } : {}),\n ...(policy.onError && policy.onError !== \"fail\" ? { onError: policy.onError } : {}),\n ...(policy.reroute ? { reroute: policy.reroute } : {}),\n } as T;\n}\n"],"names":["isAvailable","ctx","policyFromDefinition","def","policy","definitionWithPolicy","_retry","_onError","_reroute","rest"],"mappings":"AA6DO,SAASA,EAAYC,GAAgC;AAC1D,SAAKA,IACDA,EAAI,SAAS,cAAcA,EAAI,SAAS,aAAmB,KACxDA,EAAI,SAAS,cAAc,OAAOA,EAAI,kBAAmB,aAF/C;AAGnB;AAUO,SAASC,EAAqBC,GAAyC;AAC5E,QAAMC,IAAyB,CAAA;AAC/B,SAAID,EAAI,UAAOC,EAAO,QAAQD,EAAI,QAC9BA,EAAI,WAAWA,EAAI,YAAY,WAAQC,EAAO,UAAUD,EAAI,UAC5DA,EAAI,YAASC,EAAO,UAAUD,EAAI,UAC/BC;AACT;AAgBO,SAASC,EACdF,GACAC,GACG;AACH,QAAM,EAAE,OAAOE,GAAQ,SAASC,GAAU,SAASC,GAAU,GAAGC,EAAA,IAASN;AACzE,SAAO;AAAA,IACL,GAAGM;AAAA,IACH,GAAIL,EAAO,QAAQ,EAAE,OAAOA,EAAO,MAAA,IAAU,CAAA;AAAA,IAC7C,GAAIA,EAAO,WAAWA,EAAO,YAAY,SAAS,EAAE,SAASA,EAAO,QAAA,IAAY,CAAA;AAAA,IAChF,GAAIA,EAAO,UAAU,EAAE,SAASA,EAAO,QAAA,IAAY,CAAA;AAAA,EAAC;AAExD;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useQueryClient as a, useMutation as u, useQuery as d } from "@tanstack/react-query";
|
|
2
2
|
import { path as c } from "@w6w/sdk";
|
|
3
3
|
import { u as i } from "./client-context-CX61Bgw-.js";
|
|
4
|
-
import { i as w, a as y } from "./callables-
|
|
4
|
+
import { i as w, a as y } from "./callables-B49tS2vv.js";
|
|
5
5
|
import { o as m, a2 as b } from "./workflows-Dz8LMjnt.js";
|
|
6
6
|
import { i as q } from "./spec-import-invalidation-D3retX4Q.js";
|
|
7
7
|
const h = (e) => y("endpoint", e), S = (e) => y("function", e), l = {
|
|
@@ -269,4 +269,4 @@ export {
|
|
|
269
269
|
U as u,
|
|
270
270
|
C as v
|
|
271
271
|
};
|
|
272
|
-
//# sourceMappingURL=spec-import-
|
|
272
|
+
//# sourceMappingURL=spec-import-CGPqUUjN.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spec-import-FygyV8sy.js","sources":["../src/repos/versions.ts","../src/repos/documents.ts","../src/repos/spec-import.ts"],"sourcesContent":["/**\n * The `/<collection>/:id/{publish,versions,enable,disable}` repo (T3.1.1) — the Settings rail's\n * read-only version-history browser plus Publish and Enable/Disable. A NEW file, mirroring\n * `src/repos/spec-export.ts` in full: kept out of `repos/functions.ts` / `repos/workflows.ts` /\n * `repos/endpoints.ts` so this node never collides with any of them on the same file, exactly the\n * reason `spec-export.ts`'s own docblock gives for the sibling `/spec` route.\n *\n * **Workflow and Function arms go through the public `@w6w/sdk` methods** (`listVersions`,\n * `getVersion`, `publish`, `revert`, `enable`, `disable`, and `workflows.runVersion`), never\n * `apiClient.console.*`. Each hook dispatches with an explicit per-kind `switch` over LITERAL\n * receivers (`apiClient.workflows.publish(id)`, `apiClient.functions.publish(id)`) and no `default:`\n * — the same reasoning `COLLECTION_PATH` and `useRevertMutation` give against derived dispatch.\n *\n * **Two arms deliberately stay on `W6WClient.request<T>()`:** the ENDPOINT arm of every hook\n * (R-5: endpoint versions have no SDK method — intentionally excluded from the public surface),\n * and the FUNCTION arm of {@link useInvokeVersionMutation} (F-P4: `VersionHistoryModal` renders the\n * raw invocation frame, but `functions.runVersion` unwraps the output like `functions.run`, so the\n * SDK method would drop the frame; follow-up F-6).\n *\n * Every query below is gated on the CALLER'S OWN `enabled` flag, ANDed with `kind !== null` and\n * `id !== \"\"` — never on mount alone (`packages/studio/.ai/PLANNER.md` fact 11): a hook that fires\n * unconditionally against an unresolved `null`/`\"\"` argument 404s once and, because `main.tsx`\n * sets `retry: false` and an unchanged query key never re-fetches, never self-corrects. Opening\n * the Settings panel must issue ZERO `/versions` requests; only opening its History section (or\n * `WorkflowsPage.tsx`'s own editor, a separate call site with its own gate) flips `enabled`.\n *\n * T5.3.1 (project.md Phase 2, Amendments #5/#6): a version can now be reverted to and invoked\n * directly, superseding the earlier \"read-only history, restore out of scope\" pin. `useRevertMutation`\n * overwrites the LIVE resource's `definition` with the archived version's content — never its\n * `key`/address (HITL-4's pinned default) — and does post a `definition` back, by design.\n * `useInvokeVersionMutation` runs that ARCHIVED version's own definition, not the live one, which is\n * exactly why it exists as a separate call from the live invoke/run routes `functions.ts`/\n * `endpoints.ts`/`workflows.ts` already expose.\n */\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { path } from \"@w6w/sdk\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport { callableKey } from \"../lib/callable-kind.ts\";\nimport { historyKeys } from \"../lib/history-query.ts\";\nimport { invalidateSavedCallable } from \"../lib/save-invalidation.ts\";\nimport { workflowKey } from \"./workflows.ts\";\n\n/** The Endpoint / Function single-resource keys the revert arm invalidates: the same\n * `callableKey(\"<kind>\", id)` Studio's `repos/endpoints.ts` / `repos/functions.ts` export as\n * `endpointKey` / `functionKey` (byte-identical `[\"endpoint\", id]` / `[\"function\", id]`). */\nconst endpointKey = (id: string) => callableKey(\"endpoint\", id);\nconst functionKey = (id: string) => callableKey(\"function\", id);\n\n/** The three kinds the wire contract's version-history routes exist for — `connection` has none\n * (see `hasVersionHistory`, `../lib/rail-settings.ts`). */\nexport type VersionsKind = \"function\" | \"workflow\" | \"endpoint\";\n\n/** `<coll>` — the wire contract's own path segment for each kind, every one of the three arms\n * named explicitly (never derived by string pluralization), mirroring `specCollectionForKind`'s\n * own reasoning (`../lib/rail-settings.ts:69`): a typo'd suffix rule would silently send one\n * kind's requests at another kind's collection. */\nconst COLLECTION_PATH: Record<VersionsKind, \"functions\" | \"workflows\" | \"endpoints\"> = {\n function: \"functions\",\n workflow: \"workflows\",\n endpoint: \"endpoints\",\n};\n\n/** One row of `GET /<coll>/:id/versions`'s `versions` array — newest first, per the wire contract. */\nexport interface VersionSummary {\n versionNumber: number;\n createdAt: string;\n createdBy: string | null;\n isCurrentPublished: boolean;\n}\n\n/** `GET /<coll>/:id/versions`'s full 200 body. */\nexport interface VersionsEnvelope {\n enabled: boolean;\n currentPublishedVersion: number | null;\n versions: VersionSummary[];\n}\n\n/** `GET /<coll>/:id/versions/:n`'s `version` field — `definition` is the redacted stored\n * definition for THIS query; {@link useRevertMutation} is what posts a version's definition\n * back onto the live resource, and {@link useInvokeVersionMutation} is what runs it. */\nexport interface VersionDetail {\n versionNumber: number;\n createdAt: string;\n createdBy: string | null;\n isCurrentPublished: boolean;\n definition: Record<string, unknown>;\n}\n\n/** `POST /<coll>/:id/publish`'s 200 body. */\nexport interface PublishResult {\n version: {\n kind: string;\n callableId: string;\n versionNumber: number;\n createdAt: string;\n createdBy: string | null;\n };\n currentPublishedVersion: number;\n}\n\n/** `POST /<coll>/:id/versions/:n/revert`'s 200 body. */\nexport interface RevertResult {\n reverted: {\n kind: string;\n callableId: string;\n versionNumber: number;\n };\n}\n\n/** `<coll>` per kind ends its live invoke/run route in `/invoke` (Function, Endpoint) or `/run`\n * (Workflow, matching that kind's existing unversioned route) — every arm named explicitly\n * (never derived by suffix rule), mirroring `COLLECTION_PATH`'s own reasoning above: a derived\n * rule would silently send one kind's requests at the wrong verb. */\nconst VERSION_INVOKE_VERB: Record<VersionsKind, \"invoke\" | \"run\"> = {\n function: \"invoke\",\n endpoint: \"invoke\",\n workflow: \"run\",\n};\n\nexport function versionsKey(kind: VersionsKind | null, id: string) {\n return [\"versions\", kind, id] as const;\n}\n\nexport function versionKey(kind: VersionsKind | null, id: string, versionNumber: number | null) {\n return [\"version\", kind, id, versionNumber] as const;\n}\n\n/**\n * `GET /<collection>/:id/versions`. Never fires on mount — `enabled` is the caller's own flag\n * (the Settings panel's History-open state, or `WorkflowsPage.tsx`'s own editor-open gate), ANDed\n * with `kind !== null` and `id !== \"\"`, exactly `useSpecQuery`'s shape (`spec-export.ts:45-57`).\n */\nexport function useVersionsQuery(kind: VersionsKind | null, id: string, enabled: boolean) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: versionsKey(kind, id),\n queryFn: async (): Promise<VersionsEnvelope> => {\n switch (kind as VersionsKind) {\n case \"workflow\":\n return await apiClient.workflows.listVersions(id);\n case \"function\":\n return await apiClient.functions.listVersions(id);\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<VersionsEnvelope>({\n method: \"GET\",\n path: path`/${COLLECTION_PATH.endpoint}/${id}/versions`,\n });\n return res.body;\n }\n }\n },\n enabled: enabled && kind !== null && id !== \"\",\n });\n}\n\n/**\n * `GET /<collection>/:id/versions/:n`. Same gating shape as {@link useVersionsQuery}, plus\n * `versionNumber !== null` — the modal opens this only once a row has been clicked.\n */\nexport function useVersionQuery(\n kind: VersionsKind | null,\n id: string,\n versionNumber: number | null,\n enabled: boolean,\n) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: versionKey(kind, id, versionNumber),\n queryFn: async (): Promise<VersionDetail> => {\n // The SDK's `getVersion` already unwraps the `{ version }` envelope.\n const n = versionNumber as number;\n switch (kind as VersionsKind) {\n case \"workflow\":\n return (await apiClient.workflows.getVersion(id, n)) as VersionDetail;\n case \"function\":\n return (await apiClient.functions.getVersion(id, n)) as VersionDetail;\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<{ version: VersionDetail }>({\n method: \"GET\",\n path: path`/${COLLECTION_PATH.endpoint}/${id}/versions/${String(n)}`,\n });\n return res.body.version;\n }\n }\n },\n enabled: enabled && kind !== null && id !== \"\" && versionNumber !== null,\n });\n}\n\n/**\n * `POST /<collection>/:id/publish`. `kind` is fixed per hook instance — the caller already knows\n * which kind it is publishing (the rail's `ctx.kind`, or `WorkflowsPage.tsx`'s hardcoded\n * `\"workflow\"`) — and `mutate(id)` supplies the resource. `onSuccess` invalidates the SAME\n * `[\"versions\", kind, id]` key {@link useVersionsQuery} reads, so the panel's published pointer\n * and version list are fresh without a reload (A3), mirroring `useSaveFunctionMutation`'s\n * `onSuccess` shape (`./functions.ts`).\n */\nexport function usePublishMutation(kind: VersionsKind) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (id: string): Promise<PublishResult> => {\n switch (kind) {\n case \"workflow\":\n return await apiClient.workflows.publish(id);\n case \"function\":\n return await apiClient.functions.publish(id);\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<PublishResult>({\n method: \"POST\",\n path: path`/${COLLECTION_PATH.endpoint}/${id}/publish`,\n });\n return res.body;\n }\n }\n },\n onSuccess: (_result, id) => {\n return qc.invalidateQueries({ queryKey: versionsKey(kind, id) });\n },\n });\n}\n\n/**\n * `POST /<collection>/:id/{enable,disable}`. One mutation for both — the wire contract is two\n * routes distinguished only by which one is called, so `vars.enabled` picks the path segment\n * rather than this module carrying two near-identical mutations. `onSuccess` invalidates the same\n * key {@link usePublishMutation} does, for the same reason.\n */\nexport function useSetEnabledMutation(kind: VersionsKind) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (vars: { id: string; enabled: boolean }): Promise<{ enabled: boolean }> => {\n // The SDK's `enable`/`disable` return void; the hook's result stays `{ enabled }`.\n switch (kind) {\n case \"workflow\":\n if (vars.enabled) await apiClient.workflows.enable(vars.id);\n else await apiClient.workflows.disable(vars.id);\n return { enabled: vars.enabled };\n case \"function\":\n if (vars.enabled) await apiClient.functions.enable(vars.id);\n else await apiClient.functions.disable(vars.id);\n return { enabled: vars.enabled };\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<{ enabled: boolean }>({\n method: \"POST\",\n path: path`/${COLLECTION_PATH.endpoint}/${vars.id}/${vars.enabled ? \"enable\" : \"disable\"}`,\n });\n return res.body;\n }\n }\n },\n onSuccess: (_result, vars) => {\n qc.invalidateQueries({ queryKey: versionsKey(kind, vars.id) });\n },\n });\n}\n\n/**\n * `POST /<collection>/:id/versions/:n/revert`, no body — overwrites the LIVE resource's\n * `definition` with the archived version's content, preserving its `key`/address (HITL-4's\n * pinned default; see the module docblock). This is the first mutation in this family that\n * changes `definition` rather than merely appending to or flipping a flag on the version history\n * (`usePublishMutation`/`useSetEnabledMutation` above do neither), so `onSuccess` invalidates\n * BOTH `versionsKey(kind, id)` (the same key those two invalidate) AND the kind's own\n * definition-edit key — via the shared `invalidateSavedCallable` helper\n * `useSaveFunctionMutation`/`useSaveEndpointMutation` already route through\n * (`../lib/save-invalidation.ts`) — or the page a user reverted FROM keeps showing the\n * pre-revert draft until a manual reload. The definition key is picked by a `switch` naming all\n * three arms explicitly, with no `default:` — the same reasoning `COLLECTION_PATH`'s own docblock\n * gives: a derived rule would silently send one kind at another kind's key.\n */\nexport function useRevertMutation(kind: VersionsKind) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (vars: { id: string; versionNumber: number }): Promise<RevertResult> => {\n // The SDK's `revert` unwraps `{ reverted }`; the hook re-wraps it to keep its result shape.\n switch (kind) {\n case \"workflow\":\n return { reverted: await apiClient.workflows.revert(vars.id, vars.versionNumber) };\n case \"function\":\n return { reverted: await apiClient.functions.revert(vars.id, vars.versionNumber) };\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<RevertResult>({\n method: \"POST\",\n path: path`/${COLLECTION_PATH.endpoint}/${vars.id}/versions/${String(vars.versionNumber)}/revert`,\n });\n return res.body;\n }\n }\n },\n onSuccess: (_result, vars) => {\n let definitionKey: readonly unknown[];\n switch (kind) {\n case \"function\":\n definitionKey = functionKey(vars.id);\n break;\n case \"workflow\":\n definitionKey = workflowKey(vars.id);\n break;\n case \"endpoint\":\n definitionKey = endpointKey(vars.id);\n break;\n }\n invalidateSavedCallable(qc, versionsKey(kind, vars.id), definitionKey);\n },\n });\n}\n\n/**\n * `POST /<collection>/:id/versions/:n/{invoke,run}`, an EMPTY JSON body — identical to that\n * kind's unversioned invoke/run route's success body, except the requested version's OWN\n * `impl`/definition runs instead of the live one (T5.3.1's wire contract table). Unlike\n * {@link useRevertMutation}, invoking changes no resource state, so it invalidates History ONLY\n * (`onSettled`, `historyKeys.root` — a version run is a run, failed ones included, like every other\n * run path) and no resource query — the caller (`VersionHistoryModal`) renders the mutation's own `data`/`error` state\n * directly, and that state is naturally cleared whenever the modal remounts for a different\n * version (`SettingsTool.tsx`'s `openVersion` gate fully unmounts/remounts it, never leaves it\n * mounted across a prop change).\n */\nexport function useInvokeVersionMutation(kind: VersionsKind) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (vars: {\n id: string;\n versionNumber: number;\n }): Promise<Record<string, unknown>> => {\n // The workflow arm moves to `workflows.runVersion`. The FUNCTION arm (F-P4 / F-6) and the\n // ENDPOINT arm (R-5) stay on `request()`: this hook's caller renders the raw invocation\n // frame, and `functions.runVersion` unwraps the output like `functions.run` — it would drop\n // the frame. The workflow arm returns only `{ runId, status }`, as the raw body did.\n if (kind === \"workflow\") {\n const run = await apiClient.workflows.runVersion(vars.id, vars.versionNumber, {});\n // Project back to the server's own run-start body: the SDK adds `steps`/`terminal`/\n // `httpStatus`, and `VersionHistoryModal` prints this value verbatim as JSON.\n return { runId: run.runId, status: run.status };\n }\n const res = await apiClient.request<Record<string, unknown>>({\n method: \"POST\",\n path: path`/${COLLECTION_PATH[kind]}/${vars.id}/versions/${String(vars.versionNumber)}/${VERSION_INVOKE_VERB[kind]}`,\n body: {},\n });\n return res.body;\n },\n onSettled: () => qc.invalidateQueries({ queryKey: historyKeys.root }),\n });\n}\n","/**\n * The `documents` domain repo — wraps `@w6w/sdk`'s `client.documents.*` in\n * react-query (HITL-6). `QueryClientProvider` (`main.tsx`) stays the actual\n * cache; this module only centralizes the query-key factory and the\n * `queryFn`/`mutationFn` pairs so every page reads documents the same way.\n *\n * Documents are project-scoped (`documents.ts`'s `DocumentOptions.project`);\n * every mutation here invalidates the unscoped `[\"documents\"]` key, which\n * prefix-matches every project-scoped query key produced by\n * {@linkcode documentsKey} — the same invalidation shape `DocumentsPage.tsx`\n * used before this migration.\n */\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { path, type Doc, type DocumentCreateInput, type DocumentPatch } from \"@w6w/sdk\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\n\n/**\n * T1.1.1's wire shape for one document, pinned here ahead of that node\n * merging (this node is dispatched speculatively against it — see this\n * task's contract). `shared` and the six `source*`/`syncedAt` fields are all\n * additive over the SDK's own `Doc`, so a locally-created document simply\n * carries them as `null` (or `false` for `shared`) rather than omitting\n * them. Do not rename a field — the server produces these names verbatim.\n */\nexport interface DocWithProvenance extends Doc {\n shared: boolean;\n /** \"owner/name\" of the bound repository this document was pulled from. */\n sourceRepo: string | null;\n /** Repo-relative file path the document was pulled from. */\n sourcePath: string | null;\n /** The pulled file's content hash — NOT a commit SHA. */\n sourceSha: string | null;\n /** The repository's HEAD commit SHA at pull time — NOT a content hash. */\n sourceRefSha: string | null;\n /** Web link to the file; may be absent even when the rest of provenance is set. */\n sourceUrl: string | null;\n /** ISO-8601. Stamped at the document's last actual change, not at every sync. */\n syncedAt: string | null;\n}\n\n/**\n * Which provenance state `DocumentDetailPage.tsx`'s \"Source\" card should\n * render for `doc`. `shared` (not `sourceRepo`) is the gate: a shared\n * document whose provenance columns haven't been stamped yet (any document\n * synced before this feature shipped, until its next real-content sync —\n * tier-1 \"unchanged\" syncs never restamp provenance) is still shared, and\n * must say so, distinct from a genuinely private document.\n *\n * - `\"private\"` — `doc.shared` is false. No card.\n * - `\"pending\"` — shared, but `sourceRepo` hasn't been stamped yet.\n * - `\"synced\"` — shared, with full provenance available.\n */\nexport function documentProvenanceState(doc: DocWithProvenance): \"private\" | \"pending\" | \"synced\" {\n if (!doc.shared) return \"private\";\n return doc.sourceRepo == null ? \"pending\" : \"synced\";\n}\n\n/** Query key for a documents list, optionally scoped to a project. */\nexport function documentsKey(projectId?: string) {\n return [\"documents\", projectId] as const;\n}\n\n/**\n * Query key for a single document, scoped to a project (mirrors\n * {@linkcode useDocumentsQuery}'s fix at :72-79/:80-87 below — `projectId`\n * belongs in the key itself, not just the `queryFn`, so a render where the\n * key was cached under `projectId === undefined` genuinely changes key once\n * `ProjectContext` resolves the real one, instead of reusing the same cache\n * entry — and its `retry: false` wrong-project 404 — forever). Still sits\n * under the bare `[\"documents\"]` prefix every mutation below invalidates, so\n * an edit/delete refreshes this page too — `\"detail\"` keeps it from\n * colliding with {@linkcode documentsKey}'s own `[\"documents\", projectId]`\n * shape.\n */\nexport function documentKey(id: string, projectId?: string) {\n return [\"documents\", \"detail\", id, projectId] as const;\n}\n\n/**\n * A single document by id, cast to {@link DocWithProvenance} (D-5): the SDK's\n * `Doc` doesn't model T1.1.1's provenance fields yet, and this repo is not\n * the place to fork or extend `@w6w/sdk` (D-4). The `project` option is\n * passed exactly as {@linkcode useDocumentsQuery} passes it — a document in a\n * non-default project 404s without it. `enabled` defaults `true` to preserve\n * that unscoped fallback for a caller that genuinely wants it — same as\n * {@linkcode useDocumentsQuery}'s own `enabled` doc comment below — a\n * project-scoped page should instead pass `enabled: projectId != null` so it\n * never queries (and never renders) against the wrong project while\n * `ProjectContext`'s own project list is still resolving.\n */\nexport function useDocumentQuery(id: string, projectId?: string, enabled = true) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: documentKey(id, projectId),\n queryFn: async () =>\n (await apiClient.documents.get(id, { project: projectId })) as DocWithProvenance,\n enabled,\n });\n}\n\n/**\n * The current project's documents (or the tenant default when unscoped).\n * `enabled` defaults `true` to preserve that unscoped fallback for a caller\n * that genuinely wants it — a project-scoped page should instead pass\n * `enabled: projectId != null` so it never queries (and never renders)\n * against the wrong project while `ProjectContext`'s own project list is\n * still resolving.\n */\nexport function useDocumentsQuery(projectId?: string, enabled = true) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: documentsKey(projectId),\n // Cast to DocWithProvenance[], same as useDocumentQuery above: the wire\n // response already carries `shared`/`source*`/`syncedAt` (repo.list()\n // serializes every document the same way repo.get() does), but the SDK's\n // own `Doc` type doesn't declare them yet (D-5). Without this cast,\n // DocumentsPage.tsx's list rows have no type-visible way to branch on\n // `d.shared` the way DocumentDetailPage.tsx already does.\n queryFn: async () =>\n (await apiClient.documents.list({ project: projectId })) as DocWithProvenance[],\n enabled,\n });\n}\n\nexport function useCreateDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { input: DocumentCreateInput; project?: string }) =>\n apiClient.documents.create(vars.input, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\nexport function useUpdateDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; patch: DocumentPatch; project?: string }) =>\n apiClient.documents.update(vars.id, vars.patch, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\nexport function useDeleteDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; project?: string }) =>\n apiClient.documents.delete(vars.id, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\n/**\n * Re-pulls a shared document from its bound repository (\"Sync\" button, T2.1.4)\n * — `POST /documents/:id/sync` (T3.1.1). No SDK method exists for this route\n * yet (D-4/D-5), so this goes through `apiClient.request()` directly, same\n * escape hatch `repo-sync.ts`'s `useSyncRepoNowMutation` uses. The document\n * routes are project-scoped by QUERY param, not a path segment (unlike\n * `repo-binding`'s `/projects/:id/...` shape), so `project` travels in\n * `query`, mirroring {@linkcode useDocumentQuery}'s own `{ project: … }` use.\n */\nexport function useSyncDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; project?: string }) =>\n apiClient.request<{ document: DocWithProvenance }>({\n method: \"POST\",\n path: path`/documents/${vars.id}/sync`,\n query: { project: vars.project },\n }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n","/**\n * The `/spec/import` repo (T3.2.1). A NEW file, deliberately kept out of\n * `repos/functions.ts` / `repos/endpoints.ts` (T3.1.1 owns both) so the two\n * nodes never collide on the same file.\n *\n * **Every operation here goes through `W6WClient.request<T>()`, never\n * `apiClient.console.*`.** `T2.1.2`'s `inputs.touch` has no\n * `packages/wrappers` entry — there is no SDK method for this route — so\n * `request()` is the client's public escape hatch, exactly as\n * `repos/vars.ts`'s own docblock explains for the same reason.\n *\n * The posted `document` is forwarded to the server as-is (spread, never edited):\n * this module adds only `project` (and, on import, `selections`) beside it, validates nothing, and — this is the mechanism pin note 1\n * of the contract states from the side a wrong implementation must break —\n * never falls back to the sibling whole-definition save mutation\n * `FunctionIdentityModal.tsx` uses, on any response. `/spec/import` is where\n * the server-side sealed-secret walker lives (T2.1.2 §B runs\n * `assertNoSecretEnvelopes` over the WHOLE supplied body before any write);\n * a \"helpful\" fallback to that other write path would route a pasted\n * document straight around that check.\n *\n * T1.2.1 generalizes this over all three kinds: `onSuccess` invalidates the\n * ONE list key the imported document's own kind reads (`result.kind`, which\n * the server always echoes), never an unconditional `functionsKey`. The\n * decision of which key that is lives in `../lib/spec-import-invalidation.ts`\n * (a pure, `node --test`-loadable module). The three list keys are INJECTED by the host\n * (`listKeys`): Studio's `functionsKey`/`endpointsKey` live in its own `repos/callables`.\n */\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport type { PreviewDependency, Selection, SpecDependency } from \"../lib/import-bindings.ts\";\nimport {\n type SpecImportListKeys,\n invalidateImportedCallable,\n} from \"../lib/spec-import-invalidation.ts\";\n\n/**\n * Mirrors `T2.1.1`'s `SpecDocument` (`T2.1.1.contract.md:134-141`): the\n * portable document a `GET /<kind>/:id/spec` export produces and this\n * route consumes. Not a bare `FunctionDef` — connection/var references ride\n * as re-bindable `rebind` entries, never live ids.\n */\nexport interface SpecImportDocument {\n specVersion: string;\n kind: \"function\" | \"endpoint\" | \"workflow\";\n callable: Record<string, unknown>;\n rebind: unknown[];\n}\n\n/** One reference site's outcome (T2.1.2 §E's `SpecImportReferenceReport`). */\nexport interface SpecImportReferenceReport {\n path: string;\n kind: string;\n resolved: boolean;\n /** Present only when `resolved` is `true`. */\n boundTo?: string;\n /** Present only when `resolved` is `false`. */\n reason?: string;\n}\n\n/** The `201` body `POST /spec/import` returns (T2.1.2 §E). */\nexport interface SpecImportResult {\n kind: \"function\" | \"endpoint\" | \"workflow\";\n callable: { id: string; key?: string; name?: string };\n references: SpecImportReferenceReport[];\n dependencies?: ImportDependencyStatus[];\n}\n\n/** IF-1 `POST /spec/preview` result: one entry per dependency, with server options + suggestion. */\nexport interface PreviewResult {\n kind: \"function\" | \"endpoint\" | \"workflow\";\n dependencies: PreviewDependency[];\n references?: SpecImportReferenceReport[];\n}\n\n/** One dependency's outcome in the import result (IF-1 `dependencies` status[]). */\nexport interface ImportDependencyStatus {\n key: string;\n kind?: SpecDependency[\"kind\"];\n name?: string;\n status: \"bound\" | \"created\" | \"unconfigured\" | string;\n boundTo?: string;\n reason?: string;\n}\n\n/** The preview request body: the document plus the host project, sent explicitly. */\nexport function buildPreviewBody(\n document: Record<string, unknown>,\n project: string | undefined,\n): Record<string, unknown> {\n return { ...document, project };\n}\n\n/** The import request body: the preview body plus the FULL selections map (`unconfigured` included). */\nexport function buildImportBody(\n document: Record<string, unknown>,\n project: string | undefined,\n selections: Record<string, Selection>,\n): Record<string, unknown> {\n return { ...buildPreviewBody(document, project), selections };\n}\n\n/**\n * `POST /spec/preview` (IF-1). Read-only on the server; a failure rejects the mutation and the\n * caller blocks Create — there is NO fallback to posting the document verbatim to `/spec/import`.\n */\nexport function useSpecPreviewMutation(project: string | undefined) {\n const apiClient = useEmbedClient();\n return useMutation({\n mutationFn: async (document: Record<string, unknown>) => {\n const res = await apiClient.request<PreviewResult>({\n method: \"POST\",\n path: \"/spec/preview\",\n body: buildPreviewBody(document, project),\n });\n return res.body;\n },\n });\n}\n\n/**\n * `POST /spec/import`. Success is always `201` — including a partially\n * resolved import (T2.1.2 §E: \"report, never fail silently\"). This mutation\n * resolves on ANY `201`; branching on `references.every(r => r.resolved)` is\n * the caller's job (A5), never this repo's.\n *\n * `project` is the caller's current project — only the workflow arm reads it\n * (`listKeys.workflowsKey(project)`), but every caller passes it uniformly rather than branching on kind itself; see\n * `../lib/spec-import-invalidation.ts` for why the key differs by kind.\n */\nexport function useImportSpecMutation(project: string | undefined, listKeys: SpecImportListKeys) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (input: {\n document: Record<string, unknown>;\n selections: Record<string, Selection>;\n }) => {\n const res = await apiClient.request<SpecImportResult>({\n method: \"POST\",\n path: \"/spec/import\",\n body: buildImportBody(input.document, project, input.selections),\n });\n return res.body;\n },\n // A row exists in every `201` outcome (T2.1.2 §E creates it even when\n // some references stayed unresolved), so the list is stale either way —\n // but ONLY the list the imported kind actually belongs to (AC-3): the\n // unconditional `functionsKey` this used to invalidate left an imported\n // Endpoint or Workflow's own list stale while pointlessly invalidating\n // Functions.\n onSuccess: (result) => invalidateImportedCallable(qc, result.kind, listKeys, project),\n });\n}\n"],"names":["endpointKey","id","callableKey","functionKey","COLLECTION_PATH","VERSION_INVOKE_VERB","versionsKey","kind","versionKey","versionNumber","useVersionsQuery","enabled","apiClient","useEmbedClient","useQuery","path","useVersionQuery","n","usePublishMutation","qc","useQueryClient","useMutation","_result","useSetEnabledMutation","vars","useRevertMutation","definitionKey","workflowKey","invalidateSavedCallable","useInvokeVersionMutation","run","historyKeys","documentProvenanceState","doc","documentsKey","projectId","documentKey","useDocumentQuery","useDocumentsQuery","useCreateDocumentMutation","useUpdateDocumentMutation","useDeleteDocumentMutation","useSyncDocumentMutation","buildPreviewBody","document","project","buildImportBody","selections","useSpecPreviewMutation","useImportSpecMutation","listKeys","input","result","invalidateImportedCallable"],"mappings":";;;;;;AA6CA,MAAMA,IAAc,CAACC,MAAeC,EAAY,YAAYD,CAAE,GACxDE,IAAc,CAACF,MAAeC,EAAY,YAAYD,CAAE,GAUxDG,IAAiF;AAAA,EACrF,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AACZ,GAqDMC,IAA8D;AAAA,EAClE,UAAU;AAAA,EACV,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,QAAA;AAAA,IAAQ,CAChC;AAAA,IACH,WAAW,MAAML,EAAG,kBAAkB,EAAE,UAAU,CAAC,WAAW,EAAA,CAAG;AAAA,EAAA,CAClE;AACH;ACzFO,SAASwB,EACdC,GACAC,GACyB;AACzB,SAAO,EAAE,GAAGD,GAAU,SAAAC,EAAA;AACxB;AAGO,SAASC,EACdF,GACAC,GACAE,GACyB;AACzB,SAAO,EAAE,GAAGJ,EAAiBC,GAAUC,CAAO,GAAG,YAAAE,EAAA;AACnD;AAMO,SAASC,EAAuBH,GAA6B;AAClE,QAAMjC,IAAYC,EAAA;AAClB,SAAOQ,EAAY;AAAA,IACjB,YAAY,OAAOuB,OACL,MAAMhC,EAAU,QAAuB;AAAA,MACjD,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,MAAM+B,EAAiBC,GAAUC,CAAO;AAAA,IAAA,CACzC,GACU;AAAA,EACb,CACD;AACH;AAYO,SAASI,EAAsBJ,GAA6BK,GAA8B;AAC/F,QAAMtC,IAAYC,EAAA,GACZM,IAAKC,EAAA;AACX,SAAOC,EAAY;AAAA,IACjB,YAAY,OAAO8B,OAIL,MAAMvC,EAAU,QAA0B;AAAA,MACpD,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,MAAMkC,EAAgBK,EAAM,UAAUN,GAASM,EAAM,UAAU;AAAA,IAAA,CAChE,GACU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQb,WAAW,CAACC,MAAWC,EAA2BlC,GAAIiC,EAAO,MAAMF,GAAUL,CAAO;AAAA,EAAA,CACrF;AACH;"}
|
|
1
|
+
{"version":3,"file":"spec-import-CGPqUUjN.js","sources":["../src/repos/versions.ts","../src/repos/documents.ts","../src/repos/spec-import.ts"],"sourcesContent":["/**\n * The `/<collection>/:id/{publish,versions,enable,disable}` repo (T3.1.1) — the Settings rail's\n * read-only version-history browser plus Publish and Enable/Disable. A NEW file, mirroring\n * `src/repos/spec-export.ts` in full: kept out of `repos/functions.ts` / `repos/workflows.ts` /\n * `repos/endpoints.ts` so this node never collides with any of them on the same file, exactly the\n * reason `spec-export.ts`'s own docblock gives for the sibling `/spec` route.\n *\n * **Workflow and Function arms go through the public `@w6w/sdk` methods** (`listVersions`,\n * `getVersion`, `publish`, `revert`, `enable`, `disable`, and `workflows.runVersion`), never\n * `apiClient.console.*`. Each hook dispatches with an explicit per-kind `switch` over LITERAL\n * receivers (`apiClient.workflows.publish(id)`, `apiClient.functions.publish(id)`) and no `default:`\n * — the same reasoning `COLLECTION_PATH` and `useRevertMutation` give against derived dispatch.\n *\n * **Two arms deliberately stay on `W6WClient.request<T>()`:** the ENDPOINT arm of every hook\n * (R-5: endpoint versions have no SDK method — intentionally excluded from the public surface),\n * and the FUNCTION arm of {@link useInvokeVersionMutation} (F-P4: `VersionHistoryModal` renders the\n * raw invocation frame, but `functions.runVersion` unwraps the output like `functions.run`, so the\n * SDK method would drop the frame; follow-up F-6).\n *\n * Every query below is gated on the CALLER'S OWN `enabled` flag, ANDed with `kind !== null` and\n * `id !== \"\"` — never on mount alone (`packages/studio/.ai/PLANNER.md` fact 11): a hook that fires\n * unconditionally against an unresolved `null`/`\"\"` argument 404s once and, because `main.tsx`\n * sets `retry: false` and an unchanged query key never re-fetches, never self-corrects. Opening\n * the Settings panel must issue ZERO `/versions` requests; only opening its History section (or\n * `WorkflowsPage.tsx`'s own editor, a separate call site with its own gate) flips `enabled`.\n *\n * T5.3.1 (project.md Phase 2, Amendments #5/#6): a version can now be reverted to and invoked\n * directly, superseding the earlier \"read-only history, restore out of scope\" pin. `useRevertMutation`\n * overwrites the LIVE resource's `definition` with the archived version's content — never its\n * `key`/address (HITL-4's pinned default) — and does post a `definition` back, by design.\n * `useInvokeVersionMutation` runs that ARCHIVED version's own definition, not the live one, which is\n * exactly why it exists as a separate call from the live invoke/run routes `functions.ts`/\n * `endpoints.ts`/`workflows.ts` already expose.\n */\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { path } from \"@w6w/sdk\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport { callableKey } from \"../lib/callable-kind.ts\";\nimport { historyKeys } from \"../lib/history-query.ts\";\nimport { invalidateSavedCallable } from \"../lib/save-invalidation.ts\";\nimport { workflowKey } from \"./workflows.ts\";\n\n/** The Endpoint / Function single-resource keys the revert arm invalidates: the same\n * `callableKey(\"<kind>\", id)` Studio's `repos/endpoints.ts` / `repos/functions.ts` export as\n * `endpointKey` / `functionKey` (byte-identical `[\"endpoint\", id]` / `[\"function\", id]`). */\nconst endpointKey = (id: string) => callableKey(\"endpoint\", id);\nconst functionKey = (id: string) => callableKey(\"function\", id);\n\n/** The three kinds the wire contract's version-history routes exist for — `connection` has none\n * (see `hasVersionHistory`, `../lib/rail-settings.ts`). */\nexport type VersionsKind = \"function\" | \"workflow\" | \"endpoint\";\n\n/** `<coll>` — the wire contract's own path segment for each kind, every one of the three arms\n * named explicitly (never derived by string pluralization), mirroring `specCollectionForKind`'s\n * own reasoning (`../lib/rail-settings.ts:69`): a typo'd suffix rule would silently send one\n * kind's requests at another kind's collection. */\nconst COLLECTION_PATH: Record<VersionsKind, \"functions\" | \"workflows\" | \"endpoints\"> = {\n function: \"functions\",\n workflow: \"workflows\",\n endpoint: \"endpoints\",\n};\n\n/** One row of `GET /<coll>/:id/versions`'s `versions` array — newest first, per the wire contract. */\nexport interface VersionSummary {\n versionNumber: number;\n createdAt: string;\n createdBy: string | null;\n isCurrentPublished: boolean;\n}\n\n/** `GET /<coll>/:id/versions`'s full 200 body. */\nexport interface VersionsEnvelope {\n enabled: boolean;\n currentPublishedVersion: number | null;\n versions: VersionSummary[];\n}\n\n/** `GET /<coll>/:id/versions/:n`'s `version` field — `definition` is the redacted stored\n * definition for THIS query; {@link useRevertMutation} is what posts a version's definition\n * back onto the live resource, and {@link useInvokeVersionMutation} is what runs it. */\nexport interface VersionDetail {\n versionNumber: number;\n createdAt: string;\n createdBy: string | null;\n isCurrentPublished: boolean;\n definition: Record<string, unknown>;\n}\n\n/** `POST /<coll>/:id/publish`'s 200 body. */\nexport interface PublishResult {\n version: {\n kind: string;\n callableId: string;\n versionNumber: number;\n createdAt: string;\n createdBy: string | null;\n };\n currentPublishedVersion: number;\n}\n\n/** `POST /<coll>/:id/versions/:n/revert`'s 200 body. */\nexport interface RevertResult {\n reverted: {\n kind: string;\n callableId: string;\n versionNumber: number;\n };\n}\n\n/** `<coll>` per kind ends its live invoke/run route in `/invoke` (Function, Endpoint) or `/run`\n * (Workflow, matching that kind's existing unversioned route) — every arm named explicitly\n * (never derived by suffix rule), mirroring `COLLECTION_PATH`'s own reasoning above: a derived\n * rule would silently send one kind's requests at the wrong verb. */\nconst VERSION_INVOKE_VERB: Record<VersionsKind, \"invoke\" | \"run\"> = {\n function: \"invoke\",\n endpoint: \"invoke\",\n workflow: \"run\",\n};\n\nexport function versionsKey(kind: VersionsKind | null, id: string) {\n return [\"versions\", kind, id] as const;\n}\n\nexport function versionKey(kind: VersionsKind | null, id: string, versionNumber: number | null) {\n return [\"version\", kind, id, versionNumber] as const;\n}\n\n/**\n * `GET /<collection>/:id/versions`. Never fires on mount — `enabled` is the caller's own flag\n * (the Settings panel's History-open state, or `WorkflowsPage.tsx`'s own editor-open gate), ANDed\n * with `kind !== null` and `id !== \"\"`, exactly `useSpecQuery`'s shape (`spec-export.ts:45-57`).\n */\nexport function useVersionsQuery(kind: VersionsKind | null, id: string, enabled: boolean) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: versionsKey(kind, id),\n queryFn: async (): Promise<VersionsEnvelope> => {\n switch (kind as VersionsKind) {\n case \"workflow\":\n return await apiClient.workflows.listVersions(id);\n case \"function\":\n return await apiClient.functions.listVersions(id);\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<VersionsEnvelope>({\n method: \"GET\",\n path: path`/${COLLECTION_PATH.endpoint}/${id}/versions`,\n });\n return res.body;\n }\n }\n },\n enabled: enabled && kind !== null && id !== \"\",\n });\n}\n\n/**\n * `GET /<collection>/:id/versions/:n`. Same gating shape as {@link useVersionsQuery}, plus\n * `versionNumber !== null` — the modal opens this only once a row has been clicked.\n */\nexport function useVersionQuery(\n kind: VersionsKind | null,\n id: string,\n versionNumber: number | null,\n enabled: boolean,\n) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: versionKey(kind, id, versionNumber),\n queryFn: async (): Promise<VersionDetail> => {\n // The SDK's `getVersion` already unwraps the `{ version }` envelope.\n const n = versionNumber as number;\n switch (kind as VersionsKind) {\n case \"workflow\":\n return (await apiClient.workflows.getVersion(id, n)) as VersionDetail;\n case \"function\":\n return (await apiClient.functions.getVersion(id, n)) as VersionDetail;\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<{ version: VersionDetail }>({\n method: \"GET\",\n path: path`/${COLLECTION_PATH.endpoint}/${id}/versions/${String(n)}`,\n });\n return res.body.version;\n }\n }\n },\n enabled: enabled && kind !== null && id !== \"\" && versionNumber !== null,\n });\n}\n\n/**\n * `POST /<collection>/:id/publish`. `kind` is fixed per hook instance — the caller already knows\n * which kind it is publishing (the rail's `ctx.kind`, or `WorkflowsPage.tsx`'s hardcoded\n * `\"workflow\"`) — and `mutate(id)` supplies the resource. `onSuccess` invalidates the SAME\n * `[\"versions\", kind, id]` key {@link useVersionsQuery} reads, so the panel's published pointer\n * and version list are fresh without a reload (A3), mirroring `useSaveFunctionMutation`'s\n * `onSuccess` shape (`./functions.ts`).\n */\nexport function usePublishMutation(kind: VersionsKind) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (id: string): Promise<PublishResult> => {\n switch (kind) {\n case \"workflow\":\n return await apiClient.workflows.publish(id);\n case \"function\":\n return await apiClient.functions.publish(id);\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<PublishResult>({\n method: \"POST\",\n path: path`/${COLLECTION_PATH.endpoint}/${id}/publish`,\n });\n return res.body;\n }\n }\n },\n onSuccess: (_result, id) => {\n return qc.invalidateQueries({ queryKey: versionsKey(kind, id) });\n },\n });\n}\n\n/**\n * `POST /<collection>/:id/{enable,disable}`. One mutation for both — the wire contract is two\n * routes distinguished only by which one is called, so `vars.enabled` picks the path segment\n * rather than this module carrying two near-identical mutations. `onSuccess` invalidates the same\n * key {@link usePublishMutation} does, for the same reason.\n */\nexport function useSetEnabledMutation(kind: VersionsKind) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (vars: { id: string; enabled: boolean }): Promise<{ enabled: boolean }> => {\n // The SDK's `enable`/`disable` return void; the hook's result stays `{ enabled }`.\n switch (kind) {\n case \"workflow\":\n if (vars.enabled) await apiClient.workflows.enable(vars.id);\n else await apiClient.workflows.disable(vars.id);\n return { enabled: vars.enabled };\n case \"function\":\n if (vars.enabled) await apiClient.functions.enable(vars.id);\n else await apiClient.functions.disable(vars.id);\n return { enabled: vars.enabled };\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<{ enabled: boolean }>({\n method: \"POST\",\n path: path`/${COLLECTION_PATH.endpoint}/${vars.id}/${vars.enabled ? \"enable\" : \"disable\"}`,\n });\n return res.body;\n }\n }\n },\n onSuccess: (_result, vars) => {\n qc.invalidateQueries({ queryKey: versionsKey(kind, vars.id) });\n },\n });\n}\n\n/**\n * `POST /<collection>/:id/versions/:n/revert`, no body — overwrites the LIVE resource's\n * `definition` with the archived version's content, preserving its `key`/address (HITL-4's\n * pinned default; see the module docblock). This is the first mutation in this family that\n * changes `definition` rather than merely appending to or flipping a flag on the version history\n * (`usePublishMutation`/`useSetEnabledMutation` above do neither), so `onSuccess` invalidates\n * BOTH `versionsKey(kind, id)` (the same key those two invalidate) AND the kind's own\n * definition-edit key — via the shared `invalidateSavedCallable` helper\n * `useSaveFunctionMutation`/`useSaveEndpointMutation` already route through\n * (`../lib/save-invalidation.ts`) — or the page a user reverted FROM keeps showing the\n * pre-revert draft until a manual reload. The definition key is picked by a `switch` naming all\n * three arms explicitly, with no `default:` — the same reasoning `COLLECTION_PATH`'s own docblock\n * gives: a derived rule would silently send one kind at another kind's key.\n */\nexport function useRevertMutation(kind: VersionsKind) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (vars: { id: string; versionNumber: number }): Promise<RevertResult> => {\n // The SDK's `revert` unwraps `{ reverted }`; the hook re-wraps it to keep its result shape.\n switch (kind) {\n case \"workflow\":\n return { reverted: await apiClient.workflows.revert(vars.id, vars.versionNumber) };\n case \"function\":\n return { reverted: await apiClient.functions.revert(vars.id, vars.versionNumber) };\n case \"endpoint\": {\n // R-5: no SDK method for endpoint versions.\n const res = await apiClient.request<RevertResult>({\n method: \"POST\",\n path: path`/${COLLECTION_PATH.endpoint}/${vars.id}/versions/${String(vars.versionNumber)}/revert`,\n });\n return res.body;\n }\n }\n },\n onSuccess: (_result, vars) => {\n let definitionKey: readonly unknown[];\n switch (kind) {\n case \"function\":\n definitionKey = functionKey(vars.id);\n break;\n case \"workflow\":\n definitionKey = workflowKey(vars.id);\n break;\n case \"endpoint\":\n definitionKey = endpointKey(vars.id);\n break;\n }\n invalidateSavedCallable(qc, versionsKey(kind, vars.id), definitionKey);\n },\n });\n}\n\n/**\n * `POST /<collection>/:id/versions/:n/{invoke,run}`, an EMPTY JSON body — identical to that\n * kind's unversioned invoke/run route's success body, except the requested version's OWN\n * `impl`/definition runs instead of the live one (T5.3.1's wire contract table). Unlike\n * {@link useRevertMutation}, invoking changes no resource state, so it invalidates History ONLY\n * (`onSettled`, `historyKeys.root` — a version run is a run, failed ones included, like every other\n * run path) and no resource query — the caller (`VersionHistoryModal`) renders the mutation's own `data`/`error` state\n * directly, and that state is naturally cleared whenever the modal remounts for a different\n * version (`SettingsTool.tsx`'s `openVersion` gate fully unmounts/remounts it, never leaves it\n * mounted across a prop change).\n */\nexport function useInvokeVersionMutation(kind: VersionsKind) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (vars: {\n id: string;\n versionNumber: number;\n }): Promise<Record<string, unknown>> => {\n // The workflow arm moves to `workflows.runVersion`. The FUNCTION arm (F-P4 / F-6) and the\n // ENDPOINT arm (R-5) stay on `request()`: this hook's caller renders the raw invocation\n // frame, and `functions.runVersion` unwraps the output like `functions.run` — it would drop\n // the frame. The workflow arm returns only `{ runId, status }`, as the raw body did.\n if (kind === \"workflow\") {\n const run = await apiClient.workflows.runVersion(vars.id, vars.versionNumber, {});\n // Project back to the server's own run-start body: the SDK adds `steps`/`terminal`/\n // `httpStatus`, and `VersionHistoryModal` prints this value verbatim as JSON.\n return { runId: run.runId, status: run.status };\n }\n const res = await apiClient.request<Record<string, unknown>>({\n method: \"POST\",\n path: path`/${COLLECTION_PATH[kind]}/${vars.id}/versions/${String(vars.versionNumber)}/${VERSION_INVOKE_VERB[kind]}`,\n body: {},\n });\n return res.body;\n },\n onSettled: () => qc.invalidateQueries({ queryKey: historyKeys.root }),\n });\n}\n","/**\n * The `documents` domain repo — wraps `@w6w/sdk`'s `client.documents.*` in\n * react-query (HITL-6). `QueryClientProvider` (`main.tsx`) stays the actual\n * cache; this module only centralizes the query-key factory and the\n * `queryFn`/`mutationFn` pairs so every page reads documents the same way.\n *\n * Documents are project-scoped (`documents.ts`'s `DocumentOptions.project`);\n * every mutation here invalidates the unscoped `[\"documents\"]` key, which\n * prefix-matches every project-scoped query key produced by\n * {@linkcode documentsKey} — the same invalidation shape `DocumentsPage.tsx`\n * used before this migration.\n */\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { path, type Doc, type DocumentCreateInput, type DocumentPatch } from \"@w6w/sdk\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\n\n/**\n * T1.1.1's wire shape for one document, pinned here ahead of that node\n * merging (this node is dispatched speculatively against it — see this\n * task's contract). `shared` and the six `source*`/`syncedAt` fields are all\n * additive over the SDK's own `Doc`, so a locally-created document simply\n * carries them as `null` (or `false` for `shared`) rather than omitting\n * them. Do not rename a field — the server produces these names verbatim.\n */\nexport interface DocWithProvenance extends Doc {\n shared: boolean;\n /** \"owner/name\" of the bound repository this document was pulled from. */\n sourceRepo: string | null;\n /** Repo-relative file path the document was pulled from. */\n sourcePath: string | null;\n /** The pulled file's content hash — NOT a commit SHA. */\n sourceSha: string | null;\n /** The repository's HEAD commit SHA at pull time — NOT a content hash. */\n sourceRefSha: string | null;\n /** Web link to the file; may be absent even when the rest of provenance is set. */\n sourceUrl: string | null;\n /** ISO-8601. Stamped at the document's last actual change, not at every sync. */\n syncedAt: string | null;\n}\n\n/**\n * Which provenance state `DocumentDetailPage.tsx`'s \"Source\" card should\n * render for `doc`. `shared` (not `sourceRepo`) is the gate: a shared\n * document whose provenance columns haven't been stamped yet (any document\n * synced before this feature shipped, until its next real-content sync —\n * tier-1 \"unchanged\" syncs never restamp provenance) is still shared, and\n * must say so, distinct from a genuinely private document.\n *\n * - `\"private\"` — `doc.shared` is false. No card.\n * - `\"pending\"` — shared, but `sourceRepo` hasn't been stamped yet.\n * - `\"synced\"` — shared, with full provenance available.\n */\nexport function documentProvenanceState(doc: DocWithProvenance): \"private\" | \"pending\" | \"synced\" {\n if (!doc.shared) return \"private\";\n return doc.sourceRepo == null ? \"pending\" : \"synced\";\n}\n\n/** Query key for a documents list, optionally scoped to a project. */\nexport function documentsKey(projectId?: string) {\n return [\"documents\", projectId] as const;\n}\n\n/**\n * Query key for a single document, scoped to a project (mirrors\n * {@linkcode useDocumentsQuery}'s fix at :72-79/:80-87 below — `projectId`\n * belongs in the key itself, not just the `queryFn`, so a render where the\n * key was cached under `projectId === undefined` genuinely changes key once\n * `ProjectContext` resolves the real one, instead of reusing the same cache\n * entry — and its `retry: false` wrong-project 404 — forever). Still sits\n * under the bare `[\"documents\"]` prefix every mutation below invalidates, so\n * an edit/delete refreshes this page too — `\"detail\"` keeps it from\n * colliding with {@linkcode documentsKey}'s own `[\"documents\", projectId]`\n * shape.\n */\nexport function documentKey(id: string, projectId?: string) {\n return [\"documents\", \"detail\", id, projectId] as const;\n}\n\n/**\n * A single document by id, cast to {@link DocWithProvenance} (D-5): the SDK's\n * `Doc` doesn't model T1.1.1's provenance fields yet, and this repo is not\n * the place to fork or extend `@w6w/sdk` (D-4). The `project` option is\n * passed exactly as {@linkcode useDocumentsQuery} passes it — a document in a\n * non-default project 404s without it. `enabled` defaults `true` to preserve\n * that unscoped fallback for a caller that genuinely wants it — same as\n * {@linkcode useDocumentsQuery}'s own `enabled` doc comment below — a\n * project-scoped page should instead pass `enabled: projectId != null` so it\n * never queries (and never renders) against the wrong project while\n * `ProjectContext`'s own project list is still resolving.\n */\nexport function useDocumentQuery(id: string, projectId?: string, enabled = true) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: documentKey(id, projectId),\n queryFn: async () =>\n (await apiClient.documents.get(id, { project: projectId })) as DocWithProvenance,\n enabled,\n });\n}\n\n/**\n * The current project's documents (or the tenant default when unscoped).\n * `enabled` defaults `true` to preserve that unscoped fallback for a caller\n * that genuinely wants it — a project-scoped page should instead pass\n * `enabled: projectId != null` so it never queries (and never renders)\n * against the wrong project while `ProjectContext`'s own project list is\n * still resolving.\n */\nexport function useDocumentsQuery(projectId?: string, enabled = true) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: documentsKey(projectId),\n // Cast to DocWithProvenance[], same as useDocumentQuery above: the wire\n // response already carries `shared`/`source*`/`syncedAt` (repo.list()\n // serializes every document the same way repo.get() does), but the SDK's\n // own `Doc` type doesn't declare them yet (D-5). Without this cast,\n // DocumentsPage.tsx's list rows have no type-visible way to branch on\n // `d.shared` the way DocumentDetailPage.tsx already does.\n queryFn: async () =>\n (await apiClient.documents.list({ project: projectId })) as DocWithProvenance[],\n enabled,\n });\n}\n\nexport function useCreateDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { input: DocumentCreateInput; project?: string }) =>\n apiClient.documents.create(vars.input, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\nexport function useUpdateDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; patch: DocumentPatch; project?: string }) =>\n apiClient.documents.update(vars.id, vars.patch, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\nexport function useDeleteDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; project?: string }) =>\n apiClient.documents.delete(vars.id, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\n/**\n * Re-pulls a shared document from its bound repository (\"Sync\" button, T2.1.4)\n * — `POST /documents/:id/sync` (T3.1.1). No SDK method exists for this route\n * yet (D-4/D-5), so this goes through `apiClient.request()` directly, same\n * escape hatch `repo-sync.ts`'s `useSyncRepoNowMutation` uses. The document\n * routes are project-scoped by QUERY param, not a path segment (unlike\n * `repo-binding`'s `/projects/:id/...` shape), so `project` travels in\n * `query`, mirroring {@linkcode useDocumentQuery}'s own `{ project: … }` use.\n */\nexport function useSyncDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; project?: string }) =>\n apiClient.request<{ document: DocWithProvenance }>({\n method: \"POST\",\n path: path`/documents/${vars.id}/sync`,\n query: { project: vars.project },\n }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n","/**\n * The `/spec/import` repo (T3.2.1). A NEW file, deliberately kept out of\n * `repos/functions.ts` / `repos/endpoints.ts` (T3.1.1 owns both) so the two\n * nodes never collide on the same file.\n *\n * **Every operation here goes through `W6WClient.request<T>()`, never\n * `apiClient.console.*`.** `T2.1.2`'s `inputs.touch` has no\n * `packages/wrappers` entry — there is no SDK method for this route — so\n * `request()` is the client's public escape hatch, exactly as\n * `repos/vars.ts`'s own docblock explains for the same reason.\n *\n * The posted `document` is forwarded to the server as-is (spread, never edited):\n * this module adds only `project` (and, on import, `selections`) beside it, validates nothing, and — this is the mechanism pin note 1\n * of the contract states from the side a wrong implementation must break —\n * never falls back to the sibling whole-definition save mutation\n * `FunctionIdentityModal.tsx` uses, on any response. `/spec/import` is where\n * the server-side sealed-secret walker lives (T2.1.2 §B runs\n * `assertNoSecretEnvelopes` over the WHOLE supplied body before any write);\n * a \"helpful\" fallback to that other write path would route a pasted\n * document straight around that check.\n *\n * T1.2.1 generalizes this over all three kinds: `onSuccess` invalidates the\n * ONE list key the imported document's own kind reads (`result.kind`, which\n * the server always echoes), never an unconditional `functionsKey`. The\n * decision of which key that is lives in `../lib/spec-import-invalidation.ts`\n * (a pure, `node --test`-loadable module). The three list keys are INJECTED by the host\n * (`listKeys`): Studio's `functionsKey`/`endpointsKey` live in its own `repos/callables`.\n */\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport type { PreviewDependency, Selection, SpecDependency } from \"../lib/import-bindings.ts\";\nimport {\n type SpecImportListKeys,\n invalidateImportedCallable,\n} from \"../lib/spec-import-invalidation.ts\";\n\n/**\n * Mirrors `T2.1.1`'s `SpecDocument` (`T2.1.1.contract.md:134-141`): the\n * portable document a `GET /<kind>/:id/spec` export produces and this\n * route consumes. Not a bare `FunctionDef` — connection/var references ride\n * as re-bindable `rebind` entries, never live ids.\n */\nexport interface SpecImportDocument {\n specVersion: string;\n kind: \"function\" | \"endpoint\" | \"workflow\";\n callable: Record<string, unknown>;\n rebind: unknown[];\n}\n\n/** One reference site's outcome (T2.1.2 §E's `SpecImportReferenceReport`). */\nexport interface SpecImportReferenceReport {\n path: string;\n kind: string;\n resolved: boolean;\n /** Present only when `resolved` is `true`. */\n boundTo?: string;\n /** Present only when `resolved` is `false`. */\n reason?: string;\n}\n\n/** The `201` body `POST /spec/import` returns (T2.1.2 §E). */\nexport interface SpecImportResult {\n kind: \"function\" | \"endpoint\" | \"workflow\";\n callable: { id: string; key?: string; name?: string };\n references: SpecImportReferenceReport[];\n dependencies?: ImportDependencyStatus[];\n}\n\n/** IF-1 `POST /spec/preview` result: one entry per dependency, with server options + suggestion. */\nexport interface PreviewResult {\n kind: \"function\" | \"endpoint\" | \"workflow\";\n dependencies: PreviewDependency[];\n references?: SpecImportReferenceReport[];\n}\n\n/** One dependency's outcome in the import result (IF-1 `dependencies` status[]). */\nexport interface ImportDependencyStatus {\n key: string;\n kind?: SpecDependency[\"kind\"];\n name?: string;\n status: \"bound\" | \"created\" | \"unconfigured\" | string;\n boundTo?: string;\n reason?: string;\n}\n\n/** The preview request body: the document plus the host project, sent explicitly. */\nexport function buildPreviewBody(\n document: Record<string, unknown>,\n project: string | undefined,\n): Record<string, unknown> {\n return { ...document, project };\n}\n\n/** The import request body: the preview body plus the FULL selections map (`unconfigured` included). */\nexport function buildImportBody(\n document: Record<string, unknown>,\n project: string | undefined,\n selections: Record<string, Selection>,\n): Record<string, unknown> {\n return { ...buildPreviewBody(document, project), selections };\n}\n\n/**\n * `POST /spec/preview` (IF-1). Read-only on the server; a failure rejects the mutation and the\n * caller blocks Create — there is NO fallback to posting the document verbatim to `/spec/import`.\n */\nexport function useSpecPreviewMutation(project: string | undefined) {\n const apiClient = useEmbedClient();\n return useMutation({\n mutationFn: async (document: Record<string, unknown>) => {\n const res = await apiClient.request<PreviewResult>({\n method: \"POST\",\n path: \"/spec/preview\",\n body: buildPreviewBody(document, project),\n });\n return res.body;\n },\n });\n}\n\n/**\n * `POST /spec/import`. Success is always `201` — including a partially\n * resolved import (T2.1.2 §E: \"report, never fail silently\"). This mutation\n * resolves on ANY `201`; branching on `references.every(r => r.resolved)` is\n * the caller's job (A5), never this repo's.\n *\n * `project` is the caller's current project — only the workflow arm reads it\n * (`listKeys.workflowsKey(project)`), but every caller passes it uniformly rather than branching on kind itself; see\n * `../lib/spec-import-invalidation.ts` for why the key differs by kind.\n */\nexport function useImportSpecMutation(project: string | undefined, listKeys: SpecImportListKeys) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: async (input: {\n document: Record<string, unknown>;\n selections: Record<string, Selection>;\n }) => {\n const res = await apiClient.request<SpecImportResult>({\n method: \"POST\",\n path: \"/spec/import\",\n body: buildImportBody(input.document, project, input.selections),\n });\n return res.body;\n },\n // A row exists in every `201` outcome (T2.1.2 §E creates it even when\n // some references stayed unresolved), so the list is stale either way —\n // but ONLY the list the imported kind actually belongs to (AC-3): the\n // unconditional `functionsKey` this used to invalidate left an imported\n // Endpoint or Workflow's own list stale while pointlessly invalidating\n // Functions.\n onSuccess: (result) => invalidateImportedCallable(qc, result.kind, listKeys, project),\n });\n}\n"],"names":["endpointKey","id","callableKey","functionKey","COLLECTION_PATH","VERSION_INVOKE_VERB","versionsKey","kind","versionKey","versionNumber","useVersionsQuery","enabled","apiClient","useEmbedClient","useQuery","path","useVersionQuery","n","usePublishMutation","qc","useQueryClient","useMutation","_result","useSetEnabledMutation","vars","useRevertMutation","definitionKey","workflowKey","invalidateSavedCallable","useInvokeVersionMutation","run","historyKeys","documentProvenanceState","doc","documentsKey","projectId","documentKey","useDocumentQuery","useDocumentsQuery","useCreateDocumentMutation","useUpdateDocumentMutation","useDeleteDocumentMutation","useSyncDocumentMutation","buildPreviewBody","document","project","buildImportBody","selections","useSpecPreviewMutation","useImportSpecMutation","listKeys","input","result","invalidateImportedCallable"],"mappings":";;;;;;AA6CA,MAAMA,IAAc,CAACC,MAAeC,EAAY,YAAYD,CAAE,GACxDE,IAAc,CAACF,MAAeC,EAAY,YAAYD,CAAE,GAUxDG,IAAiF;AAAA,EACrF,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AACZ,GAqDMC,IAA8D;AAAA,EAClE,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AACZ;AAEO,SAASC,EAAYC,GAA2BN,GAAY;AACjE,SAAO,CAAC,YAAYM,GAAMN,CAAE;AAC9B;AAEO,SAASO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ACH;ACzFO,SAASwB,EACdC,GACAC,GACyB;AACzB,SAAO,EAAE,GAAGD,GAAU,SAAAC,EAAA;AACxB;AAGO,SAASC,EACdF,GACAC,GACAE,GACyB;AACzB,SAAO,EAAE,GAAGJ,EAAiBC,GAAUC,CAAO,GAAG,YAAAE,EAAA;AACnD;AAMO,SAASC,EAAuBH,GAA6B;AAClE,QAAMjC,IAAYC,EAAA;AAClB,SAAOQ,EAAY;AAAA,IACjB,YAAY,OAAOuB,OACL,MAAMhC,EAAU,QAAuB;AAAA,MACjD,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,MAAM+B,EAAiBC,GAAUC,CAAO;AAAA,IAAA,CACzC,GACU;AAAA,EACb,CACD;AACH;AAYO,SAASI,EAAsBJ,GAA6BK,GAA8B;AAC/F,QAAMtC,IAAYC,EAAA,GACZM,IAAKC,EAAA;AACX,SAAOC,EAAY;AAAA,IACjB,YAAY,OAAO8B,OAIL,MAAMvC,EAAU,QAA0B;AAAA,MACpD,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,MAAMkC,EAAgBK,EAAM,UAAUN,GAASM,EAAM,UAAU;AAAA,IAAA,CAChE,GACU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQb,WAAW,CAACC,MAAWC,EAA2BlC,GAAIiC,EAAO,MAAMF,GAAUL,CAAO;AAAA,EAAA,CACrF;AACH;"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { useQueryClient as be } from "@tanstack/react-query";
|
|
2
2
|
import { useState as b, useRef as p, useCallback as f, useEffect as T, useMemo as Y } from "react";
|
|
3
|
-
import { u as Ee, i as Re, c as De, a as Te } from "./callables-
|
|
4
|
-
import { c as Z
|
|
3
|
+
import { u as Ee, i as Re, c as De, a as Te } from "./callables-B49tS2vv.js";
|
|
4
|
+
import { c as Z } from "./callable-record-Bhxim8C1.js";
|
|
5
|
+
import { p as Ce, d as Ae } from "./settings-rail-BjsTjg2u.js";
|
|
5
6
|
import { c as Oe, r as xe, n as Ne, i as Pe } from "./use-workflow-draft-l3P5KZzw.js";
|
|
6
7
|
import { u as Je } from "./client-context-CX61Bgw-.js";
|
|
7
8
|
import { u as qe } from "./draft-registry-YF0tqNN0.js";
|
|
@@ -257,15 +258,15 @@ function ie(s, E) {
|
|
|
257
258
|
reload: ke
|
|
258
259
|
};
|
|
259
260
|
}
|
|
260
|
-
function
|
|
261
|
+
function Ue(s) {
|
|
261
262
|
return ie("function", s);
|
|
262
263
|
}
|
|
263
|
-
function
|
|
264
|
+
function je(s) {
|
|
264
265
|
return ie("endpoint", s);
|
|
265
266
|
}
|
|
266
267
|
export {
|
|
267
|
-
|
|
268
|
-
|
|
268
|
+
je as a,
|
|
269
|
+
Ue as b,
|
|
269
270
|
ie as u
|
|
270
271
|
};
|
|
271
|
-
//# sourceMappingURL=use-callable-draft-
|
|
272
|
+
//# sourceMappingURL=use-callable-draft-DjW7_9qb.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-callable-draft-DCauHt5o.js","sources":["../src/draft/use-callable-draft.ts"],"sourcesContent":["/**\n * `useCallableDraft` — the headless draft behind a Function / Endpoint editor: the editable\n * definition as FIELD state (an object, not text), seeded from the ONE react-query entry every\n * other writer invalidates, saved with the stale-write token, and never silently overwriting — or\n * overwritten by — another writer. `useFunctionDraft` / `useEndpointDraft` bind the kind.\n * Mirrors `use-workflow-draft.ts` (same saver, registry, flush-on-hide, no queue, no retry); that\n * file is not edited and the two do not share a runtime beyond `createAutoSaver` & co.\n *\n * ## One cache\n *\n * The buffer is seeded from `useCallableQuery(kind, id)` — the same key and queryFn as\n * `useFunctionQuery` / `useEndpointQuery`. There is no second `useQuery` and no direct\n * `console.*.get` here, so a rail save, a revert, or this draft's own save all land in the entry\n * the draft reads. `reload()` is that query's `refetch()`, then the buffer and token are replaced.\n * The record split (definition vs. `updatedAt` token) is `lib/callable-record.ts`'s `callableRecord`.\n *\n * ## External change (another writer)\n *\n * An external change is a cache update whose `callableRecord(...).updatedAt` differs from the\n * row's CURRENT token:\n *\n * - CLEAN buffer ⇒ the buffer and token are replaced from the cache (no `reload()`, no extra GET).\n * - DIRTY buffer ⇒ the buffer AND the old token are KEPT and `changedElsewhere` becomes true.\n * Adopting the new token without replacing the buffer would be the silent overwrite, so the\n * token only moves with the buffer. The next save therefore still carries the old token and the\n * server answers `409 *_stale`; `reload()` is the way out. Nothing is ever merged — a field-level\n * merge is deliberately not offered (ruling BC-stale).\n * - EQUAL ⇒ no-op. The row's token is advanced from the save response (`nextSaveToken`) BEFORE the\n * save invalidates the cache, so this draft's own save never reads as external — including an\n * edit typed while that save was in flight.\n *\n * ## The trust boundary (why the state is per ROW, not per hook)\n *\n * As the workflow draft: a pending save must be sent by the client that AUTHORED the buffer, even\n * if the host has swapped its client or moved to another resource. Each row holds `auth` (the\n * client the buffer was loaded as) and EVERY save path (debounce, `flush`, `flushThen`,\n * unmount, registry, hide) sends with it, never with the current render's. When the render's\n * client stops matching, the row hands over: one save of a dirty buffer on the authoring client,\n * then the buffer is discarded and re-seeded (the query's `refetch()`) under the new client;\n * `canSave` is false and pushes are ignored meanwhile. One `Row` per `kind:id`; a late completion\n * of an old row's save updates that old row only; `gen` is bumped whenever the buffer is replaced,\n * and a save completing from an older generation never touches the new buffer's token or clean\n * marker. No project is involved (a Function / Endpoint save carries none).\n *\n * `autoSave` defaults to FALSE (Studio saves these explicitly): `flushAll` on the draft registry\n * saves regardless of `autoSave`; hide / unmount honour it. Deliberately absent: retry, a save\n * queue — a 409 is surfaced (`stale`, `error.code`) and never retried.\n *\n * `onPolicyChange(next)` is referentially stable (it reads the buffer through a ref, because\n * `useWorkspace` keys on `JSON.stringify`, which drops functions) and saves\n * `definitionWithPolicy(<current buffer>, next)` immediately — `commit` semantics: any pending\n * editor edits ride along in that same save.\n */\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { W6WClient } from \"@w6w/sdk\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { callableKey } from \"../lib/callable-kind.ts\";\nimport { callableRecord } from \"../lib/callable-record.ts\";\nimport { invalidateSavedCallable } from \"../lib/save-invalidation.ts\";\nimport {\n type CallableDefinition,\n type CallablePolicy,\n definitionWithPolicy,\n policyFromDefinition,\n} from \"../lib/settings-rail.ts\";\nimport { callableListKey, useCallableQuery } from \"../repos/callables.ts\";\nimport { registerFlushOnHide } from \"./autosave-flush.ts\";\nimport { type AutoSaver, createAutoSaver } from \"./autosave.ts\";\nimport { useEmbedClient } from \"./client-context.ts\";\nimport { useDraftRegistry } from \"./draft-registry.ts\";\nimport type { FlushOutcome } from \"./use-workflow-draft.ts\";\nimport { isStaleWrite, nextSaveToken } from \"./workflow-save.ts\";\n\nexport type CallableDraftKind = \"function\" | \"endpoint\";\ntype Definition = Record<string, unknown>;\n\nexport interface UseCallableDraftOptions {\n /** `null` ⇒ idle (the hook stays mounted above an early return). */\n id: string | null;\n /** Default FALSE: nothing is sent until `saveNow()` / `flush()` / `commit()`. */\n autoSave?: boolean;\n /** Injected busy probe. Gates AUTOMATIC saves only. */\n canAutoSave?: () => boolean;\n /** Injected edit guard: a reason blocks saving. */\n saveGuard?: (definition: Definition) => string | null;\n /**\n * Called once when a handover or an identity switch (`flushAll`) drops a dirty buffer it could\n * not save. `blocked`: refused before a request; `failed`: the request failed or the row was\n * stale. No UI here.\n */\n onDiscard?: (info: {\n id: string;\n definition: Definition;\n reason: \"blocked\" | \"failed\";\n }) => void;\n}\n\nexport interface CallableDraft {\n /** The editable definition (no `valid` / `updatedAt`); `null` until loaded. */\n definition: Definition | null;\n setDefinition(next: Definition | ((prev: Definition) => Definition)): void;\n /** `{retry, onError, reroute}` read off the buffer. */\n policy: CallablePolicy;\n /** Referentially stable. Saves `definitionWithPolicy(buffer, next)` now. */\n onPolicyChange(policy: CallablePolicy): void;\n loading: boolean;\n loadError: unknown | null;\n dirty: boolean;\n saving: boolean;\n canSave: boolean;\n saveBlockedReason: string | null;\n /** The last save was refused as stale (`function_stale` / `endpoint_stale`). */\n stale: boolean;\n /** Another writer changed the resource while this buffer is dirty. Never merged. */\n changedElsewhere: boolean;\n error: unknown | null;\n /** Push + fire now. */\n saveNow(): void;\n flush(): Promise<FlushOutcome>;\n /** Flush, then run `action` only when the buffer is clean or just saved. */\n flushThen<T>(\n action: () => Promise<T>,\n ): Promise<{ ok: true; value: T } | { ok: false; outcome: FlushOutcome }>;\n /** `setDefinition(def)` + an immediate save. */\n commit(def: Definition): Promise<FlushOutcome>;\n /** Refetch the shared query, replace the buffer and token, clear `stale` / `changedElsewhere`. */\n reload(): Promise<void>;\n}\n\ninterface AuthCtx {\n client: W6WClient;\n}\n\ninterface SaveCtx {\n client: W6WClient;\n kind: CallableDraftKind;\n id: string;\n token: string | null;\n explicit: boolean;\n}\n\ninterface Row {\n id: string;\n kind: CallableDraftKind;\n def: Definition | null;\n /** `JSON.stringify(def)` — the saver's dirty marker compares on text. */\n text: string;\n token: string | null;\n loaded: boolean;\n stale: boolean;\n changedElsewhere: boolean;\n /** Bytes the server refused — auto-save must not re-push them. */\n refused: string | null;\n lastError: unknown;\n inflight: Promise<void> | null;\n saver: AutoSaver;\n auth: AuthCtx | null;\n handover: boolean;\n /** Bumped whenever the buffer is replaced by a fresh read. */\n gen: number;\n discardReported: number;\n}\n\nfunction evaluate(\n def: Definition | null,\n id: string,\n saveGuard: UseCallableDraftOptions[\"saveGuard\"],\n): string | null {\n if (!def) return null;\n // `upsert(def)` writes under `def.id`; a different id would save somewhere the author did not mean.\n if (typeof def.id === \"string\" && def.id !== id) return \"The id cannot be changed here.\";\n return saveGuard ? (saveGuard(def) ?? null) : null;\n}\n\nexport function useCallableDraft(kind: CallableDraftKind, o: UseCallableDraftOptions) {\n const client = useEmbedClient();\n const registry = useDraftRegistry();\n const qc = useQueryClient();\n const { id, saveGuard } = o;\n const autoSave = o.autoSave ?? false;\n\n // The ONE cache entry (see the docblock): the same hook `useFunctionQuery` / `useEndpointQuery`\n // are built on, so there is no second fetch path to drift.\n const query = useCallableQuery(kind, id ?? \"\", id !== null);\n\n const [def, setDefState] = useState<Definition | null>(null);\n const [loadedId, setLoadedId] = useState<string | null>(null);\n const [saving, setSaving] = useState(false);\n const [stale, setStale] = useState(false);\n const [changedElsewhere, setChangedElsewhere] = useState(false);\n const [error, setError] = useState<unknown | null>(null);\n const [handingOver, setHandingOver] = useState(false);\n\n const optsRef = useRef(o);\n optsRef.current = o;\n const clientRef = useRef(client);\n clientRef.current = client;\n const qcRef = useRef(qc);\n qcRef.current = qc;\n const refetchRef = useRef(query.refetch);\n refetchRef.current = query.refetch;\n const kindRef = useRef(kind);\n kindRef.current = kind;\n const rowRef = useRef<Row | null>(null);\n const guardRef = useRef(saveGuard);\n\n if (id === null) rowRef.current = null;\n else if (rowRef.current?.id !== id || rowRef.current.kind !== kind) {\n const row: Row = {\n id,\n kind,\n def: null,\n text: \"\",\n token: null,\n loaded: false,\n stale: false,\n changedElsewhere: false,\n refused: null,\n lastError: null,\n inflight: null,\n saver: undefined as unknown as AutoSaver,\n auth: null,\n handover: false,\n gen: 0,\n discardReported: -1,\n };\n row.saver = createAutoSaver({\n save: (payload, ctx) => saveRow(row, payload, ctx as SaveCtx),\n });\n rowRef.current = row;\n }\n\n /** The coalescer's sink: ONE request, sent by the client captured at push time. */\n function saveRow(row: Row, payload: string, ctx: SaveCtx): Promise<void> {\n if (row.inflight) return Promise.resolve();\n const cur = optsRef.current;\n if (!ctx.explicit && cur.canAutoSave && !cur.canAutoSave()) return Promise.resolve();\n const isCurrent = () => rowRef.current === row;\n const gen = row.gen;\n const run = async (): Promise<void> => {\n const definition = JSON.parse(payload) as Definition;\n if (isCurrent()) {\n setSaving(true);\n setError(null);\n }\n try {\n const options = { ifUnmodifiedSince: ctx.token };\n const res =\n ctx.kind === \"function\"\n ? await ctx.client.console.functions.upsert(definition as never, options)\n : await ctx.client.console.endpoints.upsert(definition as never, options);\n // Advance the row's token BEFORE invalidating the cache, so the refetch this save causes\n // reads as \"equal\" and never as another writer. A buffer replaced meanwhile owns its token.\n if (gen === row.gen) row.token = nextSaveToken(ctx.token, res as { updatedAt?: unknown });\n invalidateSavedCallable(\n qcRef.current,\n callableListKey(ctx.kind),\n callableKey(ctx.kind, ctx.id),\n );\n if (gen !== row.gen) return;\n row.saver.markSaved(payload);\n row.refused = null;\n } catch (e) {\n if (gen === row.gen) {\n row.refused = payload;\n row.lastError = e;\n row.saver.cancel();\n if (isStaleWrite(e)) row.stale = true;\n if (isCurrent()) {\n if (row.stale) setStale(true);\n setError(e);\n }\n }\n throw e;\n }\n };\n const p = run();\n row.inflight = p;\n const clear = () => {\n if (row.inflight === p) row.inflight = null;\n if (isCurrent()) setSaving(false);\n };\n p.then(clear, clear);\n return p;\n }\n const saveRowRef = useRef(saveRow);\n saveRowRef.current = saveRow;\n\n /** Replace the row's buffer and token with a fresh read (the seed, a clean external change, reload). */\n const install = useCallback(\n (row: Row, rec: { definition: Definition; updatedAt: string | null }, auth: AuthCtx) => {\n row.gen++;\n row.auth = auth;\n row.def = rec.definition;\n row.text = JSON.stringify(rec.definition);\n row.token = rec.updatedAt;\n row.saver.cancel();\n // What we just read IS the server's copy: the editor opens clean.\n row.saver.markSaved(row.text);\n row.refused = null;\n row.stale = false;\n row.lastError = null;\n row.changedElsewhere = false;\n row.loaded = true;\n setDefState(rec.definition);\n setLoadedId(row.id);\n setStale(false);\n setChangedElsewhere(false);\n setError(null);\n },\n [],\n );\n\n const reportDiscard = useCallback((row: Row, outcome: FlushOutcome) => {\n if (outcome.status !== \"blocked\" && outcome.status !== \"failed\") return;\n if (row.discardReported === row.gen) return;\n row.discardReported = row.gen;\n try {\n optsRef.current.onDiscard?.({\n id: row.id,\n definition: row.def as Definition,\n reason: outcome.status,\n });\n } catch {\n // A host callback must not break the switch.\n }\n }, []);\n\n /** Settle a row's buffer; see `use-workflow-draft.ts`'s `flushRow` (same gates). Never rejects. */\n const flushRow = useCallback(\n async (row: Row, explicit: boolean, ignoreGates = false): Promise<FlushOutcome> => {\n try {\n let drained: { error: unknown } | null = null;\n while (row.inflight) {\n try {\n await row.inflight;\n } catch (e) {\n drained = { error: e };\n }\n }\n if (!row.loaded) return { status: \"blocked\", reason: \"The definition has not loaded.\" };\n const text = row.text;\n if (!row.saver.isDirty(text)) return { status: \"clean\" };\n if (drained && row.refused === text) return { status: \"failed\", error: drained.error };\n if (row.stale) return { status: \"failed\", error: row.lastError };\n const cur = optsRef.current;\n const blocked = evaluate(row.def, row.id, guardRef.current);\n if (blocked !== null) return { status: \"blocked\", reason: blocked };\n if (!explicit) {\n if (!ignoreGates && !(cur.autoSave ?? false)) {\n return { status: \"blocked\", reason: \"Auto-save is off.\" };\n }\n if (!ignoreGates && cur.canAutoSave && !cur.canAutoSave()) {\n return { status: \"blocked\", reason: \"The editor is busy.\" };\n }\n }\n const auth = row.auth as AuthCtx;\n const ctx: SaveCtx = {\n client: auth.client,\n kind: row.kind,\n id: row.id,\n token: row.token,\n explicit: explicit || ignoreGates,\n };\n row.saver.push(text, true, true, ctx);\n await row.saver.flush();\n return { status: \"saved\" };\n } catch (error) {\n return { status: \"failed\", error };\n }\n },\n [],\n );\n\n // ── row switch ────────────────────────────────────────────────────────────\n // Keyed on the row identity ONLY: a rebuilt client neither reloads nor cancels the pending entry.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `id`/`kind` are the trigger; the row is read from a ref\n useEffect(() => {\n const row = rowRef.current;\n // Idempotent for a PERSISTED row: StrictMode replays this effect against a row the seed has\n // already installed (and which the seed will not install again, its token being equal), so\n // state is derived from the row instead of nulled. A genuinely new row is unloaded ⇒ null.\n if (row?.loaded) {\n setDefState(row.def);\n setLoadedId(row.id);\n setError(row.refused !== null ? row.lastError : null);\n setStale(row.stale);\n setChangedElsewhere(row.changedElsewhere);\n setSaving(row.inflight !== null);\n } else {\n setDefState(null);\n setLoadedId(null);\n setError(null);\n setStale(false);\n setChangedElsewhere(false);\n setSaving(false);\n }\n if (!row) return;\n return () => {\n // The pending entry belongs to the row that produced it: flush it there, never drop it.\n void flushRow(row, false);\n row.saver.cancel();\n };\n }, [id, kind, flushRow]);\n\n // ── seed / external change ────────────────────────────────────────────────\n const record = useMemo(\n () => (id === null ? null : callableRecord(kind, query.data)),\n [id, kind, query.data],\n );\n // biome-ignore lint/correctness/useExhaustiveDependencies: `record` is derived from `query.data`; the row is read from a ref\n useEffect(() => {\n const row = rowRef.current;\n if (!row || !record || row.handover) return;\n if (!row.loaded) {\n install(row, record, { client: clientRef.current });\n return;\n }\n // Equal ⇒ no-op: our own save (token already advanced) or an unrelated refetch.\n if (record.updatedAt === row.token) return;\n if (!row.saver.isDirty(row.text)) {\n // CLEAN: replace buffer and token together.\n install(row, record, row.auth as AuthCtx);\n } else if (!row.changedElsewhere) {\n // DIRTY: keep buffer AND the old token (the next save must 409, never overwrite).\n row.changedElsewhere = true;\n setChangedElsewhere(true);\n }\n }, [query.data, record, id, kind, install]);\n\n // ── derived ───────────────────────────────────────────────────────────────\n const row = rowRef.current;\n const ctxDiffers = (a: AuthCtx | null) => a !== null && a.client !== client;\n const loaded = row?.loaded === true && loadedId === id;\n const buffer = loaded ? def : null;\n const text = useMemo(() => (buffer ? JSON.stringify(buffer) : \"\"), [buffer]);\n const saveBlockedReason = evaluate(buffer, id ?? \"\", saveGuard);\n if (!(loaded && ctxDiffers(row?.auth ?? null))) guardRef.current = saveGuard;\n const switching = handingOver || (loaded && ctxDiffers(row?.auth ?? null));\n const canSave = loaded && saveBlockedReason === null && !saving && !switching;\n const dirty = loaded && row?.saver.isDirty(text) === true;\n const policy = useMemo(\n () => (buffer ? policyFromDefinition(buffer as CallableDefinition) : {}),\n [buffer],\n );\n const loadError =\n !loaded && id !== null\n ? (query.error ??\n (query.isSuccess && record === null\n ? new Error(\"The definition could not be read.\")\n : null))\n : null;\n\n // ── auto-save push ────────────────────────────────────────────────────────\n // biome-ignore lint/correctness/useExhaustiveDependencies: `text` is the trigger; the row is read from a ref\n useEffect(() => {\n const r = rowRef.current;\n if (!r || !loaded || r.id !== id) return;\n // While a 409 or a \"changed elsewhere\" notice is on screen a push would only retry into it.\n if (stale || changedElsewhere) return;\n if (text === r.refused) return;\n if (r.handover || !r.auth || ctxDiffers(r.auth)) return;\n const ctx: SaveCtx = {\n client: r.auth.client,\n kind: r.kind,\n id: r.id,\n token: r.token,\n explicit: false,\n };\n r.saver.push(text, autoSave, canSave, ctx);\n }, [loaded, id, text, stale, changedElsewhere, autoSave, canSave, client]);\n\n // ── context handover ──────────────────────────────────────────────────────\n // biome-ignore lint/correctness/useExhaustiveDependencies: the row is read from a ref\n useEffect(() => {\n const r = rowRef.current;\n if (!r || !loaded || r.id !== id || r.handover) return;\n if (!ctxDiffers(r.auth)) return;\n r.handover = true;\n setHandingOver(true);\n void (async () => {\n try {\n // Same path as the registry's flushAll (so also regardless of `autoSave`); saved or\n // refused, the buffer is then dropped.\n reportDiscard(r, await flushRow(r, false, true));\n if (rowRef.current !== r) return;\n r.saver.cancel();\n const res = await refetchRef.current();\n if (rowRef.current !== r) return;\n const rec = res.isError ? null : callableRecord(r.kind, res.data);\n if (!rec) throw res.error ?? new Error(\"The definition could not be read.\");\n install(r, rec, { client: clientRef.current });\n } catch (e) {\n if (rowRef.current === r) {\n r.loaded = false;\n setLoadedId(null);\n setError(e);\n }\n } finally {\n r.handover = false;\n if (rowRef.current === r) setHandingOver(false);\n }\n })();\n }, [loaded, id, client, handingOver, flushRow, reportDiscard, install]);\n\n // ── flush on hide / registry ──────────────────────────────────────────────\n // biome-ignore lint/correctness/useExhaustiveDependencies: `id`/`kind` are the trigger; the row is read from a ref\n useEffect(() => {\n const r = rowRef.current;\n if (!r) return;\n const w = (globalThis as { window?: Window }).window;\n const d = (globalThis as { document?: Document }).document;\n const offHide =\n w && d\n ? registerFlushOnHide(w, d, () => {\n void flushRow(r, false);\n })\n : undefined;\n // `flushAll` saves regardless of `autoSave` and the busy probe, and reports what it dropped.\n const unregister = registry?.register(async () => {\n const outcome = await flushRow(r, false, true);\n reportDiscard(r, outcome);\n return outcome;\n });\n return () => {\n offHide?.();\n unregister?.();\n };\n }, [id, kind, registry, flushRow, reportDiscard]);\n\n // ── stable actions ────────────────────────────────────────────────────────\n const setDefinition = useCallback((next: Definition | ((prev: Definition) => Definition)) => {\n const r = rowRef.current;\n if (!r || !r.loaded || !r.def) return;\n const value = typeof next === \"function\" ? next(r.def) : next;\n r.def = value;\n r.text = JSON.stringify(value);\n setDefState(value);\n }, []);\n const flush = useCallback((): Promise<FlushOutcome> => {\n const r = rowRef.current;\n return r ? flushRow(r, true) : Promise.resolve({ status: \"clean\" });\n }, [flushRow]);\n const saveNow = useCallback(() => {\n void flush();\n }, [flush]);\n const flushThen = useCallback(\n async <T>(action: () => Promise<T>) => {\n const outcome = await flush();\n if (outcome.status === \"clean\" || outcome.status === \"saved\") {\n return { ok: true as const, value: await action() };\n }\n return { ok: false as const, outcome };\n },\n [flush],\n );\n const commit = useCallback(\n (next: Definition): Promise<FlushOutcome> => {\n setDefinition(next);\n return flush();\n },\n [setDefinition, flush],\n );\n // Reads the CURRENT buffer through the row (a ref), never a render's closure: pending editor\n // edits ride along. Stable, because `useWorkspace` drops functions from its publish key.\n const onPolicyChange = useCallback(\n (next: CallablePolicy) => {\n const r = rowRef.current;\n if (!r || !r.loaded || !r.def) return;\n void commit(definitionWithPolicy(r.def as CallableDefinition, next) as Definition);\n },\n [commit],\n );\n const reload = useCallback(async () => {\n const r = rowRef.current;\n if (!r) return;\n try {\n const res = await refetchRef.current();\n if (rowRef.current !== r) return;\n const rec = res.isError ? null : callableRecord(r.kind, res.data);\n if (!rec) {\n setError(res.error ?? new Error(\"The definition could not be read.\"));\n return;\n }\n install(r, rec, { client: clientRef.current });\n } catch (e) {\n if (rowRef.current === r) setError(e);\n }\n }, [install]);\n\n const draft: CallableDraft = {\n definition: buffer,\n setDefinition,\n policy,\n onPolicyChange,\n loading: id !== null && !loaded && loadError === null,\n loadError,\n dirty,\n saving,\n canSave,\n saveBlockedReason,\n stale,\n changedElsewhere,\n error,\n saveNow,\n flush,\n flushThen,\n commit,\n reload,\n };\n return draft;\n}\n\n/** {@link useCallableDraft} bound to a Function. */\nexport function useFunctionDraft(o: UseCallableDraftOptions): CallableDraft {\n return useCallableDraft(\"function\", o);\n}\n\n/** {@link useCallableDraft} bound to an Endpoint. */\nexport function useEndpointDraft(o: UseCallableDraftOptions): CallableDraft {\n return useCallableDraft(\"endpoint\", o);\n}\n"],"names":["evaluate","def","id","saveGuard","useCallableDraft","kind","o","client","useEmbedClient","registry","useDraftRegistry","qc","useQueryClient","autoSave","query","useCallableQuery","setDefState","useState","loadedId","setLoadedId","saving","setSaving","stale","setStale","changedElsewhere","setChangedElsewhere","error","setError","handingOver","setHandingOver","optsRef","useRef","clientRef","qcRef","refetchRef","kindRef","rowRef","guardRef","_a","row","createAutoSaver","payload","ctx","saveRow","cur","isCurrent","gen","p","definition","options","res","nextSaveToken","invalidateSavedCallable","callableListKey","callableKey","e","isStaleWrite","clear","saveRowRef","install","useCallback","rec","auth","reportDiscard","outcome","_b","flushRow","explicit","ignoreGates","drained","text","blocked","useEffect","record","useMemo","callableRecord","ctxDiffers","a","loaded","buffer","saveBlockedReason","switching","canSave","dirty","policy","policyFromDefinition","loadError","r","w","d","offHide","registerFlushOnHide","unregister","setDefinition","next","value","flush","saveNow","flushThen","action","commit","onPolicyChange","definitionWithPolicy","reload","useFunctionDraft","useEndpointDraft"],"mappings":";;;;;;;AAmKA,SAASA,GACPC,GACAC,GACAC,GACe;AACf,SAAKF,IAED,OAAOA,EAAI,MAAO,YAAYA,EAAI,OAAOC,IAAW,mCACjDC,IAAaA,EAAUF,CAAG,KAAK,OAAQ,OAH7B;AAInB;AAEO,SAASG,GAAiBC,GAAyBC,GAA4B;;AACpF,QAAMC,IAASC,GAAA,GACTC,IAAWC,GAAA,GACXC,IAAKC,GAAA,GACL,EAAE,IAAAV,GAAI,WAAAC,EAAA,IAAcG,GACpBO,IAAWP,EAAE,YAAY,IAIzBQ,IAAQC,GAAiBV,GAAMH,KAAM,IAAIA,M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EAAA;AAGJ;AAGO,SAASC,GAAiBlG,GAA2C;AAC1E,SAAOF,GAAiB,YAAYE,CAAC;AACvC;AAGO,SAASmG,GAAiBnG,GAA2C;AAC1E,SAAOF,GAAiB,YAAYE,CAAC;AACvC;"}
|
|
1
|
+
{"version":3,"file":"use-callable-draft-DjW7_9qb.js","sources":["../src/draft/use-callable-draft.ts"],"sourcesContent":["/**\n * `useCallableDraft` — the headless draft behind a Function / Endpoint editor: the editable\n * definition as FIELD state (an object, not text), seeded from the ONE react-query entry every\n * other writer invalidates, saved with the stale-write token, and never silently overwriting — or\n * overwritten by — another writer. `useFunctionDraft` / `useEndpointDraft` bind the kind.\n * Mirrors `use-workflow-draft.ts` (same saver, registry, flush-on-hide, no queue, no retry); that\n * file is not edited and the two do not share a runtime beyond `createAutoSaver` & co.\n *\n * ## One cache\n *\n * The buffer is seeded from `useCallableQuery(kind, id)` — the same key and queryFn as\n * `useFunctionQuery` / `useEndpointQuery`. There is no second `useQuery` and no direct\n * `console.*.get` here, so a rail save, a revert, or this draft's own save all land in the entry\n * the draft reads. `reload()` is that query's `refetch()`, then the buffer and token are replaced.\n * The record split (definition vs. `updatedAt` token) is `lib/callable-record.ts`'s `callableRecord`.\n *\n * ## External change (another writer)\n *\n * An external change is a cache update whose `callableRecord(...).updatedAt` differs from the\n * row's CURRENT token:\n *\n * - CLEAN buffer ⇒ the buffer and token are replaced from the cache (no `reload()`, no extra GET).\n * - DIRTY buffer ⇒ the buffer AND the old token are KEPT and `changedElsewhere` becomes true.\n * Adopting the new token without replacing the buffer would be the silent overwrite, so the\n * token only moves with the buffer. The next save therefore still carries the old token and the\n * server answers `409 *_stale`; `reload()` is the way out. Nothing is ever merged — a field-level\n * merge is deliberately not offered (ruling BC-stale).\n * - EQUAL ⇒ no-op. The row's token is advanced from the save response (`nextSaveToken`) BEFORE the\n * save invalidates the cache, so this draft's own save never reads as external — including an\n * edit typed while that save was in flight.\n *\n * ## The trust boundary (why the state is per ROW, not per hook)\n *\n * As the workflow draft: a pending save must be sent by the client that AUTHORED the buffer, even\n * if the host has swapped its client or moved to another resource. Each row holds `auth` (the\n * client the buffer was loaded as) and EVERY save path (debounce, `flush`, `flushThen`,\n * unmount, registry, hide) sends with it, never with the current render's. When the render's\n * client stops matching, the row hands over: one save of a dirty buffer on the authoring client,\n * then the buffer is discarded and re-seeded (the query's `refetch()`) under the new client;\n * `canSave` is false and pushes are ignored meanwhile. One `Row` per `kind:id`; a late completion\n * of an old row's save updates that old row only; `gen` is bumped whenever the buffer is replaced,\n * and a save completing from an older generation never touches the new buffer's token or clean\n * marker. No project is involved (a Function / Endpoint save carries none).\n *\n * `autoSave` defaults to FALSE (Studio saves these explicitly): `flushAll` on the draft registry\n * saves regardless of `autoSave`; hide / unmount honour it. Deliberately absent: retry, a save\n * queue — a 409 is surfaced (`stale`, `error.code`) and never retried.\n *\n * `onPolicyChange(next)` is referentially stable (it reads the buffer through a ref, because\n * `useWorkspace` keys on `JSON.stringify`, which drops functions) and saves\n * `definitionWithPolicy(<current buffer>, next)` immediately — `commit` semantics: any pending\n * editor edits ride along in that same save.\n */\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { W6WClient } from \"@w6w/sdk\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { callableKey } from \"../lib/callable-kind.ts\";\nimport { callableRecord } from \"../lib/callable-record.ts\";\nimport { invalidateSavedCallable } from \"../lib/save-invalidation.ts\";\nimport {\n type CallableDefinition,\n type CallablePolicy,\n definitionWithPolicy,\n policyFromDefinition,\n} from \"../lib/settings-rail.ts\";\nimport { callableListKey, useCallableQuery } from \"../repos/callables.ts\";\nimport { registerFlushOnHide } from \"./autosave-flush.ts\";\nimport { type AutoSaver, createAutoSaver } from \"./autosave.ts\";\nimport { useEmbedClient } from \"./client-context.ts\";\nimport { useDraftRegistry } from \"./draft-registry.ts\";\nimport type { FlushOutcome } from \"./use-workflow-draft.ts\";\nimport { isStaleWrite, nextSaveToken } from \"./workflow-save.ts\";\n\nexport type CallableDraftKind = \"function\" | \"endpoint\";\ntype Definition = Record<string, unknown>;\n\nexport interface UseCallableDraftOptions {\n /** `null` ⇒ idle (the hook stays mounted above an early return). */\n id: string | null;\n /** Default FALSE: nothing is sent until `saveNow()` / `flush()` / `commit()`. */\n autoSave?: boolean;\n /** Injected busy probe. Gates AUTOMATIC saves only. */\n canAutoSave?: () => boolean;\n /** Injected edit guard: a reason blocks saving. */\n saveGuard?: (definition: Definition) => string | null;\n /**\n * Called once when a handover or an identity switch (`flushAll`) drops a dirty buffer it could\n * not save. `blocked`: refused before a request; `failed`: the request failed or the row was\n * stale. No UI here.\n */\n onDiscard?: (info: {\n id: string;\n definition: Definition;\n reason: \"blocked\" | \"failed\";\n }) => void;\n}\n\nexport interface CallableDraft {\n /** The editable definition (no `valid` / `updatedAt`); `null` until loaded. */\n definition: Definition | null;\n setDefinition(next: Definition | ((prev: Definition) => Definition)): void;\n /** `{retry, onError, reroute}` read off the buffer. */\n policy: CallablePolicy;\n /** Referentially stable. Saves `definitionWithPolicy(buffer, next)` now. */\n onPolicyChange(policy: CallablePolicy): void;\n loading: boolean;\n loadError: unknown | null;\n dirty: boolean;\n saving: boolean;\n canSave: boolean;\n saveBlockedReason: string | null;\n /** The last save was refused as stale (`function_stale` / `endpoint_stale`). */\n stale: boolean;\n /** Another writer changed the resource while this buffer is dirty. Never merged. */\n changedElsewhere: boolean;\n error: unknown | null;\n /** Push + fire now. */\n saveNow(): void;\n flush(): Promise<FlushOutcome>;\n /** Flush, then run `action` only when the buffer is clean or just saved. */\n flushThen<T>(\n action: () => Promise<T>,\n ): Promise<{ ok: true; value: T } | { ok: false; outcome: FlushOutcome }>;\n /** `setDefinition(def)` + an immediate save. */\n commit(def: Definition): Promise<FlushOutcome>;\n /** Refetch the shared query, replace the buffer and token, clear `stale` / `changedElsewhere`. */\n reload(): Promise<void>;\n}\n\ninterface AuthCtx {\n client: W6WClient;\n}\n\ninterface SaveCtx {\n client: W6WClient;\n kind: CallableDraftKind;\n id: string;\n token: string | null;\n explicit: boolean;\n}\n\ninterface Row {\n id: string;\n kind: CallableDraftKind;\n def: Definition | null;\n /** `JSON.stringify(def)` — the saver's dirty marker compares on text. */\n text: string;\n token: string | null;\n loaded: boolean;\n stale: boolean;\n changedElsewhere: boolean;\n /** Bytes the server refused — auto-save must not re-push them. */\n refused: string | null;\n lastError: unknown;\n inflight: Promise<void> | null;\n saver: AutoSaver;\n auth: AuthCtx | null;\n handover: boolean;\n /** Bumped whenever the buffer is replaced by a fresh read. */\n gen: number;\n discardReported: number;\n}\n\nfunction evaluate(\n def: Definition | null,\n id: string,\n saveGuard: UseCallableDraftOptions[\"saveGuard\"],\n): string | null {\n if (!def) return null;\n // `upsert(def)` writes under `def.id`; a different id would save somewhere the author did not mean.\n if (typeof def.id === \"string\" && def.id !== id) return \"The id cannot be changed here.\";\n return saveGuard ? (saveGuard(def) ?? null) : null;\n}\n\nexport function useCallableDraft(kind: CallableDraftKind, o: UseCallableDraftOptions) {\n const client = useEmbedClient();\n const registry = useDraftRegistry();\n const qc = useQueryClient();\n const { id, saveGuard } = o;\n const autoSave = o.autoSave ?? false;\n\n // The ONE cache entry (see the docblock): the same hook `useFunctionQuery` / `useEndpointQuery`\n // are built on, so there is no second fetch path to drift.\n const query = useCallableQuery(kind, id ?? \"\", id !== null);\n\n const [def, setDefState] = useState<Definition | null>(null);\n const [loadedId, setLoadedId] = useState<string | null>(null);\n const [saving, setSaving] = useState(false);\n const [stale, setStale] = useState(false);\n const [changedElsewhere, setChangedElsewhere] = useState(false);\n const [error, setError] = useState<unknown | null>(null);\n const [handingOver, setHandingOver] = useState(false);\n\n const optsRef = useRef(o);\n optsRef.current = o;\n const clientRef = useRef(client);\n clientRef.current = client;\n const qcRef = useRef(qc);\n qcRef.current = qc;\n const refetchRef = useRef(query.refetch);\n refetchRef.current = query.refetch;\n const kindRef = useRef(kind);\n kindRef.current = kind;\n const rowRef = useRef<Row | null>(null);\n const guardRef = useRef(saveGuard);\n\n if (id === null) rowRef.current = null;\n else if (rowRef.current?.id !== id || rowRef.current.kind !== kind) {\n const row: Row = {\n id,\n kind,\n def: null,\n text: \"\",\n token: null,\n loaded: false,\n stale: false,\n changedElsewhere: false,\n refused: null,\n lastError: null,\n inflight: null,\n saver: undefined as unknown as AutoSaver,\n auth: null,\n handover: false,\n gen: 0,\n discardReported: -1,\n };\n row.saver = createAutoSaver({\n save: (payload, ctx) => saveRow(row, payload, ctx as SaveCtx),\n });\n rowRef.current = row;\n }\n\n /** The coalescer's sink: ONE request, sent by the client captured at push time. */\n function saveRow(row: Row, payload: string, ctx: SaveCtx): Promise<void> {\n if (row.inflight) return Promise.resolve();\n const cur = optsRef.current;\n if (!ctx.explicit && cur.canAutoSave && !cur.canAutoSave()) return Promise.resolve();\n const isCurrent = () => rowRef.current === row;\n const gen = row.gen;\n const run = async (): Promise<void> => {\n const definition = JSON.parse(payload) as Definition;\n if (isCurrent()) {\n setSaving(true);\n setError(null);\n }\n try {\n const options = { ifUnmodifiedSince: ctx.token };\n const res =\n ctx.kind === \"function\"\n ? await ctx.client.console.functions.upsert(definition as never, options)\n : await ctx.client.console.endpoints.upsert(definition as never, options);\n // Advance the row's token BEFORE invalidating the cache, so the refetch this save causes\n // reads as \"equal\" and never as another writer. A buffer replaced meanwhile owns its token.\n if (gen === row.gen) row.token = nextSaveToken(ctx.token, res as { updatedAt?: unknown });\n invalidateSavedCallable(\n qcRef.current,\n callableListKey(ctx.kind),\n callableKey(ctx.kind, ctx.id),\n );\n if (gen !== row.gen) return;\n row.saver.markSaved(payload);\n row.refused = null;\n } catch (e) {\n if (gen === row.gen) {\n row.refused = payload;\n row.lastError = e;\n row.saver.cancel();\n if (isStaleWrite(e)) row.stale = true;\n if (isCurrent()) {\n if (row.stale) setStale(true);\n setError(e);\n }\n }\n throw e;\n }\n };\n const p = run();\n row.inflight = p;\n const clear = () => {\n if (row.inflight === p) row.inflight = null;\n if (isCurrent()) setSaving(false);\n };\n p.then(clear, clear);\n return p;\n }\n const saveRowRef = useRef(saveRow);\n saveRowRef.current = saveRow;\n\n /** Replace the row's buffer and token with a fresh read (the seed, a clean external change, reload). */\n const install = useCallback(\n (row: Row, rec: { definition: Definition; updatedAt: string | null }, auth: AuthCtx) => {\n row.gen++;\n row.auth = auth;\n row.def = rec.definition;\n row.text = JSON.stringify(rec.definition);\n row.token = rec.updatedAt;\n row.saver.cancel();\n // What we just read IS the server's copy: the editor opens clean.\n row.saver.markSaved(row.text);\n row.refused = null;\n row.stale = false;\n row.lastError = null;\n row.changedElsewhere = false;\n row.loaded = true;\n setDefState(rec.definition);\n setLoadedId(row.id);\n setStale(false);\n setChangedElsewhere(false);\n setError(null);\n },\n [],\n );\n\n const reportDiscard = useCallback((row: Row, outcome: FlushOutcome) => {\n if (outcome.status !== \"blocked\" && outcome.status !== \"failed\") return;\n if (row.discardReported === row.gen) return;\n row.discardReported = row.gen;\n try {\n optsRef.current.onDiscard?.({\n id: row.id,\n definition: row.def as Definition,\n reason: outcome.status,\n });\n } catch {\n // A host callback must not break the switch.\n }\n }, []);\n\n /** Settle a row's buffer; see `use-workflow-draft.ts`'s `flushRow` (same gates). Never rejects. */\n const flushRow = useCallback(\n async (row: Row, explicit: boolean, ignoreGates = false): Promise<FlushOutcome> => {\n try {\n let drained: { error: unknown } | null = null;\n while (row.inflight) {\n try {\n await row.inflight;\n } catch (e) {\n drained = { error: e };\n }\n }\n if (!row.loaded) return { status: \"blocked\", reason: \"The definition has not loaded.\" };\n const text = row.text;\n if (!row.saver.isDirty(text)) return { status: \"clean\" };\n if (drained && row.refused === text) return { status: \"failed\", error: drained.error };\n if (row.stale) return { status: \"failed\", error: row.lastError };\n const cur = optsRef.current;\n const blocked = evaluate(row.def, row.id, guardRef.current);\n if (blocked !== null) return { status: \"blocked\", reason: blocked };\n if (!explicit) {\n if (!ignoreGates && !(cur.autoSave ?? false)) {\n return { status: \"blocked\", reason: \"Auto-save is off.\" };\n }\n if (!ignoreGates && cur.canAutoSave && !cur.canAutoSave()) {\n return { status: \"blocked\", reason: \"The editor is busy.\" };\n }\n }\n const auth = row.auth as AuthCtx;\n const ctx: SaveCtx = {\n client: auth.client,\n kind: row.kind,\n id: row.id,\n token: row.token,\n explicit: explicit || ignoreGates,\n };\n row.saver.push(text, true, true, ctx);\n await row.saver.flush();\n return { status: \"saved\" };\n } catch (error) {\n return { status: \"failed\", error };\n }\n },\n [],\n );\n\n // ── row switch ────────────────────────────────────────────────────────────\n // Keyed on the row identity ONLY: a rebuilt client neither reloads nor cancels the pending entry.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `id`/`kind` are the trigger; the row is read from a ref\n useEffect(() => {\n const row = rowRef.current;\n // Idempotent for a PERSISTED row: StrictMode replays this effect against a row the seed has\n // already installed (and which the seed will not install again, its token being equal), so\n // state is derived from the row instead of nulled. A genuinely new row is unloaded ⇒ null.\n if (row?.loaded) {\n setDefState(row.def);\n setLoadedId(row.id);\n setError(row.refused !== null ? row.lastError : null);\n setStale(row.stale);\n setChangedElsewhere(row.changedElsewhere);\n setSaving(row.inflight !== null);\n } else {\n setDefState(null);\n setLoadedId(null);\n setError(null);\n setStale(false);\n setChangedElsewhere(false);\n setSaving(false);\n }\n if (!row) return;\n return () => {\n // The pending entry belongs to the row that produced it: flush it there, never drop it.\n void flushRow(row, false);\n row.saver.cancel();\n };\n }, [id, kind, flushRow]);\n\n // ── seed / external change ────────────────────────────────────────────────\n const record = useMemo(\n () => (id === null ? null : callableRecord(kind, query.data)),\n [id, kind, query.data],\n );\n // biome-ignore lint/correctness/useExhaustiveDependencies: `record` is derived from `query.data`; the row is read from a ref\n useEffect(() => {\n const row = rowRef.current;\n if (!row || !record || row.handover) return;\n if (!row.loaded) {\n install(row, record, { client: clientRef.current });\n return;\n }\n // Equal ⇒ no-op: our own save (token already advanced) or an unrelated refetch.\n if (record.updatedAt === row.token) return;\n if (!row.saver.isDirty(row.text)) {\n // CLEAN: replace buffer and token together.\n install(row, record, row.auth as AuthCtx);\n } else if (!row.changedElsewhere) {\n // DIRTY: keep buffer AND the old token (the next save must 409, never overwrite).\n row.changedElsewhere = true;\n setChangedElsewhere(true);\n }\n }, [query.data, record, id, kind, install]);\n\n // ── derived ───────────────────────────────────────────────────────────────\n const row = rowRef.current;\n const ctxDiffers = (a: AuthCtx | null) => a !== null && a.client !== client;\n const loaded = row?.loaded === true && loadedId === id;\n const buffer = loaded ? def : null;\n const text = useMemo(() => (buffer ? JSON.stringify(buffer) : \"\"), [buffer]);\n const saveBlockedReason = evaluate(buffer, id ?? \"\", saveGuard);\n if (!(loaded && ctxDiffers(row?.auth ?? null))) guardRef.current = saveGuard;\n const switching = handingOver || (loaded && ctxDiffers(row?.auth ?? null));\n const canSave = loaded && saveBlockedReason === null && !saving && !switching;\n const dirty = loaded && row?.saver.isDirty(text) === true;\n const policy = useMemo(\n () => (buffer ? policyFromDefinition(buffer as CallableDefinition) : {}),\n [buffer],\n );\n const loadError =\n !loaded && id !== null\n ? (query.error ??\n (query.isSuccess && record === null\n ? new Error(\"The definition could not be read.\")\n : null))\n : null;\n\n // ── auto-save push ────────────────────────────────────────────────────────\n // biome-ignore lint/correctness/useExhaustiveDependencies: `text` is the trigger; the row is read from a ref\n useEffect(() => {\n const r = rowRef.current;\n if (!r || !loaded || r.id !== id) return;\n // While a 409 or a \"changed elsewhere\" notice is on screen a push would only retry into it.\n if (stale || changedElsewhere) return;\n if (text === r.refused) return;\n if (r.handover || !r.auth || ctxDiffers(r.auth)) return;\n const ctx: SaveCtx = {\n client: r.auth.client,\n kind: r.kind,\n id: r.id,\n token: r.token,\n explicit: false,\n };\n r.saver.push(text, autoSave, canSave, ctx);\n }, [loaded, id, text, stale, changedElsewhere, autoSave, canSave, client]);\n\n // ── context handover ──────────────────────────────────────────────────────\n // biome-ignore lint/correctness/useExhaustiveDependencies: the row is read from a ref\n useEffect(() => {\n const r = rowRef.current;\n if (!r || !loaded || r.id !== id || r.handover) return;\n if (!ctxDiffers(r.auth)) return;\n r.handover = true;\n setHandingOver(true);\n void (async () => {\n try {\n // Same path as the registry's flushAll (so also regardless of `autoSave`); saved or\n // refused, the buffer is then dropped.\n reportDiscard(r, await flushRow(r, false, true));\n if (rowRef.current !== r) return;\n r.saver.cancel();\n const res = await refetchRef.current();\n if (rowRef.current !== r) return;\n const rec = res.isError ? null : callableRecord(r.kind, res.data);\n if (!rec) throw res.error ?? new Error(\"The definition could not be read.\");\n install(r, rec, { client: clientRef.current });\n } catch (e) {\n if (rowRef.current === r) {\n r.loaded = false;\n setLoadedId(null);\n setError(e);\n }\n } finally {\n r.handover = false;\n if (rowRef.current === r) setHandingOver(false);\n }\n })();\n }, [loaded, id, client, handingOver, flushRow, reportDiscard, install]);\n\n // ── flush on hide / registry ──────────────────────────────────────────────\n // biome-ignore lint/correctness/useExhaustiveDependencies: `id`/`kind` are the trigger; the row is read from a ref\n useEffect(() => {\n const r = rowRef.current;\n if (!r) return;\n const w = (globalThis as { window?: Window }).window;\n const d = (globalThis as { document?: Document }).document;\n const offHide =\n w && d\n ? registerFlushOnHide(w, d, () => {\n void flushRow(r, false);\n })\n : undefined;\n // `flushAll` saves regardless of `autoSave` and the busy probe, and reports what it dropped.\n const unregister = registry?.register(async () => {\n const outcome = await flushRow(r, false, true);\n reportDiscard(r, outcome);\n return outcome;\n });\n return () => {\n offHide?.();\n unregister?.();\n };\n }, [id, kind, registry, flushRow, reportDiscard]);\n\n // ── stable actions ────────────────────────────────────────────────────────\n const setDefinition = useCallback((next: Definition | ((prev: Definition) => Definition)) => {\n const r = rowRef.current;\n if (!r || !r.loaded || !r.def) return;\n const value = typeof next === \"function\" ? next(r.def) : next;\n r.def = value;\n r.text = JSON.stringify(value);\n setDefState(value);\n }, []);\n const flush = useCallback((): Promise<FlushOutcome> => {\n const r = rowRef.current;\n return r ? flushRow(r, true) : Promise.resolve({ status: \"clean\" });\n }, [flushRow]);\n const saveNow = useCallback(() => {\n void flush();\n }, [flush]);\n const flushThen = useCallback(\n async <T>(action: () => Promise<T>) => {\n const outcome = await flush();\n if (outcome.status === \"clean\" || outcome.status === \"saved\") {\n return { ok: true as const, value: await action() };\n }\n return { ok: false as const, outcome };\n },\n [flush],\n );\n const commit = useCallback(\n (next: Definition): Promise<FlushOutcome> => {\n setDefinition(next);\n return flush();\n },\n [setDefinition, flush],\n );\n // Reads the CURRENT buffer through the row (a ref), never a render's closure: pending editor\n // edits ride along. Stable, because `useWorkspace` drops functions from its publish key.\n const onPolicyChange = useCallback(\n (next: CallablePolicy) => {\n const r = rowRef.current;\n if (!r || !r.loaded || !r.def) return;\n void commit(definitionWithPolicy(r.def as CallableDefinition, next) as Definition);\n },\n [commit],\n );\n const reload = useCallback(async () => {\n const r = rowRef.current;\n if (!r) return;\n try {\n const res = await refetchRef.current();\n if (rowRef.current !== r) return;\n const rec = res.isError ? null : callableRecord(r.kind, res.data);\n if (!rec) {\n setError(res.error ?? new Error(\"The definition could not be read.\"));\n return;\n }\n install(r, rec, { client: clientRef.current });\n } catch (e) {\n if (rowRef.current === r) setError(e);\n }\n }, [install]);\n\n const draft: CallableDraft = {\n definition: buffer,\n setDefinition,\n policy,\n onPolicyChange,\n loading: id !== null && !loaded && loadError === null,\n loadError,\n dirty,\n saving,\n canSave,\n saveBlockedReason,\n stale,\n changedElsewhere,\n error,\n saveNow,\n flush,\n flushThen,\n commit,\n reload,\n };\n return draft;\n}\n\n/** {@link useCallableDraft} bound to a Function. */\nexport function useFunctionDraft(o: UseCallableDraftOptions): CallableDraft {\n return useCallableDraft(\"function\", o);\n}\n\n/** {@link useCallableDraft} bound to an Endpoint. */\nexport function useEndpointDraft(o: UseCallableDraftOptions): CallableDraft {\n return useCallableDraft(\"endpoint\", o);\n}\n"],"names":["evaluate","def","id","saveGuard","useCallableDraft","kind","o","client","useEmbedClient","registry","useDraftRegistry","qc","useQueryClient","autoSave","query","useCallableQuery","setDefState","useState","loadedId","setLoadedId","saving","setSaving","stale","setStale","changedElsewhere","setChangedElsewhere","error","setError","handingOver","setHandingOver","optsRef","useRef","clientRef","qcRef","refetchRef","kindRef","rowRef","guardRef","_a","row","createAutoSaver","payload","ctx","saveRow","cur","isCurrent","gen","p","definition","options","res","nextSaveToken","invalidateSavedCallable","callableListKey","callableKey","e","isStaleWrite","clear","saveRowRef","install","useCallback","rec","auth","reportDiscard","outcome","_b","flushRow","explicit","ignoreGates","drained","text","blocked","useEffect","record","useMemo","callableRecord","ctxDiffers","a","loaded","buffer","saveBlockedReason","switching","canSave","dirty","policy","policyFromDefinition","loadError","r","w","d","offHide","registerFlushOnHide","unregister","setDefinition","next","value","flush","saveNow","flushThen","action","commit","onPolicyChange","definitionWithPolicy","reload","useFunctionDraft","useEndpointDraft"],"mappings":";;;;;;;;AAmKA,SAASA,GACPC,GACAC,GACAC,GACe;AACf,SAAKF,IAED,OAAOA,EAAI,MAAO,YAAYA,EAAI,OAAOC,IAAW,mCACjDC,IAAaA,EAAUF,CAAG,KAAK,OAAQ,OAH7B;AAInB;AAEO,SAASG,GAAiBC,GAAyBC,GAA4B;;AACpF,QAAMC,IAASC,GAAA,GACTC,IAAWC,GAAA,GACXC,IAAKC,GAAA,GACL,EAAE,IAAAV,GAAI,WAAAC,EAAA,IAAcG,GACpBO,IAAWP,EAAE,YAAY,IAIzBQ,IAAQC,GAAiBV,GAAMH,KAAM,IAAIA,MAAO,IAAI,GAEpD,CAACD,IAAKe,CAAW,IAAIC,EAA4B,IAAI,GACrD,CAACC,IAAUC,CAAW,IAAIF,EAAwB,IAAI,GACtD,CAACG,GAAQC,CAAS,IAAIJ,EAAS,EAAK,GACpC,CAACK,GAAOC,CAAQ,IAAIN,EAAS,EAAK,GAClC,CAACO,GAAkBC,CAAmB,IAAIR,EAAS,EAAK,GACxD,CAACS,IAAOC,CAAQ,IAAIV,EAAyB,IAAI,GACjD,CAACW,GAAaC,EAAc,IAAIZ,EAAS,EAAK,GAE9Ca,IAAUC,EAAOzB,CAAC;AACxB,EAAAwB,EAAQ,UAAUxB;AAClB,QAAM0B,IAAYD,EAAOxB,CAAM;AAC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AAC7B,YAAIE,EAAO,YAAYmD,EAAG;AAC1B,cAAM1B,IAAMX,EAAI,UAAU,OAAOyB,EAAeY,EAAE,MAAMrC,EAAI,IAAI;AAChE,YAAI,CAACW,GAAK;AACR,UAAAlC,EAASuB,EAAI,SAAS,IAAI,MAAM,mCAAmC,CAAC;AACpE;AAAA,QACF;AACA,QAAAS,EAAQ4B,GAAG1B,GAAK,EAAE,QAAQ7B,EAAU,SAAS;AAAA,MAC/C,SAASuB,GAAG;AACV,QAAInB,EAAO,YAAYmD,KAAG5D,EAAS4B,CAAC;AAAA,MACtC;AAAA,EACF,GAAG,CAACI,CAAO,CAAC;AAsBZ,SApB6B;AAAA,IAC3B,YAAYoB;AAAA,IACZ,eAAAc;AAAA,IACA,QAAAT;AAAA,IACA,gBAAAiB;AAAA,IACA,SAASnG,MAAO,QAAQ,CAAC4E,KAAUQ,OAAc;AAAA,IACjD,WAAAA;AAAA,IACA,OAAAH;AAAA,IACA,QAAA/D;AAAA,IACA,SAAA8D;AAAA,IACA,mBAAAF;AAAA,IACA,OAAA1D;AAAA,IACA,kBAAAE;AAAA,IACA,OAAAE;AAAA,IACA,SAAAuE;AAAA,IACA,OAAAD;AAAA,IACA,WAAAE;AAAA,IACA,QAAAE;AAAA,IACA,QAAAG;AAAA,EAAA;AAGJ;AAGO,SAASC,GAAiBlG,GAA2C;AAC1E,SAAOF,GAAiB,YAAYE,CAAC;AACvC;AAGO,SAASmG,GAAiBnG,GAA2C;AAC1E,SAAOF,GAAiB,YAAYE,CAAC;AACvC;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@w6w/embed",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.31",
|
|
4
4
|
"description": "Embed w6w's managed editor and providers in a host React app.",
|
|
5
5
|
"license": "FSL-1.1-ALv2",
|
|
6
6
|
"repository": {
|
|
@@ -75,8 +75,8 @@
|
|
|
75
75
|
"@tanstack/react-query": "^5.62.7",
|
|
76
76
|
"@w6w/react": "^0.12.1",
|
|
77
77
|
"@w6w/sdk": "^0.12.1",
|
|
78
|
-
"@w6w/expr": "^0.1.
|
|
79
|
-
"@w6w/ui": "^0.2.
|
|
78
|
+
"@w6w/expr": "^0.1.6",
|
|
79
|
+
"@w6w/ui": "^0.2.67",
|
|
80
80
|
"yaml": "^2.4.2"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|