@venizia/ignis-connectors 0.5.0-2 → 0.5.0-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,4 @@
1
1
  import type { TConstValue } from '@venizia/ignis-helpers/common';
2
- /** Headers the HTTP datasource owns on the wire, beside the shared ones in `HTTP.Headers`. */
3
- export declare class HttpWireHeaders {
4
- /** The credential's `provider`, when it names one. */
5
- static readonly AUTH_PROVIDER = "x-auth-provider";
6
- }
7
2
  /** What a read expects back: LIST (a bare array or the `{ count, data }` envelope) or ONE (a single record, never unwrapped). */
8
3
  export declare class HttpReadShapes {
9
4
  static readonly LIST = "list";
@@ -1,8 +1,3 @@
1
- /** Headers the HTTP datasource owns on the wire, beside the shared ones in `HTTP.Headers`. */
2
- export class HttpWireHeaders {
3
- /** The credential's `provider`, when it names one. */
4
- static { this.AUTH_PROVIDER = 'x-auth-provider'; }
5
- }
6
1
  /** What a read expects back: LIST (a bare array or the `{ count, data }` envelope) or ONE (a single record, never unwrapped). */
7
2
  export class HttpReadShapes {
8
3
  static { this.LIST = 'list'; }
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../src/http/common/constants.ts"],"names":[],"mappings":"AAEA,8FAA8F;AAC9F,MAAM,OAAO,eAAe;IAC1B,sDAAsD;aACtC,kBAAa,GAAG,iBAAiB,CAAC;;AAGpD,iIAAiI;AACjI,MAAM,OAAO,cAAc;aACT,SAAI,GAAG,MAAM,CAAC;aACd,QAAG,GAAG,KAAK,CAAC;aAEZ,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAEpE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** Headers the HTTP datasource owns on the wire, beside the shared ones in `HTTP.Headers`. */\nexport class HttpWireHeaders {\n /** The credential's `provider`, when it names one. */\n static readonly AUTH_PROVIDER = 'x-auth-provider';\n}\n\n/** What a read expects back: LIST (a bare array or the `{ count, data }` envelope) or ONE (a single record, never unwrapped). */\nexport class HttpReadShapes {\n static readonly LIST = 'list';\n static readonly ONE = 'one';\n\n static readonly SCHEME_SET = new Set<string>([this.LIST, this.ONE]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid HTTP read shape values. */\nexport type THttpReadShape = TConstValue<typeof HttpReadShapes>;\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../src/http/common/constants.ts"],"names":[],"mappings":"AAEA,iIAAiI;AACjI,MAAM,OAAO,cAAc;aACT,SAAI,GAAG,MAAM,CAAC;aACd,QAAG,GAAG,KAAK,CAAC;aAEZ,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAEpE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** What a read expects back: LIST (a bare array or the `{ count, data }` envelope) or ONE (a single record, never unwrapped). */\nexport class HttpReadShapes {\n static readonly LIST = 'list';\n static readonly ONE = 'one';\n\n static readonly SCHEME_SET = new Set<string>([this.LIST, this.ONE]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid HTTP read shape values. */\nexport type THttpReadShape = TConstValue<typeof HttpReadShapes>;\n"]}
@@ -1,4 +1,4 @@
1
- import type { TNativeFetchSender } from '@venizia/ignis-helpers/core';
1
+ import type { THttpHeaders, TNativeFetchSender } from '@venizia/ignis-helpers/core';
2
2
  /** A credential the HTTP datasource attaches to a request: `Authorization: <type> <value>`, and `provider`, when set, as the `x-auth-provider` header. */
3
3
  export interface IAuthToken {
4
4
  value: string;
@@ -22,8 +22,6 @@ export interface IHttpRequestContext {
22
22
  /** The call's own signal: a hook may stop waiting on it. A refresh shared by other calls should not be aborted by one. */
23
23
  signal?: AbortSignal;
24
24
  }
25
- /** Not `Record` alone: header names are case-insensitive, and an object merge appends two spellings. */
26
- export type THttpHeaders = Headers | Array<[string, string]> | Record<string, string>;
27
25
  /**
28
26
  * A request body. A plain object or array goes out as JSON; a string, `Blob`, `FormData`,
29
27
  * `URLSearchParams`, `ArrayBuffer` or typed array goes out as it is. Never a stream: the 401 retry
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/http/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TNativeFetchSender } from '@venizia/ignis-helpers/core';\n\n/** A credential the HTTP datasource attaches to a request: `Authorization: <type> <value>`, and `provider`, when set, as the `x-auth-provider` header. */\nexport interface IAuthToken {\n value: string;\n /**\n * The authorization scheme.\n *\n * @default 'Bearer'\n */\n type?: string;\n provider?: string;\n}\n\n/** What `onUnauthorized` is told besides the request: `attempt` is 1 for the first 401, 2 for the retry's own. */\nexport interface IHttpUnauthorizedInfo {\n attempt: number;\n}\n\n/** The request a hook is asked about, the SAME object for every hook and every send of one call (a session map may key on it): the repository `paths`, the method, and the final URL with its query. */\nexport interface IHttpRequestContext {\n paths: Array<string>;\n method: string;\n url: string;\n /** The call's own signal: a hook may stop waiting on it. A refresh shared by other calls should not be aborted by one. */\n signal?: AbortSignal;\n}\n\n/** Not `Record` alone: header names are case-insensitive, and an object merge appends two spellings. */\nexport type THttpHeaders = Headers | Array<[string, string]> | Record<string, string>;\n\n/**\n * A request body. A plain object or array goes out as JSON; a string, `Blob`, `FormData`,\n * `URLSearchParams`, `ArrayBuffer` or typed array goes out as it is. Never a stream: the 401 retry\n * sends the same body twice.\n */\nexport type THttpBody = string | object;\n\n/** The list-extras request and result types live with the server contract, in kernel. */\nexport type { TExtraRequest, TExtraResult } from '@venizia/ignis-kernel/repository';\n\n/** What one call may add: its own headers (they win over the configured ones) and a signal to abort it. */\nexport interface IHttpCallOptions {\n headers?: THttpHeaders;\n signal?: AbortSignal;\n}\n\n/** Settings of the HTTP datasource: where to send, which headers and token to attach, and what to do on a 401. */\nexport interface IHttpDataSourceSettings {\n /** An absolute URL, or a path from the page origin (`/api`). A path-relative one is refused. */\n baseUrl: string;\n\n /** The server's `error.rootKey`: an error envelope wrapped under it is unwrapped before it is read. */\n errorRootKey?: string;\n\n /** Sent on every request. `x-request-count` is refused - the connector owns it. */\n headers?: THttpHeaders;\n\n /**\n * Headers for this request, run on every send (the 401 retry included); wins over `headers`, a call's own win over it. A throw\n * fails the request; `x-request-count` is refused, and an `authorization` stands only when no token resolves.\n */\n headersResolver?: (context: IHttpRequestContext) => THttpHeaders | undefined;\n\n /** Wins over `authTokenResolver`, and is sent whatever the request. */\n authToken?: IAuthToken;\n\n /** Run on every send, the 401 retry included. `undefined` means no token for this request. A throw fails the request with that error. */\n authTokenResolver?: (context: IHttpRequestContext) => IAuthToken | undefined;\n\n /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. `context` is the object the resolvers got for this call; `info.attempt` says which send failed. */\n onUnauthorized?: (\n context: IHttpRequestContext,\n info: IHttpUnauthorizedInfo,\n ) => Promise<boolean> | boolean;\n\n /** What sends a request: the platform `fetch` when unset. Name one to route through a test double, a proxy or an instrumented client. */\n fetch?: THttpFetch;\n}\n\n/** What sends a request: a URL and its init, a `Response` back. The public name of the sender type. */\nexport type THttpFetch = TNativeFetchSender;\n\n/** A list with no `Content-Range` has no total - `hasRange` says so rather than using the page size. */\nexport interface IHttpReadResult<R> {\n data: R;\n hasRange: boolean;\n /** Raw header: tells a present-but-unreadable one from an absent one. */\n contentRange?: string;\n total?: number;\n skip?: number;\n dataLength: number;\n /** What a list answered beside its rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** What a write answers: the rows the server returned, and its `x-response-count`. */\nexport interface IHttpWriteResult<R> {\n data: R;\n count: number;\n /** What the route answered beside the rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** Query parameters a route takes beside `filter` or `where` - a keyword, a scope. The filter and `where` win over a key of the same name. */\nexport type THttpExtraQuery = Record<string, unknown>;\n\n/** What the IGNIS search route answers: the total as `found` (`isFoundExact` is false when it is an estimate) and the hits. */\nexport interface IHttpSearchResult<R> {\n found: number;\n isFoundExact: boolean;\n hits: Array<{ document: R; score?: number; highlight?: unknown; highlights?: Array<unknown> }>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/http/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { THttpHeaders, TNativeFetchSender } from '@venizia/ignis-helpers/core';\n\n/** A credential the HTTP datasource attaches to a request: `Authorization: <type> <value>`, and `provider`, when set, as the `x-auth-provider` header. */\nexport interface IAuthToken {\n value: string;\n /**\n * The authorization scheme.\n *\n * @default 'Bearer'\n */\n type?: string;\n provider?: string;\n}\n\n/** What `onUnauthorized` is told besides the request: `attempt` is 1 for the first 401, 2 for the retry's own. */\nexport interface IHttpUnauthorizedInfo {\n attempt: number;\n}\n\n/** The request a hook is asked about, the SAME object for every hook and every send of one call (a session map may key on it): the repository `paths`, the method, and the final URL with its query. */\nexport interface IHttpRequestContext {\n paths: Array<string>;\n method: string;\n url: string;\n /** The call's own signal: a hook may stop waiting on it. A refresh shared by other calls should not be aborted by one. */\n signal?: AbortSignal;\n}\n\n/**\n * A request body. A plain object or array goes out as JSON; a string, `Blob`, `FormData`,\n * `URLSearchParams`, `ArrayBuffer` or typed array goes out as it is. Never a stream: the 401 retry\n * sends the same body twice.\n */\nexport type THttpBody = string | object;\n\n/** The list-extras request and result types live with the server contract, in kernel. */\nexport type { TExtraRequest, TExtraResult } from '@venizia/ignis-kernel/repository';\n\n/** What one call may add: its own headers (they win over the configured ones) and a signal to abort it. */\nexport interface IHttpCallOptions {\n headers?: THttpHeaders;\n signal?: AbortSignal;\n}\n\n/** Settings of the HTTP datasource: where to send, which headers and token to attach, and what to do on a 401. */\nexport interface IHttpDataSourceSettings {\n /** An absolute URL, or a path from the page origin (`/api`). A path-relative one is refused. */\n baseUrl: string;\n\n /** The server's `error.rootKey`: an error envelope wrapped under it is unwrapped before it is read. */\n errorRootKey?: string;\n\n /** Sent on every request. `x-request-count` is refused - the connector owns it. */\n headers?: THttpHeaders;\n\n /**\n * Headers for this request, run on every send (the 401 retry included); wins over `headers`, a call's own win over it. A throw\n * fails the request; `x-request-count` is refused, and an `authorization` stands only when no token resolves.\n */\n headersResolver?: (context: IHttpRequestContext) => THttpHeaders | undefined;\n\n /** Wins over `authTokenResolver`, and is sent whatever the request. */\n authToken?: IAuthToken;\n\n /** Run on every send, the 401 retry included. `undefined` means no token for this request. A throw fails the request with that error. */\n authTokenResolver?: (context: IHttpRequestContext) => IAuthToken | undefined;\n\n /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. `context` is the object the resolvers got for this call; `info.attempt` says which send failed. */\n onUnauthorized?: (\n context: IHttpRequestContext,\n info: IHttpUnauthorizedInfo,\n ) => Promise<boolean> | boolean;\n\n /** What sends a request: the platform `fetch` when unset. Name one to route through a test double, a proxy or an instrumented client. */\n fetch?: THttpFetch;\n}\n\n/** What sends a request: a URL and its init, a `Response` back. The public name of the sender type. */\nexport type THttpFetch = TNativeFetchSender;\n\n/** A list with no `Content-Range` has no total - `hasRange` says so rather than using the page size. */\nexport interface IHttpReadResult<R> {\n data: R;\n hasRange: boolean;\n /** Raw header: tells a present-but-unreadable one from an absent one. */\n contentRange?: string;\n total?: number;\n skip?: number;\n dataLength: number;\n /** What a list answered beside its rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** What a write answers: the rows the server returned, and its `x-response-count`. */\nexport interface IHttpWriteResult<R> {\n data: R;\n count: number;\n /** What the route answered beside the rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** Query parameters a route takes beside `filter` or `where` - a keyword, a scope. The filter and `where` win over a key of the same name. */\nexport type THttpExtraQuery = Record<string, unknown>;\n\n/** What the IGNIS search route answers: the total as `found` (`isFoundExact` is false when it is an estimate) and the hits. */\nexport interface IHttpSearchResult<R> {\n found: number;\n isFoundExact: boolean;\n hits: Array<{ document: R; score?: number; highlight?: unknown; highlights?: Array<unknown> }>;\n}\n"]}
@@ -1,24 +1,14 @@
1
1
  import { type THttpReadShape } from './constants.js';
2
- import type { TExtraRequest, THttpBody, THttpHeaders } from './types.js';
2
+ import type { THttpHeaders } from '@venizia/ignis-helpers/core';
3
+ import type { TExtraRequest, THttpBody } from './types.js';
3
4
  /**
4
5
  * What `HttpDataSource` puts on the wire and reads back off it: headers, request bodies, rows and
5
6
  * the path an error message names. Internal - not part of the `http` entry.
6
7
  */
7
8
  export declare class HttpWire {
8
- /**
9
- * Caller headers as unique lowercase pairs, last spelling winning.
10
- *
11
- * Never `new Headers(input)`: that constructor APPENDS, so `{ 'X-Tenant': 'north', 'x-tenant':
12
- * 'south' }` - which a merge of two config objects produces - reaches the wire as `"north, south"`,
13
- * a value neither caller wrote. A `Headers` instance arrives already joined; that one is the
14
- * caller's own, and is passed through as it stands.
15
- */
16
- static toHeaderEntries(opts: {
17
- headers?: THttpHeaders;
18
- }): Array<[string, string]>;
19
9
  /** The connector always sends `x-request-count: false`; a caller header carrying it would contradict that. */
20
10
  static assertNoRequestCountHeader(opts: {
21
- entries: Array<[string, string]>;
11
+ headers: Headers;
22
12
  name: string;
23
13
  }): void;
24
14
  /**
@@ -1,40 +1,16 @@
1
1
  import { HttpReadShapes } from './constants.js';
2
2
  import { HTTP } from '@venizia/ignis-helpers/common';
3
- import { getError } from '@venizia/ignis-helpers/core';
3
+ import { getError, HttpHeaders, NativeFetcher } from '@venizia/ignis-helpers/core';
4
4
  import { HttpExtraRequest } from '@venizia/ignis-kernel/repository';
5
5
  /**
6
6
  * What `HttpDataSource` puts on the wire and reads back off it: headers, request bodies, rows and
7
7
  * the path an error message names. Internal - not part of the `http` entry.
8
8
  */
9
9
  export class HttpWire {
10
- /**
11
- * Caller headers as unique lowercase pairs, last spelling winning.
12
- *
13
- * Never `new Headers(input)`: that constructor APPENDS, so `{ 'X-Tenant': 'north', 'x-tenant':
14
- * 'south' }` - which a merge of two config objects produces - reaches the wire as `"north, south"`,
15
- * a value neither caller wrote. A `Headers` instance arrives already joined; that one is the
16
- * caller's own, and is passed through as it stands.
17
- */
18
- static toHeaderEntries(opts) {
19
- const { headers } = opts;
20
- if (!headers) {
21
- return [];
22
- }
23
- const source = headers instanceof Headers
24
- ? [...headers.entries()]
25
- : Array.isArray(headers)
26
- ? headers
27
- : Object.entries(headers);
28
- const merged = new Map();
29
- for (const [name, value] of source) {
30
- merged.set(name.toLowerCase(), value);
31
- }
32
- return [...merged.entries()];
33
- }
34
10
  /** The connector always sends `x-request-count: false`; a caller header carrying it would contradict that. */
35
11
  static assertNoRequestCountHeader(opts) {
36
- const { entries, name } = opts;
37
- if (entries.some(([headerName]) => headerName === HTTP.Headers.REQUEST_COUNT_DATA)) {
12
+ const { headers, name } = opts;
13
+ if (headers.has(HTTP.Headers.REQUEST_COUNT_DATA)) {
38
14
  throw getError({
39
15
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
40
16
  message: `[${name}] ${HTTP.Headers.REQUEST_COUNT_DATA} is owned by HttpDataSource and always sent as false: rows come back bare, the total in Content-Range.`,
@@ -50,15 +26,6 @@ export class HttpWire {
50
26
  if (body === undefined) {
51
27
  return { payload: undefined, isJson: false, isFormData: false };
52
28
  }
53
- const isFormData = body instanceof FormData;
54
- const isSentAsIs = isFormData ||
55
- typeof body === 'string' ||
56
- body instanceof Blob ||
57
- body instanceof URLSearchParams ||
58
- body instanceof ArrayBuffer;
59
- if (isSentAsIs) {
60
- return { payload: body, isJson: false, isFormData };
61
- }
62
29
  // A typed array may sit on a SharedArrayBuffer, which `fetch` refuses; a Blob copy never does.
63
30
  if (ArrayBuffer.isView(body)) {
64
31
  return {
@@ -67,6 +34,9 @@ export class HttpWire {
67
34
  isFormData: false,
68
35
  };
69
36
  }
37
+ if (NativeFetcher.isRawBody(body)) {
38
+ return { payload: body, isJson: false, isFormData: body instanceof FormData };
39
+ }
70
40
  return {
71
41
  payload: HttpWire.toJson({ value: body, label: 'The request body' }),
72
42
  isJson: true,
@@ -116,8 +86,7 @@ export class HttpWire {
116
86
  if (value === undefined) {
117
87
  return headers;
118
88
  }
119
- const extraHeader = [HttpExtraRequest.HEADER, value];
120
- return [...HttpWire.toHeaderEntries({ headers }), extraHeader];
89
+ return HttpHeaders.merge({ layers: [headers, { [HttpExtraRequest.HEADER]: value }] });
121
90
  }
122
91
  /**
123
92
  * The path a message names - never the host or the query. A server that relays this error would
@@ -1 +1 @@
1
- {"version":3,"file":"wire.js","sourceRoot":"","sources":["../../../../src/http/common/wire.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAuB,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAGpE;;;GAGG;AACH,MAAM,OAAO,QAAQ;IACnB;;;;;;;OAOG;IACH,MAAM,CAAC,eAAe,CAAC,IAAgC;QACrD,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEzB,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,MAAM,GACV,OAAO,YAAY,OAAO;YACxB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;YACxB,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;gBACtB,CAAC,CAAC,OAAO;gBACT,C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AAC,WAAW,CAAC,IAAI,CAAC,UAAU;YAC3C,MAAM,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,2BAA2B,CAAC;QAE/D,OAAO,SAAS;YACd,CAAC,CAAC,GAAG,QAAQ,KAAK,GAAG,CAAC,MAAM,gGAAgG;YAC5H,CAAC,CAAC,QAAQ,CAAC;IACf,CAAC;CACF","sourcesContent":["import { HttpReadShapes, type THttpReadShape } from './constants';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HttpExtraRequest } from '@venizia/ignis-kernel/repository';\nimport type { TExtraRequest, THttpBody, THttpHeaders } from './types';\n\n/**\n * What `HttpDataSource` puts on the wire and reads back off it: headers, request bodies, rows and\n * the path an error message names. Internal - not part of the `http` entry.\n */\nexport class HttpWire {\n /**\n * Caller headers as unique lowercase pairs, last spelling winning.\n *\n * Never `new Headers(input)`: that constructor APPENDS, so `{ 'X-Tenant': 'north', 'x-tenant':\n * 'south' }` - which a merge of two config objects produces - reaches the wire as `\"north, south\"`,\n * a value neither caller wrote. A `Headers` instance arrives already joined; that one is the\n * caller's own, and is passed through as it stands.\n */\n static toHeaderEntries(opts: { headers?: THttpHeaders }): Array<[string, string]> {\n const { headers } = opts;\n\n if (!headers) {\n return [];\n }\n\n const source =\n headers instanceof Headers\n ? [...headers.entries()]\n : Array.isArray(headers)\n ? headers\n : Object.entries(headers);\n\n const merged = new Map<string, string>();\n\n for (const [name, value] of source) {\n merged.set(name.toLowerCase(), value);\n }\n\n return [...merged.entries()];\n }\n\n /** The connector always sends `x-request-count: false`; a caller header carrying it would contradict that. */\n static assertNoRequestCountHeader(opts: {\n entries: Array<[string, string]>;\n name: string;\n }): void {\n const { entries, name } = opts;\n\n if (entries.some(([headerName]) => headerName === HTTP.Headers.REQUEST_COUNT_DATA)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] ${HTTP.Headers.REQUEST_COUNT_DATA} is owned by HttpDataSource and always sent as false: rows come back bare, the total in Content-Range.`,\n });\n }\n }\n\n /**\n * The body as `fetch` takes it. Anything `fetch` already sends as a body passes through untouched;\n * any other object is JSON. Serialised ONCE, so the 401 retry sends the same bytes.\n */\n static toRequestBody(opts: { body?: THttpBody }): {\n payload: RequestInit['body'];\n isJson: boolean;\n isFormData: boolean;\n } {\n const { body } = opts;\n\n if (body === undefined) {\n return { payload: undefined, isJson: false, isFormData: false };\n }\n\n const isFormData = body instanceof FormData;\n const isSentAsIs =\n isFormData ||\n typeof body === 'string' ||\n body instanceof Blob ||\n body instanceof URLSearchParams ||\n body instanceof ArrayBuffer;\n\n if (isSentAsIs) {\n return { payload: body, isJson: false, isFormData };\n }\n\n // A typed array may sit on a SharedArrayBuffer, which `fetch` refuses; a Blob copy never does.\n if (ArrayBuffer.isView(body)) {\n return {\n payload: new Blob([new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice()]),\n isJson: false,\n isFormData: false,\n };\n }\n\n return {\n payload: HttpWire.toJson({ value: body, label: 'The request body' }),\n isJson: true,\n isFormData: false,\n };\n }\n\n /** JSON, or a 400 naming what failed: a bigint or a cycle would otherwise escape as a bare TypeError. */\n static toJson(opts: { value: unknown; label: string }): string {\n const { value, label } = opts;\n\n try {\n return JSON.stringify(value);\n } catch (error) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `${label} cannot be sent as JSON | ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n }\n\n /**\n * A list is a bare array or the `{ count, data }` envelope; `one` is never unwrapped, since a record\n * may carry `data` and `count` columns. The envelope `count` is the page size, never the total.\n *\n * Anything else asked for as a list throws: counting it as one row is how `existsWith` answers true\n * for an empty result and a page reports a length it does not have.\n */\n static unwrapRows<R>(opts: { body: unknown; shape: THttpReadShape; url: string }): R {\n const { body, shape, url } = opts;\n\n if (shape === HttpReadShapes.ONE || Array.isArray(body)) {\n return body as R;\n }\n\n if (body && typeof body === 'object' && 'data' in body && 'count' in body) {\n return (body as { data: R }).data;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[read] A list was asked for and the response is neither an array nor a { count, data } envelope | ${HttpWire.describeUrl({ url })}`,\n });\n }\n\n /**\n * The call's headers plus `x-request-extra` for the extras it asks for - `name`, `-name`,\n * `name(key,key)` - and `-*` first when it wants the rows alone, with every default off.\n */\n static withExtraHeader(opts: {\n headers?: THttpHeaders;\n extra?: TExtraRequest;\n isEveryDefaultOff?: boolean;\n }): THttpHeaders | undefined {\n const { headers, extra, isEveryDefaultOff } = opts;\n const value = HttpExtraRequest.toHeader({ extra, isEveryDefaultOff });\n\n if (value === undefined) {\n return headers;\n }\n\n const extraHeader: [string, string] = [HttpExtraRequest.HEADER, value];\n\n return [...HttpWire.toHeaderEntries({ headers }), extraHeader];\n }\n\n /**\n * The path a message names - never the host or the query. A server that relays this error would\n * otherwise send an internal host and a filter's values to its own clients. 414/431 add the length.\n */\n static describeUrl(opts: { url: string; status?: number }): string {\n const { url, status } = opts;\n const { pathname } = new URL(url);\n\n const isTooLong =\n status === HTTP.ResultCodes.RS_4.URITooLong ||\n status === HTTP.ResultCodes.RS_4.RequestHeaderFieldsTooLarge;\n\n return isTooLong\n ? `${pathname} (${url.length} chars) | The URL is too long for a GET - split the filter (a long inq) into smaller requests.`\n : pathname;\n }\n}\n"]}
1
+ {"version":3,"file":"wire.js","sourceRoot":"","sources":["../../../../src/http/common/wire.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAuB,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAEnF,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAGpE;;;GAGG;AACH,MAAM,OAAO,QAAQ;IACnB,8GAA8G;IAC9G,MAAM,CAAC,0BAA0B,C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ItB;QACC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;QACnD,MAAM,KAAK,GAAG,gBAAgB,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC,CAAC;QAEtE,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,OAAO,OAAO,CAAC;QACjB,CAAC;QAED,OAAO,WAAW,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,gBAAgB,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;IACxF,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,WAAW,CAAC,IAAsC;QACvD,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAC7B,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QAElC,MAAM,SAAS,GACb,MAAM,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;YAC3C,MAAM,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,2BAA2B,CAAC;QAE/D,OAAO,SAAS;YACd,CAAC,CAAC,GAAG,QAAQ,KAAK,GAAG,CAAC,MAAM,gGAAgG;YAC5H,CAAC,CAAC,QAAQ,CAAC;IACf,CAAC;CACF","sourcesContent":["import { HttpReadShapes, type THttpReadShape } from './constants';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError, HttpHeaders, NativeFetcher } from '@venizia/ignis-helpers/core';\nimport type { THttpHeaders } from '@venizia/ignis-helpers/core';\nimport { HttpExtraRequest } from '@venizia/ignis-kernel/repository';\nimport type { TExtraRequest, THttpBody } from './types';\n\n/**\n * What `HttpDataSource` puts on the wire and reads back off it: headers, request bodies, rows and\n * the path an error message names. Internal - not part of the `http` entry.\n */\nexport class HttpWire {\n /** The connector always sends `x-request-count: false`; a caller header carrying it would contradict that. */\n static assertNoRequestCountHeader(opts: { headers: Headers; name: string }): void {\n const { headers, name } = opts;\n\n if (headers.has(HTTP.Headers.REQUEST_COUNT_DATA)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] ${HTTP.Headers.REQUEST_COUNT_DATA} is owned by HttpDataSource and always sent as false: rows come back bare, the total in Content-Range.`,\n });\n }\n }\n\n /**\n * The body as `fetch` takes it. Anything `fetch` already sends as a body passes through untouched;\n * any other object is JSON. Serialised ONCE, so the 401 retry sends the same bytes.\n */\n static toRequestBody(opts: { body?: THttpBody }): {\n payload: RequestInit['body'];\n isJson: boolean;\n isFormData: boolean;\n } {\n const { body } = opts;\n\n if (body === undefined) {\n return { payload: undefined, isJson: false, isFormData: false };\n }\n\n // A typed array may sit on a SharedArrayBuffer, which `fetch` refuses; a Blob copy never does.\n if (ArrayBuffer.isView(body)) {\n return {\n payload: new Blob([new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice()]),\n isJson: false,\n isFormData: false,\n };\n }\n\n if (NativeFetcher.isRawBody(body)) {\n return { payload: body, isJson: false, isFormData: body instanceof FormData };\n }\n\n return {\n payload: HttpWire.toJson({ value: body, label: 'The request body' }),\n isJson: true,\n isFormData: false,\n };\n }\n\n /** JSON, or a 400 naming what failed: a bigint or a cycle would otherwise escape as a bare TypeError. */\n static toJson(opts: { value: unknown; label: string }): string {\n const { value, label } = opts;\n\n try {\n return JSON.stringify(value);\n } catch (error) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `${label} cannot be sent as JSON | ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n }\n\n /**\n * A list is a bare array or the `{ count, data }` envelope; `one` is never unwrapped, since a record\n * may carry `data` and `count` columns. The envelope `count` is the page size, never the total.\n *\n * Anything else asked for as a list throws: counting it as one row is how `existsWith` answers true\n * for an empty result and a page reports a length it does not have.\n */\n static unwrapRows<R>(opts: { body: unknown; shape: THttpReadShape; url: string }): R {\n const { body, shape, url } = opts;\n\n if (shape === HttpReadShapes.ONE || Array.isArray(body)) {\n return body as R;\n }\n\n if (body && typeof body === 'object' && 'data' in body && 'count' in body) {\n return (body as { data: R }).data;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[read] A list was asked for and the response is neither an array nor a { count, data } envelope | ${HttpWire.describeUrl({ url })}`,\n });\n }\n\n /**\n * The call's headers plus `x-request-extra` for the extras it asks for - `name`, `-name`,\n * `name(key,key)` - and `-*` first when it wants the rows alone, with every default off.\n */\n static withExtraHeader(opts: {\n headers?: THttpHeaders;\n extra?: TExtraRequest;\n isEveryDefaultOff?: boolean;\n }): THttpHeaders | undefined {\n const { headers, extra, isEveryDefaultOff } = opts;\n const value = HttpExtraRequest.toHeader({ extra, isEveryDefaultOff });\n\n if (value === undefined) {\n return headers;\n }\n\n return HttpHeaders.merge({ layers: [headers, { [HttpExtraRequest.HEADER]: value }] });\n }\n\n /**\n * The path a message names - never the host or the query. A server that relays this error would\n * otherwise send an internal host and a filter's values to its own clients. 414/431 add the length.\n */\n static describeUrl(opts: { url: string; status?: number }): string {\n const { url, status } = opts;\n const { pathname } = new URL(url);\n\n const isTooLong =\n status === HTTP.ResultCodes.RS_4.URITooLong ||\n status === HTTP.ResultCodes.RS_4.RequestHeaderFieldsTooLarge;\n\n return isTooLong\n ? `${pathname} (${url.length} chars) | The URL is too long for a GET - split the filter (a long inq) into smaller requests.`\n : pathname;\n }\n}\n"]}
@@ -7,7 +7,7 @@ export declare class HttpDataSource extends DataSourceRoot<IHttpDataSourceSettin
7
7
  settings: IHttpDataSourceSettings;
8
8
  schema: never;
9
9
  /** Normalised once: every request copies these, never re-parses `settings.headers`. */
10
- protected configuredHeaders: Array<[string, string]>;
10
+ protected configuredHeaders: Headers;
11
11
  constructor(opts: IHttpDataSourceSettings & {
12
12
  name?: string;
13
13
  });
@@ -21,10 +21,10 @@ export declare class HttpDataSource extends DataSourceRoot<IHttpDataSourceSettin
21
21
  /** Re-run on every send, so a header the app changed since the last request is the one sent. */
22
22
  protected resolveHeaders(opts: {
23
23
  context: IHttpRequestContext;
24
- }): Array<[string, string]>;
24
+ }): Headers;
25
25
  protected buildHeaders(opts: {
26
26
  token?: IAuthToken;
27
- requestHeaders?: Array<[string, string]>;
27
+ requestHeaders?: Headers;
28
28
  isJsonBody?: boolean;
29
29
  isFormDataBody?: boolean;
30
30
  }): Headers;
@@ -1,8 +1,7 @@
1
- import { HttpReadShapes, HttpWireHeaders } from './common/constants.js';
1
+ import { HttpReadShapes } from './common/constants.js';
2
2
  import { DataSourceRoot } from '@venizia/ignis-kernel/repository';
3
3
  import { HTTP } from '@venizia/ignis-helpers/common';
4
- import { NativeFetcher, UrlBuilder, UrlFetchError } from '@venizia/ignis-helpers/core';
5
- import { HttpResponseReader } from './common/readers.js';
4
+ import { HttpHeaders, HttpResponseReader, NativeFetcher, RecordUtility, UrlBuilder, UrlFetchError, } from '@venizia/ignis-helpers/core';
6
5
  import { HttpWire } from './common/wire.js';
7
6
  /** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */
8
7
  export class HttpDataSource extends DataSourceRoot {
@@ -10,8 +9,8 @@ export class HttpDataSource extends DataSourceRoot {
10
9
  super({ scope: opts.name ?? HttpDataSource.name });
11
10
  this.schema = {};
12
11
  const { name = 'http', ...settings } = opts;
13
- const configured = HttpWire.toHeaderEntries({ headers: settings.headers });
14
- HttpWire.assertNoRequestCountHeader({ entries: configured, name });
12
+ const configured = HttpHeaders.merge({ layers: [settings.headers] });
13
+ HttpWire.assertNoRequestCountHeader({ headers: configured, name });
15
14
  UrlBuilder.assertBase({ baseUrl: settings.baseUrl, scope: name });
16
15
  this.configuredHeaders = configured;
17
16
  this.name = name;
@@ -26,21 +25,14 @@ export class HttpDataSource extends DataSourceRoot {
26
25
  }
27
26
  /** Re-run on every send, so a header the app changed since the last request is the one sent. */
28
27
  resolveHeaders(opts) {
29
- const resolver = this.settings.headersResolver;
30
- if (!resolver) {
31
- return [];
32
- }
33
- const entries = HttpWire.toHeaderEntries({ headers: resolver(opts.context) });
34
- HttpWire.assertNoRequestCountHeader({ entries, name: this.name });
35
- return entries;
28
+ const headers = HttpHeaders.merge({ layers: [this.settings.headersResolver?.(opts.context)] });
29
+ HttpWire.assertNoRequestCountHeader({ headers, name: this.name });
30
+ return headers;
36
31
  }
37
32
  buildHeaders(opts) {
38
33
  const { token, requestHeaders, isJsonBody, isFormDataBody } = opts;
39
- const headers = new Headers(this.configuredHeaders);
40
34
  // A request's own headers win over the configured ones; the connector's below win over both.
41
- for (const [name, value] of requestHeaders ?? []) {
42
- headers.set(name, value);
43
- }
35
+ const headers = HttpHeaders.merge({ layers: [this.configuredHeaders, requestHeaders] });
44
36
  if (isJsonBody && !headers.has(HTTP.Headers.CONTENT_TYPE)) {
45
37
  headers.set(HTTP.Headers.CONTENT_TYPE, HTTP.HeaderValues.APPLICATION_JSON);
46
38
  }
@@ -56,7 +48,7 @@ export class HttpDataSource extends DataSourceRoot {
56
48
  headers.set(HTTP.Headers.AUTHORIZATION, `${token.type ?? 'Bearer'} ${token.value}`);
57
49
  // Unconditionally it would send the string "undefined".
58
50
  if (token.provider) {
59
- headers.set(HttpWireHeaders.AUTH_PROVIDER, token.provider);
51
+ headers.set(HTTP.Headers.AUTH_PROVIDER, token.provider);
60
52
  }
61
53
  return headers;
62
54
  }
@@ -84,8 +76,8 @@ export class HttpDataSource extends DataSourceRoot {
84
76
  /** `request` on a URL already built: `read` and `write` serialise a long query once, not per use. */
85
77
  async sendRequest(opts) {
86
78
  const { url, signal } = opts;
87
- const requestHeaders = HttpWire.toHeaderEntries({ headers: opts.headers });
88
- HttpWire.assertNoRequestCountHeader({ entries: requestHeaders, name: this.name });
79
+ const requestHeaders = HttpHeaders.merge({ layers: [opts.headers] });
80
+ HttpWire.assertNoRequestCountHeader({ headers: requestHeaders, name: this.name });
89
81
  const method = opts.method ?? HTTP.Methods.GET;
90
82
  const context = { paths: opts.paths, method, url, signal };
91
83
  const { payload, isJson, isFormData } = HttpWire.toRequestBody({ body: opts.body });
@@ -99,7 +91,9 @@ export class HttpDataSource extends DataSourceRoot {
99
91
  const built = this.buildHeaders({
100
92
  token: this.resolveAuthToken({ context }),
101
93
  // Resolved first, so the call's own headers win over them.
102
- requestHeaders: [...this.resolveHeaders({ context }), ...requestHeaders],
94
+ requestHeaders: HttpHeaders.merge({
95
+ layers: [this.resolveHeaders({ context }), requestHeaders],
96
+ }),
103
97
  isJsonBody: isJson,
104
98
  isFormDataBody: isFormData,
105
99
  });
@@ -223,7 +217,7 @@ export class HttpDataSource extends DataSourceRoot {
223
217
  const parsed = await this.readJsonBody({ response, url, verb: 'write' });
224
218
  const { extra } = HttpResponseReader.readExtra({ body: parsed, headers: response.headers });
225
219
  // `extra` is only read off an object body, which carries the rows under `data`.
226
- const data = (extra && HttpResponseReader.isPlainObject(parsed) ? parsed.data : parsed);
220
+ const data = (extra && RecordUtility.isPlainObject(parsed) ? parsed.data : parsed);
227
221
  const countHeader = response.headers.get(HTTP.Headers.RESPONSE_COUNT_DATA);
228
222
  const counted = countHeader === null ? Number.NaN : Number(countHeader);
229
223
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"datasource.js","sourceRoot":"","sources":["../../../src/http/datasource.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAuB,MAAM,oBAAoB,CAAC;AAC1F,OAAO,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACvF,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAWtD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,mGAAmG;AACnG,MAAM,OAAO,cAAe,SAAQ,cAAuC;IAQzE,YAAY,IAAiD;Q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W,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 { HttpReadShapes, HttpWireHeaders, type THttpReadShape } from './common/constants';\nimport { DataSourceRoot } from '@venizia/ignis-kernel/repository';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { NativeFetcher, UrlBuilder, UrlFetchError } 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/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */\nexport class HttpDataSource extends DataSourceRoot<IHttpDataSourceSettings> {\n override name: string;\n override settings: IHttpDataSourceSettings;\n override schema = {} as never;\n\n /** Normalised once: every request copies these, never re-parses `settings.headers`. */\n protected configuredHeaders: Array<[string, string]>;\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 UrlBuilder.assertBase({ baseUrl: settings.baseUrl, scope: name });\n\n this.configuredHeaders = configured;\n this.name = name;\n this.settings = settings;\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, HTTP.HeaderValues.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(HttpWireHeaders.AUTH_PROVIDER, token.provider);\n }\n\n return headers;\n }\n\n buildUrl(opts: { paths: Array<string>; query?: Record<string, unknown> }): string {\n const { paths, query } = opts;\n const url = UrlBuilder.join({ baseUrl: this.settings.baseUrl, paths, scope: this.name });\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 const { onUnauthorized } = this.settings;\n\n // One fetcher per call: its hooks close over this call's context. Both resolvers run in `onRequest`, so the retry sends what they answer after the refresh.\n const fetcher = new NativeFetcher({\n name: this.name,\n fetch: this.settings.fetch,\n hooks: {\n onRequest: ({ headers }) => {\n const built = 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 for (const name of [...headers.keys()]) {\n headers.delete(name);\n }\n\n built.forEach((value, name) => headers.set(name, value));\n },\n },\n });\n\n try {\n const response = await fetcher.send({\n url,\n method,\n body: payload,\n signal,\n // Every status is an answer the data source reads itself; a 401 with a refresh hook throws once so the retry can see it.\n acceptStatus: (status) => !onUnauthorized || status !== HTTP.ResultCodes.RS_4.Unauthorized,\n retry: onUnauthorized\n ? {\n maxAttempts: 2,\n backoff: { initialDelayMs: 0, maxDelayMs: 0 },\n shouldRetry: async ({ error, attempt }) => {\n if (\n !UrlFetchError.is(error) ||\n error.status !== HTTP.ResultCodes.RS_4.Unauthorized\n ) {\n return false;\n }\n\n const isRefreshed = await onUnauthorized(context, { attempt });\n\n // The second 401 stands: the hook hears of it, its answer is ignored, and nothing is sent a third time.\n return attempt === 1 && isRefreshed;\n },\n }\n : undefined,\n });\n\n return response;\n } catch (error) {\n // The 401 that stands is the answer: the data source reads its body into its own error.\n if (\n error instanceof UrlFetchError &&\n error.status === HTTP.ResultCodes.RS_4.Unauthorized &&\n error.response instanceof Response\n ) {\n return error.response;\n }\n\n throw error;\n }\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\n return HttpResponseReader.readJson({\n response,\n context: `[${this.name}][${verb}] ${response.status} | ${HttpWire.describeUrl({ url, status: response.status })}`,\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 // `extra` is only read off an object body, which carries the rows under `data`.\n const data = (extra && HttpResponseReader.isPlainObject(parsed) ? parsed.data : parsed) as R;\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,cAAc,EAAuB,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,aAAa,EACb,aAAa,EACb,UAAU,EACV,aAAa,GACd,MAAM,6BAA6B,CAAC;AAWrC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,mGAAmG;AACnG,MAAM,OAAO,cAAe,SAAQ,cAAuC;IAQzE,YAAY,IAAiD;QAC3D,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,IAAI,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC;QAN5C,WAAM,GAAG,EAAW,CAAC;QAQ5B,MAAM,EAAE,IAAI,GAAG,MAAM,EAAE,GAAG,QAAQ,EAAE,GAAG,IAAI,CAAC;QA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AC,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 { HttpReadShapes, type THttpReadShape } from './common/constants';\nimport { DataSourceRoot } from '@venizia/ignis-kernel/repository';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport {\n HttpHeaders,\n HttpResponseReader,\n NativeFetcher,\n RecordUtility,\n UrlBuilder,\n UrlFetchError,\n} from '@venizia/ignis-helpers/core';\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/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */\nexport class HttpDataSource extends DataSourceRoot<IHttpDataSourceSettings> {\n override name: string;\n override settings: IHttpDataSourceSettings;\n override schema = {} as never;\n\n /** Normalised once: every request copies these, never re-parses `settings.headers`. */\n protected configuredHeaders: Headers;\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 = HttpHeaders.merge({ layers: [settings.headers] });\n HttpWire.assertNoRequestCountHeader({ headers: configured, name });\n\n UrlBuilder.assertBase({ baseUrl: settings.baseUrl, scope: name });\n\n this.configuredHeaders = configured;\n this.name = name;\n this.settings = settings;\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 }): Headers {\n const headers = HttpHeaders.merge({ layers: [this.settings.headersResolver?.(opts.context)] });\n HttpWire.assertNoRequestCountHeader({ headers, name: this.name });\n\n return headers;\n }\n\n protected buildHeaders(opts: {\n token?: IAuthToken;\n requestHeaders?: Headers;\n isJsonBody?: boolean;\n isFormDataBody?: boolean;\n }): Headers {\n const { token, requestHeaders, isJsonBody, isFormDataBody } = opts;\n // A request's own headers win over the configured ones; the connector's below win over both.\n const headers = HttpHeaders.merge({ layers: [this.configuredHeaders, requestHeaders] });\n\n if (isJsonBody && !headers.has(HTTP.Headers.CONTENT_TYPE)) {\n headers.set(HTTP.Headers.CONTENT_TYPE, HTTP.HeaderValues.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(HTTP.Headers.AUTH_PROVIDER, token.provider);\n }\n\n return headers;\n }\n\n buildUrl(opts: { paths: Array<string>; query?: Record<string, unknown> }): string {\n const { paths, query } = opts;\n const url = UrlBuilder.join({ baseUrl: this.settings.baseUrl, paths, scope: this.name });\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 = HttpHeaders.merge({ layers: [opts.headers] });\n HttpWire.assertNoRequestCountHeader({ headers: 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 const { onUnauthorized } = this.settings;\n\n // One fetcher per call: its hooks close over this call's context. Both resolvers run in `onRequest`, so the retry sends what they answer after the refresh.\n const fetcher = new NativeFetcher({\n name: this.name,\n fetch: this.settings.fetch,\n hooks: {\n onRequest: ({ headers }) => {\n const built = this.buildHeaders({\n token: this.resolveAuthToken({ context }),\n // Resolved first, so the call's own headers win over them.\n requestHeaders: HttpHeaders.merge({\n layers: [this.resolveHeaders({ context }), requestHeaders],\n }),\n isJsonBody: isJson,\n isFormDataBody: isFormData,\n });\n\n for (const name of [...headers.keys()]) {\n headers.delete(name);\n }\n\n built.forEach((value, name) => headers.set(name, value));\n },\n },\n });\n\n try {\n const response = await fetcher.send({\n url,\n method,\n body: payload,\n signal,\n // Every status is an answer the data source reads itself; a 401 with a refresh hook throws once so the retry can see it.\n acceptStatus: (status) => !onUnauthorized || status !== HTTP.ResultCodes.RS_4.Unauthorized,\n retry: onUnauthorized\n ? {\n maxAttempts: 2,\n backoff: { initialDelayMs: 0, maxDelayMs: 0 },\n shouldRetry: async ({ error, attempt }) => {\n if (\n !UrlFetchError.is(error) ||\n error.status !== HTTP.ResultCodes.RS_4.Unauthorized\n ) {\n return false;\n }\n\n const isRefreshed = await onUnauthorized(context, { attempt });\n\n // The second 401 stands: the hook hears of it, its answer is ignored, and nothing is sent a third time.\n return attempt === 1 && isRefreshed;\n },\n }\n : undefined,\n });\n\n return response;\n } catch (error) {\n // The 401 that stands is the answer: the data source reads its body into its own error.\n if (\n error instanceof UrlFetchError &&\n error.status === HTTP.ResultCodes.RS_4.Unauthorized &&\n error.response instanceof Response\n ) {\n return error.response;\n }\n\n throw error;\n }\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\n return HttpResponseReader.readJson({\n response,\n context: `[${this.name}][${verb}] ${response.status} | ${HttpWire.describeUrl({ url, status: response.status })}`,\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 // `extra` is only read off an object body, which carries the rows under `data`.\n const data = (extra && RecordUtility.isPlainObject(parsed) ? parsed.data : parsed) as R;\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,5 +1,4 @@
1
1
  export * from './common/constants.js';
2
- export * from './common/readers.js';
3
2
  export * from './common/types.js';
4
3
  export * from './datasource.js';
5
4
  export * from './repository.js';
@@ -1,5 +1,4 @@
1
1
  export * from './common/constants.js';
2
- export * from './common/readers.js';
3
2
  export * from './common/types.js';
4
3
  export * from './datasource.js';
5
4
  export * from './repository.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/http/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC","sourcesContent":["export * from './common/constants';\nexport * from './common/readers';\nexport * from './common/types';\nexport * from './datasource';\nexport * from './repository';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/http/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC","sourcesContent":["export * from './common/constants';\nexport * from './common/types';\nexport * from './datasource';\nexport * from './repository';\n"]}
@@ -1,12 +1,11 @@
1
1
  import { HTTP } from '@venizia/ignis-helpers/common';
2
- import { getError } from '@venizia/ignis-helpers/core';
2
+ import { getError, RecordUtility } from '@venizia/ignis-helpers/core';
3
3
  import { Sorts } from '@venizia/ignis-filter';
4
4
  import { RequestFilterGuard } from '@venizia/ignis-kernel';
5
5
  import { SearchFieldTypes } from '../models/index.js';
6
6
  import { SearchEngineParams } from './engine-params.js';
7
7
  import { SearchInputSchema, SearchModes } from '../repositories/common/index.js';
8
8
  const SETTING_KEYS = new Set(['queryBy', 'queryByWeights', 'order', 'tuning']);
9
- const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
10
9
  /** Reads, checks and merges the `query` settings of a search controller. */
11
10
  export class SearchSettingsUtility {
12
11
  /**
@@ -40,7 +39,9 @@ export class SearchSettingsUtility {
40
39
  /** A keyed list knob (`{ title: 1, sku: 0 }`) becomes the positional list of `names`; any other value passes. */
41
40
  static toKnob(opts) {
42
41
  const { value, names } = opts;
43
- return isPlainObject(value) ? SearchSettingsUtility.toList({ record: value, names }) : value;
42
+ return RecordUtility.isPlainRecord(value)
43
+ ? SearchSettingsUtility.toList({ record: value, names })
44
+ : value;
44
45
  }
45
46
  /**
46
47
  * Checks one layer (`fixed` or `default`) against the model: only known settings; every field exists, is not hidden, and
@@ -50,7 +51,7 @@ export class SearchSettingsUtility {
50
51
  static assert(opts) {
51
52
  const { settings, scope, catalog, allowedTuning, isFixed, statusCode } = opts;
52
53
  const fail = (message) => SearchSettingsUtility.fail({ scope, message, statusCode });
53
- if (!isPlainObject(settings)) {
54
+ if (!RecordUtility.isPlainRecord(settings)) {
54
55
  throw fail(`the settings must be an object | got: ${typeof settings}`);
55
56
  }
56
57
  for (const key of Object.keys(settings)) {
@@ -82,7 +83,7 @@ export class SearchSettingsUtility {
82
83
  // A keyed setting must name the layer's own queryBy, field for field; with no queryBy in the layer, text fields.
83
84
  const checkKeyed = (keyed) => {
84
85
  const { record, where } = keyed;
85
- if (!isPlainObject(record)) {
86
+ if (!RecordUtility.isPlainRecord(record)) {
86
87
  throw fail(`${where} must be an object keyed by field name`);
87
88
  }
88
89
  for (const name of Object.keys(record)) {
@@ -125,7 +126,7 @@ export class SearchSettingsUtility {
125
126
  };
126
127
  if (queryByWeights !== undefined) {
127
128
  checkKeyed({ record: queryByWeights, where: 'queryByWeights' });
128
- for (const [name, weight] of isPlainObject(queryByWeights)
129
+ for (const [name, weight] of RecordUtility.isPlainRecord(queryByWeights)
129
130
  ? Object.entries(queryByWeights)
130
131
  : []) {
131
132
  if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0) {
@@ -154,7 +155,7 @@ export class SearchSettingsUtility {
154
155
  }
155
156
  }
156
157
  if (tuning !== undefined) {
157
- if (!isPlainObject(tuning)) {
158
+ if (!RecordUtility.isPlainRecord(tuning)) {
158
159
  throw fail('tuning must be an object');
159
160
  }
160
161
  if (order !== undefined && tuning['sortBy'] !== undefined) {
@@ -172,7 +173,7 @@ export class SearchSettingsUtility {
172
173
  if (name === 'sortBy') {
173
174
  checkSortBy(value);
174
175
  }
175
- else if (isPlainObject(value)) {
176
+ else if (RecordUtility.isPlainRecord(value)) {
176
177
  checkKeyed({ record: value, where: `tuning.${name}` });
177
178
  }
178
179
  }
@@ -357,7 +358,8 @@ export class SearchSettingsUtility {
357
358
  throw refuse(`tuning '${name}'`);
358
359
  }
359
360
  // A semantic search has no `queryBy`, so a keyed knob has nothing to align to: it is left out, as a fixed `queryBy` is.
360
- if (input.mode === SearchModes.SEMANTIC && isPlainObject(fixed.tuning[name])) {
361
+ if (input.mode === SearchModes.SEMANTIC &&
362
+ RecordUtility.isPlainRecord(fixed.tuning[name])) {
361
363
  continue;
362
364
  }
363
365
  const value = SearchSettingsUtility.toKnob({ value: fixed.tuning[name], names });
@@ -371,7 +373,8 @@ export class SearchSettingsUtility {
371
373
  tuning[name] = clientTuning[name];
372
374
  }
373
375
  else {
374
- if (input.mode === SearchModes.SEMANTIC && isPlainObject(defaults.tuning?.[name])) {
376
+ if (input.mode === SearchModes.SEMANTIC &&
377
+ RecordUtility.isPlainRecord(defaults.tuning?.[name])) {
375
378
  continue;
376
379
  }
377
380
  const value = SearchSettingsUtility.toKnob({ value: defaults.tuning?.[name], names });
@@ -1 +1 @@
1
- {"version":3,"file":"settings.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/settings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,OAAO,EAAE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gBAEvE,IAAI,MAAM,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;oBACrC,OAAO,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;gBAC3D,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,qBAAqB,CAAC,IAAI,CAAC;oBAC/B,KAAK,EAAE,gBAAgB;oBACvB,OAAO,EAAE,wDAAwD;oBACjE,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;oBACrD,KAAK,EAAE,KAAK;iBACb,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,OAAO,iBAAiB,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { Sorts } from '@venizia/ignis-filter';\nimport { RequestFilterGuard } from '@venizia/ignis-kernel';\nimport type { TInjected, TInjectMap, TRouteContext } from '@venizia/ignis-kernel';\nimport type { Env } from 'hono';\nimport { SearchFieldTypes } from '@/search/core/models';\nimport { SearchEngineParams } from './engine-params';\nimport type { ISearchQueryDialect, TSearchInput } from '@/search/core/repositories/common';\nimport { SearchInputSchema, SearchModes } from '@/search/core/repositories/common';\n\ntype TNonRawInput = Exclude<TSearchInput, { mode: typeof SearchModes.RAW }>;\n\n/** `ISearchQuerySettings` with its names as plain strings: what the build-time and per-request checks read, whatever the document. */\nexport interface ISearchLooseSettings {\n queryBy?: string[];\n queryByWeights?: Record<string, number | undefined>;\n order?: string[];\n tuning?: Record<string, unknown>;\n}\n\n/** What a function source is called with, whatever the document: the same context, scoped input and injected instances the typed options declare. */\nexport interface ISearchSourceOptions<\n RouteEnv extends Env,\n TExtra extends object,\n Inject extends TInjectMap,\n> {\n context: TRouteContext<RouteEnv>;\n input: TNonRawInput & TExtra;\n injected: TInjected<Inject>;\n}\n\n/** A function `query.fixed` or `query.default`: its result is checked on every request, so it is `unknown` here. */\nexport type TSearchLooseFunction<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n> = (opts: ISearchSourceOptions<RouteEnv, TExtra, Inject>) => ValueOrPromise<unknown>;\n\n/** A `query.fixed` or `query.default` as the controller keeps it: checked settings, or a function checked per request. */\nexport type TSearchLooseSource<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n> = ISearchLooseSettings | TSearchLooseFunction<RouteEnv, TExtra, Inject>;\n\n/** A `query.normalize`, with the text its mode carries. */\nexport type TSearchLooseNormalize<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n> = (\n opts: ISearchSourceOptions<RouteEnv, TExtra, Inject> & { text: string },\n) => ValueOrPromise<unknown>;\n\n/** What the model says about its fields, read once when the controller is built. */\nexport interface ISearchFieldCatalog {\n /** Field name to field type. */\n fields: ReadonlyMap<string, string>;\n hidden: ReadonlySet<string>;\n /** The model's own `defaultQueryBy`: the names a keyed setting aligns to when no `queryBy` is set. */\n defaultQueryBy: readonly string[];\n}\n\n/** The `query` option as the controller keeps it. */\nexport interface ISearchResolvedQuery<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n> {\n fixed?: TSearchLooseSource<RouteEnv, TExtra, Inject>;\n default?: TSearchLooseSource<RouteEnv, TExtra, Inject>;\n normalize?: TSearchLooseNormalize<RouteEnv, TExtra, Inject>;\n /** The names of `query.allow.tuning`. */\n allowedTuning: ReadonlySet<string>;\n catalog: ISearchFieldCatalog;\n}\n\nconst SETTING_KEYS = new Set(['queryBy', 'queryByWeights', 'order', 'tuning']);\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Reads, checks and merges the `query` settings of a search controller. */\nexport class SearchSettingsUtility {\n /**\n * The trust boundary of a function option (`query.fixed`, `query.default`, `query.normalize`): the typed options erase the\n * document and the engine here, and what the function returns is checked on every request.\n */\n static isFunctionOf<Fn extends (...args: never[]) => unknown>(value: unknown): value is Fn {\n return typeof value === 'function';\n }\n\n /** `statusCode` is set for what a request carries and for what a function source returns; a definition error leaves it unset, as every build error does. */\n private static fail(opts: {\n scope: string;\n message: string;\n statusCode?: number;\n cause?: unknown;\n }) {\n const { scope, message, statusCode, cause } = opts;\n\n return getError({ statusCode, message: `[${scope}] ${message}`, cause });\n }\n\n /** The values of `record` for `names`, in that order; `undefined` when `names` is empty or one of them has no value. */\n private static toList<Value>(opts: {\n record: Record<string, Value | undefined>;\n names?: readonly string[];\n }): Value[] | undefined {\n const { record, names } = opts;\n const values: Value[] = [];\n\n if (!names || names.length === 0) {\n return undefined;\n }\n\n for (const name of names) {\n const value = record[name];\n\n if (value === undefined) {\n return undefined;\n }\n\n values.push(value);\n }\n\n return values;\n }\n\n /** A keyed list knob (`{ title: 1, sku: 0 }`) becomes the positional list of `names`; any other value passes. */\n private static toKnob(opts: { value: unknown; names?: readonly string[] }): unknown {\n const { value, names } = opts;\n\n return isPlainObject(value) ? SearchSettingsUtility.toList({ record: value, names }) : value;\n }\n\n /**\n * Checks one layer (`fixed` or `default`) against the model: only known settings; every field exists, is not hidden, and\n * `queryBy` holds text fields; weights and keyed knobs name exactly the layer's `queryBy`; `order` and `tuning.sortBy` are not both given.\n * A fixed tuning name that is also in `allow.tuning` is refused.\n */\n static assert(opts: {\n settings: unknown;\n scope: string;\n catalog: ISearchFieldCatalog;\n allowedTuning: ReadonlySet<string>;\n isFixed: boolean;\n statusCode?: number;\n }): ISearchLooseSettings {\n const { settings, scope, catalog, allowedTuning, isFixed, statusCode } = opts;\n const fail = (message: string) => SearchSettingsUtility.fail({ scope, message, statusCode });\n\n if (!isPlainObject(settings)) {\n throw fail(`the settings must be an object | got: ${typeof settings}`);\n }\n\n for (const key of Object.keys(settings)) {\n if (!SETTING_KEYS.has(key)) {\n throw fail(`unknown setting '${key}' | settings: ${[...SETTING_KEYS].join(', ')}`);\n }\n }\n\n const checkField = (field: { name: string; where: string; isText?: boolean }) => {\n const type = catalog.fields.get(field.name);\n\n if (type === undefined) {\n throw fail(`${field.where} names a field the model does not have | field: ${field.name}`);\n }\n\n if (RequestFilterGuard.isHiddenByName({ key: field.name, hidden: catalog.hidden })) {\n throw fail(`${field.where} names a hidden field | field: ${field.name}`);\n }\n\n if (field.isText && !SearchFieldTypes.isText(type)) {\n throw fail(\n `${field.where} names a field that is not text; full-text search matches string and string[] fields only | field: ${field.name} | type: ${type}`,\n );\n }\n };\n\n const { queryBy, queryByWeights, order, tuning } = settings;\n\n if (queryBy !== undefined) {\n if (!Array.isArray(queryBy) || queryBy.some((name) => typeof name !== 'string')) {\n throw fail('queryBy must be a list of field names');\n }\n\n for (const name of queryBy) {\n checkField({ name, where: 'queryBy', isText: true });\n }\n }\n\n // A keyed setting must name the layer's own queryBy, field for field; with no queryBy in the layer, text fields.\n const checkKeyed = (keyed: { record: unknown; where: string }) => {\n const { record, where } = keyed;\n\n if (!isPlainObject(record)) {\n throw fail(`${where} must be an object keyed by field name`);\n }\n\n for (const name of Object.keys(record)) {\n if (queryBy === undefined) {\n checkField({ name, where, isText: true });\n } else if (!queryBy.includes(name)) {\n throw fail(`${where} names a field that is not in queryBy | field: ${name}`);\n }\n }\n\n if (queryBy !== undefined) {\n const missing = queryBy.filter((name: string) => record[name] === undefined);\n\n if (missing.length > 0) {\n throw fail(`${where} must name every queryBy field | missing: ${missing.join(', ')}`);\n }\n }\n };\n\n // The engine's own sort string (`price:desc`, `location(48.85, 2.35, precision: 2km):asc`,\n // `_text_match:desc,_eval([(status:=ACTIVATED):1]):desc`) is the server's, so the guarantee is simple: no hidden field is\n // named anywhere in it, in any position (a value equal to a hidden name is refused too). The unknown-field check is\n // separate and lenient: each top-level entry names a field of the model, or one of the engine's own sort names.\n const checkSortBy = (value: unknown) => {\n if (typeof value !== 'string') {\n throw fail('tuning.sortBy must be a string');\n }\n\n for (const token of SearchSettingsUtility.sortTokens({ value })) {\n if (RequestFilterGuard.isHiddenByName({ key: token, hidden: catalog.hidden })) {\n throw fail(`tuning.sortBy names a hidden field | field: ${token}`);\n }\n }\n\n for (const entry of SearchSettingsUtility.splitSortBy({ value })) {\n const name = SearchSettingsUtility.sortEntryName({ entry });\n\n if (name === '') {\n throw fail(\n `tuning.sortBy has an entry that names no field | entry: ${JSON.stringify(entry)}`,\n );\n }\n\n if (!SearchSettingsUtility.ENGINE_SORT_NAMES.has(name)) {\n checkField({ name, where: 'tuning.sortBy' });\n }\n }\n };\n\n if (queryByWeights !== undefined) {\n checkKeyed({ record: queryByWeights, where: 'queryByWeights' });\n\n for (const [name, weight] of isPlainObject(queryByWeights)\n ? Object.entries(queryByWeights)\n : []) {\n if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0) {\n throw fail(`queryByWeights needs a finite weight of 0 or more | field: ${name}`);\n }\n }\n }\n\n if (order !== undefined) {\n if (!Array.isArray(order) || order.some((entry) => typeof entry !== 'string')) {\n throw fail(\"order must be a list of entries such as 'price' or 'price DESC'\");\n }\n\n for (const entry of order) {\n let orderField: string;\n\n try {\n orderField = Sorts.parseEntry({ entry }).field;\n } catch (error) {\n throw SearchSettingsUtility.fail({\n scope,\n message: `order holds an entry that is not a field with an optional direction | entry: ${JSON.stringify(entry)}`,\n statusCode,\n cause: error,\n });\n }\n\n checkField({ name: orderField, where: 'order' });\n }\n }\n\n if (tuning !== undefined) {\n if (!isPlainObject(tuning)) {\n throw fail('tuning must be an object');\n }\n\n if (order !== undefined && tuning['sortBy'] !== undefined) {\n throw fail(\n 'order and tuning.sortBy are both set | give one of them: the engine takes one sort',\n );\n }\n\n for (const [name, value] of Object.entries(tuning)) {\n // `sortBy` is the one name that selects order and is allowed here: it is read below like `order`. The others select rows or fields.\n if (name !== 'sortBy' && SearchEngineParams.isNeverAllowed({ name })) {\n throw fail(\n `tuning '${name}' selects rows, fields or order | set queryBy, order or the scope for that, or pass it in server code on a repository call`,\n );\n }\n\n if (\n isFixed &&\n [...allowedTuning].some((allowed) =>\n SearchEngineParams.isSameName({ left: allowed, right: name }),\n )\n ) {\n throw fail(\n `tuning '${name}' is fixed and also in allow.tuning | a name is fixed or open to the client, never both`,\n );\n }\n\n if (name === 'sortBy') {\n checkSortBy(value);\n } else if (isPlainObject(value)) {\n checkKeyed({ record: value, where: `tuning.${name}` });\n }\n }\n }\n\n return settings;\n }\n\n /** The sort names the engine defines itself: not fields of the model. */\n static readonly ENGINE_SORT_NAMES: ReadonlySet<string> = new Set([\n '_text_match',\n '_seq_id',\n '_group_found',\n '_vector_distance',\n '_eval',\n '_vector_query',\n ]);\n\n /**\n * Every run of characters in a sort string that can be part of a field name: quotes are dropped, and whitespace, brackets,\n * commas and the operators of an `_eval` split it. A name with a hyphen or a non-ASCII letter stays whole.\n */\n static sortTokens(opts: { value: string }): string[] {\n return opts.value\n .replaceAll(/[`\"]/g, '')\n .split(/[\\s()[\\],:=!<>&|*$']+/)\n .filter((token) => token.length > 0);\n }\n\n /** The top-level entries of an engine sort string: a comma inside brackets or a quoted string does not split. */\n static splitSortBy(opts: { value: string }): string[] {\n const entries: string[] = [];\n let depth = 0;\n let quote: string | undefined;\n let start = 0;\n\n for (let index = 0; index < opts.value.length; index++) {\n const character = opts.value[index] ?? '';\n\n if (quote !== undefined) {\n quote = character === quote ? undefined : quote;\n } else if (character === '`' || character === '\"') {\n quote = character;\n } else if (character === '(' || character === '[') {\n depth += 1;\n } else if (character === ')' || character === ']') {\n depth -= 1;\n } else if (character === ',' && depth === 0) {\n entries.push(opts.value.slice(start, index));\n start = index + 1;\n }\n }\n\n entries.push(opts.value.slice(start));\n\n return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0);\n }\n\n /** The name an entry starts with: the run before the first `(`, `:` or whitespace, without quotes. */\n static sortEntryName(opts: { entry: string }): string {\n return (/^[^\\s(:,]+/.exec(opts.entry.replaceAll(/[`\"]/g, ''))?.[0] ?? '').trim();\n }\n\n /** A source's settings for this request: a value as it is, a function called with `{ context, input }` and its result checked like a definition. A function that throws, or returns what is not a valid shape, answers 500: the value is the server's. */\n static async resolveSource<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n >(opts: {\n source?: TSearchLooseSource<RouteEnv, TExtra, Inject>;\n context: TRouteContext<RouteEnv>;\n input: TNonRawInput & TExtra;\n injected: TInjected<Inject>;\n query: ISearchResolvedQuery<RouteEnv, TExtra, Inject>;\n isFixed: boolean;\n }): Promise<ISearchLooseSettings> {\n const { source, context, input, injected, query, isFixed } = opts;\n const scope = isFixed ? 'search | query.fixed' : 'search | query.default';\n const statusCode = HTTP.ResultCodes.RS_5.InternalServerError;\n\n if (source === undefined) {\n return {};\n }\n\n if (typeof source !== 'function') {\n return source;\n }\n\n let settings: unknown;\n\n try {\n const result = await source({ context, input, injected });\n settings = result;\n } catch (error) {\n throw SearchSettingsUtility.fail({\n scope,\n message: 'the settings function threw',\n statusCode,\n cause: error,\n });\n }\n\n return SearchSettingsUtility.assert({\n settings,\n scope,\n catalog: query.catalog,\n allowedTuning: query.allowedTuning,\n isFixed,\n statusCode,\n });\n }\n\n /**\n * Layers the settings of one request: `fixed`, else what the client sent (a tuning name only when allowed), else `default`,\n * else the model's `defaultQueryBy`. A client value for a fixed setting is a 400. A keyed setting becomes the positional\n * list of the request's `queryBy`; one that does not name every field is a 400 when it is fixed and dropped when it is a default.\n * `serverTuning` is the part of `engineParams` the server chose.\n */\n static merge(opts: {\n input: TNonRawInput;\n fixed: ISearchLooseSettings;\n defaults: ISearchLooseSettings;\n catalog: ISearchFieldCatalog;\n }): {\n input: Record<string, unknown>;\n serverTuning: Record<string, unknown>;\n serverOrder?: string[];\n } {\n const { input, fixed, defaults, catalog } = opts;\n const next: Record<string, unknown> = { ...input };\n const serverTuning: Record<string, unknown> = {};\n const refuse = (what: string) =>\n SearchSettingsUtility.fail({\n scope: 'search',\n message: `${what} is fixed by this search controller and cannot be sent`,\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n });\n // The fields a keyed setting aligns to: the client's own `queryBy` makes a gap its mistake (400); the server's list or the model's makes it the server's (500).\n const isNamesFromClient =\n fixed.queryBy === undefined && 'queryBy' in input && input.queryBy !== undefined;\n const notNamed = (what: string) =>\n SearchSettingsUtility.fail({\n scope: 'search',\n message: `the fixed ${what} does not name every queryBy field of this request`,\n statusCode: isNamesFromClient\n ? HTTP.ResultCodes.RS_4.BadRequest\n : HTTP.ResultCodes.RS_5.InternalServerError,\n });\n let names: readonly string[] | undefined;\n\n if (input.mode !== SearchModes.SEMANTIC) {\n if (fixed.queryBy && input.queryBy) {\n throw refuse('queryBy');\n }\n\n const queryBy = fixed.queryBy ?? input.queryBy ?? defaults.queryBy;\n names = queryBy ?? catalog.defaultQueryBy;\n\n if (queryBy) {\n next['queryBy'] = queryBy;\n } else if (input.mode === SearchModes.HYBRID) {\n // The schema asks a hybrid body for `queryBy`; with none from anywhere, the model's own list or a 400.\n if (names.length === 0) {\n throw SearchSettingsUtility.fail({\n scope: 'search',\n message:\n 'hybrid search needs queryBy: send it, or set it in query.fixed or query.default',\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n });\n }\n\n next['queryBy'] = [...names];\n }\n\n if (fixed.queryByWeights) {\n if (input.queryByWeights) {\n throw refuse('queryByWeights');\n }\n\n const list = SearchSettingsUtility.toList({ record: fixed.queryByWeights, names });\n\n if (!list) {\n throw notNamed('queryByWeights');\n }\n\n next['queryByWeights'] = list;\n } else if (!input.queryByWeights && defaults.queryByWeights) {\n const list = SearchSettingsUtility.toList({ record: defaults.queryByWeights, names });\n\n if (list) {\n next['queryByWeights'] = list;\n }\n }\n }\n\n // One sort: `order` and `tuning.sortBy` are the same setting, whichever layer gives it.\n const sortOf = (layer: ISearchLooseSettings) =>\n layer.order ?? (layer.tuning?.['sortBy'] !== undefined ? layer.tuning['sortBy'] : undefined);\n const clientOrder = input.filter?.order;\n const hasClientOrder = clientOrder !== undefined && clientOrder.length > 0;\n\n if (sortOf(fixed) !== undefined && hasClientOrder) {\n throw refuse('filter.order');\n }\n\n const sort = sortOf(fixed) ?? (hasClientOrder ? undefined : sortOf(defaults));\n\n const serverOrder = Array.isArray(sort) ? sort : undefined;\n\n if (serverOrder) {\n next['filter'] = { ...input.filter, order: serverOrder };\n }\n\n const tuning: Record<string, unknown> = {};\n const clientTuning = input.engineParams ?? {};\n\n if (sort !== undefined && !Array.isArray(sort)) {\n tuning['sortBy'] = sort;\n serverTuning['sortBy'] = sort;\n }\n\n const tuningNames = new Set([\n ...Object.keys(fixed.tuning ?? {}),\n ...Object.keys(clientTuning),\n ...Object.keys(defaults.tuning ?? {}),\n ]);\n\n for (const name of tuningNames) {\n if (name === 'sortBy') {\n continue;\n }\n\n if (fixed.tuning?.[name] !== undefined) {\n if (\n Object.keys(clientTuning).some((sent) =>\n SearchEngineParams.isSameName({ left: sent, right: name }),\n )\n ) {\n throw refuse(`tuning '${name}'`);\n }\n\n // A semantic search has no `queryBy`, so a keyed knob has nothing to align to: it is left out, as a fixed `queryBy` is.\n if (input.mode === SearchModes.SEMANTIC && isPlainObject(fixed.tuning[name])) {\n continue;\n }\n\n const value = SearchSettingsUtility.toKnob({ value: fixed.tuning[name], names });\n\n if (value === undefined) {\n throw notNamed(`tuning '${name}'`);\n }\n\n tuning[name] = value;\n serverTuning[name] = value;\n } else if (name in clientTuning) {\n tuning[name] = clientTuning[name];\n } else {\n if (input.mode === SearchModes.SEMANTIC && isPlainObject(defaults.tuning?.[name])) {\n continue;\n }\n\n const value = SearchSettingsUtility.toKnob({ value: defaults.tuning?.[name], names });\n\n if (value !== undefined) {\n tuning[name] = value;\n serverTuning[name] = value;\n }\n }\n }\n\n if (Object.keys(tuning).length > 0) {\n next['engineParams'] = tuning;\n }\n\n return { input: next, serverTuning, serverOrder };\n }\n\n /**\n * The input with the query text `query.normalize` returned: `query` of a keyword or hybrid request, `queryText` of a\n * semantic one. A request without text is left as it is. A throw, or a result that is not a string, answers 500: the\n * function is the server's.\n */\n static async normalize<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n >(opts: {\n query: ISearchResolvedQuery<RouteEnv, TExtra, Inject>;\n context: TRouteContext<RouteEnv>;\n input: TNonRawInput & TExtra;\n injected: TInjected<Inject>;\n }): Promise<TNonRawInput & TExtra> {\n const { query, context, input, injected } = opts;\n const text = input.mode === SearchModes.SEMANTIC ? input.queryText : input.query;\n\n if (!query.normalize || text === undefined) {\n return input;\n }\n\n let normalized: unknown;\n\n try {\n const result = await query.normalize({ text, context, input, injected });\n normalized = result;\n } catch (error) {\n throw SearchSettingsUtility.fail({\n scope: 'search | query.normalize',\n message: 'the normalize function threw',\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n cause: error,\n });\n }\n\n if (typeof normalized !== 'string') {\n throw SearchSettingsUtility.fail({\n scope: 'search | query.normalize',\n message: `the normalize function must return a string | got: ${typeof normalized}`,\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n });\n }\n\n return input.mode === SearchModes.SEMANTIC\n ? { ...input, queryText: normalized }\n : { ...input, query: normalized };\n }\n\n /**\n * The input of a request with the controller's `query` settings applied. What the server chose is checked with the engine's\n * own converter before the repository runs, so a bad value (`numTypos: -1`) is the server's 500 and not the client's 400.\n * The result is parsed with `SearchInputSchema`, which also drops the keys `request.body.extend` added.\n */\n static async apply<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n >(opts: {\n query: ISearchResolvedQuery<RouteEnv, TExtra, Inject>;\n context: TRouteContext<RouteEnv>;\n input: TSearchInput & TExtra;\n injected: TInjected<Inject>;\n dialect: ISearchQueryDialect;\n }): Promise<TSearchInput> {\n const { query, context, input: received, injected, dialect } = opts;\n\n if (received.mode === SearchModes.RAW) {\n return received;\n }\n\n // First: every function source below reads the text `normalize` returns.\n const input = await SearchSettingsUtility.normalize({\n query,\n context,\n input: received,\n injected,\n });\n\n const [fixed, defaults] = await Promise.all([\n SearchSettingsUtility.resolveSource({\n source: query.fixed,\n context,\n input,\n injected,\n query,\n isFixed: true,\n }),\n SearchSettingsUtility.resolveSource({\n source: query.default,\n context,\n input,\n injected,\n query,\n isFixed: false,\n }),\n ]);\n const merged = SearchSettingsUtility.merge({\n input,\n fixed,\n defaults,\n catalog: query.catalog,\n });\n\n if (Object.keys(merged.serverTuning).length > 0 || merged.serverOrder !== undefined) {\n try {\n dialect.toWireParams({ query: { engineParams: merged.serverTuning } });\n\n if (merged.serverOrder !== undefined) {\n dialect.build({ filter: { order: merged.serverOrder } });\n }\n } catch (error) {\n throw SearchSettingsUtility.fail({\n scope: 'search | query',\n message: 'the engine refuses the sort or tuning the server chose',\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n cause: error,\n });\n }\n }\n\n return SearchInputSchema.parse(merged.input);\n }\n}\n"]}
1
+ {"version":3,"file":"settings.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/settings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAG3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAqEnF,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,gBAAgB,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AAE/E,4EAA4E;AAC5E,MAAM,OAAO,qBAAqB;IAChC;;;OAG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ia/ignis-helpers/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError, RecordUtility } from '@venizia/ignis-helpers/core';\nimport { Sorts } from '@venizia/ignis-filter';\nimport { RequestFilterGuard } from '@venizia/ignis-kernel';\nimport type { TInjected, TInjectMap, TRouteContext } from '@venizia/ignis-kernel';\nimport type { Env } from 'hono';\nimport { SearchFieldTypes } from '@/search/core/models';\nimport { SearchEngineParams } from './engine-params';\nimport type { ISearchQueryDialect, TSearchInput } from '@/search/core/repositories/common';\nimport { SearchInputSchema, SearchModes } from '@/search/core/repositories/common';\n\ntype TNonRawInput = Exclude<TSearchInput, { mode: typeof SearchModes.RAW }>;\n\n/** `ISearchQuerySettings` with its names as plain strings: what the build-time and per-request checks read, whatever the document. */\nexport interface ISearchLooseSettings {\n queryBy?: string[];\n queryByWeights?: Record<string, number | undefined>;\n order?: string[];\n tuning?: Record<string, unknown>;\n}\n\n/** What a function source is called with, whatever the document: the same context, scoped input and injected instances the typed options declare. */\nexport interface ISearchSourceOptions<\n RouteEnv extends Env,\n TExtra extends object,\n Inject extends TInjectMap,\n> {\n context: TRouteContext<RouteEnv>;\n input: TNonRawInput & TExtra;\n injected: TInjected<Inject>;\n}\n\n/** A function `query.fixed` or `query.default`: its result is checked on every request, so it is `unknown` here. */\nexport type TSearchLooseFunction<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n> = (opts: ISearchSourceOptions<RouteEnv, TExtra, Inject>) => ValueOrPromise<unknown>;\n\n/** A `query.fixed` or `query.default` as the controller keeps it: checked settings, or a function checked per request. */\nexport type TSearchLooseSource<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n> = ISearchLooseSettings | TSearchLooseFunction<RouteEnv, TExtra, Inject>;\n\n/** A `query.normalize`, with the text its mode carries. */\nexport type TSearchLooseNormalize<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n> = (\n opts: ISearchSourceOptions<RouteEnv, TExtra, Inject> & { text: string },\n) => ValueOrPromise<unknown>;\n\n/** What the model says about its fields, read once when the controller is built. */\nexport interface ISearchFieldCatalog {\n /** Field name to field type. */\n fields: ReadonlyMap<string, string>;\n hidden: ReadonlySet<string>;\n /** The model's own `defaultQueryBy`: the names a keyed setting aligns to when no `queryBy` is set. */\n defaultQueryBy: readonly string[];\n}\n\n/** The `query` option as the controller keeps it. */\nexport interface ISearchResolvedQuery<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n> {\n fixed?: TSearchLooseSource<RouteEnv, TExtra, Inject>;\n default?: TSearchLooseSource<RouteEnv, TExtra, Inject>;\n normalize?: TSearchLooseNormalize<RouteEnv, TExtra, Inject>;\n /** The names of `query.allow.tuning`. */\n allowedTuning: ReadonlySet<string>;\n catalog: ISearchFieldCatalog;\n}\n\nconst SETTING_KEYS = new Set(['queryBy', 'queryByWeights', 'order', 'tuning']);\n\n/** Reads, checks and merges the `query` settings of a search controller. */\nexport class SearchSettingsUtility {\n /**\n * The trust boundary of a function option (`query.fixed`, `query.default`, `query.normalize`): the typed options erase the\n * document and the engine here, and what the function returns is checked on every request.\n */\n static isFunctionOf<Fn extends (...args: never[]) => unknown>(value: unknown): value is Fn {\n return typeof value === 'function';\n }\n\n /** `statusCode` is set for what a request carries and for what a function source returns; a definition error leaves it unset, as every build error does. */\n private static fail(opts: {\n scope: string;\n message: string;\n statusCode?: number;\n cause?: unknown;\n }) {\n const { scope, message, statusCode, cause } = opts;\n\n return getError({ statusCode, message: `[${scope}] ${message}`, cause });\n }\n\n /** The values of `record` for `names`, in that order; `undefined` when `names` is empty or one of them has no value. */\n private static toList<Value>(opts: {\n record: Record<string, Value | undefined>;\n names?: readonly string[];\n }): Value[] | undefined {\n const { record, names } = opts;\n const values: Value[] = [];\n\n if (!names || names.length === 0) {\n return undefined;\n }\n\n for (const name of names) {\n const value = record[name];\n\n if (value === undefined) {\n return undefined;\n }\n\n values.push(value);\n }\n\n return values;\n }\n\n /** A keyed list knob (`{ title: 1, sku: 0 }`) becomes the positional list of `names`; any other value passes. */\n private static toKnob(opts: { value: unknown; names?: readonly string[] }): unknown {\n const { value, names } = opts;\n\n return RecordUtility.isPlainRecord(value)\n ? SearchSettingsUtility.toList({ record: value, names })\n : value;\n }\n\n /**\n * Checks one layer (`fixed` or `default`) against the model: only known settings; every field exists, is not hidden, and\n * `queryBy` holds text fields; weights and keyed knobs name exactly the layer's `queryBy`; `order` and `tuning.sortBy` are not both given.\n * A fixed tuning name that is also in `allow.tuning` is refused.\n */\n static assert(opts: {\n settings: unknown;\n scope: string;\n catalog: ISearchFieldCatalog;\n allowedTuning: ReadonlySet<string>;\n isFixed: boolean;\n statusCode?: number;\n }): ISearchLooseSettings {\n const { settings, scope, catalog, allowedTuning, isFixed, statusCode } = opts;\n const fail = (message: string) => SearchSettingsUtility.fail({ scope, message, statusCode });\n\n if (!RecordUtility.isPlainRecord(settings)) {\n throw fail(`the settings must be an object | got: ${typeof settings}`);\n }\n\n for (const key of Object.keys(settings)) {\n if (!SETTING_KEYS.has(key)) {\n throw fail(`unknown setting '${key}' | settings: ${[...SETTING_KEYS].join(', ')}`);\n }\n }\n\n const checkField = (field: { name: string; where: string; isText?: boolean }) => {\n const type = catalog.fields.get(field.name);\n\n if (type === undefined) {\n throw fail(`${field.where} names a field the model does not have | field: ${field.name}`);\n }\n\n if (RequestFilterGuard.isHiddenByName({ key: field.name, hidden: catalog.hidden })) {\n throw fail(`${field.where} names a hidden field | field: ${field.name}`);\n }\n\n if (field.isText && !SearchFieldTypes.isText(type)) {\n throw fail(\n `${field.where} names a field that is not text; full-text search matches string and string[] fields only | field: ${field.name} | type: ${type}`,\n );\n }\n };\n\n const { queryBy, queryByWeights, order, tuning } = settings;\n\n if (queryBy !== undefined) {\n if (!Array.isArray(queryBy) || queryBy.some((name) => typeof name !== 'string')) {\n throw fail('queryBy must be a list of field names');\n }\n\n for (const name of queryBy) {\n checkField({ name, where: 'queryBy', isText: true });\n }\n }\n\n // A keyed setting must name the layer's own queryBy, field for field; with no queryBy in the layer, text fields.\n const checkKeyed = (keyed: { record: unknown; where: string }) => {\n const { record, where } = keyed;\n\n if (!RecordUtility.isPlainRecord(record)) {\n throw fail(`${where} must be an object keyed by field name`);\n }\n\n for (const name of Object.keys(record)) {\n if (queryBy === undefined) {\n checkField({ name, where, isText: true });\n } else if (!queryBy.includes(name)) {\n throw fail(`${where} names a field that is not in queryBy | field: ${name}`);\n }\n }\n\n if (queryBy !== undefined) {\n const missing = queryBy.filter((name: string) => record[name] === undefined);\n\n if (missing.length > 0) {\n throw fail(`${where} must name every queryBy field | missing: ${missing.join(', ')}`);\n }\n }\n };\n\n // The engine's own sort string (`price:desc`, `location(48.85, 2.35, precision: 2km):asc`,\n // `_text_match:desc,_eval([(status:=ACTIVATED):1]):desc`) is the server's, so the guarantee is simple: no hidden field is\n // named anywhere in it, in any position (a value equal to a hidden name is refused too). The unknown-field check is\n // separate and lenient: each top-level entry names a field of the model, or one of the engine's own sort names.\n const checkSortBy = (value: unknown) => {\n if (typeof value !== 'string') {\n throw fail('tuning.sortBy must be a string');\n }\n\n for (const token of SearchSettingsUtility.sortTokens({ value })) {\n if (RequestFilterGuard.isHiddenByName({ key: token, hidden: catalog.hidden })) {\n throw fail(`tuning.sortBy names a hidden field | field: ${token}`);\n }\n }\n\n for (const entry of SearchSettingsUtility.splitSortBy({ value })) {\n const name = SearchSettingsUtility.sortEntryName({ entry });\n\n if (name === '') {\n throw fail(\n `tuning.sortBy has an entry that names no field | entry: ${JSON.stringify(entry)}`,\n );\n }\n\n if (!SearchSettingsUtility.ENGINE_SORT_NAMES.has(name)) {\n checkField({ name, where: 'tuning.sortBy' });\n }\n }\n };\n\n if (queryByWeights !== undefined) {\n checkKeyed({ record: queryByWeights, where: 'queryByWeights' });\n\n for (const [name, weight] of RecordUtility.isPlainRecord(queryByWeights)\n ? Object.entries(queryByWeights)\n : []) {\n if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0) {\n throw fail(`queryByWeights needs a finite weight of 0 or more | field: ${name}`);\n }\n }\n }\n\n if (order !== undefined) {\n if (!Array.isArray(order) || order.some((entry) => typeof entry !== 'string')) {\n throw fail(\"order must be a list of entries such as 'price' or 'price DESC'\");\n }\n\n for (const entry of order) {\n let orderField: string;\n\n try {\n orderField = Sorts.parseEntry({ entry }).field;\n } catch (error) {\n throw SearchSettingsUtility.fail({\n scope,\n message: `order holds an entry that is not a field with an optional direction | entry: ${JSON.stringify(entry)}`,\n statusCode,\n cause: error,\n });\n }\n\n checkField({ name: orderField, where: 'order' });\n }\n }\n\n if (tuning !== undefined) {\n if (!RecordUtility.isPlainRecord(tuning)) {\n throw fail('tuning must be an object');\n }\n\n if (order !== undefined && tuning['sortBy'] !== undefined) {\n throw fail(\n 'order and tuning.sortBy are both set | give one of them: the engine takes one sort',\n );\n }\n\n for (const [name, value] of Object.entries(tuning)) {\n // `sortBy` is the one name that selects order and is allowed here: it is read below like `order`. The others select rows or fields.\n if (name !== 'sortBy' && SearchEngineParams.isNeverAllowed({ name })) {\n throw fail(\n `tuning '${name}' selects rows, fields or order | set queryBy, order or the scope for that, or pass it in server code on a repository call`,\n );\n }\n\n if (\n isFixed &&\n [...allowedTuning].some((allowed) =>\n SearchEngineParams.isSameName({ left: allowed, right: name }),\n )\n ) {\n throw fail(\n `tuning '${name}' is fixed and also in allow.tuning | a name is fixed or open to the client, never both`,\n );\n }\n\n if (name === 'sortBy') {\n checkSortBy(value);\n } else if (RecordUtility.isPlainRecord(value)) {\n checkKeyed({ record: value, where: `tuning.${name}` });\n }\n }\n }\n\n return settings;\n }\n\n /** The sort names the engine defines itself: not fields of the model. */\n static readonly ENGINE_SORT_NAMES: ReadonlySet<string> = new Set([\n '_text_match',\n '_seq_id',\n '_group_found',\n '_vector_distance',\n '_eval',\n '_vector_query',\n ]);\n\n /**\n * Every run of characters in a sort string that can be part of a field name: quotes are dropped, and whitespace, brackets,\n * commas and the operators of an `_eval` split it. A name with a hyphen or a non-ASCII letter stays whole.\n */\n static sortTokens(opts: { value: string }): string[] {\n return opts.value\n .replaceAll(/[`\"]/g, '')\n .split(/[\\s()[\\],:=!<>&|*$']+/)\n .filter((token) => token.length > 0);\n }\n\n /** The top-level entries of an engine sort string: a comma inside brackets or a quoted string does not split. */\n static splitSortBy(opts: { value: string }): string[] {\n const entries: string[] = [];\n let depth = 0;\n let quote: string | undefined;\n let start = 0;\n\n for (let index = 0; index < opts.value.length; index++) {\n const character = opts.value[index] ?? '';\n\n if (quote !== undefined) {\n quote = character === quote ? undefined : quote;\n } else if (character === '`' || character === '\"') {\n quote = character;\n } else if (character === '(' || character === '[') {\n depth += 1;\n } else if (character === ')' || character === ']') {\n depth -= 1;\n } else if (character === ',' && depth === 0) {\n entries.push(opts.value.slice(start, index));\n start = index + 1;\n }\n }\n\n entries.push(opts.value.slice(start));\n\n return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0);\n }\n\n /** The name an entry starts with: the run before the first `(`, `:` or whitespace, without quotes. */\n static sortEntryName(opts: { entry: string }): string {\n return (/^[^\\s(:,]+/.exec(opts.entry.replaceAll(/[`\"]/g, ''))?.[0] ?? '').trim();\n }\n\n /** A source's settings for this request: a value as it is, a function called with `{ context, input }` and its result checked like a definition. A function that throws, or returns what is not a valid shape, answers 500: the value is the server's. */\n static async resolveSource<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n >(opts: {\n source?: TSearchLooseSource<RouteEnv, TExtra, Inject>;\n context: TRouteContext<RouteEnv>;\n input: TNonRawInput & TExtra;\n injected: TInjected<Inject>;\n query: ISearchResolvedQuery<RouteEnv, TExtra, Inject>;\n isFixed: boolean;\n }): Promise<ISearchLooseSettings> {\n const { source, context, input, injected, query, isFixed } = opts;\n const scope = isFixed ? 'search | query.fixed' : 'search | query.default';\n const statusCode = HTTP.ResultCodes.RS_5.InternalServerError;\n\n if (source === undefined) {\n return {};\n }\n\n if (typeof source !== 'function') {\n return source;\n }\n\n let settings: unknown;\n\n try {\n const result = await source({ context, input, injected });\n settings = result;\n } catch (error) {\n throw SearchSettingsUtility.fail({\n scope,\n message: 'the settings function threw',\n statusCode,\n cause: error,\n });\n }\n\n return SearchSettingsUtility.assert({\n settings,\n scope,\n catalog: query.catalog,\n allowedTuning: query.allowedTuning,\n isFixed,\n statusCode,\n });\n }\n\n /**\n * Layers the settings of one request: `fixed`, else what the client sent (a tuning name only when allowed), else `default`,\n * else the model's `defaultQueryBy`. A client value for a fixed setting is a 400. A keyed setting becomes the positional\n * list of the request's `queryBy`; one that does not name every field is a 400 when it is fixed and dropped when it is a default.\n * `serverTuning` is the part of `engineParams` the server chose.\n */\n static merge(opts: {\n input: TNonRawInput;\n fixed: ISearchLooseSettings;\n defaults: ISearchLooseSettings;\n catalog: ISearchFieldCatalog;\n }): {\n input: Record<string, unknown>;\n serverTuning: Record<string, unknown>;\n serverOrder?: string[];\n } {\n const { input, fixed, defaults, catalog } = opts;\n const next: Record<string, unknown> = { ...input };\n const serverTuning: Record<string, unknown> = {};\n const refuse = (what: string) =>\n SearchSettingsUtility.fail({\n scope: 'search',\n message: `${what} is fixed by this search controller and cannot be sent`,\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n });\n // The fields a keyed setting aligns to: the client's own `queryBy` makes a gap its mistake (400); the server's list or the model's makes it the server's (500).\n const isNamesFromClient =\n fixed.queryBy === undefined && 'queryBy' in input && input.queryBy !== undefined;\n const notNamed = (what: string) =>\n SearchSettingsUtility.fail({\n scope: 'search',\n message: `the fixed ${what} does not name every queryBy field of this request`,\n statusCode: isNamesFromClient\n ? HTTP.ResultCodes.RS_4.BadRequest\n : HTTP.ResultCodes.RS_5.InternalServerError,\n });\n let names: readonly string[] | undefined;\n\n if (input.mode !== SearchModes.SEMANTIC) {\n if (fixed.queryBy && input.queryBy) {\n throw refuse('queryBy');\n }\n\n const queryBy = fixed.queryBy ?? input.queryBy ?? defaults.queryBy;\n names = queryBy ?? catalog.defaultQueryBy;\n\n if (queryBy) {\n next['queryBy'] = queryBy;\n } else if (input.mode === SearchModes.HYBRID) {\n // The schema asks a hybrid body for `queryBy`; with none from anywhere, the model's own list or a 400.\n if (names.length === 0) {\n throw SearchSettingsUtility.fail({\n scope: 'search',\n message:\n 'hybrid search needs queryBy: send it, or set it in query.fixed or query.default',\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n });\n }\n\n next['queryBy'] = [...names];\n }\n\n if (fixed.queryByWeights) {\n if (input.queryByWeights) {\n throw refuse('queryByWeights');\n }\n\n const list = SearchSettingsUtility.toList({ record: fixed.queryByWeights, names });\n\n if (!list) {\n throw notNamed('queryByWeights');\n }\n\n next['queryByWeights'] = list;\n } else if (!input.queryByWeights && defaults.queryByWeights) {\n const list = SearchSettingsUtility.toList({ record: defaults.queryByWeights, names });\n\n if (list) {\n next['queryByWeights'] = list;\n }\n }\n }\n\n // One sort: `order` and `tuning.sortBy` are the same setting, whichever layer gives it.\n const sortOf = (layer: ISearchLooseSettings) =>\n layer.order ?? (layer.tuning?.['sortBy'] !== undefined ? layer.tuning['sortBy'] : undefined);\n const clientOrder = input.filter?.order;\n const hasClientOrder = clientOrder !== undefined && clientOrder.length > 0;\n\n if (sortOf(fixed) !== undefined && hasClientOrder) {\n throw refuse('filter.order');\n }\n\n const sort = sortOf(fixed) ?? (hasClientOrder ? undefined : sortOf(defaults));\n\n const serverOrder = Array.isArray(sort) ? sort : undefined;\n\n if (serverOrder) {\n next['filter'] = { ...input.filter, order: serverOrder };\n }\n\n const tuning: Record<string, unknown> = {};\n const clientTuning = input.engineParams ?? {};\n\n if (sort !== undefined && !Array.isArray(sort)) {\n tuning['sortBy'] = sort;\n serverTuning['sortBy'] = sort;\n }\n\n const tuningNames = new Set([\n ...Object.keys(fixed.tuning ?? {}),\n ...Object.keys(clientTuning),\n ...Object.keys(defaults.tuning ?? {}),\n ]);\n\n for (const name of tuningNames) {\n if (name === 'sortBy') {\n continue;\n }\n\n if (fixed.tuning?.[name] !== undefined) {\n if (\n Object.keys(clientTuning).some((sent) =>\n SearchEngineParams.isSameName({ left: sent, right: name }),\n )\n ) {\n throw refuse(`tuning '${name}'`);\n }\n\n // A semantic search has no `queryBy`, so a keyed knob has nothing to align to: it is left out, as a fixed `queryBy` is.\n if (\n input.mode === SearchModes.SEMANTIC &&\n RecordUtility.isPlainRecord(fixed.tuning[name])\n ) {\n continue;\n }\n\n const value = SearchSettingsUtility.toKnob({ value: fixed.tuning[name], names });\n\n if (value === undefined) {\n throw notNamed(`tuning '${name}'`);\n }\n\n tuning[name] = value;\n serverTuning[name] = value;\n } else if (name in clientTuning) {\n tuning[name] = clientTuning[name];\n } else {\n if (\n input.mode === SearchModes.SEMANTIC &&\n RecordUtility.isPlainRecord(defaults.tuning?.[name])\n ) {\n continue;\n }\n\n const value = SearchSettingsUtility.toKnob({ value: defaults.tuning?.[name], names });\n\n if (value !== undefined) {\n tuning[name] = value;\n serverTuning[name] = value;\n }\n }\n }\n\n if (Object.keys(tuning).length > 0) {\n next['engineParams'] = tuning;\n }\n\n return { input: next, serverTuning, serverOrder };\n }\n\n /**\n * The input with the query text `query.normalize` returned: `query` of a keyword or hybrid request, `queryText` of a\n * semantic one. A request without text is left as it is. A throw, or a result that is not a string, answers 500: the\n * function is the server's.\n */\n static async normalize<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n >(opts: {\n query: ISearchResolvedQuery<RouteEnv, TExtra, Inject>;\n context: TRouteContext<RouteEnv>;\n input: TNonRawInput & TExtra;\n injected: TInjected<Inject>;\n }): Promise<TNonRawInput & TExtra> {\n const { query, context, input, injected } = opts;\n const text = input.mode === SearchModes.SEMANTIC ? input.queryText : input.query;\n\n if (!query.normalize || text === undefined) {\n return input;\n }\n\n let normalized: unknown;\n\n try {\n const result = await query.normalize({ text, context, input, injected });\n normalized = result;\n } catch (error) {\n throw SearchSettingsUtility.fail({\n scope: 'search | query.normalize',\n message: 'the normalize function threw',\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n cause: error,\n });\n }\n\n if (typeof normalized !== 'string') {\n throw SearchSettingsUtility.fail({\n scope: 'search | query.normalize',\n message: `the normalize function must return a string | got: ${typeof normalized}`,\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n });\n }\n\n return input.mode === SearchModes.SEMANTIC\n ? { ...input, queryText: normalized }\n : { ...input, query: normalized };\n }\n\n /**\n * The input of a request with the controller's `query` settings applied. What the server chose is checked with the engine's\n * own converter before the repository runs, so a bad value (`numTypos: -1`) is the server's 500 and not the client's 400.\n * The result is parsed with `SearchInputSchema`, which also drops the keys `request.body.extend` added.\n */\n static async apply<\n RouteEnv extends Env = Env,\n TExtra extends object = {},\n Inject extends TInjectMap = {},\n >(opts: {\n query: ISearchResolvedQuery<RouteEnv, TExtra, Inject>;\n context: TRouteContext<RouteEnv>;\n input: TSearchInput & TExtra;\n injected: TInjected<Inject>;\n dialect: ISearchQueryDialect;\n }): Promise<TSearchInput> {\n const { query, context, input: received, injected, dialect } = opts;\n\n if (received.mode === SearchModes.RAW) {\n return received;\n }\n\n // First: every function source below reads the text `normalize` returns.\n const input = await SearchSettingsUtility.normalize({\n query,\n context,\n input: received,\n injected,\n });\n\n const [fixed, defaults] = await Promise.all([\n SearchSettingsUtility.resolveSource({\n source: query.fixed,\n context,\n input,\n injected,\n query,\n isFixed: true,\n }),\n SearchSettingsUtility.resolveSource({\n source: query.default,\n context,\n input,\n injected,\n query,\n isFixed: false,\n }),\n ]);\n const merged = SearchSettingsUtility.merge({\n input,\n fixed,\n defaults,\n catalog: query.catalog,\n });\n\n if (Object.keys(merged.serverTuning).length > 0 || merged.serverOrder !== undefined) {\n try {\n dialect.toWireParams({ query: { engineParams: merged.serverTuning } });\n\n if (merged.serverOrder !== undefined) {\n dialect.build({ filter: { order: merged.serverOrder } });\n }\n } catch (error) {\n throw SearchSettingsUtility.fail({\n scope: 'search | query',\n message: 'the engine refuses the sort or tuning the server chose',\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n cause: error,\n });\n }\n }\n\n return SearchInputSchema.parse(merged.input);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-connectors",
3
- "version": "0.5.0-2",
3
+ "version": "0.5.0-3",
4
4
  "description": "Datasource and repository connectors for the IGNIS framework: the engine-neutral relational and search tiers, plus Postgres, SQLite, PGlite, Typesense and Meilisearch behind sub-paths.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -98,15 +98,15 @@
98
98
  },
99
99
  "dependencies": {
100
100
  "@venizia/ignis-filter": "0.5.0-0",
101
- "@venizia/ignis-helpers": "0.5.0-0",
101
+ "@venizia/ignis-helpers": "0.5.0-1",
102
102
  "@venizia/ignis-inversion": "0.5.0-0",
103
- "@venizia/ignis-kernel": "0.5.0-1",
103
+ "@venizia/ignis-kernel": "0.5.0-2",
104
104
  "zod": "^4.6.7"
105
105
  },
106
106
  "devDependencies": {
107
- "@types/bun": "^1.4.3",
107
+ "@types/bun": "^1.4.5",
108
108
  "@types/pg": "^8.23.1",
109
- "@venizia/dev-configs": "0.5.0-1",
109
+ "@venizia/dev-configs": "0.5.0-2",
110
110
  "eslint": "^10.13.0",
111
111
  "oxlint": "1.89.0",
112
112
  "oxlint-tsgolint": "7.0.2004",
@@ -1,3 +0,0 @@
1
- /** The reader lives with the server contract, so a client without this connector shares it. */
2
- export { HttpResponseReader } from '@venizia/ignis-kernel/repository';
3
- //# sourceMappingURL=readers.d.ts.map
@@ -1,3 +0,0 @@
1
- /** The reader lives with the server contract, so a client without this connector shares it. */
2
- export { HttpResponseReader } from '@venizia/ignis-kernel/repository';
3
- //# sourceMappingURL=readers.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"readers.js","sourceRoot":"","sources":["../../../../src/http/common/readers.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC","sourcesContent":["/** The reader lives with the server contract, so a client without this connector shares it. */\nexport { HttpResponseReader } from '@venizia/ignis-kernel/repository';\n"]}