symmetria 2.1.0 → 2.3.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 +34 -27
- package/dist/better-auth.d.ts +45 -0
- package/dist/better-auth.js +186 -0
- package/dist/better-auth.js.map +1 -0
- package/dist/bun.d.ts +2 -3
- package/dist/cohere.d.ts +19 -0
- package/dist/cohere.js +35 -0
- package/dist/cohere.js.map +1 -0
- package/dist/{compile-jL3rWA7P.js → compile-R1_PBIgc.js} +3 -2
- package/dist/{compile-jL3rWA7P.js.map → compile-R1_PBIgc.js.map} +1 -1
- package/dist/core-DxXVTy9r.js +1260 -0
- package/dist/core-DxXVTy9r.js.map +1 -0
- package/dist/driver.d.ts +3 -4
- package/dist/google.d.ts +16 -0
- package/dist/google.js +29 -0
- package/dist/google.js.map +1 -0
- package/dist/http-o1fpnTNy.js +33 -0
- package/dist/http-o1fpnTNy.js.map +1 -0
- package/dist/index.d.ts +1 -3
- package/dist/index.js +371 -98
- package/dist/index.js.map +1 -1
- package/dist/{inspection-XCwdKgbn.js → inspection-BlOMPoif.js} +2 -2
- package/dist/{inspection-XCwdKgbn.js.map → inspection-BlOMPoif.js.map} +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +1 -1
- package/dist/jina.d.ts +16 -0
- package/dist/jina.js +20 -0
- package/dist/jina.js.map +1 -0
- package/dist/mistral.d.ts +16 -0
- package/dist/mistral.js +18 -0
- package/dist/mistral.js.map +1 -0
- package/dist/ollama.d.ts +13 -0
- package/dist/ollama.js +30 -0
- package/dist/ollama.js.map +1 -0
- package/dist/openai.d.ts +19 -0
- package/dist/openai.js +31 -0
- package/dist/openai.js.map +1 -0
- package/dist/{pg-BYalsA8o.d.ts → pg-BP8Z91xx.d.ts} +3 -3
- package/dist/pg.d.ts +3 -4
- package/dist/{pool-BSiopqlE.d.ts → pool-yxHoV4wf.d.ts} +2 -2
- package/dist/search-BEk0Ff_y.js +157 -0
- package/dist/search-BEk0Ff_y.js.map +1 -0
- package/dist/search.d.ts +2 -0
- package/dist/search.js +1 -0
- package/dist/{table-CQdO0xkD.js → table-Bx_6J15y.js} +23 -1171
- package/dist/table-Bx_6J15y.js.map +1 -0
- package/dist/{types-BaS_bFak.d.ts → types-pQCOrPh-.d.ts} +753 -126
- package/dist/vector.d.ts +1 -1
- package/dist/vector.js +1 -1
- package/dist/voyage.d.ts +22 -0
- package/dist/voyage.js +26 -0
- package/dist/voyage.js.map +1 -0
- package/package.json +41 -1
- package/dist/binding-C_39Pgt8.d.ts +0 -69
- package/dist/index-DkXJfVJZ.d.ts +0 -398
- package/dist/table-CQdO0xkD.js.map +0 -1
package/README.md
CHANGED
|
@@ -127,21 +127,21 @@ import { createDatabase } from "symmetria";
|
|
|
127
127
|
import { postgres } from "symmetria/bun";
|
|
128
128
|
import { appSchema } from "./schema.ts";
|
|
129
129
|
|
|
130
|
-
const
|
|
130
|
+
const db = createDatabase({
|
|
131
131
|
schema: appSchema,
|
|
132
132
|
driver: postgres({ url: process.env.DATABASE_URL! }),
|
|
133
133
|
});
|
|
134
134
|
|
|
135
135
|
try {
|
|
136
|
-
await
|
|
136
|
+
await db.users
|
|
137
137
|
.insert({ name: "Ada", email: "ada@example.com" })
|
|
138
138
|
.onConflict("email")
|
|
139
139
|
.doNothing();
|
|
140
140
|
|
|
141
|
-
const author = await
|
|
142
|
-
await
|
|
141
|
+
const author = await db.users.get({ email: "ada@example.com" });
|
|
142
|
+
await db.posts.insert({ title: "Typed SQL", authorId: author.id });
|
|
143
143
|
|
|
144
|
-
const authors = await
|
|
144
|
+
const authors = await db.users(({ name, posts }) => ({
|
|
145
145
|
name,
|
|
146
146
|
posts: posts(({ title, views }) => ({ title, views }), {
|
|
147
147
|
orderBy: ({ id }) => id.descending,
|
|
@@ -152,7 +152,7 @@ try {
|
|
|
152
152
|
|
|
153
153
|
console.log(authors);
|
|
154
154
|
} finally {
|
|
155
|
-
await
|
|
155
|
+
await db.$close();
|
|
156
156
|
}
|
|
157
157
|
```
|
|
158
158
|
|
|
@@ -170,7 +170,7 @@ Each option can be a value or a synchronous callback receiving the same typed
|
|
|
170
170
|
source and SQL tools.
|
|
171
171
|
|
|
172
172
|
```ts
|
|
173
|
-
const feed =
|
|
173
|
+
const feed = db.posts(
|
|
174
174
|
({ title, authorId }, { join }) => ({ title, author: join(authorId).name }),
|
|
175
175
|
{ orderBy: ({ id }) => id.descending },
|
|
176
176
|
);
|
|
@@ -197,8 +197,8 @@ Reusable projections bind to each source occurrence, including aliases and
|
|
|
197
197
|
relations:
|
|
198
198
|
|
|
199
199
|
```ts
|
|
200
|
-
const userCard =
|
|
201
|
-
const feed =
|
|
200
|
+
const userCard = db.users.shape((user) => ({ name: user.name }));
|
|
201
|
+
const feed = db.posts((post) => ({
|
|
202
202
|
title: post.title,
|
|
203
203
|
author: post.author(userCard),
|
|
204
204
|
}));
|
|
@@ -207,14 +207,14 @@ const feed = database.posts((post) => ({
|
|
|
207
207
|
`.shape()` stores a synchronous callback and evaluates it on each application. A
|
|
208
208
|
projection belongs to its defining table, contains at least one selected field
|
|
209
209
|
and has no `$...` controls. Apply options at use sites, for example
|
|
210
|
-
`
|
|
211
|
-
|
|
212
|
-
|
|
210
|
+
`db.users(userCard, { limit: 20 })`. It can be defined on an offline schema and
|
|
211
|
+
used on its connected or transaction-bound tables. To-one selections are typed
|
|
212
|
+
as an object or `null`.
|
|
213
213
|
|
|
214
214
|
Relations offer `count`, `exists`, `sum`, `average`, `minimum` and `maximum`:
|
|
215
215
|
|
|
216
216
|
```ts
|
|
217
|
-
const totals =
|
|
217
|
+
const totals = db.users(({ name, posts }) => ({
|
|
218
218
|
name,
|
|
219
219
|
totalViews: posts.sum.views,
|
|
220
220
|
latestPost: posts.maximum.createdAt,
|
|
@@ -238,7 +238,7 @@ returns `false` for empty inputs.
|
|
|
238
238
|
## Enum mappings
|
|
239
239
|
|
|
240
240
|
```ts
|
|
241
|
-
const labels =
|
|
241
|
+
const labels = db.posts((post) => ({
|
|
242
242
|
title: post.title,
|
|
243
243
|
status: post.state.match({ draft: "Draft", published: "Published" }),
|
|
244
244
|
visibleViews: post.state.match({ draft: 0n, published: post.views }),
|
|
@@ -253,31 +253,32 @@ CTEs.
|
|
|
253
253
|
## Write callbacks
|
|
254
254
|
|
|
255
255
|
```ts
|
|
256
|
-
const updated = await
|
|
256
|
+
const updated = await db.posts
|
|
257
257
|
.byId(42)
|
|
258
258
|
.update((post) => ({ views: post.views.plus(1n) }))
|
|
259
|
-
.returning(
|
|
259
|
+
.returning("id", "views");
|
|
260
260
|
|
|
261
|
-
const userCard =
|
|
262
|
-
await
|
|
261
|
+
const userCard = db.users.shape(({ id, name }) => ({ id, name }));
|
|
262
|
+
await db.users.by
|
|
263
263
|
.email("ada@example.com")
|
|
264
264
|
.update({ name: "Ada Lovelace" })
|
|
265
265
|
.returning(userCard);
|
|
266
266
|
|
|
267
|
-
await
|
|
267
|
+
await db.users
|
|
268
268
|
.insert({ name: "Ada Lovelace", email: "ada@example.com" })
|
|
269
269
|
.onConflict("email")
|
|
270
270
|
.doUpdate((user, excluded) => ({ email: user.email, name: excluded.name }));
|
|
271
271
|
|
|
272
|
-
await
|
|
272
|
+
await db.posts.update({ state: "draft" }).all(); // whole table, spelled out
|
|
273
273
|
```
|
|
274
274
|
|
|
275
275
|
`byId()` and `.by.<key>()` lookups update and delete directly, in one statement.
|
|
276
|
-
`returning()` accepts a callback or a row-local reusable
|
|
277
|
-
table. UPDATE, WHERE and RETURNING callbacks receive the
|
|
278
|
-
nested-insert RETURNING. Upserts receive the existing
|
|
279
|
-
`excluded` row second. `.doUpdate("name")` copies a
|
|
280
|
-
UPDATE or DELETE without `where()` is refused unless
|
|
276
|
+
`returning()` accepts column names, a callback or a row-local reusable
|
|
277
|
+
projection of the same table. UPDATE, WHERE and RETURNING callbacks receive the
|
|
278
|
+
row directly, including nested-insert RETURNING. Upserts receive the existing
|
|
279
|
+
row first and the proposed `excluded` row second. `.doUpdate("name")` copies a
|
|
280
|
+
field from `excluded`. An UPDATE or DELETE without `where()` is refused unless
|
|
281
|
+
`.all()` confirms it.
|
|
281
282
|
|
|
282
283
|
## Capabilities
|
|
283
284
|
|
|
@@ -297,7 +298,7 @@ UPDATE or DELETE without `where()` is refused unless `.all()` confirms it.
|
|
|
297
298
|
`exists` / `inspect`, keyset pagination in both directions and `pages()` async
|
|
298
299
|
iteration; `count()` and `exists()` on any table or filtered source.
|
|
299
300
|
- Transactions, nested savepoints, isolation options and row locks.
|
|
300
|
-
- `Transaction<typeof
|
|
301
|
+
- `Transaction<typeof db>` for schema-specific transaction helpers.
|
|
301
302
|
- `$scope()` filters for reads, updates and deletes, including related tables,
|
|
302
303
|
and checks every row a scoped insert, upsert or update writes, like row-level
|
|
303
304
|
security's `WITH CHECK` (`SYMMETRIA_OUT_OF_SCOPE`); reused and prepared
|
|
@@ -320,6 +321,12 @@ UPDATE or DELETE without `where()` is refused unless `.all()` confirms it.
|
|
|
320
321
|
carry a code. Invalid values (out-of-range numbers, invalid `jsonb(schema)`
|
|
321
322
|
input, `null` for NOT NULL columns) reject the query's promise when it runs;
|
|
322
323
|
mistakes in the query's shape throw where it is built.
|
|
324
|
+
- `table.search()`: hybrid search declared on the table, by words (full text or
|
|
325
|
+
BM25) and by meaning (embeddings computed on insert), merged in one statement
|
|
326
|
+
(`symmetria/search`; models from `symmetria/voyage`, `openai`, `cohere`,
|
|
327
|
+
`google`, `mistral`, `jina`, `ollama`)
|
|
328
|
+
- `symmetria/better-auth`: a better-auth adapter; `auth generate` writes the
|
|
329
|
+
auth tables as part of your schema
|
|
323
330
|
- Arrays, full-text search with stored `tsvector` columns, weighted documents,
|
|
324
331
|
ranking and headlines, pgvector embeddings with distance operators and HNSW
|
|
325
332
|
indexes (`symmetria/vector`), typed JSON paths and Standard Schema JSON
|
|
@@ -362,7 +369,7 @@ Official drivers ship with `symmetria` and are maintained and released together:
|
|
|
362
369
|
import { createDatabase } from "symmetria";
|
|
363
370
|
import { postgres } from "symmetria/pg";
|
|
364
371
|
|
|
365
|
-
const
|
|
372
|
+
const db = createDatabase({
|
|
366
373
|
schema: appSchema,
|
|
367
374
|
driver: postgres({ url: process.env.DATABASE_URL!, max: 10 }),
|
|
368
375
|
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { DBAdapterDebugLogOption } from "better-auth/adapters";
|
|
2
|
+
import { BetterAuthOptions } from "better-auth";
|
|
3
|
+
//#region src/entries/better-auth.d.ts
|
|
4
|
+
export type SymmetriaAdapterOptions = {
|
|
5
|
+
/** Tables are keyed in the plural (`users`, `sessions`). */
|
|
6
|
+
readonly usePlural?: boolean;
|
|
7
|
+
readonly debugLogs?: DBAdapterDebugLogOption;
|
|
8
|
+
};
|
|
9
|
+
type Tables = Record<string, {
|
|
10
|
+
modelName: string;
|
|
11
|
+
fields: Record<string, Field>;
|
|
12
|
+
indexes?: readonly {
|
|
13
|
+
fields: readonly string[];
|
|
14
|
+
unique?: boolean | undefined;
|
|
15
|
+
}[];
|
|
16
|
+
}>;
|
|
17
|
+
type Field = {
|
|
18
|
+
type: string | readonly string[];
|
|
19
|
+
required?: boolean | undefined;
|
|
20
|
+
unique?: boolean | undefined;
|
|
21
|
+
index?: boolean | undefined;
|
|
22
|
+
bigint?: boolean | undefined;
|
|
23
|
+
fieldName?: string | undefined;
|
|
24
|
+
defaultValue?: unknown;
|
|
25
|
+
references?: {
|
|
26
|
+
model: string;
|
|
27
|
+
field: string;
|
|
28
|
+
onDelete?: string | undefined;
|
|
29
|
+
} | undefined;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* The auth tables as a Symmetria schema module, for `npx auth generate`.
|
|
33
|
+
* Tables come out in an order where each one follows the tables it
|
|
34
|
+
* references; spread `authTables` into `schema({ ... })`.
|
|
35
|
+
*/
|
|
36
|
+
export declare const authSchemaSource: (tables: Tables) => string;
|
|
37
|
+
/**
|
|
38
|
+
* `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a
|
|
39
|
+
* `$scope()` of it) whose schema holds the auth tables; better-auth's own
|
|
40
|
+
* transactions run inside `db.$transaction`.
|
|
41
|
+
*/
|
|
42
|
+
export declare const symmetriaAdapter: (db: object, options?: SymmetriaAdapterOptions) => (betterAuthOptions: BetterAuthOptions) => import("better-auth").DBAdapter<BetterAuthOptions>;
|
|
43
|
+
//#endregion
|
|
44
|
+
export {};
|
|
45
|
+
//# sourceMappingURL=better-auth.d.ts.map
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { _ as not, b as or, l as and } from "./core-DxXVTy9r.js";
|
|
2
|
+
import { createAdapterFactory } from "better-auth/adapters";
|
|
3
|
+
//#region src/entries/better-auth.ts
|
|
4
|
+
const escapeLike = (value) => String(value).replace(/[\\%_]/g, (character) => `\\${character}`);
|
|
5
|
+
const predicate = (row, clause) => {
|
|
6
|
+
const column = row[clause.field];
|
|
7
|
+
if (!column) throw new Error(`symmetria: better-auth asked for field "${clause.field}", which the table does not have`);
|
|
8
|
+
const insensitive = clause.mode === "insensitive" && typeof clause.value === "string";
|
|
9
|
+
const pattern = (text) => insensitive ? column.ilike(text) : column.like(text);
|
|
10
|
+
switch (clause.operator) {
|
|
11
|
+
case "ne": return insensitive ? not(column.ilike(escapeLike(clause.value))) : column.isNot(clause.value);
|
|
12
|
+
case "in": return column.in(clause.value);
|
|
13
|
+
case "not_in": return column.notIn(clause.value);
|
|
14
|
+
case "gt": return column.above(clause.value);
|
|
15
|
+
case "gte": return column.atLeast(clause.value);
|
|
16
|
+
case "lt": return column.below(clause.value);
|
|
17
|
+
case "lte": return column.atMost(clause.value);
|
|
18
|
+
case "contains": return pattern(`%${escapeLike(clause.value)}%`);
|
|
19
|
+
case "starts_with": return pattern(`${escapeLike(clause.value)}%`);
|
|
20
|
+
case "ends_with": return pattern(`%${escapeLike(clause.value)}`);
|
|
21
|
+
default: return insensitive ? column.ilike(escapeLike(clause.value)) : column.is(clause.value);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */
|
|
25
|
+
const filter = (where) => (row) => {
|
|
26
|
+
const clauses = where ?? [];
|
|
27
|
+
const all = clauses.filter((clause) => clause.connector !== "OR").map((clause) => predicate(row, clause));
|
|
28
|
+
const any = clauses.filter((clause) => clause.connector === "OR").map((clause) => predicate(row, clause));
|
|
29
|
+
return and(...all, any.length > 0 ? or(...any) : void 0);
|
|
30
|
+
};
|
|
31
|
+
const COLUMN_TYPES = {
|
|
32
|
+
string: "text",
|
|
33
|
+
boolean: "bool",
|
|
34
|
+
date: "timestamptz",
|
|
35
|
+
json: "jsonb",
|
|
36
|
+
"string[]": "text.array",
|
|
37
|
+
"number[]": "int.array"
|
|
38
|
+
};
|
|
39
|
+
const snakeCase = (name) => name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
|
|
40
|
+
/**
|
|
41
|
+
* The auth tables as a Symmetria schema module, for `npx auth generate`.
|
|
42
|
+
* Tables come out in an order where each one follows the tables it
|
|
43
|
+
* references; spread `authTables` into `schema({ ... })`.
|
|
44
|
+
*/
|
|
45
|
+
const authSchemaSource = (tables) => {
|
|
46
|
+
const builders = /* @__PURE__ */ new Set(["table", "text"]);
|
|
47
|
+
const models = Object.values(tables);
|
|
48
|
+
const nameOf = (model) => tables[model]?.modelName ?? models.find((entry) => entry.modelName === model)?.modelName ?? model;
|
|
49
|
+
const ordered = [];
|
|
50
|
+
const pending = [...models];
|
|
51
|
+
while (pending.length) {
|
|
52
|
+
const next = pending.find((entry) => Object.values(entry.fields).every((field) => !field.references || nameOf(field.references.model) === entry.modelName || ordered.some((done) => done.modelName === nameOf(field.references.model)))) ?? pending[0];
|
|
53
|
+
ordered.push(next);
|
|
54
|
+
pending.splice(pending.indexOf(next), 1);
|
|
55
|
+
}
|
|
56
|
+
const declarations = ordered.map((entry) => {
|
|
57
|
+
const targets = Object.values(entry.fields).flatMap((field) => field.references ? [nameOf(field.references.model)] : []);
|
|
58
|
+
const lines = Object.entries(entry.fields).map(([key, field]) => {
|
|
59
|
+
const named = field.fieldName && field.fieldName !== key && field.fieldName !== snakeCase(key) ? `.named(${JSON.stringify(field.fieldName)})` : "";
|
|
60
|
+
const reference = field.references;
|
|
61
|
+
if (reference && reference.field === "id" && key.endsWith("Id")) {
|
|
62
|
+
const target = nameOf(reference.model);
|
|
63
|
+
const action = reference.onDelete === void 0 || reference.onDelete === "cascade" ? "cascade" : reference.onDelete === "set null" ? "setNull" : void 0;
|
|
64
|
+
const relation = key.slice(0, -2);
|
|
65
|
+
const self = target === entry.modelName;
|
|
66
|
+
if (targets.filter((name) => name === target).length > 1 || self) {
|
|
67
|
+
if (self) builders.add("self");
|
|
68
|
+
return ` ${relation}: ${self ? "self" : target}${field.required === false || action === "setNull" ? ".nullable" : ""}${field.unique ? ".unique" : ".index"}${action ? `.onDelete.${action}` : ""}.inverse(${JSON.stringify(`${entry.modelName}By${relation[0].toUpperCase()}${relation.slice(1)}`)}),`;
|
|
69
|
+
}
|
|
70
|
+
const claim = field.required === false || action === "setNull" ? "maybe" : "one";
|
|
71
|
+
builders.add(claim);
|
|
72
|
+
return ` ${relation}: ${claim}(${target})${action ? `.${action}` : ""}${field.unique ? ".unique" : ""},`;
|
|
73
|
+
}
|
|
74
|
+
let type;
|
|
75
|
+
if (Array.isArray(field.type)) {
|
|
76
|
+
builders.add("oneOf");
|
|
77
|
+
type = `oneOf(${field.type.map((value) => JSON.stringify(value)).join(", ")})`;
|
|
78
|
+
} else if (field.type === "number") type = field.bigint ? "bigint" : "int";
|
|
79
|
+
else type = COLUMN_TYPES[field.type] ?? "text";
|
|
80
|
+
builders.add(type.split(/[.(]/)[0]);
|
|
81
|
+
const fallback = field.defaultValue;
|
|
82
|
+
const literal = typeof fallback === "string" || typeof fallback === "number" || typeof fallback === "boolean" ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})` : "";
|
|
83
|
+
return ` ${key}: ${type}${named}${field.required === false ? ".nullable" : ""}${field.unique ? ".unique" : ""}${field.index && !field.unique ? ".index" : ""}${literal},`;
|
|
84
|
+
});
|
|
85
|
+
const indexes = (entry.indexes ?? []).filter((definition) => definition.fields.length > 1);
|
|
86
|
+
if (indexes.length) builders.add("index");
|
|
87
|
+
return [
|
|
88
|
+
`export const ${entry.modelName} = table({`,
|
|
89
|
+
" id: text,",
|
|
90
|
+
...lines,
|
|
91
|
+
indexes.length ? `}).indexes((${entry.modelName}) => ({\n${indexes.map((definition) => ` ${definition.fields.join("_").replace(/_(\w)/g, (_match, letter) => letter.toUpperCase())}: index(${definition.fields.map((name) => `${entry.modelName}.${name}`).join(", ")})${definition.unique ? ".unique" : ""},`).join("\n")}\n}));` : "});"
|
|
92
|
+
].join("\n");
|
|
93
|
+
});
|
|
94
|
+
return [
|
|
95
|
+
"// Written by `auth generate` through symmetria/better-auth.",
|
|
96
|
+
"// Spread `authTables` into your schema: schema({ ...authTables, posts, … }).",
|
|
97
|
+
`import { ${[...builders].sort().join(", ")} } from "symmetria";`,
|
|
98
|
+
"",
|
|
99
|
+
declarations.join("\n\n"),
|
|
100
|
+
"",
|
|
101
|
+
`export const authTables = { ${ordered.map((entry) => entry.modelName).join(", ")} };`,
|
|
102
|
+
""
|
|
103
|
+
].join("\n");
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a
|
|
107
|
+
* `$scope()` of it) whose schema holds the auth tables; better-auth's own
|
|
108
|
+
* transactions run inside `db.$transaction`.
|
|
109
|
+
*/
|
|
110
|
+
const symmetriaAdapter = (db, options = {}) => {
|
|
111
|
+
let authOptions;
|
|
112
|
+
const build = (connection) => createAdapterFactory({
|
|
113
|
+
config: {
|
|
114
|
+
adapterId: "symmetria",
|
|
115
|
+
adapterName: "Symmetria",
|
|
116
|
+
usePlural: options.usePlural ?? false,
|
|
117
|
+
debugLogs: options.debugLogs ?? false,
|
|
118
|
+
supportsDates: true,
|
|
119
|
+
supportsBooleans: true,
|
|
120
|
+
supportsJSON: true,
|
|
121
|
+
supportsArrays: true,
|
|
122
|
+
transaction: (callback) => connection.$transaction((transaction) => callback(build(transaction)(authOptions ?? {})))
|
|
123
|
+
},
|
|
124
|
+
adapter: () => {
|
|
125
|
+
const table = (model) => {
|
|
126
|
+
const handle = connection[model];
|
|
127
|
+
if (!handle) throw new Error(`symmetria: better-auth uses a table "${model}" that the schema does not have; run \`npx auth generate\` and add it`);
|
|
128
|
+
return handle;
|
|
129
|
+
};
|
|
130
|
+
const filtered = (mutation, where) => where?.length ? mutation.where(filter(where)) : mutation.all();
|
|
131
|
+
return {
|
|
132
|
+
create: ({ model, data }) => table(model).insert(data).returning(),
|
|
133
|
+
findOne: ({ model, where }) => table(model)({
|
|
134
|
+
where: filter(where),
|
|
135
|
+
limit: 1
|
|
136
|
+
}).first(),
|
|
137
|
+
findMany: ({ model, where, limit, offset, sortBy }) => table(model)({
|
|
138
|
+
where: filter(where),
|
|
139
|
+
limit,
|
|
140
|
+
offset,
|
|
141
|
+
orderBy: sortBy ? { [sortBy.field]: sortBy.direction } : void 0
|
|
142
|
+
}),
|
|
143
|
+
count: ({ model, where }) => table(model)({ where: filter(where) }).count(),
|
|
144
|
+
update: async ({ model, where, update }) => {
|
|
145
|
+
const [row] = await filtered(table(model).update(update), where).returning();
|
|
146
|
+
return row ?? null;
|
|
147
|
+
},
|
|
148
|
+
updateMany: async ({ model, where, update }) => (await filtered(table(model).update(update), where)).affectedRows,
|
|
149
|
+
delete: async ({ model, where }) => {
|
|
150
|
+
await filtered(table(model).delete(), where);
|
|
151
|
+
},
|
|
152
|
+
deleteMany: async ({ model, where }) => (await filtered(table(model).delete(), where)).affectedRows,
|
|
153
|
+
consumeOne: async ({ model, where }) => {
|
|
154
|
+
const found = await table(model)({
|
|
155
|
+
where: filter(where),
|
|
156
|
+
limit: 1
|
|
157
|
+
}).first();
|
|
158
|
+
if (!found) return null;
|
|
159
|
+
const [row] = await table(model).byId(found.id).delete().returning();
|
|
160
|
+
return row ?? null;
|
|
161
|
+
},
|
|
162
|
+
incrementOne: async ({ model, where, increment, set }) => {
|
|
163
|
+
const [row] = await table(model).update((current) => ({
|
|
164
|
+
...set,
|
|
165
|
+
...Object.fromEntries(Object.entries(increment).map(([field, delta]) => [field, current[field].plus(delta)]))
|
|
166
|
+
})).where(filter(where)).returning();
|
|
167
|
+
return row ?? null;
|
|
168
|
+
},
|
|
169
|
+
createSchema: async ({ tables, file }) => ({
|
|
170
|
+
code: authSchemaSource(tables),
|
|
171
|
+
path: file ?? "./auth-schema.ts",
|
|
172
|
+
overwrite: true
|
|
173
|
+
})
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
const adapter = build(db);
|
|
178
|
+
return (betterAuthOptions) => {
|
|
179
|
+
authOptions = betterAuthOptions;
|
|
180
|
+
return adapter(betterAuthOptions);
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
//#endregion
|
|
184
|
+
export { authSchemaSource, symmetriaAdapter };
|
|
185
|
+
|
|
186
|
+
//# sourceMappingURL=better-auth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"better-auth.js","names":[],"sources":["../src/entries/better-auth.ts"],"sourcesContent":["/**\n * `symmetria/better-auth`: a better-auth database adapter over a Symmetria\n * database: `betterAuth({ database: symmetriaAdapter(db) })`. The auth tables\n * are tables of your schema, keyed and named the way better-auth names its\n * models and fields (`user.emailVerified`), so they are migrated, related and\n * queried like the rest; `npx auth generate` writes them.\n */\nimport type { BetterAuthOptions } from \"better-auth\";\nimport {\n createAdapterFactory,\n type CleanedWhere,\n type DBAdapterDebugLogOption,\n} from \"better-auth/adapters\";\nimport { and, not, or } from \"../query/expressions\";\n\nexport type SymmetriaAdapterOptions = {\n /** Tables are keyed in the plural (`users`, `sessions`). */\n readonly usePlural?: boolean;\n readonly debugLogs?: DBAdapterDebugLogOption;\n};\n\n// better-auth names tables and fields at run time, so the adapter reaches\n// them by key and leaves the typed API to the application.\ntype Loose = any;\ntype Tables = Record<\n string,\n {\n modelName: string;\n fields: Record<string, Field>;\n indexes?: readonly {\n fields: readonly string[];\n unique?: boolean | undefined;\n }[];\n }\n>;\ntype Field = {\n type: string | readonly string[];\n required?: boolean | undefined;\n unique?: boolean | undefined;\n index?: boolean | undefined;\n bigint?: boolean | undefined;\n fieldName?: string | undefined;\n defaultValue?: unknown;\n references?:\n | { model: string; field: string; onDelete?: string | undefined }\n | undefined;\n};\n\nconst escapeLike = (value: unknown): string =>\n String(value).replace(/[\\\\%_]/g, (character) => `\\\\${character}`);\n\nconst predicate = (row: Loose, clause: CleanedWhere) => {\n const column = row[clause.field];\n\n if (!column) {\n throw new Error(\n `symmetria: better-auth asked for field \"${clause.field}\", which the table does not have`,\n );\n }\n\n const insensitive =\n clause.mode === \"insensitive\" && typeof clause.value === \"string\";\n const pattern = (text: string) =>\n insensitive ? column.ilike(text) : column.like(text);\n\n switch (clause.operator) {\n case \"ne\":\n return insensitive\n ? not(column.ilike(escapeLike(clause.value)))\n : column.isNot(clause.value);\n case \"in\":\n return column.in(clause.value);\n case \"not_in\":\n return column.notIn(clause.value);\n case \"gt\":\n return column.above(clause.value);\n case \"gte\":\n return column.atLeast(clause.value);\n case \"lt\":\n return column.below(clause.value);\n case \"lte\":\n return column.atMost(clause.value);\n case \"contains\":\n return pattern(`%${escapeLike(clause.value)}%`);\n case \"starts_with\":\n return pattern(`${escapeLike(clause.value)}%`);\n case \"ends_with\":\n return pattern(`%${escapeLike(clause.value)}`);\n default:\n return insensitive\n ? column.ilike(escapeLike(clause.value))\n : column.is(clause.value);\n }\n};\n\n/** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */\nconst filter = (where: readonly CleanedWhere[] | undefined) => (row: Loose) => {\n const clauses = where ?? [];\n const all = clauses\n .filter((clause) => clause.connector !== \"OR\")\n .map((clause) => predicate(row, clause));\n const any = clauses\n .filter((clause) => clause.connector === \"OR\")\n .map((clause) => predicate(row, clause));\n\n return and(...all, any.length > 0 ? or(...any) : undefined);\n};\n\nconst COLUMN_TYPES: Readonly<Record<string, string>> = {\n string: \"text\",\n boolean: \"bool\",\n date: \"timestamptz\",\n json: \"jsonb\",\n \"string[]\": \"text.array\",\n \"number[]\": \"int.array\",\n};\n\nconst snakeCase = (name: string): string =>\n name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n\n/**\n * The auth tables as a Symmetria schema module, for `npx auth generate`.\n * Tables come out in an order where each one follows the tables it\n * references; spread `authTables` into `schema({ ... })`.\n */\nexport const authSchemaSource = (tables: Tables): string => {\n const builders = new Set<string>([\"table\", \"text\"]);\n const models = Object.values(tables);\n const nameOf = (model: string): string =>\n tables[model]?.modelName ??\n models.find((entry) => entry.modelName === model)?.modelName ??\n model;\n const ordered: typeof models = [];\n const pending = [...models];\n\n // References first; a cycle keeps the order better-auth gave.\n while (pending.length) {\n const next =\n pending.find((entry) =>\n Object.values(entry.fields).every(\n (field) =>\n !field.references ||\n nameOf(field.references.model) === entry.modelName ||\n ordered.some(\n (done) => done.modelName === nameOf(field.references!.model),\n ),\n ),\n ) ?? pending[0]!;\n\n ordered.push(next);\n pending.splice(pending.indexOf(next), 1);\n }\n\n const declarations = ordered.map((entry) => {\n const targets = Object.values(entry.fields).flatMap((field) =>\n field.references ? [nameOf(field.references.model)] : [],\n );\n const lines = Object.entries(entry.fields).map(([key, field]) => {\n const named =\n field.fieldName &&\n field.fieldName !== key &&\n field.fieldName !== snakeCase(key)\n ? `.named(${JSON.stringify(field.fieldName)})`\n : \"\";\n const reference = field.references;\n\n if (reference && reference.field === \"id\" && key.endsWith(\"Id\")) {\n const target = nameOf(reference.model);\n // better-auth's own migrations cascade when a reference names no action.\n const action =\n reference.onDelete === undefined || reference.onDelete === \"cascade\"\n ? \"cascade\"\n : reference.onDelete === \"set null\"\n ? \"setNull\"\n : undefined;\n const relation = key.slice(0, -2);\n const self = target === entry.modelName;\n\n // Two keys to one table need names for their reverse sides.\n if (targets.filter((name) => name === target).length > 1 || self) {\n if (self) {\n builders.add(\"self\");\n }\n\n return ` ${relation}: ${self ? \"self\" : target}${field.required === false || action === \"setNull\" ? \".nullable\" : \"\"}${field.unique ? \".unique\" : \".index\"}${action ? `.onDelete.${action}` : \"\"}.inverse(${JSON.stringify(`${entry.modelName}By${relation[0]!.toUpperCase()}${relation.slice(1)}`)}),`;\n }\n\n const claim =\n field.required === false || action === \"setNull\" ? \"maybe\" : \"one\";\n\n builders.add(claim);\n\n return ` ${relation}: ${claim}(${target})${action ? `.${action}` : \"\"}${field.unique ? \".unique\" : \"\"},`;\n }\n\n let type: string;\n\n if (Array.isArray(field.type)) {\n builders.add(\"oneOf\");\n type = `oneOf(${field.type.map((value) => JSON.stringify(value)).join(\", \")})`;\n } else if (field.type === \"number\") {\n type = field.bigint ? \"bigint\" : \"int\";\n } else {\n type = COLUMN_TYPES[field.type as string] ?? \"text\";\n }\n\n builders.add(type.split(/[.(]/)[0]!);\n\n const fallback = field.defaultValue;\n const literal =\n typeof fallback === \"string\" ||\n typeof fallback === \"number\" ||\n typeof fallback === \"boolean\"\n ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})`\n : \"\";\n\n return ` ${key}: ${type}${named}${field.required === false ? \".nullable\" : \"\"}${field.unique ? \".unique\" : \"\"}${field.index && !field.unique ? \".index\" : \"\"}${literal},`;\n });\n const indexes = (entry.indexes ?? []).filter(\n (definition) => definition.fields.length > 1,\n );\n\n if (indexes.length) {\n builders.add(\"index\");\n }\n\n return [\n `export const ${entry.modelName} = table({`,\n \" id: text,\",\n ...lines,\n indexes.length\n ? `}).indexes((${entry.modelName}) => ({\\n${indexes\n .map(\n (definition) =>\n ` ${definition.fields.join(\"_\").replace(/_(\\w)/g, (_match, letter: string) => letter.toUpperCase())}: index(${definition.fields.map((name) => `${entry.modelName}.${name}`).join(\", \")})${definition.unique ? \".unique\" : \"\"},`,\n )\n .join(\"\\n\")}\\n}));`\n : \"});\",\n ].join(\"\\n\");\n });\n\n return [\n \"// Written by `auth generate` through symmetria/better-auth.\",\n \"// Spread `authTables` into your schema: schema({ ...authTables, posts, … }).\",\n `import { ${[...builders].sort().join(\", \")} } from \"symmetria\";`,\n \"\",\n declarations.join(\"\\n\\n\"),\n \"\",\n `export const authTables = { ${ordered.map((entry) => entry.modelName).join(\", \")} };`,\n \"\",\n ].join(\"\\n\");\n};\n\n/**\n * `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a\n * `$scope()` of it) whose schema holds the auth tables; better-auth's own\n * transactions run inside `db.$transaction`.\n */\nexport const symmetriaAdapter = (\n db: object,\n options: SymmetriaAdapterOptions = {},\n) => {\n // What better-auth hands the adapter, kept for the adapters built around a transaction.\n let authOptions: BetterAuthOptions | undefined;\n\n const build = (connection: Loose): ReturnType<typeof createAdapterFactory> =>\n createAdapterFactory({\n config: {\n adapterId: \"symmetria\",\n adapterName: \"Symmetria\",\n usePlural: options.usePlural ?? false,\n debugLogs: options.debugLogs ?? false,\n supportsDates: true,\n supportsBooleans: true,\n supportsJSON: true,\n supportsArrays: true,\n transaction: (callback) =>\n connection.$transaction((transaction: Loose) =>\n callback(build(transaction)(authOptions ?? {}) as never),\n ),\n },\n adapter: () => {\n const table = (model: string) => {\n const handle = connection[model];\n\n if (!handle) {\n throw new Error(\n `symmetria: better-auth uses a table \"${model}\" that the schema does not have; run \\`npx auth generate\\` and add it`,\n );\n }\n\n return handle;\n };\n // An UPDATE or DELETE without a filter is refused unless spelled\n // out; better-auth means every row when it sends none.\n const filtered = (\n mutation: Loose,\n where: readonly CleanedWhere[] | undefined,\n ) => (where?.length ? mutation.where(filter(where)) : mutation.all());\n\n return {\n create: ({ model, data }) => table(model).insert(data).returning(),\n\n findOne: ({ model, where }) =>\n table(model)({ where: filter(where), limit: 1 }).first(),\n\n findMany: ({ model, where, limit, offset, sortBy }) =>\n table(model)({\n where: filter(where),\n limit,\n offset,\n orderBy: sortBy\n ? { [sortBy.field]: sortBy.direction }\n : undefined,\n }),\n\n count: ({ model, where }) =>\n table(model)({ where: filter(where) }).count(),\n\n update: async ({ model, where, update }) => {\n const [row] = await filtered(\n table(model).update(update),\n where,\n ).returning();\n\n return row ?? null;\n },\n\n updateMany: async ({ model, where, update }) =>\n (await filtered(table(model).update(update), where)).affectedRows,\n\n delete: async ({ model, where }) => {\n await filtered(table(model).delete(), where);\n },\n\n deleteMany: async ({ model, where }) =>\n (await filtered(table(model).delete(), where)).affectedRows,\n\n // One row at most: the DELETE by key decides which of two\n // concurrent callers gets it.\n consumeOne: async ({ model, where }) => {\n const found = await table(model)({\n where: filter(where),\n limit: 1,\n }).first();\n\n if (!found) {\n return null;\n }\n\n const [row] = await table(model)\n .byId(found.id)\n .delete()\n .returning();\n\n return row ?? null;\n },\n\n incrementOne: async ({ model, where, increment, set }) => {\n const [row] = await table(model)\n .update((current: Loose) => ({\n ...set,\n ...Object.fromEntries(\n Object.entries(increment).map(([field, delta]) => [\n field,\n current[field].plus(delta),\n ]),\n ),\n }))\n .where(filter(where))\n .returning();\n\n return row ?? null;\n },\n\n createSchema: async ({ tables, file }) => ({\n code: authSchemaSource(tables as Tables),\n path: file ?? \"./auth-schema.ts\",\n overwrite: true,\n }),\n };\n },\n });\n\n const adapter = build(db);\n\n return (betterAuthOptions: BetterAuthOptions) => {\n authOptions = betterAuthOptions;\n\n return adapter(betterAuthOptions);\n };\n};\n"],"mappings":";;;AAgDA,MAAM,cAAc,UAClB,OAAO,KAAK,CAAC,CAAC,QAAQ,YAAY,cAAc,KAAK,WAAW;AAElE,MAAM,aAAa,KAAY,WAAyB;CACtD,MAAM,SAAS,IAAI,OAAO;CAE1B,IAAI,CAAC,QACH,MAAM,IAAI,MACR,2CAA2C,OAAO,MAAM,iCAC1D;CAGF,MAAM,cACJ,OAAO,SAAS,iBAAiB,OAAO,OAAO,UAAU;CAC3D,MAAM,WAAW,SACf,cAAc,OAAO,MAAM,IAAI,IAAI,OAAO,KAAK,IAAI;CAErD,QAAQ,OAAO,UAAf;EACE,KAAK,MACH,OAAO,c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CAAC,MAAM;KAET,IAAI,CAAC,OACH,OAAO;KAGT,MAAM,CAAC,OAAO,MAAM,MAAM,KAAK,CAAC,CAC7B,KAAK,MAAM,EAAE,CAAC,CACd,OAAO,CAAC,CACR,UAAU;KAEb,OAAO,OAAO;IAChB;IAEA,cAAc,OAAO,EAAE,OAAO,OAAO,WAAW,UAAU;KACxD,MAAM,CAAC,OAAO,MAAM,MAAM,KAAK,CAAC,CAC7B,QAAQ,aAAoB;MAC3B,GAAG;MACH,GAAG,OAAO,YACR,OAAO,QAAQ,SAAS,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAChD,OACA,QAAQ,MAAM,CAAC,KAAK,KAAK,CAC3B,CAAC,CACH;KACF,EAAE,CAAC,CACF,MAAM,OAAO,KAAK,CAAC,CAAC,CACpB,UAAU;KAEb,OAAO,OAAO;IAChB;IAEA,cAAc,OAAO,EAAE,QAAQ,YAAY;KACzC,MAAM,iBAAiB,MAAgB;KACvC,MAAM,QAAQ;KACd,WAAW;IACb;GACF;EACF;CACF,CAAC;CAEH,MAAM,UAAU,MAAM,EAAE;CAExB,QAAQ,sBAAyC;EAC/C,cAAc;EAEd,OAAO,QAAQ,iBAAiB;CAClC;AACF"}
|
package/dist/bun.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { c as SessionDriver, l as TransactionDriver, r as Driver } from "./types-
|
|
2
|
-
import {
|
|
3
|
-
import { t as PostgresDriver } from "./pool-BSiopqlE.js";
|
|
1
|
+
import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-pQCOrPh-.js";
|
|
2
|
+
import { t as PostgresDriver } from "./pool-yxHoV4wf.js";
|
|
4
3
|
import { SQL } from "bun";
|
|
5
4
|
//#region src/driver/bun.d.ts
|
|
6
5
|
type PostgresOptions = Omit<SQL.PostgresOrMySQLOptions, "adapter" | "bigint"> & {
|
package/dist/cohere.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-pQCOrPh-.js";
|
|
2
|
+
//#region src/entries/cohere.d.ts
|
|
3
|
+
export type CohereOptions = {
|
|
4
|
+
readonly apiKey?: string;
|
|
5
|
+
/** Embedding length; sent as `output_dimension`, which embed-v4.0 accepts. */
|
|
6
|
+
readonly size?: number;
|
|
7
|
+
readonly baseUrl?: string;
|
|
8
|
+
};
|
|
9
|
+
export declare const cohere: (model: string, options?: CohereOptions) => ((...sources: SelectedColumn<string | null, string>[]) => MeaningSearch) & {
|
|
10
|
+
readonly model: EmbeddingModel;
|
|
11
|
+
};
|
|
12
|
+
export declare const embedV4: ((...sources: SelectedColumn<string | null, string>[]) => MeaningSearch) & {
|
|
13
|
+
readonly model: EmbeddingModel;
|
|
14
|
+
};
|
|
15
|
+
export declare const embedMultilingualV3: ((...sources: SelectedColumn<string | null, string>[]) => MeaningSearch) & {
|
|
16
|
+
readonly model: EmbeddingModel;
|
|
17
|
+
};
|
|
18
|
+
//#endregion
|
|
19
|
+
//# sourceMappingURL=cohere.d.ts.map
|
package/dist/cohere.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { r as embedder } from "./search-BEk0Ff_y.js";
|
|
2
|
+
import { i as postJson, r as inBatches, t as apiKey } from "./http-o1fpnTNy.js";
|
|
3
|
+
//#region src/entries/cohere.ts
|
|
4
|
+
/**
|
|
5
|
+
* `symmetria/cohere`: Cohere embedding models for `.search()`:
|
|
6
|
+
* `meaning: embedV4(chunk.title, chunk.content)`. The key is read from
|
|
7
|
+
* `COHERE_API_KEY` unless given.
|
|
8
|
+
*/
|
|
9
|
+
/** Cohere embeds at most 96 texts per request. */
|
|
10
|
+
const BATCH = 96;
|
|
11
|
+
/** Lengths of the models that have one; embed-v4.0 is asked for its length. */
|
|
12
|
+
const SIZES = {
|
|
13
|
+
"embed-v4.0": 1536,
|
|
14
|
+
"embed-multilingual-v3.0": 1024,
|
|
15
|
+
"embed-english-v3.0": 1024,
|
|
16
|
+
"embed-multilingual-light-v3.0": 384,
|
|
17
|
+
"embed-english-light-v3.0": 384
|
|
18
|
+
};
|
|
19
|
+
const cohere = (model, options = {}) => {
|
|
20
|
+
const size = options.size ?? SIZES[model];
|
|
21
|
+
if (size === void 0) throw new Error(`symmetria: the embedding length of "${model}" is not known; pass cohere("${model}", { size })`);
|
|
22
|
+
return embedder(size, (texts, kind) => inBatches(texts, BATCH, async (batch) => (await postJson("Cohere", model, `${options.baseUrl ?? "https://api.cohere.com/v2"}/embed`, { Authorization: `Bearer ${apiKey("Cohere", model, options.apiKey, "COHERE_API_KEY")}` }, {
|
|
23
|
+
model,
|
|
24
|
+
texts: batch,
|
|
25
|
+
input_type: kind === "query" ? "search_query" : "search_document",
|
|
26
|
+
embedding_types: ["float"],
|
|
27
|
+
...options.size !== void 0 || model === "embed-v4.0" ? { output_dimension: size } : {}
|
|
28
|
+
})).embeddings.float), { name: model });
|
|
29
|
+
};
|
|
30
|
+
const embedV4 = cohere("embed-v4.0");
|
|
31
|
+
const embedMultilingualV3 = cohere("embed-multilingual-v3.0");
|
|
32
|
+
//#endregion
|
|
33
|
+
export { cohere, embedMultilingualV3, embedV4 };
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=cohere.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cohere.js","names":[],"sources":["../src/entries/cohere.ts"],"sourcesContent":["/**\n * `symmetria/cohere`: Cohere embedding models for `.search()`:\n * `meaning: embedV4(chunk.title, chunk.content)`. The key is read from\n * `COHERE_API_KEY` unless given.\n */\nimport { apiKey, inBatches, postJson } from \"../embedders/http\";\nimport { embedder } from \"../schema/search\";\n\n/** Cohere embeds at most 96 texts per request. */\nconst BATCH = 96;\n/** Lengths of the models that have one; embed-v4.0 is asked for its length. */\nconst SIZES: Readonly<Record<string, number>> = {\n \"embed-v4.0\": 1536,\n \"embed-multilingual-v3.0\": 1024,\n \"embed-english-v3.0\": 1024,\n \"embed-multilingual-light-v3.0\": 384,\n \"embed-english-light-v3.0\": 384,\n};\n\nexport type CohereOptions = {\n readonly apiKey?: string;\n /** Embedding length; sent as `output_dimension`, which embed-v4.0 accepts. */\n readonly size?: number;\n readonly baseUrl?: string;\n};\n\nexport const cohere = (model: string, options: CohereOptions = {}) => {\n const size = options.size ?? SIZES[model];\n\n if (size === undefined) {\n throw new Error(\n `symmetria: the embedding length of \"${model}\" is not known; pass cohere(\"${model}\", { size })`,\n );\n }\n\n return embedder(\n size,\n (texts, kind) =>\n inBatches(\n texts,\n BATCH,\n async (batch) =>\n (\n await postJson<{ embeddings: { float: number[][] } }>(\n \"Cohere\",\n model,\n `${options.baseUrl ?? \"https://api.cohere.com/v2\"}/embed`,\n {\n Authorization: `Bearer ${apiKey(\"Cohere\", model, options.apiKey, \"COHERE_API_KEY\")}`,\n },\n {\n model,\n texts: batch,\n input_type:\n kind === \"query\" ? \"search_query\" : \"search_document\",\n embedding_types: [\"float\"],\n ...(options.size !== undefined || model === \"embed-v4.0\"\n ? { output_dimension: size }\n : {}),\n },\n )\n ).embeddings.float,\n ),\n { name: model },\n );\n};\n\nexport const embedV4 = cohere(\"embed-v4.0\");\nexport const embedMultilingualV3 = cohere(\"embed-multilingual-v3.0\");\n"],"mappings":";;;;;;;;;AASA,MAAM,QAAQ;;AAEd,MAAM,QAA0C;CAC9C,cAAc;CACd,2BAA2B;CAC3B,sBAAsB;CACtB,iCAAiC;CACjC,4BAA4B;AAC9B;AASA,MAAa,UAAU,OAAe,UAAyB,CAAC,MAAM;CACpE,MAAM,OAAO,QAAQ,QAAQ,MAAM;CAEnC,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MACR,uCAAuC,MAAM,+BAA+B,MAAM,aACpF;CAGF,OAAO,SACL,OACC,OAAO,SACN,UACE,OACA,OACA,OAAO,WAEH,MAAM,SACJ,UACA,OACA,GAAG,QAAQ,WAAW,4BAA4B,SAClD,EACE,eAAe,UAAU,OAAO,UAAU,OAAO,QAAQ,QAAQ,gBAAgB,IACnF,GACA;EACE;EACA,OAAO;EACP,YACE,SAAS,UAAU,iBAAiB;EACtC,iBAAiB,CAAC,OAAO;EACzB,GAAI,QAAQ,SAAS,KAAA,KAAa,UAAU,eACxC,EAAE,kBAAkB,KAAK,IACzB,CAAC;CACP,CACF,EAAA,CACA,WAAW,KACjB,GACF,EAAE,MAAM,MAAM,CAChB;AACF;AAEA,MAAa,UAAU,OAAO,YAAY;AAC1C,MAAa,sBAAsB,OAAO,yBAAyB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { a as containsBinding, c as numberedAlias, f as cloneParameter, g as createRowDecoder, o as mergeBindings, s as normalizeResult, t as DEFAULT_VALUE, u as bigintCodec, w as throwDataErrors, y as numericCodec } from "./types-DPWc6nQ9.js";
|
|
2
|
-
import {
|
|
2
|
+
import { $ as tsvectorSql, G as parameter, J as searchHeadlineSql, K as quoteIdentifier, Q as tsquerySql, U as aliasSql, W as createCompilation, X as searchVectorSql, Y as searchRankSql, Z as sqlString, q as renderContext } from "./table-Bx_6J15y.js";
|
|
3
3
|
import { c as scopeViolationText } from "./binding-BiJH76XX.js";
|
|
4
|
+
import { I as freeze, M as expressionSqlType, N as childNodes, P as containsNode } from "./core-DxXVTy9r.js";
|
|
4
5
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
6
|
import { randomUUID, timingSafeEqual } from "node:crypto";
|
|
6
7
|
import { createServer } from "node:http";
|
|
@@ -1232,4 +1233,4 @@ const rowDecoder = (plan) => {
|
|
|
1232
1233
|
//#endregion
|
|
1233
1234
|
export { currentScopes as a, rowDecoder as c, executorProfiling as d, postgresRenderer as f, compileTemplate as i, batchCollectors as l, compileQuery as n, executeCompiled as o, compileShape as r, executePlan as s, compilePlan as t, createProfiler as u };
|
|
1234
1235
|
|
|
1235
|
-
//# sourceMappingURL=compile-
|
|
1236
|
+
//# sourceMappingURL=compile-R1_PBIgc.js.map
|