@tangle-network/agent-app 0.60.208 → 0.60.209

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 (35) hide show
  1. package/dist/assistant/index.js +1 -1
  2. package/dist/{chunk-JDEGS53O.js → chunk-LRW36WCF.js} +25 -2
  3. package/dist/chunk-LRW36WCF.js.map +1 -0
  4. package/dist/intakes/drizzle.js +114 -6
  5. package/dist/intakes/drizzle.js.map +1 -1
  6. package/dist/intakes/index.d.ts +2 -6
  7. package/dist/intakes/index.js +6 -8
  8. package/dist/intakes/index.js.map +1 -1
  9. package/dist/intakes/model.d.ts +1 -2
  10. package/dist/public-consultation/index.d.ts +2 -2
  11. package/dist/stories/panels/fixtures.d.ts +3 -29
  12. package/dist/web-react/index.js +3 -3
  13. package/package.json +1 -16
  14. package/dist/IntakeInterview-OKT6DCBN.js +0 -8
  15. package/dist/IntakeInterview-OKT6DCBN.js.map +0 -1
  16. package/dist/chunk-I2CA5N7V.js +0 -254
  17. package/dist/chunk-I2CA5N7V.js.map +0 -1
  18. package/dist/chunk-JDEGS53O.js.map +0 -1
  19. package/dist/chunk-VWAEWOWK.js +0 -124
  20. package/dist/chunk-VWAEWOWK.js.map +0 -1
  21. package/dist/chunk-YZ6KQULN.js +0 -30
  22. package/dist/chunk-YZ6KQULN.js.map +0 -1
  23. package/dist/intakes/api.d.ts +0 -54
  24. package/dist/intakes/api.js +0 -63
  25. package/dist/intakes/api.js.map +0 -1
  26. package/dist/intakes-react/components/BrandMark.d.ts +0 -10
  27. package/dist/intakes-react/components/IntakeInterview.d.ts +0 -15
  28. package/dist/intakes-react/components/index.d.ts +0 -1
  29. package/dist/intakes-react/contracts.d.ts +0 -42
  30. package/dist/intakes-react/index.d.ts +0 -14
  31. package/dist/intakes-react/index.js +0 -8
  32. package/dist/intakes-react/index.js.map +0 -1
  33. package/dist/intakes-react/lazy.d.ts +0 -10
  34. package/dist/intakes-react/lazy.js +0 -9
  35. package/dist/intakes-react/lazy.js.map +0 -1
