@olivia-db/client 0.1.1 → 0.1.3
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/dist/dsl.d.ts +498 -0
- package/dist/dsl.js +957 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8 -0
- package/dist/native.d.ts +10 -0
- package/dist/native.js +19 -4
- package/package.json +5 -1
- package/src/dsl.ts +1228 -0
- package/src/index.ts +9 -0
- package/src/native.ts +26 -4
package/src/dsl.ts
ADDED
|
@@ -0,0 +1,1228 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Typed models and queries: the runtime of the code `oliviadb codegen --lang ts` generates
|
|
4
|
+
* (`sdk-dsl.md` of the specification). Generated code holds the schema's models, keys, paths,
|
|
5
|
+
* patches and new-node types as types, and tables that describe them; every request is made
|
|
6
|
+
* here, over HTTP (OliviaDbClient) or the native protocol (NativeClient of
|
|
7
|
+
* `@olivia-db/client/native`).
|
|
8
|
+
*
|
|
9
|
+
* const db = new Db(new OliviaDbClient({ baseUrl, apiKey }));
|
|
10
|
+
* const c = await db.get(Customer.key("42"), { tree: true });
|
|
11
|
+
* await db.txn((t) => {
|
|
12
|
+
* t.update(Customer.key("42").account("1001"), { add: { balance: amount.neg() } });
|
|
13
|
+
* t.update(Customer.key("42").account("1002"), { add: { balance: amount } });
|
|
14
|
+
* });
|
|
15
|
+
*
|
|
16
|
+
* A read's answer is decoded into the model from the node form the network API documents
|
|
17
|
+
* (`docs/network-api.md`, "Native aggregates"): over HTTP its JSON, over the native protocol
|
|
18
|
+
* the rows given in that form by the row reader (`Rows.toJson`). A node written with another
|
|
19
|
+
* layout of its type than the one the generated code was made for (an older version of the
|
|
20
|
+
* schema) is read by field number from that layout's fields (the connection's descriptors, or
|
|
21
|
+
* `GET /v1/layouts/{id}` over HTTP), fields it lacks with their declared defaults (`adapt`); a
|
|
22
|
+
* field whose type conflicts is a SchemaMismatchError naming it, never decoded by guess. A field the model requires and the answer
|
|
23
|
+
* lacks or shows masked is a DecodeError naming it, never a default.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { OliviaDbClient, OliviaDbError, type Json, type U64 } from "./index.ts";
|
|
27
|
+
|
|
28
|
+
// ---- errors ----
|
|
29
|
+
|
|
30
|
+
/** An answer the generated code cannot read as its model (a field missing or of another type). */
|
|
31
|
+
export class DecodeError extends Error {
|
|
32
|
+
override readonly name = "DecodeError";
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A node written with a layout that conflicts with the generated code's: another type under the
|
|
36
|
+
* same field number, or a layout the connection cannot describe. */
|
|
37
|
+
export class SchemaMismatchError extends Error {
|
|
38
|
+
override readonly name = "SchemaMismatchError";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ---- values ----
|
|
42
|
+
|
|
43
|
+
/** An exact decimal (`decimal(p,s)`): `unscaled × 10^-scale`. */
|
|
44
|
+
export class Decimal {
|
|
45
|
+
readonly unscaled: bigint;
|
|
46
|
+
readonly scale: number;
|
|
47
|
+
constructor(unscaled: bigint, scale: number) {
|
|
48
|
+
this.unscaled = unscaled;
|
|
49
|
+
this.scale = scale;
|
|
50
|
+
}
|
|
51
|
+
/** `-12.50`, `3`, `+0.5`; anything else throws DecodeError. */
|
|
52
|
+
static parse(s: string): Decimal {
|
|
53
|
+
const m = /^([+-]?)(\d*)(?:\.(\d*))?$/.exec(s);
|
|
54
|
+
if (!m || (m[2] === "" && (m[3] ?? "") === "")) throw new DecodeError(`decimal ${JSON.stringify(s)}`);
|
|
55
|
+
const f = m[3] ?? "";
|
|
56
|
+
const u = BigInt(`${m[2]}${f}` || "0");
|
|
57
|
+
return new Decimal(m[1] === "-" ? -u : u, f.length);
|
|
58
|
+
}
|
|
59
|
+
private at(scale: number): bigint {
|
|
60
|
+
return this.unscaled * 10n ** BigInt(scale - this.scale);
|
|
61
|
+
}
|
|
62
|
+
neg(): Decimal {
|
|
63
|
+
return new Decimal(-this.unscaled, this.scale);
|
|
64
|
+
}
|
|
65
|
+
add(o: Decimal): Decimal {
|
|
66
|
+
const s = Math.max(this.scale, o.scale);
|
|
67
|
+
return new Decimal(this.at(s) + o.at(s), s);
|
|
68
|
+
}
|
|
69
|
+
/** Equal values, whatever their scales (`1.50` equals `1.5`). */
|
|
70
|
+
equals(o: Decimal): boolean {
|
|
71
|
+
const s = Math.max(this.scale, o.scale);
|
|
72
|
+
return this.at(s) === o.at(s);
|
|
73
|
+
}
|
|
74
|
+
toString(): string {
|
|
75
|
+
const neg = this.unscaled < 0n;
|
|
76
|
+
let d = (neg ? -this.unscaled : this.unscaled).toString();
|
|
77
|
+
if (this.scale > 0) {
|
|
78
|
+
d = d.padStart(this.scale + 1, "0");
|
|
79
|
+
d = `${d.slice(0, d.length - this.scale)}.${d.slice(d.length - this.scale)}`;
|
|
80
|
+
}
|
|
81
|
+
return neg ? `-${d}` : d;
|
|
82
|
+
}
|
|
83
|
+
toJSON(): string {
|
|
84
|
+
return this.toString();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Days from a civil date and back (proleptic Gregorian; H. Hinnant, "chrono-Compatible
|
|
89
|
+
// Low-Level Date Algorithms", days_from_civil / civil_from_days).
|
|
90
|
+
function daysFromCivil(y: number, m: number, d: number): number {
|
|
91
|
+
y -= m <= 2 ? 1 : 0;
|
|
92
|
+
const era = Math.floor(y / 400);
|
|
93
|
+
const yoe = y - era * 400;
|
|
94
|
+
const doy = Math.floor((153 * ((m + 9) % 12) + 2) / 5) + d - 1;
|
|
95
|
+
const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
|
|
96
|
+
return era * 146097 + doe - 719468;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function civilFromDays(z: number): [number, number, number] {
|
|
100
|
+
z += 719468;
|
|
101
|
+
const era = Math.floor(z / 146097);
|
|
102
|
+
const doe = z - era * 146097;
|
|
103
|
+
const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
|
|
104
|
+
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
|
|
105
|
+
const mp = Math.floor((5 * doy + 2) / 153);
|
|
106
|
+
const d = doy - Math.floor((153 * mp + 2) / 5) + 1;
|
|
107
|
+
const m = mp < 10 ? mp + 3 : mp - 9;
|
|
108
|
+
return [yoe + era * 400 + (m <= 2 ? 1 : 0), m, d];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const pad = (n: number, w: number) => String(n).padStart(w, "0");
|
|
112
|
+
|
|
113
|
+
/** A calendar date (`date`): days since 1970-01-01. */
|
|
114
|
+
export class PlainDate {
|
|
115
|
+
readonly days: number;
|
|
116
|
+
constructor(days: number) {
|
|
117
|
+
this.days = days;
|
|
118
|
+
}
|
|
119
|
+
static of(y: number, m: number, d: number): PlainDate {
|
|
120
|
+
return new PlainDate(daysFromCivil(y, m, d));
|
|
121
|
+
}
|
|
122
|
+
/** `YYYY-MM-DD`. */
|
|
123
|
+
static parse(s: string): PlainDate {
|
|
124
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
|
|
125
|
+
if (!m || +m[2] < 1 || +m[2] > 12 || +m[3] < 1 || +m[3] > 31) throw new DecodeError(`date ${JSON.stringify(s)}`);
|
|
126
|
+
return PlainDate.of(+m[1], +m[2], +m[3]);
|
|
127
|
+
}
|
|
128
|
+
equals(o: PlainDate): boolean {
|
|
129
|
+
return this.days === o.days;
|
|
130
|
+
}
|
|
131
|
+
toString(): string {
|
|
132
|
+
const [y, m, d] = civilFromDays(this.days);
|
|
133
|
+
return `${pad(y, 4)}-${pad(m, 2)}-${pad(d, 2)}`;
|
|
134
|
+
}
|
|
135
|
+
toJSON(): string {
|
|
136
|
+
return this.toString();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** An instant in UTC (`timestamp`): microseconds since 1970-01-01T00:00:00Z. */
|
|
141
|
+
export class Instant {
|
|
142
|
+
readonly micros: bigint;
|
|
143
|
+
constructor(micros: bigint) {
|
|
144
|
+
this.micros = micros;
|
|
145
|
+
}
|
|
146
|
+
/** `YYYY-MM-DDTHH:MM:SS[.f{1,6}]Z`, the form the network API shows (it writes six digits). */
|
|
147
|
+
static parse(s: string): Instant {
|
|
148
|
+
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?Z$/.exec(s);
|
|
149
|
+
if (!m) throw new DecodeError(`timestamp ${JSON.stringify(s)}`);
|
|
150
|
+
const day = BigInt(PlainDate.parse(m[1]).days);
|
|
151
|
+
const secs = day * 86400n + BigInt(+m[2] * 3600 + +m[3] * 60 + +m[4]);
|
|
152
|
+
return new Instant(secs * 1_000_000n + BigInt((m[5] ?? "").padEnd(6, "0")));
|
|
153
|
+
}
|
|
154
|
+
equals(o: Instant): boolean {
|
|
155
|
+
return this.micros === o.micros;
|
|
156
|
+
}
|
|
157
|
+
toString(): string {
|
|
158
|
+
let s = this.micros / 1_000_000n;
|
|
159
|
+
let us = this.micros % 1_000_000n;
|
|
160
|
+
if (us < 0n) {
|
|
161
|
+
us += 1_000_000n;
|
|
162
|
+
s -= 1n;
|
|
163
|
+
}
|
|
164
|
+
let days = s / 86400n;
|
|
165
|
+
let rem = s % 86400n;
|
|
166
|
+
if (rem < 0n) {
|
|
167
|
+
rem += 86400n;
|
|
168
|
+
days -= 1n;
|
|
169
|
+
}
|
|
170
|
+
const r = Number(rem);
|
|
171
|
+
const t = `${pad(Math.floor(r / 3600), 2)}:${pad(Math.floor(r / 60) % 60, 2)}:${pad(r % 60, 2)}`;
|
|
172
|
+
return `${new PlainDate(Number(days)).toString()}T${t}.${us.toString().padStart(6, "0")}Z`;
|
|
173
|
+
}
|
|
174
|
+
toJSON(): string {
|
|
175
|
+
return this.toString();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** A reference field (`ref T`): the target's levels below where the reference starts, as the
|
|
180
|
+
* network API shows them (`""`: none). */
|
|
181
|
+
export class Ref<T> {
|
|
182
|
+
readonly text: string;
|
|
183
|
+
declare readonly target?: T;
|
|
184
|
+
constructor(text: string) {
|
|
185
|
+
this.text = text;
|
|
186
|
+
}
|
|
187
|
+
isNone(): boolean {
|
|
188
|
+
return this.text === "";
|
|
189
|
+
}
|
|
190
|
+
toJSON(): string {
|
|
191
|
+
return this.text;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function hex(b: Uint8Array): string {
|
|
196
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** A value as the network API's JSON writes it. */
|
|
200
|
+
export function toJson(v: unknown): unknown {
|
|
201
|
+
if (v instanceof Decimal || v instanceof PlainDate || v instanceof Instant) return v.toString();
|
|
202
|
+
if (v instanceof Ref) return v.text;
|
|
203
|
+
if (v instanceof Uint8Array) return hex(v);
|
|
204
|
+
if (typeof v === "bigint") return (v < 0n ? -v : v) < 1n << 53n ? Number(v) : v.toString();
|
|
205
|
+
return v;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** A key part's text in a path (before percent-encoding). */
|
|
209
|
+
export function keyText(v: unknown): string {
|
|
210
|
+
const j = toJson(v);
|
|
211
|
+
return typeof j === "string" ? j : JSON.stringify(j);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** How a field's JSON value becomes the model's value (`undefined`: not of the type). */
|
|
215
|
+
export interface Conv<T> {
|
|
216
|
+
from(v: unknown): T | undefined;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const intOf = (v: unknown): bigint | undefined => {
|
|
220
|
+
if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);
|
|
221
|
+
if (typeof v === "string" && /^-?\d+$/.test(v)) return BigInt(v);
|
|
222
|
+
return undefined;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
function tryParse<T>(f: (s: string) => T): Conv<T> {
|
|
226
|
+
return {
|
|
227
|
+
from: (v) => {
|
|
228
|
+
if (typeof v === "number") v = String(v);
|
|
229
|
+
if (typeof v !== "string") return undefined;
|
|
230
|
+
try {
|
|
231
|
+
return f(v);
|
|
232
|
+
} catch {
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** The conversions generated tables name, one per schema type. */
|
|
240
|
+
export const V = {
|
|
241
|
+
str: { from: (v: unknown) => (typeof v === "string" ? v : undefined) } as Conv<string>,
|
|
242
|
+
/** `int8..int32`, `uint8..uint16`. */
|
|
243
|
+
int: {
|
|
244
|
+
from: (v: unknown) => {
|
|
245
|
+
const b = intOf(v);
|
|
246
|
+
return b === undefined ? undefined : Number(b);
|
|
247
|
+
},
|
|
248
|
+
} as Conv<number>,
|
|
249
|
+
/** `int64`, `uint32`, `uint64`. */
|
|
250
|
+
big: { from: intOf } as Conv<bigint>,
|
|
251
|
+
float: { from: (v: unknown) => (typeof v === "number" ? v : undefined) } as Conv<number>,
|
|
252
|
+
bool: { from: (v: unknown) => (typeof v === "boolean" ? v : undefined) } as Conv<boolean>,
|
|
253
|
+
dec: tryParse((s) => Decimal.parse(s)),
|
|
254
|
+
date: tryParse((s) => PlainDate.parse(s)),
|
|
255
|
+
ts: tryParse((s) => Instant.parse(s)),
|
|
256
|
+
bytes: {
|
|
257
|
+
from: (v: unknown) =>
|
|
258
|
+
typeof v === "string" && /^(?:[0-9a-fA-F]{2})*$/.test(v)
|
|
259
|
+
? Uint8Array.from(v.match(/../g) ?? [], (h) => parseInt(h, 16))
|
|
260
|
+
: undefined,
|
|
261
|
+
} as Conv<Uint8Array>,
|
|
262
|
+
ref<T>(): Conv<Ref<T>> {
|
|
263
|
+
return { from: (v) => (typeof v === "string" ? new Ref<T>(v) : undefined) };
|
|
264
|
+
},
|
|
265
|
+
oneOf<T extends string>(members: readonly T[]): Conv<T> {
|
|
266
|
+
return {
|
|
267
|
+
from: (v) => (typeof v === "string" && (members as readonly string[]).includes(v) ? (v as T) : undefined),
|
|
268
|
+
};
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
// ---- the tables of generated code ----
|
|
273
|
+
|
|
274
|
+
/** A field of a model (by the language's name in the table that holds it). */
|
|
275
|
+
export interface FieldDef {
|
|
276
|
+
/** The schema's name. */
|
|
277
|
+
readonly name: string;
|
|
278
|
+
readonly conv: Conv<unknown>;
|
|
279
|
+
/** Every read shows it. */
|
|
280
|
+
readonly required: boolean;
|
|
281
|
+
/** A discriminator: its cases' fields by member. */
|
|
282
|
+
readonly cases?: Readonly<Record<string, Readonly<Record<string, FieldDef>>>>;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** A node type as generated code describes it. */
|
|
286
|
+
export interface ModelType<M> {
|
|
287
|
+
/** The type path (`Customer/Account`). */
|
|
288
|
+
readonly type: string;
|
|
289
|
+
/** The layout id (`sha256:...`) of the type in the schema the code was generated from. */
|
|
290
|
+
readonly layout: string;
|
|
291
|
+
/** The model's fields as [number, name, type text]: how a node written with another layout
|
|
292
|
+
* of the type is read (`adapt`). */
|
|
293
|
+
readonly numbered: ReadonlyArray<readonly [number, string, string]>;
|
|
294
|
+
readonly key: Readonly<Record<string, FieldDef>>;
|
|
295
|
+
readonly twin: boolean;
|
|
296
|
+
/** The fields a read shows (masked ones as strings). */
|
|
297
|
+
readonly fields: Readonly<Record<string, FieldDef>>;
|
|
298
|
+
/** Child listings a tree read fills: property -> the child type's name and model. */
|
|
299
|
+
readonly children: Readonly<Record<string, readonly [string, () => ModelType<unknown>]>>;
|
|
300
|
+
/** Every field of the type as declared: what patches and new nodes are written with. */
|
|
301
|
+
readonly decl: Readonly<Record<string, FieldDef>>;
|
|
302
|
+
/** Fields of the model that a write may send back (not masked). */
|
|
303
|
+
readonly writable: readonly string[];
|
|
304
|
+
/** Phantom: the model's type. */
|
|
305
|
+
readonly model?: M;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const typeName = (tpath: string) => tpath.slice(tpath.lastIndexOf("/") + 1);
|
|
309
|
+
|
|
310
|
+
function nodeName(v: Json): string {
|
|
311
|
+
return typeof v.type === "string" ? v.type : "?";
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function readField(v: Json, where: Json, def: FieldDef, required: boolean): unknown {
|
|
315
|
+
const x = where[def.name];
|
|
316
|
+
if (x === undefined || x === null) {
|
|
317
|
+
if (required)
|
|
318
|
+
throw new DecodeError(
|
|
319
|
+
`${nodeName(v)}.${def.name}: the answer has no field ${def.name} (a profile that does not show it: generate the code with that profile)`,
|
|
320
|
+
);
|
|
321
|
+
return undefined;
|
|
322
|
+
}
|
|
323
|
+
const out = def.conv.from(x);
|
|
324
|
+
if (out === undefined)
|
|
325
|
+
throw new DecodeError(
|
|
326
|
+
`${nodeName(v)}.${def.name}: ${JSON.stringify(x)} is not of the field's type (a masked value: generate the code with the caller's profile)`,
|
|
327
|
+
);
|
|
328
|
+
return out;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function readFields(
|
|
332
|
+
v: Json,
|
|
333
|
+
defs: Readonly<Record<string, FieldDef>>,
|
|
334
|
+
out: Record<string, unknown>,
|
|
335
|
+
all: boolean,
|
|
336
|
+
): void {
|
|
337
|
+
const fields = (v.fields ?? {}) as Json;
|
|
338
|
+
for (const [prop, def] of Object.entries(defs)) {
|
|
339
|
+
if (def.cases) {
|
|
340
|
+
const member = readField(v, fields, def, def.required && all) as string | undefined;
|
|
341
|
+
if (member === undefined) continue;
|
|
342
|
+
const fs = def.cases[member];
|
|
343
|
+
if (!fs) throw new DecodeError(`${nodeName(v)}.${def.name}: ${member} is no member`);
|
|
344
|
+
const c: Record<string, unknown> = { [prop]: member };
|
|
345
|
+
readFields(v, fs, c, all);
|
|
346
|
+
out[prop] = c;
|
|
347
|
+
} else {
|
|
348
|
+
const x = readField(v, fields, def, def.required && all);
|
|
349
|
+
if (x !== undefined) out[prop] = x;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** A writer layout's fields: [number, name, type text] each. */
|
|
355
|
+
export type LayoutFields = ReadonlyArray<readonly [number, string, string]>;
|
|
356
|
+
|
|
357
|
+
/** Where the fields of writer layouts come from: `undefined` when not asked for yet (decoding
|
|
358
|
+
* then stops with `NeedLayout`, the caller fetches it and decodes again), `null` when the
|
|
359
|
+
* connection does not know the layout. */
|
|
360
|
+
export interface Layouts {
|
|
361
|
+
fields(id: string): LayoutFields | null | undefined;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Decoding needs the fields of a writer layout not fetched yet. */
|
|
365
|
+
export class NeedLayout extends Error {
|
|
366
|
+
readonly id: string;
|
|
367
|
+
constructor(id: string) {
|
|
368
|
+
super(`the fields of layout ${id} are needed`);
|
|
369
|
+
this.name = "NeedLayout";
|
|
370
|
+
this.id = id;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** The value a field has in a version written before the field existed (`spec/schema.md` 4.5),
|
|
375
|
+
* by its type as descriptors write it, in the network API's JSON form: an empty string, zero,
|
|
376
|
+
* false, the first member of an enum, 1970-01-01 for a date and 1970-01-01T00:00:00Z for a
|
|
377
|
+
* timestamp, bytes of zeros, an empty reference. */
|
|
378
|
+
export function defaultOf(ty: string): unknown {
|
|
379
|
+
const inner = (p: string) => (ty.startsWith(p) && ty.endsWith(")") ? ty.slice(p.length, -1) : undefined);
|
|
380
|
+
if (ty.startsWith("string(") || ty === "text") return "";
|
|
381
|
+
const b = inner("bytes(");
|
|
382
|
+
if (b !== undefined) return "00".repeat(Number(b.trim()) || 0);
|
|
383
|
+
const d = inner("decimal(");
|
|
384
|
+
if (d !== undefined) {
|
|
385
|
+
const scale = Number((d.split(",")[1] ?? "0").trim()) || 0;
|
|
386
|
+
return scale === 0 ? "0" : `0.${"0".repeat(scale)}`;
|
|
387
|
+
}
|
|
388
|
+
if (ty.startsWith("int") || ty.startsWith("uint")) return 0;
|
|
389
|
+
if (ty === "date") return "1970-01-01";
|
|
390
|
+
if (ty === "timestamp") return "1970-01-01T00:00:00.000000Z";
|
|
391
|
+
if (ty === "bool") return false;
|
|
392
|
+
if (ty === "float64") return 0;
|
|
393
|
+
try {
|
|
394
|
+
const v = JSON.parse(ty) as Json;
|
|
395
|
+
if (Array.isArray(v.enum)) return ((v.enum as Json[])[0] ?? {}).name ?? "";
|
|
396
|
+
} catch {
|
|
397
|
+
// not JSON: a reference or an unknown type, read as text
|
|
398
|
+
}
|
|
399
|
+
return "";
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Whether a value written as type `written` reads as type `model` under the same field number:
|
|
403
|
+
* the same type, an enum the model's widens (every member, name and stored value, still there),
|
|
404
|
+
* or a reference (its value is the target's path either way). */
|
|
405
|
+
export function compatible(written: string, model: string): boolean {
|
|
406
|
+
if (written === model) return true;
|
|
407
|
+
let w: Json, m: Json;
|
|
408
|
+
try {
|
|
409
|
+
w = JSON.parse(written) as Json;
|
|
410
|
+
m = JSON.parse(model) as Json;
|
|
411
|
+
} catch {
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
if (Array.isArray(w.enum) && Array.isArray(m.enum)) {
|
|
415
|
+
const me = m.enum as Json[];
|
|
416
|
+
return (w.enum as Json[]).every((a) => me.some((b) => a.name === b.name && a.value === b.value));
|
|
417
|
+
}
|
|
418
|
+
return w.ref !== undefined && m.ref !== undefined;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** The node as the model's layout shows it (`spec/sdk-dsl.md` 1): as it is when written with that
|
|
422
|
+
* layout; else its fields read by field number from the writer layout's fields: a field the
|
|
423
|
+
* writer's layout lacks gets the value the server showed for it or its declared default, a field
|
|
424
|
+
* the model lacks is left out, a field under another name is renamed. A field whose written type
|
|
425
|
+
* conflicts with the model's is a SchemaMismatchError naming it and both types. */
|
|
426
|
+
export function adapt(mt: ModelType<unknown>, v: Json, layouts?: Layouts): Json {
|
|
427
|
+
const got = String(v.layout);
|
|
428
|
+
if (got === mt.layout) return v;
|
|
429
|
+
const written = layouts?.fields(got);
|
|
430
|
+
if (written === undefined && layouts) throw new NeedLayout(got);
|
|
431
|
+
if (!written)
|
|
432
|
+
throw new SchemaMismatchError(
|
|
433
|
+
`${mt.type}: the node was written with layout ${got}, whose fields the connection does not know (the generated code has ${mt.layout})`,
|
|
434
|
+
);
|
|
435
|
+
const had = (v.fields ?? {}) as Json;
|
|
436
|
+
const out: Json = {};
|
|
437
|
+
for (const [no, name, ty] of mt.numbered) {
|
|
438
|
+
const w = written.find((x) => x[0] === no);
|
|
439
|
+
if (w) {
|
|
440
|
+
if (!compatible(w[2], ty))
|
|
441
|
+
throw new SchemaMismatchError(
|
|
442
|
+
`${mt.type}.${name} (field ${no}): the node was written with layout ${got}, where the field is ${w[2]}; the generated code has ${ty}`,
|
|
443
|
+
);
|
|
444
|
+
if (had[w[1]] !== undefined) out[name] = had[w[1]];
|
|
445
|
+
} else {
|
|
446
|
+
out[name] = had[name] !== undefined ? had[name] : defaultOf(ty);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
return { ...v, fields: out, layout: mt.layout };
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** The model of a node in the network API's node form: checked to be of the type, and read by
|
|
453
|
+
* the layout the generated code knows (a node of another layout through `adapt`). */
|
|
454
|
+
export function decode<M>(mt: ModelType<M>, node: Json, layouts?: Layouts): M {
|
|
455
|
+
const got = nodeName(node);
|
|
456
|
+
if (got !== typeName(mt.type)) throw new DecodeError(`a ${got} node where the generated code reads ${mt.type}`);
|
|
457
|
+
const v = adapt(mt, node, layouts);
|
|
458
|
+
const out: Record<string, unknown> = {};
|
|
459
|
+
const key = (v.key ?? {}) as Json;
|
|
460
|
+
for (const [prop, def] of Object.entries(mt.key)) {
|
|
461
|
+
if (!(def.name in key)) throw new DecodeError(`${got}.${def.name}: the answer has no key part ${def.name}`);
|
|
462
|
+
out[prop] = readField(v, key, def, true);
|
|
463
|
+
}
|
|
464
|
+
if (mt.twin && typeof key["~"] === "string") out.ordinal = key["~"];
|
|
465
|
+
readFields(v, mt.fields, out, true);
|
|
466
|
+
const kids = v.children as Record<string, Json[]> | undefined;
|
|
467
|
+
if (Object.keys(mt.children).length > 0) {
|
|
468
|
+
out.isTree = kids !== undefined;
|
|
469
|
+
if (kids)
|
|
470
|
+
for (const [prop, [t, m]] of Object.entries(mt.children))
|
|
471
|
+
out[prop] = (kids[t] ?? []).map((c) => decode(m(), c, layouts));
|
|
472
|
+
}
|
|
473
|
+
return out as M;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** Fields of an object of the language's names as the network API's `fields` (variant cases
|
|
477
|
+
* with their discriminator). */
|
|
478
|
+
export function encodeFields(
|
|
479
|
+
defs: Readonly<Record<string, FieldDef>>,
|
|
480
|
+
o: Record<string, unknown>,
|
|
481
|
+
out: Json = {},
|
|
482
|
+
): Json {
|
|
483
|
+
for (const [prop, x] of Object.entries(o)) {
|
|
484
|
+
if (x === undefined) continue;
|
|
485
|
+
const def = defs[prop];
|
|
486
|
+
if (!def) continue;
|
|
487
|
+
if (def.cases) {
|
|
488
|
+
const c = x as Record<string, unknown>;
|
|
489
|
+
const member = c[prop] as string;
|
|
490
|
+
out[def.name] = member;
|
|
491
|
+
encodeFields(def.cases[member] ?? {}, c, out);
|
|
492
|
+
} else out[def.name] = toJson(x);
|
|
493
|
+
}
|
|
494
|
+
return out;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ---- paths ----
|
|
498
|
+
|
|
499
|
+
/** Percent-encoding of a path level or a query value (`spec/path-keys.md`). */
|
|
500
|
+
export function enc(s: string): string {
|
|
501
|
+
let o = "";
|
|
502
|
+
for (const c of new TextEncoder().encode(s)) {
|
|
503
|
+
const ch = String.fromCharCode(c);
|
|
504
|
+
if (/[A-Za-z0-9]/.test(ch) || "-._:".includes(ch)) o += ch;
|
|
505
|
+
else o += `%${c.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
506
|
+
}
|
|
507
|
+
return o;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** A path of the network API, built level by level; key parts are percent-encoded and joined
|
|
511
|
+
* by `,`, a twin's ordinal follows `~` (`spec/path-keys.md`). */
|
|
512
|
+
export class Path {
|
|
513
|
+
readonly text: string;
|
|
514
|
+
private constructor(text: string) {
|
|
515
|
+
this.text = text;
|
|
516
|
+
}
|
|
517
|
+
static root(aggregate: string): Path {
|
|
518
|
+
return new Path(enc(aggregate));
|
|
519
|
+
}
|
|
520
|
+
/** A node's level: its key parts (each a value of the key part's type). */
|
|
521
|
+
key(...parts: unknown[]): Path {
|
|
522
|
+
return this.level(parts.map((p) => enc(keyText(p))).join(","));
|
|
523
|
+
}
|
|
524
|
+
/** A twin by its ordinal, on the level just given (or alone for a type without a key). */
|
|
525
|
+
ordinal(ord: string): Path {
|
|
526
|
+
return new Path(`${this.text}~${enc(ord)}`);
|
|
527
|
+
}
|
|
528
|
+
/** A child type's level. */
|
|
529
|
+
child(type: string): Path {
|
|
530
|
+
return new Path(`${this.text}/${enc(type)}`);
|
|
531
|
+
}
|
|
532
|
+
/** A level given as its encoded text. */
|
|
533
|
+
level(encoded: string): Path {
|
|
534
|
+
return new Path(`${this.text}/${encoded}`);
|
|
535
|
+
}
|
|
536
|
+
toString(): string {
|
|
537
|
+
return this.text;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** How a path names a twin: by its ordinal (stable) or as the n-th with that key now. */
|
|
542
|
+
export type Twin = { ord: string } | { at: number };
|
|
543
|
+
|
|
544
|
+
/** The suffix a twin adds to its level. */
|
|
545
|
+
export function twinSuffix(t: Twin): string {
|
|
546
|
+
return "ord" in t ? `~${enc(t.ord)}` : `@${t.at}`;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Where an insert puts a new twin among the twins with its key. */
|
|
550
|
+
export type Position = "last" | "first" | { before: string } | { after: string };
|
|
551
|
+
|
|
552
|
+
/** Grants. Generated path classes carry the brand of each operation the profile they were
|
|
553
|
+
* generated for grants (every one without `--profile`): an operation it does not grant does
|
|
554
|
+
* not type-check. */
|
|
555
|
+
export const GET: unique symbol = Symbol("oliviadb.get");
|
|
556
|
+
export const TREE: unique symbol = Symbol("oliviadb.tree");
|
|
557
|
+
export const LIST: unique symbol = Symbol("oliviadb.list");
|
|
558
|
+
export const INSERT: unique symbol = Symbol("oliviadb.insert");
|
|
559
|
+
export const UPDATE: unique symbol = Symbol("oliviadb.update");
|
|
560
|
+
export const DELETE: unique symbol = Symbol("oliviadb.delete");
|
|
561
|
+
export const WATCH: unique symbol = Symbol("oliviadb.watch");
|
|
562
|
+
|
|
563
|
+
/** A path to one node of a type. */
|
|
564
|
+
export class NodePath<M> {
|
|
565
|
+
readonly path: Path;
|
|
566
|
+
readonly type: ModelType<M>;
|
|
567
|
+
constructor(path: Path, type: ModelType<M>) {
|
|
568
|
+
this.path = path;
|
|
569
|
+
this.type = type;
|
|
570
|
+
}
|
|
571
|
+
toString(): string {
|
|
572
|
+
return this.path.text;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** The nodes of one type under one parent (or an aggregate's roots); `N` is what an insert takes. */
|
|
577
|
+
export class CollPath<M, N> {
|
|
578
|
+
readonly path: Path;
|
|
579
|
+
readonly type: ModelType<M>;
|
|
580
|
+
declare readonly newNode?: N;
|
|
581
|
+
constructor(path: Path, type: ModelType<M>) {
|
|
582
|
+
this.path = path;
|
|
583
|
+
this.type = type;
|
|
584
|
+
}
|
|
585
|
+
toString(): string {
|
|
586
|
+
return this.path.text;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
export interface CanGet<M> extends NodePath<M> {
|
|
591
|
+
readonly [GET]: true;
|
|
592
|
+
}
|
|
593
|
+
export interface CanTree<M> extends CanGet<M> {
|
|
594
|
+
readonly [TREE]: true;
|
|
595
|
+
}
|
|
596
|
+
/** `P`: the patch type of the node's type under the profile. */
|
|
597
|
+
export interface CanUpdate<M, P> extends NodePath<M> {
|
|
598
|
+
readonly [UPDATE]: P;
|
|
599
|
+
}
|
|
600
|
+
export interface CanDelete<M> extends NodePath<M> {
|
|
601
|
+
readonly [DELETE]: true;
|
|
602
|
+
}
|
|
603
|
+
export interface CanList<M> extends CollPath<M, unknown> {
|
|
604
|
+
readonly [LIST]: true;
|
|
605
|
+
}
|
|
606
|
+
export interface CanInsert<M, N> extends CollPath<M, N> {
|
|
607
|
+
readonly [INSERT]: true;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** A path whose changes the profile lets watch; `C` is the union of its changes' nodes
|
|
611
|
+
* (`{ type, node }`: the watched type and the types under it). */
|
|
612
|
+
export interface CanWatch<C> {
|
|
613
|
+
readonly [WATCH]: C;
|
|
614
|
+
readonly path: Path;
|
|
615
|
+
/** The types a change may be of: by type name, the name the change carries and the model. */
|
|
616
|
+
watchTypes(): Readonly<Record<string, readonly [string, ModelType<unknown>]>>;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** What a change did. */
|
|
620
|
+
export type Op = "insert" | "replace" | "delete";
|
|
621
|
+
|
|
622
|
+
/** One record of the change stream (`docs/network-api.md`, "Change stream"): the node before
|
|
623
|
+
* and after, each as its model. */
|
|
624
|
+
export interface Change<C> {
|
|
625
|
+
/** The idempotency key: the same for the same change on every copy. */
|
|
626
|
+
key: string;
|
|
627
|
+
/** Where to resume after this record. */
|
|
628
|
+
position: string;
|
|
629
|
+
path: string;
|
|
630
|
+
type: string;
|
|
631
|
+
op: Op;
|
|
632
|
+
version: bigint;
|
|
633
|
+
before?: C;
|
|
634
|
+
after?: C;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** A batch of the change stream and the position after it. */
|
|
638
|
+
export interface Changes<C> {
|
|
639
|
+
changes: Change<C>[];
|
|
640
|
+
position: string;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** A change record in the HTTP JSON form: each side decoded as a node of the record's type,
|
|
644
|
+
* key and layout (the layout of the version shown last). */
|
|
645
|
+
export function changeOf<C>(
|
|
646
|
+
v: Json,
|
|
647
|
+
types: Readonly<Record<string, readonly [string, ModelType<unknown>]>>,
|
|
648
|
+
layouts?: Layouts,
|
|
649
|
+
): Change<C> {
|
|
650
|
+
const t = types[textOf(v.type)];
|
|
651
|
+
if (!t) throw new DecodeError(`a change of type ${textOf(v.type)}, which the generated code does not know`);
|
|
652
|
+
const side = (s: string): C | undefined => {
|
|
653
|
+
const f = v[s];
|
|
654
|
+
if (!f || typeof f !== "object") return undefined;
|
|
655
|
+
const node = { type: v.type, path: v.path, key: v.node_key, fields: f, layout: v.layout };
|
|
656
|
+
return { type: t[0], node: decode(t[1], node as Json, layouts) } as C;
|
|
657
|
+
};
|
|
658
|
+
const op = v.op;
|
|
659
|
+
if (op !== "insert" && op !== "replace" && op !== "delete") throw new DecodeError(`change op ${String(op)}`);
|
|
660
|
+
const c: Change<C> = {
|
|
661
|
+
key: textOf(v.key),
|
|
662
|
+
position: textOf(v.position),
|
|
663
|
+
path: textOf(v.path),
|
|
664
|
+
type: textOf(v.type),
|
|
665
|
+
op,
|
|
666
|
+
version: versionOf(v),
|
|
667
|
+
};
|
|
668
|
+
const b = side("before");
|
|
669
|
+
const a = side("after");
|
|
670
|
+
if (b !== undefined) c.before = b;
|
|
671
|
+
if (a !== undefined) c.after = a;
|
|
672
|
+
return c;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** What an update changes: fields set, numbers added (the network API's relative update). */
|
|
676
|
+
export interface PatchOf<S, A> {
|
|
677
|
+
set?: S;
|
|
678
|
+
add?: A;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// ---- the connection ----
|
|
682
|
+
|
|
683
|
+
/** What the typed layer needs of the native protocol client (`NativeClient`). */
|
|
684
|
+
export interface NativeConn {
|
|
685
|
+
get(path: string, params?: Record<string, string>): Promise<RowsLike>;
|
|
686
|
+
lookup(index: string, params?: Record<string, string>): Promise<RowsLike>;
|
|
687
|
+
search(aggregate: string, body: Json): Promise<RowsLike>;
|
|
688
|
+
changes(paths: string[], from: string): AsyncGenerator<{ toJson(): Json }>;
|
|
689
|
+
/** The fields of a writer layout a descriptor of the connection described. */
|
|
690
|
+
layoutFields?(id: string): LayoutFields | undefined;
|
|
691
|
+
txn(body: Json): Promise<[number, Json]>;
|
|
692
|
+
write(method: string, path: string, body: Json): Promise<[number, Json]>;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
interface NodeLike {
|
|
696
|
+
readonly hit: string | undefined;
|
|
697
|
+
readonly parent: string | undefined;
|
|
698
|
+
readonly score: number | undefined;
|
|
699
|
+
toJson(parent: string, defaults: boolean): Json;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/** The rows of a native answer (`Rows`). */
|
|
703
|
+
export interface RowsLike {
|
|
704
|
+
toJson(listing: boolean): Json;
|
|
705
|
+
nodes(): NodeLike[];
|
|
706
|
+
entries(): Iterable<{ node: NodeLike } | { path: string; hitPath: string }>;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function query(params: Record<string, string>): string {
|
|
710
|
+
const q = Object.entries(params).map(([k, v]) => `${k}=${enc(v)}`);
|
|
711
|
+
return q.length ? `?${q.join("&")}` : "";
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function checked([st, v]: [number, Json]): Json {
|
|
715
|
+
if (st >= 200 && st < 300) return v;
|
|
716
|
+
throw new OliviaDbError(st, v);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
type Hit = { path: string; record: string; root: Json | undefined };
|
|
720
|
+
|
|
721
|
+
class Conn {
|
|
722
|
+
private readonly http?: OliviaDbClient;
|
|
723
|
+
private readonly native?: NativeConn;
|
|
724
|
+
constructor(c: OliviaDbClient | NativeConn) {
|
|
725
|
+
if (c instanceof OliviaDbClient) this.http = c;
|
|
726
|
+
else this.native = c;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** A node, tree or listing as the network API's JSON (rows given in that form). */
|
|
730
|
+
async read(path: Path, params: Record<string, string>, listing: boolean): Promise<Json> {
|
|
731
|
+
if (this.http) return this.http.request("GET", `/v1/aggregates/${path.text}${query(params)}`);
|
|
732
|
+
return (await this.native!.get(path.text, params)).toJson(listing);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
async write(method: string, path: Path, body: Json): Promise<Json> {
|
|
736
|
+
if (this.http) return this.http.request(method, `/v1/aggregates/${path.text}`, body);
|
|
737
|
+
return checked(await this.native!.write(method, path.text, body));
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
async txn(body: Json): Promise<Json> {
|
|
741
|
+
if (this.http) return this.http.request("POST", "/v1/txn", body);
|
|
742
|
+
return checked(await this.native!.txn(body));
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** A writer layout's fields: `GET /v1/layouts/{id}` over HTTP, the connection's descriptors
|
|
746
|
+
* over the native protocol; null when neither knows it. */
|
|
747
|
+
async layoutFields(id: string): Promise<LayoutFields | null> {
|
|
748
|
+
if (this.native) return this.native.layoutFields?.(id) ?? null;
|
|
749
|
+
try {
|
|
750
|
+
const v = await this.http!.request<{ fields?: Json[] }>("GET", `/v1/layouts/${enc(id)}`);
|
|
751
|
+
return (v.fields ?? []).map((f) => [Number(f.number), textOf(f.name), textOf(f.type)] as const);
|
|
752
|
+
} catch (e) {
|
|
753
|
+
if (e instanceof OliviaDbError && e.status === 404) return null;
|
|
754
|
+
throw e;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
async changes(paths: string[], from: string, limit?: number): Promise<Json> {
|
|
759
|
+
if (!this.http)
|
|
760
|
+
throw new Error("a batch of the change stream is an HTTP request; over the native protocol use watchStream");
|
|
761
|
+
const q = [...paths.map((p) => `path=${enc(p)}`), `from=${enc(from)}`];
|
|
762
|
+
if (limit !== undefined) q.push(`limit=${limit}`);
|
|
763
|
+
return this.http.request("GET", `/v1/changes?${q.join("&")}`);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
async *stream(paths: string[], from: string): AsyncGenerator<Json> {
|
|
767
|
+
if (!this.native)
|
|
768
|
+
throw new Error("the change stream as it comes needs the native protocol; over HTTP read batches with watch");
|
|
769
|
+
for await (const c of this.native.changes(paths, from)) yield c.toJson();
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
async lookup(index: string, key: string): Promise<Hit[]> {
|
|
773
|
+
if (this.http) {
|
|
774
|
+
const v = await this.http.request<{ results?: Json[] }>("GET", `/v1/lookup/${enc(index)}${query({ key })}`);
|
|
775
|
+
return (v.results ?? []).map((h) => ({
|
|
776
|
+
path: textOf(h.path),
|
|
777
|
+
record: textOf(h.record),
|
|
778
|
+
root: h.root && typeof h.root === "object" ? (h.root as Json) : undefined,
|
|
779
|
+
}));
|
|
780
|
+
}
|
|
781
|
+
const out: Hit[] = [];
|
|
782
|
+
for (const e of (await this.native!.lookup(index, { key })).entries()) {
|
|
783
|
+
if ("node" in e) {
|
|
784
|
+
const root = e.node.toJson("", true);
|
|
785
|
+
const record = String(root.path);
|
|
786
|
+
out.push({ path: e.node.hit ?? record, record, root });
|
|
787
|
+
} else out.push({ path: e.hitPath, record: e.path, root: undefined });
|
|
788
|
+
}
|
|
789
|
+
return out;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
async search(aggregate: string, body: Json): Promise<Array<[Json, number]>> {
|
|
793
|
+
if (this.http) {
|
|
794
|
+
const v = await this.http.request<{ results?: Json[] }>("POST", `/v1/search/${enc(aggregate)}`, body);
|
|
795
|
+
return (v.results ?? []).map((h) => [h, typeof h.score === "number" ? h.score : 0]);
|
|
796
|
+
}
|
|
797
|
+
return (await this.native!.search(aggregate, body))
|
|
798
|
+
.nodes()
|
|
799
|
+
.map((n) => [n.toJson(n.parent ?? "", true), n.score ?? 0] as [Json, number]);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** A text member of an answer, or "". */
|
|
804
|
+
function textOf(x: unknown): string {
|
|
805
|
+
return typeof x === "string" ? x : "";
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function versionOf(v: Json): bigint {
|
|
809
|
+
const x = v.version;
|
|
810
|
+
if (typeof x === "number" || typeof x === "string" || typeof x === "bigint") return BigInt(x);
|
|
811
|
+
throw new DecodeError(`version: ${JSON.stringify(x)}`);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
function writeBody(fields: Json, add: Json): Json {
|
|
815
|
+
const b: Json = {};
|
|
816
|
+
if (Object.keys(fields).length > 0 || Object.keys(add).length === 0) b.fields = fields;
|
|
817
|
+
if (Object.keys(add).length > 0) b.add = add;
|
|
818
|
+
return b;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function patchBody<M>(t: ModelType<M>, p: PatchOf<object, object>): Json {
|
|
822
|
+
return writeBody(
|
|
823
|
+
encodeFields(t.decl, (p.set ?? {}) as Record<string, unknown>),
|
|
824
|
+
encodeFields(t.decl, (p.add ?? {}) as Record<string, unknown>),
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
function insertOp<M, N>(c: CollPath<M, N>, n: N, position?: Position): [Path, Json] {
|
|
829
|
+
const o = n as Record<string, unknown>;
|
|
830
|
+
const keys = Object.keys(c.type.key);
|
|
831
|
+
const level = keys.length ? keys.map((k) => enc(keyText(o[k]))).join(",") : undefined;
|
|
832
|
+
const rest = Object.fromEntries(Object.entries(o).filter(([k]) => !(k in c.type.key)));
|
|
833
|
+
const body: Json = { fields: encodeFields(c.type.decl, rest) };
|
|
834
|
+
if (position !== undefined && position !== "last")
|
|
835
|
+
body.position =
|
|
836
|
+
position === "first"
|
|
837
|
+
? "first"
|
|
838
|
+
: "before" in position
|
|
839
|
+
? { before: `${level ?? ""}~${position.before}` }
|
|
840
|
+
: { after: `${level ?? ""}~${position.after}` };
|
|
841
|
+
return [level === undefined ? c.path : c.path.level(level), body];
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/** A write's answer. */
|
|
845
|
+
export interface Written {
|
|
846
|
+
version: bigint;
|
|
847
|
+
/** The written node's path, when the answer names it (an insert: a twin's path carries the
|
|
848
|
+
* ordinal the server gave it). */
|
|
849
|
+
path?: string;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function written(v: Json): Written {
|
|
853
|
+
const w: Written = { version: versionOf(v) };
|
|
854
|
+
if (typeof v.path === "string") w.path = v.path;
|
|
855
|
+
return w;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
export interface GetOptions {
|
|
859
|
+
/** With the node's subtree (each listing the profile grants). */
|
|
860
|
+
tree?: boolean;
|
|
861
|
+
/** At most this many children of every listing in the subtree. */
|
|
862
|
+
each?: number;
|
|
863
|
+
/** At a version. */
|
|
864
|
+
asOf?: U64;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
export interface ListOptions {
|
|
868
|
+
/** Start after this key (its first parts: a value or an array of values) or a page's `next`
|
|
869
|
+
* given as `{ next }`. */
|
|
870
|
+
after?: unknown;
|
|
871
|
+
to?: unknown;
|
|
872
|
+
prefix?: unknown;
|
|
873
|
+
limit?: number;
|
|
874
|
+
asOf?: U64;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** One page of a listing. */
|
|
878
|
+
export interface Page<M> {
|
|
879
|
+
nodes: M[];
|
|
880
|
+
/** Give it as `after: { next }` for the next page; undefined after the last. */
|
|
881
|
+
next: string | undefined;
|
|
882
|
+
version: bigint;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
function cursor(k: unknown): string {
|
|
886
|
+
if (k && typeof k === "object" && "next" in k && typeof k.next === "string") return k.next;
|
|
887
|
+
return (Array.isArray(k) ? k : [k]).map((p) => enc(keyText(p))).join(",");
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
function listParams(o: ListOptions): Record<string, string> {
|
|
891
|
+
const p: Record<string, string> = {};
|
|
892
|
+
if (o.after !== undefined) p.after = cursor(o.after);
|
|
893
|
+
if (o.to !== undefined) p.to = cursor(o.to);
|
|
894
|
+
if (o.prefix !== undefined) p.prefix = cursor(o.prefix);
|
|
895
|
+
if (o.limit !== undefined) p.limit = String(o.limit);
|
|
896
|
+
if (o.asOf !== undefined) p.as_of = String(o.asOf);
|
|
897
|
+
return p;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
function getParams(o: GetOptions): Record<string, string> {
|
|
901
|
+
const p: Record<string, string> = {};
|
|
902
|
+
if (o.tree) p.tree = "true";
|
|
903
|
+
if (o.each !== undefined) p.each = String(o.each);
|
|
904
|
+
if (o.asOf !== undefined) p.as_of = String(o.asOf);
|
|
905
|
+
return p;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/** A lookup through a `unique` index: the record's root, or undefined. */
|
|
909
|
+
export class Unique<R> {
|
|
910
|
+
readonly kind = "unique";
|
|
911
|
+
readonly index: string;
|
|
912
|
+
readonly key: string;
|
|
913
|
+
readonly root: ModelType<R>;
|
|
914
|
+
constructor(index: string, parts: unknown[], root: ModelType<R>) {
|
|
915
|
+
this.index = index;
|
|
916
|
+
this.key = parts.map((p) => enc(keyText(p))).join(",");
|
|
917
|
+
this.root = root;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** A lookup through an index that is not unique: every node found. */
|
|
922
|
+
export class Many<R> {
|
|
923
|
+
readonly kind = "many";
|
|
924
|
+
readonly index: string;
|
|
925
|
+
readonly key: string;
|
|
926
|
+
readonly root: ModelType<R>;
|
|
927
|
+
constructor(index: string, parts: unknown[], root: ModelType<R>) {
|
|
928
|
+
this.index = index;
|
|
929
|
+
this.key = parts.map((p) => enc(keyText(p))).join(",");
|
|
930
|
+
this.root = root;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/** One node found through an index. */
|
|
935
|
+
export interface LookupHit<R> {
|
|
936
|
+
/** The indexed node's path. */
|
|
937
|
+
path: string;
|
|
938
|
+
/** Its record's path (the root's). */
|
|
939
|
+
record: string;
|
|
940
|
+
/** The record's root, when the caller's profile shows it. */
|
|
941
|
+
root: R | undefined;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/** An aggregate that may be searched; `H` the union of its hits (`{ type, node }`). */
|
|
945
|
+
export class Searchable<H> {
|
|
946
|
+
readonly aggregate: string;
|
|
947
|
+
/** Hit types by type name: the name the hit carries and the model. */
|
|
948
|
+
readonly hits: Readonly<Record<string, readonly [string, ModelType<unknown>]>>;
|
|
949
|
+
declare readonly hit?: H;
|
|
950
|
+
constructor(aggregate: string, hits: Record<string, readonly [string, ModelType<unknown>]>) {
|
|
951
|
+
this.aggregate = aggregate;
|
|
952
|
+
this.hits = hits;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/** A ranked search result. */
|
|
957
|
+
export interface Scored<H> {
|
|
958
|
+
hit: H;
|
|
959
|
+
path: string;
|
|
960
|
+
score: number;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/** A node of any type (`getUntyped`, `listUntyped`). */
|
|
964
|
+
export interface Node {
|
|
965
|
+
type: string;
|
|
966
|
+
path: string;
|
|
967
|
+
key: Json;
|
|
968
|
+
fields: Json;
|
|
969
|
+
layout: string;
|
|
970
|
+
/** Children by type, in a tree read. */
|
|
971
|
+
children?: Record<string, Node[]>;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
function untyped(v: Json): Node {
|
|
975
|
+
const obj = (k: string) => (v[k] && typeof v[k] === "object" ? (v[k] as Json) : {});
|
|
976
|
+
const n: Node = {
|
|
977
|
+
type: textOf(v.type),
|
|
978
|
+
path: textOf(v.path),
|
|
979
|
+
key: obj("key"),
|
|
980
|
+
fields: obj("fields"),
|
|
981
|
+
layout: textOf(v.layout),
|
|
982
|
+
};
|
|
983
|
+
if (v.children && typeof v.children === "object")
|
|
984
|
+
n.children = Object.fromEntries(
|
|
985
|
+
Object.entries(v.children as Record<string, Json[]>).map(([t, a]) => [t, a.map(untyped)]),
|
|
986
|
+
);
|
|
987
|
+
return n;
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** How often `txn` runs its function again after a 412. */
|
|
991
|
+
export const TXN_RETRIES = 3;
|
|
992
|
+
|
|
993
|
+
/** A typed database over HTTP (OliviaDbClient) or the native protocol (NativeClient). */
|
|
994
|
+
export class Db {
|
|
995
|
+
private readonly conn: Conn;
|
|
996
|
+
constructor(client: OliviaDbClient | NativeConn) {
|
|
997
|
+
this.conn = new Conn(client);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/** Writer layouts fetched so far, by id (null: the connection does not know it). */
|
|
1001
|
+
private readonly layouts = new Map<string, LayoutFields | null>();
|
|
1002
|
+
private readonly layoutsView: Layouts = { fields: (id) => this.layouts.get(id) };
|
|
1003
|
+
|
|
1004
|
+
/** `f` run with the writer layouts it needs: each one it stops at (`NeedLayout`) is fetched
|
|
1005
|
+
* once (`GET /v1/layouts/{id}`, or the connection's descriptors), then `f` runs again. */
|
|
1006
|
+
private async decoded<T>(f: (l: Layouts) => T): Promise<T> {
|
|
1007
|
+
for (;;) {
|
|
1008
|
+
try {
|
|
1009
|
+
return f(this.layoutsView);
|
|
1010
|
+
} catch (e) {
|
|
1011
|
+
if (!(e instanceof NeedLayout) || this.layouts.has(e.id)) throw e;
|
|
1012
|
+
this.layouts.set(e.id, await this.conn.layoutFields(e.id));
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/** Read a node (`tree`: with its subtree, `asOf`: at a version). */
|
|
1018
|
+
get<M>(p: CanTree<M>, o: GetOptions & { tree: true }): Promise<M>;
|
|
1019
|
+
get<M>(p: CanGet<M>, o?: GetOptions & { tree?: false; each?: undefined }): Promise<M>;
|
|
1020
|
+
async get<M>(p: CanGet<M>, o: GetOptions = {}): Promise<M> {
|
|
1021
|
+
return (await this.readOne(p, o)).model;
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/** The model and the version it was read at. */
|
|
1025
|
+
getVersioned<M>(p: CanTree<M>, o: GetOptions & { tree: true }): Promise<{ model: M; version: bigint }>;
|
|
1026
|
+
getVersioned<M>(
|
|
1027
|
+
p: CanGet<M>,
|
|
1028
|
+
o?: GetOptions & { tree?: false; each?: undefined },
|
|
1029
|
+
): Promise<{ model: M; version: bigint }>;
|
|
1030
|
+
getVersioned<M>(p: CanGet<M>, o: GetOptions = {}): Promise<{ model: M; version: bigint }> {
|
|
1031
|
+
return this.readOne(p, o);
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
private async readOne<M>(p: CanGet<M>, o: GetOptions): Promise<{ model: M; version: bigint }> {
|
|
1035
|
+
const v = await this.conn.read(p.path, getParams(o), false);
|
|
1036
|
+
return { model: await this.decoded((l) => decode(p.type, v, l)), version: versionOf(v) };
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/** A page of a listing. */
|
|
1040
|
+
async list<M>(c: CanList<M>, o: ListOptions = {}): Promise<Page<M>> {
|
|
1041
|
+
const v = await this.conn.read(c.path, listParams(o), true);
|
|
1042
|
+
return {
|
|
1043
|
+
nodes: await this.decoded((l) => ((v.nodes ?? []) as Json[]).map((n) => decode(c.type, n, l))),
|
|
1044
|
+
next: typeof v.next === "string" ? v.next : undefined,
|
|
1045
|
+
version: versionOf(v),
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** The records an index finds: a unique index's root or undefined, another's hits. */
|
|
1050
|
+
lookup<R>(k: Unique<R>): Promise<R | undefined>;
|
|
1051
|
+
lookup<R>(k: Many<R>): Promise<LookupHit<R>[]>;
|
|
1052
|
+
async lookup<R>(k: Unique<R> | Many<R>): Promise<R | undefined | LookupHit<R>[]> {
|
|
1053
|
+
const hits = await this.conn.lookup(k.index, k.key);
|
|
1054
|
+
const root = (r: Json | undefined, l: Layouts) => (r === undefined ? undefined : decode(k.root, r, l));
|
|
1055
|
+
if (k.kind === "many")
|
|
1056
|
+
return this.decoded((l) => hits.map((h) => ({ path: h.path, record: h.record, root: root(h.root, l) })));
|
|
1057
|
+
const h = hits[0];
|
|
1058
|
+
if (!h) return undefined;
|
|
1059
|
+
if (!h.root) throw new DecodeError(`${h.record}: the profile does not show the record's root`);
|
|
1060
|
+
const r = h.root;
|
|
1061
|
+
return this.decoded((l) => root(r, l));
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/** Ranked text search over an aggregate. */
|
|
1065
|
+
async search<H>(s: Searchable<H>, text: string, o: { budget?: number; limit?: number } = {}): Promise<Scored<H>[]> {
|
|
1066
|
+
const body: Json = { query: text };
|
|
1067
|
+
if (o.budget !== undefined) body.budget = o.budget;
|
|
1068
|
+
if (o.limit !== undefined) body.limit = o.limit;
|
|
1069
|
+
const found = await this.conn.search(s.aggregate, body);
|
|
1070
|
+
return this.decoded((l) =>
|
|
1071
|
+
found.map(([v, score]) => {
|
|
1072
|
+
const h = s.hits[nodeName(v)];
|
|
1073
|
+
if (!h) throw new DecodeError(`a search hit of type ${nodeName(v)}, which the generated code does not know`);
|
|
1074
|
+
return { hit: { type: h[0], node: decode(h[1], v, l) } as H, path: textOf(v.path), score };
|
|
1075
|
+
}),
|
|
1076
|
+
);
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
async insert<M, N>(c: CanInsert<M, N>, n: NoInfer<N>, o: { position?: Position } = {}): Promise<Written> {
|
|
1080
|
+
const [path, body] = insertOp(c, n, o.position);
|
|
1081
|
+
return written(await this.conn.write("POST", path, body));
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
async update<M, P extends PatchOf<object, object>>(p: CanUpdate<M, P>, patch: NoInfer<P>): Promise<Written> {
|
|
1085
|
+
return written(await this.conn.write("PATCH", p.path, patchBody(p.type, patch)));
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
/** `ifExists`: a missing node deletes nothing instead of answering 404 (in a transaction). */
|
|
1089
|
+
async delete<M>(p: CanDelete<M>, o: { ifExists?: boolean } = {}): Promise<Written> {
|
|
1090
|
+
if (o.ifExists) {
|
|
1091
|
+
const v = await this.conn.txn({ ops: [{ op: "delete", path: p.path.text, if_exists: true }] });
|
|
1092
|
+
return written(v);
|
|
1093
|
+
}
|
|
1094
|
+
return written(await this.conn.write("DELETE", p.path, {}));
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
/**
|
|
1098
|
+
* One batch of the change stream under the paths (`GET /v1/changes`, HTTP): the changes after
|
|
1099
|
+
* `from` (`start`, `now` (the default) or a record's position) up to `limit`, and the position
|
|
1100
|
+
* after them. The native protocol streams changes instead: `watchStream`.
|
|
1101
|
+
*/
|
|
1102
|
+
async watch<C>(paths: CanWatch<C> | CanWatch<C>[], o: { from?: string; limit?: number } = {}): Promise<Changes<C>> {
|
|
1103
|
+
const ws = Array.isArray(paths) ? paths : [paths];
|
|
1104
|
+
const v = await this.conn.changes(
|
|
1105
|
+
ws.map((w) => w.path.text),
|
|
1106
|
+
o.from ?? "now",
|
|
1107
|
+
o.limit,
|
|
1108
|
+
);
|
|
1109
|
+
const types = Object.assign({}, ...ws.map((w) => w.watchTypes())) as Record<
|
|
1110
|
+
string,
|
|
1111
|
+
readonly [string, ModelType<unknown>]
|
|
1112
|
+
>;
|
|
1113
|
+
const changes = await this.decoded((l) => ((v.changes ?? []) as Json[]).map((c) => changeOf<C>(c, types, l)));
|
|
1114
|
+
return { changes, position: textOf(v.position) };
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/** The changes as they come, over the native protocol's change stream, until the iteration
|
|
1118
|
+
* stops (the stream is then cancelled). Over HTTP, read batches with `watch`. */
|
|
1119
|
+
async *watchStream<C>(paths: CanWatch<C> | CanWatch<C>[], o: { from?: string } = {}): AsyncGenerator<Change<C>> {
|
|
1120
|
+
const ws = Array.isArray(paths) ? paths : [paths];
|
|
1121
|
+
const types = Object.assign({}, ...ws.map((w) => w.watchTypes())) as Record<
|
|
1122
|
+
string,
|
|
1123
|
+
readonly [string, ModelType<unknown>]
|
|
1124
|
+
>;
|
|
1125
|
+
for await (const c of this.conn.stream(
|
|
1126
|
+
ws.map((w) => w.path.text),
|
|
1127
|
+
o.from ?? "now",
|
|
1128
|
+
))
|
|
1129
|
+
yield await this.decoded((l) => changeOf<C>(c, types, l));
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
/** A node of any type, by an untyped path. */
|
|
1133
|
+
async getUntyped(p: Path, o: { tree?: boolean; asOf?: U64 } = {}): Promise<Node> {
|
|
1134
|
+
return untyped(await this.conn.read(p, getParams(o), false));
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/** A page of a listing, by an untyped path. */
|
|
1138
|
+
async listUntyped(p: Path, o: ListOptions = {}): Promise<Page<Node>> {
|
|
1139
|
+
const v = await this.conn.read(p, listParams(o), true);
|
|
1140
|
+
return {
|
|
1141
|
+
nodes: ((v.nodes ?? []) as Json[]).map(untyped),
|
|
1142
|
+
next: typeof v.next === "string" ? v.next : undefined,
|
|
1143
|
+
version: versionOf(v),
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
/**
|
|
1148
|
+
* Operations as one transaction, all or none: `f` collects them (reads in it are sent at
|
|
1149
|
+
* once), then they are sent as one `POST /v1/txn`. An answer 412 (a precondition of
|
|
1150
|
+
* `unchangedSince` or `updateChecked` failed) runs `f` again, at most TXN_RETRIES times.
|
|
1151
|
+
*/
|
|
1152
|
+
async txn(f: (t: Txn) => void | Promise<void>): Promise<Written> {
|
|
1153
|
+
let last: unknown;
|
|
1154
|
+
for (let i = 0; i <= TXN_RETRIES; i++) {
|
|
1155
|
+
const t = new Txn(this);
|
|
1156
|
+
await f(t);
|
|
1157
|
+
try {
|
|
1158
|
+
return written(await this.conn.txn({ ops: t.ops }));
|
|
1159
|
+
} catch (e) {
|
|
1160
|
+
if (!(e instanceof OliviaDbError && e.status === 412)) throw e;
|
|
1161
|
+
last = e;
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
throw last;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
/** The operations of one transaction, collected by `Db.txn`'s function. */
|
|
1169
|
+
export class Txn {
|
|
1170
|
+
private readonly db: Db;
|
|
1171
|
+
readonly ops: Json[] = [];
|
|
1172
|
+
constructor(db: Db) {
|
|
1173
|
+
this.db = db;
|
|
1174
|
+
}
|
|
1175
|
+
/** Read a node now; its version is what `unchangedSince` takes. */
|
|
1176
|
+
get<M>(p: CanGet<M>): Promise<{ model: M; version: bigint }> {
|
|
1177
|
+
return this.db.getVersioned(p);
|
|
1178
|
+
}
|
|
1179
|
+
insert<M, N>(c: CanInsert<M, N>, n: NoInfer<N>, o: { position?: Position } = {}): void {
|
|
1180
|
+
const [path, body] = insertOp(c, n, o.position);
|
|
1181
|
+
this.ops.push({ op: "insert", path: path.text, ...body });
|
|
1182
|
+
}
|
|
1183
|
+
update<M, P extends PatchOf<object, object>>(p: CanUpdate<M, P>, patch: NoInfer<P>): void {
|
|
1184
|
+
this.ops.push({ op: "update", path: p.path.text, ...patchBody(p.type, patch) });
|
|
1185
|
+
}
|
|
1186
|
+
delete<M>(p: CanDelete<M>, o: { ifExists?: boolean } = {}): void {
|
|
1187
|
+
this.ops.push(
|
|
1188
|
+
o.ifExists ? { op: "delete", path: p.path.text, if_exists: true } : { op: "delete", path: p.path.text },
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
/** The transaction applies only if the node is as it was at version `v` (412 otherwise). */
|
|
1192
|
+
unchangedSince<M>(p: NodePath<M>, v: U64): void {
|
|
1193
|
+
this.ops.push({ op: "unchanged", path: p.path.text, since: toJson(BigInt(v)) });
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Read the node, give its model to `f` to change, and write back the fields `f` changed, on
|
|
1197
|
+
* the condition that the node is unchanged since the read (a 412 runs the transaction again).
|
|
1198
|
+
*/
|
|
1199
|
+
async updateChecked<M, P>(p: CanGet<M> & CanUpdate<M, P>, f: (m: M) => M | void): Promise<void> {
|
|
1200
|
+
const { model, version } = await this.db.getVersioned(p);
|
|
1201
|
+
const before = encodeFields(p.type.decl, pick(model, p.type.writable));
|
|
1202
|
+
const copy = structuredCloneModel(model);
|
|
1203
|
+
const after = f(copy) ?? copy;
|
|
1204
|
+
const now = encodeFields(p.type.decl, pick(after, p.type.writable));
|
|
1205
|
+
const changed = Object.fromEntries(
|
|
1206
|
+
Object.entries(now).filter(([k, x]) => JSON.stringify(before[k]) !== JSON.stringify(x)),
|
|
1207
|
+
);
|
|
1208
|
+
this.unchangedSince(p, version);
|
|
1209
|
+
if (Object.keys(changed).length > 0) this.ops.push({ op: "update", path: p.path.text, fields: changed });
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
function pick(m: unknown, props: readonly string[]): Record<string, unknown> {
|
|
1214
|
+
const o = m as Record<string, unknown>;
|
|
1215
|
+
return Object.fromEntries(props.filter((k) => o[k] !== undefined).map((k) => [k, o[k]]));
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
/** A copy of a model that `updateChecked`'s function may change: its fields copied, values
|
|
1219
|
+
* (immutable classes) shared. */
|
|
1220
|
+
function structuredCloneModel<M>(m: M): M {
|
|
1221
|
+
const copy = (x: unknown): unknown =>
|
|
1222
|
+
Array.isArray(x)
|
|
1223
|
+
? x.map(copy)
|
|
1224
|
+
: x && typeof x === "object" && Object.getPrototypeOf(x) === Object.prototype
|
|
1225
|
+
? Object.fromEntries(Object.entries(x).map(([k, v]) => [k, copy(v)]))
|
|
1226
|
+
: x;
|
|
1227
|
+
return copy(m) as M;
|
|
1228
|
+
}
|