@apso/cli 0.47.6 → 0.49.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 (141) hide show
  1. package/README.md +28 -1
  2. package/dist/commands/dev.d.ts +2 -0
  3. package/dist/commands/dev.js +20 -3
  4. package/dist/commands/generate.js +55 -13
  5. package/dist/commands/mcp/serve.js +24 -41
  6. package/dist/commands/schema/diff.js +3 -4
  7. package/dist/commands/schema/pull.js +13 -11
  8. package/dist/commands/schema/push.js +6 -5
  9. package/dist/commands/schema/validate.d.ts +10 -0
  10. package/dist/commands/schema/validate.js +54 -0
  11. package/dist/commands/test/access.d.ts +11 -0
  12. package/dist/commands/test/access.js +65 -0
  13. package/dist/lib/access/cases.d.ts +120 -0
  14. package/dist/lib/access/cases.js +1163 -0
  15. package/dist/lib/access/index.d.ts +4 -0
  16. package/dist/lib/access/index.js +7 -0
  17. package/dist/lib/access/report.d.ts +75 -0
  18. package/dist/lib/access/report.js +118 -0
  19. package/dist/lib/access/rules.json +207 -0
  20. package/dist/lib/access/run.d.ts +38 -0
  21. package/dist/lib/access/run.js +111 -0
  22. package/dist/lib/access/tokens.d.ts +46 -0
  23. package/dist/lib/access/tokens.js +139 -0
  24. package/dist/lib/api/services.d.ts +10 -7
  25. package/dist/lib/api/services.js +19 -32
  26. package/dist/lib/apsorc-parser.d.ts +1 -1
  27. package/dist/lib/apsorc-parser.js +2 -0
  28. package/dist/lib/ddl/change.js +2 -0
  29. package/dist/lib/ddl/index.d.ts +11 -1
  30. package/dist/lib/ddl/index.js +30 -16
  31. package/dist/lib/ddl/sync.d.ts +25 -0
  32. package/dist/lib/ddl/sync.js +78 -0
  33. package/dist/lib/deploy/server-push.js +3 -1
  34. package/dist/lib/generators/go.d.ts +25 -7
  35. package/dist/lib/generators/go.js +365 -128
  36. package/dist/lib/generators/python.d.ts +9 -3
  37. package/dist/lib/generators/python.js +282 -47
  38. package/dist/lib/generators/typescript.d.ts +3 -5
  39. package/dist/lib/generators/typescript.js +78 -64
  40. package/dist/lib/guards.d.ts +111 -13
  41. package/dist/lib/guards.js +287 -23
  42. package/dist/lib/templates/entities/entity-col-array.eta +1 -1
  43. package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
  44. package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
  45. package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
  46. package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
  47. package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
  48. package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
  49. package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
  50. package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
  51. package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
  52. package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
  53. package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
  54. package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
  55. package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
  56. package/dist/lib/templates/go/dto/dto.eta +17 -18
  57. package/dist/lib/templates/go/handlers/handler.eta +10 -8
  58. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  59. package/dist/lib/templates/go/index-module.eta +10 -5
  60. package/dist/lib/templates/go/mcp.eta +307 -0
  61. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  62. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  63. package/dist/lib/templates/go/models/model.eta +22 -19
  64. package/dist/lib/templates/go/models/schema.eta +72 -0
  65. package/dist/lib/templates/go/services/service.eta +84 -35
  66. package/dist/lib/templates/go/utils/query.eta +68 -7
  67. package/dist/lib/templates/guards/guards.module.eta +37 -29
  68. package/dist/lib/templates/guards/index.eta +4 -0
  69. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  70. package/dist/lib/templates/guards/key.guard.eta +280 -0
  71. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  72. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  73. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  74. package/dist/lib/templates/python/auth.eta +354 -95
  75. package/dist/lib/templates/python/index-module.eta +7 -7
  76. package/dist/lib/templates/python/mcp.eta +284 -0
  77. package/dist/lib/templates/python/models/init.eta +24 -0
  78. package/dist/lib/templates/python/models/model.eta +30 -61
  79. package/dist/lib/templates/python/permissions.eta +121 -0
  80. package/dist/lib/templates/python/routers/router.eta +39 -1
  81. package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
  82. package/dist/lib/templates/python/schemas/schema.eta +27 -14
  83. package/dist/lib/templates/python/services/service.eta +38 -15
  84. package/dist/lib/templates/python/utils/query.eta +52 -25
  85. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  86. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  87. package/dist/lib/templates/rest/service-rest.eta +3 -44
  88. package/dist/lib/types/auth.d.ts +84 -80
  89. package/dist/lib/types/auth.js +77 -60
  90. package/dist/lib/types/entity.d.ts +17 -9
  91. package/dist/lib/types/entity.js +3 -0
  92. package/dist/lib/types/index.d.ts +2 -2
  93. package/dist/lib/types/index.js +6 -5
  94. package/dist/lib/utils/crud-deps.d.ts +77 -6
  95. package/dist/lib/utils/crud-deps.js +197 -14
  96. package/dist/lib/utils/field.d.ts +12 -0
  97. package/dist/lib/utils/field.js +18 -2
  98. package/dist/lib/utils/schema-convert.d.ts +20 -43
  99. package/dist/lib/utils/schema-convert.js +28 -78
  100. package/dist/lib/utils/template.d.ts +11 -0
  101. package/dist/lib/utils/template.js +36 -1
  102. package/dist/lib/verify/index.d.ts +6 -1
  103. package/dist/lib/verify/index.js +30 -13
  104. package/npm-shrinkwrap.json +2 -2
  105. package/oclif.manifest.json +36 -1
  106. package/package.json +1 -1
  107. package/dist/lib/templates/go/models/model-col-array.eta +0 -1
  108. package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
  109. package/dist/lib/templates/go/models/model-col-date.eta +0 -1
  110. package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
  111. package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
  112. package/dist/lib/templates/go/models/model-col-float.eta +0 -1
  113. package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
  114. package/dist/lib/templates/go/models/model-col-json.eta +0 -1
  115. package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
  116. package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
  117. package/dist/lib/templates/go/models/model-col-string.eta +0 -1
  118. package/dist/lib/templates/go/models/model-col-text.eta +0 -1
  119. package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
  120. package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
  121. package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
  122. package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
  123. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  124. package/dist/lib/templates/guards/auth.guard.eta +0 -233
  125. package/dist/lib/templates/python/models/model-col-array.eta +0 -4
  126. package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
  127. package/dist/lib/templates/python/models/model-col-date.eta +0 -4
  128. package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
  129. package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
  130. package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
  131. package/dist/lib/templates/python/models/model-col-float.eta +0 -6
  132. package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
  133. package/dist/lib/templates/python/models/model-col-json.eta +0 -4
  134. package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
  135. package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
  136. package/dist/lib/templates/python/models/model-col-string.eta +0 -6
  137. package/dist/lib/templates/python/models/model-col-text.eta +0 -6
  138. package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
  139. package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
  140. package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
  141. package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
