@meghjs/cli 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,398 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readMigrationSchema = readMigrationSchema;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const EXTENSIONS = /\.(c?js|mjs|c?ts|mts)$/;
10
+ const DECLARATION = /\.d\.[cm]?ts$/;
11
+ /** Every table the migrations in `folder` leave behind, keyed by name. */
12
+ function readMigrationSchema(folder) {
13
+ const tables = new Map();
14
+ if (!fs_1.default.existsSync(folder))
15
+ return tables;
16
+ const files = fs_1.default
17
+ .readdirSync(folder)
18
+ .filter((f) => EXTENSIONS.test(f) && !DECLARATION.test(f))
19
+ .sort();
20
+ for (const file of files) {
21
+ applyMigration(tables, upSource(fs_1.default.readFileSync(path_1.default.join(folder, file), "utf8")), file);
22
+ }
23
+ return tables;
24
+ }
25
+ /** The `up()` part of a migration: everything before `down`. */
26
+ function upSource(source) {
27
+ const code = stripComments(source);
28
+ const down = code.search(/\b(?:function\s+down\b|down\s*[:=(])/);
29
+ return down === -1 ? code : code.slice(0, down);
30
+ }
31
+ /** Drop `//` and `/* *\/` comments, keeping string contents intact. */
32
+ function stripComments(source) {
33
+ let out = "";
34
+ for (let i = 0; i < source.length; i++) {
35
+ const ch = source[i];
36
+ if (ch === '"' || ch === "'" || ch === "`") {
37
+ const end = skipString(source, i);
38
+ out += source.slice(i, end + 1);
39
+ i = end;
40
+ }
41
+ else if (ch === "/" && source[i + 1] === "/") {
42
+ while (i < source.length && source[i] !== "\n")
43
+ i++;
44
+ out += "\n";
45
+ }
46
+ else if (ch === "/" && source[i + 1] === "*") {
47
+ const end = source.indexOf("*/", i + 2);
48
+ i = end === -1 ? source.length : end + 1;
49
+ }
50
+ else {
51
+ out += ch;
52
+ }
53
+ }
54
+ return out;
55
+ }
56
+ /** Index of the closing quote of the string starting at `start`. */
57
+ function skipString(text, start) {
58
+ const quote = text[start];
59
+ for (let i = start + 1; i < text.length; i++) {
60
+ if (text[i] === "\\")
61
+ i++;
62
+ else if (text[i] === quote)
63
+ return i;
64
+ }
65
+ return text.length - 1;
66
+ }
67
+ /** The text between the `(` at `open` and its matching `)`, and the index after it. */
68
+ function readCall(text, open) {
69
+ let depth = 0;
70
+ for (let i = open; i < text.length; i++) {
71
+ const ch = text[i];
72
+ if (ch === '"' || ch === "'" || ch === "`")
73
+ i = skipString(text, i);
74
+ else if (ch === "(" || ch === "[" || ch === "{")
75
+ depth++;
76
+ else if (ch === ")" || ch === "]" || ch === "}") {
77
+ depth--;
78
+ if (depth === 0)
79
+ return { inner: text.slice(open + 1, i), end: i + 1 };
80
+ }
81
+ }
82
+ return { inner: text.slice(open + 1), end: text.length };
83
+ }
84
+ /** Split call arguments on top-level commas. */
85
+ function splitArgs(inner) {
86
+ const args = [];
87
+ let depth = 0;
88
+ let start = 0;
89
+ for (let i = 0; i < inner.length; i++) {
90
+ const ch = inner[i];
91
+ if (ch === '"' || ch === "'" || ch === "`")
92
+ i = skipString(inner, i);
93
+ else if (ch === "(" || ch === "[" || ch === "{")
94
+ depth++;
95
+ else if (ch === ")" || ch === "]" || ch === "}")
96
+ depth--;
97
+ else if (ch === "," && depth === 0) {
98
+ args.push(inner.slice(start, i).trim());
99
+ start = i + 1;
100
+ }
101
+ }
102
+ const last = inner.slice(start).trim();
103
+ if (last)
104
+ args.push(last);
105
+ return args;
106
+ }
107
+ /** The value of a plain string literal (no `${}`), else `undefined`. */
108
+ function literal(arg) {
109
+ const m = arg?.match(/^(["'`])((?:\\.|(?!\1).)*)\1$/s);
110
+ if (!m || (m[1] === "`" && m[2].includes("${")))
111
+ return undefined;
112
+ return m[2];
113
+ }
114
+ /** A column data type argument: `"text"`, `sql\`varchar(255)\``, … */
115
+ function dataType(arg) {
116
+ if (!arg)
117
+ return "";
118
+ const plain = literal(arg);
119
+ if (plain !== undefined)
120
+ return plain.trim().toLowerCase();
121
+ const raw = arg.match(/^sql(?:\.raw)?\s*(?:`([^`$]*)`|\(\s*["'`]([^"'`$]*)["'`]\s*\))$/);
122
+ return (raw?.[1] ?? raw?.[2] ?? "").trim().toLowerCase();
123
+ }
124
+ /** Table name without a schema prefix: `public.users` → `users`. */
125
+ function tableName(arg) {
126
+ const name = literal(arg);
127
+ return name?.split(".").pop();
128
+ }
129
+ const STATEMENT = /\.(createTable|alterTable|dropTable)\s*\(/g;
130
+ const COLUMN_CALL = /\.(addColumn|modifyColumn|dropColumn|renameColumn|alterColumn|renameTo|addPrimaryKeyConstraint)\s*\(/g;
131
+ function applyMigration(tables, code, file) {
132
+ if (/\bdefineMigration\s*\(/.test(code)) {
133
+ applySchemaMigration(tables, code, file);
134
+ return;
135
+ }
136
+ const statements = [...code.matchAll(STATEMENT)];
137
+ statements.forEach((match, index) => {
138
+ const open = match.index + match[0].length - 1;
139
+ const { inner, end } = readCall(code, open);
140
+ const name = tableName(splitArgs(inner)[0]);
141
+ if (!name)
142
+ return;
143
+ const kind = match[1];
144
+ if (kind === "dropTable") {
145
+ tables.delete(name);
146
+ return;
147
+ }
148
+ // The chain runs until the next schema statement.
149
+ const chainEnd = index + 1 < statements.length ? statements[index + 1].index : code.length;
150
+ const chain = code.slice(end, chainEnd);
151
+ let table = tables.get(name);
152
+ if (kind === "createTable") {
153
+ table = { name, columns: [], createdIn: file };
154
+ tables.set(name, table);
155
+ }
156
+ if (table)
157
+ applyChain(tables, table, chain);
158
+ });
159
+ }
160
+ function applyChain(tables, table, chain) {
161
+ for (const match of chain.matchAll(COLUMN_CALL)) {
162
+ const open = match.index + match[0].length - 1;
163
+ const args = splitArgs(readCall(chain, open).inner);
164
+ const name = literal(args[0]);
165
+ const index = name === undefined ? -1 : table.columns.findIndex((c) => c.name === name);
166
+ switch (match[1]) {
167
+ case "addColumn":
168
+ case "modifyColumn": {
169
+ if (name === undefined)
170
+ break;
171
+ const column = parseColumn(name, args[1], args[2] ?? "");
172
+ if (index === -1)
173
+ table.columns.push(column);
174
+ else
175
+ table.columns[index] = column;
176
+ break;
177
+ }
178
+ case "dropColumn":
179
+ if (index !== -1)
180
+ table.columns.splice(index, 1);
181
+ break;
182
+ case "renameColumn": {
183
+ const to = literal(args[1]);
184
+ if (index !== -1 && to)
185
+ table.columns[index] = { ...table.columns[index], name: to };
186
+ break;
187
+ }
188
+ case "alterColumn": {
189
+ if (index === -1)
190
+ break;
191
+ const column = table.columns[index];
192
+ const change = args[1] ?? "";
193
+ const setType = change.match(/\.setDataType\s*\(([^)]*)\)/);
194
+ if (setType)
195
+ column.type = dataType(setType[1].trim());
196
+ if (/\.setNotNull\s*\(/.test(change))
197
+ column.notNull = true;
198
+ if (/\.dropNotNull\s*\(/.test(change))
199
+ column.notNull = false;
200
+ if (/\.setDefault\s*\(/.test(change))
201
+ column.generated = true;
202
+ if (/\.dropDefault\s*\(/.test(change))
203
+ column.generated = column.autoIncrement;
204
+ break;
205
+ }
206
+ case "renameTo": {
207
+ if (name === undefined)
208
+ break;
209
+ tables.delete(table.name);
210
+ table.name = name;
211
+ tables.set(name, table);
212
+ break;
213
+ }
214
+ case "addPrimaryKeyConstraint": {
215
+ const columns = (args[1]?.match(/["'`][^"'`]+["'`]/g) ?? []).map((c) => c.slice(1, -1));
216
+ for (const column of table.columns) {
217
+ if (columns.includes(column.name)) {
218
+ column.primaryKey = true;
219
+ column.notNull = true;
220
+ }
221
+ }
222
+ break;
223
+ }
224
+ }
225
+ }
226
+ }
227
+ function parseColumn(name, typeArg, build) {
228
+ const type = dataType(typeArg);
229
+ const autoIncrement = /\.(autoIncrement|identity|generatedAlwaysAsIdentity|generatedByDefaultAsIdentity)\s*\(/.test(build) ||
230
+ /^(small|big)?serial\d?$/.test(type);
231
+ const primaryKey = /\.primaryKey\s*\(/.test(build);
232
+ return {
233
+ name,
234
+ type,
235
+ notNull: primaryKey || autoIncrement || /\.notNull\s*\(/.test(build),
236
+ primaryKey,
237
+ autoIncrement,
238
+ generated: autoIncrement || /\.(defaultTo|generatedAlwaysAs)\s*\(/.test(build),
239
+ };
240
+ }
241
+ // ── Megh's schema builder (defineMigration) ──────────────────────────────
242
+ const SCHEMA_STATEMENT = /\b\w+\s*\.\s*(create|table|drop|dropIfExists|rename)\s*\(/g;
243
+ /** SQL types the builder's column methods create, as `fieldType` reads them. */
244
+ const BUILDER_TYPES = {
245
+ id: "integer",
246
+ increments: "integer",
247
+ bigIncrements: "bigint",
248
+ string: "varchar",
249
+ text: "text",
250
+ integer: "integer",
251
+ bigInteger: "bigint",
252
+ float: "real",
253
+ double: "double precision",
254
+ decimal: "numeric",
255
+ boolean: "boolean",
256
+ date: "date",
257
+ datetime: "timestamp",
258
+ timestamp: "timestamptz",
259
+ time: "time",
260
+ json: "json",
261
+ uuid: "uuid",
262
+ binary: "blob",
263
+ foreignId: "integer",
264
+ };
265
+ function applySchemaMigration(tables, code, file) {
266
+ for (const match of code.matchAll(SCHEMA_STATEMENT)) {
267
+ const open = match.index + match[0].length - 1;
268
+ const args = splitArgs(readCall(code, open).inner);
269
+ const name = tableName(args[0]);
270
+ if (!name)
271
+ continue;
272
+ switch (match[1]) {
273
+ case "drop":
274
+ case "dropIfExists":
275
+ tables.delete(name);
276
+ break;
277
+ case "rename": {
278
+ const to = tableName(args[1]);
279
+ const table = tables.get(name);
280
+ if (!to || !table)
281
+ break;
282
+ tables.delete(name);
283
+ table.name = to;
284
+ tables.set(to, table);
285
+ break;
286
+ }
287
+ case "create": {
288
+ const table = { name, columns: [], createdIn: file };
289
+ tables.set(name, table);
290
+ applyBlueprint(table, args[1]);
291
+ break;
292
+ }
293
+ case "table": {
294
+ const table = tables.get(name);
295
+ if (table)
296
+ applyBlueprint(table, args[1]);
297
+ break;
298
+ }
299
+ }
300
+ }
301
+ }
302
+ /** Replay the calls in `(table) => { … }` on `table`. */
303
+ function applyBlueprint(table, callback) {
304
+ const head = callback?.match(/^(?:async\s+)?\(?\s*([A-Za-z_$][\w$]*)\s*(?::[^)=]*)?\)?\s*=>/);
305
+ if (!callback || !head)
306
+ return;
307
+ const param = head[1].replace(/[$]/g, String.raw `\$`);
308
+ const body = callback.slice(head[0].length);
309
+ const calls = [...body.matchAll(new RegExp(String.raw `(?<![\w$.])${param}\s*\.\s*(\w+)\s*\(`, "g"))];
310
+ calls.forEach((call, i) => {
311
+ const open = call.index + call[0].length - 1;
312
+ const { inner, end } = readCall(body, open);
313
+ const args = splitArgs(inner);
314
+ // Modifiers run until the next call on the blueprint.
315
+ const chain = body.slice(end, i + 1 < calls.length ? calls[i + 1].index : body.length);
316
+ applyBlueprintCall(table, call[1], args, chain);
317
+ });
318
+ }
319
+ function setColumn(table, column) {
320
+ const index = table.columns.findIndex((c) => c.name === column.name);
321
+ if (index === -1)
322
+ table.columns.push(column);
323
+ else
324
+ table.columns[index] = column;
325
+ }
326
+ function applyBlueprintCall(table, method, args, chain) {
327
+ const name = literal(args[0]);
328
+ const drop = (column) => {
329
+ const index = table.columns.findIndex((c) => c.name === column);
330
+ if (index !== -1)
331
+ table.columns.splice(index, 1);
332
+ };
333
+ switch (method) {
334
+ case "timestamps":
335
+ for (const column of ["created_at", "updated_at"]) {
336
+ setColumn(table, { name: column, type: "timestamptz", notNull: false, primaryKey: false, generated: false, autoIncrement: false });
337
+ }
338
+ return;
339
+ case "softDeletes":
340
+ setColumn(table, {
341
+ name: name ?? "deleted_at",
342
+ type: "timestamptz",
343
+ notNull: false,
344
+ primaryKey: false,
345
+ generated: false,
346
+ autoIncrement: false,
347
+ });
348
+ return;
349
+ case "dropColumn":
350
+ for (const arg of args) {
351
+ const column = literal(arg);
352
+ if (column)
353
+ drop(column);
354
+ }
355
+ return;
356
+ case "dropTimestamps":
357
+ drop("created_at");
358
+ drop("updated_at");
359
+ return;
360
+ case "dropSoftDeletes":
361
+ drop(name ?? "deleted_at");
362
+ return;
363
+ case "renameColumn": {
364
+ const to = literal(args[1]);
365
+ const column = table.columns.find((c) => c.name === name);
366
+ if (column && to)
367
+ column.name = to;
368
+ return;
369
+ }
370
+ case "primary": {
371
+ const columns = (args[0]?.match(/["'`][^"'`]+["'`]/g) ?? []).map((c) => c.slice(1, -1));
372
+ for (const column of table.columns) {
373
+ if (columns.includes(column.name)) {
374
+ column.primaryKey = true;
375
+ column.notNull = true;
376
+ }
377
+ }
378
+ return;
379
+ }
380
+ }
381
+ const type = BUILDER_TYPES[method];
382
+ if (!type)
383
+ return;
384
+ const columnName = name ?? (method === "id" ? "id" : undefined);
385
+ if (!columnName)
386
+ return;
387
+ const autoIncrement = /^(id|increments|bigIncrements)$/.test(method) || /\.autoIncrement\s*\(/.test(chain);
388
+ const primaryKey = autoIncrement || /\.primary\s*\(/.test(chain);
389
+ const nullable = /\.nullable\s*\(\s*(true)?\s*\)/.test(chain) || /\.nullOnDelete\s*\(/.test(chain);
390
+ setColumn(table, {
391
+ name: columnName,
392
+ type,
393
+ notNull: primaryKey || !nullable,
394
+ primaryKey,
395
+ autoIncrement,
396
+ generated: autoIncrement || /\.(default|useCurrent)\s*\(/.test(chain),
397
+ });
398
+ }
@@ -0,0 +1,23 @@
1
+ import type { MigrationTable } from "./migration-schema";
2
+ /** Plural of a snake_case name, inflecting the last word: `blog_post` → `blog_posts`. */
3
+ export declare function pluralize(snake: string): string;
4
+ /**
5
+ * Singular of a snake_case name, inflecting the last word: `blog_posts` → `blog_post`.
6
+ * Leaves already-singular words alone (including `status`, which must not become `statu`).
7
+ * Only accepts a candidate when `pluralize(candidate)` rebuilds `snake`.
8
+ */
9
+ export declare function singularize(snake: string): string;
10
+ /** Plural form for a route segment, even when `snake` is already plural. */
11
+ export declare function pluralRoute(snake: string): string;
12
+ type Cast = "boolean" | "number" | "json" | "date" | "datetime";
13
+ interface FieldType {
14
+ ts: string;
15
+ cast?: Cast;
16
+ }
17
+ /** TypeScript type (and cast) for a column's SQL data type. */
18
+ export declare function fieldType(sqlType: string): FieldType;
19
+ /** A model class for `table`, declaring the columns its migrations create. */
20
+ export declare function renderOrmModel(model: string, table: MigrationTable): string;
21
+ /** A model class for a table with no migration yet: placeholder columns. */
22
+ export declare function renderBlankOrmModel(model: string, table: string): string;
23
+ export {};
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pluralize = pluralize;
4
+ exports.singularize = singularize;
5
+ exports.pluralRoute = pluralRoute;
6
+ exports.fieldType = fieldType;
7
+ exports.renderOrmModel = renderOrmModel;
8
+ exports.renderBlankOrmModel = renderBlankOrmModel;
9
+ const stubs_1 = require("../utils/stubs");
10
+ /**
11
+ * Renders a Megh ORM model (`class X extends Model`), with its columns taken
12
+ * from the table's migrations when there are any.
13
+ */
14
+ const IRREGULAR = {
15
+ person: "people",
16
+ child: "children",
17
+ man: "men",
18
+ woman: "women",
19
+ mouse: "mice",
20
+ datum: "data",
21
+ };
22
+ /** Plural of a snake_case name, inflecting the last word: `blog_post` → `blog_posts`. */
23
+ function pluralize(snake) {
24
+ const parts = snake.split("_");
25
+ const last = parts.pop() ?? "";
26
+ let plural;
27
+ if (IRREGULAR[last])
28
+ plural = IRREGULAR[last];
29
+ else if (/[^aeiou]y$/.test(last))
30
+ plural = last.slice(0, -1) + "ies";
31
+ else if (/(s|x|z|ch|sh)$/.test(last))
32
+ plural = last + "es";
33
+ else
34
+ plural = last + "s";
35
+ return [...parts, plural].join("_");
36
+ }
37
+ const IRREGULAR_SINGULAR = Object.fromEntries(Object.entries(IRREGULAR).map(([singular, plural]) => [plural, singular]));
38
+ /**
39
+ * Singular of a snake_case name, inflecting the last word: `blog_posts` → `blog_post`.
40
+ * Leaves already-singular words alone (including `status`, which must not become `statu`).
41
+ * Only accepts a candidate when `pluralize(candidate)` rebuilds `snake`.
42
+ */
43
+ function singularize(snake) {
44
+ const parts = snake.split("_");
45
+ const last = parts.pop() ?? "";
46
+ const take = (candidate) => (pluralize(candidate) === last ? candidate : null);
47
+ let singular = null;
48
+ if (IRREGULAR_SINGULAR[last])
49
+ singular = IRREGULAR_SINGULAR[last];
50
+ else if (/ies$/.test(last) && last.length > 3)
51
+ singular = take(last.slice(0, -3) + "y");
52
+ else if (/(?:s|x|z|ch|sh)es$/.test(last))
53
+ singular = take(last.slice(0, -2));
54
+ if (!singular && /s$/.test(last) && !/(?:us|ss|is|ous)$/.test(last)) {
55
+ singular = take(last.slice(0, -1));
56
+ }
57
+ return [...parts, singular ?? last].join("_");
58
+ }
59
+ /** Plural form for a route segment, even when `snake` is already plural. */
60
+ function pluralRoute(snake) {
61
+ return pluralize(singularize(snake));
62
+ }
63
+ /** TypeScript type (and cast) for a column's SQL data type. */
64
+ function fieldType(sqlType) {
65
+ const base = sqlType.replace(/\(.*$/, "").trim();
66
+ if (/^(tinyint|bool|boolean|bit)$/.test(base)) {
67
+ // MySQL tinyint(1) and SQLite integers hold booleans as 0/1.
68
+ if (base !== "tinyint" || /^tinyint\(1\)/.test(sqlType))
69
+ return { ts: "boolean", cast: "boolean" };
70
+ }
71
+ if (/^(int\d?|integer|smallint|mediumint|tinyint|bigint|serial\d?|smallserial|bigserial)$/.test(base)) {
72
+ // Postgres returns bigint as a string; the cast turns it back into a number.
73
+ return /big/.test(base) ? { ts: "number", cast: "number" } : { ts: "number" };
74
+ }
75
+ if (/^(real|float\d?|double|double precision|decimal|numeric|money)$/.test(base)) {
76
+ return { ts: "number", cast: "number" };
77
+ }
78
+ if (base === "date")
79
+ return { ts: "Date", cast: "date" };
80
+ if (/^(timestamp|timestamptz|timestamp with(out)? time zone|datetime|datetime2|datetimeoffset|smalldatetime)$/.test(base)) {
81
+ return { ts: "Date", cast: "datetime" };
82
+ }
83
+ if (/^(text|tinytext|mediumtext|longtext|varchar|char|character|character varying|nvarchar|nchar|ntext|uuid|citext|enum|inet|cidr|macaddr|time|timetz|time with(out)? time zone|interval)$/.test(base)) {
84
+ return { ts: "string" };
85
+ }
86
+ if (/^jsonb?$/.test(base))
87
+ return { ts: "Record<string, unknown>", cast: "json" };
88
+ if (/^(blob|bytea|binary|varbinary|longblob|mediumblob|tinyblob|image)$/.test(base)) {
89
+ return { ts: "Buffer" };
90
+ }
91
+ return { ts: "unknown" };
92
+ }
93
+ /** Columns with their own decorator, filled in by the ORM. */
94
+ const TIMESTAMP_DECORATORS = {
95
+ created_at: "CreatedAt",
96
+ updated_at: "UpdatedAt",
97
+ deleted_at: "DeletedAt",
98
+ };
99
+ /** Column type for a cast, so the column converts its values. */
100
+ const CAST_TYPES = {
101
+ boolean: "boolean",
102
+ json: "json",
103
+ date: "date",
104
+ datetime: "datetime",
105
+ };
106
+ /** A model class for `table`, declaring the columns its migrations create. */
107
+ function renderOrmModel(model, table) {
108
+ const imports = new Set(["Model", "Table"]);
109
+ const fields = table.columns.map((column) => {
110
+ const { decorators, field } = renderField(column);
111
+ for (const d of decorators)
112
+ imports.add(d.match(/^@(\w+)/)[1]);
113
+ return `${decorators.join(" ")} ${field}`;
114
+ });
115
+ return (0, stubs_1.renderStub)("models/orm-model.stub", {
116
+ imports: [...imports].sort().join(", "),
117
+ Model: model,
118
+ table: q(table.name),
119
+ source: table.createdIn,
120
+ fields: fields.join("\n "),
121
+ });
122
+ }
123
+ /** The decorators and declaration of one column. */
124
+ function renderField(column) {
125
+ const { ts, cast } = fieldType(column.type);
126
+ const name = property(column.name);
127
+ const timestamp = TIMESTAMP_DECORATORS[column.name];
128
+ if (timestamp && ts === "Date") {
129
+ const type = timestamp === "DeletedAt" ? "Date | null" : "Date";
130
+ return { decorators: [`@${timestamp}()`], field: `${name}?: ${type};` };
131
+ }
132
+ const decorators = [];
133
+ if (column.primaryKey)
134
+ decorators.push("@PrimaryKey()");
135
+ if (column.autoIncrement)
136
+ decorators.push("@AutoIncrement()");
137
+ const options = [];
138
+ if (!column.notNull)
139
+ options.push("nullable: true");
140
+ if (cast && CAST_TYPES[cast])
141
+ options.push(`type: ${q(CAST_TYPES[cast])}`);
142
+ else if (cast === "number")
143
+ options.push(`cast: "number"`); // e.g. Postgres bigint, read as text
144
+ // Key columns are already declared by @PrimaryKey / @AutoIncrement.
145
+ if (options.length > 0 || decorators.length === 0) {
146
+ decorators.push(options.length ? `@Column({ ${options.join(", ")} })` : "@Column()");
147
+ }
148
+ // `?`: the database fills it in (auto-increment or a default), so create() may leave it out.
149
+ const mark = column.generated ? "?" : "!";
150
+ return { decorators, field: `${name}${mark}: ${column.notNull ? ts : `${ts} | null`};` };
151
+ }
152
+ /** A model class for a table with no migration yet: placeholder columns. */
153
+ function renderBlankOrmModel(model, table) {
154
+ return (0, stubs_1.renderStub)("models/orm-model-blank.stub", { Model: model, table: q(table) });
155
+ }
156
+ const q = (value) => JSON.stringify(value);
157
+ /** A property key: bare when it is a valid identifier, quoted otherwise. */
158
+ const property = (name) => (/^[A-Za-z_$][\w$]*$/.test(name) ? name : q(name));
@@ -0,0 +1,32 @@
1
+ import type { MigrationTable } from "./migration-schema";
2
+ /**
3
+ * What `make:resource` needs to know about a model to write its DTOs,
4
+ * service and controller: read from the model's source, and refined with its
5
+ * table's migration when there is one (for `varchar(n)` lengths and integer
6
+ * vs. decimal columns).
7
+ */
8
+ export interface ResourceField {
9
+ name: string;
10
+ /** TypeScript type without `| null`, e.g. `string`, `Date`. */
11
+ ts: string;
12
+ nullable: boolean;
13
+ /** The database fills it in (`static generated`), so `create()` may leave it out. */
14
+ generated: boolean;
15
+ /** SQL type from the migration, when known. */
16
+ sqlType?: string;
17
+ }
18
+ export interface ResourceSchema {
19
+ /** `megh` for `extends Model`, `typeorm` for an `@Entity` class. */
20
+ kind: "megh" | "typeorm";
21
+ /** `static table`, if the model declares one. */
22
+ table?: string;
23
+ primaryKey: string;
24
+ /** TypeScript type of the primary key. */
25
+ primaryKeyType: string;
26
+ /** Columns a client may send when creating or updating a row. */
27
+ inputFields: ResourceField[];
28
+ }
29
+ /** Read a model (Megh ORM or TypeORM) for resource generation. */
30
+ export declare function readModelSchema(source: string, table?: MigrationTable): ResourceSchema;
31
+ /** `src/dtos/<model>.dto.ts`: create, update and list-query DTOs. */
32
+ export declare function renderResourceDto(model: string, plural: string, route: string, schema: ResourceSchema): string;