@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
@@ -1,5 +1,5 @@
1
1
  import { BaseGenerator } from "./base";
2
- import { TargetLanguage, GeneratedFile, ValidationResult, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, Entity, AuthConfig } from "../types";
2
+ import { TargetLanguage, GeneratedFile, ValidationResult, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, Entity, AuthConfig, RelationshipMap } from "../types";
3
3
  /**
4
4
  * Python/FastAPI generator that produces SQLAlchemy models, Pydantic schemas,
5
5
  * and FastAPI routers.
@@ -16,9 +16,15 @@ export declare class PythonGenerator extends BaseGenerator {
16
16
  generateModule(_options: EntityGenerationOptions): Promise<GeneratedFile[]>;
17
17
  generateMigration(options: MigrationGenerationOptions): Promise<GeneratedFile[]>;
18
18
  generateEnums(entities: Entity[], _apiType: string): Promise<GeneratedFile[]>;
19
- generateIndexModule(entities: Entity[], _apiType: string, opts?: {
19
+ generateIndexModule(entities: Entity[], _apiType: string, _opts?: {
20
20
  auth?: AuthConfig;
21
21
  }): Promise<GeneratedFile[]>;
22
+ /**
23
+ * What create_all must run first: the extensions the tables use, and a
24
+ * guard that stops when the database still has a join table or enum type
25
+ * under the name older generated models gave it.
26
+ */
27
+ private modelsInitData;
22
28
  /**
23
29
  * Emits a schema-derived manifest of the entities that opted in to
24
30
  * domain-event emission (`.apsorc` `emitEvents`), mirroring the TypeScript
@@ -37,6 +43,6 @@ export declare class PythonGenerator extends BaseGenerator {
37
43
  generateDomainEvents(entities: Entity[], _apiType?: string, opts?: {
38
44
  emitEvents?: boolean;
39
45
  }): Promise<GeneratedFile[]>;
40
- generateGuards(entities: Entity[], auth?: AuthConfig): Promise<GeneratedFile[]>;
46
+ generateGuards(entities: Entity[], auth?: AuthConfig, relationshipMap?: RelationshipMap): Promise<GeneratedFile[]>;
41
47
  generateQueryUtils(_entities: Entity[], _apiType: string): Promise<GeneratedFile[]>;
42
48
  }
@@ -12,7 +12,116 @@ const casing_1 = require("../utils/casing");
12
12
  const events_1 = require("../events");
13
13
  const guards_1 = require("../guards");
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 -> [SQLAlchemy column type, Python type]. The
19
+ // column type must give the same Postgres type the DDL writer does.
20
+ const arrayElementTypes = {
21
+ text: ["Text", "str"],
22
+ varchar: ["String", "str"],
23
+ uuid: ["PGUUID(as_uuid=True)", "UUID"],
24
+ integer: ["Integer", "int"],
25
+ int: ["Integer", "int"],
26
+ int4: ["Integer", "int"],
27
+ smallint: ["SmallInteger", "int"],
28
+ bigint: ["BigInteger", "int"],
29
+ numeric: ["Numeric", "Decimal"],
30
+ decimal: ["Numeric", "Decimal"],
31
+ real: ["REAL", "float"],
32
+ float: ["Float", "float"],
33
+ float8: ["Float", "float"],
34
+ "double precision": ["Float", "float"],
35
+ boolean: ["Boolean", "bool"],
36
+ bool: ["Boolean", "bool"],
37
+ date: ["Date", "date"],
38
+ timestamp: ["DateTime", "datetime"],
39
+ timestamptz: ["DateTime(timezone=True)", "datetime"],
40
+ };
41
+ // Field type -> Pydantic schema template, where the type has none of its own.
42
+ const schemaTemplates = {
43
+ char: "varchar",
44
+ bigint: "integer",
45
+ smallint: "integer",
46
+ double: "float",
47
+ "json-plain": "json",
48
+ };
49
+ // DDL column type -> [SQLAlchemy type, Python type]; the SQLAlchemy type
50
+ // creates that same Postgres type.
51
+ const saTypes = {
52
+ text: ["Text", "str"],
53
+ integer: ["Integer", "int"],
54
+ bigint: ["BigInteger", "int"],
55
+ smallint: ["SmallInteger", "int"],
56
+ numeric: ["Numeric()", "Decimal"],
57
+ "double precision": ["DOUBLE_PRECISION", "float"],
58
+ boolean: ["Boolean", "bool"],
59
+ uuid: ["PGUUID(as_uuid=True)", "UUID"],
60
+ date: ["Date", "date"],
61
+ TIMESTAMP: ["DateTime", "datetime"],
62
+ "TIMESTAMP WITH TIME ZONE": ["DateTime(timezone=True)", "datetime"],
63
+ jsonb: ["JSONB", "dict"],
64
+ json: ["JSON", "dict"],
65
+ };
66
+ function saType(type) {
67
+ const sized = type.match(/^(character varying|character|numeric)\((\d+)(?:,(\d+))?\)$/);
68
+ if (sized) {
69
+ const [, kind, a, b] = sized;
70
+ if (kind === "numeric")
71
+ return [`Numeric(${a}, ${b})`, "Decimal"];
72
+ return [`${kind === "character" ? "CHAR" : "String"}(${a})`, "str"];
73
+ }
74
+ if (type.endsWith("[]")) {
75
+ const element = arrayElementTypes[type.slice(0, -2).toLowerCase()];
76
+ if (!element)
77
+ throw new Error(`The Python generator does not support ${type} columns. Use one of: ${Object.keys(arrayElementTypes).join(", ")}.`);
78
+ return [`ARRAY(${element[0]})`, `List[${element[1]}]`];
79
+ }
80
+ const known = saTypes[type];
81
+ if (!known)
82
+ throw new Error(`The Python generator does not support ${type} columns.`);
83
+ return known;
84
+ }
85
+ const withArrayTypes = (columns, entityName) => columns.map((c) => {
86
+ if (c.type !== "array")
87
+ return c;
88
+ const element = (0, field_1.arrayElementType)(c);
89
+ const types = arrayElementTypes[element.toLowerCase()];
90
+ if (!types)
91
+ throw new Error(`Field ${entityName}.${c.name} has elementType "${element}", which the Python generator does not support. Use one of: ${Object.keys(arrayElementTypes).join(", ")}.`);
92
+ return { ...c, arrayColumnType: types[0], arrayItemType: types[1] };
93
+ });
94
+ /** The ForeignKey(...) of a DDL foreign key constraint. */
95
+ const pyForeignKey = (fk) => {
96
+ const [, targetCol, onDelete, onUpdate] = fk.body.match(/REFERENCES "[^"]+"\("([^"]+)"\) ON DELETE (.+) ON UPDATE (.+)$/);
97
+ return `ForeignKey(${(0, migration_file_1.pyString)(`${fk.references}.${targetCol}`)}, name=${(0, migration_file_1.pyString)(fk.name)}, ondelete=${(0, migration_file_1.pyString)(onDelete)}, onupdate=${(0, migration_file_1.pyString)(onUpdate)})`;
98
+ };
99
+ /**
100
+ * A DDL column as a SQLAlchemy Column argument list: type, foreign key,
101
+ * key, NULL and default exactly as the DDL writer creates them.
102
+ */
103
+ function pyColumnArgs(table, c, field, fk, primary) {
104
+ const [type, enumOrPyType] = (field === null || field === void 0 ? void 0 : field.type) === "enum"
105
+ ? [
106
+ `SAEnum(enums.${field.dataType}, name=${(0, migration_file_1.pyString)((0, ddl_1.enumTypeName)(table, field.name))}, values_callable=lambda x: [e.value for e in x])`,
107
+ `enums.${field.dataType}`,
108
+ ]
109
+ : saType(c.type);
110
+ const args = [type];
111
+ if (fk)
112
+ args.push(pyForeignKey(fk));
113
+ if (primary)
114
+ args.push("primary_key=True");
115
+ if (c.serial)
116
+ args.push("autoincrement=True");
117
+ else if (!primary)
118
+ args.push(`nullable=${c.notNull ? "False" : "True"}`);
119
+ if (c.default !== undefined && !c.serial)
120
+ args.push(`server_default=text(${(0, migration_file_1.pyString)(c.default)})`);
121
+ if (c.name === "updated_at")
122
+ args.push("onupdate=func.now()");
123
+ return { args, pyType: c.notNull ? enumOrPyType : `Optional[${enumOrPyType}]` };
124
+ }
16
125
  /**
17
126
  * Python/FastAPI generator that produces SQLAlchemy models, Pydantic schemas,
18
127
  * and FastAPI routers.
@@ -34,20 +143,21 @@ class PythonGenerator extends base_1.BaseGenerator {
34
143
  return ".py";
35
144
  }
36
145
  validateConfig(config) {
37
- var _a;
146
+ var _a, _b;
38
147
  const errors = [];
39
148
  const warnings = [];
40
149
  // Validate that entities are provided
41
150
  if (!config.entities || config.entities.length === 0) {
42
151
  errors.push("No entities defined in configuration");
43
152
  }
153
+ errors.push(...(0, guards_1.removedScopeOptionErrors)((_a = config.entities) !== null && _a !== void 0 ? _a : []));
44
154
  // Validate each entity
45
155
  for (const entity of config.entities) {
46
156
  if (!entity.name) {
47
157
  errors.push("Entity missing required 'name' property");
48
158
  }
49
159
  // Validate field types
50
- for (const field of (_a = entity.fields) !== null && _a !== void 0 ? _a : []) {
160
+ for (const field of (_b = entity.fields) !== null && _b !== void 0 ? _b : []) {
51
161
  if (!field.name) {
52
162
  errors.push(`Entity '${entity.name}' has a field without a name`);
53
163
  }
@@ -59,7 +169,12 @@ class PythonGenerator extends base_1.BaseGenerator {
59
169
  "text",
60
170
  "varchar",
61
171
  "string",
172
+ "char",
62
173
  "integer",
174
+ "bigint",
175
+ "smallint",
176
+ "double",
177
+ "json-plain",
63
178
  "boolean",
64
179
  "float",
65
180
  "decimal",
@@ -87,31 +202,77 @@ class PythonGenerator extends base_1.BaseGenerator {
87
202
  }
88
203
  async generateEntity(options) {
89
204
  const { entity, relationships, allEntities, apiType } = options;
90
- const { name, fields = [], indexes, uniques } = entity;
91
- const columns = (0, field_1.getFieldForTemplate)(fields, name);
92
- const createPrimaryKey = columns.filter((column) => column.primary === true).length === 0;
93
- const createdAt = entity.created_at;
94
- const updatedAt = entity.updated_at;
95
- const primaryKeyType = entity.primaryKeyType || "serial";
205
+ const { name, fields = [] } = entity;
206
+ // Every table object comes from the DDL writer's model of the schema, so
207
+ // create_all builds what the migrations from `apso migrate` build.
208
+ const model = (0, ddl_1.schemaModel)({
209
+ entities: allEntities,
210
+ relationshipMap: {
211
+ ...this.config.relationshipMap,
212
+ [name]: relationships,
213
+ },
214
+ });
215
+ const table = (0, ddl_1.tableName)(entity);
216
+ const byField = new Map((0, field_1.getFieldForTemplate)(fields, name).map((f) => [f.name, f]));
217
+ const tableArgs = (t) => {
218
+ const pk = model.constraints.find((c) => c.kind === "pk" && c.table === t);
219
+ return {
220
+ pk,
221
+ args: [
222
+ `PrimaryKeyConstraint(${[...pk.columns, `name=${(0, migration_file_1.pyString)(pk.name)}`]
223
+ .map((x) => (x.startsWith("name=") ? x : (0, migration_file_1.pyString)(x)))
224
+ .join(", ")})`,
225
+ ...model.constraints
226
+ .filter((c) => c.kind === "unique" && c.table === t)
227
+ .map((c) => `UniqueConstraint(${c.columns
228
+ .map((x) => (0, migration_file_1.pyString)(x))
229
+ .join(", ")}, name=${(0, migration_file_1.pyString)(c.name)})`),
230
+ ...model.indexes
231
+ .filter((i) => i.table === t)
232
+ .map((i) => `Index(${[i.name, ...i.columns].map((x) => (0, migration_file_1.pyString)(x)).join(", ")}${i.unique ? ", unique=True" : ""})`),
233
+ ],
234
+ };
235
+ };
236
+ const columnsOf = (t, fieldOf) => {
237
+ const { pk, args } = tableArgs(t);
238
+ const columns = model.tables
239
+ .find((x) => x.name === t)
240
+ .columns.map((c) => ({
241
+ name: c.name,
242
+ ...pyColumnArgs(t, c, fieldOf === null || fieldOf === void 0 ? void 0 : fieldOf(c.name), model.constraints.find((k) => k.kind === "fk" && k.table === t && k.columns[0] === c.name), pk.columns.includes(c.name)),
243
+ }));
244
+ return { columns, tableArgs: args };
245
+ };
246
+ const own = columnsOf(table, (c) => byField.get(c));
96
247
  const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(name, relationships, allEntities);
248
+ const byName = new Map(allEntities.map((e) => [e.name, e]));
249
+ const joinTables = relationshipsForTemplate
250
+ .filter((r) => r.type === "ManyToMany" && r.joinTable && byName.get(r.name))
251
+ .map((r) => {
252
+ const j = (0, ddl_1.joinTableOf)(entity, r, byName.get(r.name));
253
+ return { name: j.name, ...columnsOf(j.name) };
254
+ });
255
+ // A non-owning ManyToMany names the join table its owner declares.
256
+ const associations = relationshipsForTemplate.map((r) => {
257
+ var _a;
258
+ if (r.type === "OneToOne" && r.joinTable)
259
+ return { ...r, fkColumn: (0, ddl_1.relationColumn)(r) };
260
+ if (r.type !== "ManyToMany" || !byName.get(r.name))
261
+ return r;
262
+ const target = byName.get(r.name);
263
+ if (r.joinTable)
264
+ return { ...r, secondary: (0, ddl_1.joinTableOf)(entity, r, target).name };
265
+ const owner = (0, relationships_1.getRelationshipForTemplate)(target.name, ((_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {})[target.name] || [], allEntities).find((o) => o.type === "ManyToMany" && o.joinTable && o.name === name);
266
+ return { ...r, secondary: owner && (0, ddl_1.joinTableOf)(target, owner, entity).name };
267
+ });
97
268
  const entitiesToImport = (0, relationships_1.getRelationshipsForImport)(name, relationshipsForTemplate);
98
269
  const data = {
99
270
  name,
100
- indexes: indexes || [],
101
- uniques: uniques || [],
102
- createPrimaryKey,
103
- primaryKeyType,
104
- snakeCasedName: (0, casing_1.snakeCase)(name),
105
- // Honor an explicit per-entity `table` override; otherwise derive from
106
- // the entity name. See apsoai/cli#107 (Python/Go parity with #98).
107
- tableName: entity.table || (0, casing_1.snakeCase)(name),
108
- // Foreign keys name the referenced entity's real table, override included.
109
- tableNames: Object.fromEntries(allEntities.map((e) => [e.name, e.table || (0, casing_1.snakeCase)(e.name)])),
110
- createdAt,
111
- updatedAt,
112
- pluralizedName: (0, casing_1.camelCase)((0, pluralize_1.default)(name)),
113
- columns,
114
- associations: [...new Set(relationshipsForTemplate)],
271
+ tableName: table,
272
+ columns: own.columns,
273
+ tableArgs: own.tableArgs,
274
+ joinTables,
275
+ associations,
115
276
  entitiesToImport,
116
277
  importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
117
278
  apiType,
@@ -135,6 +296,8 @@ class PythonGenerator extends base_1.BaseGenerator {
135
296
  pluralEntityName,
136
297
  primaryKeyType,
137
298
  associations: [...new Set(relationshipsForTemplate)],
299
+ // Operations exposed as MCP tools, and the names the tools get.
300
+ ...(0, guards_1.mcpToolNames)(entity, options.auth),
138
301
  };
139
302
  const content = await this.renderTemplate("./routers/router", data);
140
303
  return [
@@ -145,6 +308,7 @@ class PythonGenerator extends base_1.BaseGenerator {
145
308
  ];
146
309
  }
147
310
  async generateService(options) {
311
+ var _a;
148
312
  const { entity, relationships } = options;
149
313
  const { name: entityName } = entity;
150
314
  const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
@@ -156,6 +320,10 @@ class PythonGenerator extends base_1.BaseGenerator {
156
320
  primaryKeyType,
157
321
  associations: [...new Set(relationshipsForTemplate)],
158
322
  scope: (0, guards_1.entityScope)(entity, Boolean(options.auth)),
323
+ // Foreign keys a write must check: those onto tenant-scoped entities.
324
+ references: Object.entries((0, guards_1.scopedReferences)(entity, relationshipsForTemplate
325
+ .filter((a) => a.type === "ManyToOne" || (a.type === "OneToOne" && a.joinTable))
326
+ .map((a) => [a.camelCasedId, a.name]), (0, guards_1.relationScopes)(options.allEntities, (_a = options.relationshipMap) !== null && _a !== void 0 ? _a : this.config.relationshipMap, Boolean(options.auth)))).map(([field, target]) => ({ field, target })),
159
327
  };
160
328
  const content = await this.renderTemplate("./services/service", data);
161
329
  return [
@@ -168,8 +336,17 @@ class PythonGenerator extends base_1.BaseGenerator {
168
336
  async generateDto(options) {
169
337
  const { entity, relationships, allEntities, apiType } = options;
170
338
  const { name: entityName, fields = [] } = entity;
171
- const columns = (0, field_1.getFieldForTemplate)(fields, entityName);
172
- const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
339
+ const table = (0, ddl_1.tableName)(entity);
340
+ const columns = withArrayTypes((0, field_1.getFieldForTemplate)(fields, entityName), entityName).map((c) => {
341
+ const spec = (0, ddl_1.columnSpec)(table, c);
342
+ return {
343
+ ...c,
344
+ schemaTemplate: schemaTemplates[c.type] || c.type,
345
+ // NOT NULL with no default: the create schema requires it.
346
+ required: spec.notNull && spec.default === undefined,
347
+ };
348
+ });
349
+ const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships, allEntities);
173
350
  // Add foreign key columns for ManyToOne relationships
174
351
  relationshipsTemplate.forEach((rel) => {
175
352
  if (rel.type === "ManyToOne") {
@@ -199,7 +376,12 @@ class PythonGenerator extends base_1.BaseGenerator {
199
376
  createdAt,
200
377
  updatedAt,
201
378
  columns,
202
- associations: relationshipsTemplate,
379
+ // Auth entities are for service callers only, so no other entity's
380
+ // response carries one.
381
+ associations: relationshipsTemplate.map((r) => ({
382
+ ...r,
383
+ hidden: (0, guards_1.hidesRelation)(entityName, r.name, allEntities, options.auth),
384
+ })),
203
385
  apiType: apiType !== null && apiType !== void 0 ? apiType : "rest",
204
386
  importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
205
387
  };
@@ -282,18 +464,60 @@ ${downStatements || " pass"}
282
464
  },
283
465
  ];
284
466
  }
285
- async generateIndexModule(entities, _apiType, opts) {
467
+ async generateIndexModule(entities, _apiType, _opts) {
286
468
  const content = await this.renderTemplate("./index-module", {
287
469
  entities,
288
- hasAuth: Boolean(opts === null || opts === void 0 ? void 0 : opts.auth),
470
+ permissions: (0, guards_1.hasPermissions)(entities),
289
471
  });
290
472
  return [
291
473
  {
292
474
  path: "__init__.py",
293
475
  content,
294
476
  },
477
+ {
478
+ path: "models/__init__.py",
479
+ content: await this.renderTemplate("./models/init", this.modelsInitData(entities)),
480
+ },
295
481
  ];
296
482
  }
483
+ /**
484
+ * What create_all must run first: the extensions the tables use, and a
485
+ * guard that stops when the database still has a join table or enum type
486
+ * under the name older generated models gave it.
487
+ */
488
+ modelsInitData(entities) {
489
+ var _a, _b;
490
+ const relationshipMap = (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {};
491
+ const model = (0, ddl_1.schemaModel)({ entities, relationshipMap });
492
+ const legacy = [];
493
+ for (const entity of entities) {
494
+ const table = (0, ddl_1.tableName)(entity);
495
+ for (const f of (_b = entity.fields) !== null && _b !== void 0 ? _b : [])
496
+ if (f.type === "enum") {
497
+ const old = `${entity.name}_${f.name}_enum`.toLowerCase();
498
+ const now = (0, ddl_1.enumTypeName)(table, f.name);
499
+ if (old !== now)
500
+ legacy.push((0, sync_1.legacyType)(old, now));
501
+ }
502
+ for (const r of (0, relationships_1.getRelationshipForTemplate)(entity.name, relationshipMap[entity.name] || [], entities)) {
503
+ const target = entities.find((e) => e.name === r.name);
504
+ if (r.type !== "ManyToMany" || !r.joinTable || !target)
505
+ continue;
506
+ const j = (0, ddl_1.joinTableOf)(entity, r, target);
507
+ const old = r.joinTableName || `${table}_${r.name.toLowerCase()}`;
508
+ if (old !== j.name)
509
+ legacy.push((0, sync_1.legacyTable)(old, j.name, [
510
+ [r.joinColumnName || `${table}_id`, j.ownCol],
511
+ [r.inverseJoinColumnName || `${r.name.toLowerCase()}_id`, j.otherCol],
512
+ ]));
513
+ }
514
+ }
515
+ const guard = (0, sync_1.legacyGuardSql)(legacy);
516
+ return {
517
+ modules: entities.map((e) => [e.name.toLowerCase(), e.name]),
518
+ statements: [...model.extensions, ...(guard ? [guard] : [])].map((x) => (0, migration_file_1.pyString)(x)),
519
+ };
520
+ }
297
521
  /**
298
522
  * Emits a schema-derived manifest of the entities that opted in to
299
523
  * domain-event emission (`.apsorc` `emitEvents`), mirroring the TypeScript
@@ -326,28 +550,39 @@ ${downStatements || " pass"}
326
550
  },
327
551
  ];
328
552
  }
329
- async generateGuards(entities, auth) {
330
- if (!auth)
331
- return [];
332
- const nested = (0, guards_1.nestedScopeEntities)(entities);
553
+ async generateGuards(entities, auth, relationshipMap) {
554
+ var _a, _b;
555
+ if (relationshipMap === void 0) { relationshipMap = (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {}; }
556
+ const mcp = entities.some((e) => (0, guards_1.mcpToolNames)(e, auth).mcp.length > 0);
557
+ // Fails on a grants entity that would be an escalation path.
558
+ const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
559
+ if (permissions && !auth)
560
+ throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
561
+ const nested = auth ? (0, guards_1.nestedScopeEntities)(entities) : [];
333
562
  if (nested.length > 0)
334
- console.warn(`[apso] Nested scopeBy paths are enforced in TypeScript services only; ${nested.join(", ")} will not be filtered by those paths in this Python service`);
335
- let data;
336
- if ((0, types_1.isJwtAuth)(auth)) {
337
- data = { jwt: (0, types_1.resolveJwtAuth)(auth) };
338
- }
339
- else if ((0, types_1.isApiKeyAuth)(auth)) {
340
- const apiKey = (0, guards_1.apiKeyTemplateData)((0, types_1.resolveApiKeyAuth)(auth), entities);
341
- data = {
342
- apiKey: { ...apiKey, pyModule: apiKey.apiKeyEntity.toLowerCase() },
343
- };
344
- }
345
- else {
346
- throw new Error(`auth.provider "${auth.provider}" is generated for TypeScript services only. For Python, use "jwt" (Better Auth issues JWTs with its JWT plugin) or "api-key".`);
347
- }
348
- return [
563
+ throw new Error(`${nested.join(", ")}: a scopeBy path through a parent (for example "project.organizationId") is enforced in TypeScript services only for now. In Python, put the tenant field on the entity and scope by it, or generate with --language typescript.`);
564
+ // The API key check is part of every service; auth adds user sign-in.
565
+ // One entry per trusted issuer; undefined when there is no sign-in.
566
+ const jwt = (0, types_1.resolveJwtProviders)(auth);
567
+ const data = {
568
+ jwt: jwt.length > 0 ? jwt : undefined,
569
+ mcp,
570
+ // Routes only a service caller reaches (sessions, accounts, ...).
571
+ authRoutes: (0, guards_1.authEntityRoutes)(entities, auth),
572
+ relationScopes: (_b = (0, guards_1.relationScopes)(entities, relationshipMap, Boolean(auth))) !== null && _b !== void 0 ? _b : {},
573
+ };
574
+ const files = [
349
575
  { path: "auth.py", content: await this.renderTemplate("./auth", data) },
350
576
  ];
577
+ if (permissions)
578
+ files.push({
579
+ path: "permissions.py",
580
+ content: await this.renderTemplate("./permissions", { permissions }),
581
+ });
582
+ // The /mcp endpoint; app/main.py mounts it (see ensurePythonMcpWiring).
583
+ if (mcp)
584
+ files.push({ path: "mcp.py", content: await this.renderTemplate("./mcp", {}) });
585
+ return files;
351
586
  }
352
587
  async generateQueryUtils(_entities, _apiType) {
353
588
  const queryContent = await this.renderTemplate("./utils/query", {});
@@ -16,7 +16,7 @@ export declare class TypeScriptGenerator extends BaseGenerator {
16
16
  generateModule(options: EntityGenerationOptions): Promise<GeneratedFile[]>;
17
17
  generateMigration(_options: MigrationGenerationOptions): Promise<GeneratedFile[]>;
18
18
  generateEnums(entities: Entity[], apiType: string): Promise<GeneratedFile[]>;
19
- generateIndexModule(entities: Entity[], apiType: string, opts?: {
19
+ generateIndexModule(entities: Entity[], apiType: string, _opts?: {
20
20
  emitEvents?: boolean;
21
21
  auth?: AuthConfig;
22
22
  }): Promise<GeneratedFile[]>;
@@ -41,8 +41,6 @@ export declare class TypeScriptGenerator extends BaseGenerator {
41
41
  generateDomainEvents(entities: Entity[], _apiType?: string, opts?: {
42
42
  emitEvents?: boolean;
43
43
  }): Promise<GeneratedFile[]>;
44
- /**
45
- * Normalizes auth config by applying defaults for DB session providers
46
- */
47
- private normalizeAuthConfig;
44
+ /** True when requests can load a relation that is tenant-scoped or limited by role. */
45
+ private hasRelationAccess;
48
46
  }