@@ -1,254 +0,0 @@
1
- import {
2
- validateAnswer
3
- } from "./chunk-JDEGS53O.js";
4
-
5
- // src/intakes-react/components/IntakeInterview.tsx
6
- import { useEffect, useState } from "react";
7
-
8
- // src/intakes-react/components/BrandMark.tsx
9
- import { lazy, Suspense } from "react";
10
- import { jsx } from "react/jsx-runtime";
11
- function MarkSpacer({ size }) {
12
- return /* @__PURE__ */ jsx("span", { "aria-hidden": true, style: { display: "inline-block", width: size, height: size } });
13
- }
14
- var LazyKnot = lazy(async () => {
15
- try {
16
- const mod = await import("./brand/index.js");
17
- return { default: mod.TangleKnot };
18
- } catch {
19
- return { default: MarkSpacer };
20
- }
21
- });
22
- function BrandMark({ size, className }) {
23
- return /* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx(MarkSpacer, { size }), children: /* @__PURE__ */ jsx(LazyKnot, { size, className }) });
24
- }
25
-
26
- // src/intakes-react/components/IntakeInterview.tsx
27
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
28
- function IntakeInterview({
29
- view: initialView,
30
- onAnswer,
31
- onComplete,
32
- onDone,
33
- onNotice
34
- }) {
35
- const [view, setView] = useState(initialView);
36
- const [draft, setDraft] = useState(currentAnswer(initialView));
37
- const [busy, setBusy] = useState(false);
38
- const [doneFired, setDoneFired] = useState(false);
39
- useEffect(() => {
40
- setView(initialView);
41
- setDraft(currentAnswer(initialView));
42
- }, [initialView]);
43
- useEffect(() => {
44
- if (view.completed && !doneFired) {
45
- setDoneFired(true);
46
- onDone?.();
47
- }
48
- }, [view.completed, doneFired, onDone]);
49
- function notify(kind, message) {
50
- onNotice?.({ kind, message });
51
- }
52
- const question = view.nextQuestion;
53
- async function submit() {
54
- if (!question || busy) return;
55
- const validity = validateAnswer(question, draft);
56
- if (!validity.ok) {
57
- notify("error", `Please answer: ${validity.reason}`);
58
- return;
59
- }
60
- setBusy(true);
61
- try {
62
- const next = await onAnswer({ questionId: question.id, value: normalize(question, draft) });
63
- setView(next);
64
- setDraft(currentAnswer(next));
65
- } catch (err) {
66
- notify("error", err instanceof Error ? err.message : "Failed to save answer");
67
- } finally {
68
- setBusy(false);
69
- }
70
- }
71
- async function finish() {
72
- if (busy) return;
73
- setBusy(true);
74
- try {
75
- const next = await onComplete();
76
- setView(next);
77
- notify("success", "All set.");
78
- } catch (err) {
79
- notify("error", err instanceof Error ? err.message : "Failed to finish");
80
- } finally {
81
- setBusy(false);
82
- }
83
- }
84
- return /* @__PURE__ */ jsxs("section", { className: "flex flex-col gap-5", children: [
85
- /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-1", children: [
86
- /* @__PURE__ */ jsxs("span", { className: "mb-1 flex items-center gap-2 text-[var(--text-muted)]", children: [
87
- /* @__PURE__ */ jsx2(BrandMark, { size: 20, className: "shrink-0" }),
88
- /* @__PURE__ */ jsx2("span", { className: "text-xs font-semibold uppercase tracking-[0.05em]", children: "Tangle Intake" })
89
- ] }),
90
- /* @__PURE__ */ jsx2("h2", { className: "text-xl font-semibold text-[var(--text-primary)]", children: view.title }),
91
- view.description && /* @__PURE__ */ jsx2("p", { className: "text-sm text-[var(--text-muted)]", children: view.description }),
92
- /* @__PURE__ */ jsx2(ProgressBar, { answered: view.progress.answered, total: view.progress.total })
93
- ] }),
94
- view.completed ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5 rounded-lg border border-[hsl(var(--success)/0.4)] bg-[hsl(var(--success)/0.08)] px-3.5 py-3", children: [
95
- /* @__PURE__ */ jsx2("svg", { viewBox: "0 0 24 24", className: "h-4 w-4 shrink-0 text-[var(--surface-success-text)]", fill: "none", stroke: "currentColor", strokeWidth: "2.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true, children: /* @__PURE__ */ jsx2("polyline", { points: "20 6 9 17 4 12" }) }),
96
- /* @__PURE__ */ jsx2("p", { className: "text-sm text-[var(--text-primary)]", children: "You're all set \u2014 every answer is saved. You can close this panel." })
97
- ] }) : question ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
98
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
99
- /* @__PURE__ */ jsx2("p", { className: "text-sm font-medium text-[var(--text-primary)]", children: question.prompt }),
100
- question.help && /* @__PURE__ */ jsx2("p", { className: "text-xs text-[var(--text-muted)]", children: question.help })
101
- ] }),
102
- /* @__PURE__ */ jsx2(AnswerField, { question, value: draft, onChange: setDraft, onSubmit: () => void submit() }),
103
- /* @__PURE__ */ jsx2("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx2(
104
- "button",
105
- {
106
- type: "button",
107
- onClick: () => void submit(),
108
- disabled: busy || isDraftEmpty(draft),
109
- className: "rounded bg-[var(--brand-primary)] px-4 py-1.5 text-sm text-[hsl(var(--primary-foreground))] disabled:opacity-50",
110
- children: busy ? "Saving\u2026" : "Continue"
111
- }
112
- ) })
113
- ] }) : /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
114
- /* @__PURE__ */ jsx2("p", { className: "text-sm text-[var(--text-secondary)]", children: "That's everything. Ready to finish?" }),
115
- /* @__PURE__ */ jsx2("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx2(
116
- "button",
117
- {
118
- type: "button",
119
- onClick: () => void finish(),
120
- disabled: busy,
121
- className: "rounded bg-[var(--brand-primary)] px-4 py-1.5 text-sm text-[hsl(var(--primary-foreground))] disabled:opacity-50",
122
- children: busy ? "Finishing\u2026" : "Finish"
123
- }
124
- ) })
125
- ] })
126
- ] });
127
- }
128
- function AnswerField({ question, value, onChange, onSubmit }) {
129
- const inputClass = "rounded border border-[var(--border-default)] bg-[var(--bg-input)] px-3 py-2 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)]";
130
- switch (question.type) {
131
- case "long-text":
132
- return /* @__PURE__ */ jsx2(
133
- "textarea",
134
- {
135
- rows: 4,
136
- "aria-label": question.prompt,
137
- value: typeof value === "string" ? value : "",
138
- onChange: (event) => onChange(event.target.value),
139
- className: inputClass
140
- }
141
- );
142
- case "boolean":
143
- return /* @__PURE__ */ jsx2("div", { className: "flex gap-2", children: [{ v: true, l: "Yes" }, { v: false, l: "No" }].map((opt) => /* @__PURE__ */ jsx2(
144
- "button",
145
- {
146
- type: "button",
147
- onClick: () => onChange(opt.v),
148
- className: `rounded border px-4 py-1.5 text-sm ${value === opt.v ? "border-[var(--brand-primary)] bg-[var(--brand-primary)] text-[hsl(var(--primary-foreground))]" : "border-[var(--border-default)] bg-[var(--bg-input)] text-[var(--text-secondary)]"}`,
149
- children: opt.l
150
- },
151
- opt.l
152
- )) });
153
- case "number":
154
- return /* @__PURE__ */ jsx2(
155
- "input",
156
- {
157
- type: "number",
158
- "aria-label": question.prompt,
159
- value: typeof value === "number" ? value : "",
160
- onChange: (event) => onChange(event.target.value === "" ? null : Number(event.target.value)),
161
- onKeyDown: (event) => {
162
- if (event.key === "Enter") onSubmit();
163
- },
164
- className: inputClass
165
- }
166
- );
167
- case "single-select":
168
- return /* @__PURE__ */ jsx2("div", { className: "flex flex-col gap-1.5", children: (question.options ?? []).map((option) => /* @__PURE__ */ jsxs(
169
- "button",
170
- {
171
- type: "button",
172
- onClick: () => onChange(option.value),
173
- className: `flex items-center gap-2 rounded border px-3 py-2 text-left text-sm ${value === option.value ? "border-[var(--brand-primary)] bg-[color-mix(in_srgb,var(--brand-primary)_10%,transparent)] text-[var(--text-primary)]" : "border-[var(--border-default)] bg-[var(--bg-input)] text-[var(--text-secondary)]"}`,
174
- children: [
175
- value === option.value && /* @__PURE__ */ jsx2(ChoiceCheck, {}),
176
- option.label
177
- ]
178
- },
179
- option.value
180
- )) });
181
- case "multi-select": {
182
- const selected = Array.isArray(value) ? value : [];
183
- return /* @__PURE__ */ jsx2("div", { className: "flex flex-col gap-1.5", children: (question.options ?? []).map((option) => {
184
- const on = selected.includes(option.value);
185
- return /* @__PURE__ */ jsxs(
186
- "button",
187
- {
188
- type: "button",
189
- onClick: () => onChange(on ? selected.filter((v) => v !== option.value) : [...selected, option.value]),
190
- className: `flex items-center gap-2 rounded border px-3 py-2 text-left text-sm ${on ? "border-[var(--brand-primary)] bg-[color-mix(in_srgb,var(--brand-primary)_10%,transparent)] text-[var(--text-primary)]" : "border-[var(--border-default)] bg-[var(--bg-input)] text-[var(--text-secondary)]"}`,
191
- children: [
192
- on && /* @__PURE__ */ jsx2(ChoiceCheck, {}),
193
- option.label
194
- ]
195
- },
196
- option.value
197
- );
198
- }) });
199
- }
200
- default:
201
- return /* @__PURE__ */ jsx2(
202
- "input",
203
- {
204
- type: question.type === "email" ? "email" : question.type === "url" ? "url" : "text",
205
- "aria-label": question.prompt,
206
- value: typeof value === "string" ? value : "",
207
- onChange: (event) => onChange(event.target.value),
208
- onKeyDown: (event) => {
209
- if (event.key === "Enter") onSubmit();
210
- },
211
- className: inputClass
212
- }
213
- );
214
- }
215
- }
216
- function ChoiceCheck() {
217
- return /* @__PURE__ */ jsx2("svg", { viewBox: "0 0 24 24", className: "h-3.5 w-3.5 shrink-0 text-[var(--brand-primary)]", fill: "none", stroke: "currentColor", strokeWidth: "2.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true, children: /* @__PURE__ */ jsx2("polyline", { points: "20 6 9 17 4 12" }) });
218
- }
219
- function ProgressBar({ answered, total }) {
220
- const pct = total > 0 ? Math.round(answered / total * 100) : 0;
221
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
222
- /* @__PURE__ */ jsx2("div", { className: "h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--bg-input)]", children: /* @__PURE__ */ jsx2("div", { className: "h-full rounded-full bg-[var(--brand-primary)] transition-all", style: { width: `${pct}%` } }) }),
223
- /* @__PURE__ */ jsxs("span", { className: "text-xs text-[var(--text-muted)]", children: [
224
- answered,
225
- "/",
226
- total
227
- ] })
228
- ] });
229
- }
230
- function currentAnswer(view) {
231
- const id = view.nextQuestion?.id;
232
- if (!id) return null;
233
- return view.answers[id] ?? defaultDraft(view.nextQuestion);
234
- }
235
- function defaultDraft(question) {
236
- return question.type === "multi-select" ? [] : null;
237
- }
238
- function isDraftEmpty(value) {
239
- if (value === null || value === void 0) return true;
240
- if (typeof value === "string") return value.trim() === "";
241
- if (Array.isArray(value)) return value.length === 0;
242
- return false;
243
- }
244
- function normalize(question, value) {
245
- if (typeof value === "string" && (question.type === "text" || question.type === "long-text" || question.type === "url" || question.type === "email")) {
246
- return value.trim();
247
- }
248
- return value;
249
- }
250
-
251
- export {
252
- IntakeInterview
253
- };
254
- //# sourceMappingURL=chunk-I2CA5N7V.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/intakes-react/components/IntakeInterview.tsx","../src/intakes-react/components/BrandMark.tsx"],"sourcesContent":["/**\n * Agent-led intake interview: asks one question at a time, advancing as each\n * answer is saved. Fully callback-driven — the host supplies the loaded `view`\n * and the async `onAnswer` / `onComplete` callbacks (backed by `./intakes/api`),\n * so this imports no app router, fetch client, or toast. Styled with the\n * shipped Tangle Quiet tokens (`var(--*)`).\n *\n * The server owns traversal: each `onAnswer` resolves with the next view (next\n * question + progress), so the component never re-derives the graph — it renders\n * `view.nextQuestion`, and when that is null and the view is completable it\n * shows the finish action. Local validation only gates the submit button; the\n * authoritative validation runs in the store.\n */\n\nimport { useEffect, useState } from 'react'\nimport type { IntakeAnswerValue, IntakeQuestion } from '../../intakes/model'\nimport { validateAnswer } from '../../intakes/model'\nimport type { IntakeInterviewProps, IntakeView } from '../contracts'\nimport { BrandMark } from './BrandMark'\n\nexport function IntakeInterview({\n view: initialView,\n onAnswer,\n onComplete,\n onDone,\n onNotice,\n}: IntakeInterviewProps) {\n const [view, setView] = useState<IntakeView>(initialView)\n const [draft, setDraft] = useState<IntakeAnswerValue>(currentAnswer(initialView))\n const [busy, setBusy] = useState(false)\n const [doneFired, setDoneFired] = useState(false)\n\n useEffect(() => {\n setView(initialView)\n setDraft(currentAnswer(initialView))\n }, [initialView])\n\n useEffect(() => {\n if (view.completed && !doneFired) {\n setDoneFired(true)\n onDone?.()\n }\n }, [view.completed, doneFired, onDone])\n\n function notify(kind: 'success' | 'error', message: string) {\n onNotice?.({ kind, message })\n }\n\n const question = view.nextQuestion\n\n async function submit() {\n if (!question || busy) return\n const validity = validateAnswer(question, draft)\n if (!validity.ok) {\n notify('error', `Please answer: ${validity.reason}`)\n return\n }\n setBusy(true)\n try {\n const next = await onAnswer({ questionId: question.id, value: normalize(question, draft) })\n setView(next)\n setDraft(currentAnswer(next))\n } catch (err) {\n notify('error', err instanceof Error ? err.message : 'Failed to save answer')\n } finally {\n setBusy(false)\n }\n }\n\n async function finish() {\n if (busy) return\n setBusy(true)\n try {\n const next = await onComplete()\n setView(next)\n notify('success', 'All set.')\n } catch (err) {\n notify('error', err instanceof Error ? err.message : 'Failed to finish')\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <section className=\"flex flex-col gap-5\">\n <header className=\"flex flex-col gap-1\">\n <span className=\"mb-1 flex items-center gap-2 text-[var(--text-muted)]\">\n <BrandMark size={20} className=\"shrink-0\" />\n <span className=\"text-xs font-semibold uppercase tracking-[0.05em]\">Tangle Intake</span>\n </span>\n <h2 className=\"text-xl font-semibold text-[var(--text-primary)]\">{view.title}</h2>\n {view.description && <p className=\"text-sm text-[var(--text-muted)]\">{view.description}</p>}\n <ProgressBar answered={view.progress.answered} total={view.progress.total} />\n </header>\n\n {view.completed ? (\n <div className=\"flex items-center gap-2.5 rounded-lg border border-[hsl(var(--success)/0.4)] bg-[hsl(var(--success)/0.08)] px-3.5 py-3\">\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4 shrink-0 text-[var(--surface-success-text)]\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <polyline points=\"20 6 9 17 4 12\" />\n </svg>\n <p className=\"text-sm text-[var(--text-primary)]\">You're all set — every answer is saved. You can close this panel.</p>\n </div>\n ) : question ? (\n <div className=\"flex flex-col gap-3\">\n <div className=\"flex flex-col gap-1\">\n <p className=\"text-sm font-medium text-[var(--text-primary)]\">{question.prompt}</p>\n {question.help && <p className=\"text-xs text-[var(--text-muted)]\">{question.help}</p>}\n </div>\n\n <AnswerField question={question} value={draft} onChange={setDraft} onSubmit={() => void submit()} />\n\n <div className=\"flex justify-end\">\n <button\n type=\"button\"\n onClick={() => void submit()}\n disabled={busy || isDraftEmpty(draft)}\n className=\"rounded bg-[var(--brand-primary)] px-4 py-1.5 text-sm text-[hsl(var(--primary-foreground))] disabled:opacity-50\"\n >\n {busy ? 'Saving…' : 'Continue'}\n </button>\n </div>\n </div>\n ) : (\n <div className=\"flex flex-col gap-3\">\n <p className=\"text-sm text-[var(--text-secondary)]\">That's everything. Ready to finish?</p>\n <div className=\"flex justify-end\">\n <button\n type=\"button\"\n onClick={() => void finish()}\n disabled={busy}\n className=\"rounded bg-[var(--brand-primary)] px-4 py-1.5 text-sm text-[hsl(var(--primary-foreground))] disabled:opacity-50\"\n >\n {busy ? 'Finishing…' : 'Finish'}\n </button>\n </div>\n </div>\n )}\n </section>\n )\n}\n\ninterface AnswerFieldProps {\n question: IntakeQuestion\n value: IntakeAnswerValue\n onChange(value: IntakeAnswerValue): void\n onSubmit(): void\n}\n\nfunction AnswerField({ question, value, onChange, onSubmit }: AnswerFieldProps) {\n const inputClass =\n 'rounded border border-[var(--border-default)] bg-[var(--bg-input)] px-3 py-2 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)]'\n\n switch (question.type) {\n case 'long-text':\n return (\n <textarea\n rows={4}\n aria-label={question.prompt}\n value={typeof value === 'string' ? value : ''}\n onChange={(event) => onChange(event.target.value)}\n className={inputClass}\n />\n )\n case 'boolean':\n return (\n <div className=\"flex gap-2\">\n {[{ v: true, l: 'Yes' }, { v: false, l: 'No' }].map((opt) => (\n <button\n key={opt.l}\n type=\"button\"\n onClick={() => onChange(opt.v)}\n className={`rounded border px-4 py-1.5 text-sm ${\n value === opt.v\n ? 'border-[var(--brand-primary)] bg-[var(--brand-primary)] text-[hsl(var(--primary-foreground))]'\n : 'border-[var(--border-default)] bg-[var(--bg-input)] text-[var(--text-secondary)]'\n }`}\n >\n {opt.l}\n </button>\n ))}\n </div>\n )\n case 'number':\n return (\n <input\n type=\"number\"\n aria-label={question.prompt}\n value={typeof value === 'number' ? value : ''}\n onChange={(event) => onChange(event.target.value === '' ? null : Number(event.target.value))}\n onKeyDown={(event) => { if (event.key === 'Enter') onSubmit() }}\n className={inputClass}\n />\n )\n case 'single-select':\n return (\n <div className=\"flex flex-col gap-1.5\">\n {(question.options ?? []).map((option) => (\n <button\n key={option.value}\n type=\"button\"\n onClick={() => onChange(option.value)}\n className={`flex items-center gap-2 rounded border px-3 py-2 text-left text-sm ${\n value === option.value\n ? 'border-[var(--brand-primary)] bg-[color-mix(in_srgb,var(--brand-primary)_10%,transparent)] text-[var(--text-primary)]'\n : 'border-[var(--border-default)] bg-[var(--bg-input)] text-[var(--text-secondary)]'\n }`}\n >\n {value === option.value && <ChoiceCheck />}\n {option.label}\n </button>\n ))}\n </div>\n )\n case 'multi-select': {\n const selected = Array.isArray(value) ? value : []\n return (\n <div className=\"flex flex-col gap-1.5\">\n {(question.options ?? []).map((option) => {\n const on = selected.includes(option.value)\n return (\n <button\n key={option.value}\n type=\"button\"\n onClick={() =>\n onChange(on ? selected.filter((v) => v !== option.value) : [...selected, option.value])\n }\n className={`flex items-center gap-2 rounded border px-3 py-2 text-left text-sm ${\n on\n ? 'border-[var(--brand-primary)] bg-[color-mix(in_srgb,var(--brand-primary)_10%,transparent)] text-[var(--text-primary)]'\n : 'border-[var(--border-default)] bg-[var(--bg-input)] text-[var(--text-secondary)]'\n }`}\n >\n {on && <ChoiceCheck />}\n {option.label}\n </button>\n )\n })}\n </div>\n )\n }\n default:\n return (\n <input\n type={question.type === 'email' ? 'email' : question.type === 'url' ? 'url' : 'text'}\n aria-label={question.prompt}\n value={typeof value === 'string' ? value : ''}\n onChange={(event) => onChange(event.target.value)}\n onKeyDown={(event) => { if (event.key === 'Enter') onSubmit() }}\n className={inputClass}\n />\n )\n }\n}\n\n/** Leading check for a selected choice option (single/multi-select). */\nfunction ChoiceCheck() {\n return (\n <svg viewBox=\"0 0 24 24\" className=\"h-3.5 w-3.5 shrink-0 text-[var(--brand-primary)]\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <polyline points=\"20 6 9 17 4 12\" />\n </svg>\n )\n}\n\nfunction ProgressBar({ answered, total }: { answered: number; total: number }) {\n const pct = total > 0 ? Math.round((answered / total) * 100) : 0\n return (\n <div className=\"flex items-center gap-2\">\n <div className=\"h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--bg-input)]\">\n <div className=\"h-full rounded-full bg-[var(--brand-primary)] transition-all\" style={{ width: `${pct}%` }} />\n </div>\n <span className=\"text-xs text-[var(--text-muted)]\">{answered}/{total}</span>\n </div>\n )\n}\n\nfunction currentAnswer(view: IntakeView): IntakeAnswerValue {\n const id = view.nextQuestion?.id\n if (!id) return null\n return view.answers[id] ?? defaultDraft(view.nextQuestion!)\n}\n\nfunction defaultDraft(question: IntakeQuestion): IntakeAnswerValue {\n return question.type === 'multi-select' ? [] : null\n}\n\n/** No answer yet — null, empty text, or an empty multi-select. `false` and `0`\n * are real answers and never gate Continue. */\nfunction isDraftEmpty(value: IntakeAnswerValue): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\n/** Trim text answers before submit; pass others through unchanged. */\nfunction normalize(question: IntakeQuestion, value: IntakeAnswerValue): IntakeAnswerValue {\n if (typeof value === 'string' && (question.type === 'text' || question.type === 'long-text' || question.type === 'url' || question.type === 'email')) {\n return value.trim()\n }\n return value\n}\n","/**\n * Load the canonical Tangle knot only when an intakes surface renders it.\n * `/brand` imports the optional `@tangle-network/brand` peer, so a failed load\n * renders a fixed-size spacer instead of crashing the panel.\n */\n\nimport { lazy, Suspense } from 'react'\nimport type { ComponentType } from 'react'\n\nexport interface BrandMarkProps {\n size: number\n className?: string\n}\n\n/** Preserve the mark's footprint while its optional package loads or is absent. */\nfunction MarkSpacer({ size }: { size: number }) {\n return <span aria-hidden style={{ display: 'inline-block', width: size, height: size }} />\n}\n\nconst LazyKnot = lazy(async () => {\n try {\n const mod = await import('../../brand')\n return { default: mod.TangleKnot as ComponentType<BrandMarkProps> }\n } catch {\n return { default: MarkSpacer as ComponentType<BrandMarkProps> }\n }\n})\n\nexport function BrandMark({ size, className }: BrandMarkProps) {\n return (\n <Suspense fallback={<MarkSpacer size={size} />}>\n <LazyKnot size={size} className={className} />\n </Suspense>\n )\n}\n"],"mappings":";;;;;AAcA,SAAS,WAAW,gBAAgB;;;ACRpC,SAAS,MAAM,gBAAgB;AAUtB;AADT,SAAS,WAAW,EAAE,KAAK,GAAqB;AAC9C,SAAO,oBAAC,UAAK,eAAW,MAAC,OAAO,EAAE,SAAS,gBAAgB,OAAO,MAAM,QAAQ,KAAK,GAAG;AAC1F;AAEA,IAAM,WAAW,KAAK,YAAY;AAChC,MAAI;AACF,UAAM,MAAM,MAAM,OAAO,kBAAa;AACtC,WAAO,EAAE,SAAS,IAAI,WAA4C;AAAA,EACpE,QAAQ;AACN,WAAO,EAAE,SAAS,WAA4C;AAAA,EAChE;AACF,CAAC;AAEM,SAAS,UAAU,EAAE,MAAM,UAAU,GAAmB;AAC7D,SACE,oBAAC,YAAS,UAAU,oBAAC,cAAW,MAAY,GAC1C,8BAAC,YAAS,MAAY,WAAsB,GAC9C;AAEJ;;;ADoDQ,SACE,OAAAA,MADF;AAlED,SAAS,gBAAgB;AAAA,EAC9B,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAyB;AACvB,QAAM,CAAC,MAAM,OAAO,IAAI,SAAqB,WAAW;AACxD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,cAAc,WAAW,CAAC;AAChF,QAAM,CAAC,MAAM,OAAO,I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AO,UAAU,aAAa,SAAS,SAAS,UAAU,SAAS,SAAS,eAAe,SAAS,SAAS,SAAS,SAAS,SAAS,UAAU;AACpJ,WAAO,MAAM,KAAK;AAAA,EACpB;AACA,SAAO;AACT;","names":["jsx"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/intakes/model.ts"],"sourcesContent":["/**\n * Pure intake MODEL — the question-graph and the answer/completion algebra a\n * one-question-at-a-time interview runs on. Zero dependencies: no drizzle, no\n * env, no react, no I/O. The DB layer (`./intakes/drizzle`), the handlers\n * (`./intakes/api`) and the React surface (`./intakes-react`) all build on\n * these functions; this leaf imports nothing back, so a consumer can pull just\n * the intake math.\n *\n * An intake is an ordered list of questions, optionally branching: a question\n * can declare `next` as a function of the answers so far, so the next prompt\n * depends on what was said (e.g. \"do you have a website?\" → no → skip the URL\n * question). Traversal is pure and deterministic — `nextQuestion(graph, answers)`\n * folds the answers into the single question to ask next (or null = done), and\n * `isComplete` is true exactly when every REQUIRED reachable question has a\n * valid answer.\n *\n * Answers are a flat `Record<questionId, value>`. Each question declares an\n * answer `type` that `validateAnswer` checks against — the same validation the\n * UI runs before advancing and the store runs before persisting, so an invalid\n * answer can never enter the payload.\n */\n\n/** The kinds of answer a question accepts. */\nexport type IntakeAnswerType =\n | 'text'\n | 'long-text'\n | 'single-select'\n | 'multi-select'\n | 'boolean'\n | 'number'\n | 'url'\n | 'email'\n\n/** A selectable option for single/multi-select questions. */\nexport interface IntakeOption {\n value: string\n label: string\n}\n\n/** A flat map of answers keyed by question id. */\nexport type IntakeAnswers = Record<string, IntakeAnswerValue>\n\n/** Any value an answer can hold; the type is validated per-question. */\nexport type IntakeAnswerValue = string | string[] | number | boolean | null\n\n/**\n * One question in the graph. `next` (optional) makes the graph branch: given\n * the answers so far it returns the id of the question to ask next, or null to\n * end the interview early. With no `next`, traversal falls through to the next\n * question in declaration order.\n */\nexport interface IntakeQuestion {\n id: string\n /** The prompt the interviewer asks. */\n prompt: string\n type: IntakeAnswerType\n /** Required questions gate completion; optional ones may be skipped. */\n required?: boolean\n /** Help text shown under the prompt. */\n help?: string\n /** Options for single/multi-select questions. */\n options?: IntakeOption[]\n /** Min length (text) or min value (number); inclusive. */\n min?: number\n /** Max length (text) or max value (number); inclusive. */\n max?: number\n /**\n * Branch override: given the answers so far, the id of the next question\n * (or null to end early). Omit for linear flow (next in declaration order).\n */\n next?(answers: IntakeAnswers): string | null\n}\n\n/** The intake definition: an ordered, addressable set of questions. */\nexport interface IntakeGraph {\n /** Stable id for the intake definition (e.g. 'user-onboarding-v1'). */\n id: string\n /** Human title shown at the top of the interview. */\n title: string\n /** Optional one-line description. */\n description?: string\n /** Questions in declaration (default traversal) order. */\n questions: IntakeQuestion[]\n}\n\n/** The reason an answer failed validation. */\nexport type AnswerRejectionReason =\n | 'required'\n | 'wrong-type'\n | 'too-short'\n | 'too-long'\n | 'too-small'\n | 'too-large'\n | 'not-an-option'\n | 'invalid-url'\n | 'invalid-email'\n | 'unknown-question'\n\n/** Describe validation outcome of an answer including success status and optional rejection reason */\nexport interface AnswerValidationResult {\n ok: boolean\n reason?: AnswerRejectionReason\n}\n\nconst URL_PATTERN = /^https?:\\/\\/[^\\s/$.?#].[^\\s]*$/i\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Look up a question by id, or null if the graph has none. */\nexport function getQuestion(graph: IntakeGraph, questionId: string): IntakeQuestion | null {\n return graph.questions.find((q) => q.id === questionId) ?? null\n}\n\n/** True when an answer value is present (not null/undefined/empty). */\nexport function hasAnswer(value: IntakeAnswerValue | undefined): boolean {\n if (value == null) return false\n if (typeof value === 'string') return value.trim().length > 0\n if (Array.isArray(value)) return value.length > 0\n return true\n}\n\n/**\n * Validate one answer against its question. Pure: no I/O, no graph mutation.\n * An empty value is rejected as `required` only when the question is required;\n * an empty value for an optional question is OK (the user skipped it).\n */\nexport function validateAnswer(\n question: IntakeQuestion,\n value: IntakeAnswerValue | undefined,\n): AnswerValidationResult {\n if (!hasAnswer(value)) {\n return question.required ? { ok: false, reason: 'required' } : { ok: true }\n }\n\n switch (question.type) {\n case 'text':\n case 'long-text': {\n if (typeof value !== 'string') return { ok: false, reason: 'wrong-type' }\n const len = value.trim().length\n if (question.min != null && len < question.min) return { ok: false, reason: 'too-short' }\n if (question.max != null && len > question.max) return { ok: false, reason: 'too-long' }\n return { ok: true }\n }\n case 'url': {\n if (typeof value !== 'string') return { ok: false, reason: 'wrong-type' }\n return URL_PATTERN.test(value.trim()) ? { ok: true } : { ok: false, reason: 'invalid-url' }\n }\n case 'email': {\n if (typeof value !== 'string') return { ok: false, reason: 'wrong-type' }\n return EMAIL_PATTERN.test(value.trim()) ? { ok: true } : { ok: false, reason: 'invalid-email' }\n }\n case 'number': {\n if (typeof value !== 'number' || !Number.isFinite(value)) return { ok: false, reason: 'wrong-type' }\n if (question.min != null && value < question.min) return { ok: false, reason: 'too-small' }\n if (question.max != null && value > question.max) return { ok: false, reason: 'too-large' }\n return { ok: true }\n }\n case 'boolean': {\n return typeof value === 'boolean' ? { ok: true } : { ok: false, reason: 'wrong-type' }\n }\n case 'single-select': {\n if (typeof value !== 'string') return { ok: false, reason: 'wrong-type' }\n return optionExists(question, value) ? { ok: true } : { ok: false, reason: 'not-an-option' }\n }\n case 'multi-select': {\n if (!Array.isArray(value)) return { ok: false, reason: 'wrong-type' }\n if (!value.every((v) => typeof v === 'string' && optionExists(question, v))) {\n return { ok: false, reason: 'not-an-option' }\n }\n if (question.min != null && value.length < question.min) return { ok: false, reason: 'too-short' }\n if (question.max != null && value.length > question.max) return { ok: false, reason: 'too-long' }\n return { ok: true }\n }\n default:\n return { ok: false, reason: 'wrong-type' }\n }\n}\n\n/**\n * The single question to ask next given the answers so far, or null when the\n * interview is done. Walks the graph from the first question, following each\n * question's `next` branch (or declaration order) and stopping at the first\n * reachable question that has no valid answer yet. Deterministic and pure.\n *\n * A `next` that points at a missing id, or returns null, ends the walk — so a\n * malformed graph terminates rather than looping. A visited-set guards against\n * a cyclic `next`.\n */\nexport function nextQuestion(graph: IntakeGraph, answers: IntakeAnswers): IntakeQuestion | null {\n if (graph.questions.length === 0) return null\n const visited = new Set<string>()\n let current: IntakeQuestion | null = graph.questions[0] ?? null\n\n while (current) {\n if (visited.has(current.id)) return null\n visited.add(current.id)\n\n const answer = answers[current.id]\n const validity = validateAnswer(current, answer)\n if (!validity.ok || (current.required && !hasAnswer(answer))) {\n return current\n }\n\n current = advance(graph, current, answers)\n }\n\n return null\n}\n\n/**\n * True when every REQUIRED question reachable under the current answers has a\n * valid answer. Pure: it replays the same traversal `nextQuestion` uses and is\n * complete exactly when that traversal has no question left to ask.\n */\nexport function isComplete(graph: IntakeGraph, answers: IntakeAnswers): boolean {\n return nextQuestion(graph, answers) === null\n}\n\n/**\n * Progress as answered-vs-total over the REACHABLE required questions under the\n * current answers — what a progress bar renders. Optional questions don't count\n * toward the denominator (they never block completion).\n */\nexport function intakeProgress(graph: IntakeGraph, answers: IntakeAnswers): { answered: number; total: number } {\n const reachable = reachableQuestions(graph, answers)\n const required = reachable.filter((q) => q.required)\n const answered = required.filter((q) => validateAnswer(q, answers[q.id]).ok && hasAnswer(answers[q.id])).length\n return { answered, total: required.length }\n}\n\n/** The questions reachable under the current answers, in traversal order. */\nexport function reachableQuestions(graph: IntakeGraph, answers: IntakeAnswers): IntakeQuestion[] {\n if (graph.questions.length === 0) return []\n const visited = new Set<string>()\n const out: IntakeQuestion[] = []\n let current: IntakeQuestion | null = graph.questions[0] ?? null\n\n while (current) {\n if (visited.has(current.id)) break\n visited.add(current.id)\n out.push(current)\n current = advance(graph, current, answers)\n }\n return out\n}\n\nfunction advance(graph: IntakeGraph, current: IntakeQuestion, answers: IntakeAnswers): IntakeQuestion | null {\n if (current.next) {\n const nextId = current.next(answers)\n return nextId == null ? null : getQuestion(graph, nextId)\n }\n const index = graph.questions.indexOf(current)\n return graph.questions[index + 1] ?? null\n}\n\nfunction optionExists(question: IntakeQuestion, value: string): boolean {\n return (question.options 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ACtB,QAAI,KAAK,OAAO;AAChB,cAAU,QAAQ,OAAO,SAAS,OAAO;AAAA,EAC3C;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,OAAoB,SAAyB,SAA+C;AAC3G,MAAI,QAAQ,MAAM;AAChB,UAAM,SAAS,QAAQ,KAAK,OAAO;AACnC,WAAO,UAAU,OAAO,OAAO,YAAY,OAAO,MAAM;AAAA,EAC1D;AACA,QAAM,QAAQ,MAAM,UAAU,QAAQ,OAAO;AAC7C,SAAO,MAAM,UAAU,QAAQ,CAAC,KAAK;AACvC;AAEA,SAAS,aAAa,UAA0B,OAAwB;AACtE,UAAQ,SAAS,WAAW,CAAC,GAAG,KAAK,CAAC,WAAW,OAAO,UAAU,KAAK;AACzE;","names":[]}
@@ -1,124 +0,0 @@
1
- import {
2
- emptyPayload,
3
- markComplete,
4
- payloadComplete,
5
- withAnswer
6
- } from "./chunk-YZ6KQULN.js";
7
- import {
8
- getQuestion,
9
- validateAnswer
10
- } from "./chunk-JDEGS53O.js";
11
-
12
- // src/intakes/drizzle/store.ts
13
- import { eq } from "drizzle-orm";
14
- var IntakeError = class extends Error {
15
- code;
16
- constructor(code, message) {
17
- super(message);
18
- this.name = "IntakeError";
19
- this.code = code;
20
- }
21
- };
22
- function createScopedStore(opts) {
23
- const { db, graph, table, scopeColumn, scopeValue, insertScope } = opts;
24
- async function loadRow() {
25
- const [row] = await db.select().from(table).where(eq(scopeColumn, scopeValue)).limit(1);
26
- return row ?? null;
27
- }
28
- function toState(row) {
29
- if (!row) {
30
- return { payload: emptyPayload(graph), completed: false, completedAt: null };
31
- }
32
- const payload = normalizePayload(row.payload, row.graphId);
33
- const completedAt = toDate(row.completedAt);
34
- return {
35
- payload,
36
- completed: completedAt != null && payloadComplete(graph, payload),
37
- completedAt
38
- };
39
- }
40
- async function get() {
41
- return toState(await loadRow());
42
- }
43
- async function upsertPayload(payload, completedAt) {
44
- const existing = await loadRow();
45
- if (existing) {
46
- await db.update(table).set({ graphId: payload.graphId, payload, completedAt, updatedAt: /* @__PURE__ */ new Date() }).where(eq(scopeColumn, scopeValue));
47
- return;
48
- }
49
- await db.insert(table).values({
50
- ...insertScope,
51
- graphId: payload.graphId,
52
- payload,
53
- completedAt
54
- });
55
- }
56
- async function save(questionId, value) {
57
- const question = getQuestion(graph, questionId);
58
- if (!question) throw new IntakeError("unknown-question", `No question '${questionId}' in intake '${graph.id}'`);
59
- const validity = validateAnswer(question, value);
60
- if (!validity.ok) {
61
- throw new IntakeError("invalid-answer", `Answer to '${questionId}' rejected: ${validity.reason}`);
62
- }
63
- const current = await get();
64
- const next = withAnswer(current.payload, questionId, value);
65
- await upsertPayload(next, current.completedAt);
66
- return toState({ graphId: next.graphId, payload: next, completedAt: current.completedAt });
67
- }
68
- async function complete() {
69
- const current = await get();
70
- if (current.payload.graphId !== graph.id) {
71
- throw new IntakeError("stale-graph", `Intake payload was collected against '${current.payload.graphId}', not '${graph.id}'`);
72
- }
73
- if (!payloadComplete(graph, current.payload)) {
74
- throw new IntakeError("incomplete", `Intake '${graph.id}' has unanswered required questions`);
75
- }
76
- const completedPayload = markComplete(current.payload);
77
- const completedAt = new Date(completedPayload.completedAt);
78
- await upsertPayload(completedPayload, completedAt);
79
- return { payload: completedPayload, completed: true, completedAt };
80
- }
81
- return { get, save, complete };
82
- }
83
- function createUserIntakeStore(opts) {
84
- return createScopedStore({
85
- db: opts.db,
86
- graph: opts.graph,
87
- table: opts.table,
88
- scopeColumn: opts.table.userId,
89
- scopeValue: opts.userId,
90
- insertScope: { userId: opts.userId }
91
- });
92
- }
93
- function createProjectIntakeStore(opts) {
94
- return createScopedStore({
95
- db: opts.db,
96
- graph: opts.graph,
97
- table: opts.table,
98
- scopeColumn: opts.table.workspaceId,
99
- scopeValue: opts.workspaceId,
100
- insertScope: { workspaceId: opts.workspaceId }
101
- });
102
- }
103
- function normalizePayload(raw, graphId) {
104
- if (raw && typeof raw === "object" && "answers" in raw) {
105
- const candidate = raw;
106
- return {
107
- graphId: candidate.graphId ?? graphId,
108
- answers: candidate.answers ?? {},
109
- ...candidate.completedAt ? { completedAt: candidate.completedAt } : {}
110
- };
111
- }
112
- return { graphId, answers: {} };
113
- }
114
- function toDate(value) {
115
- if (value == null) return null;
116
- return value instanceof Date ? value : new Date(Number(value) * (Number(value) < 1e12 ? 1e3 : 1));
117
- }
118
-
119
- export {
120
- IntakeError,
121
- createUserIntakeStore,
122
- createProjectIntakeStore
123
- };
124
- //# sourceMappingURL=chunk-VWAEWOWK.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/intakes/drizzle/store.ts"],"sourcesContent":["/**\n * Drizzle-backed store over the tables from `createIntakeTables`. One store\n * builder per scope: `createUserIntakeStore` (keyed on userId) and\n * `createProjectIntakeStore` (keyed on workspaceId). Each returns the same\n * three-method surface — `get` / `save` / `complete` — so the api handlers and\n * the UI talk to one shape regardless of scope.\n *\n * Works against any SQLite drizzle driver (better-sqlite3, D1, libsql): the\n * builders are awaited, never `.run()`/`.all()`, so sync and async drivers\n * behave identically.\n *\n * Validation is fail-loud and pure (from the `./intakes` leaf). `save` runs\n * `validateAnswer` before writing, so an invalid answer can never enter the\n * payload; `complete` runs `payloadComplete` and refuses to stamp an\n * incomplete (or stale-graph) intake — it throws a typed `IntakeError` rather\n * than silently writing a half-finished onboarding state.\n *\n * `getProjectIntakeStore` pins `workspaceId` in every WHERE clause; RBAC runs\n * in the route before the store is built, but the scope key is enforced here\n * too, so a leaked id can never read or write across the boundary.\n *\n * Imports `drizzle-orm`, so this is a subpath, never re-exported from root.\n */\n\nimport { eq } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n type IntakeAnswerValue,\n type IntakeGraph,\n getQuestion,\n validateAnswer,\n} from '../model'\nimport {\n type IntakePayload,\n emptyPayload,\n markComplete,\n payloadComplete,\n withAnswer,\n} from '../completion'\nimport type { ProjectIntakeTable, UserIntakeTable } from './schema'\n\n/** Any SQLite drizzle database — `any` erases driver-specific generics so\n * better-sqlite3, D1, and libsql handles all fit. */\nexport type IntakeDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any>\n\n/** A loaded intake: the payload plus whether it is complete against the graph. */\nexport interface IntakeState {\n payload: IntakePayload\n completed: boolean\n completedAt: Date | null\n}\n\n/** Define error codes representing specific intake validation failures */\nexport type IntakeErrorCode = 'invalid-answer' | 'unknown-question' | 'incomplete' | 'stale-graph'\n\n/** Thrown by store mutations on a refused write — callers map it to a 4xx. */\nexport class IntakeError extends Error {\n readonly code: IntakeErrorCode\n constructor(code: IntakeErrorCode, message: string) {\n super(message)\n this.name = 'IntakeError'\n this.code = code\n }\n}\n\n/** The three-method store surface, identical for both scopes. */\nexport interface IntakeStore {\n /** Load the current intake, or seed an empty payload when none exists yet. */\n get(): Promise<IntakeState>\n /** Validate and persist one answer; returns the updated state. */\n save(questionId: string, value: IntakeAnswerValue): Promise<IntakeState>\n /** Stamp the intake complete; throws IntakeError when not yet completable. */\n complete(): Promise<IntakeState>\n}\n\ninterface IntakeTableShape {\n id: any\n graphId: any\n payload: any\n completedAt: any\n updatedAt: any\n}\n\ninterface ScopedStoreOptions {\n db: IntakeDatabase\n graph: IntakeGraph\n table: IntakeTableShape\n /** The scope column (userIntake.userId or projectIntake.workspaceId). */\n scopeColumn: any\n scopeValue: string\n /** Extra columns to set on insert (the scope key). */\n insertScope: Record<string, unknown>\n}\n\nfunction createScopedStore(opts: ScopedStoreOptions): IntakeStore {\n const { db, graph, table, scopeColumn, scopeValue, insertScope } = opts\n\n async function loadRow() {\n const [row] = await db\n .select()\n .from(table as any)\n .where(eq(scopeColumn, scopeValue))\n .limit(1)\n return (row ?? null) as\n | { id: string; graphId: string; payload: unknown; completedAt: Date | number | null }\n | null\n }\n\n function toState(\n row: { graphId: string; payload: unknown; completedAt: Date | number | null } | null,\n ): IntakeState {\n if (!row) {\n return { payload: emptyPayload(graph), completed: false, completedAt: null }\n }\n const payload = normalizePayload(row.payload, row.graphId)\n const completedAt = toDate(row.completedAt)\n return {\n payload,\n completed: completedAt != null && payloadComplete(graph, payload),\n completedAt,\n }\n }\n\n async function get(): Promise<IntakeState> {\n return toState(await loadRow())\n }\n\n async function upsertPayload(payload: IntakePayload, completedAt: Date | null) {\n const existing = await loadRow()\n if (existing) {\n await db\n .update(table as any)\n .set({ graphId: payload.graphId, payload, completedAt, updatedAt: new Date() })\n .where(eq(scopeColumn, scopeValue))\n return\n }\n await db.insert(table as any).values({\n ...insertScope,\n graphId: payload.graphId,\n payload,\n completedAt,\n })\n }\n\n async function save(questionId: string, value: IntakeAnswerValue): Promise<IntakeState> {\n const question = getQuestion(graph, questionId)\n if (!question) throw new IntakeError('unknown-question', `No question '${questionId}' in intake '${graph.id}'`)\n const validity = validateAnswer(question, value)\n if (!validity.ok) {\n throw new IntakeError('invalid-answer', `Answer to '${questionId}' rejected: ${validity.reason}`)\n }\n\n const current = await get()\n const next = withAnswer(current.payload, questionId, value)\n await upsertPayload(next, current.completedAt)\n return toState({ graphId: next.graphId, payload: next, completedAt: current.completedAt })\n }\n\n async function complete(): Promise<IntakeState> {\n const current = await get()\n if (current.payload.graphId !== graph.id) {\n throw new IntakeError('stale-graph', `Intake payload was collected against '${current.payload.graphId}', not '${graph.id}'`)\n }\n if (!payloadComplete(graph, current.payload)) {\n throw new IntakeError('incomplete', `Intake '${graph.id}' has unanswered required questions`)\n }\n const completedPayload = markComplete(current.payload)\n const completedAt = new Date(completedPayload.completedAt!)\n await upsertPayload(completedPayload, completedAt)\n return { payload: completedPayload, completed: true, completedAt }\n }\n\n return { get, save, complete }\n}\n\n/** Define options required to create a user intake store for onboarding data collection */\nexport interface CreateUserIntakeStoreOptions {\n db: IntakeDatabase\n /** The user-intake table from createIntakeTables. */\n table: UserIntakeTable\n /** The intake definition this store collects answers against. */\n graph: IntakeGraph\n /** The user whose onboarding this is. */\n userId: string\n}\n\n/** Build the per-user onboarding store, scoped to one userId. */\nexport function createUserIntakeStore(opts: CreateUserIntakeStoreOptions): IntakeStore {\n return createScopedStore({\n db: opts.db,\n graph: opts.graph,\n table: opts.table as unknown as IntakeTableShape,\n scopeColumn: opts.table.userId,\n scopeValue: opts.userId,\n insertScope: { userId: opts.userId },\n })\n}\n\n/** Define options required to create a project intake store including database, table, graph, and workspace ID */\nexport interface CreateProjectIntakeStoreOptions {\n db: IntakeDatabase\n /** The project-intake table from createIntakeTables (workspace scope). */\n table: ProjectIntakeTable\n graph: IntakeGraph\n /** The workspace this intake is attached to. */\n workspaceId: string\n}\n\n/** Build the per-project store, scoped to one workspaceId. */\nexport function createProjectIntakeStore(opts: CreateProjectIntakeStoreOptions): IntakeStore {\n return createScopedStore({\n db: opts.db,\n graph: opts.graph,\n table: opts.table as unknown as IntakeTableShape,\n scopeColumn: opts.table.workspaceId,\n scopeValue: opts.workspaceId,\n insertScope: { workspaceId: opts.workspaceId },\n })\n}\n\nfunction normalizePayload(raw: unknown, graphId: string): IntakePayload {\n if (raw && typeof raw === 'object' && 'answers' in (raw as Record<string, unknown>)) {\n const candidate = raw as Partial<IntakePayload>\n return {\n graphId: candidate.graphId ?? graphId,\n answers: candidate.answers ?? {},\n ...(candidate.completedAt ? { completedAt: candidate.completedAt } : {}),\n }\n }\n return { graphId, answers: {} }\n}\n\nfunction toDate(value: Date | number | null | undefined): Date | null {\n if (value == null) return null\n return value instanceof Date ? value : new Date(Number(value) * (Number(value) < 1e12 ? 1000 : 1))\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,SAAS,UAAU;AAgCZ,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EACT,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AA+BA,SAAS,kBAAkB,MAAuC;AAChE,QAAM,EAAE,IAAI,OAAO,OAAO,aAAa,YAAY,YAAY,IAAI;AAEnE,iBAAe,UAAU;AACvB,UAAM,CAAC,GAAG,IAAI,MAAM,GACjB,OAAO,EACP,KAAK,KAAY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,YAAY,aAAc,KAAiC;AACnF,UAAM,YAAY;AAClB,WAAO;AAAA,MACL,SAAS,UAAU,WAAW;AAAA,MAC9B,SAAS,UAAU,WAAW,CAAC;AAAA,MAC/B,GAAI,UAAU,cAAc,EAAE,aAAa,UAAU,YAAY,IAAI,CAAC;AAAA,IACxE;AAAA,EACF;AACA,SAAO,EAAE,SAAS,SAAS,CAAC,EAAE;AAChC;AAEA,SAAS,OAAO,OAAsD;AACpE,MAAI,SAAS,KAAM,QAAO;AAC1B,SAAO,iBAAiB,OAAO,QAAQ,IAAI,KAAK,OAAO,KAAK,KAAK,OAAO,KAAK,IAAI,OAAO,MAAO,EAAE;AACnG;","names":[]}
@@ -1,30 +0,0 @@
1
- import {
2
- isComplete
3
- } from "./chunk-JDEGS53O.js";
4
-
5
- // src/intakes/completion.ts
6
- function emptyPayload(graph) {
7
- return { graphId: graph.id, answers: {} };
8
- }
9
- function withAnswer(payload, questionId, value) {
10
- return { ...payload, answers: { ...payload.answers, [questionId]: value } };
11
- }
12
- function payloadComplete(graph, payload) {
13
- if (payload.graphId !== graph.id) return false;
14
- return isComplete(graph, payload.answers);
15
- }
16
- function payloadIsStale(graph, payload) {
17
- return payload.graphId !== graph.id;
18
- }
19
- function markComplete(payload, at = /* @__PURE__ */ new Date()) {
20
- return { ...payload, completedAt: at.toISOString() };
21
- }
22
-
23
- export {
24
- emptyPayload,
25
- withAnswer,
26
- payloadComplete,
27
- payloadIsStale,
28
- markComplete
29
- };
30
- //# sourceMappingURL=chunk-YZ6KQULN.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/intakes/completion.ts"],"sourcesContent":["/**\n * Pure completion-state helpers for an intake payload — the small algebra over\n * the JSON blob the store persists. No I/O: the store reads/writes the row;\n * these functions only build and judge the payload shape, so the same logic\n * runs in the UI, the handlers, and the DB layer without divergence.\n *\n * A payload is `{ graphId, answers, completedAt? }`. It carries the answers\n * and the id of the graph they were collected against, so a later graph\n * revision can detect a stale payload (`graphId` mismatch) rather than\n * silently mixing answers from two question sets.\n */\n\nimport type { IntakeAnswers, IntakeAnswerValue, IntakeGraph } from './model'\nimport { isComplete } from './model'\n\n/** The persisted JSON for one intake (the `payload` column). */\nexport interface IntakePayload {\n /** The graph id the answers were collected against — guards stale schemas. */\n graphId: string\n answers: IntakeAnswers\n /** ISO-8601 instant the intake was completed, or undefined while in progress. */\n completedAt?: string\n}\n\n/** An empty payload for a fresh intake against `graph`. */\nexport function emptyPayload(graph: IntakeGraph): IntakePayload {\n return { graphId: graph.id, answers: {} }\n}\n\n/** A copy of `payload` with one answer set (does not mutate the input). */\nexport function withAnswer(\n payload: IntakePayload,\n questionId: string,\n value: IntakeAnswerValue,\n): IntakePayload {\n return { ...payload, answers: { ...payload.answers, [questionId]: value } }\n}\n\n/**\n * True when the payload's answers complete the graph AND the payload was\n * collected against THIS graph. A `graphId` mismatch is never \"complete\" —\n * the answers belong to a different question set and must be re-collected.\n */\nexport function payloadComplete(graph: IntakeGraph, payload: IntakePayload): boolean {\n if (payload.graphId !== graph.id) return false\n return isComplete(graph, payload.answers)\n}\n\n/** True when the payload was collected against a DIFFERENT graph revision. */\nexport function payloadIsStale(graph: IntakeGraph, payload: IntakePayload): boolean {\n return payload.graphId !== graph.id\n}\n\n/**\n * Stamp the payload complete at `at` (default now). Returns a copy; pure. The\n * caller has already checked `payloadComplete` — this only records the instant.\n */\nexport function markComplete(payload: IntakePayload, at: Date = new Date()): IntakePayload {\n return { ...payload, completedAt: at.toISOString() }\n}\n"],"mappings":";;;;;AAyBO,SAAS,aAAa,OAAmC;AAC9D,SAAO,EAAE,SAAS,MAAM,IAAI,SAAS,CAAC,EAAE;AAC1C;AAGO,SAAS,WACd,SACA,YACA,OACe;AACf,SAAO,EAAE,GAAG,SAAS,SAAS,EAAE,GAAG,QAAQ,SAAS,CAAC,UAAU,GAAG,MAAM,EAAE;AAC5E;AAOO,SAAS,gBAAgB,OAAoB,SAAiC;AACnF,MAAI,QAAQ,YAAY,MAAM,GAAI,QAAO;AACzC,SAAO,WAAW,OAAO,QAAQ,OAAO;AAC1C;AAGO,SAAS,eAAe,OAAoB,SAAiC;AAClF,SAAO,QAAQ,YAAY,MAAM;AACnC;AAMO,SAAS,aAAa,SAAwB,KAAW,oBAAI,KAAK,GAAkB;AACzF,SAAO,EAAE,GAAG,SAAS,aAAa,GAAG,YAAY,EAAE;AACrD;","names":[]}
@@ -1,54 +0,0 @@
1
- /**
2
- * Framework-neutral intake API: the get-current / save-answer / complete logic,
3
- * lifted out of any one app's route file. Each app mounts these in its own
4
- * route with its own auth — the handlers take an already-resolved store (the
5
- * caller built it from `createUserIntakeStore` / `createProjectIntakeStore`
6
- * after running RBAC), the intake graph, and the parsed inputs. They return
7
- * web-standard `Response`s (available in Workers, Node 18+, Deno, browsers), so
8
- * "framework-neutral" is literal: no Remix/React-Router/Express import anywhere.
9
- *
10
- * The handlers own the graph→HTTP mapping the UI needs: `getCurrentIntake`
11
- * returns the loaded state PLUS the next question to ask (the question-graph
12
- * traversal from the `./intakes` leaf) and the progress counter, so the client
13
- * renders one question at a time without re-deriving the graph. Store
14
- * `IntakeError`s map to typed 4xx codes, never a generic 500 — an invalid
15
- * answer is a 400, an incomplete-complete is a 409, never a silent success.
16
- *
17
- * Imports `drizzle-orm` transitively (through the store types), so this is a
18
- * subpath, never re-exported from root.
19
- */
20
- import { type IntakeAnswerValue, type IntakeGraph, type IntakeQuestion } from './model';
21
- import { type IntakeStore } from './drizzle/store';
22
- /** What the client renders: the saved state, the next prompt, and progress. */
23
- export interface CurrentIntakeView {
24
- graphId: string;
25
- title: string;
26
- description?: string;
27
- answers: Record<string, IntakeAnswerValue>;
28
- /** The next question to ask, or null when the interview is done. */
29
- nextQuestion: IntakeQuestion | null;
30
- completed: boolean;
31
- completedAt: string | null;
32
- progress: {
33
- answered: number;
34
- total: number;
35
- };
36
- }
37
- /** Define configuration options for initializing the intake API with store and graph components */
38
- export interface IntakeApiOptions {
39
- store: IntakeStore;
40
- graph: IntakeGraph;
41
- }
42
- /**
43
- * Build the intake API bound to one store + graph. Returns three handlers; an
44
- * app maps its route methods onto them (GET→getCurrentIntake, POST→saveAnswer,
45
- * a complete action→completeIntake).
46
- */
47
- export declare function createIntakeApi(opts: IntakeApiOptions): {
48
- getCurrentIntake: () => Promise<Response>;
49
- saveAnswer: (input: {
50
- questionId?: string;
51
- value?: IntakeAnswerValue;
52
- }) => Promise<Response>;
53
- completeIntake: () => Promise<Response>;
54
- };
@@ -1,63 +0,0 @@
1
- import {
2
- IntakeError
3
- } from "../chunk-VWAEWOWK.js";
4
- import "../chunk-YZ6KQULN.js";
5
- import {
6
- intakeProgress,
7
- nextQuestion
8
- } from "../chunk-JDEGS53O.js";
9
-
10
- // src/intakes/api.ts
11
- function createIntakeApi(opts) {
12
- const { store, graph } = opts;
13
- function view(state) {
14
- return {
15
- graphId: graph.id,
16
- title: graph.title,
17
- ...graph.description ? { description: graph.description } : {},
18
- answers: state.payload.answers,
19
- nextQuestion: nextQuestion(graph, state.payload.answers),
20
- completed: state.completed,
21
- completedAt: state.completedAt ? state.completedAt.toISOString() : null,
22
- progress: intakeProgress(graph, state.payload.answers)
23
- };
24
- }
25
- async function getCurrentIntake() {
26
- const state = await store.get();
27
- return Response.json(view(state));
28
- }
29
- async function saveAnswer(input) {
30
- if (!input.questionId) return Response.json({ error: "Missing questionId" }, { status: 400 });
31
- try {
32
- const state = await store.save(input.questionId, input.value ?? null);
33
- return Response.json(view(state));
34
- } catch (err) {
35
- return intakeErrorResponse(err);
36
- }
37
- }
38
- async function completeIntake() {
39
- try {
40
- const state = await store.complete();
41
- return Response.json(view(state));
42
- } catch (err) {
43
- return intakeErrorResponse(err);
44
- }
45
- }
46
- return { getCurrentIntake, saveAnswer, completeIntake };
47
- }
48
- var ERROR_STATUS = {
49
- "invalid-answer": 400,
50
- "unknown-question": 404,
51
- incomplete: 409,
52
- "stale-graph": 409
53
- };
54
- function intakeErrorResponse(err) {
55
- if (err instanceof IntakeError) {
56
- return Response.json({ error: err.message, code: err.code }, { status: ERROR_STATUS[err.code] ?? 400 });
57
- }
58
- throw err;
59
- }
60
- export {
61
- createIntakeApi
62
- };
63
- //# sourceMappingURL=api.js.map