@donotdev/cli 0.2.3 → 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 (30) hide show
  1. package/dependencies-matrix.json +27 -26
  2. package/dist/bin/commands/build.js +64 -2
  3. package/dist/bin/commands/bump.js +98 -13
  4. package/dist/bin/commands/db-check.js +192804 -0
  5. package/dist/bin/commands/db.js +16 -1
  6. package/dist/bin/commands/make-admin.js +22 -6
  7. package/dist/bin/commands/seed.js +313 -236
  8. package/dist/bin/commands/setup.js +549 -97
  9. package/dist/bin/dndev.js +23 -7
  10. package/dist/index.js +64 -2
  11. package/package.json +1 -1
  12. package/templates/app-demo/index.html.example +1 -1
  13. package/templates/app-dndev/index.html.example +1 -1
  14. package/templates/app-dndev/src/globals.css.example +1 -1
  15. package/templates/app-next/src/app/AppDocument.tsx.example +3 -2
  16. package/templates/app-next/src/globals.css.example +1 -1
  17. package/templates/app-vite/csp.example.json +1 -1
  18. package/templates/app-vite/index.html.example +1 -1
  19. package/templates/app-vite/src/globals.css.example +1 -1
  20. package/templates/deploy-config/vercel.json.example +2 -2
  21. package/templates/functions-supabase/supabase/migrations/20250101000006_crud_bulk_status_guard.sql +258 -0
  22. package/templates/functions-supabase/supabase/migrations/20250101000007_rate_limit_check.sql +76 -0
  23. package/templates/root-consumer/.claude/hooks/guard-bash.sh.example +3 -3
  24. package/templates/root-consumer/.claude/hooks/typecheck-stop.sh.example +2 -2
  25. package/templates/root-consumer/.claude/rules/definition-of-done.md.example +2 -2
  26. package/templates/root-consumer/.claude/rules/framework.md.example +1 -1
  27. package/templates/root-consumer/.claude/skills/build/SKILL.md.example +1 -1
  28. package/templates/root-consumer/.claude/skills/polish/SKILL.md.example +1 -1
  29. package/templates/root-consumer/AGENTS.md.example +25 -2
  30. package/templates/root-consumer/README.md.example +1 -1
@@ -10802,6 +10802,493 @@ var init_base_generator = __esm({
10802
10802
  }
10803
10803
  });
10804
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
+
10805
11292
  // packages/tooling/src/generators/sql-generator.ts
10806
11293
  var sql_generator_exports = {};
