uql-orm 0.112.0 → 0.112.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,14 @@
1
+ import { getMeta } from '../../entity/metadata/definition.js';
1
2
  import { CRUD_ROUTES, entityPath } from '../../http/contract.js';
2
3
  import { stringifyQuery } from '../../http/query.js';
4
+ import { readWireData } from '../../http/wireRow.js';
3
5
  import { isScalarId } from '../../util/object.util.js';
4
6
  import { UqlUsageError } from '../../util/uqlError.js';
5
7
  import { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';
8
+ /** A response with its `data` as the entity holds it, by what its route answers: JSON carried dates and keys as text. */
9
+ function dataOf(entity, response, answers) {
10
+ return { ...response, data: readWireData(getMeta(entity), response.data, answers) };
11
+ }
6
12
  /** The id as one path segment, refusing a composite key, which has no spelling in `/:id` yet. Callers are `async`. */
7
13
  function idSegment(entity, id) {
8
14
  if (!isScalarId(id)) {
@@ -18,9 +24,9 @@ export class HttpQuerier {
18
24
  this.defaults = defaults;
19
25
  }
20
26
  // Typed properties instead of methods, so each takes its signature from `ClientQuerier` rather than repeating it.
21
- findOneById = async (entity, id, q, opts) => get(`${this.getBasePath(entity)}/${idSegment(entity, id)}${stringifyQuery(q)}`, this.buildOptions(opts));
22
- findOne = (entity, q, opts) => this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`, q, opts);
23
- findMany = (entity, q, opts) => this.read(this.getBasePath(entity), opts?.count ? { ...q, count: true } : q, opts);
27
+ findOneById = async (entity, id, q, opts) => dataOf(entity, await get(`${this.getBasePath(entity)}/${idSegment(entity, id)}${stringifyQuery(q)}`, this.buildOptions(opts)), CRUD_ROUTES.findOneById.answers);
28
+ findOne = async (entity, q, opts) => dataOf(entity, await this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`, q, opts), CRUD_ROUTES.findOne.answers);
29
+ findMany = async (entity, q, opts) => dataOf(entity, await this.read(this.getBasePath(entity), opts?.count ? { ...q, count: true } : q, opts), CRUD_ROUTES.findMany.answers);
24
30
  findManyAndCount = async (entity, q, opts) => {
25
31
  const response = await this.findMany(entity, q, { ...opts, count: true });
26
32
  if (typeof response.count !== 'number') {
@@ -28,19 +34,19 @@ export class HttpQuerier {
28
34
  }
29
35
  return { ...response, count: response.count };
30
36
  };
31
- findManyPage = (entity, q, opts) => this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findManyPage.path}`, q, opts);
37
+ findManyPage = async (entity, q, opts) => dataOf(entity, await this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findManyPage.path}`, q, opts), CRUD_ROUTES.findManyPage.answers);
32
38
  count = (entity, q, opts) => this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);
33
39
  /** The `count` route capped at one row, so existence needs no endpoint of its own. */
34
40
  exists = async (entity, q, opts) => {
35
41
  const res = await this.count(entity, { ...q, $limit: 1 }, opts);
36
42
  return { ...res, data: res.data > 0 };
37
43
  };
38
- insertOne = (entity, payload, opts) => post(this.getBasePath(entity), payload, this.buildOptions(opts));
39
- insertMany = (entity, payload, opts) => post(`${this.getBasePath(entity)}${CRUD_ROUTES.insertMany.path}`, payload, this.buildOptions(opts));
44
+ insertOne = async (entity, payload, opts) => dataOf(entity, await post(this.getBasePath(entity), payload, this.buildOptions(opts)), CRUD_ROUTES.insertOne.answers);
45
+ insertMany = async (entity, payload, opts) => dataOf(entity, await post(`${this.getBasePath(entity)}${CRUD_ROUTES.insertMany.path}`, payload, this.buildOptions(opts)), CRUD_ROUTES.insertMany.answers);
40
46
  updateOneById = async (entity, id, payload, opts) => patch(`${this.getBasePath(entity)}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));
41
47
  updateMany = (entity, q, payload, opts) => patch(`${this.getBasePath(entity)}${stringifyQuery(q)}`, payload, this.buildOptions(opts));
42
- saveOne = (entity, payload, opts) => put(this.getBasePath(entity), payload, this.buildOptions(opts));
43
- saveMany = (entity, payload, opts) => put(`${this.getBasePath(entity)}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts));
48
+ saveOne = async (entity, payload, opts) => dataOf(entity, await put(this.getBasePath(entity), payload, this.buildOptions(opts)), CRUD_ROUTES.saveOne.answers);
49
+ saveMany = async (entity, payload, opts) => dataOf(entity, await put(`${this.getBasePath(entity)}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts)), CRUD_ROUTES.saveMany.answers);
44
50
  deleteOneById = async (entity, id, opts = {}) => {
45
51
  const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';
46
52
  return remove(`${this.getBasePath(entity)}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));
@@ -3,7 +3,7 @@ import { generatesKey, valueFieldOf } from '../entity/metadata/definition.js';
3
3
  import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, REF_ENTITY, REF_KEY, ColumnRef, renderSql, RAW_ALIAS, } from '../type/index.js';
4
4
  import { utcTimestamp } from '../util/date.js';
5
5
  import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys, lacksValueOnInsert, } from '../util/field.util.js';
6
- import { RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, hasTriggers, foundRowAssigned, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, columnRef, refOwner, throwUnknownAggregateColumn, } from '../util/index.js';
6
+ import { RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, hasTriggers, foundRowAssigned, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isPlainObject, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, columnRef, refOwner, throwUnknownAggregateColumn, } from '../util/index.js';
7
7
  import { cachedIn, isJsonScalar } from '../util/object.util.js';
8
8
  import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
9
9
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
@@ -823,7 +823,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
823
823
  read: (mode) => this.jsonElemValue(slot, alias, mode),
824
824
  };
