@venizia/ignis-connectors 0.4.8-4 → 0.4.8-5

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 (62) hide show
  1. package/dist/esm/http/datasource.d.ts +13 -0
  2. package/dist/esm/http/datasource.js +54 -0
  3. package/dist/esm/http/datasource.js.map +1 -1
  4. package/dist/esm/relational/core/repositories/common/scope-filter.d.ts +17 -0
  5. package/dist/esm/relational/core/repositories/common/scope-filter.js +46 -1
  6. package/dist/esm/relational/core/repositories/common/scope-filter.js.map +1 -1
  7. package/dist/esm/relational/core/repositories/common/scope-write-guard.js +2 -2
  8. package/dist/esm/relational/core/repositories/common/scope-write-guard.js.map +1 -1
  9. package/dist/esm/relational/core/repositories/common/types.d.ts +18 -0
  10. package/dist/esm/relational/core/repositories/common/types.js.map +1 -1
  11. package/dist/esm/relational/core/repositories/core/base.d.ts +8 -1
  12. package/dist/esm/relational/core/repositories/core/base.js +41 -16
  13. package/dist/esm/relational/core/repositories/core/base.js.map +1 -1
  14. package/dist/esm/relational/core/repositories/dialect/filter.d.ts +35 -4
  15. package/dist/esm/relational/core/repositories/dialect/filter.js +106 -39
  16. package/dist/esm/relational/core/repositories/dialect/filter.js.map +1 -1
  17. package/dist/esm/relational/core/repositories/dialect/internal/json-utils.js +4 -4
  18. package/dist/esm/relational/core/repositories/dialect/internal/json-utils.js.map +1 -1
  19. package/dist/esm/relational/core/repositories/dialect/update.js +4 -2
  20. package/dist/esm/relational/core/repositories/dialect/update.js.map +1 -1
  21. package/dist/esm/search/core/controllers/abstract.d.ts +8 -0
  22. package/dist/esm/search/core/controllers/abstract.js +13 -0
  23. package/dist/esm/search/core/controllers/abstract.js.map +1 -1
  24. package/dist/esm/search/core/controllers/engine-params.d.ts +37 -0
  25. package/dist/esm/search/core/controllers/engine-params.js +124 -0
  26. package/dist/esm/search/core/controllers/engine-params.js.map +1 -0
  27. package/dist/esm/search/core/controllers/factory.d.ts +31 -7
  28. package/dist/esm/search/core/controllers/factory.js +13 -0
  29. package/dist/esm/search/core/controllers/factory.js.map +1 -1
  30. package/dist/esm/search/core/controllers/index.d.ts +2 -0
  31. package/dist/esm/search/core/controllers/index.js +2 -0
  32. package/dist/esm/search/core/controllers/index.js.map +1 -1
  33. package/dist/esm/search/core/controllers/raw-access.d.ts +25 -0
  34. package/dist/esm/search/core/controllers/raw-access.js +48 -0
  35. package/dist/esm/search/core/controllers/raw-access.js.map +1 -0
  36. package/dist/esm/search/core/controllers/scope.d.ts +3 -2
  37. package/dist/esm/search/core/controllers/scope.js +3 -8
  38. package/dist/esm/search/core/controllers/scope.js.map +1 -1
  39. package/dist/esm/search/core/repositories/common/constants.d.ts +3 -3
  40. package/dist/esm/search/core/repositories/common/dialect-helpers.d.ts +8 -2
  41. package/dist/esm/search/core/repositories/common/dialect-helpers.js +8 -3
  42. package/dist/esm/search/core/repositories/common/dialect-helpers.js.map +1 -1
  43. package/dist/esm/search/core/repositories/common/types.d.ts +5 -0
  44. package/dist/esm/search/core/repositories/common/types.js.map +1 -1
  45. package/dist/esm/search/core/repositories/core/base.d.ts +9 -1
  46. package/dist/esm/search/core/repositories/core/base.js +26 -0
  47. package/dist/esm/search/core/repositories/core/base.js.map +1 -1
  48. package/dist/esm/search/core/repositories/core/readable.js +29 -5
  49. package/dist/esm/search/core/repositories/core/readable.js.map +1 -1
  50. package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.d.ts +12 -0
  51. package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.js +44 -6
  52. package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.js.map +1 -1
  53. package/dist/esm/search/typesense/repositories/dialect/query-dialect.d.ts +4 -0
  54. package/dist/esm/search/typesense/repositories/dialect/query-dialect.js +7 -0
  55. package/dist/esm/search/typesense/repositories/dialect/query-dialect.js.map +1 -1
  56. package/dist/esm/testing/repository-double.d.ts +2 -0
  57. package/dist/esm/testing/repository-double.js +9 -1
  58. package/dist/esm/testing/repository-double.js.map +1 -1
  59. package/dist/esm/testing/transaction-double.d.ts +13 -1
  60. package/dist/esm/testing/transaction-double.js +18 -1
  61. package/dist/esm/testing/transaction-double.js.map +1 -1
  62. package/package.json +4 -4
@@ -34,6 +34,19 @@ export declare class HttpDataSource extends AbstractDataSource<IHttpDataSourceSe
34
34
  }): Headers;
35
35
  /** The browser global `location` is not declared for a server build, so it is probed, not assumed. */
36
36
  protected resolveLocationOrigin(): string | undefined;
