@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
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ /**
3
+ * A local token issuer for the access suite: it signs user tokens with the
4
+ * claim names of the project's own `auth` block and serves the public key as
5
+ * a JWKS, so a service started with AUTH_JWT_ISSUER and AUTH_JWKS_URI pointed
6
+ * here checks them the way it checks its real issuer's tokens.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.startIssuer = exports.setClaim = exports.sign = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const crypto = tslib_1.__importStar(require("crypto"));
12
+ const http = tslib_1.__importStar(require("http"));
13
+ const bearer = (token) => ({ authorization: `Bearer ${token}` });
14
+ const bad = (label, token) => ({ label, headers: bearer(token) });
15
+ const b64url = (v) => Buffer.from(typeof v === "string" ? v : JSON.stringify(v)).toString("base64url");
16
+ const generate = (alg) => {
17
+ if (alg === "EdDSA")
18
+ return crypto.generateKeyPairSync("ed25519");
19
+ if (alg.startsWith("ES"))
20
+ return crypto.generateKeyPairSync("ec", { namedCurve: alg === "ES384" ? "P-384" : "P-256" });
21
+ return crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
22
+ };
23
+ /**
24
+ * Sign a JWT. `alg` picks the signature; an unknown one (e.g. "none") leaves it empty.
25
+ * @param {object} payload - The claims; undefined values are dropped
26
+ * @param {string} alg - The JWS algorithm
27
+ * @param {crypto.KeyObject | string} key - The private key, or the secret for HS256
28
+ * @param {string} kid - The key id in the header
29
+ * @returns {string} The token
30
+ */
31
+ function sign(payload, alg, key, kid = "apso-test") {
32
+ const now = Math.floor(Date.now() / 1000);
33
+ const body = { iat: now, exp: now + 600, ...payload };
34
+ for (const k of Object.keys(body))
35
+ if (body[k] === undefined)
36
+ delete body[k];
37
+ const head = `${b64url({ alg, typ: "JWT", kid })}.${b64url(body)}`;
38
+ const data = Buffer.from(head);
39
+ const hash = `sha${alg.slice(2)}`;
40
+ let sig = "";
41
+ if (alg === "HS256")
42
+ sig = crypto.createHmac("sha256", key).update(head).digest("base64url");
43
+ else if (alg === "EdDSA")
44
+ sig = crypto.sign(null, data, key).toString("base64url");
45
+ else if (alg.startsWith("RS"))
46
+ sig = crypto.sign(hash, data, key).toString("base64url");
47
+ else if (alg.startsWith("PS"))
48
+ sig = crypto
49
+ .sign(hash, data, {
50
+ key: key,
51
+ padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
52
+ saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST,
53
+ })
54
+ .toString("base64url");
55
+ else if (alg.startsWith("ES"))
56
+ sig = crypto.sign(hash, data, { key: key, dsaEncoding: "ieee-p1363" }).toString("base64url");
57
+ return `${head}.${sig}`;
58
+ }
59
+ exports.sign = sign;
60
+ /** Auth0 namespaced claims are URLs with dots in them; any other dotted name is a path. */
61
+ function setClaim(payload, path, value) {
62
+ if (!path || value === undefined)
63
+ return;
64
+ if (!path.includes(".") || path.includes("://")) {
65
+ payload[path] = value;
66
+ return;
67
+ }
68
+ const parts = path.split(".");
69
+ let at = payload;
70
+ for (const part of parts.slice(0, -1)) {
71
+ at[part] = typeof at[part] === "object" && at[part] !== null ? at[part] : {};
72
+ at = at[part];
73
+ }
74
+ at[parts[parts.length - 1]] = value;
75
+ }
76
+ exports.setClaim = setClaim;
77
+ /**
78
+ * Start the issuer on a free local port.
79
+ * @param {ResolvedJwtAuth} auth - The project's auth block, defaults filled in
80
+ * @returns {Promise<Issuer>} The running issuer
81
+ */
82
+ async function startIssuer(auth) {
83
+ var _a;
84
+ const alg = auth.algorithms[0];
85
+ const keys = generate(alg);
86
+ const impostor = generate(alg);
87
+ const jwks = { keys: [{ ...keys.publicKey.export({ format: "jwk" }), kid: "apso-test", alg, use: "sig" }] };
88
+ const server = http.createServer((_req, res) => {
89
+ res.writeHead(200, { "content-type": "application/json" });
90
+ res.end(JSON.stringify(jwks));
91
+ });
92
+ await new Promise((resolve) => {
93
+ server.listen(0, "127.0.0.1", resolve);
94
+ });
95
+ const { port } = server.address();
96
+ const issuer = `http://127.0.0.1:${port}/`;
97
+ // A Better Auth service with no audience set expects the origin of its issuer as the audience.
98
+ const audience = (_a = auth.audience) !== null && _a !== void 0 ? _a : (auth.provider === "better-auth" ? new URL(issuer).origin : undefined);
99
+ const claims = ({ tenant, roles } = {}) => {
100
+ var _a;
101
+ const payload = {
102
+ iss: issuer,
103
+ aud: audience,
104
+ azp: auth.authorizedParties[0],
105
+ // Cognito access tokens carry client_id where others carry aud.
106
+ // eslint-disable-next-line camelcase
107
+ ...(auth.provider === "cognito" ? { client_id: auth.audience, token_use: "access" } : {}),
108
+ };
109
+ setClaim(payload, auth.claims.userId, `apso-test-user-${tenant !== null && tenant !== void 0 ? tenant : "none"}`);
110
+ setClaim(payload, auth.claims.email, "access-test@example.com");
111
+ setClaim(payload, (_a = auth.claims.workspaceId) !== null && _a !== void 0 ? _a : auth.claims.organizationId, tenant);
112
+ // Clerk's role claim (o.rol) is one role, not a list.
113
+ if (roles && roles.length > 0)
114
+ setClaim(payload, auth.claims.roles, auth.provider === "clerk" ? roles[0] : roles);
115
+ return payload;
116
+ };
117
+ const valid = claims({ tenant: "1" });
118
+ return {
119
+ env: { AUTH_JWT_ISSUER: issuer, AUTH_JWKS_URI: `${issuer}jwks.json` },
120
+ roles: Boolean(auth.claims.roles),
121
+ user: (caller) => bearer(sign(claims(caller), alg, keys.privateKey)),
122
+ badTokens: () => [
123
+ bad("a token that is not a JWT", "not.a.jwt"),
124
+ bad("an expired token", sign({ ...valid, exp: Math.floor(Date.now() / 1000) - 60 }, alg, keys.privateKey)),
125
+ bad("a token from another issuer", sign({ ...valid, iss: "https://evil.example/" }, alg, keys.privateKey)),
126
+ ...(audience
127
+ ? // eslint-disable-next-line camelcase
128
+ [bad("a token for another audience", sign({ ...valid, aud: "https://other.example", client_id: "other" }, alg, keys.privateKey))]
129
+ : []),
130
+ bad("a token signed by another key", sign(valid, alg, impostor.privateKey)),
131
+ bad('a token with alg "none"', sign(valid, "none", "")),
132
+ bad("an HS256 token signed with the public key", sign(valid, "HS256", keys.publicKey.export({ type: "spki", format: "pem" }))),
133
+ ],
134
+ close: () => {
135
+ server.close();
136
+ },
137
+ };
138
+ }
139
+ exports.startIssuer = startIssuer;
@@ -10,7 +10,8 @@
10
10
  * backend's snake_case / nestjsx-crud shapes and are adapted to the CLI types
