@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,22 +1,31 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.addMissingPythonDep = exports.PYJWT_DEP = exports.JOSE_DEP = exports.addMissingDeps = exports.ensureCrudDeps = exports.APSO_CRUD_DEPS = void 0;
3
+ exports.addMissingPythonDep = exports.PYJWT_DEP = exports.JOSE_DEP = exports.writeAccessManifest = exports.ACCESS_CONTRACT = exports.ensureLoggingWiring = exports.LOGGING_DEP = exports.ensureAppMcpWiring = exports.removeAppMcpWiring = exports.PYTHON_MCP_DEP = exports.ensureMcpWiring = exports.MCP_DEP = exports.addMissingDeps = exports.ensureCrudDeps = exports.APSO_CRUD_DEPS = void 0;
4
4
  const tslib_1 = require("tslib");
5
+ const child_process_1 = require("child_process");
5
6
  const fs = tslib_1.__importStar(require("fs"));
6
7
  const path = tslib_1.__importStar(require("path"));
7
8
  /**
8
9
  * Runtime packages the generated TypeScript code imports (entities, services,
9
- * controllers, guards). Versions match the pinned service-template-ts tag
10
- * (see TEMPLATE_REFS in ./template.ts); bump both together.
10
+ * controllers, guards). These are the first releases with the `dialects`
11
+ * option, Content-Range counts and PostgREST OpenAPI parameters, which the
12
+ * generated controllers rely on. The service template declares the same
13
+ * ranges (see TEMPLATE_REFS in ./template.ts); bump both together.
14
+ *
15
+ * @apso/postgrest-request is not imported by generated code. It is listed so
16
+ * a project whose lockfile holds an older copy moves to the one @apso/crud
17
+ * needs.
11
18
  */
12
19
  exports.APSO_CRUD_DEPS = {
13
- "@apso/crud": "^1.0.1",
14
- "@apso/crud-core": "^1.0.1",
20
+ "@apso/crud": "^1.1.0",
21
+ "@apso/crud-core": "^1.1.0",
15
22
  "@apso/crud-request": "^1.0.1",
16
- "@apso/crud-typeorm": "^1.0.1",
23
+ "@apso/crud-typeorm": "^1.1.0",
24
+ "@apso/postgrest-request": "^1.1.0",
17
25
  };
18
26
  /**
19
- * Add any missing @apso/crud runtime packages to the project's package.json.
27
+ * Declare the @apso/crud runtime packages in the project's package.json, and
28
+ * raise a range that starts below the version the generated code needs.
20
29
  *
21
30
  * Projects created from the v1 template (@nestjsx/crud) don't declare them, so
22
31
  * freshly generated code fails `nest build` with TS2307 "Cannot find module
@@ -24,38 +33,212 @@ exports.APSO_CRUD_DEPS = {
24
33
  * hand-written code may still import them.
25
34
  *
26
35
  * @param {string} projectDir - Directory holding the project's package.json.
27
- * @returns {string[]} Names added (empty when nothing changed or no package.json).
36
+ * @returns {string[]} Names added or raised (empty when nothing changed or no package.json).
28
37
  */
29
38
  function ensureCrudDeps(projectDir) {
30
- return addMissingDeps(projectDir, exports.APSO_CRUD_DEPS);
39
+ return addMissingDeps(projectDir, exports.APSO_CRUD_DEPS, true);
31
40
  }
32
41
  exports.ensureCrudDeps = ensureCrudDeps;
42
+ /** The first x.y.z in a version range, as numbers; undefined for a range with none (file:, a tag). */
43
+ const firstVersion = (range) => { var _a; return (_a = /^[^\d:]*(\d+)\.(\d+)\.(\d+)/.exec(range)) === null || _a === void 0 ? void 0 : _a.slice(1).map(Number); };
44
+ /** True when `declared` starts at a lower version than `wanted`. */
45
+ function startsBelow(declared, wanted) {
46
+ const [a, b] = [firstVersion(declared), firstVersion(wanted)];
47
+ if (!a || !b)
48
+ return false;
49
+ for (let i = 0; i < 3; i += 1)
50
+ if (a[i] !== b[i])
51
+ return a[i] < b[i];
52
+ return false;
53
+ }
33
54
  /**
34
55
  * Add the given dependencies to package.json where it doesn't declare them.
35
56
  *
36
57
  * @param {string} projectDir - Directory holding the project's package.json.
37
58
  * @param {Record<string, string>} deps - Package names and version ranges.
38
- * @returns {string[]} Names added (empty when nothing changed or no package.json).
59
+ * @param {boolean} [raise] - Also replace a declared range that starts below the given one.
60
+ * @returns {string[]} Names added or raised (empty when nothing changed or no package.json).
39
61
  */
