zero-rust 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js ADDED
@@ -0,0 +1,1076 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ../zerogen/src/rust-cli.ts
4
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
5
+ import { resolve as resolve3 } from "node:path";
6
+ import { Cli as Cli2, z as z4 } from "incur";
7
+
8
+ // ../zerogen/src/cli.ts
9
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { relative, resolve as resolve2 } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { Cli, z as z2 } from "incur";
13
+
14
+ // ../zerogen/src/targets/swift.ts
15
+ import { z } from "incur";
16
+ var options = {
17
+ "schema-name": z.string().optional().describe("Name of the generated ZeroSchema static (default app)"),
18
+ "zql": z.string().optional().describe("Name of the generated query builder global (default zql)"),
19
+ "type-prefix": z.string().optional().describe("Prefix for every generated type name (default none)"),
20
+ "access": z.enum(["public", "internal"]).optional().describe("Access level of the generated code (default public)")
21
+ };
22
+ var swiftKeywords = new Set(
23
+ "associatedtype borrowing class consuming deinit enum extension fileprivate func import init inout internal let nonisolated open operator package private precedencegroup protocol public rethrows static struct subscript typealias var break case catch continue default defer do else fallthrough for guard if in repeat return throw switch where while Any as await false is nil self Self super throws true try _".split(" ")
24
+ );
25
+
26
+ // ../zerogen/src/types.ts
27
+ import { dirname, resolve } from "node:path";
28
+ import ts from "typescript";
29
+ var defaultOptions = {
30
+ target: ts.ScriptTarget.ES2022,
31
+ module: ts.ModuleKind.NodeNext,
32
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
33
+ allowImportingTsExtensions: true,
34
+ strict: true,
35
+ noEmit: true,
36
+ skipLibCheck: true
37
+ };
38
+ function readCustomTypes(schemaPath, exportName) {
39
+ const file = resolve(schemaPath);
40
+ const program = ts.createProgram([file], compilerOptions(file));
41
+ const checker = program.getTypeChecker();
42
+ const source = program.getSourceFile(file);
43
+ const module = source && checker.getSymbolAtLocation(source);
44
+ if (!module) {
45
+ throw new Error(`Cannot read the types of ${schemaPath}`);
46
+ }
47
+ let symbol = checker.getExportsOfModule(module).find((s) => s.name === exportName);
48
+ if (!symbol) {
49
+ throw new Error(`${schemaPath} does not export "${exportName}"`);
50
+ }
51
+ if (symbol.flags & ts.SymbolFlags.Alias) {
52
+ symbol = checker.getAliasedSymbol(symbol);
53
+ }
54
+ const schemaType = checker.getTypeOfSymbol(symbol);
55
+ const out = /* @__PURE__ */ new Map();
56
+ const tables = property(checker, schemaType, "tables");
57
+ for (const table of tables ? checker.getPropertiesOfType(tables) : []) {
58
+ const columns = property(
59
+ checker,
60
+ checker.getTypeOfSymbol(table),
61
+ "columns"
62
+ );
63
+ const byColumn = /* @__PURE__ */ new Map();
64
+ for (const column of columns ? checker.getPropertiesOfType(columns) : []) {
65
+ const custom = property(
66
+ checker,
67
+ checker.getTypeOfSymbol(column),
68
+ "customType"
69
+ );
70
+ if (custom) {
71
+ byColumn.set(column.name, model(checker, custom));
72
+ }
73
+ }
74
+ out.set(table.name, byColumn);
75
+ }
76
+ return out;
77
+ }
78
+ function compilerOptions(file) {
79
+ const configPath = ts.findConfigFile(dirname(file), ts.sys.fileExists);
80
+ if (!configPath) {
81
+ return defaultOptions;
82
+ }
83
+ const parsed = ts.getParsedCommandLineOfConfigFile(configPath, void 0, {
84
+ ...ts.sys,
85
+ onUnRecoverableConfigFileDiagnostic: () => {
86
+ }
87
+ });
88
+ return parsed ? { ...parsed.options, noEmit: true, skipLibCheck: true } : defaultOptions;
89
+ }
90
+ function property(checker, type, name) {
91
+ const p = checker.getPropertyOfType(type, name);
92
+ return p && checker.getTypeOfSymbol(p);
93
+ }
94
+ var maxDepth = 32;
95
+ var nullish = ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void;
96
+ function model(checker, type, outer = /* @__PURE__ */ new Set()) {
97
+ if (outer.has(type) || outer.size >= maxDepth) {
98
+ return { kind: "json" };
99
+ }
100
+ const alias = aliasName(type);
101
+ if (type.isUnion()) {
102
+ const parts = type.types.filter((t) => !(t.flags & nullish));
103
+ const nullable = parts.length !== type.types.length;
104
+ const inner = unionModel(checker, parts, alias, outer);
105
+ return nullable ? { kind: "nullable", wrapped: inner } : inner;
106
+ }
107
+ if (type.isIntersection()) {
108
+ for (const t of type.types) {
109
+ if (t.flags & ts.TypeFlags.StringLike) return { kind: "string" };
110
+ if (t.flags & ts.TypeFlags.NumberLike) return { kind: "number" };
111
+ }
112
+ return { kind: "json" };
113
+ }
114
+ if (type.isStringLiteral()) {
115
+ return enumModel([type.value], alias);
116
+ }
117
+ if (type.flags & ts.TypeFlags.StringLike) return { kind: "string" };
118
+ if (type.flags & ts.TypeFlags.NumberLike) return { kind: "number" };
119
+ if (type.flags & ts.TypeFlags.BooleanLike) return { kind: "boolean" };
120
+ if (checker.isArrayType(type)) {
121
+ const [element] = checker.getTypeArguments(type);
122
+ return {
123
+ kind: "array",
124
+ element: element ? model(checker, element, outer) : { kind: "json" }
125
+ };
126
+ }
127
+ if (type.flags & ts.TypeFlags.Object && isPlainObject(checker, type)) {
128
+ const inside = new Set(outer).add(type);
129
+ const fields = checker.getPropertiesOfType(type).map((p) => {
130
+ const optional = (p.flags & ts.SymbolFlags.Optional) !== 0;
131
+ let t = checker.getTypeOfSymbol(p);
132
+ if (optional) {
133
+ t = checker.getNonNullableType(t);
134
+ }
135
+ return { name: p.name, type: model(checker, t, inside), optional };
136
+ });
137
+ return { kind: "object", ...alias ? { alias } : {}, fields };
138
+ }
139
+ return { kind: "json" };
140
+ }
141
+ function unionModel(checker, parts, alias, outer) {
142
+ if (parts.length === 0) return { kind: "json" };
143
+ if (parts.every((t) => t.isStringLiteral())) {
144
+ return enumModel(
145
+ parts.map((t) => t.value),
146
+ alias
147
+ );
148
+ }
149
+ if (parts.every((t) => t.flags & ts.TypeFlags.BooleanLike)) {
150
+ return { kind: "boolean" };
151
+ }
152
+ if (parts.every((t) => t.flags & ts.TypeFlags.NumberLike)) {
153
+ return { kind: "number" };
154
+ }
155
+ if (parts.length === 1) return model(checker, parts[0], outer);
156
+ return { kind: "json" };
157
+ }
158
+ function enumModel(cases, alias) {
159
+ return { kind: "enum", ...alias ? { alias } : {}, cases };
160
+ }
161
+ function isPlainObject(checker, type) {
162
+ return checker.getPropertiesOfType(type).length > 0 && type.getCallSignatures().length === 0 && type.getConstructSignatures().length === 0 && checker.getIndexInfosOfType(type).length === 0;
163
+ }
164
+ function aliasName(type) {
165
+ if (type.aliasSymbol && !type.aliasTypeArguments?.length) {
166
+ return type.aliasSymbol.name;
167
+ }
168
+ const name = type.getSymbol()?.name;
169
+ if (name && !name.startsWith("__") && type.flags & ts.TypeFlags.Object && (type.getSymbol().flags & ts.SymbolFlags.Interface) !== 0) {
170
+ return name;
171
+ }
172
+ return void 0;
173
+ }
174
+
175
+ // ../zerogen/src/cli.ts
176
+ var UsageError = class extends Error {
177
+ code;
178
+ constructor(code, message) {
179
+ super(message);
180
+ this.code = code;
181
+ }
182
+ };
183
+ function mustExist(path, code, message) {
184
+ if (!existsSync(path)) {
185
+ throw new UsageError(code, message);
186
+ }
187
+ }
188
+ async function loadSchema(config, cwd, configFile2) {
189
+ const schemaPath = resolve2(cwd, config.schema ?? "schema.ts");
190
+ mustExist(
191
+ schemaPath,
192
+ "SCHEMA_NOT_FOUND",
193
+ `Schema ${relative(cwd, schemaPath)} doesn't exist. Pass --schema-file, or set "schema" in ${configFile2}.`
194
+ );
195
+ const exportName = config.export ?? "schema";
196
+ const module = await import(pathToFileURL(schemaPath).href);
197
+ const schema = module[exportName];
198
+ if (!schema || typeof schema !== "object" || !("tables" in schema)) {
199
+ throw new UsageError(
200
+ "SCHEMA_NOT_EXPORTED",
201
+ `${relative(cwd, schemaPath)} does not export a schema as "${exportName}". Pass --export, or set "export" in ${configFile2}.`
202
+ );
203
+ }
204
+ return {
205
+ schema,
206
+ customTypes: readCustomTypes(schemaPath, exportName),
207
+ source: relative(cwd, schemaPath).replaceAll("\\", "/")
208
+ };
209
+ }
210
+ async function reporting(fail, body) {
211
+ try {
212
+ return await body();
213
+ } catch (e) {
214
+ if (e instanceof UsageError) {
215
+ return fail({ code: e.code, message: e.message });
216
+ }
217
+ throw e;
218
+ }
219
+ }
220
+ function writeOutput(output, contents, check2, cwd) {
221
+ const path = relative(cwd, output);
222
+ const current = existsSync(output) ? readFileSync(output, "utf8") : void 0;
223
+ if (check2) {
224
+ if (current !== contents) {
225
+ throw new UsageError(
226
+ "OUT_OF_DATE",
227
+ `${path} is out of date. Run the command again without --check to update it.`
228
+ );
229
+ }
230
+ return { path, upToDate: true };
231
+ }
232
+ if (current !== contents) {
233
+ writeFileSync(output, contents);
234
+ }
235
+ return { path, written: current !== contents };
236
+ }
237
+ var check = z2.boolean().optional().describe("Fail when the output is out of date instead of writing it");
238
+
239
+ // ../zerogen/src/targets/rust.ts
240
+ import { z as z3 } from "incur";
241
+ var options2 = {
242
+ "type-prefix": z3.string().optional().describe("Prefix for every generated type name (default none)")
243
+ };
244
+ function overrides2(input) {
245
+ return input["type-prefix"] !== void 0 ? { typePrefix: input["type-prefix"] } : {};
246
+ }
247
+ var keywords = new Set(
248
+ "as break const continue crate else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while async await dyn abstract become box do final macro override priv typeof unsized virtual yield try gen".split(" ")
249
+ );
250
+ var rawless = /* @__PURE__ */ new Set(["self", "Self", "super", "crate", "_"]);
251
+ var reservedTypeNames = /* @__PURE__ */ new Set([
252
+ "Option",
253
+ "Some",
254
+ "None",
255
+ "Result",
256
+ "Ok",
257
+ "Err",
258
+ "Vec",
259
+ "Box",
260
+ "String",
261
+ "ToString",
262
+ "ToOwned",
263
+ "Clone",
264
+ "Copy",
265
+ "Send",
266
+ "Sync",
267
+ "Sized",
268
+ "Unpin",
269
+ "Drop",
270
+ "Fn",
271
+ "FnMut",
272
+ "FnOnce",
273
+ "Iterator",
274
+ "IntoIterator",
275
+ "Extend",
276
+ "Default",
277
+ "Debug",
278
+ "PartialEq",
279
+ "Eq",
280
+ "PartialOrd",
281
+ "Ord",
282
+ "Hash",
283
+ "AsRef",
284
+ "AsMut",
285
+ "Into",
286
+ "From",
287
+ "TryFrom",
288
+ "TryInto",
289
+ "FromIterator",
290
+ "Column",
291
+ "ColumnRef",
292
+ "ColumnUpdate",
293
+ "ColumnValues",
294
+ "Condition",
295
+ "Direction",
296
+ "DistinctRow",
297
+ "ExistsOptions",
298
+ "GroupRow",
299
+ "Grouped",
300
+ "GroupedQuery",
301
+ "JsonPath",
302
+ "Object",
303
+ "Query",
304
+ "Relationship",
305
+ "RelationshipAggregates",
306
+ "RowExpression",
307
+ "Schema",
308
+ "Transaction",
309
+ "TypedTableMutator",
310
+ "Value",
311
+ "ViewEntry",
312
+ "ViewValue",
313
+ "ZeroRow",
314
+ "ZeroValue",
315
+ "ZeroValueError"
316
+ ]);
317
+ var rowConsts = ["TABLE"];
318
+ var aggregatesField = "aggregates";
319
+ var enumMembers = ["ALL"];
320
+ var wordBoundary = /([a-z0-9])([A-Z])/g;
321
+ var nonWord = /[^A-Za-z0-9]+/;
322
+ var leadingDigit = /^[0-9]/;
323
+ function words(name) {
324
+ const out = name.replace(wordBoundary, "$1 $2").split(nonWord).filter((w) => w !== "");
325
+ if (out.length) {
326
+ return out;
327
+ }
328
+ return [
329
+ "x" + Array.from(name, (ch) => ch.codePointAt(0).toString(16)).join("x")
330
+ ];
331
+ }
332
+ function head(id) {
333
+ return leadingDigit.test(id) ? "_" + id : id;
334
+ }
335
+ function snakeCase(name) {
336
+ return head(
337
+ words(name).map((w) => w.toLowerCase()).join("_")
338
+ );
339
+ }
340
+ function screamingCase(name) {
341
+ return head(
342
+ words(name).map((w) => w.toUpperCase()).join("_")
343
+ );
344
+ }
345
+ function capitalize(w) {
346
+ const rest = w.slice(1);
347
+ return w[0].toUpperCase() + (w.length > 1 && w === w.toUpperCase() ? rest.toLowerCase() : rest);
348
+ }
349
+ function pascalCase(name) {
350
+ return head(words(name).map(capitalize).join(""));
351
+ }
352
+ function ref(id) {
353
+ return keywords.has(id) ? `r#${id}` : id;
354
+ }
355
+ var Members = class {
356
+ #used;
357
+ constructor(reserved = []) {
358
+ this.#used = new Set(reserved);
359
+ }
360
+ #free(id) {
361
+ return !this.#used.has(id) && !rawless.has(id);
362
+ }
363
+ claim(id) {
364
+ while (!this.#free(id)) {
365
+ id += "_";
366
+ }
367
+ this.#used.add(id);
368
+ return id;
369
+ }
370
+ /**
371
+ * Claims an identifier for each name. The names that are their
372
+ * identifier claim first, so a name that works as it is keeps it.
373
+ */
374
+ claimAll(names) {
375
+ const out = [];
376
+ const keep = names.map((n) => n.id === n.name && this.#free(n.id));
377
+ for (const pass of [true, false]) {
378
+ for (const [i, n] of names.entries()) {
379
+ if (keep[i] === pass) {
380
+ out[i] = this.claim(n.id);
381
+ }
382
+ }
383
+ }
384
+ return out;
385
+ }
386
+ };
387
+ function str(s) {
388
+ let out = '"';
389
+ for (const ch of s) {
390
+ const c = ch.codePointAt(0);
391
+ if (ch === '"' || ch === "\\") {
392
+ out += "\\" + ch;
393
+ } else if (ch === "\n") {
394
+ out += "\\n";
395
+ } else if (ch === "\r") {
396
+ out += "\\r";
397
+ } else if (ch === " ") {
398
+ out += "\\t";
399
+ } else if (c < 32 || c === 127 || c >= 55296 && c <= 57343) {
400
+ out += `\\u{${(c >= 55296 && c <= 57343 ? 65533 : c).toString(16)}}`;
401
+ } else {
402
+ out += ch;
403
+ }
404
+ }
405
+ return out + '"';
406
+ }
407
+ function rawStr(s) {
408
+ let hashes = "#";
409
+ while (s.includes('"' + hashes)) {
410
+ hashes += "#";
411
+ }
412
+ return `r${hashes}"${s}"${hashes}`;
413
+ }
414
+ function typeTaken(name, used) {
415
+ return used.has(name) || reservedTypeNames.has(name) || keywords.has(name);
416
+ }
417
+ var Emitter = class {
418
+ #named = [];
419
+ #names;
420
+ /** Declared types by alias and shape, so a type used twice is one type. */
421
+ #byAlias = /* @__PURE__ */ new Map();
422
+ #prefix;
423
+ constructor(prefix, rowNames) {
424
+ this.#prefix = prefix;
425
+ this.#names = new Set(rowNames);
426
+ }
427
+ bare(name) {
428
+ return this.#prefix && name.startsWith(this.#prefix) ? name.slice(this.#prefix.length) : name;
429
+ }
430
+ get named() {
431
+ return this.#named;
432
+ }
433
+ /** `name`, else `name` with a number from 2: the first that is free. */
434
+ claimNumbered(name) {
435
+ let out = name;
436
+ for (let i = 2; typeTaken(out, this.#names); i++) {
437
+ out = name + i;
438
+ }
439
+ this.#names.add(out);
440
+ return out;
441
+ }
442
+ /** A free type name: the alias, else `path`, else that with a number. */
443
+ #claim(preferred, path) {
444
+ const free = (name) => !typeTaken(name, this.#names);
445
+ const candidates = [preferred, path].filter((n) => n !== void 0).map((n) => this.#prefix + pascalCase(n));
446
+ for (const name of candidates) {
447
+ if (free(name)) {
448
+ this.#names.add(name);
449
+ return name;
450
+ }
451
+ }
452
+ const fallback = this.#prefix + pascalCase(path);
453
+ for (let i = 2; ; i++) {
454
+ if (free(fallback + i)) {
455
+ this.#names.add(fallback + i);
456
+ return fallback + i;
457
+ }
458
+ }
459
+ }
460
+ /** The Rust type of a model, naming its enums and objects after `path`. */
461
+ rustType(model2, path) {
462
+ switch (model2.kind) {
463
+ case "string":
464
+ return "String";
465
+ case "number":
466
+ return "f64";
467
+ case "boolean":
468
+ return "bool";
469
+ case "json":
470
+ return "z::Value";
471
+ case "nullable":
472
+ return option(this.rustType(model2.wrapped, path));
473
+ case "array":
474
+ return `Vec<${this.rustType(model2.element, path)}>`;
475
+ case "enum":
476
+ case "object": {
477
+ const key = model2.alias && `${model2.alias}:${JSON.stringify(model2)}`;
478
+ const existing = key && this.#byAlias.get(key);
479
+ if (existing) {
480
+ return existing;
481
+ }
482
+ const name = this.#claim(model2.alias, path);
483
+ if (key) {
484
+ this.#byAlias.set(key, name);
485
+ }
486
+ this.#named.push(
487
+ model2.kind === "enum" ? { kind: "enum", name, cases: model2.cases } : { kind: "object", name, fields: model2.fields }
488
+ );
489
+ return name;
490
+ }
491
+ }
492
+ }
493
+ };
494
+ function option(type) {
495
+ return type.startsWith("Option<") ? type : `Option<${type}>`;
496
+ }
497
+ function generate2(schema, customTypes, config, source) {
498
+ const tableNames = Object.keys(schema.tables);
499
+ const prefix = config.typePrefix ?? "";
500
+ const rowNames = /* @__PURE__ */ new Map();
501
+ const used = /* @__PURE__ */ new Set();
502
+ for (const t of tableNames) {
503
+ const preferred = config.tables?.[t]?.type ?? prefix + pascalCase(t);
504
+ let name = preferred;
505
+ for (let i = 1; typeTaken(name, used); i++) {
506
+ name = `${preferred}Row${i === 1 ? "" : i}`;
507
+ }
508
+ used.add(name);
509
+ rowNames.set(t, name);
510
+ }
511
+ const fns = new Members().claimAll(
512
+ tableNames.map((t) => ({ name: t, id: snakeCase(t) }))
513
+ );
514
+ const e = new Emitter(prefix, used);
515
+ const out = [
516
+ `// @generated by \`zero-rust codegen\` from ${source}. Do not edit.`,
517
+ "//",
518
+ "// Declare it as `#[rustfmt::skip] mod schema;`: rustfmt would reformat it,",
519
+ "// and `zero-rust codegen --check` compares it as generated.",
520
+ "#![allow(dead_code)]",
521
+ "",
522
+ "use ::zero_client::typed as z;",
523
+ ""
524
+ ];
525
+ const tables = [];
526
+ for (const t of tableNames) {
527
+ const table = schema.tables[t];
528
+ const row = rowNames.get(t);
529
+ const columns = Object.entries(table.columns).map(([name, c]) => {
530
+ const custom = customTypes.get(t)?.get(name);
531
+ const override = config.tables?.[t]?.columns?.[name]?.type;
532
+ const path = e.bare(row) + pascalCase(name);
533
+ let base;
534
+ if (override === "int") {
535
+ base = "i64";
536
+ } else if (c.type === "number" || override === "double") {
537
+ base = "f64";
538
+ } else if (c.type === "boolean") {
539
+ base = "bool";
540
+ } else if (c.type === "string") {
541
+ base = custom?.kind === "enum" ? e.rustType(custom, path) : "String";
542
+ } else if (c.type === "json") {
543
+ base = custom ? e.rustType(custom, path) : "z::Value";
544
+ } else {
545
+ base = "z::Value";
546
+ }
547
+ const rustType = c.optional === true ? option(base) : base;
548
+ return {
549
+ name,
550
+ field: snakeCase(name),
551
+ constant: screamingCase(name),
552
+ rustType
553
+ };
554
+ });
555
+ const relationships = Object.entries(
556
+ schema.relationships[t] ?? {}
557
+ ).map(([name, hops]) => {
558
+ const last = hops.at(-1);
559
+ return {
560
+ name,
561
+ field: snakeCase(name),
562
+ constant: screamingCase(name),
563
+ dest: rowNames.get(last.destSchema),
564
+ one: last.cardinality === "one"
565
+ };
566
+ });
567
+ const props = [...columns, ...relationships];
568
+ const fields = new Members(
569
+ relationships.length ? [aggregatesField] : []
570
+ ).claimAll(props.map((p) => ({ name: p.name, id: p.field })));
571
+ const constants = new Members(rowConsts).claimAll(
572
+ props.map((p) => ({ name: p.name, id: p.constant }))
573
+ );
574
+ for (const [i, p] of props.entries()) {
575
+ p.field = fields[i];
576
+ p.constant = constants[i];
577
+ }
578
+ tables.push({ t, columns, relationships });
579
+ }
580
+ const updateNames = /* @__PURE__ */ new Map();
581
+ const keyNames = /* @__PURE__ */ new Map();
582
+ for (const t of tableNames) {
583
+ updateNames.set(t, e.claimNumbered(rowNames.get(t) + "Update"));
584
+ keyNames.set(t, e.claimNumbered(rowNames.get(t) + "Key"));
585
+ }
586
+ const rowDecls = [];
587
+ for (const { t, columns, relationships } of tables) {
588
+ const table = schema.tables[t];
589
+ const row = rowNames.get(t);
590
+ const lines = [];
591
+ const serverName = table.serverName ? ` (\`${table.serverName}\` on the server)` : "";
592
+ lines.push(`/// A row of \`${t}\`${serverName}.`);
593
+ lines.push("#[derive(Clone, Debug, PartialEq)]");
594
+ lines.push(`pub struct ${row} {`);
595
+ for (const c of columns) {
596
+ lines.push(` pub ${ref(c.field)}: ${c.rustType},`);
597
+ }
598
+ if (relationships.length) {
599
+ lines.push(
600
+ " // Relationships, filled when a query asks for them with `related`."
601
+ );
602
+ for (const r of relationships) {
603
+ lines.push(
604
+ ` pub ${ref(r.field)}: ${r.one ? `Option<Box<${r.dest}>>` : `Option<Vec<${r.dest}>>`},`
605
+ );
606
+ }
607
+ lines.push(
608
+ " /// The aggregates a query asked for in `related`.",
609
+ ` pub ${aggregatesField}: z::RelationshipAggregates<${row}>,`
610
+ );
611
+ }
612
+ lines.push("}");
613
+ lines.push("");
614
+ lines.push(`impl ${row} {`);
615
+ for (const c of columns) {
616
+ lines.push(
617
+ ` pub const ${c.constant}: z::Column<${row}, ${c.rustType}> = z::Column::new(${str(c.name)});`
618
+ );
619
+ }
620
+ for (const r of relationships) {
621
+ lines.push(
622
+ ` pub const ${r.constant}: z::Relationship<${row}, ${r.dest}> = z::Relationship::new(${str(r.name)});`
623
+ );
624
+ }
625
+ lines.push("}");
626
+ lines.push("");
627
+ lines.push(`impl z::QueryElement for ${row} {`);
628
+ lines.push(
629
+ " fn from_entry(entry: &z::ViewEntry) -> Result<Self, z::ZeroValueError> {"
630
+ );
631
+ lines.push(` Ok(${row} {`);
632
+ for (const [i, c] of columns.entries()) {
633
+ lines.push(
634
+ ` ${ref(c.field)}: z::column(entry, ${str(c.name)}, ${i})?,`
635
+ );
636
+ }
637
+ for (const r of relationships) {
638
+ lines.push(
639
+ ` ${ref(r.field)}: z::${r.one ? "one" : "many"}(entry, ${str(r.name)})?,`
640
+ );
641
+ }
642
+ if (relationships.length) {
643
+ lines.push(
644
+ ` ${aggregatesField}: z::RelationshipAggregates::from_entry(entry),`
645
+ );
646
+ }
647
+ lines.push(" })");
648
+ lines.push(" }");
649
+ lines.push("}");
650
+ lines.push("");
651
+ lines.push(`impl z::ZeroRow for ${row} {`);
652
+ lines.push(` const TABLE: &'static str = ${str(t)};`);
653
+ lines.push(` type Update = ${updateNames.get(t)};`);
654
+ lines.push(` type Key = ${keyNames.get(t)};`);
655
+ lines.push("");
656
+ lines.push(" fn column_values(&self) -> z::Object {");
657
+ lines.push(
658
+ ` let mut row = z::Object::with_capacity(${columns.length});`
659
+ );
660
+ for (const c of columns) {
661
+ lines.push(
662
+ ` row.insert(${str(c.name)}, z::ZeroValue::to_zero_value(&self.${ref(c.field)}));`
663
+ );
664
+ }
665
+ lines.push(" row");
666
+ lines.push(" }");
667
+ lines.push("}");
668
+ lines.push("");
669
+ lines.push(...optionalElement(row, "optional_row"));
670
+ const keyColumns = table.primaryKey.map(
671
+ (k) => columns.find((c) => c.name === k)
672
+ );
673
+ const fn = ref(fns[tableNames.indexOf(t)]);
674
+ lines.push(
675
+ "",
676
+ ...columnsDecl(
677
+ updateNames.get(t),
678
+ `What \`mutate::${fn}(tx).update\` takes: the primary key, and the other columns to set. A column that is \`None\`, or \`ColumnUpdate::Unchanged\`, keeps its value.`,
679
+ columns.map((c) => ({ ...c, key: keyColumns.includes(c) }))
680
+ ),
681
+ "",
682
+ ...columnsDecl(
683
+ keyNames.get(t),
684
+ `What \`mutate::${fn}(tx).delete\` takes: the primary key.`,
685
+ keyColumns.map((c) => ({ ...c, key: true }))
686
+ )
687
+ );
688
+ rowDecls.push(lines.join("\n"));
689
+ }
690
+ const namedDecls = [];
691
+ for (let i = 0; i < e.named.length; i++) {
692
+ const n = e.named[i];
693
+ namedDecls.push(n.kind === "enum" ? enumDecl(n) : objectDecl(e, n));
694
+ }
695
+ out.push(...rowDecls.flatMap((d) => [d, ""]));
696
+ out.push(...namedDecls.flatMap((d) => [d, ""]));
697
+ out.push(...schemaDecl(schema));
698
+ out.push("");
699
+ out.push(
700
+ `/// The queries of the schema, one per table: \`zql::${tableNames[0] ? ref(snakeCase(tableNames[0])) : "table"}()\`.`
701
+ );
702
+ out.push("pub mod zql {");
703
+ for (const [i, t] of tableNames.entries()) {
704
+ const row = rowNames.get(t);
705
+ if (i > 0) out.push("");
706
+ out.push(` /// The rows of \`${t}\`.`);
707
+ out.push(` pub fn ${ref(fns[i])}() -> super::z::Query<super::${row}> {`);
708
+ out.push(" super::z::Query::table(super::schema())");
709
+ out.push(" }");
710
+ }
711
+ out.push("}");
712
+ out.push("");
713
+ out.push(
714
+ `/// The CRUD operations of a mutator, one per table: \`mutate::${tableNames[0] ? ref(fns[0]) : "table"}(tx).insert(&row)\`.`
715
+ );
716
+ out.push("pub mod mutate {");
717
+ for (const [i, t] of tableNames.entries()) {
718
+ const row = rowNames.get(t);
719
+ if (i > 0) out.push("");
720
+ out.push(
721
+ ` /// Inserts, upserts, updates, and deletes rows of \`${t}\`.`
722
+ );
723
+ out.push(
724
+ ` pub fn ${ref(fns[i])}(tx: &super::z::Transaction) -> super::z::TypedTableMutator<'_, super::${row}> {`
725
+ );
726
+ out.push(" super::z::TypedTableMutator::new(tx)");
727
+ out.push(" }");
728
+ }
729
+ out.push("}");
730
+ out.push("");
731
+ return out.join("\n");
732
+ }
733
+ function columnsDecl(name, doc, columns) {
734
+ const nullable = (c) => c.rustType.startsWith("Option<");
735
+ const type = (c) => c.key ? c.rustType : nullable(c) ? `z::ColumnUpdate<${c.rustType.slice("Option<".length, -1)}>` : `Option<${c.rustType}>`;
736
+ const keys = columns.filter((c) => c.key);
737
+ const lines = [
738
+ `/// ${doc}`,
739
+ "#[derive(Clone, Debug, PartialEq)]",
740
+ `pub struct ${name} {`
741
+ ];
742
+ for (const c of columns) {
743
+ lines.push(` pub ${ref(c.field)}: ${type(c)},`);
744
+ }
745
+ lines.push("}");
746
+ if (keys.length < columns.length) {
747
+ lines.push("");
748
+ lines.push(`impl ${name} {`);
749
+ lines.push(
750
+ " /// The primary key, with every other column left as it is."
751
+ );
752
+ lines.push(
753
+ ` pub fn new(${keys.map((c) => `${ref(c.field)}: ${c.rustType}`).join(", ")}) -> Self {`
754
+ );
755
+ lines.push(` ${name} {`);
756
+ for (const c of columns) {
757
+ lines.push(
758
+ c.key ? ` ${ref(c.field)},` : ` ${ref(c.field)}: ${nullable(c) ? "z::ColumnUpdate::Unchanged" : "None"},`
759
+ );
760
+ }
761
+ lines.push(" }");
762
+ lines.push(" }");
763
+ lines.push("}");
764
+ }
765
+ lines.push("");
766
+ lines.push(`impl z::ColumnValues for ${name} {`);
767
+ lines.push(" fn column_values(&self) -> z::Object {");
768
+ lines.push(
769
+ ` let mut row = z::Object::with_capacity(${columns.length});`
770
+ );
771
+ for (const c of columns) {
772
+ const f = `self.${ref(c.field)}`;
773
+ lines.push(
774
+ c.key ? ` row.insert(${str(c.name)}, z::ZeroValue::to_zero_value(&${f}));` : nullable(c) ? ` if let Some(v) = ${f}.to_zero_value() {
775
+ row.insert(${str(c.name)}, v);
776
+ }` : ` if let Some(v) = &${f} {
777
+ row.insert(${str(c.name)}, z::ZeroValue::to_zero_value(v));
778
+ }`
779
+ );
780
+ }
781
+ lines.push(" row");
782
+ lines.push(" }");
783
+ lines.push("}");
784
+ return lines;
785
+ }
786
+ function optionalElement(type, read) {
787
+ return [
788
+ `impl z::OptionalQueryElement for ${type} {`,
789
+ " fn optional_from_view(view: &z::ViewValue) -> Result<Option<Self>, z::ZeroValueError> {",
790
+ ` z::${read}(view)`,
791
+ " }",
792
+ "}"
793
+ ];
794
+ }
795
+ function enumDecl(n) {
796
+ const variants = new Members(enumMembers).claimAll(
797
+ n.cases.map((value) => ({ name: value, id: pascalCase(value) }))
798
+ );
799
+ const lines = [
800
+ `/// The cases of \`${n.name}\`.`,
801
+ "#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]",
802
+ `pub enum ${n.name} {`
803
+ ];
804
+ for (const [i, value] of n.cases.entries()) {
805
+ if (variants[i] !== value) lines.push(` /// ${str(value)}`);
806
+ lines.push(` ${ref(variants[i])},`);
807
+ }
808
+ lines.push("}");
809
+ lines.push("");
810
+ lines.push(`impl ${n.name} {`);
811
+ lines.push(" /// Every case, in declaration order.");
812
+ lines.push(
813
+ ` pub const ALL: [${n.name}; ${n.cases.length}] = [${variants.map((v) => `${n.name}::${ref(v)}`).join(", ")}];`
814
+ );
815
+ lines.push("");
816
+ lines.push(" /// The string a row holds for this case.");
817
+ lines.push(" pub fn as_str(self) -> &'static str {");
818
+ lines.push(" match self {");
819
+ for (const [i, value] of n.cases.entries()) {
820
+ lines.push(` ${n.name}::${ref(variants[i])} => ${str(value)},`);
821
+ }
822
+ lines.push(" }");
823
+ lines.push(" }");
824
+ lines.push("}");
825
+ lines.push("");
826
+ lines.push(`impl z::ZeroValue for ${n.name} {`);
827
+ lines.push(
828
+ " fn from_zero_value(value: &z::Value) -> Result<Self, z::ZeroValueError> {"
829
+ );
830
+ lines.push(" match value.as_str() {");
831
+ for (const [i, value] of n.cases.entries()) {
832
+ lines.push(
833
+ ` Some(${str(value)}) => Ok(${n.name}::${ref(variants[i])}),`
834
+ );
835
+ }
836
+ lines.push(
837
+ ` _ => Err(z::ZeroValueError::mismatch(${str(`one of the cases of ${n.name}`)}, value)),`
838
+ );
839
+ lines.push(" }");
840
+ lines.push(" }");
841
+ lines.push("");
842
+ lines.push(" fn to_zero_value(&self) -> z::Value {");
843
+ lines.push(" z::Value::String(self.as_str().to_owned())");
844
+ lines.push(" }");
845
+ lines.push("}");
846
+ lines.push("");
847
+ lines.push(`impl z::OrderedZeroValue for ${n.name} {`);
848
+ lines.push(` type Unwrapped = ${n.name};`);
849
+ lines.push("}");
850
+ lines.push("");
851
+ lines.push(...optionalElement(n.name, "optional_value"));
852
+ return lines.join("\n");
853
+ }
854
+ function objectDecl(e, n) {
855
+ const ids = new Members().claimAll(
856
+ n.fields.map((f) => ({ name: f.name, id: snakeCase(f.name) }))
857
+ );
858
+ const fields = n.fields.map((f, i) => {
859
+ const base = e.rustType(f.type, e.bare(n.name) + pascalCase(f.name));
860
+ return {
861
+ ...f,
862
+ field: ref(ids[i]),
863
+ rustType: f.optional ? option(base) : base
864
+ };
865
+ });
866
+ const lines = [
867
+ `/// The \`${n.name}\` objects of a \`json\` column.`,
868
+ "#[derive(Clone, Debug, PartialEq)]",
869
+ `pub struct ${n.name} {`
870
+ ];
871
+ for (const f of fields) {
872
+ lines.push(` pub ${f.field}: ${f.rustType},`);
873
+ }
874
+ lines.push("}");
875
+ lines.push("");
876
+ lines.push(`impl z::ZeroValue for ${n.name} {`);
877
+ lines.push(
878
+ " fn from_zero_value(value: &z::Value) -> Result<Self, z::ZeroValueError> {"
879
+ );
880
+ lines.push(` let object = z::object(value, ${str(n.name)})?;`);
881
+ lines.push(` Ok(${n.name} {`);
882
+ for (const f of fields) {
883
+ lines.push(` ${f.field}: z::field(object, ${str(f.name)})?,`);
884
+ }
885
+ lines.push(" })");
886
+ lines.push(" }");
887
+ lines.push("");
888
+ lines.push(" fn to_zero_value(&self) -> z::Value {");
889
+ lines.push(
890
+ ` let mut object = z::Object::with_capacity(${fields.length});`
891
+ );
892
+ for (const f of fields) {
893
+ lines.push(
894
+ f.optional ? ` if let Some(v) = &self.${f.field} {
895
+ object.insert(${str(f.name)}, z::ZeroValue::to_zero_value(v));
896
+ }` : ` object.insert(${str(f.name)}, z::ZeroValue::to_zero_value(&self.${f.field}));`
897
+ );
898
+ }
899
+ lines.push(" z::Value::Object(object)");
900
+ lines.push(" }");
901
+ lines.push("}");
902
+ return lines.join("\n");
903
+ }
904
+ function schemaDecl(schema) {
905
+ const tables = {};
906
+ for (const [t, table] of Object.entries(schema.tables)) {
907
+ const columns = {};
908
+ for (const [c, col] of Object.entries(table.columns)) {
909
+ columns[c] = {
910
+ type: col.type,
911
+ ...col.optional ? { optional: true } : {},
912
+ ...col.serverName ? { serverName: col.serverName } : {}
913
+ };
914
+ }
915
+ tables[t] = {
916
+ name: t,
917
+ ...table.serverName ? { serverName: table.serverName } : {},
918
+ columns,
919
+ primaryKey: table.primaryKey
920
+ };
921
+ }
922
+ const relationships = {};
923
+ for (const [t, byName] of Object.entries(schema.relationships)) {
924
+ if (Object.keys(byName).length === 0) continue;
925
+ relationships[t] = Object.fromEntries(
926
+ Object.entries(byName).map(([r, hops]) => [
927
+ r,
928
+ hops.map((h) => ({
929
+ sourceField: h.sourceField,
930
+ destField: h.destField,
931
+ destSchema: h.destSchema,
932
+ cardinality: h.cardinality
933
+ }))
934
+ ])
935
+ );
936
+ }
937
+ const json = JSON.stringify({ tables, relationships }, null, 2);
938
+ return [
939
+ "/// The schema the queries of `zql` are over.",
940
+ "pub fn schema() -> ::std::sync::Arc<z::Schema> {",
941
+ " static SCHEMA: ::std::sync::OnceLock<::std::sync::Arc<z::Schema>> = ::std::sync::OnceLock::new();",
942
+ ` SCHEMA.get_or_init(|| z::schema_from_json(${rawStr(json)})).clone()`,
943
+ "}"
944
+ ];
945
+ }
946
+
947
+ // ../zerogen/src/rust-cli.ts
948
+ var configFile = "zero-rust.json";
949
+ async function codegenRustFile(config, cwd) {
950
+ const { schema, customTypes, source } = await loadSchema(
951
+ config,
952
+ cwd,
953
+ configFile
954
+ );
955
+ return generate2(schema, customTypes, config, source);
956
+ }
957
+ function createRustCli(version) {
958
+ return Cli2.create("zero-rust", {
959
+ version,
960
+ description: "Generates what the Zero Rust client needs from a Zero app's TypeScript schema."
961
+ }).command("codegen", {
962
+ description: `Generate the Rust row types, schema, and query builder from the app's TypeScript schema. Options override ${configFile}, which is read when present. See rust/README.md in github.com/wevm/zero.`,
963
+ options: z4.object({
964
+ "config": z4.string().optional().describe(`Config file (default ${configFile}, when present)`),
965
+ "schema-file": z4.string().optional().describe("TS schema module (default schema.ts)"),
966
+ "export": z4.string().optional().describe(
967
+ "Export of the module that holds the schema (default schema)"
968
+ ),
969
+ "out": z4.string().optional().describe("Rust file to write (default src/schema.rs)"),
970
+ ...options2,
971
+ check
972
+ }),
973
+ examples: [
974
+ { description: `Generate from ${configFile}` },
975
+ {
976
+ options: { "schema-file": "shared/schema.ts", "out": "src/schema.rs" },
977
+ description: "Generate without a config file"
978
+ }
979
+ ],
980
+ hint: "In CI, zero-rust codegen --check fails when the output is stale.",
981
+ run: (c) => reporting(c.error, async () => {
982
+ const cwd = process.cwd();
983
+ const {
984
+ "config": configOption,
985
+ "schema-file": schemaFile,
986
+ out
987
+ } = c.options;
988
+ const configPath = configOption ?? (existsSync2(resolve3(cwd, configFile)) ? configFile : void 0);
989
+ if (configPath) {
990
+ mustExist(
991
+ resolve3(cwd, configPath),
992
+ "CONFIG_NOT_FOUND",
993
+ `Config ${configPath} doesn't exist.`
994
+ );
995
+ }
996
+ const fileConfig = configPath ? JSON.parse(
997
+ readFileSync2(resolve3(cwd, configPath), "utf8")
998
+ ) : {};
999
+ const config = {
1000
+ ...fileConfig,
1001
+ ...overrides2(c.options),
1002
+ ...c.options.export !== void 0 ? { export: c.options.export } : {},
1003
+ ...schemaFile ? { schema: schemaFile } : {},
1004
+ ...out ? { output: out } : {}
1005
+ };
1006
+ return writeOutput(
1007
+ resolve3(cwd, config.output ?? "src/schema.rs"),
1008
+ await codegenRustFile(config, cwd),
1009
+ c.options.check ?? false,
1010
+ cwd
1011
+ );
1012
+ })
1013
+ });
1014
+ }
1015
+
1016
+ // package.json
1017
+ var package_default = {
1018
+ name: "zero-rust",
1019
+ version: "0.1.0",
1020
+ description: "Generates the Rust row types, schema, and query builder of a Zero app for the Zero Rust client.",
1021
+ license: "Apache-2.0",
1022
+ repository: {
1023
+ type: "git",
1024
+ url: "git+https://github.com/wevm/zero.git",
1025
+ directory: "packages/zero-rust-cli"
1026
+ },
1027
+ bin: {
1028
+ "zero-rust": "./src/bin.ts"
1029
+ },
1030
+ files: [
1031
+ "dist"
1032
+ ],
1033
+ type: "module",
1034
+ publishConfig: {
1035
+ bin: {
1036
+ "zero-rust": "./dist/bin.js"
1037
+ }
1038
+ },
1039
+ scripts: {
1040
+ build: "esbuild src/bin.ts --bundle --platform=node --format=esm --target=node22 --splitting --outdir=dist --external:@rocicorp/zero --external:typescript --external:incur",
1041
+ test: "vitest run",
1042
+ smoke: "node test/packed.ts",
1043
+ generate: "UPDATE_GENERATED=1 vitest run",
1044
+ "check-types": "tsc",
1045
+ lint: "oxlint --quiet --config ../../oxlint.config.ts src/ test/",
1046
+ format: "oxfmt .",
1047
+ "check-format": "oxfmt --check .",
1048
+ "sync-version": `sh ../../rust/scripts/set-version.sh "$(node -p 'require("./package.json").version')"`
1049
+ },
1050
+ dependencies: {
1051
+ incur: "0.7.1",
1052
+ typescript: "6.0.3"
1053
+ },
1054
+ devDependencies: {
1055
+ "@rocicorp/zero": "workspace:*",
1056
+ "@types/node": "^22.19.19",
1057
+ esbuild: "0.28.2",
1058
+ oxfmt: "^0.74.0",
1059
+ vitest: "^5.0.5",
1060
+ "zero-schema": "workspace:*",
1061
+ zerogen: "workspace:*",
1062
+ zql: "workspace:*"
1063
+ },
1064
+ peerDependencies: {
1065
+ "@rocicorp/zero": ">=1.11.0"
1066
+ },
1067
+ engines: {
1068
+ node: ">=22.18"
1069
+ }
1070
+ };
1071
+
1072
+ // src/cli.ts
1073
+ var cli = createRustCli(package_default.version);
1074
+
1075
+ // src/bin.ts
1076
+ await cli.serve(process.argv.slice(2));