@onyx.dev/onyx-database 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1569 @@
1
+ // src/config/defaults.ts
2
+ var DEFAULT_BASE_URL = "https://api.onyx.dev";
3
+ var sanitizeBaseUrl = (u) => u.replace(/\/+$/, "");
4
+
5
+ // src/errors/config-error.ts
6
+ var OnyxConfigError = class extends Error {
7
+ name = "OnyxConfigError";
8
+ constructor(message) {
9
+ super(message);
10
+ }
11
+ };
12
+
13
+ // src/config/chain.ts
14
+ var gProcess = globalThis.process;
15
+ var isNode = !!gProcess?.versions?.node;
16
+ var dbg = (...args) => {
17
+ if (gProcess?.env?.ONYX_DEBUG == "true") {
18
+ const fmt = (v) => {
19
+ if (typeof v === "string") return v;
20
+ try {
21
+ return JSON.stringify(v);
22
+ } catch {
23
+ return String(v);
24
+ }
25
+ };
26
+ gProcess.stderr?.write?.(`[onyx-config] ${args.map(fmt).join(" ")}
27
+ `);
28
+ }
29
+ };
30
+ function dropUndefined(obj) {
31
+ if (!obj) return {};
32
+ const out = {};
33
+ for (const [k, v] of Object.entries(obj)) {
34
+ if (v !== void 0) out[k] = v;
35
+ }
36
+ return out;
37
+ }
38
+ function readEnv(targetId) {
39
+ if (!gProcess?.env) return {};
40
+ const env = gProcess.env;
41
+ const pick = (...keys) => {
42
+ for (const k of keys) {
43
+ const v = env[k];
44
+ if (typeof v === "string") {
45
+ const cleaned = v.replace(/[\r\n]+/g, "").trim();
46
+ if (cleaned !== "") return cleaned;
47
+ }
48
+ }
49
+ return void 0;
50
+ };
51
+ const envId = pick("ONYX_DATABASE_ID");
52
+ if (targetId && envId !== targetId) return {};
53
+ const res = dropUndefined({
54
+ baseUrl: pick("ONYX_DATABASE_BASE_URL"),
55
+ databaseId: envId,
56
+ apiKey: pick("ONYX_DATABASE_API_KEY"),
57
+ apiSecret: pick("ONYX_DATABASE_API_SECRET")
58
+ });
59
+ if (Object.keys(res).length === 0) return {};
60
+ dbg("env:", mask(res));
61
+ return res;
62
+ }
63
+ async function readProjectFile(databaseId) {
64
+ if (!isNode) return {};
65
+ const fs = await import('fs/promises');
66
+ const path = await import('path');
67
+ const cwd = gProcess?.cwd?.() ?? ".";
68
+ const tryRead = async (p) => {
69
+ const txt = await fs.readFile(p, "utf8");
70
+ const sanitized = txt.replace(/[\r\n]+/g, "");
71
+ const json = dropUndefined(JSON.parse(sanitized));
72
+ dbg("project file:", p, "\u2192", mask(json));
73
+ return json;
74
+ };
75
+ if (databaseId) {
76
+ const specific = path.resolve(cwd, `onyx-database-${databaseId}.json`);
77
+ try {
78
+ return await tryRead(specific);
79
+ } catch {
80
+ dbg("project file not found:", specific);
81
+ }
82
+ }
83
+ const fallback = path.resolve(cwd, "onyx-database.json");
84
+ try {
85
+ return await tryRead(fallback);
86
+ } catch {
87
+ dbg("project file not found:", fallback);
88
+ return {};
89
+ }
90
+ }
91
+ async function readHomeProfile(databaseId) {
92
+ if (!isNode) return {};
93
+ const fs = await import('fs/promises');
94
+ const os = await import('os');
95
+ const path = await import('path');
96
+ const home = os.homedir();
97
+ const dir = path.join(home, ".onyx");
98
+ const fileExists = async (p) => {
99
+ try {
100
+ await fs.access(p);
101
+ return true;
102
+ } catch {
103
+ return false;
104
+ }
105
+ };
106
+ const readProfile = async (p) => {
107
+ try {
108
+ const txt = await fs.readFile(p, "utf8");
109
+ const sanitized = txt.replace(/[\r\n]+/g, "");
110
+ const json = dropUndefined(JSON.parse(sanitized));
111
+ dbg("home profile used:", p, "\u2192", mask(json));
112
+ return json;
113
+ } catch (e) {
114
+ const msg = e instanceof Error ? e.message : String(e);
115
+ throw new OnyxConfigError(`Failed to read ${p}: ${msg}`);
116
+ }
117
+ };
118
+ if (databaseId) {
119
+ const specific = `${dir}/onyx-database-${databaseId}.json`;
120
+ if (await fileExists(specific)) return readProfile(specific);
121
+ dbg("no specific profile:", specific);
122
+ }
123
+ const defaultInDir = `${dir}/onyx-database.json`;
124
+ if (await fileExists(defaultInDir)) return readProfile(defaultInDir);
125
+ dbg("no default profile in dir:", defaultInDir);
126
+ const defaultInHome = `${home}/onyx-database.json`;
127
+ if (await fileExists(defaultInHome)) return readProfile(defaultInHome);
128
+ dbg("no home-root fallback:", defaultInHome);
129
+ if (!await fileExists(dir)) {
130
+ dbg("~/.onyx does not exist:", dir);
131
+ return {};
132
+ }
133
+ const files = await fs.readdir(dir).catch(() => []);
134
+ const matches2 = files.filter((f) => f.startsWith("onyx-database-") && f.endsWith(".json"));
135
+ if (matches2.length === 1) {
136
+ const only = `${dir}/${matches2[0]}`;
137
+ return readProfile(only);
138
+ }
139
+ if (matches2.length > 1) {
140
+ throw new OnyxConfigError(
141
+ "Multiple ~/.onyx/onyx-database-*.json profiles found. Specify databaseId via env or provide ./onyx-database.json."
142
+ );
143
+ }
144
+ dbg("no usable home profiles found in", dir);
145
+ return {};
146
+ }
147
+ async function readConfigPath(p) {
148
+ if (!isNode) return {};
149
+ const fs = await import('fs/promises');
150
+ const path = await import('path');
151
+ const cwd = gProcess?.cwd?.() ?? ".";
152
+ const resolved = path.isAbsolute(p) ? p : path.resolve(cwd, p);
153
+ try {
154
+ const txt = await fs.readFile(resolved, "utf8");
155
+ const sanitized = txt.replace(/[\r\n]+/g, "");
156
+ const json = dropUndefined(JSON.parse(sanitized));
157
+ dbg("config path:", resolved, "\u2192", mask(json));
158
+ return json;
159
+ } catch (e) {
160
+ const msg = e instanceof Error ? e.message : String(e);
161
+ throw new OnyxConfigError(`Failed to read ${resolved}: ${msg}`);
162
+ }
163
+ }
164
+ async function resolveConfig(input) {
165
+ const configPath = gProcess?.env?.ONYX_CONFIG_PATH;
166
+ const env = readEnv(input?.databaseId);
167
+ let cfgPath = {};
168
+ if (configPath) {
169
+ cfgPath = await readConfigPath(configPath);
170
+ }
171
+ const targetId = input?.databaseId ?? env.databaseId ?? cfgPath.databaseId;
172
+ let haveDbId = !!(input?.databaseId ?? env.databaseId ?? cfgPath.databaseId);
173
+ let haveApiKey = !!(input?.apiKey ?? env.apiKey ?? cfgPath.apiKey);
174
+ let haveApiSecret = !!(input?.apiSecret ?? env.apiSecret ?? cfgPath.apiSecret);
175
+ let project = {};
176
+ if (!(haveDbId && haveApiKey && haveApiSecret)) {
177
+ project = await readProjectFile(targetId);
178
+ if (project.databaseId) haveDbId = true;
179
+ if (project.apiKey) haveApiKey = true;
180
+ if (project.apiSecret) haveApiSecret = true;
181
+ }
182
+ let home = {};
183
+ if (!(haveDbId && haveApiKey && haveApiSecret)) {
184
+ home = await readHomeProfile(targetId);
185
+ }
186
+ const merged = {
187
+ baseUrl: DEFAULT_BASE_URL,
188
+ ...dropUndefined(home),
189
+ ...dropUndefined(project),
190
+ ...dropUndefined(cfgPath),
191
+ ...dropUndefined(env),
192
+ ...dropUndefined(input)
193
+ };
194
+ dbg("merged (pre-validate):", mask(merged));
195
+ const baseUrl = sanitizeBaseUrl(merged.baseUrl ?? DEFAULT_BASE_URL);
196
+ const databaseId = merged.databaseId ?? "";
197
+ const apiKey = merged.apiKey ?? "";
198
+ const apiSecret = merged.apiSecret ?? "";
199
+ const gfetch = globalThis.fetch;
200
+ const fetchImpl = merged.fetch ?? (typeof gfetch === "function" ? (u, i) => gfetch(u, i) : async () => {
201
+ throw new OnyxConfigError("No fetch available; provide OnyxConfig.fetch");
202
+ });
203
+ const missing = [];
204
+ if (!databaseId) missing.push("databaseId");
205
+ if (!apiKey) missing.push("apiKey");
206
+ if (!apiSecret) missing.push("apiSecret");
207
+ if (missing.length) {
208
+ dbg("validation failed. merged:", mask(merged));
209
+ const sources = [
210
+ "env",
211
+ configPath ?? "env ONYX_CONFIG_PATH",
212
+ ...isNode ? [
213
+ "./onyx-database-<databaseId>.json",
214
+ "./onyx-database.json",
215
+ "~/.onyx/onyx-database-<databaseId>.json",
216
+ "~/.onyx/onyx-database.json",
217
+ "~/onyx-database.json"
218
+ ] : [],
219
+ "explicit config"
220
+ ];
221
+ throw new OnyxConfigError(
222
+ `Missing required config: ${missing.join(", ")}. Sources: ${sources.join(", ")}`
223
+ );
224
+ }
225
+ const resolved = { baseUrl, databaseId, apiKey, apiSecret, fetch: fetchImpl };
226
+ const source = {
227
+ databaseId: input?.databaseId ? "explicit config" : env.databaseId ? "env" : cfgPath.databaseId ? "env ONYX_CONFIG_PATH" : project.databaseId ? "project file" : home.databaseId ? "home profile" : "unknown",
228
+ apiKey: input?.apiKey ? "explicit config" : env.apiKey ? "env" : cfgPath.apiKey ? "env ONYX_CONFIG_PATH" : project.apiKey ? "project file" : home.apiKey ? "home profile" : "unknown",
229
+ apiSecret: input?.apiSecret ? "explicit config" : env.apiSecret ? "env" : cfgPath.apiSecret ? "env ONYX_CONFIG_PATH" : project.apiSecret ? "project file" : home.apiSecret ? "home profile" : "unknown"
230
+ };
231
+ dbg("credential source:", JSON.stringify(source));
232
+ dbg("resolved:", mask(resolved));
233
+ return resolved;
234
+ }
235
+ function mask(obj) {
236
+ if (!obj) return obj;
237
+ const clone = { ...obj };
238
+ if (typeof clone.apiKey === "string") clone.apiKey = "***";
239
+ if (typeof clone.apiSecret === "string") clone.apiSecret = "***";
240
+ return clone;
241
+ }
242
+
243
+ // src/errors/http-error.ts
244
+ var OnyxHttpError = class extends Error {
245
+ name = "OnyxHttpError";
246
+ status;
247
+ statusText;
248
+ body;
249
+ rawBody;
250
+ constructor(message, status, statusText, body, rawBody) {
251
+ super(message);
252
+ this.status = status;
253
+ this.statusText = statusText;
254
+ this.body = body;
255
+ this.rawBody = rawBody;
256
+ }
257
+ toJSON() {
258
+ return {
259
+ name: this.name,
260
+ message: this.message,
261
+ status: this.status,
262
+ statusText: this.statusText,
263
+ body: this.body,
264
+ rawBody: this.rawBody,
265
+ stack: this.stack
266
+ };
267
+ }
268
+ [Symbol.for("nodejs.util.inspect.custom")]() {
269
+ return this.toJSON();
270
+ }
271
+ };
272
+
273
+ // src/core/http.ts
274
+ function parseJsonAllowNaN(txt) {
275
+ try {
276
+ return JSON.parse(txt);
277
+ } catch {
278
+ const fixed = txt.replace(/(:\s*)(NaN|Infinity|-Infinity)(\s*[,}])/g, "$1null$3");
279
+ return JSON.parse(fixed);
280
+ }
281
+ }
282
+ var HttpClient = class {
283
+ baseUrl;
284
+ apiKey;
285
+ apiSecret;
286
+ fetchImpl;
287
+ defaults;
288
+ requestLoggingEnabled;
289
+ responseLoggingEnabled;
290
+ constructor(opts) {
291
+ if (!opts.baseUrl || opts.baseUrl.trim() === "") {
292
+ throw new OnyxConfigError("baseUrl is required");
293
+ }
294
+ try {
295
+ new URL(opts.baseUrl);
296
+ } catch {
297
+ throw new OnyxConfigError("baseUrl must include protocol, e.g. https://");
298
+ }
299
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
300
+ this.apiKey = opts.apiKey;
301
+ this.apiSecret = opts.apiSecret;
302
+ const gfetch = globalThis.fetch;
303
+ if (opts.fetchImpl) {
304
+ this.fetchImpl = opts.fetchImpl;
305
+ } else if (typeof gfetch === "function") {
306
+ this.fetchImpl = (url, init) => gfetch(url, init);
307
+ } else {
308
+ throw new Error("global fetch is not available; provide OnyxConfig.fetch");
309
+ }
310
+ this.defaults = Object.assign({}, opts.defaultHeaders);
311
+ const envDebug = globalThis.process?.env?.ONYX_DEBUG === "true";
312
+ this.requestLoggingEnabled = !!opts.requestLoggingEnabled || envDebug;
313
+ this.responseLoggingEnabled = !!opts.responseLoggingEnabled || envDebug;
314
+ }
315
+ headers(extra) {
316
+ const extras = { ...extra ?? {} };
317
+ delete extras["x-onyx-key"];
318
+ delete extras["x-onyx-secret"];
319
+ return {
320
+ "x-onyx-key": this.apiKey,
321
+ "x-onyx-secret": this.apiSecret,
322
+ "Accept": "application/json",
323
+ "Content-Type": "application/json",
324
+ ...this.defaults,
325
+ ...extras
326
+ };
327
+ }
328
+ async request(method, path, body, extraHeaders) {
329
+ if (!path.startsWith("/")) {
330
+ throw new OnyxConfigError("path must start with /");
331
+ }
332
+ const url = `${this.baseUrl}${path}`;
333
+ const headers = this.headers({
334
+ ...method === "DELETE" ? { Prefer: "return=representation" } : {},
335
+ ...extraHeaders ?? {}
336
+ });
337
+ if (body == null) delete headers["Content-Type"];
338
+ if (this.requestLoggingEnabled) {
339
+ console.log(`${method} ${url}`);
340
+ if (body != null) {
341
+ const logBody = typeof body === "string" ? body : JSON.stringify(body);
342
+ console.log(logBody);
343
+ }
344
+ const headerLog = { ...headers, "x-onyx-secret": "[REDACTED]" };
345
+ console.log("Headers:", headerLog);
346
+ }
347
+ const payload = body == null ? void 0 : typeof body === "string" ? body : JSON.stringify(body);
348
+ const init = {
349
+ method,
350
+ headers,
351
+ body: payload
352
+ };
353
+ const isQuery = path.includes("/query/") && !/\/query\/(?:update|delete)\//.test(path);
354
+ const canRetry = method === "GET" || isQuery;
355
+ const maxAttempts = canRetry ? 3 : 1;
356
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
357
+ try {
358
+ const res = await this.fetchImpl(url, init);
359
+ const contentType = res.headers.get("Content-Type") || "";
360
+ const raw = await res.text();
361
+ if (this.responseLoggingEnabled) {
362
+ const statusLine = `${res.status} ${res.statusText}`.trim();
363
+ console.log(statusLine);
364
+ if (raw.trim().length > 0) {
365
+ console.log(raw);
366
+ }
367
+ }
368
+ const isJson = raw.trim().length > 0 && (contentType.includes("application/json") || /^[\[{]/.test(raw.trim()));
369
+ const data = isJson ? parseJsonAllowNaN(raw) : raw;
370
+ if (!res.ok) {
371
+ const msg = typeof data === "object" && data !== null && "error" in data && typeof data.error?.message === "string" ? String(data.error.message) : `${res.status} ${res.statusText}`;
372
+ if (canRetry && res.status >= 500 && attempt + 1 < maxAttempts) {
373
+ await new Promise((r) => setTimeout(r, 100 * 2 ** attempt));
374
+ continue;
375
+ }
376
+ throw new OnyxHttpError(msg, res.status, res.statusText, data, raw);
377
+ }
378
+ return data;
379
+ } catch (err) {
380
+ const retryable = canRetry && (!(err instanceof OnyxHttpError) || err.status >= 500);
381
+ if (attempt + 1 < maxAttempts && retryable) {
382
+ await new Promise((r) => setTimeout(r, 100 * 2 ** attempt));
383
+ continue;
384
+ }
385
+ throw err;
386
+ }
387
+ }
388
+ throw new Error("Request failed after retries");
389
+ }
390
+ };
391
+
392
+ // src/core/stream.ts
393
+ var debug = (...args) => {
394
+ if (globalThis.process?.env?.ONYX_STREAM_DEBUG == "true")
395
+ console.log("[onyx-stream]", ...args);
396
+ };
397
+ async function openJsonLinesStream(fetchImpl, url, init = {}, handlers = {}) {
398
+ const decoder = new TextDecoder("utf-8");
399
+ let buffer = "";
400
+ let canceled = false;
401
+ let currentReader = null;
402
+ let retryCount = 0;
403
+ const maxRetries = 4;
404
+ const processLine = (line) => {
405
+ const trimmed = line.trim();
406
+ debug("line", trimmed);
407
+ if (!trimmed || trimmed.startsWith(":")) return;
408
+ const jsonLine = trimmed.startsWith("data:") ? trimmed.slice(5).trim() : trimmed;
409
+ let obj;
410
+ try {
411
+ obj = parseJsonAllowNaN(jsonLine);
412
+ } catch {
413
+ return;
414
+ }
415
+ const rawAction = obj.action ?? obj.event ?? obj.type ?? obj.eventType ?? obj.changeType;
416
+ const entity = obj.entity;
417
+ const action = rawAction?.toUpperCase();
418
+ if (action === "CREATE" || action === "CREATED" || action === "ADDED" || action === "ADD" || action === "INSERT" || action === "INSERTED")
419
+ handlers.onItemAdded?.(entity);
420
+ else if (action === "UPDATE" || action === "UPDATED")
421
+ handlers.onItemUpdated?.(entity);
422
+ else if (action === "DELETE" || action === "DELETED" || action === "REMOVE" || action === "REMOVED")
423
+ handlers.onItemDeleted?.(entity);
424
+ const canonical = action === "ADDED" || action === "ADD" || action === "CREATE" || action === "CREATED" || action === "INSERT" || action === "INSERTED" ? "CREATE" : action === "UPDATED" || action === "UPDATE" ? "UPDATE" : action === "DELETED" || action === "DELETE" || action === "REMOVE" || action === "REMOVED" ? "DELETE" : action;
425
+ if (canonical && canonical !== "KEEP_ALIVE")
426
+ handlers.onItem?.(entity ?? null, canonical);
427
+ debug("dispatch", canonical, entity);
428
+ };
429
+ const connect = async () => {
430
+ if (canceled) return;
431
+ debug("connecting", url);
432
+ try {
433
+ const res = await fetchImpl(url, {
434
+ method: init.method ?? "PUT",
435
+ headers: init.headers ?? {},
436
+ body: init.body
437
+ });
438
+ debug("response", res.status, res.statusText);
439
+ if (!res.ok) {
440
+ const raw = await res.text();
441
+ let parsed = raw;
442
+ try {
443
+ parsed = parseJsonAllowNaN(raw);
444
+ } catch {
445
+ }
446
+ debug("non-ok", res.status);
447
+ throw new OnyxHttpError(`${res.status} ${res.statusText}`, res.status, res.statusText, parsed, raw);
448
+ }
449
+ const body = res.body;
450
+ if (!body || typeof body.getReader !== "function") {
451
+ debug("no reader");
452
+ return;
453
+ }
454
+ currentReader = body.getReader();
455
+ debug("connected");
456
+ retryCount = 0;
457
+ pump();
458
+ } catch (err) {
459
+ debug("connect error", err);
460
+ if (canceled) return;
461
+ if (retryCount >= maxRetries) return;
462
+ const delay = Math.min(1e3 * 2 ** retryCount, 3e4);
463
+ retryCount++;
464
+ await new Promise((resolve) => setTimeout(resolve, delay));
465
+ void connect();
466
+ }
467
+ };
468
+ const pump = () => {
469
+ if (canceled || !currentReader) return;
470
+ currentReader.read().then(({ done, value }) => {
471
+ if (canceled) return;
472
+ debug("chunk", { done, length: value?.length ?? 0 });
473
+ if (done) {
474
+ debug("done");
475
+ void connect();
476
+ return;
477
+ }
478
+ buffer += decoder.decode(value, { stream: true });
479
+ const lines = buffer.split("\n");
480
+ buffer = lines.pop() ?? "";
481
+ for (const line of lines) processLine(line);
482
+ pump();
483
+ }).catch((err) => {
484
+ debug("pump error", err);
485
+ if (!canceled) void connect();
486
+ });
487
+ };
488
+ await connect();
489
+ return {
490
+ cancel() {
491
+ if (canceled) return;
492
+ canceled = true;
493
+ try {
494
+ currentReader?.cancel();
495
+ } catch {
496
+ }
497
+ }
498
+ };
499
+ }
500
+
501
+ // src/builders/query-results.ts
502
+ var QueryResults = class extends Array {
503
+ /** Token for the next page of results or null. */
504
+ nextPage;
505
+ fetcher;
506
+ /**
507
+ * @param records - Records in the current page.
508
+ * @param nextPage - Token representing the next page.
509
+ * @param fetcher - Function used to fetch the next page when needed.
510
+ * @example
511
+ * ```ts
512
+ * const results = new QueryResults(users, token, t => fetchMore(t));
513
+ * ```
514
+ */
515
+ constructor(records, nextPage, fetcher) {
516
+ super(...records);
517
+ Object.setPrototypeOf(this, new.target.prototype);
518
+ this.nextPage = nextPage;
519
+ this.fetcher = fetcher;
520
+ }
521
+ /**
522
+ * Returns the first record in the result set.
523
+ * @throws Error if the result set is empty.
524
+ * @example
525
+ * ```ts
526
+ * const user = results.first();
527
+ * ```
528
+ */
529
+ first() {
530
+ if (this.length === 0) throw new Error("QueryResults is empty");
531
+ return this[0];
532
+ }
533
+ /**
534
+ * Returns the first record or `null` if the result set is empty.
535
+ * @example
536
+ * ```ts
537
+ * const user = results.firstOrNull();
538
+ * ```
539
+ */
540
+ firstOrNull() {
541
+ return this.length > 0 ? this[0] : null;
542
+ }
543
+ /**
544
+ * Checks whether the current page has no records.
545
+ * @example
546
+ * ```ts
547
+ * if (results.isEmpty()) console.log('no data');
548
+ * ```
549
+ */
550
+ isEmpty() {
551
+ return this.length === 0;
552
+ }
553
+ /**
554
+ * Number of records on the current page.
555
+ * @example
556
+ * ```ts
557
+ * console.log(results.size());
558
+ * ```
559
+ */
560
+ size() {
561
+ return this.length;
562
+ }
563
+ /**
564
+ * Iterates over each record on the current page only.
565
+ * @param action - Function to invoke for each record.
566
+ * @example
567
+ * ```ts
568
+ * results.forEachOnPage(u => console.log(u.id));
569
+ * ```
570
+ */
571
+ forEachOnPage(action) {
572
+ this.forEach(action);
573
+ }
574
+ /**
575
+ * Iterates over every record across all pages sequentially.
576
+ * @param action - Function executed for each record. Returning `false`
577
+ * stops iteration early.
578
+ * @example
579
+ * ```ts
580
+ * await results.forEachAll(u => {
581
+ * if (u.disabled) return false;
582
+ * });
583
+ * ```
584
+ */
585
+ async forEachAll(action) {
586
+ await this.forEachPage(async (records) => {
587
+ for (const r of records) {
588
+ const res = await action(r);
589
+ if (res === false) return false;
590
+ }
591
+ return true;
592
+ });
593
+ }
594
+ /**
595
+ * Iterates page by page across the result set.
596
+ * @param action - Function invoked with each page of records. Returning
597
+ * `false` stops iteration.
598
+ * @example
599
+ * ```ts
600
+ * await results.forEachPage(page => {
601
+ * console.log(page.length);
602
+ * });
603
+ * ```
604
+ */
605
+ async forEachPage(action) {
606
+ let page = this;
607
+ while (page) {
608
+ const cont = await action(Array.from(page));
609
+ if (cont === false) return;
610
+ if (page.nextPage && page.fetcher) {
611
+ page = await page.fetcher(page.nextPage);
612
+ } else {
613
+ page = null;
614
+ }
615
+ }
616
+ }
617
+ /**
618
+ * Collects all records from every page into a single array.
619
+ * @returns All records.
620
+ * @example
621
+ * ```ts
622
+ * const allUsers = await results.getAllRecords();
623
+ * ```
624
+ */
625
+ async getAllRecords() {
626
+ const all = [];
627
+ await this.forEachPage((records) => {
628
+ all.push(...records);
629
+ });
630
+ return all;
631
+ }
632
+ /**
633
+ * Filters all records using the provided predicate.
634
+ * @param predicate - Function used to test each record.
635
+ * @example
636
+ * ```ts
637
+ * const enabled = await results.filterAll(u => u.enabled);
638
+ * ```
639
+ */
640
+ async filterAll(predicate) {
641
+ const all = await this.getAllRecords();
642
+ return all.filter(predicate);
643
+ }
644
+ /**
645
+ * Maps all records using the provided transform.
646
+ * @param transform - Mapping function.
647
+ * @example
648
+ * ```ts
649
+ * const names = await results.mapAll(u => u.name);
650
+ * ```
651
+ */
652
+ async mapAll(transform) {
653
+ const all = await this.getAllRecords();
654
+ return all.map(transform);
655
+ }
656
+ /**
657
+ * Extracts values for a field across all records.
658
+ * @param field - Name of the field to pluck.
659
+ * @example
660
+ * ```ts
661
+ * const ids = await results.values('id');
662
+ * ```
663
+ */
664
+ // @ts-expect-error overriding Array#values
665
+ async values(field) {
666
+ const all = await this.getAllRecords();
667
+ return all.map((r) => r[field]);
668
+ }
669
+ /**
670
+ * Maximum value produced by the selector across all records.
671
+ * @param selector - Function extracting a numeric value.
672
+ * @example
673
+ * ```ts
674
+ * const maxAge = await results.maxOfDouble(u => u.age);
675
+ * ```
676
+ */
677
+ async maxOfDouble(selector) {
678
+ const all = await this.getAllRecords();
679
+ return all.reduce((max2, r) => Math.max(max2, selector(r)), -Infinity);
680
+ }
681
+ /**
682
+ * Minimum value produced by the selector across all records.
683
+ * @param selector - Function extracting a numeric value.
684
+ * @example
685
+ * ```ts
686
+ * const minAge = await results.minOfDouble(u => u.age);
687
+ * ```
688
+ */
689
+ async minOfDouble(selector) {
690
+ const all = await this.getAllRecords();
691
+ return all.reduce((min2, r) => Math.min(min2, selector(r)), Infinity);
692
+ }
693
+ /**
694
+ * Sum of values produced by the selector across all records.
695
+ * @param selector - Function extracting a numeric value.
696
+ * @example
697
+ * ```ts
698
+ * const total = await results.sumOfDouble(u => u.score);
699
+ * ```
700
+ */
701
+ async sumOfDouble(selector) {
702
+ const all = await this.getAllRecords();
703
+ return all.reduce((sum2, r) => sum2 + selector(r), 0);
704
+ }
705
+ /**
706
+ * Maximum float value from the selector.
707
+ * @param selector - Function extracting a numeric value.
708
+ */
709
+ async maxOfFloat(selector) {
710
+ return this.maxOfDouble(selector);
711
+ }
712
+ /**
713
+ * Minimum float value from the selector.
714
+ * @param selector - Function extracting a numeric value.
715
+ */
716
+ async minOfFloat(selector) {
717
+ return this.minOfDouble(selector);
718
+ }
719
+ /**
720
+ * Sum of float values from the selector.
721
+ * @param selector - Function extracting a numeric value.
722
+ */
723
+ async sumOfFloat(selector) {
724
+ return this.sumOfDouble(selector);
725
+ }
726
+ /**
727
+ * Maximum integer value from the selector.
728
+ * @param selector - Function extracting a numeric value.
729
+ */
730
+ async maxOfInt(selector) {
731
+ return this.maxOfDouble(selector);
732
+ }
733
+ /**
734
+ * Minimum integer value from the selector.
735
+ * @param selector - Function extracting a numeric value.
736
+ */
737
+ async minOfInt(selector) {
738
+ return this.minOfDouble(selector);
739
+ }
740
+ /**
741
+ * Sum of integer values from the selector.
742
+ * @param selector - Function extracting a numeric value.
743
+ */
744
+ async sumOfInt(selector) {
745
+ return this.sumOfDouble(selector);
746
+ }
747
+ /**
748
+ * Maximum long value from the selector.
749
+ * @param selector - Function extracting a numeric value.
750
+ */
751
+ async maxOfLong(selector) {
752
+ return this.maxOfDouble(selector);
753
+ }
754
+ /**
755
+ * Minimum long value from the selector.
756
+ * @param selector - Function extracting a numeric value.
757
+ */
758
+ async minOfLong(selector) {
759
+ return this.minOfDouble(selector);
760
+ }
761
+ /**
762
+ * Sum of long values from the selector.
763
+ * @param selector - Function extracting a numeric value.
764
+ */
765
+ async sumOfLong(selector) {
766
+ return this.sumOfDouble(selector);
767
+ }
768
+ /**
769
+ * Sum of bigint values from the selector.
770
+ * @param selector - Function extracting a bigint value.
771
+ * @example
772
+ * ```ts
773
+ * const total = await results.sumOfBigInt(u => u.balance);
774
+ * ```
775
+ */
776
+ async sumOfBigInt(selector) {
777
+ const all = await this.getAllRecords();
778
+ return all.reduce((sum2, r) => sum2 + selector(r), 0n);
779
+ }
780
+ /**
781
+ * Executes an action for each page in parallel.
782
+ * @param action - Function executed for each record concurrently.
783
+ * @example
784
+ * ```ts
785
+ * await results.forEachPageParallel(async u => sendEmail(u));
786
+ * ```
787
+ */
788
+ async forEachPageParallel(action) {
789
+ await this.forEachPage((records) => Promise.all(records.map(action)).then(() => true));
790
+ }
791
+ };
792
+
793
+ // src/builders/cascade-relationship-builder.ts
794
+ var CascadeRelationshipBuilder = class {
795
+ graphName;
796
+ typeName;
797
+ target;
798
+ /**
799
+ * Set the graph name component.
800
+ *
801
+ * @param name Graph name or namespace.
802
+ * @example
803
+ * ```ts
804
+ * builder.graph('programs');
805
+ * ```
806
+ */
807
+ graph(name) {
808
+ this.graphName = name;
809
+ return this;
810
+ }
811
+ /**
812
+ * Set the graph type component.
813
+ *
814
+ * @param type Graph type to target.
815
+ * @example
816
+ * ```ts
817
+ * builder.graphType('StreamingProgram');
818
+ * ```
819
+ */
820
+ graphType(type) {
821
+ this.typeName = type;
822
+ return this;
823
+ }
824
+ /**
825
+ * Set the target field for the relationship.
826
+ *
827
+ * @param field Target field name.
828
+ * @example
829
+ * ```ts
830
+ * builder.targetField('channelId');
831
+ * ```
832
+ */
833
+ targetField(field) {
834
+ this.target = field;
835
+ return this;
836
+ }
837
+ /**
838
+ * Produce the cascade relationship string using the provided source field.
839
+ *
840
+ * @param field Source field name.
841
+ * @example
842
+ * ```ts
843
+ * const rel = builder
844
+ * .graph('programs')
845
+ * .graphType('StreamingProgram')
846
+ * .targetField('channelId')
847
+ * .sourceField('id');
848
+ * // rel === 'programs:StreamingProgram(channelId, id)'
849
+ * ```
850
+ */
851
+ sourceField(field) {
852
+ if (!this.graphName || !this.typeName || !this.target) {
853
+ throw new Error("Cascade relationship requires graph, type, target, and source fields");
854
+ }
855
+ return `${this.graphName}:${this.typeName}(${this.target}, ${field})`;
856
+ }
857
+ };
858
+
859
+ // src/errors/onyx-error.ts
860
+ var OnyxError = class extends Error {
861
+ name = "OnyxError";
862
+ constructor(message) {
863
+ super(message);
864
+ }
865
+ };
866
+
867
+ // src/impl/onyx.ts
868
+ var DEFAULT_CACHE_TTL = 5 * 60 * 1e3;
869
+ var cachedCfg = null;
870
+ function resolveConfigWithCache(config) {
871
+ const ttl = config?.ttl ?? DEFAULT_CACHE_TTL;
872
+ const now = Date.now();
873
+ if (cachedCfg && cachedCfg.expires > now) {
874
+ return cachedCfg.promise;
875
+ }
876
+ const { ttl: _ttl, requestLoggingEnabled: _reqLog, responseLoggingEnabled: _resLog, ...rest } = config ?? {};
877
+ const promise = resolveConfig(rest);
878
+ cachedCfg = { promise, expires: now + ttl };
879
+ return promise;
880
+ }
881
+ function clearCacheConfig() {
882
+ cachedCfg = null;
883
+ }
884
+ function toSingleCondition(criteria) {
885
+ return { conditionType: "SingleCondition", criteria };
886
+ }
887
+ function toCondition(input) {
888
+ if (typeof input.toCondition === "function") {
889
+ return input.toCondition();
890
+ }
891
+ const c2 = input;
892
+ if (c2 && typeof c2.field === "string" && typeof c2.operator === "string") {
893
+ return toSingleCondition(c2);
894
+ }
895
+ throw new Error("Invalid condition passed to builder.");
896
+ }
897
+ function serializeDates(value) {
898
+ if (value instanceof Date) return value.toISOString();
899
+ if (Array.isArray(value)) return value.map(serializeDates);
900
+ if (value && typeof value === "object") {
901
+ const out = {};
902
+ for (const [k, v] of Object.entries(value)) {
903
+ out[k] = serializeDates(v);
904
+ }
905
+ return out;
906
+ }
907
+ return value;
908
+ }
909
+ var OnyxDatabaseImpl = class {
910
+ cfgPromise;
911
+ resolved = null;
912
+ http = null;
913
+ streams = /* @__PURE__ */ new Set();
914
+ requestLoggingEnabled;
915
+ responseLoggingEnabled;
916
+ defaultPartition;
917
+ constructor(config) {
918
+ this.requestLoggingEnabled = !!config?.requestLoggingEnabled;
919
+ this.responseLoggingEnabled = !!config?.responseLoggingEnabled;
920
+ this.defaultPartition = config?.partition;
921
+ this.cfgPromise = resolveConfigWithCache(config);
922
+ }
923
+ async ensureClient() {
924
+ if (!this.resolved) {
925
+ this.resolved = await this.cfgPromise;
926
+ }
927
+ if (!this.http) {
928
+ this.http = new HttpClient({
929
+ baseUrl: this.resolved.baseUrl,
930
+ apiKey: this.resolved.apiKey,
931
+ apiSecret: this.resolved.apiSecret,
932
+ fetchImpl: this.resolved.fetch,
933
+ requestLoggingEnabled: this.requestLoggingEnabled,
934
+ responseLoggingEnabled: this.responseLoggingEnabled
935
+ });
936
+ }
937
+ return {
938
+ http: this.http,
939
+ fetchImpl: this.resolved.fetch,
940
+ baseUrl: this.resolved.baseUrl,
941
+ databaseId: this.resolved.databaseId
942
+ };
943
+ }
944
+ registerStream(handle) {
945
+ this.streams.add(handle);
946
+ return {
947
+ cancel: () => {
948
+ try {
949
+ handle.cancel();
950
+ } finally {
951
+ this.streams.delete(handle);
952
+ }
953
+ }
954
+ };
955
+ }
956
+ /** -------- IOnyxDatabase -------- */
957
+ from(table) {
958
+ return new QueryBuilderImpl(this, String(table), this.defaultPartition);
959
+ }
960
+ select(...fields) {
961
+ const qb = new QueryBuilderImpl(
962
+ this,
963
+ null,
964
+ this.defaultPartition
965
+ );
966
+ qb.selectFields(...fields);
967
+ return qb;
968
+ }
969
+ cascade(...relationships) {
970
+ const cb = new CascadeBuilderImpl(this);
971
+ return cb.cascade(...relationships);
972
+ }
973
+ cascadeBuilder() {
974
+ return new CascadeRelationshipBuilder();
975
+ }
976
+ // Impl
977
+ save(table, entityOrEntities, options) {
978
+ if (arguments.length === 1) {
979
+ return new SaveBuilderImpl(this, table);
980
+ }
981
+ return this._saveInternal(table, entityOrEntities, options);
982
+ }
983
+ async batchSave(table, entities, batchSize = 1e3, options) {
984
+ for (let i = 0; i < entities.length; i += batchSize) {
985
+ const chunk = entities.slice(i, i + batchSize);
986
+ if (chunk.length) {
987
+ await this._saveInternal(String(table), chunk, options);
988
+ }
989
+ }
990
+ }
991
+ async findById(table, primaryKey, options) {
992
+ const { http, databaseId } = await this.ensureClient();
993
+ const params = new URLSearchParams();
994
+ const partition = options?.partition ?? this.defaultPartition;
995
+ if (partition) params.append("partition", partition);
996
+ if (options?.resolvers?.length) params.append("resolvers", options.resolvers.join(","));
997
+ const path = `/data/${encodeURIComponent(databaseId)}/${encodeURIComponent(
998
+ String(table)
999
+ )}/${encodeURIComponent(primaryKey)}${params.toString() ? `?${params.toString()}` : ""}`;
1000
+ try {
1001
+ return await http.request("GET", path);
1002
+ } catch (err) {
1003
+ if (err instanceof OnyxHttpError && err.status === 404) return null;
1004
+ throw err;
1005
+ }
1006
+ }
1007
+ async delete(table, primaryKey, options) {
1008
+ const { http, databaseId } = await this.ensureClient();
1009
+ const params = new URLSearchParams();
1010
+ const partition = options?.partition ?? this.defaultPartition;
1011
+ if (partition) params.append("partition", partition);
1012
+ if (options?.relationships?.length) {
1013
+ params.append("relationships", options.relationships.map(encodeURIComponent).join(","));
1014
+ }
1015
+ const path = `/data/${encodeURIComponent(databaseId)}/${encodeURIComponent(
1016
+ table
1017
+ )}/${encodeURIComponent(primaryKey)}${params.toString() ? `?${params.toString()}` : ""}`;
1018
+ return http.request("DELETE", path);
1019
+ }
1020
+ async saveDocument(doc) {
1021
+ const { http, databaseId } = await this.ensureClient();
1022
+ const path = `/data/${encodeURIComponent(databaseId)}/document`;
1023
+ return http.request("PUT", path, serializeDates(doc));
1024
+ }
1025
+ async getDocument(documentId, options) {
1026
+ const { http, databaseId } = await this.ensureClient();
1027
+ const params = new URLSearchParams();
1028
+ if (options?.width != null) params.append("width", String(options.width));
1029
+ if (options?.height != null) params.append("height", String(options.height));
1030
+ const path = `/data/${encodeURIComponent(databaseId)}/document/${encodeURIComponent(
1031
+ documentId
1032
+ )}${params.toString() ? `?${params.toString()}` : ""}`;
1033
+ return http.request("GET", path);
1034
+ }
1035
+ async deleteDocument(documentId) {
1036
+ const { http, databaseId } = await this.ensureClient();
1037
+ const path = `/data/${encodeURIComponent(databaseId)}/document/${encodeURIComponent(
1038
+ documentId
1039
+ )}`;
1040
+ return http.request("DELETE", path);
1041
+ }
1042
+ close() {
1043
+ for (const h of Array.from(this.streams)) {
1044
+ try {
1045
+ h.cancel();
1046
+ } catch {
1047
+ } finally {
1048
+ this.streams.delete(h);
1049
+ }
1050
+ }
1051
+ }
1052
+ /** -------- internal helpers used by builders -------- */
1053
+ async _count(table, select, partition) {
1054
+ const { http, databaseId } = await this.ensureClient();
1055
+ const params = new URLSearchParams();
1056
+ const p = partition ?? this.defaultPartition;
1057
+ if (p) params.append("partition", p);
1058
+ const path = `/data/${encodeURIComponent(databaseId)}/query/count/${encodeURIComponent(
1059
+ table
1060
+ )}${params.toString() ? `?${params.toString()}` : ""}`;
1061
+ return http.request("PUT", path, serializeDates(select));
1062
+ }
1063
+ async _queryPage(table, select, opts = {}) {
1064
+ const { http, databaseId } = await this.ensureClient();
1065
+ const params = new URLSearchParams();
1066
+ if (opts.pageSize != null) params.append("pageSize", String(opts.pageSize));
1067
+ if (opts.nextPage) params.append("nextPage", opts.nextPage);
1068
+ const p = opts.partition ?? this.defaultPartition;
1069
+ if (p) params.append("partition", p);
1070
+ const path = `/data/${encodeURIComponent(databaseId)}/query/${encodeURIComponent(
1071
+ table
1072
+ )}${params.toString() ? `?${params.toString()}` : ""}`;
1073
+ return http.request("PUT", path, serializeDates(select));
1074
+ }
1075
+ async _update(table, update, partition) {
1076
+ const { http, databaseId } = await this.ensureClient();
1077
+ const params = new URLSearchParams();
1078
+ const p = partition ?? this.defaultPartition;
1079
+ if (p) params.append("partition", p);
1080
+ const path = `/data/${encodeURIComponent(databaseId)}/query/update/${encodeURIComponent(
1081
+ table
1082
+ )}${params.toString() ? `?${params.toString()}` : ""}`;
1083
+ return http.request("PUT", path, serializeDates(update));
1084
+ }
1085
+ async _deleteByQuery(table, select, partition) {
1086
+ const { http, databaseId } = await this.ensureClient();
1087
+ const params = new URLSearchParams();
1088
+ const p = partition ?? this.defaultPartition;
1089
+ if (p) params.append("partition", p);
1090
+ const path = `/data/${encodeURIComponent(databaseId)}/query/delete/${encodeURIComponent(
1091
+ table
1092
+ )}${params.toString() ? `?${params.toString()}` : ""}`;
1093
+ return http.request("PUT", path, serializeDates(select));
1094
+ }
1095
+ async _stream(table, select, includeQueryResults, keepAlive, handlers) {
1096
+ const { http, baseUrl, databaseId, fetchImpl } = await this.ensureClient();
1097
+ const params = new URLSearchParams();
1098
+ if (includeQueryResults) params.append("includeQueryResults", "true");
1099
+ if (keepAlive) params.append("keepAlive", "true");
1100
+ const url = `${baseUrl}/data/${encodeURIComponent(databaseId)}/query/stream/${encodeURIComponent(
1101
+ table
1102
+ )}${params.toString() ? `?${params.toString()}` : ""}`;
1103
+ const handle = await openJsonLinesStream(
1104
+ fetchImpl,
1105
+ url,
1106
+ {
1107
+ method: "PUT",
1108
+ headers: http.headers({
1109
+ Accept: "application/x-ndjson",
1110
+ "Content-Type": "application/json"
1111
+ }),
1112
+ body: JSON.stringify(serializeDates(select))
1113
+ },
1114
+ handlers
1115
+ );
1116
+ return this.registerStream(handle);
1117
+ }
1118
+ async _saveInternal(table, entityOrEntities, options) {
1119
+ const { http, databaseId } = await this.ensureClient();
1120
+ const params = new URLSearchParams();
1121
+ if (options?.relationships?.length) {
1122
+ params.append("relationships", options.relationships.map(encodeURIComponent).join(","));
1123
+ }
1124
+ const path = `/data/${encodeURIComponent(databaseId)}/${encodeURIComponent(table)}${params.toString() ? `?${params.toString()}` : ""}`;
1125
+ return http.request("PUT", path, serializeDates(entityOrEntities));
1126
+ }
1127
+ };
1128
+ var QueryBuilderImpl = class {
1129
+ db;
1130
+ table;
1131
+ fields = null;
1132
+ resolvers = null;
1133
+ conditions = null;
1134
+ sort = null;
1135
+ limitValue = null;
1136
+ distinctValue = false;
1137
+ groupByValues = null;
1138
+ partitionValue;
1139
+ pageSizeValue = null;
1140
+ nextPageValue = null;
1141
+ mode = "select";
1142
+ updates = null;
1143
+ onItemAddedListener = null;
1144
+ onItemUpdatedListener = null;
1145
+ onItemDeletedListener = null;
1146
+ onItemListener = null;
1147
+ constructor(db, table, partition) {
1148
+ this.db = db;
1149
+ this.table = table;
1150
+ this.partitionValue = partition;
1151
+ }
1152
+ ensureTable() {
1153
+ if (!this.table) throw new Error("Table is not defined. Call from(<table>) first.");
1154
+ return this.table;
1155
+ }
1156
+ toSelectQuery() {
1157
+ return {
1158
+ type: "SelectQuery",
1159
+ fields: this.fields,
1160
+ conditions: this.conditions,
1161
+ sort: this.sort,
1162
+ limit: this.limitValue,
1163
+ distinct: this.distinctValue,
1164
+ groupBy: this.groupByValues,
1165
+ partition: this.partitionValue ?? null,
1166
+ resolvers: this.resolvers
1167
+ };
1168
+ }
1169
+ from(table) {
1170
+ this.table = table;
1171
+ return this;
1172
+ }
1173
+ selectFields(...fields) {
1174
+ const flat = fields.flatMap((f) => Array.isArray(f) ? f : [f]);
1175
+ this.fields = flat.length > 0 ? flat : null;
1176
+ return this;
1177
+ }
1178
+ resolve(...values) {
1179
+ const flat = values.flatMap((v) => Array.isArray(v) ? v : [v]);
1180
+ this.resolvers = flat.length > 0 ? flat : null;
1181
+ return this;
1182
+ }
1183
+ where(condition) {
1184
+ const c2 = toCondition(condition);
1185
+ if (!this.conditions) {
1186
+ this.conditions = c2;
1187
+ } else {
1188
+ this.conditions = {
1189
+ conditionType: "CompoundCondition",
1190
+ operator: "AND",
1191
+ conditions: [this.conditions, c2]
1192
+ };
1193
+ }
1194
+ return this;
1195
+ }
1196
+ and(condition) {
1197
+ const c2 = toCondition(condition);
1198
+ if (!this.conditions) {
1199
+ this.conditions = c2;
1200
+ } else if (this.conditions.conditionType === "CompoundCondition" && this.conditions.operator === "AND") {
1201
+ this.conditions.conditions.push(c2);
1202
+ } else {
1203
+ this.conditions = {
1204
+ conditionType: "CompoundCondition",
1205
+ operator: "AND",
1206
+ conditions: [this.conditions, c2]
1207
+ };
1208
+ }
1209
+ return this;
1210
+ }
1211
+ or(condition) {
1212
+ const c2 = toCondition(condition);
1213
+ if (!this.conditions) {
1214
+ this.conditions = c2;
1215
+ } else if (this.conditions.conditionType === "CompoundCondition" && this.conditions.operator === "OR") {
1216
+ this.conditions.conditions.push(c2);
1217
+ } else {
1218
+ this.conditions = {
1219
+ conditionType: "CompoundCondition",
1220
+ operator: "OR",
1221
+ conditions: [this.conditions, c2]
1222
+ };
1223
+ }
1224
+ return this;
1225
+ }
1226
+ orderBy(...sorts) {
1227
+ this.sort = sorts;
1228
+ return this;
1229
+ }
1230
+ groupBy(...fields) {
1231
+ this.groupByValues = fields.length ? fields : null;
1232
+ return this;
1233
+ }
1234
+ distinct() {
1235
+ this.distinctValue = true;
1236
+ return this;
1237
+ }
1238
+ limit(n) {
1239
+ this.limitValue = n;
1240
+ return this;
1241
+ }
1242
+ inPartition(partition) {
1243
+ this.partitionValue = partition;
1244
+ return this;
1245
+ }
1246
+ pageSize(n) {
1247
+ this.pageSizeValue = n;
1248
+ return this;
1249
+ }
1250
+ nextPage(token) {
1251
+ this.nextPageValue = token;
1252
+ return this;
1253
+ }
1254
+ setUpdates(updates) {
1255
+ this.mode = "update";
1256
+ this.updates = updates;
1257
+ return this;
1258
+ }
1259
+ async count() {
1260
+ if (this.mode !== "select") throw new Error("Cannot call count() in update mode.");
1261
+ const table = this.ensureTable();
1262
+ return this.db._count(table, this.toSelectQuery(), this.partitionValue);
1263
+ }
1264
+ async page(options = {}) {
1265
+ if (this.mode !== "select") throw new Error("Cannot call page() in update mode.");
1266
+ const table = this.ensureTable();
1267
+ const final = {
1268
+ pageSize: this.pageSizeValue ?? options.pageSize,
1269
+ nextPage: this.nextPageValue ?? options.nextPage,
1270
+ partition: this.partitionValue
1271
+ };
1272
+ return this.db._queryPage(table, this.toSelectQuery(), final);
1273
+ }
1274
+ list(options = {}) {
1275
+ const size = this.pageSizeValue ?? options.pageSize;
1276
+ const pgPromise = this.page(options).then((pg) => {
1277
+ const fetcher = (token) => this.nextPage(token).list({ pageSize: size });
1278
+ return new QueryResults(Array.isArray(pg.records) ? pg.records : [], pg.nextPage ?? null, fetcher);
1279
+ });
1280
+ for (const m of Object.getOwnPropertyNames(QueryResults.prototype)) {
1281
+ if (m === "constructor") continue;
1282
+ pgPromise[m] = (...args) => pgPromise.then((res) => res[m](...args));
1283
+ }
1284
+ return pgPromise;
1285
+ }
1286
+ async firstOrNull() {
1287
+ if (this.mode !== "select") throw new Error("Cannot call firstOrNull() in update mode.");
1288
+ if (!this.conditions) throw new OnyxError("firstOrNull() requires a where() clause.");
1289
+ this.limitValue = 1;
1290
+ const pg = await this.page();
1291
+ return Array.isArray(pg.records) && pg.records.length > 0 ? pg.records[0] : null;
1292
+ }
1293
+ async one() {
1294
+ return this.firstOrNull();
1295
+ }
1296
+ async delete() {
1297
+ if (this.mode !== "select") throw new Error("delete() is only applicable in select mode.");
1298
+ const table = this.ensureTable();
1299
+ return this.db._deleteByQuery(table, this.toSelectQuery(), this.partitionValue);
1300
+ }
1301
+ async update() {
1302
+ if (this.mode !== "update") throw new Error("Call setUpdates(...) before update().");
1303
+ const table = this.ensureTable();
1304
+ const update = {
1305
+ type: "UpdateQuery",
1306
+ conditions: this.conditions,
1307
+ updates: this.updates ?? {},
1308
+ sort: this.sort,
1309
+ limit: this.limitValue,
1310
+ partition: this.partitionValue ?? null
1311
+ };
1312
+ return this.db._update(table, update, this.partitionValue);
1313
+ }
1314
+ onItemAdded(listener) {
1315
+ this.onItemAddedListener = listener;
1316
+ return this;
1317
+ }
1318
+ onItemUpdated(listener) {
1319
+ this.onItemUpdatedListener = listener;
1320
+ return this;
1321
+ }
1322
+ onItemDeleted(listener) {
1323
+ this.onItemDeletedListener = listener;
1324
+ return this;
1325
+ }
1326
+ onItem(listener) {
1327
+ this.onItemListener = listener;
1328
+ return this;
1329
+ }
1330
+ async streamEventsOnly(keepAlive = true) {
1331
+ return this.stream(false, keepAlive);
1332
+ }
1333
+ async streamWithQueryResults(keepAlive = false) {
1334
+ return this.stream(true, keepAlive);
1335
+ }
1336
+ async stream(includeQueryResults = true, keepAlive = false) {
1337
+ if (this.mode !== "select") throw new Error("Streaming is only applicable in select mode.");
1338
+ const table = this.ensureTable();
1339
+ return this.db._stream(table, this.toSelectQuery(), includeQueryResults, keepAlive, {
1340
+ onItemAdded: this.onItemAddedListener ?? void 0,
1341
+ onItemUpdated: this.onItemUpdatedListener ?? void 0,
1342
+ onItemDeleted: this.onItemDeletedListener ?? void 0,
1343
+ onItem: this.onItemListener ?? void 0
1344
+ });
1345
+ }
1346
+ };
1347
+ var SaveBuilderImpl = class {
1348
+ db;
1349
+ table;
1350
+ relationships = null;
1351
+ constructor(db, table) {
1352
+ this.db = db;
1353
+ this.table = table;
1354
+ }
1355
+ cascade(...relationships) {
1356
+ this.relationships = relationships.flat();
1357
+ return this;
1358
+ }
1359
+ one(entity) {
1360
+ const opts = this.relationships ? { relationships: this.relationships } : void 0;
1361
+ return this.db._saveInternal(this.table, entity, opts);
1362
+ }
1363
+ many(entities) {
1364
+ const opts = this.relationships ? { relationships: this.relationships } : void 0;
1365
+ return this.db._saveInternal(this.table, entities, opts);
1366
+ }
1367
+ };
1368
+ var CascadeBuilderImpl = class {
1369
+ db;
1370
+ rels = null;
1371
+ constructor(db) {
1372
+ this.db = db;
1373
+ }
1374
+ cascade(...relationships) {
1375
+ this.rels = relationships.flat();
1376
+ return this;
1377
+ }
1378
+ save(table, entityOrEntities) {
1379
+ const opts = this.rels ? { relationships: this.rels } : void 0;
1380
+ return this.db._saveInternal(String(table), entityOrEntities, opts);
1381
+ }
1382
+ delete(table, primaryKey) {
1383
+ const opts = this.rels ? { relationships: this.rels } : void 0;
1384
+ return this.db.delete(table, primaryKey, opts);
1385
+ }
1386
+ };
1387
+ var onyx = {
1388
+ init(config) {
1389
+ return new OnyxDatabaseImpl(config);
1390
+ },
1391
+ clearCacheConfig
1392
+ };
1393
+
1394
+ // src/helpers/sort.ts
1395
+ var asc = (field) => ({ field, order: "ASC" });
1396
+ var desc = (field) => ({ field, order: "DESC" });
1397
+
1398
+ // src/builders/condition-builder.ts
1399
+ var ConditionBuilderImpl = class {
1400
+ condition;
1401
+ /**
1402
+ * Initialize with an optional starting criteria.
1403
+ *
1404
+ * @param criteria Initial query criteria to seed the builder.
1405
+ * @example
1406
+ * ```ts
1407
+ * const builder = new ConditionBuilderImpl({ field: 'id', operator: 'eq', value: '1' });
1408
+ * ```
1409
+ */
1410
+ constructor(criteria = null) {
1411
+ this.condition = criteria ? this.single(criteria) : null;
1412
+ }
1413
+ /**
1414
+ * Add a criteria combined with AND.
1415
+ *
1416
+ * @param condition Another builder or raw criteria to AND.
1417
+ * @example
1418
+ * ```ts
1419
+ * builder.and({ field: 'name', operator: 'eq', value: 'Ada' });
1420
+ * ```
1421
+ */
1422
+ and(condition) {
1423
+ this.addCompound("AND", this.prepare(condition));
1424
+ return this;
1425
+ }
1426
+ /**
1427
+ * Add a criteria combined with OR.
1428
+ *
1429
+ * @param condition Another builder or raw criteria to OR.
1430
+ * @example
1431
+ * ```ts
1432
+ * builder.or({ field: 'status', operator: 'eq', value: 'active' });
1433
+ * ```
1434
+ */
1435
+ or(condition) {
1436
+ this.addCompound("OR", this.prepare(condition));
1437
+ return this;
1438
+ }
1439
+ /**
1440
+ * Produce the composed QueryCondition.
1441
+ *
1442
+ * @example
1443
+ * ```ts
1444
+ * const condition = builder.toCondition();
1445
+ * ```
1446
+ */
1447
+ toCondition() {
1448
+ if (!this.condition) {
1449
+ throw new Error("ConditionBuilder has no criteria.");
1450
+ }
1451
+ return this.condition;
1452
+ }
1453
+ /**
1454
+ * Wrap raw criteria into a single condition object.
1455
+ *
1456
+ * @param criteria Criteria to wrap.
1457
+ * @example
1458
+ * ```ts
1459
+ * builder['single']({ field: 'id', operator: 'eq', value: '1' });
1460
+ * ```
1461
+ */
1462
+ single(criteria) {
1463
+ return { conditionType: "SingleCondition", criteria };
1464
+ }
1465
+ /**
1466
+ * Create a compound condition using the provided operator.
1467
+ *
1468
+ * @param operator Logical operator to apply.
1469
+ * @param conditions Child conditions to combine.
1470
+ * @example
1471
+ * ```ts
1472
+ * builder['compound']('AND', [condA, condB]);
1473
+ * ```
1474
+ */
1475
+ compound(operator, conditions) {
1476
+ return { conditionType: "CompoundCondition", operator, conditions };
1477
+ }
1478
+ /**
1479
+ * Merge the next condition into the existing tree using the operator.
1480
+ *
1481
+ * @param operator Logical operator for the merge.
1482
+ * @param next Condition to merge into the tree.
1483
+ * @example
1484
+ * ```ts
1485
+ * builder['addCompound']('AND', someCondition);
1486
+ * ```
1487
+ */
1488
+ addCompound(operator, next) {
1489
+ if (!this.condition) {
1490
+ this.condition = next;
1491
+ return;
1492
+ }
1493
+ if (this.condition.conditionType === "CompoundCondition" && this.condition.operator === operator) {
1494
+ this.condition.conditions.push(next);
1495
+ return;
1496
+ }
1497
+ this.condition = this.compound(operator, [this.condition, next]);
1498
+ }
1499
+ /**
1500
+ * Normalize input into a QueryCondition instance.
1501
+ *
1502
+ * @param condition Builder or raw criteria to normalize.
1503
+ * @example
1504
+ * ```ts
1505
+ * const qc = builder['prepare']({ field: 'id', operator: 'eq', value: '1' });
1506
+ * ```
1507
+ */
1508
+ prepare(condition) {
1509
+ if (typeof condition.toCondition === "function") {
1510
+ return condition.toCondition();
1511
+ }
1512
+ const c2 = condition;
1513
+ if (c2 && typeof c2.field === "string" && typeof c2.operator === "string") {
1514
+ return this.single(c2);
1515
+ }
1516
+ throw new Error("Invalid condition");
1517
+ }
1518
+ };
1519
+
1520
+ // src/helpers/conditions.ts
1521
+ var c = (field, operator, value) => new ConditionBuilderImpl({ field, operator, value });
1522
+ var eq = (field, value) => c(field, "EQUAL", value);
1523
+ var neq = (field, value) => c(field, "NOT_EQUAL", value);
1524
+ var inOp = (field, values) => c(
1525
+ field,
1526
+ "IN",
1527
+ typeof values === "string" ? values.split(",").map((v) => v.trim()).filter((v) => v.length) : values
1528
+ );
1529
+ var notIn = (field, values) => c(field, "NOT_IN", values);
1530
+ var between = (field, lower2, upper2) => c(field, "BETWEEN", [lower2, upper2]);
1531
+ var gt = (field, value) => c(field, "GREATER_THAN", value);
1532
+ var gte = (field, value) => c(field, "GREATER_THAN_EQUAL", value);
1533
+ var lt = (field, value) => c(field, "LESS_THAN", value);
1534
+ var lte = (field, value) => c(field, "LESS_THAN_EQUAL", value);
1535
+ var matches = (field, regex) => c(field, "MATCHES", regex);
1536
+ var notMatches = (field, regex) => c(field, "NOT_MATCHES", regex);
1537
+ var like = (field, pattern) => c(field, "LIKE", pattern);
1538
+ var notLike = (field, pattern) => c(field, "NOT_LIKE", pattern);
1539
+ var contains = (field, value) => c(field, "CONTAINS", value);
1540
+ var containsIgnoreCase = (field, value) => c(field, "CONTAINS_IGNORE_CASE", value);
1541
+ var notContains = (field, value) => c(field, "NOT_CONTAINS", value);
1542
+ var notContainsIgnoreCase = (field, value) => c(field, "NOT_CONTAINS_IGNORE_CASE", value);
1543
+ var startsWith = (field, prefix) => c(field, "STARTS_WITH", prefix);
1544
+ var notStartsWith = (field, prefix) => c(field, "NOT_STARTS_WITH", prefix);
1545
+ var isNull = (field) => c(field, "IS_NULL");
1546
+ var notNull = (field) => c(field, "NOT_NULL");
1547
+
1548
+ // src/helpers/aggregates.ts
1549
+ var avg = (attribute) => `avg(${attribute})`;
1550
+ var sum = (attribute) => `sum(${attribute})`;
1551
+ var count = (attribute) => `count(${attribute})`;
1552
+ var min = (attribute) => `min(${attribute})`;
1553
+ var max = (attribute) => `max(${attribute})`;
1554
+ var std = (attribute) => `std(${attribute})`;
1555
+ var variance = (attribute) => `variance(${attribute})`;
1556
+ var median = (attribute) => `median(${attribute})`;
1557
+ var upper = (attribute) => `upper(${attribute})`;
1558
+ var lower = (attribute) => `lower(${attribute})`;
1559
+ var substring = (attribute, from, length) => `substring(${attribute},${from},${length})`;
1560
+ var replace = (attribute, pattern, repl) => `replace(${attribute}, '${pattern.replace(/'/g, "\\'")}', '${repl.replace(/'/g, "\\'")}')`;
1561
+ var percentile = (attribute, p) => `percentile(${attribute}, ${p})`;
1562
+
1563
+ // src/index.ts
1564
+ var sdkName = "@onyx.dev/onyx-database";
1565
+ var sdkVersion = "0.1.0";
1566
+
1567
+ export { QueryResults, asc, avg, between, contains, containsIgnoreCase, count, desc, eq, gt, gte, inOp, isNull, like, lower, lt, lte, matches, max, median, min, neq, notContains, notContainsIgnoreCase, notIn, notLike, notMatches, notNull, notStartsWith, onyx, percentile, replace, sdkName, sdkVersion, startsWith, std, substring, sum, upper, variance };
1568
+ //# sourceMappingURL=index.js.map
1569
+ //# sourceMappingURL=index.js.map