10807
11294
  __export(sql_generator_exports, {
@@ -10828,43 +11315,9 @@ function roleToSqlCondition(role) {
10828
11315
  return "false";
10829
11316
  }
10830
11317
  }
10831
- function camelToSnake(str) {
11318
+ function camelToSnake2(str) {
10832
11319
  return str.replace(/[A-Z]/g, (c3) => `_${c3.toLowerCase()}`);
10833
11320
  }
10834
- function fieldTypeToSql(fieldType) {
10835
- return FIELD_TYPE_TO_SQL[fieldType] ?? null;
10836
- }
10837
- function inferSqlTypeFromValidation(validation) {
10838
- if (!validation) return "text";
10839
- if (validation.min !== void 0 || validation.max !== void 0)
10840
- return "numeric";
10841
- if (validation.minLength !== void 0 || validation.maxLength !== void 0)
10842
- return "text";
10843
- if (Array.isArray(validation.options) && validation.options.length > 0) {
10844
- const first = validation.options[0];
10845
- if (isObjectLike(first) && typeof first.value === "number")
10846
- return "numeric";
10847
- }
10848
- return "text";
10849
- }
10850
- function schemaRequiresJsonb(schema) {
10851
- if (!isObjectLike(schema)) return false;
10852
- const s = schema;
10853
- const kind = s.type ?? s.kind ?? s._tag;
10854
- if (typeof kind === "string") {
10855
- if (kind === "array" || kind === "object") return true;
10856
- if (kind === "optional" || kind === "nullable" || kind === "nullish") {
10857
- return schemaRequiresJsonb(s.wrapped);
10858
- }
10859
- if (kind === "pipe" || kind === "union" || kind === "intersect") {
10860
- const items = s.pipe ?? s.items ?? s.options;
10861
- if (Array.isArray(items) && items.length > 0) {
10862
- return schemaRequiresJsonb(items[0]);
10863
- }
10864
- }
10865
- }
10866
- return false;
10867
- }
10868
11321
  async function main2() {
10869
11322
  try {
10870
11323
  const envEntityDir = process.env.ENTITY_DIR;
@@ -10885,13 +11338,15 @@ async function main2() {
10885
11338
  process.exit(1);
10886
11339
  }
10887
11340
  }
10888
- var HIDDEN_STATUSES, ROLE_LEVEL, FIELD_TYPE_TO_SQL, TECHNICAL_KEYS, SqlGenerator;
11341
+ var HIDDEN_STATUSES, ROLE_LEVEL, KIND_TO_SQL, TECHNICAL_KEYS2, SqlGenerator;
10889
11342
  var init_sql_generator = __esm({
10890
11343
  "packages/tooling/src/generators/sql-generator.ts"() {
10891
11344
  "use strict";
10892
11345
  init_utils2();
10893
11346
  init_base_generator();
11347
+ init_sqlChecks();
10894
11348
  init_cli_output();
11349
+ init_coreSemantics();
10895
11350
  init_errors();
10896
11351
  init_pathResolver();
10897
11352
  init_type_guards();
@@ -10902,56 +11357,18 @@ var init_sql_generator = __esm({
10902
11357
  admin: 2,
10903
11358
  super: 3
10904
11359
  };
10905
- FIELD_TYPE_TO_SQL = {
11360
+ KIND_TO_SQL = {
10906
11361
  text: "text",
10907
- textarea: "text",
10908
- email: "text",
10909
- tel: "text",
10910
- url: "text",
10911
- password: "text",
10912
- hidden: "text",
10913
- badge: "text",
10914
- avatar: "text",
10915
- combobox: "text",
10916
- reset: "text",
10917
- submit: "text",
10918
11362
  number: "numeric",
10919
- range: "numeric",
10920
- rating: "numeric",
10921
- currency: "numeric",
10922
- price: "jsonb",
11363
+ integer: "integer",
10923
11364
  boolean: "boolean",
10924
- checkbox: "boolean",
10925
- switch: "boolean",
10926
11365
  date: "date",
10927
11366
  time: "time",
10928
- month: "date",
10929
- week: "date",
10930
- year: "integer",
10931
- "datetime-local": "timestamptz",
10932
11367
  timestamp: "timestamptz",
10933
- reference: "uuid",
10934
- select: "text",
10935
- radio: "text",
10936
- status: "text",
10937
- multiselect: "jsonb",
10938
- image: "text",
10939
- images: "jsonb",
10940
- file: "text",
10941
- files: "jsonb",
10942
- document: "text",
10943
- documents: "jsonb",
10944
- geopoint: "jsonb",
10945
- address: "jsonb",
10946
- map: "jsonb",
10947
- array: "jsonb",
10948
- color: "text",
10949
- iban: "text",
10950
- richtext: "text",
10951
- duration: "numeric",
10952
- gdprConsent: "boolean"
11368
+ json: "jsonb",
11369
+ ref: "uuid"
10953
11370
  };
10954
- TECHNICAL_KEYS = /* @__PURE__ */ new Set([
11371
+ TECHNICAL_KEYS2 = /* @__PURE__ */ new Set([
10955
11372
  "id",
10956
11373
  "createdAt",
10957
11374
  "updatedAt",
@@ -10961,6 +11378,7 @@ var init_sql_generator = __esm({
10961
11378
  ]);
10962
11379
  SqlGenerator = class extends BaseGenerator {
10963
11380
  singleFile;
11381
+ core;
10964
11382
  constructor(options = {}) {
10965
11383
  super("SQL", {
10966
11384
  entityDirs: options.entityDir ? [options.entityDir] : void 0,
@@ -10971,6 +11389,11 @@ var init_sql_generator = __esm({
10971
11389
  });
10972
11390
  this.singleFile = options.singleFile !== false;
10973
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
+ }
10974
11397
  async processEntityFile(entityFilePath, result) {
10975
11398
  const entityFileName = getBasename(entityFilePath, ".ts");
10976
11399
  let entityModule;
@@ -10989,7 +11412,12 @@ var init_sql_generator = __esm({
10989
11412
  if (this.singleFile) {
10990
11413
  return resolvedName;
10991
11414
  }
10992
- await this.writeMigrationForEntity(entity, entityFileName, result);
11415
+ await this.writeMigrationForEntity(
11416
+ entity,
11417
+ entityFileName,
11418
+ await this.coreFor(entityFilePath),
11419
+ result
11420
+ );
10993
11421
  return resolvedName;
10994
11422
  }
10995
11423
  extractEntityFromModule(entityModule, fileName) {
@@ -11015,29 +11443,29 @@ var init_sql_generator = __esm({
11015
11443
  }
11016
11444
  return `"${collection.replace(/"/g, '""')}"`;
11017
11445
  }
11018
- buildTableSql(entity) {
11446
+ buildTableSql(entity, core) {
11019
11447
  const tableName = this.safeTableName(entity.collection);
11448
+ const descriptor = core.describeEntity(entity);
11020
11449
  const columns = [];
11021
11450
  columns.push("id uuid PRIMARY KEY DEFAULT gen_random_uuid()");
11022
11451
  columns.push("created_at timestamptz NOT NULL DEFAULT now()");
11023
11452
  columns.push("updated_at timestamptz NOT NULL DEFAULT now()");
11024
11453
  columns.push("created_by_id uuid");
11025
11454
  columns.push("updated_by_id uuid");
11026
- columns.push("status text NOT NULL DEFAULT 'available'");
11455
+ columns.push(`status text NOT NULL DEFAULT '${core.defaultStatus}'`);
11027
11456
  const fields = isObjectLike(entity.fields) ? entity.fields : {};
11028
11457
  for (const [key, field] of Object.entries(fields)) {
11029
- if (TECHNICAL_KEYS.has(key)) continue;
11458
+ if (TECHNICAL_KEYS2.has(key)) continue;
11030
11459
  if (!isObjectLike(field)) continue;
11031
- const colName = camelToSnake(key);
11032
- let sqlType;
11033
- const validation = isObjectLike(field.validation) ? field.validation : void 0;
11034
- const schema = validation?.schema;
11035
- if (schema && schemaRequiresJsonb(schema)) {
11036
- sqlType = "jsonb";
11037
- } else {
11038
- sqlType = fieldTypeToSql(String(field.type || "text")) ?? inferSqlTypeFromValidation(validation);
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
+ );
11039
11466
  }
11040
- columns.push(`${colName} ${sqlType}`);
11467
+ const colName = camelToSnake2(key);
11468
+ columns.push(`${colName} ${KIND_TO_SQL[described.value.kind]}`);
11041
11469
  if (field.i18n === true) {
11042
11470
  columns.push(`${colName}_i18n jsonb NOT NULL DEFAULT '{}'::jsonb`);
11043
11471
  }
@@ -11051,7 +11479,7 @@ var init_sql_generator = __esm({
11051
11479
  `ALTER TABLE ${tableName} ALTER COLUMN id SET DEFAULT gen_random_uuid();`,
11052
11480
  `ALTER TABLE ${tableName} ALTER COLUMN created_at SET DEFAULT now();`,
11053
11481
  `ALTER TABLE ${tableName} ALTER COLUMN updated_at SET DEFAULT now();`,
11054
- `ALTER TABLE ${tableName} ALTER COLUMN status SET DEFAULT 'available';`
11482
+ `ALTER TABLE ${tableName} ALTER COLUMN status SET DEFAULT '${core.defaultStatus}';`
11055
11483
  ].join("\n");
11056
11484
  return `${createSql}
11057
11485
 
@@ -11059,6 +11487,20 @@ ${addColumns}
11059
11487
 
11060
11488
  ${alterDefaults}`;
11061
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
+ }
11062
11504
  buildRlsSql(tableName, access) {
11063
11505
  const quoted = this.safeTableName(tableName);
11064
11506
  const readRole = access?.read ?? "guest";
@@ -11164,7 +11606,7 @@ CREATE TRIGGER ${auditTrigger}
11164
11606
  EXECUTE PROCEDURE set_audit_fields_${tableName}();
11165
11607
  `;
11166
11608
  }
11167
- async writeMigrationForEntity(entity, entityFileName, result) {
11609
+ async writeMigrationForEntity(entity, entityFileName, core, result) {
11168
11610
  if (!isSqlEntity(entity)) {
11169
11611
  throw new DoNotDevError(
11170
11612
  `Entity in ${entityFileName} missing name or collection`,
@@ -11172,13 +11614,15 @@ CREATE TRIGGER ${auditTrigger}
11172
11614
  );
11173
11615
  }
11174
11616
  const tableName = entity.collection;
11175
- const tableSql = this.buildTableSql(entity);
11617
+ const tableSql = this.buildTableSql(entity, core);
11618
+ const checksSql = this.buildChecksSql(entity, core);
11176
11619
  const rlsSql = this.buildRlsSql(tableName, entity.access);
11177
11620
  const triggerSql = this.buildTriggerSqlPerTable(tableName);
11178
11621
  const content = `-- Auto-generated from entity: ${entity.name} (${entityFileName})
11179
11622
  -- Do not edit by hand; re-run SQL generator to regenerate.
11180
11623
 
11181
11624
  ${tableSql}
11625
+ ${checksSql}
11182
11626
  ${rlsSql}
11183
11627
  ${triggerSql}
11184
11628
  `;
@@ -11203,21 +11647,29 @@ ${triggerSql}
11203
11647
  entityFileName
11204
11648
  );
11205
11649
  if (isSqlEntity(entity)) {
11206
- entities.push({ entity, fileName: entityFileName });
11650
+ entities.push({ entity, fileName: entityFileName, path: entityFilePath });
11207
11651
  }
11208
11652
  } catch {
11209
11653
  continue;
11210
11654
  }
11211
11655
  }
11212
11656
  if (entities.length === 0) return;
11657
+ const core = await this.coreFor(entities[0].path);
11213
11658
  const parts = [
11214
11659
  "-- Auto-generated entity tables (Do not edit by hand; re-run SQL generator.)",
11215
11660
  ""
11216
11661
  ];
11217
11662
  for (const { entity } of entities) {
11218
- parts.push(this.buildTableSql(entity));
11663
+ parts.push(this.buildTableSql(entity, core));
11219
11664
  parts.push("");
11220
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
+ }
11221
11673
  for (const { entity } of entities) {
11222
11674
  parts.push(this.buildRlsSql(entity.collection, entity.access));
11223
11675
  }