@hulla/db-cli 0.0.0-stage → 0.4.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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/dist/build.d.ts +45 -0
  4. package/dist/build.js +141 -0
  5. package/dist/cli-address.d.ts +35 -0
  6. package/dist/cli-address.js +135 -0
  7. package/dist/cli-options.d.ts +13 -0
  8. package/dist/cli-options.js +43 -0
  9. package/dist/cli-output.d.ts +36 -0
  10. package/dist/cli-output.js +69 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +101 -0
  13. package/dist/codegen.d.ts +39 -0
  14. package/dist/codegen.js +358 -0
  15. package/dist/database-capture.d.ts +3 -0
  16. package/dist/database-capture.js +32 -0
  17. package/dist/database-codegen.d.ts +4 -0
  18. package/dist/database-codegen.js +46 -0
  19. package/dist/database-function-discovery.d.ts +10 -0
  20. package/dist/database-function-discovery.js +87 -0
  21. package/dist/dev-worker.d.ts +1 -0
  22. package/dist/dev-worker.js +138 -0
  23. package/dist/dev.d.ts +6 -0
  24. package/dist/dev.js +209 -0
  25. package/dist/development-compiler.d.ts +3 -0
  26. package/dist/development-compiler.js +5 -0
  27. package/dist/development-runtime.d.ts +2 -0
  28. package/dist/development-runtime.js +25 -0
  29. package/dist/function-analysis.d.ts +62 -0
  30. package/dist/function-analysis.js +425 -0
  31. package/dist/function-shapes.d.ts +8 -0
  32. package/dist/function-shapes.js +142 -0
  33. package/dist/host-codegen.d.ts +3 -0
  34. package/dist/host-codegen.js +45 -0
  35. package/dist/local-postgres-assets.d.ts +5 -0
  36. package/dist/local-postgres-assets.js +107 -0
  37. package/dist/local-postgres-assets.json +1 -0
  38. package/dist/local-postgres.d.ts +7 -0
  39. package/dist/local-postgres.js +180 -0
  40. package/dist/names.d.ts +2 -0
  41. package/dist/names.js +10 -0
  42. package/dist/project-codegen.d.ts +3 -0
  43. package/dist/project-codegen.js +107 -0
  44. package/dist/runtime-conditions.d.ts +2 -0
  45. package/dist/runtime-conditions.js +10 -0
  46. package/dist/schema-codegen.d.ts +16 -0
  47. package/dist/schema-codegen.js +212 -0
  48. package/dist/sdk-declarations.d.ts +1 -0
  49. package/dist/sdk-declarations.js +4 -0
  50. package/dist/setup-ignore.d.ts +6 -0
  51. package/dist/setup-ignore.js +35 -0
  52. package/dist/source-codegen.d.ts +7 -0
  53. package/dist/source-codegen.js +46 -0
  54. package/dist/studio.d.ts +8 -0
  55. package/dist/studio.js +28 -0
  56. package/dist/worker-codegen.d.ts +4 -0
  57. package/dist/worker-codegen.js +51 -0
  58. package/package.json +59 -4