825
825
  const conditions = values.map((value) => {
826
- const holds = isOperatorMap(value) || Array.isArray(value)
826
+ const holds = isPlainObject(value) || Array.isArray(value)
827
827
  ? this.jsonHolds(ctx, element, value, scope)
828
828
  : [this.jsonElemEquals(ctx, slot, alias, value)];
829
829
  return jsonElemExists(from, holds, this.jsonElemHint);
@@ -2241,7 +2241,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
2241
2241
  }
2242
2242
  /** `<distance> <op> ?`, the `$where` half of a vector search, its bounds checked here since `/http` input is untyped. */
2243
2243
  vectorNearCondition(ctx, meta, key, near, prefix) {
2244
- if (!isOperatorMap(near)) {
2244
+ if (!isPlainObject(near)) {
2245
2245
  throw new UqlUsageError(`$near on '${key}' expects an object of its $vector and bounds, got ${kindOf(near)}`);
2246
2246
  }
2247
2247
  const bounds = Object.entries(near).filter(([op, val]) => !VECTOR_QUERY_KEY_SET.has(op) && val !== undefined);
@@ -1,7 +1,6 @@
1
1
  import { QuerySql } from '../type/index.js';
2
- import { isOperatorMap } from '../util/dialect.util.js';
3
2
  import { columnFamily, declaresNotNull, jsonPathKeys } from '../util/field.util.js';
4
- import { isOperatorKey, someKey } from '../util/object.util.js';
3
+ import { isOperatorKey, isPlainObject, someKey } from '../util/object.util.js';
5
4
  import { JSON_SKIP_KEY } from './aliases.js';
6
5
  /**
7
6
  * A `'$.a.b'` JSON path literal, and `'$'` for an empty path, the document itself. `suffix` appends an
@@ -108,5 +107,5 @@ export function holdsOperator(value) {
108
107
  if (Array.isArray(value)) {
109
108
  return value.some(holdsOperator);
110
109
  }
111
- return isOperatorMap(value) && someKey(value, (key) => isOperatorKey(key) || holdsOperator(value[key]));
110
+ return isPlainObject(value) && someKey(value, (key) => isOperatorKey(key) || holdsOperator(value[key]));
112
111
  }
@@ -1,7 +1,6 @@
1
1
  import { ColumnRef, QuerySql, REF_ENTITY, REF_KEY, VECTOR_QUERY_KEYS, } from '../type/index.js';
2
- import { isOperatorMap } from '../util/dialect.util.js';
3
2
  import { aggregateOf, isInlinedExpression } from '../util/field.util.js';
4
- import { getKeys, hasKeys, isOperatorKey, isRecord, isWhereMap, someKey } from '../util/object.util.js';
3
+ import { getKeys, hasKeys, isOperatorKey, isPlainObject, isRecord, someKey } from '../util/object.util.js';
5
4
  import { escapeRegExp } from '../util/string.util.js';
6
5
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
7
6
  /**
@@ -37,7 +36,7 @@ export function namesRows(where) {
37
36
  return (where !== undefined &&
38
37
  someKey(where, (key) => isGroupOp(key)
39
38
  ? groupClauses(key, where[key]).some((clause) => clause instanceof QuerySql || namesRows(clause))
40
- : !(isWhereMap(where[key]) && !hasKeys(where[key]))));
39
+ : !(isPlainObject(where[key]) && !hasKeys(where[key]))));
41
40
  }
42
41
  /**
43
42
  * The fields of `meta` a `$where` reads, through every group: each key, a JSON path by its column, and each ref to
@@ -78,7 +77,7 @@ export function fieldsRead(meta, where) {
78
77
  * anything else `$eq`. Each key is checked here, once, refused as `refusal` where it is no operator.
79
78
  */
80
79
  export function whereOperators(val, refusal) {
81
- const ops = Array.isArray(val) ? { $in: val } : isOperatorMap(val) ? val : { $eq: val };
80
+ const ops = Array.isArray(val) ? { $in: val } : isPlainObject(val) ? val : { $eq: val };
82
81
  return Object.entries(ops).map(([op, value]) => {
83
82
  if (!isFieldOp(op)) {
84
83
  throw new UqlUsageError(`${refusal}: ${op}`);
@@ -164,7 +163,7 @@ export function sizeComparisons(size) {
164
163
  if (typeof size === 'number') {
165
164
  return [['$eq', size]];
166
165
  }
167
- if (!isOperatorMap(size)) {
166
+ if (!isPlainObject(size)) {
168
167
  throw new UqlUsageError(`$size expects a number or bounds, got ${kindOf(size)}`);
169
168
  }
170
169
  const comparisons = Object.entries(size).filter(([, bound]) => bound !== undefined);
@@ -1,4 +1,6 @@
1
1
  import type { AbstractType } from '../type/index.js';
2
+ /** What a route answers in `data`, which says how its values cross JSON: rows, a page of them, keys, or a count. */
3
+ export type WireAnswer = 'rows' | 'page' | 'ids' | 'count';
2
4
  /**
3
5
  * Single source of truth for the CRUD-over-HTTP surface, shared by server adapters and the browser client.
4
6
  * Keys are constrained to {@link UniversalQuerier} method names, so renaming a querier method
@@ -8,54 +10,67 @@ export declare const CRUD_ROUTES: {
8
10
  readonly findMany: {
9
11
  readonly method: 'GET';
10
12
  readonly path: '';
13
+ readonly answers: 'rows';
11
14
  };
12
15
  readonly findManyPage: {
13
16
  readonly method: 'GET';
14
17
  readonly path: '/page';
18
+ readonly answers: 'page';
15
19
  };
16
20
  readonly findOne: {
17
21
  readonly method: 'GET';
18
22
  readonly path: '/one';
23
+ readonly answers: 'rows';
19
24
  };
20
25
  readonly count: {
21
26
  readonly method: 'GET';
22
27
  readonly path: '/count';
28
+ readonly answers: 'count';
23
29
  };
24
30
  readonly findOneById: {
25
31
  readonly method: 'GET';
26
32
  readonly path: '/:id';
33
+ readonly answers: 'rows';
27
34
  };
28
35
  readonly insertOne: {
29
36
  readonly method: 'POST';
30
37
  readonly path: '';
38
+ readonly answers: 'ids';
31
39
  };
32
40
  readonly insertMany: {
33
41
  readonly method: 'POST';
34
42
  readonly path: '/many';
43
+ readonly answers: 'ids';
35
44
  };
36
45
  readonly saveOne: {
37
46
  readonly method: 'PUT';
38
47
  readonly path: '';
48
+ readonly answers: 'ids';
39
49
  };
40
50
  readonly saveMany: {
41
51
  readonly method: 'PUT';
42
52
  readonly path: '/many';
53
+ readonly answers: 'ids';
43
54
  };
44
55
  readonly updateMany: {
45
56
  readonly method: 'PATCH';
46
57
  readonly path: '';
58
+ readonly answers: 'count';
47
59
  };
48
60
  readonly updateOneById: {
49
61
  readonly method: 'PATCH';
50
62
  readonly path: '/:id';
63
+ readonly answers: 'count';
51
64
  };
52
65
  readonly deleteOneById: {
53
66
  readonly method: 'DELETE';
54
67
  readonly path: '/:id';
68
+ readonly answers: 'count';
55
69
  };
56
70
  readonly deleteMany: {
57
71
  readonly method: 'DELETE';
58
72
  readonly path: '';
73
+ readonly answers: 'count';
59
74
  };
60
75
  };
61
76
  export type CrudOperation = keyof typeof CRUD_ROUTES;
@@ -1,5 +1,5 @@
1
1
  import { queryErrorKind } from '../querier/queryError.js';
2
- // the specific util modules, not the barrel, so the browser bundle does not pull in entity metadata
2
+ // the specific util modules, not the barrel, which reaches every dialect helper and would land in the browser bundle
3
3
  import { getKeys } from '../util/object.util.js';
4
4
  import { kebabCase } from '../util/string.util.js';
5
5
  /**
@@ -8,19 +8,19 @@ import { kebabCase } from '../util/string.util.js';
8
8
  * (or routing a non-existent one) is a compile error.
9
9
  */
10
10
  export const CRUD_ROUTES = {
11
- findMany: { method: 'GET', path: '' },
12
- findManyPage: { method: 'GET', path: '/page' },
13
- findOne: { method: 'GET', path: '/one' },
14
- count: { method: 'GET', path: '/count' },
15
- findOneById: { method: 'GET', path: '/:id' },
16
- insertOne: { method: 'POST', path: '' },
17
- insertMany: { method: 'POST', path: '/many' },
18
- saveOne: { method: 'PUT', path: '' },
19
- saveMany: { method: 'PUT', path: '/many' },
20
- updateMany: { method: 'PATCH', path: '' },
21
- updateOneById: { method: 'PATCH', path: '/:id' },
22
- deleteOneById: { method: 'DELETE', path: '/:id' },
23
- deleteMany: { method: 'DELETE', path: '' },
11
+ findMany: { method: 'GET', path: '', answers: 'rows' },
12
+ findManyPage: { method: 'GET', path: '/page', answers: 'page' },
13
+ findOne: { method: 'GET', path: '/one', answers: 'rows' },
14
+ count: { method: 'GET', path: '/count', answers: 'count' },
15
+ findOneById: { method: 'GET', path: '/:id', answers: 'rows' },
16
+ insertOne: { method: 'POST', path: '', answers: 'ids' },
17
+ insertMany: { method: 'POST', path: '/many', answers: 'ids' },
18
+ saveOne: { method: 'PUT', path: '', answers: 'ids' },
19
+ saveMany: { method: 'PUT', path: '/many', answers: 'ids' },
20
+ updateMany: { method: 'PATCH', path: '', answers: 'count' },
21
+ updateOneById: { method: 'PATCH', path: '/:id', answers: 'count' },
22
+ deleteOneById: { method: 'DELETE', path: '/:id', answers: 'count' },
23
+ deleteMany: { method: 'DELETE', path: '', answers: 'count' },
24
24
  };
25
25
  const CRUD_OPS = getKeys(CRUD_ROUTES);
26
26
  // derived from CRUD_ROUTES (the literal-path GET routes) so the sub-paths live in exactly one place
@@ -5,6 +5,7 @@ import { whereWith } from '../util/query.util.js';
5
5
  import { UqlUsageError } from '../util/uqlError.js';
6
6
  import { CRUD_ROUTES, entityPath, matchRoute, } from './contract.js';
7
7
  import { parseQueryParams } from './query.js';
8
+ import { readWireData, readWireQuery, writeWireData } from './wireRow.js';
8
9
  /** `Company (crm.Company)`: the class, and the table it maps, which is what tells two apart. */
9
10
  function tableOf(entity) {
10
11
  const meta = getMeta(entity);
@@ -42,7 +43,7 @@ export function createRequestHandler(opts) {
42
43
  async function run(entity, { op, method, id }, req) {
43
44
  const meta = getMeta(entity);
44
45
  // QUERY (RFC 10008) carries the JSON query in the body instead of the query string
45
- const query = parseQueryParams(method === 'QUERY' ? req.body : req.query);
46
+ const query = readWireQuery(meta, parseQueryParams(method === 'QUERY' ? req.body : req.query));
46
47
  const { method: verb } = CRUD_ROUTES[op];
47
48
  // What the client sent, before the hooks: a relation a hook adds is the server's own to add.
48
49
  assertServed(meta, query, served);
@@ -58,11 +59,13 @@ export function createRequestHandler(opts) {
58
59
  // A read acquires and releases; a write is one transaction, so a failing cascade takes its parent with it.
59
60
  const envelope = await (verb === 'GET' ? resolved.withQuerier(execute) : resolved.transaction(execute));
60
61
  await post?.(hookCtx, envelope);
61
- return { status: 200, body: envelope };
62
+ return { status: 200, body: { ...envelope, data: writeWireData(meta, envelope.data, CRUD_ROUTES[op].answers) } };
62
63
  });
63
64
  /** Runs `op`, reading the query and body after the hooks, which may have reshaped or reassigned them. */
64
65
  async function execute(querier) {
65
- const { query, body } = hookCtx;
66
+ const { query } = hookCtx;
67
+ // A write's rows as the entity holds them: JSON carried each `Date` and `bigint` as text.
68
+ const body = readWireData(meta, hookCtx.body, 'rows');
66
69
  const { hardDelete = false, count: counts } = query;
67
70
  const scoped = id === undefined
68
71
  ? query
@@ -18,11 +18,9 @@ export declare function parseQueryParams<E = unknown>(params?: unknown): WireQue
18
18
  */
19
19
  export declare function stringifyQuery(query?: Record<string, unknown>): string;
20
20
  /**
21
- * What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server
22
- * build a statement around the remains. A `sql` fragment renders SQL against a dialect the client does not
23
- * have and arrives as `{}`; binary arrives as an object keyed by index. A `Date` is not among them - it
24
- * serializes to ISO 8601, which is what a date column reads. This is what a cast, or a JavaScript caller,
25
- * hits where the client's types already refuse a fragment.
21
+ * What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server build a
22
+ * statement around the remains: a `sql` fragment, which arrives as `{}`, and binary, keyed by index. A `bigint` goes
23
+ * as its digits and a `Date` as its ISO text, which the server reads back by the entity.
26
24
  */
27
25
  export declare function wireJson(value: unknown): string;
28
26
  export {};
@@ -1,10 +1,9 @@
1
1
  // the clause table itself, not the barrel: this module is in the browser bundle's graph
2
2
  import { QUERY_CLAUSES } from '../type/query.js';
3
- // the brand alone, not the class: importing `QuerySql` for an `instanceof` kept it, and `ColumnRef`
4
- // with it, in the browser bundle, which is on a size budget
3
+ // the brand, which a `sql` fragment and a column ref both carry
5
4
  import { SQL_FN } from '../type/querySql.js';
6
- // the specific util module, not the barrel, so the browser bundle does not pull in entity metadata
7
- import { getKeys, isRecord, isWhereMap } from '../util/object.util.js';
5
+ // the specific util module, not the barrel, which reaches every dialect helper
6
+ import { getKeys, isRecord, isPlainObject } from '../util/object.util.js';
8
7
  // the error class alone, from its own leaf module: `queryError.ts` carries every driver's code map
9
8
  import { UqlUsageError } from '../util/uqlError.js';
10
9
  /** The flags a request carries beside its query: `hardDelete` on a delete, `count` on a `findMany`. */
@@ -43,7 +42,7 @@ export function parseQueryParams(params = {}) {
43
42
  }
44
43
  }
45
44
  query['$where'] ??= {};
46
- if (!isWhereMap(query['$where'])) {
45
+ if (!isPlainObject(query['$where'])) {
47
46
  throw new UqlUsageError("'$where' must be a JSON object");
48
47
  }
49
48
  return query;
@@ -96,14 +95,15 @@ export function stringifyQuery(query) {
96
95
  return qs ? `?${qs}` : '';
97
96
  }
98
97
  /**
99
- * What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server
100
- * build a statement around the remains. A `sql` fragment renders SQL against a dialect the client does not
101
- * have and arrives as `{}`; binary arrives as an object keyed by index. A `Date` is not among them - it
102
- * serializes to ISO 8601, which is what a date column reads. This is what a cast, or a JavaScript caller,
103
- * hits where the client's types already refuse a fragment.
98
+ * What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server build a
99
+ * statement around the remains: a `sql` fragment, which arrives as `{}`, and binary, keyed by index. A `bigint` goes
100
+ * as its digits and a `Date` as its ISO text, which the server reads back by the entity.
104
101
  */
105
102
  export function wireJson(value) {
106
103
  return JSON.stringify(value, (_key, held) => {
104
+ if (typeof held === 'bigint') {
105
+ return String(held);
106
+ }
107
107
  if (typeof held !== 'object' || held === null) {
108
108
  return held;
109
109
  }
@@ -0,0 +1,18 @@
1
+ import type { EntityMeta } from '../type/index.js';
2
+ import type { WireAnswer } from './contract.js';
3
+ /** `data` as JSON is to carry it, by what its route `answers`; the client reads it back by {@link readWireData}. */
4
+ export declare function writeWireData<E>(meta: EntityMeta<E>, data: unknown, answers: WireAnswer): unknown;
5
+ /** `data` JSON carried, a response or a write's body, read back as the entity holds it by what it `answers`. */
6
+ export declare function readWireData<E>(meta: EntityMeta<E>, data: unknown, answers: WireAnswer): unknown;
7
+ /**
8
+ * `query` with each value it compares a field with read back as the entity holds it, its `$populate` and `$count`
9
+ * relations' included: JSON carried each date and `bigint` as text, which an engine would compare as text.
10
+ */
11
+ export declare function readWireQuery<E, Q extends RelationClauses>(meta: EntityMeta<E>, query: Q): Q;
12
+ /** The clauses of a query that compare or reach a relation's rows. */
13
+ type RelationClauses = {
14
+ readonly $where?: unknown;
15
+ readonly $populate?: object;
16
+ readonly $count?: object;
17
+ };
18
+ export {};
@@ -0,0 +1,157 @@
1
+ import { EQUALITY_OPS, isGroupOp, isOrderedOp } from '../dialect/operators.js';
2
+ import { getMeta, relationOf, valueFieldOf } from '../entity/metadata/definition.js';
3
+ import { decodeDate } from '../util/date.js';
4
+ import { aggregateOf, columnFamily } from '../util/field.util.js';
5
+ import { cachedIn, definedEntries, isPlainObject } from '../util/object.util.js';
6
+ /** What JSON cannot hold as the server holds it: a `bigint`, sent as its digits. */
7
+ const sent = (field) => (valueFieldOf(field).type === BigInt ? String : undefined);
8
+ /**
9
+ * What JSON carried as text: a `bigint`'s digits, and a date's ISO text. A time of day stays the text it is, and so
10
+ * does text no `bigint` spells, for the engine to refuse as it refuses any malformed value.
11
+ */
12
+ const received = (field) => {
13
+ const { type } = valueFieldOf(field);
14
+ if (type === BigInt) {
15
+ return (text) => {
16
+ try {
17
+ return BigInt(String(text));
18
+ }
19
+ catch {
20
+ return text;
21
+ }
22
+ };
23
+ }
24
+ return columnFamily(type) === 'date' ? (text) => decodeDate(String(text)) : undefined;
25
+ };
26
+ /** `data` as JSON is to carry it, by what its route `answers`; the client reads it back by {@link readWireData}. */
27
+ export function writeWireData(meta, data, answers) {
28
+ return across(meta, data, answers, SENDING);
29
+ }
30
+ /** `data` JSON carried, a response or a write's body, read back as the entity holds it by what it `answers`. */
31
+ export function readWireData(meta, data, answers) {
32
+ return across(meta, data, answers, RECEIVING);
33
+ }
34
+ /**
35
+ * `query` with each value it compares a field with read back as the entity holds it, its `$populate` and `$count`
36
+ * relations' included: JSON carried each date and `bigint` as text, which an engine would compare as text.
37
+ */
38
+ export function readWireQuery(meta, query) {
39
+ const plan = planIn(RECEIVING, meta);
40
+ const related = (clause) => Object.fromEntries(Object.entries(clause).map(([key, nested]) => {
41
+ const target = plan.relations.get(key);
42
+ return [key, target && isPlainObject(nested) ? readWireQuery(target, nested) : nested];
43
+ }));
44
+ return {
45
+ ...query,
46
+ ...(query.$where !== undefined && { $where: whereOf(meta, query.$where) }),
47
+ ...(query.$populate !== undefined && { $populate: related(query.$populate) }),
48
+ ...(query.$count !== undefined && { $count: related(query.$count) }),
49
+ };
50
+ }
51
+ const SENDING = { field: sent, plans: new WeakMap() };
52
+ const RECEIVING = { field: received, plans: new WeakMap() };
53
+ function planIn(way, meta) {
54
+ return cachedIn(way.plans, meta, () => planOf(meta, way.field));
55
+ }
56
+ function across(meta, data, answers, way) {
57
+ switch (answers) {
58
+ case 'count':
59
+ return data;
60
+ case 'rows':
61
+ return convert(meta, data, way);
62
+ case 'page': {
63
+ if (!isPlainObject(data)) {
64
+ return data;
65
+ }
66
+ const items = convert(meta, data['items'], way);
67
+ return items === data['items'] ? data : { ...data, items };
68
+ }
69
+ case 'ids': {
70
+ const [idKey] = meta.ids;
71
+ const sole = meta.ids.length === 1 ? planIn(way, meta).fields.get(idKey) : undefined;
72
+ // A composite key is a row of its columns; a sole one its value.
73
+ const id = (key) => isPlainObject(key) ? convert(meta, key, way) : sole && key != null ? sole(key) : key;
74
+ return Array.isArray(data) ? data.map(id) : id(data);
75
+ }
76
+ }
77
+ }
78
+ function convert(meta, rows, way) {
79
+ if (Array.isArray(rows)) {
80
+ const converted = rows.map((row) => convert(meta, row, way));
81
+ return converted.every((row, index) => row === rows[index]) ? rows : converted;
82
+ }
83
+ if (!isPlainObject(rows)) {
84
+ return rows;
85
+ }
86
+ const plan = planIn(way, meta);
87
+ let row;
88
+ for (const [key, to] of plan.fields) {
89
+ const value = rows[key];
90
+ if (value != null) {
91
+ row ??= { ...rows };
92
+ // An update's operator, `{ $inc: 1 }`, holds the values it applies.
93
+ row[key] = isPlainObject(value)
94
+ ? Object.fromEntries(Object.entries(value).map(([op, operand]) => [op, to(operand)]))
95
+ : to(value);
96
+ }
97
+ }
98
+ for (const [key, target] of plan.relations) {
99
+ const read = convert(target, rows[key], way);
100
+ if (read !== rows[key]) {
101
+ row ??= { ...rows };
102
+ row[key] = read;
103
+ }
104
+ }
105
+ return row ?? rows;
106
+ }
107
+ function planOf(meta, convertField) {
108
+ return {
109
+ fields: new Map(definedEntries(meta.fields).flatMap(([key, field]) => {
110
+ const source = readField(meta, field);
111
+ const to = source && convertField(source);
112
+ return to ? [[key, to]] : [];
113
+ })),
114
+ relations: new Map(definedEntries(meta.relations).map(([key, relation]) => [key, getMeta(relation.entity())])),
115
+ };
116
+ }
117
+ /** A `$where` of `meta` with each value a field is compared with read back, through groups and relations. */
118
+ function whereOf(meta, where) {
119
+ if (Array.isArray(where)) {
120
+ return where.map((clause) => whereOf(meta, clause));
121
+ }
122
+ if (!isPlainObject(where)) {
123
+ return where;
124
+ }
125
+ const plan = planIn(RECEIVING, meta);
126
+ return Object.fromEntries(Object.entries(where).map(([key, value]) => {
127
+ const to = plan.fields.get(key);
128
+ if (to) {
129
+ return [key, compared(value, to)];
130
+ }
131
+ const target = plan.relations.get(key);
132
+ return [key, target ? whereOf(target, value) : isGroupOp(key) ? whereOf(meta, value) : value];
133
+ }));
134
+ }
135
+ /** A field's condition with each value it compares with read by `to`: a pattern or a null check stays as it is. */
136
+ function compared(condition, to) {
137
+ if (Array.isArray(condition)) {
138
+ return condition.map(to);
139
+ }
140
+ if (!isPlainObject(condition)) {
141
+ return condition == null ? condition : to(condition);
142
+ }
143
+ return Object.fromEntries(Object.entries(condition).map(([op, value]) => [
144
+ op,
145
+ op === '$not' || EQUALITY_OPS.has(op) || isOrderedOp(op) ? compared(value, to) : value,
146
+ ]));
147
+ }
148
+ /** The field a field's value reads as: a relation aggregate's, none for a tally or a mean, which read as numbers. */
149
+ function readField(meta, field) {
150
+ const spec = aggregateOf(field);
151
+ if (!spec) {
152
+ return field;
153
+ }
154
+ return spec.field && spec.op !== '$avg'
155
+ ? getMeta(relationOf(meta, spec.relation).entity()).fields[spec.field]
156
+ : undefined;
157
+ }
@@ -46,7 +46,10 @@ export declare class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
46
46
  * JSON column's `json_valid()` is its type, read by {@link getColumns}, so it is left out.
47
47
  */
48
48
  protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
49
- /** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
49
+ /**
50
+ * MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL, a function it
51
+ * prints by an alias named as declared ({@link MARIADB_ALIASES}).
52
+ */
50
53
  protected sqlText(defaultValue: string): string | undefined;
51
54
  /** Whether an index is MariaDB's vector index, and the distance it was built for. */
52
55
  protected readonly indexFacets: ReadonlySet<IndexFacet>;
@@ -175,6 +175,10 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
175
175
  }
176
176
  }
177
177
  const TIMESTAMP_TYPES = new Set(['datetime', 'timestamp']);
178
+ /** The functions MariaDB prints by an alias, each with the name SQL declares it by. */
179
+ const MARIADB_ALIASES = { lcase: 'lower', ucase: 'upper' };
180
+ /** A quoted literal, kept as it is, or an alias called. */
181
+ const MARIADB_ALIAS = new RegExp(`'(?:[^']|'')*'|\\b(?:${Object.keys(MARIADB_ALIASES).join('|')})(?=\\()`, 'gi');
178
182
  /**
179
183
  * MariaDB reads out of the same `information_schema` as MySQL, save for one column type it does not
180
184
  * have: `JSON` there is an alias for `LONGTEXT` plus a `json_valid()` check constraint named after
@@ -196,9 +200,15 @@ export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
196
200
  AND CHECK_CLAUSE <> CONCAT('json_valid(\`', CONSTRAINT_NAME, '\`)')
197
201
  `);
198
202
  }
199
- /** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
203
+ /**
204
+ * MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL, a function it
205
+ * prints by an alias named as declared ({@link MARIADB_ALIASES}).
206
+ */
200
207
  sqlText(defaultValue) {
201
- return defaultValue.startsWith("'") ? undefined : defaultValue;
208
+ if (defaultValue.startsWith("'")) {
209
+ return undefined;
210
+ }
211
+ return defaultValue.replace(MARIADB_ALIAS, (match) => MARIADB_ALIASES[match.toLowerCase()] ?? match);
202
212
  }
203
213
  /** Whether an index is MariaDB's vector index, and the distance it was built for. */
204
214
  indexFacets = new Set(['vector', 'distance']);
@@ -7,7 +7,7 @@ import { assertSoleId, fieldOf, getMeta, relationOf, soleIdOf } from '../entity/
7
7
  import { referenceKeys } from '../entity/metadata/definition.js';
8
8
  import { COUNT_RESULT_KEY } from '../type/query.js';
9
9
  import { ColumnRef, QuerySql, REF_ENTITY, REF_KEY } from '../type/querySql.js';
10
- import { aggregateOf, isSelectList, assertAggregateColumns, assertNoUndefined, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, definedEntries, getKeys, holdsForeignKey, jsonPathKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, foldJson, writesKeys, isJsonUpdateOp, isOperatorMap, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey, targetJoins, textSortOf, indexedDistance, vectorDistanceOf, vectorCandidates, populatesRelations, cachedIn, } from '../util/index.js';
10
+ import { aggregateOf, isSelectList, assertAggregateColumns, assertNoUndefined, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, definedEntries, getKeys, holdsForeignKey, jsonPathKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, foldJson, writesKeys, isJsonUpdateOp, isPlainObject, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey, targetJoins, textSortOf, indexedDistance, vectorDistanceOf, vectorCandidates, populatesRelations, cachedIn, } from '../util/index.js';
11
11
  import { UqlUsageError } from '../util/uqlError.js';
12
12
  import { decodeBigIntsExcept } from '../util/wideNumber.js';
13
13
  import { textLanguage } from './textLanguage.js';
@@ -470,7 +470,7 @@ export class MongoDialect extends AbstractDialect {
470
470
  }
471
471
  // An object or an array is matched by what it holds, as the SQL engines read it, where native `$all`
472
472
  // compares the whole element. MongoDB takes `$elemMatch` there only when every value is one.
473
- if (op === '$all' && Array.isArray(val) && val.some((value) => Array.isArray(value) || isOperatorMap(value))) {
473
+ if (op === '$all' && Array.isArray(val) && val.some((value) => Array.isArray(value) || isPlainObject(value))) {
474
474
  result[op] = this.allHolding(val);
475
475
  continue;
476
476
  }
@@ -515,7 +515,7 @@ export class MongoDialect extends AbstractDialect {
515
515
  if (Array.isArray(value)) {
516
516
  return this.transformOperators({ $all: value });
517
517
  }
518
- if (!isOperatorMap(value)) {
518
+ if (!isPlainObject(value)) {
519
519
  return value;
520
520
  }
521
521
  return isOperatorObject(value) ? this.transformOperators(value) : this.containment(value);
@@ -529,7 +529,7 @@ export class MongoDialect extends AbstractDialect {
529
529
  if (Array.isArray(value)) {
530
530
  return { $elemMatch: { $all: this.allHolding(value) } };
531
531
  }
532
- return { $elemMatch: isOperatorMap(value) ? this.held(value) : { $eq: value } };
532
+ return { $elemMatch: isPlainObject(value) ? this.held(value) : { $eq: value } };
533
533
  });
534
534
  }
535
535
  /** An object's keys as {@link held} reads each, a nested object's by its dotted path rather than whole. */
@@ -1504,7 +1504,7 @@ export class MongoDialect extends AbstractDialect {
1504
1504
  * by `$in`, which stops at the first match where testing each element would map them all.
1505
1505
  */
1506
1506
  allHeld(ref, values, read) {
1507
- return allOf(values.map((value) => isOperatorMap(value) || Array.isArray(value)
1507
+ return allOf(values.map((value) => isPlainObject(value) || Array.isArray(value)
1508
1508
  ? anyElement(ref, this.heldExpression('$$this', value, read))
1509
1509
  : { $cond: [{ $isArray: ref }, { $in: [read(value), ref] }, false] }));
1510
1510
  }
@@ -1515,7 +1515,7 @@ export class MongoDialect extends AbstractDialect {
1515
1515
  // Classified exactly as the SQL side classifies a `$where`/`$having` value, so the two agree
1516
1516
  // on identical input. Keeping only numbers and objects dropped a string or boolean without a
1517
1517
  // word, handing back every group instead of the filtered ones.
1518
- if (isOperatorMap(condition)) {
1518
+ if (isPlainObject(condition)) {
1519
1519
  filter[alias] = this.transformOperators(condition, 'unsupported HAVING operator');
1520
1520
  }
1521
1521
  else {
@@ -10,7 +10,7 @@ import { QuerySql } from '../type/index.js';
10
10
  import { parseQueryLock } from '../type/index.js';
11
11
  import { bytesToHex } from '../util/bytes.js';
12
12
  import { isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
13
- import { assertNonNegativeInteger, definedEntries, isOperatorMap, keySet, RETURNED_ID } from '../util/index.js';
13
+ import { assertNonNegativeInteger, definedEntries, isPlainObject, keySet, RETURNED_ID } from '../util/index.js';
14
14
  import { escapeSingleQuotes } from '../util/sqlLiteral.js';
15
15
  import { UqlUsageError } from '../util/uqlError.js';
16
16
  /** What SQL Server has. */
@@ -59,7 +59,7 @@ function openJsonType(value) {
59
59
  if (Array.isArray(value)) {
60
60
  return OPENJSON_TYPE.array;
61
61
  }
62
- if (isOperatorMap(value)) {
62
+ if (isPlainObject(value)) {
63
63
  return OPENJSON_TYPE.object;
64
64
  }
65
65
  if (typeof value === 'number') {
@@ -18,7 +18,7 @@ export type LocalSqlitePoolOptions = {
18
18
  export type LocalSqliteDatabase = {
19
19
  prepare(sql: string): SqlitePreparedStatement;
20
20
  loadExtension(path: string): void;
21
- /** Defines a SQL function, which `bun:sqlite` has only in its newer releases. */
21
+ /** Defines a SQL function, which `bun:sqlite` has from Bun 1.4.4. */
22
22
  function?(name: string, options: {
23
23
  deterministic: boolean;
24
24
  }, fn: (...args: SqlValue[]) => SqlValue): unknown;
@@ -178,13 +178,6 @@ export declare function parseSortByCount(val: unknown): unknown;
178
178
  * entries consumable by any dialect. Grouped columns come first, then computed columns.
179
179
  */
180
180
  export declare function parseGroupMap<E>(group?: QueryGroupMap<E>, select?: QueryAggMap<E>): ParsedGroupEntry<E>[];
181
- /**
182
- * Whether `value` is a map of comparison operators rather than a value to compare against. Only a
183
- * plain object qualifies: `Date`, `QuerySql`, `Uint8Array` and arrays are all `typeof 'object'`, and
184
- * reading their keys as operators drops the condition (a `Date` has none) or throws on an array's
185
- * indices. Shared by the SQL and MongoDB builders, whose `$where` and `$having` all face this.
186
- */
187
- export declare function isOperatorMap(value: unknown): value is Record<string, unknown>;
188
181
  /** A JSON object, matched by what it holds: a plain object with no operator key. */
189
182
  export declare function isJsonObject(value: unknown): value is Record<string, unknown>;
190
183
  /**
@@ -4,7 +4,7 @@ import { QuerySql, resolveAggregateOp, } from '../type/index.js';
4
4
  import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
5
5
  import { defaultReadKeys, fieldKeys, isDatabaseWritten, jsonKey, jsonPathKeys } from './field.util.js';
6
6
  import { withDeleted } from './filters.util.js';
7
- import { entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isRecord, someKey, } from './object.util.js';
7
+ import { entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isPlainObject, isRecord, someKey, } from './object.util.js';
8
8
  import { assertNoUndefined, whereAnd } from './query.util.js';
9
9
  import { UqlSecurityError, UqlUsageError } from './uqlError.js';
10
10
  /** The keys of `payload` a write persists as columns. */
@@ -571,23 +571,9 @@ function aggregateField(alias, arg) {
571
571
  function namedKeys(map) {
572
572
  return isRecord(map) ? getKeys(map).filter((key) => map[key]) : [];
573
573
  }
574
- /**
575
- * Whether `value` is a map of comparison operators rather than a value to compare against. Only a
576
- * plain object qualifies: `Date`, `QuerySql`, `Uint8Array` and arrays are all `typeof 'object'`, and
577
- * reading their keys as operators drops the condition (a `Date` has none) or throws on an array's
578
- * indices. Shared by the SQL and MongoDB builders, whose `$where` and `$having` all face this.
579
- */
580
- export function isOperatorMap(value) {
581
- return (typeof value === 'object' &&
582
- value !== null &&
583
- !Array.isArray(value) &&
584
- !(value instanceof Date) &&
585
- !(value instanceof Uint8Array) &&
586
- !(value instanceof QuerySql));
587
- }
588
574
  /** A JSON object, matched by what it holds: a plain object with no operator key. */
589
575
  export function isJsonObject(value) {
590
- return isOperatorMap(value) && !isOperatorObject(value);
576
+ return isPlainObject(value) && !isOperatorObject(value);
591
577
  }
592
578
  /**
593
579
  * A page operand, checked before it reaches an engine. These arrive from page arithmetic and from
@@ -23,6 +23,11 @@ export declare function isOperatorKey(key: string): boolean;
23
23
  export declare function isOperatorObject(value: unknown): value is Record<string, unknown>;
24
24
  /** Whether `value` is an object that is not an array, whose keys can be read. */
25
25
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
26
+ /**
27
+ * Whether `value` is an object literal, or one with no prototype, which a query-string parser hands back: what a
28
+ * query, a payload and JSON are built of. A `Date`, bytes, SQL and any class instance are objects too, but not maps.
29
+ */
30
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
26
31
  /** A shallow copy of `value` without `keys`. */
27
32
  export declare function omitKeys<T extends object>(value: T, keys: Iterable<string>): T;
28
33
  /** The value `cache` holds for `key`, computed and held the first time it is asked for. */
@@ -45,7 +50,5 @@ export declare function entityName<E>(meta: EntityMeta<E>): string;
45
50
  * is what a `$where` map and a composite key's id object both are; an array is a list of either.
46
51
  */
47
52
  export declare function isScalarId(value: unknown): boolean;
48
- /** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */
49
- export declare function isWhereMap(value: unknown): value is Record<string, unknown>;
50
53
  /** What `text` spells as JSON, or nothing where it is no JSON at all. */
51
54
  export declare function jsonDocument(text: string): unknown;
@@ -63,6 +63,17 @@ export function isOperatorObject(value) {
63
63
  export function isRecord(value) {
64
64
  return value !== null && typeof value === 'object' && !Array.isArray(value);
65
65
  }
66
+ /**
67
+ * Whether `value` is an object literal, or one with no prototype, which a query-string parser hands back: what a
68
+ * query, a payload and JSON are built of. A `Date`, bytes, SQL and any class instance are objects too, but not maps.
69
+ */
70
+ export function isPlainObject(value) {
71
+ if (typeof value !== 'object' || value === null) {
72
+ return false;
73
+ }
74
+ const prototype = Object.getPrototypeOf(value);
75
+ return prototype === Object.prototype || prototype === null;
76
+ }
66
77
  /** A shallow copy of `value` without `keys`. */
67
78
  export function omitKeys(value, keys) {
68
79
  const copy = { ...value };
@@ -101,21 +112,7 @@ export function entityName(meta) {
101
112
  * is what a `$where` map and a composite key's id object both are; an array is a list of either.
102
113
  */
103
114
  export function isScalarId(value) {
104
- if (typeof value !== 'object' || value === null) {
105
- return true;
106
- }
107
- if (Array.isArray(value)) {
108
- return false;
109
- }
110
- // `null` as well as `Object.prototype`: an object with no prototype is what a query-string parser
111
- // hands back (`qs`, express's `req.params`), and reading one as a bare id would name one column
112
- // with a map of several.
113
- const proto = Object.getPrototypeOf(value);
114
- return proto !== Object.prototype && proto !== null;
115
- }
116
- /** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */
117
- export function isWhereMap(value) {
118
- return !Array.isArray(value) && !isScalarId(value);
115
+ return !Array.isArray(value) && !isPlainObject(value);
119
116
  }
120
117
  /** What `text` spells as JSON, or nothing where it is no JSON at all. */
121
118
  export function jsonDocument(text) {
@@ -1,5 +1,5 @@
1
1
  import { soleIdOf } from '../entity/metadata/definition.js';
2
- import { entityName, getKeys, isRecord, isScalarId, isWhereMap } from './object.util.js';
2
+ import { entityName, getKeys, isPlainObject, isScalarId } from './object.util.js';
3
3
  import { UqlUsageError } from './uqlError.js';
4
4
  /**
5
5
  * Maps each of `keys` to `true`, the shape of a `$select` or conflict keys. This and the builders below hold
@@ -61,7 +61,7 @@ export function whereIds(meta, ids) {
61
61
  * and a scalar read as a map has no keys, so the statement would match every row.
62
62
  */
63
63
  export function assertWhere(meta, where) {
64
- if (!isWhereMap(where)) {
64
+ if (!isPlainObject(where)) {
65
65
  throw new UqlUsageError(`$where on '${entityName(meta)}' must be a map of conditions, such as { id: 1 }`);
66
66
  }
67
67
  }
@@ -97,14 +97,7 @@ function undefinedPath(value) {
97
97
  }
98
98
  /** An array or a plain object: what a filter nests, and not a `Date`, a `sql` or a driver's value. */
99
99
  function isWalkable(value) {
100
- if (Array.isArray(value)) {
101
- return true;
102
- }
103
- if (!isRecord(value)) {
104
- return false;
105
- }
106
- const proto = Object.getPrototypeOf(value);
107
- return proto === Object.prototype || proto === null;
100
+ return Array.isArray(value) || isPlainObject(value);
108
101
  }
109
102
  const SORT_DIRECTIONS = new Map([
110
103
  [1, { desc: false }],
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.112.0",
6
+ "version": "0.112.1",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -26,11 +26,7 @@
26
26
  "./http": "./dist/http/index.js",
27
27
  "./express": "./dist/express/index.js",
28
28
  "./nestjs": "./dist/nestjs/index.js",
29
- "./browser": {
30
- "types": "./dist/browser/index.d.ts",
31
- "import": "./dist/browser/index.js",
32
- "default": "./dist/browser/uql-browser.min.js"
33
- },
29
+ "./browser": "./dist/browser/index.js",
34
30
  "./libsql": "./dist/libsql/index.js",
35
31
  "./turso": "./dist/turso/index.js",
36
32
  "./turso/local": "./dist/turso/local.js",
@@ -49,8 +45,7 @@
49
45
  "scripts": {
50
46
  "prepack": "bun run build && cp ../../README.md . && cp -R ../../skills .",
51
47
  "postpack": "rm -r README.md skills && npm pkg delete gitHead",
52
- "compile.browser": "bun build src/browser/index.ts --minify --sourcemap=linked --format=esm --target=browser --outdir=dist/browser --entry-naming 'uql-browser.min.[ext]'",
53
- "build": "bun run clean && tsc -b tsconfig.build.json && bun run compile.browser && bun run verify-dist.ts",
48
+ "build": "bun run clean && tsc -b tsconfig.build.json && bun run verify-dist.ts",
54
49
  "start": "tsc --watch",
55
50
  "clean": "rimraf dist .tsconfig.tsbuildinfo"
56
51
  },
@@ -139,9 +134,9 @@
139
134
  "@types/ws": "^8.18.2",
140
135
  "better-sqlite3": "^13.0.3",
141
136
  "express": "^5.3.0",
142
- "mariadb": "^3.5.4",
137
+ "mariadb": "^3.5.5",
143
138
  "mongodb": "^7.8.0",
144
- "mssql": "^12.7.13",
139
+ "mssql": "^12.7.14",
145
140
  "mysql2": "^3.24.6",
146
141
  "pg": "^8.23.1",
147
142
  "pg-query-stream": "^4.17.1",
@@ -91,6 +91,7 @@ export class Post {
91
91
  - A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the version uql fills. A key the database generates is `@Field(f.number().autoIncrement()) id?: number` (`f.bigint().autoIncrement()` past 2^53); `.id()` alone generates nothing, so `f.number().id()` is a key the caller supplies and `@Field` refuses `?` on it, as on a `.references()` key. A NOT NULL field something fills (`.default()`, `.onInsert()`, a generated key) stays `!` when listed in the class's `[filledKey]?: 'id' | 'createdAt'`: inserts may omit it, reads always have it. MongoDB fills a text key declared `?` and `_id`. `insertOne`, `insertMany`, `saveOne` and `saveMany` resolve to a defined key, so no `!`; an upsert's may be `undefined`. On SQL engines an insert leaving out a key nothing declared fills throws before writing. `defineEntity` works all of this out.
92
92
  - `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included. A JSON column defaults to a value, `.default({})` or `.default(0)`, never its JSON text (`'{}'`, `'0'` are refused); any other string there is a JSON string.
93
93
  - `Date` is an instant, stored in UTC to the millisecond. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
94
+ - The browser client (`HttpQuerier`) reads rows back by the entity it is handed, which must be registered (importing its class does it): a `Date` field is a `Date` and a `bigint` exact, so its rows are not plain JSON and a cache persisting them needs a serializer. A `bigint` travels as its digits, both ways.
94
95
  - A JSON column's property is `Json<T>`: `settings?: Json<{ theme?: string }> | null`. A plain object type reads as a relation, which `$where`, `$sort` and the update operators refuse.
95
96
  - A relation decorator takes its target first, then its options, as `rel.*` does. `mappedBy` and `references` may be left out where only one member fits, and then the options too: `@OneToMany(() => Post)`. `@ManyToMany(() => Tag, { through: () => PostTag })` names the junction entity. `cascade: true` writes related rows with their row, in one transaction on SQL and, on MongoDB, inside one the caller opens; an update replaces a to-many's rows.
96
97
  - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring entity options but no table is `@Entity({ abstract: true, ... }) abstract class`, which cannot be queried.
@@ -1,4 +0,0 @@
1
- var f=new Set;function l(e){for(let r of f)r(e)}function A(e){return f.add(e),()=>{f.delete(e)}}var p={$select:{value:"object",scope:"relation"},$populate:{value:"object",scope:"relation"},$where:{value:"object",scope:"relation"},$sort:{value:"object",scope:"relation"},$skip:{value:"number",scope:"relation"},$limit:{value:"number",scope:"relation"},$distinct:{value:"boolean",scope:"relation"},$count:{value:"object",scope:"statement"},$candidates:{value:"number",scope:"statement"},$lock:{value:"object",scope:"statement",wire:!1},$after:{value:"string",scope:"statement"},$before:{value:"string",scope:"statement"}};var R=Symbol("sqlFn"),F=Symbol("rawAlias"),N=Symbol("sqlText"),W=Symbol("sqlValueType"),L=Symbol("refKey"),v=Symbol("refEntity"),_=Symbol("jsonPath"),D=Symbol("jsonValue");function d(e){return e?Object.keys(e):[]}function b(e){if(typeof e!=="object"||e===null)return!0;if(Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null}class k extends Error{}class i extends k{name="UqlUsageError";kind="usage";status=400}var O=["hardDelete","count"],ee=new Map([...d(p).filter((e)=>M(p[e])).map((e)=>[e,p[e].value]),...O.map((e)=>[e,"boolean"])]);function M(e){return e.wire!==!1}function a(e){if(!e)return"";let r=new URLSearchParams;for(let n of d(e)){let s=e[n];if(s===void 0)continue;r.append(n,typeof s==="object"&&s!==null?u(s):String(s))}let t=r.toString();return t?`?${t}`:""}function u(e){return JSON.stringify(e,(r,t)=>{if(typeof t!=="object"||t===null)return t;if(R in t)throw new i("raw SQL cannot travel over HTTP: what leaves the browser is JSON");if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))throw new i("binary cannot travel over HTTP: what leaves the browser is JSON");return t})}class w extends Error{status;constructor(e,r){super(e);this.status=r;this.name="RequestError"}}function h(e,r){return y(e,{method:"GET"},r)}function E(e,r,t){return y(e,{method:"POST",body:u(r)},t)}function x(e,r,t){return y(e,{method:"PATCH",body:u(r)},t)}function g(e,r,t){return y(e,{method:"PUT",body:u(r)},t)}function Q(e,r){return y(e,{method:"DELETE"},r)}function q(e,r,t){return y(e,{method:"QUERY",body:u(r)},t)}function y(e,r,t){if(l({phase:"start",opts:t}),r.headers={accept:"application/json","content-type":"application/json",...t?.headers},t?.signal)r.signal=t.signal;return fetch(e,r).then((n)=>n.json().then((s)=>{if(n.status>=200&&n.status<300)return l({phase:"success",opts:t}),s;let m=s,c={message:m?.error?.message??n.statusText,code:m?.error?.code??n.status};throw l({phase:"error",error:c,opts:t}),new w(c.message,c.code)})).finally(()=>{l({phase:"complete",opts:t})})}function T(e){let r=e.charAt(0).toLowerCase();for(let t=1;t<e.length;++t)r+=e[t]===e[t].toUpperCase()?"-"+e[t].toLowerCase():e[t];return r}var o={findMany:{method:"GET",path:""},findManyPage:{method:"GET",path:"/page"},findOne:{method:"GET",path:"/one"},count:{method:"GET",path:"/count"},findOneById:{method:"GET",path:"/:id"},insertOne:{method:"POST",path:""},insertMany:{method:"POST",path:"/many"},saveOne:{method:"PUT",path:""},saveMany:{method:"PUT",path:"/many"},updateMany:{method:"PATCH",path:""},updateOneById:{method:"PATCH",path:"/:id"},deleteOneById:{method:"DELETE",path:"/:id"},deleteMany:{method:"DELETE",path:""}},C=d(o),ue=new Map(C.filter((e)=>o[e].method==="GET"&&o[e].path!=="/:id").map((e)=>[o[e].path,e]));function P(e){return T(e.name)}function S(e,r){if(!b(r))throw new i(`'${e.name}' was addressed by an id object, which the HTTP route cannot carry.`);return String(r)}class K{basePath;defaults;constructor(e,r={}){this.basePath=e;this.defaults=r}findOneById=async(e,r,t,n)=>h(`${this.getBasePath(e)}/${S(e,r)}${a(t)}`,this.buildOptions(n));findOne=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.findOne.path}`,r,t);findMany=(e,r,t)=>this.read(this.getBasePath(e),t?.count?{...r,count:!0}:r,t);findManyAndCount=async(e,r,t)=>{let n=await this.findMany(e,r,{...t,count:!0});if(typeof n.count!=="number")throw TypeError("findManyAndCount response has an invalid count");return{...n,count:n.count}};findManyPage=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.findManyPage.path}`,r,t);count=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.count.path}`,r,t);exists=async(e,r,t)=>{let n=await this.count(e,{...r,$limit:1},t);return{...n,data:n.data>0}};insertOne=(e,r,t)=>E(this.getBasePath(e),r,this.buildOptions(t));insertMany=(e,r,t)=>E(`${this.getBasePath(e)}${o.insertMany.path}`,r,this.buildOptions(t));updateOneById=async(e,r,t,n)=>x(`${this.getBasePath(e)}/${S(e,r)}`,t,this.buildOptions(n));updateMany=(e,r,t,n)=>x(`${this.getBasePath(e)}${a(r)}`,t,this.buildOptions(n));saveOne=(e,r,t)=>g(this.getBasePath(e),r,this.buildOptions(t));saveMany=(e,r,t)=>g(`${this.getBasePath(e)}${o.saveMany.path}`,r,this.buildOptions(t));deleteOneById=async(e,r,t={})=>{let n=t.hardDelete?a({hardDelete:t.hardDelete}):"";return Q(`${this.getBasePath(e)}/${S(e,r)}${n}`,this.buildOptions(t))};deleteMany=(e,r,t={})=>Q(`${this.getBasePath(e)}${a(t.hardDelete?{...r,hardDelete:t.hardDelete}:r)}`,this.buildOptions(t));getBasePath(e){return`${this.basePath}/${(this.defaults.entityPath??P)(e)}`}read(e,r,t){if(this.defaults.readMethod==="QUERY")return q(e,r??{},this.buildOptions(t));return h(`${e}${a(r)}`,this.buildOptions(t))}buildOptions(e){if(!this.defaults.headers&&!e?.headers)return e;return{...e,headers:{...this.defaults.headers,...e?.headers}}}}export{K as HttpQuerier,w as RequestError,h as get,l as notify,A as on,x as patch,E as post,g as put,q as query,Q as remove};
2
-
3
- //# debugId=41A453F874C392D864756E2164756E21
4
- //# sourceMappingURL=uql-browser.min.js.map
@@ -1,19 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/browser/http/bus.ts", "../../src/type/query.ts", "../../src/type/querySql.ts", "../../src/util/object.util.ts", "../../src/util/uqlError.ts", "../../src/http/query.ts", "../../src/browser/http/http.ts", "../../src/util/string.util.ts", "../../src/http/contract.ts", "../../src/browser/querier/httpQuerier.ts"],
4
- "sourcesContent": [
5
- "import type { RequestCallback, RequestNotification } from '../type/index.js';\n\nconst subscriptors = new Set<RequestCallback>();\n\nexport function notify(notification: RequestNotification): void {\n for (const subscriptor of subscriptors) {\n subscriptor(notification);\n }\n}\n\nexport function on(cb: RequestCallback): () => void {\n subscriptors.add(cb);\n return (): void => {\n subscriptors.delete(cb);\n };\n}\n",
6
- "import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n MethodKey,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n UpdateWrite,\n WrittenId,\n} from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QuerySql } from './querySql.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { QueryVectorQuery, QueryVectorSearch } from './vector.js';\n\nexport type QueryOptions = {\n /**\n * Toggle named entity filters for this query. `false` disables all filters;\n * `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.\n * Security filters cannot be disabled here.\n */\n filters?: false | Record<string, boolean>;\n /**\n * Delete only: physically remove rows instead of soft-deleting, ignoring the soft-delete filter so\n * already-deleted rows are removed too. No effect on entities without a soft-delete field.\n */\n hardDelete?: boolean;\n /**\n * `updateMany`/`deleteMany` only: address every row of the table on purpose. Without it a bulk write\n * that names none - no `$where` and no `$limit` - is refused, since a forgotten filter and the whole\n * table look alike. The entity's own filters never count as naming one.\n */\n unfiltered?: boolean;\n};\n\n/**\n * What a statement is rendered with, on top of the options its caller passed. Kept apart from\n * {@link QueryOptions} because that one is public - it is the third argument of every querier method -\n * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.\n */\nexport type QueryRenderOptions = QueryOptions & {\n /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */\n prefix?: string;\n /**\n * The prefix already written out, for the one caller whose row is not an identifier: a trigger reads\n * `NEW.\"col\"`, where `NEW` is a record the engine declares, and quoting it names a table that is not\n * in scope. Defaults to {@link prefix} escaped.\n */\n escapedPrefix?: string;\n /** Whether to infer the alias where none is given. */\n autoPrefix?: boolean;\n};\n\n/**\n * Field selection - `{ name: true }` whitelists fields; relations go in `$populate`. Declared over\n * `F extends keyof E`, like every map keyed by an entity's members, so each key stays linked to its\n * property and an editor rename reaches it.\n */\nexport type QuerySelect<E, F extends keyof E = FieldKey<E>, V = BooleanLike> = {\n [K in F]?: V;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `sql()`\n * (e.g. ``[sql`*`, sql`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E, Sql = QuerySql> = QuerySelect<E> | readonly Sql[];\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E, Sql = QuerySql, R extends keyof E = RelationKey<E>> = {\n [K in R]?: BooleanLike | QueryPopulateRelationOptions<E[K], Sql>;\n};\n\n/**\n * The key a read carries its relation tallies under. One spelling for the type and the runtime that\n * fills it: they sit in different modules, so a drift would type-check and answer `undefined`.\n */\nexport const COUNT_RESULT_KEY = '_count';\n\n/**\n * How many rows each named relation holds per parent, `true` for all of them or a filter to narrow\n * which ones count: a correlated count in the read's own statement, so no related row is loaded. Comes\n * back under `_count`, which keeps it clear of a relation of the same name `$populate` filled.\n */\nexport type QueryCount<E, Sql = QuerySql, R extends keyof E = ToManyRelationKey<E>> = {\n [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Sql>;\n};\n\n/** The fields of a unique key an upsert finds a row by, `{ email: true }`, as `$select` names them. */\nexport type QueryConflictKeys<E> = QuerySelect<E, FieldKey<E>, true>;\n\n/**\n * The rows an upsert writes: a row `$conflict`'s keys find, `{ email: true }`, takes `$update` where it matches `$where`,\n * as `updateMany` reads one, `{ status: ['done', 'failed'] }`, and stays as it is elsewhere; the rest insert. Without\n * `$update` a found row takes the payload less its key and `$conflict`'s; `$update: {}` keeps it as it is.\n */\nexport type QueryUpsert<E, Sql = QuerySql, U = UpdateWrite<E, Sql>> = QueryFilter<E, Sql> & {\n readonly $conflict: QueryConflictKeys<E>;\n readonly $update?: U;\n};\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V, Sql = QuerySql> =\n IsMany<V> extends true\n ? RelationQuery<RelationTarget<V>, Sql>\n : QueryUnique<RelationTarget<V>, Sql> & { $required?: boolean };\n\n/**\n * The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,\n * so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.\n */\nexport interface UqlContext {\n [key: string]: unknown;\n}\n\n/**\n * A filter's `$where` fragment: a plain fragment, or a function of the ambient {@link UqlContext}.\n * Return `undefined` when the condition can't resolve (see {@link FilterOptions.onMissing}).\n */\nexport type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly where: FilterWhere<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\n} & (\n | {\n readonly security?: false;\n /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */\n readonly onMissing?: FilterOnMissing;\n }\n | {\n /**\n * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and\n * AND-merged so a client `$where` on the same field can't override it. It fails closed.\n */\n readonly security: true;\n readonly onMissing?: 'throw';\n }\n);\n\n/**\n * direction for the sort, and where nulls land in it.\n *\n * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,\n * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, Sql = QuerySql> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n};\n\n/**\n * A filter plus the page `count` takes. No `$sort`: ordering picks *which* rows a page holds, never\n * how many, so a count that accepted one would promise an influence it cannot have.\n */\nexport type QueryPage<E, Sql = QuerySql> = QueryFilter<E, Sql> & QueryPager;\n\n/**\n * A filter plus the ordering and page `updateMany`/`deleteMany` take. Both settle the\n * rows they address with a SELECT first, so the page is portable rather than MySQL-only, and a\n * vector `$sort` is as valid here as on a read: it ranks the settle query's rows, which has the\n * projection list to hold the distance. `$lock` stays off these, declared on {@link Query} instead.\n */\nexport type QuerySearch<E, Sql = QuerySql> = QueryPage<E, Sql> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E, Sql = QuerySql> = {\n /**\n * field selection - `{ name: true }` whitelists fields, `{ body: false }` leaves fields out, or raw SQL\n * projections (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * A map with a positive entry selects those alone. Keys a relation is assembled from (a joined row's primary\n * key, a to-many's foreign key) are read regardless, since leaving them out would leave the relation unfilled.\n */\n $select?: QuerySelectValue<E, Sql>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E, Sql>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E, Sql>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * Lock the rows this query returns, `SELECT ... FOR UPDATE`, inside an open transaction: outside one\n * it is refused, since the lock would drop before the rows are used. SQL only, and not the SQLite family.\n */\n $lock?: QueryLock;\n\n /**\n * How many candidates an ANN index explores before ranking a vector search, in that index's own units\n * (`hnsw.ef_search`, `numCandidates`...); ignored where the search is exact. Postgres needs a transaction.\n */\n $candidates?: number;\n\n // `$where`, `$skip` and `$limit` are declared here rather than intersected in from\n // {@link QueryFilter} and {@link QueryPager}: an assignability check against an intersection is\n // repeated per constituent, and every query in a consuming codebase pays that. The two shapes are\n // pinned together in `queryStatementClauses.test-d.ts` so the copies cannot drift.\n\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * A {@link Query} as it travels as JSON, which a `sql` SQL fragment cannot: what the browser client takes,\n * and what an RPC contract (tRPC, oRPC, TanStack Start) declares as its input.\n */\nexport type WireQuery<E> = Query<E, never>;\n\n/**\n * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a\n * populated relation's own query, a `statement` clause only in the statement itself, and a `wire: false`\n * clause never over HTTP.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\n readonly wire?: false;\n};\n\n/**\n * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It\n * must cover both types, so a clause added to either fails to compile until it is declared here.\n */\nexport const QUERY_CLAUSES = {\n $select: { value: 'object', scope: 'relation' },\n $populate: { value: 'object', scope: 'relation' },\n $where: { value: 'object', scope: 'relation' },\n $sort: { value: 'object', scope: 'relation' },\n $skip: { value: 'number', scope: 'relation' },\n $limit: { value: 'number', scope: 'relation' },\n $distinct: { value: 'boolean', scope: 'relation' },\n // Statement only: tallies are read for the statement's rows, never for a populated relation's.\n $count: { value: 'object', scope: 'statement' },\n // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.\n $candidates: { value: 'number', scope: 'statement' },\n // Each request commits on its own, so a lock taken over HTTP would be released before its response.\n $lock: { value: 'object', scope: 'statement', wire: false },\n // Statement only: keyset paging per parent of a populated relation is not supported.\n $after: { value: 'string', scope: 'statement' },\n $before: { value: 'string', scope: 'statement' },\n} as const satisfies { readonly [K in keyof Query<unknown> | keyof QueryKeyset<unknown>]-?: QueryClause };\n\ntype QueryClauseKey = keyof typeof QUERY_CLAUSES;\n\n/** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */\nexport type QueryClauseOf<Shape extends Partial<QueryClause>> = {\n [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;\n}[QueryClauseKey];\n\n/**\n * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime\n * check reads the same table, so the two cannot drift.\n */\nexport type RelationQuery<E = object, Sql = QuerySql> = Pick<Query<E, Sql>, QueryClauseOf<{ scope: 'relation' }>> & {\n $required?: boolean;\n};\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E, Sql = QuerySql> = Except<Query<E, Sql>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E, Sql = QuerySql> = Pick<QueryOne<E, Sql>, '$select' | '$populate' | '$where'>;\n\n/**\n * A query as a read captures it: `Q` is inferred from the literal, so the row sees every clause at every\n * depth, while the parameter is `Concrete` itself, so a typo'd key fails its excess-property check at any\n * depth too. A query assembled elsewhere, typed `Concrete`, captures nothing and reads the whole entity.\n */\nexport type Captured<Concrete, Q> = [Concrete] extends [Q] ? Q : Concrete;\n\n/**\n * The query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and\n * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.\n */\nexport type QueryKeyset<E, Sql = QuerySql> = Except<Query<E, Sql>, '$skip'> & {\n /** The page size, required here although `Query` leaves it optional. */\n $limit: number;\n /** A page's `endCursor`, to read the rows after it. */\n $after?: string;\n /** A page's `startCursor`, to read the rows before it. */\n $before?: string;\n};\n\n/**\n * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading\n * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,\n * `hasNextPage` backward), since checking for rows on that side would cost another statement.\n */\nexport type CursorPage<T> = {\n readonly items: T[];\n /** Pass as `$before` to read the page before this one. */\n readonly startCursor?: string;\n /** Pass as `$after` to read the page after this one. */\n readonly endCursor?: string;\n readonly hasNextPage: boolean;\n readonly hasPrevPage: boolean;\n};\n\n/**\n * A find's row: the entity narrowed to what the query `Q` projected and populated, at every depth, so\n * reading anything else does not compile, plus {@link SortProjections}. The entity itself where nothing\n * narrows it. A key union names a projection by hand.\n * @example `QueryFindResult<User, 'id' | 'name'>`, `QueryFindResult<User, typeof query>`\n */\nexport type QueryFindResult<E, Q = {}> = [Q] extends [PropertyKey] ? Pick<E, Q & keyof E> : FindRow<E, Q>;\n\n/** What a `$sort` projects, each a number under the name its `$project` gives. */\ntype SortProjections<Q> = Q extends { readonly $sort: { readonly [key: string]: infer V } }\n ? Projected<ProjectedName<V>>\n : unknown;\n\ntype ProjectedName<V> = V extends { readonly $project: infer N extends string } ? N : never;\n\ntype Projected<N extends string> = [N] extends [never] ? unknown : { readonly [K in N]: number };\n\n/** The clauses that shape a row; a query naming none of them reads the entity as it is. */\ntype ShapingQuery = { readonly $select: object } | { readonly $populate: object } | { readonly $count: object };\n\n/**\n * A row at any depth, as {@link QueryFindResult} without the key-union form. Every alias layer and\n * conditional from here down is paid on each read, measured with `bun run ts.perf`: the shaping is\n * written twice so a read with no `$sort` skips the projections, cheaper than an alias over it.\n */\ntype FindRow<E, Q> = Q extends { readonly $sort: object }\n ? (Q extends ShapingQuery ? ShapedRow<E, Q> : DataRow<E>) & SortProjections<Q>\n : Q extends ShapingQuery\n ? ShapedRow<E, Q>\n : DataRow<E>;\n\n/**\n * The entity as a row reads it: plain data, so a method of the class it is read through is `never` and does not\n * compile. Still an `E`, which generic code returning or indexing its rows relies on.\n */\ntype DataRow<E> = E & MethodMask<E>;\n\n/** Each method of `E` as `never`, built once per entity and laid over any row read off it. */\ntype MethodMask<E, M extends keyof E = MethodKey<E>> = [M] extends [never] ? unknown : { readonly [K in M]: never };\n\n/**\n * The row's own fields, and its relations beside them. A positive `$select` entry wins outright at runtime, so a\n * map with one selects its positive keys alone; one with none leaves its keys out. `Pick`,\n * not a key remap: an entity keyed by an index signature, a content type defined at runtime, has `string` for its\n * keys, which a remap drops.\n */\ntype ShapedRow<E, Q> = Q extends { readonly $select: infer M }\n ? (M extends readonly unknown[]\n ? WholeRow<E, Q>\n : M[keyof M] extends true | 1\n ? Pick<E, ([keyof M] extends [never] ? FieldKey<E> : keyof M) & keyof E>\n : M[keyof M] extends Off\n ? Pick<E, Exclude<FieldKey<E>, keyof M> & keyof E>\n : Pick<E, OnKeys<M> & keyof E> & MaybeFields<E, M>) &\n RelatedRows<E, Q>\n : WholeRow<E, Q> & RelatedRows<E, Q>;\n\ntype Off = false | 0 | undefined;\n\n/** The keys of a clause's map whose entry asks for something. */\ntype OnKeys<M> = { [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? K : never }[keyof M];\n\n/** The keys whose entry may or may not ask, a `boolean`: what they name may be absent. */\ntype MaybeKeys<M> = {\n [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? never : M[K] extends Off ? never : K;\n}[keyof M];\n\n/** The fields a `boolean` entry names, each possibly absent; inert where every entry is literal. */\ntype MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick<E, MaybeKeys<M> & keyof E>>;\n\n/** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */\ntype WholeRow<E, Q> = Q extends { readonly $populate: infer M }\n ? Except<E, keyof M & keyof E> & MethodMask<E>\n : DataRow<E>;\n\n/** The populated relations, and the `_count` a query asked for. */\ntype RelatedRows<E, Q> = Q extends { readonly $populate: infer M }\n ? PopulatedRelations<E, M, keyof M & keyof E> & CountedRelations<E, Q>\n : CountedRelations<E, Q>;\n\n/**\n * Each populated relation as its own query shapes it, mapped over parameters constrained to `keyof E` so each\n * member stays linked to its declaration for a rename. A list is always there, empty where the parent has no\n * children, and so is a `$required` to-one; any other to-one may be absent, since a join can find no row.\n */\ntype PopulatedRelations<\n E,\n M,\n K extends keyof E,\n Present extends keyof E = PresentKeys<E, M, K>,\n Absent extends keyof E = Exclude<K, Present>,\n> = { [P in Present]-?: PopulatedRow<E[P], M[P & keyof M]> } & {\n [P in Absent]: PopulatedRow<E[P], M[P & keyof M]> | undefined;\n};\n\ntype PresentKeys<E, M, K extends keyof E> = {\n [P in K]: M[P & keyof M] extends true | 1 | object\n ? IsMany<E[P]> extends true\n ? P\n : M[P & keyof M] extends { readonly $required: true }\n ? P\n : never\n : never;\n}[K];\n\ntype PopulatedRow<V, O> =\n NonNullable<V> extends readonly (infer T)[]\n ? NonNullable<V> extends unknown[]\n ? FindRow<T, O>[]\n : readonly FindRow<T, O>[]\n : FindRow<NonNullable<V>, O>;\n\n/** The `_count` a query asked for, an inert intersection member where it asked for none. */\ntype CountedRelations<E, Q> = Q extends { readonly $count: infer M }\n ? { [K in typeof COUNT_RESULT_KEY]: Tallies<E, OnKeys<M> & keyof E, MaybeKeys<M> & keyof E> }\n : unknown;\n\n/**\n * Each tally a count, over parameters constrained to `keyof E` and naming `E[R]`, which is what keeps each key\n * linked to its relation for a rename: a template that never names `E[R]` loses it.\n */\ntype Tallies<E, On extends keyof E, Maybe extends keyof E> = { [R in On]-?: Tally<E[R]> } & {\n [R in Maybe]?: Tally<E[R]>;\n};\n\ntype Tally<_Relation> = number;\n\n/**\n * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,\n * or `true` for every field a read returns, read in the same transaction after the write (before it, for a delete), so\n * they hold what the database filled. `W` is `true` for `returning: true`, and `boolean` for a map.\n */\nexport type WriteOptions<E, S extends FieldKey<E> = FieldKey<E>, V = BooleanLike, W = boolean> = {\n readonly returning?: QuerySelect<E, S, V> | W;\n};\n\n/** What each kind of write resolves to: its ids or its count where it reads nothing back, else the rows it reads. */\nexport type WriteResults<E, S, V, W = false> = [W] extends [true]\n ? ReturnedRows<Pick<E, FieldKey<E>>>\n : [W] extends [false]\n ? WrittenIds<E>\n : [S] extends [never]\n ? WrittenIds<E>\n : ReturnedRows<ReturnedRow<E, S, V>>;\n\ntype WrittenIds<E> = {\n readonly inserted: NonNullable<WrittenId<E>>;\n readonly upserted: WrittenId<E> | undefined;\n readonly affected: number;\n readonly affectedMany: number;\n};\n\ntype ReturnedRows<R> = {\n readonly inserted: R;\n readonly upserted: R;\n readonly affected: R | undefined;\n readonly affectedMany: R[];\n};\n\n/**\n * The row `returning` reads back: its keys, every field but them where it subtracts, and where it mixes both, its\n * positive keys, which a key set cannot tell apart, so each may be absent. `NoInfer`: a write naming no `returning`\n * would otherwise infer `S` from the type its result is assigned to.\n */\ntype ReturnedRow<E, S, V> = [V] extends [true | 1]\n ? Pick<E, NoInfer<S> & keyof E>\n : [V] extends [false | 0]\n ? Pick<E, Exclude<FieldKey<E>, NoInfer<S>> & keyof E>\n : Partial<Pick<E, NoInfer<S> & keyof E>>;\n\n/**\n * result of an update operation, as the driver reports it - which is what `run` hands back, where\n * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the IDs the statement reported, in payload order, `undefined` where it reported none for that\n * row - a MongoDB upsert names only the documents it inserted. Exact on `'returning'` dialects;\n * inferred from the driver header on the others (see {@link InsertIdSource}), and absent\n * altogether when the header reports nothing.\n */\n ids?: (PrimaryKey | undefined)[];\n};\n",
7
- "import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Scalar, AbstractType } from './utility.js';\n\n/** What a `sql` callback receives. See {@link QuerySqlFn}. */\nexport type QuerySqlRenderOptions = {\n /** The dialect rendering the SQL. */\n dialect: SqlQueryDialect;\n /** The alias of the table in scope, unescaped; empty where there is none. */\n prefix: string;\n /** {@link prefix} escaped, with its trailing dot. */\n escapedPrefix: string;\n /** The query context the SQL is written into. */\n ctx: QueryContext;\n /**\n * The entity being rendered, which a ref read off a definition's map resolves its column against: a\n * computed field's own, or the one whose schema is built. Absent where a statement renders SQL.\n */\n entity?: AbstractType<unknown>;\n /**\n * The rows a set-based trigger's writes read. Absent where the body reads `NEW` and `OLD` bare, and\n * outside a trigger.\n */\n rows?: TriggerRows;\n};\n\n/** {@link QuerySqlRenderOptions} as the callers along the way fill them in, every one still optional. */\nexport type QuerySqlFnOptions = Partial<QuerySqlRenderOptions>;\n\n/**\n * A `sql` callback: write into `ctx`, or return a string or number to have it appended. Anything else\n * it returns is ignored, which is why the return type is `unknown` rather than `void | Scalar` - the\n * latter rejected `({ ctx }) => ctx.append(...)`, the form every computed field is written in, because\n * TypeScript's \"returning a value where void is expected\" allowance does not apply to a union.\n */\nexport type QuerySqlFn = (opts: QuerySqlRenderOptions) => unknown;\n\nexport const SQL_FN: unique symbol = Symbol('sqlFn');\nexport const RAW_ALIAS: unique symbol = Symbol('rawAlias');\nexport const SQL_TEXT: unique symbol = Symbol('sqlText');\n/** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */\nexport const SQL_VALUE_TYPE: unique symbol = Symbol('sqlValueType');\n/** The member a ref names. A symbol, as each of a ref's own keys is, so every string key is the data's. */\nexport const REF_KEY: unique symbol = Symbol('refKey');\n\n/** The entity a {@link ColumnRef} was read off, where it names one: a definition's refs name none. */\nexport const REF_ENTITY: unique symbol = Symbol('refEntity');\n/** The dotted path a {@link JsonPathRef} reads down its column's document. */\nexport const JSON_PATH: unique symbol = Symbol('jsonPath');\n/** Keys the phantom a {@link JsonPathRef} carries the value at its path in. */\nexport const JSON_VALUE: unique symbol = Symbol('jsonValue');\n\n/**\n * What a `sql` template interpolates: a value it binds, a list of them (`= ANY(${ids})`), or SQL it renders in\n * place. Never `undefined`, which would bind nothing: leave it out, or interpolate `null`.\n */\nexport type SqlArg = Scalar | null | readonly (Scalar | null)[] | QuerySql;\n\n/** A statement as `all` and `run` take one: a tagged template's strings and values, or a `sql` built apart. */\nexport type SqlStatement = readonly [strings: TemplateStringsArray, ...values: SqlArg[]] | readonly [sql: QuerySql];\n\nexport class QuerySql {\n readonly [SQL_FN]: QuerySqlFn;\n readonly [RAW_ALIAS]?: string;\n /**\n * The SQL verbatim, set only where it is a constant: a template that interpolates nothing binds no\n * value and reads no column, so it needs no dialect to render. What a DDL clause with nowhere to\n * bind reads - see {@link constantSql}.\n */\n readonly [SQL_TEXT]?: string;\n\n constructor(value: QuerySqlFn, { alias, text }: { readonly alias?: string; readonly text?: string } = {}) {\n this[SQL_FN] = value;\n this[RAW_ALIAS] = alias;\n this[SQL_TEXT] = text;\n }\n\n /** The same expression under an alias, for a `$select` projection. */\n as(alias: string): QuerySql {\n return new QuerySql(this[SQL_FN], { alias, text: this[SQL_TEXT] });\n }\n}\n\n/** Writes `statement` into `opts.ctx`. The alias is the projection's to write, after the term. */\nexport function renderSql(statement: QuerySql, opts: QuerySqlRenderOptions): void {\n const emitted = statement[SQL_FN](opts);\n if (typeof emitted === 'string' || (typeof emitted === 'number' && !Number.isNaN(emitted))) {\n opts.ctx.append(String(emitted));\n }\n}\n\n/**\n * A field of an entity as SQL, read off `refs(Entity)` or a definition's refs: interpolated into `sql`, it\n * renders as the field's column. Its key is how an index tells a column from an expression, and `V`,\n * the field's type, is what a value slot checks it against: see {@link SqlFor}.\n */\nexport class ColumnRef<K extends string = string, V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n readonly [REF_KEY]: K;\n readonly #entity?: () => AbstractType<unknown>;\n\n /** `entity` is read when the ref is, so an entity declared after the ref resolves. */\n constructor(key: K, value: QuerySqlFn, entity?: () => AbstractType<unknown>) {\n super(value);\n this[REF_KEY] = key;\n this.#entity = entity;\n }\n\n get [REF_ENTITY](): AbstractType<unknown> | undefined {\n return this.#entity?.();\n }\n}\n\n/**\n * A path inside a JSON column, read off an index's refs as the `$where` key it is: `user.settings.theme`\n * for `'settings.theme'`. `V`, the value at the path, decides how the index has to read it.\n */\nexport class JsonPathRef<V = unknown> {\n declare readonly [JSON_VALUE]?: V;\n readonly [REF_KEY]: string;\n readonly [JSON_PATH]: string;\n\n constructor(key: string, path: string) {\n this[REF_KEY] = key;\n this[JSON_PATH] = path;\n }\n}\n\n/**\n * SQL where a value of type `V` goes: bare SQL, whose type is its author's to know, or a ref to a column\n * holding one, nullability aside. `Sql` is what the transport carries, so the wire's `never` stays one.\n */\nexport type SqlFor<Sql, V> = Sql & { readonly [SQL_VALUE_TYPE]?: V | null };\n\n/**\n * A relation aggregate as SQL, read off a `computed` field's refs: `(user) => user.resources.count()`.\n * It renders as the correlated subquery a `$count` reads, so a field holding one is read, filtered and\n * sorted like any other.\n *\n * `V` is the value it reads, carried in a phantom field so the aggregate a field declares decides the\n * property's type.\n */\nexport class RelationAggregate<V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n\n constructor(\n /** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */\n readonly spec: RelationAggregateSpec,\n value: QuerySqlFn,\n ) {\n super(value);\n }\n}\n\n/**\n * A write `insertInto`, `updateTable` or `deleteFrom` renders, or several joined in one `sql`. It reads a\n * set-based trigger's rows through {@link QuerySqlRenderOptions.rows}, which is how `of` and `where` narrow\n * them there; SQL of its own reads `inserted` and `deleted` whole.\n */\nexport class TriggerWriteSql extends QuerySql {}\n",
8
- "import type { EntityMeta, JsonScalar } from '../type/index.js';\n\n/** Does nothing: a listener or `catch` that only has to be there. `undefined` rather than `void`, so `.catch(noop)` keeps `T | undefined`. */\nexport const noop = (): undefined => undefined;\n\n/** Whether `value` is a {@link JsonScalar}, which `$addToSet` and an `=` on a JSON path compare by equality. */\nexport function isJsonScalar(value: unknown): value is JsonScalar {\n return typeof value === 'string' || typeof value === 'boolean' || Number.isFinite(value);\n}\n\n/** Orders two strings by code unit, or two numbers by value, the order every engine sorts text by, so names and JSON keys agree across them. */\nexport function byCodeUnit<T extends string | number>(a: T, b: T): number {\n return a < b ? -1 : 1;\n}\n\nexport function clone<T>(value: T): T {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((it) => clone(it)) as T;\n }\n return { ...value };\n}\n\n/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n if (!(size >= 1)) {\n throw new RangeError(`a chunk holds at least one item, not ${size}`);\n }\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\n/** Whether `value` is a class, which an arrow, with no `prototype`, is not. */\nexport function isClass(value: unknown): boolean {\n return typeof value === 'function' && value.prototype !== undefined;\n}\n\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether `key` names an operator (`$eq`, `$push`...) rather than a field. */\nexport function isOperatorKey(key: string): boolean {\n return key.startsWith('$');\n}\n\n/** Whether `value` is a non-empty object with an operator key (`$eq`, `$push`...): the one test every dialect classifies with. */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether `value` is an object that is not an array, whose keys can be read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** A shallow copy of `value` without `keys`. */\nexport function omitKeys<T extends object>(value: T, keys: Iterable<string>): T {\n const copy = { ...value };\n for (const key of keys) {\n Reflect.deleteProperty(copy, key);\n }\n return copy;\n}\n\n/** The value `cache` holds for `key`, computed and held the first time it is asked for. */\nexport function cachedIn<K, V>(\n cache: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n compute: () => V,\n): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = compute();\n cache.set(key, value);\n }\n return value;\n}\n\nexport function getKeys<T extends object>(obj: T | null | undefined): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/** The entries of `record` holding a value: a key declared but left `undefined` is no entry at all. */\nexport function definedEntries<K extends string, V>(record: Partial<Record<K, V>>): [K, V][] {\n return (Object.entries(record) as [K, V | undefined][]).filter((entry): entry is [K, V] => entry[1] !== undefined);\n}\n\n/**\n * The entity's own name, declared or its class's. `meta.name` holds only what the author wrote, so\n * the fallback is what an entity that named no table is called - which is why the sites spelling this\n * out reached for three different fallbacks, `?? ''` among them, and named nothing at all.\n */\nexport function entityName<E>(meta: EntityMeta<E>): string {\n return meta.name ?? meta.entity.name;\n}\n\n/**\n * Whether `value` addresses a row by itself rather than naming columns: every primitive, and the\n * object ids a driver deals in (`ObjectId`, `Date`, bytes). Only a plain object names columns, which\n * is what a `$where` map and a composite key's id object both are; an array is a list of either.\n */\nexport function isScalarId(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return true;\n }\n if (Array.isArray(value)) {\n return false;\n }\n // `null` as well as `Object.prototype`: an object with no prototype is what a query-string parser\n // hands back (`qs`, express's `req.params`), and reading one as a bare id would name one column\n // with a map of several.\n const proto = Object.getPrototypeOf(value);\n return proto !== Object.prototype && proto !== null;\n}\n\n/** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */\nexport function isWhereMap(value: unknown): value is Record<string, unknown> {\n return !Array.isArray(value) && !isScalarId(value);\n}\n\n/** What `text` spells as JSON, or nothing where it is no JSON at all. */\nexport function jsonDocument(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n",
9
- "/**\n * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers\n * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization\n * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the\n * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.\n */\nexport type QueryErrorKind =\n | 'uniqueViolation'\n | 'foreignKeyViolation'\n | 'notNullViolation'\n | 'checkViolation'\n | 'optimisticLock'\n | 'retryable'\n | 'usage'\n | 'security';\n\n/** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */\nexport abstract class UqlError extends Error {\n abstract readonly kind: QueryErrorKind;\n abstract readonly status: number;\n}\n\n/**\n * Thrown where the caller used the API in a way no statement can carry out: an update payload with no\n * version, a `$lock` outside a transaction, a method with no version to match. A `400` over HTTP: the\n * request is malformed, not the server's failure, and an untyped client is exactly who reaches this.\n */\nexport class UqlUsageError extends UqlError {\n override name = 'UqlUsageError';\n readonly kind = 'usage';\n readonly status = 400;\n}\n\n/**\n * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.\n * Fails the statement closed.\n */\nexport class UqlSecurityError extends UqlError {\n override name = 'UqlSecurityError';\n readonly kind = 'security';\n readonly status = 403;\n}\n\n/** What a value is, for a refusal naming what `/http` handed over instead of what the types require. */\nexport function kindOf(value: unknown): string {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;\n}\n\n/**\n * Thrown when an update's `f.version()` column no longer matches the row: another writer moved it on,\n * or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`\n * where there is no row left.\n */\nexport class UqlOptimisticLockError extends UqlError {\n override name = 'UqlOptimisticLockError';\n readonly kind = 'optimisticLock';\n readonly status = 409;\n\n constructor(\n message: string,\n readonly expected: unknown,\n readonly actual: unknown,\n ) {\n super(message);\n }\n}\n",
10
- "import type { QueryKeyset, QueryOptions, WireQuery } from '../type/index.js';\n// the clause table itself, not the barrel: this module is in the browser bundle's graph\nimport { QUERY_CLAUSES, type QueryClause } from '../type/query.js';\n// the brand alone, not the class: importing `QuerySql` for an `instanceof` kept it, and `ColumnRef`\n// with it, in the browser bundle, which is on a size budget\nimport { SQL_FN } from '../type/querySql.js';\n// the specific util module, not the barrel, so the browser bundle does not pull in entity metadata\nimport { getKeys, isRecord, isWhereMap } from '../util/object.util.js';\n// the error class alone, from its own leaf module: `queryError.ts` carries every driver's code map\nimport { UqlUsageError } from '../util/uqlError.js';\n\n/** The flags a request carries beside its query: `hardDelete` on a delete, `count` on a `findMany`. */\nconst WIRE_FLAGS = ['hardDelete', 'count'] as const satisfies (keyof Pick<QueryOptions, 'hardDelete'> | 'count')[];\n\n/** {@link WIRE_FLAGS} as the booleans {@link parseQueryParams} decodes them to, where a hook may also set them. */\nexport type WireFlags = { readonly [K in (typeof WIRE_FLAGS)[number]]?: boolean };\n\n/** The cursors a page request carries; only `findManyPage` reads them. */\nexport type WireCursors = Pick<QueryKeyset<unknown>, '$after' | '$before'>;\n\n/**\n * The keys accepted from the wire, mapped to how each value is decoded: every query clause ({@link QUERY_CLAUSES})\n * HTTP carries, plus the {@link WIRE_FLAGS}. Any other `$` key is refused, since dropping a clause answers a read\n * other than the one asked for; any other key (e.g. `filters`, `context`) is dropped, so a remote client can't\n * bypass a security filter or inject ambient context.\n */\nconst WIRE_VALUES: ReadonlyMap<string, QueryClause['value']> = new Map([\n ...getKeys(QUERY_CLAUSES)\n .filter((key) => carriedOverHttp(QUERY_CLAUSES[key]))\n .map((key) => [key, QUERY_CLAUSES[key].value] as const),\n ...WIRE_FLAGS.map((flag) => [flag, 'boolean'] as const),\n]);\n\nfunction carriedOverHttp(clause: QueryClause): boolean {\n return clause.wire !== false;\n}\n\n/**\n * Parse raw query-string entries (with JSON-stringified values), or a `QUERY` body, into a UQL query\n * object. Symmetric counterpart of {@link stringifyQuery}. Only the keys in {@link WIRE_VALUES} are honored.\n */\nexport function parseQueryParams<E = unknown>(params: unknown = {}): WireQuery<E> & WireFlags & WireCursors {\n if (!isRecord(params)) {\n throw new UqlUsageError('the query must be a JSON object');\n }\n const query: Record<string, unknown> = {};\n for (const key of getKeys(params)) {\n const shape = WIRE_VALUES.get(key);\n if (!shape && key.startsWith('$')) {\n throw new UqlUsageError(`'${key}' is not a query key HTTP takes`);\n }\n if (shape && params[key] !== undefined) {\n query[key] = decodeWireValue(key, shape, params[key]);\n }\n }\n query['$where'] ??= {};\n if (!isWhereMap(query['$where'])) {\n throw new UqlUsageError(\"'$where' must be a JSON object\");\n }\n return query;\n}\n\n/**\n * Decodes a value to the type its clause declares. A query string carries every value as text, so a boolean\n * must be decoded: `'false'` is a non-empty string, and taken as is, `$distinct=false` would turn it on.\n */\nfunction decodeWireValue(key: string, shape: QueryClause['value'], value: unknown): unknown {\n switch (shape) {\n case 'object':\n return typeof value === 'string' ? parseJson(key, value) : value;\n case 'number':\n return Number(value);\n case 'boolean':\n return value === true || value === 'true';\n case 'string':\n // A cursor arrives as the exact text a page handed out, never as JSON, so any other value is not a cursor.\n if (typeof value !== 'string') {\n throw new UqlUsageError(`'${key}' must be a cursor a page handed out`);\n }\n return value;\n }\n}\n\nfunction parseJson(key: string, text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new UqlUsageError(`invalid JSON in '${key}'`);\n }\n}\n\n/**\n * Serialize a UQL query object into a percent-encoded query string where object values\n * are JSON-stringified. Symmetric counterpart of {@link parseQueryParams}.\n */\nexport function stringifyQuery(query?: Record<string, unknown>): string {\n if (!query) {\n return '';\n }\n const params = new URLSearchParams();\n for (const key of getKeys(query)) {\n const value = query[key];\n if (value === undefined) {\n continue;\n }\n params.append(key, typeof value === 'object' && value !== null ? wireJson(value) : String(value));\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\n/**\n * What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server\n * build a statement around the remains. A `sql` fragment renders SQL against a dialect the client does not\n * have and arrives as `{}`; binary arrives as an object keyed by index. A `Date` is not among them - it\n * serializes to ISO 8601, which is what a date column reads. This is what a cast, or a JavaScript caller,\n * hits where the client's types already refuse a fragment.\n */\nexport function wireJson(value: unknown): string {\n return JSON.stringify(value, (_key: string, held: unknown) => {\n if (typeof held !== 'object' || held === null) {\n return held;\n }\n if (SQL_FN in held) {\n throw new UqlUsageError('raw SQL cannot travel over HTTP: what leaves the browser is JSON');\n }\n // A blob is a field value, so no type parameter reaches it: this is the only place it is caught.\n if (held instanceof ArrayBuffer || ArrayBuffer.isView(held)) {\n throw new UqlUsageError('binary cannot travel over HTTP: what leaves the browser is JSON');\n }\n return held;\n });\n}\n",
11
- "import type { RequestErrorResponse } from '../../http/contract.js';\nimport { wireJson } from '../../http/query.js';\nimport type { RequestSuccessResponse } from '../../type/index.js';\nimport type { RequestOptions } from '../type/index.js';\nimport { notify } from './bus.js';\n\n/**\n * Error thrown for non-2xx responses. Carries the HTTP status so callers can key\n * behavior on it (401 redirects, 402 payment flows, error-boundary routing).\n */\nexport class RequestError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n this.name = 'RequestError';\n }\n}\n\n// Methods are upper-case because `fetch` normalizes only the classic verbs: a lowercase `patch` or `query`\n// is sent as written, and servers refuse it.\nexport function get<T>(url: string, opts?: RequestOptions) {\n return request<T>(url, { method: 'GET' }, opts);\n}\n\nexport function post<T>(url: string, payload: unknown, opts?: RequestOptions) {\n return request<T>(url, { method: 'POST', body: wireJson(payload) }, opts);\n}\n\nexport function patch<T>(url: string, payload: unknown, opts?: RequestOptions) {\n return request<T>(url, { method: 'PATCH', body: wireJson(payload) }, opts);\n}\n\nexport function put<T>(url: string, payload: unknown, opts?: RequestOptions) {\n return request<T>(url, { method: 'PUT', body: wireJson(payload) }, opts);\n}\n\nexport function remove<T>(url: string, opts?: RequestOptions) {\n return request<T>(url, { method: 'DELETE' }, opts);\n}\n\n/**\n * HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the\n * request body, avoiding URL-length limits.\n */\nexport function query<T>(url: string, payload: unknown, opts?: RequestOptions) {\n return request<T>(url, { method: 'QUERY', body: wireJson(payload) }, opts);\n}\n\nfunction request<T>(url: string, init: RequestInit, opts?: RequestOptions) {\n notify({ phase: 'start', opts });\n\n init.headers = {\n accept: 'application/json',\n 'content-type': 'application/json',\n ...opts?.headers,\n };\n if (opts?.signal) {\n init.signal = opts.signal;\n }\n\n return fetch(url, init)\n .then((rawResp) =>\n rawResp.json().then((resp: unknown) => {\n const isSuccess = rawResp.status >= 200 && rawResp.status < 300;\n if (isSuccess) {\n notify({ phase: 'success', opts });\n return resp as RequestSuccessResponse<T>;\n }\n const errorResp = resp as Partial<RequestErrorResponse> | undefined;\n const error = {\n message: errorResp?.error?.message ?? rawResp.statusText,\n code: errorResp?.error?.code ?? rawResp.status,\n };\n notify({ phase: 'error', error, opts });\n throw new RequestError(error.message, error.code);\n }),\n )\n .finally(() => {\n notify({ phase: 'complete', opts });\n });\n}\n",
12
- "export function kebabCase(val: string): string {\n let resp = val.charAt(0).toLowerCase();\n for (let i = 1; i < val.length; ++i) {\n resp += val[i] === val[i].toUpperCase() ? '-' + val[i].toLowerCase() : val[i];\n }\n return resp;\n}\n\nexport function upperFirst(text: string): string {\n return text.charAt(0).toUpperCase() + text.slice(1);\n}\n\nexport function lowerFirst(text: string): string {\n return text.charAt(0).toLowerCase() + text.slice(1);\n}\n\nexport function snakeCase(val: string): string {\n if (!val) return '';\n let resp = val.charAt(0).toLowerCase();\n for (let i = 1; i < val.length; ++i) {\n const char = val[i];\n const charLower = char.toLowerCase();\n if (char !== charLower && char === char.toUpperCase()) {\n resp += '_' + charLower;\n } else {\n resp += char;\n }\n }\n return resp;\n}\n\n/**\n * Convert a string to PascalCase (UpperCamelCase).\n * @example 'user_profile' -> 'UserProfile'\n * @example 'some-text' -> 'SomeText'\n */\nexport function pascalCase(str: string): string {\n if (!str) return '';\n return str\n .split(/[_\\s-]+/)\n .map((word) => {\n // Lower-casing the rest is only right for a word that carries no case of its own: it turns\n // `USER_ID` into `UserId`, but it also turns `tenantId` into `Tenantid`.\n const rest = word === word.toUpperCase() ? word.slice(1).toLowerCase() : word.slice(1);\n return word.charAt(0).toUpperCase() + rest;\n })\n .join('');\n}\n\n/**\n * Convert a string to camelCase.\n * @example 'user_profile' -> 'userProfile'\n * @example 'SomeText' -> 'someText'\n */\nexport function camelCase(str: string): string {\n const pascal = pascalCase(str);\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n\n/**\n * Simple singularize function for English words.\n * @example 'users' -> 'user'\n * @example 'categories' -> 'category'\n */\nexport function singularize(name: string): string {\n if (!name) return '';\n if (name.endsWith('ies')) {\n return name.slice(0, -3) + 'y';\n }\n if (name.endsWith('ses') || name.endsWith('xes') || name.endsWith('zes')) {\n return name.slice(0, -2);\n }\n if (name.endsWith('s') && !name.endsWith('ss')) {\n return name.slice(0, -1);\n }\n return name;\n}\n\n/**\n * Simple pluralize function for English words.\n * @example 'user' -> 'users'\n * @example 'category' -> 'categories'\n */\nexport function pluralize(name: string): string {\n if (!name) return '';\n if (name.endsWith('y') && name.length > 1 && !/[aeiou]/.test(name[name.length - 2])) {\n return name.slice(0, -1) + 'ies';\n }\n if (name.endsWith('s') || name.endsWith('x') || name.endsWith('z') || name.endsWith('ch') || name.endsWith('sh')) {\n return name + 'es';\n }\n return name + 's';\n}\n\n/**\n * The FNV-1a hash of `value`, written by hand because the package has zero runtime dependencies and the\n * browser and edge entries cannot reach `node:crypto`. It is not a security hash; it only tells inputs apart.\n */\nexport function fnv1a(value: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash;\n}\n\n/** `text` as a regex matching it literally. */\nexport function escapeRegExp(text: string): string {\n return text.replaceAll(/[\\\\^$.*+?()[\\]{}|]/g, '\\\\$&');\n}\n",
13
- "import { queryErrorKind } from '../querier/queryError.js';\nimport type { AbstractType, UniversalQuerier } from '../type/index.js';\n// the specific util modules, not the barrel, so the browser bundle does not pull in entity metadata\nimport { getKeys } from '../util/object.util.js';\nimport { kebabCase } from '../util/string.util.js';\nimport type { QueryErrorKind } from '../util/uqlError.js';\n\ntype RouteShape = {\n readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly path: '' | `/${string}`;\n};\n\n/**\n * Single source of truth for the CRUD-over-HTTP surface, shared by server adapters and the browser client.\n * Keys are constrained to {@link UniversalQuerier} method names, so renaming a querier method\n * (or routing a non-existent one) is a compile error.\n */\nexport const CRUD_ROUTES = {\n findMany: { method: 'GET', path: '' },\n findManyPage: { method: 'GET', path: '/page' },\n findOne: { method: 'GET', path: '/one' },\n count: { method: 'GET', path: '/count' },\n findOneById: { method: 'GET', path: '/:id' },\n insertOne: { method: 'POST', path: '' },\n insertMany: { method: 'POST', path: '/many' },\n saveOne: { method: 'PUT', path: '' },\n saveMany: { method: 'PUT', path: '/many' },\n updateMany: { method: 'PATCH', path: '' },\n updateOneById: { method: 'PATCH', path: '/:id' },\n deleteOneById: { method: 'DELETE', path: '/:id' },\n deleteMany: { method: 'DELETE', path: '' },\n} as const satisfies Partial<Record<keyof UniversalQuerier, RouteShape>>;\n\nexport type CrudOperation = keyof typeof CRUD_ROUTES;\n\nexport type CrudRoute = (typeof CRUD_ROUTES)[CrudOperation];\n\n/**\n * `QUERY` (RFC 10008) is an alternate transport for the read operations: same semantics as the\n * GET routes, but the JSON query travels in the request body instead of the query string,\n * avoiding URL-length limits for large queries.\n */\nexport type HttpMethod = CrudRoute['method'] | 'QUERY';\n\nconst CRUD_OPS = getKeys(CRUD_ROUTES);\n\n// derived from CRUD_ROUTES (the literal-path GET routes) so the sub-paths live in exactly one place\nconst QUERY_READ_OPS: ReadonlyMap<string, CrudOperation> = new Map(\n CRUD_OPS.filter((op) => CRUD_ROUTES[op].method === 'GET' && CRUD_ROUTES[op].path !== '/:id').map((op) => [\n CRUD_ROUTES[op].path,\n op,\n ]),\n);\n\n/**\n * URL segment for an entity, e.g. `entityPath(UserProfile) === 'user-profile'`.\n */\nexport function entityPath<E>(entity: AbstractType<E>): string {\n return kebabCase(entity.name);\n}\n\nexport type RouteMatch = {\n readonly op: CrudOperation;\n /**\n * the resolved transport method - differs from the op's canonical route method for QUERY.\n */\n readonly method: HttpMethod;\n readonly id?: string;\n};\n\n/**\n * Resolve a (method, sub-path) pair to a CRUD operation. Literal sub-paths win over `:id`.\n */\nexport function matchRoute(method: string, subPath: string | undefined): RouteMatch | undefined {\n const raw = method.toUpperCase();\n const literal = subPath === undefined ? '' : `/${subPath}`;\n if (raw === 'QUERY') {\n const op = QUERY_READ_OPS.get(literal);\n return op ? { op, method: 'QUERY' } : undefined;\n }\n // HEAD reads like GET per HTTP semantics; the server runtime omits the response body\n const verb = raw === 'HEAD' ? 'GET' : raw;\n let idOp: CrudOperation | undefined;\n for (const op of CRUD_OPS) {\n const route = CRUD_ROUTES[op];\n if (route.method !== verb) {\n continue;\n }\n if (route.path === literal) {\n return { op, method: route.method };\n }\n if (route.path === '/:id') {\n idOp = op;\n }\n }\n return idOp && subPath !== undefined ? { op: idOp, method: CRUD_ROUTES[idOp].method, id: subPath } : undefined;\n}\n\nexport type RequestErrorResponse = {\n readonly error: {\n readonly message: string;\n readonly code: number;\n };\n};\n\n/** Generic on purpose: a driver's constraint message names tables and constraints, and Postgres echoes the value. */\nconst CONSTRAINT_ERRORS: ReadonlyMap<QueryErrorKind | undefined, RequestErrorResponse['error']> = new Map([\n ['uniqueViolation', { message: 'Conflict', code: 409 }],\n ['foreignKeyViolation', { message: 'Conflict', code: 409 }],\n ['notNullViolation', { message: 'Bad Request', code: 400 }],\n ['checkViolation', { message: 'Bad Request', code: 400 }],\n]);\n\n/**\n * Map a thrown error to the wire error envelope. Honors a numeric `status` on the error\n * (e.g. hooks throwing 403), then a constraint violation (409/400), defaults to 500; `code` mirrors the HTTP status.\n */\nexport function toErrorResponse(err: unknown): { status: number; body: RequestErrorResponse } {\n const error =\n err instanceof Error && 'status' in err && typeof err.status === 'number'\n ? { message: err.message, code: err.status }\n : (CONSTRAINT_ERRORS.get(queryErrorKind(err)) ?? {\n message: err instanceof Error ? err.message : 'Internal Server Error',\n code: 500,\n });\n return { status: error.code, body: { error } };\n}\n",
14
- "import { CRUD_ROUTES, entityPath, type HttpMethod } from '../../http/contract.js';\nimport { stringifyQuery } from '../../http/query.js';\nimport type { EntityId, SharedQuerier, AbstractType } from '../../type/index.js';\nimport { isScalarId } from '../../util/object.util.js';\nimport { UqlUsageError } from '../../util/uqlError.js';\nimport { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';\nimport type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';\n\nexport type HttpQuerierDefaults = {\n /**\n * headers sent with every request from this instance, merged under per-call headers.\n * Create one instance per request (e.g. during SSR) to scope auth headers safely.\n */\n readonly headers?: Record<string, string>;\n /**\n * transport for read queries (findOne, findMany, findManyPage, count). 'QUERY' (RFC 10008) sends the\n * JSON query in the request body, avoiding URL-length limits for large queries; requires\n * infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.\n */\n readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;\n /**\n * The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same\n * option the server handler takes, so one map serves both. State it where the default cannot: a\n * build that minifies class names renames every route.\n */\n readonly entityPath?: (entity: AbstractType<unknown>) => string;\n};\n\n/** The id as one path segment, refusing a composite key, which has no spelling in `/:id` yet. Callers are `async`. */\nfunction idSegment<E>(entity: AbstractType<E>, id: EntityId<E>): string {\n if (!isScalarId(id)) {\n throw new UqlUsageError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);\n }\n return String(id);\n}\n\nexport class HttpQuerier implements ClientQuerier {\n constructor(\n readonly basePath: string,\n readonly defaults: HttpQuerierDefaults = {},\n ) {}\n\n // Typed properties instead of methods, so each takes its signature from `ClientQuerier` rather than repeating it.\n readonly findOneById: ClientQuerier['findOneById'] = async (entity, id, q, opts) =>\n get(`${this.getBasePath(entity)}/${idSegment(entity, id)}${stringifyQuery(q)}`, this.buildOptions(opts));\n\n readonly findOne: ClientQuerier['findOne'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`, q, opts);\n\n readonly findMany: SharedQuerier<'client', RequestFindOptions>['findMany'] = (entity, q, opts) =>\n this.read(this.getBasePath(entity), opts?.count ? { ...q, count: true } : q, opts);\n\n readonly findManyAndCount: SharedQuerier<'client', RequestFindOptions>['findManyAndCount'] = async (\n entity,\n q,\n opts,\n ) => {\n const response = await this.findMany(entity, q, { ...opts, count: true });\n if (typeof response.count !== 'number') {\n throw new TypeError('findManyAndCount response has an invalid count');\n }\n return { ...response, count: response.count };\n };\n\n readonly findManyPage: ClientQuerier['findManyPage'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findManyPage.path}`, q, opts);\n\n readonly count: ClientQuerier['count'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);\n\n /** The `count` route capped at one row, so existence needs no endpoint of its own. */\n readonly exists: ClientQuerier['exists'] = async (entity, q, opts) => {\n const res = await this.count(entity, { ...q, $limit: 1 }, opts);\n return { ...res, data: res.data > 0 };\n };\n\n readonly insertOne: ClientQuerier['insertOne'] = (entity, payload, opts) =>\n post(this.getBasePath(entity), payload, this.buildOptions(opts));\n\n readonly insertMany: ClientQuerier['insertMany'] = (entity, payload, opts) =>\n post(`${this.getBasePath(entity)}${CRUD_ROUTES.insertMany.path}`, payload, this.buildOptions(opts));\n\n readonly updateOneById: ClientQuerier['updateOneById'] = async (entity, id, payload, opts) =>\n patch(`${this.getBasePath(entity)}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));\n\n readonly updateMany: ClientQuerier['updateMany'] = (entity, q, payload, opts) =>\n patch(`${this.getBasePath(entity)}${stringifyQuery(q)}`, payload, this.buildOptions(opts));\n\n readonly saveOne: ClientQuerier['saveOne'] = (entity, payload, opts) =>\n put(this.getBasePath(entity), payload, this.buildOptions(opts));\n\n readonly saveMany: ClientQuerier['saveMany'] = (entity, payload, opts) =>\n put(`${this.getBasePath(entity)}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts));\n\n readonly deleteOneById: ClientQuerier['deleteOneById'] = async (entity, id, opts = {}) => {\n const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';\n return remove(`${this.getBasePath(entity)}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));\n };\n\n readonly deleteMany: ClientQuerier['deleteMany'] = (entity, q, opts = {}) =>\n remove(\n `${this.getBasePath(entity)}${stringifyQuery(opts.hardDelete ? { ...q, hardDelete: opts.hardDelete } : q)}`,\n this.buildOptions(opts),\n );\n\n getBasePath<E>(entity: AbstractType<E>) {\n return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;\n }\n\n protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions) {\n if (this.defaults.readMethod === 'QUERY') {\n return httpQuery<T>(path, q ?? {}, this.buildOptions(opts));\n }\n return get<T>(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));\n }\n\n protected buildOptions(opts?: RequestOptions): RequestOptions | undefined {\n if (!this.defaults.headers && !opts?.headers) {\n return opts;\n }\n return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };\n }\n}\n"
15
- ],
16
- "mappings": "AAEA,IAAM,EAAe,IAAI,IAElB,SAAS,CAAM,CAAC,EAAyC,CAC9D,QAAW,KAAe,EACxB,EAAY,CAAY,EAIrB,SAAS,CAAE,CAAC,EAAiC,CAElD,OADA,EAAa,IAAI,CAAE,EACZ,IAAY,CACjB,EAAa,OAAO,CAAE,GCiVnB,IAAM,EAAgB,CAC3B,QAAS,CAAE,MAAO,SAAU,MAAO,UAAW,EAC9C,UAAW,CAAE,MAAO,SAAU,MAAO,UAAW,EAChD,OAAQ,CAAE,MAAO,SAAU,MAAO,UAAW,EAC7C,MAAO,CAAE,MAAO,SAAU,MAAO,UAAW,EAC5C,MAAO,CAAE,MAAO,SAAU,MAAO,UAAW,EAC5C,OAAQ,CAAE,MAAO,SAAU,MAAO,UAAW,EAC7C,UAAW,CAAE,MAAO,UAAW,MAAO,UAAW,EAEjD,OAAQ,CAAE,MAAO,SAAU,MAAO,WAAY,EAE9C,YAAa,CAAE,MAAO,SAAU,MAAO,WAAY,EAEnD,MAAO,CAAE,MAAO,SAAU,MAAO,YAAa,KAAM,EAAM,EAE1D,OAAQ,CAAE,MAAO,SAAU,MAAO,WAAY,EAC9C,QAAS,CAAE,MAAO,SAAU,MAAO,WAAY,CACjD,EC3UO,IAAM,EAAwB,OAAO,OAAO,EACtC,EAA2B,OAAO,UAAU,EAC5C,EAA0B,OAAO,SAAS,EAE1C,EAAgC,OAAO,cAAc,EAErD,EAAyB,OAAO,QAAQ,EAGxC,EAA4B,OAAO,WAAW,EAE9C,EAA2B,OAAO,UAAU,EAE5C,EAA4B,OAAO,WAAW,ECiDpD,SAAS,CAAyB,CAAC,EAAiD,CACzF,OAAO,EAAO,OAAO,KAAK,CAAG,EAA6B,CAAC,EAsBtD,SAAS,CAAU,CAAC,EAAyB,CAClD,GAAI,OAAO,IAAU,UAAY,IAAU,KACzC,MAAO,GAET,GAAI,MAAM,QAAQ,CAAK,EACrB,MAAO,GAKT,IAAM,EAAQ,OAAO,eAAe,CAAK,EACzC,OAAO,IAAU,OAAO,WAAa,IAAU,KCnH1C,MAAe,UAAiB,KAAM,CAG7C,CAOO,MAAM,UAAsB,CAAS,CACjC,KAAO,gBACP,KAAO,QACP,OAAS,GACpB,CCnBA,IAAM,EAAa,CAAC,aAAc,OAAO,EAcnC,GAAyD,IAAI,IAAI,CACrE,GAAG,EAAQ,CAAa,EACrB,OAAO,CAAC,IAAQ,EAAgB,EAAc,EAAI,CAAC,EACnD,IAAI,CAAC,IAAQ,CAAC,EAAK,EAAc,GAAK,KAAK,CAAU,EACxD,GAAG,EAAW,IAAI,CAAC,IAAS,CAAC,EAAM,SAAS,CAAU,CACxD,CAAC,EAED,SAAS,CAAe,CAAC,EAA8B,CACrD,OAAO,EAAO,OAAS,GA6DlB,SAAS,CAAc,CAAC,EAAyC,CACtE,GAAI,CAAC,EACH,MAAO,GAET,IAAM,EAAS,IAAI,gBACnB,QAAW,KAAO,EAAQ,CAAK,EAAG,CAChC,IAAM,EAAQ,EAAM,GACpB,GAAI,IAAU,OACZ,SAEF,EAAO,OAAO,EAAK,OAAO,IAAU,UAAY,IAAU,KAAO,EAAS,CAAK,EAAI,OAAO,CAAK,CAAC,EAElG,IAAM,EAAK,EAAO,SAAS,EAC3B,OAAO,EAAK,IAAI,IAAO,GAUlB,SAAS,CAAQ,CAAC,EAAwB,CAC/C,OAAO,KAAK,UAAU,EAAO,CAAC,EAAc,IAAkB,CAC5D,GAAI,OAAO,IAAS,UAAY,IAAS,KACvC,OAAO,EAET,GAAI,KAAU,EACZ,MAAM,IAAI,EAAc,kEAAkE,EAG5F,GAAI,aAAgB,aAAe,YAAY,OAAO,CAAI,EACxD,MAAM,IAAI,EAAc,iEAAiE,EAE3F,OAAO,EACR,ECzHI,MAAM,UAAqB,KAAM,CAG3B,OAFX,WAAW,CACT,EACS,EACT,CACA,MAAM,CAAO,EAFJ,cAGT,KAAK,KAAO,eAEhB,CAIO,SAAS,CAAM,CAAC,EAAa,EAAuB,CACzD,OAAO,EAAW,EAAK,CAAE,OAAQ,KAAM,EAAG,CAAI,EAGzC,SAAS,CAAO,CAAC,EAAa,EAAkB,EAAuB,CAC5E,OAAO,EAAW,EAAK,CAAE,OAAQ,OAAQ,KAAM,EAAS,CAAO,CAAE,EAAG,CAAI,EAGnE,SAAS,CAAQ,CAAC,EAAa,EAAkB,EAAuB,CAC7E,OAAO,EAAW,EAAK,CAAE,OAAQ,QAAS,KAAM,EAAS,CAAO,CAAE,EAAG,CAAI,EAGpE,SAAS,CAAM,CAAC,EAAa,EAAkB,EAAuB,CAC3E,OAAO,EAAW,EAAK,CAAE,OAAQ,MAAO,KAAM,EAAS,CAAO,CAAE,EAAG,CAAI,EAGlE,SAAS,CAAS,CAAC,EAAa,EAAuB,CAC5D,OAAO,EAAW,EAAK,CAAE,OAAQ,QAAS,EAAG,CAAI,EAO5C,SAAS,CAAQ,CAAC,EAAa,EAAkB,EAAuB,CAC7E,OAAO,EAAW,EAAK,CAAE,OAAQ,QAAS,KAAM,EAAS,CAAO,CAAE,EAAG,CAAI,EAG3E,SAAS,CAAU,CAAC,EAAa,EAAmB,EAAuB,CAQzE,GAPA,EAAO,CAAE,MAAO,QAAS,MAAK,CAAC,EAE/B,EAAK,QAAU,CACb,OAAQ,mBACR,eAAgB,sBACb,GAAM,OACX,EACI,GAAM,OACR,EAAK,OAAS,EAAK,OAGrB,OAAO,MAAM,EAAK,CAAI,EACnB,KAAK,CAAC,IACL,EAAQ,KAAK,EAAE,KAAK,CAAC,IAAkB,CAErC,GADkB,EAAQ,QAAU,KAAO,EAAQ,OAAS,IAG1D,OADA,EAAO,CAAE,MAAO,UAAW,MAAK,CAAC,EAC1B,EAET,IAAM,EAAY,EACZ,EAAQ,CACZ,QAAS,GAAW,OAAO,SAAW,EAAQ,WAC9C,KAAM,GAAW,OAAO,MAAQ,EAAQ,MAC1C,EAEA,MADA,EAAO,CAAE,MAAO,QAAS,QAAO,MAAK,CAAC,EAChC,IAAI,EAAa,EAAM,QAAS,EAAM,IAAI,EACjD,CACH,EACC,QAAQ,IAAM,CACb,EAAO,CAAE,MAAO,WAAY,MAAK,CAAC,EACnC,ECjFE,SAAS,CAAS,CAAC,EAAqB,CAC7C,IAAI,EAAO,EAAI,OAAO,CAAC,EAAE,YAAY,EACrC,QAAS,EAAI,EAAG,EAAI,EAAI,OAAQ,EAAE,EAChC,GAAQ,EAAI,KAAO,EAAI,GAAG,YAAY,EAAI,IAAM,EAAI,GAAG,YAAY,EAAI,EAAI,GAE7E,OAAO,ECYF,IAAM,EAAc,CACzB,SAAU,CAAE,OAAQ,MAAO,KAAM,EAAG,EACpC,aAAc,CAAE,OAAQ,MAAO,KAAM,OAAQ,EAC7C,QAAS,CAAE,OAAQ,MAAO,KAAM,MAAO,EACvC,MAAO,CAAE,OAAQ,MAAO,KAAM,QAAS,EACvC,YAAa,CAAE,OAAQ,MAAO,KAAM,MAAO,EAC3C,UAAW,CAAE,OAAQ,OAAQ,KAAM,EAAG,EACtC,WAAY,CAAE,OAAQ,OAAQ,KAAM,OAAQ,EAC5C,QAAS,CAAE,OAAQ,MAAO,KAAM,EAAG,EACnC,SAAU,CAAE,OAAQ,MAAO,KAAM,OAAQ,EACzC,WAAY,CAAE,OAAQ,QAAS,KAAM,EAAG,EACxC,cAAe,CAAE,OAAQ,QAAS,KAAM,MAAO,EAC/C,cAAe,CAAE,OAAQ,SAAU,KAAM,MAAO,EAChD,WAAY,CAAE,OAAQ,SAAU,KAAM,EAAG,CAC3C,EAaM,EAAW,EAAQ,CAAW,EAG9B,GAAqD,IAAI,IAC7D,EAAS,OAAO,CAAC,IAAO,EAAY,GAAI,SAAW,OAAS,EAAY,GAAI,OAAS,MAAM,EAAE,IAAI,CAAC,IAAO,CACvG,EAAY,GAAI,KAChB,CACF,CAAC,CACH,EAKO,SAAS,CAAa,CAAC,EAAiC,CAC7D,OAAO,EAAU,EAAO,IAAI,EC7B9B,SAAS,CAAY,CAAC,EAAyB,EAAyB,CACtE,GAAI,CAAC,EAAW,CAAE,EAChB,MAAM,IAAI,EAAc,IAAI,EAAO,yEAAyE,EAE9G,OAAO,OAAO,CAAE,EAGX,MAAM,CAAqC,CAErC,SACA,SAFX,WAAW,CACA,EACA,EAAgC,CAAC,EAC1C,CAFS,gBACA,gBAIF,YAA4C,MAAO,EAAQ,EAAI,EAAG,IACzE,EAAI,GAAG,KAAK,YAAY,CAAM,KAAK,EAAU,EAAQ,CAAE,IAAI,EAAe,CAAC,IAAK,KAAK,aAAa,CAAI,CAAC,EAEhG,QAAoC,CAAC,EAAQ,EAAG,IACvD,KAAK,KAAK,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,QAAQ,OAAQ,EAAG,CAAI,EAEpE,SAAoE,CAAC,EAAQ,EAAG,IACvF,KAAK,KAAK,KAAK,YAAY,CAAM,EAAG,GAAM,MAAQ,IAAK,EAAG,MAAO,EAAK,EAAI,EAAG,CAAI,EAE1E,iBAAoF,MAC3F,EACA,EACA,IACG,CACH,IAAM,EAAW,MAAM,KAAK,SAAS,EAAQ,EAAG,IAAK,EAAM,MAAO,EAAK,CAAC,EACxE,GAAI,OAAO,EAAS,QAAU,SAC5B,MAAU,UAAU,gDAAgD,EAEtE,MAAO,IAAK,EAAU,MAAO,EAAS,KAAM,GAGrC,aAA8C,CAAC,EAAQ,EAAG,IACjE,KAAK,KAAK,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,aAAa,OAAQ,EAAG,CAAI,EAEzE,MAAgC,CAAC,EAAQ,EAAG,IACnD,KAAK,KAAK,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,MAAM,OAAQ,EAAG,CAAI,EAGlE,OAAkC,MAAO,EAAQ,EAAG,IAAS,CACpE,IAAM,EAAM,MAAM,KAAK,MAAM,EAAQ,IAAK,EAAG,OAAQ,CAAE,EAAG,CAAI,EAC9D,MAAO,IAAK,EAAK,KAAM,EAAI,KAAO,CAAE,GAG7B,UAAwC,CAAC,EAAQ,EAAS,IACjE,EAAK,KAAK,YAAY,CAAM,EAAG,EAAS,KAAK,aAAa,CAAI,CAAC,EAExD,WAA0C,CAAC,EAAQ,EAAS,IACnE,EAAK,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,WAAW,OAAQ,EAAS,KAAK,aAAa,CAAI,CAAC,EAE3F,cAAgD,MAAO,EAAQ,EAAI,EAAS,IACnF,EAAM,GAAG,KAAK,YAAY,CAAM,KAAK,EAAU,EAAQ,CAAE,IAAK,EAAS,KAAK,aAAa,CAAI,CAAC,EAEvF,WAA0C,CAAC,EAAQ,EAAG,EAAS,IACtE,EAAM,GAAG,KAAK,YAAY,CAAM,IAAI,EAAe,CAAC,IAAK,EAAS,KAAK,aAAa,CAAI,CAAC,EAElF,QAAoC,CAAC,EAAQ,EAAS,IAC7D,EAAI,KAAK,YAAY,CAAM,EAAG,EAAS,KAAK,aAAa,CAAI,CAAC,EAEvD,SAAsC,CAAC,EAAQ,EAAS,IAC/D,EAAI,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,SAAS,OAAQ,EAAS,KAAK,aAAa,CAAI,CAAC,EAExF,cAAgD,MAAO,EAAQ,EAAI,EAAO,CAAC,IAAM,CACxF,IAAM,EAAK,EAAK,WAAa,EAAe,CAAE,WAAY,EAAK,UAAW,CAAC,EAAI,GAC/E,OAAO,EAAO,GAAG,KAAK,YAAY,CAAM,KAAK,EAAU,EAAQ,CAAE,IAAI,IAAM,KAAK,aAAa,CAAI,CAAC,GAG3F,WAA0C,CAAC,EAAQ,EAAG,EAAO,CAAC,IACrE,EACE,GAAG,KAAK,YAAY,CAAM,IAAI,EAAe,EAAK,WAAa,IAAK,EAAG,WAAY,EAAK,UAAW,EAAI,CAAC,IACxG,KAAK,aAAa,CAAI,CACxB,EAEF,WAAc,CAAC,EAAyB,CACtC,MAAO,GAAG,KAAK,aAAa,KAAK,SAAS,YAAc,GAAY,CAAM,IAGlE,IAAO,CAAC,EAAc,EAAwC,EAAuB,CAC7F,GAAI,KAAK,SAAS,aAAe,QAC/B,OAAO,EAAa,EAAM,GAAK,CAAC,EAAG,KAAK,aAAa,CAAI,CAAC,EAE5D,OAAO,EAAO,GAAG,IAAO,EAAe,CAAC,IAAK,KAAK,aAAa,CAAI,CAAC,EAG5D,YAAY,CAAC,EAAmD,CACxE,GAAI,CAAC,KAAK,SAAS,SAAW,CAAC,GAAM,QACnC,OAAO,EAET,MAAO,IAAK,EAAM,QAAS,IAAK,KAAK,SAAS,WAAY,GAAM,OAAQ,CAAE,EAE9E",
17
- "debugId": "41A453F874C392D864756E2164756E21",
18
- "names": []
19
- }