@yydb/yydb 0.0.5 → 0.0.7

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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # `@yydb/yydb`
2
2
 
3
3
  Node all-in-one and browser wasm core from one package. On Node.js, `Database.open` starts a private loopback `yydb serve`
4
- process and talks over the YY wire protocol. In browsers, `@yydb/yydb/wasm` loads an in-process wasm session with KV,
5
- schema, and VOS `query` / `execute` on memory or OPFS paths.
4
+ process and talks over the YY wire protocol. In browsers, `@yydb/yydb/wasm` loads an in-process wasm session with KV
5
+ and schema on memory or OPFS paths.
6
6
 
7
7
  For a wire client only (renderer or an app that already runs `yydb serve`), use
8
8
  [`@yydb/yydb-client`](https://www.npmjs.com/package/@yydb/yydb-client).
@@ -23,7 +23,7 @@ For a wire client only (renderer or an app that already runs `yydb serve`), use
23
23
  Node.js 18+. Platform `.node` bindings install via optional dependencies.
24
24
 
25
25
  Schema truth lives in the `.yydb` file via `ensureSchema` and VOS documents. Wasm sessions mirror KV and schema calls
26
- and add VOS pipelines directly on the embedded core.
26
+ on the embedded core.
27
27
 
28
28
  ## Node example
29
29
 
@@ -85,8 +85,6 @@ await db.info();
85
85
  await db.serverVersion();
86
86
  await db.registerMicro(microDefinition);
87
87
  await db.callScalar('double', 1, [21]);
88
- db.query('User.filter(x => x.active).collect()');
89
- db.execute('User { name: "Ada" }.insert()');
90
88
  db.close();
91
89
  ```
92
90
 
@@ -1,5 +1,5 @@
1
1
  import { defineMicro as buildMicro, type DefinedMicro, type MicroHandle } from '../shared/micro.js';
2
- import type { UdfTypeDescriptor } from '../shared/udf-types.js';
2
+ import type { UdfScalarDescriptor } from '../shared/udf-types.js';
3
3
  export type { SchemaVersion } from '@yydb/yydb-client';
4
4
  export interface OpenOptions {
5
5
  /** Override CLI script path (tests / special installs). */
@@ -36,13 +36,13 @@ export declare class Database {
36
36
  * Build a typed session-local micro definition. Does not register it with
37
37
  * the engine until [`registerMicro`](./database.ts) is called.
38
38
  */
39
- defineMicro<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(definition: Parameters<typeof buildMicro<TArgs, TReturn>>[0]): DefinedMicro<TArgs, TReturn>;
39
+ defineMicro<TArgs extends readonly UdfScalarDescriptor[], TReturn extends UdfScalarDescriptor>(definition: Parameters<typeof buildMicro<TArgs, TReturn>>[0]): DefinedMicro<TArgs, TReturn>;
40
40
  /**
41
41
  * Install a [`defineMicro`](./database.ts) definition into the current
42
42
  * session registry and sync metadata to the private engine. Host micros are
43
43
  * session-local and never written to `.yydb`.
44
44
  */
45
- registerMicro<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(definition: DefinedMicro<TArgs, TReturn>): Promise<MicroHandle>;
45
+ registerMicro<TArgs extends readonly UdfScalarDescriptor[], TReturn extends UdfScalarDescriptor>(definition: DefinedMicro<TArgs, TReturn>): Promise<MicroHandle>;
46
46
  /** Invoke a registered scalar UDF on the private engine. */
47
47
  callScalar(name: string, version: number, args: readonly (string | number | boolean | null)[]): Promise<string | number | boolean | null>;
48
48
  /** Stop the private engine process. */
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import net from 'node:net';
4
4
  import path from 'node:path';
5
5
  import { connect } from '@yydb/yydb-client/node';
6
- import { defineMicro as buildMicro, microFingerprint, MicroSessionRegistry } from '../shared/micro.js';
6
+ import { defineMicro as buildMicro, microFingerprint, udfWireKind, MicroSessionRegistry, } from '../shared/micro.js';
7
7
  import { resolveYydbCli } from './resolve-bin.js';
8
8
  async function freeLoopbackPort() {
9
9
  return await new Promise((resolve, reject) => {
@@ -141,8 +141,8 @@ export class Database {
141
141
  udfVersion: definition.version,
142
142
  name: definition.name,
143
143
  functionId: handle.functionId,
144
- args: definition.args.map((arg) => arg.kind),
145
- returns: definition.returns.kind,
144
+ args: definition.args.map(udfWireKind),
145
+ returns: udfWireKind(definition.returns),
146
146
  fingerprint: microFingerprint(definition.name, definition.version),
147
147
  });
148
148
  return handle;
@@ -1,4 +1,7 @@
1
1
  export { Database, type OpenOptions } from './database.js';
2
+ export { YydbError, YydbErrorCodes, isRetryableYydbCode, isYydbError } from '@yydb/yydb-client';
3
+ export type { YydbErrorCode, YydbErrorOptions } from '@yydb/yydb-client';
2
4
  export { defineMicro, type DefinedMicro, type MicroHandle, type TsMicroDefinitionInput, MicroSessionRegistry } from '../shared/micro.js';
3
- export { bool, i64, nullType, text, type InferUdfArgs, type InferUdfReturn, type MicroEffect, type MicroInvocationMode, type UdfScalarKind, type UdfTypeDescriptor, } from '../shared/udf-types.js';
5
+ export { type InferUdfArgs, type InferUdfReturn, type MicroEffect, type MicroInvocationMode, type UdfScalarDescriptor, type UdfScalarKind, } from '../shared/udf-types.js';
4
6
  export { nativeBindingName, platformKey, resolveYydbBinary, resolveYydbCli } from './resolve-bin.js';
7
+ export * from '../shared/vos.js';
@@ -1,4 +1,5 @@
1
1
  export { Database } from './database.js';
2
+ export { YydbError, YydbErrorCodes, isRetryableYydbCode, isYydbError } from '@yydb/yydb-client';
2
3
  export { defineMicro, MicroSessionRegistry } from '../shared/micro.js';
3
- export { bool, i64, nullType, text, } from '../shared/udf-types.js';
4
4
  export { nativeBindingName, platformKey, resolveYydbBinary, resolveYydbCli } from './resolve-bin.js';
5
+ export * from '../shared/vos.js';
@@ -1,6 +1,19 @@
1
- import type { InferUdfArgs, InferUdfReturn, MicroEffect, MicroInvocationMode, UdfTypeDescriptor } from './udf-types.js';
1
+ import type { InferUdfArgs, InferUdfReturn, MicroEffect, MicroInvocationMode, UdfScalarDescriptor } from './udf-types.js';
2
+ import type { AnyTypeDescriptor } from '@voml/vos';
3
+ /** Value shape accepted and produced on the wire micro path. */
4
+ type MicroWireValue = string | number | boolean | null;
5
+ /** Wire kinds a VOS descriptor can map onto (`UdfType::Null` is never a type here). */
6
+ type UdfWireKind = 'i64' | 'bool' | 'text';
7
+ /**
8
+ * Maps a VOS descriptor onto its wire `UdfType` tag.
9
+ *
10
+ * Accepts any VOS descriptor so the runtime layer can reject a kind that
11
+ * slipped past the type layer; throws for everything outside the Phase-1
12
+ * subset instead of letting it reach the engine.
13
+ */
14
+ export declare function udfWireKind(descriptor: AnyTypeDescriptor): UdfWireKind;
2
15
  /** Input accepted by [`Database.defineMicro`](./database.ts). */
3
- export interface TsMicroDefinitionInput<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor> {
16
+ export interface TsMicroDefinitionInput<TArgs extends readonly UdfScalarDescriptor[], TReturn extends UdfScalarDescriptor> {
4
17
  readonly name: string;
5
18
  readonly version: number;
6
19
  readonly args: TArgs;
@@ -11,7 +24,7 @@ export interface TsMicroDefinitionInput<TArgs extends readonly UdfTypeDescriptor
11
24
  readonly fn: (...args: InferUdfArgs<TArgs>) => InferUdfReturn<TReturn>;
12
25
  }
13
26
  /** Opaque definition produced by `defineMicro` before session registration. */
14
- export interface DefinedMicro<TArgs extends readonly UdfTypeDescriptor[] = readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor = UdfTypeDescriptor> {
27
+ export interface DefinedMicro<TArgs extends readonly UdfScalarDescriptor[] = readonly UdfScalarDescriptor[], TReturn extends UdfScalarDescriptor = UdfScalarDescriptor> {
15
28
  readonly name: string;
16
29
  readonly version: number;
17
30
  readonly args: TArgs;
@@ -31,7 +44,7 @@ export interface MicroHandle {
31
44
  /** Monotonic host implementation version for opaque handle checks. */
32
45
  readonly implementationVersion: number;
33
46
  }
34
- type AnyDefinedMicro = DefinedMicro<readonly UdfTypeDescriptor[], UdfTypeDescriptor>;
47
+ type AnyDefinedMicro = DefinedMicro<readonly UdfScalarDescriptor[], UdfScalarDescriptor>;
35
48
  /**
36
49
  * Process-local registry for JS functions behind opaque host handles.
37
50
  * Rust keeps `host_id + function_id + version`, not the closure.
@@ -43,7 +56,7 @@ export declare class MicroSessionRegistry {
43
56
  private readonly byFunctionId;
44
57
  constructor(hostId?: number);
45
58
  /** Installs a defined micro into the current session registry. */
46
- register<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(definition: DefinedMicro<TArgs, TReturn>): MicroHandle;
59
+ register<TArgs extends readonly UdfScalarDescriptor[], TReturn extends UdfScalarDescriptor>(definition: DefinedMicro<TArgs, TReturn>): MicroHandle;
47
60
  /** Returns a registered micro by opaque host handle. */
48
61
  resolve(handle: MicroHandle): AnyDefinedMicro | undefined;
49
62
  /** Invokes a registered micro from a wire `MicroHostInvoke` payload. */
@@ -52,14 +65,14 @@ export declare class MicroSessionRegistry {
52
65
  handleVersion: number;
53
66
  functionId: string;
54
67
  args: readonly unknown[];
55
- }): string | number | boolean | null;
68
+ }): MicroWireValue;
56
69
  /** Invokes a registered scalar micro (host adapter entry point). */
57
70
  invokeScalar(handle: MicroHandle, args: unknown[]): unknown;
58
71
  /** Lists logical names currently registered in this session. */
59
72
  list(): string[];
60
73
  }
61
74
  /** 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>;
75
+ export declare function defineMicro<TArgs extends readonly UdfScalarDescriptor[], TReturn extends UdfScalarDescriptor>(input: TsMicroDefinitionInput<TArgs, TReturn>): DefinedMicro<TArgs, TReturn>;
63
76
  /** Stable 32-byte fingerprint for a logical micro name and version. */
64
77
  export declare function microFingerprint(name: string, version: number): Uint8Array;
65
78
  export {};
@@ -1,3 +1,22 @@
1
+ /**
2
+ * Maps a VOS descriptor onto its wire `UdfType` tag.
3
+ *
4
+ * Accepts any VOS descriptor so the runtime layer can reject a kind that
5
+ * slipped past the type layer; throws for everything outside the Phase-1
6
+ * subset instead of letting it reach the engine.
7
+ */
8
+ export function udfWireKind(descriptor) {
9
+ switch (descriptor.kind) {
10
+ case 'i64':
11
+ return 'i64';
12
+ case 'bool':
13
+ return 'bool';
14
+ case 'utf8':
15
+ return 'text';
16
+ default:
17
+ throw new Error(`unsupported micro type descriptor: ${descriptor.kind}`);
18
+ }
19
+ }
1
20
  let nextHostId = 1;
2
21
  /**
3
22
  * Process-local registry for JS functions behind opaque host handles.
@@ -46,7 +65,12 @@ export class MicroSessionRegistry {
46
65
  name: '',
47
66
  version: 0,
48
67
  };
49
- return this.invokeScalar(handle, [...payload.args]);
68
+ const definition = this.resolve(handle);
69
+ if (!definition) {
70
+ throw new Error(`micro not found: ${payload.functionId}`);
71
+ }
72
+ const args = definition.args.map((descriptor, index) => wireToBoundary(descriptor, payload.args[index]));
73
+ return boundaryToWire(definition.returns, this.invokeScalar(handle, args));
50
74
  }
51
75
  /** Invokes a registered scalar micro (host adapter entry point). */
52
76
  invokeScalar(handle, args) {
@@ -60,9 +84,11 @@ export class MicroSessionRegistry {
60
84
  if (args.length !== definition.args.length) {
61
85
  throw new Error(`micro ${definition.name} arity mismatch: expected ${definition.args.length}, got ${args.length}`);
62
86
  }
63
- validateArgTypes(definition, args);
87
+ definition.args.forEach((descriptor, index) => {
88
+ validateValue(descriptor, args[index], `micro ${definition.name} arg ${index}`);
89
+ });
64
90
  const result = definition.fn(...args);
65
- validateReturnType(definition.returns, result);
91
+ validateValue(definition.returns, result, `micro ${definition.name} return`);
66
92
  return result;
67
93
  }
68
94
  /** Lists logical names currently registered in this session. */
@@ -87,6 +113,12 @@ export function defineMicro(input) {
87
113
  if (typeof input.fn !== 'function') {
88
114
  throw new Error('micro fn must be a function');
89
115
  }
116
+ // Reject descriptors outside the Phase-1 subset while the definition is
117
+ // still session-local, instead of at register time.
118
+ input.args.forEach((descriptor, index) => {
119
+ assertSupportedDescriptor(descriptor, `micro ${input.name} arg ${index}`);
120
+ });
121
+ assertSupportedDescriptor(input.returns, `micro ${input.name} return`);
90
122
  return {
91
123
  name: input.name,
92
124
  version: input.version,
@@ -111,59 +143,51 @@ export function microFingerprint(name, version) {
111
143
  function logicalKey(name, version) {
112
144
  return `${name}@${version}`;
113
145
  }
114
- function validateArgTypes(definition, args) {
115
- for (let index = 0; index < definition.args.length; index += 1) {
116
- const kind = definition.args[index]?.kind;
117
- const value = args[index];
118
- switch (kind) {
119
- case 'i64':
120
- if (typeof value !== 'number' || !Number.isInteger(value)) {
121
- throw new Error(`micro ${definition.name} arg ${index} expects i64`);
122
- }
123
- break;
124
- case 'bool':
125
- if (typeof value !== 'boolean') {
126
- throw new Error(`micro ${definition.name} arg ${index} expects bool`);
127
- }
128
- break;
129
- case 'text':
130
- if (typeof value !== 'string') {
131
- throw new Error(`micro ${definition.name} arg ${index} expects text`);
132
- }
133
- break;
134
- case 'null':
135
- if (value !== null) {
136
- throw new Error(`micro ${definition.name} arg ${index} expects null`);
137
- }
138
- break;
139
- default:
140
- throw new Error(`unsupported micro arg kind: ${kind}`);
141
- }
146
+ function assertSupportedDescriptor(descriptor, label) {
147
+ try {
148
+ udfWireKind(descriptor);
149
+ }
150
+ catch {
151
+ throw new Error(`${label} uses a descriptor outside the Phase-1 micro subset`);
142
152
  }
143
153
  }
144
- function validateReturnType(descriptor, value) {
145
- switch (descriptor.kind) {
154
+ /** Boundary value a VOS descriptor carries in the host runtime. */
155
+ function validateValue(descriptor, value, label) {
156
+ switch (udfWireKind(descriptor)) {
146
157
  case 'i64':
147
- if (typeof value !== 'number' || !Number.isInteger(value)) {
148
- throw new Error('micro return expects i64');
158
+ if (typeof value !== 'bigint') {
159
+ throw new Error(`${label} expects VOS \`i64\` (a bigint)`);
149
160
  }
