@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.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/dist/build.d.ts +45 -0
- package/dist/build.js +141 -0
- package/dist/cli-address.d.ts +35 -0
- package/dist/cli-address.js +135 -0
- package/dist/cli-options.d.ts +13 -0
- package/dist/cli-options.js +43 -0
- package/dist/cli-output.d.ts +36 -0
- package/dist/cli-output.js +69 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +101 -0
- package/dist/codegen.d.ts +39 -0
- package/dist/codegen.js +358 -0
- package/dist/database-capture.d.ts +3 -0
- package/dist/database-capture.js +32 -0
- package/dist/database-codegen.d.ts +4 -0
- package/dist/database-codegen.js +46 -0
- package/dist/database-function-discovery.d.ts +10 -0
- package/dist/database-function-discovery.js +87 -0
- package/dist/dev-worker.d.ts +1 -0
- package/dist/dev-worker.js +138 -0
- package/dist/dev.d.ts +6 -0
- package/dist/dev.js +209 -0
- package/dist/development-compiler.d.ts +3 -0
- package/dist/development-compiler.js +5 -0
- package/dist/development-runtime.d.ts +2 -0
- package/dist/development-runtime.js +25 -0
- package/dist/function-analysis.d.ts +62 -0
- package/dist/function-analysis.js +425 -0
- package/dist/function-shapes.d.ts +8 -0
- package/dist/function-shapes.js +142 -0
- package/dist/host-codegen.d.ts +3 -0
- package/dist/host-codegen.js +45 -0
- package/dist/local-postgres-assets.d.ts +5 -0
- package/dist/local-postgres-assets.js +107 -0
- package/dist/local-postgres-assets.json +1 -0
- package/dist/local-postgres.d.ts +7 -0
- package/dist/local-postgres.js +180 -0
- package/dist/names.d.ts +2 -0
- package/dist/names.js +10 -0
- package/dist/project-codegen.d.ts +3 -0
- package/dist/project-codegen.js +107 -0
- package/dist/runtime-conditions.d.ts +2 -0
- package/dist/runtime-conditions.js +10 -0
- package/dist/schema-codegen.d.ts +16 -0
- package/dist/schema-codegen.js +212 -0
- package/dist/sdk-declarations.d.ts +1 -0
- package/dist/sdk-declarations.js +4 -0
- package/dist/setup-ignore.d.ts +6 -0
- package/dist/setup-ignore.js +35 -0
- package/dist/source-codegen.d.ts +7 -0
- package/dist/source-codegen.js +46 -0
- package/dist/studio.d.ts +8 -0
- package/dist/studio.js +28 -0
- package/dist/worker-codegen.d.ts +4 -0
- package/dist/worker-codegen.js +51 -0
- package/package.json +59 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { parseCLI, usage } from "./cli-options.js";
|
|
4
|
+
import { cliError, cliOutput } from "./cli-output.js";
|
|
5
|
+
import { startCLIListener, StartupCancelled } from "./cli-address.js";
|
|
6
|
+
async function main() {
|
|
7
|
+
const args = process.argv.slice(2);
|
|
8
|
+
if (!args.length || args.includes("--help") || args.includes("-h")) {
|
|
9
|
+
cliOutput.help();
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
const { command, config, studio, check, ignoreFile } = parseCLI(args, process.env.NODE_ENV === "production");
|
|
13
|
+
const configPath = resolve(config);
|
|
14
|
+
if (command === "generate" || command === "dev" || command === "setup") {
|
|
15
|
+
if (typeof Bun === "undefined")
|
|
16
|
+
return (await import("./development-runtime.js")).runDevelopmentCLI();
|
|
17
|
+
}
|
|
18
|
+
cliOutput.heading(command, configPath);
|
|
19
|
+
if (command === "setup") {
|
|
20
|
+
const { setupGeneratedIgnore } = await import("./setup-ignore.js");
|
|
21
|
+
const result = await setupGeneratedIgnore(configPath, ignoreFile);
|
|
22
|
+
cliOutput.success(`${result.changed ? "Added" : "Already configured"} ${result.pattern} in ${result.path}`);
|
|
23
|
+
}
|
|
24
|
+
else if (command === "generate") {
|
|
25
|
+
const { generateProject } = await import("./project-codegen.js");
|
|
26
|
+
await generateProject(configPath);
|
|
27
|
+
cliOutput.success("Generated database entrypoints.");
|
|
28
|
+
}
|
|
29
|
+
else if (command === "serve" || command === "dev" || command === "studio") {
|
|
30
|
+
let service;
|
|
31
|
+
let stopping = false;
|
|
32
|
+
const startup = new AbortController();
|
|
33
|
+
const stop = () => { stopping = true; startup.abort(); void service?.close().catch(() => { }); };
|
|
34
|
+
process.on("SIGINT", stop);
|
|
35
|
+
process.on("SIGTERM", stop);
|
|
36
|
+
try {
|
|
37
|
+
if (command === "dev")
|
|
38
|
+
service = await (await import("./dev.js")).startDevelopment(configPath, studio);
|
|
39
|
+
else if (command === "studio") {
|
|
40
|
+
const { startStudio } = await import("./studio.js");
|
|
41
|
+
service = (await startCLIListener("Hulla Studio", { host: "127.0.0.1", port: studio.port }, address => startStudio(configPath, { ...studio, port: address.port }), { signal: startup.signal, fixedHost: true })).listener;
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
const { loadHostConfiguration } = await import("@hulla/db-postgres/internal/host");
|
|
45
|
+
const { config } = await loadHostConfiguration(configPath);
|
|
46
|
+
const { startService } = await import("@hulla/db-postgres/service");
|
|
47
|
+
service = (await startCLIListener("Database service", { host: config.service?.host ?? "127.0.0.1", port: config.service?.port ?? 3001 }, address => startService(configPath, address), { signal: startup.signal })).listener;
|
|
48
|
+
}
|
|
49
|
+
if (stopping)
|
|
50
|
+
await service.close();
|
|
51
|
+
else if (service.url)
|
|
52
|
+
cliOutput.listening(command === "studio" ? "Hulla Studio" : "Database service", service.url);
|
|
53
|
+
await service.closed;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (!stopping)
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
process.off("SIGINT", stop);
|
|
61
|
+
process.off("SIGTERM", stop);
|
|
62
|
+
await service?.close();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
const { loadHostConfiguration } = await import("@hulla/db-postgres/internal/host");
|
|
67
|
+
const { initializeDatabase, migrateDatabase } = await import("@hulla/db-postgres/server");
|
|
68
|
+
const { resolveDatabaseConnection } = await import("@hulla/db-postgres/server");
|
|
69
|
+
const { config, schema } = await loadHostConfiguration(configPath);
|
|
70
|
+
const connection = resolveDatabaseConnection(config.database.server, configPath);
|
|
71
|
+
if (command === "migrate") {
|
|
72
|
+
const plan = await migrateDatabase(schema, connection, { check: check ?? false });
|
|
73
|
+
for (const change of plan.changes) {
|
|
74
|
+
cliOutput.info("field" in change ? `Add ${change.kind === "add_field" ? "field" : "reference"} ${JSON.stringify(change.table)}.${JSON.stringify(change.field)}` : `${change.kind === "add_table" ? "Add table" : "Reorder fields in table"} ${JSON.stringify(change.table)}`);
|
|
75
|
+
}
|
|
76
|
+
cliOutput.success(plan.changes.length === 0 ? "Schema is already current." : check ? "Check complete. No changes applied. Run migrate to apply this plan." : "Schema migration applied.");
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
await initializeDatabase(schema, connection);
|
|
80
|
+
cliOutput.success("Database initialized and schema verified.");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
await main();
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
// Do not dump imported config contents, driver errors or connection URLs.
|
|
89
|
+
if (error instanceof StartupCancelled) {
|
|
90
|
+
cliOutput.info(error.message);
|
|
91
|
+
}
|
|
92
|
+
else if (error instanceof Error && error.message === usage) {
|
|
93
|
+
cliError.error("Invalid command or options.");
|
|
94
|
+
cliError.help();
|
|
95
|
+
process.exitCode = 1;
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
cliError.error(error instanceof Error ? error.message : "Database setup failed");
|
|
99
|
+
process.exitCode = 1;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type ClientConnection, type InvocationLimits } from "@hulla/db/config";
|
|
2
|
+
import { FunctionAnalysis } from "./function-analysis.ts";
|
|
3
|
+
import type { DatabaseConfiguration } from "@hulla/db/internal/codegen";
|
|
4
|
+
export { generateProject } from "./project-codegen.ts";
|
|
5
|
+
export { generateDatabase } from "./database-codegen.ts";
|
|
6
|
+
export { generateSchema, generateRustSchema } from "./schema-codegen.ts";
|
|
7
|
+
export type { SchemaGenerationOptions } from "./schema-codegen.ts";
|
|
8
|
+
export interface GenerationOptions {
|
|
9
|
+
/** Only declarations bound to this database are included. */
|
|
10
|
+
readonly database?: DatabaseConfiguration;
|
|
11
|
+
/** Database export from the explicit, shared metadata entrypoint. */
|
|
12
|
+
readonly databaseExport?: string;
|
|
13
|
+
readonly databaseArtifacts?: {
|
|
14
|
+
readonly worker: string;
|
|
15
|
+
readonly bundle: string;
|
|
16
|
+
readonly host: string;
|
|
17
|
+
readonly rootModule?: string | undefined;
|
|
18
|
+
};
|
|
19
|
+
readonly databaseSource?: {
|
|
20
|
+
readonly wrapper: string;
|
|
21
|
+
readonly bundle: string;
|
|
22
|
+
readonly declaration: string;
|
|
23
|
+
};
|
|
24
|
+
readonly client?: ClientConnection;
|
|
25
|
+
readonly limits?: InvocationLimits;
|
|
26
|
+
/** Low-level explicit source mapping. Normally omit this and use discovery. */
|
|
27
|
+
readonly modules?: Readonly<Record<string, string>>;
|
|
28
|
+
/** Defaults to ./db/schema.ts. Discovery starts beside this file. */
|
|
29
|
+
readonly schema?: string;
|
|
30
|
+
/** Optional discovery directory override. */
|
|
31
|
+
readonly functions?: string;
|
|
32
|
+
/** Stable base for operation paths, independent of the discovery directory. Defaults beside the schema. */
|
|
33
|
+
readonly moduleRoot?: string;
|
|
34
|
+
readonly outDir: string;
|
|
35
|
+
}
|
|
36
|
+
/** Find declarations without evaluating candidate modules or their dependencies. */
|
|
37
|
+
export declare function discoverFunctions(options: Pick<GenerationOptions, "schema" | "functions" | "moduleRoot" | "outDir">, sharedAnalysis?: FunctionAnalysis): Promise<Readonly<Record<string, string>>>;
|
|
38
|
+
/** Discovery is static. Only selected declaration modules execute in the trusted build process. */
|
|
39
|
+
export declare function generateFunctions(options: GenerationOptions, sharedAnalysis?: FunctionAnalysis): Promise<void>;
|
package/dist/codegen.js
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { resolveLimits, clientConnection } from "@hulla/db/config";
|
|
10
|
+
import { lstat, mkdir, readdir } from "node:fs/promises";
|
|
11
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
12
|
+
import { FunctionAnalysis } from "./function-analysis.js";
|
|
13
|
+
import { isFunctionDefinition } from "@hulla/db/internal/functions";
|
|
14
|
+
import { assertModuleName, validExportName } from "./names.js";
|
|
15
|
+
import { checkGeneratedDirectory } from "./schema-codegen.js";
|
|
16
|
+
import { compileFunctionShapes } from "./function-shapes.js";
|
|
17
|
+
import { functionDatabases, tableBindings } from "@hulla/db/internal/codegen";
|
|
18
|
+
import { workerBundleHeader } from "./worker-codegen.js";
|
|
19
|
+
export { generateProject } from "./project-codegen.js";
|
|
20
|
+
export { generateDatabase } from "./database-codegen.js";
|
|
21
|
+
export { generateSchema, generateRustSchema } from "./schema-codegen.js";
|
|
22
|
+
const header = "// Generated by @hulla/db. Do not edit.\n";
|
|
23
|
+
const schemaHeader = "// Generated schema by @hulla/db. Do not edit.\n";
|
|
24
|
+
function importPath(from, target) {
|
|
25
|
+
const path = relative(from, target).split(sep).join("/");
|
|
26
|
+
return path.startsWith(".") ? path : `./${path}`;
|
|
27
|
+
}
|
|
28
|
+
const excludedDirectories = new Set(["_generated", "node_modules", "tests", "test", "__tests__", "__mocks__"]);
|
|
29
|
+
/** Find declarations without evaluating candidate modules or their dependencies. */
|
|
30
|
+
export async function discoverFunctions(options, sharedAnalysis) {
|
|
31
|
+
const schema = resolve(options.schema ?? "db/schema.ts");
|
|
32
|
+
const root = resolve(options.functions ?? dirname(schema));
|
|
33
|
+
const moduleRoot = resolve(options.moduleRoot ?? dirname(schema));
|
|
34
|
+
const outDir = resolve(options.outDir);
|
|
35
|
+
const candidates = [];
|
|
36
|
+
async function scan(directory) {
|
|
37
|
+
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
38
|
+
const path = resolve(directory, entry.name);
|
|
39
|
+
if (path === outDir || entry.name.startsWith("."))
|
|
40
|
+
continue;
|
|
41
|
+
if (entry.isDirectory()) {
|
|
42
|
+
if (!excludedDirectories.has(entry.name))
|
|
43
|
+
await scan(path);
|
|
44
|
+
}
|
|
45
|
+
else if (entry.isFile() && /\.[cm]?tsx?$/.test(entry.name)
|
|
46
|
+
&& !/\.(?:d|test|spec)\.[cm]?tsx?$/.test(entry.name)
|
|
47
|
+
&& !/\.config\.[cm]?tsx?$/.test(entry.name)
|
|
48
|
+
&& path !== schema)
|
|
49
|
+
candidates.push(path);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
await scan(root);
|
|
53
|
+
if (!candidates.length)
|
|
54
|
+
return {};
|
|
55
|
+
const analysis = sharedAnalysis ?? new FunctionAnalysis();
|
|
56
|
+
try {
|
|
57
|
+
await analysis.open(candidates);
|
|
58
|
+
const modules = Object.create(null);
|
|
59
|
+
for (const source of candidates) {
|
|
60
|
+
const project = await analysis.project(source);
|
|
61
|
+
const syntax = await project.program.getSyntacticDiagnostics(source);
|
|
62
|
+
if (syntax.length)
|
|
63
|
+
throw new TypeError(`Invalid function source ${source}: ${syntax[0].text} (TS${syntax[0].code})`);
|
|
64
|
+
const exports = await analysis.functions(source);
|
|
65
|
+
if (!exports.length)
|
|
66
|
+
continue;
|
|
67
|
+
for (const exported of exports)
|
|
68
|
+
if (!validExportName(exported.name))
|
|
69
|
+
throw new Error(`Invalid function export name: ${exported.name}`);
|
|
70
|
+
const module = relative(moduleRoot, source).split(sep).join("/").replace(/\.[cm]?tsx?$/, "");
|
|
71
|
+
if (module.startsWith("../"))
|
|
72
|
+
throw new Error(`Function source ${source} is outside moduleRoot ${moduleRoot}; set moduleRoot to a common project directory`);
|
|
73
|
+
assertModuleName(module);
|
|
74
|
+
if (modules[module])
|
|
75
|
+
throw new Error(`Duplicate discovered function module: ${module}`);
|
|
76
|
+
modules[module] = source;
|
|
77
|
+
}
|
|
78
|
+
return modules;
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
if (!sharedAnalysis)
|
|
82
|
+
await analysis.close();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async function outputFiles(directory) {
|
|
86
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch((error) => {
|
|
87
|
+
if (error.code === "ENOENT")
|
|
88
|
+
return [];
|
|
89
|
+
throw error;
|
|
90
|
+
});
|
|
91
|
+
const files = [];
|
|
92
|
+
for (const entry of entries) {
|
|
93
|
+
if (entry.isDirectory())
|
|
94
|
+
for (const name of await outputFiles(resolve(directory, entry.name)))
|
|
95
|
+
files.push(`${entry.name}/${name}`);
|
|
96
|
+
else
|
|
97
|
+
files.push(entry.name);
|
|
98
|
+
}
|
|
99
|
+
return files;
|
|
100
|
+
}
|
|
101
|
+
async function checkOutputPath(directory, name) {
|
|
102
|
+
await checkGeneratedDirectory(directory);
|
|
103
|
+
const parts = name.split("/");
|
|
104
|
+
for (let index = 0; index < parts.length; index++) {
|
|
105
|
+
const path = resolve(directory, ...parts.slice(0, index + 1));
|
|
106
|
+
const info = await lstat(path).catch((error) => {
|
|
107
|
+
if (error.code === "ENOENT")
|
|
108
|
+
return undefined;
|
|
109
|
+
throw error;
|
|
110
|
+
});
|
|
111
|
+
if (!info)
|
|
112
|
+
break;
|
|
113
|
+
if (info.isSymbolicLink() || (index < parts.length - 1 ? !info.isDirectory() : !info.isFile())) {
|
|
114
|
+
throw new Error(`Refusing to overwrite an authored path: ${parts.slice(0, index + 1).join("/")}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Discovery is static. Only selected declaration modules execute in the trusted build process. */
|
|
119
|
+
export async function generateFunctions(options, sharedAnalysis) {
|
|
120
|
+
const analysis = sharedAnalysis ?? new FunctionAnalysis();
|
|
121
|
+
try {
|
|
122
|
+
await generateWithAnalysis(options, analysis);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
if (!sharedAnalysis)
|
|
126
|
+
await analysis.close();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function generateWithAnalysis(options, analysis) {
|
|
130
|
+
if (options.databaseExport !== undefined && (!options.database || !options.schema || options.client))
|
|
131
|
+
throw new TypeError("Database bindings require an explicit entrypoint and connect-time transport settings");
|
|
132
|
+
const outDir = resolve(options.outDir);
|
|
133
|
+
if (options.modules && options.functions)
|
|
134
|
+
throw new Error("Use either explicit modules or a functions discovery directory");
|
|
135
|
+
await checkGeneratedDirectory(outDir);
|
|
136
|
+
let moduleSources = options.modules ?? await discoverFunctions(options, analysis);
|
|
137
|
+
if (options.database) {
|
|
138
|
+
const selected = Object.create(null);
|
|
139
|
+
for (const [name, path] of Object.entries(moduleSources)) {
|
|
140
|
+
const exports = await import(__rewriteRelativeImportExtension(Bun.pathToFileURL(resolve(path)).href));
|
|
141
|
+
if (Object.values(exports).some(value => isFunctionDefinition(value) && functionDatabases.get(value) === options.database.identity))
|
|
142
|
+
selected[name] = path;
|
|
143
|
+
}
|
|
144
|
+
moduleSources = selected;
|
|
145
|
+
}
|
|
146
|
+
const existing = await outputFiles(outDir);
|
|
147
|
+
// Reject collisions before evaluating selected server modules or writing output.
|
|
148
|
+
for (const module of Object.keys(moduleSources)) {
|
|
149
|
+
assertModuleName(module);
|
|
150
|
+
if (module.split("/").at(-1) === "index")
|
|
151
|
+
throw new Error("Function module index is reserved for generated namespace entrypoints");
|
|
152
|
+
if (options.databaseArtifacts && ["_worker", "_host", "_client"].includes(module))
|
|
153
|
+
throw new Error(`Function module ${module} is reserved by the database generator`);
|
|
154
|
+
if (options.databaseSource && ["source", "_source"].includes(module))
|
|
155
|
+
throw new Error(`Function module ${module} is reserved for the shared source contract`);
|
|
156
|
+
if (!options.database && (module === "types" || module === "functions" || module === "tables"))
|
|
157
|
+
throw new Error(`Function module name conflicts with a generated schema output: ${module}.ts`);
|
|
158
|
+
}
|
|
159
|
+
const namespaces = namespaceFiles(Object.keys(moduleSources));
|
|
160
|
+
for (const name of ["runtime.ts", "functions.json", ...(options.databaseArtifacts ? ["_worker.ts", "_worker.js", "_host.js", "_client.ts"] : []), ...(options.databaseSource ? ["source.ts", "_source.js", "_source.d.ts"] : []), ...namespaces.keys(), ...Object.keys(moduleSources).map(module => `${module}.ts`)]) {
|
|
161
|
+
await checkOutputPath(outDir, name);
|
|
162
|
+
if (existing.includes(name) && !ownsOutput(name, await Bun.file(resolve(outDir, name)).text())) {
|
|
163
|
+
throw new Error(`Refusing to overwrite an authored file: ${name}`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const sources = Object.fromEntries(Object.entries(moduleSources).map(([name, path]) => [name, resolve(path)]));
|
|
167
|
+
await analysis.open(Object.values(sources));
|
|
168
|
+
const modules = new Map();
|
|
169
|
+
const declarations = Object.create(null);
|
|
170
|
+
const operations = [];
|
|
171
|
+
for (const [module, source] of Object.entries(sources)) {
|
|
172
|
+
const fromOutput = relative(outDir, source);
|
|
173
|
+
if (!fromOutput.startsWith(`..${sep}`) && !isAbsolute(fromOutput))
|
|
174
|
+
throw new Error("Function definitions must be outside the generated output directory");
|
|
175
|
+
const exported = await import(__rewriteRelativeImportExtension(Bun.pathToFileURL(source).href));
|
|
176
|
+
const definitions = Object.fromEntries(Object.entries(exported).filter(([, value]) => !isFunctionDefinition(value) || !options.database || functionDatabases.get(value) === options.database.identity));
|
|
177
|
+
modules.set(module, definitions);
|
|
178
|
+
declarations[module] = Object.entries(definitions).filter(([, value]) => isFunctionDefinition(value)).map(([name]) => {
|
|
179
|
+
if (!validExportName(name))
|
|
180
|
+
throw new Error(`Invalid function export name: ${name}`);
|
|
181
|
+
return name;
|
|
182
|
+
});
|
|
183
|
+
const exports = await analysis.functions(source);
|
|
184
|
+
for (const name of declarations[module]) {
|
|
185
|
+
const origin = exports.find(exported => exported.name === name);
|
|
186
|
+
operations.push({ module, name, definition: definitions[name],
|
|
187
|
+
original: origin?.original ?? false });
|
|
188
|
+
}
|
|
189
|
+
if (!declarations[module].length)
|
|
190
|
+
throw new Error(`No query/mutation exports in ${source}`);
|
|
191
|
+
}
|
|
192
|
+
// Reexports are import paths for the same callable, not new remote operations.
|
|
193
|
+
// Prefer the original exported declaration, independently of scan order.
|
|
194
|
+
const canonical = new Map();
|
|
195
|
+
for (const operation of operations.sort((a, b) => Number(b.original) - Number(a.original)
|
|
196
|
+
|| `${a.module}.${a.name}`.localeCompare(`${b.module}.${b.name}`))) {
|
|
197
|
+
if (!canonical.has(operation.definition))
|
|
198
|
+
canonical.set(operation.definition, operation);
|
|
199
|
+
}
|
|
200
|
+
const canonicalDeclarations = Object.create(null);
|
|
201
|
+
for (const [module] of Object.entries(sources))
|
|
202
|
+
canonicalDeclarations[module] = [];
|
|
203
|
+
for (const { module, name } of canonical.values())
|
|
204
|
+
canonicalDeclarations[module].push(name);
|
|
205
|
+
const shapes = await compileFunctionShapes(sources, canonicalDeclarations, analysis);
|
|
206
|
+
const files = new Map();
|
|
207
|
+
for (const [name, contents] of namespaces)
|
|
208
|
+
files.set(name, contents);
|
|
209
|
+
if (options.databaseArtifacts) {
|
|
210
|
+
files.set("_worker.ts", options.databaseArtifacts.worker);
|
|
211
|
+
files.set("_worker.js", options.databaseArtifacts.bundle);
|
|
212
|
+
files.set("_host.js", options.databaseArtifacts.host);
|
|
213
|
+
}
|
|
214
|
+
if (options.databaseSource) {
|
|
215
|
+
files.set("source.ts", options.databaseSource.wrapper);
|
|
216
|
+
files.set("_source.js", options.databaseSource.bundle);
|
|
217
|
+
files.set("_source.d.ts", options.databaseSource.declaration);
|
|
218
|
+
}
|
|
219
|
+
const contracts = [];
|
|
220
|
+
const manifest = Object.create(null);
|
|
221
|
+
const limits = resolveLimits(options.limits);
|
|
222
|
+
let maxOutputBytes = Math.max(16 * 1024 * 1024, limits.inputBytes, limits.outputBytes);
|
|
223
|
+
for (const [module, sourcePath] of Object.entries(moduleSources)) {
|
|
224
|
+
assertModuleName(module);
|
|
225
|
+
const source = resolve(sourcePath);
|
|
226
|
+
const definitions = modules.get(module);
|
|
227
|
+
const localNames = new Map(canonicalDeclarations[module].sort().map((name, index) => [name, `$function${index}`]));
|
|
228
|
+
const lines = [
|
|
229
|
+
header.trimEnd(),
|
|
230
|
+
"",
|
|
231
|
+
...(localNames.size ? [
|
|
232
|
+
`import type * as $definitions from ${JSON.stringify(importPath(dirname(resolve(outDir, `${module}.ts`)), source))}`,
|
|
233
|
+
`import { runtime as $runtime } from ${JSON.stringify(importPath(dirname(resolve(outDir, `${module}.ts`)), resolve(outDir, "runtime.ts")))}`,
|
|
234
|
+
"",
|
|
235
|
+
] : []),
|
|
236
|
+
];
|
|
237
|
+
const bindings = new Set();
|
|
238
|
+
bindings.add("valueCodec");
|
|
239
|
+
let count = 0;
|
|
240
|
+
for (const [name, definition] of Object.entries(definitions).sort(([a], [b]) => a.localeCompare(b))) {
|
|
241
|
+
if (!isFunctionDefinition(definition))
|
|
242
|
+
continue;
|
|
243
|
+
if (!validExportName(name))
|
|
244
|
+
throw new Error(`Invalid function export name: ${name}`);
|
|
245
|
+
const target = canonical.get(definition);
|
|
246
|
+
if (target.module !== module || target.name !== name) {
|
|
247
|
+
lines.push(target.module === module
|
|
248
|
+
? `export { ${localNames.get(target.name)} as ${name} }`
|
|
249
|
+
: `export { ${target.name} as ${name} } from ${JSON.stringify(importPath(dirname(resolve(outDir, `${module}.ts`)), resolve(outDir, `${target.module}.ts`)))}`);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
const binding = definition.kind === "query" ? "queryBinding" : "mutationBinding";
|
|
253
|
+
bindings.add(binding);
|
|
254
|
+
const shape = shapes.get(`${module}.${name}`);
|
|
255
|
+
if (!shape)
|
|
256
|
+
throw new TypeError(`No portable value contract for ${module}.${name}`);
|
|
257
|
+
if (shape.paginated && definition.kind !== "query")
|
|
258
|
+
throw new TypeError(`Paginated results require a query: ${module}.${name}`);
|
|
259
|
+
maxOutputBytes = Math.max(maxOutputBytes, definition.limits?.inputBytes ?? limits.inputBytes, definition.limits?.outputBytes ?? limits.outputBytes);
|
|
260
|
+
manifest[`${module}.${name}`] = { kind: definition.kind, ...shape, ...(definition.limits ? { limits: definition.limits } : {}) };
|
|
261
|
+
const source = definition.replica ? tableBindings.get(definition.replica) : undefined;
|
|
262
|
+
const replica = source ? `, replica: ${JSON.stringify({ table: source.name, columns: source.columns })}` : "";
|
|
263
|
+
contracts.push(`${JSON.stringify(`${module}.${name}`)}: { kind: ${JSON.stringify(definition.kind)}, input: valueCodec(${JSON.stringify(shape.input)}), result: valueCodec(${JSON.stringify(shape.result)})${replica} }`);
|
|
264
|
+
lines.push(`const ${localNames.get(name)} = $${binding}<typeof $definitions.${name}>($runtime, ${JSON.stringify(`${module}.${name}`)}, ${definition.hasInput}, { input: $valueCodec(${JSON.stringify(shape.input)}), result: $valueCodec(${JSON.stringify(shape.result)}) }${shape.paginated ? ", true" : ""})`);
|
|
265
|
+
lines.push(`export { ${localNames.get(name)} as ${name} }`);
|
|
266
|
+
count++;
|
|
267
|
+
}
|
|
268
|
+
if (count)
|
|
269
|
+
lines.splice(3, 0, `import { ${[...bindings]
|
|
270
|
+
.sort()
|
|
271
|
+
.map((binding) => `${binding} as $${binding}`)
|
|
272
|
+
.join(", ")} } from '@hulla/db/internal/client'`);
|
|
273
|
+
files.set(`${module}.ts`, `${lines.join("\n")}\n`);
|
|
274
|
+
}
|
|
275
|
+
const client = options.client === undefined ? undefined : clientConnection(options.client);
|
|
276
|
+
const binding = options.databaseSource ? "import { source as $database } from './source.ts'\n" : options.databaseExport === undefined ? "" : `import { ${validExportName(options.databaseExport) ? options.databaseExport : JSON.stringify(options.databaseExport)} as $database } from ${JSON.stringify(importPath(outDir, resolve(options.schema)))}\n`;
|
|
277
|
+
const fingerprint = new Bun.CryptoHasher("sha256").update(contracts.join("\n")).digest("hex");
|
|
278
|
+
files.set("runtime.ts", `${header}\nimport { ${client ? "createBrowserRuntime" : "createRuntimeScope"}, valueCodec } from '@hulla/db/internal/client'\n${binding}\nexport const contracts = {\n${contracts.join(",\n")}\n} as const\n${client
|
|
279
|
+
? `const browser = createBrowserRuntime(contracts, ${JSON.stringify(client)}, { maxResponseBytes: ${maxOutputBytes + 2 * 1024 * 1024} })\nexport const { runtime, setAuth, setHeaders, dispose } = browser`
|
|
280
|
+
: `export const runtime = createRuntimeScope(${binding ? `contracts, $database, ${JSON.stringify(fingerprint)}` : ""})\nexport const setAuth = runtime.setAuth.bind(runtime)`}\n`);
|
|
281
|
+
if (options.databaseArtifacts) {
|
|
282
|
+
const root = options.databaseArtifacts.rootModule;
|
|
283
|
+
files.set("_client.ts", `${header}
|
|
284
|
+
import { bindClientFunctions, createBrowserRuntime, type BrowserOptions } from '@hulla/db/internal/client'
|
|
285
|
+
import { contracts } from './runtime.ts'
|
|
286
|
+
import * as modules from './index.ts'
|
|
287
|
+
${root ? `const { ${JSON.stringify(root)}: root, ...groups } = modules\nconst references = { ...groups, ...root }` : 'const references = modules'}
|
|
288
|
+
|
|
289
|
+
export function createClient(options: BrowserOptions) {
|
|
290
|
+
const { runtime, ...client } = createBrowserRuntime(contracts, options, { maxResponseBytes: ${maxOutputBytes + 2 * 1024 * 1024} })
|
|
291
|
+
return { ...client, functions: bindClientFunctions(runtime, references) }
|
|
292
|
+
}
|
|
293
|
+
`);
|
|
294
|
+
}
|
|
295
|
+
files.set("functions.json", JSON.stringify({ generatedBy: "@hulla/db", limits: resolveLimits(options.limits), functions: manifest }, null, 2) + "\n");
|
|
296
|
+
// Validate ownership of every output before any write; never replace authored files.
|
|
297
|
+
await mkdir(outDir, { recursive: true });
|
|
298
|
+
for (const name of files.keys()) {
|
|
299
|
+
if (existing.includes(name) &&
|
|
300
|
+
!ownsOutput(name, await Bun.file(resolve(outDir, name)).text())) {
|
|
301
|
+
throw new Error(`Refusing to overwrite an authored file: ${name}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
for (const [name, contents] of files) {
|
|
305
|
+
await mkdir(dirname(resolve(outDir, name)), { recursive: true });
|
|
306
|
+
await Bun.write(resolve(outDir, name), contents);
|
|
307
|
+
}
|
|
308
|
+
// Retire only generator-owned modules, not other files in the directory.
|
|
309
|
+
for (const name of existing) {
|
|
310
|
+
if ((name.endsWith(".ts") || name === "_source.js" || name === "_worker.js" || name === "_host.js") &&
|
|
311
|
+
!files.has(name) &&
|
|
312
|
+
!(await lstat(resolve(outDir, name))).isSymbolicLink() &&
|
|
313
|
+
(await Bun.file(resolve(outDir, name)).text()).startsWith(name === "_worker.js" ? workerBundleHeader : header)) {
|
|
314
|
+
await Bun.file(resolve(outDir, name)).delete();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/** Static ESM reexports preserve callable identity and keep native/handler code out of clients. */
|
|
319
|
+
function namespaceFiles(modules) {
|
|
320
|
+
const directories = new Map([["", new Map()]]);
|
|
321
|
+
const add = (directory, name, target) => {
|
|
322
|
+
let entries = directories.get(directory);
|
|
323
|
+
if (!entries)
|
|
324
|
+
directories.set(directory, entries = new Map());
|
|
325
|
+
const previous = entries.get(name);
|
|
326
|
+
if (previous && previous !== target)
|
|
327
|
+
throw new Error(`Function module and directory conflict at ${directory}${name}`);
|
|
328
|
+
entries.set(name, target);
|
|
329
|
+
};
|
|
330
|
+
for (const module of [...modules].sort()) {
|
|
331
|
+
const parts = module.split("/");
|
|
332
|
+
let directory = "";
|
|
333
|
+
for (let index = 0; index < parts.length; index++) {
|
|
334
|
+
const name = parts[index];
|
|
335
|
+
add(directory, name, index === parts.length - 1 ? `./${name}.ts` : `./${name}/index.ts`);
|
|
336
|
+
if (index < parts.length - 1)
|
|
337
|
+
directory += `${name}/`;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return new Map([...directories].map(([directory, entries]) => [
|
|
341
|
+
`${directory}index.ts`,
|
|
342
|
+
header + "\n" + [...entries].map(([name, target]) => `export * as ${validExportName(name) ? name : JSON.stringify(name)} from ${JSON.stringify(target)}`).join("\n") + "\n",
|
|
343
|
+
]));
|
|
344
|
+
}
|
|
345
|
+
function ownsOutput(name, contents) {
|
|
346
|
+
if (contents.startsWith(schemaHeader))
|
|
347
|
+
throw new Error(`Function output conflicts with a generated schema file: ${name}`);
|
|
348
|
+
if (name === "_worker.js")
|
|
349
|
+
return contents.startsWith(workerBundleHeader);
|
|
350
|
+
if (name !== "functions.json")
|
|
351
|
+
return contents.startsWith(header);
|
|
352
|
+
try {
|
|
353
|
+
return JSON.parse(contents).generatedBy === "@hulla/db";
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { FunctionAnalysis, DatabaseDeclaration } from './function-analysis.ts';
|
|
2
|
+
/** Inspect typed registrations without importing or running application startup code. */
|
|
3
|
+
export declare function captureDatabaseEntry(source: string, analysis: FunctionAnalysis, declarations?: readonly DatabaseDeclaration[]): Promise<Record<string, unknown> | undefined>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { databaseConfiguration } from '@hulla/db/internal/codegen';
|
|
10
|
+
import { factoryEngine } from '@hulla/db/internal/codegen';
|
|
11
|
+
/** Inspect typed registrations without importing or running application startup code. */
|
|
12
|
+
export async function captureDatabaseEntry(source, analysis, declarations) {
|
|
13
|
+
const values = declarations ?? await analysis.databaseDeclarations(source);
|
|
14
|
+
if (!values.length)
|
|
15
|
+
return undefined;
|
|
16
|
+
if ((await analysis.functions(source)).length)
|
|
17
|
+
throw new TypeError('Keep schema/function declarations separate from database initialization');
|
|
18
|
+
const result = Object.create(null);
|
|
19
|
+
for (const value of values) {
|
|
20
|
+
if (!value.schemaExport)
|
|
21
|
+
throw new TypeError('Generation requires an exported schema from a separate inert authoring module');
|
|
22
|
+
if (!value.factoryExport)
|
|
23
|
+
throw new TypeError('Generation requires an imported database adapter factory');
|
|
24
|
+
const implementation = (file) => file.replace(/\.d\.(ts|mts|cts)$/, (_match, extension) => extension === 'mts' ? '.mjs' : extension === 'cts' ? '.cjs' : '.js');
|
|
25
|
+
const schemas = await import(__rewriteRelativeImportExtension(Bun.pathToFileURL(implementation(value.schemaExport.file)).href));
|
|
26
|
+
const adapters = await import(__rewriteRelativeImportExtension(Bun.pathToFileURL(implementation(value.factoryExport.file)).href));
|
|
27
|
+
const engine = factoryEngine(adapters[value.factoryExport.name]);
|
|
28
|
+
const functions = value.functions?.kind === 'glob' ? value.functions.pattern : value.functions ? async () => ({}) : undefined;
|
|
29
|
+
result[value.exportName] = databaseConfiguration(engine, { schema: schemas[value.schemaExport.name], ...(functions === undefined ? {} : { functions }) });
|
|
30
|
+
}
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type GenerationOptions } from "./codegen.ts";
|
|
2
|
+
export { exportedDatabase } from "@hulla/db/internal/codegen";
|
|
3
|
+
/** Generate caller modules next to an explicit database entrypoint, without connecting. */
|
|
4
|
+
export declare function generateDatabase(entrypoint: string, options?: Pick<GenerationOptions, "functions" | "moduleRoot" | "limits">): Promise<void>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { basename, dirname, extname, relative, resolve, sep } from "node:path";
|
|
2
|
+
import { generateFunctions } from "./codegen.js";
|
|
3
|
+
import { compileWorker } from "./worker-codegen.js";
|
|
4
|
+
import { FunctionAnalysis } from "./function-analysis.js";
|
|
5
|
+
import { mkdir } from "node:fs/promises";
|
|
6
|
+
import { checkGeneratedDirectory } from "./schema-codegen.js";
|
|
7
|
+
import { databaseEntry } from "@hulla/db/internal/codegen";
|
|
8
|
+
import { catalogueImports, databaseFunctions } from "./database-function-discovery.js";
|
|
9
|
+
import { generateSource } from "./source-codegen.js";
|
|
10
|
+
import { captureDatabaseEntry } from "./database-capture.js";
|
|
11
|
+
import { generateHost } from "./host-codegen.js";
|
|
12
|
+
export { exportedDatabase } from "@hulla/db/internal/codegen";
|
|
13
|
+
/** Generate caller modules next to an explicit database entrypoint, without connecting. */
|
|
14
|
+
export async function generateDatabase(entrypoint, options = {}) {
|
|
15
|
+
const source = resolve(entrypoint);
|
|
16
|
+
const analysis = new FunctionAnalysis();
|
|
17
|
+
try {
|
|
18
|
+
await analysis.open([source]);
|
|
19
|
+
const declarations = await analysis.databaseDeclarations(source);
|
|
20
|
+
const allowed = catalogueImports(analysis, declarations);
|
|
21
|
+
const exports = await captureDatabaseEntry(source, analysis, declarations) ?? {};
|
|
22
|
+
const entry = databaseEntry(exports);
|
|
23
|
+
if (!entry)
|
|
24
|
+
throw new TypeError("Database entrypoint must export exactly one database instance; found 0");
|
|
25
|
+
const { database, name: databaseExport } = entry;
|
|
26
|
+
const namespace = basename(source, extname(source));
|
|
27
|
+
const outDir = resolve(dirname(source), "_generated", namespace);
|
|
28
|
+
const { modules, rootModule } = await databaseFunctions(database, source, outDir, declarations, options, analysis);
|
|
29
|
+
const importPath = (path) => { const value = relative(outDir, path).split(sep).join("/"); return value.startsWith(".") ? value : `./${value}`; };
|
|
30
|
+
const entries = Object.entries(modules);
|
|
31
|
+
await checkGeneratedDirectory(outDir);
|
|
32
|
+
await mkdir(outDir, { recursive: true });
|
|
33
|
+
const shared = await generateSource(source, databaseExport, outDir, analysis, database.engine.name);
|
|
34
|
+
const schemaExport = declarations.find(value => value.exportName === databaseExport)?.schemaExport;
|
|
35
|
+
if (!schemaExport)
|
|
36
|
+
throw new TypeError('Generation requires an exported schema from a separate inert authoring module');
|
|
37
|
+
const schemaImport = `import { ${JSON.stringify(schemaExport.name)} as schema } from ${JSON.stringify(importPath(schemaExport.file))}`;
|
|
38
|
+
const worker = `// Generated by @hulla/db. Do not edit.\n\n${schemaImport}\nimport { installWorker } from '@hulla/db/internal/worker'\n${entries.map(([, path], index) => `import * as module${index} from ${JSON.stringify(importPath(path))}`).join("\n")}\n\ninstallWorker({ schema, modules: {\n${entries.map(([name], index) => ` ${JSON.stringify(name)}: module${index},`).join("\n")}\n} })\n`;
|
|
39
|
+
const bundle = await compileWorker(resolve(outDir, "_worker.ts"), worker, allowed);
|
|
40
|
+
const host = await generateHost(source, databaseExport, declarations);
|
|
41
|
+
await generateFunctions({ ...(options.limits === undefined ? {} : { limits: options.limits }), database, databaseExport, schema: source, outDir, modules, databaseArtifacts: { worker, bundle, host, rootModule }, databaseSource: shared }, analysis);
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
await analysis.close();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type GenerationOptions } from "./codegen.ts";
|
|
2
|
+
import type { DatabaseConfiguration } from "@hulla/db/internal/codegen";
|
|
3
|
+
import { FunctionAnalysis, type DatabaseDeclaration } from "./function-analysis.ts";
|
|
4
|
+
import { type FunctionImportCheck } from "./worker-codegen.ts";
|
|
5
|
+
export declare function catalogueImports(analysis: FunctionAnalysis, declarations?: readonly DatabaseDeclaration[]): FunctionImportCheck;
|
|
6
|
+
/** Resolve explicit selectors before executing selected declaration modules. */
|
|
7
|
+
export declare function databaseFunctions(database: DatabaseConfiguration, source: string, outDir: string, declarations: readonly DatabaseDeclaration[], options: Pick<GenerationOptions, "functions" | "moduleRoot">, analysis: FunctionAnalysis): Promise<{
|
|
8
|
+
modules: Readonly<Record<string, string>>;
|
|
9
|
+
rootModule: string | undefined;
|
|
10
|
+
}>;
|