@@ -12,7 +12,76 @@ const relationships_1 = require("../utils/relationships");
12
12
  const casing_1 = require("../utils/casing");
13
13
  const events_1 = require("../events");
14
14
  const migration_file_1 = require("../ddl/migration-file");
15
+ const ddl_1 = require("../ddl");
16
+ const sync_1 = require("../ddl/sync");
15
17
  const pluralize_1 = tslib_1.__importDefault(require("pluralize"));
18
+ // Postgres array element type -> lib/pq array type and its Go element type.
19
+ // Anything else is read and written as text (pq.StringArray).
20
+ const pqArrayTypes = {
21
+ integer: ["pq.Int32Array", "int32"],
22
+ int: ["pq.Int32Array", "int32"],
23
+ int4: ["pq.Int32Array", "int32"],
24
+ smallint: ["pq.Int32Array", "int32"],
25
+ bigint: ["pq.Int64Array", "int64"],
26
+ numeric: ["pq.Float64Array", "float64"],
27
+ decimal: ["pq.Float64Array", "float64"],
28
+ float: ["pq.Float64Array", "float64"],
29
+ float8: ["pq.Float64Array", "float64"],
30
+ "double precision": ["pq.Float64Array", "float64"],
31
+ real: ["pq.Float32Array", "float32"],
32
+ boolean: ["pq.BoolArray", "bool"],
33
+ bool: ["pq.BoolArray", "bool"],
34
+ };
35
+ // Field type -> [Go type, DTO template]. Arrays and enums are typed per field.
36
+ const goFieldTypes = {
37
+ text: ["string", "text"],
38
+ string: ["string", "string"],
39
+ varchar: ["string", "varchar"],
40
+ char: ["string", "varchar"],
41
+ uuid: ["string", "uuid"],
42
+ enum: ["string", "enum"],
43
+ integer: ["int", "integer"],
44
+ bigint: ["int64", "integer"],
45
+ smallint: ["int16", "integer"],
46
+ float: ["float64", "float"],
47
+ double: ["float64", "float"],
48
+ decimal: ["float64", "decimal"],
49
+ numeric: ["float64", "numeric"],
50
+ boolean: ["bool", "boolean"],
51
+ date: ["time.Time", "date"],
52
+ timestamp: ["time.Time", "timestamp"],
53
+ timestamptz: ["time.Time", "timestamptz"],
54
+ json: ["map[string]interface{}", "json"],
55
+ jsonb: ["map[string]interface{}", "jsonb"],
56
+ "json-plain": ["map[string]interface{}", "json"],
57
+ array: ["", "array"],
58
+ };
59
+ /**
60
+ * A gorm struct tag value from its settings. gorm splits on ";" (a "\;"
61
+ * stays literal), and the tag is a Go string literal, so quotes and
62
+ * backslashes are escaped for it.
63
+ */
64
+ const gormTag = (settings) => settings
65
+ .map((s) => s.replace(/;/g, "\\;"))
66
+ .join(";")
67
+ .replace(/\\/g, "\\\\")
68
+ .replace(/"/g, '\\"');
69
+ /** The JSON Schema of a Go DTO field type, for MCP tool input schemas. */
70
+ const jsonType = (goType) => {
71
+ if (goType === "string")
72
+ return { type: "string" };
73
+ if (goType === "time.Time")
74
+ return { type: "string", format: "date-time" };
75
+ if (goType === "bool")
76
+ return { type: "boolean" };
77
+ if (goType.startsWith("int") || goType.startsWith("uint"))
78
+ return { type: "integer" };
79
+ if (goType.startsWith("float"))
80
+ return { type: "number" };
81
+ if (goType.startsWith("[]") || goType.endsWith("Array"))
82
+ return { type: "array" };
83
+ return {};
84
+ };
16
85
  /**
17
86
  * Go/Gin generator that produces GORM models, DTOs, Gin handlers,
18
87
  * and service layer code.
@@ -34,20 +103,21 @@ class GoGenerator extends base_1.BaseGenerator {
34
103
  return ".go";
35
104
  }
36
105
  validateConfig(config) {
37
- var _a;
106
+ var _a, _b;
38
107
  const errors = [];
39
108
  const warnings = [];
40
109
  // Validate that entities are provided
41
110
  if (!config.entities || config.entities.length === 0) {
42
111
  errors.push("No entities defined in configuration");
43
112
  }
113
+ errors.push(...(0, guards_1.removedScopeOptionErrors)((_a = config.entities) !== null && _a !== void 0 ? _a : []));
44
114
  // Validate each entity
45
115
  for (const entity of config.entities) {
46
116
  if (!entity.name) {
47
117
  errors.push("Entity missing required 'name' property");
48
118
  }
49
119
  // Validate field types
50
- for (const field of (_a = entity.fields) !== null && _a !== void 0 ? _a : []) {
120
+ for (const field of (_b = entity.fields) !== null && _b !== void 0 ? _b : []) {
51
121
  if (!field.name) {
52
122
  errors.push(`Entity '${entity.name}' has a field without a name`);
53
123
  }
@@ -59,7 +129,12 @@ class GoGenerator extends base_1.BaseGenerator {
59
129
  "text",
60
130
  "varchar",
61
131
  "string",
132
+ "char",
62
133
  "integer",
134
+ "bigint",
135
+ "smallint",
136
+ "double",
137
+ "json-plain",
63
138
  "boolean",
64
139
  "float",
65
140
  "decimal",
@@ -84,30 +159,6 @@ class GoGenerator extends base_1.BaseGenerator {
84
159
  }
85
160
  return this.createValidationResult(errors, warnings);
86
161
  }
87
- /**
88
- * Maps .apsorc field types to Go types
89
- */
90
- mapFieldToGoType(field) {
91
- const typeMap = {
92
- text: "string",
93
- varchar: "string",
94
- string: "string",
95
- integer: "int",
96
- boolean: "bool",
97
- float: "float64",
98
- decimal: "float64",
99
- numeric: "float64",
100
- date: "time.Time",
101
- timestamp: "time.Time",
102
- timestamptz: "time.Time",
103
- json: "map[string]interface{}",
104
- jsonb: "map[string]interface{}",
105
- uuid: "string",
106
- enum: "string",
107
- array: "[]string",
108
- };
109
- return typeMap[field.type || "string"] || "string";
110
- }
111
162
  /**
112
163
  * Gets the Go type for primary keys
113
164
  */
@@ -120,58 +171,130 @@ class GoGenerator extends base_1.BaseGenerator {
120
171
  getPrimaryKeySwaggerType(primaryKeyType) {
121
172
  return primaryKeyType === "uuid" ? "string" : "integer";
122
173
  }
174
+ arrayTypes(field, entityName) {
175
+ const elementType = (0, field_1.arrayElementType)(field);
176
+ // It goes into a struct tag, so only a plain type name.
177
+ if (!/^[a-z][\w ]*$/i.test(elementType))
178
+ throw new Error(`Field ${entityName}.${field.name} has an invalid elementType "${elementType}".`);
179
+ const [arrayGoType, arrayItemGoType] = pqArrayTypes[elementType.toLowerCase()] || ["pq.StringArray", "string"];
180
+ return { elementType, arrayGoType, arrayItemGoType };
181
+ }
123
182
  /**
124
- * Transforms fields for Go templates with additional Go-specific properties
183
+ * Fields for the Go templates. The gorm tag carries the column exactly as
184
+ * the DDL writer creates it (name, type, NOT NULL, default), so the model
185
+ * reads and writes the database `apso migrate` builds.
125
186
  */
126
- getGoFieldsForTemplate(fields, entityName) {
127
- const baseFields = (0, field_1.getFieldForTemplate)(fields, entityName);
128
- return baseFields.map((field) => ({
129
- ...field,
130
- goType: this.mapFieldToGoType(field),
131
- pascalName: (0, casing_1.pascalCase)(field.name),
132
- snakeName: (0, casing_1.snakeCase)(field.name),
133
- // The enum type the enums package declares (EntityFieldEnum).
134
- enumType: field.type === "enum" ? field.dataType : undefined,
135
- }));
187
+ getGoFieldsForTemplate(fields, entity) {
188
+ const table = (0, ddl_1.tableName)(entity);
189
+ return (0, field_1.getFieldForTemplate)(fields, entity.name).map((field) => {
190
+ const spec = (0, ddl_1.columnSpec)(table, field);
191
+ const [goScalar, dtoTemplate] = goFieldTypes[field.type] || [];
192
+ const array = field.type === "array" && this.arrayTypes(field, entity.name);
193
+ const enumType = field.type === "enum" ? field.dataType : undefined;
194
+ const scalar = enumType ? `enums.${enumType}` : goScalar;
195
+ const tag = [
196
+ `column:${field.name}`,
197
+ `type:${field.type === "enum"
198
+ ? `"${(0, ddl_1.enumTypeName)(table, field.name)}"`
199
+ : spec.type.toLowerCase().replace("timestamp with time zone", "timestamptz")}`,
200
+ ...(field.primary ? ["primaryKey"] : []),
201
+ ...(spec.notNull ? ["not null"] : []),
202
+ // gorm parses a number or boolean default itself, so it goes unquoted.
203
+ ...(spec.default === undefined
204
+ ? []
205
+ : [`default:${/^(u?int|float|bool)/.test(goScalar) ? String(field.default) : spec.default}`]),
206
+ ...(goScalar === "map[string]interface{}" ? ["serializer:json"] : []),
207
+ ];
208
+ return {
209
+ ...field,
210
+ ...array,
211
+ goType: scalar,
212
+ modelGoType: array
213
+ ? array.arrayGoType
214
+ : goScalar === "map[string]interface{}"
215
+ ? goScalar
216
+ : `*${scalar}`,
217
+ gormTag: gormTag(tag),
218
+ dtoTemplate,
219
+ pascalName: (0, casing_1.pascalCase)(field.name),
220
+ snakeName: (0, casing_1.snakeCase)(field.name),
221
+ // NOT NULL with no default: the create DTO requires it.
222
+ mustSend: spec.notNull && spec.default === undefined,
223
+ enumType,
224
+ };
225
+ });
226
+ }
227
+ /** Relationships with what the Go templates need: field names, columns, join tables. */
228
+ goAssociations(entity, relationships, allEntities) {
229
+ var _a;
230
+ const byName = new Map(allEntities.map((e) => [e.name, e]));
231
+ const relationshipMap = (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {};
232
+ return (0, relationships_1.getRelationshipForTemplate)(entity.name, relationships, allEntities).map((rel) => {
233
+ const target = byName.get(rel.name);
234
+ const many = rel.type === "OneToMany" || rel.type === "ManyToMany";
235
+ const fieldName = (0, casing_1.pascalCase)(many ? rel.pluralizedRelationshipName : rel.relationshipName);
236
+ const owns = rel.type === "ManyToOne" || (rel.type === "OneToOne" && rel.joinTable);
237
+ const fkNullable = rel.type === "OneToOne" || Boolean(rel.nullable);
238
+ const pkGoType = this.getPrimaryKeyGoType((target === null || target === void 0 ? void 0 : target.primaryKeyType) || "serial");
239
+ let join;
240
+ if (rel.type === "ManyToMany" && target) {
241
+ if (rel.joinTable)
242
+ join = (0, ddl_1.joinTableOf)(entity, rel, target);
243
+ else {
244
+ // The other side owns the join table; its key columns swap.
245
+ const owner = (0, relationships_1.getRelationshipForTemplate)(target.name, relationshipMap[target.name] || [], allEntities).find((r) => r.type === "ManyToMany" && r.joinTable && r.name === entity.name);
246
+ if (owner) {
247
+ const j = (0, ddl_1.joinTableOf)(target, owner, entity);
248
+ join = { name: j.name, ownCol: j.otherCol, otherCol: j.ownCol };
249
+ }
250
+ }
251
+ }
252
+ return {
253
+ ...rel,
254
+ fieldName,
255
+ jsonName: (0, casing_1.camelCase)(fieldName),
256
+ owns,
257
+ fkField: `${(0, casing_1.pascalCase)(rel.relationshipName)}ID`,
258
+ fkColumn: owns ? (0, ddl_1.relationColumn)(rel) : undefined,
259
+ fkNullable,
260
+ primaryKeyGoType: pkGoType,
261
+ fkGoType: `${fkNullable ? "*" : ""}${pkGoType}`,
262
+ fkTag: owns
263
+ ? gormTag([
264
+ `column:${(0, ddl_1.relationColumn)(rel)}`,
265
+ `type:${(0, ddl_1.fkType)(target)}`,
266
+ ...(fkNullable ? [] : ["not null"]),
267
+ ])
268
+ : undefined,
269
+ // The child's foreign key field, for OneToMany and the inverse OneToOne.
270
+ foreignKey: `${(0, casing_1.pascalCase)(rel.inverseReferenceName || entity.name)}ID`,
271
+ onDeleteCascade: rel.type === "OneToOne" || Boolean(rel.cascadeDelete),
272
+ join,
273
+ camelReferenceName: (0, casing_1.camelCase)(rel.referenceName || rel.name),
274
+ snakeReferenceName: (0, casing_1.snakeCase)(rel.referenceName || rel.name),
275
+ };
276
+ });
136
277
  }
137
278
  async generateEntity(options) {
138
279
  const { entity, relationships, allEntities, apiType } = options;
139
- const { name, fields = [], indexes, uniques } = entity;
140
- const columns = this.getGoFieldsForTemplate(fields, name);
280
+ const { name, fields = [] } = entity;
281
+ const columns = this.getGoFieldsForTemplate(fields, entity);
141
282
  const createPrimaryKey = columns.filter((column) => column.primary === true).length === 0;
142
- const createdAt = entity.created_at;
143
- const updatedAt = entity.updated_at;
144
283
  const primaryKeyType = entity.primaryKeyType || "serial";
145
- const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(name, relationships, allEntities);
146
- // Add Go-specific properties to relationships
147
- const goRelationships = relationshipsForTemplate.map((rel) => ({
148
- ...rel,
149
- primaryKeyGoType: this.getPrimaryKeyGoType(primaryKeyType),
150
- camelReferenceName: (0, casing_1.camelCase)(rel.referenceName || rel.name),
151
- snakeReferenceName: (0, casing_1.snakeCase)(rel.referenceName || rel.name),
152
- pluralName: (0, casing_1.pascalCase)((0, pluralize_1.default)(rel.name)),
153
- camelPluralName: (0, casing_1.camelCase)((0, pluralize_1.default)(rel.name)),
154
- inverseName: (0, casing_1.pascalCase)(rel.inversePropertyName || name),
155
- }));
156
- const entitiesToImport = (0, relationships_1.getRelationshipsForImport)(name, relationshipsForTemplate);
284
+ const associations = this.goAssociations(entity, relationships, allEntities);
157
285
  const data = {
158
286
  name,
159
- indexes: indexes || [],
160
- uniques: uniques || [],
161
287
  createPrimaryKey,
162
288
  primaryKeyType,
163
- snakeCasedName: (0, casing_1.snakeCase)(name),
164
- // Honor an explicit per-entity `table` override; otherwise derive from
165
- // the entity name. See apsoai/cli#107 (Python/Go parity with #98).
166
- tableName: entity.table || (0, casing_1.snakeCase)(name),
167
- createdAt,
168
- updatedAt,
169
- pluralizedName: (0, casing_1.camelCase)((0, pluralize_1.default)(name)),
170
- pluralName: (0, casing_1.pascalCase)((0, pluralize_1.default)(name)),
289
+ tableName: (0, ddl_1.tableName)(entity),
290
+ createdAt: entity.created_at,
291
+ updatedAt: entity.updated_at,
171
292
  columns,
172
- associations: [...new Set(goRelationships)],
173
- entitiesToImport,
293
+ associations,
294
+ importTime: Boolean(entity.created_at || entity.updated_at) ||
295
+ columns.some((c) => c.goType === "time.Time"),
174
296
  importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
297
+ importPq: (0, field_1.typeExistsInEntity)(entity, "array") !== -1,
175
298
  apiType,
176
299
  };
177
300
  const content = await this.renderTemplate("./models/model", data);
@@ -197,6 +320,8 @@ class GoGenerator extends base_1.BaseGenerator {
197
320
  primaryKeySwaggerType: this.getPrimaryKeySwaggerType(primaryKeyType),
198
321
  associations: [...new Set(relationshipsForTemplate)],
199
322
  scope: (0, guards_1.entityScope)(entity, Boolean(options.auth)),
323
+ // A write that names a row the caller cannot read is answered like a scope error.
324
+ references: this.goReferences(entity, this.goAssociations(entity, relationships, options.allEntities), options.allEntities, options.auth).length > 0,
200
325
  };
201
326
  const content = await this.renderTemplate("./handlers/handler", data);
202
327
  return [
@@ -209,18 +334,8 @@ class GoGenerator extends base_1.BaseGenerator {
209
334
  async generateService(options) {
210
335
  const { entity, relationships, allEntities } = options;
211
336
  const { name: entityName, fields = [] } = entity;
212
- const columns = this.getGoFieldsForTemplate(fields, entityName);
213
- const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships, allEntities);
214
- // Add Go-specific properties to relationships
215
- const goRelationships = relationshipsForTemplate.map((rel) => {
216
- const referencedEntity = allEntities === null || allEntities === void 0 ? void 0 : allEntities.find((e) => e.name === rel.name);
217
- const referencedPrimaryKeyType = (referencedEntity === null || referencedEntity === void 0 ? void 0 : referencedEntity.primaryKeyType) || "serial";
218
- return {
219
- ...rel,
220
- primaryKeyGoType: this.getPrimaryKeyGoType(referencedPrimaryKeyType),
221
- snakeReferenceName: (0, casing_1.snakeCase)(rel.referenceName || rel.name),
222
- };
223
- });
337
+ const columns = this.getGoFieldsForTemplate(fields, entity);
338
+ const goRelationships = this.goAssociations(entity, relationships, allEntities);
224
339
  const pluralEntityName = (0, pluralize_1.default)(entityName);
225
340
  const primaryKeyType = entity.primaryKeyType || "serial";
226
341
  const createdAt = entity.created_at;
@@ -232,8 +347,14 @@ class GoGenerator extends base_1.BaseGenerator {
232
347
  createdAt,
233
348
  updatedAt,
234
349
  columns,
235
- associations: [...new Set(goRelationships)],
350
+ // Auth entities are for service callers only, so no other entity's
351
+ // response carries one.
352
+ associations: goRelationships.map((r) => ({
353
+ ...r,
354
+ hidden: (0, guards_1.hidesRelation)(entityName, r.name, allEntities, options.auth),
355
+ })),
236
356
  scope: this.goScope(entity, Boolean(options.auth)),
357
+ references: this.goReferences(entity, goRelationships, allEntities, options.auth),
237
358
  };
238
359
  const content = await this.renderTemplate("./services/service", data);
239
360
  return [
@@ -248,22 +369,12 @@ class GoGenerator extends base_1.BaseGenerator {
248
369
  const { entity, relationships, allEntities, apiType } = options;
249
370
  const { name: entityName, fields = [] } = entity;
250
371
  const scopeFields = new Set((_a = (0, guards_1.entityScope)(entity, Boolean(options.auth))) === null || _a === void 0 ? void 0 : _a.fields.map((f) => f.field));
251
- const columns = this.getGoFieldsForTemplate(fields, entityName);
252
- const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships, allEntities);
253
- // Add Go-specific properties to relationships
254
- const goRelationships = relationshipsTemplate.map((rel) => {
255
- const referencedEntity = allEntities === null || allEntities === void 0 ? void 0 : allEntities.find((e) => e.name === rel.name);
256
- const referencedPrimaryKeyType = (referencedEntity === null || referencedEntity === void 0 ? void 0 : referencedEntity.primaryKeyType) || "serial";
257
- return {
258
- ...rel,
259
- primaryKeyGoType: this.getPrimaryKeyGoType(referencedPrimaryKeyType),
260
- camelReferenceName: (0, casing_1.camelCase)(rel.referenceName || rel.name),
261
- pluralName: (0, casing_1.pascalCase)((0, pluralize_1.default)(rel.name)),
262
- camelPluralName: (0, casing_1.camelCase)((0, pluralize_1.default)(rel.name)),
263
- // The service sets a scopeBy foreign key from the caller on create.
264
- scoped: scopeFields.has(`${(0, casing_1.camelCase)(rel.referenceName || rel.name)}Id`),
265
- };
266
- });
372
+ const columns = this.getGoFieldsForTemplate(fields, entity);
373
+ const goRelationships = this.goAssociations(entity, relationships, allEntities).map((rel) => ({
374
+ ...rel,
375
+ // The service sets a scopeBy foreign key from the caller on create.
376
+ scoped: scopeFields.has(`${rel.camelReferenceName}Id`),
377
+ }));
267
378
  const primaryKeyColumns = columns.filter((column) => column.primary === true);
268
379
  const addDefaultPKProperty = primaryKeyColumns.length === 0;
269
380
  const createdAt = entity.created_at;
@@ -278,6 +389,8 @@ class GoGenerator extends base_1.BaseGenerator {
278
389
  columns,
279
390
  associations: goRelationships,
280
391
  apiType: apiType !== null && apiType !== void 0 ? apiType : "rest",
392
+ importTime: Boolean(createdAt || updatedAt) ||
393
+ columns.some((c) => c.goType === "time.Time"),
281
394
  importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
282
395
  };
283
396
  const content = await this.renderTemplate("./dto/dto", data);
@@ -367,15 +480,14 @@ ${downStatements}
367
480
  });
368
481
  const content = await this.renderTemplate("./index-module", {
369
482
  entities: entitiesData,
370
- hasAuth: Boolean(opts === null || opts === void 0 ? void 0 : opts.auth),
483
+ permissions: (0, guards_1.hasPermissions)(entities),
371
484
  });
372
- // Generate model registry for AutoMigrate support
373
485
  const modelRefs = entities
374
486
  .map((e) => `\t\t&${(0, casing_1.pascalCase)(e.name)}{},`)
375
487
  .join("\n");
376
488
  const registryContent = `package models
377
489
 
378
- // All returns all registered GORM models for AutoMigrate.
490
+ // All returns all registered GORM models.
379
491
  // This file is auto-generated by the Apso CLI.
380
492
  func All() []interface{} {
381
493
  \treturn []interface{}{
@@ -392,8 +504,47 @@ ${modelRefs}
392
504
  path: "models/registry.go",
393
505
  content: registryContent,
394
506
  },
507
+ {
508
+ path: "models/schema.go",
509
+ content: await this.renderTemplate("./models/schema", this.schemaData(entities)),
510
+ },
395
511
  ];
396
512
  }
513
+ /**
514
+ * DATABASE_SYNC's statements (the DDL writer's, creating only what is
515
+ * missing) and the join table columns gorm must be told about.
516
+ */
517
+ schemaData(entities) {
518
+ var _a, _b;
519
+ const relationshipMap = (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {};
520
+ const legacy = [];
521
+ const joinColumns = new Map();
522
+ for (const entity of entities) {
523
+ const table = (0, ddl_1.tableName)(entity);
524
+ // Older Go models let gorm name columns: snake_case of the Go field.
525
+ const renames = ((_b = entity.fields) !== null && _b !== void 0 ? _b : []).map((f) => [
526
+ (0, casing_1.snakeCase)(f.name),
527
+ f.name,
528
+ ]);
529
+ for (const a of this.goAssociations(entity, relationshipMap[entity.name] || [], entities)) {
530
+ if (a.owns)
531
+ renames.push([`${(0, casing_1.snakeCase)(a.relationshipName)}_id`, a.fkColumn]);
532
+ if (a.join)
533
+ for (const c of [a.join.ownCol, a.join.otherCol])
534
+ joinColumns.set(c.charAt(0).toUpperCase() + c.slice(1), c);
535
+ }
536
+ for (const [from, to] of renames)
537
+ if (from !== to)
538
+ legacy.push((0, sync_1.legacyColumn)(table, from, to));
539
+ }
540
+ return {
541
+ statements: (0, sync_1.syncStatements)({ entities, relationshipMap }, legacy).map((sql) => JSON.stringify(sql)),
542
+ joinColumns: [...joinColumns].map(([k, v]) => [
543
+ JSON.stringify(k),
544
+ JSON.stringify(v),
545
+ ]),
546
+ };
547
+ }
397
548
  /**
398
549
  * Emits a schema-derived manifest of the entities that opted in to
399
550
  * domain-event emission (`.apsorc` `emitEvents`), mirroring the TypeScript
@@ -428,7 +579,7 @@ ${modelRefs}
428
579
  }
429
580
  /**
430
581
  * Scope data for a Go service: each direct scopeBy field's struct field and
431
- * gorm column (snake_case of the Go field). A field declared on the entity is
582
+ * column (the .apsorc name, as the DDL writer names it). A field declared on the entity is
432
583
  * pascalCase; a relation's foreign key (organizationId) is OrganizationID.
433
584
  */
434
585
  goScope(entity, hasAuth) {
@@ -444,43 +595,129 @@ ${modelRefs}
444
595
  goField: declared.has(f.field) || !f.field.endsWith("Id")
445
596
  ? (0, casing_1.pascalCase)(f.field)
446
597
  : `${(0, casing_1.pascalCase)(f.field.slice(0, -2))}ID`,
447
- column: (0, casing_1.snakeCase)(f.field),
598
+ column: f.field,
448
599
  })),
449
600
  };
450
601
  }
451
- async generateGuards(entities, auth) {
452
- if (!auth)
453
- return [];
454
- const nested = (0, guards_1.nestedScopeEntities)(entities);
602
+ /**
603
+ * The foreign keys of an entity that a write must check: those onto
604
+ * tenant-scoped entities, with the Go field and column of each.
605
+ */
606
+ goReferences(entity, associations, allEntities, auth) {
607
+ const owned = associations.filter((a) => a.owns);
608
+ const scoped = (0, guards_1.scopedReferences)(entity, owned.map((a) => [`${a.camelReferenceName}Id`, a.name]), (0, guards_1.relationScopes)(allEntities, this.config.relationshipMap, Boolean(auth)));
609
+ return owned
610
+ .filter((a) => scoped[`${a.camelReferenceName}Id`])
611
+ .map((a) => ({ target: a.name, goField: a.fkField, column: a.fkColumn }));
612
+ }
613
+ /**
614
+ * The MCP tools of every entity that opts in. Gin has no OpenAPI document at
615
+ * run time, so each tool's input schema is written from .apsorc here, from
616
+ * the same columns and foreign keys as the DTOs.
617
+ */
618
+ goMcpTools(entities, auth, relationshipMap) {
619
+ return entities.flatMap((entity) => {
620
+ var _a, _b;
621
+ const { mcp, mcpName, mcpPluralName } = (0, guards_1.mcpToolNames)(entity, auth);
622
+ if (mcp.length === 0)
623
+ return [];
624
+ const scoped = new Set((_a = (0, guards_1.entityScope)(entity, true)) === null || _a === void 0 ? void 0 : _a.fields.map((f) => f.field));
625
+ const properties = {};
626
+ const required = [];
627
+ for (const c of this.getGoFieldsForTemplate((_b = entity.fields) !== null && _b !== void 0 ? _b : [], entity)) {
628
+ properties[c.name] =
629
+ c.type === "enum" && Array.isArray(c.values)
630
+ ? { type: "string", enum: c.values }
631
+ : jsonType(c.goType);
632
+ if (c.mustSend)
633
+ required.push(c.name);
634
+ }
635
+ for (const a of this.goAssociations(entity, relationshipMap[entity.name] || [], entities)) {
636
+ if (!a.owns)
637
+ continue;
638
+ const name = `${a.camelReferenceName}Id`;
639
+ properties[name] = jsonType(a.fkGoType.replace(/^\*/, ""));
640
+ if (!a.fkNullable && !scoped.has(name))
641
+ required.push(name);
642
+ }
643
+ const id = { type: entity.primaryKeyType === "uuid" ? "string" : "integer" };
644
+ const schema = (props, req) => JSON.stringify({ type: "object", properties: props, required: req });
645
+ const body = (req) => ({ type: "object", properties, required: req });
646
+ const plural = (0, pluralize_1.default)(entity.name);
647
+ const path = `/${(0, casing_1.kebabCase)(plural)}`;
648
+ const one = `${path}/:id`;
649
+ const tool = (op, name, method, toolPath, description, toolSchema) => mcp.includes(op)
650
+ ? [{ name, method, path: toolPath, description, schema: toolSchema, list: !toolSchema }]
651
+ : [];
652
+ return [
653
+ ...tool("read", `list_${mcpPluralName}`, "GET", path, `List ${plural}. Supports filter, sort, join, limit and page.`),
654
+ ...tool("read", `get_${mcpName}`, "GET", one, `Get one ${entity.name} by id.`, schema({ id }, ["id"])),
655
+ ...tool("create", `create_${mcpName}`, "POST", path, `Create a ${entity.name}.`, schema({ body: body(required) }, ["body"])),
656
+ ...tool("update", `update_${mcpName}`, "PATCH", one, `Update fields of one ${entity.name} by id.`, schema({ id, body: body([]) }, ["id", "body"])),
657
+ ...tool("delete", `delete_${mcpName}`, "DELETE", one, `Delete one ${entity.name} by id. This cannot be undone.`, schema({ id }, ["id"])),
658
+ ];
659
+ });
660
+ }
661
+ async generateGuards(entities, auth, relationshipMap) {
662
+ var _a, _b;
663
+ if (relationshipMap === void 0) { relationshipMap = (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {}; }
664
+ const tools = this.goMcpTools(entities, auth, relationshipMap !== null && relationshipMap !== void 0 ? relationshipMap : {});
665
+ // Fails on a grants entity that would be an escalation path.
666
+ const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
667
+ if (permissions && !auth)
668
+ throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
669
+ const nested = auth ? (0, guards_1.nestedScopeEntities)(entities) : [];
455
670
  if (nested.length > 0)
456
- console.warn(`[apso] Nested scopeBy paths are enforced in TypeScript services only; ${nested.join(", ")} will not be filtered by those paths in this Go service`);
457
- let data;
458
- if ((0, types_1.isJwtAuth)(auth)) {
459
- data = { jwt: (0, types_1.resolveJwtAuth)(auth) };
460
- }
461
- else if ((0, types_1.isApiKeyAuth)(auth)) {
462
- const apiKey = (0, guards_1.apiKeyTemplateData)((0, types_1.resolveApiKeyAuth)(auth), entities);
463
- const entity = entities.find((e) => e.name === apiKey.apiKeyEntity);
464
- // gorm's default naming: snake_case of the Go field name.
465
- const column = (name) => (0, casing_1.snakeCase)(name);
466
- data = {
467
- apiKey: {
468
- ...apiKey,
469
- goModel: (0, casing_1.pascalCase)(entity.name),
470
- keyColumn: column(apiKey.keyField),
471
- expiresColumn: column("expiresAt"),
472
- workspaceColumn: column(apiKey.workspaceField),
473
- roleColumn: apiKey.roleField ? column(apiKey.roleField) : undefined,
474
- },
475
- };
476
- }
477
- else {
478
- throw new Error(`auth.provider "${auth.provider}" is generated for TypeScript services only. For Go, use "jwt" (Better Auth issues JWTs with its JWT plugin) or "api-key".`);
479
- }
671
+ throw new Error(`${nested.join(", ")}: a scopeBy path through a parent (for example "project.organizationId") is enforced in TypeScript services only for now. In Go, put the tenant field on the entity and scope by it, or generate with --language typescript.`);
672
+ // The API key check is part of every service; auth adds user sign-in.
673
+ // One entry per trusted issuer; undefined when there is no sign-in.
674
+ const jwt = (0, types_1.resolveJwtProviders)(auth);
675
+ const data = {
676
+ jwt: jwt.length > 0 ? jwt : undefined,
677
+ mcp: tools.length > 0,
678
+ // Routes only a service caller reaches (sessions, accounts, ...).
679
+ authRoutes: (0, guards_1.authEntityNames)(entities, auth).map((name) => (0, casing_1.kebabCase)((0, pluralize_1.default)(name))),
680
+ relationScopes: (_b = (0, guards_1.relationScopes)(entities, relationshipMap, Boolean(auth))) !== null && _b !== void 0 ? _b : {},
681
+ tables: Object.fromEntries(entities.map((e) => [e.name, (0, ddl_1.tableName)(e)])),
682
+ };
480
683
  const content = await this.renderTemplate("./middleware/auth", data);
481
684
  const files = [{ path: "middleware/auth.go", content }];
685
+ if (permissions) {
686
+ // Go routes are kebab-case (/role-permissions); the rules are the same.
687
+ const rulesOf = (name) => { var _a; return (_a = permissions.routes[(0, pluralize_1.default)(name).toLowerCase()]) !== null && _a !== void 0 ? _a : {}; };
688
+ const grants = permissions.grants && {
689
+ ...permissions.grants,
690
+ table: (0, ddl_1.tableName)(entities.find((e) => e.name === permissions.grants.entity)),
691
+ };
692
+ files.push({
693
+ path: "middleware/permission.go",
694
+ content: await this.renderTemplate("./middleware/permission", {
695
+ routes: entities
696
+ .filter((e) => e.permissions)
697
+ .map((e) => ({
698
+ path: (0, casing_1.kebabCase)((0, pluralize_1.default)(e.name)),
699
+ rules: Object.entries(rulesOf(e.name)).map(([op, rule]) => ({ op, ...rule })),
700
+ })),
701
+ joins: Object.entries(permissions.joins).map(([name, rules]) => ({ name, rules })),
702
+ grants,
703
+ }),
704
+ });
705
+ }
706
+ // The /mcp endpoint; cmd/main.go mounts it (see ensureGoMcpWiring).
707
+ if (tools.length > 0)
708
+ files.push({
709
+ path: "routes/mcp.go",
710
+ content: await this.renderTemplate("./mcp", {
711
+ tools,
712
+ // The same variables auth.go reads: AUTH_JWT_ISSUER, then _2 and so on.
713
+ issuers: jwt.map((p, i) => ({
714
+ env: `AUTH_JWT_ISSUER${i === 0 ? "" : `_${i + 1}`}`,
715
+ issuer: p.issuer,
716
+ })),
717
+ }),
718
+ });
482
719
  // Shared helpers for services and handlers of entities with a direct scopeBy.
483
- if (entities.some((e) => (0, guards_1.entityScope)(e, true))) {
720
+ if (auth && entities.some((e) => (0, guards_1.entityScope)(e, true))) {
484
721
  files.push({
485
722
  path: "services/scope.go",
486
723
  content: await this.renderTemplate("./services/scope", {}),