@yydb/yydb 0.0.11 → 0.0.15

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 (53) hide show
  1. package/README.md +86 -86
  2. package/dist/api/database.d.ts +127 -12
  3. package/dist/api/database.js +156 -14
  4. package/dist/cli/cli.js +28 -1
  5. package/dist/cli/info-cmd.js +30 -1
  6. package/dist/cli/verify-cmd.d.ts +11 -0
  7. package/dist/cli/verify-cmd.js +73 -0
  8. package/dist/database.d.ts +50 -0
  9. package/dist/database.js +181 -0
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/micro.d.ts +63 -0
  13. package/dist/micro.js +160 -0
  14. package/dist/native/binding.d.ts +28 -0
  15. package/dist/native.d.ts +9 -0
  16. package/dist/native.js +32 -0
  17. package/dist/node/cli/cli.d.ts +1 -0
  18. package/dist/node/cli/cli.js +25 -0
  19. package/dist/node/cli/info-cmd.d.ts +3 -0
  20. package/dist/node/cli/info-cmd.js +10 -0
  21. package/dist/node/cli/init-cmd.d.ts +3 -0
  22. package/dist/node/cli/init-cmd.js +18 -0
  23. package/dist/node/cli/options.d.ts +4 -0
  24. package/dist/node/cli/options.js +14 -0
  25. package/dist/node/cli/serve-cmd.d.ts +3 -0
  26. package/dist/node/cli/serve-cmd.js +14 -0
  27. package/dist/node/cli/version-cmd.d.ts +3 -0
  28. package/dist/node/cli/version-cmd.js +8 -0
  29. package/dist/node/cli.d.ts +2 -0
  30. package/dist/node/cli.js +6 -0
  31. package/dist/node/database.d.ts +50 -0
  32. package/dist/node/database.js +173 -0
  33. package/dist/node/index.d.ts +7 -0
  34. package/dist/node/index.js +5 -0
  35. package/dist/node/native.d.ts +9 -0
  36. package/dist/node/native.js +32 -0
  37. package/dist/node/resolve-bin.d.ts +15 -0
  38. package/dist/node/resolve-bin.js +62 -0
  39. package/dist/resolve-bin.d.ts +15 -0
  40. package/dist/resolve-bin.js +62 -0
  41. package/dist/shared/errors.d.ts +90 -15
  42. package/dist/shared/errors.js +112 -26
  43. package/dist/shared/wasm-envelope.d.ts +41 -0
  44. package/dist/shared/wasm-envelope.js +56 -0
  45. package/dist/udf-types.d.ts +26 -0
  46. package/dist/udf-types.js +16 -0
  47. package/dist/wasm/binding.d.ts +1 -0
  48. package/dist/wasm/binding.js +1 -0
  49. package/dist/wasm/database.d.ts +54 -0
  50. package/dist/wasm/database.js +118 -0
  51. package/dist/wasm/index.d.ts +8 -0
  52. package/dist/wasm/index.js +5 -0
  53. package/package.json +40 -40