150
161
  break;
151
162
  case 'bool':
152
163
  if (typeof value !== 'boolean') {
153
- throw new Error('micro return expects bool');
164
+ throw new Error(`${label} expects VOS \`bool\``);
154
165
  }
155
166
  break;
156
167
  case 'text':
157
168
  if (typeof value !== 'string') {
158
- throw new Error('micro return expects text');
159
- }
160
- break;
161
- case 'null':
162
- if (value !== null) {
163
- throw new Error('micro return expects null');
169
+ throw new Error(`${label} expects VOS \`utf8\` (a string)`);
164
170
  }
165
171
  break;
166
- default:
167
- throw new Error(`unsupported micro return kind: ${descriptor.kind}`);
168
172
  }
169
173
  }
174
+ /**
175
+ * Wire value to boundary value. The YY wire carries `i64` as a JS number, so
176
+ * it becomes the VOS `i64` boundary value here rather than in author code.
177
+ */
178
+ function wireToBoundary(descriptor, value) {
179
+ if (udfWireKind(descriptor) === 'i64' && typeof value === 'number' && Number.isSafeInteger(value)) {
180
+ return BigInt(value);
181
+ }
182
+ return value;
183
+ }
184
+ /** Boundary value back to the wire subset; `i64` must still fit a JS number. */
185
+ function boundaryToWire(descriptor, value) {
186
+ if (udfWireKind(descriptor) === 'i64' && typeof value === 'bigint') {
187
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
188
+ throw new Error(`micro return i64 ${value} does not fit the wire number path`);
189
+ }
190
+ return Number(value);
191
+ }
192
+ return value;
193
+ }
@@ -1,25 +1,33 @@
1
- /** Phase-1 scalar UDF wire kinds aligned with `yydb-udf`. */
1
+ /**
2
+ * Host micro (UDF) boundary types.
3
+ *
4
+ * Descriptors come straight from `@voml/vos`: `v.i64()`, `v.bool()`, `v.utf8()`.
5
+ * YYDB keeps no scalar descriptor algebra of its own — only the VOS descriptors
6
+ * the Phase-1 UDF boundary accepts.
7
+ *
8
+ * `null` is not a type here. It is a value carried by the wire subset, so it
9
+ * gets no descriptor.
10
+ *
11
+ * This module is types only, so a host test can load it through type stripping.
12
+ * The mapping onto the wire `UdfType` tags lives in `micro.ts`.
13
+ */
14
+ import type { Infer, TypeDescriptor } from '@voml/vos';
15
+ /** Phase-1 scalar kinds on the YY wire micro path, aligned with `yydb-udf`. */
2
16
  export type UdfScalarKind = 'i64' | 'bool' | 'text' | 'null';
