symmetria 3.4.1 → 3.6.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 -28
- package/dist/better-auth.d.ts +8 -2
- package/dist/better-auth.js +321 -63
- package/dist/better-auth.js.map +1 -1
- package/dist/{pool-IYDUq-NI.js → binding-QAk-KW4L.js} +84 -209
- package/dist/binding-QAk-KW4L.js.map +1 -0
- package/dist/bun.d.ts +2 -2
- package/dist/bun.js +32 -13
- package/dist/bun.js.map +1 -1
- package/dist/cohere.d.ts +3 -2
- package/dist/cohere.js +4 -3
- package/dist/cohere.js.map +1 -1
- package/dist/{compile-DGX9ghGd.js → compile-D02-A2r9.js} +202 -55
- package/dist/compile-D02-A2r9.js.map +1 -0
- package/dist/{core-BPJgSfz7.js → core-BHndSuCB.js} +319 -179
- package/dist/core-BHndSuCB.js.map +1 -0
- package/dist/driver.d.ts +3 -3
- package/dist/driver.js +2 -2
- package/dist/{errors-D7nAgODm.js → errors-CLFkJWgJ.js} +13 -8
- package/dist/errors-CLFkJWgJ.js.map +1 -0
- package/dist/google.d.ts +3 -2
- package/dist/google.js +4 -3
- package/dist/google.js.map +1 -1
- package/dist/http-BHV8rkKW.d.ts +16 -0
- package/dist/http-BWqJ9rei.js +75 -0
- package/dist/http-BWqJ9rei.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4731 -655
- package/dist/index.js.map +1 -1
- package/dist/{inspection-JWG1TB4Q.js → inspection-DK0UJaG0.js} +4 -4
- package/dist/{inspection-JWG1TB4Q.js.map → inspection-DK0UJaG0.js.map} +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +4 -4
- package/dist/jina.d.ts +3 -2
- package/dist/jina.js +11 -8
- package/dist/jina.js.map +1 -1
- package/dist/metadata-BzA69T0R.js +148 -0
- package/dist/metadata-BzA69T0R.js.map +1 -0
- package/dist/mistral.d.ts +3 -2
- package/dist/mistral.js +9 -6
- package/dist/mistral.js.map +1 -1
- package/dist/ollama.d.ts +3 -2
- package/dist/ollama.js +40 -9
- package/dist/ollama.js.map +1 -1
- package/dist/openai.d.ts +3 -2
- package/dist/openai.js +4 -3
- package/dist/openai.js.map +1 -1
- package/dist/opentelemetry.d.ts +4 -3
- package/dist/opentelemetry.js +432 -61
- package/dist/opentelemetry.js.map +1 -1
- package/dist/{pg-fs6x4Suq.d.ts → pg-CcmvCsRo.d.ts} +3 -3
- package/dist/{pg-CFLpqlwI.js → pg-DxC503O5.js} +4 -4
- package/dist/{pg-CFLpqlwI.js.map → pg-DxC503O5.js.map} +1 -1
- package/dist/pg.d.ts +3 -3
- package/dist/pg.js +2 -2
- package/dist/pool-BTrHoEWY.js +281 -0
- package/dist/pool-BTrHoEWY.js.map +1 -0
- package/dist/{pool-D9fn_QMV.d.ts → pool-C7rw4zkO.d.ts} +2 -2
- package/dist/{profiling-DJryCjEd.js → profiling-DMJLtQEj.js} +120 -37
- package/dist/profiling-DMJLtQEj.js.map +1 -0
- package/dist/search-BRkAlGfT.js +394 -0
- package/dist/search-BRkAlGfT.js.map +1 -0
- package/dist/search-BeNPJPTA.js +111 -0
- package/dist/search-BeNPJPTA.js.map +1 -0
- package/dist/search.d.ts +1 -1
- package/dist/search.js +1 -1
- package/dist/{table-DpN_w2iS.js → table-AFCbXHL8.js} +224 -72
- package/dist/table-AFCbXHL8.js.map +1 -0
- package/dist/{types-DGEtOzjC.js → types-CBBesvuC.js} +348 -23
- package/dist/types-CBBesvuC.js.map +1 -0
- package/dist/{types-FMTFyI6m.d.ts → types-t7LyUyKP.d.ts} +235 -53
- package/dist/{values-qxAv9Duz.js → values-BxqBvh27.js} +2 -2
- package/dist/{values-qxAv9Duz.js.map → values-BxqBvh27.js.map} +1 -1
- package/dist/vector.d.ts +1 -1
- package/dist/vector.js +2 -2
- package/dist/voyage.d.ts +3 -2
- package/dist/voyage.js +14 -10
- package/dist/voyage.js.map +1 -1
- package/package.json +1 -1
- package/dist/binding-CD-0xNaB.js +0 -12
- package/dist/binding-CD-0xNaB.js.map +0 -1
- package/dist/compile-DGX9ghGd.js.map +0 -1
- package/dist/core-BPJgSfz7.js.map +0 -1
- package/dist/errors-D7nAgODm.js.map +0 -1
- package/dist/freeze-D2-KMR2m.js +0 -12
- package/dist/freeze-D2-KMR2m.js.map +0 -1
- package/dist/http-o1fpnTNy.js +0 -33
- package/dist/http-o1fpnTNy.js.map +0 -1
- package/dist/pool-IYDUq-NI.js.map +0 -1
- package/dist/profiling-DJryCjEd.js.map +0 -1
- package/dist/search-DC9dfaK9.js +0 -174
- package/dist/search-DC9dfaK9.js.map +0 -1
- package/dist/search-ks_yELtx.js +0 -47
- package/dist/search-ks_yELtx.js.map +0 -1
- package/dist/table-DpN_w2iS.js.map +0 -1
- package/dist/types-DGEtOzjC.js.map +0 -1
package/README.md
CHANGED
|
@@ -179,10 +179,11 @@ const page = feed({ limit: 10 });
|
|
|
179
179
|
|
|
180
180
|
`join`, `innerJoin` and `leftJoin` infer the target and ON condition from a
|
|
181
181
|
relation or FK column. Smart `join` uses INNER for required forward references
|
|
182
|
-
and LEFT for optional/reverse relations
|
|
183
|
-
automatic aliases. Explicit sources use
|
|
184
|
-
|
|
185
|
-
|
|
182
|
+
and LEFT for optional/reverse relations and for a target a `$scope()` filters.
|
|
183
|
+
Repeated sources and self-JOINs receive automatic aliases. Explicit sources use
|
|
184
|
+
an ON callback; a query with its own fields or options joins only as a subquery
|
|
185
|
+
named with `.as("name")`. `crossJoin` creates a Cartesian product. Options-only
|
|
186
|
+
calls preserve the previous selection; branches are immutable.
|
|
186
187
|
|
|
187
188
|
Smart JOINs also use LEFT for junction relations and propagate optional
|
|
188
189
|
ancestry. `crossJoin` can infer its target from an FK or relation, without an ON
|
|
@@ -205,8 +206,8 @@ const feed = db.posts((post) => ({
|
|
|
205
206
|
```
|
|
206
207
|
|
|
207
208
|
`.shape()` stores a synchronous callback and evaluates it on each application. A
|
|
208
|
-
projection belongs to its defining table
|
|
209
|
-
|
|
209
|
+
projection belongs to its defining table and selects at least one field; field
|
|
210
|
+
names starting with `$` are reserved. Apply options at use sites, for example
|
|
210
211
|
`db.users(userCard, { limit: 20 })`. It can be defined on an offline schema and
|
|
211
212
|
used on its connected or transaction-bound tables. To-one selections are typed
|
|
212
213
|
as an object or `null`.
|
|
@@ -229,11 +230,11 @@ const totals = db.users(({ name, posts }) => ({
|
|
|
229
230
|
|
|
230
231
|
Plain columns aggregate through properties (`posts.sum.views`); expressions use
|
|
231
232
|
the callback form. Filters and pagination select input rows before aggregation.
|
|
232
|
-
`sum` / `average` return decimal strings or `null
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
all-NULL value inputs produce `null`; `count()` returns `0`
|
|
236
|
-
returns `false` for empty inputs.
|
|
233
|
+
`sum` / `average` return decimal strings or `null`. `minimum` / `maximum` keep
|
|
234
|
+
the column's value type and codec, plus `null`, and take any column: booleans,
|
|
235
|
+
`uuid` and `bytea` too, and JSON values, which they order as jsonb does (numbers
|
|
236
|
+
by value). Empty or all-NULL value inputs produce `null`; `count()` returns `0`
|
|
237
|
+
and `exists()` returns `false` for empty inputs.
|
|
237
238
|
|
|
238
239
|
## Enum mappings
|
|
239
240
|
|
|
@@ -278,7 +279,8 @@ projection of the same table. UPDATE, WHERE and RETURNING callbacks receive the
|
|
|
278
279
|
row directly, including nested-insert RETURNING. Upserts receive the existing
|
|
279
280
|
row first and the proposed `excluded` row second. `.doUpdate("name")` copies a
|
|
280
281
|
field from `excluded`. An UPDATE or DELETE without `where()` is refused unless
|
|
281
|
-
`.all()` confirms it
|
|
282
|
+
`.all()` confirms it, and so is one whose filter holds for every row, such as
|
|
283
|
+
`and()` or `notIn([])`.
|
|
282
284
|
|
|
283
285
|
## Capabilities
|
|
284
286
|
|
|
@@ -299,10 +301,12 @@ field from `excluded`. An UPDATE or DELETE without `where()` is refused unless
|
|
|
299
301
|
iteration; `count()` and `exists()` on any table or filtered source.
|
|
300
302
|
- Transactions, nested savepoints, isolation options and row locks.
|
|
301
303
|
- `Transaction<typeof db>` for schema-specific transaction helpers.
|
|
302
|
-
- `$scope()` filters for reads, updates and deletes, including related
|
|
303
|
-
and checks every row a scoped insert, upsert or update writes,
|
|
304
|
-
security's `WITH CHECK` (`SYMMETRIA_OUT_OF_SCOPE`); reused and
|
|
305
|
-
queries bind the current tenant at every execution.
|
|
304
|
+
- `$scope()` filters for reads, updates and deletes, including related and
|
|
305
|
+
joined tables, and checks every row a scoped insert, upsert or update writes,
|
|
306
|
+
like row-level security's `WITH CHECK` (`SYMMETRIA_OUT_OF_SCOPE`); reused and
|
|
307
|
+
prepared queries bind the current tenant at every execution. A scope filter
|
|
308
|
+
that holds for every row, such as `and(tenant && post.tenantId.is(tenant))`
|
|
309
|
+
without a tenant, is refused instead of reading every tenant's rows.
|
|
306
310
|
- Bigint, decimal-string, Date and custom codecs, including nested JSON results;
|
|
307
311
|
`smallint`, `real`, `doublePrecision`, `date`, `time`, `interval`, `bytea` and
|
|
308
312
|
`inet` as first-class builders.
|
|
@@ -324,13 +328,13 @@ field from `excluded`. An UPDATE or DELETE without `where()` is refused unless
|
|
|
324
328
|
- `table.search()`: hybrid search declared on the table, by words (full text or
|
|
325
329
|
BM25) and by meaning (embeddings computed on insert), merged in one statement
|
|
326
330
|
(`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
|
|
331
|
+
`google`, `mistral`, `jina`, `ollama`).
|
|
332
|
+
- `symmetria/better-auth`: a better-auth adapter; `npx auth generate` writes the
|
|
333
|
+
auth tables as part of your schema.
|
|
330
334
|
- Arrays, full-text search with stored `tsvector` columns, weighted documents,
|
|
331
335
|
ranking and headlines, pgvector embeddings with distance operators and HNSW
|
|
332
|
-
indexes (`symmetria/vector`), typed JSON paths and Standard Schema
|
|
333
|
-
validation.
|
|
336
|
+
and IVFFlat indexes (`symmetria/vector`), typed JSON paths and Standard Schema
|
|
337
|
+
JSON validation.
|
|
334
338
|
- Computed fields, branded IDs, indexes, primary keys and CHECK constraints.
|
|
335
339
|
- Condition relations (`.relations()`) that join by a predicate without a
|
|
336
340
|
foreign key, in both directions, invisible to migrations.
|
|
@@ -384,13 +388,15 @@ const db = createDatabase({
|
|
|
384
388
|
underlying pool options plus `url` and `profiler`.
|
|
385
389
|
|
|
386
390
|
Both adapters return `{ rows, affectedRows }`, read values the same way,
|
|
387
|
-
preserve bigint/numeric precision
|
|
388
|
-
sessions
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
391
|
+
preserve bigint/numeric precision and support nested transactions and pinned
|
|
392
|
+
sessions. On close they refuse new work, end the transactions of open `stream()`
|
|
393
|
+
loops and wait for the other operations they accepted. Operations on a
|
|
394
|
+
transaction or session run one at a time in call order. Session settings belong
|
|
395
|
+
to a connection: use `driver.session()` for multi-statement workflows; its
|
|
396
|
+
connection is closed afterwards, so its settings, locks and temporary tables
|
|
397
|
+
never reach other queries. For isolated PostgreSQL test schemas, use
|
|
398
|
+
`testDatabase()` from `symmetria-kit/testing`, optionally passing a `driver`
|
|
399
|
+
factory.
|
|
394
400
|
|
|
395
401
|
Behind a transaction-mode pooler such as PgBouncer, queries, transactions,
|
|
396
402
|
streams and prepared queries work on both adapters; pass `prepare: false` to
|
package/dist/better-auth.d.ts
CHANGED
|
@@ -31,9 +31,15 @@ type Field = {
|
|
|
31
31
|
/**
|
|
32
32
|
* The auth tables as a Symmetria schema module, for `npx auth generate`.
|
|
33
33
|
* Tables come out in an order where each one follows the tables it
|
|
34
|
-
* references; spread `authTables` into `schema({ ... })`.
|
|
34
|
+
* references; spread `authTables` into `schema({ ... })`. With `usePlural`
|
|
35
|
+
* the tables are keyed in the plural (`users`), as the adapter then asks for
|
|
36
|
+
* them; `casing` is the schema's (`"preserve"` keeps a reference key such as
|
|
37
|
+
* `requestedBy` as its SQL name).
|
|
35
38
|
*/
|
|
36
|
-
export declare const authSchemaSource: (
|
|
39
|
+
export declare const authSchemaSource: (input: Tables, options?: {
|
|
40
|
+
readonly usePlural?: boolean;
|
|
41
|
+
readonly casing?: "snake_case" | "preserve";
|
|
42
|
+
}) => string;
|
|
37
43
|
/**
|
|
38
44
|
* `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a
|
|
39
45
|
* `$scope()` of it) whose schema holds the auth tables; better-auth's own
|
package/dist/better-auth.js
CHANGED
|
@@ -1,24 +1,61 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { S as not, T as or, g as coalesce, m as and } from "./core-BHndSuCB.js";
|
|
2
2
|
import { createAdapterFactory } from "better-auth/adapters";
|
|
3
3
|
//#region src/entries/better-auth.ts
|
|
4
4
|
const escapeLike = (value) => String(value).replace(/[\\%_]/g, (character) => `\\${character}`);
|
|
5
|
+
/** `target[key]`, unless it is only what every object inherits (`constructor`). */
|
|
6
|
+
const member = (target, key) => {
|
|
7
|
+
const value = target[key];
|
|
8
|
+
return value === Object.prototype[key] ? void 0 : value;
|
|
9
|
+
};
|
|
10
|
+
/** The column `key` of a row, for better-auth's field `field`. */
|
|
11
|
+
const columnOf = (row, key, field) => {
|
|
12
|
+
const column = member(row, key);
|
|
13
|
+
if (!column) throw new Error(`symmetria: better-auth asked for field "${field}", which the table does not have`);
|
|
14
|
+
return column;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* A where value in the form its field's column compares. better-auth passes
|
|
18
|
+
* request values on as they come (the admin plugin's `filterValue: 1984` for
|
|
19
|
+
* a text field): node-postgres sends a number untyped, which PostgreSQL reads
|
|
20
|
+
* as text, while Bun.SQL binds it as an integer and the comparison fails, so a
|
|
21
|
+
* string field gets a string on every driver. A list for a boolean field
|
|
22
|
+
* reads "true" and "false" as better-auth reads a single value.
|
|
23
|
+
*/
|
|
24
|
+
const comparable = (type, value) => {
|
|
25
|
+
if (Array.isArray(value)) return value.map((item) => comparable(type, item));
|
|
26
|
+
if ((type === "string" || Array.isArray(type)) && (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean")) return String(value);
|
|
27
|
+
return type === "boolean" && (value === "true" || value === "false") ? value === "true" : value;
|
|
28
|
+
};
|
|
29
|
+
const none = (column) => column.in([]);
|
|
5
30
|
const predicate = (row, clause) => {
|
|
6
|
-
const column = row
|
|
7
|
-
|
|
8
|
-
const
|
|
31
|
+
const column = columnOf(row, clause.key, clause.field);
|
|
32
|
+
const { value } = clause;
|
|
33
|
+
const missing = value === void 0 || value === null;
|
|
34
|
+
const insensitive = clause.mode === "insensitive" && typeof value === "string";
|
|
9
35
|
const pattern = (text) => insensitive ? column.ilike(text) : column.like(text);
|
|
10
36
|
switch (clause.operator) {
|
|
11
|
-
case "ne":
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
case "
|
|
15
|
-
case "
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
37
|
+
case "ne":
|
|
38
|
+
if (value === null) return column.isNot(null);
|
|
39
|
+
return value === void 0 ? none(column) : insensitive ? not(column.ilike(escapeLike(value))) : column.isNot(value);
|
|
40
|
+
case "in":
|
|
41
|
+
case "not_in": {
|
|
42
|
+
const list = Array.isArray(value) ? value : [value];
|
|
43
|
+
const present = list.filter((item) => item !== void 0 && item !== null);
|
|
44
|
+
const insensitiveList = clause.mode === "insensitive" && present.length > 0 && present.every((item) => typeof item === "string");
|
|
45
|
+
if (clause.operator === "in") return insensitiveList ? or(...present.map((item) => column.ilike(escapeLike(item)))) : column.in(present);
|
|
46
|
+
if (present.length < list.length) return none(column);
|
|
47
|
+
return insensitiveList ? and(...present.map((item) => not(column.ilike(escapeLike(item))))) : column.notIn(present);
|
|
48
|
+
}
|
|
49
|
+
case "gt": return missing ? none(column) : column.above(value);
|
|
50
|
+
case "gte": return missing ? none(column) : column.atLeast(value);
|
|
51
|
+
case "lt": return missing ? none(column) : column.below(value);
|
|
52
|
+
case "lte": return missing ? none(column) : column.atMost(value);
|
|
53
|
+
case "contains": return missing ? none(column) : pattern(`%${escapeLike(value)}%`);
|
|
54
|
+
case "starts_with": return missing ? none(column) : pattern(`${escapeLike(value)}%`);
|
|
55
|
+
case "ends_with": return missing ? none(column) : pattern(`%${escapeLike(value)}`);
|
|
56
|
+
default:
|
|
57
|
+
if (value === null) return column.is(null);
|
|
58
|
+
return value === void 0 ? none(column) : insensitive ? column.ilike(escapeLike(value)) : column.is(value);
|
|
22
59
|
}
|
|
23
60
|
};
|
|
24
61
|
/** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */
|
|
@@ -36,16 +73,110 @@ const COLUMN_TYPES = {
|
|
|
36
73
|
"string[]": "text.array",
|
|
37
74
|
"number[]": "int.array"
|
|
38
75
|
};
|
|
39
|
-
|
|
76
|
+
/** A key's SQL name under schema()'s default casing (`requestedBy` → `requested_by`). */
|
|
77
|
+
const snakeCase = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
78
|
+
/** Names a module cannot declare: JavaScript's reserved words and what it imports. */
|
|
79
|
+
const TAKEN = /* @__PURE__ */ new Set([
|
|
80
|
+
"arguments",
|
|
81
|
+
"await",
|
|
82
|
+
"break",
|
|
83
|
+
"case",
|
|
84
|
+
"catch",
|
|
85
|
+
"class",
|
|
86
|
+
"const",
|
|
87
|
+
"continue",
|
|
88
|
+
"debugger",
|
|
89
|
+
"default",
|
|
90
|
+
"delete",
|
|
91
|
+
"do",
|
|
92
|
+
"else",
|
|
93
|
+
"enum",
|
|
94
|
+
"eval",
|
|
95
|
+
"export",
|
|
96
|
+
"extends",
|
|
97
|
+
"false",
|
|
98
|
+
"finally",
|
|
99
|
+
"for",
|
|
100
|
+
"function",
|
|
101
|
+
"if",
|
|
102
|
+
"implements",
|
|
103
|
+
"import",
|
|
104
|
+
"in",
|
|
105
|
+
"instanceof",
|
|
106
|
+
"interface",
|
|
107
|
+
"let",
|
|
108
|
+
"new",
|
|
109
|
+
"null",
|
|
110
|
+
"package",
|
|
111
|
+
"private",
|
|
112
|
+
"protected",
|
|
113
|
+
"public",
|
|
114
|
+
"return",
|
|
115
|
+
"static",
|
|
116
|
+
"super",
|
|
117
|
+
"switch",
|
|
118
|
+
"this",
|
|
119
|
+
"throw",
|
|
120
|
+
"true",
|
|
121
|
+
"try",
|
|
122
|
+
"typeof",
|
|
123
|
+
"undefined",
|
|
124
|
+
"var",
|
|
125
|
+
"void",
|
|
126
|
+
"while",
|
|
127
|
+
"with",
|
|
128
|
+
"yield",
|
|
129
|
+
"Infinity",
|
|
130
|
+
"NaN",
|
|
131
|
+
"authTables",
|
|
132
|
+
"bigint",
|
|
133
|
+
"bool",
|
|
134
|
+
"index",
|
|
135
|
+
"int",
|
|
136
|
+
"jsonb",
|
|
137
|
+
"maybe",
|
|
138
|
+
"one",
|
|
139
|
+
"oneOf",
|
|
140
|
+
"self",
|
|
141
|
+
"table",
|
|
142
|
+
"text",
|
|
143
|
+
"timestamptz"
|
|
144
|
+
]);
|
|
145
|
+
/** A JavaScript name for a model: `auth-user` → `authUser`, `default` → `defaultTable`. */
|
|
146
|
+
const identifierOf = (name) => {
|
|
147
|
+
const joined = name.split(/[^\p{ID_Continue}$]+/u).filter(Boolean).map((word, position) => position ? `${word[0].toUpperCase()}${word.slice(1)}` : word).join("");
|
|
148
|
+
const named = /^[\p{ID_Start}$_]/u.test(joined) ? joined : `_${joined}`;
|
|
149
|
+
return TAKEN.has(named) ? `${named}Table` : named;
|
|
150
|
+
};
|
|
151
|
+
/** The relation a reference field becomes: `userId` → `user`, `requestedBy` stays. */
|
|
152
|
+
const relationOf = (key) => key.length > 2 && key.endsWith("Id") ? key.slice(0, -2) : key;
|
|
40
153
|
/**
|
|
41
154
|
* The auth tables as a Symmetria schema module, for `npx auth generate`.
|
|
42
155
|
* Tables come out in an order where each one follows the tables it
|
|
43
|
-
* references; spread `authTables` into `schema({ ... })`.
|
|
156
|
+
* references; spread `authTables` into `schema({ ... })`. With `usePlural`
|
|
157
|
+
* the tables are keyed in the plural (`users`), as the adapter then asks for
|
|
158
|
+
* them; `casing` is the schema's (`"preserve"` keeps a reference key such as
|
|
159
|
+
* `requestedBy` as its SQL name).
|
|
44
160
|
*/
|
|
45
|
-
const authSchemaSource = (
|
|
161
|
+
const authSchemaSource = (input, options = {}) => {
|
|
162
|
+
const tables = options.usePlural ? Object.fromEntries(Object.entries(input).map(([model, entry]) => [model, {
|
|
163
|
+
...entry,
|
|
164
|
+
modelName: `${entry.modelName}s`
|
|
165
|
+
}])) : input;
|
|
46
166
|
const builders = /* @__PURE__ */ new Set(["table", "text"]);
|
|
47
167
|
const models = Object.values(tables);
|
|
48
168
|
const nameOf = (model) => tables[model]?.modelName ?? models.find((entry) => entry.modelName === model)?.modelName ?? model;
|
|
169
|
+
const identifiers = /* @__PURE__ */ new Map();
|
|
170
|
+
const used = /* @__PURE__ */ new Set();
|
|
171
|
+
for (const plain of [true, false]) for (const { modelName } of models) {
|
|
172
|
+
const base = identifierOf(modelName);
|
|
173
|
+
if (base === modelName !== plain || identifiers.has(modelName)) continue;
|
|
174
|
+
let name = base;
|
|
175
|
+
for (let count = 2; used.has(name); count++) name = `${base}${count}`;
|
|
176
|
+
used.add(name);
|
|
177
|
+
identifiers.set(modelName, name);
|
|
178
|
+
}
|
|
179
|
+
const identifier = (modelName) => identifiers.get(modelName) ?? modelName;
|
|
49
180
|
const ordered = [];
|
|
50
181
|
const pending = [...models];
|
|
51
182
|
while (pending.length) {
|
|
@@ -54,22 +185,43 @@ const authSchemaSource = (tables) => {
|
|
|
54
185
|
pending.splice(pending.indexOf(next), 1);
|
|
55
186
|
}
|
|
56
187
|
const declarations = ordered.map((entry) => {
|
|
57
|
-
const
|
|
58
|
-
const
|
|
59
|
-
|
|
188
|
+
const name = identifier(entry.modelName);
|
|
189
|
+
const fields = entry.fields;
|
|
190
|
+
const columnKey = (key) => fields[key]?.references ? `${relationOf(key)}Id` : key;
|
|
191
|
+
const single = /* @__PURE__ */ new Map();
|
|
192
|
+
const composite = [];
|
|
193
|
+
for (const definition of entry.indexes ?? []) {
|
|
194
|
+
const [only, ...others] = definition.fields;
|
|
195
|
+
if (only !== void 0 && !others.length && Object.hasOwn(fields, only)) single.set(only, single.get(only) === true || definition.unique === true);
|
|
196
|
+
else composite.push(definition);
|
|
197
|
+
}
|
|
198
|
+
const targets = Object.values(fields).flatMap((field) => field.references ? [nameOf(field.references.model)] : []);
|
|
199
|
+
const lines = Object.entries(fields).map(([key, field]) => {
|
|
200
|
+
const sqlName = field.fieldName && field.fieldName !== key ? field.fieldName : void 0;
|
|
201
|
+
const unique = field.unique === true || single.get(key) === true;
|
|
60
202
|
const reference = field.references;
|
|
61
|
-
if (reference
|
|
203
|
+
if (reference) {
|
|
62
204
|
const target = nameOf(reference.model);
|
|
63
|
-
const
|
|
64
|
-
const
|
|
205
|
+
const relation = relationOf(key);
|
|
206
|
+
const clash = [relation, `${relation}Id`].find((other) => other !== key && Object.hasOwn(fields, other));
|
|
207
|
+
if (clash) throw new Error(`symmetria: ${entry.modelName}.${key} references ${target} and becomes the relation "${relation}" with the key "${relation}Id", but ${entry.modelName} has another field "${clash}"; rename one of the two`);
|
|
208
|
+
const column = sqlName ?? (relation === key ? options.casing === "preserve" ? key : snakeCase(key) : void 0);
|
|
209
|
+
const keyColumn = column === void 0 ? "" : `.column(${JSON.stringify(column)})`;
|
|
210
|
+
const targetFields = models.find((model) => model.modelName === target)?.fields;
|
|
211
|
+
const targetKey = reference.field === "id" || !targetFields || Object.hasOwn(targetFields, reference.field) ? reference.field : Object.entries(targetFields).find(([, candidate]) => candidate.fieldName === reference.field)?.[0] ?? reference.field;
|
|
212
|
+
const by = targetKey === "id" ? "" : `.by(${JSON.stringify(targetFields?.[targetKey]?.references ? `${relationOf(targetKey)}Id` : targetKey)})`;
|
|
213
|
+
const action = reference.onDelete === void 0 || reference.onDelete === "cascade" ? "cascade" : reference.onDelete === "set null" || reference.onDelete === "set default" && field.required === false ? "setNull" : reference.onDelete === "no action" || reference.onDelete === "set default" ? "noAction" : void 0;
|
|
214
|
+
const nullable = field.required === false || action === "setNull";
|
|
65
215
|
const self = target === entry.modelName;
|
|
66
|
-
|
|
216
|
+
const shared = targets.filter((other) => other === target).length > 1;
|
|
217
|
+
if (shared || self || action === "noAction") {
|
|
67
218
|
if (self) builders.add("self");
|
|
68
|
-
|
|
219
|
+
const inverse = shared || self ? `.inverse(${JSON.stringify(`${name}By${relation[0].toUpperCase()}${relation.slice(1)}`)})` : "";
|
|
220
|
+
return ` ${relation}: ${self ? "self" : identifier(target)}${by}${keyColumn}${nullable ? ".nullable" : ""}${unique ? ".unique" : ".index"}${action ? `.onDelete.${action}` : ""}${inverse},`;
|
|
69
221
|
}
|
|
70
|
-
const claim =
|
|
222
|
+
const claim = nullable ? "maybe" : "one";
|
|
71
223
|
builders.add(claim);
|
|
72
|
-
return ` ${relation}: ${claim}(${target})${action ? `.${action}` : ""}${
|
|
224
|
+
return ` ${relation}: ${claim}(${identifier(target)})${action ? `.${action}` : ""}${unique ? ".unique" : ""}${by}${keyColumn},`;
|
|
73
225
|
}
|
|
74
226
|
let type;
|
|
75
227
|
if (Array.isArray(field.type)) {
|
|
@@ -80,15 +232,15 @@ const authSchemaSource = (tables) => {
|
|
|
80
232
|
builders.add(type.split(/[.(]/)[0]);
|
|
81
233
|
const fallback = field.defaultValue;
|
|
82
234
|
const literal = typeof fallback === "string" || typeof fallback === "number" || typeof fallback === "boolean" ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})` : "";
|
|
83
|
-
|
|
235
|
+
const indexed = (field.index === true || single.has(key)) && !unique;
|
|
236
|
+
return ` ${key}: ${type}${sqlName ? `.named(${JSON.stringify(sqlName)})` : ""}${field.required === false ? ".nullable" : ""}${unique ? ".unique" : ""}${indexed ? ".index" : ""}${literal},`;
|
|
84
237
|
});
|
|
85
|
-
|
|
86
|
-
if (indexes.length) builders.add("index");
|
|
238
|
+
if (composite.length) builders.add("index");
|
|
87
239
|
return [
|
|
88
|
-
`export const ${
|
|
240
|
+
`export const ${name} = table({`,
|
|
89
241
|
" id: text,",
|
|
90
242
|
...lines,
|
|
91
|
-
|
|
243
|
+
composite.length ? `}).indexes((${name}) => ({\n${composite.map((definition) => ` ${definition.fields.join("_").replace(/_(\w)/g, (_match, letter) => letter.toUpperCase())}: index(${definition.fields.map((field) => `${name}.${columnKey(field)}`).join(", ")})${definition.unique ? ".unique" : ""},`).join("\n")}\n}));` : "});"
|
|
92
244
|
].join("\n");
|
|
93
245
|
});
|
|
94
246
|
return [
|
|
@@ -98,10 +250,15 @@ const authSchemaSource = (tables) => {
|
|
|
98
250
|
"",
|
|
99
251
|
declarations.join("\n\n"),
|
|
100
252
|
"",
|
|
101
|
-
`export const authTables = { ${ordered.map((entry) =>
|
|
253
|
+
`export const authTables = { ${ordered.map((entry) => {
|
|
254
|
+
const name = identifier(entry.modelName);
|
|
255
|
+
return name === entry.modelName ? name : `${JSON.stringify(entry.modelName)}: ${name}`;
|
|
256
|
+
}).join(", ")} };`,
|
|
102
257
|
""
|
|
103
258
|
].join("\n");
|
|
104
259
|
};
|
|
260
|
+
const SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);
|
|
261
|
+
const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
|
|
105
262
|
/**
|
|
106
263
|
* `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a
|
|
107
264
|
* `$scope()` of it) whose schema holds the auth tables; better-auth's own
|
|
@@ -109,6 +266,11 @@ const authSchemaSource = (tables) => {
|
|
|
109
266
|
*/
|
|
110
267
|
const symmetriaAdapter = (db, options = {}) => {
|
|
111
268
|
let authOptions;
|
|
269
|
+
let columns;
|
|
270
|
+
const columnsOf = (model) => {
|
|
271
|
+
columns ??= new Map((db.$snapshot?.()?.tables ?? []).map((table) => [table.name, new Set(table.columns.map((column) => column.name))]));
|
|
272
|
+
return columns.get(model);
|
|
273
|
+
};
|
|
112
274
|
const build = (connection) => createAdapterFactory({
|
|
113
275
|
config: {
|
|
114
276
|
adapterId: "symmetria",
|
|
@@ -119,55 +281,151 @@ const symmetriaAdapter = (db, options = {}) => {
|
|
|
119
281
|
supportsBooleans: true,
|
|
120
282
|
supportsJSON: true,
|
|
121
283
|
supportsArrays: true,
|
|
284
|
+
supportsNumericIds: false,
|
|
122
285
|
transaction: (callback) => connection.$transaction((transaction) => callback(build(transaction)(authOptions ?? {})))
|
|
123
286
|
},
|
|
124
|
-
adapter: () => {
|
|
287
|
+
adapter: ({ getDefaultFieldName, getDefaultModelName, getFieldAttributes, getFieldName, schema }) => {
|
|
125
288
|
const table = (model) => {
|
|
126
|
-
const handle = connection
|
|
289
|
+
const handle = member(connection, model);
|
|
127
290
|
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
291
|
return handle;
|
|
129
292
|
};
|
|
130
|
-
const
|
|
293
|
+
const relationKeys = /* @__PURE__ */ new Map();
|
|
294
|
+
const relationKeysOf = (model) => {
|
|
295
|
+
let keys = relationKeys.get(model);
|
|
296
|
+
if (!keys) {
|
|
297
|
+
const present = columnsOf(model);
|
|
298
|
+
let fields = {};
|
|
299
|
+
try {
|
|
300
|
+
fields = schema[getDefaultModelName(model)]?.fields ?? {};
|
|
301
|
+
} catch {}
|
|
302
|
+
keys = new Map(Object.entries(fields).flatMap(([key, field]) => field.references && present && !present.has(key) && present.has(`${key}Id`) ? [[key, `${key}Id`]] : []));
|
|
303
|
+
relationKeys.set(model, keys);
|
|
304
|
+
}
|
|
305
|
+
return keys;
|
|
306
|
+
};
|
|
307
|
+
const keyOf = (model, field) => {
|
|
308
|
+
let key;
|
|
309
|
+
try {
|
|
310
|
+
key = getDefaultFieldName({
|
|
311
|
+
model,
|
|
312
|
+
field
|
|
313
|
+
});
|
|
314
|
+
} catch {
|
|
315
|
+
return field;
|
|
316
|
+
}
|
|
317
|
+
return relationKeysOf(model).get(key) ?? key;
|
|
318
|
+
};
|
|
319
|
+
const typeOf = (model, field) => {
|
|
320
|
+
try {
|
|
321
|
+
return getFieldAttributes({
|
|
322
|
+
model,
|
|
323
|
+
field
|
|
324
|
+
}).type;
|
|
325
|
+
} catch {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
const keyed = (model, data) => Object.fromEntries(Object.entries(data).map(([field, value]) => [keyOf(model, field), value]));
|
|
330
|
+
const isField = (model, key) => {
|
|
331
|
+
if (key === "id") return true;
|
|
332
|
+
try {
|
|
333
|
+
const fields = schema[getDefaultModelName(model)]?.fields;
|
|
334
|
+
return fields !== void 0 && Object.hasOwn(fields, key);
|
|
335
|
+
} catch {
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
const fieldOf = (model, key) => {
|
|
340
|
+
if (isField(model, key)) return key;
|
|
341
|
+
const field = key.slice(0, -2);
|
|
342
|
+
return key.endsWith("Id") && relationKeysOf(model).get(field) === key ? field : void 0;
|
|
343
|
+
};
|
|
344
|
+
const output = (model, field, value) => typeof value === "bigint" && value >= SAFE_MIN && value <= SAFE_MAX && typeOf(model, field) === "number" ? Number(value) : value;
|
|
345
|
+
const fielded = (model, row) => {
|
|
346
|
+
if (!row) return null;
|
|
347
|
+
const own = [];
|
|
348
|
+
const fields = [];
|
|
349
|
+
for (const [key, value] of Object.entries(row)) {
|
|
350
|
+
const field = fieldOf(model, key);
|
|
351
|
+
if (field === void 0) own.push([key, value]);
|
|
352
|
+
else fields.push([getFieldName({
|
|
353
|
+
model,
|
|
354
|
+
field
|
|
355
|
+
}), output(model, field, value)]);
|
|
356
|
+
}
|
|
357
|
+
return Object.fromEntries([...own, ...fields]);
|
|
358
|
+
};
|
|
359
|
+
const where = (model, clauses) => (clauses ?? []).map((clause) => ({
|
|
360
|
+
...clause,
|
|
361
|
+
key: keyOf(model, clause.field),
|
|
362
|
+
value: comparable(typeOf(model, clause.field), clause.value)
|
|
363
|
+
}));
|
|
364
|
+
const read = (model, select, query) => select?.length ? table(model)((row) => Object.fromEntries(select.map((field) => {
|
|
365
|
+
const key = keyOf(model, field);
|
|
366
|
+
return [key, columnOf(row, key, field)];
|
|
367
|
+
})), query) : table(model)(query);
|
|
368
|
+
const filtered = (model, mutation, clauses) => clauses?.length ? mutation.where(filter(where(model, clauses))) : mutation.all();
|
|
369
|
+
const refusing = async (method, model, run) => {
|
|
370
|
+
try {
|
|
371
|
+
return await run();
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (error instanceof Error && error.message.includes("leaves no condition")) throw new Error(`symmetria: better-auth's ${method}() on "${model}" has a where that holds for every row (such as not_in an empty list, or ne null on a required field), so the adapter refuses it rather than write every row; call ${method}() without a where to write every row`, { cause: error });
|
|
374
|
+
throw error;
|
|
375
|
+
}
|
|
376
|
+
};
|
|
131
377
|
return {
|
|
132
|
-
create: ({ model, data }) => table(model).insert(data).returning(),
|
|
133
|
-
findOne: ({ model, where }) =>
|
|
134
|
-
where: filter(where),
|
|
378
|
+
create: async ({ model, data }) => fielded(model, await table(model).insert(keyed(model, data)).returning()),
|
|
379
|
+
findOne: async ({ model, where: clauses, select }) => fielded(model, await read(model, select, {
|
|
380
|
+
where: filter(where(model, clauses)),
|
|
135
381
|
limit: 1
|
|
136
|
-
}).first(),
|
|
137
|
-
findMany: ({ model, where, limit, offset, sortBy }) =>
|
|
138
|
-
where: filter(where),
|
|
382
|
+
}).first()),
|
|
383
|
+
findMany: async ({ model, where: clauses, limit, offset, sortBy, select }) => (await read(model, select, {
|
|
384
|
+
where: filter(where(model, clauses)),
|
|
139
385
|
limit,
|
|
140
386
|
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),
|
|
146
|
-
return row ?? null;
|
|
387
|
+
orderBy: sortBy ? { [keyOf(model, sortBy.field)]: sortBy.direction } : void 0
|
|
388
|
+
})).map((row) => fielded(model, row)),
|
|
389
|
+
count: ({ model, where: clauses }) => table(model)({ where: filter(where(model, clauses)) }).count(),
|
|
390
|
+
update: async ({ model, where: clauses, update }) => {
|
|
391
|
+
const [row] = await refusing("update", model, () => filtered(model, table(model).update(keyed(model, update)), clauses).returning());
|
|
392
|
+
return fielded(model, row ?? null);
|
|
147
393
|
},
|
|
148
|
-
updateMany: async ({ model, where, update }) => (await filtered(table(model).update(update),
|
|
149
|
-
delete: async ({ model, where }) => {
|
|
150
|
-
await filtered(table(model).delete(),
|
|
394
|
+
updateMany: async ({ model, where: clauses, update }) => (await refusing("updateMany", model, () => filtered(model, table(model).update(keyed(model, update)), clauses))).affectedRows,
|
|
395
|
+
delete: async ({ model, where: clauses }) => {
|
|
396
|
+
await refusing("delete", model, () => filtered(model, table(model).delete(), clauses));
|
|
151
397
|
},
|
|
152
|
-
deleteMany: async ({ model, where }) => (await filtered(table(model).delete(),
|
|
153
|
-
consumeOne: async ({ model, where }) => {
|
|
398
|
+
deleteMany: async ({ model, where: clauses }) => (await refusing("deleteMany", model, () => filtered(model, table(model).delete(), clauses))).affectedRows,
|
|
399
|
+
consumeOne: async ({ model, where: clauses }) => {
|
|
154
400
|
const found = await table(model)({
|
|
155
|
-
where: filter(where),
|
|
401
|
+
where: filter(where(model, clauses)),
|
|
156
402
|
limit: 1
|
|
157
403
|
}).first();
|
|
158
404
|
if (!found) return null;
|
|
159
405
|
const [row] = await table(model).byId(found.id).delete().returning();
|
|
160
|
-
return row ?? null;
|
|
406
|
+
return fielded(model, row ?? null);
|
|
161
407
|
},
|
|
162
|
-
incrementOne: async ({ model, where, increment, set }) => {
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
408
|
+
incrementOne: async ({ model, where: clauses, increment, set }) => {
|
|
409
|
+
const handle = table(model);
|
|
410
|
+
const keyedWhere = where(model, clauses);
|
|
411
|
+
const condition = keyedWhere.length ? filter(keyedWhere) : void 0;
|
|
412
|
+
const [row] = await handle.update((current) => ({
|
|
413
|
+
...keyed(model, set ?? {}),
|
|
414
|
+
...Object.fromEntries(Object.entries(increment).map(([field, delta]) => {
|
|
415
|
+
const key = keyOf(model, field);
|
|
416
|
+
return [key, coalesce(columnOf(current, key, field), 0).plus(delta)];
|
|
417
|
+
}))
|
|
418
|
+
})).where((target) => [...condition ? [condition(target)] : [], columnOf(target, "id", "id").in(handle((first) => ({ id: first.id }), {
|
|
419
|
+
where: condition,
|
|
420
|
+
limit: 1
|
|
421
|
+
}))]).returning();
|
|
422
|
+
return fielded(model, row ?? null);
|
|
168
423
|
},
|
|
169
424
|
createSchema: async ({ tables, file }) => ({
|
|
170
|
-
code: authSchemaSource(tables
|
|
425
|
+
code: authSchemaSource(tables, {
|
|
426
|
+
usePlural: options.usePlural ?? false,
|
|
427
|
+
casing: db.$snapshot?.()?.casing
|
|
428
|
+
}),
|
|
171
429
|
path: file ?? "./auth-schema.ts",
|
|
172
430
|
overwrite: true
|
|
173
431
|
})
|