@zenstackhq/cli 3.0.0-beta.3 → 3.0.0-beta.30

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/index.js CHANGED
@@ -1,5 +1,11 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
3
9
  var __export = (target, all) => {
4
10
  for (var name in all)
5
11
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -7,33 +13,11 @@ var __export = (target, all) => {
7
13
 
8
14
  // src/index.ts
9
15
  import { ZModelLanguageMetaData } from "@zenstackhq/language";
10
- import colors7 from "colors";
16
+ import colors9 from "colors";
11
17
  import { Command, CommanderError, Option } from "commander";
12
18
 
13
- // src/actions/db.ts
14
- import fs2 from "fs";
15
-
16
- // src/utils/exec-utils.ts
17
- import { execSync as _exec } from "child_process";
18
- function execSync(cmd, options) {
19
- const { env: env2, ...restOptions } = options ?? {};
20
- const mergedEnv = env2 ? {
21
- ...process.env,
22
- ...env2
23
- } : void 0;
24
- _exec(cmd, {
25
- encoding: "utf-8",
26
- stdio: options?.stdio ?? "inherit",
27
- env: mergedEnv,
28
- ...restOptions
29
- });
30
- }
31
- __name(execSync, "execSync");
32
- function execPackage(cmd, options) {
33
- const packageManager = process?.versions?.["bun"] ? "bunx" : "npx";
34
- execSync(`${packageManager} ${cmd}`, options);
35
- }
36
- __name(execPackage, "execPackage");
19
+ // src/actions/check.ts
20
+ import colors2 from "colors";
37
21
 
38
22
  // src/actions/action-utils.ts
39
23
  import { loadDocument } from "@zenstackhq/language";
@@ -63,14 +47,22 @@ function getSchemaFile(file) {
63
47
  if (!fs.existsSync(pkgJsonConfig.schema)) {
64
48
  throw new CliError(`Schema file not found: ${pkgJsonConfig.schema}`);
65
49
  }
66
- return pkgJsonConfig.schema;
50
+ if (fs.statSync(pkgJsonConfig.schema).isDirectory()) {
51
+ const schemaPath = path.join(pkgJsonConfig.schema, "schema.zmodel");
52
+ if (!fs.existsSync(schemaPath)) {
53
+ throw new CliError(`Schema file not found: ${schemaPath}`);
54
+ }
55
+ return schemaPath;
56
+ } else {
57
+ return pkgJsonConfig.schema;
58
+ }
67
59
  }
68
- if (fs.existsSync("./zenstack/schema.zmodel")) {
69
- return "./zenstack/schema.zmodel";
70
- } else if (fs.existsSync("./schema.zmodel")) {
60
+ if (fs.existsSync("./schema.zmodel")) {
71
61
  return "./schema.zmodel";
62
+ } else if (fs.existsSync("./zenstack/schema.zmodel")) {
63
+ return "./zenstack/schema.zmodel";
72
64
  } else {
73
- throw new CliError('Schema file not found in default locations ("./zenstack/schema.zmodel" or "./schema.zmodel").');
65
+ throw new CliError('Schema file not found in default locations ("./schema.zmodel" or "./zenstack/schema.zmodel").');
74
66
  }
75
67
  }
76
68
  __name(getSchemaFile, "getSchemaFile");
@@ -113,7 +105,8 @@ __name(generateTempPrismaSchema, "generateTempPrismaSchema");
113
105
  function getPkgJsonConfig(startPath) {
114
106
  const result = {
115
107
  schema: void 0,
116
- output: void 0
108
+ output: void 0,
109
+ seed: void 0
117
110
  };
118
111
  const pkgJsonFile = findUp([
119
112
  "package.json"
@@ -128,8 +121,9 @@ function getPkgJsonConfig(startPath) {
128
121
  return result;
129
122
  }
130
123
  if (pkgJson.zenstack && typeof pkgJson.zenstack === "object") {
131
- result.schema = pkgJson.zenstack.schema && path.resolve(path.dirname(pkgJsonFile), pkgJson.zenstack.schema);
132
- result.output = pkgJson.zenstack.output && path.resolve(path.dirname(pkgJsonFile), pkgJson.zenstack.output);
124
+ result.schema = pkgJson.zenstack.schema && typeof pkgJson.zenstack.schema === "string" ? path.resolve(path.dirname(pkgJsonFile), pkgJson.zenstack.schema) : void 0;
125
+ result.output = pkgJson.zenstack.output && typeof pkgJson.zenstack.output === "string" ? path.resolve(path.dirname(pkgJsonFile), pkgJson.zenstack.output) : void 0;
126
+ result.seed = typeof pkgJson.zenstack.seed === "string" && pkgJson.zenstack.seed ? pkgJson.zenstack.seed : void 0;
133
127
  }
134
128
  return result;
135
129
  }
@@ -152,29 +146,101 @@ function findUp(names, cwd = process.cwd(), multiple = false, result = []) {
152
146
  return findUp(names, up, multiple, result);
153
147
  }
154
148
  __name(findUp, "findUp");
149
+ async function requireDataSourceUrl(schemaFile) {
150
+ const zmodel = await loadSchemaDocument(schemaFile);
151
+ const dataSource = zmodel.declarations.find(isDataSource);
152
+ if (!dataSource?.fields.some((f) => f.name === "url")) {
153
+ throw new CliError(`The schema's "datasource" must have a "url" field to use this command.`);
154
+ }
155
+ }
156
+ __name(requireDataSourceUrl, "requireDataSourceUrl");
157
+
158
+ // src/actions/check.ts
159
+ async function run(options) {
160
+ const schemaFile = getSchemaFile(options.schema);
161
+ try {
162
+ await loadSchemaDocument(schemaFile);
163
+ console.log(colors2.green("\u2713 Schema validation completed successfully."));
164
+ } catch (error) {
165
+ console.error(colors2.red("\u2717 Schema validation failed."));
166
+ throw error;
167
+ }
168
+ }
169
+ __name(run, "run");
170
+
171
+ // src/actions/db.ts
172
+ import fs2 from "fs";
173
+
174
+ // src/utils/exec-utils.ts
175
+ import { execSync as _exec } from "child_process";
176
+ import { fileURLToPath } from "url";
177
+ function execSync(cmd, options) {
178
+ const { env: env2, ...restOptions } = options ?? {};
179
+ const mergedEnv = env2 ? {
180
+ ...process.env,
181
+ ...env2
182
+ } : void 0;
183
+ _exec(cmd, {
184
+ encoding: "utf-8",
185
+ stdio: options?.stdio ?? "inherit",
186
+ env: mergedEnv,
187
+ ...restOptions
188
+ });
189
+ }
190
+ __name(execSync, "execSync");
191
+ function execPackage(cmd, options) {
192
+ const packageManager = process?.versions?.["bun"] ? "bunx" : "npx";
193
+ execSync(`${packageManager} ${cmd}`, options);
194
+ }
195
+ __name(execPackage, "execPackage");
196
+ function execPrisma(args, options) {
197
+ let prismaPath;
198
+ try {
199
+ if (typeof import.meta.resolve === "function") {
200
+ prismaPath = fileURLToPath(import.meta.resolve("prisma/build/index.js"));
201
+ } else {
202
+ prismaPath = __require.resolve("prisma/build/index.js");
203
+ }
204
+ } catch {
205
+ }
206
+ const _options = {
207
+ ...options,
208
+ env: {
209
+ ...options?.env,
210
+ PRISMA_HIDE_UPDATE_MESSAGE: "1"
211
+ }
212
+ };
213
+ if (!prismaPath) {
214
+ execPackage(`prisma ${args}`, _options);
215
+ return;
216
+ }
217
+ execSync(`node ${prismaPath} ${args}`, _options);
218
+ }
219
+ __name(execPrisma, "execPrisma");
155
220
 
156
221
  // src/actions/db.ts
157
- async function run(command, options) {
222
+ async function run2(command, options) {
158
223
  switch (command) {
159
224
  case "push":
160
225
  await runPush(options);
161
226
  break;
162
227
  }
163
228
  }
164
- __name(run, "run");
229
+ __name(run2, "run");
165
230
  async function runPush(options) {
166
231
  const schemaFile = getSchemaFile(options.schema);
232
+ await requireDataSourceUrl(schemaFile);
167
233
  const prismaSchemaFile = await generateTempPrismaSchema(schemaFile);
168
234
  try {
169
235
  const cmd = [
170
- "prisma db push",
236
+ "db push",
171
237
  ` --schema "${prismaSchemaFile}"`,
172
238
  options.acceptDataLoss ? " --accept-data-loss" : "",
173
239
  options.forceReset ? " --force-reset" : "",
174
240
  " --skip-generate"
175
241
  ].join("");
176
242
  try {
177
- await execPackage(cmd);
243
+ execPrisma(cmd);
178
244
  } catch (err) {
179
245
  handleSubProcessError(err);
180
246
  }
@@ -186,11 +252,29 @@ async function runPush(options) {
186
252
  }
187
253
  __name(runPush, "runPush");
188
254
 
255
+ // src/actions/format.ts
256
+ import { formatDocument } from "@zenstackhq/language";
257
+ import colors3 from "colors";
258
+ import fs3 from "fs";
259
+ async function run3(options) {
260
+ const schemaFile = getSchemaFile(options.schema);
261
+ let formattedContent;
262
+ try {
263
+ formattedContent = await formatDocument(fs3.readFileSync(schemaFile, "utf-8"));
264
+ } catch (error) {
265
+ console.error(colors3.red("\u2717 Schema formatting failed."));
266
+ throw error;
267
+ }
268
+ fs3.writeFileSync(schemaFile, formattedContent, "utf-8");
269
+ console.log(colors3.green("\u2713 Schema formatting completed successfully."));
270
+ }
271
+ __name(run3, "run");
272
+
189
273
  // src/actions/generate.ts
190
274
  import { invariant } from "@zenstackhq/common-helpers";
191
275
  import { isPlugin } from "@zenstackhq/language/ast";
192
276
  import { getLiteral, getLiteralArray } from "@zenstackhq/language/utils";
193
- import colors2 from "colors";
277
+ import colors4 from "colors";
194
278
  import path4 from "path";
195
279
  import ora from "ora";
196
280
 
@@ -203,30 +287,30 @@ __export(plugins_exports, {
203
287
 
204
288
  // src/plugins/prisma.ts
205
289
  import { PrismaSchemaGenerator as PrismaSchemaGenerator2 } from "@zenstackhq/sdk";
206
- import fs3 from "fs";
290
+ import fs4 from "fs";
207
291
  import path2 from "path";
208
292
  var plugin = {
209
293
  name: "Prisma Schema Generator",
210
294
  statusText: "Generating Prisma schema",
211
- async generate({ model, schemaFile, defaultOutputPath, pluginOptions }) {
295
+ async generate({ model, defaultOutputPath, pluginOptions }) {
212
296
  let outFile = path2.join(defaultOutputPath, "schema.prisma");
213
297
  if (typeof pluginOptions["output"] === "string") {
214
- outFile = path2.resolve(path2.dirname(schemaFile), pluginOptions["output"]);
215
- if (!fs3.existsSync(path2.dirname(outFile))) {
216
- fs3.mkdirSync(path2.dirname(outFile), {
298
+ outFile = path2.resolve(defaultOutputPath, pluginOptions["output"]);
299
+ if (!fs4.existsSync(path2.dirname(outFile))) {
300
+ fs4.mkdirSync(path2.dirname(outFile), {
217
301
  recursive: true
218
302
  });
219
303
  }
220
304
  }
221
305
  const prismaSchema = await new PrismaSchemaGenerator2(model).generate();
222
- fs3.writeFileSync(outFile, prismaSchema);
306
+ fs4.writeFileSync(outFile, prismaSchema);
223
307
  }
224
308
  };
225
309
  var prisma_default = plugin;
226
310
 
227
311
  // src/plugins/typescript.ts
228
312
  import { TsSchemaGenerator } from "@zenstackhq/sdk";
229
- import fs4 from "fs";
313
+ import fs5 from "fs";
230
314
  import path3 from "path";
231
315
  var plugin2 = {
232
316
  name: "TypeScript Schema Generator",
@@ -235,31 +319,42 @@ var plugin2 = {
235
319
  let outDir = defaultOutputPath;
236
320
  if (typeof pluginOptions["output"] === "string") {
237
321
  outDir = path3.resolve(defaultOutputPath, pluginOptions["output"]);
238
- if (!fs4.existsSync(outDir)) {
239
- fs4.mkdirSync(outDir, {
322
+ if (!fs5.existsSync(outDir)) {
323
+ fs5.mkdirSync(outDir, {
240
324
  recursive: true
241
325
  });
242
326
  }
243
327
  }
244
- await new TsSchemaGenerator().generate(model, outDir);
328
+ const lite = pluginOptions["lite"] === true;
329
+ const liteOnly = pluginOptions["liteOnly"] === true;
330
+ const importWithFileExtension = pluginOptions["importWithFileExtension"];
331
+ if (importWithFileExtension && typeof importWithFileExtension !== "string") {
332
+ throw new Error('The "importWithFileExtension" option must be a string if specified.');
333
+ }
334
+ await new TsSchemaGenerator().generate(model, {
335
+ outDir,
336
+ lite,
337
+ liteOnly,
338
+ importWithFileExtension
339
+ });
245
340
  }
246
341
  };
247
342
  var typescript_default = plugin2;
248
343
 
249
344
  // src/actions/generate.ts
250
- async function run2(options) {
345
+ async function run4(options) {
251
346
  const start = Date.now();
252
347
  const schemaFile = getSchemaFile(options.schema);
253
348
  const model = await loadSchemaDocument(schemaFile);
254
349
  const outputPath = getOutputPath(options, schemaFile);
255
350
  await runPlugins(schemaFile, model, outputPath, options);
256
351
  if (!options.silent) {
257
- console.log(colors2.green(`Generation completed successfully in ${Date.now() - start}ms.
352
+ console.log(colors4.green(`Generation completed successfully in ${Date.now() - start}ms.
258
353
  `));
259
354
  console.log(`You can now create a ZenStack client with it.
260
355
 
261
356
  \`\`\`ts
262
- import { ZenStackClient } from '@zenstackhq/runtime';
357
+ import { ZenStackClient } from '@zenstackhq/orm';
263
358
  import { schema } from '${outputPath}/schema';
264
359
 
265
360
  const client = new ZenStackClient(schema, {
@@ -270,7 +365,7 @@ const client = new ZenStackClient(schema, {
270
365
  Check documentation: https://zenstack.dev/docs/3.x`);
271
366
  }
272
367
  }
273
- __name(run2, "run");
368
+ __name(run4, "run");
274
369
  function getOutputPath(options, schemaFile) {
275
370
  if (options.output) {
276
371
  return options.output;
@@ -301,23 +396,39 @@ async function runPlugins(schemaFile, model, outputPath, options) {
301
396
  }
302
397
  try {
303
398
  cliPlugin = (await import(moduleSpec)).default;
304
- } catch (error) {
305
- throw new CliError(`Failed to load plugin ${provider}: ${error}`);
399
+ } catch {
306
400
  }
307
401
  }
308
- processedPlugins.push({
309
- cliPlugin,
310
- pluginOptions: getPluginOptions(plugin3)
311
- });
402
+ if (cliPlugin) {
403
+ const pluginOptions = getPluginOptions(plugin3);
404
+ if (provider === "@core/typescript") {
405
+ if (pluginOptions["lite"] === void 0) {
406
+ pluginOptions["lite"] = options.lite;
407
+ }
408
+ if (pluginOptions["liteOnly"] === void 0) {
409
+ pluginOptions["liteOnly"] = options.liteOnly;
410
+ }
411
+ }
412
+ processedPlugins.push({
413
+ cliPlugin,
414
+ pluginOptions
415
+ });
416
+ }
312
417
  }
313
418
  const defaultPlugins = [
314
- typescript_default
315
- ].reverse();
316
- defaultPlugins.forEach((d) => {
317
- if (!processedPlugins.some((p) => p.cliPlugin === d)) {
419
+ {
420
+ plugin: typescript_default,
421
+ options: {
422
+ lite: options.lite,
423
+ liteOnly: options.liteOnly
424
+ }
425
+ }
426
+ ];
427
+ defaultPlugins.forEach(({ plugin: plugin3, options: options2 }) => {
428
+ if (!processedPlugins.some((p) => p.cliPlugin === plugin3)) {
318
429
  processedPlugins.push({
319
- cliPlugin: d,
320
- pluginOptions: {}
430
+ cliPlugin: plugin3,
431
+ pluginOptions: options2
321
432
  });
322
433
  }
323
434
  });
@@ -367,9 +478,9 @@ function getPluginOptions(plugin3) {
367
478
  __name(getPluginOptions, "getPluginOptions");
368
479
 
369
480
  // src/actions/info.ts
370
- import colors3 from "colors";
481
+ import colors5 from "colors";
371
482
  import path5 from "path";
372
- async function run3(projectPath) {
483
+ async function run5(projectPath) {
373
484
  const packages = await getZenStackPackages(projectPath);
374
485
  if (!packages) {
375
486
  console.error("Unable to locate package.json. Are you in a valid project directory?");
@@ -381,13 +492,13 @@ async function run3(projectPath) {
381
492
  if (version2) {
382
493
  versions.add(version2);
383
494
  }
384
- console.log(` ${colors3.green(pkg.padEnd(20))} ${version2}`);
495
+ console.log(` ${colors5.green(pkg.padEnd(20))} ${version2}`);
385
496
  }
386
497
  if (versions.size > 1) {
387
- console.warn(colors3.yellow("WARNING: Multiple versions of Zenstack packages detected. This may cause issues."));
498
+ console.warn(colors5.yellow("WARNING: Multiple versions of Zenstack packages detected. This may cause issues."));
388
499
  }
389
500
  }
390
- __name(run3, "run");
501
+ __name(run5, "run");
391
502
  async function getZenStackPackages(projectPath) {
392
503
  let pkgJson;
393
504
  const resolvedPath = path5.resolve(projectPath);
@@ -430,8 +541,8 @@ async function getZenStackPackages(projectPath) {
430
541
  __name(getZenStackPackages, "getZenStackPackages");
431
542
 
432
543
  // src/actions/init.ts
433
- import colors4 from "colors";
434
- import fs5 from "fs";
544
+ import colors6 from "colors";
545
+ import fs6 from "fs";
435
546
  import path6 from "path";
436
547
  import ora2 from "ora";
437
548
  import { detect, resolveCommand } from "package-manager-detector";
@@ -466,14 +577,14 @@ model Post {
466
577
  `;
467
578
 
468
579
  // src/actions/init.ts
469
- async function run4(projectPath) {
580
+ async function run6(projectPath) {
470
581
  const packages = [
471
582
  {
472
583
  name: "@zenstackhq/cli@next",
473
584
  dev: true
474
585
  },
475
586
  {
476
- name: "@zenstackhq/runtime@next",
587
+ name: "@zenstackhq/orm@next",
477
588
  dev: false
478
589
  }
479
590
  ];
@@ -484,7 +595,7 @@ async function run4(projectPath) {
484
595
  name: "npm"
485
596
  };
486
597
  }
487
- console.log(colors4.gray(`Using package manager: ${pm.agent}`));
598
+ console.log(colors6.gray(`Using package manager: ${pm.agent}`));
488
599
  for (const pkg of packages) {
489
600
  const resolved = resolveCommand(pm.agent, "install", [
490
601
  pkg.name,
@@ -507,25 +618,55 @@ async function run4(projectPath) {
507
618
  }
508
619
  }
509
620
  const generationFolder = "zenstack";
510
- if (!fs5.existsSync(path6.join(projectPath, generationFolder))) {
511
- fs5.mkdirSync(path6.join(projectPath, generationFolder));
621
+ if (!fs6.existsSync(path6.join(projectPath, generationFolder))) {
622
+ fs6.mkdirSync(path6.join(projectPath, generationFolder));
512
623
  }
513
- if (!fs5.existsSync(path6.join(projectPath, generationFolder, "schema.zmodel"))) {
514
- fs5.writeFileSync(path6.join(projectPath, generationFolder, "schema.zmodel"), STARTER_ZMODEL);
624
+ if (!fs6.existsSync(path6.join(projectPath, generationFolder, "schema.zmodel"))) {
625
+ fs6.writeFileSync(path6.join(projectPath, generationFolder, "schema.zmodel"), STARTER_ZMODEL);
515
626
  } else {
516
- console.log(colors4.yellow("Schema file already exists. Skipping generation of sample."));
627
+ console.log(colors6.yellow("Schema file already exists. Skipping generation of sample."));
517
628
  }
518
- console.log(colors4.green("ZenStack project initialized successfully!"));
519
- console.log(colors4.gray(`See "${generationFolder}/schema.zmodel" for your database schema.`));
520
- console.log(colors4.gray("Run `zenstack generate` to compile the the schema into a TypeScript file."));
629
+ console.log(colors6.green("ZenStack project initialized successfully!"));
630
+ console.log(colors6.gray(`See "${generationFolder}/schema.zmodel" for your database schema.`));
631
+ console.log(colors6.gray("Run `zenstack generate` to compile the the schema into a TypeScript file."));
521
632
  }
522
- __name(run4, "run");
633
+ __name(run6, "run");
523
634
 
524
635
  // src/actions/migrate.ts
525
- import fs6 from "fs";
636
+ import fs7 from "fs";
526
637
  import path7 from "path";
527
- async function run5(command, options) {
638
+
639
+ // src/actions/seed.ts
640
+ import colors7 from "colors";
641
+ import { execaCommand } from "execa";
642
+ async function run7(options, args) {
643
+ const pkgJsonConfig = getPkgJsonConfig(process.cwd());
644
+ if (!pkgJsonConfig.seed) {
645
+ if (!options.noWarnings) {
646
+ console.warn(colors7.yellow("No seed script defined in package.json. Skipping seeding."));
647
+ }
648
+ return;
649
+ }
650
+ const command = `${pkgJsonConfig.seed}${args.length > 0 ? " " + args.join(" ") : ""}`;
651
+ if (options.printStatus) {
652
+ console.log(colors7.gray(`Running seed script "${command}"...`));
653
+ }
654
+ try {
655
+ await execaCommand(command, {
656
+ stdout: "inherit",
657
+ stderr: "inherit"
658
+ });
659
+ } catch (err) {
660
+ console.error(colors7.red(err instanceof Error ? err.message : String(err)));
661
+ throw new CliError("Failed to seed the database. Please check the error message above for details.");
662
+ }
663
+ }
664
+ __name(run7, "run");
665
+
666
+ // src/actions/migrate.ts
667
+ async function run8(command, options) {
528
668
  const schemaFile = getSchemaFile(options.schema);
669
+ await requireDataSourceUrl(schemaFile);
529
670
  const prismaSchemaDir = options.migrations ? path7.dirname(options.migrations) : void 0;
530
671
  const prismaSchemaFile = await generateTempPrismaSchema(schemaFile, prismaSchemaDir);
531
672
  try {
@@ -547,22 +688,23 @@ async function run5(command, options) {
547
688
  break;
548
689
  }
549
690
  } finally {
550
- if (fs6.existsSync(prismaSchemaFile)) {
551
- fs6.unlinkSync(prismaSchemaFile);
691
+ if (fs7.existsSync(prismaSchemaFile)) {
692
+ fs7.unlinkSync(prismaSchemaFile);
552
693
  }
553
694
  }
554
695
  }
555
- __name(run5, "run");
556
- async function runDev(prismaSchemaFile, options) {
696
+ __name(run8, "run");
697
+ function runDev(prismaSchemaFile, options) {
557
698
  try {
558
699
  const cmd = [
559
- "prisma migrate dev",
700
+ "migrate dev",
560
701
  ` --schema "${prismaSchemaFile}"`,
561
702
  " --skip-generate",
562
- options.name ? ` --name ${options.name}` : "",
703
+ " --skip-seed",
704
+ options.name ? ` --name "${options.name}"` : "",
563
705
  options.createOnly ? " --create-only" : ""
564
706
  ].join("");
565
- await execPackage(cmd);
707
+ execPrisma(cmd);
566
708
  } catch (err) {
567
709
  handleSubProcessError2(err);
568
710
  }
@@ -571,48 +713,56 @@ __name(runDev, "runDev");
571
713
  async function runReset(prismaSchemaFile, options) {
572
714
  try {
573
715
  const cmd = [
574
- "prisma migrate reset",
716
+ "migrate reset",
575
717
  ` --schema "${prismaSchemaFile}"`,
718
+ " --skip-generate",
719
+ " --skip-seed",
576
720
  options.force ? " --force" : ""
577
721
  ].join("");
578
- await execPackage(cmd);
722
+ execPrisma(cmd);
579
723
  } catch (err) {
580
724
  handleSubProcessError2(err);
581
725
  }
726
+ if (!options.skipSeed) {
727
+ await run7({
728
+ noWarnings: true,
729
+ printStatus: true
730
+ }, []);
731
+ }
582
732
  }
583
733
  __name(runReset, "runReset");
584
- async function runDeploy(prismaSchemaFile, _options) {
734
+ function runDeploy(prismaSchemaFile, _options) {
585
735
  try {
586
736
  const cmd = [
587
- "prisma migrate deploy",
737
+ "migrate deploy",
588
738
  ` --schema "${prismaSchemaFile}"`
589
739
  ].join("");
590
- await execPackage(cmd);
740
+ execPrisma(cmd);
591
741
  } catch (err) {
592
742
  handleSubProcessError2(err);
593
743
  }
594
744
  }
595
745
  __name(runDeploy, "runDeploy");
596
- async function runStatus(prismaSchemaFile, _options) {
746
+ function runStatus(prismaSchemaFile, _options) {
597
747
  try {
598
- await execPackage(`prisma migrate status --schema "${prismaSchemaFile}"`);
748
+ execPrisma(`migrate status --schema "${prismaSchemaFile}"`);
599
749
  } catch (err) {
600
750
  handleSubProcessError2(err);
601
751
  }
602
752
  }
603
753
  __name(runStatus, "runStatus");
604
- async function runResolve(prismaSchemaFile, options) {
754
+ function runResolve(prismaSchemaFile, options) {
605
755
  if (!options.applied && !options.rolledBack) {
606
756
  throw new CliError("Either --applied or --rolled-back option must be provided");
607
757
  }
608
758
  try {
609
759
  const cmd = [
610
- "prisma migrate resolve",
760
+ "migrate resolve",
611
761
  ` --schema "${prismaSchemaFile}"`,
612
- options.applied ? ` --applied ${options.applied}` : "",
613
- options.rolledBack ? ` --rolled-back ${options.rolledBack}` : ""
762
+ options.applied ? ` --applied "${options.applied}"` : "",
763
+ options.rolledBack ? ` --rolled-back "${options.rolledBack}"` : ""
614
764
  ].join("");
615
- await execPackage(cmd);
765
+ execPrisma(cmd);
616
766
  } catch (err) {
617
767
  handleSubProcessError2(err);
618
768
  }
@@ -627,24 +777,10 @@ function handleSubProcessError2(err) {
627
777
  }
628
778
  __name(handleSubProcessError2, "handleSubProcessError");
629
779
 
630
- // src/actions/check.ts
631
- import colors5 from "colors";
632
- async function run6(options) {
633
- const schemaFile = getSchemaFile(options.schema);
634
- try {
635
- await loadSchemaDocument(schemaFile);
636
- console.log(colors5.green("\u2713 Schema validation completed successfully."));
637
- } catch (error) {
638
- console.error(colors5.red("\u2717 Schema validation failed."));
639
- throw error;
640
- }
641
- }
642
- __name(run6, "run");
643
-
644
780
  // src/telemetry.ts
645
781
  import { init } from "mixpanel";
646
782
  import { randomUUID as randomUUID2 } from "crypto";
647
- import fs11 from "fs";
783
+ import fs12 from "fs";
648
784
  import * as os2 from "os";
649
785
 
650
786
  // src/constants.ts
@@ -655,14 +791,14 @@ import { env } from "process";
655
791
  var isInCi = env["CI"] !== "0" && env["CI"] !== "false" && ("CI" in env || "CONTINUOUS_INTEGRATION" in env || Object.keys(env).some((key) => key.startsWith("CI_")));
656
792
 
657
793
  // src/utils/is-container.ts
658
- import fs8 from "fs";
794
+ import fs9 from "fs";
659
795
 
660
796
  // src/utils/is-docker.ts
661
- import fs7 from "fs";
797
+ import fs8 from "fs";
662
798
  var isDockerCached;
663
799
  function hasDockerEnv() {
664
800
  try {
665
- fs7.statSync("/.dockerenv");
801
+ fs8.statSync("/.dockerenv");
666
802
  return true;
667
803
  } catch {
668
804
  return false;
@@ -671,7 +807,7 @@ function hasDockerEnv() {
671
807
  __name(hasDockerEnv, "hasDockerEnv");
672
808
  function hasDockerCGroup() {
673
809
  try {
674
- return fs7.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
810
+ return fs8.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
675
811
  } catch {
676
812
  return false;
677
813
  }
@@ -689,7 +825,7 @@ __name(isDocker, "isDocker");
689
825
  var cachedResult;
690
826
  var hasContainerEnv = /* @__PURE__ */ __name(() => {
691
827
  try {
692
- fs8.statSync("/run/.containerenv");
828
+ fs9.statSync("/run/.containerenv");
693
829
  return true;
694
830
  } catch {
695
831
  return false;
@@ -706,7 +842,7 @@ __name(isInContainer, "isInContainer");
706
842
  // src/utils/is-wsl.ts
707
843
  import process2 from "process";
708
844
  import os from "os";
709
- import fs9 from "fs";
845
+ import fs10 from "fs";
710
846
  var isWsl = /* @__PURE__ */ __name(() => {
711
847
  if (process2.platform !== "linux") {
712
848
  return false;
@@ -715,7 +851,7 @@ var isWsl = /* @__PURE__ */ __name(() => {
715
851
  return true;
716
852
  }
717
853
  try {
718
- return fs9.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft");
854
+ return fs10.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft");
719
855
  } catch {
720
856
  return false;
721
857
  }
@@ -779,17 +915,17 @@ function getMachineId() {
779
915
  __name(getMachineId, "getMachineId");
780
916
 
781
917
  // src/utils/version-utils.ts
782
- import colors6 from "colors";
783
- import fs10 from "fs";
918
+ import colors8 from "colors";
919
+ import fs11 from "fs";
784
920
  import path8 from "path";
785
- import { fileURLToPath } from "url";
921
+ import { fileURLToPath as fileURLToPath2 } from "url";
786
922
  import semver from "semver";
787
923
  var CHECK_VERSION_TIMEOUT = 2e3;
788
924
  var VERSION_CHECK_TAG = "next";
789
925
  function getVersion() {
790
926
  try {
791
- const _dirname = typeof __dirname !== "undefined" ? __dirname : path8.dirname(fileURLToPath(import.meta.url));
792
- return JSON.parse(fs10.readFileSync(path8.join(_dirname, "../package.json"), "utf8")).version;
927
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : path8.dirname(fileURLToPath2(import.meta.url));
928
+ return JSON.parse(fs11.readFileSync(path8.join(_dirname, "../package.json"), "utf8")).version;
793
929
  } catch {
794
930
  return void 0;
795
931
  }
@@ -804,7 +940,7 @@ async function checkNewVersion() {
804
940
  return;
805
941
  }
806
942
  if (latestVersion && currVersion && semver.gt(latestVersion, currVersion)) {
807
- console.log(`A newer version ${colors6.cyan(latestVersion)} is available.`);
943
+ console.log(`A newer version ${colors8.cyan(latestVersion)} is available.`);
808
944
  }
809
945
  }
810
946
  __name(checkNewVersion, "checkNewVersion");
@@ -919,7 +1055,7 @@ var Telemetry = class {
919
1055
  try {
920
1056
  const packageJsonPath = import.meta.resolve("prisma/package.json");
921
1057
  const packageJsonUrl = new URL(packageJsonPath);
922
- const packageJson = JSON.parse(fs11.readFileSync(packageJsonUrl, "utf8"));
1058
+ const packageJson = JSON.parse(fs12.readFileSync(packageJsonUrl, "utf8"));
923
1059
  return packageJson.version;
924
1060
  } catch {
925
1061
  return void 0;
@@ -930,45 +1066,62 @@ var telemetry = new Telemetry();
930
1066
 
931
1067
  // src/index.ts
932
1068
  var generateAction = /* @__PURE__ */ __name(async (options) => {
933
- await telemetry.trackCommand("generate", () => run2(options));
1069
+ await telemetry.trackCommand("generate", () => run4(options));
934
1070
  }, "generateAction");
935
1071
  var migrateAction = /* @__PURE__ */ __name(async (subCommand, options) => {
936
- await telemetry.trackCommand(`migrate ${subCommand}`, () => run5(subCommand, options));
1072
+ await telemetry.trackCommand(`migrate ${subCommand}`, () => run8(subCommand, options));
937
1073
  }, "migrateAction");
938
1074
  var dbAction = /* @__PURE__ */ __name(async (subCommand, options) => {
939
- await telemetry.trackCommand(`db ${subCommand}`, () => run(subCommand, options));
1075
+ await telemetry.trackCommand(`db ${subCommand}`, () => run2(subCommand, options));
940
1076
  }, "dbAction");
941
1077
  var infoAction = /* @__PURE__ */ __name(async (projectPath) => {
942
- await telemetry.trackCommand("info", () => run3(projectPath));
1078
+ await telemetry.trackCommand("info", () => run5(projectPath));
943
1079
  }, "infoAction");
944
1080
  var initAction = /* @__PURE__ */ __name(async (projectPath) => {
945
- await telemetry.trackCommand("init", () => run4(projectPath));
1081
+ await telemetry.trackCommand("init", () => run6(projectPath));
946
1082
  }, "initAction");
947
1083
  var checkAction = /* @__PURE__ */ __name(async (options) => {
948
- await telemetry.trackCommand("check", () => run6(options));
1084
+ await telemetry.trackCommand("check", () => run(options));
949
1085
  }, "checkAction");
1086
+ var formatAction = /* @__PURE__ */ __name(async (options) => {
1087
+ await telemetry.trackCommand("format", () => run3(options));
1088
+ }, "formatAction");
1089
+ var seedAction = /* @__PURE__ */ __name(async (options, args) => {
1090
+ await telemetry.trackCommand("db seed", () => run7(options, args));
1091
+ }, "seedAction");
950
1092
  function createProgram() {
951
- const program = new Command("zen");
952
- program.version(getVersion(), "-v --version", "display CLI version");
1093
+ const program = new Command("zen").alias("zenstack").helpOption("-h, --help", "Show this help message").version(getVersion(), "-v --version", "Show CLI version");
953
1094
  const schemaExtensions = ZModelLanguageMetaData.fileExtensions.join(", ");
954
- program.description(`${colors7.bold.blue("\u03B6")} ZenStack is the data layer for modern TypeScript apps.
1095
+ program.description(`${colors9.bold.blue("\u03B6")} ZenStack is the data layer for modern TypeScript apps.
955
1096
 
956
1097
  Documentation: https://zenstack.dev/docs/3.x`).showHelpAfterError().showSuggestionAfterError();
957
1098
  const schemaOption = new Option("--schema <file>", `schema file (with extension ${schemaExtensions}). Defaults to "zenstack/schema.zmodel" unless specified in package.json.`);
958
1099
  const noVersionCheckOption = new Option("--no-version-check", "do not check for new version");
959
- program.command("generate").description("Run code generation plugins.").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("-o, --output <path>", "default output directory for code generation")).addOption(new Option("--silent", "suppress all output except errors").default(false)).action(generateAction);
1100
+ program.command("generate").description("Run code generation plugins").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("-o, --output <path>", "default output directory for code generation")).addOption(new Option("--lite", "also generate a lite version of schema without attributes").default(false)).addOption(new Option("--lite-only", "only generate lite version of schema without attributes").default(false)).addOption(new Option("--silent", "suppress all output except errors").default(false)).action(generateAction);
960
1101
  const migrateCommand = program.command("migrate").description("Run database schema migration related tasks.");
961
1102
  const migrationsOption = new Option("--migrations <path>", 'path that contains the "migrations" directory');
962
- migrateCommand.command("dev").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("-n, --name <name>", "migration name")).addOption(new Option("--create-only", "only create migration, do not apply")).addOption(migrationsOption).description("Create a migration from changes in schema and apply it to the database.").action((options) => migrateAction("dev", options));
963
- migrateCommand.command("reset").addOption(schemaOption).addOption(new Option("--force", "skip the confirmation prompt")).addOption(migrationsOption).addOption(noVersionCheckOption).description("Reset your database and apply all migrations, all data will be lost.").action((options) => migrateAction("reset", options));
964
- migrateCommand.command("deploy").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).description("Deploy your pending migrations to your production/staging database.").action((options) => migrateAction("deploy", options));
965
- migrateCommand.command("status").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).description("Check the status of your database migrations.").action((options) => migrateAction("status", options));
966
- migrateCommand.command("resolve").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).addOption(new Option("--applied <migration>", "record a specific migration as applied")).addOption(new Option("--rolled-back <migration>", "record a specific migration as rolled back")).description("Resolve issues with database migrations in deployment databases.").action((options) => migrateAction("resolve", options));
967
- const dbCommand = program.command("db").description("Manage your database schema during development.");
968
- dbCommand.command("push").description("Push the state from your schema to your database.").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("--accept-data-loss", "ignore data loss warnings")).addOption(new Option("--force-reset", "force a reset of the database before push")).action((options) => dbAction("push", options));
969
- program.command("info").description("Get information of installed ZenStack packages.").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(infoAction);
970
- program.command("init").description("Initialize an existing project for ZenStack.").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(initAction);
971
- program.command("check").description("Check a ZModel schema for syntax or semantic errors.").addOption(schemaOption).addOption(noVersionCheckOption).action(checkAction);
1103
+ migrateCommand.command("dev").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("-n, --name <name>", "migration name")).addOption(new Option("--create-only", "only create migration, do not apply")).addOption(migrationsOption).description("Create a migration from changes in schema and apply it to the database").action((options) => migrateAction("dev", options));
1104
+ migrateCommand.command("reset").addOption(schemaOption).addOption(new Option("--force", "skip the confirmation prompt")).addOption(migrationsOption).addOption(new Option("--skip-seed", "skip seeding the database after reset")).addOption(noVersionCheckOption).description("Reset your database and apply all migrations, all data will be lost").addHelpText("after", "\nIf there is a seed script defined in package.json, it will be run after the reset. Use --skip-seed to skip it.").action((options) => migrateAction("reset", options));
1105
+ migrateCommand.command("deploy").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).description("Deploy your pending migrations to your production/staging database").action((options) => migrateAction("deploy", options));
1106
+ migrateCommand.command("status").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).description("Check the status of your database migrations").action((options) => migrateAction("status", options));
1107
+ migrateCommand.command("resolve").addOption(schemaOption).addOption(noVersionCheckOption).addOption(migrationsOption).addOption(new Option("--applied <migration>", "record a specific migration as applied")).addOption(new Option("--rolled-back <migration>", "record a specific migration as rolled back")).description("Resolve issues with database migrations in deployment databases").action((options) => migrateAction("resolve", options));
1108
+ const dbCommand = program.command("db").description("Manage your database schema during development");
1109
+ dbCommand.command("push").description("Push the state from your schema to your database").addOption(schemaOption).addOption(noVersionCheckOption).addOption(new Option("--accept-data-loss", "ignore data loss warnings")).addOption(new Option("--force-reset", "force a reset of the database before push")).action((options) => dbAction("push", options));
1110
+ dbCommand.command("seed").description("Seed the database").allowExcessArguments(true).addHelpText("after", `
1111
+ Seed script is configured under the "zenstack.seed" field in package.json.
1112
+ E.g.:
1113
+ {
1114
+ "zenstack": {
1115
+ "seed": "ts-node ./zenstack/seed.ts"
1116
+ }
1117
+ }
1118
+
1119
+ Arguments following -- are passed to the seed script. E.g.: "zen db seed -- --users 10"`).addOption(noVersionCheckOption).action((options, command) => seedAction(options, command.args));
1120
+ program.command("info").description("Get information of installed ZenStack packages").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(infoAction);
1121
+ program.command("init").description("Initialize an existing project for ZenStack").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(initAction);
1122
+ program.command("check").description("Check a ZModel schema for syntax or semantic errors").addOption(schemaOption).addOption(noVersionCheckOption).action(checkAction);
1123
+ program.command("format").description("Format a ZModel schema file").addOption(schemaOption).addOption(noVersionCheckOption).action(formatAction);
1124
+ program.addHelpCommand("help [command]", "Display help for a command");
972
1125
  program.hook("preAction", async (_thisCommand, actionCommand) => {
973
1126
  if (actionCommand.getOptionValue("versionCheck") !== false) {
974
1127
  await checkNewVersion();
@@ -989,10 +1142,10 @@ async function main() {
989
1142
  if (e instanceof CommanderError) {
990
1143
  exitCode = e.exitCode;
991
1144
  } else if (e instanceof CliError) {
992
- console.error(colors7.red(e.message));
1145
+ console.error(colors9.red(e.message));
993
1146
  exitCode = 1;
994
1147
  } else {
995
- console.error(colors7.red(`Unhandled error: ${e}`));
1148
+ console.error(colors9.red(`Unhandled error: ${e}`));
996
1149
  exitCode = 1;
997
1150
  }
998
1151
  }