@w6w/embed 0.2.34 → 0.2.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{CreateFunctionModal-glk2zg1r.js → CreateFunctionModal-CYNHJUGJ.js} +3 -3
  2. package/dist/{CreateFunctionModal-glk2zg1r.js.map → CreateFunctionModal-CYNHJUGJ.js.map} +1 -1
  3. package/dist/{DocumentFormModal-B3OkvI5v.js → DocumentFormModal-CLmdGx34.js} +2 -2
  4. package/dist/{DocumentFormModal-B3OkvI5v.js.map → DocumentFormModal-CLmdGx34.js.map} +1 -1
  5. package/dist/ImportSpecModal-BzEyiNWD.js +378 -0
  6. package/dist/ImportSpecModal-BzEyiNWD.js.map +1 -0
  7. package/dist/WorkflowEditor-CxTuK8_d.js +1272 -0
  8. package/dist/WorkflowEditor-CxTuK8_d.js.map +1 -0
  9. package/dist/{apps-CFWdgGst.js → apps-CyEszfIu.js} +33 -33
  10. package/dist/{apps-CFWdgGst.js.map → apps-CyEszfIu.js.map} +1 -1
  11. package/dist/callable-row-actions-BPBPflMn.js +56 -0
  12. package/dist/callable-row-actions-BPBPflMn.js.map +1 -0
  13. package/dist/callables-dLF2IcwA.js +317 -0
  14. package/dist/callables-dLF2IcwA.js.map +1 -0
  15. package/dist/chrome/TagEditor.d.ts +6 -1
  16. package/dist/chrome/workspace.d.ts +16 -0
  17. package/dist/documents-hgltn0xe.js +1017 -0
  18. package/dist/documents-hgltn0xe.js.map +1 -0
  19. package/dist/draft.mjs +1 -1
  20. package/dist/editor/WaitingForm.d.ts +19 -0
  21. package/dist/{editor-apps-ShwCmvLY.js → editor-apps-DsGrGKfe.js} +3 -3
  22. package/dist/{editor-apps-ShwCmvLY.js.map → editor-apps-DsGrGKfe.js.map} +1 -1
  23. package/dist/{editor-tools-rY9nddqr.js → editor-tools-Ct7YPPj8.js} +682 -784
  24. package/dist/editor-tools-Ct7YPPj8.js.map +1 -0
  25. package/dist/editor.mjs +1 -1
  26. package/dist/editors.mjs +18 -18
  27. package/dist/{endpoints-zOuwci2U.js → endpoints-DJxXRh-I.js} +12 -12
  28. package/dist/{endpoints-zOuwci2U.js.map → endpoints-DJxXRh-I.js.map} +1 -1
  29. package/dist/forms.mjs +1 -1
  30. package/dist/index.mjs +140 -115
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/lib/callable-row-actions.d.ts +17 -0
  33. package/dist/lib/index.d.ts +2 -0
  34. package/dist/lib/run-event-stream.d.ts +122 -0
  35. package/dist/lib/tag-editor.d.ts +6 -0
  36. package/dist/lib/workflow-live-run.d.ts +7 -0
  37. package/dist/lib/workflow-validity.d.ts +7 -1
  38. package/dist/lib.mjs +52 -47
  39. package/dist/lists/CallableKindList.d.ts +12 -0
  40. package/dist/lists/CallableRowParts.d.ts +8 -1
  41. package/dist/lists/EndpointList.d.ts +3 -0
  42. package/dist/lists/FunctionList.d.ts +3 -0
  43. package/dist/lists/WorkflowList.d.ts +3 -0
  44. package/dist/lists.d.ts +1 -0
  45. package/dist/lists.mjs +1589 -1513
  46. package/dist/lists.mjs.map +1 -1
  47. package/dist/rail.mjs +1 -1
  48. package/dist/repos/callables.d.ts +25 -0
  49. package/dist/repos/documents.d.ts +9 -1
  50. package/dist/repos/saved-file-names.d.ts +10 -0
  51. package/dist/repos/workflows.d.ts +19 -13
  52. package/dist/repos.mjs +333 -328
  53. package/dist/{setup-incomplete-BHs3Lpfy.js → setup-incomplete-6PAbN0EW.js} +50 -49
  54. package/dist/setup-incomplete-6PAbN0EW.js.map +1 -0
  55. package/dist/spec-import-BKyfhTYG.js +200 -0
  56. package/dist/spec-import-BKyfhTYG.js.map +1 -0
  57. package/dist/{use-callable-draft-w4tDTYcb.js → use-callable-draft-7HwfTuYQ.js} +3 -3
  58. package/dist/{use-callable-draft-w4tDTYcb.js.map → use-callable-draft-7HwfTuYQ.js.map} +1 -1
  59. package/package.json +3 -3
  60. package/src/styles.css +43 -0
  61. package/dist/ImportSpecModal-SQvTwtcX.js +0 -252
  62. package/dist/ImportSpecModal-SQvTwtcX.js.map +0 -1
  63. package/dist/WorkflowEditor-D2EfEP-U.js +0 -1201
  64. package/dist/WorkflowEditor-D2EfEP-U.js.map +0 -1
  65. package/dist/callable-record-Bhxim8C1.js +0 -14
  66. package/dist/callable-record-Bhxim8C1.js.map +0 -1
  67. package/dist/callables-B49tS2vv.js +0 -297
  68. package/dist/callables-B49tS2vv.js.map +0 -1
  69. package/dist/editor-tools-rY9nddqr.js.map +0 -1
  70. package/dist/setup-incomplete-BHs3Lpfy.js.map +0 -1
  71. package/dist/spec-import-CPbDnnuv.js +0 -272
  72. package/dist/spec-import-CPbDnnuv.js.map +0 -1
  73. package/dist/workflows-RhR8kwt7.js +0 -667
  74. package/dist/workflows-RhR8kwt7.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"use-callable-draft-w4tDTYcb.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,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AAGO,SAASmG,GAAiBnG,GAA2C;AAC1E,SAAOF,GAAiB,YAAYE,CAAC;AACvC;"}
