symmetria 3.5.0 → 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 +3 -1
- package/dist/better-auth.js +261 -54
- package/dist/better-auth.js.map +1 -1
- package/dist/{binding-Dli_0DsL.js → binding-QAk-KW4L.js} +3 -3
- 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-C4NC4mYL.js → compile-D02-A2r9.js} +150 -45
- package/dist/compile-D02-A2r9.js.map +1 -0
- package/dist/{core-CFWazQET.js → core-BHndSuCB.js} +271 -180
- 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 +4257 -683
- package/dist/index.js.map +1 -1
- package/dist/{inspection-5zJQONLh.js → inspection-DK0UJaG0.js} +4 -4
- package/dist/{inspection-5zJQONLh.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-BoYrQZ-z.d.ts → pg-CcmvCsRo.d.ts} +3 -3
- package/dist/{pg-CGgCDyKe.js → pg-DxC503O5.js} +4 -4
- package/dist/{pg-CGgCDyKe.js.map → pg-DxC503O5.js.map} +1 -1
- package/dist/pg.d.ts +3 -3
- package/dist/pg.js +2 -2
- package/dist/{pool-BGAPbBOW.js → pool-BTrHoEWY.js} +93 -10
- package/dist/pool-BTrHoEWY.js.map +1 -0
- package/dist/{pool-7vV2Kz6X.d.ts → pool-C7rw4zkO.d.ts} +2 -2
- package/dist/{profiling-OwcSXK1S.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-Dy0lctYU.js → table-AFCbXHL8.js} +222 -70
- package/dist/table-AFCbXHL8.js.map +1 -0
- package/dist/{types-DceSuhlk.js → types-CBBesvuC.js} +342 -20
- package/dist/types-CBBesvuC.js.map +1 -0
- package/dist/{types-BwMsRia9.d.ts → types-t7LyUyKP.d.ts} +230 -54
- package/dist/{values-BheIqXI2.js → values-BxqBvh27.js} +2 -2
- package/dist/{values-BheIqXI2.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-Dli_0DsL.js.map +0 -1
- package/dist/compile-C4NC4mYL.js.map +0 -1
- package/dist/core-CFWazQET.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-BGAPbBOW.js.map +0 -1
- package/dist/profiling-OwcSXK1S.js.map +0 -1
- package/dist/search-DZQ8afs5.js +0 -174
- package/dist/search-DZQ8afs5.js.map +0 -1
- package/dist/search-ks_yELtx.js +0 -47
- package/dist/search-ks_yELtx.js.map +0 -1
- package/dist/table-Dy0lctYU.js.map +0 -1
- package/dist/types-DceSuhlk.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
|
@@ -33,10 +33,12 @@ type Field = {
|
|
|
33
33
|
* Tables come out in an order where each one follows the tables it
|
|
34
34
|
* references; spread `authTables` into `schema({ ... })`. With `usePlural`
|
|
35
35
|
* the tables are keyed in the plural (`users`), as the adapter then asks for
|
|
36
|
-
* them
|
|
36
|
+
* them; `casing` is the schema's (`"preserve"` keeps a reference key such as
|
|
37
|
+
* `requestedBy` as its SQL name).
|
|
37
38
|
*/
|
|
38
39
|
export declare const authSchemaSource: (input: Tables, options?: {
|
|
39
40
|
readonly usePlural?: boolean;
|
|
41
|
+
readonly casing?: "snake_case" | "preserve";
|
|
40
42
|
}) => string;
|
|
41
43
|
/**
|
|
42
44
|
* `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a
|
package/dist/better-auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as or,
|
|
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}`);
|
|
@@ -7,24 +7,55 @@ const member = (target, key) => {
|
|
|
7
7
|
const value = target[key];
|
|
8
8
|
return value === Object.prototype[key] ? void 0 : value;
|
|
9
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([]);
|
|
10
30
|
const predicate = (row, clause) => {
|
|
11
|
-
const column =
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
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";
|
|
15
35
|
const pattern = (text) => insensitive ? column.ilike(text) : column.like(text);
|
|
16
36
|
switch (clause.operator) {
|
|
17
|
-
case "ne":
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
case "
|
|
21
|
-
case "
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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);
|
|
28
59
|
}
|
|
29
60
|
};
|
|
30
61
|
/** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */
|
|
@@ -42,13 +73,90 @@ const COLUMN_TYPES = {
|
|
|
42
73
|
"string[]": "text.array",
|
|
43
74
|
"number[]": "int.array"
|
|
44
75
|
};
|
|
45
|
-
|
|
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;
|
|
46
153
|
/**
|
|
47
154
|
* The auth tables as a Symmetria schema module, for `npx auth generate`.
|
|
48
155
|
* Tables come out in an order where each one follows the tables it
|
|
49
156
|
* references; spread `authTables` into `schema({ ... })`. With `usePlural`
|
|
50
157
|
* the tables are keyed in the plural (`users`), as the adapter then asks for
|
|
51
|
-
* them
|
|
158
|
+
* them; `casing` is the schema's (`"preserve"` keeps a reference key such as
|
|
159
|
+
* `requestedBy` as its SQL name).
|
|
52
160
|
*/
|
|
53
161
|
const authSchemaSource = (input, options = {}) => {
|
|
54
162
|
const tables = options.usePlural ? Object.fromEntries(Object.entries(input).map(([model, entry]) => [model, {
|
|
@@ -58,6 +166,17 @@ const authSchemaSource = (input, options = {}) => {
|
|
|
58
166
|
const builders = /* @__PURE__ */ new Set(["table", "text"]);
|
|
59
167
|
const models = Object.values(tables);
|
|
60
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;
|
|
61
180
|
const ordered = [];
|
|
62
181
|
const pending = [...models];
|
|
63
182
|
while (pending.length) {
|
|
@@ -66,23 +185,43 @@ const authSchemaSource = (input, options = {}) => {
|
|
|
66
185
|
pending.splice(pending.indexOf(next), 1);
|
|
67
186
|
}
|
|
68
187
|
const declarations = ordered.map((entry) => {
|
|
69
|
-
const
|
|
70
|
-
const
|
|
71
|
-
|
|
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;
|
|
72
202
|
const reference = field.references;
|
|
73
|
-
if (reference
|
|
203
|
+
if (reference) {
|
|
74
204
|
const target = nameOf(reference.model);
|
|
75
|
-
const
|
|
76
|
-
const
|
|
77
|
-
|
|
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";
|
|
78
215
|
const self = target === entry.modelName;
|
|
79
|
-
|
|
216
|
+
const shared = targets.filter((other) => other === target).length > 1;
|
|
217
|
+
if (shared || self || action === "noAction") {
|
|
80
218
|
if (self) builders.add("self");
|
|
81
|
-
|
|
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},`;
|
|
82
221
|
}
|
|
83
|
-
const claim =
|
|
222
|
+
const claim = nullable ? "maybe" : "one";
|
|
84
223
|
builders.add(claim);
|
|
85
|
-
return ` ${relation}: ${claim}(${target})${action ? `.${action}` : ""}${
|
|
224
|
+
return ` ${relation}: ${claim}(${identifier(target)})${action ? `.${action}` : ""}${unique ? ".unique" : ""}${by}${keyColumn},`;
|
|
86
225
|
}
|
|
87
226
|
let type;
|
|
88
227
|
if (Array.isArray(field.type)) {
|
|
@@ -93,15 +232,15 @@ const authSchemaSource = (input, options = {}) => {
|
|
|
93
232
|
builders.add(type.split(/[.(]/)[0]);
|
|
94
233
|
const fallback = field.defaultValue;
|
|
95
234
|
const literal = typeof fallback === "string" || typeof fallback === "number" || typeof fallback === "boolean" ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})` : "";
|
|
96
|
-
|
|
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},`;
|
|
97
237
|
});
|
|
98
|
-
|
|
99
|
-
if (indexes.length) builders.add("index");
|
|
238
|
+
if (composite.length) builders.add("index");
|
|
100
239
|
return [
|
|
101
|
-
`export const ${
|
|
240
|
+
`export const ${name} = table({`,
|
|
102
241
|
" id: text,",
|
|
103
242
|
...lines,
|
|
104
|
-
|
|
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}));` : "});"
|
|
105
244
|
].join("\n");
|
|
106
245
|
});
|
|
107
246
|
return [
|
|
@@ -111,10 +250,15 @@ const authSchemaSource = (input, options = {}) => {
|
|
|
111
250
|
"",
|
|
112
251
|
declarations.join("\n\n"),
|
|
113
252
|
"",
|
|
114
|
-
`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(", ")} };`,
|
|
115
257
|
""
|
|
116
258
|
].join("\n");
|
|
117
259
|
};
|
|
260
|
+
const SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);
|
|
261
|
+
const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
|
|
118
262
|
/**
|
|
119
263
|
* `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a
|
|
120
264
|
* `$scope()` of it) whose schema holds the auth tables; better-auth's own
|
|
@@ -122,6 +266,11 @@ const authSchemaSource = (input, options = {}) => {
|
|
|
122
266
|
*/
|
|
123
267
|
const symmetriaAdapter = (db, options = {}) => {
|
|
124
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
|
+
};
|
|
125
274
|
const build = (connection) => createAdapterFactory({
|
|
126
275
|
config: {
|
|
127
276
|
adapterId: "symmetria",
|
|
@@ -135,21 +284,47 @@ const symmetriaAdapter = (db, options = {}) => {
|
|
|
135
284
|
supportsNumericIds: false,
|
|
136
285
|
transaction: (callback) => connection.$transaction((transaction) => callback(build(transaction)(authOptions ?? {})))
|
|
137
286
|
},
|
|
138
|
-
adapter: ({ getDefaultFieldName, getDefaultModelName, getFieldName, schema }) => {
|
|
287
|
+
adapter: ({ getDefaultFieldName, getDefaultModelName, getFieldAttributes, getFieldName, schema }) => {
|
|
139
288
|
const table = (model) => {
|
|
140
289
|
const handle = member(connection, model);
|
|
141
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`);
|
|
142
291
|
return handle;
|
|
143
292
|
};
|
|
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
|
+
};
|
|
144
307
|
const keyOf = (model, field) => {
|
|
308
|
+
let key;
|
|
145
309
|
try {
|
|
146
|
-
|
|
310
|
+
key = getDefaultFieldName({
|
|
147
311
|
model,
|
|
148
312
|
field
|
|
149
313
|
});
|
|
150
314
|
} catch {
|
|
151
315
|
return field;
|
|
152
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
|
+
}
|
|
153
328
|
};
|
|
154
329
|
const keyed = (model, data) => Object.fromEntries(Object.entries(data).map(([field, value]) => [keyOf(model, field), value]));
|
|
155
330
|
const isField = (model, key) => {
|
|
@@ -161,28 +336,51 @@ const symmetriaAdapter = (db, options = {}) => {
|
|
|
161
336
|
return false;
|
|
162
337
|
}
|
|
163
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;
|
|
164
345
|
const fielded = (model, row) => {
|
|
165
346
|
if (!row) return null;
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
model,
|
|
170
|
-
field
|
|
171
|
-
|
|
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
|
+
}
|
|
172
357
|
return Object.fromEntries([...own, ...fields]);
|
|
173
358
|
};
|
|
174
359
|
const where = (model, clauses) => (clauses ?? []).map((clause) => ({
|
|
175
360
|
...clause,
|
|
176
|
-
key: keyOf(model, clause.field)
|
|
361
|
+
key: keyOf(model, clause.field),
|
|
362
|
+
value: comparable(typeOf(model, clause.field), clause.value)
|
|
177
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);
|
|
178
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
|
+
};
|
|
179
377
|
return {
|
|
180
378
|
create: async ({ model, data }) => fielded(model, await table(model).insert(keyed(model, data)).returning()),
|
|
181
|
-
findOne: async ({ model, where: clauses }) => fielded(model, await
|
|
379
|
+
findOne: async ({ model, where: clauses, select }) => fielded(model, await read(model, select, {
|
|
182
380
|
where: filter(where(model, clauses)),
|
|
183
381
|
limit: 1
|
|
184
382
|
}).first()),
|
|
185
|
-
findMany: async ({ model, where: clauses, limit, offset, sortBy }) => (await
|
|
383
|
+
findMany: async ({ model, where: clauses, limit, offset, sortBy, select }) => (await read(model, select, {
|
|
186
384
|
where: filter(where(model, clauses)),
|
|
187
385
|
limit,
|
|
188
386
|
offset,
|
|
@@ -190,14 +388,14 @@ const symmetriaAdapter = (db, options = {}) => {
|
|
|
190
388
|
})).map((row) => fielded(model, row)),
|
|
191
389
|
count: ({ model, where: clauses }) => table(model)({ where: filter(where(model, clauses)) }).count(),
|
|
192
390
|
update: async ({ model, where: clauses, update }) => {
|
|
193
|
-
const [row] = await filtered(model, table(model).update(keyed(model, update)), clauses).returning();
|
|
391
|
+
const [row] = await refusing("update", model, () => filtered(model, table(model).update(keyed(model, update)), clauses).returning());
|
|
194
392
|
return fielded(model, row ?? null);
|
|
195
393
|
},
|
|
196
|
-
updateMany: async ({ model, where: clauses, update }) => (await filtered(model, table(model).update(keyed(model, update)), clauses)).affectedRows,
|
|
394
|
+
updateMany: async ({ model, where: clauses, update }) => (await refusing("updateMany", model, () => filtered(model, table(model).update(keyed(model, update)), clauses))).affectedRows,
|
|
197
395
|
delete: async ({ model, where: clauses }) => {
|
|
198
|
-
await filtered(model, table(model).delete(), clauses);
|
|
396
|
+
await refusing("delete", model, () => filtered(model, table(model).delete(), clauses));
|
|
199
397
|
},
|
|
200
|
-
deleteMany: async ({ model, where: clauses }) => (await filtered(model, table(model).delete(), clauses)).affectedRows,
|
|
398
|
+
deleteMany: async ({ model, where: clauses }) => (await refusing("deleteMany", model, () => filtered(model, table(model).delete(), clauses))).affectedRows,
|
|
201
399
|
consumeOne: async ({ model, where: clauses }) => {
|
|
202
400
|
const found = await table(model)({
|
|
203
401
|
where: filter(where(model, clauses)),
|
|
@@ -208,17 +406,26 @@ const symmetriaAdapter = (db, options = {}) => {
|
|
|
208
406
|
return fielded(model, row ?? null);
|
|
209
407
|
},
|
|
210
408
|
incrementOne: async ({ model, where: clauses, increment, set }) => {
|
|
211
|
-
const
|
|
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) => ({
|
|
212
413
|
...keyed(model, set ?? {}),
|
|
213
414
|
...Object.fromEntries(Object.entries(increment).map(([field, delta]) => {
|
|
214
415
|
const key = keyOf(model, field);
|
|
215
|
-
return [key, current
|
|
416
|
+
return [key, coalesce(columnOf(current, key, field), 0).plus(delta)];
|
|
216
417
|
}))
|
|
217
|
-
})),
|
|
418
|
+
})).where((target) => [...condition ? [condition(target)] : [], columnOf(target, "id", "id").in(handle((first) => ({ id: first.id }), {
|
|
419
|
+
where: condition,
|
|
420
|
+
limit: 1
|
|
421
|
+
}))]).returning();
|
|
218
422
|
return fielded(model, row ?? null);
|
|
219
423
|
},
|
|
220
424
|
createSchema: async ({ tables, file }) => ({
|
|
221
|
-
code: authSchemaSource(tables, {
|
|
425
|
+
code: authSchemaSource(tables, {
|
|
426
|
+
usePlural: options.usePlural ?? false,
|
|
427
|
+
casing: db.$snapshot?.()?.casing
|
|
428
|
+
}),
|
|
222
429
|
path: file ?? "./auth-schema.ts",
|
|
223
430
|
overwrite: true
|
|
224
431
|
})
|