@hulla/db-cli 0.0.0-stage → 0.3.4

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,212 @@
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 { lstat, mkdir } from "node:fs/promises";
10
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
11
+ import { validExportName } from "./names.js";
12
+ import { compileSchema, } from "@hulla/db/schema";
13
+ const header = "// Generated schema by @hulla/db. Do not edit.\n";
14
+ const scalarNames = {
15
+ string: "String",
16
+ boolean: "Boolean",
17
+ int64: "Int64",
18
+ uuid: "Uuid",
19
+ float64: "Float64",
20
+ json: "Json",
21
+ date: "Date",
22
+ timestamp: "Timestamp",
23
+ localTimestamp: "LocalTimestamp",
24
+ };
25
+ function rustString(value) {
26
+ if (/[\uD800-\uDFFF]/u.test(value))
27
+ throw new TypeError("Rust schema strings must contain valid Unicode scalars");
28
+ return `"${[...value]
29
+ .map((char) => {
30
+ if (char === '"' || char === "\\")
31
+ return `\\${char}`;
32
+ const code = char.codePointAt(0);
33
+ return code < 32 || code === 127 ? `\\u{${code.toString(16)}}` : char;
34
+ })
35
+ .join("")}"`;
36
+ }
37
+ function rustValue(scalar, value) {
38
+ if (value === null)
39
+ return "hulladb_schema::Value::Null";
40
+ if (scalar === "json")
41
+ return `hulladb_schema::Value::json(${rustString(JSON.stringify(value))}).expect("validated JSON default")`;
42
+ if (scalar === "float64")
43
+ return `hulladb_schema::Value::float64(${value}f64).expect("finite number default")`;
44
+ if (["date", "timestamp", "localTimestamp"].includes(scalar))
45
+ return `hulladb_schema::Value::${scalarNames[scalar]}(${rustString(value)}.into())`;
46
+ if (scalar === "string")
47
+ return `hulladb_schema::Value::String(${rustString(value)}.into())`;
48
+ if (scalar === "boolean")
49
+ return `hulladb_schema::Value::Boolean(${value})`;
50
+ if (scalar === "int64")
51
+ return `hulladb_schema::Value::Int64(${value}i64)`;
52
+ const bytes = value.replaceAll("-", "").match(/../g);
53
+ return `hulladb_schema::Value::Uuid([${bytes.map((byte) => `0x${byte}`).join(", ")}])`;
54
+ }
55
+ function rustJsonShape(shape) {
56
+ const prefix = "hulladb_schema::JsonShape::";
57
+ switch (shape.kind) {
58
+ case "any": return prefix + "Any";
59
+ case "string": return prefix + "String";
60
+ case "boolean": return prefix + "Boolean";
61
+ case "number": return prefix + "Number";
62
+ case "array": return `${prefix}Array { item: Box::new(${rustJsonShape(shape.item)}) }`;
63
+ case "nullable": return `${prefix}Nullable { inner: Box::new(${rustJsonShape(shape.inner)}) }`;
64
+ case "object": return `${prefix}Object { fields: [${Object.entries(shape.fields).map(([key, field]) => `(${rustString(key)}.into(), hulladb_schema::JsonProperty { shape: ${rustJsonShape(field.shape)}, optional: ${field.optional} })`).join(", ")}].into() }`;
65
+ }
66
+ }
67
+ function rustGenerator(generation) {
68
+ if (typeof generation === "object")
69
+ return `hulladb_schema::KeyGeneration::Custom { handler: ${rustString(generation.handler)}.into(), output_type: hulladb_schema::ScalarType::${scalarNames[generation.outputType]} }`;
70
+ return `hulladb_schema::KeyGeneration::${generation === "none" ? "None" : generation === "uuidV4" ? "UuidV4" : "UuidV7"}`;
71
+ }
72
+ /** Emit native declarations, then let Rust normalize through its existing contract. */
73
+ export function generateRustSchema(schema) {
74
+ const tables = compileSchema(schema);
75
+ const lines = [
76
+ header.trimEnd(),
77
+ "",
78
+ "pub fn schema() -> Result<hulladb_schema::SchemaContract, hulladb_schema::SchemaError> {",
79
+ " let tables = vec![",
80
+ ];
81
+ for (const table of tables) {
82
+ lines.push(" {", ` let mut table = hulladb_schema::TableDeclaration::new(${rustString(table.name)}, vec![`);
83
+ for (const [name, field] of Object.entries(table.fields)) {
84
+ const boundScalar = field.scalar === "string" ? "int64" : field.scalar;
85
+ const minimum = field.constraints?.min;
86
+ const maximum = field.constraints?.max;
87
+ const constraints = `hulladb_schema::FieldConstraints { min: ${minimum === undefined ? "None" : `Some(${rustValue(boundScalar, minimum)})`}, max: ${maximum === undefined ? "None" : `Some(${rustValue(boundScalar, maximum)})`}, one_of: vec![${(field.constraints?.oneOf ?? []).map(value => rustValue(field.scalar, value)).join(", ")}] }`;
88
+ lines.push(` hulladb_schema::FieldDefinition { name: ${rustString(name)}.into(), scalar_type: hulladb_schema::ScalarType::${scalarNames[field.scalar]}, nullable: ${field.allowsNull}, precision: ${field.precision === undefined ? "None" : `Some(${field.precision})`}, json_shape: ${field.jsonShape ? `Some(${rustJsonShape(field.jsonShape)})` : "None"}, default: ${field.hasDefault ? `Some(${rustValue(field.scalar, field.encode(field.defaultValue))})` : "None"}, constraints: ${constraints} },`);
89
+ }
90
+ lines.push(" ]);", ` table.primary_key = Some(${rustString(table.primaryKey)}.into());`, ` table.key_generation = Some(${rustGenerator(table.keyGeneration)});`, ` table.insert_key_policy = hulladb_schema::InsertKeyPolicy::${table.insertKeyPolicy === "generatedOnly" ? "GeneratedOnly" : "AllowExplicit"};`);
91
+ for (const [name, constraint] of Object.entries(table.unique)) {
92
+ lines.push(` table.unique_constraints.push(hulladb_schema::UniqueConstraintDeclaration { name: ${rustString(name)}.into(), fields: vec![${constraint.fields.map((field) => `${rustString(field)}.into()`).join(", ")}], null_policy: Some(hulladb_schema::UniqueNullPolicy::${constraint.nulls === "distinct" ? "Distinct" : "NotDistinct"}) });`);
93
+ }
94
+ for (const index of table.indexes)
95
+ lines.push(` table.indexes.push(hulladb_schema::IndexDeclaration { name: ${rustString(index.name)}.into(), fields: vec![${index.fields.map(field => `${rustString(field)}.into()`).join(", ")}] });`);
96
+ for (const check of table.checks)
97
+ lines.push(` table.checks.push(hulladb_schema::CheckDefinition { name: ${rustString(check.name)}.into(), parts: vec![${check.parts.map(part => `${rustString(part)}.into()`).join(", ")}], operands: vec![${check.operands.map(operand => "field" in operand ? `hulladb_schema::CheckOperand::Field(${rustString(operand.field)}.into())` : `hulladb_schema::CheckOperand::Value(${rustValue(typeof operand.value === "bigint" ? "int64" : typeof operand.value === "number" ? "float64" : typeof operand.value === "boolean" ? "boolean" : "string", operand.value)})`).join(", ")}] });`);
98
+ lines.push(" table", " },");
99
+ }
100
+ lines.push(" ];", " let mut schema = hulladb_schema::SchemaDeclaration::new(tables);", ` schema.default_uuid_generation = hulladb_schema::UuidGeneration::${schema.defaultUuidGeneration === "v4" ? "V4" : "V7"};`);
101
+ for (const table of tables)
102
+ for (const [name, field] of Object.entries(table.fields)) {
103
+ if (typeof field.target === "string")
104
+ lines.push(` { let mut reference = hulladb_schema::ReferenceDeclaration::new(${rustString(table.name)}, ${rustString(name)}, ${rustString(field.target)}); reference.on_delete = hulladb_schema::ReferenceOnDelete::${{ restrict: "Restrict", cascade: "Cascade", setNull: "SetNull" }[field.onDelete ?? "restrict"]}; schema.references.push(reference); }`);
105
+ }
106
+ lines.push(" schema.normalize()", "}", "");
107
+ return lines.join("\n");
108
+ }
109
+ export async function generateSchema(options) {
110
+ const source = resolve(options.schema);
111
+ const outDir = resolve(options.outDir);
112
+ const fromOutput = relative(outDir, source);
113
+ if (!fromOutput.startsWith(`..${sep}`) && !isAbsolute(fromOutput))
114
+ throw new Error("Schema definitions must be outside the generated output directory");
115
+ const { default: schema } = (await import(__rewriteRelativeImportExtension(Bun.pathToFileURL(source).href)));
116
+ const compiled = compileSchema(schema);
117
+ const rust = options.rustOutput === undefined ? undefined : generateRustSchema(schema);
118
+ let sourceImport = relative(outDir, source).split(sep).join("/");
119
+ if (!sourceImport.startsWith("."))
120
+ sourceImport = `./${sourceImport}`;
121
+ const referenceTargets = Object.fromEntries(compiled.map(table => [table.name, Object.fromEntries(Object.entries(table.fields).flatMap(([name, field]) => field.target === undefined ? [] : [[name, field.target]]))]));
122
+ const types = `${header}\nimport type schema from ${JSON.stringify(sourceImport)}
123
+ import type { ResolveReferences, Row as SchemaRow, Insert as SchemaInsert, Patch as SchemaPatch, Id as SchemaId } from '@hulla/db/schema'
124
+ import type { ReadDatabase as SchemaReadDatabase, WriteDatabase as SchemaWriteDatabase, ConnectedDatabase as SchemaDatabase } from '@hulla/db'
125
+
126
+ export type Schema = ResolveReferences<typeof schema, ${JSON.stringify(referenceTargets)}>
127
+ export type Database = SchemaDatabase<Schema>
128
+ export type ReadDatabase = SchemaReadDatabase<Schema>
129
+ export type WriteDatabase = SchemaWriteDatabase<Schema>
130
+ export type Tables = keyof Schema['tables']
131
+ export type Row<T extends Tables> = SchemaRow<Schema, T>
132
+ export type Insert<T extends Tables> = SchemaInsert<Schema, T>
133
+ export type Patch<T extends Tables> = SchemaPatch<Schema, T>
134
+ export type Id<T extends Tables> = SchemaId<Schema, T>
135
+ `;
136
+ let configImport;
137
+ if (options.config !== undefined) {
138
+ configImport = relative(outDir, resolve(options.config)).split(sep).join("/");
139
+ if (!configImport.startsWith("."))
140
+ configImport = `./${configImport}`;
141
+ }
142
+ const identityImports = configImport === undefined ? "" : `import type config from ${JSON.stringify(configImport)}\nimport type { ConfigIdentity } from '@hulla/db/config'\n`;
143
+ const functions = `${header}\nimport type { Schema } from './types'
144
+ import type { QueryContext, MutationContext } from '@hulla/db'
145
+ import { defineFunctions } from '@hulla/db/internal/functions'
146
+ ${identityImports}
147
+ export const { query, mutation } = defineFunctions<QueryContext<Schema${configImport === undefined ? "" : ", ConfigIdentity<typeof config>"}>, MutationContext<Schema${configImport === undefined ? "" : ", ConfigIdentity<typeof config>"}>>()
148
+ `;
149
+ const tableMetadata = `JSON.parse(${JSON.stringify(JSON.stringify(Object.fromEntries(compiled.map(table => [table.name, Object.fromEntries(Object.entries(table.fields).map(([name, field]) => [name, { ...(field.jsonShape ? { jsonShape: field.jsonShape } : {}) }]))]))))})`;
150
+ const tableReferences = `${header}\nimport type { Schema } from './types'
151
+ import { createTables } from '@hulla/db/schema'
152
+
153
+ const $tables = createTables<Schema>(${tableMetadata})
154
+ export default $tables
155
+ ${compiled.filter(table => validExportName(table.name)).map((table, index) => `const $table${index} = $tables[${JSON.stringify(table.name)}]\nexport { $table${index} as ${table.name} }`).join("\n")}
156
+ `;
157
+ const outputs = new Map([
158
+ [resolve(outDir, "types.ts"), types],
159
+ [resolve(outDir, "functions.ts"), functions],
160
+ [resolve(outDir, "tables.ts"), tableReferences],
161
+ ]);
162
+ if (options.rustOutput !== undefined)
163
+ outputs.set(resolve(options.rustOutput), rust);
164
+ if (outputs.size !== (options.rustOutput === undefined ? 3 : 4))
165
+ throw new Error("Schema outputs must use distinct paths");
166
+ // Check every destination before writing; never replace authored code.
167
+ await checkGeneratedDirectory(outDir);
168
+ for (const path of outputs.keys()) {
169
+ await checkGeneratedDirectory(dirname(path));
170
+ const info = await lstat(path).catch((error) => {
171
+ if (error.code === "ENOENT")
172
+ return undefined;
173
+ throw error;
174
+ });
175
+ if (info && (!info.isFile() || info.isSymbolicLink()))
176
+ throw new Error(`Refusing to overwrite an authored path: ${path}`);
177
+ let existing;
178
+ try {
179
+ existing = await Bun.file(path).text();
180
+ }
181
+ catch (error) {
182
+ if (error.code === "ENOENT")
183
+ continue;
184
+ throw error;
185
+ }
186
+ if (existing.startsWith("// Generated by @hulla/db. Do not edit.\n"))
187
+ throw new Error(`Schema output conflicts with a generated function file: ${path}`);
188
+ if (!existing.startsWith(header))
189
+ throw new Error(`Refusing to overwrite an authored file: ${path}`);
190
+ }
191
+ for (const [path, content] of outputs) {
192
+ await mkdir(dirname(path), { recursive: true });
193
+ await Bun.write(path, content);
194
+ }
195
+ }
196
+ /** Check the requested directory and missing ancestors before recursive mkdir. */
197
+ export async function checkGeneratedDirectory(directory) {
198
+ const absolute = resolve(directory);
199
+ const info = await lstat(absolute).catch((error) => {
200
+ if (error.code === "ENOENT")
201
+ return undefined;
202
+ throw error;
203
+ });
204
+ if (info) {
205
+ if (!info.isDirectory() || info.isSymbolicLink())
206
+ throw new Error(`Refusing to overwrite an authored path: ${absolute}`);
207
+ return;
208
+ }
209
+ const parent = dirname(absolute);
210
+ if (parent !== absolute)
211
+ await checkGeneratedDirectory(parent);
212
+ }
@@ -0,0 +1 @@
1
+ export declare function sdkDeclarations(module: string): string[];
@@ -0,0 +1,4 @@
1
+ const sdk = new URL("../", import.meta.resolve("@hulla/db"));
2
+ export function sdkDeclarations(module) {
3
+ return [`src/${module}.ts`, `dist/${module}.d.ts`].map(path => Bun.fileURLToPath(new URL(path, sdk)));
4
+ }
@@ -0,0 +1,6 @@
1
+ /** Explicit setup for a user-selected gitignore-syntax file; never detects a formatter. */
2
+ export declare function setupGeneratedIgnore(configPath: string, ignoreFile: string): Promise<{
3
+ path: string;
4
+ pattern: string;
5
+ changed: boolean;
6
+ }>;
@@ -0,0 +1,35 @@
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 { lstat, mkdir } from "node:fs/promises";
10
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
11
+ import { defineConfig } from "@hulla/db/config";
12
+ /** Explicit setup for a user-selected gitignore-syntax file; never detects a formatter. */
13
+ export async function setupGeneratedIgnore(configPath, ignoreFile) {
14
+ const source = resolve(configPath);
15
+ const config = defineConfig((await import(__rewriteRelativeImportExtension(Bun.pathToFileURL(source).href))).default);
16
+ const output = resolve(dirname(resolve(dirname(source), config.schema ?? "db/schema.ts")), "_generated");
17
+ const path = resolve(ignoreFile);
18
+ if (/\.(?:jsonc?|[cm]?[jt]s)$/i.test(path))
19
+ throw new Error("--ignore-file expects gitignore syntax, not a JSON or source-code configuration file.");
20
+ const fromIgnore = relative(dirname(path), output);
21
+ if (!fromIgnore || fromIgnore === ".." || fromIgnore.startsWith(`..${sep}`) || isAbsolute(fromIgnore))
22
+ throw new Error("Choose an ignore file in an ancestor of the generated output directory.");
23
+ const info = await lstat(path).catch((error) => { if (error.code === "ENOENT")
24
+ return undefined; throw error; });
25
+ if (info && (!info.isFile() || info.isSymbolicLink()))
26
+ throw new Error(`Ignore path must be a regular file: ${path}`);
27
+ const pattern = "/" + fromIgnore.split(sep).join("/").replace(/[\\*?\[\]]/g, "\\$&") + "/";
28
+ const before = info ? await Bun.file(path).text() : "";
29
+ if (before.split(/\r?\n/).some(line => line.trim() === pattern))
30
+ return { path, pattern, changed: false };
31
+ const newline = before.includes("\r\n") ? "\r\n" : "\n";
32
+ await mkdir(dirname(path), { recursive: true });
33
+ await Bun.write(path, before + (before && !before.endsWith("\n") ? newline : "") + `# Managed database output (@hulla/db)${newline}${pattern}${newline}`);
34
+ return { path, pattern, changed: true };
35
+ }
@@ -0,0 +1,7 @@
1
+ import type { FunctionAnalysis } from './function-analysis.ts';
2
+ /** Bundle only the inert schema/codecs. Application startup and handlers stay outside the graph. */
3
+ export declare function generateSource(source: string, exported: string, outDir: string, analysis: FunctionAnalysis, engine: string): Promise<{
4
+ wrapper: string;
5
+ bundle: string;
6
+ declaration: string;
7
+ }>;
@@ -0,0 +1,46 @@
1
+ import { dirname, relative, resolve, sep } from 'node:path';
2
+ import { runtimeExportConditions } from './runtime-conditions.js';
3
+ import { isImportDeclaration, isExportDeclaration, isStringLiteral } from './development-compiler.js';
4
+ const header = '// Generated by @hulla/db. Do not edit.\n';
5
+ /** Bundle only the inert schema/codecs. Application startup and handlers stay outside the graph. */
6
+ export async function generateSource(source, exported, outDir, analysis, engine) {
7
+ const declaration = (await analysis.databaseDeclarations(source)).find(value => value.exportName === exported);
8
+ const schema = declaration?.schemaExport;
9
+ if (!schema)
10
+ throw new TypeError('Generation requires a schema exported from a separate inert authoring module');
11
+ const core = new Map(['@hulla/db', '@hulla/db/schema', '@hulla/db/zod'].map(specifier => [Bun.fileURLToPath(import.meta.resolve(specifier)), specifier]));
12
+ const build = await Bun.build({
13
+ entrypoints: ['__hulla_shared_source__'], target: 'browser', format: 'esm', packages: 'external', conditions: runtimeExportConditions(), throw: false,
14
+ plugins: [{ name: 'hulla-shared-source', setup(builder) {
15
+ builder.onResolve({ filter: /^__hulla_shared_source__$/ }, () => ({ path: resolve(outDir, '_source-entry.ts'), namespace: 'hulla-source' }));
16
+ builder.onLoad({ filter: /.*/, namespace: 'hulla-source' }, () => ({ contents: `import { ${JSON.stringify(schema.name)} as schema } from ${JSON.stringify(schema.file)}\nimport { schemaIdentity } from '@hulla/db/internal/engine'\nexport default schemaIdentity(schema)\nexport const engine = ${JSON.stringify(engine)}`, loader: 'ts', resolveDir: dirname(source) }));
17
+ builder.onLoad({ filter: /\.[cm]?[tj]sx?$/, namespace: 'file' }, async (args) => {
18
+ if (args.path.includes(`${sep}node_modules${sep}`))
19
+ return undefined;
20
+ const project = await analysis.project(args.path);
21
+ const file = await project.program.getSourceFile(args.path);
22
+ const patches = [];
23
+ for (const statement of file?.statements ?? []) {
24
+ if ((!isImportDeclaration(statement) && !isExportDeclaration(statement)) || !statement.moduleSpecifier || !isStringLiteral(statement.moduleSpecifier) || !statement.moduleSpecifier.text.startsWith('.'))
25
+ continue;
26
+ const external = core.get(Bun.resolveSync(statement.moduleSpecifier.text, dirname(args.path)));
27
+ if (external)
28
+ patches.push({ start: statement.moduleSpecifier.pos, end: statement.moduleSpecifier.end, text: JSON.stringify(external) });
29
+ }
30
+ if (!patches.length)
31
+ return undefined;
32
+ let contents = await Bun.file(args.path).text();
33
+ for (const patch of patches.sort((a, b) => b.start - a.start))
34
+ contents = contents.slice(0, patch.start) + patch.text + contents.slice(patch.end);
35
+ return { contents, loader: /\.[cm]?jsx?$/.test(args.path) ? 'jsx' : 'tsx', resolveDir: dirname(args.path) };
36
+ });
37
+ } }],
38
+ });
39
+ if (!build.success || build.outputs.length !== 1)
40
+ throw new TypeError(`Cannot generate shared schema source:\n${build.logs.map(log => log.message).join('\n')}`);
41
+ const path = relative(outDir, source).split(sep).join('/');
42
+ const specifier = path.startsWith('.') ? path : `./${path}`;
43
+ const wrapper = `${header}\nexport { default as source } from './_source.js'\n`;
44
+ const types = `${header}\nimport type { DatabaseSource } from '@hulla/db'\nimport type { ${JSON.stringify(exported)} as Original } from ${JSON.stringify(specifier)}\n\ndeclare const source: DatabaseSource<typeof Original.schema>\nexport default source\nexport declare const engine: ${JSON.stringify(engine)}\n`;
45
+ return { wrapper, bundle: header + await build.outputs[0].text(), declaration: types };
46
+ }
@@ -0,0 +1,8 @@
1
+ import type { StudioFlags } from "./cli-options.ts";
2
+ export interface StudioService {
3
+ readonly url: string;
4
+ readonly closed: Promise<void>;
5
+ close(): Promise<void>;
6
+ }
7
+ /** Resolve from the application so the Studio package remains entirely optional. */
8
+ export declare function startStudio(configPath: string, options: StudioFlags): Promise<StudioService>;
package/dist/studio.js ADDED
@@ -0,0 +1,28 @@
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 { createRequire } from "node:module";
10
+ import { resolve } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { resolveDatabaseConnection } from "@hulla/db-postgres/server";
13
+ import { loadHostConfiguration } from "@hulla/db-postgres/internal/host";
14
+ /** Resolve from the application so the Studio package remains entirely optional. */
15
+ export async function startStudio(configPath, options) {
16
+ const path = resolve(configPath);
17
+ let entry;
18
+ try {
19
+ entry = createRequire(path).resolve("@hulla/db-studio");
20
+ }
21
+ catch {
22
+ throw new Error("Studio requires @hulla/db-studio. Install it alongside @hulla/db to use hulla-db studio or dev --studio.");
23
+ }
24
+ const { config, schema } = await loadHostConfiguration(path);
25
+ const studio = await import(__rewriteRelativeImportExtension(pathToFileURL(entry).href));
26
+ return studio.startStudio({ schema, connection: resolveDatabaseConnection(config.database.server, path), limits: config.limits,
27
+ accessToken: process.env.HULLADB_STUDIO_TOKEN, ...options });
28
+ }
@@ -0,0 +1,4 @@
1
+ export declare const workerBundleHeader = "// Generated restricted worker by @hulla/db. Do not edit.\n";
2
+ /** Build trusted source into one portable script. The execution engine has no loader. */
3
+ export type FunctionImportCheck = (importer: string, specifier: string) => Promise<boolean>;
4
+ export declare function compileWorker(entrypoint: string, contents?: string, functionImports?: ReadonlySet<string> | FunctionImportCheck): Promise<string>;
@@ -0,0 +1,51 @@
1
+ import { builtinModules } from "node:module";
2
+ import { runtimeExportConditions } from "./runtime-conditions.js";
3
+ import { dirname, resolve } from "node:path";
4
+ export const workerBundleHeader = "// Generated restricted worker by @hulla/db. Do not edit.\n";
5
+ const escapePattern = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6
+ const forbiddenImports = new RegExp(`^(?:[a-zA-Z][\\w+.-]*:|bun(?:/|$)|(?:${builtinModules.map(escapePattern).join("|")})$)|\\.(?:node|so|dylib)$`);
7
+ function unsupportedImport(path, importer) {
8
+ return new Error(`Unsupported declaration import ${JSON.stringify(path)} in ${importer}. Queries and mutations support bundled computation/validation code; move server I/O to ordinary server code.`);
9
+ }
10
+ export async function compileWorker(entrypoint, contents, functionImports = new Set()) {
11
+ const build = await Bun.build({
12
+ conditions: ["hulladb-worker", ...runtimeExportConditions()],
13
+ entrypoints: [contents === undefined ? entrypoint : "__hulla_virtual_worker__"], target: "browser", format: "iife", throw: false, metafile: true,
14
+ plugins: [{
15
+ name: "hulla-declaration-capabilities",
16
+ setup(builder) {
17
+ if (contents !== undefined) {
18
+ builder.onResolve({ filter: /^__hulla_virtual_worker__$/ }, () => ({ path: entrypoint, namespace: "hulla-worker" }));
19
+ builder.onLoad({ filter: /.*/, namespace: "hulla-worker" }, () => ({ contents, loader: "ts", resolveDir: dirname(entrypoint) }));
20
+ }
21
+ // Leave ordinary resolution to Bun. A wildcard onResolve callback can
22
+ // corrupt reexported namespace bindings in Bun 1.4, including Zod's.
23
+ builder.onResolve({ filter: forbiddenImports }, args => {
24
+ throw unsupportedImport(args.path, args.importer);
25
+ });
26
+ },
27
+ }],
28
+ });
29
+ if (!build.success)
30
+ throw new Error(`Cannot bundle database declarations:\n${build.logs.map(log => log.message).join("\n")}`);
31
+ if (build.outputs.length !== 1 || !build.metafile)
32
+ throw new Error("Database declarations must compile to one self-contained script");
33
+ // Inspect dynamic imports without intercepting library namespace resolution.
34
+ // Bun labels tree-shaken relative imports as external in input metadata, even
35
+ // when nothing is external in the emitted bundle. Check the output below for
36
+ // surviving external imports. The native runtime also denies dynamic imports.
37
+ for (const [importer, input] of Object.entries(build.metafile.inputs)) {
38
+ for (const dependency of input.imports) {
39
+ if (dependency.kind === "dynamic-import") {
40
+ const specifier = dependency.original ?? dependency.path;
41
+ if (typeof functionImports === "function" ? await functionImports(resolve(importer), specifier) : functionImports.has(JSON.stringify([resolve(importer), specifier])))
42
+ continue;
43
+ throw unsupportedImport(dependency.original ?? dependency.path, importer);
44
+ }
45
+ }
46
+ }
47
+ if (Object.values(build.metafile.outputs).some(output => output.imports.length !== 0)) {
48
+ throw new Error("Database declarations must compile to one self-contained script");
49
+ }
50
+ return workerBundleHeader + await build.outputs[0].text();
51
+ }
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@hulla/db-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.4",
4
+ "type": "module",
5
+ "description": "Build, generate and run local development for @hulla/db",
6
+ "exports": {
7
+ "./build": {
8
+ "types": "./dist/build.d.ts",
9
+ "default": "./dist/build.js"
10
+ },
11
+ "./codegen": {
12
+ "types": "./dist/codegen.d.ts",
13
+ "default": "./dist/codegen.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "peerDependencies": {
22
+ "@hulla/db": "^0.3.4",
23
+ "@hulla/db-postgres": "^0.3.4",
24
+ "@hulla/db-studio": "^0.3.4"
25
+ },
26
+ "engines": {
27
+ "node": ">=22.18.0"
28
+ },
29
+ "license": "MIT",
30
+ "author": {
31
+ "name": "Samuel Hulla",
32
+ "url": "https://hulla.dev"
33
+ },
34
+ "homepage": "https://github.com/hulladev/db#readme",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/hulladev/db.git",
38
+ "directory": "packages/db-cli"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/hulladev/db/issues"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "registry": "https://registry.npmjs.org/"
46
+ },
47
+ "bin": {
48
+ "hulla-db": "./dist/cli.js"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "@hulla/db-postgres": {
52
+ "optional": true
53
+ },
54
+ "@hulla/db-studio": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "dependencies": {
59
+ "typescript": "7.0.2"
60
+ }
61
+ }