11
11
  * below.
12
12
  */
13
- import { UserProfile, Workspace, Service, ServiceSchema, GitHubRepo, GitHubConnection, BuildStatus, PaginatedResponse, TokenExchangeResponse } from "./types";
13
+ import { UserProfile, Workspace, Service, GitHubRepo, GitHubConnection, BuildStatus, PaginatedResponse, TokenExchangeResponse } from "./types";
14
+ import type { ApsorcType } from "../apsorc-parser";
14
15
  type Raw = Record<string, any>;
15
16
  /**
16
17
  * Authentication API
@@ -61,18 +62,20 @@ export declare const servicesApi: {
61
62
  delete(_workspaceSlug: string, serviceSlugOrId: string): Promise<void>;
62
63
  };
63
64
  /**
64
- * Schema API — the schema lives on the service as its `apsorc` field, and
65
- * versioned rows exist under /api/ServiceSchemas.
65
+ * Schema API. The schema lives on the service as its `apsorc` field: the
66
+ * .apsorc itself, whole, which is also what the web editor saves. Versioned
67
+ * rows exist under /api/ServiceSchemas.
66
68
  */
67
69
  export declare const schemaApi: {
68
- getByServiceId(serviceId: string): Promise<ServiceSchema>;
69
- get(_workspaceSlug: string, serviceSlug: string): Promise<ServiceSchema>;
70
- update(_workspaceSlug: string, serviceSlugOrId: string, schema: Omit<ServiceSchema, "id" | "serviceId" | "version" | "createdAt" | "updatedAt">): Promise<ServiceSchema>;
70
+ /** The service's .apsorc, or null when the platform has none yet. */
71
+ get(_workspaceSlug: string, serviceSlug: string): Promise<ApsorcType | null>;
72
+ update(_workspaceSlug: string, serviceSlugOrId: string, apsorc: ApsorcType): Promise<ApsorcType | null>;
71
73
  validate(_workspaceSlug?: string, _serviceSlug?: string, _schema?: unknown): Promise<{
72
74
  valid: boolean;
73
75
  errors: string[];
74
76
  }>;
75
- diff(_workspaceSlug?: string, _serviceSlug?: string, _localSchema?: unknown): Promise<{
77
+ /** What pushing the local .apsorc would change on the platform. */
78
+ diff(workspaceSlug: string, serviceSlug: string, local: ApsorcType): Promise<{
76
79
  hasChanges: boolean;
77
80
  added: string[];
78
81
  removed: string[];
@@ -14,6 +14,7 @@
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.codeApi = exports.githubApi = exports.envApi = exports.SERVICE_ENVS = exports.toBuildStatus = exports.buildApi = exports.schemaApi = exports.servicesApi = exports.workspacesApi = exports.authApi = void 0;
16
16
  const client_1 = require("./client");
17
+ const schema_convert_1 = require("../utils/schema-convert");
17
18
  function adaptWorkspace(raw) {
18
19
  var _a, _b, _c, _d;
19
20
  // /api/workspaces returns workspace_user rows with a nested `workspace`;
@@ -181,55 +182,41 @@ async function resolveServiceId(serviceSlugOrId) {
181
182
  return svc.id;
182
183
  }
183
184
  /**
184
- * Schema API — the schema lives on the service as its `apsorc` field, and
185
- * versioned rows exist under /api/ServiceSchemas.
185
+ * Schema API. The schema lives on the service as its `apsorc` field: the
186
+ * .apsorc itself, whole, which is also what the web editor saves. Versioned
187
+ * rows exist under /api/ServiceSchemas.
186
188
  */
187
189
  exports.schemaApi = {
188
- async getByServiceId(serviceId) {
189
- const raw = await client_1.api.get(`/api/services/${serviceId}`);
190
- return adaptSchemaFromService(raw);
191
- },
190
+ /** The service's .apsorc, or null when the platform has none yet. */
192
191
  async get(_workspaceSlug, serviceSlug) {
193
192
  const id = await resolveServiceId(serviceSlug);
194
- return this.getByServiceId(id);
193
+ return apsorcFromService(await client_1.api.get(`/api/services/${id}`));
195
194
  },
196
- async update(_workspaceSlug, serviceSlugOrId, schema) {
195
+ async update(_workspaceSlug, serviceSlugOrId, apsorc) {
197
196
  const id = await resolveServiceId(serviceSlugOrId);
198
- // Persist the schema onto the service's apsorc; the deploy pipeline reads it.
199
- const raw = await client_1.api.patch(`/api/services/${id}`, {
200
- apsorc: JSON.stringify(schema),
201
- });
202
- return adaptSchemaFromService(raw);
197
+ return apsorcFromService(await client_1.api.patch(`/api/services/${id}`, { apsorc }));
203
198
  },
204
- // Validation and diff are computed locally by the CLI (the schema format is
205
- // fully known client-side), so these do not call the BFF. Signatures are kept
206
- // for the callers; the arguments are intentionally unused here.
199
+ // Validation is computed locally by the CLI (the schema format is fully
200
+ // known client-side), so this does not call the BFF. The signature is kept
201
+ // for the caller; the arguments are intentionally unused here.
207
202
  async validate(_workspaceSlug, _serviceSlug, _schema) {
208
203
  return { valid: true, errors: [] };
209
204
  },
210
- async diff(_workspaceSlug, _serviceSlug, _localSchema) {
211
- return { hasChanges: false, added: [], removed: [], modified: [] };
205
+ /** What pushing the local .apsorc would change on the platform. */
206
+ async diff(workspaceSlug, serviceSlug, local) {
207
+ return (0, schema_convert_1.diffApsorc)(await this.get(workspaceSlug, serviceSlug), local);
212
208
  },
213
209
  };
214
- function adaptSchemaFromService(raw) {
215
- var _a, _b, _c;
216
- let entities = [];
210
+ function apsorcFromService(raw) {
211
+ var _a;
217
212
  const rc = raw.apsorc;
218
213
  try {
219
- const parsed = typeof rc === "string" ? JSON.parse(rc) : rc;
220
- entities = (_a = parsed === null || parsed === void 0 ? void 0 : parsed.entities) !== null && _a !== void 0 ? _a : [];
214
+ // Old rows hold the .apsorc as a JSON string.
215
+ return (_a = (typeof rc === "string" ? JSON.parse(rc) : rc)) !== null && _a !== void 0 ? _a : null;
221
216
  }
222
217
  catch {
223
- entities = [];
218
+ return null;
224
219
  }
225
- return {
226
- id: String(raw.id),
227
- serviceId: String(raw.id),
228
- version: 1,
229
- entities,
230
- createdAt: (_b = raw.created_at) !== null && _b !== void 0 ? _b : raw.createdAt,
231
- updatedAt: (_c = raw.updated_at) !== null && _c !== void 0 ? _c : raw.updatedAt,
232
- };
233
220
  }
234
221
  /**
235
222
  * Build / Deploy API
@@ -36,7 +36,7 @@ type ParsedApsorcData = {
36
36
  entities: Entity[];
37
37
  relationshipMap: RelationshipMap;
38
38
  };
39
- type ParsedApsorc = {
39
+ export type ParsedApsorc = {
40
40
  rootFolder: string;
41
41
  apiType: string;
42
42
  entities: Entity[];
@@ -5,6 +5,7 @@ const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
7
7
  const rc_1 = tslib_1.__importDefault(require("rc"));
8
+ const auth_1 = require("./types/auth");
8
9
  const relationships_1 = require("./utils/relationships");
9
10
  const perf_hooks_1 = require("perf_hooks");
10
11
  // @apso/schema-tools is published on npm (apsoai/apso-packages).
@@ -130,6 +131,7 @@ const parseRc = () => {
130
131
  const entities = apsoConfig.entities || [];
131
132
  const relationships = apsoConfig.relationships || [];
132
133
  const auth = apsoConfig.auth;
134
+ (0, auth_1.authProviders)(auth);
133
135
  const language = apsoConfig.language;
134
136
  const emitEvents = apsoConfig.emitEvents;
135
137
  const http = apsoConfig.http;
@@ -112,6 +112,8 @@ function changeDdl(before, after, plan) {
112
112
  return (0, _1.tableName)(e);
113
113
  };
114
114
  const up = renames(was, R);
115
+ // A new uuid-keyed table needs uuid-ossp; schemaDdl creates it, so do the same here.
116
+ up.unshift(...A.extensions.filter((x) => !R.extensions.includes(x)));
115
117
  const later = [];
116
118
  const rTables = new Map(R.tables.map((t) => [t.name, t]));
117
119
  const aTables = new Map(A.tables.map((t) => [t.name, t]));
@@ -1,6 +1,6 @@
1
1
  import { Entity } from "../types/entity";
2
2
  import { ComputedField } from "../types/field";
3
- import { RelationshipMap } from "../types/relationship";
3
+ import { RelationshipForTemplate, RelationshipMap } from "../types/relationship";
4
4
  export declare const constraintName: {
5
5
  primaryKey: (t: string, cols: string[]) => string;
6
6
  unique: (t: string, cols: string[]) => string;
@@ -71,6 +71,16 @@ export interface Model {
71
71
  constraints: ModelConstraint[];
72
72
  indexes: ModelIndex[];
73
73
  }
74
+ export declare const pkColumn: (e: Entity) => string;
75
+ export declare const fkType: (target?: Entity) => string;
76
+ /** The foreign key column of a ManyToOne or an owning OneToOne. */
77
+ export declare const relationColumn: (r: RelationshipForTemplate) => string;
78
+ /** The join table of an owning ManyToMany and its two key columns. */
79
+ export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity) => {
80
+ name: string;
81
+ ownCol: string;
82
+ otherCol: string;
83
+ };
74
84
  export declare function schemaModel(input: SchemaInput): Model;
75
85
  export declare const createTypeSql: (e: ModelEnum) => string;
76
86
  export declare const createIndexSql: (i: ModelIndex) => string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.schemaDdl = exports.createTableSql = exports.addConstraintSql = exports.createIndexSql = exports.createTypeSql = exports.schemaModel = exports.columnSpec = exports.enumTypeName = exports.tableName = exports.literal = exports.q = exports.constraintName = void 0;
3
+ exports.schemaDdl = exports.createTableSql = exports.addConstraintSql = exports.createIndexSql = exports.createTypeSql = exports.schemaModel = exports.joinTableOf = exports.relationColumn = exports.fkType = exports.pkColumn = exports.columnSpec = exports.enumTypeName = exports.tableName = exports.literal = exports.q = exports.constraintName = void 0;
4
4
  /**
5
5
  * Apso's own DDL writer: the CREATE statements for a whole .apsorc schema.
6
6
  *
@@ -109,7 +109,7 @@ function columnSpec(table, f) {
109
109
  break;
110
110
  case "array": {
111
111
  // entity-col-array.eta: { type: elementType || "text", array: true }, no default.
112
- const element = f.elementType || "text";
112
+ const element = (0, field_1.arrayElementType)(f);
113
113
  if (!/^[a-z][\w ]*$/i.test(element))
114
114
  throw new Error(`Field ${table}.${f.name} has an invalid elementType "${element}".`);
115
115
  type = `${element}[]`;
@@ -144,7 +144,27 @@ const column = (name, type, notNull, def, serial) => ({
144
144
  serial,
145
145
  });
146
146
  const pkColumn = (e) => { var _a, _b, _c; return (_c = (_b = ((_a = e.fields) !== null && _a !== void 0 ? _a : []).find((f) => f.primary)) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : "id"; };
147
+ exports.pkColumn = pkColumn;
147
148
  const fkType = (target) => (target === null || target === void 0 ? void 0 : target.primaryKeyType) === "uuid" ? "uuid" : "integer";
149
+ exports.fkType = fkType;
150
+ /** The foreign key column of a ManyToOne or an owning OneToOne. */
151
+ const relationColumn = (r) => r.type === "ManyToOne"
152
+ ? r.camelCasedId
153
+ : typeormCase.camelCase(`${r.relationshipName}_id`);
154
+ exports.relationColumn = relationColumn;
155
+ /** The join table of an owning ManyToMany and its two key columns. */
156
+ const joinTableOf = (e, r, target) => {
157
+ const table = (0, exports.tableName)(e);
158
+ const targetTable = (0, exports.tableName)(target);
159
+ return {
160
+ name: r.joinTableName ||
161
+ typeormCase.snakeCase(`${table}_${r.pluralizedRelationshipName}_${targetTable}`),
162
+ ownCol: r.joinColumnName || typeormCase.camelCase(`${table}_${(0, exports.pkColumn)(e)}`),
163
+ otherCol: r.inverseJoinColumnName ||
164
+ typeormCase.camelCase(`${targetTable}_${(0, exports.pkColumn)(target)}`),
165
+ };
166
+ };
167
+ exports.joinTableOf = joinTableOf;
148
168
  function schemaModel(input) {
149
169
  var _a, _b, _c, _d, _e;
150
170
  const { entities, relationshipMap } = input;
@@ -254,27 +274,21 @@ function schemaModel(input) {
254
274
  const oneToOne = r.type === "OneToOne";
255
275
  const onDelete = r.cascadeDelete || oneToOne ? "CASCADE" : "NO ACTION";
256
276
  if (r.type === "ManyToOne" || (oneToOne && r.joinTable)) {
257
- const col = r.type === "ManyToOne"
258
- ? r.camelCasedId
259
- : typeormCase.camelCase(`${r.relationshipName}_id`);
260
- t.columns.push(column(col, fkType(target), !(r.nullable || oneToOne)));
277
+ const col = (0, exports.relationColumn)(r);
278
+ t.columns.push(column(col, (0, exports.fkType)(target), !(r.nullable || oneToOne)));
261
279
  if (oneToOne)
262
280
  unique(table, [col], exports.constraintName.relation(table, [col]));
263
281
  if (r.type === "ManyToOne" && r.index)
264
282
  index(table, [col]);
265
- foreignKey(table, col, targetTable, pkColumn(target), `ON DELETE ${onDelete} ON UPDATE NO ACTION`);
283
+ foreignKey(table, col, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${onDelete} ON UPDATE NO ACTION`);
266
284
  }
267
285
  if (r.type === "ManyToMany" && r.joinTable) {
268
- const join = r.joinTableName ||
269
- typeormCase.snakeCase(`${table}_${r.pluralizedRelationshipName}_${targetTable}`);
270
- const ownCol = r.joinColumnName || typeormCase.camelCase(`${table}_${pkColumn(e)}`);
271
- const otherCol = r.inverseJoinColumnName ||
272
- typeormCase.camelCase(`${targetTable}_${pkColumn(target)}`);
286
+ const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target);
273
287
  joinTables.push({
274
288
  name: join,
275
289
  columns: [
276
- column(ownCol, fkType(e), true),
277
- column(otherCol, fkType(target), true),
290
+ column(ownCol, (0, exports.fkType)(e), true),
291
+ column(otherCol, (0, exports.fkType)(target), true),
278
292
  ],
279
293
  });
280
294
  primaryKey(join, [ownCol, otherCol]);
@@ -282,8 +296,8 @@ function schemaModel(input) {
282
296
  index(join, [otherCol]);
283
297
  // TypeORM cascades the inverse key only when no inverse relation exists.
284
298
  const inverse = r.biDirectional ? "NO ACTION" : "CASCADE";
285
- foreignKey(join, ownCol, table, pkColumn(e), "ON DELETE CASCADE ON UPDATE CASCADE");
286
- foreignKey(join, otherCol, targetTable, pkColumn(target), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
299
+ foreignKey(join, ownCol, table, (0, exports.pkColumn)(e), "ON DELETE CASCADE ON UPDATE CASCADE");
300
+ foreignKey(join, otherCol, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
287
301
  }
288
302
  }
289
303
  primaryKey(table, customPk
@@ -0,0 +1,25 @@
1
+ /**
2
+ * DATABASE_SYNC for services whose ORM can't build the DDL on its own (Go):
3
+ * the same objects schemaDdl creates, as statements that create only what is
4
+ * missing. A fresh database ends up exactly as `apso migrate` builds it, and
5
+ * a database built by the migrations is left as it is. Nothing is altered or
6
+ * dropped, like gorm's AutoMigrate.
7
+ */
8
+ import { SchemaInput } from ".";
9
+ /** Something an older generated service named differently, and the SQL that renames it. */
10
+ export interface LegacyName {
11
+ /** SQL that is true when the database still has the old name. */
12
+ when: string;
13
+ fix: string[];
14
+ }
15
+ export declare const legacyColumn: (table: string, from: string, to: string) => LegacyName;
16
+ export declare const legacyTable: (from: string, to: string, columns?: [string, string][]) => LegacyName;
17
+ export declare const legacyType: (from: string, to: string) => LegacyName;
18
+ /**
19
+ * One statement that fails, naming the renames to run, when the database
20
+ * still has names an older generated service used. Run before anything
21
+ * else, so a sync never adds empty columns beside ones that hold the data.
22
+ */
23
+ export declare function legacyGuardSql(legacy: LegacyName[]): string | undefined;
24
+ /** Statements that bring a database up to the schema without dropping or altering anything. */
25
+ export declare function syncStatements(input: SchemaInput, legacy?: LegacyName[]): string[];
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.syncStatements = exports.legacyGuardSql = exports.legacyType = exports.legacyTable = exports.legacyColumn = void 0;
4
+ /**
5
+ * DATABASE_SYNC for services whose ORM can't build the DDL on its own (Go):
6
+ * the same objects schemaDdl creates, as statements that create only what is
7
+ * missing. A fresh database ends up exactly as `apso migrate` builds it, and
8
+ * a database built by the migrations is left as it is. Nothing is altered or
9
+ * dropped, like gorm's AutoMigrate.
10
+ */
11
+ const _1 = require(".");
12
+ const columnExists = (table, column) => `EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ${(0, _1.literal)(table)} AND column_name = ${(0, _1.literal)(column)})`;
13
+ const tableExists = (table) => `to_regclass(${(0, _1.literal)((0, _1.q)(table))}) IS NOT NULL`;
14
+ const typeExists = (name) => `EXISTS (SELECT 1 FROM pg_type WHERE typname = ${(0, _1.literal)(name)} AND typnamespace = 'public'::regnamespace)`;
15
+ const legacyColumn = (table, from, to) => ({
16
+ when: `${columnExists(table, from)} AND NOT ${columnExists(table, to)}`,
17
+ fix: [`ALTER TABLE ${(0, _1.q)(table)} RENAME COLUMN ${(0, _1.q)(from)} TO ${(0, _1.q)(to)}`],
18
+ });
19
+ exports.legacyColumn = legacyColumn;
20
+ const legacyTable = (from, to, columns = []) => ({
21
+ when: `${tableExists(from)} AND NOT ${tableExists(to)}`,
22
+ fix: [
23
+ `ALTER TABLE ${(0, _1.q)(from)} RENAME TO ${(0, _1.q)(to)}`,
24
+ ...columns
25
+ .filter(([a, b]) => a !== b)
26
+ .map(([a, b]) => `ALTER TABLE ${(0, _1.q)(to)} RENAME COLUMN ${(0, _1.q)(a)} TO ${(0, _1.q)(b)}`),
27
+ ],
28
+ });
29
+ exports.legacyTable = legacyTable;
30
+ const legacyType = (from, to) => ({
31
+ when: `${typeExists(from)} AND NOT ${typeExists(to)}`,
32
+ fix: [`ALTER TYPE "public".${(0, _1.q)(from)} RENAME TO ${(0, _1.q)(to)}`],
33
+ });
34
+ exports.legacyType = legacyType;
35
+ const block = (body) => `DO $apso$ BEGIN ${body} END $apso$`;
36
+ /**
37
+ * One statement that fails, naming the renames to run, when the database
38
+ * still has names an older generated service used. Run before anything
39
+ * else, so a sync never adds empty columns beside ones that hold the data.
40
+ */
41
+ function legacyGuardSql(legacy) {
42
+ if (legacy.length === 0)
43
+ return undefined;
44
+ const checks = legacy
45
+ .map((l) => `IF ${l.when} THEN fix := fix || ${(0, _1.literal)(l.fix.map((s) => s + ";\n").join(""))}; END IF;`)
46
+ .join(" ");
47
+ return `DO $apso$ DECLARE fix text := ''; BEGIN ${checks} IF fix <> '' THEN RAISE EXCEPTION USING MESSAGE = ${(0, _1.literal)("This database was created by an older Apso-generated service, which named these columns, tables or types differently. Nothing was changed. Run this SQL once to keep the data, then start the service again:\n")} || fix; END IF; END $apso$`;
48
+ }
49
+ exports.legacyGuardSql = legacyGuardSql;
50
+ /** Statements that bring a database up to the schema without dropping or altering anything. */
51
+ function syncStatements(input, legacy = []) {
52
+ const m = (0, _1.schemaModel)(input);
53
+ const guard = legacyGuardSql(legacy);
54
+ return [
55
+ ...(guard ? [guard] : []),
56
+ ...m.extensions,
57
+ ...m.enums.map((e) => block(`IF NOT ${typeExists(e.name)} THEN ${(0, _1.createTypeSql)(e)}; END IF;`)),
58
+ ...m.tables.flatMap((t) => {
59
+ const pk = new Set(m.constraints
60
+ .filter((c) => c.kind === "pk" && c.table === t.name)
61
+ .flatMap((c) => c.columns));
62
+ return [
63
+ (0, _1.createTableSql)(t, m.constraints).replace(/^CREATE TABLE /, "CREATE TABLE IF NOT EXISTS "),
64
+ // A table from an older .apsorc gets the columns added since. Key
65
+ // columns are left out: an existing table has them, and ADD COLUMN
66
+ // IF NOT EXISTS with SERIAL makes a sequence even when it skips.
67
+ ...t.columns
68
+ .filter((c) => !pk.has(c.name))
69
+ .map((c) => `ALTER TABLE ${(0, _1.q)(t.name)} ADD COLUMN IF NOT EXISTS ${c.sql}`),
70
+ ];
71
+ }),
72
+ ...m.indexes.map((i) => (0, _1.createIndexSql)(i).replace(/^CREATE (UNIQUE )?INDEX /, "CREATE $1INDEX IF NOT EXISTS ")),
73
+ ...m.constraints
74
+ .filter((c) => c.kind !== "pk")
75
+ .map((c) => block(`IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${(0, _1.literal)(c.name)} AND conrelid = to_regclass(${(0, _1.literal)((0, _1.q)(c.table))})) THEN ALTER TABLE ${(0, _1.q)(c.table)} ADD CONSTRAINT ${(0, _1.q)(c.name)} ${c.body}; END IF;`)),
76
+ ];
77
+ }
78
+ exports.syncStatements = syncStatements;
@@ -31,7 +31,9 @@ function zipProject(cwd) {
31
31
  const zip = new adm_zip_1.default();
32
32
  zip.addLocalFolder(cwd, "", (filename) => {
33
33
  const parts = filename.split(path.sep);
34
- if (parts.some((p) => EXCLUDE_DIRS.has(p)))
34
+ // .apso is local state, except the manifest the platform reads.
35
+ const kept = parts.join("/") === ".apso/manifest.json";
36
+ if (!kept && parts.some((p) => EXCLUDE_DIRS.has(p)))
35
37
  return false;
36
38
  const base = parts[parts.length - 1];
37
39
  if (isSecretEnvFile(base))
@@ -1,5 +1,6 @@
1
1
  import { BaseGenerator } from "./base";
2
2
  import { TargetLanguage, GeneratedFile, ValidationResult, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, Entity, AuthConfig } from "../types";
3
+ import { RelationshipMap } from "../types";
3
4
  /**
4
5
  * Go/Gin generator that produces GORM models, DTOs, Gin handlers,
5
6
  * and service layer code.
@@ -9,10 +10,6 @@ export declare class GoGenerator extends BaseGenerator {
9
10
  getLanguage(): TargetLanguage;
10
11
  getFileExtension(): string;
11
12
  validateConfig(config: GeneratorConfig): ValidationResult;
12
- /**
13
- * Maps .apsorc field types to Go types
14
- */
15
- private mapFieldToGoType;
16
13
  /**
17
14
  * Gets the Go type for primary keys
18
15
  */
@@ -21,10 +18,15 @@ export declare class GoGenerator extends BaseGenerator {
21
18
  * Gets the Swagger type for primary keys
22
19
  */
23
20
  private getPrimaryKeySwaggerType;
21
+ private arrayTypes;
24
22
  /**
25
- * Transforms fields for Go templates with additional Go-specific properties
23
+ * Fields for the Go templates. The gorm tag carries the column exactly as
24
+ * the DDL writer creates it (name, type, NOT NULL, default), so the model
25
+ * reads and writes the database `apso migrate` builds.
26
26
  */
27
27
  private getGoFieldsForTemplate;
28
+ /** Relationships with what the Go templates need: field names, columns, join tables. */
29
+ private goAssociations;
28
30
  generateEntity(options: EntityGenerationOptions): Promise<GeneratedFile[]>;
29
31
  generateController(options: ControllerGenerationOptions): Promise<GeneratedFile[]>;
30
32
  generateService(options: ServiceGenerationOptions): Promise<GeneratedFile[]>;
@@ -37,6 +39,11 @@ export declare class GoGenerator extends BaseGenerator {
37
39
  http?: boolean;
38
40
  auth?: AuthConfig;
39
41
  }): Promise<GeneratedFile[]>;
42
+ /**
43
+ * DATABASE_SYNC's statements (the DDL writer's, creating only what is
44
+ * missing) and the join table columns gorm must be told about.
45
+ */
46
+ private schemaData;
40
47
  /**
41
48
  * Emits a schema-derived manifest of the entities that opted in to
42
49
  * domain-event emission (`.apsorc` `emitEvents`), mirroring the TypeScript
@@ -57,10 +64,21 @@ export declare class GoGenerator extends BaseGenerator {
57
64
  }): Promise<GeneratedFile[]>;
58
65
  /**
59
66
  * Scope data for a Go service: each direct scopeBy field's struct field and
60
- * gorm column (snake_case of the Go field). A field declared on the entity is
67
+ * column (the .apsorc name, as the DDL writer names it). A field declared on the entity is
61
68
  * pascalCase; a relation's foreign key (organizationId) is OrganizationID.
62
69
  */
63
70
  private goScope;
64
- generateGuards(entities: Entity[], auth?: AuthConfig): Promise<GeneratedFile[]>;
71
+ /**
72
+ * The foreign keys of an entity that a write must check: those onto
73
+ * tenant-scoped entities, with the Go field and column of each.
74
+ */
75
+ private goReferences;
76
+ /**
77
+ * The MCP tools of every entity that opts in. Gin has no OpenAPI document at
78
+ * run time, so each tool's input schema is written from .apsorc here, from
79
+ * the same columns and foreign keys as the DTOs.
80
+ */
81
+ private goMcpTools;
82
+ generateGuards(entities: Entity[], auth?: AuthConfig, relationshipMap?: RelationshipMap): Promise<GeneratedFile[]>;
65
83
  generateQueryUtils(_entities: Entity[], _apiType: string): Promise<GeneratedFile[]>;
66
84
  }