@@ -0,0 +1,73 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { formatDiagnostic } from '@vmz/diagnostic';
4
+ import { loadNative } from '../native/binding.js';
5
+ import { requiredPositional } from './options.js';
6
+ /**
7
+ * Inline CLI catalog — commander's `.locales()` resolution is not exposed
8
+ * outside the CLI builder, so we ship a static copy here. Only one locale is
9
+ * loaded at runtime; future locale awareness should resolve the chosen locale
10
+ * from commander internals once they surface it.
11
+ */
12
+ const CLI_CATALOG = JSON.parse(fs.readFileSync(path.resolve(import.meta.dirname, '../../locales/en-US/cli.json'), 'utf8'));
13
+ const DIAGNOSTIC_STYLE = 'compact';
14
+ const DIAGNOSTIC_LOCALE = 'en-US';
15
+ export function registerVerifyCommand(cli) {
16
+ cli.command('verify', 'cli.cmd.verify').action((options) => cmdVerify(options));
17
+ }
18
+ /**
19
+ * Run read-only consistency probes against a YYDB database file.
20
+ *
21
+ * Exit codes:
22
+ * 0 — clean (no issues)
23
+ * 1 — doctor found at least one error (database may be corrupt)
24
+ * 13 — only warnings present (readable but should be inspected)
25
+ */
26
+ export function cmdVerify(options) {
27
+ const dbPath = requiredPositional(options, 'verify');
28
+ let report;
29
+ try {
30
+ const native = loadNative();
31
+ const db = native.Database.open(dbPath);
32
+ report = JSON.parse(db.doctor());
33
+ }
34
+ catch (err) {
35
+ const message = err instanceof Error ? err.message : String(err);
36
+ console.error(formatDiagnostic({
37
+ path: dbPath,
38
+ severity: 'error',
39
+ code: 'cli.err.open_failed',
40
+ args: { path: dbPath, reason: message },
41
+ }, {
42
+ locale: DIAGNOSTIC_LOCALE,
43
+ catalog: CLI_CATALOG,
44
+ style: DIAGNOSTIC_STYLE,
45
+ }));
46
+ return 1;
47
+ }
48
+ for (const issue of report.issues) {
49
+ const severity = issue.severity === 'error' ? 'error' : 'warning';
50
+ console.error(formatDiagnostic({
51
+ path: dbPath,
52
+ severity,
53
+ code: issue.code,
54
+ message: issue.message,
55
+ }, {
56
+ locale: DIAGNOSTIC_LOCALE,
57
+ catalog: CLI_CATALOG,
58
+ style: DIAGNOSTIC_STYLE,
59
+ }));
60
+ }
61
+ const errCount = report.issues.filter((i) => i.severity === 'error').length;
62
+ const warnCount = report.issues.length - errCount;
63
+ if (errCount > 0) {
64
+ console.log(`exit=1 errors=${errCount} warnings=${warnCount}`);
65
+ return 1;
66
+ }
67
+ if (warnCount > 0) {
68
+ console.log(`exit=13 errors=0 warnings=${warnCount}`);
69
+ return 13;
70
+ }
71
+ console.log(`exit=0 clean last_commit=${report.last_commit_sequence}`);
72
+ return 0;
73
+ }
@@ -0,0 +1,50 @@
1
+ import { defineMicro as buildMicro, type DefinedMicro, type MicroHandle } from './micro.js';
2
+ import type { UdfTypeDescriptor } from './udf-types.js';
3
+ export type { SchemaVersion } from '@yydb/yydb-client';
4
+ export interface OpenOptions {
5
+ /** Override CLI script path (tests / special installs). */
6
+ cli?: string;
7
+ /** @deprecated Use `cli`. */
8
+ binary?: string;
9
+ /** Prefer a specific loopback port; default = ephemeral free port. */
10
+ port?: number;
11
+ /** Extra args after `serve <path> --bind …`. */
12
+ serveArgs?: string[];
13
+ }
14
+ /**
15
+ * Node-facing YYDB handle. Looks like one library; owns a private loopback
16
+ * `yydb serve` child under the hood.
17
+ */
18
+ export declare class Database {
19
+ readonly path: string;
20
+ readonly endpoint: string;
21
+ private client;
22
+ private child;
23
+ private readonly microRegistry;
24
+ private constructor();
25
+ /**
26
+ * Open (create) a `.yydb` file. Spawns the engine on `127.0.0.1` automatically.
27
+ */
28
+ static open(dbPath: string, options?: OpenOptions): Promise<Database>;
29
+ serverVersion(): Promise<string>;
30
+ info(): Promise<string>;
31
+ getSchema(): Promise<import("@yydb/yydb-client").SchemaVersion | null>;
32
+ ensureSchema(version: number, document: string): Promise<void>;
33
+ get(key: string): Promise<Uint8Array | null>;
34
+ put(key: string, value: Uint8Array | string): Promise<void>;
35
+ /**
36
+ * Build a typed session-local micro definition. Does not register it with
37
+ * the engine until [`registerMicro`](./database.ts) is called.
38
+ */
39
+ defineMicro<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(definition: Parameters<typeof buildMicro<TArgs, TReturn>>[0]): DefinedMicro<TArgs, TReturn>;
40
+ /**
41
+ * Install a [`defineMicro`](./database.ts) definition into the current
42
+ * session registry and sync metadata to the private engine. Host micros are
43
+ * session-local and never written to `.yydb`.
44
+ */
45
+ registerMicro<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(definition: DefinedMicro<TArgs, TReturn>): Promise<MicroHandle>;
46
+ /** Invoke a registered scalar UDF on the private engine. */
47
+ callScalar(name: string, version: number, args: readonly (string | number | boolean | null)[]): Promise<string | number | boolean | null>;
48
+ /** Stop the private engine process. */
49
+ close(): Promise<void>;
50
+ }
@@ -0,0 +1,181 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import net from 'node:net';
4
+ import path from 'node:path';
5
+ import { connect } from '@yydb/yydb-client/node';
6
+ import { defineMicro as buildMicro, MicroSessionRegistry } from './micro.js';
7
+ import { resolveYydbCli } from './resolve-bin.js';
8
+ function microFingerprint(name, version) {
9
+ const bytes = new Uint8Array(32);
10
+ const seed = `${name}@${version}`;
11
+ for (let index = 0; index < bytes.byteLength; index += 1) {
12
+ bytes[index] = seed.charCodeAt(index % seed.length) & 0xff;
13
+ }
14
+ return bytes;
15
+ }
16
+ async function freeLoopbackPort() {
17
+ return await new Promise((resolve, reject) => {
18
+ const server = net.createServer();
19
+ server.listen(0, '127.0.0.1', () => {
20
+ const address = server.address();
21
+ if (!address || typeof address === 'string') {
22
+ server.close();
23
+ reject(new Error('could not allocate loopback port'));
24
+ return;
25
+ }
26
+ const { port } = address;
27
+ server.close((error) => {
28
+ if (error)
29
+ reject(error);
30
+ else
31
+ resolve(port);
32
+ });
33
+ });
34
+ server.on('error', reject);
35
+ });
36
+ }
37
+ async function waitForTcp(host, port, timeoutMs) {
38
+ const deadline = Date.now() + timeoutMs;
39
+ while (Date.now() < deadline) {
40
+ try {
41
+ await new Promise((resolve, reject) => {
42
+ const socket = net.connect({ host, port }, () => {
43
+ socket.end();
44
+ resolve();
45
+ });
46
+ socket.on('error', reject);
47
+ });
48
+ return;
49
+ }
50
+ catch {
51
+ await new Promise((r) => setTimeout(r, 40));
52
+ }
53
+ }
54
+ throw new Error(`yydb engine did not accept connections on ${host}:${port}`);
55
+ }
56
+ /**
57
+ * Node-facing YYDB handle. Looks like one library; owns a private loopback
58
+ * `yydb serve` child under the hood.
59
+ */
60
+ export class Database {
61
+ path;
62
+ endpoint;
63
+ client;
64
+ child;
65
+ microRegistry;
66
+ constructor(dbPath, endpoint, client, child) {
67
+ this.path = dbPath;
68
+ this.endpoint = endpoint;
69
+ this.client = client;
70
+ this.child = child;
71
+ this.microRegistry = new MicroSessionRegistry();
72
+ this.client.setMicroHostHandler((payload) => this.microRegistry.invokeFromWire(payload));
73
+ }
74
+ /**
75
+ * Open (create) a `.yydb` file. Spawns the engine on `127.0.0.1` automatically.
76
+ */
77
+ static async open(dbPath, options = {}) {
78
+ const resolved = path.resolve(dbPath);
79
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
80
+ const cli = options.cli ?? options.binary ?? resolveYydbCli();
81
+ const port = options.port ?? (await freeLoopbackPort());
82
+ const bind = `127.0.0.1:${port}`;
83
+ const args = [cli, 'serve', resolved, '--bind', bind, ...(options.serveArgs ?? [])];
84
+ const child = spawn(process.execPath, args, {
85
+ stdio: 'pipe',
86
+ windowsHide: true,
87
+ });
88
+ let stderr = '';
89
+ child.stderr?.setEncoding('utf8');
90
+ child.stderr?.on('data', (chunk) => {
91
+ stderr += chunk;
92
+ });
93
+ const exitPromise = new Promise((_, reject) => {
94
+ child.once('exit', (code, signal) => {
95
+ reject(new Error(`yydb engine exited early (code=${code}, signal=${signal}): ${stderr.trim()}`));
96
+ });
97
+ child.once('error', reject);
98
+ });
99
+ try {
100
+ await Promise.race([waitForTcp('127.0.0.1', port, 8000), exitPromise]);
101
+ const client = await connect(bind);
102
+ child.removeAllListeners('exit');
103
+ child.removeAllListeners('error');
104
+ child.on('exit', () => {
105
+ /* closed via Database.close or crash */
106
+ });
107
+ return new Database(resolved, bind, client, child);
108
+ }
109
+ catch (error) {
110
+ child.kill('SIGTERM');
111
+ throw error;
112
+ }
113
+ }
114
+ async serverVersion() {
115
+ return this.client.serverVersion();
116
+ }
117
+ async info() {
118
+ return this.client.info();
119
+ }
120
+ async getSchema() {
121
+ return this.client.getSchema();
122
+ }
123
+ async ensureSchema(version, document) {
124
+ await this.client.ensureSchema(version, document);
125
+ }
126
+ async get(key) {
127
+ return this.client.get(key);
128
+ }
129
+ async put(key, value) {
130
+ await this.client.put(key, value);
131
+ }
132
+ /**
133
+ * Build a typed session-local micro definition. Does not register it with
134
+ * the engine until [`registerMicro`](./database.ts) is called.
135
+ */
136
+ defineMicro(definition) {
137
+ return buildMicro(definition);
138
+ }
139
+ /**
140
+ * Install a [`defineMicro`](./database.ts) definition into the current
141
+ * session registry and sync metadata to the private engine. Host micros are
142
+ * session-local and never written to `.yydb`.
143
+ */
144
+ async registerMicro(definition) {
145
+ const handle = this.microRegistry.register(definition);
146
+ await this.client.registerMicro({
147
+ hostId: handle.hostId,
148
+ handleVersion: handle.implementationVersion,
149
+ udfVersion: definition.version,
150
+ name: definition.name,
151
+ functionId: handle.functionId,
152
+ args: definition.args.map((arg) => arg.kind),
153
+ returns: definition.returns.kind,
154
+ fingerprint: microFingerprint(definition.name, definition.version),
155
+ });
156
+ return handle;
157
+ }
158
+ /** Invoke a registered scalar UDF on the private engine. */
159
+ async callScalar(name, version, args) {
160
+ return this.client.callScalar(name, version, args);
161
+ }
162
+ /** Stop the private engine process. */
163
+ async close() {
164
+ this.client.close();
165
+ const child = this.child;
166
+ this.child = null;
167
+ if (!child || child.exitCode !== null || child.killed) {
168
+ return;
169
+ }
170
+ await new Promise((resolve) => {
171
+ child.once('exit', () => resolve());
172
+ child.kill('SIGTERM');
173
+ setTimeout(() => {
174
+ if (child.exitCode === null && !child.killed) {
175
+ child.kill('SIGKILL');
176
+ }
177
+ resolve();
178
+ }, 2000);
179
+ });
180
+ }
181
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Database, type OpenOptions, type SchemaVersion } from './api/database.js';
2
- export { YydbError, YydbErrorCodes, isRetryableYydbCode, isYydbError } from './shared/errors.js';
2
+ export { YydbError, YydbErrorCodes, YydbClientErrorCodes, isYydbError } from './shared/errors.js';
3
3
  export type { YydbErrorCode, YydbErrorOptions } from './shared/errors.js';
