@drzl/cli 4.23.0 → 4.24.1

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.
@@ -1,634 +0,0 @@
1
- // ../generator-effect/dist/index.js
2
- import { fileWriter } from "@drzl/validation-core";
3
- import {
4
- buildBrandPlan,
5
- buildNestedPlan,
6
- formatCode,
7
- nestedArmNotes,
8
- nestedNodeColumns,
9
- nestedSchemaName,
10
- nestedTypeName,
11
- resolveNestedDepth,
12
- applyWirePolicy,
13
- canonicalMembers,
14
- canonicalNumericText,
15
- comparisonWire,
16
- describeSet,
17
- needsNumericCanon,
18
- CODEPOINT_LENGTH,
19
- COERCIBLE_DATE_STRING,
20
- COLUMN_FORMATS,
21
- NUMERIC_CANON_NAME,
22
- NUMERIC_CANON_SOURCE,
23
- insertColumns,
24
- isIntegerColumn,
25
- lengthCheckLabel,
26
- lengthMeasure,
27
- measureExpression,
28
- moduleFileName,
29
- moduleSpecifier,
30
- nonFiniteAccepted,
31
- parseCheck,
32
- parsesToADate,
33
- renderDuplicateFinder,
34
- resolveAffix,
35
- resolveConfiguredImport,
36
- schemaName,
37
- selectColumns,
38
- typeName,
39
- updateColumns,
40
- wireNumberLiteral
41
- } from "@drzl/validation-core";
42
- var DEFAULT_FILE_SUFFIX = ".effect.ts";
43
- var STANDARD_PREFIX = "Standard";
44
- var NS = "Schema";
45
- var OPS = {
46
- ">=": ">=",
47
- ">": ">",
48
- "<=": "<=",
49
- "<": "<",
50
- "=": "===",
51
- "<>": "!=="
52
- };
53
- function filter(expr, description) {
54
- return `${NS}.filter((v) => ${expr}, { description: ${JSON.stringify(description)} })`;
55
- }
56
- function piped(base, steps) {
57
- return steps.length ? `${base}.pipe(${steps.join(", ")})` : base;
58
- }
59
- var JSON_CONST = "DrzlJsonValue";
60
- var JSON_PREAMBLE = `type ${JSON_CONST}Type =
61
- | string
62
- | number
63
- | boolean
64
- | null
65
- | readonly ${JSON_CONST}Type[]
66
- | { readonly [key: string]: ${JSON_CONST}Type };
67
-
68
- const ${JSON_CONST}: ${NS}.Schema<${JSON_CONST}Type, unknown> = ${NS}.suspend(() =>
69
- ${NS}.Union(
70
- ${NS}.String,
71
- ${NS}.Finite,
72
- ${NS}.Boolean,
73
- ${NS}.Null,
74
- ${NS}.Array(${JSON_CONST}),
75
- // The plain-object test comes before the record, not after it. \`Schema.Record\` rebuilds its
76
- // output, so a check placed after it inspects that new object and reports every input as
77
- // plain. A Date sailed through: it has no own enumerable keys, so the record accepted it and
78
- // rebuilt it as \`{}\`.
79
- ${NS}.Unknown.pipe(
80
- ${NS}.filter(
81
- (o) => {
82
- if (typeof o !== 'object' || o === null || Array.isArray(o)) return false;
83
- const p = Object.getPrototypeOf(o);
84
- return p === Object.prototype || p === null;
85
- },
86
- { description: 'a plain object' }
87
- ),
88
- ${NS}.compose(${NS}.Record({ key: ${NS}.String, value: ${JSON_CONST} }), { strict: false })
89
- )
90
- )
91
- );
92
- `;
93
- var UNKNOWN_EXPR = `${NS}.Unknown`;
94
- function isUnknownExpr(expr) {
95
- return expr === UNKNOWN_EXPR;
96
- }
97
- function withNarrowedType(expr, ref) {
98
- return `${expr} as unknown as ${NS}.Schema<${ref}>`;
99
- }
100
- function numericBounds(c, checks) {
101
- let lo = c.min !== void 0 ? { fn: "greaterThanOrEqualTo", value: c.min } : void 0;
102
- let hi = c.max !== void 0 ? { fn: "lessThanOrEqualTo", value: c.max } : void 0;
103
- for (const k of checks.filter((x) => x.column === c.name && x.kind === "number")) {
104
- if (k.operator === ">=") lo = { fn: "greaterThanOrEqualTo", value: k.value };
105
- else if (k.operator === ">") lo = { fn: "greaterThan", value: k.value };
106
- else if (k.operator === "<=") hi = { fn: "lessThanOrEqualTo", value: k.value };
107
- else if (k.operator === "<") hi = { fn: "lessThan", value: k.value };
108
- }
109
- return [lo, hi].filter(Boolean).map((x) => `${NS}.${x.fn}(${x.value})`);
110
- }
111
- function foldedIntoBounds(c, checks) {
112
- if (c.arrayDimensions || c.shape) return /* @__PURE__ */ new Set();
113
- if (c.tsType !== "number" && c.tsType !== "bigint") return /* @__PURE__ */ new Set();
114
- return new Set(
115
- checks.filter(
116
- (k) => k.column === c.name && k.kind === "number" && k.operator !== "=" && k.operator !== "<>"
117
- )
118
- );
119
- }
120
- function nonFiniteBranches(c) {
121
- const { nan, infinity } = nonFiniteAccepted(c);
122
- return [
123
- ...nan ? [`${NS}.Number.pipe(${filter("Number.isNaN(v)", "NaN, which this column stores")})`] : [],
124
- ...infinity ? [`${NS}.Literal(Infinity, -Infinity)`] : []
125
- ];
126
- }
127
- function withNonFinite(c, base) {
128
- const branches = nonFiniteBranches(c);
129
- return branches.length ? `${NS}.Union(${base}, ${branches.join(", ")})` : base;
130
- }
131
- function dateExpr(mode, coerceDates) {
132
- const plain = `${NS}.ValidDateFromSelf`;
133
- if (coerceDates === "none") return plain;
134
- const fromString = piped(`${NS}.String`, [
135
- `${NS}.pattern(new RegExp(${JSON.stringify(COERCIBLE_DATE_STRING)}))`,
136
- filter(parsesToADate("new Date(v)"), "a date the runtime can parse")
137
- ]);
138
- const fromNumber = piped(`${NS}.Number`, [
139
- filter(parsesToADate("new Date(v)"), "a date the runtime can parse")
140
- ]);
141
- const union = `${NS}.Union(${plain}, ${fromString}, ${fromNumber})`;
142
- if (coerceDates === "all") return union;
143
- return mode === "select" ? plain : union;
144
- }
145
- function capSteps(c, mode) {
146
- const steps = [];
147
- if (c.shape?.kind === "byteString") {
148
- const n = c.shape.length;
149
- if (!n) return steps;
150
- return mode === "select" ? [filter(`${CODEPOINT_LENGTH} <= ${n}`, `at most ${n} characters`)] : [filter(`new TextEncoder().encode(v).length <= ${n}`, `at most ${n} bytes`)];
151
- }
152
- if (c.maxLength) {
153
- steps.push(
154
- filter(`${CODEPOINT_LENGTH} <= ${c.maxLength}`, `at most ${c.maxLength} characters`)
155
- );
156
- }
157
- if (c.maxBytes) {
158
- steps.push(
159
- filter(`new TextEncoder().encode(v).length <= ${c.maxBytes}`, `at most ${c.maxBytes} bytes`)
160
- );
161
- }
162
- return steps;
163
- }
164
- function lengthSteps(c, lengths) {
165
- return lengths.filter((k) => k.column === c.name).flatMap((k) => {
166
- const measure = lengthMeasure(c, k);
167
- if (!measure) return [];
168
- return [
169
- filter(
170
- `${measureExpression(measure, "v")} ${OPS[k.operator]} ${k.value}`,
171
- lengthCheckLabel(k)
172
- )
173
- ];
174
- });
175
- }
176
- function cardinalitySteps(c, cardinalities) {
177
- if (!c.arrayDimensions) return [];
178
- return cardinalities.filter((k) => k.column === c.name).map(
179
- (k) => filter(
180
- `v.length ${OPS[k.operator]} ${k.value}`,
181
- `${k.name ? `${k.name}: ` : ""}cardinality(${c.name}) ${k.operator} ${k.value}`
182
- )
183
- );
184
- }
185
- function checkSteps(c, checks) {
186
- if (c.arrayDimensions || c.shape) return [];
187
- const folded = foldedIntoBounds(c, checks);
188
- const numericWire = comparisonWire(c) === "numeric-string";
189
- return checks.filter((k) => k.column === c.name && !folded.has(k)).map((k) => {
190
- const label = `${k.name ? `${k.name}: ` : ""}${c.name} ${k.operator} ${k.value}`;
191
- if (numericWire) {
192
- if (k.operator === "=" || k.operator === "<>") {
193
- const canon = JSON.stringify(canonicalNumericText(k.value));
194
- const op = k.operator === "=" ? "===" : "!==";
195
- return filter(`${NUMERIC_CANON_NAME}(v) ${op} ${canon}`, label);
196
- }
197
- return filter(`Number(v) ${OPS[k.operator]} ${k.value}`, label);
198
- }
199
- const literal = k.kind === "string" ? JSON.stringify(k.value) : wireNumberLiteral(c, k.value);
200
- return filter(`v ${OPS[k.operator]} ${literal}`, label);
201
- });
202
- }
203
- function hasNoRuntimeType(c) {
204
- return c.tsType === "any" || c.shape?.kind === "custom" || c.shape?.kind === "json";
205
- }
206
- function shapeExpr(c, mode, replaced = false) {
207
- const s = c.shape;
208
- if (!s) return void 0;
209
- switch (s.kind) {
210
- case "json":
211
- return replaced ? UNKNOWN_EXPR : JSON_CONST;
212
- case "custom":
213
- return UNKNOWN_EXPR;
214
- case "buffer":
215
- return `${NS}.Uint8ArrayFromSelf`;
216
- case "tuple":
217
- return `${NS}.Tuple(${Array.from({ length: s.length }, () => `${NS}.Number`).join(", ")})`;
218
- case "numberObject":
219
- return `${NS}.Struct({ ${s.fields.map((f) => `${f}: ${NS}.Number`).join(", ")} })`;
220
- case "numberVector":
221
- return piped(
222
- `${NS}.Array(${NS}.Number)`,
223
- s.length ? [filter(`v.length === ${s.length}`, `exactly ${s.length} elements`)] : []
224
- );
225
- case "bitstring":
226
- return piped(`${NS}.String`, [
227
- `${NS}.pattern(/^[01]*$/)`,
228
- ...s.length ? [
229
- s.exact ? filter(`v.length === ${s.length}`, `exactly ${s.length} binary digits`) : filter(`v.length <= ${s.length}`, `at most ${s.length} binary digits`)
230
- ] : []
231
- ]);
232
- case "byteString":
233
- return piped(`${NS}.String`, capSteps(c, mode));
234
- }
235
- }
236
- function exprForColumn(c, mode, coerceDates, checks, sets, lengths, replaced) {
237
- const shaped = shapeExpr(c, mode, replaced);
238
- if (shaped) return piped(shaped, lengthSteps(c, lengths));
239
- const set = sets.find((x) => x.column === c.name);
240
- if (set) {
241
- if (comparisonWire(c) === "numeric-string") {
242
- const members = canonicalMembers(set.values);
243
- const test = members.map((m) => `canon === ${JSON.stringify(m)}`).join(" || ");
244
- return piped(`${NS}.String`, [
245
- filter(`((canon) => ${test})(${NUMERIC_CANON_NAME}(v))`, describeSet(set))
246
- ]);
247
- }
248
- const values = set.values.map(
249
- (v) => set.kind === "string" ? JSON.stringify(v) : wireNumberLiteral(c, v)
250
- );
251
- return `${NS}.Literal(${values.join(", ")})`;
252
- }
253
- if (c.arrayDimensions) checks = [];
254
- if (c.enumValues && c.enumValues.length) {
255
- return `${NS}.Literal(${c.enumValues.map((v) => JSON.stringify(v)).join(", ")})`;
256
- }
257
- const eq = checks.find((k) => k.column === c.name && k.operator === "=");
258
- if (eq && !c.shape && comparisonWire(c) !== "numeric-string") {
259
- return `${NS}.Literal(${eq.kind === "string" ? JSON.stringify(eq.value) : wireNumberLiteral(c, eq.value)})`;
260
- }
261
- const rest = [...checkSteps(c, checks), ...lengthSteps(c, lengths)];
262
- switch (c.tsType) {
263
- case "string": {
264
- const base = c.format === "uuid" ? `${NS}.UUID` : `${NS}.String`;
265
- const pattern = c.format && c.format !== "uuid" && COLUMN_FORMATS[c.format] ? [`${NS}.pattern(new RegExp(${JSON.stringify(COLUMN_FORMATS[c.format])}))`] : [];
266
- return piped(base, [...pattern, ...capSteps(c, mode), ...rest]);
267
- }
268
- case "number": {
269
- const base = isIntegerColumn(c) ? `${NS}.Int` : `${NS}.Finite`;
270
- return withNonFinite(c, piped(base, [...numericBounds(c, checks), ...rest]));
271
- }
272
- case "bigint":
273
- return piped(`${NS}.BigIntFromSelf`, [
274
- ...c.min !== void 0 ? [`${NS}.greaterThanOrEqualToBigInt(${c.min}n)`] : [],
275
- ...c.max !== void 0 ? [`${NS}.lessThanOrEqualToBigInt(${c.max}n)`] : [],
276
- ...rest
277
- ]);
278
- case "boolean":
279
- return `${NS}.Boolean`;
280
- case "Date":
281
- return dateExpr(mode, coerceDates);
282
- case "Uint8Array":
283
- return `${NS}.Uint8ArrayFromSelf`;
284
- case "any":
285
- return UNKNOWN_EXPR;
286
- default:
287
- return UNKNOWN_EXPR;
288
- }
289
- }
290
- function renderField(c, mode, coerceDates, checks, sets, lengths, cardinalities, applyDefault, narrowRef, brand) {
291
- let expr = exprForColumn(
292
- c,
293
- mode,
294
- coerceDates,
295
- checks,
296
- sets,
297
- lengths,
298
- !!narrowRef && hasNoRuntimeType(c)
299
- );
300
- const dims = c.arrayDimensions ?? 0;
301
- for (let i = 0; i < dims; i++) {
302
- expr = `${NS}.Array(${expr})`;
303
- if (i === dims - 1) expr = piped(expr, cardinalitySteps(c, cardinalities));
304
- }
305
- if (brand) expr = piped(expr, [`${NS}.brand(${JSON.stringify(brand)})`]);
306
- if (c.nullable && !isUnknownExpr(expr)) expr = `${NS}.NullOr(${expr})`;
307
- if (narrowRef && !brand) expr = withNarrowedType(expr, narrowRef);
308
- if (mode === "select") return expr;
309
- const wantsDefault = mode === "insert" && applyDefault && c.defaultValue !== void 0;
310
- if (wantsDefault) {
311
- return `${NS}.optionalWith(${expr}, { default: () => ${JSON.stringify(c.defaultValue)} })`;
312
- }
313
- if (mode === "update" || c.nullable || c.hasDefault) return `${NS}.optional(${expr})`;
314
- return expr;
315
- }
316
- function wantsRef(c, allColumns) {
317
- return allColumns || hasNoRuntimeType(c);
318
- }
319
- function renderObjectShape(cols, mode, coerceDates, checks, sets, lengths, cardinalities, typedJson, applyDefaults, brands) {
320
- return cols.map((c) => {
321
- const ref = typedJson && wantsRef(c, !!typedJson.allColumns) ? `(typeof ${typedJson.table}.$infer${typedJson.mode === "insert" ? "Insert" : "Select"})[${JSON.stringify(c.name)}]` : void 0;
322
- const field = renderField(
323
- c,
324
- mode,
325
- coerceDates,
326
- checks,
327
- sets,
328
- lengths,
329
- cardinalities,
330
- applyDefaults,
331
- ref,
332
- brands?.plan.brandOf(brands.tsName, c.name)
333
- );
334
- return ` ${JSON.stringify(c.name)}: ${field},`;
335
- }).join("\n");
336
- }
337
- function rowSteps(rows, cols) {
338
- const present = new Set(cols.map((c) => c.name));
339
- return rows.filter((r) => present.has(r.left) && present.has(r.right)).map((r) => {
340
- const l = `o[${JSON.stringify(r.left)}]`;
341
- const rt = `o[${JSON.stringify(r.right)}]`;
342
- const msg = `${r.name ? `${r.name}: ` : ""}${r.left} ${r.operator} ${r.right}`;
343
- return `${NS}.filter((o) => ${l} == null || ${rt} == null || ${l} ${OPS[r.operator]} ${rt}, { description: ${JSON.stringify(msg)} })`;
344
- });
345
- }
346
- function indentBlock(code, by = " ") {
347
- return code.split("\n").map((line) => line ? by + line : line).join("\n");
348
- }
349
- function parsedChecksFor(table) {
350
- const parsed = (table.checks ?? []).map((k) => parseCheck(k.expression, k.name));
351
- const { checks, sets } = applyWirePolicy(
352
- table.columns,
353
- parsed.flatMap((p) => p.ok ? p.checks : []),
354
- parsed.flatMap((p) => p.ok ? p.sets ?? [] : [])
355
- );
356
- return {
357
- checks,
358
- sets,
359
- rows: parsed.flatMap((p) => p.ok ? p.rows ?? [] : []),
360
- lengths: parsed.flatMap((p) => p.ok ? p.lengths ?? [] : []),
361
- cardinalities: parsed.flatMap((p) => p.ok ? p.cardinalities ?? [] : [])
362
- };
363
- }
364
- function nestedNodeCols(node, mode) {
365
- const all = mode === "insert" ? insertColumns(node.table) : selectColumns(node.table);
366
- return nestedNodeColumns(all, node);
367
- }
368
- function nestedNodes(node, into = []) {
369
- into.push(node);
370
- for (const arm of node.arms) nestedNodes(arm.child, into);
371
- return into;
372
- }
373
- function renderNestedObject(node, mode, coerceDates, typedJson, applyDefaults, brands) {
374
- const cols = nestedNodeCols(node, mode);
375
- const { checks, sets, rows, lengths, cardinalities } = parsedChecksFor(node.table);
376
- const tj = typedJson ? { table: node.table.tsName, mode, allColumns: typedJson.allColumns } : void 0;
377
- const fields = renderObjectShape(
378
- cols,
379
- mode,
380
- coerceDates,
381
- checks,
382
- sets,
383
- lengths,
384
- cardinalities,
385
- tj,
386
- applyDefaults,
387
- brands ? { plan: brands, tsName: node.table.tsName } : void 0
388
- );
389
- const arms = node.arms.map((arm) => {
390
- const notes = nestedArmNotes(arm).map((n) => ` // ${n}
391
- `).join("");
392
- const child = renderNestedObject(
393
- arm.child,
394
- mode,
395
- coerceDates,
396
- typedJson,
397
- applyDefaults,
398
- brands
399
- );
400
- const inner = arm.single ? `${NS}.NullOr(
401
- ${indentBlock(indentBlock(child))}
402
- )` : `${NS}.Array(
403
- ${indentBlock(indentBlock(child))}
404
- )`;
405
- return `${notes} ${JSON.stringify(arm.key)}: ${NS}.optional(${inner}),`;
406
- });
407
- const body = [fields, ...arms].filter(Boolean).join("\n");
408
- return piped(`${NS}.Struct({
409
- ${body}
410
- })`, rowSteps(rows, cols));
411
- }
412
- function renderNestedSchemas(table, affix, coerceDates, typedJson, applyDefaults, plans, brands) {
413
- const out = [];
414
- for (const mode of ["insert", "select"]) {
415
- const plan = plans[mode];
416
- if (!plan) continue;
417
- const name = nestedSchemaName(mode, table.tsName, affix);
418
- const tname = nestedTypeName(mode, table.tsName, affix);
419
- const expr = renderNestedObject(plan, mode, coerceDates, typedJson, applyDefaults, brands);
420
- out.push(
421
- `export const ${name} = ${expr};
422
-
423
- export type ${tname} = ${NS}.Schema.Type<typeof ${name}>;
424
-
425
- export const ${STANDARD_PREFIX}${name} = ${NS}.standardSchemaV1(${name});`
426
- );
427
- }
428
- return out.length ? `
429
- ${out.join("\n\n")}
430
- ` : "";
431
- }
432
- function nestedPlansFor(table, analysis, depth) {
433
- const out = {};
434
- for (const mode of ["insert", "select"]) {
435
- if (mode === "insert" && table.readOnly) continue;
436
- const plan = buildNestedPlan(table, analysis.tables, analysis.relations ?? [], mode, depth);
437
- if (plan) out[mode] = plan;
438
- }
439
- return out;
440
- }
441
- function renderTableSchemas(table, affix, coerceDates, typedJson, applyDefaults = false, wantsDuplicateFinder = false, nested = {}, brands) {
442
- const T = table.tsName;
443
- const insertCols = insertColumns(table);
444
- const updateCols = updateColumns(table);
445
- const selectCols = selectColumns(table);
446
- const { checks, sets, rows, lengths, cardinalities } = parsedChecksFor(table);
447
- const tj = typedJson ? { table: T, allColumns: typedJson.allColumns } : void 0;
448
- const modes = [
449
- ["insert", insertCols],
450
- ["update", updateCols],
451
- ["select", selectCols]
452
- ];
453
- const blocks = modes.map(([mode, cols]) => {
454
- const name = schemaName(mode, T, affix);
455
- const tname = typeName(mode, T, affix);
456
- const body = renderObjectShape(
457
- cols,
458
- mode,
459
- coerceDates,
460
- checks,
461
- sets,
462
- lengths,
463
- cardinalities,
464
- // The update schema references the insert-side inferred types: both describe a value going
465
- // in, and `$inferSelect` would name the post-default type for a column a write may omit.
466
- tj ? { ...tj, mode: mode === "select" ? "select" : "insert" } : void 0,
467
- applyDefaults,
468
- brands ? { plan: brands, tsName: T } : void 0
469
- );
470
- const expr = piped(`${NS}.Struct({
471
- ${body}
472
- })`, rowSteps(rows, cols));
473
- return `export const ${name} = ${expr};
474
-
475
- export type ${tname} = ${NS}.Schema.Type<typeof ${name}>;
476
-
477
- export const ${STANDARD_PREFIX}${name} = ${NS}.standardSchemaV1(${name});`;
478
- });
479
- const nestedByTable = ["insert", "select"].flatMap((m) => {
480
- const plan = nested[m];
481
- return plan ? nestedNodes(plan).map((n) => [n.table.tsName, nestedNodeCols(n, m)]) : [];
482
- });
483
- const nestedCols = nestedByTable.flatMap(([, cs]) => cs);
484
- const referenced = /* @__PURE__ */ new Set();
485
- if (typedJson) {
486
- const all = !!typedJson.allColumns;
487
- if ([...insertCols, ...updateCols, ...selectCols].some((c) => wantsRef(c, all))) {
488
- referenced.add(T);
489
- }
490
- for (const [name, cs] of nestedByTable) {
491
- if (cs.some((c) => wantsRef(c, all))) referenced.add(name);
492
- }
493
- }
494
- const schemaImport = referenced.size ? `import type { ${[...referenced].join(", ")} } from '${typedJson.schemaSpecifier}';
495
- ` : "";
496
- const needsJson = !typedJson && [...insertCols, ...updateCols, ...selectCols, ...nestedCols].some(
497
- (c) => c.shape?.kind === "json"
498
- );
499
- const finder = wantsDuplicateFinder ? renderDuplicateFinder(table, `findDuplicate${T}`, typeName("insert", T, affix)) : void 0;
500
- const duplicates = finder ? `
501
- ${finder}
502
- ` : "";
503
- const nestedCode = renderNestedSchemas(
504
- table,
505
- affix,
506
- coerceDates,
507
- typedJson,
508
- applyDefaults,
509
- nested,
510
- brands
511
- );
512
- const selectName = schemaName("select", T, affix);
513
- const brandAliases = (brands?.aliasesFor(T) ?? []).map(
514
- (a) => `/** The nominal type of ${T}.${a.column}. */
515
- export type ${a.alias} = ${NS}.Schema.Type<typeof ${selectName}>[${JSON.stringify(a.column)}];`
516
- ).join("\n\n");
517
- const brandCode = brandAliases ? `
518
- ${brandAliases}
519
- ` : "";
520
- const involved = [
521
- table,
522
- ...["insert", "select"].flatMap((m) => {
523
- const plan = nested[m];
524
- return plan ? nestedNodes(plan).map((n) => n.table) : [];
525
- })
526
- ];
527
- const canonPreamble = involved.some((t) => {
528
- const own = parsedChecksFor(t);
529
- return needsNumericCanon(t.columns, own.checks, own.sets);
530
- }) ? `
531
- ${NUMERIC_CANON_SOURCE}` : "";
532
- return `import * as ${NS} from 'effect/Schema';
533
- ${schemaImport}${needsJson ? `
534
- ${JSON_PREAMBLE}` : ""}${canonPreamble}
535
- ${blocks.join("\n\n")}
536
- ${brandCode}${nestedCode}${duplicates}`;
537
- }
538
- var EffectGenerator = class {
539
- constructor(analysis) {
540
- this.analysis = analysis;
541
- this.library = "effect";
542
- }
543
- async generate(opts) {
544
- const fs = fileWriter(opts.fileSink);
545
- const path = await import("path");
546
- const out = path.resolve(process.cwd(), opts.outDir);
547
- const files = [];
548
- await fs.mkdir(out, { recursive: true });
549
- const affix = resolveAffix(opts);
550
- const coerceDates = opts.coerceDates ?? "input";
551
- const fileSuffix = opts.fileSuffix ?? DEFAULT_FILE_SUFFIX;
552
- const wantsTypes = opts.typedJson || opts.typedColumns;
553
- const typedJson = wantsTypes && opts.schemaPath ? {
554
- schemaSpecifier: resolveConfiguredImport(
555
- opts.schemaPath,
556
- out,
557
- process.cwd(),
558
- opts.importExtension
559
- ),
560
- allColumns: !!opts.typedColumns
561
- } : void 0;
562
- if (wantsTypes && !opts.schemaPath) {
563
- console.warn(
564
- "[drzl] typedJson was requested but the schema path is unknown, so json columns keep their wide type."
565
- );
566
- }
567
- const nestedDepth = opts.nestedSchemas ? resolveNestedDepth(opts.nestedDepth, (m) => console.warn(m)) : 0;
568
- const brands = buildBrandPlan(this.analysis.tables, opts.branded);
569
- for (const note of brands?.notes ?? []) console.warn(`[drzl] ${note}`);
570
- for (const table of this.analysis.tables) {
571
- const filePath = path.join(out, moduleFileName(table.tsName, fileSuffix));
572
- const code = renderTableSchemas(
573
- table,
574
- affix,
575
- coerceDates,
576
- typedJson,
577
- !!opts.applyDefaults,
578
- !!opts?.duplicateFinder,
579
- opts.nestedSchemas ? nestedPlansFor(table, this.analysis, nestedDepth) : {},
580
- brands
581
- );
582
- const formatted = await formatCode(
583
- buildHeader(opts.outputHeader) + code,
584
- filePath,
585
- opts.format
586
- );
587
- await fs.writeFile(filePath, formatted, "utf8");
588
- files.push(filePath);
589
- }
590
- const indexPath = path.join(out, "index.ts");
591
- const indexFormatted = await formatCode(
592
- buildHeader(opts.outputHeader) + this.defaultIndex(this.analysis, opts),
593
- indexPath,
594
- opts.format
595
- );
596
- await fs.writeFile(indexPath, indexFormatted, "utf8");
597
- files.push(indexPath);
598
- return files;
599
- }
600
- renderTable(table, opts) {
601
- return renderTableSchemas(
602
- table,
603
- resolveAffix(opts),
604
- opts?.coerceDates ?? "input",
605
- void 0,
606
- !!opts?.applyDefaults,
607
- !!opts?.duplicateFinder,
608
- {},
609
- buildBrandPlan(this.analysis.tables, opts?.branded)
610
- );
611
- }
612
- defaultIndex(analysis, opts) {
613
- const fileSuffix = opts.fileSuffix ?? DEFAULT_FILE_SUFFIX;
614
- return analysis.tables.map(
615
- (t) => `export * from '${moduleSpecifier(t.tsName, fileSuffix, opts.importExtension)}';`
616
- ).join("\n") + "\n";
617
- }
618
- };
619
- var index_default = EffectGenerator;
620
- function buildHeader(h) {
621
- if (h && h.enabled === false) return "";
622
- const text = h?.text?.trim();
623
- const lines = text ? text.split(/\r?\n/).map((l) => `// ${l}`) : [
624
- "// Generated by DRZL (@drzl/*)",
625
- "// Generated output is granted to you under your project's license.",
626
- "// You may use, copy, modify, and distribute without attribution."
627
- ];
628
- return lines.join("\n") + "\n\n";
629
- }
630
- export {
631
- EffectGenerator,
632
- index_default as default
633
- };
634
- //# sourceMappingURL=dist-KX62ETKK.js.map