@objectstack/cli 3.0.5 → 3.0.7

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 (141) hide show
  1. package/.turbo/turbo-build.log +2 -26
  2. package/CHANGELOG.md +27 -0
  3. package/README.md +98 -54
  4. package/bin/run-dev.js +5 -0
  5. package/bin/run.js +5 -0
  6. package/dist/bin.d.ts +11 -0
  7. package/dist/bin.d.ts.map +1 -0
  8. package/dist/bin.js +12 -3759
  9. package/dist/bin.js.map +1 -0
  10. package/dist/commands/codemod/v2-to-v3.d.ts +10 -0
  11. package/dist/commands/codemod/v2-to-v3.d.ts.map +1 -0
  12. package/dist/commands/codemod/v2-to-v3.js +145 -0
  13. package/dist/commands/codemod/v2-to-v3.js.map +1 -0
  14. package/dist/commands/compile.d.ts +13 -0
  15. package/dist/commands/compile.d.ts.map +1 -0
  16. package/dist/commands/compile.js +91 -0
  17. package/dist/commands/compile.js.map +1 -0
  18. package/dist/commands/create.d.ts +91 -0
  19. package/dist/commands/create.d.ts.map +1 -0
  20. package/dist/commands/create.js +259 -0
  21. package/dist/commands/create.js.map +1 -0
  22. package/dist/commands/dev.d.ts +14 -0
  23. package/dist/commands/dev.d.ts.map +1 -0
  24. package/dist/commands/dev.js +67 -0
  25. package/dist/commands/dev.js.map +1 -0
  26. package/dist/commands/diff.d.ts +16 -0
  27. package/dist/commands/diff.d.ts.map +1 -0
  28. package/dist/commands/diff.js +239 -0
  29. package/dist/commands/diff.js.map +1 -0
  30. package/dist/commands/doctor.d.ts +10 -0
  31. package/dist/commands/doctor.d.ts.map +1 -0
  32. package/dist/commands/doctor.js +532 -0
  33. package/dist/commands/doctor.js.map +1 -0
  34. package/dist/commands/explain.d.ts +12 -0
  35. package/dist/commands/explain.d.ts.map +1 -0
  36. package/dist/commands/explain.js +368 -0
  37. package/dist/commands/explain.js.map +1 -0
  38. package/dist/commands/generate.d.ts +17 -0
  39. package/dist/commands/generate.d.ts.map +1 -0
  40. package/dist/commands/generate.js +833 -0
  41. package/dist/commands/generate.js.map +1 -0
  42. package/dist/commands/info.d.ts +12 -0
  43. package/dist/commands/info.d.ts.map +1 -0
  44. package/dist/commands/info.js +100 -0
  45. package/dist/commands/info.js.map +1 -0
  46. package/dist/commands/init.d.ts +22 -0
  47. package/dist/commands/init.d.ts.map +1 -0
  48. package/dist/commands/init.js +295 -0
  49. package/dist/commands/init.js.map +1 -0
  50. package/dist/commands/lint.d.ts +13 -0
  51. package/dist/commands/lint.d.ts.map +1 -0
  52. package/dist/commands/lint.js +255 -0
  53. package/dist/commands/lint.js.map +1 -0
  54. package/dist/commands/plugin/add.d.ts +22 -0
  55. package/dist/commands/plugin/add.d.ts.map +1 -0
  56. package/dist/commands/plugin/add.js +93 -0
  57. package/dist/commands/plugin/add.js.map +1 -0
  58. package/dist/commands/plugin/info.d.ts +10 -0
  59. package/dist/commands/plugin/info.d.ts.map +1 -0
  60. package/dist/commands/plugin/info.js +65 -0
  61. package/dist/commands/plugin/info.js.map +1 -0
  62. package/dist/commands/plugin/list.d.ts +13 -0
  63. package/dist/commands/plugin/list.d.ts.map +1 -0
  64. package/dist/commands/plugin/list.js +78 -0
  65. package/dist/commands/plugin/list.js.map +1 -0
  66. package/dist/commands/plugin/remove.d.ts +20 -0
  67. package/dist/commands/plugin/remove.d.ts.map +1 -0
  68. package/dist/commands/plugin/remove.js +79 -0
  69. package/dist/commands/plugin/remove.js.map +1 -0
  70. package/dist/commands/serve.d.ts +15 -0
  71. package/dist/commands/serve.d.ts.map +1 -0
  72. package/dist/commands/serve.js +286 -0
  73. package/dist/commands/serve.js.map +1 -0
  74. package/dist/commands/studio.d.ts +19 -0
  75. package/dist/commands/studio.d.ts.map +1 -0
  76. package/dist/commands/studio.js +43 -0
  77. package/dist/commands/studio.js.map +1 -0
  78. package/dist/commands/test.d.ts +13 -0
  79. package/dist/commands/test.d.ts.map +1 -0
  80. package/dist/commands/test.js +120 -0
  81. package/dist/commands/test.js.map +1 -0
  82. package/dist/commands/validate.d.ts +13 -0
  83. package/dist/commands/validate.d.ts.map +1 -0
  84. package/dist/commands/validate.js +115 -0
  85. package/dist/commands/validate.js.map +1 -0
  86. package/dist/index.d.ts +15 -114
  87. package/dist/index.d.ts.map +1 -0
  88. package/dist/index.js +20 -2799
  89. package/dist/index.js.map +1 -0
  90. package/dist/utils/config.d.ts +21 -0
  91. package/dist/utils/config.d.ts.map +1 -0
  92. package/dist/utils/config.js +66 -0
  93. package/dist/utils/config.js.map +1 -0
  94. package/dist/utils/format.d.ts +52 -0
  95. package/dist/utils/format.d.ts.map +1 -0
  96. package/dist/utils/format.js +202 -0
  97. package/dist/utils/format.js.map +1 -0
  98. package/dist/utils/plugin-helpers.d.ts +14 -0
  99. package/dist/utils/plugin-helpers.d.ts.map +1 -0
  100. package/dist/utils/plugin-helpers.js +40 -0
  101. package/dist/utils/plugin-helpers.js.map +1 -0
  102. package/dist/utils/studio.d.ts +58 -0
  103. package/dist/utils/studio.d.ts.map +1 -0
  104. package/dist/utils/studio.js +288 -0
  105. package/dist/utils/studio.js.map +1 -0
  106. package/package.json +33 -15
  107. package/src/bin.ts +11 -104
  108. package/src/commands/{codemod.ts → codemod/v2-to-v3.ts} +21 -28
  109. package/src/commands/compile.ts +35 -25
  110. package/src/commands/create.ts +29 -19
  111. package/src/commands/dev.ts +21 -10
  112. package/src/commands/diff.ts +28 -19
  113. package/src/commands/doctor.ts +20 -11
  114. package/src/commands/explain.ts +20 -10
  115. package/src/commands/generate.ts +81 -90
  116. package/src/commands/info.ts +22 -11
  117. package/src/commands/init.ts +32 -20
  118. package/src/commands/lint.ts +27 -15
  119. package/src/commands/plugin/add.ts +112 -0
  120. package/src/commands/plugin/info.ts +79 -0
  121. package/src/commands/plugin/list.ts +93 -0
  122. package/src/commands/plugin/remove.ts +97 -0
  123. package/src/commands/serve.ts +30 -20
  124. package/src/commands/studio.ts +21 -11
  125. package/src/commands/test.ts +21 -10
  126. package/src/commands/validate.ts +36 -25
  127. package/src/index.ts +20 -12
  128. package/src/utils/format.ts +10 -6
  129. package/src/utils/plugin-helpers.ts +37 -0
  130. package/src/utils/studio.ts +0 -1
  131. package/test/commands.test.ts +76 -37
  132. package/test/plugin-commands.test.ts +42 -160
  133. package/test/plugin.test.ts +19 -23
  134. package/tsconfig.build.json +18 -0
  135. package/bin/objectstack.js +0 -2
  136. package/dist/chunk-CSHQEILI.js +0 -246
  137. package/dist/chunk-Q74JNWKD.js +0 -248
  138. package/dist/config-A7BN6UIT.js +0 -11
  139. package/dist/config-UN34WBHT.js +0 -10
  140. package/src/commands/plugin.ts +0 -372
  141. package/src/utils/plugin-commands.ts +0 -163