4
4
  export { defineMicro, type DefinedMicro, type MicroHandle, type TsMicroDefinitionInput, MicroSessionRegistry } from './shared/micro.js';
5
5
  export { type InferUdfArgs, type InferUdfReturn, type MicroEffect, type MicroInvocationMode, type UdfScalarDescriptor, type UdfScalarKind, } from './shared/udf-types.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Database } from './api/database.js';
2
- export { YydbError, YydbErrorCodes, isRetryableYydbCode, isYydbError } from './shared/errors.js';
2
+ export { YydbError, YydbErrorCodes, YydbClientErrorCodes, isYydbError } from './shared/errors.js';
3
3
  export { defineMicro, MicroSessionRegistry } from './shared/micro.js';
4
4
  export { nativeBindingName, platformKey, resolveYydbBinary, resolveYydbCli } from './native/resolve.js';
5
5
  export * from './shared/vos.js';
@@ -0,0 +1,63 @@
1
+ import type { InferUdfArgs, InferUdfReturn, MicroEffect, MicroInvocationMode, UdfTypeDescriptor } from './udf-types.js';
2
+ /** Input accepted by [`Database.defineMicro`](./database.ts). */
3
+ export interface TsMicroDefinitionInput<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor> {
4
+ readonly name: string;
5
+ readonly version: number;
6
+ readonly args: TArgs;
7
+ readonly returns: TReturn;
8
+ readonly effect: MicroEffect;
9
+ readonly deterministic: boolean;
10
+ readonly mode?: MicroInvocationMode;
11
+ readonly fn: (...args: InferUdfArgs<TArgs>) => InferUdfReturn<TReturn>;
12
+ }
13
+ /** Opaque definition produced by `defineMicro` before session registration. */
14
+ export interface DefinedMicro<TArgs extends readonly UdfTypeDescriptor[] = readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor = UdfTypeDescriptor> {
15
+ readonly name: string;
16
+ readonly version: number;
17
+ readonly args: TArgs;
18
+ readonly returns: TReturn;
19
+ readonly effect: MicroEffect;
20
+ readonly deterministic: boolean;
21
+ readonly mode: MicroInvocationMode;
22
+ readonly placement: 'host';
23
+ readonly fn: (...args: InferUdfArgs<TArgs>) => InferUdfReturn<TReturn>;
24
+ }
25
+ /** Handle returned after `registerMicro` installs a micro into the session. */
26
+ export interface MicroHandle {
27
+ readonly name: string;
28
+ readonly version: number;
29
+ readonly functionId: string;
30
+ readonly hostId: number;
31
+ /** Monotonic host implementation version for opaque handle checks. */
32
+ readonly implementationVersion: number;
33
+ }
34
+ type AnyDefinedMicro = DefinedMicro<readonly UdfTypeDescriptor[], UdfTypeDescriptor>;
35
+ /**
36
+ * Process-local registry for JS functions behind opaque host handles.
37
+ * Rust keeps `host_id + function_id + version`, not the closure.
38
+ */
39
+ export declare class MicroSessionRegistry {
40
+ readonly hostId: number;
41
+ private nextFunctionId;
42
+ private readonly byKey;
43
+ private readonly byFunctionId;
44
+ constructor(hostId?: number);
45
+ /** Installs a defined micro into the current session registry. */
46
+ register<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(definition: DefinedMicro<TArgs, TReturn>): MicroHandle;
47
+ /** Returns a registered micro by opaque host handle. */
48
+ resolve(handle: MicroHandle): AnyDefinedMicro | undefined;
49
+ /** Invokes a registered micro from a wire `MicroHostInvoke` payload. */
50
+ invokeFromWire(payload: {
51
+ hostId: number;
52
+ handleVersion: number;
53
+ functionId: string;
54
+ args: readonly unknown[];
55
+ }): string | number | boolean | null;
56
+ /** Invokes a registered scalar micro (host adapter entry point). */
57
+ invokeScalar(handle: MicroHandle, args: unknown[]): unknown;
58
+ /** Lists logical names currently registered in this session. */
59
+ list(): string[];
60
+ }
61
+ /** Builds a session-local micro definition without registering it. */
62
+ export declare function defineMicro<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(input: TsMicroDefinitionInput<TArgs, TReturn>): DefinedMicro<TArgs, TReturn>;
63
+ export {};
package/dist/micro.js ADDED
@@ -0,0 +1,160 @@
1
+ let nextHostId = 1;
2
+ /**
3
+ * Process-local registry for JS functions behind opaque host handles.
4
+ * Rust keeps `host_id + function_id + version`, not the closure.
5
+ */
6
+ export class MicroSessionRegistry {
7
+ hostId;
8
+ nextFunctionId = 1;
9
+ byKey = new Map();
10
+ byFunctionId = new Map();
11
+ constructor(hostId = nextHostId++) {
12
+ this.hostId = hostId;
13
+ }
14
+ /** Installs a defined micro into the current session registry. */
15
+ register(definition) {
16
+ const key = logicalKey(definition.name, definition.version);
17
+ if (this.byKey.has(key)) {
18
+ throw new Error(`micro already registered: ${definition.name}@${definition.version}`);
19
+ }
20
+ const functionId = String(this.nextFunctionId++);
21
+ const handle = {
22
+ name: definition.name,
23
+ version: definition.version,
24
+ functionId,
25
+ hostId: this.hostId,
26
+ implementationVersion: 1,
27
+ };
28
+ const entry = { handle, definition: definition };
29
+ this.byKey.set(key, entry);
30
+ this.byFunctionId.set(functionId, entry);
31
+ return handle;
32
+ }
33
+ /** Returns a registered micro by opaque host handle. */
34
+ resolve(handle) {
35
+ if (handle.hostId !== this.hostId) {
36
+ return undefined;
37
+ }
38
+ return this.byFunctionId.get(handle.functionId)?.definition;
39
+ }
40
+ /** Invokes a registered micro from a wire `MicroHostInvoke` payload. */
41
+ invokeFromWire(payload) {
42
+ const handle = {
43
+ hostId: payload.hostId,
44
+ functionId: payload.functionId,
45
+ implementationVersion: payload.handleVersion,
46
+ name: '',
47
+ version: 0,
48
+ };
49
+ return this.invokeScalar(handle, [...payload.args]);
50
+ }
51
+ /** Invokes a registered scalar micro (host adapter entry point). */
52
+ invokeScalar(handle, args) {
53
+ const definition = this.resolve(handle);
54
+ if (!definition) {
55
+ throw new Error(`micro not found: ${handle.functionId}`);
56
+ }
57
+ if (definition.mode !== 'scalar') {
58
+ throw new Error(`micro ${definition.name} is not scalar mode`);
59
+ }
60
+ if (args.length !== definition.args.length) {
61
+ throw new Error(`micro ${definition.name} arity mismatch: expected ${definition.args.length}, got ${args.length}`);
62
+ }
63
+ validateArgTypes(definition, args);
64
+ const result = definition.fn(...args);
65
+ validateReturnType(definition.returns, result);
66
+ return result;
67
+ }
68
+ /** Lists logical names currently registered in this session. */
69
+ list() {
70
+ return [...this.byKey.values()].map((entry) => entry.definition.name).sort();
71
+ }
72
+ }
73
+ /** Builds a session-local micro definition without registering it. */
74
+ export function defineMicro(input) {
75
+ if (!input.name.trim()) {
76
+ throw new Error('micro name must not be empty');
77
+ }
78
+ if (!Number.isInteger(input.version) || input.version <= 0) {
79
+ throw new Error('micro version must be a positive integer');
80
+ }
81
+ if (input.effect !== 'pure') {
82
+ throw new Error('TS micro effect must be pure in Phase 1');
83
+ }
84
+ if (!input.deterministic) {
85
+ throw new Error('TS micro must be deterministic in Phase 1');
86
+ }
87
+ if (typeof input.fn !== 'function') {
88
+ throw new Error('micro fn must be a function');
89
+ }
90
+ return {
91
+ name: input.name,
92
+ version: input.version,
93
+ args: input.args,
94
+ returns: input.returns,
95
+ effect: input.effect,
96
+ deterministic: input.deterministic,
97
+ mode: input.mode ?? 'scalar',
98
+ placement: 'host',
99
+ fn: input.fn,
100
+ };
101
+ }
102
+ function logicalKey(name, version) {
103
+ return `${name}@${version}`;
104
+ }
105
+ function validateArgTypes(definition, args) {
106
+ for (let index = 0; index < definition.args.length; index += 1) {
107
+ const kind = definition.args[index]?.kind;
108
+ const value = args[index];
109
+ switch (kind) {
110
+ case 'i64':
111
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
112
+ throw new Error(`micro ${definition.name} arg ${index} expects i64`);
113
+ }
114
+ break;
115
+ case 'bool':
116
+ if (typeof value !== 'boolean') {
117
+ throw new Error(`micro ${definition.name} arg ${index} expects bool`);
118
+ }
119
+ break;
120
+ case 'text':
121
+ if (typeof value !== 'string') {
122
+ throw new Error(`micro ${definition.name} arg ${index} expects text`);
123
+ }
124
+ break;
125
+ case 'null':
126
+ if (value !== null) {
127
+ throw new Error(`micro ${definition.name} arg ${index} expects null`);
128
+ }
129
+ break;
130
+ default:
131
+ throw new Error(`unsupported micro arg kind: ${kind}`);
132
+ }
133
+ }
134
+ }
135
+ function validateReturnType(descriptor, value) {
136
+ switch (descriptor.kind) {
137
+ case 'i64':
138
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
139
+ throw new Error('micro return expects i64');
140
+ }
141
+ break;
142
+ case 'bool':
143
+ if (typeof value !== 'boolean') {
144
+ throw new Error('micro return expects bool');
145
+ }
146
+ break;
147
+ case 'text':
148
+ if (typeof value !== 'string') {
149
+ throw new Error('micro return expects text');
150
+ }
151
+ break;
152
+ case 'null':
153
+ if (value !== null) {
154
+ throw new Error('micro return expects null');
155
+ }
156
+ break;
157
+ default:
158
+ throw new Error(`unsupported micro return kind: ${descriptor.kind}`);
159
+ }
160
+ }
@@ -18,6 +18,34 @@ export interface NativeDatabase {
18
18
  walFrameCount(): number;
19
19
  get(key: string): Uint8Array | null;
20
20
  put(key: string, value: Uint8Array): void;
21
+ /** Delete one record by key. */
22
+ delete(key: string): void;
23
+ /** Scan keys with a prefix; returns JSON `[{ key, value }, ...]`. */
24
+ scanPrefix(prefix: string, after: string | null, limit: number): string;
25
+ /** Atomically write or delete many keys; body is JSON `[{ key, value|null }, ...]`. */
26
+ writeBatch(changesJson: string): void;
27
+ /** Compare-and-swap; returns true on success. */
28
+ compareExchange(key: string, expected: Uint8Array | null, replacement: Uint8Array | null): boolean;
29
+ /** Begin an explicit transaction. */
30
+ begin(): void;
31
+ /** Commit the current transaction. */
32
+ commit(): void;
33
+ /** Roll back the current transaction. */
34
+ rollback(): void;
35
+ /** Execute a VOS read pipeline; returns JSON rows. */
36
+ queryVos(source: string): string;
37
+ /** Execute a VOS write program. */
38
+ executeVosWrite(source: string): void;
39
+ /** Publish a new schema version, optionally with rename map. */
40
+ migrateSchema(document: string, renamesJson?: string | null): void;
41
+ /** Checkpoint + copy self-contained `.yydb` main file (no WAL sidecars). */
42
+ backup(dest: string): void;
43
+ /** Copy main + WAL + SHM without checkpoint (opening replays the tail). */
44
+ backupWithWal(dest: string): void;
45
+ /** Read-only consistency probe; returns DoctorReport JSON. */
46
+ doctor(): string;
47
+ /** Fold WAL + reclaim orphan blobs (`.yydx` only); returns CompactReport JSON. */
48
+ compactYydx(): string;
21
49
  registerMicro(name: string, version: number, args: string[], returns: string, hostId: number, functionId: string, handleVersion: number, fingerprint: Uint8Array): void;
22
50
  callScalar(name: string, version: number, argsJson: string): string;
23
51
  }