1
+ {"version":3,"file":"use-callable-draft-7HwfTuYQ.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/B,EAAAyB,EAAU,UAAUzB;AACpB,QAAM0B,KAAQF,EAAOpB,CAAE;AACvB,EAAAsB,GAAM,UAAUt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E,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.34",
3
+ "version": "0.2.35",
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.8",
79
- "@w6w/ui": "^0.2.70",
78
+ "@w6w/expr": "^0.1.9",
79
+ "@w6w/ui": "^0.2.71",
80
80
  "yaml": "^2.4.2"
81
81
  },
82
82
  "peerDependencies": {
package/src/styles.css CHANGED
@@ -1048,10 +1048,53 @@
1048
1048
  }
1049
1049
 
1050
1050
  .w6w-embed-root .wf-run-log {
1051
+ display: flex;
1052
+ flex-direction: column;
1051
1053
  height: 100%;
1052
1054
  min-height: 0;
1053
1055
  }
1054
1056
 
1057
+ .w6w-embed-root .wf-run-log > .w6w-log-view {
1058
+ flex: 1;
1059
+ height: auto;
1060
+ }
1061
+
1062
+ /* A run paused at a form reached mid-run: the form itself, above the run log. */
1063
+ .w6w-embed-root .wf-waiting-forms {
1064
+ flex: none;
1065
+ max-height: 70%;
1066
+ overflow: auto;
1067
+ display: flex;
1068
+ flex-direction: column;
1069
+ gap: var(--w6w-sp-3);
1070
+ padding: var(--w6w-sp-3) var(--w6w-sp-4);
1071
+ border-bottom: 1px solid var(--border);
1072
+ }
1073
+
1074
+ .w6w-embed-root .wf-waiting-form-head {
1075
+ display: flex;
1076
+ align-items: center;
1077
+ gap: var(--w6w-sp-2);
1078
+ }
1079
+
1080
+ .w6w-embed-root .wf-waiting-form-head .btn {
1081
+ margin-left: auto;
1082
+ }
1083
+
1084
+ .w6w-embed-root .wf-waiting-form-hint {
1085
+ margin: var(--w6w-sp-1) 0 var(--w6w-sp-2);
1086
+ font-size: var(--w6w-fs-sm);
1087
+ }
1088
+
1089
+ .w6w-embed-root .wf-waiting-form-frame {
1090
+ display: block;
1091
+ width: 100%;
1092
+ height: 420px;
1093
+ border: 1px solid var(--border);
1094
+ border-radius: var(--w6w-radius);
1095
+ background: var(--panel);
1096
+ }
1097
+
1055
1098
  .w6w-embed-root .wf-run-log-idle {
1056
1099
  margin: 0;
1057
1100
  padding: var(--w6w-sp-4);
@@ -1,252 +0,0 @@
1
- import { jsxs as i, jsx as t } from "react/jsx-runtime";
2
- import { p as R, g as F, j as x, w as L, k as D, s as J, b as U, t as B } from "./import-bindings-EUtxZ9Ti.js";
3
- import { ApiError as I } from "@w6w/sdk";
4
- import { JsonEditor as G, AddConnectionModal as H } from "@w6w/ui";
5
- import { useState as p } from "react";
6
- import { u as K, a as V } from "./spec-import-CPbDnnuv.js";
7
- import { M as q } from "./ConfirmModal-WqBfWftD.js";
8
- const z = {
9
- function: "functions",
10
- endpoint: "endpoints",
11
- workflow: "workflows"
12
- }, Q = {
13
- function: {
14
- json: "functions-import-json",
15
- submit: "functions-import-submit",
16
- unresolved: "functions-import-unresolved",
17
- goto: "functions-import-goto"
18
- },
19
- endpoint: {
20
- json: "endpoints-import-json",
21
- submit: "endpoints-import-submit",
22
- unresolved: "endpoints-import-unresolved",
23
- goto: "endpoints-import-goto"
24
- },
25
- workflow: {
26
- json: "workflows-import-json",
27
- submit: "workflows-import-submit",
28
- unresolved: "workflows-import-unresolved",
29
- goto: "workflows-import-goto"
30
- }
31
- };
32
- function te(l) {
33
- const { kind: s } = l, d = z[s], h = Q[s], [v, P] = p(""), [N, r] = p(null), [m, C] = p(null), [a, c] = p(null), [k, y] = p(null), f = K(l.project, l.listKeys), b = V(l.project), { parsed: g, blockedReason: u } = R(v, s), j = a !== null, w = !j || !F(a) || u !== null || f.isPending;
34
- function S(e) {
35
- P(e), C(null), r(null), c(null);
36
- }
37
- function E() {
38
- u !== null || g === null || b.isPending || (r(null), b.mutate(g, {
39
- onSuccess: (e) => c(U(e.dependencies)),
40
- onError: (e) => {
41
- c(null), r(e instanceof I ? e.message : String(e));
42
- }
43
- }));
44
- }
45
- function M(e) {
46
- e && e.text().then(S, (n) => r(String(n)));
47
- }
48
- function $(e) {
49
- l.onClose(), l.onOpenImported(s, e);
50
- }
51
- function T() {
52
- a === null || u !== null || g === null || f.isPending || (r(null), C(null), f.mutate(
53
- { document: g, selections: B(a) },
54
- {
55
- onSuccess: (e) => {
56
- if (e.references.every((o) => o.resolved)) {
57
- $(e.callable.id);
58
- return;
59
- }
60
- C({
61
- callableId: e.callable.id,
62
- references: e.references.filter((o) => !o.resolved)
63
- });
64
- },
65
- onError: (e) => r(e instanceof I ? e.message : String(e))
66
- }
67
- ));
68
- }
69
- function A(e) {
70
- const n = e.selection;
71
- return n.mode === "bind" ? `bind:${n.target}` : n.mode;
72
- }
73
- function O(e, n) {
74
- c((o) => o && (n === "unconfigured" ? D(o, e.key) : n === "create" ? x(o, e.key, e.createName) : J(o, e.key, n.slice(5))));
75
- }
76
- return /* @__PURE__ */ i(q, { title: `Import ${s}`, onClose: l.onClose, wide: !0, children: [
77
- /* @__PURE__ */ i("div", { className: "modal-body", children: [
78
- /* @__PURE__ */ i("p", { className: "muted small", children: [
79
- "Paste a portable ",
80
- s,
81
- " spec document (exported via",
82
- " ",
83
- /* @__PURE__ */ i("code", { children: [
84
- "GET /",
85
- d,
86
- "/:id/spec"
87
- ] }),
88
- "). A fresh id is minted here; connection references are re-bound to whatever this account already has connected, and anything that couldn't be re-bound is reported below."
89
- ] }),
90
- /* @__PURE__ */ t("div", { "data-testid": h.json, children: /* @__PURE__ */ t(
91
- G,
92
- {
93
- value: v,
94
- onChange: S,
95
- minHeight: "320px",
96
- "aria-label": `${s} spec document JSON`
97
- }
98
- ) }),
99
- /* @__PURE__ */ i("label", { className: "muted small", children: [
100
- "Or choose a ",
101
- /* @__PURE__ */ t("code", { children: ".json" }),
102
- " file:",
103
- " ",
104
- /* @__PURE__ */ t(
105
- "input",
106
- {
107
- type: "file",
108
- accept: ".json,application/json",
109
- "data-testid": `${d}-import-file`,
110
- onChange: (e) => {
111
- var n;
112
- return M((n = e.target.files) == null ? void 0 : n[0]);
113
- }
114
- }
115
- )
116
- ] }),
117
- u && v !== "" && /* @__PURE__ */ t("p", { className: "muted small", children: u }),
118
- N && /* @__PURE__ */ t("div", { className: "result error", children: N }),
119
- a && a.length === 0 && /* @__PURE__ */ i("p", { className: "muted small", "data-testid": `${d}-import-nodeps`, children: [
120
- "This ",
121
- s,
122
- " has no dependencies."
123
- ] }),
124
- a && a.length > 0 && /* @__PURE__ */ t("ul", { className: "list", "data-testid": `${d}-import-rows`, children: a.map((e) => /* @__PURE__ */ i("li", { "data-testid": `${d}-import-row-${e.key}`, children: [
125
- /* @__PURE__ */ t("code", { children: e.dep.name }),
126
- " ",
127
- /* @__PURE__ */ i("span", { className: "muted", children: [
128
- "(",
129
- e.dep.kind,
130
- ")"
131
- ] }),
132
- " ",
133
- e.dep.dynamic ? /* @__PURE__ */ t("span", { className: "muted small", children: "Dynamic store name — configure it manually after import." }) : null,
134
- /* @__PURE__ */ i(
135
- "select",
136
- {
137
- value: A(e),
138
- onChange: (n) => O(e, n.target.value),
139
- "aria-label": `Configure ${e.dep.name}`,
140
- children: [
141
- /* @__PURE__ */ t("option", { value: "unconfigured", children: "Leave unconfigured" }),
142
- !e.dep.dynamic && e.options.map((n) => /* @__PURE__ */ i(
143
- "option",
144
- {
145
- value: `bind:${n.id}`,
146
- disabled: n.compatible === !1,
147
- title: n.reason,
148
- children: [
149
- n.label,
150
- n.compatible === !1 && n.reason ? ` — ${n.reason}` : ""
151
- ]
152
- },
153
- n.id
154
- )),
155
- e.dep.kind === "store" && e.dep.canCreate && !e.dep.dynamic && /* @__PURE__ */ t("option", { value: "create", children: "Create new" })
156
- ]
157
- }
158
- ),
159
- e.selection.mode === "create" && /* @__PURE__ */ t(
160
- "input",
161
- {
162
- type: "text",
163
- value: e.selection.name,
164
- "aria-label": `New name for ${e.dep.name}`,
165
- onChange: (n) => c((o) => o && x(o, e.key, n.target.value))
166
- }
167
- ),
168
- e.dep.kind === "connection" && e.dep.app && /* @__PURE__ */ t("button", { type: "button", className: "btn ghost", onClick: () => y(e), children: "Add connection" })
169
- ] }, e.key)) }),
170
- k && /* @__PURE__ */ t(
171
- H,
172
- {
173
- onCreateSharedCredential: l.onCreateSharedCredential,
174
- initialAppId: k.dep.app,
175
- onClose: () => y(null),
176
- onCreated: ({ connectionId: e }) => {
177
- const n = k.key;
178
- c(
179
- (o) => o && L(o, n, e, e)
180
- ), y(null);
181
- }
182
- }
183
- ),
184
- m && /* @__PURE__ */ i("div", { className: "result", "data-testid": h.unresolved, children: [
185
- /* @__PURE__ */ i("p", { children: [
186
- "The ",
187
- s,
188
- " was created, but ",
189
- m.references.length,
190
- " reference",
191
- m.references.length === 1 ? "" : "s",
192
- " could not be resolved:"
193
- ] }),
194
- /* @__PURE__ */ t("ul", { className: "list", children: m.references.map((e) => /* @__PURE__ */ i("li", { children: [
195
- /* @__PURE__ */ t("code", { children: e.path }),
196
- " ",
197
- /* @__PURE__ */ i("span", { className: "muted", children: [
198
- "(",
199
- e.kind,
200
- ")"
201
- ] }),
202
- e.reason && /* @__PURE__ */ i("span", { className: "muted", children: [
203
- " — ",
204
- e.reason
205
- ] })
206
- ] }, e.path)) }),
207
- /* @__PURE__ */ i(
208
- "button",
209
- {
210
- type: "button",
211
- className: "btn",
212
- "data-testid": h.goto,
213
- onClick: () => $(m.callableId),
214
- children: [
215
- "Open the created ",
216
- s
217
- ]
218
- }
219
- )
220
- ] })
221
- ] }),
222
- /* @__PURE__ */ i("div", { className: "modal-actions", children: [
223
- /* @__PURE__ */ t("button", { type: "button", className: "btn ghost", onClick: l.onClose, children: "Cancel" }),
224
- !j && /* @__PURE__ */ t(
225
- "button",
226
- {
227
- type: "button",
228
- className: "btn",
229
- "data-testid": `${d}-import-next`,
230
- disabled: u !== null || b.isPending,
231
- onClick: E,
232
- children: b.isPending ? "Checking…" : "Next"
233
- }
234
- ),
235
- /* @__PURE__ */ t(
236
- "button",
237
- {
238
- type: "button",
239
- className: "btn",
240
- "data-testid": h.submit,
241
- disabled: w,
242
- onClick: T,
243
- children: f.isPending ? "Importing…" : "Create"
244
- }
245
- )
246
- ] })
247
- ] });
248
- }
249
- export {
250
- te as I
251
- };
252
- //# sourceMappingURL=ImportSpecModal-SQvTwtcX.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ImportSpecModal-SQvTwtcX.js","sources":["../src/chrome/ImportSpecModal.tsx"],"sourcesContent":["import {\n type ImportRow,\n type SpecImportKind,\n type SpecImportListKeys,\n buildRows,\n parseImportPaste,\n rowsReady,\n setBind,\n setCreateName,\n setUnconfigured,\n toSelections,\n withCreatedConnection,\n} from \"@w6w/embed/lib\";\nimport { ApiError } from \"@w6w/sdk\";\nimport { AddConnectionModal, JsonEditor } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport {\n type SpecImportReferenceReport,\n useImportSpecMutation,\n useSpecPreviewMutation,\n} from \"../repos/spec-import.ts\";\nimport { Modal } from \"./Modal.tsx\";\n\n/** The list route segment for each kind — `goto()`'s `<collection>/<id>` nav target. */\nconst COLLECTION: Record<SpecImportKind, \"functions\" | \"endpoints\" | \"workflows\"> = {\n function: \"functions\",\n endpoint: \"endpoints\",\n workflow: \"workflows\",\n};\n\n/**\n * P2's `<collection>-import-*` testid scheme, spelled out literally per kind rather than built by\n * string interpolation — so the Functions arm's four testids stay the exact byte strings\n * `functions-page-guards.test.cjs` (IM1–IM3) already asserts against, verifiable by a plain\n * substring search over this file rather than only by running the browser suite.\n */\nconst TESTIDS: Record<\n SpecImportKind,\n { json: string; submit: string; unresolved: string; goto: string }\n> = {\n function: {\n json: \"functions-import-json\",\n submit: \"functions-import-submit\",\n unresolved: \"functions-import-unresolved\",\n goto: \"functions-import-goto\",\n },\n endpoint: {\n json: \"endpoints-import-json\",\n submit: \"endpoints-import-submit\",\n unresolved: \"endpoints-import-unresolved\",\n goto: \"endpoints-import-goto\",\n },\n workflow: {\n json: \"workflows-import-json\",\n submit: \"workflows-import-submit\",\n unresolved: \"workflows-import-unresolved\",\n goto: \"workflows-import-goto\",\n },\n};\n\n/**\n * Import modal for the Functions, Endpoints and Workflows lists (T1.2.1, generalizing T3.2.1's\n * Functions-only `ImportFunctionModal`): paste a portable spec document (rfcs/function.md), POST\n * it to `/spec/import` and either land in the created resource's editor (every reference resolved)\n * or stay open with the unresolved-reference report (A5).\n *\n * **P1 — one parameterized component, not three.** The Function-specific surface was four strings,\n * one nav target and a testid prefix — forking it into three siblings would duplicate the state\n * machine below for no gain. The `kind` prop drives all of it: `parseImportPaste`'s expected kind,\n * the title/copy, the `goto()` navigation target (`<collection>/<id>`), and every testid (P2 — the\n * four `functions-import-*` ones this file used to hardcode keep matching byte-for-byte; see\n * `TESTIDS` above for why they are spelled out literally per kind rather than interpolated).\n *\n * Mirrors `FunctionIdentityModal.tsx` (note 3 — same studio-local `Modal`,\n * same `ApiError.message` handling, same \"the row was created, hand the\n * operator the id\" shape as `onCreated`) but is a structurally PARALLEL,\n * distinct trigger — not a second \"create a resource and land in its editor\"\n * flow built on top of it. It owns its own navigation (unlike the identity\n * modal, which reports back to the list) because A5's \"created but\n * partially resolved\" outcome has nowhere else to render the report: the\n * modal has to stay mounted to show it, so it is also the one place that can\n * decide whether and when to leave the list route.\n *\n * **A `201` whose `references` carry any `resolved: false` entry is NOT\n * \"done\" (A5)** — the near-miss this exists to kill is \"201 ⇒ close and\n * navigate\", which would hide exactly the unresolved-reference report the\n * intake asks for.\n */\nexport interface ImportSpecModalProps {\n kind: SpecImportKind;\n /** The host's current project (only the workflow list key reads it). */\n project: string | undefined;\n /** The three list query keys, injected by the host. */\n listKeys: SpecImportListKeys;\n /** Navigate to the imported row; the modal closes itself first. */\n onOpenImported: (kind: SpecImportKind, id: string) => void;\n onClose: () => void;\n /** Optional: where the connect form's Use existing empty state sends the user. */\n onCreateSharedCredential?: () => void;\n}\n\nexport function ImportSpecModal(props: ImportSpecModalProps) {\n const { kind } = props;\n const collection = COLLECTION[kind];\n const testids = TESTIDS[kind];\n const [text, setText] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const [unresolved, setUnresolved] = useState<{\n callableId: string;\n references: SpecImportReferenceReport[];\n } | null>(null);\n // Two steps: \"paste\" (parse → explicit Next → ONE preview request) then \"configure\" (rows).\n const [rows, setRows] = useState<ImportRow[] | null>(null);\n const [addingFor, setAddingFor] = useState<ImportRow | null>(null);\n const importMut = useImportSpecMutation(props.project, props.listKeys);\n const previewMut = useSpecPreviewMutation(props.project);\n\n const { parsed, blockedReason } = parseImportPaste(text, kind);\n const configuring = rows !== null;\n // Create is enabled ONLY after a successful preview (never a verbatim post).\n const disabled =\n !configuring || !rowsReady(rows) || blockedReason !== null || importMut.isPending;\n\n function edit(next: string) {\n setText(next);\n setUnresolved(null);\n setError(null);\n setRows(null);\n }\n\n function next() {\n if (blockedReason !== null || parsed === null || previewMut.isPending) return;\n setError(null);\n previewMut.mutate(parsed as Record<string, unknown>, {\n onSuccess: (res) => setRows(buildRows(res.dependencies)),\n onError: (e) => {\n setRows(null);\n setError(e instanceof ApiError ? e.message : String(e));\n },\n });\n }\n\n function onFile(file: File | undefined) {\n if (!file) return;\n file.text().then(edit, (e) => setError(String(e)));\n }\n\n function goto(id: string) {\n props.onClose();\n props.onOpenImported(kind, id);\n }\n\n function submit() {\n // Defensive, not decorative: a forced click (e.g. `dispatchEvent`) on a\n // disabled button must still issue zero requests (A3, IM1(a)/(b)).\n if (rows === null || blockedReason !== null || parsed === null || importMut.isPending) return;\n setError(null);\n setUnresolved(null);\n // The parsed paste plus EVERY row's selection (`unconfigured` included).\n importMut.mutate(\n { document: parsed as Record<string, unknown>, selections: toSelections(rows) },\n {\n onSuccess: (result) => {\n const allResolved = result.references.every((r) => r.resolved);\n if (allResolved) {\n goto(result.callable.id);\n return;\n }\n // Kept open (A5): the resource WAS created, but at least one\n // reference did not bind — report every unresolved entry, and give\n // the operator an explicit way to still reach the row.\n setUnresolved({\n callableId: result.callable.id,\n references: result.references.filter((r) => !r.resolved),\n });\n },\n onError: (e) => setError(e instanceof ApiError ? e.message : String(e)),\n },\n );\n }\n\n function selectValue(row: ImportRow): string {\n const s = row.selection;\n return s.mode === \"bind\" ? `bind:${s.target}` : s.mode;\n }\n\n function onPick(row: ImportRow, value: string) {\n setRows((cur) => {\n if (!cur) return cur;\n if (value === \"unconfigured\") return setUnconfigured(cur, row.key);\n if (value === \"create\") return setCreateName(cur, row.key, row.createName);\n return setBind(cur, row.key, value.slice(\"bind:\".length));\n });\n }\n\n return (\n <Modal title={`Import ${kind}`} onClose={props.onClose} wide>\n <div className=\"modal-body\">\n <p className=\"muted small\">\n Paste a portable {kind} spec document (exported via{\" \"}\n <code>GET /{collection}/:id/spec</code>\n ). A fresh id is minted here; connection references are re-bound to whatever this account\n already has connected, and anything that couldn't be re-bound is reported below.\n </p>\n\n <div data-testid={testids.json}>\n <JsonEditor\n value={text}\n onChange={edit}\n minHeight=\"320px\"\n aria-label={`${kind} spec document JSON`}\n />\n </div>\n\n <label className=\"muted small\">\n Or choose a <code>.json</code> file:{\" \"}\n <input\n type=\"file\"\n accept=\".json,application/json\"\n data-testid={`${collection}-import-file`}\n onChange={(e) => onFile(e.target.files?.[0])}\n />\n </label>\n\n {blockedReason && text !== \"\" && <p className=\"muted small\">{blockedReason}</p>}\n {error && <div className=\"result error\">{error}</div>}\n\n {rows && rows.length === 0 && (\n <p className=\"muted small\" data-testid={`${collection}-import-nodeps`}>\n This {kind} has no dependencies.\n </p>\n )}\n {rows && rows.length > 0 && (\n <ul className=\"list\" data-testid={`${collection}-import-rows`}>\n {rows.map((row) => (\n <li key={row.key} data-testid={`${collection}-import-row-${row.key}`}>\n <code>{row.dep.name}</code> <span className=\"muted\">({row.dep.kind})</span>{\" \"}\n {row.dep.dynamic ? (\n <span className=\"muted small\">\n Dynamic store name — configure it manually after import.\n </span>\n ) : null}\n <select\n value={selectValue(row)}\n onChange={(e) => onPick(row, e.target.value)}\n aria-label={`Configure ${row.dep.name}`}\n >\n <option value=\"unconfigured\">Leave unconfigured</option>\n {!row.dep.dynamic &&\n row.options.map((o) => (\n <option\n key={o.id}\n value={`bind:${o.id}`}\n disabled={o.compatible === false}\n title={o.reason}\n >\n {o.label}\n {o.compatible === false && o.reason ? ` — ${o.reason}` : \"\"}\n </option>\n ))}\n {row.dep.kind === \"store\" && row.dep.canCreate && !row.dep.dynamic && (\n <option value=\"create\">Create new</option>\n )}\n </select>\n {row.selection.mode === \"create\" && (\n <input\n type=\"text\"\n value={row.selection.name}\n aria-label={`New name for ${row.dep.name}`}\n onChange={(e) =>\n setRows((cur) => (cur ? setCreateName(cur, row.key, e.target.value) : cur))\n }\n />\n )}\n {row.dep.kind === \"connection\" && row.dep.app && (\n <button type=\"button\" className=\"btn ghost\" onClick={() => setAddingFor(row)}>\n Add connection\n </button>\n )}\n </li>\n ))}\n </ul>\n )}\n {addingFor && (\n <AddConnectionModal\n onCreateSharedCredential={props.onCreateSharedCredential}\n initialAppId={addingFor.dep.app}\n onClose={() => setAddingFor(null)}\n onCreated={({ connectionId }) => {\n // Append the new connection as an option and bind the row to it (no re-preview).\n const key = addingFor.key;\n setRows((cur) =>\n cur ? withCreatedConnection(cur, key, connectionId, connectionId) : cur,\n );\n setAddingFor(null);\n }}\n />\n )}\n\n {unresolved && (\n <div className=\"result\" data-testid={testids.unresolved}>\n <p>\n The {kind} was created, but {unresolved.references.length} reference\n {unresolved.references.length === 1 ? \"\" : \"s\"} could not be resolved:\n </p>\n <ul className=\"list\">\n {unresolved.references.map((r) => (\n <li key={r.path}>\n <code>{r.path}</code> <span className=\"muted\">({r.kind})</span>\n {r.reason && <span className=\"muted\"> — {r.reason}</span>}\n </li>\n ))}\n </ul>\n <button\n type=\"button\"\n className=\"btn\"\n data-testid={testids.goto}\n onClick={() => goto(unresolved.callableId)}\n >\n Open the created {kind}\n </button>\n </div>\n )}\n </div>\n\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Cancel\n </button>\n {!configuring && (\n <button\n type=\"button\"\n className=\"btn\"\n data-testid={`${collection}-import-next`}\n disabled={blockedReason !== null || previewMut.isPending}\n onClick={next}\n >\n {previewMut.isPending ? \"Checking…\" : \"Next\"}\n </button>\n )}\n <button\n type=\"button\"\n className=\"btn\"\n data-testid={testids.submit}\n disabled={disabled}\n onClick={submit}\n >\n {importMut.isPending ? \"Importing…\" : \"Create\"}\n </button>\n </div>\n </Modal>\n );\n}\n"],"names":["COLLECTION","TESTIDS","ImportSpecModal","props","kind","collection","testids","text","setText","useState","error","setError","unresolved","setUnresolved","rows","setRows","addingFor","setAddingFor","importMut","useImportSpecMutation","previewMut","useSpecPreviewMutation","parsed","blockedReason","parseImportPaste","configuring","disabled","rowsReady","edit","next","res","buildRows","ApiError","onFile","file","e","goto","id","submit","toSelections","result","r","selectValue","row","s","onPick","value","cur","setUnconfigured","setCreateName","setBind","jsxs","Modal","jsx","JsonEditor","_a","o","AddConnectionModal","connectionId","key","withCreatedConnection"],"mappings":";;;;;;;AAwBA,MAAMA,IAA8E;AAAA,EAClF,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AACZ,GAQMC,IAGF;AAAA,EACF,UAAU;AAAA,IACR,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,MAAM;AAAA,EAAA;AAAA,EAER,UAAU;AAAA,IACR,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,MAAM;AAAA,EAAA;AAAA,EAER,UAAU;AAAA,IACR,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,MAAM;AAAA,EAAA;AAEV;AA2CO,SAASC,GAAgBC,GAA6B;AAC3D,QAAM,EAAE,MAAAC,MAASD,GACXE,IAAaL,EAAWI,CAAI,GAC5BE,IAAUL,EAAQG,CAAI,GACtB,CAACG,GAAMC,CAAO,IAAIC,EAAS,EAAE,GAC7B,CAACC,GAAOC,CAAQ,IAAIF,EAAwB,IAAI,GAChD,CAACG,GAAYC,CAAa,IAAIJ,EAG1B,IAAI,GAER,CAACK,GAAMC,CAAO,IAAIN,EAA6B,IAAI,GACnD,CAACO,GAAWC,CAAY,IAAIR,EAA2B,IAAI,GAC3DS,IAAYC,EAAsBhB,EAAM,SAASA,EAAM,QAAQ,GAC/DiB,IAAaC,EAAuBlB,EAAM,OAAO,GAEjD,EAAE,QAAAmB,GAAQ,eAAAC,EAAA,IAAkBC,EAAiBjB,GAAMH,CAAI,GACvDqB,IAAcX,MAAS,MAEvBY,IACJ,CAACD,KAAe,CAACE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