37
+ /** The path as an error message quotes it: cut at 200 characters, with an ellipsis. */
38
+ protected static toEchoedPath(opts: {
39
+ path: string;
40
+ }): string;
41
+ /** The request paths name a place under the base path, so none may be a dot segment, hide one, or carry a separator the URL parser would read differently from a server. */
42
+ protected assertPathsStayUnderBase(opts: {
43
+ paths: Array<string>;
44
+ }): void;
45
+ /** The resolved URL, whatever built it, is on the base's origin and under its path: the check that holds when the text checks above miss a form. */
46
+ protected assertUnderBase(opts: {
47
+ url: URL;
48
+ origin?: string;
49
+ }): void;
37
50
  buildUrl(opts: {
38
51
  paths: Array<string>;
39
52
  query?: Record<string, unknown>;
@@ -1,3 +1,4 @@
1
+ import { EchoUtility } from '../common/internal/index.js';
1
2
  import { HttpReadShapes } from './common/constants.js';
2
3
  import { AbstractDataSource } from '@venizia/ignis-kernel/repository';
3
4
  import { HTTP } from '@venizia/ignis-helpers/common';
@@ -7,6 +8,14 @@ import { HttpResponseReader } from './common/readers.js';
7
8
  import { HttpWire } from './common/wire.js';
8
9
  /** A scheme and `//` make a URL absolute - `localhost:3000` has neither. Read by pattern: `URL.canParse` needs Safari 17 or Chrome 120, and this runs in pages. */
9
10
  const ABSOLUTE_URL_PATTERN = /^[a-z][a-z\d+.-]*:\/\//i;
11
+ /** A backslash is a separator to the URL parser, and a control character (a tab or a newline inside `.<TAB>.`) is dropped by it: neither may hide a dot segment. `%5c` is the encoded backslash. */
12
+ const UNSAFE_REQUEST_PATH_PATTERN = /[\p{Cc}\\]|%5c/iu;
13
+ /** What ends a path segment for the URL parser: a slash, a `?` or a `#` (it ends the path itself, so `..?` is a `..` segment), and the encoded slash, which a server may decode into a separator. */
14
+ const REQUEST_PATH_SEPARATOR_PATTERN = /[/?#]|%2f/i;
15
+ /** The longest part of a refused path an error message copies: a huge path is not copied whole into the error and the log. */
16
+ const MAX_ECHOED_PATH_LENGTH = 200;
17
+ /** A segment that is `.` or `..` once its `%2e` is decoded. */
18
+ const DOT_SEGMENT_PATTERN = /^(?:\.|%2e){1,2}$/i;
10
19
  /** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */
11
20
  export class HttpDataSource extends AbstractDataSource {
12
21
  constructor(opts) {
@@ -23,6 +32,13 @@ export class HttpDataSource extends AbstractDataSource {
23
32
  message: `[${name}] baseUrl '${settings.baseUrl}' is neither absolute nor a path from the origin | Pass '/api' or an absolute URL such as 'https://api.example.com'`,
24
33
  });
25
34
  }
35
+ // A `?` or `#` in the base would swallow the request paths into the query or the fragment.
36
+ if (/[?#]/.test(settings.baseUrl)) {
37
+ throw getError({
38
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
39
+ message: `[${name}] baseUrl must not carry a query or a fragment: the request paths would end up inside it | Pass the base without '?' or '#', and use the call's query option`,
40
+ });
41
+ }
26
42
  this.configuredHeaders = configured;
27
43
  this.name = name;
28
44
  this.settings = settings;
@@ -82,8 +98,45 @@ export class HttpDataSource extends AbstractDataSource {
82
98
  }
83
99
  return typeof location.origin === 'string' ? location.origin : undefined;
84
100
  }
101
+ /** The path as an error message quotes it: cut at 200 characters, with an ellipsis. */
102
+ static toEchoedPath(opts) {
103
+ const { path } = opts;
104
+ return path.length > MAX_ECHOED_PATH_LENGTH
105
+ ? `${path.slice(0, MAX_ECHOED_PATH_LENGTH)}…`
106
+ : path;
107
+ }
108
+ /** The request paths name a place under the base path, so none may be a dot segment, hide one, or carry a separator the URL parser would read differently from a server. */
109
+ assertPathsStayUnderBase(opts) {
110
+ for (const path of opts.paths) {
111
+ const segments = path.split(REQUEST_PATH_SEPARATOR_PATTERN);
112
+ const isEscaping = UNSAFE_REQUEST_PATH_PATTERN.test(path) ||
113
+ // A trailing space is stripped from the whole URL by the parser, so `.. ` ends as `..`.
114
+ segments.some((segment) => DOT_SEGMENT_PATTERN.test(segment.trimEnd()));
115
+ if (isEscaping) {
116
+ throw getError({
117
+ statusCode: HTTP.ResultCodes.RS_4.BadRequest,
118
+ message: `[${this.name}] A request path must stay under the base path: no dot segment, backslash or control character | path: '${EchoUtility.toSafeEcho({ value: HttpDataSource.toEchoedPath({ path }) })}'`,
119
+ });
120
+ }
121
+ }
122
+ }
123
+ /** The resolved URL, whatever built it, is on the base's origin and under its path: the check that holds when the text checks above miss a form. */
124
+ assertUnderBase(opts) {
125
+ const { url, origin } = opts;
126
+ const base = new URL(this.settings.baseUrl, origin);
127
+ const basePath = base.pathname.replace(/\/+$/, '');
128
+ const isUnderBase = url.origin === base.origin &&
129
+ (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`));
130
+ if (!isUnderBase) {
131
+ throw getError({
132
+ statusCode: HTTP.ResultCodes.RS_4.BadRequest,
133
+ message: `[${this.name}] A request path must stay under the base path: the URL left the origin or the base path`,
134
+ });
135
+ }
136
+ }
85
137
  buildUrl(opts) {
86
138
  const { paths, query } = opts;
139
+ this.assertPathsStayUnderBase({ paths });
87
140
  const requestUrl = this.network.getRequestUrl({ paths });
88
141
  // A page or a Web Worker has an origin to resolve '/api' against; a server has none.
89
142
  const origin = this.isRelativeBaseUrl ? this.resolveLocationOrigin() : undefined;
@@ -94,6 +147,7 @@ export class HttpDataSource extends AbstractDataSource {
94
147
  });
95
148
  }
96
149
  const url = new URL(requestUrl, origin);
150
+ this.assertUnderBase({ url, origin });
97
151
  const parameters = Object.entries(query ?? {});
98
152
  for (const [key, value] of parameters) {
99
153
  if (value === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"datasource.js","sourceRoot":"","sources":["../../../src/http/datasource.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAuB,MAA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I,CAAC;oBACnB,CAAC,CAAC,IAAI,CAAC,MAAM;oBACb,CAAC,CAAC,IAAI,KAAK,IAAI;wBACb,CAAC,CAAC,CAAC;wBACH,CAAC,CAAC,CAAC;YACT,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { HttpReadShapes, type THttpReadShape } from './common/constants';\nimport { AbstractDataSource } from '@venizia/ignis-kernel/repository';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HttpResponseReader } from './common/readers';\nimport type {\n IAuthToken,\n IHttpCallOptions,\n IHttpDataSourceSettings,\n TExtraRequest,\n IHttpReadResult,\n IHttpRequestContext,\n IHttpWriteResult,\n THttpBody,\n} from './common/types';\nimport { HttpWire } from './common/wire';\n\n/** A scheme and `//` make a URL absolute - `localhost:3000` has neither. Read by pattern: `URL.canParse` needs Safari 17 or Chrome 120, and this runs in pages. */\nconst ABSOLUTE_URL_PATTERN = /^[a-z][a-z\\d+.-]*:\\/\\//i;\n\n/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */\nexport class HttpDataSource extends AbstractDataSource<IHttpDataSourceSettings> {\n override name: string;\n override settings: IHttpDataSourceSettings;\n override schema = {} as never;\n\n protected network: NodeFetchNetworkRequest;\n /** Normalised once: every request copies these, never re-parses `settings.headers`. */\n protected configuredHeaders: Array<[string, string]>;\n /** Decided once: a relative baseUrl (`/api`) is resolved against the page origin on every request. */\n protected isRelativeBaseUrl: boolean;\n\n constructor(opts: IHttpDataSourceSettings & { name?: string }) {\n super({ scope: opts.name ?? HttpDataSource.name });\n\n const { name = 'http', ...settings } = opts;\n\n const configured = HttpWire.toHeaderEntries({ headers: settings.headers });\n HttpWire.assertNoRequestCountHeader({ entries: configured, name });\n\n this.isRelativeBaseUrl = !ABSOLUTE_URL_PATTERN.test(settings.baseUrl);\n\n // Against the page, `api` would follow the current route; `localhost:3000` is not a URL at all.\n if (this.isRelativeBaseUrl && !settings.baseUrl.startsWith('/')) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] baseUrl '${settings.baseUrl}' is neither absolute nor a path from the origin | Pass '/api' or an absolute URL such as 'https://api.example.com'`,\n });\n }\n\n this.configuredHeaders = configured;\n this.name = name;\n this.settings = settings;\n this.network = new NodeFetchNetworkRequest({\n name,\n networkOptions: { baseUrl: settings.baseUrl },\n });\n }\n\n async configure(): Promise<void> {}\n\n override getCapabilities() {\n return { transactions: false };\n }\n\n protected resolveAuthToken(opts: { context: IHttpRequestContext }): IAuthToken | undefined {\n return this.settings.authToken ?? this.settings.authTokenResolver?.(opts.context);\n }\n\n /** Re-run on every send, so a header the app changed since the last request is the one sent. */\n protected resolveHeaders(opts: { context: IHttpRequestContext }): Array<[string, string]> {\n const resolver = this.settings.headersResolver;\n\n if (!resolver) {\n return [];\n }\n\n const entries = HttpWire.toHeaderEntries({ headers: resolver(opts.context) });\n HttpWire.assertNoRequestCountHeader({ entries, name: this.name });\n\n return entries;\n }\n\n protected buildHeaders(opts: {\n token?: IAuthToken;\n requestHeaders?: Array<[string, string]>;\n isJsonBody?: boolean;\n isFormDataBody?: boolean;\n }): Headers {\n const { token, requestHeaders, isJsonBody, isFormDataBody } = opts;\n const headers = new Headers(this.configuredHeaders);\n\n // A request's own headers win over the configured ones; the connector's below win over both.\n for (const [name, value] of requestHeaders ?? []) {\n headers.set(name, value);\n }\n\n if (isJsonBody && !headers.has(HTTP.Headers.CONTENT_TYPE)) {\n headers.set(HTTP.Headers.CONTENT_TYPE, 'application/json');\n }\n\n // Only `fetch` knows the multipart boundary; any other content-type here would drop it.\n if (isFormDataBody) {\n headers.delete(HTTP.Headers.CONTENT_TYPE);\n }\n\n // Set last: under the envelope a record read answers `{ count, data }`.\n headers.set(HTTP.Headers.REQUEST_COUNT_DATA, 'false');\n\n if (!token) {\n return headers;\n }\n\n headers.set(HTTP.Headers.AUTHORIZATION, `${token.type ?? 'Bearer'} ${token.value}`);\n\n // Unconditionally it would send the string \"undefined\".\n if (token.provider) {\n headers.set('x-auth-provider', token.provider);\n }\n\n return headers;\n }\n\n /** The browser global `location` is not declared for a server build, so it is probed, not assumed. */\n protected resolveLocationOrigin(): string | undefined {\n const location: unknown = Reflect.get(globalThis, 'location');\n\n if (typeof location !== 'object' || location === null || !('origin' in location)) {\n return undefined;\n }\n\n return typeof location.origin === 'string' ? location.origin : undefined;\n }\n\n buildUrl(opts: { paths: Array<string>; query?: Record<string, unknown> }): string {\n const { paths, query } = opts;\n const requestUrl = this.network.getRequestUrl({ paths });\n\n // A page or a Web Worker has an origin to resolve '/api' against; a server has none.\n const origin = this.isRelativeBaseUrl ? this.resolveLocationOrigin() : undefined;\n\n if (this.isRelativeBaseUrl && !origin) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${this.name}] Relative baseUrl '${this.settings.baseUrl}' needs a page or worker location to resolve against, and there is none here | Pass an absolute baseUrl such as 'https://api.example.com'`,\n });\n }\n\n const url = new URL(requestUrl, origin);\n\n const parameters = Object.entries(query ?? {});\n\n for (const [key, value] of parameters) {\n if (value === undefined) {\n continue;\n }\n\n url.searchParams.set(\n key,\n typeof value === 'string'\n ? value\n : HttpWire.toJson({ value, label: `[${this.name}] Query parameter '${key}'` }),\n );\n }\n\n return url.toString();\n }\n\n /**\n * The raw `Response`, on any method - for what the repository verbs do not cover, like an export\n * or a PUT to a hand-written route. Auth and the 401 retry apply; the retry resends the same body.\n */\n async request(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n return this.sendRequest({ ...opts, url: this.buildUrl(opts) });\n }\n\n /** `request` on a URL already built: `read` and `write` serialise a long query once, not per use. */\n protected async sendRequest(\n opts: {\n paths: Array<string>;\n url: string;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n const { url, signal } = opts;\n const requestHeaders = HttpWire.toHeaderEntries({ headers: opts.headers });\n HttpWire.assertNoRequestCountHeader({ entries: requestHeaders, name: this.name });\n\n const method = opts.method ?? HTTP.Methods.GET;\n const context: IHttpRequestContext = { paths: opts.paths, method, url, signal };\n const { payload, isJson, isFormData } = HttpWire.toRequestBody({ body: opts.body });\n\n // Both hooks run inside `send`, so the retry sends what they answer after the refresh.\n const send = () =>\n this.network.getNetworkService().send({\n url,\n method: method as never,\n body: payload,\n signal,\n headers: this.buildHeaders({\n token: this.resolveAuthToken({ context }),\n // Resolved first, so the call's own headers win over them.\n requestHeaders: [...this.resolveHeaders({ context }), ...requestHeaders],\n isJsonBody: isJson,\n isFormDataBody: isFormData,\n }),\n });\n\n let response = await send();\n\n if (response.status === HTTP.ResultCodes.RS_4.Unauthorized && this.settings.onUnauthorized) {\n const shouldRetry = await this.settings.onUnauthorized(context);\n\n // A call aborted while the session refreshed is not sent again.\n if (shouldRetry) {\n signal?.throwIfAborted();\n const result = await send();\n response = result;\n }\n }\n\n return response;\n }\n\n /**\n * The body as JSON, `null` when there is none; a body that is not JSON is the server's fault, named\n * as such. Its content stays out of the message, which a relaying server may pass to its clients.\n */\n protected async readJsonBody(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const text = await response.text();\n\n if (!text) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.BadGateway,\n message: `[${this.name}][${verb}] ${response.status} | ${HttpWire.describeUrl({ url, status: response.status })} | The response body is not JSON (${text.length} chars, content-type: ${response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? 'none'})`,\n });\n }\n }\n\n /**\n * A failed response as the error the server threw: its status, code, args and text, and its\n * `extra` with the `requestId` added. `message` adds where it failed, for logs; `normalized.text`\n * stays the server's, for display - `HTTP <status>` when the server sent none. `cause` is the server's `details.cause` - a 422's per-field\n * issues, `{ path, message, code }`.\n */\n protected async toResponseError(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const described = HttpWire.describeUrl({ url, status: response.status });\n\n return HttpResponseReader.toApplicationError({\n response,\n rootKey: this.settings.errorRootKey,\n context: `[${this.name}][${verb}] ${response.status} | ${described}`,\n });\n }\n\n /**\n * Rows plus the total from `Content-Range`, reported absent when the header is. A GET unless told\n * otherwise: `method` and `body` reach a list route a service wrote to take its filter in a body.\n */\n async read<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n shape?: THttpReadShape;\n method?: string;\n body?: THttpBody;\n /** Extras the route offers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n /** The rows alone: every default extra off (`-*`), for a read that only counts or probes. */\n isEveryDefaultOff?: boolean;\n } & IHttpCallOptions,\n ): Promise<IHttpReadResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({\n headers: opts.headers,\n extra: opts.extra,\n isEveryDefaultOff: opts.isEveryDefaultOff,\n });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'read' });\n throw result;\n }\n\n // A 204 or an empty body is no row; a list asked for of it still throws below.\n const parsed = await this.readJsonBody({ response, url, verb: 'read' });\n const { body, extra } = HttpResponseReader.readExtra({\n body: parsed,\n headers: response.headers,\n });\n const contentRange = response.headers.get(HTTP.Headers.CONTENT_RANGE) ?? undefined;\n const range = HttpResponseReader.parseContentRange({ header: contentRange });\n const data = HttpWire.unwrapRows<R>({ body, shape: opts.shape ?? HttpReadShapes.LIST, url });\n\n return {\n data,\n hasRange: range !== undefined,\n contentRange,\n total: range?.total,\n skip: range?.skip,\n dataLength: Array.isArray(data) ? data.length : data === null ? 0 : 1,\n extra,\n };\n }\n\n /**\n * A write, and what it answered: the body as the rows, the count from `x-response-count`. The\n * connector asks for bare rows, so an IGNIS write answers the row or the rows, never the envelope.\n */\n async write<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method: string;\n body?: THttpBody;\n /** Extras the route answers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n } & IHttpCallOptions,\n ): Promise<IHttpWriteResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({ headers: opts.headers, extra: opts.extra });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'write' });\n throw result;\n }\n\n // A 204, or a route that answers nothing, has no body to parse.\n const parsed = await this.readJsonBody({ response, url, verb: 'write' });\n const { extra } = HttpResponseReader.readExtra({ body: parsed, headers: response.headers });\n const data = extra ? parsed.data : parsed;\n\n const countHeader = response.headers.get(HTTP.Headers.RESPONSE_COUNT_DATA);\n const counted = countHeader === null ? Number.NaN : Number(countHeader);\n\n return {\n data,\n count: Number.isFinite(counted)\n ? counted\n : Array.isArray(data)\n ? data.length\n : data === null\n ? 0\n : 1,\n ...(extra ? { extra } : {}),\n };\n }\n}\n"]}
1
+ {"version":3,"file":"datasource.js","sourceRoot":"","sources":["../../../src/http/datasource.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAuB,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAWtD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,mKAAmK;AACnK,MAAM,oBAAoB,GAAG,yBAAyB,CAA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GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QACzE,MAAM,EAAE,KAAK,EAAE,GAAG,kBAAkB,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;QAC5F,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;QAE1C,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QAC3E,MAAM,OAAO,GAAG,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QAExE,OAAO;YACL,IAAI;YACJ,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;gBAC7B,CAAC,CAAC,OAAO;gBACT,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;oBACnB,CAAC,CAAC,IAAI,CAAC,MAAM;oBACb,CAAC,CAAC,IAAI,KAAK,IAAI;wBACb,CAAC,CAAC,CAAC;wBACH,CAAC,CAAC,CAAC;YACT,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { EchoUtility } from '@/common/internal';\nimport { HttpReadShapes, type THttpReadShape } from './common/constants';\nimport { AbstractDataSource } from '@venizia/ignis-kernel/repository';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HttpResponseReader } from './common/readers';\nimport type {\n IAuthToken,\n IHttpCallOptions,\n IHttpDataSourceSettings,\n TExtraRequest,\n IHttpReadResult,\n IHttpRequestContext,\n IHttpWriteResult,\n THttpBody,\n} from './common/types';\nimport { HttpWire } from './common/wire';\n\n/** A scheme and `//` make a URL absolute - `localhost:3000` has neither. Read by pattern: `URL.canParse` needs Safari 17 or Chrome 120, and this runs in pages. */\nconst ABSOLUTE_URL_PATTERN = /^[a-z][a-z\\d+.-]*:\\/\\//i;\n\n/** A backslash is a separator to the URL parser, and a control character (a tab or a newline inside `.<TAB>.`) is dropped by it: neither may hide a dot segment. `%5c` is the encoded backslash. */\nconst UNSAFE_REQUEST_PATH_PATTERN = /[\\p{Cc}\\\\]|%5c/iu;\n\n/** What ends a path segment for the URL parser: a slash, a `?` or a `#` (it ends the path itself, so `..?` is a `..` segment), and the encoded slash, which a server may decode into a separator. */\nconst REQUEST_PATH_SEPARATOR_PATTERN = /[/?#]|%2f/i;\n\n/** The longest part of a refused path an error message copies: a huge path is not copied whole into the error and the log. */\nconst MAX_ECHOED_PATH_LENGTH = 200;\n\n/** A segment that is `.` or `..` once its `%2e` is decoded. */\nconst DOT_SEGMENT_PATTERN = /^(?:\\.|%2e){1,2}$/i;\n\n/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */\nexport class HttpDataSource extends AbstractDataSource<IHttpDataSourceSettings> {\n override name: string;\n override settings: IHttpDataSourceSettings;\n override schema = {} as never;\n\n protected network: NodeFetchNetworkRequest;\n /** Normalised once: every request copies these, never re-parses `settings.headers`. */\n protected configuredHeaders: Array<[string, string]>;\n /** Decided once: a relative baseUrl (`/api`) is resolved against the page origin on every request. */\n protected isRelativeBaseUrl: boolean;\n\n constructor(opts: IHttpDataSourceSettings & { name?: string }) {\n super({ scope: opts.name ?? HttpDataSource.name });\n\n const { name = 'http', ...settings } = opts;\n\n const configured = HttpWire.toHeaderEntries({ headers: settings.headers });\n HttpWire.assertNoRequestCountHeader({ entries: configured, name });\n\n this.isRelativeBaseUrl = !ABSOLUTE_URL_PATTERN.test(settings.baseUrl);\n\n // Against the page, `api` would follow the current route; `localhost:3000` is not a URL at all.\n if (this.isRelativeBaseUrl && !settings.baseUrl.startsWith('/')) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] baseUrl '${settings.baseUrl}' is neither absolute nor a path from the origin | Pass '/api' or an absolute URL such as 'https://api.example.com'`,\n });\n }\n\n // A `?` or `#` in the base would swallow the request paths into the query or the fragment.\n if (/[?#]/.test(settings.baseUrl)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] baseUrl must not carry a query or a fragment: the request paths would end up inside it | Pass the base without '?' or '#', and use the call's query option`,\n });\n }\n\n this.configuredHeaders = configured;\n this.name = name;\n this.settings = settings;\n this.network = new NodeFetchNetworkRequest({\n name,\n networkOptions: { baseUrl: settings.baseUrl },\n });\n }\n\n async configure(): Promise<void> {}\n\n override getCapabilities() {\n return { transactions: false };\n }\n\n protected resolveAuthToken(opts: { context: IHttpRequestContext }): IAuthToken | undefined {\n return this.settings.authToken ?? this.settings.authTokenResolver?.(opts.context);\n }\n\n /** Re-run on every send, so a header the app changed since the last request is the one sent. */\n protected resolveHeaders(opts: { context: IHttpRequestContext }): Array<[string, string]> {\n const resolver = this.settings.headersResolver;\n\n if (!resolver) {\n return [];\n }\n\n const entries = HttpWire.toHeaderEntries({ headers: resolver(opts.context) });\n HttpWire.assertNoRequestCountHeader({ entries, name: this.name });\n\n return entries;\n }\n\n protected buildHeaders(opts: {\n token?: IAuthToken;\n requestHeaders?: Array<[string, string]>;\n isJsonBody?: boolean;\n isFormDataBody?: boolean;\n }): Headers {\n const { token, requestHeaders, isJsonBody, isFormDataBody } = opts;\n const headers = new Headers(this.configuredHeaders);\n\n // A request's own headers win over the configured ones; the connector's below win over both.\n for (const [name, value] of requestHeaders ?? []) {\n headers.set(name, value);\n }\n\n if (isJsonBody && !headers.has(HTTP.Headers.CONTENT_TYPE)) {\n headers.set(HTTP.Headers.CONTENT_TYPE, 'application/json');\n }\n\n // Only `fetch` knows the multipart boundary; any other content-type here would drop it.\n if (isFormDataBody) {\n headers.delete(HTTP.Headers.CONTENT_TYPE);\n }\n\n // Set last: under the envelope a record read answers `{ count, data }`.\n headers.set(HTTP.Headers.REQUEST_COUNT_DATA, 'false');\n\n if (!token) {\n return headers;\n }\n\n headers.set(HTTP.Headers.AUTHORIZATION, `${token.type ?? 'Bearer'} ${token.value}`);\n\n // Unconditionally it would send the string \"undefined\".\n if (token.provider) {\n headers.set('x-auth-provider', token.provider);\n }\n\n return headers;\n }\n\n /** The browser global `location` is not declared for a server build, so it is probed, not assumed. */\n protected resolveLocationOrigin(): string | undefined {\n const location: unknown = Reflect.get(globalThis, 'location');\n\n if (typeof location !== 'object' || location === null || !('origin' in location)) {\n return undefined;\n }\n\n return typeof location.origin === 'string' ? location.origin : undefined;\n }\n\n /** The path as an error message quotes it: cut at 200 characters, with an ellipsis. */\n protected static toEchoedPath(opts: { path: string }): string {\n const { path } = opts;\n\n return path.length > MAX_ECHOED_PATH_LENGTH\n ? `${path.slice(0, MAX_ECHOED_PATH_LENGTH)}…`\n : path;\n }\n\n /** The request paths name a place under the base path, so none may be a dot segment, hide one, or carry a separator the URL parser would read differently from a server. */\n protected assertPathsStayUnderBase(opts: { paths: Array<string> }): void {\n for (const path of opts.paths) {\n const segments = path.split(REQUEST_PATH_SEPARATOR_PATTERN);\n const isEscaping =\n UNSAFE_REQUEST_PATH_PATTERN.test(path) ||\n // A trailing space is stripped from the whole URL by the parser, so `.. ` ends as `..`.\n segments.some((segment) => DOT_SEGMENT_PATTERN.test(segment.trimEnd()));\n\n if (isEscaping) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[${this.name}] A request path must stay under the base path: no dot segment, backslash or control character | path: '${EchoUtility.toSafeEcho({ value: HttpDataSource.toEchoedPath({ path }) })}'`,\n });\n }\n }\n }\n\n /** The resolved URL, whatever built it, is on the base's origin and under its path: the check that holds when the text checks above miss a form. */\n protected assertUnderBase(opts: { url: URL; origin?: string }): void {\n const { url, origin } = opts;\n const base = new URL(this.settings.baseUrl, origin);\n const basePath = base.pathname.replace(/\\/+$/, '');\n const isUnderBase =\n url.origin === base.origin &&\n (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`));\n\n if (!isUnderBase) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[${this.name}] A request path must stay under the base path: the URL left the origin or the base path`,\n });\n }\n }\n\n buildUrl(opts: { paths: Array<string>; query?: Record<string, unknown> }): string {\n const { paths, query } = opts;\n this.assertPathsStayUnderBase({ paths });\n\n const requestUrl = this.network.getRequestUrl({ paths });\n\n // A page or a Web Worker has an origin to resolve '/api' against; a server has none.\n const origin = this.isRelativeBaseUrl ? this.resolveLocationOrigin() : undefined;\n\n if (this.isRelativeBaseUrl && !origin) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${this.name}] Relative baseUrl '${this.settings.baseUrl}' needs a page or worker location to resolve against, and there is none here | Pass an absolute baseUrl such as 'https://api.example.com'`,\n });\n }\n\n const url = new URL(requestUrl, origin);\n this.assertUnderBase({ url, origin });\n\n const parameters = Object.entries(query ?? {});\n\n for (const [key, value] of parameters) {\n if (value === undefined) {\n continue;\n }\n\n url.searchParams.set(\n key,\n typeof value === 'string'\n ? value\n : HttpWire.toJson({ value, label: `[${this.name}] Query parameter '${key}'` }),\n );\n }\n\n return url.toString();\n }\n\n /**\n * The raw `Response`, on any method - for what the repository verbs do not cover, like an export\n * or a PUT to a hand-written route. Auth and the 401 retry apply; the retry resends the same body.\n */\n async request(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n return this.sendRequest({ ...opts, url: this.buildUrl(opts) });\n }\n\n /** `request` on a URL already built: `read` and `write` serialise a long query once, not per use. */\n protected async sendRequest(\n opts: {\n paths: Array<string>;\n url: string;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n const { url, signal } = opts;\n const requestHeaders = HttpWire.toHeaderEntries({ headers: opts.headers });\n HttpWire.assertNoRequestCountHeader({ entries: requestHeaders, name: this.name });\n\n const method = opts.method ?? HTTP.Methods.GET;\n const context: IHttpRequestContext = { paths: opts.paths, method, url, signal };\n const { payload, isJson, isFormData } = HttpWire.toRequestBody({ body: opts.body });\n\n // Both hooks run inside `send`, so the retry sends what they answer after the refresh.\n const send = () =>\n this.network.getNetworkService().send({\n url,\n method: method as never,\n body: payload,\n signal,\n headers: this.buildHeaders({\n token: this.resolveAuthToken({ context }),\n // Resolved first, so the call's own headers win over them.\n requestHeaders: [...this.resolveHeaders({ context }), ...requestHeaders],\n isJsonBody: isJson,\n isFormDataBody: isFormData,\n }),\n });\n\n let response = await send();\n\n if (response.status === HTTP.ResultCodes.RS_4.Unauthorized && this.settings.onUnauthorized) {\n const shouldRetry = await this.settings.onUnauthorized(context);\n\n // A call aborted while the session refreshed is not sent again.\n if (shouldRetry) {\n signal?.throwIfAborted();\n const result = await send();\n response = result;\n }\n }\n\n return response;\n }\n\n /**\n * The body as JSON, `null` when there is none; a body that is not JSON is the server's fault, named\n * as such. Its content stays out of the message, which a relaying server may pass to its clients.\n */\n protected async readJsonBody(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const text = await response.text();\n\n if (!text) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.BadGateway,\n message: `[${this.name}][${verb}] ${response.status} | ${HttpWire.describeUrl({ url, status: response.status })} | The response body is not JSON (${text.length} chars, content-type: ${response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? 'none'})`,\n });\n }\n }\n\n /**\n * A failed response as the error the server threw: its status, code, args and text, and its\n * `extra` with the `requestId` added. `message` adds where it failed, for logs; `normalized.text`\n * stays the server's, for display - `HTTP <status>` when the server sent none. `cause` is the server's `details.cause` - a 422's per-field\n * issues, `{ path, message, code }`.\n */\n protected async toResponseError(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const described = HttpWire.describeUrl({ url, status: response.status });\n\n return HttpResponseReader.toApplicationError({\n response,\n rootKey: this.settings.errorRootKey,\n context: `[${this.name}][${verb}] ${response.status} | ${described}`,\n });\n }\n\n /**\n * Rows plus the total from `Content-Range`, reported absent when the header is. A GET unless told\n * otherwise: `method` and `body` reach a list route a service wrote to take its filter in a body.\n */\n async read<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n shape?: THttpReadShape;\n method?: string;\n body?: THttpBody;\n /** Extras the route offers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n /** The rows alone: every default extra off (`-*`), for a read that only counts or probes. */\n isEveryDefaultOff?: boolean;\n } & IHttpCallOptions,\n ): Promise<IHttpReadResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({\n headers: opts.headers,\n extra: opts.extra,\n isEveryDefaultOff: opts.isEveryDefaultOff,\n });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'read' });\n throw result;\n }\n\n // A 204 or an empty body is no row; a list asked for of it still throws below.\n const parsed = await this.readJsonBody({ response, url, verb: 'read' });\n const { body, extra } = HttpResponseReader.readExtra({\n body: parsed,\n headers: response.headers,\n });\n const contentRange = response.headers.get(HTTP.Headers.CONTENT_RANGE) ?? undefined;\n const range = HttpResponseReader.parseContentRange({ header: contentRange });\n const data = HttpWire.unwrapRows<R>({ body, shape: opts.shape ?? HttpReadShapes.LIST, url });\n\n return {\n data,\n hasRange: range !== undefined,\n contentRange,\n total: range?.total,\n skip: range?.skip,\n dataLength: Array.isArray(data) ? data.length : data === null ? 0 : 1,\n extra,\n };\n }\n\n /**\n * A write, and what it answered: the body as the rows, the count from `x-response-count`. The\n * connector asks for bare rows, so an IGNIS write answers the row or the rows, never the envelope.\n */\n async write<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method: string;\n body?: THttpBody;\n /** Extras the route answers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n } & IHttpCallOptions,\n ): Promise<IHttpWriteResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({ headers: opts.headers, extra: opts.extra });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'write' });\n throw result;\n }\n\n // A 204, or a route that answers nothing, has no body to parse.\n const parsed = await this.readJsonBody({ response, url, verb: 'write' });\n const { extra } = HttpResponseReader.readExtra({ body: parsed, headers: response.headers });\n const data = extra ? parsed.data : parsed;\n\n const countHeader = response.headers.get(HTTP.Headers.RESPONSE_COUNT_DATA);\n const counted = countHeader === null ? Number.NaN : Number(countHeader);\n\n return {\n data,\n count: Number.isFinite(counted)\n ? counted\n : Array.isArray(data)\n ? data.length\n : data === null\n ? 0\n : 1,\n ...(extra ? { extra } : {}),\n };\n }\n}\n"]}
@@ -1,4 +1,6 @@
1
+ import { ScopeFilters } from '@venizia/ignis-kernel';
1
2
  import type { TWhere } from '@venizia/ignis-kernel';
3
+ import type { TNullable } from '@venizia/ignis-helpers/common';
2
4
  /**
3
5
  * The `where` that matches zero rows - shared by the repository tier's `applyScopeFilter` and the
4
6
  * dialect tier's `toInclude`, so an unresolved or denied row scope compiles to the same deny
@@ -8,4 +10,19 @@ export declare class ScopeFilterDenial {
8
10
  /** The empty `inq` compiles to `sql\`false\`` in every dialect, deterministically matching zero rows. */
9
11
  static where<DataObject = any>(): TWhere<DataObject>;
10
12
  }
13
+ /**
14
+ * What a model's `access.resolve` returned, read once, the same way by the read path and the write guard.
15
+ *
16
+ * A scope is the symbol `ScopeFilters.UNRESTRICTED`, a usable `where`, or nothing (`null` / `undefined`). Anything else
17
+ * is a resolver that built something wrong, such as `false`, `0`, `''`, a list, `{}`, or an object with a key that is
18
+ * `undefined` (`{ merchantId: user.merchantId }` for a user without one). Reading it as "no restriction" would open
19
+ * every row, so it is nothing: the scope was not resolved, and `onMissing` decides (deny by default).
20
+ */
21
+ export declare class ScopeResolution {
22
+ /** A non-empty plain object whose every value is defined, and whose `and` / `or` branches are themselves usable (an `and` has at least one). */
23
+ private static isUsableWhere;
24
+ static normalize<DataObject = any>(opts: {
25
+ value: unknown;
26
+ }): TNullable<TWhere<DataObject>> | typeof ScopeFilters.UNRESTRICTED;
27
+ }
11
28
  //# sourceMappingURL=scope-filter.d.ts.map
@@ -1,4 +1,4 @@
1
- import { QueryOperators } from '@venizia/ignis-kernel';
1
+ import { QueryOperators, ScopeFilters } from '@venizia/ignis-kernel';
2
2
  /**
3
3
  * The `where` that matches zero rows - shared by the repository tier's `applyScopeFilter` and the
4
4
  * dialect tier's `toInclude`, so an unresolved or denied row scope compiles to the same deny
@@ -10,4 +10,49 @@ export class ScopeFilterDenial {
10
10
  return { id: { [QueryOperators.INQ]: [] } };
11
11
  }
12
12
  }
13
+ /**
14
+ * What a model's `access.resolve` returned, read once, the same way by the read path and the write guard.
15
+ *
16
+ * A scope is the symbol `ScopeFilters.UNRESTRICTED`, a usable `where`, or nothing (`null` / `undefined`). Anything else
17
+ * is a resolver that built something wrong, such as `false`, `0`, `''`, a list, `{}`, or an object with a key that is
18
+ * `undefined` (`{ merchantId: user.merchantId }` for a user without one). Reading it as "no restriction" would open
19
+ * every row, so it is nothing: the scope was not resolved, and `onMissing` decides (deny by default).
20
+ */
21
+ export class ScopeResolution {
22
+ /** A non-empty plain object whose every value is defined, and whose `and` / `or` branches are themselves usable (an `and` has at least one). */
23
+ static isUsableWhere(value) {
24
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
25
+ return false;
26
+ }
27
+ const entries = Object.entries(value);
28
+ if (entries.length === 0) {
29
+ return false;
30
+ }
31
+ return entries.every(([key, entry]) => {
32
+ if (entry === undefined) {
33
+ return false;
34
+ }
35
+ // An empty `and` is "all of nothing", true for every row, so it restricts nothing. An empty `or` matches nothing and stays.
36
+ if (key === QueryOperators.AND) {
37
+ return (Array.isArray(entry) &&
38
+ entry.length > 0 &&
39
+ entry.every((branch) => ScopeResolution.isUsableWhere(branch)));
40
+ }
41
+ if (key === QueryOperators.OR) {
42
+ return (Array.isArray(entry) && entry.every((branch) => ScopeResolution.isUsableWhere(branch)));
43
+ }
44
+ return true;
45
+ });
46
+ }
47
+ static normalize(opts) {
48
+ const { value } = opts;
49
+ if (value === ScopeFilters.UNRESTRICTED) {
50
+ return ScopeFilters.UNRESTRICTED;
51
+ }
52
+ if (value === null || value === undefined) {
53
+ return value;
54
+ }
55
+ return ScopeResolution.isUsableWhere(value) ? value : null;
56
+ }
57
+ }
13
58
  //# sourceMappingURL=scope-filter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"scope-filter.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/scope-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAGvD;;;;GAIG;AACH,MAAM,OAAO,iBAAiB;IAC5B,yGAAyG;IACzG,MAAM,CAAC,KAAK;QACV,OAAO,EAAE,EAAE,EAAE,EAAE,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,EAAwB,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { QueryOperators } from '@venizia/ignis-kernel';\nimport type { TWhere } from '@venizia/ignis-kernel';\n\n/**\n * The `where` that matches zero rows - shared by the repository tier's `applyScopeFilter` and the\n * dialect tier's `toInclude`, so an unresolved or denied row scope compiles to the same deny\n * predicate everywhere rather than two copies of a security predicate that could drift apart.\n */\nexport class ScopeFilterDenial {\n /** The empty `inq` compiles to `sql\\`false\\`` in every dialect, deterministically matching zero rows. */\n static where<DataObject = any>(): TWhere<DataObject> {\n return { id: { [QueryOperators.INQ]: [] } } as TWhere<DataObject>;\n }\n}\n"]}
1
+ {"version":3,"file":"scope-filter.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/scope-filter.ts"],"names":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KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,eAAe,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CACvF,CAAC;YACJ,CAAC;YAED,OAAO,IAAI,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,CAAC,SAAS,CAAmB,IAElC;QACC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEvB,IAAI,KAAK,KAAK,YAAY,CAAC,YAAY,EAAE,CAAC;YACxC,OAAO,YAAY,CAAC,YAAY,CAAC;QACnC,CAAC;QAED,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YAC1C,OAAO,KAAK,CAAC;QACf,CAAC;QAED,OAAO,eAAe,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,KAA4B,CAAC,CAAC,CAAC,IAAI,CAAC;IACrF,CAAC;CACF","sourcesContent":["import { QueryOperators, ScopeFilters } from '@venizia/ignis-kernel';\nimport type { TWhere } from '@venizia/ignis-kernel';\nimport type { TNullable } from '@venizia/ignis-helpers/common';\n\n/**\n * The `where` that matches zero rows - shared by the repository tier's `applyScopeFilter` and the\n * dialect tier's `toInclude`, so an unresolved or denied row scope compiles to the same deny\n * predicate everywhere rather than two copies of a security predicate that could drift apart.\n */\nexport class ScopeFilterDenial {\n /** The empty `inq` compiles to `sql\\`false\\`` in every dialect, deterministically matching zero rows. */\n static where<DataObject = any>(): TWhere<DataObject> {\n return { id: { [QueryOperators.INQ]: [] } } as TWhere<DataObject>;\n }\n}\n\n/**\n * What a model's `access.resolve` returned, read once, the same way by the read path and the write guard.\n *\n * A scope is the symbol `ScopeFilters.UNRESTRICTED`, a usable `where`, or nothing (`null` / `undefined`). Anything else\n * is a resolver that built something wrong, such as `false`, `0`, `''`, a list, `{}`, or an object with a key that is\n * `undefined` (`{ merchantId: user.merchantId }` for a user without one). Reading it as \"no restriction\" would open\n * every row, so it is nothing: the scope was not resolved, and `onMissing` decides (deny by default).\n */\nexport class ScopeResolution {\n /** A non-empty plain object whose every value is defined, and whose `and` / `or` branches are themselves usable (an `and` has at least one). */\n private static isUsableWhere(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n\n const entries = Object.entries(value);\n\n if (entries.length === 0) {\n return false;\n }\n\n return entries.every(([key, entry]) => {\n if (entry === undefined) {\n return false;\n }\n\n // An empty `and` is \"all of nothing\", true for every row, so it restricts nothing. An empty `or` matches nothing and stays.\n if (key === QueryOperators.AND) {\n return (\n Array.isArray(entry) &&\n entry.length > 0 &&\n entry.every((branch) => ScopeResolution.isUsableWhere(branch))\n );\n }\n\n if (key === QueryOperators.OR) {\n return (\n Array.isArray(entry) && entry.every((branch) => ScopeResolution.isUsableWhere(branch))\n );\n }\n\n return true;\n });\n }\n\n static normalize<DataObject = any>(opts: {\n value: unknown;\n }): TNullable<TWhere<DataObject>> | typeof ScopeFilters.UNRESTRICTED {\n const { value } = opts;\n\n if (value === ScopeFilters.UNRESTRICTED) {\n return ScopeFilters.UNRESTRICTED;\n }\n\n if (value === null || value === undefined) {\n return value;\n }\n\n return ScopeResolution.isUsableWhere(value) ? (value as TWhere<DataObject>) : null;\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { getError, RecordUtility } from '@venizia/ignis-helpers/core';
2
2
  import { QueryOperators, RepositoryErrorCodes, ScopeFilterMissingBehaviors, ScopeFilters, ScopeOperations, ScopeWriteGuards, } from '@venizia/ignis-kernel';
3
3
  import { HTTP } from '@venizia/ignis-helpers/common';
4
- import { ScopeFilterDenial } from './scope-filter.js';
4
+ import { ScopeFilterDenial, ScopeResolution } from './scope-filter.js';
5
5
  const WRITE_DENIED_STATUS = HTTP.ResultCodes.RS_4.Forbidden;
6
6
  const isScalar = (value) => {
7
7
  return (value === null ||
@@ -277,7 +277,7 @@ export class ScopeWriteGuard {
277
277
  static apply(opts) {
278
278
  const { settings, model, rows, operation } = opts;
279
279
  ScopeWriteGuard.assertWrite({ model, operation });
280
- const scope = settings.resolve({ operation });
280
+ const scope = ScopeResolution.normalize({ value: settings.resolve({ operation }) });
281
281
  if (scope === ScopeFilters.UNRESTRICTED) {
282
282
  return rows;
283
283
  }
@@ -1 +1 @@
1
- {"version":3,"file":"scope-write-guard.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/scope-write-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,2BAA2B,EAC3B,YAAY,EACZ,eAAe,EACf,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAO/B,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAiBnD,MAAM,mBAAmB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC;AAE5D,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoB,EAAE;IACpD,OAAO,CACL,KAAK,KAAK,IAAI;QACd,KAAK,YAAY,IAAI;QACrB,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,OAAO,KAAK,CAAC,CACjE,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,SAAS,GAAG,CAAC,KAAc,EAAiB,EAAE;IAClD,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACnB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrE,CAAC,CAAC;AAEF,MAAM,SAAS,GAAG,CAAC,IAA6D,EAAE,EAAE;IAClF,OAAO,IAAI,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,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AAM,CAAC,WAAW,CAAC,IAAmD;QAC5E,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QAElC,IAAI,eAAe,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,eAAe,CAAC,KAAK,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC;YAC1E,OAAO;QACT,CAAC;QAED,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,+EAA+E,KAAK,iBAAiB,SAAS,EAAE;SAC1H,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,YAAY,CAAC,IAAmE;QACrF,OAAO,eAAe,CAAC,MAAM,CAAC;YAC5B,GAAG,IAAI;YACP,MAAM,EAAE,qDAAqD;SAC9D,CAAC,CAAC;IACL,CAAC;IAED,kFAAkF;IAC1E,MAAM,CAAC,MAAM,CAAC,IAKrB;QACC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAElD,OAAO,QAAQ,CAAC;YACd,UAAU,EAAE,mBAAmB;YAC/B,WAAW,EAAE,oBAAoB,CAAC,kBAAkB;YACpD,OAAO,EAAE;gBACP,IAAI,SAAS,iDAAiD,KAAK,EAAE;gBACrE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBACxC,MAAM;aACP,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { getError, RecordUtility } from '@venizia/ignis-helpers/core';\nimport {\n QueryOperators,\n RepositoryErrorCodes,\n ScopeFilterMissingBehaviors,\n ScopeFilters,\n ScopeOperations,\n ScopeWriteGuards,\n} from '@venizia/ignis-kernel';\nimport type {\n IModelAccessSettings,\n TModelAccessSettings,\n TScopeOperation,\n TWhere,\n} from '@venizia/ignis-kernel';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { ScopeFilterDenial } from './scope-filter';\n\ntype TScalar = string | number | bigint | boolean | Date | null;\n\n/** The allowed values per scope column, each normalised so `1` and `'1'` and equal dates compare equal. */\ntype TConstraints = Map<string, Set<string | null>>;\n\ntype TExtraction =\n | { isVerifiable: true; constraints: TConstraints }\n | { isVerifiable: false; reason: string };\n\n/** What the scope becomes for a write: a `where`, no row at all, or a shape that cannot be narrowed. */\ntype TNarrowed =\n | { kind: 'where'; where: TWhere }\n | { kind: 'none' }\n | { kind: 'unverifiable'; reason: string };\n\nconst WRITE_DENIED_STATUS = HTTP.ResultCodes.RS_4.Forbidden;\n\nconst isScalar = (value: unknown): value is TScalar => {\n return (\n value === null ||\n value instanceof Date ||\n ['string', 'number', 'bigint', 'boolean'].includes(typeof value)\n );\n};\n\nconst normalise = (value: TScalar): string | null => {\n if (value === null) {\n return null;\n }\n\n return value instanceof Date ? value.toISOString() : String(value);\n};\n\nconst intersect = (opts: { left: Set<string | null>; right: Set<string | null> }) => {\n return new Set([...opts.left].filter((value) => opts.right.has(value)));\n};\n\n/**\n * The write side of `@model` settings.access. The resolved scope is a `where`; the guard reads\n * from it the columns it constrains and the values it allows, and holds every written row to them.\n *\n * Only shapes that can be checked are read: a column equal to a scalar or `null`, `{ eq }`, `{ inq }`\n * (or `in`), an array, `and` of those, and an `or` whose branches all constrain the same column. Anything\n * else - an `or` over several columns, ranges, `like`, a nested path - makes\n * the scope unverifiable, and the write is refused with its own message instead of being skipped.\n */\nexport class ScopeWriteGuard {\n static extractConstraints(opts: { where: TWhere }): TExtraction {\n const constraints: TConstraints = new Map();\n const reason = ScopeWriteGuard.collect({\n where: opts.where as Record<string, unknown>,\n constraints,\n });\n\n return reason === undefined\n ? { isVerifiable: true, constraints }\n : { isVerifiable: false, reason };\n }\n\n /** Adds the where's constraints to `constraints`; returns the reason it cannot be verified, if any. */\n private static collect(opts: {\n where: Record<string, unknown>;\n constraints: TConstraints;\n }): string | undefined {\n const { where, constraints } = opts;\n\n for (const [key, value] of Object.entries(where)) {\n if (key === 'and') {\n if (!Array.isArray(value)) {\n return \"'and' is not a list\";\n }\n\n for (const part of value) {\n const reason = ScopeWriteGuard.collect({\n where: part as Record<string, unknown>,\n constraints,\n });\n\n if (reason !== undefined) {\n return reason;\n }\n }\n\n continue;\n }\n\n if (key === 'or') {\n const union = ScopeWriteGuard.unionOfBranches({ branches: value });\n\n if (typeof union === 'string') {\n return union;\n }\n\n const existing = constraints.get(union.column);\n constraints.set(\n union.column,\n existing ? intersect({ left: existing, right: union.allowed }) : union.allowed,\n );\n continue;\n }\n\n if (key.includes('.')) {\n return `the nested path '${key}' cannot be checked on a write`;\n }\n\n const allowed = ScopeWriteGuard.allowedValues({ value });\n\n if (typeof allowed === 'string') {\n return `column '${key}': ${allowed}`;\n }\n\n const existing = constraints.get(key);\n constraints.set(key, existing ? intersect({ left: existing, right: allowed }) : allowed);\n }\n\n return undefined;\n }\n\n /**\n * An `or` is checkable only when every branch constrains the same single column with a scalar,\n * `null`, `eq`, `in` or `inq`: the allowed values are then the union of the branches. This is the\n * shared-rows scope, `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }`. Any other `or`\n * (several columns, ranges, nested `and` or `or`) cannot be checked.\n */\n private static unionOfBranches(opts: {\n branches: unknown;\n }): { column: string; allowed: Set<string | null> } | string {\n const { branches } = opts;\n\n if (!Array.isArray(branches) || branches.length === 0) {\n return \"'or' is not a list\";\n }\n\n let column: string | undefined;\n const allowed = new Set<string | null>();\n\n for (const branch of branches) {\n const entries = Object.entries((branch ?? {}) as Record<string, unknown>);\n\n if (entries.length !== 1) {\n return \"an 'or' branch with several conditions cannot be checked on a write\";\n }\n\n const [key, value] = entries[0];\n\n if (key === 'and' || key === 'or' || key.includes('.')) {\n return `an 'or' branch over '${key}' cannot be checked on a write`;\n }\n\n if (column !== undefined && column !== key) {\n return \"an 'or' over different columns cannot be checked on a write\";\n }\n\n column = key;\n const values = ScopeWriteGuard.allowedValues({ value });\n\n if (typeof values === 'string') {\n return `column '${key}': ${values}`;\n }\n\n values.forEach((entry) => allowed.add(entry));\n }\n\n return { column: column as string, allowed };\n }\n\n /** The values one column's condition allows, or a string naming why it cannot be checked. */\n private static allowedValues(opts: { value: unknown }): Set<string | null> | string {\n const { value } = opts;\n\n if (isScalar(value)) {\n return new Set([normalise(value)]);\n }\n\n if (Array.isArray(value)) {\n return value.every(isScalar)\n ? new Set(value.map(normalise))\n : 'a list with a non-scalar entry';\n }\n\n if (typeof value !== 'object' || value === undefined) {\n return 'an unsupported condition';\n }\n\n const operators = Object.keys(value as object);\n\n if (operators.length !== 1) {\n return `a condition with ${operators.length} operators cannot be checked on a write`;\n }\n\n const [operator] = operators;\n const operand = (value as Record<string, unknown>)[operator];\n\n if (operator === QueryOperators.EQ && isScalar(operand)) {\n return new Set([normalise(operand)]);\n }\n\n if (\n (operator === QueryOperators.INQ || operator === QueryOperators.IN) &&\n Array.isArray(operand)\n ) {\n return operand.every(isScalar)\n ? new Set(operand.map(normalise))\n : 'a list with a non-scalar entry';\n }\n\n return `the operator '${operator}' cannot be checked on a write`;\n }\n\n /**\n * The scope as a MUTATION `where` (update, delete, soft delete, restore). A scope with a `null`\n * branch - `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }` - lets the caller READ the\n * shared rows. Changing or deleting one is the same permission as creating one, `write.sharedRows`,\n * so without it the `null` branch is removed and only the caller's own rows match. With\n * `sharedRows` the scope is returned as it is.\n *\n * Only the shapes the write guard can read are narrowed. Any other shape cannot be shown to exclude\n * the shared rows, so the mutation is refused, as an update with a payload already is.\n */\n static mutationWhere(opts: {\n settings: TModelAccessSettings;\n model: string;\n operation: TScopeOperation;\n scopeWhere: TWhere;\n }): TWhere {\n const { settings, model, operation, scopeWhere } = opts;\n\n ScopeWriteGuard.assertWrite({ model, operation });\n\n // Checked with `sharedRows` too: it lets the null branch through, not a shape the guard cannot read.\n const narrowed = ScopeWriteGuard.withoutShared({ where: scopeWhere });\n\n if (narrowed.kind === 'unverifiable') {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope cannot be verified on a write | ${narrowed.reason}`,\n });\n }\n\n if (settings.write?.sharedRows === true) {\n return scopeWhere;\n }\n\n return narrowed.kind === 'none' ? ScopeFilterDenial.where() : narrowed.where;\n }\n\n /** `where` with every `null` the scope allows removed; `none` when nothing but `null` was allowed. */\n private static withoutShared(opts: { where: TWhere }): TNarrowed {\n const result: TWhere = {};\n\n for (const [key, value] of Object.entries(opts.where)) {\n if (key === 'and' || key === 'or') {\n if (!Array.isArray(value) || (key === 'or' && value.length === 0)) {\n return { kind: 'unverifiable', reason: `'${key}' is not a list` };\n }\n\n // An 'or' is read only when every branch constrains the same column, as the guard reads it: a branch over another column\n // could match a shared row without a null in sight.\n if (key === 'or') {\n const union = ScopeWriteGuard.unionOfBranches({ branches: value });\n\n if (typeof union === 'string') {\n return { kind: 'unverifiable', reason: union };\n }\n }\n\n const kept: TWhere[] = [];\n\n for (const part of value) {\n const narrowed = ScopeWriteGuard.withoutShared({\n where: RecordUtility.isPlainRecord(part) ? part : {},\n });\n\n if (narrowed.kind === 'unverifiable') {\n return narrowed;\n }\n\n if (narrowed.kind === 'none') {\n // One impossible 'and' part makes the whole 'and' impossible; an impossible 'or' branch just drops out.\n if (key === 'and') {\n return narrowed;\n }\n\n continue;\n }\n\n kept.push(narrowed.where);\n }\n\n if (key === 'or' && kept.length === 0) {\n return { kind: 'none' };\n }\n\n result[key] = kept;\n continue;\n }\n\n if (key.includes('.')) {\n return {\n kind: 'unverifiable',\n reason: `the nested path '${key}' cannot be checked on a write`,\n };\n }\n\n const narrowed = ScopeWriteGuard.conditionWithoutNull({ value });\n\n if (narrowed.kind !== 'condition') {\n return narrowed.kind === 'none'\n ? { kind: 'none' }\n : { kind: 'unverifiable', reason: `column '${key}': ${narrowed.reason}` };\n }\n\n result[key] = narrowed.value;\n }\n\n return { kind: 'where', where: result };\n }\n\n /** One column's condition without its `null` values, reading the same shapes `allowedValues` reads. */\n private static conditionWithoutNull(opts: {\n value: unknown;\n }):\n | { kind: 'condition'; value: unknown }\n | { kind: 'none' }\n | { kind: 'unverifiable'; reason: string } {\n const { value } = opts;\n\n const list = (entries: unknown[]) => {\n if (!entries.every(isScalar)) {\n return { kind: 'unverifiable' as const, reason: 'a list with a non-scalar entry' };\n }\n\n const kept = entries.filter((entry) => entry !== null);\n\n return kept.length === 0\n ? { kind: 'none' as const }\n : { kind: 'condition' as const, value: kept };\n };\n\n if (isScalar(value)) {\n return value === null ? { kind: 'none' } : { kind: 'condition', value };\n }\n\n if (Array.isArray(value)) {\n return list(value);\n }\n\n if (!RecordUtility.isPlainRecord(value)) {\n return { kind: 'unverifiable', reason: 'an unsupported condition' };\n }\n\n const operators = Object.keys(value);\n\n if (operators.length !== 1) {\n return {\n kind: 'unverifiable',\n reason: `a condition with ${operators.length} operators cannot be checked on a write`,\n };\n }\n\n const [operator] = operators;\n const operand = value[operator];\n\n if (operator === QueryOperators.EQ && isScalar(operand)) {\n return operand === null ? { kind: 'none' } : { kind: 'condition', value };\n }\n\n if (\n (operator === QueryOperators.INQ || operator === QueryOperators.IN) &&\n Array.isArray(operand)\n ) {\n const narrowed = list(operand);\n\n return narrowed.kind === 'condition'\n ? { kind: 'condition', value: { [operator]: narrowed.value } }\n : narrowed;\n }\n\n return {\n kind: 'unverifiable',\n reason: `the operator '${operator}' cannot be checked on a write`,\n };\n }\n\n /**\n * Holds `rows` to the scope `settings.resolve()` returns now. Returns the rows to write: the same\n * objects when nothing changes, copies with the scope columns filled in for `assign`. Throws, and\n * so writes nothing, when any row is outside the scope.\n */\n static apply<Row extends Record<string, unknown>>(opts: {\n settings: IModelAccessSettings;\n model: string;\n rows: Row[];\n operation: TScopeOperation;\n }): Row[] {\n const { settings, model, rows, operation } = opts;\n\n ScopeWriteGuard.assertWrite({ model, operation });\n\n const scope = settings.resolve({ operation });\n\n if (scope === ScopeFilters.UNRESTRICTED) {\n return rows;\n }\n\n if (scope === null || scope === undefined) {\n // An update is already confined by the scoped `where`, which under `deny` matches no row; the\n // guard adds nothing there. A create has no such `where`, so an unresolved scope refuses it.\n if (\n settings.onMissing === ScopeFilterMissingBehaviors.ALLOW ||\n operation !== ScopeOperations.CREATE\n ) {\n return rows;\n }\n\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: 'no scope could be resolved for this caller',\n });\n }\n\n const extraction = ScopeWriteGuard.extractConstraints({ where: scope });\n\n if (!extraction.isVerifiable) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope cannot be verified on a write | ${extraction.reason}`,\n });\n }\n\n const { constraints } = extraction;\n const declared = settings.columns;\n\n if (declared) {\n const undeclared = [...constraints.keys()].find((column) => !declared.includes(column));\n\n if (undeclared !== undefined) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope constrains column '${undeclared}', which access.columns does not declare`,\n });\n }\n }\n\n const isAssign =\n settings.write?.mode === ScopeWriteGuards.ASSIGN && operation === ScopeOperations.CREATE;\n const sharedRows = settings.write?.sharedRows === true;\n\n return rows.map((row) => {\n let result = row;\n\n for (const [column, allowed] of constraints) {\n const value = (row as Record<string, unknown>)[column];\n\n if (value === undefined) {\n if (operation !== ScopeOperations.CREATE) {\n continue;\n }\n\n // `assign` first: stamping gives the row an owner, which is safer than leaving it shared.\n const only = allowed.size === 1 ? [...allowed][0] : undefined;\n\n if (isAssign && only !== undefined && only !== null) {\n result = { ...result, [column]: only };\n continue;\n }\n\n // Absent means the database default, usually `null`, so it is held to the `null` rule.\n if (sharedRows) {\n continue;\n }\n\n throw ScopeWriteGuard.denied({\n model,\n operation,\n column,\n detail: 'the scope column is missing',\n });\n }\n\n const normalised = isScalar(value) ? normalise(value) : undefined;\n // A `null` branch in the scope lets this caller READ shared rows. Writing one (or moving a\n // row into the shared set) is a separate permission: only `sharedRows` grants it.\n const isOutside = normalised === null ? !sharedRows : !allowed.has(normalised as string);\n\n if (normalised === undefined || isOutside) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n column,\n detail: 'the value is outside the resolved scope',\n });\n }\n }\n\n return result;\n });\n }\n\n /**\n * The write guard runs for a write only. A READ reaching it is a bug in the caller, not a request,\n * so it throws a plain error rather than a refusal the caller could map to a status.\n */\n private static assertWrite(opts: { model: string; operation: TScopeOperation }): void {\n const { model, operation } = opts;\n\n if (ScopeOperations.includes({ group: ScopeOperations.WRITE, operation })) {\n return;\n }\n\n throw getError({\n message: `[ScopeWriteGuard] the write guard runs for a write operation only | entity: ${model} | operation: ${operation}`,\n });\n }\n\n /**\n * A write to a `through` model named no parent, a parent that does not exist, or one outside the caller's scope. One\n * message for all three, so a foreign parent's existence does not leak.\n */\n static parentDenied(opts: { model: string; operation: TScopeOperation; column: string }) {\n return ScopeWriteGuard.denied({\n ...opts,\n detail: \"the parent is missing or outside the caller's scope\",\n });\n }\n\n /** Names the model and the column, never a value: the caller may be a request. */\n private static denied(opts: {\n model: string;\n operation: TScopeOperation;\n column?: string;\n detail: string;\n }) {\n const { model, operation, column, detail } = opts;\n\n return getError({\n statusCode: WRITE_DENIED_STATUS,\n messageCode: RepositoryErrorCodes.SCOPE_WRITE_DENIED,\n message: [\n `[${operation}] write refused by the access scope | entity: ${model}`,\n ...(column ? [`column: ${column}`] : []),\n detail,\n ].join(' | '),\n });\n }\n}\n"]}
1
+ {"version":3,"file":"scope-write-guard.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/scope-write-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,2BAA2B,EAC3B,YAAY,EACZ,eAAe,EACf,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAO/B,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAiBpE,MAAM,mBAAmB,GAAG,IAAI,CAAC,WAA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KrB;QACC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAElD,OAAO,QAAQ,CAAC;YACd,UAAU,EAAE,mBAAmB;YAC/B,WAAW,EAAE,oBAAoB,CAAC,kBAAkB;YACpD,OAAO,EAAE;gBACP,IAAI,SAAS,iDAAiD,KAAK,EAAE;gBACrE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBACxC,MAAM;aACP,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { getError, RecordUtility } from '@venizia/ignis-helpers/core';\nimport {\n QueryOperators,\n RepositoryErrorCodes,\n ScopeFilterMissingBehaviors,\n ScopeFilters,\n ScopeOperations,\n ScopeWriteGuards,\n} from '@venizia/ignis-kernel';\nimport type {\n IModelAccessSettings,\n TModelAccessSettings,\n TScopeOperation,\n TWhere,\n} from '@venizia/ignis-kernel';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { ScopeFilterDenial, ScopeResolution } from './scope-filter';\n\ntype TScalar = string | number | bigint | boolean | Date | null;\n\n/** The allowed values per scope column, each normalised so `1` and `'1'` and equal dates compare equal. */\ntype TConstraints = Map<string, Set<string | null>>;\n\ntype TExtraction =\n | { isVerifiable: true; constraints: TConstraints }\n | { isVerifiable: false; reason: string };\n\n/** What the scope becomes for a write: a `where`, no row at all, or a shape that cannot be narrowed. */\ntype TNarrowed =\n | { kind: 'where'; where: TWhere }\n | { kind: 'none' }\n | { kind: 'unverifiable'; reason: string };\n\nconst WRITE_DENIED_STATUS = HTTP.ResultCodes.RS_4.Forbidden;\n\nconst isScalar = (value: unknown): value is TScalar => {\n return (\n value === null ||\n value instanceof Date ||\n ['string', 'number', 'bigint', 'boolean'].includes(typeof value)\n );\n};\n\nconst normalise = (value: TScalar): string | null => {\n if (value === null) {\n return null;\n }\n\n return value instanceof Date ? value.toISOString() : String(value);\n};\n\nconst intersect = (opts: { left: Set<string | null>; right: Set<string | null> }) => {\n return new Set([...opts.left].filter((value) => opts.right.has(value)));\n};\n\n/**\n * The write side of `@model` settings.access. The resolved scope is a `where`; the guard reads\n * from it the columns it constrains and the values it allows, and holds every written row to them.\n *\n * Only shapes that can be checked are read: a column equal to a scalar or `null`, `{ eq }`, `{ inq }`\n * (or `in`), an array, `and` of those, and an `or` whose branches all constrain the same column. Anything\n * else - an `or` over several columns, ranges, `like`, a nested path - makes\n * the scope unverifiable, and the write is refused with its own message instead of being skipped.\n */\nexport class ScopeWriteGuard {\n static extractConstraints(opts: { where: TWhere }): TExtraction {\n const constraints: TConstraints = new Map();\n const reason = ScopeWriteGuard.collect({\n where: opts.where as Record<string, unknown>,\n constraints,\n });\n\n return reason === undefined\n ? { isVerifiable: true, constraints }\n : { isVerifiable: false, reason };\n }\n\n /** Adds the where's constraints to `constraints`; returns the reason it cannot be verified, if any. */\n private static collect(opts: {\n where: Record<string, unknown>;\n constraints: TConstraints;\n }): string | undefined {\n const { where, constraints } = opts;\n\n for (const [key, value] of Object.entries(where)) {\n if (key === 'and') {\n if (!Array.isArray(value)) {\n return \"'and' is not a list\";\n }\n\n for (const part of value) {\n const reason = ScopeWriteGuard.collect({\n where: part as Record<string, unknown>,\n constraints,\n });\n\n if (reason !== undefined) {\n return reason;\n }\n }\n\n continue;\n }\n\n if (key === 'or') {\n const union = ScopeWriteGuard.unionOfBranches({ branches: value });\n\n if (typeof union === 'string') {\n return union;\n }\n\n const existing = constraints.get(union.column);\n constraints.set(\n union.column,\n existing ? intersect({ left: existing, right: union.allowed }) : union.allowed,\n );\n continue;\n }\n\n if (key.includes('.')) {\n return `the nested path '${key}' cannot be checked on a write`;\n }\n\n const allowed = ScopeWriteGuard.allowedValues({ value });\n\n if (typeof allowed === 'string') {\n return `column '${key}': ${allowed}`;\n }\n\n const existing = constraints.get(key);\n constraints.set(key, existing ? intersect({ left: existing, right: allowed }) : allowed);\n }\n\n return undefined;\n }\n\n /**\n * An `or` is checkable only when every branch constrains the same single column with a scalar,\n * `null`, `eq`, `in` or `inq`: the allowed values are then the union of the branches. This is the\n * shared-rows scope, `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }`. Any other `or`\n * (several columns, ranges, nested `and` or `or`) cannot be checked.\n */\n private static unionOfBranches(opts: {\n branches: unknown;\n }): { column: string; allowed: Set<string | null> } | string {\n const { branches } = opts;\n\n if (!Array.isArray(branches) || branches.length === 0) {\n return \"'or' is not a list\";\n }\n\n let column: string | undefined;\n const allowed = new Set<string | null>();\n\n for (const branch of branches) {\n const entries = Object.entries((branch ?? {}) as Record<string, unknown>);\n\n if (entries.length !== 1) {\n return \"an 'or' branch with several conditions cannot be checked on a write\";\n }\n\n const [key, value] = entries[0];\n\n if (key === 'and' || key === 'or' || key.includes('.')) {\n return `an 'or' branch over '${key}' cannot be checked on a write`;\n }\n\n if (column !== undefined && column !== key) {\n return \"an 'or' over different columns cannot be checked on a write\";\n }\n\n column = key;\n const values = ScopeWriteGuard.allowedValues({ value });\n\n if (typeof values === 'string') {\n return `column '${key}': ${values}`;\n }\n\n values.forEach((entry) => allowed.add(entry));\n }\n\n return { column: column as string, allowed };\n }\n\n /** The values one column's condition allows, or a string naming why it cannot be checked. */\n private static allowedValues(opts: { value: unknown }): Set<string | null> | string {\n const { value } = opts;\n\n if (isScalar(value)) {\n return new Set([normalise(value)]);\n }\n\n if (Array.isArray(value)) {\n return value.every(isScalar)\n ? new Set(value.map(normalise))\n : 'a list with a non-scalar entry';\n }\n\n if (typeof value !== 'object' || value === undefined) {\n return 'an unsupported condition';\n }\n\n const operators = Object.keys(value as object);\n\n if (operators.length !== 1) {\n return `a condition with ${operators.length} operators cannot be checked on a write`;\n }\n\n const [operator] = operators;\n const operand = (value as Record<string, unknown>)[operator];\n\n if (operator === QueryOperators.EQ && isScalar(operand)) {\n return new Set([normalise(operand)]);\n }\n\n if (\n (operator === QueryOperators.INQ || operator === QueryOperators.IN) &&\n Array.isArray(operand)\n ) {\n return operand.every(isScalar)\n ? new Set(operand.map(normalise))\n : 'a list with a non-scalar entry';\n }\n\n return `the operator '${operator}' cannot be checked on a write`;\n }\n\n /**\n * The scope as a MUTATION `where` (update, delete, soft delete, restore). A scope with a `null`\n * branch - `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }` - lets the caller READ the\n * shared rows. Changing or deleting one is the same permission as creating one, `write.sharedRows`,\n * so without it the `null` branch is removed and only the caller's own rows match. With\n * `sharedRows` the scope is returned as it is.\n *\n * Only the shapes the write guard can read are narrowed. Any other shape cannot be shown to exclude\n * the shared rows, so the mutation is refused, as an update with a payload already is.\n */\n static mutationWhere(opts: {\n settings: TModelAccessSettings;\n model: string;\n operation: TScopeOperation;\n scopeWhere: TWhere;\n }): TWhere {\n const { settings, model, operation, scopeWhere } = opts;\n\n ScopeWriteGuard.assertWrite({ model, operation });\n\n // Checked with `sharedRows` too: it lets the null branch through, not a shape the guard cannot read.\n const narrowed = ScopeWriteGuard.withoutShared({ where: scopeWhere });\n\n if (narrowed.kind === 'unverifiable') {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope cannot be verified on a write | ${narrowed.reason}`,\n });\n }\n\n if (settings.write?.sharedRows === true) {\n return scopeWhere;\n }\n\n return narrowed.kind === 'none' ? ScopeFilterDenial.where() : narrowed.where;\n }\n\n /** `where` with every `null` the scope allows removed; `none` when nothing but `null` was allowed. */\n private static withoutShared(opts: { where: TWhere }): TNarrowed {\n const result: TWhere = {};\n\n for (const [key, value] of Object.entries(opts.where)) {\n if (key === 'and' || key === 'or') {\n if (!Array.isArray(value) || (key === 'or' && value.length === 0)) {\n return { kind: 'unverifiable', reason: `'${key}' is not a list` };\n }\n\n // An 'or' is read only when every branch constrains the same column, as the guard reads it: a branch over another column\n // could match a shared row without a null in sight.\n if (key === 'or') {\n const union = ScopeWriteGuard.unionOfBranches({ branches: value });\n\n if (typeof union === 'string') {\n return { kind: 'unverifiable', reason: union };\n }\n }\n\n const kept: TWhere[] = [];\n\n for (const part of value) {\n const narrowed = ScopeWriteGuard.withoutShared({\n where: RecordUtility.isPlainRecord(part) ? part : {},\n });\n\n if (narrowed.kind === 'unverifiable') {\n return narrowed;\n }\n\n if (narrowed.kind === 'none') {\n // One impossible 'and' part makes the whole 'and' impossible; an impossible 'or' branch just drops out.\n if (key === 'and') {\n return narrowed;\n }\n\n continue;\n }\n\n kept.push(narrowed.where);\n }\n\n if (key === 'or' && kept.length === 0) {\n return { kind: 'none' };\n }\n\n result[key] = kept;\n continue;\n }\n\n if (key.includes('.')) {\n return {\n kind: 'unverifiable',\n reason: `the nested path '${key}' cannot be checked on a write`,\n };\n }\n\n const narrowed = ScopeWriteGuard.conditionWithoutNull({ value });\n\n if (narrowed.kind !== 'condition') {\n return narrowed.kind === 'none'\n ? { kind: 'none' }\n : { kind: 'unverifiable', reason: `column '${key}': ${narrowed.reason}` };\n }\n\n result[key] = narrowed.value;\n }\n\n return { kind: 'where', where: result };\n }\n\n /** One column's condition without its `null` values, reading the same shapes `allowedValues` reads. */\n private static conditionWithoutNull(opts: {\n value: unknown;\n }):\n | { kind: 'condition'; value: unknown }\n | { kind: 'none' }\n | { kind: 'unverifiable'; reason: string } {\n const { value } = opts;\n\n const list = (entries: unknown[]) => {\n if (!entries.every(isScalar)) {\n return { kind: 'unverifiable' as const, reason: 'a list with a non-scalar entry' };\n }\n\n const kept = entries.filter((entry) => entry !== null);\n\n return kept.length === 0\n ? { kind: 'none' as const }\n : { kind: 'condition' as const, value: kept };\n };\n\n if (isScalar(value)) {\n return value === null ? { kind: 'none' } : { kind: 'condition', value };\n }\n\n if (Array.isArray(value)) {\n return list(value);\n }\n\n if (!RecordUtility.isPlainRecord(value)) {\n return { kind: 'unverifiable', reason: 'an unsupported condition' };\n }\n\n const operators = Object.keys(value);\n\n if (operators.length !== 1) {\n return {\n kind: 'unverifiable',\n reason: `a condition with ${operators.length} operators cannot be checked on a write`,\n };\n }\n\n const [operator] = operators;\n const operand = value[operator];\n\n if (operator === QueryOperators.EQ && isScalar(operand)) {\n return operand === null ? { kind: 'none' } : { kind: 'condition', value };\n }\n\n if (\n (operator === QueryOperators.INQ || operator === QueryOperators.IN) &&\n Array.isArray(operand)\n ) {\n const narrowed = list(operand);\n\n return narrowed.kind === 'condition'\n ? { kind: 'condition', value: { [operator]: narrowed.value } }\n : narrowed;\n }\n\n return {\n kind: 'unverifiable',\n reason: `the operator '${operator}' cannot be checked on a write`,\n };\n }\n\n /**\n * Holds `rows` to the scope `settings.resolve()` returns now. Returns the rows to write: the same\n * objects when nothing changes, copies with the scope columns filled in for `assign`. Throws, and\n * so writes nothing, when any row is outside the scope.\n */\n static apply<Row extends Record<string, unknown>>(opts: {\n settings: IModelAccessSettings;\n model: string;\n rows: Row[];\n operation: TScopeOperation;\n }): Row[] {\n const { settings, model, rows, operation } = opts;\n\n ScopeWriteGuard.assertWrite({ model, operation });\n\n const scope = ScopeResolution.normalize({ value: settings.resolve({ operation }) });\n\n if (scope === ScopeFilters.UNRESTRICTED) {\n return rows;\n }\n\n if (scope === null || scope === undefined) {\n // An update is already confined by the scoped `where`, which under `deny` matches no row; the\n // guard adds nothing there. A create has no such `where`, so an unresolved scope refuses it.\n if (\n settings.onMissing === ScopeFilterMissingBehaviors.ALLOW ||\n operation !== ScopeOperations.CREATE\n ) {\n return rows;\n }\n\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: 'no scope could be resolved for this caller',\n });\n }\n\n const extraction = ScopeWriteGuard.extractConstraints({ where: scope });\n\n if (!extraction.isVerifiable) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope cannot be verified on a write | ${extraction.reason}`,\n });\n }\n\n const { constraints } = extraction;\n const declared = settings.columns;\n\n if (declared) {\n const undeclared = [...constraints.keys()].find((column) => !declared.includes(column));\n\n if (undeclared !== undefined) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope constrains column '${undeclared}', which access.columns does not declare`,\n });\n }\n }\n\n const isAssign =\n settings.write?.mode === ScopeWriteGuards.ASSIGN && operation === ScopeOperations.CREATE;\n const sharedRows = settings.write?.sharedRows === true;\n\n return rows.map((row) => {\n let result = row;\n\n for (const [column, allowed] of constraints) {\n const value = (row as Record<string, unknown>)[column];\n\n if (value === undefined) {\n if (operation !== ScopeOperations.CREATE) {\n continue;\n }\n\n // `assign` first: stamping gives the row an owner, which is safer than leaving it shared.\n const only = allowed.size === 1 ? [...allowed][0] : undefined;\n\n if (isAssign && only !== undefined && only !== null) {\n result = { ...result, [column]: only };\n continue;\n }\n\n // Absent means the database default, usually `null`, so it is held to the `null` rule.\n if (sharedRows) {\n continue;\n }\n\n throw ScopeWriteGuard.denied({\n model,\n operation,\n column,\n detail: 'the scope column is missing',\n });\n }\n\n const normalised = isScalar(value) ? normalise(value) : undefined;\n // A `null` branch in the scope lets this caller READ shared rows. Writing one (or moving a\n // row into the shared set) is a separate permission: only `sharedRows` grants it.\n const isOutside = normalised === null ? !sharedRows : !allowed.has(normalised as string);\n\n if (normalised === undefined || isOutside) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n column,\n detail: 'the value is outside the resolved scope',\n });\n }\n }\n\n return result;\n });\n }\n\n /**\n * The write guard runs for a write only. A READ reaching it is a bug in the caller, not a request,\n * so it throws a plain error rather than a refusal the caller could map to a status.\n */\n private static assertWrite(opts: { model: string; operation: TScopeOperation }): void {\n const { model, operation } = opts;\n\n if (ScopeOperations.includes({ group: ScopeOperations.WRITE, operation })) {\n return;\n }\n\n throw getError({\n message: `[ScopeWriteGuard] the write guard runs for a write operation only | entity: ${model} | operation: ${operation}`,\n });\n }\n\n /**\n * A write to a `through` model named no parent, a parent that does not exist, or one outside the caller's scope. One\n * message for all three, so a foreign parent's existence does not leak.\n */\n static parentDenied(opts: { model: string; operation: TScopeOperation; column: string }) {\n return ScopeWriteGuard.denied({\n ...opts,\n detail: \"the parent is missing or outside the caller's scope\",\n });\n }\n\n /** Names the model and the column, never a value: the caller may be a request. */\n private static denied(opts: {\n model: string;\n operation: TScopeOperation;\n column?: string;\n detail: string;\n }) {\n const { model, operation, column, detail } = opts;\n\n return getError({\n statusCode: WRITE_DENIED_STATUS,\n messageCode: RepositoryErrorCodes.SCOPE_WRITE_DENIED,\n message: [\n `[${operation}] write refused by the access scope | entity: ${model}`,\n ...(column ? [`column: ${column}`] : []),\n detail,\n ].join(' | '),\n });\n }\n}\n"]}
@@ -21,10 +21,28 @@ export type TRelationConfig = {
21
21
  export type TTableColumns = ReturnType<typeof getTableColumns>;
22
22
  /** The engine-neutral query-dialect surface a repository consumes via `dataSource.getQueryDialect()`, never constructed inside the repository. */
23
23
  export interface IRelationalQueryDialect {
24
+ /** The relations a schema declares, by name. */
25
+ resolveRelations(opts: {
26
+ schema: TTableSchemaWithId;
27
+ }): Record<string, TRelationConfig>;
28
+ /** The error the query gives for a `where` key or an `order` field that names no column. */
29
+ columnNotFoundError(opts: {
30
+ kind: 'where' | 'order';
31
+ key: string;
32
+ tableName: string;
33
+ }): Error;
34
+ /** The fields the model of a schema hides. */
35
+ resolveHiddenProperties(opts: {
36
+ schema: TTableSchemaWithId;
37
+ }): Set<string>;
24
38
  mergeFilter<T = any>(opts: {
25
39
  defaultFilter?: TFilter<T>;
26
40
  userFilter?: TFilter<T>;
27
41
  }): TFilter<T>;
42
+ composeScope<T = any>(opts: {
43
+ scopeWhere: TWhere<T>;
44
+ userFilter?: TFilter<T>;
45
+ }): TFilter<T>;
28
46
  build<Schema extends TTableSchemaWithId>(opts: {
29
47
  tableName: string;
30
48
  schema: Schema;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n IExtraOptions,\n IModelAccessThroughSettings,\n RelationTypes,\n ScopeFilters,\n TDrizzleQueryOptions,\n TFilter,\n TModelAccessSettings,\n TScopeOperation,\n TWhere,\n} from '@venizia/ignis-kernel';\nimport type { TNullable } from '@venizia/ignis-helpers/common';\nimport type { ScopeThroughLink } from './scope-through';\nimport type {\n IRelationalDataSource,\n IRelationalTransaction,\n} from '@/relational/core/datasources/common';\nimport type { TTableObject, TTableSchemaWithId } from '@/relational/core/models/common';\nimport type {\n AnyColumn,\n createTableRelationsHelpers,\n getTableColumns,\n SQL,\n SQLWrapper,\n} from 'drizzle-orm';\n\n/** Entity relationship config (one-to-one/many-to-one, one-to-many); Drizzle-specific. */\nexport type TRelationConfig = {\n name: string;\n} & (\n | {\n type: typeof RelationTypes.ONE;\n schema: TTableSchemaWithId;\n /** `fields` and `references` may be left out: they are read off the table's foreign key. */\n metadata?: Partial<\n NonNullable<\n Parameters<ReturnType<typeof createTableRelationsHelpers>[typeof RelationTypes.ONE]>[1]\n >\n >;\n }\n | {\n type: typeof RelationTypes.MANY;\n schema: TTableSchemaWithId;\n metadata: Parameters<\n ReturnType<typeof createTableRelationsHelpers>[typeof RelationTypes.MANY]\n >[1];\n }\n);\n\n/** The column map of a table, as returned by Drizzle's `getTableColumns`. */\nexport type TTableColumns = ReturnType<typeof getTableColumns>;\n\n/** The engine-neutral query-dialect surface a repository consumes via `dataSource.getQueryDialect()`, never constructed inside the repository. */\nexport interface IRelationalQueryDialect {\n mergeFilter<T = any>(opts: { defaultFilter?: TFilter<T>; userFilter?: TFilter<T> }): TFilter<T>;\n build<Schema extends TTableSchemaWithId>(opts: {\n tableName: string;\n schema: Schema;\n filter: TFilter<TTableObject<Schema>>;\n }): TDrizzleQueryOptions;\n toWhere<Schema extends TTableSchemaWithId>(opts: {\n tableName: string;\n schema: Schema;\n where: TWhere<TTableObject<Schema>>;\n }): SQL | undefined;\n /** `expressions` names sort targets the schema cannot: a joined column or a computed `SQL`, keyed by the name an order entry uses. */\n toOrderBy<Schema extends TTableSchemaWithId>(opts: {\n tableName: string;\n schema: Schema;\n order: string[];\n expressions?: Readonly<Record<string, AnyColumn | SQLWrapper>>;\n }): SQL[];\n\n /** Splits update data into plain column assignments and engine-specific JSON-path expressions. Postgres composes `jsonb_set`; another engine composes its own. */\n transformUpdate<Schema extends TTableSchemaWithId>(opts: {\n tableName: string;\n schema: Schema;\n data: Record<string, unknown>;\n }): ITransformedUpdateData;\n\n /** Flattens a transform result into the object handed to the driver's `set()`. */\n toUpdateData(opts: { transformed: ITransformedUpdateData }): Record<string, unknown>;\n\n /** The foreign key link of a `through` model and the scope its parent resolves for `operation`: what a write must check its rows against. */\n resolveThrough(opts: {\n settings: IModelAccessThroughSettings;\n schema: TTableSchemaWithId;\n operation: TScopeOperation;\n }): {\n link: ReturnType<typeof ScopeThroughLink.of>;\n scope: TNullable<TWhere> | typeof ScopeFilters.UNRESTRICTED;\n };\n\n /** The parent's scope as a `where` on the parent table. */\n toParentWhere(opts: {\n link: ReturnType<typeof ScopeThroughLink.of>;\n scope: TWhere;\n }): ReturnType<IRelationalQueryDialect['toWhere']>;\n\n /**\n * The scope of a model for one call: what its `resolve` answers, or, for a `through` model, a `where` on its\n * foreign key built from its parent's own scope (`UNRESTRICTED` or null when the parent's is).\n */\n resolveAccessScope(opts: {\n settings: TModelAccessSettings;\n schema: TTableSchemaWithId;\n operation: TScopeOperation;\n }): TNullable<TWhere> | typeof ScopeFilters.UNRESTRICTED;\n}\n\n/** The SQL branch's `IExtraOptions`: narrows `transaction` to a connector-bearing SQL handle so `options.transaction.connector` needs no cast. An engine binds `TConnector` to keep that access typed; unbound it is `unknown`, which is all neutral code can know. */\nexport interface IRelationalExtraOptions<TConnector = unknown> extends IExtraOptions {\n transaction?: IRelationalTransaction<TConnector>;\n}\n\n/** The connector type a given datasource hands out, so a repository's `resolveConnector` stays as specific as the datasource it was bound to. */\nexport type TRelationalConnectorOf<TDataSource extends IRelationalDataSource> = ReturnType<\n TDataSource['getConnector']\n>;\n\n/** The transaction-options shape a given datasource's own `beginTransaction` accepts - Postgres adds `isolationLevel`. */\nexport type TRelationalTransactionOptionsOf<TDataSource extends IRelationalDataSource> = Parameters<\n TDataSource['beginTransaction']\n>[0];\n\n/** The transaction handle a given datasource's own `beginTransaction` resolves to. */\nexport type TRelationalTransactionOf<TDataSource extends IRelationalDataSource> = Awaited<\n ReturnType<TDataSource['beginTransaction']>\n>;\n\n/** Update data split into plain column values and JSON-path updates that need SQL expressions. */\nexport interface ITransformedUpdateData {\n /** Regular field updates (non-JSON-path keys) */\n regularFields: Record<string, any>;\n\n /** SQL expressions for JSON path updates, keyed by the schema PROPERTY name - not the column name, which is what the emitted SQL quotes. The two diverge whenever a column is declared as `jsonb('meta_data')` under a property called `metadata`. */\n jsonExpressions: Record<string, SQL>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n IExtraOptions,\n IModelAccessThroughSettings,\n RelationTypes,\n ScopeFilters,\n TDrizzleQueryOptions,\n TFilter,\n TModelAccessSettings,\n TScopeOperation,\n TWhere,\n} from '@venizia/ignis-kernel';\nimport type { TNullable } from '@venizia/ignis-helpers/common';\nimport type { ScopeThroughLink } from './scope-through';\nimport type {\n IRelationalDataSource,\n IRelationalTransaction,\n} from '@/relational/core/datasources/common';\nimport type { TTableObject, TTableSchemaWithId } from '@/relational/core/models/common';\nimport type {\n AnyColumn,\n createTableRelationsHelpers,\n getTableColumns,\n SQL,\n SQLWrapper,\n} from 'drizzle-orm';\n\n/** Entity relationship config (one-to-one/many-to-one, one-to-many); Drizzle-specific. */\nexport type TRelationConfig = {\n name: string;\n} & (\n | {\n type: typeof RelationTypes.ONE;\n schema: TTableSchemaWithId;\n /** `fields` and `references` may be left out: they are read off the table's foreign key. */\n metadata?: Partial<\n NonNullable<\n Parameters<ReturnType<typeof createTableRelationsHelpers>[typeof RelationTypes.ONE]>[1]\n >\n >;\n }\n | {\n type: typeof RelationTypes.MANY;\n schema: TTableSchemaWithId;\n metadata: Parameters<\n ReturnType<typeof createTableRelationsHelpers>[typeof RelationTypes.MANY]\n >[1];\n }\n);\n\n/** The column map of a table, as returned by Drizzle's `getTableColumns`. */\nexport type TTableColumns = ReturnType<typeof getTableColumns>;\n\n/** The engine-neutral query-dialect surface a repository consumes via `dataSource.getQueryDialect()`, never constructed inside the repository. */\nexport interface IRelationalQueryDialect {\n /** The relations a schema declares, by name. */\n resolveRelations(opts: { schema: TTableSchemaWithId }): Record<string, TRelationConfig>;\n /** The error the query gives for a `where` key or an `order` field that names no column. */\n columnNotFoundError(opts: { kind: 'where' | 'order'; key: string; tableName: string }): Error;\n /** The fields the model of a schema hides. */\n resolveHiddenProperties(opts: { schema: TTableSchemaWithId }): Set<string>;\n mergeFilter<T = any>(opts: { defaultFilter?: TFilter<T>; userFilter?: TFilter<T> }): TFilter<T>;\n composeScope<T = any>(opts: { scopeWhere: TWhere<T>; userFilter?: TFilter<T> }): TFilter<T>;\n build<Schema extends TTableSchemaWithId>(opts: {\n tableName: string;\n schema: Schema;\n filter: TFilter<TTableObject<Schema>>;\n }): TDrizzleQueryOptions;\n toWhere<Schema extends TTableSchemaWithId>(opts: {\n tableName: string;\n schema: Schema;\n where: TWhere<TTableObject<Schema>>;\n }): SQL | undefined;\n /** `expressions` names sort targets the schema cannot: a joined column or a computed `SQL`, keyed by the name an order entry uses. */\n toOrderBy<Schema extends TTableSchemaWithId>(opts: {\n tableName: string;\n schema: Schema;\n order: string[];\n expressions?: Readonly<Record<string, AnyColumn | SQLWrapper>>;\n }): SQL[];\n\n /** Splits update data into plain column assignments and engine-specific JSON-path expressions. Postgres composes `jsonb_set`; another engine composes its own. */\n transformUpdate<Schema extends TTableSchemaWithId>(opts: {\n tableName: string;\n schema: Schema;\n data: Record<string, unknown>;\n }): ITransformedUpdateData;\n\n /** Flattens a transform result into the object handed to the driver's `set()`. */\n toUpdateData(opts: { transformed: ITransformedUpdateData }): Record<string, unknown>;\n\n /** The foreign key link of a `through` model and the scope its parent resolves for `operation`: what a write must check its rows against. */\n resolveThrough(opts: {\n settings: IModelAccessThroughSettings;\n schema: TTableSchemaWithId;\n operation: TScopeOperation;\n }): {\n link: ReturnType<typeof ScopeThroughLink.of>;\n scope: TNullable<TWhere> | typeof ScopeFilters.UNRESTRICTED;\n };\n\n /** The parent's scope as a `where` on the parent table. */\n toParentWhere(opts: {\n link: ReturnType<typeof ScopeThroughLink.of>;\n scope: TWhere;\n }): ReturnType<IRelationalQueryDialect['toWhere']>;\n\n /**\n * The scope of a model for one call: what its `resolve` answers, or, for a `through` model, a `where` on its\n * foreign key built from its parent's own scope (`UNRESTRICTED` or null when the parent's is).\n */\n resolveAccessScope(opts: {\n settings: TModelAccessSettings;\n schema: TTableSchemaWithId;\n operation: TScopeOperation;\n }): TNullable<TWhere> | typeof ScopeFilters.UNRESTRICTED;\n}\n\n/** The SQL branch's `IExtraOptions`: narrows `transaction` to a connector-bearing SQL handle so `options.transaction.connector` needs no cast. An engine binds `TConnector` to keep that access typed; unbound it is `unknown`, which is all neutral code can know. */\nexport interface IRelationalExtraOptions<TConnector = unknown> extends IExtraOptions {\n transaction?: IRelationalTransaction<TConnector>;\n}\n\n/** The connector type a given datasource hands out, so a repository's `resolveConnector` stays as specific as the datasource it was bound to. */\nexport type TRelationalConnectorOf<TDataSource extends IRelationalDataSource> = ReturnType<\n TDataSource['getConnector']\n>;\n\n/** The transaction-options shape a given datasource's own `beginTransaction` accepts - Postgres adds `isolationLevel`. */\nexport type TRelationalTransactionOptionsOf<TDataSource extends IRelationalDataSource> = Parameters<\n TDataSource['beginTransaction']\n>[0];\n\n/** The transaction handle a given datasource's own `beginTransaction` resolves to. */\nexport type TRelationalTransactionOf<TDataSource extends IRelationalDataSource> = Awaited<\n ReturnType<TDataSource['beginTransaction']>\n>;\n\n/** Update data split into plain column values and JSON-path updates that need SQL expressions. */\nexport interface ITransformedUpdateData {\n /** Regular field updates (non-JSON-path keys) */\n regularFields: Record<string, any>;\n\n /** SQL expressions for JSON path updates, keyed by the schema PROPERTY name - not the column name, which is what the emitted SQL quotes. The two diverge whenever a column is declared as `jsonb('meta_data')` under a property called `metadata`. */\n jsonExpressions: Record<string, SQL>;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { IdType, IExtraOptions, IPersistableRepository, IModelAccessThroughSettings, TModelAccessSettings, ITransaction, TCount, TByIdFilter, TDataRange, TDrizzleQueryOptions, TFields, TFilter, TFindOneOptions, TFindOptions, TFindRangeOptions, TLockOptions, TRepositoryOperationScope, TRow, TScopeOperation, TWhere } from '@venizia/ignis-kernel';
1
+ import type { IdType, IExtraOptions, IPersistableRepository, IRequestFilterJudge, IModelAccessThroughSettings, TModelAccessSettings, ITransaction, TCount, TByIdFilter, TDataRange, TDrizzleQueryOptions, TFields, TFilter, TFindOneOptions, TFindOptions, TFindRangeOptions, TLockOptions, TRepositoryOperationScope, TRow, TScopeOperation, TWhere } from '@venizia/ignis-kernel';
2
2
  import { AbstractRepository } from '@venizia/ignis-kernel';
3
3
  import type { IRelationalDataSource } from '../../datasources/common/index.js';
4
4
  import type { BaseRelationalEntity, TTableInsert, TTableObject, TTableSchemaWithId } from '../../models/index.js';
@@ -37,6 +37,13 @@ export declare abstract class RelationalBaseRepository<EntitySchema extends TTab
37
37
  dataSource: TDataSource;
38
38
  }): void;
39
39
  getEntitySchema(): EntitySchema;
40
+ /**
41
+ * Judges a request filter's keys as this repository's query reads them: a JSON path names the column it starts with
42
+ * (`[meta].pin`, `.meta.pin` and `meta.pin` all read `meta`), and a refusal is the error the query gives for a column that does
43
+ * not exist. An include scope is judged by the hidden fields of the model its relation points to.
44
+ */
45
+ protected createRequestFilterJudge(): IRequestFilterJudge;
46
+ private judgeSchema;
40
47
  /** Hidden fields as a memoized Set, derived from the base's class-keyed `hiddenFields` array. */
41
48
  getHiddenProperties(): Set<string>;
42
49
  hasHiddenProperties(): boolean;