@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.
- 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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Samuel Hulla
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hulla/db-cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Install this development dependency alongside `@hulla/db` for schema and client
|
|
4
|
+
generation, build integration, and local provisioning. For PostgreSQL commands,
|
|
5
|
+
also install `@hulla/db-postgres`.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install --save-dev @hulla/db-cli
|
|
9
|
+
npx hulla-db generate db/server.ts
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Generation uses Bun and the CLI's pinned TypeScript dependency. Install Bun on
|
|
13
|
+
your development and build machines. Node can launch the command when `bun` is
|
|
14
|
+
on PATH.
|
|
15
|
+
|
|
16
|
+
With no PostgreSQL URL configured, `hulla-db dev` downloads and caches a verified
|
|
17
|
+
PostgreSQL build on first use. SDK releases that use the same build share its
|
|
18
|
+
cached archive. Managed PostgreSQL supports macOS arm64 and Linux
|
|
19
|
+
x64 with glibc. Set the server URL or `DATABASE_URL` to use an existing database.
|
|
20
|
+
Deploy the generated client or server artifacts with their runtime packages.
|
|
21
|
+
See the [deployment guide](https://github.com/hulladev/db/blob/main/docs/deployment.md).
|
package/dist/build.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
interface TransformContext {
|
|
2
|
+
parse(code: string): unknown;
|
|
3
|
+
addWatchFile?(file: string): void;
|
|
4
|
+
}
|
|
5
|
+
interface ViteServer {
|
|
6
|
+
watcher: {
|
|
7
|
+
on(event: string, listener: (file: string) => void): unknown;
|
|
8
|
+
off(event: string, listener: (file: string) => void): unknown;
|
|
9
|
+
};
|
|
10
|
+
moduleGraph: {
|
|
11
|
+
getModuleById(id: string): unknown;
|
|
12
|
+
invalidateModule(module: never): void;
|
|
13
|
+
};
|
|
14
|
+
ws: {
|
|
15
|
+
send(message: {
|
|
16
|
+
type: 'full-reload';
|
|
17
|
+
}): void;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
type Loader = 'ts' | 'tsx' | 'js' | 'jsx';
|
|
21
|
+
interface BunBuilder {
|
|
22
|
+
onLoad(options: {
|
|
23
|
+
filter: RegExp;
|
|
24
|
+
namespace?: string;
|
|
25
|
+
}, callback: (args: {
|
|
26
|
+
path: string;
|
|
27
|
+
}) => Promise<{
|
|
28
|
+
contents: string;
|
|
29
|
+
loader: Loader;
|
|
30
|
+
} | undefined>): void;
|
|
31
|
+
}
|
|
32
|
+
export interface FunctionGlobsPlugin {
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly enforce: 'post';
|
|
35
|
+
transform(this: TransformContext, code: string, id: string): Promise<{
|
|
36
|
+
code: string;
|
|
37
|
+
map: null;
|
|
38
|
+
} | null>;
|
|
39
|
+
configureServer(server: ViteServer): void;
|
|
40
|
+
closeBundle(): void;
|
|
41
|
+
setup(build: BunBuilder): void;
|
|
42
|
+
}
|
|
43
|
+
/** Expand literal functions globs using the application's existing build host. */
|
|
44
|
+
export declare function functionGlobs(): FunctionGlobsPlugin;
|
|
45
|
+
export {};
|
package/dist/build.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { glob, lstat, readFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
|
+
const excluded = new Set(['_generated', 'node_modules', 'tests', 'test', '__tests__', '__mocks__']);
|
|
4
|
+
const ignored = (path) => path.split(sep).some(part => part.startsWith('.') && part !== '.' || excluded.has(part));
|
|
5
|
+
const codeFile = /\.[cm]?[tj]sx?$/;
|
|
6
|
+
function dynamicImports(node, result = []) {
|
|
7
|
+
if (!node || typeof node !== 'object')
|
|
8
|
+
return result;
|
|
9
|
+
if ('type' in node && node.type === 'ImportExpression' && 'source' in node) {
|
|
10
|
+
const source = node.source;
|
|
11
|
+
if (source && typeof source === 'object' && 'value' in source && typeof source.value === 'string')
|
|
12
|
+
result.push(source.value);
|
|
13
|
+
}
|
|
14
|
+
for (const child of Object.values(node)) {
|
|
15
|
+
if (Array.isArray(child))
|
|
16
|
+
for (const value of child)
|
|
17
|
+
dynamicImports(value, result);
|
|
18
|
+
else if (child && typeof child === 'object')
|
|
19
|
+
dynamicImports(child, result);
|
|
20
|
+
}
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
function catalogue(files, directory, imports, prefix) {
|
|
24
|
+
const tree = new Map();
|
|
25
|
+
for (const file of files) {
|
|
26
|
+
const path = relative(directory, file).split(sep).join('/');
|
|
27
|
+
const parts = path.replace(codeFile, '').split('/');
|
|
28
|
+
if (!parts.every(part => /^[\w$-]+$/.test(part) && !['constructor', '__proto__', 'prototype'].includes(part)))
|
|
29
|
+
throw new TypeError(`Invalid function glob module: ${path}`);
|
|
30
|
+
let target = tree;
|
|
31
|
+
const leaf = parts.pop();
|
|
32
|
+
for (const part of parts) {
|
|
33
|
+
let child = target.get(part);
|
|
34
|
+
if (typeof child === 'string')
|
|
35
|
+
throw new TypeError(`Function glob namespace collision: ${path}`);
|
|
36
|
+
if (!child)
|
|
37
|
+
target.set(part, child = new Map());
|
|
38
|
+
target = child;
|
|
39
|
+
}
|
|
40
|
+
if (target.has(leaf))
|
|
41
|
+
throw new TypeError(`Function glob namespace collision: ${path}`);
|
|
42
|
+
const name = `${prefix}${imports.length}`;
|
|
43
|
+
imports.push(`import * as ${name} from ${JSON.stringify(path.startsWith('.') ? path : './' + path)};`);
|
|
44
|
+
target.set(leaf, name);
|
|
45
|
+
}
|
|
46
|
+
const object = (node) => `{${[...node].map(([key, value]) => `${JSON.stringify(key)}:${typeof value === 'string' ? value : object(value)}`).join(',')}}`;
|
|
47
|
+
return object(tree);
|
|
48
|
+
}
|
|
49
|
+
/** Expand literal functions globs using the application's existing build host. */
|
|
50
|
+
export function functionGlobs() {
|
|
51
|
+
const watched = new Map();
|
|
52
|
+
const cleanups = new Set();
|
|
53
|
+
const transform = async (code, id, scan, watch) => {
|
|
54
|
+
watched.delete(id);
|
|
55
|
+
if (!isAbsolute(id) || !codeFile.test(id) || id.includes(`${sep}node_modules${sep}`) || !code.includes('functions'))
|
|
56
|
+
return null;
|
|
57
|
+
let prefix = '$hullaFunctions_';
|
|
58
|
+
while (code.includes(prefix))
|
|
59
|
+
prefix += '_';
|
|
60
|
+
const candidates = [];
|
|
61
|
+
// Temporary imports let the host parser distinguish code from strings,
|
|
62
|
+
// comments, regexes, JSX text and type-only properties without another parser.
|
|
63
|
+
const trial = code.replace(/(?:\bfunctions|["']functions["'])\s*:\s*('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*")(?=\s*[,}])/g, (match, literal, offset) => {
|
|
64
|
+
const start = offset + match.length - literal.length;
|
|
65
|
+
const marker = prefix + candidates.length + ':';
|
|
66
|
+
candidates.push({ start, end: start + literal.length, marker });
|
|
67
|
+
return match.slice(0, -literal.length) + `import(${literal[0]}${marker}${literal.slice(1)})`;
|
|
68
|
+
});
|
|
69
|
+
if (!candidates.length)
|
|
70
|
+
return null;
|
|
71
|
+
const paths = scan(trial);
|
|
72
|
+
const directory = dirname(id), imports = [], patches = [];
|
|
73
|
+
const roots = new Set();
|
|
74
|
+
watched.set(id, roots);
|
|
75
|
+
for (const candidate of candidates) {
|
|
76
|
+
const pattern = paths.find(path => path.startsWith(candidate.marker))?.slice(candidate.marker.length);
|
|
77
|
+
if (!pattern?.startsWith('./') || !/[*?{[]/.test(pattern))
|
|
78
|
+
continue;
|
|
79
|
+
const staticPath = pattern.slice(0, pattern.search(/[*?{[]/));
|
|
80
|
+
const root = resolve(directory, dirname(staticPath + (staticPath.endsWith('/') ? '_' : '')));
|
|
81
|
+
roots.add(root);
|
|
82
|
+
watch?.(root);
|
|
83
|
+
const files = [];
|
|
84
|
+
for await (const path of glob(pattern, { cwd: directory })) {
|
|
85
|
+
if (ignored(path) || !codeFile.test(path) || /\.(?:d|test|spec)\.[cm]?[tj]sx?$/.test(path))
|
|
86
|
+
continue;
|
|
87
|
+
const file = resolve(directory, path);
|
|
88
|
+
if (file !== id && (await lstat(file)).isFile())
|
|
89
|
+
files.push(file);
|
|
90
|
+
}
|
|
91
|
+
if (!files.length)
|
|
92
|
+
throw new TypeError(`Function glob matched no files: ${pattern}`);
|
|
93
|
+
for (const file of files)
|
|
94
|
+
watch?.(file);
|
|
95
|
+
patches.push({ ...candidate, text: `()=>Promise.resolve(${catalogue(files.sort(), directory, imports, prefix)})` });
|
|
96
|
+
}
|
|
97
|
+
if (!patches.length) {
|
|
98
|
+
watched.delete(id);
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
for (const patch of patches.reverse())
|
|
102
|
+
code = code.slice(0, patch.start) + patch.text + code.slice(patch.end);
|
|
103
|
+
const insertion = code.startsWith('#!') ? code.indexOf('\n') + 1 : 0;
|
|
104
|
+
return { code: code.slice(0, insertion) + imports.join('') + code.slice(insertion), map: null };
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
name: 'hulla-function-globs', enforce: 'post',
|
|
108
|
+
transform(code, id) { return transform(code, id.split('?')[0], source => dynamicImports(this.parse(source)), file => this.addWatchFile?.(file)); },
|
|
109
|
+
configureServer(server) {
|
|
110
|
+
const membership = (file) => {
|
|
111
|
+
if (!codeFile.test(file))
|
|
112
|
+
return;
|
|
113
|
+
let changed = false;
|
|
114
|
+
for (const [id, roots] of watched)
|
|
115
|
+
if ([...roots].some(root => { const path = relative(root, file); return !isAbsolute(path) && !ignored(path); })) {
|
|
116
|
+
const module = server.moduleGraph.getModuleById(id);
|
|
117
|
+
if (module) {
|
|
118
|
+
server.moduleGraph.invalidateModule(module);
|
|
119
|
+
changed = true;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (changed)
|
|
123
|
+
server.ws.send({ type: 'full-reload' });
|
|
124
|
+
};
|
|
125
|
+
server.watcher.on('add', membership);
|
|
126
|
+
server.watcher.on('unlink', membership);
|
|
127
|
+
cleanups.add(() => { server.watcher.off('add', membership); server.watcher.off('unlink', membership); });
|
|
128
|
+
},
|
|
129
|
+
closeBundle() { for (const cleanup of cleanups)
|
|
130
|
+
cleanup(); cleanups.clear(); watched.clear(); },
|
|
131
|
+
setup(build) {
|
|
132
|
+
build.onLoad({ filter: codeFile, namespace: 'file' }, async ({ path }) => {
|
|
133
|
+
if (path.includes(`${sep}node_modules${sep}`))
|
|
134
|
+
return undefined;
|
|
135
|
+
const loader = /\.[cm]?tsx?$/.test(path) ? path.endsWith('x') ? 'tsx' : 'ts' : path.endsWith('x') ? 'jsx' : 'js';
|
|
136
|
+
const result = await transform(await readFile(path, 'utf8'), path, source => new Bun.Transpiler({ loader }).scanImports(source).filter(value => value.kind === 'dynamic-import').map(value => value.path));
|
|
137
|
+
return result ? { contents: result.code, loader } : undefined;
|
|
138
|
+
});
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Readable, Writable } from "node:stream";
|
|
2
|
+
export interface ListenAddress {
|
|
3
|
+
readonly host: string;
|
|
4
|
+
readonly port: number;
|
|
5
|
+
}
|
|
6
|
+
export interface RememberedAddress {
|
|
7
|
+
readonly requested: ListenAddress;
|
|
8
|
+
readonly address: ListenAddress;
|
|
9
|
+
}
|
|
10
|
+
export type DevelopmentAddresses = Partial<Record<"service" | "studio", RememberedAddress>>;
|
|
11
|
+
export declare class StartupCancelled extends Error {
|
|
12
|
+
constructor();
|
|
13
|
+
}
|
|
14
|
+
export declare class AddressConflict extends Error {
|
|
15
|
+
}
|
|
16
|
+
interface PromptStreams {
|
|
17
|
+
readonly input: Readable & {
|
|
18
|
+
readonly isTTY?: boolean;
|
|
19
|
+
};
|
|
20
|
+
readonly output: Writable & {
|
|
21
|
+
readonly isTTY?: boolean;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
interface AddressOptions {
|
|
25
|
+
readonly signal: AbortSignal;
|
|
26
|
+
readonly fixedHost?: boolean;
|
|
27
|
+
readonly streams?: PromptStreams;
|
|
28
|
+
}
|
|
29
|
+
export declare function addressURL({ host, port }: ListenAddress): string;
|
|
30
|
+
/** Retry only real bind conflicts; other startup failures retain their original cause. */
|
|
31
|
+
export declare function startCLIListener<T>(label: string, requested: ListenAddress, start: (address: ListenAddress) => Promise<T>, options: AddressOptions): Promise<{
|
|
32
|
+
listener: T;
|
|
33
|
+
address: ListenAddress;
|
|
34
|
+
}>;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { createServer } from "node:net";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
export class StartupCancelled extends Error {
|
|
4
|
+
constructor() { super("Startup cancelled."); }
|
|
5
|
+
}
|
|
6
|
+
export class AddressConflict extends Error {
|
|
7
|
+
}
|
|
8
|
+
export function addressURL({ host, port }) {
|
|
9
|
+
return `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
|
|
10
|
+
}
|
|
11
|
+
function inUse(error) {
|
|
12
|
+
return !!error && typeof error === "object" && "code" in error && error.code === "EADDRINUSE";
|
|
13
|
+
}
|
|
14
|
+
async function nextAvailable(address, signal) {
|
|
15
|
+
for (let port = address.port + 1; port <= 65535; port++) {
|
|
16
|
+
signal.throwIfAborted();
|
|
17
|
+
const server = createServer();
|
|
18
|
+
try {
|
|
19
|
+
await new Promise((resolve, reject) => {
|
|
20
|
+
server.once("error", reject);
|
|
21
|
+
server.listen({ host: address.host, port, exclusive: true }, resolve);
|
|
22
|
+
});
|
|
23
|
+
return { host: address.host, port };
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (!inUse(error))
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
if (server.listening)
|
|
31
|
+
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
throw new Error(`No available port after ${address.port}; enter a lower port instead.`);
|
|
35
|
+
}
|
|
36
|
+
function customAddress(value, current, fixedHost) {
|
|
37
|
+
let host = current.host, port;
|
|
38
|
+
if (/^\d+$/.test(value))
|
|
39
|
+
port = Number(value);
|
|
40
|
+
else {
|
|
41
|
+
if (!/^(?:http:\/\/)?(?:\[[\da-fA-F:]+\]|[a-zA-Z\d.-]+):\d+\/?$/.test(value))
|
|
42
|
+
throw new Error("Enter a port or an HTTP address such as 127.0.0.1:3002.");
|
|
43
|
+
const url = new URL(value.startsWith("http://") ? value : `http://${value}`);
|
|
44
|
+
host = url.hostname.replace(/^\[|\]$/g, "");
|
|
45
|
+
port = Number(url.port || 80);
|
|
46
|
+
}
|
|
47
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
48
|
+
throw new Error("Enter a port from 1 to 65535.");
|
|
49
|
+
if (fixedHost && host !== current.host)
|
|
50
|
+
throw new Error(`This listener must stay on ${current.host}; enter a different port.`);
|
|
51
|
+
return { host, port };
|
|
52
|
+
}
|
|
53
|
+
async function chooseAddress(label, address, options) {
|
|
54
|
+
const { input, output } = options.streams ?? { input: process.stdin, output: process.stderr };
|
|
55
|
+
if (!input.isTTY || !output.isTTY) {
|
|
56
|
+
throw new AddressConflict(`${label} address ${addressURL(address)} is in use. Choose another port in your config or use --studio-port for Studio. Run in a terminal to choose interactively.`);
|
|
57
|
+
}
|
|
58
|
+
// readline supports cancellable input in both the Node CLI and Bun workers.
|
|
59
|
+
const readline = createInterface({ input, output, terminal: true });
|
|
60
|
+
const closed = new AbortController();
|
|
61
|
+
const signal = AbortSignal.any([options.signal, closed.signal]);
|
|
62
|
+
let ended = false;
|
|
63
|
+
readline.once("close", () => { ended = true; closed.abort(); });
|
|
64
|
+
const cancel = () => readline.close();
|
|
65
|
+
readline.on("SIGINT", cancel);
|
|
66
|
+
const ask = (question) => new Promise((resolve, reject) => {
|
|
67
|
+
if (ended || signal.aborted) {
|
|
68
|
+
reject(new StartupCancelled());
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const cleanup = () => {
|
|
72
|
+
readline.off("close", onClose);
|
|
73
|
+
signal.removeEventListener("abort", cancel);
|
|
74
|
+
};
|
|
75
|
+
const onClose = () => { cleanup(); reject(new StartupCancelled()); };
|
|
76
|
+
readline.once("close", onClose);
|
|
77
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
78
|
+
readline.question(question, answer => { cleanup(); resolve(answer.trim()); });
|
|
79
|
+
});
|
|
80
|
+
try {
|
|
81
|
+
output.write(`\n ${label} address ${addressURL(address)} is already in use.\n\n`);
|
|
82
|
+
output.write(" 1) Use the next available port (default)\n 2) Enter a custom address\n 3) Exit\n\n");
|
|
83
|
+
while (true) {
|
|
84
|
+
const choice = await ask(" Choose [1]: ");
|
|
85
|
+
if (!choice || choice === "1") {
|
|
86
|
+
try {
|
|
87
|
+
const next = await nextAvailable(address, signal);
|
|
88
|
+
if (signal.aborted)
|
|
89
|
+
throw new StartupCancelled();
|
|
90
|
+
return next;
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (signal.aborted)
|
|
94
|
+
throw new StartupCancelled();
|
|
95
|
+
output.write(` ${error instanceof Error ? error.message : "Cannot find an available port."}\n`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
else if (choice === "2") {
|
|
99
|
+
while (true) {
|
|
100
|
+
const value = await ask(` ${options.fixedHost ? "Port" : "Address or port"} (blank to go back): `);
|
|
101
|
+
if (!value)
|
|
102
|
+
break;
|
|
103
|
+
try {
|
|
104
|
+
return customAddress(value, address, !!options.fixedHost);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
output.write(` ${error instanceof Error ? error.message : "Invalid address."}\n`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
else if (choice === "3")
|
|
112
|
+
throw new StartupCancelled();
|
|
113
|
+
else
|
|
114
|
+
output.write(" Choose 1, 2, or 3. Press Enter to use the next available port.\n");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
readline.close();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** Retry only real bind conflicts; other startup failures retain their original cause. */
|
|
122
|
+
export async function startCLIListener(label, requested, start, options) {
|
|
123
|
+
let address = requested;
|
|
124
|
+
while (true) {
|
|
125
|
+
options.signal.throwIfAborted();
|
|
126
|
+
try {
|
|
127
|
+
return { listener: await start(address), address };
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (!inUse(error))
|
|
131
|
+
throw error;
|
|
132
|
+
address = await chooseAddress(label, address, options);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface StudioFlags {
|
|
2
|
+
readonly port: number;
|
|
3
|
+
readonly readOnly: boolean;
|
|
4
|
+
}
|
|
5
|
+
export interface CLIOptions {
|
|
6
|
+
readonly command: "setup" | "generate" | "init" | "migrate" | "serve" | "dev" | "studio";
|
|
7
|
+
readonly ignoreFile?: string;
|
|
8
|
+
readonly config: string;
|
|
9
|
+
readonly studio?: StudioFlags;
|
|
10
|
+
readonly check?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export declare const usage = "Usage: hulla-db <setup|generate|init|migrate|serve|dev|studio> [entrypoint-or-db.config.ts] [--ignore-file <path>] [--check] [--studio] [--studio-port <port>] [--read-only|--write]";
|
|
13
|
+
export declare function parseCLI(args: readonly string[], production?: boolean): CLIOptions;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export const usage = "Usage: hulla-db <setup|generate|init|migrate|serve|dev|studio> [entrypoint-or-db.config.ts] [--ignore-file <path>] [--check] [--studio] [--studio-port <port>] [--read-only|--write]";
|
|
2
|
+
export function parseCLI(args, production = false) {
|
|
3
|
+
const [command, ...rest] = args;
|
|
4
|
+
if (!["setup", "generate", "init", "migrate", "serve", "dev", "studio"].includes(command ?? ""))
|
|
5
|
+
throw new Error(usage);
|
|
6
|
+
let config, enabled = false, port, readOnly, check = false;
|
|
7
|
+
let ignoreFile;
|
|
8
|
+
for (let i = 0; i < rest.length; i++) {
|
|
9
|
+
const arg = rest[i];
|
|
10
|
+
if (arg === "--ignore-file" && command === "setup" && ignoreFile === undefined) {
|
|
11
|
+
const value = rest[++i];
|
|
12
|
+
if (!value || value.startsWith("-") || /[\r\n\0]/.test(value))
|
|
13
|
+
throw new Error("--ignore-file requires an explicit gitignore-syntax file path");
|
|
14
|
+
ignoreFile = value;
|
|
15
|
+
}
|
|
16
|
+
else if (arg === "--check" && command === "migrate" && !check)
|
|
17
|
+
check = true;
|
|
18
|
+
else if (arg === "--studio" && !enabled)
|
|
19
|
+
enabled = true;
|
|
20
|
+
else if (arg === "--studio-port" && port === undefined) {
|
|
21
|
+
const value = rest[++i];
|
|
22
|
+
if (!value || !/^\d+$/.test(value) || Number(value) > 65535)
|
|
23
|
+
throw new Error("--studio-port requires an integer from 0 to 65535");
|
|
24
|
+
port = Number(value);
|
|
25
|
+
}
|
|
26
|
+
else if ((arg === "--read-only" || arg === "--write") && readOnly === undefined)
|
|
27
|
+
readOnly = arg === "--read-only";
|
|
28
|
+
else if (!arg.startsWith("-") && config === undefined)
|
|
29
|
+
config = arg;
|
|
30
|
+
else
|
|
31
|
+
throw new Error(usage);
|
|
32
|
+
}
|
|
33
|
+
if ((enabled && command !== "dev") || ((port !== undefined || readOnly !== undefined) && command !== "studio" && !(command === "dev" && enabled)))
|
|
34
|
+
throw new Error(usage);
|
|
35
|
+
if (command === "setup" && ignoreFile === undefined)
|
|
36
|
+
throw new Error("setup requires --ignore-file <path>; choose the ignore file your tools use.");
|
|
37
|
+
return {
|
|
38
|
+
command: command, config: config ?? "db.config.ts",
|
|
39
|
+
...(ignoreFile === undefined ? {} : { ignoreFile }),
|
|
40
|
+
...(command === "migrate" ? { check } : {}),
|
|
41
|
+
...(command === "studio" || enabled ? { studio: { port: port ?? 4983, readOnly: readOnly ?? production } } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
interface OutputStream {
|
|
2
|
+
readonly isTTY?: boolean;
|
|
3
|
+
write(text: string): unknown;
|
|
4
|
+
}
|
|
5
|
+
/** Shared by the Node bootstrap and Bun development workers. No runtime dependency. */
|
|
6
|
+
export declare function createCLIOutput(stream: OutputStream, env?: NodeJS.ProcessEnv): {
|
|
7
|
+
success: (message: string) => void;
|
|
8
|
+
info: (message: string) => void;
|
|
9
|
+
warn: (message: string) => void;
|
|
10
|
+
error: (message: string) => void;
|
|
11
|
+
file: (path: string, label?: string) => string;
|
|
12
|
+
heading(command: string, configPath: string): void;
|
|
13
|
+
listening(label: string, url: string): void;
|
|
14
|
+
help(): void;
|
|
15
|
+
};
|
|
16
|
+
export declare const cliOutput: {
|
|
17
|
+
success: (message: string) => void;
|
|
18
|
+
info: (message: string) => void;
|
|
19
|
+
warn: (message: string) => void;
|
|
20
|
+
error: (message: string) => void;
|
|
21
|
+
file: (path: string, label?: string) => string;
|
|
22
|
+
heading(command: string, configPath: string): void;
|
|
23
|
+
listening(label: string, url: string): void;
|
|
24
|
+
help(): void;
|
|
25
|
+
};
|
|
26
|
+
export declare const cliError: {
|
|
27
|
+
success: (message: string) => void;
|
|
28
|
+
info: (message: string) => void;
|
|
29
|
+
warn: (message: string) => void;
|
|
30
|
+
error: (message: string) => void;
|
|
31
|
+
file: (path: string, label?: string) => string;
|
|
32
|
+
heading(command: string, configPath: string): void;
|
|
33
|
+
listening(label: string, url: string): void;
|
|
34
|
+
help(): void;
|
|
35
|
+
};
|
|
36
|
+
export {};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { pathToFileURL } from "node:url";
|
|
2
|
+
import { usage } from "./cli-options.js";
|
|
3
|
+
/** Shared by the Node bootstrap and Bun development workers. No runtime dependency. */
|
|
4
|
+
export function createCLIOutput(stream, env = process.env) {
|
|
5
|
+
const interactive = !!stream.isTTY && env.TERM !== "dumb";
|
|
6
|
+
const decorated = interactive && !env.NO_COLOR && env.FORCE_COLOR !== "0";
|
|
7
|
+
const hyperlinks = decorated && (/^(iTerm\.app|WezTerm|vscode|ghostty)$/.test(env.TERM_PROGRAM ?? "")
|
|
8
|
+
|| /^(xterm-kitty|foot|foot-extra|wezterm)$/.test(env.TERM ?? "")
|
|
9
|
+
|| !!env.WT_SESSION || !!env.KONSOLE_VERSION || Number(env.VTE_VERSION) >= 5000);
|
|
10
|
+
const style = (code, text) => decorated ? `\x1b[${code}m${text}\x1b[0m` : text;
|
|
11
|
+
const line = (text) => { stream.write(text + "\n"); };
|
|
12
|
+
const status = (symbol, color, message) => line(decorated ? ` ${style(color, symbol)} ${message}` : message);
|
|
13
|
+
const link = (url, label = url) => {
|
|
14
|
+
// Never allow a path or URL to terminate an OSC sequence or inject terminal controls.
|
|
15
|
+
const target = url.replace(/[\x00-\x1f\x7f-\x9f]/g, "");
|
|
16
|
+
const text = label.replace(/[\x00-\x1f\x7f-\x9f]/g, "");
|
|
17
|
+
return hyperlinks ? `\x1b]8;;${target}\x1b\\${style("36;4", text)}\x1b]8;;\x1b\\` : style("36;4", text);
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
success: (message) => status("✓", "32", message),
|
|
21
|
+
info: (message) => status("›", "2", message),
|
|
22
|
+
warn: (message) => status("!", "33", message),
|
|
23
|
+
error: (message) => status("✗", "31", message),
|
|
24
|
+
file: (path, label = path) => link(pathToFileURL(path).href, label),
|
|
25
|
+
heading(command, configPath) {
|
|
26
|
+
if (!interactive)
|
|
27
|
+
return;
|
|
28
|
+
line(`\n ${style("1;36", "hulla/db")} ${style("2", command)}`);
|
|
29
|
+
line(` ${style("2", "Source")} ${link(pathToFileURL(configPath).href, configPath)}\n`);
|
|
30
|
+
},
|
|
31
|
+
listening(label, url) {
|
|
32
|
+
status("✓", "32", `${style("1", label)} listening at ${link(url)}`);
|
|
33
|
+
},
|
|
34
|
+
help() {
|
|
35
|
+
line(`\n${style("1;36", "hulla/db")} — typed database tools\n`);
|
|
36
|
+
line(usage);
|
|
37
|
+
line(`\n${style("1", "Commands")}`);
|
|
38
|
+
for (const [command, description] of [
|
|
39
|
+
["dev", "Generate, start the service, and watch for changes"],
|
|
40
|
+
["generate", "Generate typed database and function entrypoints"],
|
|
41
|
+
["setup", "Add generated output to an explicitly selected ignore file"],
|
|
42
|
+
["init", "Initialize the database and verify its schema"],
|
|
43
|
+
["migrate", "Apply supported schema changes; use --check to preview"],
|
|
44
|
+
["serve", "Start the service from generated artifacts"],
|
|
45
|
+
["studio", "Open the database administration UI"],
|
|
46
|
+
])
|
|
47
|
+
line(` ${style("36", command.padEnd(12))}${description}`);
|
|
48
|
+
line(`\n${style("1", "Options")}`);
|
|
49
|
+
for (const [option, description] of [
|
|
50
|
+
["entrypoint or config", "Generate from db/server.ts, or use db.config.ts (default)"],
|
|
51
|
+
["--check", "Preview schema changes without applying them"],
|
|
52
|
+
["--ignore-file <path>", "Setup only: gitignore-syntax file used by your tools"],
|
|
53
|
+
["--studio", "Start Studio alongside dev"],
|
|
54
|
+
["--studio-port <port>", "Studio port (default: 4983; 0 picks a free port)"],
|
|
55
|
+
["--read-only", "Disable writes in Studio (default in production)"],
|
|
56
|
+
["--write", "Allow writes in Studio"],
|
|
57
|
+
["-h, --help", "Show this help"],
|
|
58
|
+
])
|
|
59
|
+
line(` ${style("36", option.padEnd(24))}${description}`);
|
|
60
|
+
line(`\n${style("1", "Examples")}`);
|
|
61
|
+
line(" hulla-db dev --studio");
|
|
62
|
+
line(" hulla-db studio --read-only");
|
|
63
|
+
line(" hulla-db setup --ignore-file '<ignore-file-path>'");
|
|
64
|
+
line(" hulla-db generate ./db/server.ts\n");
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export const cliOutput = createCLIOutput(process.stdout);
|
|
69
|
+
export const cliError = createCLIOutput(process.stderr);
|
package/dist/cli.d.ts
ADDED