@@ -0,0 +1,833 @@
1
+ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2
+ import { Args, Command, Flags } from '@oclif/core';
3
+ import chalk from 'chalk';
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+ import { printHeader, printSuccess, printError, printInfo, printStep, createTimer } from '../utils/format.js';
7
+ // ─── Metadata Type Templates ────────────────────────────────────────
8
+ const GENERATORS = {
9
+ object: {
10
+ description: 'Business data object',
11
+ defaultDir: 'src/objects',
12
+ generate: (name) => `import { Data } from '@objectstack/spec';
13
+
14
+ /**
15
+ * ${toTitleCase(name)} Object
16
+ */
17
+ const ${toCamelCase(name)}: Data.Object = {
18
+ name: '${toSnakeCase(name)}',
19
+ label: '${toTitleCase(name)}',
20
+ pluralLabel: '${toTitleCase(name)}s',
21
+ ownership: 'own',
22
+ fields: {
23
+ name: {
24
+ type: 'text',
25
+ label: 'Name',
26
+ required: true,
27
+ maxLength: 255,
28
+ },
29
+ description: {
30
+ type: 'textarea',
31
+ label: 'Description',
32
+ },
33
+ },
34
+ };
35
+
36
+ export default ${toCamelCase(name)};
37
+ `,
38
+ },
39
+ view: {
40
+ description: 'List or form view',
41
+ defaultDir: 'src/views',
42
+ generate: (name) => `import { UI } from '@objectstack/spec';
43
+
44
+ /**
45
+ * ${toTitleCase(name)} List View
46
+ */
47
+ const ${toCamelCase(name)}ListView: UI.View = {
48
+ name: '${toSnakeCase(name)}_list',
49
+ label: '${toTitleCase(name)} List',
50
+ type: 'list',
51
+ objectName: '${toSnakeCase(name)}',
52
+ list: {
53
+ type: 'grid',
54
+ columns: [
55
+ { field: 'name', width: 200 },
56
+ ],
57
+ defaultSort: { field: 'name', direction: 'asc' },
58
+ pageSize: 25,
59
+ },
60
+ };
61
+
62
+ export default ${toCamelCase(name)}ListView;
63
+ `,
64
+ },
65
+ action: {
66
+ description: 'Button or batch action',
67
+ defaultDir: 'src/actions',
68
+ generate: (name) => `import { UI } from '@objectstack/spec';
69
+
70
+ /**
71
+ * ${toTitleCase(name)} Action
72
+ */
73
+ const ${toCamelCase(name)}Action: UI.Action = {
74
+ name: '${toSnakeCase(name)}',
75
+ label: '${toTitleCase(name)}',
76
+ type: 'custom',
77
+ objectName: '${toSnakeCase(name)}',
78
+ handler: {
79
+ type: 'flow',
80
+ target: '${toSnakeCase(name)}_flow',
81
+ },
82
+ };
83
+
84
+ export default ${toCamelCase(name)}Action;
85
+ `,
86
+ },
87
+ flow: {
88
+ description: 'Automation flow',
89
+ defaultDir: 'src/flows',
90
+ generate: (name) => `import { Automation } from '@objectstack/spec';
91
+
92
+ /**
93
+ * ${toTitleCase(name)} Flow
94
+ */
95
+ const ${toCamelCase(name)}Flow: Automation.Flow = {
96
+ name: '${toSnakeCase(name)}_flow',
97
+ label: '${toTitleCase(name)} Flow',
98
+ type: 'autolaunched',
99
+ status: 'draft',
100
+ trigger: {
101
+ type: 'record_change',
102
+ object: '${toSnakeCase(name)}',
103
+ events: ['after_insert', 'after_update'],
104
+ },
105
+ nodes: [
106
+ {
107
+ id: 'start',
108
+ type: 'start',
109
+ name: 'Start',
110
+ next: 'end',
111
+ },
112
+ ],
113
+ };
114
+
115
+ export default ${toCamelCase(name)}Flow;
116
+ `,
117
+ },
118
+ agent: {
119
+ description: 'AI agent',
120
+ defaultDir: 'src/agents',
121
+ generate: (name) => `import { AI } from '@objectstack/spec';
122
+
123
+ /**
124
+ * ${toTitleCase(name)} Agent
125
+ */
126
+ const ${toCamelCase(name)}Agent: AI.Agent = {
127
+ name: '${toSnakeCase(name)}_agent',
128
+ label: '${toTitleCase(name)} Agent',
129
+ role: '${toTitleCase(name)} assistant',
130
+ instructions: 'You are a helpful ${toTitleCase(name).toLowerCase()} assistant.',
131
+ model: {
132
+ provider: 'openai',
133
+ model: 'gpt-4o',
134
+ },
135
+ tools: [],
136
+ };
137
+
138
+ export default ${toCamelCase(name)}Agent;
139
+ `,
140
+ },
141
+ dashboard: {
142
+ description: 'Analytics dashboard',
143
+ defaultDir: 'src/dashboards',
144
+ generate: (name) => `import { UI } from '@objectstack/spec';
145
+
146
+ /**
147
+ * ${toTitleCase(name)} Dashboard
148
+ */
149
+ const ${toCamelCase(name)}Dashboard: UI.Dashboard = {
150
+ name: '${toSnakeCase(name)}_dashboard',
151
+ label: '${toTitleCase(name)} Dashboard',
152
+ widgets: [],
153
+ };
154
+
155
+ export default ${toCamelCase(name)}Dashboard;
156
+ `,
157
+ },
158
+ app: {
159
+ description: 'Application navigation',
160
+ defaultDir: 'src/apps',
161
+ generate: (name) => `import { UI } from '@objectstack/spec';
162
+
163
+ /**
164
+ * ${toTitleCase(name)} App
165
+ */
166
+ const ${toCamelCase(name)}App: UI.App = {
167
+ name: '${toSnakeCase(name)}_app',
168
+ label: '${toTitleCase(name)}',
169
+ navigation: {
170
+ type: 'sidebar',
171
+ items: [],
172
+ },
173
+ };
174
+
175
+ export default ${toCamelCase(name)}App;
176
+ `,
177
+ },
178
+ };
179
+ // ─── Helpers ────────────────────────────────────────────────────────
180
+ function toCamelCase(str) {
181
+ return str.replace(/[-_]([a-z])/g, (_, c) => c.toUpperCase());
182
+ }
183
+ function toTitleCase(str) {
184
+ return str.replace(/[-_]/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
185
+ }
186
+ function toSnakeCase(str) {
187
+ return str.replace(/[-]/g, '_').replace(/[A-Z]/g, c => `_${c.toLowerCase()}`).replace(/^_/, '');
188
+ }
189
+ // ─── Field Type Mapping ─────────────────────────────────────────────
190
+ const FIELD_TYPE_MAP = {
191
+ text: 'string',
192
+ textarea: 'string',
193
+ richtext: 'string',
194
+ html: 'string',
195
+ markdown: 'string',
196
+ number: 'number',
197
+ integer: 'number',
198
+ currency: 'number',
199
+ percent: 'number',
200
+ boolean: 'boolean',
201
+ date: 'string',
202
+ datetime: 'string',
203
+ time: 'string',
204
+ email: 'string',
205
+ phone: 'string',
206
+ url: 'string',
207
+ select: 'string',
208
+ multiselect: 'string[]',
209
+ lookup: 'string',
210
+ master_detail: 'string',
211
+ formula: 'unknown',
212
+ autonumber: 'string',
213
+ json: 'Record<string, unknown>',
214
+ file: 'string',
215
+ image: 'string',
216
+ password: 'string',
217
+ slug: 'string',
218
+ uuid: 'string',
219
+ ip_address: 'string',
220
+ color: 'string',
221
+ rating: 'number',
222
+ geo_point: '{ lat: number; lng: number }',
223
+ vector: 'number[]',
224
+ encrypted: 'string',
225
+ };
226
+ function fieldTypeToTs(fieldType, multiple) {
227
+ const base = FIELD_TYPE_MAP[fieldType] || 'unknown';
228
+ return multiple ? `${base}[]` : base;
229
+ }
230
+ function generateTypesFromConfig(config) {
231
+ const lines = [
232
+ '// Auto-generated by ObjectStack CLI — do not edit manually',
233
+ `// Generated at ${new Date().toISOString()}`,
234
+ '',
235
+ "import type { Data } from '@objectstack/spec';",
236
+ '',
237
+ ];
238
+ // Extract objects from config (supports both top-level and nested)
239
+ const objects = [];
240
+ const rawObjects = config.objects ?? config.data?.objects ?? {};
241
+ if (Array.isArray(rawObjects)) {
242
+ objects.push(...rawObjects);
243
+ }
244
+ else if (typeof rawObjects === 'object') {
245
+ for (const val of Object.values(rawObjects)) {
246
+ if (val && typeof val === 'object')
247
+ objects.push(val);
248
+ }
249
+ }
250
+ if (objects.length === 0) {
251
+ lines.push('// No objects found in configuration');
252
+ return lines.join('\n') + '\n';
253
+ }
254
+ for (const obj of objects) {
255
+ const name = String(obj.name || 'unknown');
256
+ const typeName = name
257
+ .split('_')
258
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
259
+ .join('');
260
+ const fields = (obj.fields ?? {});
261
+ lines.push(`/** ${String(obj.label || typeName)} record type */`);
262
+ lines.push(`export interface ${typeName}Record {`);
263
+ lines.push(' id: string;');
264
+ for (const [fieldName, fieldDef] of Object.entries(fields)) {
265
+ const fType = String(fieldDef.type || 'text');
266
+ const tsType = fieldTypeToTs(fType, !!fieldDef.multiple);
267
+ const required = fieldDef.required ? '' : '?';
268
+ if (fieldDef.label) {
269
+ lines.push(` /** ${fieldDef.label} */`);
270
+ }
271
+ lines.push(` ${fieldName}${required}: ${tsType};`);
272
+ }
273
+ lines.push('}');
274
+ lines.push('');
275
+ }
276
+ return lines.join('\n') + '\n';
277
+ }
278
+ // ─── Command ────────────────────────────────────────────────────────
279
+ async function runMetadataGeneration(type, name, flags) {
280
+ printHeader('Generate');
281
+ const generator = GENERATORS[type];
282
+ if (!generator) {
283
+ printError(`Unknown type: ${type}`);
284
+ console.log('');
285
+ console.log(chalk.bold(' Available types:'));
286
+ for (const [key, gen] of Object.entries(GENERATORS)) {
287
+ console.log(` ${chalk.cyan(key.padEnd(12))} ${chalk.dim(gen.description)}`);
288
+ }
289
+ console.log('');
290
+ console.log(chalk.dim(' Usage: objectstack generate <type> <name>'));
291
+ console.log(chalk.dim(' Example: objectstack generate object project'));
292
+ console.log(chalk.dim(' Alias: os g object project'));
293
+ process.exit(1);
294
+ }
295
+ const dir = flags.dir || generator.defaultDir;
296
+ const fileName = `${toSnakeCase(name)}.ts`;
297
+ const filePath = path.join(process.cwd(), dir, fileName);
298
+ console.log(` ${chalk.dim('Type:')} ${chalk.cyan(type)} — ${generator.description}`);
299
+ console.log(` ${chalk.dim('Name:')} ${chalk.white(name)}`);
300
+ console.log(` ${chalk.dim('File:')} ${chalk.white(path.join(dir, fileName))}`);
301
+ console.log('');
302
+ if (flags.dryRun) {
303
+ printInfo('Dry run — no files written');
304
+ console.log('');
305
+ console.log(chalk.dim(' Content:'));
306
+ console.log(chalk.dim(' ' + '-'.repeat(38)));
307
+ const content = generator.generate(name);
308
+ for (const line of content.split('\n')) {
309
+ console.log(chalk.dim(` ${line}`));
310
+ }
311
+ console.log('');
312
+ return;
313
+ }
314
+ // Check if file exists
315
+ if (fs.existsSync(filePath)) {
316
+ printError(`File already exists: ${filePath}`);
317
+ process.exit(1);
318
+ }
319
+ try {
320
+ // Create directory
321
+ const fullDir = path.dirname(filePath);
322
+ if (!fs.existsSync(fullDir)) {
323
+ fs.mkdirSync(fullDir, { recursive: true });
324
+ }
325
+ // Write file
326
+ const content = generator.generate(name);
327
+ fs.writeFileSync(filePath, content);
328
+ printSuccess(`Created ${path.join(dir, fileName)}`);
329
+ // Check for barrel index
330
+ const indexPath = path.join(process.cwd(), dir, 'index.ts');
331
+ if (fs.existsSync(indexPath)) {
332
+ const indexContent = fs.readFileSync(indexPath, 'utf-8');
333
+ const exportLine = `export { default as ${toCamelCase(name)} } from './${toSnakeCase(name)}';`;
334
+ if (!indexContent.includes(toCamelCase(name))) {
335
+ fs.appendFileSync(indexPath, exportLine + '\n');
336
+ printSuccess(`Updated ${dir}/index.ts with export`);
337
+ }
338
+ }
339
+ else {
340
+ // Create barrel index
341
+ const exportLine = `export { default as ${toCamelCase(name)} } from './${toSnakeCase(name)}';\n`;
342
+ fs.writeFileSync(indexPath, exportLine);
343
+ printSuccess(`Created ${dir}/index.ts`);
344
+ }
345
+ console.log('');
346
+ console.log(chalk.dim(` Tip: Run \`objectstack validate\` to check your config`));
347
+ console.log('');
348
+ }
349
+ catch (error) {
350
+ printError(error.message || String(error));
351
+ process.exit(1);
352
+ }
353
+ }
354
+ async function runTypesGeneration(configPath, flags) {
355
+ printHeader('Generate Types');
356
+ try {
357
+ const { loadConfig } = await import('../utils/config.js');
358
+ printInfo('Loading configuration...');
359
+ const { config, absolutePath } = await loadConfig(configPath);
360
+ console.log(` ${chalk.dim('Config:')} ${chalk.white(absolutePath)}`);
361
+ console.log(` ${chalk.dim('Output:')} ${chalk.white(flags.output)}`);
362
+ console.log('');
363
+ const content = generateTypesFromConfig(config);
364
+ if (flags.dryRun) {
365
+ printInfo('Dry run — no files written');
366
+ console.log('');
367
+ for (const line of content.split('\n')) {
368
+ console.log(chalk.dim(` ${line}`));
369
+ }
370
+ console.log('');
371
+ return;
372
+ }
373
+ const outPath = path.resolve(process.cwd(), flags.output);
374
+ const outDir = path.dirname(outPath);
375
+ if (!fs.existsSync(outDir)) {
376
+ fs.mkdirSync(outDir, { recursive: true });
377
+ }
378
+ fs.writeFileSync(outPath, content);
379
+ printSuccess(`Generated types at ${flags.output}`);
380
+ console.log('');
381
+ }
382
+ catch (error) {
383
+ printError(error.message || String(error));
384
+ process.exit(1);
385
+ }
386
+ }
387
+ // ─── Client SDK Generator ───────────────────────────────────────────
388
+ function generateClientFromConfig(config) {
389
+ const lines = [
390
+ '// Auto-generated by ObjectStack CLI — do not edit manually',
391
+ `// Generated at ${new Date().toISOString()}`,
392
+ '',
393
+ "import type { Data } from '@objectstack/spec';",
394
+ '',
395
+ ];
396
+ const objects = [];
397
+ const rawObjects = config.objects ?? config.data?.objects ?? {};
398
+ if (Array.isArray(rawObjects)) {
399
+ objects.push(...rawObjects);
400
+ }
401
+ else if (typeof rawObjects === 'object') {
402
+ for (const val of Object.values(rawObjects)) {
403
+ if (val && typeof val === 'object')
404
+ objects.push(val);
405
+ }
406
+ }
407
+ if (objects.length === 0) {
408
+ lines.push('// No objects found in configuration');
409
+ return lines.join('\n') + '\n';
410
+ }
411
+ // Generate type interfaces
412
+ for (const obj of objects) {
413
+ const name = String(obj.name || 'unknown');
414
+ const typeName = name
415
+ .split('_')
416
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
417
+ .join('');
418
+ const fields = (obj.fields ?? {});
419
+ lines.push(`export interface ${typeName}Record {`);
420
+ lines.push(' id: string;');
421
+ for (const [fieldName, fieldDef] of Object.entries(fields)) {
422
+ const fType = String(fieldDef.type || 'text');
423
+ const tsType = fieldTypeToTs(fType, !!fieldDef.multiple);
424
+ const required = fieldDef.required ? '' : '?';
425
+ lines.push(` ${fieldName}${required}: ${tsType};`);
426
+ }
427
+ lines.push('}');
428
+ lines.push('');
429
+ }
430
+ // Generate client class
431
+ lines.push('export class ObjectStackClient {');
432
+ lines.push(' constructor(private baseUrl: string, private headers: Record<string, string> = {}) {}');
433
+ lines.push('');
434
+ lines.push(' private async request<T>(method: string, path: string, body?: unknown): Promise<T> {');
435
+ lines.push(' const res = await fetch(`${this.baseUrl}${path}`, {');
436
+ lines.push(' method,');
437
+ lines.push(" headers: { 'Content-Type': 'application/json', ...this.headers },");
438
+ lines.push(' body: body ? JSON.stringify(body) : undefined,');
439
+ lines.push(' });');
440
+ lines.push(' if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);');
441
+ lines.push(' return res.json() as Promise<T>;');
442
+ lines.push(' }');
443
+ for (const obj of objects) {
444
+ const name = String(obj.name || 'unknown');
445
+ const typeName = name
446
+ .split('_')
447
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
448
+ .join('');
449
+ const endpoint = `/api/${name}`;
450
+ lines.push('');
451
+ lines.push(` async list${typeName}(): Promise<${typeName}Record[]> {`);
452
+ lines.push(` return this.request<${typeName}Record[]>('GET', '${endpoint}');`);
453
+ lines.push(' }');
454
+ lines.push('');
455
+ lines.push(` async get${typeName}(id: string): Promise<${typeName}Record> {`);
456
+ lines.push(` return this.request<${typeName}Record>('GET', '${endpoint}/\${id}');`);
457
+ lines.push(' }');
458
+ lines.push('');
459
+ lines.push(` async create${typeName}(data: Omit<${typeName}Record, 'id'>): Promise<${typeName}Record> {`);
460
+ lines.push(` return this.request<${typeName}Record>('POST', '${endpoint}', data);`);
461
+ lines.push(' }');
462
+ lines.push('');
463
+ lines.push(` async update${typeName}(id: string, data: Partial<${typeName}Record>): Promise<${typeName}Record> {`);
464
+ lines.push(` return this.request<${typeName}Record>('PATCH', '${endpoint}/\${id}', data);`);
465
+ lines.push(' }');
466
+ lines.push('');
467
+ lines.push(` async delete${typeName}(id: string): Promise<void> {`);
468
+ lines.push(` return this.request<void>('DELETE', '${endpoint}/\${id}');`);
469
+ lines.push(' }');
470
+ }
471
+ lines.push('}');
472
+ lines.push('');
473
+ return lines.join('\n') + '\n';
474
+ }
475
+ async function runClientGeneration(configPath, flags) {
476
+ printHeader('Generate Client SDK');
477
+ try {
478
+ const { loadConfig } = await import('../utils/config.js');
479
+ const timer = createTimer();
480
+ printInfo('Loading configuration...');
481
+ const { config, absolutePath } = await loadConfig(configPath);
482
+ console.log(` ${chalk.dim('Config:')} ${chalk.white(absolutePath)}`);
483
+ console.log(` ${chalk.dim('Output:')} ${chalk.white(flags.output)}`);
484
+ console.log('');
485
+ printStep('Generating client SDK...');
486
+ const content = generateClientFromConfig(config);
487
+ if (flags.dryRun) {
488
+ printInfo('Dry run — no files written');
489
+ console.log('');
490
+ for (const line of content.split('\n')) {
491
+ console.log(chalk.dim(` ${line}`));
492
+ }
493
+ console.log('');
494
+ return;
495
+ }
496
+ const outPath = path.resolve(process.cwd(), flags.output);
497
+ const outDir = path.dirname(outPath);
498
+ if (!fs.existsSync(outDir)) {
499
+ fs.mkdirSync(outDir, { recursive: true });
500
+ }
501
+ fs.writeFileSync(outPath, content);
502
+ printSuccess(`Generated client SDK at ${flags.output} (${timer.display()})`);
503
+ console.log('');
504
+ }
505
+ catch (error) {
506
+ printError(error.message || String(error));
507
+ process.exit(1);
508
+ }
509
+ }
510
+ // ─── Migration Generator ────────────────────────────────────────────
511
+ const FIELD_TYPE_SQL_MAP = {
512
+ text: 'VARCHAR(255)',
513
+ textarea: 'TEXT',
514
+ richtext: 'TEXT',
515
+ html: 'TEXT',
516
+ markdown: 'TEXT',
517
+ number: 'DECIMAL(18,2)',
518
+ integer: 'INTEGER',
519
+ currency: 'DECIMAL(18,2)',
520
+ percent: 'DECIMAL(5,2)',
521
+ boolean: 'BOOLEAN',
522
+ date: 'DATE',
523
+ datetime: 'TIMESTAMP',
524
+ time: 'TIME',
525
+ email: 'VARCHAR(255)',
526
+ phone: 'VARCHAR(50)',
527
+ url: 'VARCHAR(2048)',
528
+ select: 'VARCHAR(255)',
529
+ multiselect: 'TEXT',
530
+ lookup: 'VARCHAR(36)',
531
+ master_detail: 'VARCHAR(36)',
532
+ formula: 'TEXT',
533
+ autonumber: 'SERIAL',
534
+ json: 'JSONB',
535
+ file: 'VARCHAR(2048)',
536
+ image: 'VARCHAR(2048)',
537
+ password: 'VARCHAR(255)',
538
+ slug: 'VARCHAR(255)',
539
+ uuid: 'UUID',
540
+ ip_address: 'VARCHAR(45)',
541
+ color: 'VARCHAR(7)',
542
+ rating: 'INTEGER',
543
+ geo_point: 'POINT',
544
+ vector: 'VECTOR',
545
+ encrypted: 'TEXT',
546
+ };
547
+ function fieldTypeToSql(fieldType) {
548
+ return FIELD_TYPE_SQL_MAP[fieldType] || 'TEXT';
549
+ }
550
+ function generateMigrationSql(config) {
551
+ const lines = [
552
+ '-- Auto-generated by ObjectStack CLI — do not edit manually',
553
+ `-- Generated at ${new Date().toISOString()}`,
554
+ '',
555
+ ];
556
+ const objects = [];
557
+ const rawObjects = config.objects ?? config.data?.objects ?? {};
558
+ if (Array.isArray(rawObjects)) {
559
+ objects.push(...rawObjects);
560
+ }
561
+ else if (typeof rawObjects === 'object') {
562
+ for (const val of Object.values(rawObjects)) {
563
+ if (val && typeof val === 'object')
564
+ objects.push(val);
565
+ }
566
+ }
567
+ if (objects.length === 0) {
568
+ lines.push('-- No objects found in configuration');
569
+ return lines.join('\n') + '\n';
570
+ }
571
+ for (const obj of objects) {
572
+ const tableName = String(obj.name || 'unknown');
573
+ const fields = (obj.fields ?? {});
574
+ lines.push(`CREATE TABLE IF NOT EXISTS "${tableName}" (`);
575
+ lines.push(' "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),');
576
+ const fieldLines = [];
577
+ for (const [fieldName, fieldDef] of Object.entries(fields)) {
578
+ const sqlType = fieldTypeToSql(String(fieldDef.type || 'text'));
579
+ const notNull = fieldDef.required ? ' NOT NULL' : '';
580
+ fieldLines.push(` "${fieldName}" ${sqlType}${notNull}`);
581
+ }
582
+ fieldLines.push(' "created_at" TIMESTAMP NOT NULL DEFAULT now()');
583
+ fieldLines.push(' "updated_at" TIMESTAMP NOT NULL DEFAULT now()');
584
+ lines.push(fieldLines.join(',\n'));
585
+ lines.push(');');
586
+ lines.push('');
587
+ }
588
+ return lines.join('\n') + '\n';
589
+ }
590
+ function generateMigrationTs(config) {
591
+ const lines = [
592
+ '// Auto-generated by ObjectStack CLI — do not edit manually',
593
+ `// Generated at ${new Date().toISOString()}`,
594
+ '',
595
+ 'export async function up(db: any): Promise<void> {',
596
+ ];
597
+ const objects = [];
598
+ const rawObjects = config.objects ?? config.data?.objects ?? {};
599
+ if (Array.isArray(rawObjects)) {
600
+ objects.push(...rawObjects);
601
+ }
602
+ else if (typeof rawObjects === 'object') {
603
+ for (const val of Object.values(rawObjects)) {
604
+ if (val && typeof val === 'object')
605
+ objects.push(val);
606
+ }
607
+ }
608
+ if (objects.length === 0) {
609
+ lines.push(' // No objects found in configuration');
610
+ lines.push('}');
611
+ lines.push('');
612
+ lines.push('export async function down(db: any): Promise<void> {');
613
+ lines.push(' // No objects found in configuration');
614
+ lines.push('}');
615
+ return lines.join('\n') + '\n';
616
+ }
617
+ for (const obj of objects) {
618
+ const tableName = String(obj.name || 'unknown');
619
+ const fields = (obj.fields ?? {});
620
+ lines.push(` await db.schema.createTable('${tableName}', (table: any) => {`);
621
+ lines.push(" table.uuid('id').primary().defaultTo(db.fn.uuid());");
622
+ for (const [fieldName, fieldDef] of Object.entries(fields)) {
623
+ const fType = String(fieldDef.type || 'text');
624
+ const required = fieldDef.required ? '.notNullable()' : '.nullable()';
625
+ let colMethod;
626
+ switch (fType) {
627
+ case 'text':
628
+ case 'email':
629
+ case 'phone':
630
+ case 'url':
631
+ case 'select':
632
+ case 'slug':
633
+ case 'password':
634
+ case 'color':
635
+ case 'ip_address':
636
+ colMethod = `table.string('${fieldName}')`;
637
+ break;
638
+ case 'textarea':
639
+ case 'richtext':
640
+ case 'html':
641
+ case 'markdown':
642
+ case 'formula':
643
+ case 'encrypted':
644
+ colMethod = `table.text('${fieldName}')`;
645
+ break;
646
+ case 'number':
647
+ case 'currency':
648
+ case 'percent':
649
+ colMethod = `table.decimal('${fieldName}')`;
650
+ break;
651
+ case 'integer':
652
+ case 'rating':
653
+ colMethod = `table.integer('${fieldName}')`;
654
+ break;
655
+ case 'boolean':
656
+ colMethod = `table.boolean('${fieldName}')`;
657
+ break;
658
+ case 'date':
659
+ colMethod = `table.date('${fieldName}')`;
660
+ break;
661
+ case 'datetime':
662
+ colMethod = `table.timestamp('${fieldName}')`;
663
+ break;
664
+ case 'time':
665
+ colMethod = `table.time('${fieldName}')`;
666
+ break;
667
+ case 'json':
668
+ case 'multiselect':
669
+ colMethod = `table.jsonb('${fieldName}')`;
670
+ break;
671
+ case 'uuid':
672
+ case 'lookup':
673
+ case 'master_detail':
674
+ colMethod = `table.uuid('${fieldName}')`;
675
+ break;
676
+ default:
677
+ colMethod = `table.text('${fieldName}')`;
678
+ }
679
+ lines.push(` ${colMethod}${required};`);
680
+ }
681
+ lines.push(" table.timestamps(true, true);");
682
+ lines.push(' });');
683
+ }
684
+ lines.push('}');
685
+ lines.push('');
686
+ lines.push('export async function down(db: any): Promise<void> {');
687
+ // Drop tables in reverse order
688
+ const tableNames = objects.map(o => String(o.name || 'unknown')).reverse();
689
+ for (const tableName of tableNames) {
690
+ lines.push(` await db.schema.dropTableIfExists('${tableName}');`);
691
+ }
692
+ lines.push('}');
693
+ return lines.join('\n') + '\n';
694
+ }
695
+ async function runMigrationGeneration(configPath, flags) {
696
+ printHeader('Generate Migration');
697
+ try {
698
+ const { loadConfig } = await import('../utils/config.js');
699
+ const timer = createTimer();
700
+ printInfo('Loading configuration...');
701
+ const { config, absolutePath } = await loadConfig(configPath);
702
+ const ext = flags.format === 'sql' ? 'sql' : 'ts';
703
+ // Format: YYYYMMDDHHmmss (e.g. 20250101120000)
704
+ const timestamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);
705
+ const defaultOutput = `migrations/${timestamp}_migration.${ext}`;
706
+ const output = flags.output || defaultOutput;
707
+ console.log(` ${chalk.dim('Config:')} ${chalk.white(absolutePath)}`);
708
+ console.log(` ${chalk.dim('Format:')} ${chalk.white(flags.format)}`);
709
+ console.log(` ${chalk.dim('Output:')} ${chalk.white(output)}`);
710
+ console.log('');
711
+ printStep('Generating migration...');
712
+ const content = flags.format === 'sql'
713
+ ? generateMigrationSql(config)
714
+ : generateMigrationTs(config);
715
+ if (flags.dryRun) {
716
+ printInfo('Dry run — no files written');
717
+ console.log('');
718
+ for (const line of content.split('\n')) {
719
+ console.log(chalk.dim(` ${line}`));
720
+ }
721
+ console.log('');
722
+ return;
723
+ }
724
+ const outPath = path.resolve(process.cwd(), output);
725
+ const outDir = path.dirname(outPath);
726
+ if (!fs.existsSync(outDir)) {
727
+ fs.mkdirSync(outDir, { recursive: true });
728
+ }
729
+ fs.writeFileSync(outPath, content);
730
+ printSuccess(`Generated migration at ${output} (${timer.display()})`);
731
+ console.log('');
732
+ }
733
+ catch (error) {
734
+ printError(error.message || String(error));
735
+ process.exit(1);
736
+ }
737
+ }
738
+ // ─── JSON Schema Generator ──────────────────────────────────────────
739
+ async function runSchemaGeneration(flags) {
740
+ printHeader('Generate Schema');
741
+ try {
742
+ const timer = createTimer();
743
+ printStep('Loading ObjectStackDefinitionSchema...');
744
+ const { z } = await import('zod');
745
+ const { ObjectStackDefinitionSchema } = await import('@objectstack/spec');
746
+ printStep('Converting to JSON Schema...');
747
+ const jsonSchema = z.toJSONSchema(ObjectStackDefinitionSchema, {
748
+ target: 'draft-2020-12',
749
+ });
750
+ // Add metadata
751
+ const schema = {
752
+ ...jsonSchema,
753
+ $id: 'https://schema.objectstack.io/objectstack.config.json',
754
+ title: 'ObjectStack Configuration',
755
+ description: 'JSON Schema for objectstack.config.ts — generated from ObjectStackDefinitionSchema',
756
+ };
757
+ const content = JSON.stringify(schema, null, 2) + '\n';
758
+ if (flags.dryRun) {
759
+ printInfo('Dry run — no files written');
760
+ console.log('');
761
+ console.log(content);
762
+ return;
763
+ }
764
+ const outPath = path.resolve(process.cwd(), flags.output);
765
+ const outDir = path.dirname(outPath);
766
+ if (!fs.existsSync(outDir)) {
767
+ fs.mkdirSync(outDir, { recursive: true });
768
+ }
769
+ fs.writeFileSync(outPath, content);
770
+ printSuccess(`Generated JSON Schema at ${flags.output} (${timer.display()})`);
771
+ console.log('');
772
+ console.log(chalk.dim(' Usage: Reference in your IDE or editor for autocomplete'));
773
+ console.log(chalk.dim(` Path: ${outPath}`));
774
+ console.log('');
775
+ }
776
+ catch (error) {
777
+ printError(error.message || String(error));
778
+ process.exit(1);
779
+ }
780
+ }
781
+ // ─── Main Generate Command ──────────────────────────────────────────
782
+ export default class Generate extends Command {
783
+ static description = 'Generate metadata files or TypeScript types';
784
+ static aliases = ['g'];
785
+ static args = {
786
+ type: Args.string({ description: 'Metadata type to generate (object, view, action, flow, agent, dashboard, app)', required: true }),
787
+ name: Args.string({ description: 'Name for the metadata (use kebab-case)', required: false }),
788
+ };
789
+ static flags = {
790
+ dir: Flags.string({ char: 'd', description: 'Target directory (overrides default)' }),
791
+ 'dry-run': Flags.boolean({ description: 'Show what would be created without writing files' }),
792
+ output: Flags.string({ char: 'o', description: 'Output file path' }),
793
+ format: Flags.string({ description: 'Output format: sql or typescript', default: 'typescript' }),
794
+ };
795
+ async run() {
796
+ const { args, flags } = await this.parse(Generate);
797
+ // Route to sub-commands by type name
798
+ switch (args.type) {
799
+ case 'types':
800
+ return runTypesGeneration(args.name, {
801
+ output: flags.output ?? 'src/types/objectstack.d.ts',
802
+ dryRun: flags['dry-run'],
803
+ });
804
+ case 'client':
805
+ return runClientGeneration(args.name, {
806
+ output: flags.output ?? 'src/client/objectstack-client.ts',
807
+ dryRun: flags['dry-run'],
808
+ });
809
+ case 'migration':
810
+ return runMigrationGeneration(args.name, {
811
+ output: flags.output,
812
+ format: flags.format ?? 'typescript',
813
+ dryRun: flags['dry-run'],
814
+ });
815
+ case 'schema':
816
+ return runSchemaGeneration({
817
+ output: flags.output ?? 'objectstack.schema.json',
818
+ dryRun: flags['dry-run'],
819
+ });
820
+ }
821
+ // Metadata generation
822
+ if (!args.name) {
823
+ printError('Missing required argument: <name>');
824
+ console.log(chalk.dim(' Usage: objectstack generate <type> <name>'));
825
+ process.exit(1);
826
+ }
827
+ await runMetadataGeneration(args.type, args.name, {
828
+ dir: flags.dir,
829
+ dryRun: flags['dry-run'],
830
+ });
831
+ }
832
+ }
833
+ //# sourceMappingURL=generate.js.map