3
- /** Runtime type descriptor used in `defineMicro` contracts. */
4
- export interface UdfTypeDescriptor<T = unknown> {
5
- readonly kind: UdfScalarKind;
6
- /** Phantom type for author-side inference only. */
7
- readonly _type?: T;
8
- }
9
- /** `i64` argument or return descriptor. */
10
- export declare function i64(): UdfTypeDescriptor<number>;
11
- /** `bool` argument or return descriptor. */
12
- export declare function bool(): UdfTypeDescriptor<boolean>;
13
- /** `text` argument or return descriptor. */
14
- export declare function text(): UdfTypeDescriptor<string>;
15
- /** `null` return descriptor. */
16
- export declare function nullType(): UdfTypeDescriptor<null>;
17
- /** Maps descriptor tuple types to positional argument types. */
18
- export type InferUdfArgs<T extends readonly UdfTypeDescriptor[]> = {
19
- [K in keyof T]: T[K] extends UdfTypeDescriptor<infer V> ? V : never;
17
+ /**
18
+ * VOS descriptors accepted at the Phase-1 host micro boundary.
19
+ *
20
+ * Drawn from the frozen VOS type algebra, so `v.utf16()`, `v.optional(…)`,
21
+ * `v.list(…)` and every non-scalar descriptor are rejected before they reach
22
+ * the wire.
23
+ */
24
+ export type UdfScalarDescriptor = TypeDescriptor<'i64', bigint> | TypeDescriptor<'bool', boolean> | TypeDescriptor<'utf8', string>;
25
+ /** Maps a descriptor tuple to positional boundary value types. */
26
+ export type InferUdfArgs<T extends readonly UdfScalarDescriptor[]> = {
27
+ [K in keyof T]: Infer<T[K]>;
20
28
  };
21
- /** Maps a return descriptor to its value type. */
22
- export type InferUdfReturn<T extends UdfTypeDescriptor> = T extends UdfTypeDescriptor<infer V> ? V : never;
29
+ /** Maps a return descriptor to its boundary value type. */
30
+ export type InferUdfReturn<T extends UdfScalarDescriptor> = Infer<T>;
23
31
  /** Session micro effect surface (Phase 1: pure only). */
24
32
  export type MicroEffect = 'pure';
25
33
  /** Invocation mode stored with the definition for future batch host calls. */
@@ -1,16 +1,14 @@
1
- /** `i64` argument or return descriptor. */
2
- export function i64() {
3
- return { kind: 'i64' };
4
- }
5
- /** `bool` argument or return descriptor. */
6
- export function bool() {
7
- return { kind: 'bool' };
8
- }
9
- /** `text` argument or return descriptor. */
10
- export function text() {
11
- return { kind: 'text' };
12
- }
13
- /** `null` return descriptor. */
14
- export function nullType() {
15
- return { kind: 'null' };
16
- }
1
+ /**
2
+ * Host micro (UDF) boundary types.
3
+ *
4
+ * Descriptors come straight from `@voml/vos`: `v.i64()`, `v.bool()`, `v.utf8()`.
5
+ * YYDB keeps no scalar descriptor algebra of its own — only the VOS descriptors
6
+ * the Phase-1 UDF boundary accepts.
7
+ *
8
+ * `null` is not a type here. It is a value carried by the wire subset, so it
9
+ * gets no descriptor.
10
+ *
11
+ * This module is types only, so a host test can load it through type stripping.
12
+ * The mapping onto the wire `UdfType` tags lives in `micro.ts`.
13
+ */
14
+ export {};
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@yydb/yydb` 对 `@voml/vos` 的 re-export 门。
3
+ *
4
+ * 普通 YYDB 用户只依赖 `@yydb/yydb`,不必再显式安装或引入 `@voml/vos`。
5
+ * 这里只转发 YYDB 作者面需要的 VOS 建模面:`v` builder、descriptor 类型与 `Infer` 推导。
6
+ *
7
+ * 刻意不转发:
8
+ * - VOS source 发射:`@voml/vos` 不生成 `.vos` 文本(descriptor 直接编译 canonical artifact),
9
+ * 源码书写与格式化属于 `@voml/vos-language`。
10
+ * - `checkSource` / `VosDiagnostic`:VOS source 检查与语言层诊断属于 `@voml/vos-language`,
11
+ * 不属于 `@voml/vos` 建模面,也不进 YYDB 作者面。
12
+ *
13
+ * 依赖边界见内部决策文档「VOS + YYDB TypeScript 门面设计」§1.1。
14
+ */
15
+ export { v } from '@voml/vos';
16
+ export type { VBuiltinName, VItemName, VWrapperName } from '@voml/vos';
17
+ export type { AnyTypeDescriptor, Attribute, BuiltinKind, FieldDescriptor, Infer, RefDescriptor, ReferenceTarget, ScalarKind, TypeDescriptor, WrapperKind, } from '@voml/vos';
18
+ export type { ClassDescriptor, FieldAccess, FieldMap, ItemKind, ItemMetadataKey, NamedFieldMap, NamedItemDescriptor, NamedItemKind, ObjectDescriptor, RowOf, StructuralDescriptor, TableDescriptor, } from '@voml/vos';
19
+ export type { ReferenceKey, VosFileRef } from '@voml/vos';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@yydb/yydb` 对 `@voml/vos` 的 re-export 门。
3
+ *
4
+ * 普通 YYDB 用户只依赖 `@yydb/yydb`,不必再显式安装或引入 `@voml/vos`。
5
+ * 这里只转发 YYDB 作者面需要的 VOS 建模面:`v` builder、descriptor 类型与 `Infer` 推导。
6
+ *
7
+ * 刻意不转发:
8
+ * - VOS source 发射:`@voml/vos` 不生成 `.vos` 文本(descriptor 直接编译 canonical artifact),
9
+ * 源码书写与格式化属于 `@voml/vos-language`。
10
+ * - `checkSource` / `VosDiagnostic`:VOS source 检查与语言层诊断属于 `@voml/vos-language`,
11
+ * 不属于 `@voml/vos` 建模面,也不进 YYDB 作者面。
12
+ *
13
+ * 依赖边界见内部决策文档「VOS + YYDB TypeScript 门面设计」§1.1。
14
+ */
15
+ export { v } from '@voml/vos';
@@ -1,10 +1,11 @@
1
- /** Parsed `{ ok, rows, error }` envelope from wasm VOS calls. */
1
+ /** Parsed `{ ok, rows, error, code }` envelope from wasm unit-valued calls. */
2
2
  export type WasmRowsResult = {
3
3
  ok: boolean;
4
4
  rows: Record<string, unknown>[];
5
5
  error: string | null;
6
+ code: string | null;
6
7
  };
7
- /** Parsed `{ ok, schema, error }` envelope from wasm `getSchema`. */
8
+ /** Parsed `{ ok, schema, error, code }` envelope from wasm `getSchema`. */
8
9
  export type WasmSchemaResult = {
9
10
  ok: boolean;
10
11
  schema: {
@@ -12,26 +13,28 @@ export type WasmSchemaResult = {
12
13
  document: string;
13
14
  } | null;
14
15
  error: string | null;
16
+ code: string | null;
15
17
  };
16
- /** Parsed `{ ok, value, error }` envelope from wasm `get`. */
18
+ /** Parsed `{ ok, value, error, code }` envelope from wasm `get`. */
17
19
  export type WasmKvGetResult = {
18
20
  ok: boolean;
19
21
  value: number[] | null;
20
22
  error: string | null;
23
+ code: string | null;
21
24
  };
22
- /** Parsed `{ ok, value, error }` envelope from wasm `callScalar`. */
25
+ /** Parsed `{ ok, value, error, code }` envelope from wasm `callScalar`. */
23
26
  export type WasmScalarResult = {
24
27
  ok: boolean;
25
28
  value: string | number | boolean | null;
26
29
  error: string | null;
30
+ code: string | null;
27
31
  };
28
32
  export type WireScalarValue = string | number | boolean | null;
29
33
  export type SchemaVersion = {
30
34
  version: number;
31
35
  document: string;
32
36
  };
33
- export declare function parseWasmRowsResult(payload: string): WasmRowsResult;
34
- export declare function parseWasmUnitResult(payload: string): void;
35
- export declare function parseWasmSchemaResult(payload: string): SchemaVersion | null;
36
- export declare function parseWasmScalarResult(payload: string): WireScalarValue;
37
- export declare function parseWasmKvGetResult(payload: string): Uint8Array | null;
37
+ export declare function parseWasmUnitResult(payload: string, operation: string): void;
38
+ export declare function parseWasmSchemaResult(payload: string, operation: string): SchemaVersion | null;
39
+ export declare function parseWasmScalarResult(payload: string, operation: string): WireScalarValue;
40
+ export declare function parseWasmKvGetResult(payload: string, operation: string): Uint8Array | null;
@@ -1,43 +1,46 @@
1
- function parseJson(payload, label) {
1
+ import { YydbError, YydbErrorCodes } from '@yydb/yydb-client';
2
+ function parseJson(payload, operation) {
2
3
  try {
3
4
  return JSON.parse(payload);
4
5
  }
5
- catch (error) {
6
- const message = error instanceof Error ? error.message : String(error);
7
- throw new Error(`${label}: invalid JSON (${message})`);
6
+ catch (cause) {
7
+ throw new YydbError(YydbErrorCodes.clientDecodeFailure, `${operation}: invalid JSON envelope`, { operation, cause });
8
8
  }
9
9
  }
10
- export function parseWasmRowsResult(payload) {
11
- const parsed = parseJson(payload, 'wasm query/execute');
12
- if (!parsed.ok) {
13
- throw new Error(parsed.error ?? 'wasm query/execute failed');
14
- }
15
- return parsed;
10
+ /**
11
+ * Build the error for a failed wasm envelope. The Rust core always sends a
12
+ * stable `code`; a missing one means the wasm artifact is stale, which is a
13
+ * decode failure rather than an engine failure.
14
+ */
15
+ function envelopeError(envelope, operation) {
16
+ const code = envelope.code ?? YydbErrorCodes.clientDecodeFailure;
17
+ const message = envelope.error ?? `${operation}: wasm envelope carried no message`;
18
+ return new YydbError(code, message, { operation });
16
19
  }
17
- export function parseWasmUnitResult(payload) {
18
- const parsed = parseJson(payload, 'wasm unit call');
20
+ export function parseWasmUnitResult(payload, operation) {
21
+ const parsed = parseJson(payload, operation);
19
22
  if (!parsed.ok) {
20
- throw new Error(parsed.error ?? 'wasm unit call failed');
23
+ throw envelopeError(parsed, operation);
21
24
  }
22
25
  }
23
- export function parseWasmSchemaResult(payload) {
24
- const parsed = parseJson(payload, 'wasm getSchema');
26
+ export function parseWasmSchemaResult(payload, operation) {
27
+ const parsed = parseJson(payload, operation);
25
28
  if (!parsed.ok) {
26
- throw new Error(parsed.error ?? 'wasm getSchema failed');
29
+ throw envelopeError(parsed, operation);
27
30
  }
28
31
  return parsed.schema;
29
32
  }
30
- export function parseWasmScalarResult(payload) {
31
- const parsed = parseJson(payload, 'wasm callScalar');
33
+ export function parseWasmScalarResult(payload, operation) {
34
+ const parsed = parseJson(payload, operation);
32
35
  if (!parsed.ok) {
33
- throw new Error(parsed.error ?? 'wasm callScalar failed');
36
+ throw envelopeError(parsed, operation);
34
37
  }
35
38
  return parsed.value;
36
39
  }
37
- export function parseWasmKvGetResult(payload) {
38
- const parsed = parseJson(payload, 'wasm get');
40
+ export function parseWasmKvGetResult(payload, operation) {
41
+ const parsed = parseJson(payload, operation);
39
42
  if (!parsed.ok) {
40
- throw new Error(parsed.error ?? 'wasm get failed');
43
+ throw envelopeError(parsed, operation);
41
44
  }
42
45
  if (parsed.value === null) {
43
46
  return null;
@@ -1 +1 @@
1
- export { checkSchema, createMemorySession, initWasm, introspectSchema, openPersistentSession, queryMemory, resetWasmBindingForTests, yydbVersion, type CheckSchemaResult, type InitWasmOptions, type WasmInitInput, type WasmSession, } from '@yydb/yydb-unknown-wasm32';
1
+ export { checkSchema, createMemorySession, initWasm, introspectSchema, openPersistentSession, resetWasmBindingForTests, yydbVersion, type CheckSchemaResult, type InitWasmOptions, type WasmInitInput, type WasmSession, } from '@yydb/yydb-unknown-wasm32';
@@ -1 +1 @@
1
- export { checkSchema, createMemorySession, initWasm, introspectSchema, openPersistentSession, queryMemory, resetWasmBindingForTests, yydbVersion, } from '@yydb/yydb-unknown-wasm32';
1
+ export { checkSchema, createMemorySession, initWasm, introspectSchema, openPersistentSession, resetWasmBindingForTests, yydbVersion, } from '@yydb/yydb-unknown-wasm32';
@@ -1,5 +1,5 @@
1
1
  import { defineMicro as buildMicro, type DefinedMicro, type MicroHandle } from '../shared/micro.js';
2
- import type { UdfTypeDescriptor } from '../shared/udf-types.js';
2
+ import type { UdfScalarDescriptor } from '../shared/udf-types.js';
3
3
  import { type SchemaVersion } from '../shared/wasm-envelope.js';
4
4
  import { type CheckSchemaResult, type InitWasmOptions } from './binding.js';
5
5
  export type WasmOpenOptions = InitWasmOptions;
@@ -30,24 +30,21 @@ export declare class Database {
30
30
  getSchema(): Promise<SchemaVersion | null>;
31
31
  get(key: string): Promise<Uint8Array | null>;
32
32
  put(key: string, value: Uint8Array | string): Promise<void>;
33
- /** VOS read pipeline (for example `User.filter(x => x.active).collect()`). */
34
- query(source: string): Record<string, unknown>[];
35
- /** Unit-valued VOS write programs (for example `User { … }.insert()`). */
36
- execute(source: string): void;
37
33
  /**
38
34
  * Build a typed session-local micro definition. Does not register it with
39
35
  * the engine until `registerMicro` is called.
40
36
  */
41
- defineMicro<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(definition: Parameters<typeof buildMicro<TArgs, TReturn>>[0]): DefinedMicro<TArgs, TReturn>;
37
+ defineMicro<TArgs extends readonly UdfScalarDescriptor[], TReturn extends UdfScalarDescriptor>(definition: Parameters<typeof buildMicro<TArgs, TReturn>>[0]): DefinedMicro<TArgs, TReturn>;
42
38
  /**
43
39
  * Install a `defineMicro` definition into the current session registry and
44
40
  * sync metadata to the embedded engine. Host micros are session-local.
45
41
  */
46
- registerMicro<TArgs extends readonly UdfTypeDescriptor[], TReturn extends UdfTypeDescriptor>(definition: DefinedMicro<TArgs, TReturn>): Promise<MicroHandle>;
42
+ registerMicro<TArgs extends readonly UdfScalarDescriptor[], TReturn extends UdfScalarDescriptor>(definition: DefinedMicro<TArgs, TReturn>): Promise<MicroHandle>;
47
43
  /** Invoke a registered scalar UDF on the embedded engine. */
48
44
  callScalar(name: string, version: number, args: readonly (string | number | boolean | null)[]): Promise<string | number | boolean | null>;
49
45
  /** Whether this handle owns a persistent OPFS session. */
50
46
  isPersistent(): boolean;
51
- close(): void;
47
+ /** Close the embedded session. Idempotent; further calls fail with `yydb.session.closed`. */
48
+ close(): Promise<void>;
52
49
  private requireSession;
53
50
  }
@@ -1,6 +1,6 @@
1
- import { encodeMicroRegister, encodeScalarCall } from '@yydb/yydb-client';
2
- import { defineMicro as buildMicro, microFingerprint, MicroSessionRegistry } from '../shared/micro.js';
3
- import { parseWasmKvGetResult, parseWasmRowsResult, parseWasmScalarResult, parseWasmSchemaResult, parseWasmUnitResult, } from '../shared/wasm-envelope.js';
1
+ import { encodeMicroRegister, encodeScalarCall, YydbError, YydbErrorCodes } from '@yydb/yydb-client';
2
+ import { defineMicro as buildMicro, microFingerprint, udfWireKind, MicroSessionRegistry, } from '../shared/micro.js';
3
+ import { parseWasmKvGetResult, parseWasmScalarResult, parseWasmSchemaResult, parseWasmUnitResult, } from '../shared/wasm-envelope.js';
4
4
  import { checkSchema, createMemorySession, initWasm, openPersistentSession, yydbVersion, } from './binding.js';
5
5
  /**
6
6
  * Browser-facing YYDB handle backed by an in-process wasm session.
@@ -40,7 +40,7 @@ export class Database {
40
40
  }
41
41
  /** Database info text (`path=…\\n…`), matching the YY wire `Info` reply. */
42
42
  async info() {
43
- return this.requireSession().info();
43
+ return this.requireSession('info').info();
44
44
  }
45
45
  /** Parse and validate a VOS schema document without opening a session. */
46
46
  checkSchema(source) {
@@ -48,25 +48,17 @@ export class Database {
48
48
  }
49
49
  /** Persist schema document. `version` is accepted for Node API parity; wasm uses the document body. */
50
50
  async ensureSchema(_version, document) {
51
- parseWasmUnitResult(this.requireSession().ensureSchema(document));
51
+ parseWasmUnitResult(this.requireSession('schemaEnsure').ensureSchema(document), 'schemaEnsure');
52
52
  }
53
53
  async getSchema() {
54
- return parseWasmSchemaResult(this.requireSession().getSchema());
54
+ return parseWasmSchemaResult(this.requireSession('schemaGet').getSchema(), 'schemaGet');
55
55
  }
56
56
  async get(key) {
57
- return parseWasmKvGetResult(this.requireSession().get(key));
57
+ return parseWasmKvGetResult(this.requireSession('kvGet').get(key), 'kvGet');
58
58
  }
59
59
  async put(key, value) {
60
60
  const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : value;
61
- parseWasmUnitResult(this.requireSession().put(key, bytes));
62
- }
63
- /** VOS read pipeline (for example `User.filter(x => x.active).collect()`). */
64
- query(source) {
65
- return parseWasmRowsResult(this.requireSession().query(source)).rows;
66
- }
67
- /** Unit-valued VOS write programs (for example `User { … }.insert()`). */
68
- execute(source) {
69
- parseWasmUnitResult(this.requireSession().execute(source));
61
+ parseWasmUnitResult(this.requireSession('kvPut').put(key, bytes), 'kvPut');
70
62
  }
71
63
  /**
72
64
  * Build a typed session-local micro definition. Does not register it with
@@ -87,29 +79,31 @@ export class Database {
87
79
  udfVersion: definition.version,
88
80
  name: definition.name,
89
81
  functionId: handle.functionId,
90
- args: definition.args.map((arg) => arg.kind),
91
- returns: definition.returns.kind,
82
+ args: definition.args.map(udfWireKind),
83
+ returns: udfWireKind(definition.returns),
92
84
  fingerprint: microFingerprint(definition.name, definition.version),
93
85
  });
94
- parseWasmUnitResult(this.requireSession().registerMicro(body));
86
+ parseWasmUnitResult(this.requireSession('microRegister').registerMicro(body), 'microRegister');
95
87
  return handle;
96
88
  }
97
89
  /** Invoke a registered scalar UDF on the embedded engine. */
98
90
  async callScalar(name, version, args) {
99
91
  const body = encodeScalarCall(name, version, args);
100
- return parseWasmScalarResult(this.requireSession().callScalar(body));
92
+ return parseWasmScalarResult(this.requireSession('callScalar').callScalar(body), 'callScalar');
101
93
  }
102
94
  /** Whether this handle owns a persistent OPFS session. */
103
95
  isPersistent() {
104
96
  return this.kind === 'persistent';
105
97
  }
106
- close() {
107
- this.session?.close();
98
+ /** Close the embedded session. Idempotent; further calls fail with `yydb.session.closed`. */
99
+ async close() {
100
+ const session = this.session;
108
101
  this.session = null;
102
+ session?.close();
109
103
  }
110
- requireSession() {
104
+ requireSession(operation) {
111
105
  if (!this.session) {
112
- throw new Error('@yydb/yydb/wasm: database session is closed');
106
+ throw new YydbError(YydbErrorCodes.sessionClosed, `${operation}: @yydb/yydb/wasm session is closed`, { operation });
113
107
  }
114
108
  return this.session;
115
109
  }
@@ -1,5 +1,8 @@
1
1
  export { Database, type WasmOpenOptions } from './database.js';
2
- export { checkSchema, createMemorySession, initWasm, introspectSchema, openPersistentSession, queryMemory, resetWasmBindingForTests, yydbVersion, type CheckSchemaResult, type InitWasmOptions, type WasmInitInput, type WasmSession, } from './binding.js';
2
+ export { YydbError, YydbErrorCodes, isRetryableYydbCode, isYydbError } from '@yydb/yydb-client';
3
+ export type { YydbErrorCode, YydbErrorOptions } from '@yydb/yydb-client';
4
+ export { checkSchema, createMemorySession, initWasm, introspectSchema, openPersistentSession, resetWasmBindingForTests, yydbVersion, type CheckSchemaResult, type InitWasmOptions, type WasmInitInput, type WasmSession, } from './binding.js';
3
5
  export { defineMicro, type DefinedMicro, type MicroHandle, type TsMicroDefinitionInput, MicroSessionRegistry } from '../shared/micro.js';
4
- export { bool, i64, nullType, text, type InferUdfArgs, type InferUdfReturn, type MicroEffect, type MicroInvocationMode, type UdfScalarKind, type UdfTypeDescriptor, } from '../shared/udf-types.js';
6
+ export { type InferUdfArgs, type InferUdfReturn, type MicroEffect, type MicroInvocationMode, type UdfScalarDescriptor, type UdfScalarKind, } from '../shared/udf-types.js';
5
7
  export type { SchemaVersion } from '../shared/wasm-envelope.js';
8
+ export * from '../shared/vos.js';
@@ -1,4 +1,5 @@
1
1
  export { Database } from './database.js';
2
- export { checkSchema, createMemorySession, initWasm, introspectSchema, openPersistentSession, queryMemory, resetWasmBindingForTests, yydbVersion, } from './binding.js';
2
+ export { YydbError, YydbErrorCodes, isRetryableYydbCode, isYydbError } from '@yydb/yydb-client';
3
+ export { checkSchema, createMemorySession, initWasm, introspectSchema, openPersistentSession, resetWasmBindingForTests, yydbVersion, } from './binding.js';
3
4
  export { defineMicro, MicroSessionRegistry } from '../shared/micro.js';
4
- export { bool, i64, nullType, text, } from '../shared/udf-types.js';
5
+ export * from '../shared/vos.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yydb/yydb",
3
- "version": "0.0.5",
3
+ "version": "0.0.7",
4
4
  "description": "YYDB all-in-one: Node embedded engine and CLI, browser wasm core",
5
5
  "license": "MPL-2.0",
6
6
  "type": "module",
@@ -57,8 +57,9 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "@vmz/commander": "^0.2.0",
60
- "@yydb/yydb-client": "0.0.5",
61
- "@yydb/yydb-unknown-wasm32": "0.0.5"
60
+ "@voml/vos": "^0.0.1",
61
+ "@yydb/yydb-client": "0.0.7",
62
+ "@yydb/yydb-unknown-wasm32": "0.0.7"
62
63
  },
63
64
  "devDependencies": {
64
65
  "@types/node": "^20.10.0",
@@ -68,9 +69,9 @@
68
69
  "node": ">=18"
69
70
  },
70
71
  "optionalDependencies": {
71
- "@yydb/yydb-win32-x64": "0.0.5",
72
- "@yydb/yydb-linux-x64": "0.0.5",
73
- "@yydb/yydb-darwin-x64": "0.0.5",
74
- "@yydb/yydb-darwin-arm64": "0.0.5"
72
+ "@yydb/yydb-win32-x64": "0.0.7",
73
+ "@yydb/yydb-linux-x64": "0.0.7",
74
+ "@yydb/yydb-darwin-x64": "0.0.7",
75
+ "@yydb/yydb-darwin-arm64": "0.0.7"
75
76
  }
76
77
  }