40
- function addMissingDeps(projectDir, deps) {
41
- var _a;
62
+ function addMissingDeps(projectDir, deps, raise = false) {
63
+ var _a, _b;
42
64
  const pkgPath = path.join(projectDir, "package.json");
43
65
  if (!fs.existsSync(pkgPath))
44
66
  return [];
45
67
  const raw = fs.readFileSync(pkgPath, "utf8");
46
68
  const pkg = JSON.parse(raw);
47
69
  const declared = { ...pkg.devDependencies, ...pkg.dependencies };
48
- const missing = Object.keys(deps).filter((name) => !declared[name]);
70
+ const missing = Object.keys(deps).filter((name) => !declared[name] || (raise && startsBelow(declared[name], deps[name])));
49
71
  if (missing.length === 0)
50
72
  return [];
51
73
  pkg.dependencies = (_a = pkg.dependencies) !== null && _a !== void 0 ? _a : {};
52
- for (const name of missing)
74
+ for (const name of missing) {
75
+ // A range raised here replaces the one declared, wherever it was declared.
76
+ if ((_b = pkg.devDependencies) === null || _b === void 0 ? void 0 : _b[name])
77
+ delete pkg.devDependencies[name];
53
78
  pkg.dependencies[name] = deps[name];
79
+ }
54
80
  pkg.dependencies = Object.fromEntries(Object.entries(pkg.dependencies).sort(([a], [b]) => a.localeCompare(b)));
55
81
  fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + (raw.endsWith("\n") ? "\n" : ""));
56
82
  return missing;
57
83
  }
58
84
  exports.addMissingDeps = addMissingDeps;