@@ -0,0 +1,425 @@
1
+ import { API, SymbolFlags, SyntaxKind, isExportSpecifier, isImportSpecifier, isExportDeclaration, isImportDeclaration, isImportClause } from "./development-compiler.js";
2
+ import { dirname } from 'node:path';
3
+ import { sdkDeclarations } from "./sdk-declarations.js";
4
+ import { isVariableDeclaration, isExportAssignment, isCallExpression, isIdentifier, isObjectLiteralExpression, isPropertyAssignment, isShorthandPropertyAssignment, isArrowFunction, isFunctionExpression, isStringLiteral, isParenthesizedExpression, isAsExpression, isSatisfiesExpression, isNonNullExpression, isBlock, isReturnStatement } from "./development-compiler.js";
5
+ /** One compiler session shared by discovery, selection and contract inference. */
6
+ export class FunctionAnalysis {
7
+ api = new API();
8
+ snapshot;
9
+ projects = new Map();
10
+ exports = new Map();
11
+ symbols = new Map();
12
+ runtime = new Map();
13
+ declarationFiles = new Map();
14
+ brands = new Map();
15
+ opened = new Set();
16
+ databases = new Map();
17
+ async open(files) {
18
+ if (this.snapshot && files.every(file => this.opened.has(file)))
19
+ return;
20
+ for (const file of files)
21
+ this.opened.add(file);
22
+ const previous = this.snapshot;
23
+ this.snapshot = await this.api.updateSnapshot({ openFiles: [...this.opened] });
24
+ this.projects.clear();
25
+ this.exports.clear();
26
+ this.symbols.clear();
27
+ this.runtime.clear();
28
+ this.declarationFiles.clear();
29
+ this.brands.clear();
30
+ this.databases.clear();
31
+ await previous?.dispose();
32
+ }
33
+ async project(source) {
34
+ let project = this.projects.get(source);
35
+ if (!project) {
36
+ project = await this.snapshot?.getDefaultProjectForFile(source);
37
+ if (!project)
38
+ throw new TypeError(`No TypeScript project for ${source}`);
39
+ this.projects.set(source, project);
40
+ }
41
+ return project;
42
+ }
43
+ async moduleExports(project, file) {
44
+ let symbols = this.symbols.get(file);
45
+ if (!symbols) {
46
+ const module = await project.checker.getSymbolAtLocation(file);
47
+ symbols = module ? await project.checker.getExportsOfModule(module) : [];
48
+ // Native TS can expose no SourceFile module symbol for an object assigned
49
+ // to module.exports. Its checked RHS still provides the named exports.
50
+ for (const statement of file.statements) {
51
+ if (statement.kind !== SyntaxKind.ExpressionStatement || !('expression' in statement))
52
+ continue;
53
+ const expression = statement.expression;
54
+ if (expression.kind !== SyntaxKind.BinaryExpression || !('left' in expression) || !('right' in expression))
55
+ continue;
56
+ const left = expression.left;
57
+ if (left.kind !== SyntaxKind.PropertyAccessExpression || !('expression' in left) || !('name' in left))
58
+ continue;
59
+ const target = left.expression;
60
+ const name = left.name;
61
+ if (!isIdentifier(target) || target.text !== 'module' || !name || typeof name !== 'object' || !('text' in name) || name.text !== 'exports')
62
+ continue;
63
+ const type = await project.checker.getTypeAtLocation(expression.right);
64
+ if (type) {
65
+ symbols = await project.checker.getPropertiesOfType(type);
66
+ this.runtime.set(file, new Set(symbols.map(value => value.name)));
67
+ }
68
+ }
69
+ const common = symbols.find(symbol => symbol.name === 'export=');
70
+ if (common) {
71
+ const type = await project.checker.getTypeOfSymbol(common);
72
+ if (type)
73
+ symbols = [...symbols, ...await project.checker.getPropertiesOfType(type)];
74
+ }
75
+ this.symbols.set(file, symbols);
76
+ }
77
+ return symbols;
78
+ }
79
+ async moduleFile(project, specifier) {
80
+ const symbol = await project.checker.getSymbolAtLocation(specifier);
81
+ const declaration = symbol?.declarations[0];
82
+ return declaration ? project.program.getSourceFile(declaration.path) : undefined;
83
+ }
84
+ requiredBinding(node) {
85
+ let initializer, name;
86
+ if (node.kind === SyntaxKind.BindingElement && node.parent?.parent && isVariableDeclaration(node.parent.parent)) {
87
+ initializer = node.parent.parent.initializer;
88
+ const binding = 'propertyName' in node && node.propertyName ? node.propertyName : 'name' in node ? node.name : undefined;
89
+ if (binding && typeof binding === 'object' && 'text' in binding && typeof binding.text === 'string')
90
+ name = binding.text;
91
+ }
92
+ else if (isVariableDeclaration(node) && node.initializer?.kind === SyntaxKind.PropertyAccessExpression && 'expression' in node.initializer && 'name' in node.initializer) {
93
+ initializer = node.initializer.expression;
94
+ const binding = node.initializer.name;
95
+ if (binding && typeof binding === 'object' && 'text' in binding && typeof binding.text === 'string')
96
+ name = binding.text;
97
+ }
98
+ if (!initializer || !name || !isCallExpression(initializer) || !isIdentifier(initializer.expression) || initializer.expression.text !== 'require' || !initializer.arguments[0] || !isStringLiteral(initializer.arguments[0]))
99
+ return undefined;
100
+ let root = node;
101
+ while (root.parent)
102
+ root = root.parent;
103
+ return { specifier: initializer.arguments[0], importer: root.fileName, name };
104
+ }
105
+ async valueBinding(project, node, seen) {
106
+ let originalName;
107
+ for (let parent = node; parent; parent = parent.parent) {
108
+ if ("isTypeOnly" in parent && parent.isTypeOnly)
109
+ return false;
110
+ if (isImportClause(parent) && parent.phaseModifier === SyntaxKind.TypeKeyword)
111
+ return false;
112
+ if (isExportSpecifier(parent) || isImportSpecifier(parent)) {
113
+ originalName = (parent.propertyName ?? parent.name).text;
114
+ }
115
+ if ((isExportDeclaration(parent) || isImportDeclaration(parent)) && parent.moduleSpecifier && originalName) {
116
+ const file = await this.moduleFile(project, parent.moduleSpecifier);
117
+ return !!file && this.runtimeExport(project, file, originalName, seen);
118
+ }
119
+ }
120
+ // `import type { value }; export { value }` must not become an endpoint.
121
+ if (isExportSpecifier(node)) {
122
+ const local = await project.checker.getExportSpecifierLocalTargetSymbol(node);
123
+ if (local && local.flags & SymbolFlags.Alias) {
124
+ for (const declaration of local.declarations) {
125
+ const binding = await declaration.resolve(project);
126
+ if (binding && await this.valueBinding(project, binding, seen))
127
+ return true;
128
+ }
129
+ return false;
130
+ }
131
+ }
132
+ return true;
133
+ }
134
+ async runtimeExport(project, file, name, seen = new Set()) {
135
+ if (this.runtime.get(file)?.has(name))
136
+ return true;
137
+ const key = `${file.path}\0${name}`;
138
+ if (seen.has(key))
139
+ return false;
140
+ const nested = new Set(seen).add(key);
141
+ const exported = (await this.moduleExports(project, file)).find(symbol => symbol.name === name);
142
+ if (!exported)
143
+ return false;
144
+ let found = false;
145
+ for (const declaration of exported.declarations) {
146
+ if (declaration.path !== file.path)
147
+ continue;
148
+ const node = await declaration.resolve(project);
149
+ if (node && await this.valueBinding(project, node, nested)) {
150
+ found = true;
151
+ break;
152
+ }
153
+ }
154
+ // The checker returns the original symbols for star exports, including
155
+ // `export type *`. Follow only runtime star edges, including through barrels.
156
+ if (!found)
157
+ for (const statement of file.statements) {
158
+ if (!isExportDeclaration(statement) || statement.isTypeOnly || statement.exportClause || !statement.moduleSpecifier)
159
+ continue;
160
+ const target = await this.moduleFile(project, statement.moduleSpecifier);
161
+ if (target && await this.runtimeExport(project, target, name, nested)) {
162
+ found = true;
163
+ break;
164
+ }
165
+ }
166
+ if (found) {
167
+ let names = this.runtime.get(file);
168
+ if (!names)
169
+ this.runtime.set(file, names = new Set());
170
+ names.add(name);
171
+ }
172
+ return found;
173
+ }
174
+ async functions(source) {
175
+ const cached = this.exports.get(source);
176
+ if (cached)
177
+ return cached;
178
+ const project = await this.project(source);
179
+ const file = await project.program.getSourceFile(source);
180
+ if (!file)
181
+ throw new TypeError(`Cannot read ${source}`);
182
+ const syntax = await project.program.getSyntacticDiagnostics(source);
183
+ if (syntax.length)
184
+ throw new TypeError(`Invalid function source ${source}: ${syntax[0].text} (TS${syntax[0].code})`);
185
+ if (!this.declarationFiles.has(project)) {
186
+ const declarations = await Promise.all(sdkDeclarations('declarations').map(path => project.program.getSourceFile(path)));
187
+ this.declarationFiles.set(project, declarations.flatMap(value => value ? [value.path] : []));
188
+ }
189
+ const declarationPaths = this.declarationFiles.get(project);
190
+ let brands = this.brands.get(project);
191
+ if (!brands)
192
+ this.brands.set(project, brands = new Map());
193
+ const functions = [];
194
+ if (declarationPaths.length)
195
+ for (const exported of await this.moduleExports(project, file)) {
196
+ const target = exported.flags & SymbolFlags.Alias ? await project.checker.getAliasedSymbol(exported) : exported;
197
+ if (!(target.flags & SymbolFlags.Value))
198
+ continue;
199
+ const type = await project.checker.getTypeOfSymbol(target);
200
+ if (!type)
201
+ continue;
202
+ let branded = brands.get(type.id);
203
+ if (branded === undefined) {
204
+ branded = (await project.checker.getPropertiesOfType(type)).some(property => property.name.startsWith("__@definitionBrand@") && property.declarations.some(declaration => declarationPaths.includes(declaration.path)));
205
+ brands.set(type.id, branded);
206
+ }
207
+ if (branded && await this.runtimeExport(project, file, exported.name))
208
+ functions.push({
209
+ name: exported.name, symbol: exported,
210
+ original: target.name === exported.name && target.declarations.some(declaration => declaration.path === file.path),
211
+ });
212
+ }
213
+ this.exports.set(source, functions);
214
+ return functions;
215
+ }
216
+ /** Locate configuration through exported aliases without evaluating a loader. */
217
+ async databaseDeclarations(source) {
218
+ const cached = this.databases.get(source);
219
+ if (cached)
220
+ return cached;
221
+ const project = await this.project(source);
222
+ const file = await project.program.getSourceFile(source);
223
+ if (!file)
224
+ throw new TypeError(`Cannot read ${source}`);
225
+ const results = new Map();
226
+ const span = (node) => {
227
+ let root = node;
228
+ while (root.parent)
229
+ root = root.parent;
230
+ return { file: root.fileName, start: node.pos, end: node.end };
231
+ };
232
+ const follow = async (node, seen = new Set()) => {
233
+ if (isParenthesizedExpression(node) || isAsExpression(node) || isSatisfiesExpression(node) || isNonNullExpression(node))
234
+ return follow(node.expression, seen);
235
+ if (isVariableDeclaration(node) && node.initializer)
236
+ return follow(node.initializer, seen);
237
+ if (isPropertyAssignment(node))
238
+ return follow(node.initializer, seen);
239
+ if (isShorthandPropertyAssignment(node)) {
240
+ const symbol = await project.checker.getShorthandAssignmentValueSymbol(node);
241
+ const declaration = symbol?.declarations[0];
242
+ const value = await declaration?.resolve(project);
243
+ if (value)
244
+ return follow(value, seen);
245
+ }
246
+ if (isExportAssignment(node))
247
+ return follow(node.expression, seen);
248
+ if (node.kind === SyntaxKind.BinaryExpression && 'right' in node)
249
+ return follow(node.right, seen);
250
+ if (node.kind === SyntaxKind.PropertyAccessExpression && node.parent?.kind === SyntaxKind.BinaryExpression && 'right' in node.parent)
251
+ return follow(node.parent.right, seen);
252
+ if (isIdentifier(node)) {
253
+ let symbol = await project.checker.getSymbolAtLocation(node);
254
+ if (symbol && symbol.flags & SymbolFlags.Alias)
255
+ symbol = await project.checker.getAliasedSymbol(symbol);
256
+ for (const declaration of symbol?.declarations ?? []) {
257
+ const key = `${declaration.path}:${declaration.index}`;
258
+ if (seen.has(key))
259
+ continue;
260
+ const target = await declaration.resolve(project);
261
+ if (target && (isVariableDeclaration(target) || isExportAssignment(target)))
262
+ return follow(target, new Set(seen).add(key));
263
+ }
264
+ }
265
+ return node;
266
+ };
267
+ const exportedBinding = async (node) => {
268
+ let symbol = isShorthandPropertyAssignment(node)
269
+ ? await project.checker.getShorthandAssignmentValueSymbol(node)
270
+ : await project.checker.getSymbolAtLocation(node);
271
+ for (const declaration of symbol?.declarations ?? []) {
272
+ const value = await declaration.resolve(project);
273
+ const required = value && this.requiredBinding(value);
274
+ if (required)
275
+ return { file: Bun.resolveSync(required.specifier.text, dirname(required.importer)), name: required.name };
276
+ }
277
+ // Resolve through the actual import/export conditions, rather than assume
278
+ // a package's .d.ts has a same-directory JavaScript implementation.
279
+ if (symbol && symbol.flags & SymbolFlags.Alias)
280
+ for (const declaration of symbol.declarations) {
281
+ let imported;
282
+ for (let binding = await declaration.resolve(project); binding; binding = binding.parent) {
283
+ if ('isTypeOnly' in binding && binding.isTypeOnly)
284
+ return undefined;
285
+ if (isImportSpecifier(binding))
286
+ imported = (binding.propertyName ?? binding.name).text;
287
+ else if (isImportClause(binding) && binding.name && imported === undefined)
288
+ imported = 'default';
289
+ if (isImportDeclaration(binding) && binding.moduleSpecifier && isStringLiteral(binding.moduleSpecifier) && imported) {
290
+ return { file: Bun.resolveSync(binding.moduleSpecifier.text, dirname(span(binding).file)), name: imported };
291
+ }
292
+ }
293
+ }
294
+ if (symbol && symbol.flags & SymbolFlags.Alias)
295
+ symbol = await project.checker.getAliasedSymbol(symbol);
296
+ for (const declaration of symbol?.declarations ?? []) {
297
+ let root = await declaration.resolve(project);
298
+ if (!root)
299
+ continue;
300
+ while (root.parent)
301
+ root = root.parent;
302
+ const file = root;
303
+ for (const exported of await this.moduleExports(project, file)) {
304
+ const target = exported.flags & SymbolFlags.Alias ? await project.checker.getAliasedSymbol(exported) : exported;
305
+ if (target.declarations.some(value => value.path === declaration.path && value.index === declaration.index))
306
+ return { file: file.fileName, name: exported.name };
307
+ }
308
+ }
309
+ return undefined;
310
+ };
311
+ const namespaceImport = async (node) => {
312
+ const symbol = node.kind === SyntaxKind.NamespaceImport ? undefined : await project.checker.getSymbolAtLocation(node);
313
+ const bindings = node.kind === SyntaxKind.NamespaceImport ? [node] : await Promise.all((symbol?.declarations ?? []).map(declaration => declaration.resolve(project)));
314
+ for (const binding of bindings) {
315
+ if (binding?.kind !== SyntaxKind.NamespaceImport)
316
+ continue;
317
+ const clause = binding.parent;
318
+ if (!clause || !isImportClause(clause) || clause.phaseModifier === SyntaxKind.TypeKeyword)
319
+ continue;
320
+ const statement = clause.parent;
321
+ if (statement && isImportDeclaration(statement) && isStringLiteral(statement.moduleSpecifier)) {
322
+ return { specifier: statement.moduleSpecifier.text, importer: span(statement).file };
323
+ }
324
+ }
325
+ };
326
+ const candidates = [];
327
+ for (const exported of await this.moduleExports(project, file)) {
328
+ const target = exported.flags & SymbolFlags.Alias ? await project.checker.getAliasedSymbol(exported) : exported;
329
+ const type = await project.checker.getTypeOfSymbol(target);
330
+ if (!type || !(await project.checker.getPropertiesOfType(type)).some(property => property.name.startsWith('__@instanceType@')))
331
+ continue;
332
+ for (const declaration of target.declarations) {
333
+ const root = await declaration.resolve(project);
334
+ if (root)
335
+ candidates.push({ name: exported.name, root });
336
+ }
337
+ }
338
+ for (const candidate of candidates) {
339
+ const root = candidate.root;
340
+ const call = await follow(root);
341
+ if (!isCallExpression(call) || !call.arguments[0])
342
+ continue;
343
+ const options = await follow(call.arguments[0]);
344
+ if (!isObjectLiteralExpression(options))
345
+ continue;
346
+ // AST nodes expose names as text; no source printer or string parser is needed.
347
+ const named = (name) => options.properties.find(property => (isPropertyAssignment(property) || isShorthandPropertyAssignment(property)) && "text" in property.name && property.name.text === name);
348
+ const schemaProperty = named("schema");
349
+ if (!schemaProperty || (!isPropertyAssignment(schemaProperty) && !isShorthandPropertyAssignment(schemaProperty)))
350
+ continue;
351
+ const schemaNode = isPropertyAssignment(schemaProperty) ? schemaProperty.initializer : schemaProperty;
352
+ const functions = named("functions");
353
+ let selection;
354
+ if (functions && (isPropertyAssignment(functions) || isShorthandPropertyAssignment(functions))) {
355
+ const node = isPropertyAssignment(functions) ? functions.initializer : functions;
356
+ const value = await follow(node);
357
+ const location = { ...span(node), ...(isShorthandPropertyAssignment(functions) ? { shorthand: true } : {}) };
358
+ if (isIdentifier(value) && value.text === "undefined") { /* Explicit omission. */ }
359
+ else if (isStringLiteral(value))
360
+ selection = { ...location, kind: "glob", pattern: value.text };
361
+ else if (isArrowFunction(value) || isFunctionExpression(value)) {
362
+ let body = value.body;
363
+ if (isBlock(body)) {
364
+ if (body.statements.length !== 1 || !isReturnStatement(body.statements[0]) || !body.statements[0].expression)
365
+ throw new TypeError("functions loader must return one literal import()");
366
+ body = body.statements[0].expression;
367
+ }
368
+ body = await follow(body);
369
+ if (body.kind === SyntaxKind.AwaitExpression && "expression" in body)
370
+ body = body.expression;
371
+ if (!isCallExpression(body) || body.expression.kind !== SyntaxKind.ImportKeyword || body.arguments.length !== 1 || !isStringLiteral(body.arguments[0]))
372
+ throw new TypeError("functions loader must return one literal import()");
373
+ selection = { ...location, kind: "import", specifier: body.arguments[0].text, importer: span(body).file };
374
+ }
375
+ else {
376
+ const imported = await namespaceImport(value);
377
+ if (!imported)
378
+ throw new TypeError("For hosting, functions must be an imported module namespace, a lazy literal import(), or a glob");
379
+ selection = { ...location, kind: "namespace", ...imported };
380
+ }
381
+ }
382
+ const location = span(call);
383
+ const schemaBinding = await exportedBinding(schemaNode);
384
+ const schemaExport = schemaBinding?.file !== location.file ? schemaBinding : undefined;
385
+ const factoryNode = call.expression.kind === SyntaxKind.PropertyAccessExpression && "expression" in call.expression ? call.expression.expression : call.expression;
386
+ const factoryExport = await exportedBinding(factoryNode);
387
+ results.set(`${location.file}:${location.start}`, { exportName: candidate.name, call: location, factory: span(call.expression), argument: span(call.arguments[0]), ...(schemaExport ? { schemaExport } : {}), ...(factoryExport ? { factoryExport } : {}), ...(selection ? { functions: selection } : {}) });
388
+ }
389
+ const declarations = [...results.values()];
390
+ this.databases.set(source, declarations);
391
+ return declarations;
392
+ }
393
+ /** Namespace barrel exports describe module groups; flat exports form one module. */
394
+ async catalogue(source, prefix) {
395
+ const project = await this.project(source);
396
+ const modules = Object.create(null);
397
+ const visit = async (path, name, ancestors, root = false) => {
398
+ if (ancestors.has(path))
399
+ throw new TypeError(`Cyclic function catalogue namespace: ${name}`);
400
+ const file = await project.program.getSourceFile(path);
401
+ if (!file)
402
+ throw new TypeError(`Cannot resolve function catalogue ${path}`);
403
+ if ((await this.functions(path)).length)
404
+ modules[name] = file.fileName;
405
+ for (const exported of await this.moduleExports(project, file)) {
406
+ const target = exported.flags & SymbolFlags.Alias ? await project.checker.getAliasedSymbol(exported) : exported;
407
+ if (!(target.flags & (SymbolFlags.ValueModule | SymbolFlags.NamespaceModule)) || !await this.runtimeExport(project, file, exported.name))
408
+ continue;
409
+ const declaration = target.declarations.find(value => value.kind === SyntaxKind.SourceFile);
410
+ if (declaration)
411
+ await visit(declaration.path, root ? exported.name : `${name}/${exported.name}`, new Set(ancestors).add(path));
412
+ }
413
+ };
414
+ await visit(source, prefix, new Set(), true);
415
+ return modules;
416
+ }
417
+ async close() {
418
+ try {
419
+ await this.snapshot?.dispose();
420
+ }
421
+ finally {
422
+ await this.api.close();
423
+ }
424
+ }
425
+ }
@@ -0,0 +1,8 @@
1
+ import { FunctionAnalysis } from "./function-analysis.ts";
2
+ import type { ValueShape } from "@hulla/db/internal/codegen";
3
+ /** TypeScript's checker provides inferred contracts; applications need no second result schema. */
4
+ export declare function compileFunctionShapes(modules: Readonly<Record<string, string>>, declarations: Readonly<Record<string, readonly string[]>>, sharedAnalysis?: FunctionAnalysis): Promise<Map<string, {
5
+ input: ValueShape;
6
+ result: ValueShape;
7
+ paginated?: true;
8
+ }>>;
@@ -0,0 +1,142 @@
1
+ import { TypeFlags, SymbolFlags, isDateLibrary } from "./development-compiler.js";
2
+ import { FunctionAnalysis } from "./function-analysis.js";
3
+ import { sdkDeclarations } from "./sdk-declarations.js";
4
+ const canonicalPath = (path) => {
5
+ const normalized = path.replaceAll("\\", "/");
6
+ return process.platform === "win32" || process.platform === "darwin" ? normalized.toLowerCase() : normalized;
7
+ };
8
+ const pagePaths = new Set(sdkDeclarations("page").map(canonicalPath));
9
+ const jsonPaths = new Set(sdkDeclarations("json-value").map(canonicalPath));
10
+ async function pageBrand(checker, type) {
11
+ const fields = await checker.getPropertiesOfType(type);
12
+ if (fields.length !== 3 || !fields.some(field => field.name === "page") || !fields.some(field => field.name === "cursor"))
13
+ return;
14
+ const brand = fields.find(field => field.name.startsWith("__@pageEligibility@") && field.declarations.some(declaration => pagePaths.has(canonicalPath(declaration.path))));
15
+ return brand?.name;
16
+ }
17
+ async function shape(checker, type, parents = new Set()) {
18
+ if (!type || type.isErrorType())
19
+ throw new TypeError("Cannot infer a function value contract");
20
+ const alias = await type.getAliasSymbol();
21
+ if (alias?.name === "JsonValue" && alias.declarations.some(declaration => jsonPaths.has(canonicalPath(declaration.path))))
22
+ return { kind: "json" };
23
+ if (parents.has(type.id))
24
+ throw new TypeError("Recursive function value types are not supported");
25
+ const nested = new Set(parents).add(type.id);
26
+ if (type.flags & (TypeFlags.Any | TypeFlags.Unknown | TypeFlags.Never | TypeFlags.TypeParameter)) {
27
+ const name = type.flags & TypeFlags.Any ? "any" : type.flags & TypeFlags.Unknown ? "unknown" : type.flags & TypeFlags.Never ? "never" : "type parameter";
28
+ throw new TypeError(`Unsupported function value type: ${name}`);
29
+ }
30
+ if (type.flags & TypeFlags.Void || type.flags & TypeFlags.Undefined)
31
+ return { kind: "undefined" };
32
+ if (type.flags & TypeFlags.Null)
33
+ return { kind: "null" };
34
+ if (type.isBigIntLiteralType())
35
+ throw new TypeError("Bigint literal signatures are not supported; use bigint");
36
+ if (type.flags & TypeFlags.BigInt)
37
+ return { kind: "bigint" };
38
+ if (type.isLiteralType())
39
+ return { kind: "literal", value: type.value };
40
+ if (type.flags & TypeFlags.String)
41
+ return { kind: "string" };
42
+ if (type.flags & TypeFlags.Number)
43
+ return { kind: "number" };
44
+ if (type.flags & TypeFlags.Boolean)
45
+ return { kind: "boolean" };
46
+ const symbol = await type.getSymbol();
47
+ if (symbol?.name === "Date" && symbol.declarations.some(declaration => isDateLibrary(canonicalPath(declaration.path))))
48
+ return { kind: "date" };
49
+ if (type.isUnionType())
50
+ return { kind: "union", choices: await Promise.all((await type.getTypes()).map(t => shape(checker, t, nested))) };
51
+ if (type.isIntersectionType()) {
52
+ // Phantom ID brands do not add wire fields to a primitive.
53
+ const parts = await type.getTypes();
54
+ const primitive = parts.find(t => t.flags & (TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.BooleanLike));
55
+ if (primitive)
56
+ return shape(checker, primitive, nested);
57
+ // Standard Schema extension inputs intersect the original submitted shapes.
58
+ // Ask the checker for merged properties so overlapping fields retain their
59
+ // actual intersection type and required/optional status.
60
+ if (parts.some(part => !(part.flags & TypeFlags.Object) && !part.isIntersectionType())) {
61
+ throw new TypeError("Unsupported intersection value; use portable object fields");
62
+ }
63
+ }
64
+ if (await checker.isArrayType(type)) {
65
+ if (!type.isTypeReference())
66
+ throw new TypeError("Unsupported array value");
67
+ return { kind: "array", item: await shape(checker, (await checker.getTypeArguments(type))[0], nested) };
68
+ }
69
+ if (await checker.isTupleType(type)) {
70
+ if (!type.isTypeReference())
71
+ throw new TypeError("Unsupported tuple value");
72
+ const target = await type.getTarget();
73
+ if (!target.isTupleType() || target.elementFlags.some(flag => flag !== 1))
74
+ throw new TypeError("Only fixed required tuples are supported");
75
+ return { kind: "tuple", items: await Promise.all((await checker.getTypeArguments(type)).map(t => shape(checker, t, nested))) };
76
+ }
77
+ if (type.flags & TypeFlags.Object || type.isIntersectionType()) {
78
+ if ((await checker.getSignaturesOfType(type, 0)).length || (await checker.getIndexInfosOfType(type)).length) {
79
+ throw new TypeError("Functions and open index signatures are not portable function values");
80
+ }
81
+ const symbol = await type.getSymbol();
82
+ if (symbol && ["Date", "Map", "Set", "Promise", "Uint8Array"].includes(symbol.name))
83
+ throw new TypeError(`Unsupported function value: ${symbol.name}`);
84
+ const fields = Object.create(null);
85
+ const brand = await pageBrand(checker, type);
86
+ for (const field of await checker.getPropertiesOfType(type)) {
87
+ if (field.name === brand)
88
+ continue;
89
+ if (field.name.startsWith("__@"))
90
+ throw new TypeError("Symbol properties are not portable values");
91
+ fields[field.name] = { shape: await shape(checker, await checker.getTypeOfSymbol(field), nested), optional: !!(field.flags & SymbolFlags.Optional) };
92
+ }
93
+ return { kind: "object", fields };
94
+ }
95
+ throw new TypeError(`Unsupported function value type: ${await checker.typeToString(type)}`);
96
+ }
97
+ /** TypeScript's checker provides inferred contracts; applications need no second result schema. */
98
+ export async function compileFunctionShapes(modules, declarations, sharedAnalysis) {
99
+ const analysis = sharedAnalysis ?? new FunctionAnalysis();
100
+ try {
101
+ await analysis.open(Object.values(modules));
102
+ const shapes = new Map();
103
+ for (const [module, source] of Object.entries(modules)) {
104
+ if (!declarations[module]?.length)
105
+ continue;
106
+ const project = await analysis.project(source);
107
+ const checker = project.checker;
108
+ const names = new Set(declarations[module]);
109
+ for (const exported of await analysis.functions(source)) {
110
+ if (!names.has(exported.name))
111
+ continue;
112
+ const definition = await checker.getTypeOfSymbol(exported.symbol);
113
+ if (!definition)
114
+ continue;
115
+ const types = await checker.getPropertyOfType(definition, "$types");
116
+ if (!types)
117
+ continue;
118
+ let metadata = await checker.getTypeOfSymbol(types);
119
+ if (metadata?.isUnionType())
120
+ metadata = (await metadata.getTypes()).find(type => type.flags & TypeFlags.Object);
121
+ if (!metadata)
122
+ throw new TypeError(`Cannot infer ${module}.${exported.name}`);
123
+ const input = await checker.getPropertyOfType(metadata, "input");
124
+ const output = await checker.getPropertyOfType(metadata, "output");
125
+ if (!input || !output)
126
+ throw new TypeError("Missing function signature metadata");
127
+ const outputType = await checker.getTypeOfSymbol(output);
128
+ const paginated = outputType && await pageBrand(checker, outputType);
129
+ shapes.set(`${module}.${exported.name}`, {
130
+ ...(paginated ? { paginated: true } : {}),
131
+ input: await shape(checker, await checker.getTypeOfSymbol(input)),
132
+ result: await shape(checker, outputType),
133
+ });
134
+ }
135
+ }
136
+ return shapes;
137
+ }
138
+ finally {
139
+ if (!sharedAnalysis)
140
+ await analysis.close();
141
+ }
142
+ }
@@ -0,0 +1,3 @@
1
+ import type { DatabaseDeclaration } from './function-analysis.ts';
2
+ /** Server-only settings preserve runtime expressions without running an eager initializer. */
3
+ export declare function generateHost(source: string, name: string, declarations: readonly DatabaseDeclaration[]): Promise<string>;
@@ -0,0 +1,45 @@
1
+ import { dirname, resolve } from 'node:path';
2
+ import { runtimeExportConditions } from './runtime-conditions.js';
3
+ /** Server-only settings preserve runtime expressions without running an eager initializer. */
4
+ export async function generateHost(source, name, declarations) {
5
+ const files = new Map();
6
+ function edit(file, change) {
7
+ const edits = files.get(file) ?? [];
8
+ edits.push(change);
9
+ files.set(file, edits);
10
+ }
11
+ for (const { call, factory, argument, functions } of declarations) {
12
+ edit(call.file, { start: call.start, end: argument.start,
13
+ replace: original => ` (await import('@hulla/db/internal/engine')).captureHostDatabase(${original.slice(factory.start, factory.end)},` });
14
+ edit(call.file, { start: argument.end, end: call.end, replace: () => ')' });
15
+ // Prepared hosting uses the compiled worker catalogue, not host-side handlers.
16
+ if (functions?.kind === 'namespace')
17
+ edit(functions.file, { start: functions.start, end: functions.end,
18
+ replace: original => functions.shorthand ? ` ${original.slice(functions.start, functions.end).trim()}: undefined` : ' undefined' });
19
+ }
20
+ const build = await Bun.build({
21
+ entrypoints: ['__hulla_host_settings__'], target: 'node', format: 'esm',
22
+ packages: 'external', conditions: runtimeExportConditions(), throw: false,
23
+ plugins: [{ name: 'hulla-host-settings', setup(builder) {
24
+ builder.onResolve({ filter: /^__hulla_host_settings__$/ }, () => ({ path: resolve(dirname(source), '_host-entry.ts'), namespace: 'hulla-host' }));
25
+ builder.onLoad({ filter: /.*/, namespace: 'hulla-host' }, () => ({
26
+ contents: `export { ${JSON.stringify(name)} as default } from ${JSON.stringify(source)}`,
27
+ loader: 'ts', resolveDir: dirname(source),
28
+ }));
29
+ builder.onLoad({ filter: /\.[cm]?[tj]sx?$/, namespace: 'file' }, async (args) => {
30
+ const patches = files.get(args.path);
31
+ if (!patches)
32
+ return undefined;
33
+ const original = await Bun.file(args.path).text();
34
+ let contents = original;
35
+ for (const patch of [...patches].sort((a, b) => b.start - a.start)) {
36
+ contents = contents.slice(0, patch.start) + patch.replace(original) + contents.slice(patch.end);
37
+ }
38
+ return { contents, loader: /\.[cm]?jsx?$/.test(args.path) ? 'jsx' : 'tsx', resolveDir: dirname(args.path) };
39
+ });
40
+ } }],
41
+ });
42
+ if (!build.success || build.outputs.length !== 1)
43
+ throw new TypeError(`Cannot prepare database host settings:\n${build.logs.map(log => log.message).join('\n')}`);
44
+ return '// Generated by @hulla/db. Do not edit.\n' + await build.outputs[0].text();
45
+ }
@@ -0,0 +1,5 @@
1
+ /** Cache verified archives by digest. Each running server owns its extracted files. */
2
+ export declare function openLocalPostgresAssets(signal: AbortSignal): Promise<{
3
+ bin: string;
4
+ close: () => Promise<void>;
5
+ }>;