@onyx.dev/onyx-database 1.0.3 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,8 +18,10 @@ TypeScript client SDK for **Onyx Cloud Database** — a zero-dependency, strict-
18
18
  - [Getting started](#getting-started-cloud--keys--connect)
19
19
  - [Install](#install)
20
20
  - [Initialize the client](#initialize-the-client)
21
+ - [Onyx AI (chat & models)](#onyx-ai-chat--models)
21
22
  - [Generate schema types](#optional-generate-typescript-types-from-your-schema)
22
23
  - [Query helpers](#query-helpers-at-a-glance)
24
+ - [Full-text search](#full-text-search-lucene)
23
25
  - [Examples](#usage-examples-with-user-role-permission)
24
26
  - [Error handling](#error-handling)
25
27
  - [HTTP retries](#http-retries)
@@ -91,6 +93,7 @@ Set the following environment variables for your database:
91
93
  - `ONYX_DATABASE_BASE_URL`
92
94
  - `ONYX_DATABASE_API_KEY`
93
95
  - `ONYX_DATABASE_API_SECRET`
96
+ - `ONYX_AI_BASE_URL` (optional; defaults to `https://ai.onyx.dev`)
94
97
 
95
98
  ```ts
96
99
  import { onyx } from '@onyx.dev/onyx-database';
@@ -106,6 +109,7 @@ import { onyx } from '@onyx.dev/onyx-database';
106
109
 
107
110
  const db = onyx.init({
108
111
  baseUrl: 'https://api.onyx.dev',
112
+ aiBaseUrl: 'https://ai.onyx.dev', // optional: override AI base path
109
113
  databaseId: 'YOUR_DATABASE_ID',
110
114
  apiKey: 'YOUR_KEY',
111
115
  apiSecret: 'YOUR_SECRET',
@@ -178,6 +182,105 @@ necessary unless you create many short‑lived clients.
178
182
 
179
183
  ---
180
184
 
185
+ ## Onyx AI (chat & models)
186
+
187
+ AI endpoints are OpenAI-compatible and use the same credentials as database calls. The AI base URL defaults to `https://ai.onyx.dev` and can be overridden with `aiBaseUrl` (or `ONYX_AI_BASE_URL`). The `databaseId` query param is optional; when omitted, the configured databaseId is used for grounding and billing.
188
+
189
+ ### Chat completions
190
+
191
+ Examples: `examples/ai/chat.ts`, `examples/ai/chat-stream.ts`.
192
+
193
+ ```ts
194
+ import { onyx } from '@onyx.dev/onyx-database';
195
+
196
+ const db = onyx.init();
197
+
198
+ const completion = await db.chat().create({
199
+ model: 'onyx-chat',
200
+ messages: [{ role: 'user', content: 'Summarize last week’s traffic.' }],
201
+ });
202
+ console.log(completion.choices[0]?.message?.content);
203
+ ```
204
+
205
+ Streaming works as an async iterable:
206
+
207
+ ```ts
208
+ const stream = await db.chat().create({
209
+ model: 'onyx-chat',
210
+ stream: true,
211
+ messages: [{ role: 'user', content: 'Write a short onboarding checklist.' }],
212
+ });
213
+
214
+ for await (const chunk of stream) {
215
+ process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
216
+ }
217
+ // stream.cancel() is available if you need to stop early
218
+ ```
219
+
220
+ Tool calls mirror the ChatGPT TypeScript client:
221
+
222
+ ```ts
223
+ const prompt = {
224
+ model: 'onyx-chat',
225
+ messages: [{ role: 'user', content: 'Find revenue for ACME in 2023.' }],
226
+ tools: [
227
+ {
228
+ type: 'function',
229
+ function: {
230
+ name: 'get_revenue',
231
+ description: 'Fetch revenue for a company and year',
232
+ parameters: {
233
+ type: 'object',
234
+ properties: {
235
+ company: { type: 'string' },
236
+ year: { type: 'number' },
237
+ },
238
+ required: ['company', 'year'],
239
+ },
240
+ },
241
+ },
242
+ ],
243
+ };
244
+
245
+ const first = await db.chat().create(prompt);
246
+ const toolCall = first.choices[0]?.message?.tool_calls?.[0];
247
+
248
+ if (toolCall) {
249
+ const toolResult = await getRevenue(JSON.parse(toolCall.function.arguments)); // your impl
250
+ const followup = await db.chat().create({
251
+ model: prompt.model,
252
+ messages: [
253
+ ...prompt.messages,
254
+ first.choices[0].message,
255
+ { role: 'tool', tool_call_id: toolCall.id ?? '', content: JSON.stringify(toolResult) },
256
+ ],
257
+ });
258
+ console.log(followup.choices[0]?.message?.content);
259
+ }
260
+ ```
261
+
262
+ ### Model metadata
263
+
264
+ Example: `examples/ai/models.ts`.
265
+
266
+ ```ts
267
+ const models = await db.getModels();
268
+ const chatModel = await db.getModel('onyx-chat');
269
+ ```
270
+
271
+ ### Script mutation approvals
272
+
273
+ ```ts
274
+ const approval = await db.requestScriptApproval({
275
+ script: "db.save({ id: 'u1', email: 'a@b.com' })",
276
+ });
277
+ if (approval.requiresApproval) {
278
+ console.log(`Requires approval until ${approval.expiresAtIso}`);
279
+ }
280
+ ```
281
+
282
+ ---
283
+
181
284
  ## Optional: generate TypeScript types from your schema
182
285
 
183
286
  The package ships a small codegen CLI that emits per-table interfaces, a `tables` enum, and a `Schema` mapping for compile-time safety and IntelliSense. Each generated interface also includes an index signature so extra properties (for graph attachments in cascade saves) don't trigger type errors.
@@ -410,7 +513,7 @@ import {
410
513
  between,
411
514
  gt, gte, lt, lte,
412
515
  like, notLike, contains, notContains,
413
- startsWith, notStartsWith, matches, notMatches,
516
+ startsWith, notStartsWith, matches, notMatches, search,
414
517
  isNull, notNull,
415
518
  asc, desc
416
519
  } from '@onyx.dev/onyx-database';
@@ -418,6 +521,7 @@ import {
418
521
 
419
522
  - Prefer `within`/`notWithin` for inclusion checks (supports arrays, comma-separated strings, or inner queries).
420
523
  - `inOp`/`notIn` remain available for backward compatibility and are exact aliases.
524
+ - `search(text, minScore?)` builds a Lucene `MATCHES` predicate on `__full_text__` and always serializes `minScore` (null when omitted).
421
525
 
422
526
  ### Inner queries (IN/NOT IN with sub-selects)
423
527
 
@@ -453,6 +557,42 @@ const rolesMissingPermission = await db
453
557
 
454
558
  ---
455
559
 
560
+ ## Full-text search (Lucene)
561
+
562
+ Use `.search(text, minScore?)` on a query builder for table-level full-text search, or call `db.search(...)` to target **all** tables (`table = "ALL"` in the request body). The search value always includes `minScore` and falls back to `null` when you omit it.
563
+
564
+ ```ts
565
+ import { desc, eq, onyx, search, tables, type Schema } from '@onyx.dev/onyx-database';
566
+
567
+ const db = onyx.init<Schema>();
568
+
569
+ // Table-specific search with a minimum score
570
+ const recentUsers = await db
571
+ .from(tables.User)
572
+ .search('user bio text', 4.4)
573
+ .orderBy(desc('createdAt'))
574
+ .limit(5)
575
+ .list();
576
+
577
+ // Search across all tables (table: "ALL")
578
+ const acrossTables = await db.search('user bio text').list({ pageSize: 5 });
579
+
580
+ // Combine a search predicate with other filters
581
+ const activeMatch = await db
582
+ .from(tables.User)
583
+ .where(search('user bio text'))
584
+ .and(eq('isActive', true))
585
+ .firstOrNull();
586
+ ```
587
+
588
+ **Examples**
589
+ - Table search (minScore null): `examples/query/lucine-table-search.ts`
590
+ - Table search (minScore 4.4): `examples/query/lucine-table-search-min-score.ts`
591
+ - ALL tables search (minScore null): `examples/query/lucine-search-all-tables.ts`
592
+ - ALL tables search (minScore 4.4): `examples/query/lucine-search-all-tables-min-score.ts`
593
+
594
+ ---
595
+
456
596
  ## Usage examples with `User`, `Role`, `Permission`
457
597
 
458
598
  > The examples assume your schema has tables named `User`, `Role`, and `Permission`.
@@ -7,6 +7,11 @@
7
7
  * ```
8
8
  */
9
9
  type QueryCriteriaOperator = 'EQUAL' | 'NOT_EQUAL' | 'IN' | 'NOT_IN' | 'GREATER_THAN' | 'GREATER_THAN_EQUAL' | 'LESS_THAN' | 'LESS_THAN_EQUAL' | 'MATCHES' | 'NOT_MATCHES' | 'BETWEEN' | 'LIKE' | 'NOT_LIKE' | 'CONTAINS' | 'CONTAINS_IGNORE_CASE' | 'NOT_CONTAINS' | 'NOT_CONTAINS_IGNORE_CASE' | 'STARTS_WITH' | 'NOT_STARTS_WITH' | 'IS_NULL' | 'NOT_NULL';
10
+ /** Value payload for full-text (Lucene) searches. */
11
+ interface FullTextQuery {
12
+ queryText: string;
13
+ minScore: number | null;
14
+ }
10
15
  /** Logical operator used to join conditions in a query. */
11
16
  type LogicalOperator = 'AND' | 'OR';
12
17
  /**
@@ -133,6 +138,7 @@ type QueryCondition = {
133
138
  */
134
139
  interface SelectQuery {
135
140
  type: 'SelectQuery';
141
+ table?: string | null;
136
142
  fields?: string[] | null;
137
143
  conditions?: QueryCondition | null;
138
144
  sort?: Sort[] | null;
@@ -473,6 +479,16 @@ interface IQueryBuilder<T = unknown> {
473
479
  * ```
474
480
  */
475
481
  resolve(...values: Array<string | string[]>): IQueryBuilder<T>;
482
+ /**
483
+ * Adds a Lucene full-text search predicate.
484
+ * @example
485
+ * ```ts
486
+ * const results = await db.from('User').search('hello world', 4.4).list();
487
+ * ```
488
+ * @param queryText - Text to match against `__full_text__`.
489
+ * @param minScore - Optional minimum score; serializes as `null` when omitted.
490
+ */
491
+ search(queryText: string, minScore?: number | null): IQueryBuilder<T>;
476
492
  /**
477
493
  * Adds a filter condition.
478
494
  * @example
@@ -798,6 +814,10 @@ interface RetryOptions {
798
814
  }
799
815
  interface OnyxConfig {
800
816
  baseUrl?: string;
817
+ /**
818
+ * Base URL for AI endpoints. Defaults to https://ai.onyx.dev.
819
+ */
820
+ aiBaseUrl?: string;
801
821
  databaseId?: string;
802
822
  apiKey?: string;
803
823
  apiSecret?: string;
@@ -824,7 +844,187 @@ interface OnyxConfig {
824
844
  */
825
845
  retry?: RetryOptions;
826
846
  }
847
+ interface AiRequestOptions {
848
+ /**
849
+ * Optional database scope for AI calls. Defaults to the configured databaseId.
850
+ */
851
+ databaseId?: string;
852
+ }
853
+ type AiChatRole = 'system' | 'user' | 'assistant' | 'tool';
854
+ interface AiToolCallFunction {
855
+ name: string;
856
+ arguments: string;
857
+ }
858
+ interface AiToolCall {
859
+ id?: string | null;
860
+ type?: string | null;
861
+ function: AiToolCallFunction;
862
+ }
863
+ interface AiChatMessage {
864
+ role: AiChatRole;
865
+ content?: string | null;
866
+ tool_calls?: AiToolCall[] | null;
867
+ tool_call_id?: string | null;
868
+ name?: string | null;
869
+ }
870
+ interface AiToolFunction {
871
+ name: string;
872
+ description?: string | null;
873
+ parameters?: Record<string, unknown> | null;
874
+ }
875
+ interface AiTool {
876
+ type: string;
877
+ function: AiToolFunction;
878
+ }
879
+ type AiToolChoice = 'none' | 'auto' | {
880
+ type: 'function';
881
+ function: {
882
+ name: string;
883
+ };
884
+ } | null;
885
+ interface AiChatCompletionRequest {
886
+ model: string;
887
+ messages: AiChatMessage[];
888
+ stream?: boolean;
889
+ temperature?: number | null;
890
+ top_p?: number | null;
891
+ max_tokens?: number | null;
892
+ metadata?: Record<string, unknown>;
893
+ tools?: AiTool[];
894
+ tool_choice?: AiToolChoice;
895
+ user?: string | null;
896
+ }
897
+ interface AiChatCompletionUsage {
898
+ prompt_tokens?: number | null;
899
+ completion_tokens?: number | null;
900
+ total_tokens?: number | null;
901
+ }
902
+ interface AiChatCompletionChoice {
903
+ index: number;
904
+ message: AiChatMessage;
905
+ finish_reason?: string | null;
906
+ }
907
+ interface AiChatCompletionResponse {
908
+ id: string;
909
+ object: string;
910
+ created: number;
911
+ model: string;
912
+ choices: AiChatCompletionChoice[];
913
+ usage?: AiChatCompletionUsage;
914
+ }
915
+ interface AiChatCompletionChunkDelta {
916
+ role?: AiChatRole | null;
917
+ content?: string | null;
918
+ tool_calls?: AiToolCall[] | null;
919
+ tool_call_id?: string | null;
920
+ name?: string | null;
921
+ }
922
+ interface AiChatCompletionChunkChoice {
923
+ index: number;
924
+ delta: AiChatCompletionChunkDelta;
925
+ finish_reason?: string | null;
926
+ }
927
+ interface AiChatCompletionChunk {
928
+ id: string;
929
+ object: string;
930
+ created: number;
931
+ model?: string | null;
932
+ choices: AiChatCompletionChunkChoice[];
933
+ }
934
+ interface AiChatCompletionStream extends AsyncIterable<AiChatCompletionChunk> {
935
+ cancel(): void;
936
+ }
937
+ interface AiChatClient {
938
+ create(request: AiChatCompletionRequest & {
939
+ stream?: false;
940
+ }, options?: AiRequestOptions): Promise<AiChatCompletionResponse>;
941
+ create(request: AiChatCompletionRequest & {
942
+ stream: true;
943
+ }, options?: AiRequestOptions): Promise<AiChatCompletionStream>;
944
+ create(request: AiChatCompletionRequest, options?: AiRequestOptions): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
945
+ }
946
+ interface AiScriptApprovalRequest {
947
+ script: string;
948
+ }
949
+ interface AiScriptApprovalResponse {
950
+ normalizedScript: string;
951
+ expiresAtIso: string;
952
+ requiresApproval: boolean;
953
+ findings?: string;
954
+ }
955
+ interface AiModelsResponse {
956
+ object: string;
957
+ data: AiModel[];
958
+ }
959
+ interface AiModel {
960
+ id: string;
961
+ object: string;
962
+ created: number;
963
+ owned_by: string;
964
+ }
965
+ interface AiErrorResponse {
966
+ error?: string | {
967
+ message?: string;
968
+ [key: string]: unknown;
969
+ } | null;
970
+ }
827
971
  interface IOnyxDatabase<Schema = Record<string, unknown>> {
972
+ /**
973
+ * Access OpenAI-compatible chat completions.
974
+ *
975
+ * @example
976
+ * ```ts
977
+ * const chat = db.chat();
978
+ * const completion = await chat.create({
979
+ * model: 'onyx-chat',
980
+ * messages: [{ role: 'user', content: 'Summarize last week.' }],
981
+ * });
982
+ * ```
983
+ *
984
+ * @example
985
+ * ```ts
986
+ * const stream = await db
987
+ * .chat()
988
+ * .create({
989
+ * model: 'onyx-chat',
990
+ * stream: true,
991
+ * messages: [{ role: 'user', content: 'Draft an onboarding checklist.' }],
992
+ * });
993
+ * for await (const chunk of stream) {
994
+ * process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
995
+ * }
996
+ * ```
997
+ */
998
+ chat(): AiChatClient;
999
+ /**
1000
+ * List available AI models.
1001
+ *
1002
+ * @example
1003
+ * ```ts
1004
+ * const models = await db.getModels();
1005
+ * ```
1006
+ */
1007
+ getModels(): Promise<AiModelsResponse>;
1008
+ /**
1009
+ * Retrieve a single AI model by ID.
1010
+ *
1011
+ * @example
1012
+ * ```ts
1013
+ * const model = await db.getModel('onyx-chat');
1014
+ * ```
1015
+ */
1016
+ getModel(modelId: string): Promise<AiModel>;
1017
+ /**
1018
+ * Request mutation approval for a script.
1019
+ *
1020
+ * @example
1021
+ * ```ts
1022
+ * const approval = await db.requestScriptApproval({
1023
+ * script: "db.save({ id: 'u1', email: 'a@b.com' })"
1024
+ * });
1025
+ * ```
1026
+ */
1027
+ requestScriptApproval(input: AiScriptApprovalRequest): Promise<AiScriptApprovalResponse>;
828
1028
  /**
829
1029
  * Begin a query against a table.
830
1030
  *
@@ -861,6 +1061,18 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
861
1061
  * @param fields Field names to project; omit to select all.
862
1062
  */
863
1063
  select(...fields: string[]): IQueryBuilder<Record<string, unknown>>;
1064
+ /**
1065
+ * Run a Lucene full-text search across all tables.
1066
+ *
1067
+ * @example
1068
+ * ```ts
1069
+ * const results = await db.search('hello world', 4.4).list();
1070
+ * ```
1071
+ *
1072
+ * @param queryText Text to match against `__full_text__`.
1073
+ * @param minScore Optional minimum score; serialized as `null` when omitted.
1074
+ */
1075
+ search(queryText: string, minScore?: number | null): IQueryBuilder<Record<string, unknown>>;
864
1076
  /**
865
1077
  * Include related records in the next save or delete.
866
1078
  *
@@ -1395,6 +1607,7 @@ declare const gte: (field: string, value: unknown) => ConditionBuilderImpl;
1395
1607
  declare const lt: (field: string, value: unknown) => ConditionBuilderImpl;
1396
1608
  declare const lte: (field: string, value: unknown) => ConditionBuilderImpl;
1397
1609
  declare const matches: (field: string, regex: string) => ConditionBuilderImpl;
1610
+ declare const search: (queryText: string, minScore?: number | null) => ConditionBuilderImpl;
1398
1611
  declare const notMatches: (field: string, regex: string) => ConditionBuilderImpl;
1399
1612
  declare const like: (field: string, pattern: string) => ConditionBuilderImpl;
1400
1613
  declare const notLike: (field: string, pattern: string) => ConditionBuilderImpl;
@@ -1421,4 +1634,4 @@ declare const substring: (attribute: string, from: number, length: number) => st
1421
1634
  declare const replace: (attribute: string, pattern: string, repl: string) => string;
1422
1635
  declare const percentile: (attribute: string, p: number) => string;
1423
1636
 
1424
- export { within as $, type QueryCriteriaOperator as A, type Sort as B, type StreamAction as C, type OnyxDocument as D, type FetchImpl as E, type FetchResponse as F, type QueryCriteria as G, type QueryCondition as H, type IOnyxDatabase as I, type SelectQuery as J, type QueryPage as K, type LogicalOperator as L, type IConditionBuilder as M, type IQueryBuilder as N, type OnyxFacade as O, type ISaveBuilder as P, QueryResults as Q, type RetryOptions as R, type SecretMetadata as S, type ICascadeBuilder as T, type UpdateQuery as U, type ICascadeRelationshipBuilder as V, asc as W, desc as X, eq as Y, neq as Z, inOp as _, type QueryResultsPromise as a, notIn as a0, notWithin as a1, between as a2, gt as a3, gte as a4, lt as a5, lte as a6, matches as a7, notMatches as a8, like as a9, notLike as aa, contains as ab, containsIgnoreCase as ac, notContains as ad, notContainsIgnoreCase as ae, startsWith as af, notStartsWith as ag, isNull as ah, notNull as ai, avg as aj, sum as ak, count as al, min as am, max as an, std as ao, variance as ap, median as aq, upper as ar, lower as as, substring as at, replace as au, percentile as av, type OnyxConfig as b, type SecretRecord as c, type SecretsListResponse as d, type SecretSaveRequest as e, type SchemaDataType as f, type SchemaIdentifierGenerator as g, type SchemaIdentifier as h, type SchemaAttribute as i, type SchemaIndexType as j, type SchemaIndex as k, type SchemaResolver as l, type SchemaTriggerEvent as m, type SchemaTrigger as n, type SchemaEntity as o, type SchemaRevisionMetadata as p, type SchemaRevision as q, type SchemaHistoryEntry as r, type SchemaUpsertRequest as s, type SchemaValidationResult as t, type SchemaAttributeChange as u, type SchemaIndexChange as v, type SchemaResolverChange as w, type SchemaTriggerChange as x, type SchemaTableDiff as y, type SchemaDiff as z };
1637
+ export { type SchemaDiff as $, type AiRequestOptions as A, type SchemaDataType as B, type SchemaIdentifierGenerator as C, type SchemaIdentifier as D, type SchemaAttribute as E, type FullTextQuery as F, type SchemaIndexType as G, type SchemaIndex as H, type IOnyxDatabase as I, type SchemaResolver as J, type SchemaTriggerEvent as K, type SchemaTrigger as L, type SchemaEntity as M, type SchemaRevisionMetadata as N, type OnyxFacade as O, type SchemaRevision as P, QueryResults as Q, type RetryOptions as R, type SecretMetadata as S, type SchemaHistoryEntry as T, type SchemaUpsertRequest as U, type SchemaValidationResult as V, type SchemaAttributeChange as W, type SchemaIndexChange as X, type SchemaResolverChange as Y, type SchemaTriggerChange as Z, type SchemaTableDiff as _, type QueryResultsPromise as a, type QueryCriteriaOperator as a0, type LogicalOperator as a1, type Sort as a2, type StreamAction as a3, type OnyxDocument as a4, type FetchResponse as a5, type FetchImpl as a6, type QueryCriteria as a7, type QueryCondition as a8, type SelectQuery as a9, containsIgnoreCase as aA, notContains as aB, notContainsIgnoreCase as aC, startsWith as aD, notStartsWith as aE, isNull as aF, notNull as aG, avg as aH, sum as aI, count as aJ, min as aK, max as aL, std as aM, variance as aN, median as aO, upper as aP, lower as aQ, substring as aR, replace as aS, percentile as aT, type UpdateQuery as aa, type QueryPage as ab, type IConditionBuilder as ac, type IQueryBuilder as ad, type ISaveBuilder as ae, type ICascadeBuilder as af, type ICascadeRelationshipBuilder as ag, asc as ah, desc as ai, eq as aj, neq as ak, inOp as al, within as am, notIn as an, notWithin as ao, between as ap, gt as aq, gte as ar, lt as as, lte as at, matches as au, search as av, notMatches as aw, like as ax, notLike as ay, contains as az, type OnyxConfig as b, type AiChatRole as c, type AiToolCallFunction as d, type AiToolCall as e, type AiChatMessage as f, type AiToolFunction as g, type AiTool as h, type AiToolChoice as i, type AiChatCompletionRequest as j, type AiChatCompletionUsage as k, type AiChatCompletionChoice as l, type AiChatCompletionResponse as m, type AiChatCompletionChunkDelta as n, type AiChatCompletionChunkChoice as o, type AiChatCompletionChunk as p, type AiChatCompletionStream as q, type AiChatClient as r, type AiScriptApprovalRequest as s, type AiScriptApprovalResponse as t, type AiModelsResponse as u, type AiModel as v, type AiErrorResponse as w, type SecretRecord as x, type SecretsListResponse as y, type SecretSaveRequest as z };