uql-orm 0.112.0 → 0.113.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +1 -1
  2. package/dist/browser/http/httpTransport.d.ts +29 -0
  3. package/dist/browser/http/httpTransport.js +59 -0
  4. package/dist/browser/http/index.d.ts +1 -2
  5. package/dist/browser/http/index.js +1 -2
  6. package/dist/browser/index.d.ts +1 -0
  7. package/dist/browser/querier/clientQuerier.d.ts +7 -0
  8. package/dist/browser/querier/clientQuerier.js +43 -0
  9. package/dist/browser/querier/index.d.ts +2 -1
  10. package/dist/browser/querier/index.js +2 -1
  11. package/dist/browser/querier/queryOptions.d.ts +23 -0
  12. package/dist/browser/querier/queryOptions.js +35 -0
  13. package/dist/browser/type/clientQuerier.d.ts +10 -11
  14. package/dist/browser/type/index.d.ts +1 -1
  15. package/dist/browser/type/index.js +1 -1
  16. package/dist/browser/type/transport.d.ts +13 -0
  17. package/dist/dialect/abstractDialect.d.ts +2 -2
  18. package/dist/dialect/abstractSqlDialect.js +3 -3
  19. package/dist/dialect/jsonSql.js +2 -3
  20. package/dist/dialect/operators.js +4 -5
  21. package/dist/express/index.d.ts +1 -1
  22. package/dist/express/index.js +1 -1
  23. package/dist/express/router.d.ts +8 -0
  24. package/dist/express/router.js +50 -0
  25. package/dist/http/api.d.ts +36 -0
  26. package/dist/http/api.js +136 -0
  27. package/dist/http/apiCall.d.ts +59 -0
  28. package/dist/http/apiCall.js +52 -0
  29. package/dist/http/errors.d.ts +20 -0
  30. package/dist/http/errors.js +27 -0
  31. package/dist/http/exposure.d.ts +54 -0
  32. package/dist/http/exposure.js +171 -0
  33. package/dist/http/handler.d.ts +23 -88
  34. package/dist/http/handler.js +42 -155
  35. package/dist/http/index.d.ts +8 -4
  36. package/dist/http/index.js +6 -3
  37. package/dist/http/route.d.ts +34 -0
  38. package/dist/http/route.js +82 -0
  39. package/dist/http/wireCall.d.ts +115 -0
  40. package/dist/http/wireCall.js +126 -0
  41. package/dist/http/wireQuery.d.ts +8 -0
  42. package/dist/http/wireQuery.js +51 -0
  43. package/dist/http/wireRow.d.ts +20 -0
  44. package/dist/http/wireRow.js +170 -0
  45. package/dist/index.d.ts +1 -1
  46. package/dist/index.js +1 -1
  47. package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -1
  48. package/dist/migrate/introspection/mysqlIntrospector.js +12 -2
  49. package/dist/mongodb/mongoDialect.d.ts +6 -6
  50. package/dist/mongodb/mongoDialect.js +6 -6
  51. package/dist/mongodb/mongodbQuerier.d.ts +8 -8
  52. package/dist/mssql/mssqlDialect.js +2 -2
  53. package/dist/nestjs/uqlContextInterceptor.d.ts +3 -3
  54. package/dist/nestjs/uqlContextInterceptor.js +7 -7
  55. package/dist/nestjs/uqlModule.d.ts +5 -11
  56. package/dist/nestjs/uqlModule.js +10 -15
  57. package/dist/querier/abstractQuerier.d.ts +8 -8
  58. package/dist/querier/abstractQuerier.js +15 -8
  59. package/dist/querier/abstractSqlQuerier.d.ts +8 -8
  60. package/dist/querier/keyset.d.ts +15 -0
  61. package/dist/querier/keyset.js +16 -11
  62. package/dist/sqlite/localSqliteQuerierPool.d.ts +1 -1
  63. package/dist/type/column.d.ts +4 -1
  64. package/dist/type/querier.d.ts +2 -2
  65. package/dist/type/query.d.ts +18 -4
  66. package/dist/type/universalQuerier.d.ts +16 -16
  67. package/dist/type/wire.d.ts +1 -31
  68. package/dist/util/dialect.util.d.ts +9 -16
  69. package/dist/util/dialect.util.js +20 -26
  70. package/dist/util/field.util.d.ts +4 -1
  71. package/dist/util/field.util.js +5 -2
  72. package/dist/util/object.util.d.ts +5 -2
  73. package/dist/util/object.util.js +12 -15
  74. package/dist/util/query.util.js +3 -10
  75. package/dist/util/uqlError.d.ts +27 -1
  76. package/dist/util/uqlError.js +43 -0
  77. package/package.json +5 -10
  78. package/skills/uql-orm/SKILL.md +4 -1
  79. package/dist/browser/http/bus.d.ts +0 -3
  80. package/dist/browser/http/bus.js +0 -12
  81. package/dist/browser/http/http.d.ts +0 -20
  82. package/dist/browser/http/http.js +0 -67
  83. package/dist/browser/querier/httpQuerier.d.ts +0 -46
  84. package/dist/browser/querier/httpQuerier.js +0 -64
  85. package/dist/browser/type/request.d.ts +0 -27
  86. package/dist/browser/uql-browser.min.js +0 -4
  87. package/dist/browser/uql-browser.min.js.map +0 -19
  88. package/dist/express/querierMiddleware.d.ts +0 -11
  89. package/dist/express/querierMiddleware.js +0 -39
  90. package/dist/http/contract.d.ts +0 -98
  91. package/dist/http/contract.js +0 -83
  92. package/dist/http/fetchHandler.d.ts +0 -13
  93. package/dist/http/fetchHandler.js +0 -63
  94. package/dist/http/query.d.ts +0 -28
  95. package/dist/http/query.js +0 -119
  96. /package/dist/browser/type/{request.js → transport.js} +0 -0