85
+ /** MCP library the generated controllers import when an entity sets `mcp`. */
86
+ exports.MCP_DEP = { "@apso/mcp": "^0.2.0" };
87
+ const SWAGGER_SETUP = "SwaggerModule.setup('_docs', app, document);";
88
+ /**
89
+ * Wire @apso/mcp into a TypeScript project: declare the package and call
90
+ * mountMcp where the app builds its OpenAPI document. Safe to run again.
91
+ *
92
+ * @param {string} projectDir - Directory holding the project's package.json.
93
+ * @param {string} rootFolder - Source folder from .apsorc (usually "src").
94
+ * @returns {string[]} Files changed (empty when the project was already wired).
95
+ */
96
+ function ensureMcpWiring(projectDir, rootFolder) {
97
+ const changed = addMissingDeps(projectDir, exports.MCP_DEP, true).length > 0 ? ["package.json"] : [];
98
+ const relative = path.join(rootFolder, "config", "nest-app.config.ts");
99
+ const file = path.join(projectDir, relative);
100
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
101
+ if (text.includes("mountMcp"))
102
+ return changed;
103
+ // A bootstrap that no longer looks like the template's is the owner's to edit.
104
+ if (!text.includes(SWAGGER_SETUP))
105
+ throw new Error(`mcp in .apsorc: could not add the MCP endpoint to ${relative}. Where your app is configured, import { mountMcp } from '@apso/mcp' and call mountMcp(app, document) after SwaggerModule.createDocument. Without it no tools are served.`);
106
+ fs.writeFileSync(file, "import { mountMcp } from '@apso/mcp';\n" +
107
+ text.replace(SWAGGER_SETUP, `${SWAGGER_SETUP}\n\n // Serve the routes marked with @McpTool as MCP tools at /mcp.\n mountMcp(app, document);`));
108
+ return [...changed, relative];
109
+ }
110
+ exports.ensureMcpWiring = ensureMcpWiring;
111
+ /** The official MCP SDK for Python; 2.x has the constructor-handler server the generated mcp.py uses. */
112
+ exports.PYTHON_MCP_DEP = "mcp>=2.3,<3";
113
+ /** The entry point of a Python or Go project and the MCP call the CLI adds to it. */
114
+ function appMcpWiring(language) {
115
+ const python = language === "python";
116
+ const relative = python ? path.join("app", "main.py") : path.join("cmd", "main.go");
117
+ const anchor = python
118
+ ? "app.include_router(autogen_router)"
119
+ : "routes.RegisterAllRoutes(api, db)";
120
+ const call = python
121
+ ? "\n\n# Serve the routes marked with mcp_tool as MCP tools at /mcp.\nfrom app.autogen.mcp import mount_mcp # noqa: E402\n\nmount_mcp(app)"
122
+ : "\n\n\t// Serve the routes .apsorc marks with mcp as MCP tools at /mcp.\n\troutes.MountMCP(r, api)";
123
+ return { relative, anchor, call };
124
+ }
125
+ /**
126
+ * Take the MCP call back out of a Python or Go entry point when no entity has
127
+ * `mcp` any more: the generated file it calls is no longer written, so the
128
+ * service would not build or start. Only the exact lines the CLI added are
129
+ * removed.
130
+ *
131
+ * @param {string} projectDir - The project root.
132
+ * @param {"python" | "go"} language - The project's language.
133
+ * @returns {string[]} Files changed.
134
+ */
135
+ function removeAppMcpWiring(projectDir, language) {
136
+ const { relative, call } = appMcpWiring(language);
137
+ const file = path.join(projectDir, relative);
138
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
139
+ if (!text.includes(call))
140
+ return [];
141
+ fs.writeFileSync(file, text.replace(call, ""));
142
+ return [relative];
143
+ }
144
+ exports.removeAppMcpWiring = removeAppMcpWiring;
145
+ /**
146
+ * Wire the generated MCP endpoint into a Python or Go project: one call in the
147
+ * app's entry point, after the generated routes are registered (and the SDK in
148
+ * pyproject.toml for Python; go mod tidy adds it for Go). Safe to run again.
149
+ *
150
+ * @param {string} projectDir - The project root.
151
+ * @param {"python" | "go"} language - The project's language.
152
+ * @returns {string[]} Files changed (empty when the project was already wired).
153
+ */
154
+ function ensureAppMcpWiring(projectDir, language) {
155
+ const python = language === "python";
156
+ const changed = python && addMissingPythonDep(projectDir, exports.PYTHON_MCP_DEP)
157
+ ? ["pyproject.toml"]
158
+ : [];
159
+ const { relative, anchor, call } = appMcpWiring(language);
160
+ const file = path.join(projectDir, relative);
161
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
162
+ if (text.includes(python ? "mount_mcp" : "MountMCP"))
163
+ return changed;
164
+ // An entry point that no longer looks like the template's is the owner's to edit.
165
+ if (!text.includes(anchor))
166
+ throw new Error(python
167
+ ? `mcp in .apsorc: could not add the MCP endpoint to ${relative}. After your routers are included, add: from app.autogen.mcp import mount_mcp, then mount_mcp(app). Without it no tools are served.`
168
+ : `mcp in .apsorc: could not add the MCP endpoint to ${relative}. After routes.RegisterAllRoutes, call routes.MountMCP(engine, group) with the Gin engine and the group the routes are registered on. Without it no tools are served.`);
169
+ fs.writeFileSync(file, text.replace(anchor, anchor + call));
170
+ return [...changed, relative];
171
+ }
172
+ exports.ensureAppMcpWiring = ensureAppMcpWiring;
173
+ /** Request logging library every generated TypeScript service uses. */
174
+ exports.LOGGING_DEP = { "@apso/logging": "^0.1.0" };
175
+ const NEST_IMPORT = /^import {[^}]*\bNestFactory\b[^}]*} from ["']@nestjs\/core["'];?$/m;
176
+ const NEST_CREATE = /^([\t ]*)(?:const|let) (\w+) = await NestFactory\.create\(AppModule\);?$/m;
177
+ /**
178
+ * Wire @apso/logging into a TypeScript project: declare the package and call
179
+ * useApsoLogging straight after NestFactory.create in the server entry point
180
+ * (main.ts) and the Lambda handler (lambda.ts). Safe to run again.
181
+ *
182
+ * @param {string} projectDir - Directory holding the project's package.json.
183
+ * @param {string} rootFolder - Source folder from .apsorc (usually "src").
184
+ * @returns {{ changed: string[], manual: string[] }} Files changed, and entry
185
+ * points that no longer look like the template's and were left alone.
186
+ */
187
+ function ensureLoggingWiring(projectDir, rootFolder) {
188
+ const changed = addMissingDeps(projectDir, exports.LOGGING_DEP).length > 0 ? ["package.json"] : [];
189
+ const manual = [];
190
+ for (const name of ["main.ts", "lambda.ts"]) {
191
+ const relative = path.join(rootFolder, name);
192
+ const file = path.join(projectDir, relative);
193
+ if (!fs.existsSync(file))
194
+ continue;
195
+ const text = fs.readFileSync(file, "utf8");
196
+ if (text.includes("useApsoLogging"))
197
+ continue;
198
+ // A bootstrap that no longer looks like the template's is the owner's to edit.
199
+ if (!NEST_IMPORT.test(text) || !NEST_CREATE.test(text)) {
200
+ manual.push(relative);
201
+ continue;
202
+ }
203
+ fs.writeFileSync(file, text
204
+ // After the NestFactory import: main.ts must import ./tracing first.
205
+ .replace(NEST_IMPORT, "$&\nimport { useApsoLogging } from '@apso/logging';")
206
+ .replace(NEST_CREATE, "$1const $2 = await NestFactory.create(AppModule, { bufferLogs: true });\n$1// One JSON line per request with who called, and a request id on every line.\n$1useApsoLogging($2);"));
207
+ changed.push(relative);
208
+ }
209
+ return { changed, manual };
210
+ }
211
+ exports.ensureLoggingWiring = ensureLoggingWiring;
212
+ /** Version of the access rules the generated code enforces. */
213
+ exports.ACCESS_CONTRACT = 1;
214
+ /**
215
+ * Record in .apso/manifest.json that the generated code has the built-in
216
+ * access check (no valid API key or signed-in user, no access). The hosted
217
+ * platform reads this from the pushed source before it opens a service to
218
+ * requests it has not checked a key for. Other fields in the file are kept.
219
+ *
220
+ * @param {string} projectDir - The project root.
221
+ * @param {string} cliVersion - Version of the CLI that generated the code.
222
+ * @returns {boolean} True when git ignores the file, so it would not be pushed.
223
+ */
224
+ function writeAccessManifest(projectDir, cliVersion) {
225
+ const file = path.join(projectDir, ".apso", "manifest.json");
226
+ let current = {};
227
+ try {
228
+ // eslint-disable-next-line unicorn/prefer-json-parse-buffer -- JSON.parse's TS type requires a string
229
+ current = JSON.parse(fs.readFileSync(file, "utf8"));
230
+ }
231
+ catch {
232
+ // no manifest yet
233
+ }
234
+ fs.mkdirSync(path.dirname(file), { recursive: true });
235
+ fs.writeFileSync(file, JSON.stringify({ ...current, accessContract: exports.ACCESS_CONTRACT, cliVersion }, null, 2) + "\n");
236
+ const ignored = (0, child_process_1.spawnSync)("git", ["check-ignore", "-q", ".apso/manifest.json"], {
237
+ cwd: projectDir,
238
+ });
239
+ return ignored.status === 0;
240
+ }
241
+ exports.writeAccessManifest = writeAccessManifest;
59
242
  /** JWT verification library the generated TypeScript JWT guard imports. */
60
243
  exports.JOSE_DEP = { jose: "^5.10.0" };
61
244
  /** JWT verification library the generated Python auth module imports. */
@@ -12,6 +12,18 @@ export declare const fieldTypeToColumnType: Record<string, string>;
12
12
  */
13
13
  export declare const normalizeFieldType: (type: string) => string;
14
14
  export declare const getJsTypeFromFieldType: (type: FieldType | string) => string;
15
+ /**
16
+ * Postgres element type of an "array" field, as the DDL writer reads it.
17
+ * Python read `arrayType` and Go `arrayItemType` before `elementType`; both
18
+ * still work so older schemas generate the same code.
19
+ *
20
+ * @param {Field} field - An "array" field from .apsorc.
21
+ * @returns {string} The element type, "text" when none is set.
22
+ */
23
+ export declare const arrayElementType: (field: Field & {
24
+ arrayType?: string;
25
+ arrayItemType?: string;
26
+ }) => string;
15
27
  export declare const getDefaultValueForField: (field: Field) => string | null;
16
28
  export declare const getFieldForTemplate: (fields: Field[], entityName: string) => ComputedField[];
17
29
  export declare const fieldToEnumType: (fieldName: string, entityName: string) => string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateDecimalField = exports.typeExistsInEntity = exports.fieldToEnumType = exports.getFieldForTemplate = exports.getDefaultValueForField = exports.getJsTypeFromFieldType = exports.normalizeFieldType = exports.fieldTypeToColumnType = void 0;
3
+ exports.validateDecimalField = exports.typeExistsInEntity = exports.fieldToEnumType = exports.getFieldForTemplate = exports.getDefaultValueForField = exports.arrayElementType = exports.getJsTypeFromFieldType = exports.normalizeFieldType = exports.fieldTypeToColumnType = void 0;
4
4
  const casing_1 = require("./casing");
5
5
  /**
6
6
  * Canonical mapping from .apsorc field types to Postgres column types.
@@ -83,6 +83,8 @@ const typeToJsType = {
83
83
  array: "string[]",
84
84
  boolean: "boolean",
85
85
  integer: "number",
86
+ int: "number",
87
+ float8: "number",
86
88
  float: "number",
87
89
  real: "number",
88
90
  double: "number",
@@ -128,6 +130,16 @@ const typeToJsType = {
128
130
  };
129
131
  const getJsTypeFromFieldType = (type) => { var _a; return (_a = typeToJsType[type]) !== null && _a !== void 0 ? _a : "string"; };
130
132
  exports.getJsTypeFromFieldType = getJsTypeFromFieldType;
133
+ /**
134
+ * Postgres element type of an "array" field, as the DDL writer reads it.
135
+ * Python read `arrayType` and Go `arrayItemType` before `elementType`; both
136
+ * still work so older schemas generate the same code.
137
+ *
138
+ * @param {Field} field - An "array" field from .apsorc.
139
+ * @returns {string} The element type, "text" when none is set.
140
+ */
141
+ const arrayElementType = (field) => field.elementType || field.arrayType || field.arrayItemType || "text";
142
+ exports.arrayElementType = arrayElementType;
131
143
  const getDefaultValueForField = (field) => {
132
144
  var _a, _b;
133
145
  switch (field.type) {
@@ -167,10 +179,14 @@ const getFieldForTemplate = (fields, entityName) => fields.map((field) => {
167
179
  ...field,
168
180
  // Use normalized type for template lookup
169
181
  type: normalizedType,
182
+ // Resolved here so every template and the DDL writer read one key.
183
+ ...(field.type === "array" && { elementType: (0, exports.arrayElementType)(field) }),
170
184
  default: (0, exports.getDefaultValueForField)(field),
171
185
  dataType: field.type === "enum"
172
186
  ? (0, exports.fieldToEnumType)(field.name, entityName)
173
- : (0, exports.getJsTypeFromFieldType)(field.type),
187
+ : field.type === "array"
188
+ ? `${(0, exports.getJsTypeFromFieldType)((0, exports.arrayElementType)(field))}[]`
189
+ : (0, exports.getJsTypeFromFieldType)(field.type),
174
190
  };
175
191
  });
176
192
  exports.getFieldForTemplate = getFieldForTemplate;
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Schema Conversion Utilities
3
3
  *
4
- * Converts between local .apsorc format and platform ServiceSchema format.
4
+ * The platform stores a service's .apsorc as it is, so push and pull send the
5
+ * file whole. apsorcToServiceSchema only feeds the entity, field and
6
+ * relationship counts that validate, deploy and the MCP server print.
5
7
  */
6
8
  import { Entity } from "../types/entity";
7
9
  import { RelationshipMap } from "../types/relationship";
@@ -15,41 +17,6 @@ export interface ParsedApsorcInput {
15
17
  entities: Entity[];
16
18
  relationshipMap: RelationshipMap;
17
19
  }
18
- /**
19
- * Shape returned by serviceSchemaToApsorc for writing back to .apsorc
20
- */
21
- export interface ApsorcOutput {
22
- version: number;
23
- rootFolder: string;
24
- apiType: string;
25
- entities: ApsorcEntityOutput[];
26
- relationships: ApsorcRelationshipOutput[];
27
- }
28
- export interface ApsorcEntityOutput {
29
- name: string;
30
- primaryKeyType?: "serial" | "uuid";
31
- created_at?: boolean;
32
- updated_at?: boolean;
33
- fields?: ApsorcFieldOutput[];
34
- scopeBy?: string | string[];
35
- }
36
- export interface ApsorcFieldOutput {
37
- name: string;
38
- type: string;
39
- nullable?: boolean;
40
- unique?: boolean;
41
- default?: unknown;
42
- index?: boolean;
43
- }
44
- export interface ApsorcRelationshipOutput {
45
- from: string;
46
- to: string;
47
- type: "OneToMany" | "ManyToOne" | "ManyToMany" | "OneToOne";
48
- to_name?: string;
49
- nullable?: boolean;
50
- bi_directional?: boolean;
51
- cascadeDelete?: boolean;
52
- }
53
20
  /**
54
21
  * Convert parsed .apsorc data to platform ServiceSchema format.
55
22
  *
@@ -57,15 +24,25 @@ export interface ApsorcRelationshipOutput {
57
24
  * The platform ServiceSchema stores relationships embedded per-entity.
58
25
  */
59
26
  export declare function apsorcToServiceSchema(parsed: ParsedApsorcInput): Omit<ServiceSchema, "id" | "serviceId" | "version" | "createdAt" | "updatedAt">;
60
- /**
61
- * Convert platform ServiceSchema to .apsorc format for writing to disk.
62
- *
63
- * Reverses the conversion: flattens per-entity relationships back into a
64
- * top-level relationships array in v2 format.
65
- */
66
- export declare function serviceSchemaToApsorc(schema: ServiceSchema): ApsorcOutput;
67
27
  /**
68
28
  * Compute a SHA-256 hash of a schema for sync tracking.
69
29
  * Uses deterministic JSON serialization (recursively sorted keys).
70
30
  */
71
31
  export declare function computeSchemaHash(schema: unknown): string;
32
+ type Apsorc = {
33
+ entities?: {
34
+ name: string;
35
+ }[];
36
+ } & Record<string, unknown>;
37
+ /**
38
+ * What pushing `local` would change on the platform's `remote` .apsorc:
39
+ * entities by name, plus one line when anything outside `entities`
40
+ * (relationships, auth, language and so on) differs.
41
+ */
42
+ export declare function diffApsorc(remote: Apsorc | null, local: Apsorc): {
43
+ hasChanges: boolean;
44
+ added: string[];
45
+ removed: string[];
46
+ modified: string[];
47
+ };
48
+ export {};
@@ -2,24 +2,14 @@
2
2
  /**
3
3
  * Schema Conversion Utilities
4
4
  *
5
- * Converts between local .apsorc format and platform ServiceSchema format.
5
+ * The platform stores a service's .apsorc as it is, so push and pull send the
6
+ * file whole. apsorcToServiceSchema only feeds the entity, field and
7
+ * relationship counts that validate, deploy and the MCP server print.
6
8
  */
7
9
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.computeSchemaHash = exports.serviceSchemaToApsorc = exports.apsorcToServiceSchema = void 0;
10
+ exports.diffApsorc = exports.computeSchemaHash = exports.apsorcToServiceSchema = void 0;
9
11
  const tslib_1 = require("tslib");
10
12
  const crypto = tslib_1.__importStar(require("crypto"));
11
- /**
12
- * Map from SchemaRelationship type format to ApsorcRelationship type format
13
- */
14
- function platformTypeToApsorcType(type) {
15
- const map = {
16
- "one-to-one": "OneToOne",
17
- "one-to-many": "OneToMany",
18
- "many-to-one": "ManyToOne",
19
- "many-to-many": "ManyToMany",
20
- };
21
- return map[type];
22
- }
23
13
  /**
24
14
  * Map from ApsorcRelationship type format to SchemaRelationship type format
25
15
  */
@@ -78,70 +68,6 @@ function apsorcToServiceSchema(parsed) {
78
68
  return { entities };
79
69
  }
80
70
  exports.apsorcToServiceSchema = apsorcToServiceSchema;
81
- /**
82
- * Convert platform ServiceSchema to .apsorc format for writing to disk.
83
- *
84
- * Reverses the conversion: flattens per-entity relationships back into a
85
- * top-level relationships array in v2 format.
86
- */
87
- function serviceSchemaToApsorc(schema) {
88
- const entities = [];
89
- const relationships = [];
90
- for (const schemaEntity of schema.entities) {
91
- // Convert fields back to .apsorc format
92
- const fields = (schemaEntity.fields || [])
93
- .filter((f) => !f.primaryKey) // Primary keys are implicit in .apsorc
94
- .map((field) => {
95
- const out = {
96
- name: field.name,
97
- type: field.type,
98
- };
99
- if (field.nullable)
100
- out.nullable = true;
101
- if (field.unique)
102
- out.unique = true;
103
- if (field.default !== undefined)
104
- out.default = field.default;
105
- if (field.index)
106
- out.index = true;
107
- return out;
108
- });
109
- const entityOut = {
110
- name: schemaEntity.name,
111
- };
112
- if (fields.length > 0) {
113
- entityOut.fields = fields;
114
- }
115
- if (schemaEntity.scopeBy && schemaEntity.scopeBy.length > 0) {
116
- entityOut.scopeBy =
117
- schemaEntity.scopeBy.length === 1
118
- ? schemaEntity.scopeBy[0]
119
- : schemaEntity.scopeBy;
120
- }
121
- entities.push(entityOut);
122
- // Convert per-entity relationships to flat array
123
- if (schemaEntity.relationships) {
124
- for (const rel of schemaEntity.relationships) {
125
- relationships.push({
126
- from: schemaEntity.name,
127
- to: rel.target,
128
- type: platformTypeToApsorcType(rel.type),
129
- to_name: rel.inverseSide || undefined,
130
- nullable: rel.nullable,
131
- cascadeDelete: rel.cascade,
132
- });
133
- }
134
- }
135
- }
136
- return {
137
- version: 2,
138
- rootFolder: "src",
139
- apiType: "rest",
140
- entities,
141
- relationships,
142
- };
143
- }
144
- exports.serviceSchemaToApsorc = serviceSchemaToApsorc;
145
71
  /**
146
72
  * Recursively sort all object keys for deterministic serialization.
147
73
  */
@@ -167,3 +93,27 @@ function computeSchemaHash(schema) {
167
93
  return crypto.createHash("sha256").update(serialized).digest("hex");
168
94
  }
169
95
  exports.computeSchemaHash = computeSchemaHash;
96
+ /**
97
+ * What pushing `local` would change on the platform's `remote` .apsorc:
98
+ * entities by name, plus one line when anything outside `entities`
99
+ * (relationships, auth, language and so on) differs.
100
+ */
101
+ function diffApsorc(remote, local) {
102
+ const hashes = (rc) => { var _a; return new Map(((_a = rc === null || rc === void 0 ? void 0 : rc.entities) !== null && _a !== void 0 ? _a : []).map((e) => [e.name, computeSchemaHash(e)])); };
103
+ const settings = (rc) => computeSchemaHash({ ...rc, entities: undefined });
104
+ const before = hashes(remote);
105
+ const after = hashes(local);
106
+ const added = [...after.keys()].filter((name) => !before.has(name));
107
+ const removed = [...before.keys()].filter((name) => !after.has(name));
108
+ const modified = [...after.keys()].filter((name) => before.has(name) && before.get(name) !== after.get(name));
109
+ if (settings(remote) !== settings(local)) {
110
+ modified.push("relationships and settings");
111
+ }
112
+ return {
113
+ hasChanges: added.length + removed.length + modified.length > 0,
114
+ added,
115
+ removed,
116
+ modified,
117
+ };
118
+ }
119
+ exports.diffApsorc = diffApsorc;
@@ -14,6 +14,17 @@ export declare const PROJECT_NAME_PATTERN: RegExp;
14
14
  * Removes the .git directory after cloning.
15
15
  */
16
16
  export declare function cloneTemplate(projectPath: string, language: TargetLanguage, log: (msg: string) => void): void;
17
+ /**
18
+ * Give a project a development API key in its .env, which the templates keep
19
+ * out of git. Every generated service refuses requests without a key or a
20
+ * signed-in user, so a new or freshly cloned project needs one to run.
21
+ * APSO_LOCAL=1 turns on the detailed 401 messages.
22
+ *
23
+ * @param {string} projectPath - The project root.
24
+ * @returns {string | undefined} The key when one was created; undefined when
25
+ * .env already sets APSO_API_KEY.
26
+ */
27
+ export declare function ensureDevKey(projectPath: string): string | undefined;
17
28
  /**
18
29
  * Stamp the chosen language into the scaffolded `.apsorc`.
19
30
  *
@@ -1,10 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.initGitRepo = exports.ensureEnvFile = exports.stampApsorcLanguage = exports.cloneTemplate = exports.PROJECT_NAME_PATTERN = exports.TEMPLATE_REFS = exports.TEMPLATE_REPOS = void 0;
3
+ exports.initGitRepo = exports.ensureEnvFile = exports.stampApsorcLanguage = exports.ensureDevKey = exports.cloneTemplate = exports.PROJECT_NAME_PATTERN = exports.TEMPLATE_REFS = exports.TEMPLATE_REPOS = void 0;
4
4
  const tslib_1 = require("tslib");
5
+ const crypto_1 = require("crypto");
5
6
  const fs = tslib_1.__importStar(require("fs"));
6
7
  const path = tslib_1.__importStar(require("path"));
7
8
  const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
9
+ const crud_deps_1 = require("./crud-deps");
8
10
  exports.TEMPLATE_REPOS = {
9
11
  typescript: "https://github.com/apsoai/service-template-ts.git",
10
12
  python: "https://github.com/apsoai/service-template-python.git",
@@ -49,9 +51,42 @@ function cloneTemplate(projectPath, language, log) {
49
51
  }
50
52
  shelljs_1.default.rm("-rf", path.join(projectPath, ".git"));
51
53
  ensureEnvFile(projectPath, log);
54
+ ensureDevKey(projectPath);
55
+ // The generated API key check imports a JWT library; declare it now so the
56
+ // first install covers it.
57
+ if (language === "typescript")
58
+ (0, crud_deps_1.addMissingDeps)(projectPath, crud_deps_1.JOSE_DEP);
59
+ if (language === "python")
60
+ (0, crud_deps_1.addMissingPythonDep)(projectPath, crud_deps_1.PYJWT_DEP);
52
61
  stampApsorcLanguage(projectPath, language, log);
53
62
  }
54
63
  exports.cloneTemplate = cloneTemplate;
64
+ /**
65
+ * Give a project a development API key in its .env, which the templates keep
66
+ * out of git. Every generated service refuses requests without a key or a
67
+ * signed-in user, so a new or freshly cloned project needs one to run.
68
+ * APSO_LOCAL=1 turns on the detailed 401 messages.
69
+ *
70
+ * @param {string} projectPath - The project root.
71
+ * @returns {string | undefined} The key when one was created; undefined when
72
+ * .env already sets APSO_API_KEY.
73
+ */
74
+ function ensureDevKey(projectPath) {
75
+ const envPath = path.join(projectPath, ".env");
76
+ const text = fs.existsSync(envPath) ? fs.readFileSync(envPath, "utf8") : "";
77
+ if (/^\s*APSO_API_KEY\s*=/m.test(text))
78
+ return undefined;
79
+ const key = `apso_dev_${(0, crypto_1.randomBytes)(24).toString("hex")}`;
80
+ fs.writeFileSync(envPath, `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}
81
+ # Development API key for this machine, created by the Apso CLI. Send it in the
82
+ # x-api-key header. This is the key itself, not a hash; do not commit it.
83
+ APSO_API_KEY=${key}
84
+ # Local development: 401 responses say what is missing.
85
+ APSO_LOCAL=1
86
+ `);
87
+ return key;
88
+ }
89
+ exports.ensureDevKey = ensureDevKey;
55
90
  /**
56
91
  * Stamp the chosen language into the scaffolded `.apsorc`.
57
92
  *
@@ -74,12 +74,17 @@ export declare function verifyMigration(projectDir: string, baselineApsorc: stri
74
74
  checkFile?: string;
75
75
  acceptLoss?: string[];
76
76
  }): Promise<CheckResult>;
77
+ export declare const SMOKE_KEY: string;
77
78
  /** The route each language's generated controller serves an entity on. */
78
79
  export declare const entityRoute: (language: TargetLanguage, name: string) => string;
79
80
  export interface SmokeOptions {
80
81
  skipBuild?: boolean;
81
82
  timeoutMs?: number;
82
83
  language?: TargetLanguage;
84
+ /** Added to the service's environment. */
85
+ env?: NodeJS.ProcessEnv;
86
+ /** Runs against the started service in place of the endpoint checks. */
87
+ check?: (base: string, done: (s: Step) => boolean) => Promise<void>;
83
88
  }
84
89
  /**
85
90
  * Start the service and call GET /health, every entity's list endpoint, and a
@@ -87,7 +92,7 @@ export interface SmokeOptions {
87
92
  * PGlite database synced to their entities; Python and Go services run on the
88
93
  * database in DATABASE_URL.
89
94
  */
90
- export declare function smokeTest(projectDir: string, entities: Entity[], relationships?: RelationshipMap, { skipBuild, timeoutMs, language, }?: SmokeOptions): Promise<CheckResult>;
95
+ export declare function smokeTest(projectDir: string, entities: Entity[], relationships?: RelationshipMap, { skipBuild, timeoutMs, language, env: extraEnv, check, }?: SmokeOptions): Promise<CheckResult>;
91
96
  /** KEY=value lines of the project's .env; no interpolation. */
92
97
  export declare function readDotEnv(projectDir: string): Record<string, string>;
93
98
  /** The CLI's own entry point, for running `generate` in the baseline copy. */