@onyx.dev/onyx-database 1.2.0 → 2.0.1

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.
@@ -1,3 +1,6 @@
1
+ var name = "@onyx.dev/onyx-database";
2
+ var version = "2.0.1";
3
+
1
4
  /**
2
5
  * Supported operators for building query criteria.
3
6
  *
@@ -822,6 +825,10 @@ interface OnyxConfig {
822
825
  apiKey?: string;
823
826
  apiSecret?: string;
824
827
  fetch?: FetchImpl;
828
+ /**
829
+ * Default AI model when using shorthand chat calls (`db.chat('...')`). Defaults to `onyx`.
830
+ */
831
+ defaultModel?: string;
825
832
  /**
826
833
  * Default partition for queries, `findById`, and deletes when removing by
827
834
  * primary key. Saves rely on the entity's partition field instead.
@@ -934,6 +941,28 @@ interface AiChatCompletionChunk {
934
941
  interface AiChatCompletionStream extends AsyncIterable<AiChatCompletionChunk> {
935
942
  cancel(): void;
936
943
  }
944
+ interface AiChatOptions extends AiRequestOptions {
945
+ /**
946
+ * Model to use for the shorthand `db.chat()` call. Defaults to config.defaultModel or `onyx`.
947
+ */
948
+ model?: string;
949
+ /**
950
+ * Role for the constructed message. Defaults to `user`.
951
+ */
952
+ role?: AiChatRole;
953
+ /**
954
+ * Temperature for the completion. Omit to use the service default.
955
+ */
956
+ temperature?: number | null;
957
+ /**
958
+ * Enable SSE streaming. Defaults to `false`.
959
+ */
960
+ stream?: boolean;
961
+ /**
962
+ * When true, return the raw completion response instead of the first message content.
963
+ */
964
+ raw?: boolean;
965
+ }
937
966
  interface AiChatClient {
938
967
  create(request: AiChatCompletionRequest & {
939
968
  stream?: false;
@@ -968,9 +997,90 @@ interface AiErrorResponse {
968
997
  [key: string]: unknown;
969
998
  } | null;
970
999
  }
1000
+ interface AiClient {
1001
+ /**
1002
+ * Run a chat completion. Accepts shorthand strings or full requests.
1003
+ *
1004
+ * @example
1005
+ * ```ts
1006
+ * const quick = await db.ai.chat('Summarize last week.'); // returns first message content
1007
+ * const completion = await db.ai.chat(
1008
+ * { model: 'onyx-chat', messages: [{ role: 'user', content: 'Summarize last week.' }] },
1009
+ * { databaseId: 'db1', raw: true }, // returns full response
1010
+ * );
1011
+ * ```
1012
+ */
1013
+ chat(content: string, options?: AiChatOptions & {
1014
+ stream?: false;
1015
+ raw?: false | undefined;
1016
+ }): Promise<string>;
1017
+ chat(content: string, options: AiChatOptions & {
1018
+ stream: true;
1019
+ }): Promise<AiChatCompletionStream>;
1020
+ chat(content: string, options: AiChatOptions & {
1021
+ raw: true;
1022
+ }): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
1023
+ chat(request: AiChatCompletionRequest & {
1024
+ stream?: false;
1025
+ }, options?: AiRequestOptions): Promise<AiChatCompletionResponse>;
1026
+ chat(request: AiChatCompletionRequest & {
1027
+ stream: true;
1028
+ }, options?: AiRequestOptions): Promise<AiChatCompletionStream>;
1029
+ chat(request: AiChatCompletionRequest, options?: AiRequestOptions): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
1030
+ /**
1031
+ * Access the chat client for more control over streaming and cancellation.
1032
+ */
1033
+ chatClient(): AiChatClient;
1034
+ /**
1035
+ * List available AI models.
1036
+ *
1037
+ * @example
1038
+ * ```ts
1039
+ * const models = await db.ai.getModels();
1040
+ * ```
1041
+ */
1042
+ getModels(): Promise<AiModelsResponse>;
1043
+ /**
1044
+ * Retrieve a single AI model by ID.
1045
+ *
1046
+ * @example
1047
+ * ```ts
1048
+ * const model = await db.ai.getModel('onyx-chat');
1049
+ * ```
1050
+ */
1051
+ getModel(modelId: string): Promise<AiModel>;
1052
+ /**
1053
+ * Request mutation approval for a script.
1054
+ *
1055
+ * @example
1056
+ * ```ts
1057
+ * const approval = await db.ai.requestScriptApproval({
1058
+ * script: "db.save({ id: 'u1', email: 'a@b.com' })"
1059
+ * });
1060
+ * ```
1061
+ */
1062
+ requestScriptApproval(input: AiScriptApprovalRequest): Promise<AiScriptApprovalResponse>;
1063
+ }
971
1064
  interface IOnyxDatabase<Schema = Record<string, unknown>> {
972
1065
  /**
973
- * Access OpenAI-compatible chat completions.
1066
+ * AI helpers (chat, models, script approvals) grouped under `db.ai`.
1067
+ *
1068
+ * @example
1069
+ * ```ts
1070
+ * const completion = await db.ai.chat({
1071
+ * model: 'onyx-chat',
1072
+ * messages: [{ role: 'user', content: 'Summarize last week.' }],
1073
+ * });
1074
+ * ```
1075
+ */
1076
+ ai: AiClient;
1077
+ /**
1078
+ * Access OpenAI-compatible chat completions via `db.chat('...')` or `db.chat().create(...)`.
1079
+ *
1080
+ * @example
1081
+ * ```ts
1082
+ * const completion = await db.chat('Summarize last week.'); // returns first message content
1083
+ * ```
974
1084
  *
975
1085
  * @example
976
1086
  * ```ts
@@ -995,10 +1105,22 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
995
1105
  * }
996
1106
  * ```
997
1107
  */
1108
+ chat(content: string, options?: AiChatOptions & {
1109
+ stream?: false;
1110
+ raw?: false | undefined;
1111
+ }): Promise<string>;
1112
+ chat(content: string, options: AiChatOptions & {
1113
+ stream: true;
1114
+ }): Promise<AiChatCompletionStream>;
1115
+ chat(content: string, options: AiChatOptions & {
1116
+ raw: true;
1117
+ }): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
998
1118
  chat(): AiChatClient;
999
1119
  /**
1000
1120
  * List available AI models.
1001
1121
  *
1122
+ * @deprecated Prefer `db.ai.getModels()`.
1123
+ *
1002
1124
  * @example
1003
1125
  * ```ts
1004
1126
  * const models = await db.getModels();
@@ -1008,6 +1130,8 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
1008
1130
  /**
1009
1131
  * Retrieve a single AI model by ID.
1010
1132
  *
1133
+ * @deprecated Prefer `db.ai.getModel(...)`.
1134
+ *
1011
1135
  * @example
1012
1136
  * ```ts
1013
1137
  * const model = await db.getModel('onyx-chat');
@@ -1017,6 +1141,8 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
1017
1141
  /**
1018
1142
  * Request mutation approval for a script.
1019
1143
  *
1144
+ * @deprecated Prefer `db.ai.requestScriptApproval(...)`.
1145
+ *
1020
1146
  * @example
1021
1147
  * ```ts
1022
1148
  * const approval = await db.requestScriptApproval({
@@ -1632,6 +1758,7 @@ declare const upper: (attribute: string) => string;
1632
1758
  declare const lower: (attribute: string) => string;
1633
1759
  declare const substring: (attribute: string, from: number, length: number) => string;
1634
1760
  declare const replace: (attribute: string, pattern: string, repl: string) => string;
1761
+ declare const format: (attribute: string, formatter: string) => string;
1635
1762
  declare const percentile: (attribute: string, p: number) => string;
1636
1763
 
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 };
1764
+ export { type SchemaIndexChange as $, type AiRequestOptions as A, type AiClient as B, type SecretRecord as C, type SecretsListResponse as D, type SecretSaveRequest as E, type FullTextQuery as F, type SchemaDataType as G, type SchemaIdentifierGenerator as H, type IOnyxDatabase as I, type SchemaIdentifier as J, type SchemaAttribute as K, type SchemaIndexType as L, type SchemaIndex as M, type SchemaResolver as N, type OnyxFacade as O, type SchemaTriggerEvent as P, QueryResults as Q, type RetryOptions as R, type SecretMetadata as S, type SchemaTrigger as T, type SchemaEntity as U, type SchemaRevisionMetadata as V, type SchemaRevision as W, type SchemaHistoryEntry as X, type SchemaUpsertRequest as Y, type SchemaValidationResult as Z, type SchemaAttributeChange as _, type QueryResultsPromise as a, type SchemaResolverChange as a0, type SchemaTriggerChange as a1, type SchemaTableDiff as a2, type SchemaDiff as a3, type QueryCriteriaOperator as a4, type LogicalOperator as a5, type Sort as a6, type StreamAction as a7, type OnyxDocument as a8, type FetchResponse as a9, notMatches as aA, like as aB, notLike as aC, contains as aD, containsIgnoreCase as aE, notContains as aF, notContainsIgnoreCase as aG, startsWith as aH, notStartsWith as aI, isNull as aJ, notNull as aK, avg as aL, sum as aM, count as aN, min as aO, max as aP, std as aQ, variance as aR, median as aS, upper as aT, lower as aU, substring as aV, replace as aW, format as aX, percentile as aY, type FetchImpl as aa, type QueryCriteria as ab, type QueryCondition as ac, type SelectQuery as ad, type UpdateQuery as ae, type QueryPage as af, type IConditionBuilder as ag, type IQueryBuilder as ah, type ISaveBuilder as ai, type ICascadeBuilder as aj, type ICascadeRelationshipBuilder as ak, asc as al, desc as am, eq as an, neq as ao, inOp as ap, within as aq, notIn as ar, notWithin as as, between as at, gt as au, gte as av, lt as aw, lte as ax, matches as ay, search 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, name as n, type AiChatCompletionChunkDelta as o, type AiChatCompletionChunkChoice as p, type AiChatCompletionChunk as q, type AiChatCompletionStream as r, type AiChatOptions as s, type AiChatClient as t, type AiScriptApprovalRequest as u, version as v, type AiScriptApprovalResponse as w, type AiModelsResponse as x, type AiModel as y, type AiErrorResponse as z };
package/dist/edge.cjs CHANGED
@@ -1,8 +1,13 @@
1
1
  'use strict';
2
2
 
3
+ // package.json
4
+ var name = "@onyx.dev/onyx-database";
5
+ var version = "2.0.1";
6
+
3
7
  // src/config/defaults.ts
4
8
  var DEFAULT_BASE_URL = "https://api.onyx.dev";
5
9
  var DEFAULT_AI_BASE_URL = "https://ai.onyx.dev";
10
+ var DEFAULT_AI_MODEL = "onyx";
6
11
  var sanitizeBaseUrl = (u) => u.replace(/\/+$/, "");
7
12
 
8
13
  // src/errors/config-error.ts
@@ -55,6 +60,7 @@ function readEnv(targetId) {
55
60
  const res = dropUndefined({
56
61
  baseUrl: pick("ONYX_DATABASE_BASE_URL"),
57
62
  aiBaseUrl: pick("ONYX_AI_BASE_URL"),
63
+ defaultModel: pick("ONYX_DEFAULT_MODEL"),
58
64
  databaseId: envId,
59
65
  apiKey: pick("ONYX_DATABASE_API_KEY"),
60
66
  apiSecret: pick("ONYX_DATABASE_API_SECRET")
@@ -74,12 +80,14 @@ async function resolveConfig(input) {
74
80
  const merged = {
75
81
  baseUrl: DEFAULT_BASE_URL,
76
82
  aiBaseUrl: DEFAULT_AI_BASE_URL,
83
+ defaultModel: DEFAULT_AI_MODEL,
77
84
  ...dropUndefined(env),
78
85
  ...dropUndefined(input)
79
86
  };
80
87
  dbg("merged (pre-validate):", mask(merged));
81
88
  const baseUrl = sanitizeBaseUrl(merged.baseUrl ?? DEFAULT_BASE_URL);
82
89
  const aiBaseUrl = sanitizeBaseUrl(merged.aiBaseUrl ?? DEFAULT_AI_BASE_URL);
90
+ const defaultModel = typeof merged.defaultModel === "string" && merged.defaultModel.trim() ? merged.defaultModel.trim() : DEFAULT_AI_MODEL;
83
91
  const databaseId = merged.databaseId ?? "";
84
92
  const apiKey = merged.apiKey ?? "";
85
93
  const apiSecret = merged.apiSecret ?? "";
@@ -105,6 +113,7 @@ async function resolveConfig(input) {
105
113
  const resolved = {
106
114
  baseUrl,
107
115
  aiBaseUrl,
116
+ defaultModel,
108
117
  databaseId,
109
118
  apiKey,
110
119
  apiSecret,
@@ -798,8 +807,8 @@ var CascadeRelationshipBuilder = class {
798
807
  * builder.graph('programs');
799
808
  * ```
800
809
  */
801
- graph(name) {
802
- this.graphName = name;
810
+ graph(name2) {
811
+ this.graphName = name2;
803
812
  return this;
804
813
  }
805
814
  /**
@@ -886,24 +895,24 @@ function diffAttributes(apiAttrs, localAttrs) {
886
895
  const added = [];
887
896
  const removed = [];
888
897
  const changed = [];
889
- for (const [name, local] of localMap.entries()) {
890
- if (!apiMap.has(name)) {
898
+ for (const [name2, local] of localMap.entries()) {
899
+ if (!apiMap.has(name2)) {
891
900
  added.push(local);
892
901
  continue;
893
902
  }
894
- const api = apiMap.get(name);
903
+ const api = apiMap.get(name2);
895
904
  const apiNull = Boolean(api.isNullable);
896
905
  const localNull = Boolean(local.isNullable);
897
906
  if (api.type !== local.type || apiNull !== localNull) {
898
907
  changed.push({
899
- name,
908
+ name: name2,
900
909
  from: { type: api.type, isNullable: apiNull },
901
910
  to: { type: local.type, isNullable: localNull }
902
911
  });
903
912
  }
904
913
  }
905
- for (const name of apiMap.keys()) {
906
- if (!localMap.has(name)) removed.push(name);
914
+ for (const name2 of apiMap.keys()) {
915
+ if (!localMap.has(name2)) removed.push(name2);
907
916
  }
908
917
  added.sort((a, b) => a.name.localeCompare(b.name));
909
918
  removed.sort();
@@ -917,22 +926,22 @@ function diffIndexes(apiIndexes, localIndexes) {
917
926
  const added = [];
918
927
  const removed = [];
919
928
  const changed = [];
920
- for (const [name, local] of localMap.entries()) {
921
- if (!apiMap.has(name)) {
929
+ for (const [name2, local] of localMap.entries()) {
930
+ if (!apiMap.has(name2)) {
922
931
  added.push(local);
923
932
  continue;
924
933
  }
925
- const api = apiMap.get(name);
934
+ const api = apiMap.get(name2);
926
935
  const apiType = api.type ?? "DEFAULT";
927
936
  const localType = local.type ?? "DEFAULT";
928
937
  const apiScore = api.minimumScore;
929
938
  const localScore = local.minimumScore;
930
939
  if (apiType !== localType || apiScore !== localScore) {
931
- changed.push({ name, from: api, to: local });
940
+ changed.push({ name: name2, from: api, to: local });
932
941
  }
933
942
  }
934
- for (const name of apiMap.keys()) {
935
- if (!localMap.has(name)) removed.push(name);
943
+ for (const name2 of apiMap.keys()) {
944
+ if (!localMap.has(name2)) removed.push(name2);
936
945
  }
937
946
  added.sort((a, b) => a.name.localeCompare(b.name));
938
947
  removed.sort();
@@ -946,18 +955,18 @@ function diffResolvers(apiResolvers, localResolvers) {
946
955
  const added = [];
947
956
  const removed = [];
948
957
  const changed = [];
949
- for (const [name, local] of localMap.entries()) {
950
- if (!apiMap.has(name)) {
958
+ for (const [name2, local] of localMap.entries()) {
959
+ if (!apiMap.has(name2)) {
951
960
  added.push(local);
952
961
  continue;
953
962
  }
954
- const api = apiMap.get(name);
963
+ const api = apiMap.get(name2);
955
964
  if (api.resolver !== local.resolver) {
956
- changed.push({ name, from: api, to: local });
965
+ changed.push({ name: name2, from: api, to: local });
957
966
  }
958
967
  }
959
- for (const name of apiMap.keys()) {
960
- if (!localMap.has(name)) removed.push(name);
968
+ for (const name2 of apiMap.keys()) {
969
+ if (!localMap.has(name2)) removed.push(name2);
961
970
  }
962
971
  added.sort((a, b) => a.name.localeCompare(b.name));
963
972
  removed.sort();
@@ -971,18 +980,18 @@ function diffTriggers(apiTriggers, localTriggers) {
971
980
  const added = [];
972
981
  const removed = [];
973
982
  const changed = [];
974
- for (const [name, local] of localMap.entries()) {
975
- if (!apiMap.has(name)) {
983
+ for (const [name2, local] of localMap.entries()) {
984
+ if (!apiMap.has(name2)) {
976
985
  added.push(local);
977
986
  continue;
978
987
  }
979
- const api = apiMap.get(name);
988
+ const api = apiMap.get(name2);
980
989
  if (api.event !== local.event || api.trigger !== local.trigger) {
981
- changed.push({ name, from: api, to: local });
990
+ changed.push({ name: name2, from: api, to: local });
982
991
  }
983
992
  }
984
- for (const name of apiMap.keys()) {
985
- if (!localMap.has(name)) removed.push(name);
993
+ for (const name2 of apiMap.keys()) {
994
+ if (!localMap.has(name2)) removed.push(name2);
986
995
  }
987
996
  added.sort((a, b) => a.name.localeCompare(b.name));
988
997
  removed.sort();
@@ -998,13 +1007,13 @@ function computeSchemaDiff(apiSchema, localSchema) {
998
1007
  const newTables = [];
999
1008
  const removedTables = [];
1000
1009
  const changedTables = [];
1001
- for (const [name, localEntity] of localMap.entries()) {
1002
- if (!apiMap.has(name)) {
1003
- newTables.push(name);
1010
+ for (const [name2, localEntity] of localMap.entries()) {
1011
+ if (!apiMap.has(name2)) {
1012
+ newTables.push(name2);
1004
1013
  continue;
1005
1014
  }
1006
- const apiEntity = apiMap.get(name);
1007
- const tableDiff = { name };
1015
+ const apiEntity = apiMap.get(name2);
1016
+ const tableDiff = { name: name2 };
1008
1017
  const partitionFrom = normalizePartition(apiEntity.partition);
1009
1018
  const partitionTo = normalizePartition(localEntity.partition);
1010
1019
  if (partitionFrom !== partitionTo) {
@@ -1029,8 +1038,8 @@ function computeSchemaDiff(apiSchema, localSchema) {
1029
1038
  changedTables.push(tableDiff);
1030
1039
  }
1031
1040
  }
1032
- for (const name of apiMap.keys()) {
1033
- if (!localMap.has(name)) removedTables.push(name);
1041
+ for (const name2 of apiMap.keys()) {
1042
+ if (!localMap.has(name2)) removedTables.push(name2);
1034
1043
  }
1035
1044
  newTables.sort();
1036
1045
  removedTables.sort();
@@ -1130,58 +1139,64 @@ var OnyxDatabaseImpl = class {
1130
1139
  requestLoggingEnabled;
1131
1140
  responseLoggingEnabled;
1132
1141
  defaultPartition;
1142
+ ai;
1133
1143
  constructor(config, resolveConfigWithCache) {
1134
1144
  this.requestLoggingEnabled = !!config?.requestLoggingEnabled;
1135
1145
  this.responseLoggingEnabled = !!config?.responseLoggingEnabled;
1136
1146
  this.defaultPartition = config?.partition;
1137
1147
  this.cfgPromise = resolveConfigWithCache(config);
1148
+ this.ai = this.createAiFacade();
1138
1149
  }
1139
- async ensureClient() {
1150
+ async resolveConfig() {
1140
1151
  if (!this.resolved) {
1141
1152
  this.resolved = await this.cfgPromise;
1142
1153
  }
1154
+ return this.resolved;
1155
+ }
1156
+ async ensureClient() {
1157
+ const cfg = await this.resolveConfig();
1143
1158
  if (!this.http) {
1144
1159
  this.http = new HttpClient({
1145
- baseUrl: this.resolved.baseUrl,
1146
- apiKey: this.resolved.apiKey,
1147
- apiSecret: this.resolved.apiSecret,
1148
- fetchImpl: this.resolved.fetch,
1160
+ baseUrl: cfg.baseUrl,
1161
+ apiKey: cfg.apiKey,
1162
+ apiSecret: cfg.apiSecret,
1163
+ fetchImpl: cfg.fetch,
1149
1164
  requestLoggingEnabled: this.requestLoggingEnabled,
1150
1165
  responseLoggingEnabled: this.responseLoggingEnabled,
1151
- retryEnabled: this.resolved.retryEnabled,
1152
- maxRetries: this.resolved.maxRetries,
1153
- retryInitialDelayMs: this.resolved.retryInitialDelayMs
1166
+ retryEnabled: cfg.retryEnabled,
1167
+ maxRetries: cfg.maxRetries,
1168
+ retryInitialDelayMs: cfg.retryInitialDelayMs
1154
1169
  });
1155
1170
  }
1156
1171
  return {
1157
1172
  http: this.http,
1158
- fetchImpl: this.resolved.fetch,
1159
- baseUrl: this.resolved.baseUrl,
1160
- databaseId: this.resolved.databaseId
1173
+ fetchImpl: cfg.fetch,
1174
+ baseUrl: cfg.baseUrl,
1175
+ databaseId: cfg.databaseId,
1176
+ defaultModel: cfg.defaultModel ?? DEFAULT_AI_MODEL
1161
1177
  };
1162
1178
  }
1163
1179
  async ensureAiClient() {
1164
- if (!this.resolved) {
1165
- this.resolved = await this.cfgPromise;
1166
- }
1180
+ const cfg = await this.resolveConfig();
1167
1181
  if (!this.aiHttp) {
1168
1182
  this.aiHttp = new HttpClient({
1169
- baseUrl: this.resolved.aiBaseUrl,
1170
- apiKey: this.resolved.apiKey,
1171
- apiSecret: this.resolved.apiSecret,
1172
- fetchImpl: this.resolved.fetch,
1183
+ baseUrl: cfg.aiBaseUrl,
1184
+ apiKey: cfg.apiKey,
1185
+ apiSecret: cfg.apiSecret,
1186
+ fetchImpl: cfg.fetch,
1173
1187
  requestLoggingEnabled: this.requestLoggingEnabled,
1174
1188
  responseLoggingEnabled: this.responseLoggingEnabled,
1175
- retryEnabled: this.resolved.retryEnabled,
1176
- maxRetries: this.resolved.maxRetries,
1177
- retryInitialDelayMs: this.resolved.retryInitialDelayMs
1189
+ retryEnabled: cfg.retryEnabled,
1190
+ maxRetries: cfg.maxRetries,
1191
+ retryInitialDelayMs: cfg.retryInitialDelayMs
1178
1192
  });
1179
1193
  }
1180
1194
  return {
1181
1195
  http: this.aiHttp,
1182
- fetchImpl: this.resolved.fetch,
1183
- aiBaseUrl: this.resolved.aiBaseUrl,
1184
- databaseId: this.resolved.databaseId
1196
+ fetchImpl: cfg.fetch,
1197
+ aiBaseUrl: cfg.aiBaseUrl,
1198
+ databaseId: cfg.databaseId,
1199
+ defaultModel: cfg.defaultModel ?? DEFAULT_AI_MODEL
1185
1200
  };
1186
1201
  }
1187
1202
  registerStream(handle) {
@@ -1196,6 +1211,21 @@ var OnyxDatabaseImpl = class {
1196
1211
  }
1197
1212
  };
1198
1213
  }
1214
+ createAiFacade() {
1215
+ const chat = ((contentOrRequest, options) => {
1216
+ if (typeof contentOrRequest === "string") {
1217
+ return this.chatWithContent(contentOrRequest, options);
1218
+ }
1219
+ return this.getAiChatClient().create(contentOrRequest, options);
1220
+ });
1221
+ return {
1222
+ chat,
1223
+ chatClient: () => this.getAiChatClient(),
1224
+ getModels: () => this.getModels(),
1225
+ getModel: (modelId) => this.getModel(modelId),
1226
+ requestScriptApproval: (input) => this.requestScriptApproval(input)
1227
+ };
1228
+ }
1199
1229
  getRequestLoggingEnabled() {
1200
1230
  return this.requestLoggingEnabled;
1201
1231
  }
@@ -1203,7 +1233,7 @@ var OnyxDatabaseImpl = class {
1203
1233
  return this.responseLoggingEnabled;
1204
1234
  }
1205
1235
  /** -------- IOnyxDatabase -------- */
1206
- chat() {
1236
+ getAiChatClient() {
1207
1237
  return new AiChatClientImpl(
1208
1238
  () => this.ensureAiClient(),
1209
1239
  (handle) => this.registerStream(handle),
@@ -1211,6 +1241,32 @@ var OnyxDatabaseImpl = class {
1211
1241
  () => this.responseLoggingEnabled
1212
1242
  );
1213
1243
  }
1244
+ async chatWithContent(content, options) {
1245
+ const { defaultModel } = await this.ensureAiClient();
1246
+ const stream = options?.stream ?? false;
1247
+ const request = {
1248
+ model: options?.model ?? defaultModel,
1249
+ messages: [{ role: options?.role ?? "user", content }],
1250
+ stream
1251
+ };
1252
+ if (options && "temperature" in options) {
1253
+ request.temperature = options.temperature ?? null;
1254
+ }
1255
+ const result = await this.getAiChatClient().create(request, options);
1256
+ if (stream) return result;
1257
+ if (options?.raw) return result;
1258
+ const first = result.choices?.[0]?.message?.content;
1259
+ if (typeof first === "string" && first.trim().length > 0) {
1260
+ return first;
1261
+ }
1262
+ throw new Error("Chat completion response is missing message content");
1263
+ }
1264
+ chat(content, options) {
1265
+ if (typeof content === "string") {
1266
+ return this.chatWithContent(content, options);
1267
+ }
1268
+ return this.getAiChatClient();
1269
+ }
1214
1270
  async getModels() {
1215
1271
  const { http } = await this.ensureAiClient();
1216
1272
  return http.request("GET", "/v1/models");
@@ -2127,12 +2183,9 @@ var upper = (attribute) => `upper(${attribute})`;
2127
2183
  var lower = (attribute) => `lower(${attribute})`;
2128
2184
  var substring = (attribute, from, length) => `substring(${attribute},${from},${length})`;
2129
2185
  var replace = (attribute, pattern, repl) => `replace(${attribute}, '${pattern.replace(/'/g, "\\'")}', '${repl.replace(/'/g, "\\'")}')`;
2186
+ var format = (attribute, formatter) => `format(${attribute}, '${formatter.replace(/'/g, "\\'")}')`;
2130
2187
  var percentile = (attribute, p) => `percentile(${attribute}, ${p})`;
2131
2188
 
2132
- // src/edge.ts
2133
- var sdkName = "@onyx.dev/onyx-database";
2134
- var sdkVersion = "0.1.0";
2135
-
2136
2189
  exports.QueryResults = QueryResults;
2137
2190
  exports.asc = asc;
2138
2191
  exports.avg = avg;
@@ -2142,6 +2195,7 @@ exports.containsIgnoreCase = containsIgnoreCase;
2142
2195
  exports.count = count;
2143
2196
  exports.desc = desc;
2144
2197
  exports.eq = eq;
2198
+ exports.format = format;
2145
2199
  exports.gt = gt;
2146
2200
  exports.gte = gte;
2147
2201
  exports.inOp = inOp;
@@ -2166,8 +2220,8 @@ exports.notWithin = notWithin;
2166
2220
  exports.onyx = onyx;
2167
2221
  exports.percentile = percentile;
2168
2222
  exports.replace = replace;
2169
- exports.sdkName = sdkName;
2170
- exports.sdkVersion = sdkVersion;
2223
+ exports.sdkName = name;
2224
+ exports.sdkVersion = version;
2171
2225
  exports.search = search;
2172
2226
  exports.startsWith = startsWith;
2173
2227
  exports.std = std;