@@ -0,0 +1,9 @@
1
+ export interface YydbNative {
2
+ version(): string;
3
+ serve(dbPath: string, bind: string, insecureBind?: boolean): void;
4
+ initDb(dbPath: string, schemaVersion: number, schemaDocument?: string | null): void;
5
+ infoText(dbPath: string): string;
6
+ readSchemaFile(schemaPath: string): string;
7
+ }
8
+ /** Load the platform native binding used by the `yydb` CLI. */
9
+ export declare function loadNative(): YydbNative;
package/dist/native.js ADDED
@@ -0,0 +1,32 @@
1
+ import { createRequire } from 'node:module';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { platformKey } from './resolve-bin.js';
5
+ function loadModule(specifier) {
6
+ const require = createRequire(import.meta.url);
7
+ const loaded = require(specifier);
8
+ return (loaded.default ?? loaded);
9
+ }
10
+ /** Load the platform native binding used by the `yydb` CLI. */
11
+ export function loadNative() {
12
+ const fromEnv = process.env.YYDB_NATIVE?.trim();
13
+ if (fromEnv) {
14
+ const bindingPath = path.resolve(fromEnv);
15
+ if (!fs.existsSync(bindingPath)) {
16
+ throw new Error(`YYDB_NATIVE points to missing binding: ${fromEnv}`);
17
+ }
18
+ return loadModule(bindingPath);
19
+ }
20
+ const key = platformKey();
21
+ if (!key) {
22
+ throw new Error(`YYDB native binding not available for ${process.platform}-${process.arch}`);
23
+ }
24
+ const pkg = `@yydb/yydb-${key}`;
25
+ try {
26
+ return loadModule(pkg);
27
+ }
28
+ catch (error) {
29
+ const message = error instanceof Error ? error.message : String(error);
30
+ throw new Error(`YYDB native binding not found. Reinstall @yydb/yydb with optional dependencies, set YYDB_NATIVE, or stage ${pkg}. ${message}`);
31
+ }
32
+ }
@@ -0,0 +1 @@
1
+ export declare function runCli(argv: string[]): Promise<number>;
@@ -0,0 +1,25 @@
1
+ import { dirname, join } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { createCli } from '@vmz/commander';
4
+ import { registerInfoCommand } from './info-cmd.js';
5
+ import { registerInitCommand } from './init-cmd.js';
6
+ import { registerServeCommand } from './serve-cmd.js';
7
+ import { registerVersionCommand } from './version-cmd.js';
8
+ function buildYydbCli() {
9
+ const localesRoot = join(dirname(fileURLToPath(import.meta.url)), '../../../locales');
10
+ const cli = createCli('yydb').locales(localesRoot).intro('cli.intro');
11
+ registerVersionCommand(cli);
12
+ registerInitCommand(cli);
13
+ registerInfoCommand(cli);
14
+ registerServeCommand(cli);
15
+ return cli;
16
+ }
17
+ export async function runCli(argv) {
18
+ try {
19
+ return await buildYydbCli().parse(argv);
20
+ }
21
+ catch (error) {
22
+ console.error(`error: ${error instanceof Error ? error.message : String(error)}`);
23
+ return 1;
24
+ }
25
+ }
@@ -0,0 +1,3 @@
1
+ import type { Cli, ParsedOptions } from '@vmz/commander';
2
+ export declare function registerInfoCommand(cli: Cli): void;
3
+ export declare function cmdInfo(options: ParsedOptions): number;
@@ -0,0 +1,10 @@
1
+ import { loadNative } from '../native.js';
2
+ import { requiredPositional } from './options.js';
3
+ export function registerInfoCommand(cli) {
4
+ cli.command('info', 'cli.cmd.info').action((options) => cmdInfo(options));
5
+ }
6
+ export function cmdInfo(options) {
7
+ const dbPath = requiredPositional(options, 'info');
8
+ console.log(loadNative().infoText(dbPath));
9
+ return 0;
10
+ }
@@ -0,0 +1,3 @@
1
+ import type { Cli, ParsedOptions } from '@vmz/commander';
2
+ export declare function registerInitCommand(cli: Cli): void;
3
+ export declare function cmdInit(options: ParsedOptions): number;