@niscorp/strata 0.1.3 → 0.1.5

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 (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +2 -2
  3. package/dist/check/index.cjs +23 -228
  4. package/dist/check/index.cjs.map +1 -1
  5. package/dist/check/index.js +2 -2
  6. package/dist/{chunk-274M232S.js → chunk-4BLHBVSC.js} +3 -3
  7. package/dist/{chunk-274M232S.js.map → chunk-4BLHBVSC.js.map} +1 -1
  8. package/dist/{chunk-U5CPF4LQ.js → chunk-5KTXEN43.js} +3 -3
  9. package/dist/{chunk-U5CPF4LQ.js.map → chunk-5KTXEN43.js.map} +1 -1
  10. package/dist/{chunk-EGFF63GA.js → chunk-AKKWEXO2.js} +2 -2
  11. package/dist/{chunk-EGFF63GA.js.map → chunk-AKKWEXO2.js.map} +1 -1
  12. package/dist/chunk-ATHZ7HT5.cjs +18 -0
  13. package/dist/chunk-ATHZ7HT5.cjs.map +1 -0
  14. package/dist/chunk-CL5DF2IQ.cjs +192 -0
  15. package/dist/chunk-CL5DF2IQ.cjs.map +1 -0
  16. package/dist/chunk-IHYBGLNW.cjs +161 -0
  17. package/dist/chunk-IHYBGLNW.cjs.map +1 -0
  18. package/dist/chunk-KNBS3AJZ.cjs +223 -0
  19. package/dist/chunk-KNBS3AJZ.cjs.map +1 -0
  20. package/dist/{chunk-TWAEZHTB.js → chunk-OLDORFOQ.js} +4 -4
  21. package/dist/{chunk-TWAEZHTB.js.map → chunk-OLDORFOQ.js.map} +1 -1
  22. package/dist/{chunk-2FIZEJXW.js → chunk-WU3OJHVZ.js} +4 -4
  23. package/dist/{chunk-2FIZEJXW.js.map → chunk-WU3OJHVZ.js.map} +1 -1
  24. package/dist/chunk-YXFEJJMC.cjs +136 -0
  25. package/dist/chunk-YXFEJJMC.cjs.map +1 -0
  26. package/dist/index.cjs +75 -330
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +3 -3
  31. package/dist/node/index.cjs +14 -493
  32. package/dist/node/index.cjs.map +1 -1
  33. package/dist/node/index.js +5 -5
  34. package/dist/{plan-BEIlXVUt.d.cts → plan-CxuteSH1.d.cts} +2 -2
  35. package/dist/{plan-BAewc8DG.d.ts → plan-mFmdh0qT.d.ts} +2 -2
  36. package/dist/postgres/index.cjs +30 -198
  37. package/dist/postgres/index.cjs.map +1 -1
  38. package/dist/postgres/index.d.cts +7 -2
  39. package/dist/postgres/index.d.ts +7 -2
  40. package/dist/postgres/index.js +17 -3
  41. package/dist/postgres/index.js.map +1 -1
  42. package/dist/upgrade/index.cjs +19 -240
  43. package/dist/upgrade/index.cjs.map +1 -1
  44. package/dist/upgrade/index.js +3 -3
  45. package/package.json +1 -1
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+
3
+ var chunkCL5DF2IQ_cjs = require('./chunk-CL5DF2IQ.cjs');
4
+ var chunkATHZ7HT5_cjs = require('./chunk-ATHZ7HT5.cjs');
5
+
6
+ // src/documents.ts
7
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8
+ var pathText = (path) => path.reduce((text, key) => typeof key === "number" ? `${text}[${key}]` : text === "" ? key : `${text}.${key}`, "");
9
+ var reach = (value, pattern) => {
10
+ let frontier = [{ path: [], value }];
11
+ for (const segment of pattern.split(".")) {
12
+ const array = segment.endsWith("[]");
13
+ const key = array ? segment.slice(0, -2) : segment;
14
+ const next = [];
15
+ for (const at of frontier) {
16
+ if (!isRecord(at.value)) continue;
17
+ const found = key === "*" ? Object.entries(at.value).map(([k, v]) => ({ path: [...at.path, k], value: v })) : key in at.value ? [{ path: [...at.path, key], value: at.value[key] }] : [];
18
+ for (const f of found) {
19
+ if (!array) next.push(f);
20
+ else if (Array.isArray(f.value)) f.value.forEach((item, i) => next.push({ path: [...f.path, i], value: item }));
21
+ }
22
+ }
23
+ frontier = next;
24
+ }
25
+ return frontier;
26
+ };
27
+ var getAt = (root, path) => path.reduce((at, key) => {
28
+ if (typeof key === "number") return Array.isArray(at) ? at[key] : void 0;
29
+ return isRecord(at) ? at[key] : void 0;
30
+ }, root);
31
+ var setAt = (root, path, value) => {
32
+ const [head, ...rest] = path;
33
+ if (head === void 0) return value;
34
+ if (typeof head === "number" && Array.isArray(root)) return root.map((item, i) => i === head ? setAt(item, rest, value) : item);
35
+ if (typeof head === "string" && isRecord(root)) return { ...root, [head]: setAt(root[head], rest, value) };
36
+ return root;
37
+ };
38
+ var createUpgrader = async (sequences, options) => {
39
+ const prepared = await chunkCL5DF2IQ_cjs.prepare(sequences);
40
+ const tables = prepared.filter((s) => !s.grammar);
41
+ if (tables.length > 0) {
42
+ throw new chunkATHZ7HT5_cjs.StrataError(
43
+ "WRONG_OWNER",
44
+ "Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`). If one of them is a grammar, declare its `documents` \u2014 a sequence with no `documents` and no document step is read as owning tables.",
45
+ tables.map((s) => s.id)
46
+ );
47
+ }
48
+ const grammars = prepared;
49
+ const kinds = /* @__PURE__ */ new Map();
50
+ for (const sequence of grammars) {
51
+ for (const [name, kind] of Object.entries(sequence.documents)) kinds.set(`${sequence.id}/${name}`, kind);
52
+ }
53
+ const unknown = [
54
+ ...grammars.flatMap((s) => s.migrations.flatMap((m) => m.steps.flatMap((step) => step.kind === "document" && !kinds.has(step.at) ? [`${m.ref} rewrites ${step.at}`] : []))),
55
+ ...[...kinds].flatMap(([ref, kind]) => Object.entries(kind.embeds ?? {}).flatMap(([path, target]) => kinds.has(target) ? [] : [`${ref} embeds ${target} at ${path}`]))
56
+ ];
57
+ if (unknown.length > 0) throw new chunkATHZ7HT5_cjs.StrataError("UNKNOWN_KIND", "A document kind is named that no sequence declares.", unknown);
58
+ const stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));
59
+ const ownIds = new Set(grammars.map((s) => s.id));
60
+ const stampAfter = (given) => {
61
+ const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));
62
+ return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };
63
+ };
64
+ const locate = (document, kind) => {
65
+ if (!kinds.has(kind)) throw new chunkATHZ7HT5_cjs.StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
66
+ const found = [];
67
+ const visit = (value, at, path) => {
68
+ if (!isRecord(value)) return;
69
+ found.push({ path, kind: at, value });
70
+ for (const [pattern, target] of Object.entries(kinds.get(at)?.embeds ?? {})) {
71
+ for (const hit of reach(value, pattern)) visit(hit.value, target, [...path, ...hit.path]);
72
+ }
73
+ };
74
+ visit(document, kind, []);
75
+ return found;
76
+ };
77
+ const positionOf = (given, id) => given?.[id] ?? 0;
78
+ const behind = (given) => {
79
+ const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);
80
+ if (ahead.length > 0) {
81
+ throw new chunkATHZ7HT5_cjs.StrataError(
82
+ "TOO_NEW",
83
+ "This document was written by newer code than this \u2014 reading it would be guessing.",
84
+ ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`)
85
+ );
86
+ }
87
+ return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);
88
+ };
89
+ const upgrade = (document, { kind, stamp: given }) => {
90
+ if (!isRecord(document)) throw new chunkATHZ7HT5_cjs.StrataError("STEP_FAILED", `A ${kind} document must be a JSON object.`);
91
+ if (!kinds.has(kind)) throw new chunkATHZ7HT5_cjs.StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
92
+ if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };
93
+ const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));
94
+ const { pending, stuck } = chunkCL5DF2IQ_cjs.orderPending(
95
+ grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),
96
+ done
97
+ );
98
+ if (stuck.length > 0) throw new chunkATHZ7HT5_cjs.StrataError("CYCLE", "Document migrations wait on each other and can never run.", stuck.map((m) => m.ref));
99
+ let current = document;
100
+ const applied = [];
101
+ const runStep = (migration, at, transform) => {
102
+ const targets = locate(current, kind).filter((l) => l.kind === at).sort((a, b) => b.path.length - a.path.length);
103
+ for (const target of targets) {
104
+ const value = getAt(current, target.path);
105
+ let rewritten;
106
+ try {
107
+ rewritten = options.transform(transform, { document: value, path: pathText(target.path) });
108
+ } catch (cause) {
109
+ throw new chunkATHZ7HT5_cjs.StrataError(
110
+ "STEP_FAILED",
111
+ `${migration.ref} ("${migration.description}") failed on the ${at} at ${pathText(target.path) || "(root)"}.`,
112
+ [cause instanceof Error ? cause.message : String(cause)],
113
+ { cause }
114
+ );
115
+ }
116
+ if (!isRecord(rewritten)) {
117
+ throw new chunkATHZ7HT5_cjs.StrataError("STEP_FAILED", `${migration.ref} turned the ${at} at ${pathText(target.path) || "(root)"} into something that is not a document.`, [
118
+ JSON.stringify(rewritten)?.slice(0, 200) ?? String(rewritten)
119
+ ]);
120
+ }
121
+ const next = setAt(current, target.path, rewritten);
122
+ if (isRecord(next)) current = next;
123
+ }
124
+ };
125
+ for (const migration of pending) {
126
+ for (const step of migration.steps) if (step.kind === "document") runStep(migration, step.at, step.transform);
127
+ applied.push(migration.ref);
128
+ }
129
+ return { document: current, stamp: stampAfter(given), applied };
130
+ };
131
+ return { stamp, upgrade, locate, behind };
132
+ };
133
+
134
+ exports.createUpgrader = createUpgrader;
135
+ //# sourceMappingURL=chunk-YXFEJJMC.cjs.map
136
+ //# sourceMappingURL=chunk-YXFEJJMC.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/documents.ts"],"names":["prepare","StrataError","orderPending"],"mappings":";;;;;;AAqDA,IAAM,QAAA,GAAW,CAAC,KAAA,KAChB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,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C5G,MAAA,OAAA,CAAQ,IAAA,CAAK,UAAU,GAAG,CAAA;AAAA,IAC5B;AACA,IAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,OAAO,UAAA,CAAW,KAAK,GAAG,OAAA,EAAQ;AAAA,EAChE,CAAA;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,OAAA,EAAS,MAAA,EAAQ,MAAA,EAAO;AAC1C","file":"chunk-YXFEJJMC.cjs","sourcesContent":["import { prepare, orderPending, type PreparedMigration, type PreparedSequence } from './plan';\nimport type { DocumentKind, Sequence } from './schema';\nimport { StrataError } from './errors';\n\n// ═══════════════════════════════════════════════════════════════\n// Documents — the JSON a grammar describes, wherever it is kept.\n//\n// A document carries a STAMP: for each grammar sequence, how far along that\n// sequence the writer was (`{ \"nisc.nova\": 3, \"nisc.prism\": 1 }`). Upgrading\n// runs every document migration the stamp has not seen, in the ledger's order,\n// and hands back the document with a current stamp. The same function serves a\n// row read at boot, a submission at intake and a file in an app's source tree:\n// the document does not care where it was kept.\n//\n// NESTING IS THE GRAMMAR'S, NOT THE MIGRATION'S. A kind declares where other\n// documents sit inside it (its embeddings: nova's layout holds layouts at\n// `children`, `children[]`, `then`, `else`, `do`; an action holds a layout and\n// Prism configs). The walker finds every document of a step's kind at any\n// depth and rewrites each on its own, deepest first. A transform only ever sees\n// ONE node — so migrations stay flat, and a Prism config can express them\n// without recursion of its own.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Stamp = Readonly<Record<string, number>>;\n\n// Where a document sits: the path from the root (keys and indexes) and its kind.\nexport type Location = { path: readonly (string | number)[]; kind: string; value: Record<string, unknown> };\n\n// The injected evaluator — nova's `transform` socket, the same shape: under moss\n// it is Prism's `evaluate`, and a migration runs exactly the way an endpoint does.\nexport type Transform = (config: unknown, source: unknown) => unknown;\n\nexport type UpgradeResult = {\n document: Record<string, unknown>;\n // What to store with the document: current on every grammar the upgrader was\n // given, and the document's entries for any other grammar kept as they were.\n stamp: Stamp;\n // What ran, in order — empty when the document was already current.\n applied: readonly string[];\n};\n\nexport type Upgrader = {\n // The stamp a document written NOW carries.\n stamp: Stamp;\n upgrade: (document: unknown, options: { kind: string; stamp?: Stamp | null }) => UpgradeResult;\n // Every document inside `document` (itself included), by kind — what the\n // walker sees. For a page that shows it, and for a check that asserts it.\n locate: (document: unknown, kind: string) => Location[];\n // Is a document at this stamp behind the code (true), current (false)? Throws\n // TOO_NEW if it is ahead.\n behind: (stamp: Stamp | null | undefined) => boolean;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst pathText = (path: readonly (string | number)[]): string =>\n path.reduce<string>((text, key) => (typeof key === 'number' ? `${text}[${key}]` : text === '' ? key : `${text}.${key}`), '');\n\n// One embedding pattern, applied to one value: every (relative path, value)\n// the pattern reaches. `key` descends, `*` crosses a record's values, and a\n// `[]` suffix crosses the array found there.\nconst reach = (value: unknown, pattern: string): { path: (string | number)[]; value: unknown }[] => {\n let frontier: { path: (string | number)[]; value: unknown }[] = [{ path: [], value }];\n for (const segment of pattern.split('.')) {\n const array = segment.endsWith('[]');\n const key = array ? segment.slice(0, -2) : segment;\n const next: { path: (string | number)[]; value: unknown }[] = [];\n for (const at of frontier) {\n if (!isRecord(at.value)) continue;\n const found: { path: (string | number)[]; value: unknown }[] =\n key === '*'\n ? Object.entries(at.value).map(([k, v]) => ({ path: [...at.path, k], value: v }))\n : key in at.value\n ? [{ path: [...at.path, key], value: at.value[key] }]\n : [];\n for (const f of found) {\n if (!array) next.push(f);\n else if (Array.isArray(f.value)) f.value.forEach((item, i) => next.push({ path: [...f.path, i], value: item }));\n }\n }\n frontier = next;\n }\n return frontier;\n};\n\nconst getAt = (root: unknown, path: readonly (string | number)[]): unknown =>\n path.reduce<unknown>((at, key) => {\n if (typeof key === 'number') return Array.isArray(at) ? at[key] : undefined;\n return isRecord(at) ? at[key] : undefined;\n }, root);\n\nconst setAt = (root: unknown, path: readonly (string | number)[], value: unknown): unknown => {\n const [head, ...rest] = path;\n if (head === undefined) return value;\n if (typeof head === 'number' && Array.isArray(root)) return root.map((item, i) => (i === head ? setAt(item, rest, value) : item));\n if (typeof head === 'string' && isRecord(root)) return { ...root, [head]: setAt(root[head], rest, value) };\n return root;\n};\n\nexport const createUpgrader = async (sequences: readonly Sequence[], options: { transform: Transform }): Promise<Upgrader> => {\n const prepared = await prepare(sequences);\n const tables = prepared.filter((s) => !s.grammar);\n if (tables.length > 0) {\n // A sequence is read as a grammar by what it declares (plan.ts). One with\n // nothing but markers and no `documents` reads as owning tables, so the\n // refusal says how a grammar says it is one — `migrate` alone would send a\n // kit's markers to a database's ledger.\n throw new StrataError(\n 'WRONG_OWNER',\n 'Documents are upgraded by grammar sequences; these own tables and belong to a database\\'s ledger (`migrate`). If one of them is a grammar, declare its `documents` — a sequence with no `documents` and no document step is read as owning tables.',\n tables.map((s) => s.id),\n );\n }\n const grammars: readonly PreparedSequence[] = prepared;\n\n const kinds = new Map<string, DocumentKind>();\n for (const sequence of grammars) {\n for (const [name, kind] of Object.entries(sequence.documents)) kinds.set(`${sequence.id}/${name}`, kind);\n }\n const unknown = [\n ...grammars.flatMap((s) => s.migrations.flatMap((m) => m.steps.flatMap((step) => (step.kind === 'document' && !kinds.has(step.at) ? [`${m.ref} rewrites ${step.at}`] : [])))),\n ...[...kinds].flatMap(([ref, kind]) => Object.entries(kind.embeds ?? {}).flatMap(([path, target]) => (kinds.has(target) ? [] : [`${ref} embeds ${target} at ${path}`]))),\n ];\n if (unknown.length > 0) throw new StrataError('UNKNOWN_KIND', 'A document kind is named that no sequence declares.', unknown);\n\n const stamp: Stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));\n\n // The stamp a document carries once this code has read it: this code's\n // position on every grammar it was given and — as they were — the document's\n // own entries for grammars it was not. Those record code this reader lacks (a\n // kit it does not have); dropping them would let code that does have the\n // grammar run its migrations over the document a second time.\n const ownIds = new Set(grammars.map((s) => s.id));\n const stampAfter = (given: Stamp | null | undefined): Stamp => {\n const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));\n return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };\n };\n\n const locate = (document: unknown, kind: string): Location[] => {\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n const found: Location[] = [];\n const visit = (value: unknown, at: string, path: (string | number)[]): void => {\n if (!isRecord(value)) return;\n found.push({ path, kind: at, value });\n for (const [pattern, target] of Object.entries(kinds.get(at)?.embeds ?? {})) {\n for (const hit of reach(value, pattern)) visit(hit.value, target, [...path, ...hit.path]);\n }\n };\n visit(document, kind, []);\n return found;\n };\n\n const positionOf = (given: Stamp | null | undefined, id: string): number => given?.[id] ?? 0;\n\n const behind = (given: Stamp | null | undefined): boolean => {\n const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);\n if (ahead.length > 0) {\n throw new StrataError(\n 'TOO_NEW',\n 'This document was written by newer code than this — reading it would be guessing.',\n ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`),\n );\n }\n return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);\n };\n\n const upgrade = (document: unknown, { kind, stamp: given }: { kind: string; stamp?: Stamp | null }): UpgradeResult => {\n if (!isRecord(document)) throw new StrataError('STEP_FAILED', `A ${kind} document must be a JSON object.`);\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };\n\n // What this document has seen: everything up to its stamp, per sequence.\n // A sequence it has never heard of starts at 0 — a document written before\n // a grammar existed simply has none of its migrations yet.\n const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));\n const { pending, stuck } = orderPending(\n grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),\n done,\n );\n if (stuck.length > 0) throw new StrataError('CYCLE', 'Document migrations wait on each other and can never run.', stuck.map((m) => m.ref));\n\n let current: Record<string, unknown> = document;\n const applied: string[] = [];\n const runStep = (migration: PreparedMigration, at: string, transform: unknown): void => {\n // Deepest first: a parent's rewrite sees its children already rewritten,\n // and replacing a child never moves the path to its parent.\n const targets = locate(current, kind)\n .filter((l) => l.kind === at)\n .sort((a, b) => b.path.length - a.path.length);\n for (const target of targets) {\n // The value NOW, not when the targets were found: a child rewritten a\n // moment ago lives in `current`, and the parent must see — and keep — it.\n const value = getAt(current, target.path);\n let rewritten: unknown;\n try {\n rewritten = options.transform(transform, { document: value, path: pathText(target.path) });\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed on the ${at} at ${pathText(target.path) || '(root)'}.`,\n [cause instanceof Error ? cause.message : String(cause)],\n { cause },\n );\n }\n if (!isRecord(rewritten)) {\n throw new StrataError('STEP_FAILED', `${migration.ref} turned the ${at} at ${pathText(target.path) || '(root)'} into something that is not a document.`, [\n JSON.stringify(rewritten)?.slice(0, 200) ?? String(rewritten),\n ]);\n }\n const next = setAt(current, target.path, rewritten);\n if (isRecord(next)) current = next;\n }\n };\n for (const migration of pending) {\n for (const step of migration.steps) if (step.kind === 'document') runStep(migration, step.at, step.transform);\n applied.push(migration.ref);\n }\n return { document: current, stamp: stampAfter(given), applied };\n };\n\n return { stamp, upgrade, locate, behind };\n};\n"]}
package/dist/index.cjs CHANGED
@@ -1,317 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
-
5
- // src/schema.ts
6
- var SEQUENCE_ID = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
7
- var MIGRATION_REF = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+\/[1-9][0-9]*$/;
8
- var KIND_NAME = /^[a-z][a-z0-9-]*$/;
9
- var KIND_REF = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+\/[a-z][a-z0-9-]*$/;
10
- var EMBED_PATH = /^([A-Za-z_$][\w$]*|\*)(\[\])?(\.([A-Za-z_$][\w$]*|\*)(\[\])?)*$/;
11
- var SqlStepSchema = zod.z.object({
12
- kind: zod.z.literal("sql"),
13
- sql: zod.z.string().min(1).describe(
14
- "ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string carrying several \u2014 split them into steps rather than joining them with semicolons."
15
- )
16
- }).strict().describe("A statement run against the database, inside the migration transaction.");
17
- var DocumentStepSchema = zod.z.object({
18
- kind: zod.z.literal("document"),
19
- at: zod.z.string().regex(KIND_REF).describe('The kind of document this step rewrites, e.g. "nisc.nova/layout" \u2014 wherever one sits, at any depth.'),
20
- transform: zod.z.unknown().describe(
21
- "A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the grammar's embeddings and rewritten on their own, deepest first \u2014 a transform only ever sees one flat node."
22
- )
23
- }).strict().describe("A rewrite of stored JSON documents of one kind.");
24
- var StepSchema = zod.z.discriminatedUnion("kind", [SqlStepSchema, DocumentStepSchema]);
25
- var DocumentKindSchema = zod.z.object({
26
- embeds: zod.z.record(zod.z.string().regex(EMBED_PATH), zod.z.string().regex(KIND_REF)).optional().describe("Where other documents sit inside this one: path \u2192 the kind found there (possibly this kind itself).")
27
- }).strict();
28
- var MigrationSchema = zod.z.object({
29
- description: zod.z.string().min(1).describe("One sentence: what this migration does. It is the changelog line and the ledger's description."),
30
- steps: zod.z.array(StepSchema).describe(
31
- "Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: the version moves and nothing runs \u2014 how an addition to a strict grammar tells older readers to refuse."
32
- ),
33
- dependsOn: zod.z.array(zod.z.string().regex(MIGRATION_REF)).optional().describe('Migrations of OTHER sequences that must be applied first, each as "<sequence>/<n>".')
34
- }).strict();
35
- var SequenceSchema = zod.z.object({
36
- id: zod.z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. "nisc.vex.cache" or "midas.app".'),
37
- documents: zod.z.record(zod.z.string().regex(KIND_NAME), DocumentKindSchema).optional().describe('The document kinds this sequence owns (a GRAMMAR sequence), each named "<id>/<kind>" elsewhere.'),
38
- migrations: zod.z.array(MigrationSchema).describe("Append-only. A migration is numbered by its position (from 1); the sequence's version is its length.")
39
- }).strict().superRefine((sequence, ctx) => {
40
- const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));
41
- if (kinds.has("sql") && (kinds.has("document") || sequence.documents !== void 0)) {
42
- ctx.addIssue({
43
- code: "custom",
44
- message: "A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both."
45
- });
46
- }
47
- });
48
-
49
- // src/checksum.ts
50
- var canonical = (value) => {
51
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
52
- if (value !== null && typeof value === "object") {
53
- const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
54
- return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
55
- }
56
- return JSON.stringify(value);
57
- };
58
- var effectOf = (sql) => sql.split("\n").filter((line) => !line.trimStart().startsWith("--")).map((line) => line.trimEnd()).join("\n").trim();
59
- var checksumOf = async (migration) => {
60
- const steps = migration.steps.map((step) => step.kind === "sql" ? { ...step, sql: effectOf(step.sql) } : step);
61
- const bytes = new TextEncoder().encode(canonical(steps));
62
- const digest = await crypto.subtle.digest("SHA-256", bytes);
63
- return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
64
- };
65
-
66
- // src/errors.ts
67
- var StrataError = class extends Error {
68
- code;
69
- details;
70
- constructor(code, message, details = [], options) {
71
- super(details.length > 0 ? `${message}
72
- ${details.map((d) => ` ${d}`).join("\n")}` : message, options);
73
- this.name = "StrataError";
74
- this.code = code;
75
- this.details = details;
76
- }
77
- };
78
-
79
- // src/plan.ts
80
- var refOf = (sequence, n) => `${sequence}/${n}`;
81
- var prepare = async (sequences) => {
82
- const seen = /* @__PURE__ */ new Set();
83
- const prepared = [];
84
- for (const input of sequences) {
85
- const parsed = SequenceSchema.safeParse(input);
86
- if (!parsed.success) {
87
- const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`);
88
- throw new StrataError("INVALID_SEQUENCE", `A sequence does not parse${typeof input.id === "string" ? ` ("${input.id}")` : ""}.`, issues);
89
- }
90
- const sequence = parsed.data;
91
- if (seen.has(sequence.id)) {
92
- throw new StrataError("INVALID_SEQUENCE", `Two sequences are both called "${sequence.id}" \u2014 a sequence id names one owner.`);
93
- }
94
- seen.add(sequence.id);
95
- const migrations = [];
96
- for (const [index, migration] of sequence.migrations.entries()) {
97
- const n = index + 1;
98
- migrations.push({
99
- sequence: sequence.id,
100
- n,
101
- ref: refOf(sequence.id, n),
102
- description: migration.description,
103
- checksum: await checksumOf(migration),
104
- steps: migration.steps,
105
- dependsOn: migration.dependsOn ?? []
106
- });
107
- }
108
- const grammar = sequence.documents !== void 0 || sequence.migrations.some((m) => m.steps.some((s) => s.kind === "document"));
109
- prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });
110
- }
111
- return prepared;
112
- };
113
- var orderPending = (queues, alreadyDone) => {
114
- const done = new Set(alreadyDone);
115
- const waiting = queues.map((q) => [...q.waiting]);
116
- const pending = [];
117
- let moved = true;
118
- while (moved) {
119
- moved = false;
120
- for (const queue of waiting) {
121
- for (let head = queue[0]; head !== void 0; head = queue[0]) {
122
- if (!head.dependsOn.every((d) => done.has(d))) break;
123
- pending.push(head);
124
- done.add(head.ref);
125
- queue.shift();
126
- moved = true;
127
- }
128
- }
129
- }
130
- return { pending, stuck: waiting.flat() };
131
- };
132
- var planMigrations = (sequences, ledger) => {
133
- const problems = [];
134
- const applied = {};
135
- const done = new Set(ledger.map((row) => refOf(row.sequence, row.n)));
136
- const byRef = new Map(ledger.map((row) => [refOf(row.sequence, row.n), row]));
137
- const queues = [];
138
- for (const sequence of sequences) {
139
- const rows = ledger.filter((row) => row.sequence === sequence.id);
140
- applied[sequence.id] = rows.length;
141
- const beyond = rows.filter((row) => row.n > sequence.migrations.length);
142
- if (beyond.length > 0) {
143
- problems.push({
144
- code: "TOO_NEW",
145
- detail: `${sequence.id}: the database is at ${Math.max(...rows.map((r) => r.n))}, this code knows ${sequence.migrations.length} \u2014 it was migrated by newer code.`
146
- });
147
- }
148
- const waiting = [];
149
- for (const migration of sequence.migrations) {
150
- const row = byRef.get(migration.ref);
151
- if (row === void 0) {
152
- waiting.push(migration);
153
- } else if (row.checksum !== migration.checksum) {
154
- problems.push({
155
- code: "EDITED",
156
- detail: `${migration.ref} ("${migration.description}") was applied ${row.appliedAt} and its steps have changed since. An applied migration is history \u2014 append a new one.`
157
- });
158
- }
159
- }
160
- const firstWaiting = waiting[0];
161
- if (firstWaiting !== void 0 && rows.some((row) => row.n > firstWaiting.n)) {
162
- problems.push({ code: "EDITED", detail: `${sequence.id}: ${firstWaiting.ref} never ran, but a later migration of the sequence did.` });
163
- }
164
- queues.push({ id: sequence.id, waiting });
165
- }
166
- const provided = new Set(sequences.flatMap((s) => s.migrations.map((m) => m.ref)));
167
- for (const { waiting } of queues) {
168
- for (const migration of waiting) {
169
- for (const dependency of migration.dependsOn) {
170
- if (!done.has(dependency) && !provided.has(dependency)) {
171
- problems.push({ code: "UNKNOWN_DEPENDENCY", detail: `${migration.ref} depends on ${dependency}, which nothing provides and the database has not run.` });
172
- }
173
- }
174
- }
175
- }
176
- const { pending, stuck } = orderPending(queues, done);
177
- if (stuck.length > 0 && !problems.some((p) => p.code === "UNKNOWN_DEPENDENCY")) {
178
- problems.push({ code: "CYCLE", detail: `These wait on each other and can never run: ${stuck.map((m) => m.ref).join(", ")}.` });
179
- }
180
- return { applied, pending, problems };
181
- };
182
- var refuseProblems = (plan) => {
183
- const first = plan.problems[0];
184
- if (first === void 0) return;
185
- throw new StrataError(first.code, "The migrations cannot be applied safely.", plan.problems.map((p) => `${p.code}: ${p.detail}`));
186
- };
187
-
188
- // src/documents.ts
189
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
190
- var pathText = (path) => path.reduce((text, key) => typeof key === "number" ? `${text}[${key}]` : text === "" ? key : `${text}.${key}`, "");
191
- var reach = (value, pattern) => {
192
- let frontier = [{ path: [], value }];
193
- for (const segment of pattern.split(".")) {
194
- const array = segment.endsWith("[]");
195
- const key = array ? segment.slice(0, -2) : segment;
196
- const next = [];
197
- for (const at of frontier) {
198
- if (!isRecord(at.value)) continue;
199
- const found = key === "*" ? Object.entries(at.value).map(([k, v]) => ({ path: [...at.path, k], value: v })) : key in at.value ? [{ path: [...at.path, key], value: at.value[key] }] : [];
200
- for (const f of found) {
201
- if (!array) next.push(f);
202
- else if (Array.isArray(f.value)) f.value.forEach((item, i) => next.push({ path: [...f.path, i], value: item }));
203
- }
204
- }
205
- frontier = next;
206
- }
207
- return frontier;
208
- };
209
- var getAt = (root, path) => path.reduce((at, key) => {
210
- if (typeof key === "number") return Array.isArray(at) ? at[key] : void 0;
211
- return isRecord(at) ? at[key] : void 0;
212
- }, root);
213
- var setAt = (root, path, value) => {
214
- const [head, ...rest] = path;
215
- if (head === void 0) return value;
216
- if (typeof head === "number" && Array.isArray(root)) return root.map((item, i) => i === head ? setAt(item, rest, value) : item);
217
- if (typeof head === "string" && isRecord(root)) return { ...root, [head]: setAt(root[head], rest, value) };
218
- return root;
219
- };
220
- var createUpgrader = async (sequences, options) => {
221
- const prepared = await prepare(sequences);
222
- const tables = prepared.filter((s) => !s.grammar);
223
- if (tables.length > 0) {
224
- throw new StrataError(
225
- "WRONG_OWNER",
226
- "Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`). If one of them is a grammar, declare its `documents` \u2014 a sequence with no `documents` and no document step is read as owning tables.",
227
- tables.map((s) => s.id)
228
- );
229
- }
230
- const grammars = prepared;
231
- const kinds = /* @__PURE__ */ new Map();
232
- for (const sequence of grammars) {
233
- for (const [name, kind] of Object.entries(sequence.documents)) kinds.set(`${sequence.id}/${name}`, kind);
234
- }
235
- const unknown = [
236
- ...grammars.flatMap((s) => s.migrations.flatMap((m) => m.steps.flatMap((step) => step.kind === "document" && !kinds.has(step.at) ? [`${m.ref} rewrites ${step.at}`] : []))),
237
- ...[...kinds].flatMap(([ref, kind]) => Object.entries(kind.embeds ?? {}).flatMap(([path, target]) => kinds.has(target) ? [] : [`${ref} embeds ${target} at ${path}`]))
238
- ];
239
- if (unknown.length > 0) throw new StrataError("UNKNOWN_KIND", "A document kind is named that no sequence declares.", unknown);
240
- const stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));
241
- const ownIds = new Set(grammars.map((s) => s.id));
242
- const stampAfter = (given) => {
243
- const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));
244
- return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };
245
- };
246
- const locate = (document, kind) => {
247
- if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
248
- const found = [];
249
- const visit = (value, at, path) => {
250
- if (!isRecord(value)) return;
251
- found.push({ path, kind: at, value });
252
- for (const [pattern, target] of Object.entries(kinds.get(at)?.embeds ?? {})) {
253
- for (const hit of reach(value, pattern)) visit(hit.value, target, [...path, ...hit.path]);
254
- }
255
- };
256
- visit(document, kind, []);
257
- return found;
258
- };
259
- const positionOf = (given, id) => given?.[id] ?? 0;
260
- const behind = (given) => {
261
- const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);
262
- if (ahead.length > 0) {
263
- throw new StrataError(
264
- "TOO_NEW",
265
- "This document was written by newer code than this \u2014 reading it would be guessing.",
266
- ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`)
267
- );
268
- }
269
- return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);
270
- };
271
- const upgrade = (document, { kind, stamp: given }) => {
272
- if (!isRecord(document)) throw new StrataError("STEP_FAILED", `A ${kind} document must be a JSON object.`);
273
- if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
274
- if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };
275
- const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));
276
- const { pending, stuck } = orderPending(
277
- grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),
278
- done
279
- );
280
- if (stuck.length > 0) throw new StrataError("CYCLE", "Document migrations wait on each other and can never run.", stuck.map((m) => m.ref));
281
- let current = document;
282
- const applied = [];
283
- const runStep = (migration, at, transform) => {
284
- const targets = locate(current, kind).filter((l) => l.kind === at).sort((a, b) => b.path.length - a.path.length);
285
- for (const target of targets) {
286
- const value = getAt(current, target.path);
287
- let rewritten;
288
- try {
289
- rewritten = options.transform(transform, { document: value, path: pathText(target.path) });
290
- } catch (cause) {
291
- throw new StrataError(
292
- "STEP_FAILED",
293
- `${migration.ref} ("${migration.description}") failed on the ${at} at ${pathText(target.path) || "(root)"}.`,
294
- [cause instanceof Error ? cause.message : String(cause)],
295
- { cause }
296
- );
297
- }
298
- if (!isRecord(rewritten)) {
299
- throw new StrataError("STEP_FAILED", `${migration.ref} turned the ${at} at ${pathText(target.path) || "(root)"} into something that is not a document.`, [
300
- JSON.stringify(rewritten)?.slice(0, 200) ?? String(rewritten)
301
- ]);
302
- }
303
- const next = setAt(current, target.path, rewritten);
304
- if (isRecord(next)) current = next;
305
- }
306
- };
307
- for (const migration of pending) {
308
- for (const step of migration.steps) if (step.kind === "document") runStep(migration, step.at, step.transform);
309
- applied.push(migration.ref);
310
- }
311
- return { document: current, stamp: stampAfter(given), applied };
312
- };
313
- return { stamp, upgrade, locate, behind };
314
- };
3
+ var chunkYXFEJJMC_cjs = require('./chunk-YXFEJJMC.cjs');
4
+ var chunkCL5DF2IQ_cjs = require('./chunk-CL5DF2IQ.cjs');
5
+ var chunkATHZ7HT5_cjs = require('./chunk-ATHZ7HT5.cjs');
315
6
 
316
7
  // src/sql.ts
317
8
  var isComment = (line) => line.trim().startsWith("--");
@@ -348,28 +39,82 @@ var depthRefusal = (limit = DOCUMENT_DEPTH_LIMIT) => `the document nests deeper
348
39
  // src/index.ts
349
40
  var defineSequence = (sequence) => sequence;
350
41
 
42
+ Object.defineProperty(exports, "createUpgrader", {
43
+ enumerable: true,
44
+ get: function () { return chunkYXFEJJMC_cjs.createUpgrader; }
45
+ });
46
+ Object.defineProperty(exports, "DocumentKindSchema", {
47
+ enumerable: true,
48
+ get: function () { return chunkCL5DF2IQ_cjs.DocumentKindSchema; }
49
+ });
50
+ Object.defineProperty(exports, "DocumentStepSchema", {
51
+ enumerable: true,
52
+ get: function () { return chunkCL5DF2IQ_cjs.DocumentStepSchema; }
53
+ });
54
+ Object.defineProperty(exports, "EMBED_PATH", {
55
+ enumerable: true,
56
+ get: function () { return chunkCL5DF2IQ_cjs.EMBED_PATH; }
57
+ });
58
+ Object.defineProperty(exports, "KIND_NAME", {
59
+ enumerable: true,
60
+ get: function () { return chunkCL5DF2IQ_cjs.KIND_NAME; }
61
+ });
62
+ Object.defineProperty(exports, "KIND_REF", {
63
+ enumerable: true,
64
+ get: function () { return chunkCL5DF2IQ_cjs.KIND_REF; }
65
+ });
66
+ Object.defineProperty(exports, "MIGRATION_REF", {
67
+ enumerable: true,
68
+ get: function () { return chunkCL5DF2IQ_cjs.MIGRATION_REF; }
69
+ });
70
+ Object.defineProperty(exports, "MigrationSchema", {
71
+ enumerable: true,
72
+ get: function () { return chunkCL5DF2IQ_cjs.MigrationSchema; }
73
+ });
74
+ Object.defineProperty(exports, "SEQUENCE_ID", {
75
+ enumerable: true,
76
+ get: function () { return chunkCL5DF2IQ_cjs.SEQUENCE_ID; }
77
+ });
78
+ Object.defineProperty(exports, "SequenceSchema", {
79
+ enumerable: true,
80
+ get: function () { return chunkCL5DF2IQ_cjs.SequenceSchema; }
81
+ });
82
+ Object.defineProperty(exports, "SqlStepSchema", {
83
+ enumerable: true,
84
+ get: function () { return chunkCL5DF2IQ_cjs.SqlStepSchema; }
85
+ });
86
+ Object.defineProperty(exports, "StepSchema", {
87
+ enumerable: true,
88
+ get: function () { return chunkCL5DF2IQ_cjs.StepSchema; }
89
+ });
90
+ Object.defineProperty(exports, "checksumOf", {
91
+ enumerable: true,
92
+ get: function () { return chunkCL5DF2IQ_cjs.checksumOf; }
93
+ });
94
+ Object.defineProperty(exports, "orderPending", {
95
+ enumerable: true,
96
+ get: function () { return chunkCL5DF2IQ_cjs.orderPending; }
97
+ });
98
+ Object.defineProperty(exports, "planMigrations", {
99
+ enumerable: true,
100
+ get: function () { return chunkCL5DF2IQ_cjs.planMigrations; }
101
+ });
102
+ Object.defineProperty(exports, "prepare", {
103
+ enumerable: true,
104
+ get: function () { return chunkCL5DF2IQ_cjs.prepare; }
105
+ });
106
+ Object.defineProperty(exports, "refuseProblems", {
107
+ enumerable: true,
108
+ get: function () { return chunkCL5DF2IQ_cjs.refuseProblems; }
109
+ });
110
+ Object.defineProperty(exports, "StrataError", {
111
+ enumerable: true,
112
+ get: function () { return chunkATHZ7HT5_cjs.StrataError; }
113
+ });
351
114
  exports.DOCUMENT_DEPTH_LIMIT = DOCUMENT_DEPTH_LIMIT;
352
- exports.DocumentKindSchema = DocumentKindSchema;
353
- exports.DocumentStepSchema = DocumentStepSchema;
354
- exports.EMBED_PATH = EMBED_PATH;
355
- exports.KIND_NAME = KIND_NAME;
356
- exports.KIND_REF = KIND_REF;
357
- exports.MIGRATION_REF = MIGRATION_REF;
358
- exports.MigrationSchema = MigrationSchema;
359
- exports.SEQUENCE_ID = SEQUENCE_ID;
360
- exports.SequenceSchema = SequenceSchema;
361
- exports.SqlStepSchema = SqlStepSchema;
362
- exports.StepSchema = StepSchema;
363
- exports.StrataError = StrataError;
364
- exports.checksumOf = checksumOf;
365
- exports.createUpgrader = createUpgrader;
366
115
  exports.defineSequence = defineSequence;
367
116
  exports.depthRefusal = depthRefusal;
368
117
  exports.exceedsDepth = exceedsDepth;
369
- exports.orderPending = orderPending;
370
- exports.planMigrations = planMigrations;
371
- exports.prepare = prepare;
372
- exports.refuseProblems = refuseProblems;
373
118
  exports.sqlSteps = sqlSteps;
374
119
  //# sourceMappingURL=index.cjs.map
375
120
  //# sourceMappingURL=index.cjs.map