@donotdev/cli 0.2.2 → 0.3.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.
Files changed (64) hide show
  1. package/dependencies-matrix.json +44 -42
  2. package/dist/bin/commands/agent-setup.js +135 -67
  3. package/dist/bin/commands/build.js +352 -234
  4. package/dist/bin/commands/bump.js +385 -257
  5. package/dist/bin/commands/cacheout.js +59 -49
  6. package/dist/bin/commands/coach.js +80 -50
  7. package/dist/bin/commands/create-app.js +501 -228
  8. package/dist/bin/commands/create-project.js +377 -241
  9. package/dist/bin/commands/db-check.js +192804 -0
  10. package/dist/bin/commands/db.js +1889 -1805
  11. package/dist/bin/commands/deploy.js +476 -287
  12. package/dist/bin/commands/dev.js +139 -108
  13. package/dist/bin/commands/doctor.js +91 -57
  14. package/dist/bin/commands/emu.js +196 -154
  15. package/dist/bin/commands/format.js +83 -50
  16. package/dist/bin/commands/get-demo.js +422 -197
  17. package/dist/bin/commands/make-admin.js +835 -713
  18. package/dist/bin/commands/preview.js +139 -108
  19. package/dist/bin/commands/seed.js +2186 -2044
  20. package/dist/bin/commands/setup-cicd.js +258 -204
  21. package/dist/bin/commands/setup.js +890 -339
  22. package/dist/bin/commands/staging.js +476 -287
  23. package/dist/bin/commands/sync-secrets.js +472 -141
  24. package/dist/bin/commands/type-check.js +163 -119
  25. package/dist/bin/commands/wai.js +53 -46
  26. package/dist/bin/dndev.js +32 -7
  27. package/dist/bin/donotdev.js +18 -8
  28. package/dist/index.js +654 -375
  29. package/package.json +2 -2
  30. package/templates/app-demo/index.html.example +1 -1
  31. package/templates/app-dndev/index.html.example +1 -1
  32. package/templates/app-dndev/src/globals.css.example +1 -1
  33. package/templates/app-dndev/src/pages/legal/LegalNoticePage.tsx.example +1 -1
  34. package/templates/app-dndev/src/pages/legal/PrivacyPage.tsx.example +1 -1
  35. package/templates/app-dndev/src/pages/legal/TermsPage.tsx.example +1 -1
  36. package/templates/app-next/src/app/AppDocument.tsx.example +58 -0
  37. package/templates/app-next/src/app/ClientLayout.tsx.example +6 -2
  38. package/templates/app-next/src/globals.css.example +1 -1
  39. package/templates/app-next/src/pages/legal/LegalNoticePage.tsx.example +1 -1
  40. package/templates/app-next/src/pages/legal/PrivacyPage.tsx.example +1 -1
  41. package/templates/app-next/src/pages/legal/TermsPage.tsx.example +1 -1
  42. package/templates/app-vite/csp.example.json +1 -1
  43. package/templates/app-vite/index.html.example +1 -1
  44. package/templates/app-vite/src/globals.css.example +1 -1
  45. package/templates/app-vite/src/pages/FormPageExample.tsx.example +21 -16
  46. package/templates/app-vite/src/pages/legal/LegalNoticePage.tsx.example +1 -1
  47. package/templates/app-vite/src/pages/legal/PrivacyPage.tsx.example +1 -1
  48. package/templates/app-vite/src/pages/legal/TermsPage.tsx.example +1 -1
  49. package/templates/deploy-config/vercel.json.example +2 -2
  50. package/templates/functions-supabase/supabase/migrations/20250101000006_crud_bulk_status_guard.sql +258 -0
  51. package/templates/functions-supabase/supabase/migrations/20250101000007_rate_limit_check.sql +76 -0
  52. package/templates/overlay-supabase/src/config/providers.nextjs.ts.example +37 -0
  53. package/templates/root-consumer/.claude/hooks/guard-bash.sh.example +3 -3
  54. package/templates/root-consumer/.claude/hooks/guard-write.sh.example +5 -1
  55. package/templates/root-consumer/.claude/hooks/typecheck-stop.sh.example +2 -2
  56. package/templates/root-consumer/.claude/rules/definition-of-done.md.example +2 -2
  57. package/templates/root-consumer/.claude/rules/framework.md.example +1 -1
  58. package/templates/root-consumer/.claude/skills/build/SKILL.md.example +1 -1
  59. package/templates/root-consumer/.claude/skills/polish/SKILL.md.example +1 -1
  60. package/templates/root-consumer/.gitignore.example +7 -1
  61. package/templates/root-consumer/AGENTS.md.example +25 -2
  62. package/templates/root-consumer/README.md.example +1 -1
  63. package/templates/app-next/src/app/layout.tsx.example +0 -80
  64. package/templates/app-next/src/app/not-found.tsx.example +0 -40
