@apso/cli 0.56.0 → 0.57.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.
@@ -6,6 +6,7 @@ export declare function resolveTargetConnectionString(flagValue: string | undefi
6
6
  /** Render a copy result (or dry-run plan) as a human-readable summary. */
7
7
  export declare function formatCopyResult(result: CopyResult): string;
8
8
  export default class ImportData extends BaseCommand {
9
+ protected reportErrorText: boolean;
9
10
  static description: string;
10
11
  static examples: string[];
11
12
  static flags: {
@@ -6,7 +6,7 @@ const core_1 = require("@oclif/core");
6
6
  const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
7
7
  const base_command_1 = tslib_1.__importDefault(require("../../lib/base-command"));
8
8
  const import_1 = require("../../lib/import");
9
- const supabase_1 = require("./supabase");
9
+ const index_1 = require("./index");
10
10
  /** Resolve the target connection string from flag/env, else undefined. */
11
11
  function resolveTargetConnectionString(flagValue, env = process.env) {
12
12
  return flagValue || env.TARGET_DATABASE_URL || env.APSO_DATABASE_URL || undefined;
@@ -41,6 +41,11 @@ function formatCopyResult(result) {
41
41
  }
42
42
  exports.formatCopyResult = formatCopyResult;
43
43
  class ImportData extends base_command_1.default {
44
+ constructor() {
45
+ super(...arguments);
46
+ // Errors here can name the database host, so the text stays on this machine.
47
+ this.reportErrorText = false;
48
+ }
44
49
  async promptConnection(role) {
45
50
  const answer = await inquirer_1.default.prompt([
46
51
  {
@@ -55,7 +60,7 @@ class ImportData extends base_command_1.default {
55
60
  }
56
61
  async run() {
57
62
  const { flags } = await this.parse(ImportData);
58
- const sourceConn = (0, supabase_1.resolveConnectionString)(flags.source) ||
63
+ const sourceConn = (0, index_1.resolveConnectionString)(flags.source) ||
59
64
  (await this.promptConnection("Source"));
60
65
  const targetConn = resolveTargetConnectionString(flags.target) ||
61
66
  (await this.promptConnection("Target"));
@@ -122,7 +127,7 @@ class ImportData extends base_command_1.default {
122
127
  }
123
128
  }
124
129
  }
125
- ImportData.description = "Copy table data from a source Supabase (Postgres) database into the target database rebuilt from the imported schema. Reads the source read-only; inserts into empty target tables.";
130
+ ImportData.description = "Copy table data from a source Postgres database (Supabase, Neon, RDS, or any other) into the target database rebuilt from the imported schema. Reads the source read-only; inserts into empty target tables.";
126
131
  ImportData.examples = [
127
132
  `$ apso import data -s "postgresql://...source..." -t "postgresql://...target..."`,
128
133
  `$ apso import data --dry-run`,
@@ -26,9 +26,11 @@ export declare function formatReport(report: ImportReport): string;
26
26
  export declare function writeApsorcFile(apsorc: ApsorcImportOutput, outPath: string): {
27
27
  backupPath?: string;
28
28
  };
29
- export default class ImportSupabase extends BaseCommand {
29
+ export default class Import extends BaseCommand {
30
30
  static description: string;
31
31
  static examples: string[];
32
+ static aliases: string[];
33
+ static deprecateAliases: boolean;
32
34
  static flags: {
33
35
  "connection-string": import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
34
36
  schema: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
@@ -36,6 +38,7 @@ export default class ImportSupabase extends BaseCommand {
36
38
  "dry-run": import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
37
39
  yes: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
38
40
  };
41
+ protected reportErrorText: boolean;
39
42
  /** Overridable for testing. */
40
43
  protected makeIntrospector(connectionString: string): Introspector;
41
44
  run(): Promise<void>;
@@ -111,14 +111,19 @@ function writeApsorcFile(apsorc, outPath) {
111
111
  return { backupPath };
112
112
  }
113
113
  exports.writeApsorcFile = writeApsorcFile;
114
- class ImportSupabase extends base_command_1.default {
114
+ class Import extends base_command_1.default {
115
+ constructor() {
116
+ super(...arguments);
117
+ // Errors here can name the database host, so the text stays on this machine.
118
+ this.reportErrorText = false;
119
+ }
115
120
  /** Overridable for testing. */
116
121
  makeIntrospector(connectionString) {
117
122
  return new import_1.PgIntrospector(connectionString);
118
123
  }
119
124
  async run() {
120
125
  var _a, _b;
121
- const { flags } = await this.parse(ImportSupabase);
126
+ const { flags } = await this.parse(Import);
122
127
  let connectionString = resolveConnectionString(flags["connection-string"]);
123
128
  if (!connectionString) {
124
129
  const answer = await inquirer_1.default.prompt([
@@ -126,7 +131,7 @@ class ImportSupabase extends base_command_1.default {
126
131
  type: "password",
127
132
  name: "connectionString",
128
133
  mask: "*",
129
- message: "Supabase Postgres connection string:",
134
+ message: "Postgres connection string:",
130
135
  validate: (input) => input.trim().length > 0 || "A connection string is required",
131
136
  },
132
137
  ]);
@@ -189,13 +194,17 @@ class ImportSupabase extends base_command_1.default {
189
194
  }
190
195
  }
191
196
  }
192
- ImportSupabase.description = "Introspect an existing Supabase (Postgres) database and generate a local .apsorc schema. Read-only: it never writes to the source database.";
193
- ImportSupabase.examples = [
194
- `$ apso import supabase`,
195
- `$ apso import supabase -c "postgresql://postgres:[pw]@db.[ref].supabase.co:5432/postgres"`,
196
- `$ SUPABASE_DB_URL="postgresql://..." apso import supabase --dry-run`,
197
+ Import.description = "Introspect an existing Postgres database (Supabase, Neon, RDS, or any Postgres you can reach with a connection string) and generate a local .apsorc schema. Runs on your machine and is read-only: it never writes to the source database.";
198
+ Import.examples = [
199
+ `$ apso import`,
200
+ `$ apso import -c "postgresql://user:[pw]@host:5432/dbname"`,
201
+ `$ apso import -c "postgresql://postgres:[pw]@db.[ref].supabase.co:5432/postgres"`,
202
+ `$ DATABASE_URL="postgresql://..." apso import --dry-run`,
197
203
  ];
198
- ImportSupabase.flags = {
204
+ // "apso import supabase" was the first name of this command. It still works.
205
+ Import.aliases = ["import:supabase"];
206
+ Import.deprecateAliases = true;
207
+ Import.flags = {
199
208
  "connection-string": core_1.Flags.string({
200
209
  char: "c",
201
210
  description: "Postgres connection string. Falls back to SUPABASE_DB_URL or DATABASE_URL, then prompts.",
@@ -218,4 +227,4 @@ ImportSupabase.flags = {
218
227
  default: false,
219
228
  }),
220
229
  };
221
- exports.default = ImportSupabase;
230
+ exports.default = Import;
@@ -10,6 +10,7 @@ const services_1 = require("../../lib/api/services");
10
10
  const schema_tools_1 = require("@apso/schema-tools");
11
11
  const apsorc_parser_1 = require("../../lib/apsorc-parser");
12
12
  const generators_1 = require("../../lib/generators");
13
+ const ddl_1 = require("../../lib/ddl");
13
14
  const schema_convert_1 = require("../../lib/utils/schema-convert");
14
15
  /**
15
16
  * A validation error that includes the individual error messages.
@@ -55,6 +56,10 @@ async function accessRuleErrors(parsed) {
55
56
  };
56
57
  // auth and permissions for every language; mcp for Python and Go.
57
58
  await attempt(() => generator.generateGuards(entities, auth, relationshipMap));
59
+ // Python and Go build the database with the DDL writer, which refuses a
60
+ // field type it cannot write. apso generate fails on the same schema.
61
+ if (config.language !== "typescript")
62
+ await attempt(async () => (0, ddl_1.schemaModel)({ entities, relationshipMap }));
58
63
  // mcp in TypeScript is checked where the controller is generated.
59
64
  if (config.language === "typescript")
60
65
  for (const entity of entities)
@@ -85,8 +85,7 @@ function buildModel(entities, relationships, language, auth) {
85
85
  }));
86
86
  const config = scoped.find((s) => s.name === entity.name);
87
87
  const direct = config === null || config === void 0 ? void 0 : config.scopes.find((s) => s.direct && s.contextKey !== "userId" && s.contextKey !== "email");
88
- // Only TypeScript enforces a path through a parent; Python and Go refuse it at generate.
89
- const nested = language === "typescript" ? config === null || config === void 0 ? void 0 : config.scopes.find((s) => s.fkField) : undefined;
88
+ const nested = config === null || config === void 0 ? void 0 : config.scopes.find((s) => s.fkField);
90
89
  let scope;
91
90
  if (config && direct) {
92
91
  scope = { field: direct.field, bypassRoles: config.bypassRoles };
@@ -49,7 +49,7 @@
49
49
  "group": "Tenant scope",
50
50
  "rule": "A user caller reads and changes only rows of their own tenant.",
51
51
  "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" },
52
- "note": "A scopeBy path through a parent (project.organizationId) is enforced in TypeScript and refused at generate in Python and Go. The scope covers every operation: `apso generate` refuses `scopeOptions.enforceOn`."
52
+ "note": "A scopeBy path through a parent (project.organizationId) is enforced in every language: the foreign key must name a parent in the caller's tenant. The scope covers every operation: `apso generate` refuses `scopeOptions.enforceOn`."
53
53
  },
54
54
  {
55
55
  "id": "R7",
@@ -158,10 +158,24 @@ exports.servicesApi = {
158
158
  return match;
159
159
  },
160
160
  async create(workspaceId, data) {
161
+ var _a;
161
162
  const headers = workspaceId
162
163
  ? { "X-Workspace-Id": String(workspaceId) }
163
164
  : undefined;
164
- const raw = await client_1.api.post("/api/services", { name: data.name }, { headers });
165
+ // Send the body the web app sends. workspaceUserId is the caller's own
166
+ // membership in the workspace: the id of their row in GET /api/workspaces.
167
+ // Without it the platform does not record the creator as the service's
168
+ // Owner. A failed lookup must not stop the create.
169
+ const rows = workspaceId
170
+ ? await client_1.api.get("/api/workspaces").catch(() => null)
171
+ : null;
172
+ const memberships = Array.isArray(rows) ? rows : (_a = rows === null || rows === void 0 ? void 0 : rows.data) !== null && _a !== void 0 ? _a : [];
173
+ const membership = memberships.find((m) => { var _a, _b; return String((_b = (_a = m === null || m === void 0 ? void 0 : m.workspace) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : m === null || m === void 0 ? void 0 : m.workspaceId) === String(workspaceId); });
174
+ const raw = await client_1.api.post("/api/services", {
175
+ name: data.name,
176
+ workspaceId: Number(workspaceId) || undefined,
177
+ workspaceUserId: membership === null || membership === void 0 ? void 0 : membership.id,
178
+ }, { headers });
165
179
  return adaptService(raw);
166
180
  },
167
181
  async update(_workspaceSlug, serviceSlugOrId, data) {
@@ -6,6 +6,12 @@ import { Command } from "@oclif/core";
6
6
  */
7
7
  export declare function isUserError(err: unknown): boolean;
8
8
  export default abstract class BaseCommand extends Command {
9
+ /**
10
+ * Whether a failure's message is sent with the cli_command_failed event.
11
+ * Commands that connect to the user's own database set this to false: their
12
+ * error text can name the database host.
13
+ */
14
+ protected reportErrorText: boolean;
9
15
  /**
10
16
  * Report failures to Sentry + PostHog before oclif exits. The postrun hook
11
17
  * does not fire on error, so the flush has to happen here.
@@ -19,6 +19,15 @@ function isUserError(err) {
19
19
  }
20
20
  exports.isUserError = isUserError;
21
21
  class BaseCommand extends core_1.Command {
22
+ constructor() {
23
+ super(...arguments);
24
+ /**
25
+ * Whether a failure's message is sent with the cli_command_failed event.
26
+ * Commands that connect to the user's own database set this to false: their
27
+ * error text can name the database host.
28
+ */
29
+ this.reportErrorText = true;
30
+ }
22
31
  /**
23
32
  * Report failures to Sentry + PostHog before oclif exits. The postrun hook
24
33
  * does not fire on error, so the flush has to happen here.
@@ -43,6 +52,11 @@ class BaseCommand extends core_1.Command {
43
52
  (0, telemetry_1.capturePostHogException)(err, { command: this.id });
44
53
  // Extract detailed error properties for the cli_command_failed event
45
54
  const errorProps = (0, error_utils_1.extractErrorProperties)(err);
55
+ if (!this.reportErrorText) {
56
+ // Commands that connect to the user's own database: the message can name the host.
57
+ delete errorProps.error_message;
58
+ delete errorProps.error_messages;
59
+ }
46
60
  // Track the failure event with structured error properties
47
61
  (0, telemetry_1.track)("cli_command_failed", {
48
62
  command: this.id,
@@ -1,6 +1,22 @@
1
1
  import { BaseGenerator } from "./base";
2
2
  import { TargetLanguage, GeneratedFile, ValidationResult, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, Entity, AuthConfig } from "../types";
3
+ import { NestedScopeData } from "../guards";
3
4
  import { RelationshipMap } from "../types";
5
+ /**
6
+ * A scopeBy path through parents as SQL names: the entity's foreign key column,
7
+ * each parent's table with its foreign key column to the next, and the tenant
8
+ * column on the last parent. Columns are the .apsorc names, as the DDL writer
9
+ * names them.
10
+ */
11
+ export declare function goNestedScopes(nested: NestedScopeData[], entities: Entity[]): {
12
+ column: string;
13
+ parents: {
14
+ table: string;
15
+ column: string;
16
+ }[];
17
+ tenantColumn: string;
18
+ source: "email" | "userId" | "tenant";
19
+ }[];
4
20
  /**
5
21
  * Go/Gin generator that produces GORM models, DTOs, Gin handlers,
6
22
  * and service layer code.
@@ -66,6 +82,8 @@ export declare class GoGenerator extends BaseGenerator {
66
82
  * Scope data for a Go service: each direct scopeBy field's struct field and
67
83
  * column (the .apsorc name, as the DDL writer names it). A field declared on the entity is
68
84
  * pascalCase; a relation's foreign key (organizationId) is OrganizationID.
85
+ * A path through a parent (task.workspaceId) carries the foreign key the
86
+ * service reads from a write, to check the parent is the caller's.
69
87
  */
70
88
  private goScope;
71
89
  /**
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GoGenerator = void 0;
3
+ exports.GoGenerator = exports.goNestedScopes = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const path = tslib_1.__importStar(require("path"));
6
6
  const Eta = tslib_1.__importStar(require("eta"));
@@ -84,6 +84,22 @@ const jsonType = (goType) => {
84
84
  return { type: "array" };
85
85
  return {};
86
86
  };
87
+ /**
88
+ * A scopeBy path through parents as SQL names: the entity's foreign key column,
89
+ * each parent's table with its foreign key column to the next, and the tenant
90
+ * column on the last parent. Columns are the .apsorc names, as the DDL writer
91
+ * names them.
92
+ */
93
+ function goNestedScopes(nested, entities) {
94
+ const table = (name) => (0, ddl_1.tableName)(entities.find((e) => e.name === name));
95
+ return nested.map((n) => ({
96
+ column: n.field,
97
+ parents: n.parents.map((p) => { var _a; return ({ table: table(p.entity), column: (_a = p.field) !== null && _a !== void 0 ? _a : "" }); }),
98
+ tenantColumn: n.tenantField,
99
+ source: n.source,
100
+ }));
101
+ }
102
+ exports.goNestedScopes = goNestedScopes;
87
103
  /**
88
104
  * Go/Gin generator that produces GORM models, DTOs, Gin handlers,
89
105
  * and service layer code.
@@ -162,7 +178,7 @@ class GoGenerator extends base_1.BaseGenerator {
162
178
  "array",
163
179
  ];
164
180
  if (field.type && !supportedTypes.includes(field.type)) {
165
- warnings.push(`Entity '${entity.name}' field '${field.name}' has type '${field.type}' which may not be fully supported`);
181
+ errors.push(`Entity '${entity.name}' field '${field.name}': the Go generator does not support field type "${field.type}"; use one of ${supportedTypes.join(", ")} or generate a TypeScript service.`);
166
182
  }
167
183
  }
168
184
  }
@@ -323,6 +339,7 @@ class GoGenerator extends base_1.BaseGenerator {
323
339
  ];
324
340
  }
325
341
  async generateController(options) {
342
+ var _a;
326
343
  const { entity, relationships } = options;
327
344
  const { name: entityName } = entity;
328
345
  const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
@@ -336,7 +353,7 @@ class GoGenerator extends base_1.BaseGenerator {
336
353
  primaryKeyGoType: this.getPrimaryKeyGoType(primaryKeyType),
337
354
  primaryKeySwaggerType: this.getPrimaryKeySwaggerType(primaryKeyType),
338
355
  associations: [...new Set(relationshipsForTemplate)],
339
- scope: (0, guards_1.entityScope)(entity, Boolean(options.auth)),
356
+ scope: (0, guards_1.entityScope)(entity, Boolean(options.auth), (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {}),
340
357
  // A write that names a row the caller cannot read is answered like a scope error.
341
358
  references: this.goReferences(entity, this.goAssociations(entity, relationships, options.allEntities), options.allEntities, options.auth).length > 0,
342
359
  };
@@ -370,7 +387,7 @@ class GoGenerator extends base_1.BaseGenerator {
370
387
  ...r,
371
388
  hidden: (0, guards_1.hidesRelation)(entityName, r.name, allEntities, options.auth),
372
389
  })),
373
- scope: this.goScope(entity, Boolean(options.auth)),
390
+ scope: this.goScope(entity, Boolean(options.auth), allEntities),
374
391
  references: this.goReferences(entity, goRelationships, allEntities, options.auth),
375
392
  };
376
393
  const content = await this.renderTemplate("./services/service", data);
@@ -598,21 +615,24 @@ ${modelRefs}
598
615
  * Scope data for a Go service: each direct scopeBy field's struct field and
599
616
  * column (the .apsorc name, as the DDL writer names it). A field declared on the entity is
600
617
  * pascalCase; a relation's foreign key (organizationId) is OrganizationID.
618
+ * A path through a parent (task.workspaceId) carries the foreign key the
619
+ * service reads from a write, to check the parent is the caller's.
601
620
  */
602
- goScope(entity, hasAuth) {
603
- var _a;
604
- const scope = (0, guards_1.entityScope)(entity, hasAuth);
621
+ goScope(entity, hasAuth, allEntities) {
622
+ var _a, _b;
623
+ const scope = (0, guards_1.entityScope)(entity, hasAuth, (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {});
605
624
  if (!scope)
606
625
  return;
607
- const declared = new Set(((_a = entity.fields) !== null && _a !== void 0 ? _a : []).map((f) => f.name));
626
+ const declared = new Set(((_b = entity.fields) !== null && _b !== void 0 ? _b : []).map((f) => f.name));
627
+ const goField = (field) => declared.has(field) || !field.endsWith("Id")
628
+ ? (0, casing_1.pascalCase)(field)
629
+ : `${(0, casing_1.pascalCase)(field.slice(0, -2))}ID`;
608
630
  return {
609
631
  ...scope,
610
- fields: scope.fields.map((f) => ({
611
- ...f,
612
- goField: declared.has(f.field) || !f.field.endsWith("Id")
613
- ? (0, casing_1.pascalCase)(f.field)
614
- : `${(0, casing_1.pascalCase)(f.field.slice(0, -2))}ID`,
615
- column: f.field,
632
+ fields: scope.fields.map((f) => ({ ...f, goField: goField(f.field), column: f.field })),
633
+ nested: goNestedScopes(scope.nested, allEntities).map((n) => ({
634
+ ...n,
635
+ goField: goField(n.column),
616
636
  })),
617
637
  };
618
638
  }
@@ -683,9 +703,6 @@ ${modelRefs}
683
703
  const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
684
704
  if (permissions && !auth)
685
705
  throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
686
- const nested = auth ? (0, guards_1.nestedScopeEntities)(entities) : [];
687
- if (nested.length > 0)
688
- 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.`);
689
706
  // The API key check is part of every service; auth adds user sign-in.
690
707
  // One entry per trusted issuer; undefined when there is no sign-in.
691
708
  const jwt = (0, types_1.resolveJwtProviders)(auth);
@@ -696,6 +713,11 @@ ${modelRefs}
696
713
  authRoutes: (0, guards_1.authEntityNames)(entities, auth).map((name) => (0, casing_1.kebabCase)((0, pluralize_1.default)(name))),
697
714
  relationScopes: (_b = (0, guards_1.relationScopes)(entities, relationshipMap, Boolean(auth))) !== null && _b !== void 0 ? _b : {},
698
715
  tables: Object.fromEntries(entities.map((e) => [e.name, (0, ddl_1.tableName)(e)])),
716
+ // Each entity's scopeBy paths through a parent, as tables and columns.
717
+ nestedScopes: Object.fromEntries(entities.map((e) => [
718
+ e.name,
719
+ auth ? goNestedScopes((0, guards_1.nestedScopes)(e, relationshipMap), entities) : [],
720
+ ])),
699
721
  };
700
722
  const content = await this.renderTemplate("./middleware/auth", data);
701
723
  const files = [{ path: "middleware/auth.go", content }];
@@ -736,7 +758,7 @@ ${modelRefs}
736
758
  }),
737
759
  });
738
760
  // Shared helpers for services and handlers of entities with a direct scopeBy.
739
- if (auth && entities.some((e) => (0, guards_1.entityScope)(e, true))) {
761
+ if (auth && entities.some((e) => (0, guards_1.entityScope)(e, true, relationshipMap))) {
740
762
  files.push({
741
763
  path: "services/scope.go",
742
764
  content: await this.renderTemplate("./services/scope", {}),
@@ -204,7 +204,7 @@ class PythonGenerator extends base_1.BaseGenerator {
204
204
  "array",
205
205
  ];
206
206
  if (field.type && !supportedTypes.includes(field.type)) {
207
- warnings.push(`Entity '${entity.name}' field '${field.name}' has type '${field.type}' which may not be fully supported`);
207
+ errors.push(`Entity '${entity.name}' field '${field.name}': the Python generator does not support field type "${field.type}"; use one of ${supportedTypes.join(", ")} or generate a TypeScript service.`);
208
208
  }
209
209
  }
210
210
  }
@@ -325,7 +325,7 @@ class PythonGenerator extends base_1.BaseGenerator {
325
325
  ];
326
326
  }
327
327
  async generateService(options) {
328
- var _a;
328
+ var _a, _b, _c;
329
329
  const { entity, relationships } = options;
330
330
  const { name: entityName } = entity;
331
331
  const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
@@ -336,11 +336,11 @@ class PythonGenerator extends base_1.BaseGenerator {
336
336
  pluralEntityName,
337
337
  primaryKeyType,
338
338
  associations: [...new Set(relationshipsForTemplate)],
339
- scope: (0, guards_1.entityScope)(entity, Boolean(options.auth)),
339
+ scope: (0, guards_1.entityScope)(entity, Boolean(options.auth), (_b = (_a = options.relationshipMap) !== null && _a !== void 0 ? _a : this.config.relationshipMap) !== null && _b !== void 0 ? _b : {}),
340
340
  // Foreign keys a write must check: those onto tenant-scoped entities.
341
341
  references: Object.entries((0, guards_1.scopedReferences)(entity, relationshipsForTemplate
342
342
  .filter((a) => a.type === "ManyToOne" || (a.type === "OneToOne" && a.joinTable))
343
- .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 })),
343
+ .map((a) => [a.camelCasedId, a.name]), (0, guards_1.relationScopes)(options.allEntities, (_c = options.relationshipMap) !== null && _c !== void 0 ? _c : this.config.relationshipMap, Boolean(options.auth)))).map(([field, target]) => ({ field, target })),
344
344
  };
345
345
  const content = await this.renderTemplate("./services/service", data);
346
346
  return [
@@ -575,9 +575,6 @@ ${downStatements || " pass"}
575
575
  const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
576
576
  if (permissions && !auth)
577
577
  throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
578
- const nested = auth ? (0, guards_1.nestedScopeEntities)(entities) : [];
579
- if (nested.length > 0)
580
- 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.`);
581
578
  // The API key check is part of every service; auth adds user sign-in.
582
579
  // One entry per trusted issuer; undefined when there is no sign-in.
583
580
  const jwt = (0, types_1.resolveJwtProviders)(auth);
@@ -587,6 +584,8 @@ ${downStatements || " pass"}
587
584
  // Routes only a service caller reaches (sessions, accounts, ...).
588
585
  authRoutes: (0, guards_1.authEntityRoutes)(entities, auth),
589
586
  relationScopes: (_b = (0, guards_1.relationScopes)(entities, relationshipMap, Boolean(auth))) !== null && _b !== void 0 ? _b : {},
587
+ // Each entity's scopeBy paths through a parent, resolved to foreign keys.
588
+ nestedScopes: Object.fromEntries(entities.map((e) => [e.name, auth ? (0, guards_1.nestedScopes)(e, relationshipMap) : []])),
590
589
  };
591
590
  const files = [
592
591
  { path: "auth.py", content: await this.renderTemplate("./auth", data) },
@@ -205,7 +205,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
205
205
  ];
206
206
  }
207
207
  async generateController(options) {
208
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
208
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
209
209
  const { entity, relationships, relationshipMap, auth } = options;
210
210
  const { name: entityName } = entity;
211
211
  // Auth entities are for service callers only, so no other entity's
@@ -251,13 +251,27 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
251
251
  .filter((r) => r.primary)
252
252
  .map((r) => r.camelCasedId),
253
253
  ];
254
+ // Each role-gated handler's rule, added to its OpenAPI description.
255
+ const handlers = {
256
+ read: ["getMany", "get"],
257
+ create: ["create", "createMany"],
258
+ update: ["update", "replace", "recoverOneBase"],
259
+ delete: ["delete"],
260
+ };
261
+ const roleDocs = {};
262
+ if (auth)
263
+ for (const [op, rule] of Object.entries((0, guards_1.entityRoleRules)(entity)))
264
+ for (const handler of (_c = handlers[op]) !== null && _c !== void 0 ? _c : [])
265
+ roleDocs[handler] = (0, guards_1.roleRuleText)(rule, auth);
254
266
  const data = {
267
+ hasAuth: Boolean(auth),
268
+ roleDocs,
255
269
  svcName,
256
270
  ctrlName,
257
271
  entityName,
258
272
  pluralEntityName,
259
273
  primaryKeyType,
260
- generatedFields: ((_c = entity.fields) !== null && _c !== void 0 ? _c : [])
274
+ generatedFields: ((_d = entity.fields) !== null && _d !== void 0 ? _d : [])
261
275
  .filter((f) => f.generated)
262
276
  .map((f) => f.name),
263
277
  keyField: keyFields.length === 1 ? keyFields[0] : "id",
@@ -276,10 +290,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
276
290
  mcp,
277
291
  mcpName: (0, casing_1.snakeCase)(entityName),
278
292
  mcpPluralName: (0, casing_1.snakeCase)(pluralEntityName),
279
- dialects: (_e = (_d = options.query) === null || _d === void 0 ? void 0 : _d.dialects) !== null && _e !== void 0 ? _e : ["postgrest"],
280
- dialectList: ((_g = (_f = options.query) === null || _f === void 0 ? void 0 : _f.dialects) !== null && _g !== void 0 ? _g : ["postgrest"]).map((d) => `'${d}'`).join(", "),
281
- limit: (_j = (_h = options.query) === null || _h === void 0 ? void 0 : _h.limit) !== null && _j !== void 0 ? _j : 25,
282
- alwaysPaginate: (_l = (_k = options.query) === null || _k === void 0 ? void 0 : _k.alwaysPaginate) !== null && _l !== void 0 ? _l : false,
293
+ dialects: (_f = (_e = options.query) === null || _e === void 0 ? void 0 : _e.dialects) !== null && _f !== void 0 ? _f : ["postgrest"],
294
+ dialectList: ((_h = (_g = options.query) === null || _g === void 0 ? void 0 : _g.dialects) !== null && _h !== void 0 ? _h : ["postgrest"]).map((d) => `'${d}'`).join(", "),
295
+ limit: (_k = (_j = options.query) === null || _j === void 0 ? void 0 : _j.limit) !== null && _k !== void 0 ? _k : 25,
296
+ alwaysPaginate: (_m = (_l = options.query) === null || _l === void 0 ? void 0 : _l.alwaysPaginate) !== null && _m !== void 0 ? _m : false,
283
297
  };
284
298
  const controllerContent = await this.renderTemplate("./rest/controller-rest", data);
285
299
  const specContent = await this.renderTemplate("./rest/controller-rest-spec", data);
@@ -346,7 +360,8 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
346
360
  ];
347
361
  }
348
362
  async generateDto(options) {
349
- const { entity, relationships, allEntities, apiType } = options;
363
+ var _a, _b;
364
+ const { entity, relationships, allEntities, apiType, auth } = options;
350
365
  const { name: entityName, fields = [] } = entity;
351
366
  const columns = (0, field_1.getFieldForTemplate)(fields, entityName);
352
367
  const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
@@ -367,6 +382,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
367
382
  dataType: fkDataType,
368
383
  type: fkType,
369
384
  ...(rel.primary && { primary: true }),
385
+ nullable: rel.nullable,
370
386
  });
371
387
  }
372
388
  }
@@ -376,7 +392,25 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
376
392
  const createdAt = entity.created_at;
377
393
  const updatedAt = entity.updated_at;
378
394
  const primaryKeyType = entity.primaryKeyType || "serial";
379
- const dtoColumns = columns.filter((col) => !["id", "createdAt", "updatedAt"].includes(col.name));
395
+ // With sign-in configured, @CrudAuth sets the scopeBy field from the
396
+ // caller's tenant on every write, so the request schemas leave it out.
397
+ const scopeFields = auth
398
+ ? ((_b = (_a = (0, guards_1.getScopedEntities)([entity])[0]) === null || _a === void 0 ? void 0 : _a.scopes) !== null && _b !== void 0 ? _b : [])
399
+ .filter((s) => s.direct)
400
+ .map((s) => s.field)
401
+ : [];
402
+ const dtoColumns = columns
403
+ .filter((col) => !["id", "createdAt", "updatedAt"].includes(col.name))
404
+ .map((col) => ({
405
+ ...col,
406
+ // A create must send it: NOT NULL with no default the database fills in.
407
+ required: !col.nullable &&
408
+ !col.auto &&
409
+ !col.primary &&
410
+ (col.default === null || col.default === undefined) &&
411
+ !scopeFields.includes(col.name),
412
+ serverSet: scopeFields.includes(col.name),
413
+ }));
380
414
  const createDtoName = `Create${(0, casing_1.pascalCase)(entityName)}Dto`;
381
415
  const updateDtoName = `Update${(0, casing_1.pascalCase)(entityName)}Dto`;
382
416
  const data = {
@@ -462,7 +496,12 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
462
496
  // "sqlIndexes" are created by a generated module, after TypeORM's sync.
463
497
  const statements = entities.flatMap((e) => (0, ddl_1.sqlIndexStatements)(e));
464
498
  const schemaExtras = apiType === "rest" && statements.length > 0;
465
- const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, { entities, schemaExtras, guards: (opts === null || opts === void 0 ? void 0 : opts.guards) !== false });
499
+ const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, {
500
+ entities,
501
+ schemaExtras,
502
+ guards: (opts === null || opts === void 0 ? void 0 : opts.guards) !== false,
503
+ apiDescription: (0, guards_1.accessSummary)(entities, opts === null || opts === void 0 ? void 0 : opts.auth),
504
+ });
466
505
  return [
467
506
  {
468
507
  path: "index.ts",