@specverse/engines 6.7.8 → 6.16.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.
- package/dist/ai/behavior-ai-service.js +2 -2
- package/dist/ai/behavior-ai-service.js.map +1 -1
- package/dist/inference/core/specly-converter.d.ts.map +1 -1
- package/dist/inference/core/specly-converter.js +20 -0
- package/dist/inference/core/specly-converter.js.map +1 -1
- package/dist/inference/index.d.ts.map +1 -1
- package/dist/inference/index.js +72 -22
- package/dist/inference/index.js.map +1 -1
- package/dist/inference/logical/generators/controller-generator.d.ts.map +1 -1
- package/dist/inference/logical/generators/controller-generator.js +26 -4
- package/dist/inference/logical/generators/controller-generator.js.map +1 -1
- package/dist/libs/instance-factories/applications/templates/generic/backend-package-json-generator.js +22 -5
- package/dist/libs/instance-factories/controllers/templates/fastify/routes-generator.js +50 -15
- package/dist/libs/instance-factories/controllers/templates/fastify/server-generator.js +26 -6
- package/dist/libs/instance-factories/services/postgres-native-services.yaml +90 -0
- package/dist/libs/instance-factories/services/templates/_shared/step-matching.js +44 -0
- package/dist/libs/instance-factories/services/templates/mongodb-native/controller-generator.js +68 -13
- package/dist/libs/instance-factories/services/templates/mongodb-native/step-conventions.js +515 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/client-generator.js +165 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/controller-generator.js +300 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/ddl-generator.js +169 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/service-generator.js +65 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/step-conventions.js +433 -0
- package/dist/libs/instance-factories/services/templates/prisma/ai-behaviors-generator.js +27 -4
- package/dist/libs/instance-factories/services/templates/prisma/step-conventions.js +7 -34
- package/dist/parser/processors/ExecutableProcessor.d.ts.map +1 -1
- package/dist/parser/processors/ExecutableProcessor.js +14 -1
- package/dist/parser/processors/ExecutableProcessor.js.map +1 -1
- package/dist/realize/index.d.ts.map +1 -1
- package/dist/realize/index.js +30 -3
- package/dist/realize/index.js.map +1 -1
- package/libs/instance-factories/applications/templates/generic/backend-package-json-generator.ts +46 -24
- package/libs/instance-factories/controllers/templates/fastify/routes-generator.ts +80 -21
- package/libs/instance-factories/controllers/templates/fastify/server-generator.ts +48 -7
- package/libs/instance-factories/services/postgres-native-services.yaml +90 -0
- package/libs/instance-factories/services/templates/_shared/step-matching.ts +103 -0
- package/libs/instance-factories/services/templates/mongodb-native/controller-generator.ts +97 -23
- package/libs/instance-factories/services/templates/mongodb-native/step-conventions.ts +691 -0
- package/libs/instance-factories/services/templates/postgres-native/__tests__/controller-generator.test.ts +193 -0
- package/libs/instance-factories/services/templates/postgres-native/client-generator.ts +178 -0
- package/libs/instance-factories/services/templates/postgres-native/controller-generator.ts +372 -0
- package/libs/instance-factories/services/templates/postgres-native/ddl-generator.ts +236 -0
- package/libs/instance-factories/services/templates/postgres-native/service-generator.ts +84 -0
- package/libs/instance-factories/services/templates/postgres-native/step-conventions.ts +539 -0
- package/libs/instance-factories/services/templates/prisma/ai-behaviors-generator.ts +61 -7
- package/libs/instance-factories/services/templates/prisma/step-conventions.ts +21 -68
- package/package.json +4 -3
package/dist/libs/instance-factories/services/templates/postgres-native/controller-generator.js
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { buildTransitionMap, isAutoField } from "@specverse/types/spec-rules";
|
|
2
|
+
function generatePgNativeController(context) {
|
|
3
|
+
const { controller, model, models } = context;
|
|
4
|
+
if (!controller) throw new Error("Controller is required in template context");
|
|
5
|
+
if (!model) throw new Error("Model is required for controller generation");
|
|
6
|
+
const controllerName = controller.name;
|
|
7
|
+
const modelName = model.name;
|
|
8
|
+
const modelVar = lowerFirst(modelName);
|
|
9
|
+
const table = tableName(model);
|
|
10
|
+
const curedOps = controller.cured || {};
|
|
11
|
+
const modelRegistry = {};
|
|
12
|
+
if (Array.isArray(models)) {
|
|
13
|
+
for (const m of models) if (m?.name) modelRegistry[m.name] = m;
|
|
14
|
+
} else if (models && typeof models === "object") {
|
|
15
|
+
Object.assign(modelRegistry, models);
|
|
16
|
+
}
|
|
17
|
+
const customActions = generateCustomActions(controller, modelRegistry);
|
|
18
|
+
const validate = generateValidateMethod(model, modelName);
|
|
19
|
+
const create = curedOps.create ? generateCreateMethod(modelName, modelVar) : "";
|
|
20
|
+
const retrieve = curedOps.retrieve ? generateRetrieveMethod(modelName, modelVar) : "";
|
|
21
|
+
const update = curedOps.update ? generateUpdateMethod(modelName, modelVar) : "";
|
|
22
|
+
const evolve = curedOps.evolve ? generateEvolveMethod(model, modelName, modelVar) : "";
|
|
23
|
+
const del = curedOps.delete ? generateDeleteMethod(modelName, modelVar) : "";
|
|
24
|
+
const hasEventPublishing = curedOps.create || curedOps.update || curedOps.evolve || curedOps.delete;
|
|
25
|
+
const helperImports = [
|
|
26
|
+
"insertOne",
|
|
27
|
+
"findOneByField",
|
|
28
|
+
"findAll",
|
|
29
|
+
"updateOneById",
|
|
30
|
+
"deleteOneById",
|
|
31
|
+
"query",
|
|
32
|
+
customActions.code.includes("findOneByFields(") ? "findOneByFields" : "",
|
|
33
|
+
customActions.code.includes("insertMany(") ? "insertMany" : ""
|
|
34
|
+
].filter(Boolean).join(", ");
|
|
35
|
+
return `/**
|
|
36
|
+
* ${controllerName}
|
|
37
|
+
* Model-specific business logic for ${modelName} (PostgreSQL native driver)
|
|
38
|
+
* ${controller.description || ""}
|
|
39
|
+
*/
|
|
40
|
+
import { ${helperImports} } from '../db/pgClient.js';
|
|
41
|
+
${hasEventPublishing || customActions.needsAiBehaviors ? `import { eventBus } from '../events/eventBus.js';` : ""}
|
|
42
|
+
${customActions.needsAiBehaviors ? `import * as aiBehaviors from '../behaviors/${controllerName}.ai.js';` : ""}
|
|
43
|
+
|
|
44
|
+
const TABLE_NAME = '${table}';
|
|
45
|
+
|
|
46
|
+
export class ${controllerName} {
|
|
47
|
+
${validate}
|
|
48
|
+
${create}
|
|
49
|
+
${retrieve}
|
|
50
|
+
${update}
|
|
51
|
+
${evolve}
|
|
52
|
+
${del}
|
|
53
|
+
${customActions.code}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const ${modelVar}Controller = new ${controllerName}();
|
|
57
|
+
export default ${modelVar}Controller;
|
|
58
|
+
`;
|
|
59
|
+
}
|
|
60
|
+
function lowerFirst(s) {
|
|
61
|
+
return s.charAt(0).toLowerCase() + s.slice(1);
|
|
62
|
+
}
|
|
63
|
+
function tableName(model) {
|
|
64
|
+
if (model?.storage?.table) return String(model.storage.table);
|
|
65
|
+
return model.name.toLowerCase() + "s";
|
|
66
|
+
}
|
|
67
|
+
function generateValidateMethod(model, modelName) {
|
|
68
|
+
return `
|
|
69
|
+
/**
|
|
70
|
+
* Validate ${modelName} data \u2014 runs before create / update / evolve.
|
|
71
|
+
*/
|
|
72
|
+
public validate(
|
|
73
|
+
_data: any,
|
|
74
|
+
_context: { operation: 'create' | 'update' | 'evolve' }
|
|
75
|
+
): { valid: boolean; errors: string[] } {
|
|
76
|
+
const errors: string[] = [];
|
|
77
|
+
${generateValidationLogic(model)}
|
|
78
|
+
return { valid: errors.length === 0, errors };
|
|
79
|
+
}
|
|
80
|
+
`;
|
|
81
|
+
}
|
|
82
|
+
function generateValidationLogic(model) {
|
|
83
|
+
if (!model.attributes) return " // No validation rules defined";
|
|
84
|
+
const attrList = Array.isArray(model.attributes) ? model.attributes.map((a) => [a.name, a]) : Object.entries(model.attributes);
|
|
85
|
+
const out = [];
|
|
86
|
+
attrList.forEach(([name, attr]) => {
|
|
87
|
+
if (attr.required && !isAutoField(name, attr)) {
|
|
88
|
+
out.push(` if (_context.operation === 'create' && !_data.${name}) errors.push('${name} is required');`);
|
|
89
|
+
}
|
|
90
|
+
if (attr.type === "String" || attr.type === "string") {
|
|
91
|
+
if (attr.min) out.push(` if (_data.${name} && _data.${name}.length < ${attr.min}) errors.push('${name} must be at least ${attr.min} characters');`);
|
|
92
|
+
if (attr.max) out.push(` if (_data.${name} && _data.${name}.length > ${attr.max}) errors.push('${name} must be at most ${attr.max} characters');`);
|
|
93
|
+
}
|
|
94
|
+
if (attr.values && Array.isArray(attr.values)) {
|
|
95
|
+
const values = attr.values.map((v) => `'${v}'`).join(", ");
|
|
96
|
+
out.push(` if (_data.${name} && ![${values}].includes(_data.${name})) errors.push('${name} must be one of: ${attr.values.join(", ")}');`);
|
|
97
|
+
}
|
|
98
|
+
if (attr.format === "email") {
|
|
99
|
+
out.push(` if (_data.${name} && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(_data.${name})) errors.push('${name} must be a valid email address');`);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
return out.join("\n") || " // No validation rules defined";
|
|
103
|
+
}
|
|
104
|
+
function generateCreateMethod(modelName, modelVar) {
|
|
105
|
+
return `
|
|
106
|
+
/**
|
|
107
|
+
* Create a new ${modelName}.
|
|
108
|
+
*/
|
|
109
|
+
public async create(data: any): Promise<any> {
|
|
110
|
+
const validation = this.validate(data, { operation: 'create' });
|
|
111
|
+
if (!validation.valid) throw new Error(\`Validation failed: \${validation.errors.join(', ')}\`);
|
|
112
|
+
|
|
113
|
+
const ${modelVar} = await insertOne(TABLE_NAME, { ...data });
|
|
114
|
+
|
|
115
|
+
await eventBus.publish('${modelName}Created', { ...${modelVar}, timestamp: new Date().toISOString() } as any);
|
|
116
|
+
return ${modelVar};
|
|
117
|
+
}
|
|
118
|
+
`;
|
|
119
|
+
}
|
|
120
|
+
function generateRetrieveMethod(modelName, _modelVar) {
|
|
121
|
+
return `
|
|
122
|
+
/**
|
|
123
|
+
* Retrieve ${modelName} by id. Returns null when not found.
|
|
124
|
+
*/
|
|
125
|
+
public async retrieve(id: string): Promise<any | null> {
|
|
126
|
+
return await findOneByField(TABLE_NAME, 'id', id);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Retrieve a page of ${modelName}s.
|
|
131
|
+
*/
|
|
132
|
+
public async retrieveAll(options: { skip?: number; take?: number } = {}): Promise<any[]> {
|
|
133
|
+
if (!options.skip && !options.take) {
|
|
134
|
+
return await findAll(TABLE_NAME);
|
|
135
|
+
}
|
|
136
|
+
const limit = options.take ?? 100;
|
|
137
|
+
const offset = options.skip ?? 0;
|
|
138
|
+
const result = await query(\`SELECT * FROM "\${TABLE_NAME}" LIMIT $1 OFFSET $2\`, [limit, offset]);
|
|
139
|
+
return result.rows;
|
|
140
|
+
}
|
|
141
|
+
`;
|
|
142
|
+
}
|
|
143
|
+
function generateUpdateMethod(modelName, modelVar) {
|
|
144
|
+
return `
|
|
145
|
+
/**
|
|
146
|
+
* Update ${modelName}.
|
|
147
|
+
*/
|
|
148
|
+
public async update(id: string, data: any): Promise<any> {
|
|
149
|
+
const validation = this.validate(data, { operation: 'update' });
|
|
150
|
+
if (!validation.valid) throw new Error(\`Validation failed: \${validation.errors.join(', ')}\`);
|
|
151
|
+
|
|
152
|
+
// Strip nested objects + id \u2014 only scalar fields are written.
|
|
153
|
+
const updateData: Record<string, unknown> = {};
|
|
154
|
+
for (const [key, value] of Object.entries(data)) {
|
|
155
|
+
if (key === 'id') continue;
|
|
156
|
+
if (Array.isArray(value)) continue;
|
|
157
|
+
if (value !== null && typeof value === 'object' && !(value instanceof Date)) continue;
|
|
158
|
+
updateData[key] = value;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
await updateOneById(TABLE_NAME, id, updateData);
|
|
162
|
+
const ${modelVar} = await findOneByField(TABLE_NAME, 'id', id);
|
|
163
|
+
if (!${modelVar}) throw new Error('${modelName} not found after update');
|
|
164
|
+
|
|
165
|
+
await eventBus.publish('${modelName}Updated', { ...${modelVar}, timestamp: new Date().toISOString() } as any);
|
|
166
|
+
return ${modelVar};
|
|
167
|
+
}
|
|
168
|
+
`;
|
|
169
|
+
}
|
|
170
|
+
function generateEvolveMethod(model, modelName, modelVar) {
|
|
171
|
+
const lifecycles = Array.isArray(model.lifecycles) ? model.lifecycles : model.lifecycles ? Object.entries(model.lifecycles).map(([name, lc]) => ({ name, ...lc })) : [];
|
|
172
|
+
const lifecycle = lifecycles[0];
|
|
173
|
+
const lifecycleName = lifecycle?.name || "status";
|
|
174
|
+
const validTransitions = lifecycle ? buildTransitionMap(lifecycle) : {};
|
|
175
|
+
const states = lifecycle?.states && lifecycle.states.length > 0 ? lifecycle.states.map((s) => typeof s === "string" ? s : s.name) : Array.from(/* @__PURE__ */ new Set([
|
|
176
|
+
...Object.keys(validTransitions),
|
|
177
|
+
...Object.values(validTransitions).flat()
|
|
178
|
+
]));
|
|
179
|
+
return `
|
|
180
|
+
/**
|
|
181
|
+
* Evolve ${modelName} through lifecycle "${lifecycleName}"
|
|
182
|
+
* States: ${states.join(" \u2192 ") || "(none declared)"}
|
|
183
|
+
*/
|
|
184
|
+
public async evolve(id: string, data: any): Promise<any> {
|
|
185
|
+
const current = await findOneByField(TABLE_NAME, 'id', id);
|
|
186
|
+
if (!current) throw new Error('${modelName} not found');
|
|
187
|
+
|
|
188
|
+
const targetLifecycle = data?.lifecycleName || '${lifecycleName}';
|
|
189
|
+
const targetState = data?.toState ?? data?.state ?? data?.[targetLifecycle];
|
|
190
|
+
if (!targetState) throw new Error('evolve requires toState (or ${lifecycleName}) in the request body');
|
|
191
|
+
|
|
192
|
+
${states.length > 0 ? `
|
|
193
|
+
const currentState = (current as any)[targetLifecycle];
|
|
194
|
+
const validTransitions: Record<string, string[]> = ${JSON.stringify(validTransitions)};
|
|
195
|
+
const allowed = validTransitions[currentState] || [];
|
|
196
|
+
if (!allowed.includes(targetState)) {
|
|
197
|
+
throw new Error(\`Invalid transition: \${currentState} \u2192 \${targetState}. Allowed: \${allowed.join(', ') || 'none'}\`);
|
|
198
|
+
}
|
|
199
|
+
` : ""}
|
|
200
|
+
|
|
201
|
+
await updateOneById(TABLE_NAME, id, { [targetLifecycle]: targetState });
|
|
202
|
+
const ${modelVar} = await findOneByField(TABLE_NAME, 'id', id);
|
|
203
|
+
if (!${modelVar}) throw new Error('${modelName} not found after evolve');
|
|
204
|
+
|
|
205
|
+
await eventBus.publish('${modelName}Evolved', { ...${modelVar}, timestamp: new Date().toISOString() } as any);
|
|
206
|
+
return ${modelVar};
|
|
207
|
+
}
|
|
208
|
+
`;
|
|
209
|
+
}
|
|
210
|
+
function generateDeleteMethod(modelName, modelVar) {
|
|
211
|
+
return `
|
|
212
|
+
/**
|
|
213
|
+
* Delete ${modelName}.
|
|
214
|
+
*/
|
|
215
|
+
public async delete(id: string): Promise<void> {
|
|
216
|
+
const ${modelVar} = await findOneByField(TABLE_NAME, 'id', id);
|
|
217
|
+
await deleteOneById(TABLE_NAME, id);
|
|
218
|
+
if (${modelVar}) {
|
|
219
|
+
await eventBus.publish('${modelName}Deleted', { ...${modelVar}, timestamp: new Date().toISOString() } as any);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
`;
|
|
223
|
+
}
|
|
224
|
+
import { matchPgStep } from "./step-conventions.js";
|
|
225
|
+
function generateCustomActions(controller, modelRegistry = {}) {
|
|
226
|
+
if (!controller.actions || Object.keys(controller.actions).length === 0) {
|
|
227
|
+
return { code: "", needsAiBehaviors: false };
|
|
228
|
+
}
|
|
229
|
+
const CRUD_NAMES = /* @__PURE__ */ new Set(["create", "retrieve", "retrieveAll", "update", "evolve", "delete", "validate"]);
|
|
230
|
+
const modelName = controller.model || (controller.name || "").replace(/Controller$/, "") || "Model";
|
|
231
|
+
const tableNameLocal = modelName.toLowerCase() + "s";
|
|
232
|
+
const out = [];
|
|
233
|
+
let needsAiBehaviors = false;
|
|
234
|
+
for (const [actionName, action] of Object.entries(controller.actions)) {
|
|
235
|
+
if (CRUD_NAMES.has(actionName)) {
|
|
236
|
+
console.warn(
|
|
237
|
+
`\u26A0\uFE0F ${controller.name || "Controller"}.${actionName} \u2014 behaviour-derived action collides with the auto-generated CURVED \`${actionName}\` op. Dropped to avoid TS2393 duplicate-implementation. Rename the behaviour (e.g. \`${actionName}Soft\` / \`hardDelete\`) if you need the custom logic.`
|
|
238
|
+
);
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const steps = Array.isArray(action.steps) ? action.steps : [];
|
|
242
|
+
const stepsHeader = steps.length > 0 ? steps.map((s) => ` * - ${typeof s === "string" ? s : s.action || JSON.stringify(s)}`).join("\n") : " * (no spec steps declared)";
|
|
243
|
+
const declaredVars = /* @__PURE__ */ new Set();
|
|
244
|
+
const stepBodies = [];
|
|
245
|
+
let usesArgs = false;
|
|
246
|
+
let actionRefersToAi = false;
|
|
247
|
+
steps.forEach((rawStep, i) => {
|
|
248
|
+
const stepText = typeof rawStep === "string" ? rawStep : rawStep?.step || rawStep?.action;
|
|
249
|
+
if (typeof stepText !== "string") {
|
|
250
|
+
stepBodies.push(` // Step ${i + 1}: (non-string step ignored)`);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const ctx = {
|
|
254
|
+
modelName,
|
|
255
|
+
tableName: tableNameLocal,
|
|
256
|
+
serviceName: controller.name || "Controller",
|
|
257
|
+
operationName: actionName,
|
|
258
|
+
stepNum: i + 1,
|
|
259
|
+
parameterNames: Object.keys(action.parameters || {}),
|
|
260
|
+
declaredVars,
|
|
261
|
+
models: modelRegistry
|
|
262
|
+
};
|
|
263
|
+
const result = matchPgStep(stepText, ctx);
|
|
264
|
+
stepBodies.push(result.call);
|
|
265
|
+
if (/\bargs\./.test(result.call)) usesArgs = true;
|
|
266
|
+
if (!result.matched) actionRefersToAi = true;
|
|
267
|
+
});
|
|
268
|
+
if (actionRefersToAi) needsAiBehaviors = true;
|
|
269
|
+
const argsParam = usesArgs ? "args: any = {}" : "_args: any = {}";
|
|
270
|
+
let combined = stepBodies.join("\n\n");
|
|
271
|
+
const stepResultRe = /const\s+(step\d+Result)\s*=/g;
|
|
272
|
+
let mres;
|
|
273
|
+
const declared = [];
|
|
274
|
+
while ((mres = stepResultRe.exec(combined)) !== null) declared.push(mres[1]);
|
|
275
|
+
for (const name of declared) {
|
|
276
|
+
const refCount = (combined.match(new RegExp(`\\b${name}\\b`, "g")) || []).length;
|
|
277
|
+
if (refCount <= 1) {
|
|
278
|
+
combined = combined.replace(new RegExp(`const\\s+${name}\\s*=\\s*`), "");
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const body = steps.length > 0 ? combined + `
|
|
282
|
+
return { success: true };` : ` throw new Error('${controller.name || "Controller"}.${actionName} is not implemented');`;
|
|
283
|
+
out.push(`
|
|
284
|
+
/**
|
|
285
|
+
* ${actionName}
|
|
286
|
+
* ${action.description || ""}
|
|
287
|
+
*
|
|
288
|
+
* Spec steps:
|
|
289
|
+
${stepsHeader}
|
|
290
|
+
*/
|
|
291
|
+
public async ${actionName}(${argsParam}): Promise<any> {
|
|
292
|
+
${body}
|
|
293
|
+
}
|
|
294
|
+
`);
|
|
295
|
+
}
|
|
296
|
+
return { code: out.join("\n"), needsAiBehaviors };
|
|
297
|
+
}
|
|
298
|
+
export {
|
|
299
|
+
generatePgNativeController as default
|
|
300
|
+
};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
function generatePgSchemaSql(context) {
|
|
2
|
+
const { spec, models } = context;
|
|
3
|
+
const allModels = [];
|
|
4
|
+
if (Array.isArray(models) && models.length > 0) {
|
|
5
|
+
for (const m of models) if (m?.name) allModels.push([m.name, m]);
|
|
6
|
+
} else if (spec?.components) {
|
|
7
|
+
const components = Array.isArray(spec.components) ? spec.components : Object.values(spec.components);
|
|
8
|
+
for (const comp of components) {
|
|
9
|
+
const ms = comp?.models;
|
|
10
|
+
if (!ms) continue;
|
|
11
|
+
const entries = Array.isArray(ms) ? ms.map((m) => [m.name, m]) : Object.entries(ms);
|
|
12
|
+
for (const [name, m] of entries) {
|
|
13
|
+
if (name) allModels.push([name, m]);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const banner = `-- ============================================================
|
|
18
|
+
-- ${spec?.metadata?.component || "Application"} \u2014 schema.sql
|
|
19
|
+
-- Generated by @specverse/engines (postgres-native).
|
|
20
|
+
-- Run via: psql "$POSTGRES_URL" -f src/db/schema.sql
|
|
21
|
+
-- Re-runnable: every statement is IF NOT EXISTS / idempotent.
|
|
22
|
+
-- ============================================================
|
|
23
|
+
CREATE EXTENSION IF NOT EXISTS "pgcrypto"; -- for gen_random_uuid()
|
|
24
|
+
`;
|
|
25
|
+
if (allModels.length === 0) {
|
|
26
|
+
return banner + "\n-- No models declared. (Add one to your spec to populate this file.)\n";
|
|
27
|
+
}
|
|
28
|
+
const tableBlocks = allModels.map(([name, model]) => generateTable(name, model));
|
|
29
|
+
return banner + "\n" + tableBlocks.join("\n\n") + "\n";
|
|
30
|
+
}
|
|
31
|
+
function generateTable(modelName, model) {
|
|
32
|
+
const table = model?.storage?.table || modelName.toLowerCase() + "s";
|
|
33
|
+
const attrs = model.attributes;
|
|
34
|
+
if (!attrs) {
|
|
35
|
+
return `-- ${modelName}
|
|
36
|
+
CREATE TABLE IF NOT EXISTS "${table}" (
|
|
37
|
+
id TEXT PRIMARY KEY
|
|
38
|
+
);`;
|
|
39
|
+
}
|
|
40
|
+
const list = Array.isArray(attrs) ? attrs.map((a) => [a.name, a]) : Object.entries(attrs);
|
|
41
|
+
const columns = [];
|
|
42
|
+
const indexes = [];
|
|
43
|
+
let hasIdColumn = false;
|
|
44
|
+
for (const [colName, attr] of list) {
|
|
45
|
+
if (!colName) continue;
|
|
46
|
+
const { sql, isPk, isUnique } = columnDef(colName, attr, modelName);
|
|
47
|
+
if (isPk) hasIdColumn = true;
|
|
48
|
+
columns.push(" " + sql);
|
|
49
|
+
if (isUnique && !isPk) {
|
|
50
|
+
indexes.push(
|
|
51
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS "${table}_${colName}_uq" ON "${table}" ("${colName}");`
|
|
52
|
+
);
|
|
53
|
+
} else if (colName.endsWith("Id") && colName !== "id") {
|
|
54
|
+
indexes.push(
|
|
55
|
+
`CREATE INDEX IF NOT EXISTS "${table}_${colName}_idx" ON "${table}" ("${colName}");`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (!hasIdColumn) {
|
|
60
|
+
columns.unshift(' "id" TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text');
|
|
61
|
+
}
|
|
62
|
+
const declaredNames = new Set(list.map(([n]) => n));
|
|
63
|
+
if (!declaredNames.has("createdAt")) {
|
|
64
|
+
columns.push(' "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()');
|
|
65
|
+
}
|
|
66
|
+
if (!declaredNames.has("updatedAt")) {
|
|
67
|
+
columns.push(' "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()');
|
|
68
|
+
}
|
|
69
|
+
const lifecycles = Array.isArray(model.lifecycles) ? model.lifecycles : model.lifecycles ? Object.entries(model.lifecycles).map(([name, lc]) => ({ name, ...lc })) : [];
|
|
70
|
+
for (const lc of lifecycles) {
|
|
71
|
+
const lcName = lc?.name;
|
|
72
|
+
if (!lcName || declaredNames.has(lcName)) continue;
|
|
73
|
+
const initial = deriveInitialState(lc);
|
|
74
|
+
const defaultClause = initial ? ` DEFAULT '${initial.replace(/'/g, "''")}'` : "";
|
|
75
|
+
columns.push(` "${lcName}" TEXT NOT NULL${defaultClause}`);
|
|
76
|
+
}
|
|
77
|
+
const indexBlock = indexes.length > 0 ? "\n\n" + indexes.join("\n") : "";
|
|
78
|
+
return `-- ${modelName}
|
|
79
|
+
CREATE TABLE IF NOT EXISTS "${table}" (
|
|
80
|
+
${columns.join(",\n")}
|
|
81
|
+
);${indexBlock}`;
|
|
82
|
+
}
|
|
83
|
+
function columnDef(name, attr, _modelName) {
|
|
84
|
+
const required = !!attr.required;
|
|
85
|
+
const unique = !!attr.unique;
|
|
86
|
+
const type = (attr.type || "String").toLowerCase();
|
|
87
|
+
const isIdColumn = name === "id";
|
|
88
|
+
if (isIdColumn) {
|
|
89
|
+
if (type === "uuid") {
|
|
90
|
+
return { sql: `"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()`, isPk: true, isUnique: true };
|
|
91
|
+
}
|
|
92
|
+
return { sql: `"id" TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text`, isPk: true, isUnique: true };
|
|
93
|
+
}
|
|
94
|
+
let sqlType;
|
|
95
|
+
switch (type) {
|
|
96
|
+
case "integer":
|
|
97
|
+
case "int":
|
|
98
|
+
sqlType = "INTEGER";
|
|
99
|
+
break;
|
|
100
|
+
case "bigint":
|
|
101
|
+
sqlType = "BIGINT";
|
|
102
|
+
break;
|
|
103
|
+
case "float":
|
|
104
|
+
case "number":
|
|
105
|
+
case "double":
|
|
106
|
+
sqlType = "DOUBLE PRECISION";
|
|
107
|
+
break;
|
|
108
|
+
case "boolean":
|
|
109
|
+
case "bool":
|
|
110
|
+
sqlType = "BOOLEAN";
|
|
111
|
+
break;
|
|
112
|
+
case "datetime":
|
|
113
|
+
case "date":
|
|
114
|
+
case "timestamp":
|
|
115
|
+
sqlType = "TIMESTAMPTZ";
|
|
116
|
+
break;
|
|
117
|
+
case "uuid":
|
|
118
|
+
sqlType = "UUID";
|
|
119
|
+
break;
|
|
120
|
+
case "json":
|
|
121
|
+
case "jsonb":
|
|
122
|
+
sqlType = "JSONB";
|
|
123
|
+
break;
|
|
124
|
+
default:
|
|
125
|
+
sqlType = "TEXT";
|
|
126
|
+
}
|
|
127
|
+
const nullness = required ? " NOT NULL" : "";
|
|
128
|
+
const uniqueClause = unique ? " UNIQUE" : "";
|
|
129
|
+
const defaultClause = formatColumnDefault(attr.default, type);
|
|
130
|
+
return {
|
|
131
|
+
sql: `"${name}" ${sqlType}${nullness}${uniqueClause}${defaultClause}`,
|
|
132
|
+
isPk: false,
|
|
133
|
+
isUnique: unique
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function deriveInitialState(lc) {
|
|
137
|
+
if (!lc) return null;
|
|
138
|
+
if (typeof lc.initial === "string") return lc.initial;
|
|
139
|
+
if (Array.isArray(lc.states) && lc.states.length > 0) {
|
|
140
|
+
const first = lc.states[0];
|
|
141
|
+
return typeof first === "string" ? first : first?.name ?? null;
|
|
142
|
+
}
|
|
143
|
+
if (typeof lc.flow === "string") {
|
|
144
|
+
const head = lc.flow.split(/\s*->\s*/)[0]?.trim();
|
|
145
|
+
return head || null;
|
|
146
|
+
}
|
|
147
|
+
if (lc.transitions && typeof lc.transitions === "object") {
|
|
148
|
+
const first = Object.values(lc.transitions)[0];
|
|
149
|
+
if (typeof first === "string") return first.split(/\s*->\s*/)[0]?.trim() || null;
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
function formatColumnDefault(value, type) {
|
|
154
|
+
if (value === void 0 || value === null) return "";
|
|
155
|
+
if (typeof value === "boolean") return ` DEFAULT ${value}`;
|
|
156
|
+
if (typeof value === "number") return ` DEFAULT ${value}`;
|
|
157
|
+
if (typeof value === "string") {
|
|
158
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) return ` DEFAULT ${value}`;
|
|
159
|
+
if (value === "true" || value === "false") return ` DEFAULT ${value}`;
|
|
160
|
+
if (value === "now" && (type === "datetime" || type === "date" || type === "timestamp")) {
|
|
161
|
+
return ` DEFAULT NOW()`;
|
|
162
|
+
}
|
|
163
|
+
return ` DEFAULT '${value.replace(/'/g, "''")}'`;
|
|
164
|
+
}
|
|
165
|
+
return "";
|
|
166
|
+
}
|
|
167
|
+
export {
|
|
168
|
+
generatePgSchemaSql as default
|
|
169
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
function generatePgNativeService(context) {
|
|
2
|
+
const { service } = context;
|
|
3
|
+
if (!service) throw new Error("Service is required in template context");
|
|
4
|
+
const serviceName = service.name;
|
|
5
|
+
const operationsCode = generateOperations(service);
|
|
6
|
+
const usesDb = /\bquery\b|\bgetPool\b/.test(operationsCode);
|
|
7
|
+
const hasEvents = service.publishes && service.publishes.length > 0 || service.subscribes && service.subscribes.length > 0;
|
|
8
|
+
return `/**
|
|
9
|
+
* ${serviceName}
|
|
10
|
+
* Abstract business logic service (PostgreSQL native driver)
|
|
11
|
+
* ${service.description || ""}
|
|
12
|
+
*/
|
|
13
|
+
${usesDb ? `import { query, getPool } from '../db/pgClient.js';` : ""}
|
|
14
|
+
${hasEvents ? `import { eventBus } from '../events/eventBus.js';` : ""}
|
|
15
|
+
|
|
16
|
+
export class ${serviceName} {
|
|
17
|
+
${operationsCode}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const ${lowerFirst(serviceName)} = new ${serviceName}();
|
|
21
|
+
export const ${lowerFirst(serviceName)}Instance = ${lowerFirst(serviceName)};
|
|
22
|
+
export default ${lowerFirst(serviceName)};
|
|
23
|
+
`;
|
|
24
|
+
}
|
|
25
|
+
function lowerFirst(s) {
|
|
26
|
+
return s.charAt(0).toLowerCase() + s.slice(1);
|
|
27
|
+
}
|
|
28
|
+
function generateOperations(service) {
|
|
29
|
+
const ops = service.operations;
|
|
30
|
+
if (!ops || Array.isArray(ops) && ops.length === 0 || !Array.isArray(ops) && Object.keys(ops).length === 0) {
|
|
31
|
+
return `
|
|
32
|
+
/**
|
|
33
|
+
* Default service entrypoint \u2014 replace with real operations once declared
|
|
34
|
+
* on the service's spec.
|
|
35
|
+
*/
|
|
36
|
+
public async execute(_params: any = {}): Promise<any> {
|
|
37
|
+
throw new Error('${service.name}.execute is not implemented');
|
|
38
|
+
}
|
|
39
|
+
`;
|
|
40
|
+
}
|
|
41
|
+
const entries = Array.isArray(ops) ? ops.map((op) => [op.name, op]) : Object.entries(ops);
|
|
42
|
+
return entries.map(([name, op]) => generateOperation(name, op, service.name)).join("\n");
|
|
43
|
+
}
|
|
44
|
+
function generateOperation(operationName, operation, serviceName) {
|
|
45
|
+
const stepsHeader = operation.steps && operation.steps.length > 0 ? operation.steps.map((s) => ` * - ${typeof s === "string" ? s : s.action || JSON.stringify(s)}`).join("\n") : " * (no spec steps declared)";
|
|
46
|
+
return `
|
|
47
|
+
/**
|
|
48
|
+
* ${operationName}
|
|
49
|
+
* ${operation.description || ""}
|
|
50
|
+
*
|
|
51
|
+
* Spec steps:
|
|
52
|
+
${stepsHeader}
|
|
53
|
+
*/
|
|
54
|
+
public async ${operationName}(_args: any = {}): Promise<any> {
|
|
55
|
+
// TODO: translate spec steps into pg-native SQL calls. Controllers
|
|
56
|
+
// already inline conventions today; service-side parity is a
|
|
57
|
+
// follow-up. For now this stub keeps realize completing and the
|
|
58
|
+
// service surface callable.
|
|
59
|
+
throw new Error('${serviceName}.${operationName} is not implemented');
|
|
60
|
+
}
|
|
61
|
+
`;
|
|
62
|
+
}
|
|
63
|
+
export {
|
|
64
|
+
generatePgNativeService as default
|
|
65
|
+
};
|