@@ -143,7 +143,7 @@ var init_dist = __esm({
143
143
  if (index >= length) {
144
144
  break outer;
145
145
  }
146
- for (let i2 = 0, l2 = PARSE_BLOCKS.length; i2 < l2; i2++) {
146
+ for (let i2 = 0, l = PARSE_BLOCKS.length; i2 < l; i2++) {
147
147
  const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i2];
148
148
  BLOCK_RE.lastIndex = index;
149
149
  if (BLOCK_RE.test(input)) {
@@ -409,25 +409,29 @@ var init_main = __esm({
409
409
  }
410
410
  });
411
411
 
412
- // node_modules/.bun/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
413
- var require_src = __commonJS({
414
- "node_modules/.bun/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
415
- "use strict";
412
+ // node_modules/.bun/sisteransi@2.0.0/node_modules/sisteransi/dist/index.js
413
+ var ESC2, CSI2, cursor, erase, clear;
414
+ var init_dist3 = __esm({
415
+ "node_modules/.bun/sisteransi@2.0.0/node_modules/sisteransi/dist/index.js"() {
416
416
  init_utils2();
417
- var ESC2 = "\x1B";
418
- var CSI2 = `${ESC2}[`;
419
- var beep = "\x07";
420
- var cursor3 = {
421
- to(x, y2) {
422
- if (!y2) return `${CSI2}${x + 1}G`;
423
- return `${CSI2}${y2 + 1};${x + 1}H`;
417
+ ESC2 = "\x1B";
418
+ CSI2 = `${ESC2}[`;
419
+ cursor = {
420
+ to(x, y) {
421
+ if (!y)
422
+ return `${CSI2}${x + 1}G`;
423
+ return `${CSI2}${y + 1};${x + 1}H`;
424
424
  },
425
- move(x, y2) {
425
+ move(x, y) {
426
426
  let ret = "";
427
- if (x < 0) ret += `${CSI2}${-x}D`;
428
- else if (x > 0) ret += `${CSI2}${x}C`;
429
- if (y2 < 0) ret += `${CSI2}${-y2}A`;
430
- else if (y2 > 0) ret += `${CSI2}${y2}B`;
427
+ if (x < 0)
428
+ ret += `${CSI2}${-x}D`;
429
+ else if (x > 0)
430
+ ret += `${CSI2}${x}C`;
431
+ if (y < 0)
432
+ ret += `${CSI2}${-y}A`;
433
+ else if (y > 0)
434
+ ret += `${CSI2}${y}B`;
431
435
  return ret;
432
436
  },
433
437
  up: (count = 1) => `${CSI2}${count}A`,
@@ -442,11 +446,7 @@ var require_src = __commonJS({
442
446
  save: `${ESC2}7`,
443
447
  restore: `${ESC2}8`
444
448
  };
445
- var scroll = {
446
- up: (count = 1) => `${CSI2}S`.repeat(count),
447
- down: (count = 1) => `${CSI2}T`.repeat(count)
448
- };
449
- var erase3 = {
449
+ erase = {
450
450
  screen: `${CSI2}2J`,
451
451
  up: (count = 1) => `${CSI2}1J`.repeat(count),
452
452
  down: (count = 1) => `${CSI2}J`.repeat(count),
@@ -454,29 +454,31 @@ var require_src = __commonJS({
454
454
  lineEnd: `${CSI2}K`,
455
455
  lineStart: `${CSI2}1K`,
456
456
  lines(count) {
457
- let clear = "";
457
+ let clear2 = "";
458
458
  for (let i2 = 0; i2 < count; i2++)
459
- clear += this.line + (i2 < count - 1 ? cursor3.up() : "");
459
+ clear2 += this.line + (i2 < count - 1 ? cursor.up() : "");
460
460
  if (count)
461
- clear += cursor3.left;
462
- return clear;
461
+ clear2 += cursor.left;
462
+ return clear2;
463
463
  }
464
464
  };
465
- module.exports = { cursor: cursor3, scroll, erase: erase3, beep };
465
+ clear = {
466
+ screen: `${ESC2}c`
467
+ };
466
468
  }
467
469
  });
468
470
 
469
- // node_modules/.bun/@clack+core@1.5.1/node_modules/@clack/core/dist/index.mjs
471
+ // node_modules/.bun/@clack+core@1.6.0/node_modules/@clack/core/dist/index.mjs
470
472
  import { styleText } from "node:util";
471
473
  import { stdout, stdin } from "node:process";
472
- import * as l from "node:readline";
473
- import l__default from "node:readline";
474
+ import * as f$1 from "node:readline";
475
+ import f__default from "node:readline";
474
476
  import { ReadStream } from "node:tty";
475
- function findCursor(s, o, l2) {
476
- if (!l2.some((r2) => !r2.disabled))
477
- return s;
478
- const t2 = s + o, n3 = Math.max(l2.length - 1, 0), e = t2 < 0 ? n3 : t2 > n3 ? 0 : t2;
479
- return l2[e]?.disabled ? findCursor(e, o < 0 ? -1 : 1, l2) : e;
477
+ function findCursor(o, s, l) {
478
+ if (!l.some((r2) => !r2.disabled))
479
+ return o;
480
+ const t2 = o + s, n3 = Math.max(l.length - 1, 0), e = t2 < 0 ? n3 : t2 > n3 ? 0 : t2;
481
+ return l[e]?.disabled ? findCursor(e, s < 0 ? -1 : 1, l) : e;
480
482
  }
481
483
  function isAccessible(n3) {
482
484
  if (n3 !== void 0) return n3;
@@ -519,40 +521,40 @@ function block({
519
521
  overwrite: o = true,
520
522
  hideCursor: n3 = true
521
523
  } = {}) {
522
- const s = l.createInterface({
524
+ const s = f$1.createInterface({
523
525
  input: e,
524
526
  output: r2,
525
527
  prompt: "",
526
528
  tabSize: 1
527
529
  });
528
- l.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);
529
- const t2 = (f, { name: a2, sequence: w }) => {
530
- const c2 = String(f);
531
- if (isActionKey([c2, a2, w], "cancel")) {
532
- n3 && r2.write(import_sisteransi.cursor.show), process.exit(0);
530
+ f$1.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);
531
+ const t2 = (l, { name: i2, sequence: p }) => {
532
+ const w = String(l);
533
+ if (isActionKey([w, i2, p], "cancel")) {
534
+ n3 && r2.write(cursor.show), process.exit(0);
533
535
  return;
534
536
  }
535
537
  if (!o) return;
536
- const i2 = a2 === "return" ? 0 : -1, m = a2 === "return" ? -1 : 0;
537
- l.moveCursor(r2, i2, m, () => {
538
- l.clearLine(r2, 1, () => {
538
+ const c3 = i2 === "return" ? 0 : -1, a2 = i2 === "return" ? -1 : 0;
539
+ f$1.moveCursor(r2, c3, a2, () => {
540
+ f$1.clearLine(r2, 1, () => {
539
541
  e.once("keypress", t2);
540
542
  });
541
543
  });
542
544
  };
543
- return n3 && r2.write(import_sisteransi.cursor.hide), e.once("keypress", t2), () => {
544
- e.off("keypress", t2), n3 && r2.write(import_sisteransi.cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
545
+ return n3 && r2.write(cursor.hide), e.once("keypress", t2), () => {
546
+ e.off("keypress", t2), n3 && r2.write(cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
545
547
  };
546
548
  }
547
549
  function wrapTextWithPrefix(e, r2, o, n3 = o, s = o, t2) {
548
- const f = getColumns(e ?? stdout);
549
- return wrapAnsi(r2, f - o.length, {
550
+ const l = getColumns(e ?? stdout), i2 = dist_default2(o);
551
+ return wrapAnsi(r2, l - i2, {
550
552
  hard: true,
551
553
  trim: false
552
554
  }).split(`
553
- `).map((c2, i2, m) => {
554
- const d = t2 ? t2(c2, i2) : c2;
555
- return i2 === 0 ? `${n3}${d}` : i2 === m.length - 1 ? `${s}${d}` : `${o}${d}`;
555
+ `).map((c3, a2, g) => {
556
+ const m = t2 ? t2(c3, a2) : c3;
557
+ return a2 === 0 ? `${n3}${m}` : a2 === g.length - 1 ? `${s}${m}` : `${o}${m}`;
556
558
  }).join(`
557
559
  `);
558
560
  }
@@ -563,12 +565,13 @@ function runValidation(e, a2) {
563
565
  }
564
566
  return e(a2);
565
567
  }
566
- var import_sisteransi, a$1, t, settings, R, CANCEL_SYMBOL, getColumns, getRows, y, r, n$1, n2;
567
- var init_dist3 = __esm({
568
- "node_modules/.bun/@clack+core@1.5.1/node_modules/@clack/core/dist/index.mjs"() {
568
+ var a$1, t, settings, R, CANCEL_SYMBOL, getColumns, getRows, C$1, r, n$1, n2;
569
+ var init_dist4 = __esm({
570
+ "node_modules/.bun/@clack+core@1.6.0/node_modules/@clack/core/dist/index.mjs"() {
569
571
  init_utils2();
570
572
  init_main();
571
- import_sisteransi = __toESM(require_src(), 1);
573
+ init_dist3();
574
+ init_dist2();
572
575
  a$1 = ["up", "down", "left", "right", "space", "enter", "cancel"];
573
576
  t = [
574
577
  "January",
@@ -617,7 +620,7 @@ var init_dist3 = __esm({
617
620
  CANCEL_SYMBOL = /* @__PURE__ */ Symbol("clack:cancel");
618
621
  getColumns = (e) => "columns" in e && typeof e.columns == "number" ? e.columns : 80;
619
622
  getRows = (e) => "rows" in e && typeof e.rows == "number" ? e.rows : 20;
620
- y = class {
623
+ C$1 = class C {
621
624
  input;
622
625
  output;
623
626
  _abortSignal;
@@ -699,16 +702,16 @@ var init_dist3 = __esm({
699
702
  { once: true }
700
703
  );
701
704
  }
702
- this.rl = l__default.createInterface({
705
+ this.rl = f__default.createInterface({
703
706
  input: this.input,
704
707
  tabSize: 2,
705
708
  prompt: "",
706
709
  escapeCodeTimeout: 50,
707
710
  terminal: true
708
711
  }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), setRawMode(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
709
- this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(this.value);
712
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(this.value);
710
713
  }), this.once("cancel", () => {
711
- this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(CANCEL_SYMBOL);
714
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(CANCEL_SYMBOL);
712
715
  });
713
716
  });
714
717
  }
@@ -745,18 +748,18 @@ var init_dist3 = __esm({
745
748
  `), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
746
749
  }
747
750
  restoreCursor() {
748
- const t2 = wrapAnsi(this._prevFrame, process.stdout.columns, { hard: true, trim: false }).split(`
751
+ const t2 = wrapAnsi(this._prevFrame, getColumns(this.output), { hard: true, trim: false }).split(`
749
752
  `).length - 1;
750
- this.output.write(import_sisteransi.cursor.move(-999, t2 * -1));
753
+ this.output.write(cursor.move(-999, t2 * -1));
751
754
  }
752
755
  render() {
753
- const t2 = wrapAnsi(this._render(this) ?? "", process.stdout.columns, {
756
+ const t2 = wrapAnsi(this._render(this) ?? "", getColumns(this.output), {
754
757
  hard: true,
755
758
  trim: false
756
759
  });
757
760
  if (t2 !== this._prevFrame) {
758
761
  if (this.state === "initial")
759
- this.output.write(import_sisteransi.cursor.hide);
762
+ this.output.write(cursor.hide);
760
763
  else {
761
764
  const e = diffLines(this._prevFrame, t2), i2 = getRows(this.output);
762
765
  if (this.restoreCursor(), e) {
@@ -767,33 +770,33 @@ var init_dist3 = __esm({
767
770
  return;
768
771
  }
769
772
  if (e.lines.length === 1) {
770
- this.output.write(import_sisteransi.cursor.move(0, n3 - r2)), this.output.write(import_sisteransi.erase.lines(1));
773
+ this.output.write(cursor.move(0, n3 - r2)), this.output.write(erase.lines(1));
771
774
  const o = t2.split(`
772
775
  `);
773
- this.output.write(o[n3]), this._prevFrame = t2, this.output.write(import_sisteransi.cursor.move(0, o.length - n3 - 1));
776
+ this.output.write(o[n3]), this._prevFrame = t2, this.output.write(cursor.move(0, o.length - n3 - 1));
774
777
  return;
775
778
  } else if (e.lines.length > 1) {
776
779
  if (s < r2)
777
780
  n3 = s;
778
781
  else {
779
782
  const h2 = n3 - r2;
780
- h2 > 0 && this.output.write(import_sisteransi.cursor.move(0, h2));
783
+ h2 > 0 && this.output.write(cursor.move(0, h2));
781
784
  }
782
- this.output.write(import_sisteransi.erase.down());
783
- const f = t2.split(`
785
+ this.output.write(erase.down());
786
+ const m = t2.split(`
784
787
  `).slice(n3);
785
- this.output.write(f.join(`
788
+ this.output.write(m.join(`
786
789
  `)), this._prevFrame = t2;
787
790
  return;
788
791
  }
789
792
  }
790
- this.output.write(import_sisteransi.erase.down());
793
+ this.output.write(erase.down());
791
794
  }
792
795
  this.output.write(t2), this.state === "initial" && (this.state = "active"), this._prevFrame = t2;
793
796
  }
794
797
  }
795
798
  };
796
- r = class extends y {
799
+ r = class extends C$1 {
797
800
  get cursor() {
798
801
  return this.value ? 0 : 1;
799
802
  }
@@ -804,13 +807,13 @@ var init_dist3 = __esm({
804
807
  super(t2, false), this.value = !!t2.initialValue, this.on("userInput", () => {
805
808
  this.value = this._value;
806
809
  }), this.on("confirm", (i2) => {
807
- this.output.write(import_sisteransi.cursor.move(0, -1)), this.value = i2, this.state = "submit", this.close();
810
+ this.output.write(cursor.move(0, -1)), this.value = i2, this.state = "submit", this.close();
808
811
  }), this.on("cursor", () => {
809
812
  this.value = !this.value;
810
813
  });
811
814
  }
812
815
  };
813
- n$1 = class n extends y {
816
+ n$1 = class n extends C$1 {
814
817
  options;
815
818
  cursor = 0;
816
819
  get _selectedValue() {
@@ -838,7 +841,7 @@ var init_dist3 = __esm({
838
841
  });
839
842
  }
840
843
  };
841
- n2 = class extends y {
844
+ n2 = class extends C$1 {
842
845
  get userInputWithCursor() {
843
846
  if (this.state === "submit")
844
847
  return this.userInput;
@@ -865,7 +868,7 @@ var init_dist3 = __esm({
865
868
  }
866
869
  });
867
870
 
868
- // node_modules/.bun/@clack+prompts@1.8.1/node_modules/@clack/prompts/dist/index.mjs
871
+ // node_modules/.bun/@clack+prompts@1.9.0/node_modules/@clack/prompts/dist/index.mjs
869
872
  import { styleText as styleText2, stripVTControlCharacters } from "node:util";
870
873
  import process$1 from "node:process";
871
874
  import { existsSync, lstatSync, readdirSync } from "node:fs";
@@ -876,22 +879,23 @@ function isUnicodeSupported() {
876
879
  }
877
880
  return Boolean(process$1.env.CI) || Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
878
881
  }
879
- function formatInstructionFooter(o, e) {
880
- const r2 = [`${e ? `${styleText2("cyan", S_BAR)} ` : ""}${o.join(" \u2022 ")}`];
881
- return e && r2.push(styleText2("cyan", S_BAR_END)), r2;
882
+ function formatInstructionFooter(e, o, r2) {
883
+ const s = r2 ? `${styleText2("cyan", S_BAR)} ` : "", n3 = wrapTextWithPrefix(e, o.join(" \u2022 "), s).split(`
884
+ `);
885
+ return r2 && n3.push(styleText2("cyan", S_BAR_END)), n3;
882
886
  }
883
- var import_sisteransi2, unicode, isCI, unicodeOr, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, S_BAR_START, S_BAR, S_BAR_END, S_BAR_START_RIGHT, S_BAR_END_RIGHT, S_RADIO_ACTIVE, S_RADIO_INACTIVE, S_CHECKBOX_ACTIVE, S_CHECKBOX_SELECTED, S_CHECKBOX_INACTIVE, S_PASSWORD_MASK, S_BAR_H, S_CORNER_TOP_RIGHT, S_CONNECT_LEFT, S_CORNER_BOTTOM_RIGHT, S_CORNER_BOTTOM_LEFT, S_CORNER_TOP_LEFT, S_INFO, S_SUCCESS, S_WARN, S_ERROR, symbol, symbolBar, I, limitOptions, confirm, MULTISELECT_INSTRUCTIONS, log, cancel, intro, outro, W$1, C, note, W, spinner, u2, SELECT_INSTRUCTIONS, c, select, i, text;
884
- var init_dist4 = __esm({
885
- "node_modules/.bun/@clack+prompts@1.8.1/node_modules/@clack/prompts/dist/index.mjs"() {
887
+ var unicode, isCI, unicodeOr, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, S_BAR_START, S_BAR, S_BAR_END, S_BAR_START_RIGHT, S_BAR_END_RIGHT, S_RADIO_ACTIVE, S_RADIO_INACTIVE, S_CHECKBOX_ACTIVE, S_CHECKBOX_SELECTED, S_CHECKBOX_INACTIVE, S_PASSWORD_MASK, S_BAR_H, S_CORNER_TOP_RIGHT, S_CONNECT_LEFT, S_CORNER_BOTTOM_RIGHT, S_CORNER_BOTTOM_LEFT, S_CORNER_TOP_LEFT, S_INFO, S_SUCCESS, S_WARN, S_ERROR, symbol, symbolBar, E$1, limitOptions, confirm, MULTISELECT_INSTRUCTIONS, log, cancel, intro, outro, W, C2, note, Y, Z, spinner, u2, SELECT_INSTRUCTIONS, c2, select, i, text;
888
+ var init_dist5 = __esm({
889
+ "node_modules/.bun/@clack+prompts@1.9.0/node_modules/@clack/prompts/dist/index.mjs"() {
886
890
  init_utils2();
887
- init_dist3();
888
- init_dist3();
891
+ init_dist4();
892
+ init_dist4();
889
893
  init_main();
890
894
  init_dist2();
891
- import_sisteransi2 = __toESM(require_src(), 1);
895
+ init_dist3();
892
896
  unicode = isUnicodeSupported();
893
897
  isCI = () => process.env.CI === "true";
894
- unicodeOr = (o, e) => unicode ? o : e;
898
+ unicodeOr = (e, o) => unicode ? e : o;
895
899
  S_STEP_ACTIVE = unicodeOr("\u25C6", "*");
896
900
  S_STEP_CANCEL = unicodeOr("\u25A0", "x");
897
901
  S_STEP_ERROR = unicodeOr("\u25B2", "x");
@@ -917,8 +921,8 @@ var init_dist4 = __esm({
917
921
  S_SUCCESS = unicodeOr("\u25C6", "*");
918
922
  S_WARN = unicodeOr("\u25B2", "!");
919
923
  S_ERROR = unicodeOr("\u25A0", "x");
920
- symbol = (o) => {
921
- switch (o) {
924
+ symbol = (e) => {
925
+ switch (e) {
922
926
  case "initial":
923
927
  case "active":
924
928
  return styleText2("cyan", S_STEP_ACTIVE);
@@ -932,8 +936,8 @@ var init_dist4 = __esm({
932
936
  return styleText2("dim", S_STEP_ACTIVE);
933
937
  }
934
938
  };
935
- symbolBar = (o) => {
936
- switch (o) {
939
+ symbolBar = (e) => {
940
+ switch (e) {
937
941
  case "initial":
938
942
  case "active":
939
943
  return styleText2("cyan", S_BAR);
@@ -945,45 +949,45 @@ var init_dist4 = __esm({
945
949
  return styleText2("green", S_BAR);
946
950
  }
947
951
  };
948
- I = (l2, e, w, p, b, C2 = false) => {
952
+ E$1 = (l, e, w, p, b, C3 = false) => {
949
953
  let r2 = e, O = 0;
950
- if (C2)
954
+ if (C3)
951
955
  for (let i2 = p - 1; i2 >= w; i2--) {
952
- const m = l2[i2];
956
+ const m = l[i2];
953
957
  if (m && (r2 -= m.length), O++, r2 <= b) break;
954
958
  }
955
959
  else
956
960
  for (let i2 = w; i2 < p; i2++) {
957
- const m = l2[i2];
961
+ const m = l[i2];
958
962
  if (m && (r2 -= m.length), O++, r2 <= b) break;
959
963
  }
960
964
  return { lineCount: r2, removals: O };
961
965
  };
962
966
  limitOptions = ({
963
- cursor: l2,
967
+ cursor: l,
964
968
  options: e,
965
969
  style: w,
966
970
  output: p = process.stdout,
967
971
  maxItems: b = Number.POSITIVE_INFINITY,
968
- columnPadding: C2 = 0,
972
+ columnPadding: C3 = 0,
969
973
  rowPadding: r2 = 4
970
974
  }) => {
971
- const i2 = getColumns(p) - C2, m = getRows(p), M = styleText2("dim", "..."), v = Math.max(m - r2, 0), a2 = Math.max(Math.min(b, v), 5);
975
+ const i2 = getColumns(p) - C3, m = getRows(p), M = styleText2("dim", "..."), v = Math.max(m - r2, 0), a2 = Math.max(Math.min(b, v), 5);
972
976
  let f = 0;
973
- l2 >= a2 - 3 && (f = Math.max(
974
- Math.min(l2 - a2 + 3, e.length - a2),
977
+ l >= a2 - 3 && (f = Math.max(
978
+ Math.min(l - a2 + 3, e.length - a2),
975
979
  0
976
980
  ));
977
- let d = a2 < e.length && f > 0, c2 = a2 < e.length && f + a2 < e.length;
978
- const W2 = Math.min(
981
+ let d = a2 < e.length && f > 0, c3 = a2 < e.length && f + a2 < e.length;
982
+ const I = Math.min(
979
983
  f + a2,
980
984
  e.length
981
985
  ), s = [];
982
986
  let g = 0;
983
- d && g++, c2 && g++;
984
- const T = f + (d ? 1 : 0), y2 = W2 - (c2 ? 1 : 0);
985
- for (let t2 = T; t2 < y2; t2++) {
986
- const n3 = e[t2], o = n3 ? w(n3, t2 === l2) : "", h2 = wrapAnsi(o, i2, {
987
+ d && g++, c3 && g++;
988
+ const T = f + (d ? 1 : 0), W2 = I - (c3 ? 1 : 0);
989
+ for (let t2 = T; t2 < W2; t2++) {
990
+ const n3 = e[t2], o = n3 !== void 0 ? w(n3, t2 === l) : "", h2 = wrapAnsi(o, i2, {
987
991
  hard: true,
988
992
  trim: false
989
993
  }).split(`
@@ -992,9 +996,9 @@ var init_dist4 = __esm({
992
996
  }
993
997
  if (g > v) {
994
998
  let t2 = 0, n3 = 0, o = g;
995
- const h2 = l2 - T;
999
+ const h2 = l - T;
996
1000
  let u3 = v;
997
- const L = () => I(s, o, 0, h2, u3), E = () => I(
1001
+ const L = () => E$1(s, o, 0, h2, u3), y = () => E$1(
998
1002
  s,
999
1003
  o,
1000
1004
  h2 + 1,
@@ -1002,14 +1006,14 @@ var init_dist4 = __esm({
1002
1006
  u3,
1003
1007
  true
1004
1008
  );
1005
- d ? ({ lineCount: o, removals: t2 } = L(), o > u3 && (c2 || (u3 -= 1), { lineCount: o, removals: n3 } = E())) : (c2 || (u3 -= 1), { lineCount: o, removals: n3 } = E(), o > u3 && (u3 -= 1, { lineCount: o, removals: t2 } = L())), t2 > 0 && (d = true, s.splice(0, t2)), n3 > 0 && (c2 = true, s.splice(s.length - n3, n3));
1009
+ d ? ({ lineCount: o, removals: t2 } = L(), o > u3 && (c3 || (u3 -= 1), { lineCount: o, removals: n3 } = y())) : (c3 || (u3 -= 1), { lineCount: o, removals: n3 } = y(), o > u3 && (u3 -= 1, { lineCount: o, removals: t2 } = L())), t2 > 0 && (d = true, s.splice(0, t2)), n3 > 0 && (c3 = true, s.splice(s.length - n3, n3));
1006
1010
  }
1007
1011
  const x = [];
1008
1012
  d && x.push(M);
1009
1013
  for (const t2 of s)
1010
1014
  for (const n3 of t2)
1011
1015
  x.push(n3);
1012
- return c2 && x.push(M), x;
1016
+ return c3 && x.push(M), x;
1013
1017
  };
1014
1018
  confirm = (e) => {
1015
1019
  const a2 = e.active ?? "Yes", o = e.inactive ?? "No";
@@ -1021,22 +1025,22 @@ var init_dist4 = __esm({
1021
1025
  output: e.output,
1022
1026
  initialValue: e.initialValue ?? true,
1023
1027
  render() {
1024
- const i2 = e.withGuide ?? settings.withGuide, u3 = `${symbol(this.state)} `, l2 = i2 ? `${styleText2("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(
1028
+ const i2 = e.withGuide ?? settings.withGuide, u3 = `${symbol(this.state)} `, l = i2 ? `${styleText2("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(
1025
1029
  e.output,
1026
1030
  e.message,
1027
- l2,
1031
+ l,
1028
1032
  u3
1029
1033
  ), s = `${i2 ? `${styleText2("gray", S_BAR)}
1030
1034
  ` : ""}${f}
1031
- `, c2 = this.value ? a2 : o;
1035
+ `, c3 = this.value ? a2 : o;
1032
1036
  switch (this.state) {
1033
1037
  case "submit": {
1034
1038
  const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
1035
- return `${s}${r2}${styleText2("dim", c2)}`;
1039
+ return `${s}${r2}${styleText2("dim", c3)}`;
1036
1040
  }
1037
1041
  case "cancel": {
1038
1042
  const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
1039
- return `${s}${r2}${styleText2(["strikethrough", "dim"], c2)}${i2 ? `
1043
+ return `${s}${r2}${styleText2(["strikethrough", "dim"], c3)}${i2 ? `
1040
1044
  ${styleText2("gray", S_BAR)}` : ""}`;
1041
1045
  }
1042
1046
  default: {
@@ -1061,18 +1065,18 @@ ${g}
1061
1065
  symbol: e = styleText2("gray", S_BAR),
1062
1066
  secondarySymbol: r2 = styleText2("gray", S_BAR),
1063
1067
  output: m = process.stdout,
1064
- spacing: l2 = 1,
1065
- withGuide: c2
1068
+ spacing: l = 1,
1069
+ withGuide: c3
1066
1070
  } = {}) => {
1067
- const t2 = [], o = c2 ?? settings.withGuide, f = o ? r2 : "", O = o ? `${e} ` : "", u3 = o ? `${r2} ` : "";
1068
- for (let i2 = 0; i2 < l2; i2++)
1071
+ const t2 = [], o = c3 ?? settings.withGuide, f = o ? r2 : "", O = o ? `${e} ` : "", u3 = o ? `${r2} ` : "";
1072
+ for (let i2 = 0; i2 < l; i2++)
1069
1073
  t2.push(f);
1070
1074
  const g = Array.isArray(s) ? s : s.split(`
1071
1075
  `);
1072
1076
  if (g.length > 0) {
1073
- const [i2, ...y2] = g;
1077
+ const [i2, ...y] = g;
1074
1078
  i2.length > 0 ? t2.push(`${O}${i2}`) : t2.push(o ? e : "");
1075
- for (const p of y2)
1079
+ for (const p of y)
1076
1080
  p.length > 0 ? t2.push(`${u3}${p}`) : t2.push(o ? r2 : "");
1077
1081
  }
1078
1082
  m.write(`${t2.join(`
@@ -1117,18 +1121,18 @@ ${styleText2("gray", S_BAR_END)} ` : "";
1117
1121
 
1118
1122
  `);
1119
1123
  };
1120
- W$1 = (o) => o;
1121
- C = (o, e, s) => {
1124
+ W = (o) => o;
1125
+ C2 = (o, e, s) => {
1122
1126
  const a2 = {
1123
1127
  hard: true,
1124
1128
  trim: false
1125
1129
  }, i2 = wrapAnsi(o, e, a2).split(`
1126
- `), c2 = i2.reduce((n3, t2) => Math.max(dist_default2(t2), n3), 0), u3 = i2.map(s).reduce((n3, t2) => Math.max(dist_default2(t2), n3), 0), g = e - (u3 - c2);
1130
+ `), c3 = i2.reduce((n3, t2) => Math.max(dist_default2(t2), n3), 0), u3 = i2.map(s).reduce((n3, t2) => Math.max(dist_default2(t2), n3), 0), g = e - (u3 - c3);
1127
1131
  return wrapAnsi(o, g, a2);
1128
1132
  };
1129
1133
  note = (o = "", e = "", s) => {
1130
- const a2 = s?.output ?? process$1.stdout, i2 = s?.withGuide ?? settings.withGuide, c2 = s?.format ?? W$1, g = ["", ...C(o, getColumns(a2) - 6, c2).split(`
1131
- `).map(c2), ""], n3 = dist_default2(e), t2 = Math.max(
1134
+ const a2 = s?.output ?? process$1.stdout, i2 = s?.withGuide ?? settings.withGuide, c3 = s?.format ?? W, g = ["", ...C2(o, getColumns(a2) - 6, c3).split(`
1135
+ `).map(c3), ""], n3 = dist_default2(e), t2 = Math.max(
1132
1136
  g.reduce((m, F) => {
1133
1137
  const O = dist_default2(F);
1134
1138
  return O > m ? O : m;
@@ -1149,83 +1153,102 @@ ${styleText2("gray", l$1 + S_BAR_H.repeat(t2 + 2) + S_CORNER_BOTTOM_RIGHT)}
1149
1153
  `
1150
1154
  );
1151
1155
  };
1152
- W = (l2) => styleText2("magenta", l2);
1156
+ Y = 3e4;
1157
+ Z = (c3) => styleText2("magenta", c3);
1153
1158
  spinner = ({
1154
- indicator: l2 = "dots",
1155
- onCancel: h2,
1159
+ indicator: c3 = "dots",
1160
+ onCancel: b,
1156
1161
  output: n3 = process.stdout,
1157
- cancelMessage: G,
1158
- errorMessage: O,
1159
- frames: E = unicode ? ["\u25D2", "\u25D0", "\u25D3", "\u25D1"] : ["\u2022", "o", "O", "0"],
1160
- delay: F = unicode ? 80 : 120,
1161
- signal: m,
1162
- ...I2
1162
+ cancelMessage: _,
1163
+ errorMessage: C3,
1164
+ frames: M = unicode ? ["\u25D2", "\u25D0", "\u25D3", "\u25D1"] : ["\u2022", "o", "O", "0"],
1165
+ delay: O = unicode ? 80 : 120,
1166
+ signal: g,
1167
+ ...E
1163
1168
  } = {}) => {
1164
- const u3 = isCI();
1165
- let M, T, d = false, S = false, s = "", p, w = performance.now();
1166
- const x = getColumns(n3), k = I2?.styleFrame ?? W, g = (e) => {
1167
- const r2 = e > 1 ? O ?? settings.messages.error : G ?? settings.messages.cancel;
1168
- S = e === 1, d && (a2(r2, e), S && typeof h2 == "function" && h2());
1169
- }, f = () => g(2), i2 = () => g(1), A = () => {
1170
- process.on("uncaughtExceptionMonitor", f), process.on("unhandledRejection", f), process.on("SIGINT", i2), process.on("SIGTERM", i2), process.on("exit", g), m && m.addEventListener("abort", i2);
1171
- }, H = () => {
1172
- process.removeListener("uncaughtExceptionMonitor", f), process.removeListener("unhandledRejection", f), process.removeListener("SIGINT", i2), process.removeListener("SIGTERM", i2), process.removeListener("exit", g), m && m.removeEventListener("abort", i2);
1173
- }, y2 = () => {
1174
- if (p === void 0) return;
1169
+ const u3 = isCI(), h2 = isAccessible(E.accessible);
1170
+ let x, I, p = false, l = false, r2 = "", v, w = performance.now();
1171
+ const y = getColumns(n3), F = E?.styleFrame ?? Z, S = (e) => {
1172
+ const s = e > 1 ? C3 ?? settings.messages.error : _ ?? settings.messages.cancel;
1173
+ l = e === 1, p && (m(s, e), l && typeof b == "function" && b());
1174
+ }, $ = () => S(2), a2 = () => S(1), H = () => {
1175
+ process.on("uncaughtExceptionMonitor", $), process.on("unhandledRejection", $), process.on("SIGINT", a2), process.on("SIGTERM", a2), process.on("exit", S), g && g.addEventListener("abort", a2);
1176
+ }, B = () => {
1177
+ process.removeListener("uncaughtExceptionMonitor", $), process.removeListener("unhandledRejection", $), process.removeListener("SIGINT", a2), process.removeListener("SIGTERM", a2), process.removeListener("exit", S), g && g.removeEventListener("abort", a2);
1178
+ }, R2 = () => {
1179
+ if (v === void 0) return;
1175
1180
  u3 && n3.write(`
1176
1181
  `);
1177
- const r2 = wrapAnsi(p, x, {
1182
+ const s = wrapAnsi(v, y, {
1178
1183
  hard: true,
1179
1184
  trim: false
1180
1185
  }).split(`
1181
1186
  `);
1182
- r2.length > 1 && n3.write(import_sisteransi2.cursor.up(r2.length - 1)), n3.write(import_sisteransi2.cursor.to(0)), n3.write(import_sisteransi2.erase.down());
1183
- }, C2 = (e) => e.replace(/\.+$/, ""), _ = (e) => {
1184
- const r2 = (performance.now() - e) / 1e3, t2 = Math.floor(r2 / 60), o = Math.floor(r2 % 60);
1185
- return t2 > 0 ? `[${t2}m ${o}s]` : `[${o}s]`;
1186
- }, N = I2.withGuide ?? settings.withGuide, P = (e = "") => {
1187
- d = true, M = block({ output: n3 }), s = C2(e), w = performance.now(), N && n3.write(`${styleText2("gray", S_BAR)}
1187
+ s.length > 1 && n3.write(cursor.up(s.length - 1)), n3.write(cursor.to(0)), n3.write(erase.down());
1188
+ }, L = (e) => e.replace(/\.+$/, ""), T = (e) => {
1189
+ const s = (performance.now() - e) / 1e3, i2 = Math.floor(s / 60), t2 = Math.floor(s % 60);
1190
+ return i2 > 0 ? `[${i2}m ${t2}s]` : `[${t2}s]`;
1191
+ }, N = E.withGuide ?? settings.withGuide, P = (e = "") => {
1192
+ if (p = true, l = false, r2 = L(e), w = performance.now(), H(), h2) {
1193
+ r2 !== "" && n3.write(`${r2}
1194
+ `), I = setInterval(() => {
1195
+ n3.write(r2 === "" ? `still working
1196
+ ` : `still working: ${r2}
1197
+ `);
1198
+ }, Y);
1199
+ return;
1200
+ }
1201
+ x = block({ output: n3 }), N && n3.write(`${styleText2("gray", S_BAR)}
1188
1202
  `);
1189
- let r2 = 0, t2 = 0;
1190
- A(), T = setInterval(() => {
1191
- if (u3 && s === p)
1203
+ let s = 0, i2 = 0;
1204
+ I = setInterval(() => {
1205
+ if (u3 && r2 === v)
1192
1206
  return;
1193
- y2(), p = s;
1194
- const o = k(E[r2]);
1195
- let v;
1207
+ R2(), v = r2;
1208
+ const t2 = F(M[s]);
1209
+ let o;
1196
1210
  if (u3)
1197
- v = `${o} ${s}...`;
1198
- else if (l2 === "timer")
1199
- v = `${o} ${s} ${_(w)}`;
1211
+ o = `${t2} ${r2}...`;
1212
+ else if (c3 === "timer")
1213
+ o = `${t2} ${r2} ${T(w)}`;
1200
1214
  else {
1201
- const B = ".".repeat(Math.floor(t2)).slice(0, 3);
1202
- v = `${o} ${s}${B}`;
1215
+ const j = ".".repeat(Math.floor(i2)).slice(0, 3);
1216
+ o = `${t2} ${r2}${j}`;
1203
1217
  }
1204
- const j = wrapAnsi(v, x, {
1218
+ const D = wrapAnsi(o, y, {
1205
1219
  hard: true,
1206
1220
  trim: false
1207
1221
  });
1208
- n3.write(j), r2 = r2 + 1 < E.length ? r2 + 1 : 0, t2 = t2 < 4 ? t2 + 0.125 : 0;
1209
- }, F);
1210
- }, a2 = (e = "", r2 = 0, t2 = false) => {
1211
- if (!d) return;
1212
- d = false, clearInterval(T), y2();
1213
- const o = r2 === 0 ? styleText2("green", S_STEP_SUBMIT) : r2 === 1 ? styleText2("red", S_STEP_CANCEL) : styleText2("red", S_STEP_ERROR);
1214
- s = e ?? s, t2 || (l2 === "timer" ? n3.write(`${o} ${s} ${_(w)}
1215
- `) : n3.write(`${o} ${s}
1216
- `)), H(), M();
1222
+ n3.write(D), s = s + 1 < M.length ? s + 1 : 0, i2 = i2 < 4 ? i2 + 0.125 : 0;
1223
+ }, O);
1224
+ }, m = (e = "", s = 0, i2 = false) => {
1225
+ if (p) {
1226
+ if (p = false, l = s === 1, clearInterval(I), h2 || R2(), r2 = e ?? r2, !i2)
1227
+ if (h2) {
1228
+ const t2 = s === 1 ? _ ?? settings.messages.cancel : s === 2 ? C3 ?? settings.messages.error : "Done", o = r2 || t2;
1229
+ c3 === "timer" ? n3.write(`${o} ${T(w)}
1230
+ `) : n3.write(`${o}
1231
+ `);
1232
+ } else {
1233
+ const t2 = s === 0 ? styleText2("green", S_STEP_SUBMIT) : s === 1 ? styleText2("red", S_STEP_CANCEL) : styleText2("red", S_STEP_ERROR);
1234
+ c3 === "timer" ? n3.write(`${t2} ${r2} ${T(w)}
1235
+ `) : n3.write(`${t2} ${r2}
1236
+ `);
1237
+ }
1238
+ B(), x?.();
1239
+ }
1217
1240
  };
1218
1241
  return {
1219
1242
  start: P,
1220
- stop: (e = "") => a2(e, 0),
1243
+ stop: (e = "") => m(e, 0),
1221
1244
  message: (e = "") => {
1222
- s = C2(e ?? s);
1245
+ r2 = L(e ?? r2);
1223
1246
  },
1224
- cancel: (e = "") => a2(e, 1),
1225
- error: (e = "") => a2(e, 2),
1226
- clear: () => a2("", 0, true),
1247
+ cancel: (e = "") => m(e, 1),
1248
+ error: (e = "") => m(e, 2),
1249
+ clear: () => m("", 0, true),
1227
1250
  get isCancelled() {
1228
- return S;
1251
+ return l;
1229
1252
  }
1230
1253
  };
1231
1254
  };
@@ -1238,7 +1261,7 @@ ${styleText2("gray", l$1 + S_BAR_H.repeat(t2 + 2) + S_CORNER_BOTTOM_RIGHT)}
1238
1261
  `${styleText2("dim", "\u2191/\u2193")} to navigate`,
1239
1262
  `${styleText2("dim", "Enter:")} confirm`
1240
1263
  ];
1241
- c = (t2, o) => t2.includes(`
1264
+ c2 = (t2, o) => t2.includes(`
1242
1265
  `) ? t2.split(`
1243
1266
  `).map((d) => o(d)).join(`
1244
1267
  `) : o(t2);
@@ -1249,15 +1272,15 @@ ${styleText2("gray", l$1 + S_BAR_H.repeat(t2 + 2) + S_CORNER_BOTTOM_RIGHT)}
1249
1272
  const s = n3.label ?? String(n3.value);
1250
1273
  switch (m) {
1251
1274
  case "disabled":
1252
- return `${styleText2("gray", S_RADIO_INACTIVE)} ${c(s, (i2) => styleText2("gray", i2))}${n3.hint ? ` ${styleText2("dim", `(${n3.hint ?? "disabled"})`)}` : ""}`;
1275
+ return `${styleText2("gray", S_RADIO_INACTIVE)} ${c2(s, (i2) => styleText2("gray", i2))}${n3.hint ? ` ${styleText2("dim", `(${n3.hint ?? "disabled"})`)}` : ""}`;
1253
1276
  case "selected":
1254
- return `${c(s, (i2) => styleText2("dim", i2))}`;
1277
+ return `${c2(s, (i2) => styleText2("dim", i2))}`;
1255
1278
  case "active":
1256
1279
  return `${styleText2("green", S_RADIO_ACTIVE)} ${s}${n3.hint ? ` ${styleText2("dim", `(${n3.hint})`)}` : ""}`;
1257
1280
  case "cancelled":
1258
- return `${c(s, (i2) => styleText2(["strikethrough", "dim"], i2))}`;
1281
+ return `${c2(s, (i2) => styleText2(["strikethrough", "dim"], i2))}`;
1259
1282
  default:
1260
- return `${styleText2("dim", S_RADIO_INACTIVE)} ${c(s, (i2) => styleText2("dim", i2))}`;
1283
+ return `${styleText2("dim", S_RADIO_INACTIVE)} ${c2(s, (i2) => styleText2("dim", i2))}`;
1261
1284
  }
1262
1285
  }, d = t2.showInstructions ?? true;
1263
1286
  return new n$1({
@@ -1295,7 +1318,7 @@ ${styleText2("gray", S_BAR)}` : ""}`;
1295
1318
  }
1296
1319
  default: {
1297
1320
  const r2 = n3 ? `${styleText2("cyan", S_BAR)} ` : "", a2 = u3.split(`
1298
- `).length, p = d ? formatInstructionFooter(SELECT_INSTRUCTIONS, n3) : n3 ? [styleText2("cyan", S_BAR_END)] : [], f = p.join(`
1321
+ `).length, p = d ? formatInstructionFooter(t2.output, SELECT_INSTRUCTIONS, n3) : n3 ? [styleText2("cyan", S_BAR_END)] : [], f = p.join(`
1299
1322
  `), b = p.length + 1;
1300
1323
  return `${u3}${r2}${limitOptions({
1301
1324
  output: t2.output,
@@ -1324,7 +1347,7 @@ ${f}
1324
1347
  signal: t2.signal,
1325
1348
  input: t2.input,
1326
1349
  render() {
1327
- const r2 = t2?.withGuide ?? settings.withGuide, l2 = `${`${r2 ? `${styleText2("gray", S_BAR)}
1350
+ const r2 = t2?.withGuide ?? settings.withGuide, l = `${`${r2 ? `${styleText2("gray", S_BAR)}
1328
1351
  ` : ""}${symbol(this.state)} `}${t2.message}
1329
1352
  `, d = t2.placeholder && t2.placeholder.length > 0 ? (
1330
1353
  // biome-ignore lint/style/noNonNullAssertion: guarded by placeholder.length > 0
@@ -1332,30 +1355,30 @@ ${f}
1332
1355
  ) : styleText2(["inverse", "hidden"], "_"), o = this.userInput ? this.userInputWithCursor : d, s = this.value ?? "";
1333
1356
  switch (this.state) {
1334
1357
  case "validating": {
1335
- const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "", c2 = styleText2("dim", o), $ = styleText2("dim", "Validating...");
1336
- return `${l2}${n3}${c2}
1358
+ const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "", c3 = styleText2("dim", o), $ = styleText2("dim", "Validating...");
1359
+ return `${l}${n3}${c3}
1337
1360
  ${i2} ${$}
1338
1361
  `;
1339
1362
  }
1340
1363
  case "error": {
1341
- const n3 = this.error ? ` ${styleText2("yellow", this.error)}` : "", i2 = r2 ? `${styleText2("yellow", S_BAR)} ` : "", c2 = r2 ? styleText2("yellow", S_BAR_END) : "";
1342
- return `${l2.trim()}
1364
+ const n3 = this.error ? ` ${styleText2("yellow", this.error)}` : "", i2 = r2 ? `${styleText2("yellow", S_BAR)} ` : "", c3 = r2 ? styleText2("yellow", S_BAR_END) : "";
1365
+ return `${l.trim()}
1343
1366
  ${i2}${o}
1344
- ${c2}${n3}
1367
+ ${c3}${n3}
1345
1368
  `;
1346
1369
  }
1347
1370
  case "submit": {
1348
1371
  const n3 = s ? `${r2 ? " " : ""}${styleText2("dim", s)}` : "", i2 = r2 ? styleText2("gray", S_BAR) : "";
1349
- return `${l2}${i2}${n3}`;
1372
+ return `${l}${i2}${n3}`;
1350
1373
  }
1351
1374
  case "cancel": {
1352
1375
  const n3 = s ? ` ${styleText2(["strikethrough", "dim"], s)}` : "", i2 = r2 ? styleText2("gray", S_BAR) : "";
1353
- return `${l2}${i2}${n3}${s.trim() ? `
1376
+ return `${l}${i2}${n3}${s.trim() ? `
1354
1377
  ${i2}` : ""}`;
1355
1378
  }
1356
1379
  default: {
1357
1380
  const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "";
1358
- return `${l2}${n3}${o}
1381
+ return `${l}${n3}${o}
1359
1382
  ${i2}
1360
1383
  `;
1361
1384
  }
@@ -1411,8 +1434,8 @@ var init_cli_output = __esm({
1411
1434
  "packages/tooling/src/utils/cli-output.ts"() {
1412
1435
  "use strict";
1413
1436
  init_utils2();
1414
- init_dist4();
1415
- init_dist4();
1437
+ init_dist5();
1438
+ init_dist5();
1416
1439
  colors = {
1417
1440
  reset: "\x1B[0m",
1418
1441
  // Success (green)
@@ -1570,7 +1593,7 @@ var init_errors = __esm({
1570
1593
  * @param {DoNotDevErrorCode} code - Error code
1571
1594
  * @param {object} [options] - Additional error options
1572
1595
  * @param {Error} [options.originalError] - Original error if wrapping
1573
- * @param {Record<string, any>} [options.context] - Additional context data
1596
+ * @param {Record<string, unknown>} [options.context] - Additional context data
1574
1597
  * @param {boolean} [options.displayable=true] - Whether this error should be displayed to the user
1575
1598
  */
1576
1599
  constructor(message, code = DO_NOT_DEV_ERROR_CODES.UNKNOWN_ERROR, options) {
@@ -1600,7 +1623,7 @@ var init_errors = __esm({
1600
1623
  * @param {string} [context] - Additional context for the error
1601
1624
  * @param {DoNotDevErrorCode} [code='unknown-error'] - Error code
1602
1625
  * @param {object} [options] - Additional error options
1603
- * @param {Record<string, any>} [options.context] - Additional context data
1626
+ * @param {Record<string, unknown>} [options.context] - Additional context data
1604
1627
  * @param {boolean} [options.displayable=true] - Whether this error should be displayed to the user
1605
1628
  * @returns {DoNotDevError} New DoNotDev error wrapping the original
1606
1629
  */
@@ -7651,6 +7674,9 @@ import {
7651
7674
  extname
7652
7675
  } from "node:path";
7653
7676
  import { fileURLToPath } from "node:url";
7677
+ function isEexistError(error2) {
7678
+ return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "EEXIST";
7679
+ }
7654
7680
  function safeExecuteAsync2(fn, message) {
7655
7681
  return fn().catch((error2) => {
7656
7682
  throw new Error(
@@ -8022,7 +8048,7 @@ var init_PathResolver = __esm({
8022
8048
  try {
8023
8049
  await fs.promises.mkdir(dir, { recursive: true });
8024
8050
  } catch (error2) {
8025
- if (error2?.code !== "EEXIST") throw error2;
8051
+ if (!isEexistError(error2)) throw error2;
8026
8052
  }
8027
8053
  const detectedFormat = this._detectFormat(filePath, format);
8028
8054
  let writeContent;
@@ -8084,7 +8110,7 @@ var init_PathResolver = __esm({
8084
8110
  try {
8085
8111
  fs.mkdirSync(dir, { recursive: true });
8086
8112
  } catch (error2) {
8087
- if (error2?.code !== "EEXIST") throw error2;
8113
+ if (!isEexistError(error2)) throw error2;
8088
8114
  }
8089
8115
  const detectedFormat = this._detectFormat(filePath, format);
8090
8116
  let writeContent;
@@ -8141,7 +8167,7 @@ var init_PathResolver = __esm({
8141
8167
  try {
8142
8168
  await fs.promises.mkdir(dir, { recursive: true });
8143
8169
  } catch (error2) {
8144
- if (error2?.code !== "EEXIST") throw error2;
8170
+ if (!isEexistError(error2)) throw error2;
8145
8171
  }
8146
8172
  try {
8147
8173
  return await safeExecuteAsync2(async () => {
@@ -8183,7 +8209,7 @@ var init_PathResolver = __esm({
8183
8209
  try {
8184
8210
  fs.mkdirSync(dir, { recursive: true });
8185
8211
  } catch (error2) {
8186
- if (error2?.code !== "EEXIST") throw error2;
8212
+ if (!isEexistError(error2)) throw error2;
8187
8213
  }
8188
8214
  try {
8189
8215
  fs.copyFileSync(srcPath, normalizedDestPath);
@@ -8299,7 +8325,7 @@ var init_PathResolver = __esm({
8299
8325
  try {
8300
8326
  await fs.promises.mkdir(dirPath, { recursive: true });
8301
8327
  } catch (error2) {
8302
- if (error2?.code !== "EEXIST") throw error2;
8328
+ if (!isEexistError(error2)) throw error2;
8303
8329
  }
8304
8330
  }
8305
8331
  /**
@@ -8311,7 +8337,7 @@ var init_PathResolver = __esm({
8311
8337
  try {
8312
8338
  fs.mkdirSync(dirPath, { recursive: true });
8313
8339
  } catch (error2) {
8314
- if (error2?.code !== "EEXIST") throw error2;
8340
+ if (!isEexistError(error2)) throw error2;
8315
8341
  }
8316
8342
  }
8317
8343
  /**
@@ -8560,6 +8586,7 @@ var init_PathResolver = __esm({
8560
8586
  * @param patternType - Type of patterns (css, routes, i18n, assets, pwa)
8561
8587
  * @returns Resolved patterns with absolute paths
8562
8588
  */
8589
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: mirrors the public PathResolver.d.ts signature; tightening it is a breaking change (any-audit)
8563
8590
  async resolvePatterns(patternType) {
8564
8591
  if (!constants.getPatternsFor) {
8565
8592
  return { framework: [], consumer: [], all: [] };
@@ -8714,6 +8741,9 @@ import {
8714
8741
  } from "node:path";
8715
8742
  import { fileURLToPath as fileURLToPath2 } from "node:url";
8716
8743
  function readdirSync3(dirPath, options) {
8744
+ if (options !== null && typeof options === "object" && options.withFileTypes === true) {
8745
+ return pathResolverInstance.readdirSync(dirPath, options);
8746
+ }
8717
8747
  return pathResolverInstance.readdirSync(dirPath, options);
8718
8748
  }
8719
8749
  function getDirnameFromUrl(importMetaUrl) {
@@ -8896,6 +8926,34 @@ var init_typed_file_operations = __esm({
8896
8926
  }
8897
8927
  });
8898
8928
 
8929
+ // packages/tooling/src/utils/type-guards.ts
8930
+ function isRecord(value) {
8931
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8932
+ }
8933
+ function isObjectLike(value) {
8934
+ return typeof value === "object" && value !== null;
8935
+ }
8936
+ function asText(value) {
8937
+ return typeof value === "string" ? value : null;
8938
+ }
8939
+ function requireText(value, filePath) {
8940
+ if (typeof value !== "string") {
8941
+ throw new DoNotDevError(
8942
+ `Cannot read text file: ${filePath}`,
8943
+ DO_NOT_DEV_ERROR_CODES.FILE_NOT_FOUND,
8944
+ { context: { filePath } }
8945
+ );
8946
+ }
8947
+ return value;
8948
+ }
8949
+ var init_type_guards = __esm({
8950
+ "packages/tooling/src/utils/type-guards.ts"() {
8951
+ "use strict";
8952
+ init_utils2();
8953
+ init_errors();
8954
+ }
8955
+ });
8956
+
8899
8957
  // packages/tooling/src/bundler/utils.ts
8900
8958
  import { Buffer as Buffer2 } from "node:buffer";
8901
8959
  import { copyFileSync as copyFileSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "node:fs";
@@ -8997,7 +9055,7 @@ function analyzeApp(appPath, appName) {
8997
9055
  try {
8998
9056
  const envPath = joinPath(appPath, ".env");
8999
9057
  if (pathExists(envPath)) {
9000
- const envContent = readSync(envPath);
9058
+ const envContent = requireText(readSync(envPath), envPath);
9001
9059
  if (envContent.match(/VITE_SUPABASE_URL=.+/)) {
9002
9060
  hasSupabase = true;
9003
9061
  }
@@ -9044,7 +9102,7 @@ function analyzeApp(appPath, appName) {
9044
9102
  try {
9045
9103
  const envPath = joinPath(appPath, ".env");
9046
9104
  if (pathExists(envPath)) {
9047
- const envContent = readSync(envPath);
9105
+ const envContent = requireText(readSync(envPath), envPath);
9048
9106
  const urlMatch = envContent.match(/VITE_SUPABASE_URL=(.+)/);
9049
9107
  if (urlMatch && urlMatch[1]) {
9050
9108
  url = urlMatch[1].trim();
@@ -9148,6 +9206,7 @@ var init_app_detection = __esm({
9148
9206
  init_utils2();
9149
9207
  init_pathResolver();
9150
9208
  init_typed_file_operations();
9209
+ init_type_guards();
9151
9210
  PROVIDERS_CANDIDATES = [
9152
9211
  "src/config/providers.ts",
9153
9212
  "src/config/providers.tsx",
@@ -9197,7 +9256,7 @@ var init_app_selector = __esm({
9197
9256
  "packages/tooling/src/utils/app-selector.ts"() {
9198
9257
  "use strict";
9199
9258
  init_utils2();
9200
- init_dist4();
9259
+ init_dist5();
9201
9260
  init_app_detection();
9202
9261
  init_cli_output();
9203
9262
  }
@@ -9228,27 +9287,31 @@ async function askForConfirmation(message, defaultValue = false) {
9228
9287
  return result;
9229
9288
  }
9230
9289
  async function askForSelection(message, choices, defaultValue = 0) {
9231
- const options = choices.map((choice) => ({
9232
- value: choice.value,
9233
- label: choice.title,
9234
- hint: choice.hint
9235
- }));
9290
+ const options = choices.map((choice) => {
9291
+ const value = choice.value;
9292
+ return { value, label: choice.title, hint: choice.hint };
9293
+ });
9294
+ const initialValue = choices[defaultValue]?.value;
9236
9295
  const result = await select({
9237
9296
  message,
9238
9297
  options,
9239
- initialValue: choices[defaultValue]?.value
9298
+ initialValue
9240
9299
  });
9241
9300
  if (isCancel(result)) {
9242
9301
  cancel("Operation cancelled.");
9243
9302
  process.exit(0);
9244
9303
  }
9245
- return result;
9304
+ const picked = choices.find((choice) => choice.value === result);
9305
+ if (!picked) {
9306
+ throw new Error(`Unknown selection: ${result}`);
9307
+ }
9308
+ return picked.value;
9246
9309
  }
9247
9310
  var init_cli_input = __esm({
9248
9311
  "packages/tooling/src/utils/cli-input.ts"() {
9249
9312
  "use strict";
9250
9313
  init_utils2();
9251
- init_dist4();
9314
+ init_dist5();
9252
9315
  }
9253
9316
  });
9254
9317
 
@@ -9738,9 +9801,12 @@ function writeEnvFile(appDir, config, framework) {
9738
9801
  const prefix = framework === "nextjs" ? "NEXT_PUBLIC_" : "VITE_";
9739
9802
  let existingContent = "";
9740
9803
  if (pathExists(envPath)) {
9741
- existingContent = readSync(envPath);
9804
+ existingContent = requireText(readSync(envPath), envPath);
9742
9805
  } else if (pathExists(envPath + ".example")) {
9743
- existingContent = readSync(envPath + ".example");
9806
+ existingContent = requireText(
9807
+ readSync(envPath + ".example"),
9808
+ envPath + ".example"
9809
+ );
9744
9810
  }
9745
9811
  const existingLines = existingContent.split("\n");
9746
9812
  const preserved = [];
@@ -9777,7 +9843,7 @@ function writeEnvFile(appDir, config, framework) {
9777
9843
  `${prefix}FIREBASE_FUNCTIONS_REGION=europe-west1`
9778
9844
  ];
9779
9845
  const content = [
9780
- ...preserved.filter((l2) => l2.trim() !== ""),
9846
+ ...preserved.filter((l) => l.trim() !== ""),
9781
9847
  "",
9782
9848
  ...firebaseBlock,
9783
9849
  ""
@@ -9808,13 +9874,28 @@ function updateFirebaserc(projectRoot, projectId) {
9808
9874
  function updateFirebaseJson(projectRoot, projectId) {
9809
9875
  const fjPath = joinPath(projectRoot, "firebase.json");
9810
9876
  if (!pathExists(fjPath)) return;
9811
- let content = readSync(fjPath);
9812
- if (content.includes("{{YOUR_FIREBASE_PROJECT_ID}}") || content.includes("{{firebaseProjectId}}")) {
9813
- content = content.replace(/\{\{YOUR_FIREBASE_PROJECT_ID\}\}/g, projectId);
9814
- content = content.replace(/\{\{firebaseProjectId\}\}/g, projectId);
9815
- write(fjPath, content);
9816
- log2.success("Updated firebase.json with project ID");
9817
- }
9877
+ const firebaseJson2 = readSync(fjPath);
9878
+ if (!isRecord(firebaseJson2)) {
9879
+ throw new Error(`firebase.json is not a valid JSON object: ${fjPath}`);
9880
+ }
9881
+ let replaced = false;
9882
+ const fill = (value) => {
9883
+ if (typeof value === "string") {
9884
+ const next = value.replace(FIREBASE_PROJECT_ID_PLACEHOLDER, projectId);
9885
+ if (next !== value) replaced = true;
9886
+ return next;
9887
+ }
9888
+ if (Array.isArray(value)) return value.map(fill);
9889
+ if (isRecord(value)) return fillRecord(value);
9890
+ return value;
9891
+ };
9892
+ const fillRecord = (record) => Object.fromEntries(
9893
+ Object.entries(record).map(([key, entry]) => [key, fill(entry)])
9894
+ );
9895
+ const updated = fillRecord(firebaseJson2);
9896
+ if (!replaced) return;
9897
+ writeSync(fjPath, updated, { overwrite: true });
9898
+ log2.success("Updated firebase.json with project ID");
9818
9899
  }
9819
9900
  async function main(options = {}) {
9820
9901
  intro("Firebase Setup");
@@ -9890,7 +9971,7 @@ async function main(options = {}) {
9890
9971
  "Firebase setup done. Complete the manual steps above, then run dndev emu start."
9891
9972
  );
9892
9973
  }
9893
- var firebase_default, firebaseWizard;
9974
+ var FIREBASE_PROJECT_ID_PLACEHOLDER, firebase_default, firebaseWizard;
9894
9975
  var init_firebase = __esm({
9895
9976
  "packages/tooling/src/cli/setup/firebase.ts"() {
9896
9977
  "use strict";
@@ -9902,6 +9983,8 @@ var init_firebase = __esm({
9902
9983
  init_cli_output();
9903
9984
  init_error_handling();
9904
9985
  init_pathResolver();
9986
+ init_type_guards();
9987
+ FIREBASE_PROJECT_ID_PLACEHOLDER = /\{\{(?:YOUR_FIREBASE_PROJECT_ID|firebaseProjectId)\}\}/g;
9905
9988
  firebase_default = main;
9906
9989
  firebaseWizard = {
9907
9990
  id: "firebase",
@@ -10097,7 +10180,7 @@ async function executeMigration(options) {
10097
10180
  if (sqlFiles.length === 0) {
10098
10181
  throw new Error(`No .sql files found in ${migrationsDir}`);
10099
10182
  }
10100
- const sql = sqlFiles.map((f) => readSync(f)).filter(Boolean).join("\n\n");
10183
+ const sql = sqlFiles.map((f) => asText(readSync(f))).filter(Boolean).join("\n\n");
10101
10184
  const projectRef = extractProjectRef(supabaseUrl);
10102
10185
  const mgmtUrl = `https://api.supabase.com/v1/projects/${projectRef}/database/query`;
10103
10186
  const response = await fetch(mgmtUrl, {
@@ -10124,6 +10207,7 @@ var init_supabase_management = __esm({
10124
10207
  init_utils2();
10125
10208
  init_cli_output();
10126
10209
  init_pathResolver();
10210
+ init_type_guards();
10127
10211
  }
10128
10212
  });
10129
10213
 
@@ -10136,6 +10220,7 @@ var init_base_generator = __esm({
10136
10220
  init_cli_output();
10137
10221
  init_errors();
10138
10222
  init_pathResolver();
10223
+ init_type_guards();
10139
10224
  __dirname2 = getDirnameFromUrl(import.meta.url);
10140
10225
  BaseGenerator = class {
10141
10226
  /** Generator display name for logs */
@@ -10344,7 +10429,7 @@ var init_base_generator = __esm({
10344
10429
  * Renders a template file with context data
10345
10430
  *
10346
10431
  * @param {string} templatePath - Path to the template file
10347
- * @param {Record<string, any>} context - Context data for the template
10432
+ * @param {Record<string, unknown>} context - Context data for the template
10348
10433
  * @returns {Promise<string>} Rendered template content
10349
10434
  *
10350
10435
  * @version 0.1.0
@@ -10378,9 +10463,12 @@ var init_base_generator = __esm({
10378
10463
  "template-not-found"
10379
10464
  );
10380
10465
  }
10381
- templateContent = await read(resolvedPath, {
10382
- format: "text"
10383
- });
10466
+ templateContent = requireText(
10467
+ await read(resolvedPath, {
10468
+ format: "text"
10469
+ }),
10470
+ resolvedPath
10471
+ );
10384
10472
  } catch (err) {
10385
10473
  throw new DoNotDevError(
10386
10474
  `Failed to load template: ${templatePath}`,
@@ -10483,7 +10571,7 @@ var init_base_generator = __esm({
10483
10571
  *
10484
10572
  * @param {string} templateDirPath - Path to the template directory
10485
10573
  * @param {string} outputDirPath - Path to the output directory
10486
- * @param {Record<string, any>} context - Context data for templates
10574
+ * @param {Record<string, unknown>} context - Context data for templates
10487
10575
  * @param {GeneratorResult} result - Generator result to update
10488
10576
  * @returns {Promise<boolean>} True if any files were copied
10489
10577
  *
@@ -10594,7 +10682,7 @@ var init_base_generator = __esm({
10594
10682
  * Loads a JavaScript/TypeScript module from a file
10595
10683
  *
10596
10684
  * @param {string} filePath - Path to the module file
10597
- * @returns {Promise<any>} The loaded module
10685
+ * @returns {Promise<Record<string, unknown>>} The loaded module namespace
10598
10686
  *
10599
10687
  * @version 0.1.0
10600
10688
  * @since 0.0.1
@@ -10603,7 +10691,8 @@ var init_base_generator = __esm({
10603
10691
  async importModule(filePath) {
10604
10692
  try {
10605
10693
  const importPath = `file://${normalizePath(filePath)}`;
10606
- return await import(importPath);
10694
+ const moduleNamespace = await import(importPath);
10695
+ return moduleNamespace;
10607
10696
  } catch (err) {
10608
10697
  const errorMessage = err instanceof Error ? err.message : "Unknown error";
10609
10698
  throw new DoNotDevError(
@@ -10713,12 +10802,502 @@ var init_base_generator = __esm({
10713
10802
  }
10714
10803
  });
10715
10804
 
10805
+ // packages/providers/supabase/src/common/checkConstraints.ts
10806
+ function checkConstraintName(table, column, rule) {
10807
+ const name = `${table}_${column}_${rule}`;
10808
+ if (new TextEncoder().encode(name).length > MAX_IDENTIFIER_LENGTH) {
10809
+ throw new Error(
10810
+ `CHECK constraint name "${name}" exceeds ${MAX_IDENTIFIER_LENGTH} bytes: shorten the table or column name`
10811
+ );
10812
+ }
10813
+ return name;
10814
+ }
10815
+ var MAX_IDENTIFIER_LENGTH;
10816
+ var init_checkConstraints = __esm({
10817
+ "packages/providers/supabase/src/common/checkConstraints.ts"() {
10818
+ "use strict";
10819
+ init_utils2();
10820
+ MAX_IDENTIFIER_LENGTH = 63;
10821
+ }
10822
+ });
10823
+
10824
+ // packages/tooling/src/generators/pgRegex.ts
10825
+ function toPostgresRegex(regex) {
10826
+ const source = typeof regex === "string" ? regex : regex.source;
10827
+ if (typeof regex !== "string" && regex.flags !== "") {
10828
+ throw new UnsupportedRegexError(source, `flags "${regex.flags}"`);
10829
+ }
10830
+ try {
10831
+ new RegExp(source);
10832
+ } catch (error2) {
10833
+ throw new UnsupportedRegexError(source, error2 instanceof Error ? error2.message : "invalid regex");
10834
+ }
10835
+ const fail = (reason) => {
10836
+ throw new UnsupportedRegexError(source, reason);
10837
+ };
10838
+ let out = "";
10839
+ let i2 = 0;
10840
+ const escape = (inClass) => {
10841
+ const c3 = source[i2];
10842
+ if (c3 === void 0) return fail("trailing backslash");
10843
+ if (!/[A-Za-z0-9]/.test(c3)) {
10844
+ i2++;
10845
+ return `\\${c3}`;
10846
+ }
10847
+ if (c3 === "d") {
10848
+ i2++;
10849
+ return inClass ? DIGIT : `[${DIGIT}]`;
10850
+ }
10851
+ if (c3 === "w") {
10852
+ i2++;
10853
+ return inClass ? WORD : `[${WORD}]`;
10854
+ }
10855
+ if (c3 === "D" || c3 === "W") {
10856
+ if (inClass) return fail(`\\${c3} inside a character class`);
10857
+ i2++;
10858
+ return `[^${c3 === "D" ? DIGIT : WORD}]`;
10859
+ }
10860
+ if (c3 === "S" && inClass) return fail("\\S inside a character class");
10861
+ if (c3 === "b" || c3 === "B") {
10862
+ if (inClass) return fail(`\\${c3} inside a character class`);
10863
+ i2++;
10864
+ return c3 === "b" ? "\\y" : "\\Y";
10865
+ }
10866
+ if (SAME_ESCAPES.has(c3)) {
10867
+ i2++;
10868
+ return `\\${c3}`;
10869
+ }
10870
+ if (c3 === "x") {
10871
+ const hex = source.slice(i2 + 1, i2 + 3);
10872
+ if (!/^[0-9A-Fa-f]{2}$/.test(hex)) return fail("\\x without two hex digits");
10873
+ i2 += 3;
10874
+ return `\\u00${hex}`;
10875
+ }
10876
+ if (c3 === "u") {
10877
+ const hex = source.slice(i2 + 1, i2 + 5);
10878
+ if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return fail("\\u without four hex digits (\\u{\u2026} needs the u flag)");
10879
+ i2 += 5;
10880
+ return `\\u${hex}`;
10881
+ }
10882
+ return fail(`escape \\${c3}`);
10883
+ };
10884
+ const charClass = () => {
10885
+ i2++;
10886
+ let body = "";
10887
+ if (source[i2] === "^") {
10888
+ body += "^";
10889
+ i2++;
10890
+ }
10891
+ if (source[i2] === "]") fail("empty character class");
10892
+ while (i2 < source.length && source[i2] !== "]") {
10893
+ const c3 = source[i2];
10894
+ if (c3 === "\\") {
10895
+ i2++;
10896
+ body += escape(true);
10897
+ } else if (c3 === "[") {
10898
+ body += "\\[";
10899
+ i2++;
10900
+ } else {
10901
+ body += c3;
10902
+ i2++;
10903
+ }
10904
+ }
10905
+ if (source[i2] !== "]") fail("unterminated character class");
10906
+ i2++;
10907
+ return `[${body}]`;
10908
+ };
10909
+ while (i2 < source.length) {
10910
+ const c3 = source[i2];
10911
+ if (c3 === "\\") {
10912
+ i2++;
10913
+ out += escape(false);
10914
+ } else if (c3 === "[") {
10915
+ out += charClass();
10916
+ } else if (c3 === ".") {
10917
+ out += NOT_LINE_TERMINATOR;
10918
+ i2++;
10919
+ } else if (c3 === "(") {
10920
+ if (source[i2 + 1] === "?") {
10921
+ const head = source.slice(i2, i2 + 4);
10922
+ if (head.startsWith("(?:") || head.startsWith("(?=") || head.startsWith("(?!")) {
10923
+ out += source.slice(i2, i2 + 3);
10924
+ i2 += 3;
10925
+ } else if (head === "(?<=" || head === "(?<!") {
10926
+ out += head;
10927
+ i2 += 4;
10928
+ } else {
10929
+ fail("named group");
10930
+ }
10931
+ } else {
10932
+ out += "(";
10933
+ i2++;
10934
+ }
10935
+ } else if (c3 === "{") {
10936
+ const quantifier = /^\{\d+(,\d*)?\}\??/.exec(source.slice(i2));
10937
+ if (!quantifier || out === "") fail('"{" that is not a quantifier');
10938
+ out += quantifier[0];
10939
+ i2 += quantifier[0].length;
10940
+ } else if (c3 === "}") {
10941
+ fail('unmatched "}"');
10942
+ } else {
10943
+ out += c3;
10944
+ i2++;
10945
+ }
10946
+ }
10947
+ return out;
10948
+ }
10949
+ function sqlRegexLiteral(are) {
10950
+ return `'${are.replace(/'/g, "''")}'`;
10951
+ }
10952
+ var DIGIT, WORD, NOT_LINE_TERMINATOR, SAME_ESCAPES, UnsupportedRegexError;
10953
+ var init_pgRegex = __esm({
10954
+ "packages/tooling/src/generators/pgRegex.ts"() {
10955
+ "use strict";
10956
+ init_utils2();
10957
+ DIGIT = "0-9";
10958
+ WORD = "A-Za-z0-9_";
10959
+ NOT_LINE_TERMINATOR = "[^\\n\\r\\u2028\\u2029]";
10960
+ SAME_ESCAPES = /* @__PURE__ */ new Set(["t", "n", "r", "f", "v", "s", "S"]);
10961
+ UnsupportedRegexError = class extends Error {
10962
+ constructor(source, reason) {
10963
+ super(`Regex /${source}/ cannot be translated to a PostgreSQL CHECK: ${reason}`);
10964
+ this.name = "UnsupportedRegexError";
10965
+ }
10966
+ };
10967
+ }
10968
+ });
10969
+
10970
+ // packages/tooling/src/generators/sqlChecks.ts
10971
+ function camelToSnake(str) {
10972
+ return str.replace(/[A-Z]/g, (c3) => `_${c3.toLowerCase()}`);
10973
+ }
10974
+ function sqlText(value) {
10975
+ return `'${value.replace(/'/g, "''")}'`;
10976
+ }
10977
+ function sqlOption(value, where) {
10978
+ if (typeof value === "string") return sqlText(value);
10979
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
10980
+ throw new Error(`${where}: option value ${JSON.stringify(value)} has no SQL literal`);
10981
+ }
10982
+ function unwrap(schema) {
10983
+ let current = schema;
10984
+ for (let depth = 0; depth < 8; depth++) {
10985
+ if (!isObjectLike(current) || typeof current.type !== "string") return void 0;
10986
+ if (!WRAPPERS.has(current.type)) return current;
10987
+ current = current.wrapped;
10988
+ }
10989
+ return void 0;
10990
+ }
10991
+ function pipeRequirements(schema, type) {
10992
+ const pipe = schema.pipe;
10993
+ if (!Array.isArray(pipe)) return [];
10994
+ return pipe.filter((action) => isObjectLike(action) && action.type === type).map((action) => action.requirement);
10995
+ }
10996
+ function firstNumber(values) {
10997
+ const n3 = values.find((value) => typeof value === "number" && Number.isFinite(value));
10998
+ return typeof n3 === "number" ? n3 : void 0;
10999
+ }
11000
+ function jsonTypes(schema, depth = 0) {
11001
+ const s = unwrap(schema);
11002
+ if (!s || depth > 8) return null;
11003
+ switch (s.type) {
11004
+ case "array":
11005
+ case "tuple":
11006
+ case "loose_tuple":
11007
+ case "strict_tuple":
11008
+ case "tuple_with_rest":
11009
+ return /* @__PURE__ */ new Set(["array"]);
11010
+ case "object":
11011
+ case "loose_object":
11012
+ case "strict_object":
11013
+ case "object_with_rest":
11014
+ case "record":
11015
+ return /* @__PURE__ */ new Set(["object"]);
11016
+ case "string":
11017
+ return /* @__PURE__ */ new Set(["string"]);
11018
+ case "number":
11019
+ return /* @__PURE__ */ new Set(["number"]);
11020
+ case "boolean":
11021
+ return /* @__PURE__ */ new Set(["boolean"]);
11022
+ case "literal": {
11023
+ const t2 = typeof s.literal;
11024
+ return t2 === "string" || t2 === "number" || t2 === "boolean" ? /* @__PURE__ */ new Set([t2]) : null;
11025
+ }
11026
+ case "picklist": {
11027
+ const options = Array.isArray(s.options) ? s.options : [];
11028
+ const types = new Set(options.map((o) => typeof o));
11029
+ return [...types].every((t2) => t2 === "string" || t2 === "number") ? types : null;
11030
+ }
11031
+ case "union":
11032
+ case "variant": {
11033
+ const options = Array.isArray(s.options) ? s.options : [];
11034
+ const all = /* @__PURE__ */ new Set();
11035
+ for (const option of options) {
11036
+ const types = jsonTypes(option, depth + 1);
11037
+ if (!types) return null;
11038
+ for (const t2 of types) all.add(t2);
11039
+ }
11040
+ return all.size > 0 ? all : null;
11041
+ }
11042
+ default:
11043
+ return null;
11044
+ }
11045
+ }
11046
+ function buildEntityChecks(entity, descriptor, hiddenStatuses) {
11047
+ const table = entity.collection;
11048
+ const fields = isObjectLike(entity.fields) ? entity.fields : {};
11049
+ const checks = [];
11050
+ const hidden = hiddenStatuses.map(sqlText).join(", ");
11051
+ for (const [key, field] of Object.entries(fields)) {
11052
+ if (TECHNICAL_KEYS.has(key) || !isObjectLike(field)) continue;
11053
+ const d = descriptor.fields[key];
11054
+ if (!d) continue;
11055
+ const column = camelToSnake(key);
11056
+ const where = `${descriptor.name}.${key}`;
11057
+ const add = (rule, variants) => {
11058
+ checks.push({ name: checkConstraintName(table, column, rule), table, column, rule, variants });
11059
+ };
11060
+ const kind = d.value.kind;
11061
+ const validation = isObjectLike(field.validation) ? field.validation : void 0;
11062
+ const ownSchema = validation?.schema !== void 0;
11063
+ const value = unwrap(d.value.schema);
11064
+ if (d.required === "always") {
11065
+ const variants = [];
11066
+ if (TEXT_KINDS.has(kind)) {
11067
+ variants.push({
11068
+ types: TEXT_TYPES,
11069
+ expr: `status IN (${hidden}) OR (${column} IS NOT NULL AND ${column} <> '')`
11070
+ });
11071
+ }
11072
+ variants.push({ types: null, expr: `status IN (${hidden}) OR ${column} IS NOT NULL` });
11073
+ add("required", variants);
11074
+ }
11075
+ if (!ownSchema && value) {
11076
+ if (kind === "text" && value.type === "string") {
11077
+ const min = firstNumber(pipeRequirements(value, "min_length"));
11078
+ const max = firstNumber(pipeRequirements(value, "max_length"));
11079
+ if (min !== void 0 || max !== void 0) {
11080
+ const bounds = [
11081
+ ...min !== void 0 ? [`char_length(${column}) >= ${min}`] : [],
11082
+ ...max !== void 0 ? [`char_length(${column}) <= ${max}`] : []
11083
+ ].join(" AND ");
11084
+ add("length", [{ types: TEXT_TYPES, expr: `${column} IS NULL OR (${bounds})` }]);
11085
+ }
11086
+ const patterns = pipeRequirements(value, "regex").filter(
11087
+ (r2) => r2 instanceof RegExp
11088
+ );
11089
+ if (patterns.length > 0) {
11090
+ const tests = patterns.map((regex) => {
11091
+ try {
11092
+ return `${column} ~ ${sqlRegexLiteral(toPostgresRegex(regex))}`;
11093
+ } catch (error2) {
11094
+ throw new Error(`${where}: ${error2 instanceof Error ? error2.message : String(error2)}`);
11095
+ }
11096
+ }).join(" AND ");
11097
+ add("pattern", [{ types: TEXT_TYPES, expr: `${column} IS NULL OR (${tests})` }]);
11098
+ }
11099
+ }
11100
+ if (value.type === "picklist" && Array.isArray(value.options)) {
11101
+ const options = value.options;
11102
+ const numeric = options.every((o) => typeof o === "number");
11103
+ add("options", [
11104
+ {
11105
+ types: numeric ? NUMERIC_TYPES : TEXT_TYPES,
11106
+ expr: `${column} IS NULL OR ${column} IN (${options.map((o) => sqlOption(o, where)).join(", ")})`
11107
+ }
11108
+ ]);
11109
+ } else if (value.type === "array") {
11110
+ const item = unwrap(value.item);
11111
+ if (item?.type === "picklist" && Array.isArray(item.options)) {
11112
+ const list = JSON.stringify(item.options);
11113
+ add("options", [
11114
+ { types: JSONB_TYPES, expr: `${column} IS NULL OR ${column} <@ ${sqlText(list)}::jsonb` }
11115
+ ]);
11116
+ }
11117
+ }
11118
+ if ((kind === "number" || kind === "integer") && value.type === "number") {
11119
+ const min = firstNumber(pipeRequirements(value, "min_value"));
11120
+ const max = firstNumber(pipeRequirements(value, "max_value"));
11121
+ if (min !== void 0 || max !== void 0) {
11122
+ const bounds = [
11123
+ ...min !== void 0 ? [`${column} >= ${min}`] : [],
11124
+ ...max !== void 0 ? [`${column} <= ${max}`] : []
11125
+ ].join(" AND ");
11126
+ add("range", [{ types: NUMERIC_TYPES, expr: `${column} IS NULL OR (${bounds})` }]);
11127
+ }
11128
+ }
11129
+ }
11130
+ if (kind === "integer") {
11131
+ add("integer", [{ types: NUMERIC_TYPES, expr: `${column} IS NULL OR ${column} = trunc(${column})` }]);
11132
+ }
11133
+ if (kind === "json") {
11134
+ const types = jsonTypes(d.value.schema);
11135
+ if (types) {
11136
+ add("json", [
11137
+ {
11138
+ types: JSONB_TYPES,
11139
+ expr: `${column} IS NULL OR jsonb_typeof(${column}) IN (${[...types].sort().map(sqlText).join(", ")})`
11140
+ }
11141
+ ]);
11142
+ }
11143
+ }
11144
+ }
11145
+ return checks;
11146
+ }
11147
+ function checkConstraintSql(spec) {
11148
+ const rel = sqlText(`"${spec.table}"`);
11149
+ const branches = spec.variants.map((variant, index) => {
11150
+ if (variant.expr.includes(EXPR_TAG) || variant.expr.includes("$dndev$")) {
11151
+ throw new Error(`${spec.name}: expression contains a reserved dollar-quote tag`);
11152
+ }
11153
+ const assign = `expr := ${EXPR_TAG}${variant.expr}${EXPR_TAG};`;
11154
+ const keyword = index === 0 ? "IF" : "ELSIF";
11155
+ if (variant.types === null) {
11156
+ return index === 0 ? ` ${assign}` : ` ELSE
11157
+ ${assign}`;
11158
+ }
11159
+ return ` ${keyword} col_type = ANY (ARRAY[${variant.types.map(sqlText).join(", ")}]) THEN
11160
+ ${assign}`;
11161
+ });
11162
+ const hasTyped = spec.variants.some((variant) => variant.types !== null);
11163
+ const select2 = hasTyped ? `${branches.join("\n")}
11164
+ END IF;` : branches.join("\n");
11165
+ const name = sqlText(spec.name);
11166
+ const table = sqlText(spec.table);
11167
+ return `-- ${spec.name} (${spec.rule})
11168
+ DO $dndev$
11169
+ DECLARE
11170
+ col_type text;
11171
+ expr text;
11172
+ wanted text;
11173
+ existing text;
11174
+ is_validated boolean;
11175
+ BEGIN
11176
+ SELECT format_type(a.atttypid, a.atttypmod) INTO col_type
11177
+ FROM pg_attribute a
11178
+ WHERE a.attrelid = ${rel}::regclass AND a.attname = ${sqlText(spec.column)} AND NOT a.attisdropped;
11179
+ IF col_type IS NULL THEN
11180
+ RAISE NOTICE 'dndev: % skipped: column missing', ${name};
11181
+ RETURN;
11182
+ END IF;
11183
+ ${select2}
11184
+ IF expr IS NULL THEN
11185
+ RAISE NOTICE 'dndev: % skipped: column type % cannot hold the rule', ${name}, col_type;
11186
+ RETURN;
11187
+ END IF;
11188
+ EXECUTE format('ALTER TABLE %I ADD CONSTRAINT %I CHECK (%s) NOT VALID', ${table}, '${PROBE}', expr);
11189
+ SELECT pg_get_constraintdef(c.oid) INTO wanted
11190
+ FROM pg_constraint c WHERE c.conrelid = ${rel}::regclass AND c.conname = '${PROBE}';
11191
+ EXECUTE format('ALTER TABLE %I DROP CONSTRAINT %I', ${table}, '${PROBE}');
11192
+ SELECT pg_get_constraintdef(c.oid), c.convalidated INTO existing, is_validated
11193
+ FROM pg_constraint c WHERE c.conrelid = ${rel}::regclass AND c.conname = ${name};
11194
+ IF existing IS NULL THEN
11195
+ EXECUTE format('ALTER TABLE %I ADD CONSTRAINT %I CHECK (%s) NOT VALID', ${table}, ${name}, expr);
11196
+ ELSIF regexp_replace(existing, ' NOT VALID$', '') = regexp_replace(wanted, ' NOT VALID$', '') THEN
11197
+ NULL;
11198
+ ELSIF is_validated THEN
11199
+ RAISE WARNING 'dndev: % is validated and differs from the entity: kept (never dropped); replace it by hand', ${name};
11200
+ ELSE
11201
+ EXECUTE format('ALTER TABLE %I DROP CONSTRAINT %I', ${table}, ${name});
11202
+ EXECUTE format('ALTER TABLE %I ADD CONSTRAINT %I CHECK (%s) NOT VALID', ${table}, ${name}, expr);
11203
+ END IF;
11204
+ END
11205
+ $dndev$;`;
11206
+ }
11207
+ var TEXT_TYPES, NUMERIC_TYPES, JSONB_TYPES, TEXT_KINDS, TECHNICAL_KEYS, WRAPPERS, EXPR_TAG, PROBE;
11208
+ var init_sqlChecks = __esm({
11209
+ "packages/tooling/src/generators/sqlChecks.ts"() {
11210
+ "use strict";
11211
+ init_utils2();
11212
+ init_checkConstraints();
11213
+ init_type_guards();
11214
+ init_pgRegex();
11215
+ TEXT_TYPES = ["text", "character varying"];
11216
+ NUMERIC_TYPES = [
11217
+ "numeric",
11218
+ "integer",
11219
+ "bigint",
11220
+ "smallint",
11221
+ "double precision",
11222
+ "real"
11223
+ ];
11224
+ JSONB_TYPES = ["jsonb"];
11225
+ TEXT_KINDS = /* @__PURE__ */ new Set(["text"]);
11226
+ TECHNICAL_KEYS = /* @__PURE__ */ new Set([
11227
+ "id",
11228
+ "createdAt",
11229
+ "updatedAt",
11230
+ "createdById",
11231
+ "updatedById",
11232
+ "status"
11233
+ ]);
11234
+ WRAPPERS = /* @__PURE__ */ new Set([
11235
+ "optional",
11236
+ "exact_optional",
11237
+ "nullable",
11238
+ "nullish",
11239
+ "undefinedable",
11240
+ "non_nullable",
11241
+ "non_nullish",
11242
+ "non_optional"
11243
+ ]);
11244
+ EXPR_TAG = "$dndev_expr$";
11245
+ PROBE = "dndev_check_probe";
11246
+ }
11247
+ });
11248
+
11249
+ // packages/tooling/src/utils/coreSemantics.ts
11250
+ import { createRequire as createRequire4 } from "node:module";
11251
+ import { pathToFileURL } from "node:url";
11252
+ function isFunction(value) {
11253
+ return typeof value === "function";
11254
+ }
11255
+ async function loadCoreSemantics(fromFile) {
11256
+ let resolved;
11257
+ try {
11258
+ resolved = createRequire4(fromFile).resolve("@donotdev/core/server");
11259
+ } catch (error2) {
11260
+ throw new DoNotDevError(
11261
+ `Cannot resolve @donotdev/core from ${fromFile}: install it in the app (entities import it).`,
11262
+ DO_NOT_DEV_ERROR_CODES.CONFIGURATION_ERROR,
11263
+ { originalError: error2 instanceof Error ? error2 : void 0 }
11264
+ );
11265
+ }
11266
+ const mod = await import(pathToFileURL(resolved).href);
11267
+ if (!isRecord(mod) || !isFunction(mod.describeEntity) || !isFunction(mod.createSchemas) || !Array.isArray(mod.HIDDEN_STATUSES) || typeof mod.DEFAULT_STATUS_VALUE !== "string") {
11268
+ throw new DoNotDevError(
11269
+ `@donotdev/core at ${resolved} has no describeEntity / createSchemas / HIDDEN_STATUSES / DEFAULT_STATUS_VALUE: upgrade @donotdev/core.`,
11270
+ DO_NOT_DEV_ERROR_CODES.CONFIGURATION_ERROR
11271
+ );
11272
+ }
11273
+ const describeEntity = mod.describeEntity;
11274
+ const createSchemas = mod.createSchemas;
11275
+ return {
11276
+ // why: the shapes are the core exports' (see the interfaces above); checked as functions
11277
+ describeEntity: (entity) => describeEntity(entity),
11278
+ createSchemas: (entity) => createSchemas(entity),
11279
+ hiddenStatuses: mod.HIDDEN_STATUSES.map(String),
11280
+ defaultStatus: mod.DEFAULT_STATUS_VALUE
11281
+ };
11282
+ }
11283
+ var init_coreSemantics = __esm({
11284
+ "packages/tooling/src/utils/coreSemantics.ts"() {
11285
+ "use strict";
11286
+ init_utils2();
11287
+ init_errors();
11288
+ init_type_guards();
11289
+ }
11290
+ });
11291
+
10716
11292
  // packages/tooling/src/generators/sql-generator.ts
10717
11293
  var sql_generator_exports = {};
10718
11294
  __export(sql_generator_exports, {
10719
11295
  SqlGenerator: () => SqlGenerator,
10720
11296
  main: () => main2
10721
11297
  });
11298
+ function isSqlEntity(value) {
11299
+ return isObjectLike(value) && !!value.name && typeof value.collection === "string" && value.collection !== "";
11300
+ }
10722
11301
  function roleToSqlCondition(role) {
10723
11302
  switch (role) {
10724
11303
  case "guest":
@@ -10736,42 +11315,8 @@ function roleToSqlCondition(role) {
10736
11315
  return "false";
10737
11316
  }
10738
11317
  }
10739
- function camelToSnake(str) {
10740
- return str.replace(/[A-Z]/g, (c2) => `_${c2.toLowerCase()}`);
10741
- }
10742
- function fieldTypeToSql(fieldType) {
10743
- return FIELD_TYPE_TO_SQL[fieldType] ?? null;
10744
- }
10745
- function inferSqlTypeFromValidation(validation) {
10746
- if (!validation) return "text";
10747
- if (validation.min !== void 0 || validation.max !== void 0)
10748
- return "numeric";
10749
- if (validation.minLength !== void 0 || validation.maxLength !== void 0)
10750
- return "text";
10751
- if (Array.isArray(validation.options) && validation.options.length > 0) {
10752
- const first = validation.options[0];
10753
- if (first && typeof first === "object" && typeof first.value === "number")
10754
- return "numeric";
10755
- }
10756
- return "text";
10757
- }
10758
- function schemaRequiresJsonb(schema) {
10759
- if (!schema || typeof schema !== "object") return false;
10760
- const s = schema;
10761
- const kind = s.type ?? s.kind ?? s._tag;
10762
- if (typeof kind === "string") {
10763
- if (kind === "array" || kind === "object") return true;
10764
- if (kind === "optional" || kind === "nullable" || kind === "nullish") {
10765
- return schemaRequiresJsonb(s.wrapped);
10766
- }
10767
- if (kind === "pipe" || kind === "union" || kind === "intersect") {
10768
- const items = s.pipe ?? s.items ?? s.options;
10769
- if (Array.isArray(items) && items.length > 0) {
10770
- return schemaRequiresJsonb(items[0]);
10771
- }
10772
- }
10773
- }
10774
- return false;
11318
+ function camelToSnake2(str) {
11319
+ return str.replace(/[A-Z]/g, (c3) => `_${c3.toLowerCase()}`);
10775
11320
  }
10776
11321
  async function main2() {
10777
11322
  try {
@@ -10793,15 +11338,18 @@ async function main2() {
10793
11338
  process.exit(1);
10794
11339
  }
10795
11340
  }
10796
- var HIDDEN_STATUSES, ROLE_LEVEL, FIELD_TYPE_TO_SQL, TECHNICAL_KEYS, SqlGenerator;
11341
+ var HIDDEN_STATUSES, ROLE_LEVEL, KIND_TO_SQL, TECHNICAL_KEYS2, SqlGenerator;
10797
11342
  var init_sql_generator = __esm({
10798
11343
  "packages/tooling/src/generators/sql-generator.ts"() {
10799
11344
  "use strict";
10800
11345
  init_utils2();
10801
11346
  init_base_generator();
11347
+ init_sqlChecks();
10802
11348
  init_cli_output();
11349
+ init_coreSemantics();
10803
11350
  init_errors();
10804
11351
  init_pathResolver();
11352
+ init_type_guards();
10805
11353
  HIDDEN_STATUSES = ["draft", "deleted"];
10806
11354
  ROLE_LEVEL = {
10807
11355
  guest: 0,
@@ -10809,56 +11357,18 @@ var init_sql_generator = __esm({
10809
11357
  admin: 2,
10810
11358
  super: 3
10811
11359
  };
10812
- FIELD_TYPE_TO_SQL = {
11360
+ KIND_TO_SQL = {
10813
11361
  text: "text",
10814
- textarea: "text",
10815
- email: "text",
10816
- tel: "text",
10817
- url: "text",
10818
- password: "text",
10819
- hidden: "text",
10820
- badge: "text",
10821
- avatar: "text",
10822
- combobox: "text",
10823
- reset: "text",
10824
- submit: "text",
10825
11362
  number: "numeric",
10826
- range: "numeric",
10827
- rating: "numeric",
10828
- currency: "numeric",
10829
- price: "jsonb",
11363
+ integer: "integer",
10830
11364
  boolean: "boolean",
10831
- checkbox: "boolean",
10832
- switch: "boolean",
10833
11365
  date: "date",
10834
11366
  time: "time",
10835
- month: "date",
10836
- week: "date",
10837
- year: "integer",
10838
- "datetime-local": "timestamptz",
10839
11367
  timestamp: "timestamptz",
10840
- reference: "uuid",
10841
- select: "text",
10842
- radio: "text",
10843
- status: "text",
10844
- multiselect: "jsonb",
10845
- image: "text",
10846
- images: "jsonb",
10847
- file: "text",
10848
- files: "jsonb",
10849
- document: "text",
10850
- documents: "jsonb",
10851
- geopoint: "jsonb",
10852
- address: "jsonb",
10853
- map: "jsonb",
10854
- array: "jsonb",
10855
- color: "text",
10856
- iban: "text",
10857
- richtext: "text",
10858
- duration: "numeric",
10859
- gdprConsent: "boolean"
11368
+ json: "jsonb",
11369
+ ref: "uuid"
10860
11370
  };
10861
- TECHNICAL_KEYS = /* @__PURE__ */ new Set([
11371
+ TECHNICAL_KEYS2 = /* @__PURE__ */ new Set([
10862
11372
  "id",
10863
11373
  "createdAt",
10864
11374
  "updatedAt",
@@ -10868,6 +11378,7 @@ var init_sql_generator = __esm({
10868
11378
  ]);
10869
11379
  SqlGenerator = class extends BaseGenerator {
10870
11380
  singleFile;
11381
+ core;
10871
11382
  constructor(options = {}) {
10872
11383
  super("SQL", {
10873
11384
  entityDirs: options.entityDir ? [options.entityDir] : void 0,
@@ -10878,6 +11389,11 @@ var init_sql_generator = __esm({
10878
11389
  });
10879
11390
  this.singleFile = options.singleFile !== false;
10880
11391
  }
11392
+ /** Entity semantics of the app the entity file belongs to (loaded once). */
11393
+ async coreFor(entityFilePath) {
11394
+ this.core ??= await loadCoreSemantics(entityFilePath);
11395
+ return this.core;
11396
+ }
10881
11397
  async processEntityFile(entityFilePath, result) {
10882
11398
  const entityFileName = getBasename(entityFilePath, ".ts");
10883
11399
  let entityModule;
@@ -10891,20 +11407,27 @@ var init_sql_generator = __esm({
10891
11407
  if (!entity) {
10892
11408
  return null;
10893
11409
  }
11410
+ const entityName = isObjectLike(entity) ? entity.name : void 0;
11411
+ const resolvedName = typeof entityName === "string" ? entityName : entityFileName;
10894
11412
  if (this.singleFile) {
10895
- return entity.name ?? entityFileName;
11413
+ return resolvedName;
10896
11414
  }
10897
- await this.writeMigrationForEntity(entity, entityFileName, result);
10898
- return entity.name ?? entityFileName;
11415
+ await this.writeMigrationForEntity(
11416
+ entity,
11417
+ entityFileName,
11418
+ await this.coreFor(entityFilePath),
11419
+ result
11420
+ );
11421
+ return resolvedName;
10899
11422
  }
10900
11423
  extractEntityFromModule(entityModule, fileName) {
10901
11424
  const expectedName = fileName + "Entity";
10902
11425
  if (entityModule[expectedName]) return entityModule[expectedName];
10903
- const entityName = fileName.replace(/[-_](\w)/g, (_, c2) => c2.toUpperCase()).replace(/^\w/, (c2) => c2.toUpperCase());
11426
+ const entityName = fileName.replace(/[-_](\w)/g, (_, c3) => c3.toUpperCase()).replace(/^\w/, (c3) => c3.toUpperCase());
10904
11427
  if (entityModule[entityName]) return entityModule[entityName];
10905
11428
  for (const key of Object.keys(entityModule)) {
10906
11429
  const potential = entityModule[key];
10907
- if (potential && typeof potential === "object" && potential.name && potential.collection) {
11430
+ if (isObjectLike(potential) && potential.name && potential.collection) {
10908
11431
  return potential;
10909
11432
  }
10910
11433
  }
@@ -10920,28 +11443,32 @@ var init_sql_generator = __esm({
10920
11443
  }
10921
11444
  return `"${collection.replace(/"/g, '""')}"`;
10922
11445
  }
10923
- buildTableSql(entity) {
11446
+ buildTableSql(entity, core) {
10924
11447
  const tableName = this.safeTableName(entity.collection);
11448
+ const descriptor = core.describeEntity(entity);
10925
11449
  const columns = [];
10926
11450
  columns.push("id uuid PRIMARY KEY DEFAULT gen_random_uuid()");
10927
11451
  columns.push("created_at timestamptz NOT NULL DEFAULT now()");
10928
11452
  columns.push("updated_at timestamptz NOT NULL DEFAULT now()");
10929
11453
  columns.push("created_by_id uuid");
10930
11454
  columns.push("updated_by_id uuid");
10931
- columns.push("status text NOT NULL DEFAULT 'available'");
10932
- const fields = entity.fields || {};
11455
+ columns.push(`status text NOT NULL DEFAULT '${core.defaultStatus}'`);
11456
+ const fields = isObjectLike(entity.fields) ? entity.fields : {};
10933
11457
  for (const [key, field] of Object.entries(fields)) {
10934
- if (TECHNICAL_KEYS.has(key)) continue;
10935
- if (!field || typeof field !== "object") continue;
10936
- const colName = camelToSnake(key);
10937
- let sqlType;
10938
- const schema = field.validation?.schema;
10939
- if (schema && schemaRequiresJsonb(schema)) {
10940
- sqlType = "jsonb";
10941
- } else {
10942
- sqlType = fieldTypeToSql(field.type || "text") ?? inferSqlTypeFromValidation(field.validation);
11458
+ if (TECHNICAL_KEYS2.has(key)) continue;
11459
+ if (!isObjectLike(field)) continue;
11460
+ const described = descriptor.fields[key];
11461
+ if (!described) {
11462
+ throw new DoNotDevError(
11463
+ `${String(entity.name)}.${key}: no descriptor (field missing from describeEntity)`,
11464
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
11465
+ );
11466
+ }
11467
+ const colName = camelToSnake2(key);
11468
+ columns.push(`${colName} ${KIND_TO_SQL[described.value.kind]}`);
11469
+ if (field.i18n === true) {
11470
+ columns.push(`${colName}_i18n jsonb NOT NULL DEFAULT '{}'::jsonb`);
10943
11471
  }
10944
- columns.push(`${colName} ${sqlType}`);
10945
11472
  }
10946
11473
  const columnList = columns.join(",\n ");
10947
11474
  const createSql = `CREATE TABLE IF NOT EXISTS ${tableName} (
@@ -10952,7 +11479,7 @@ var init_sql_generator = __esm({
10952
11479
  `ALTER TABLE ${tableName} ALTER COLUMN id SET DEFAULT gen_random_uuid();`,
10953
11480
  `ALTER TABLE ${tableName} ALTER COLUMN created_at SET DEFAULT now();`,
10954
11481
  `ALTER TABLE ${tableName} ALTER COLUMN updated_at SET DEFAULT now();`,
10955
- `ALTER TABLE ${tableName} ALTER COLUMN status SET DEFAULT 'available';`
11482
+ `ALTER TABLE ${tableName} ALTER COLUMN status SET DEFAULT '${core.defaultStatus}';`
10956
11483
  ].join("\n");
10957
11484
  return `${createSql}
10958
11485
 
@@ -10960,6 +11487,20 @@ ${addColumns}
10960
11487
 
10961
11488
  ${alterDefaults}`;
10962
11489
  }
11490
+ /** CHECK constraints of the entity (design doc §5), one idempotent DO block each. */
11491
+ buildChecksSql(entity, core) {
11492
+ this.safeTableName(entity.collection);
11493
+ const checks = buildEntityChecks(
11494
+ entity,
11495
+ core.describeEntity(entity),
11496
+ core.hiddenStatuses
11497
+ );
11498
+ if (checks.length === 0) return "";
11499
+ return [
11500
+ `-- CHECK constraints for ${entity.collection} (NOT VALID: existing rows are not checked; list violations with \`dndev db-check\`, VALIDATE in a later migration)`,
11501
+ ...checks.map(checkConstraintSql)
11502
+ ].join("\n\n");
11503
+ }
10963
11504
  buildRlsSql(tableName, access) {
10964
11505
  const quoted = this.safeTableName(tableName);
10965
11506
  const readRole = access?.read ?? "guest";
@@ -11065,21 +11606,23 @@ CREATE TRIGGER ${auditTrigger}
11065
11606
  EXECUTE PROCEDURE set_audit_fields_${tableName}();
11066
11607
  `;
11067
11608
  }
11068
- async writeMigrationForEntity(entity, entityFileName, result) {
11069
- if (!entity?.name || !entity?.collection) {
11609
+ async writeMigrationForEntity(entity, entityFileName, core, result) {
11610
+ if (!isSqlEntity(entity)) {
11070
11611
  throw new DoNotDevError(
11071
11612
  `Entity in ${entityFileName} missing name or collection`,
11072
11613
  "generation-error"
11073
11614
  );
11074
11615
  }
11075
11616
  const tableName = entity.collection;
11076
- const tableSql = this.buildTableSql(entity);
11617
+ const tableSql = this.buildTableSql(entity, core);
11618
+ const checksSql = this.buildChecksSql(entity, core);
11077
11619
  const rlsSql = this.buildRlsSql(tableName, entity.access);
11078
11620
  const triggerSql = this.buildTriggerSqlPerTable(tableName);
11079
11621
  const content = `-- Auto-generated from entity: ${entity.name} (${entityFileName})
11080
11622
  -- Do not edit by hand; re-run SQL generator to regenerate.
11081
11623
 
11082
11624
  ${tableSql}
11625
+ ${checksSql}
11083
11626
  ${rlsSql}
11084
11627
  ${triggerSql}
11085
11628
  `;
@@ -11103,22 +11646,30 @@ ${triggerSql}
11103
11646
  entityModule,
11104
11647
  entityFileName
11105
11648
  );
11106
- if (entity?.name && entity?.collection) {
11107
- entities.push({ entity, fileName: entityFileName });
11649
+ if (isSqlEntity(entity)) {
11650
+ entities.push({ entity, fileName: entityFileName, path: entityFilePath });
11108
11651
  }
11109
11652
  } catch {
11110
11653
  continue;
11111
11654
  }
11112
11655
  }
11113
11656
  if (entities.length === 0) return;
11657
+ const core = await this.coreFor(entities[0].path);
11114
11658
  const parts = [
11115
11659
  "-- Auto-generated entity tables (Do not edit by hand; re-run SQL generator.)",
11116
11660
  ""
11117
11661
  ];
11118
11662
  for (const { entity } of entities) {
11119
- parts.push(this.buildTableSql(entity));
11663
+ parts.push(this.buildTableSql(entity, core));
11120
11664
  parts.push("");
11121
11665
  }
11666
+ for (const { entity } of entities) {
11667
+ const checksSql = this.buildChecksSql(entity, core);
11668
+ if (checksSql) {
11669
+ parts.push(checksSql);
11670
+ parts.push("");
11671
+ }
11672
+ }
11122
11673
  for (const { entity } of entities) {
11123
11674
  parts.push(this.buildRlsSql(entity.collection, entity.access));
11124
11675
  }
@@ -11211,7 +11762,7 @@ function writeEnvFile2(appDir, supabaseUrl, supabasePublicKey, framework) {
11211
11762
  `${prefix}${keyVar}=${supabasePublicKey}`
11212
11763
  ];
11213
11764
  const content = [
11214
- ...preserved.filter((l2) => l2.trim() !== ""),
11765
+ ...preserved.filter((l) => l.trim() !== ""),
11215
11766
  "",
11216
11767
  ...supabaseBlock,
11217
11768
  ""