@@ -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. */
@@ -433,16 +433,24 @@ export function applyFilters(meta, whereMap, opts) {
433
433
  }
434
434
  }
435
435
  const merged = result;
436
- const security = securityConditions(meta).map(([, condition]) => condition);
436
+ const security = securityConditions(meta, SCOPED_BY[opts?.access ?? 'read']).map(([, condition]) => condition);
437
437
  return security.length ? whereAnd(merged, security) : merged;
438
438
  }
439
+ /** The accesses whose `security` filters scope a statement: an update or a delete reads the rows it changes too. */
440
+ const SCOPED_BY = {
441
+ read: ['read'],
442
+ insert: ['insert'],
443
+ update: ['read', 'update'],
444
+ delete: ['read', 'delete'],
445
+ };
439
446
  /**
440
- * Each `security` filter's condition, by name, resolved against the ambient context. One resolving to
441
- * `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
447
+ * The condition of each `security` filter holding any of `accesses`, by name, resolved against the ambient context.
448
+ * One resolving to `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
442
449
  */
443
- export function securityConditions(meta) {
450
+ export function securityConditions(meta, accesses) {
444
451
  return Object.entries(meta.filters ?? {}).flatMap(([name, filter]) => {
445
- const condition = filter.security ? resolveFilter(meta, name, filter) : undefined;
452
+ const holds = filter.security && (!filter.ops || filter.ops.some((op) => accesses.includes(op)));
453
+ const condition = holds ? resolveFilter(meta, name, filter) : undefined;
446
454
  return condition && hasKeys(condition) ? [[name, condition]] : [];
447
455
  });
448
456
  }
@@ -462,7 +470,7 @@ function resolveFilter(meta, name, filter) {
462
470
  * See architecture/security-filter-writes.md.
463
471
  */
464
472
  export function guardWrite(meta, rows, write) {
465
- for (const [name, condition] of securityConditions(meta)) {
473
+ for (const [name, condition] of securityConditions(meta, [write])) {
466
474
  const values = condition;
467
475
  const keys = fieldKeys(meta, () => true).filter((key) => Object.hasOwn(values, key));
468
476
  const equalities = keys.length === getKeys(values).length;
@@ -571,29 +579,15 @@ function aggregateField(alias, arg) {
571
579
  function namedKeys(map) {
572
580
  return isRecord(map) ? getKeys(map).filter((key) => map[key]) : [];
573
581
  }
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
582
  /** A JSON object, matched by what it holds: a plain object with no operator key. */
589
583
  export function isJsonObject(value) {
590
- return isOperatorMap(value) && !isOperatorObject(value);
584
+ return isPlainObject(value) && !isOperatorObject(value);
591
585
  }
592
586
  /**
593
- * A page operand, checked before it reaches an engine. These arrive from page arithmetic and from
594
- * REST query strings (`parseQueryParams` yields `NaN` for a non-numeric one), and each engine's own
595
- * complaint names neither the clause nor the value - or, for `$limit: 0`, quietly means something
596
- * else. Shared so every backend rejects the same input.
587
+ * A page operand, checked before it reaches an engine. These arrive from page arithmetic and from a
588
+ * client's call, where JSON carries a fraction or a negative alike, and each engine's own complaint
589
+ * names neither the clause nor the value - or, for `$limit: 0`, quietly means something else.
590
+ * Shared so every backend rejects the same input.
597
591
  */
598
592
  export function assertNonNegativeInteger(value, clause) {
599
593
  if (!Number.isInteger(value) || value < 0) {
@@ -54,7 +54,10 @@ export declare function lacksValue(column: {
54
54
  * holds a value too, unlike on the rows a migration finds.
55
55
  */
56
56
  export declare function lacksValueOnInsert(field: FieldOptions): boolean;
57
- /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
57
+ /**
58
+ * Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key: an own key alone, so
59
+ * a client's `constructor` is none.
60
+ */
58
61
  export declare function isFieldKey<E>(meta: EntityMeta<E>, key: string): key is FieldKey<E>;
59
62
  /** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
60
63
  export declare function fieldKeys<E>(meta: EntityMeta<E>, pick: (field: FieldMeta) => unknown): FieldKey<E>[];
@@ -107,9 +107,12 @@ export function lacksValueOnInsert(field) {
107
107
  isAutoIncrement: field.autoIncrement === true,
108
108
  }));
109
109
  }
110
- /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
110
+ /**
111
+ * Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key: an own key alone, so
112
+ * a client's `constructor` is none.
113
+ */
111
114
  export function isFieldKey(meta, key) {
112
- return meta.fields[key] !== undefined;
115
+ return Object.hasOwn(meta.fields, key) && meta.fields[key] !== undefined;
113
116
  }
114
117
  /** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
115
118
  export function fieldKeys(meta, pick) {
@@ -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 }],
@@ -4,11 +4,26 @@
4
4
  * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
5
5
  * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.
6
6
  */
7
- export type QueryErrorKind = 'uniqueViolation' | 'foreignKeyViolation' | 'notNullViolation' | 'checkViolation' | 'optimisticLock' | 'retryable' | 'usage' | 'security';
7
+ export declare const QUERY_ERROR_KINDS: readonly ['uniqueViolation', 'foreignKeyViolation', 'notNullViolation', 'checkViolation', 'optimisticLock', 'retryable', 'usage', 'security'];
8
+ export type QueryErrorKind = (typeof QUERY_ERROR_KINDS)[number];
9
+ export declare function isQueryErrorKind(value: unknown): value is QueryErrorKind;
10
+ /**
11
+ * Where in a call the refused value sits, as `['query', '$where', 'password']`: a form highlights the field by it. A
12
+ * querier's refusal names it within the query, `['$limit']`, which the API places within the call.
13
+ */
14
+ export type UqlErrorPath = readonly (string | number)[];
15
+ export type UqlErrorOptions = ErrorOptions & {
16
+ readonly path?: UqlErrorPath;
17
+ /** What HTTP answers beside the status, as a 405's `allow`. */
18
+ readonly headers?: Readonly<Record<string, string>>;
19
+ };
8
20
  /** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */
9
21
  export declare abstract class UqlError extends Error {
10
22
  abstract readonly kind: QueryErrorKind;
11
23
  abstract readonly status: number;
24
+ readonly path?: UqlErrorPath;
25
+ readonly headers?: Readonly<Record<string, string>>;
26
+ constructor(message?: string, opts?: UqlErrorOptions);
12
27
  }
13
28
  /**
14
29
  * Thrown where the caller used the API in a way no statement can carry out: an update payload with no
@@ -20,6 +35,17 @@ export declare class UqlUsageError extends UqlError {
20
35
  readonly kind = "usage";
21
36
  readonly status = 400;
22
37
  }
38
+ /**
39
+ * A request refused with a 4xx `status`: what the API answers a route nothing serves (404), a method its op does
40
+ * not take (405, naming the ones it does in `allow`) or a body that is not JSON (415) with, and what a middleware or
41
+ * a hook throws to refuse a client, `new UqlRequestError('unauthorized', 401)`: only a `UqlError` reaches one.
42
+ */
43
+ export declare class UqlRequestError extends UqlError {
44
+ readonly status: number;
45
+ name: string;
46
+ readonly kind = "usage";
47
+ constructor(message: string, status: number, opts?: UqlErrorOptions);
48
+ }
23
49
  /**
24
50
  * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
25
51
  * Fails the statement closed.
@@ -1,5 +1,34 @@
1
+ /**
2
+ * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers
3
+ * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization
4
+ * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
5
+ * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.
6
+ */
7
+ export const QUERY_ERROR_KINDS = [
8
+ 'uniqueViolation',
9
+ 'foreignKeyViolation',
10
+ 'notNullViolation',
11
+ 'checkViolation',
12
+ 'optimisticLock',
13
+ 'retryable',
14
+ 'usage',
15
+ 'security',
16
+ ];
17
+ const KINDS = new Set(QUERY_ERROR_KINDS);
18
+ export function isQueryErrorKind(value) {
19
+ return KINDS.has(value);
20
+ }
1
21
  /** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */
2
22
  export class UqlError extends Error {
23
+ constructor(message, opts) {
24
+ super(message, opts);
25
+ if (opts?.path) {
26
+ this.path = opts.path;
27
+ }
28
+ if (opts?.headers) {
29
+ this.headers = opts.headers;
30
+ }
31
+ }
3
32
  }
4
33
  /**
5
34
  * Thrown where the caller used the API in a way no statement can carry out: an update payload with no
@@ -11,6 +40,20 @@ export class UqlUsageError extends UqlError {
11
40
  kind = 'usage';
12
41
  status = 400;
13
42
  }
43
+ /**
44
+ * A request refused with a 4xx `status`: what the API answers a route nothing serves (404), a method its op does
45
+ * not take (405, naming the ones it does in `allow`) or a body that is not JSON (415) with, and what a middleware or
46
+ * a hook throws to refuse a client, `new UqlRequestError('unauthorized', 401)`: only a `UqlError` reaches one.
47
+ */
48
+ export class UqlRequestError extends UqlError {
49
+ status;
50
+ name = 'UqlRequestError';
51
+ kind = 'usage';
52
+ constructor(message, status, opts) {
53
+ super(message, opts);
54
+ this.status = status;
55
+ }
56
+ }
14
57
  /**
15
58
  * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
16
59
  * Fails the statement closed.
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.113.0",
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,8 @@ 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
+ - Serve entities to a client with `createApi({ pool, include, contextOf, use })` from `uql-orm/http`, mounted under a versioned base as `toFetchHandler(api)` on a catch-all, `app.use('/api/v1', toExpress(api))` (`uql-orm/express`) or `toRequestHandler(api)`; the wire is `{base}/:entity/:op` (`GET ?q=` or a JSON `POST` for reads, a JSON `POST` for writes) and a failure answers `{ error: { message, status, kind, path } }`, or called inside a tRPC or oRPC procedure as `api.call(input, ctx.req)`, which checks the call itself. `include` is required and fences relations too; `serve(User, { ops: ['read', 'update'], members: { passwordHash: false, role: ['read'], password: ['insert'] }, use: [...] })` narrows one, where a member's `read` covers select, filter, sort and aggregate and an unlisted member keeps every op. A middleware is `(call, context, next) => next(call)`: the API's `use` runs on every call, a `serve`'s on its entity's alone, typed by it (`call.op === 'insertOne'` types `call.payload` as a row). `.eager(false)` only leaves a field out of a read naming no fields, so a client's `$select` still reads it: hide a secret (`password`, a token) with `members: { password: false }`. Scope tenants with a `security` filter and `contextOf`, never a middleware; without `contextOf` a call keeps its caller's context.
95
+ - The client is `createClientQuerier(httpTransport('/api/v1'))` from `uql-orm/browser`, or `createClientQuerier((call) => trpc.uql.mutate(call))` over any transport; it answers what the pool answers (rows, not `{ data }`) and 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. For TanStack Query, `const uql = createQueryOptions(transport)` and `useQuery(uql((db) => db.findMany(User, q)))`: the key is the call the read makes (`['uql', 'user', 'findMany', { query }]`), so it cannot drift from the fetch, and `uql.key(User)` invalidates every read of `User`.
94
96
  - 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
97
  - 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
98
  - 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.
@@ -176,7 +178,7 @@ await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {}));
176
178
  - A filter is on unless `default: false`. A `$where` naming its field wins over it. Per call, the options argument takes `{ filters: false }`, `{ filters: { softDelete: false } }` or `{ filters: { active: true } }`.
177
179
  - `.softDelete()` on one field turns a delete into a stamp (`new Date()`, or the value or callback given), and registers a `softDelete` filter hiding stamped rows. `withDeleted()` as the options reads both; `restoreOneById` and `restoreMany` undo it; `{ hardDelete: true }` removes rows for good. A restore does not cascade.
178
180
  - A `where` may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`.
179
- - `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
181
+ - `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. `ops: ['insert', 'update', 'delete']` makes one hold those statements alone (anyone reads a row, only its author writes it); an update or delete is also held to the read ones. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
180
182
 
181
183
  ## Queries
182
184
 
@@ -289,4 +291,5 @@ Upgrading uql itself: `npx uql-codemod --dry-run`, then `npx uql-codemod`, which
289
291
  - JSON paths and operators: https://uql-orm.dev/querying/json.md
290
292
  - Full-text and vector search: https://uql-orm.dev/querying/full-text.md, https://uql-orm.dev/querying/semantic-search.md
291
293
  - Computed fields: https://uql-orm.dev/entities/computed-fields.md
294
+ - Serving queries to a client: https://uql-orm.dev/http.md, https://uql-orm.dev/browser.md
292
295
  - Coming from Prisma, Drizzle, TypeORM, MikroORM or Mongoose: https://uql-orm.dev/switching-to-uql.md
@@ -1,3 +0,0 @@
1
- import type { RequestCallback, RequestNotification } from '../type/index.js';
2
- export declare function notify(notification: RequestNotification): void;
3
- export declare function on(cb: RequestCallback): () => void;
@@ -1,12 +0,0 @@
1
- const subscriptors = new Set();
2
- export function notify(notification) {
3
- for (const subscriptor of subscriptors) {
4
- subscriptor(notification);
5
- }
6
- }
7
- export function on(cb) {
8
- subscriptors.add(cb);
9
- return () => {
10
- subscriptors.delete(cb);
11
- };
12
- }
@@ -1,20 +0,0 @@
1
- import type { RequestSuccessResponse } from '../../type/index.js';
2
- import type { RequestOptions } from '../type/index.js';
3
- /**
4
- * Error thrown for non-2xx responses. Carries the HTTP status so callers can key
5
- * behavior on it (401 redirects, 402 payment flows, error-boundary routing).
6
- */
7
- export declare class RequestError extends Error {
8
- readonly status: number;
9
- constructor(message: string, status: number);
10
- }
11
- export declare function get<T>(url: string, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
12
- export declare function post<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
13
- export declare function patch<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
14
- export declare function put<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
15
- export declare function remove<T>(url: string, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
16
- /**
17
- * HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the
18
- * request body, avoiding URL-length limits.
19
- */
20
- export declare function query<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
@@ -1,67 +0,0 @@
1
- import { wireJson } from '../../http/query.js';
2
- import { notify } from './bus.js';
3
- /**
4
- * Error thrown for non-2xx responses. Carries the HTTP status so callers can key
5
- * behavior on it (401 redirects, 402 payment flows, error-boundary routing).
6
- */
7
- export class RequestError extends Error {
8
- status;
9
- constructor(message, status) {
10
- super(message);
11
- this.status = status;
12
- this.name = 'RequestError';
13
- }
14
- }
15
- // Methods are upper-case because `fetch` normalizes only the classic verbs: a lowercase `patch` or `query`
16
- // is sent as written, and servers refuse it.
17
- export function get(url, opts) {
18
- return request(url, { method: 'GET' }, opts);
19
- }
20
- export function post(url, payload, opts) {
21
- return request(url, { method: 'POST', body: wireJson(payload) }, opts);
22
- }
23
- export function patch(url, payload, opts) {
24
- return request(url, { method: 'PATCH', body: wireJson(payload) }, opts);
25
- }
26
- export function put(url, payload, opts) {
27
- return request(url, { method: 'PUT', body: wireJson(payload) }, opts);
28
- }
29
- export function remove(url, opts) {
30
- return request(url, { method: 'DELETE' }, opts);
31
- }
32
- /**
33
- * HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the
34
- * request body, avoiding URL-length limits.
35
- */
36
- export function query(url, payload, opts) {
37
- return request(url, { method: 'QUERY', body: wireJson(payload) }, opts);
38
- }
39
- function request(url, init, opts) {
40
- notify({ phase: 'start', opts });
41
- init.headers = {
42
- accept: 'application/json',
43
- 'content-type': 'application/json',
44
- ...opts?.headers,
45
- };
46
- if (opts?.signal) {
47
- init.signal = opts.signal;
48
- }
49
- return fetch(url, init)
50
- .then((rawResp) => rawResp.json().then((resp) => {
51
- const isSuccess = rawResp.status >= 200 && rawResp.status < 300;
52
- if (isSuccess) {
53
- notify({ phase: 'success', opts });
54
- return resp;
55
- }
56
- const errorResp = resp;
57
- const error = {
58
- message: errorResp?.error?.message ?? rawResp.statusText,
59
- code: errorResp?.error?.code ?? rawResp.status,
60
- };
61
- notify({ phase: 'error', error, opts });
62
- throw new RequestError(error.message, error.code);
63
- }))
64
- .finally(() => {
65
- notify({ phase: 'complete', opts });
66
- });
67
- }
@@ -1,46 +0,0 @@
1
- import { type HttpMethod } from '../../http/contract.js';
2
- import type { SharedQuerier, AbstractType } from '../../type/index.js';
3
- import type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';
4
- export type HttpQuerierDefaults = {
5
- /**
6
- * headers sent with every request from this instance, merged under per-call headers.
7
- * Create one instance per request (e.g. during SSR) to scope auth headers safely.
8
- */
9
- readonly headers?: Record<string, string>;
10
- /**
11
- * transport for read queries (findOne, findMany, findManyPage, count). 'QUERY' (RFC 10008) sends the
12
- * JSON query in the request body, avoiding URL-length limits for large queries; requires
13
- * infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.
14
- */
15
- readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;
16
- /**
17
- * The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same
18
- * option the server handler takes, so one map serves both. State it where the default cannot: a
19
- * build that minifies class names renames every route.
20
- */
21
- readonly entityPath?: (entity: AbstractType<unknown>) => string;
22
- };
23
- export declare class HttpQuerier implements ClientQuerier {
24
- readonly basePath: string;
25
- readonly defaults: HttpQuerierDefaults;
26
- constructor(basePath: string, defaults?: HttpQuerierDefaults);
27
- readonly findOneById: ClientQuerier['findOneById'];
28
- readonly findOne: ClientQuerier['findOne'];
29
- readonly findMany: SharedQuerier<'client', RequestFindOptions>['findMany'];
30
- readonly findManyAndCount: SharedQuerier<'client', RequestFindOptions>['findManyAndCount'];
31
- readonly findManyPage: ClientQuerier['findManyPage'];
32
- readonly count: ClientQuerier['count'];
33
- /** The `count` route capped at one row, so existence needs no endpoint of its own. */
34
- readonly exists: ClientQuerier['exists'];
35
- readonly insertOne: ClientQuerier['insertOne'];
36
- readonly insertMany: ClientQuerier['insertMany'];
37
- readonly updateOneById: ClientQuerier['updateOneById'];
38
- readonly updateMany: ClientQuerier['updateMany'];
39
- readonly saveOne: ClientQuerier['saveOne'];
40
- readonly saveMany: ClientQuerier['saveMany'];
41
- readonly deleteOneById: ClientQuerier['deleteOneById'];
42
- readonly deleteMany: ClientQuerier['deleteMany'];
43
- getBasePath<E>(entity: AbstractType<E>): string;
44
- protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions): Promise<import("../../type/wire.js").RequestSuccessResponse<T>>;
45
- protected buildOptions(opts?: RequestOptions): RequestOptions | undefined;
46
- }
@@ -1,64 +0,0 @@
1
- import { CRUD_ROUTES, entityPath } from '../../http/contract.js';
2
- import { stringifyQuery } from '../../http/query.js';
3
- import { isScalarId } from '../../util/object.util.js';
4
- import { UqlUsageError } from '../../util/uqlError.js';
5
- import { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';
6
- /** The id as one path segment, refusing a composite key, which has no spelling in `/:id` yet. Callers are `async`. */
7
- function idSegment(entity, id) {
8
- if (!isScalarId(id)) {
9
- throw new UqlUsageError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);
10
- }
11
- return String(id);
12
- }
13
- export class HttpQuerier {
14
- basePath;
15
- defaults;
16
- constructor(basePath, defaults = {}) {
17
- this.basePath = basePath;
18
- this.defaults = defaults;
19
- }
20
- // 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);
24
- findManyAndCount = async (entity, q, opts) => {
25
- const response = await this.findMany(entity, q, { ...opts, count: true });
26
- if (typeof response.count !== 'number') {
27
- throw new TypeError('findManyAndCount response has an invalid count');
28
- }
29
- return { ...response, count: response.count };
30
- };
31
- findManyPage = (entity, q, opts) => this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findManyPage.path}`, q, opts);
32
- count = (entity, q, opts) => this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);
33
- /** The `count` route capped at one row, so existence needs no endpoint of its own. */
34
- exists = async (entity, q, opts) => {
35
- const res = await this.count(entity, { ...q, $limit: 1 }, opts);
36
- return { ...res, data: res.data > 0 };
37
- };
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));
40
- updateOneById = async (entity, id, payload, opts) => patch(`${this.getBasePath(entity)}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));
41
- 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));
44
- deleteOneById = async (entity, id, opts = {}) => {
45
- const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';
46
- return remove(`${this.getBasePath(entity)}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));
47
- };
48
- deleteMany = (entity, q, opts = {}) => remove(`${this.getBasePath(entity)}${stringifyQuery(opts.hardDelete ? { ...q, hardDelete: opts.hardDelete } : q)}`, this.buildOptions(opts));
49
- getBasePath(entity) {
50
- return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;
51
- }
52
- read(path, q, opts) {
53
- if (this.defaults.readMethod === 'QUERY') {
54
- return httpQuery(path, q ?? {}, this.buildOptions(opts));
55
- }
56
- return get(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));
57
- }
58
- buildOptions(opts) {
59
- if (!this.defaults.headers && !opts?.headers) {
60
- return opts;
61
- }
62
- return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };
63
- }
64
- }
@@ -1,27 +0,0 @@
1
- import type { RequestErrorResponse } from '../../http/contract.js';
2
- export type RequestOptions = {
3
- silent?: boolean;
4
- /**
5
- * extra headers merged over the defaults (e.g. `{ Authorization: 'Bearer ...' }`).
6
- */
7
- headers?: Record<string, string>;
8
- /**
9
- * abort/timeout control, e.g. `AbortSignal.timeout(120_000)` for long-running calls.
10
- */
11
- signal?: AbortSignal;
12
- };
13
- export type RequestFindOptions = RequestOptions & {
14
- count?: boolean;
15
- };
16
- type RequestBaseNotification = {
17
- readonly opts?: RequestOptions;
18
- };
19
- type RequestSuccessNotification = {
20
- readonly phase: 'start' | 'success' | 'complete';
21
- } & RequestBaseNotification;
22
- type RequestErrorNotification = {
23
- readonly phase: 'error';
24
- } & RequestErrorResponse & RequestBaseNotification;
25
- export type RequestNotification = RequestSuccessNotification | RequestErrorNotification;
26
- export type RequestCallback = (msg: RequestNotification) => void;
27
- export {};