@venizia/ignis-connectors 0.4.8-12 → 0.4.8-14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/http/common/types.d.ts +4 -0
- package/dist/esm/http/common/types.js.map +1 -1
- package/dist/esm/http/common/wire.d.ts +5 -0
- package/dist/esm/http/common/wire.js +6 -0
- package/dist/esm/http/common/wire.js.map +1 -1
- package/dist/esm/http/datasource.d.ts +2 -4
- package/dist/esm/http/datasource.js +7 -11
- package/dist/esm/http/datasource.js.map +1 -1
- package/dist/esm/search/core/controllers/abstract.d.ts +7 -3
- package/dist/esm/search/core/controllers/abstract.js +6 -1
- package/dist/esm/search/core/controllers/abstract.js.map +1 -1
- package/dist/esm/search/core/controllers/factory.d.ts +29 -4
- package/dist/esm/search/core/controllers/factory.js +25 -2
- package/dist/esm/search/core/controllers/factory.js.map +1 -1
- package/dist/esm/search/core/controllers/scope.d.ts +6 -4
- package/dist/esm/search/core/controllers/scope.js +1 -1
- package/dist/esm/search/core/controllers/scope.js.map +1 -1
- package/package.json +6 -6
|
@@ -57,7 +57,11 @@ export interface IHttpDataSourceSettings {
|
|
|
57
57
|
authTokenResolver?: TAuthTokenResolver;
|
|
58
58
|
/** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. */
|
|
59
59
|
onUnauthorized?: (context: IHttpRequestContext) => Promise<boolean> | boolean;
|
|
60
|
+
/** What sends a request: the platform `fetch` when unset. Name one to route through a test double, a proxy or an instrumented client. */
|
|
61
|
+
fetch?: THttpFetch;
|
|
60
62
|
}
|
|
63
|
+
/** The part of `fetch` the data source uses: a URL and its init, a `Response` back. */
|
|
64
|
+
export type THttpFetch = (url: string, init: RequestInit) => Promise<Response>;
|
|
61
65
|
/** A list with no `Content-Range` has no total - `hasRange` says so rather than using the page size. */
|
|
62
66
|
export interface IHttpReadResult<R> {
|
|
63
67
|
data: R;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/http/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TFilter } from '@venizia/ignis-filter';\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/** The request a hook is asked about: 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/** `undefined` means no token for this request. A throw fails the request with that error. */\nexport type TAuthTokenResolver = (context: IHttpRequestContext) => IAuthToken | undefined;\n\n/** Headers for this request. A throw fails the request with that error. */\nexport type THttpHeadersResolver = (context: IHttpRequestContext) => THttpHeaders | undefined;\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 * Run on every send, the 401 retry included. Wins over `headers`; a call's own headers win over\n * it. `x-request-count` is refused here too; an `authorization` here stands only when no token is\n * resolved.\n */\n headersResolver?: THttpHeadersResolver;\n\n /** Wins over `authTokenResolver`, and is sent whatever the request. */\n authToken?: IAuthToken;\n\n /** Run on every send, the 401 retry included. */\n authTokenResolver?: TAuthTokenResolver;\n\n /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. */\n onUnauthorized?: (context: IHttpRequestContext) => Promise<boolean> | boolean;\n}\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/** The query a repository call sends: an optional `filter` typed against the entity `E`. */\nexport type THttpQuery<E extends object> = { filter?: TFilter<E> };\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 { TFilter } from '@venizia/ignis-filter';\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/** The request a hook is asked about: 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/** `undefined` means no token for this request. A throw fails the request with that error. */\nexport type TAuthTokenResolver = (context: IHttpRequestContext) => IAuthToken | undefined;\n\n/** Headers for this request. A throw fails the request with that error. */\nexport type THttpHeadersResolver = (context: IHttpRequestContext) => THttpHeaders | undefined;\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 * Run on every send, the 401 retry included. Wins over `headers`; a call's own headers win over\n * it. `x-request-count` is refused here too; an `authorization` here stands only when no token is\n * resolved.\n */\n headersResolver?: THttpHeadersResolver;\n\n /** Wins over `authTokenResolver`, and is sent whatever the request. */\n authToken?: IAuthToken;\n\n /** Run on every send, the 401 retry included. */\n authTokenResolver?: TAuthTokenResolver;\n\n /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. */\n onUnauthorized?: (context: IHttpRequestContext) => 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/** The part of `fetch` the data source uses: a URL and its init, a `Response` back. */\nexport type THttpFetch = (url: string, init: RequestInit) => Promise<Response>;\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/** The query a repository call sends: an optional `filter` typed against the entity `E`. */\nexport type THttpQuery<E extends object> = { filter?: TFilter<E> };\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"]}
|
|
@@ -21,6 +21,11 @@ export declare class HttpWire {
|
|
|
21
21
|
entries: Array<[string, string]>;
|
|
22
22
|
name: string;
|
|
23
23
|
}): void;
|
|
24
|
+
/** `baseUrl` (no trailing slash) followed by each path with one leading slash: `('/api/', ['a', '/b'])` is `/api/a/b`. */
|
|
25
|
+
static toRequestUrl(opts: {
|
|
26
|
+
baseUrl: string;
|
|
27
|
+
paths: Array<string>;
|
|
28
|
+
}): string;
|
|
24
29
|
/**
|
|
25
30
|
* The body as `fetch` takes it. Anything `fetch` already sends as a body passes through untouched;
|
|
26
31
|
* any other object is JSON. Serialised ONCE, so the 401 retry sends the same bytes.
|
|
@@ -41,6 +41,12 @@ export class HttpWire {
|
|
|
41
41
|
});
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
+
/** `baseUrl` (no trailing slash) followed by each path with one leading slash: `('/api/', ['a', '/b'])` is `/api/a/b`. */
|
|
45
|
+
static toRequestUrl(opts) {
|
|
46
|
+
const { baseUrl, paths } = opts;
|
|
47
|
+
const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
|
|
48
|
+
return `${base}${paths.map((path) => (path.startsWith('/') ? path : `/${path}`)).join('')}`;
|
|
49
|
+
}
|
|
44
50
|
/**
|
|
45
51
|
* The body as `fetch` takes it. Anything `fetch` already sends as a body passes through untouched;
|
|
46
52
|
* any other object is JSON. Serialised ONCE, so the 401 retry sends the same bytes.
|
|
@@ -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,CAA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G,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 } 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,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,gBAA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'./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 /** `baseUrl` (no trailing slash) followed by each path with one leading slash: `('/api/', ['a', '/b'])` is `/api/a/b`. */\n static toRequestUrl(opts: { baseUrl: string; paths: Array<string> }): string {\n const { baseUrl, paths } = opts;\n const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n\n return `${base}${paths.map((path) => (path.startsWith('/') ? path : `/${path}`)).join('')}`;\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,13 +1,11 @@
|
|
|
1
1
|
import { type THttpReadShape } from './common/constants.js';
|
|
2
|
-
import {
|
|
3
|
-
import { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
|
|
2
|
+
import { DataSourceRoot } from '@venizia/ignis-kernel/repository';
|
|
4
3
|
import type { IAuthToken, IHttpCallOptions, IHttpDataSourceSettings, TExtraRequest, IHttpReadResult, IHttpRequestContext, IHttpWriteResult, THttpBody } from './common/types.js';
|
|
5
4
|
/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */
|
|
6
|
-
export declare class HttpDataSource extends
|
|
5
|
+
export declare class HttpDataSource extends DataSourceRoot<IHttpDataSourceSettings> {
|
|
7
6
|
name: string;
|
|
8
7
|
settings: IHttpDataSourceSettings;
|
|
9
8
|
schema: never;
|
|
10
|
-
protected network: NodeFetchNetworkRequest;
|
|
11
9
|
/** Normalised once: every request copies these, never re-parses `settings.headers`. */
|
|
12
10
|
protected configuredHeaders: Array<[string, string]>;
|
|
13
11
|
/** Decided once: a relative baseUrl (`/api`) is resolved against the page origin on every request. */
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { EchoUtility } from '../common/internal/index.js';
|
|
2
2
|
import { HttpReadShapes } from './common/constants.js';
|
|
3
|
-
import {
|
|
3
|
+
import { DataSourceRoot } from '@venizia/ignis-kernel/repository';
|
|
4
4
|
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
5
|
-
import { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
|
|
6
5
|
import { getError } from '@venizia/ignis-helpers/core';
|
|
7
6
|
import { HttpResponseReader } from './common/readers.js';
|
|
8
7
|
import { HttpWire } from './common/wire.js';
|
|
@@ -17,7 +16,7 @@ const MAX_ECHOED_PATH_LENGTH = 200;
|
|
|
17
16
|
/** A segment that is `.` or `..` once its `%2e` is decoded. */
|
|
18
17
|
const DOT_SEGMENT_PATTERN = /^(?:\.|%2e){1,2}$/i;
|
|
19
18
|
/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */
|
|
20
|
-
export class HttpDataSource extends
|
|
19
|
+
export class HttpDataSource extends DataSourceRoot {
|
|
21
20
|
constructor(opts) {
|
|
22
21
|
super({ scope: opts.name ?? HttpDataSource.name });
|
|
23
22
|
this.schema = {};
|
|
@@ -42,10 +41,6 @@ export class HttpDataSource extends AbstractDataSource {
|
|
|
42
41
|
this.configuredHeaders = configured;
|
|
43
42
|
this.name = name;
|
|
44
43
|
this.settings = settings;
|
|
45
|
-
this.network = new NodeFetchNetworkRequest({
|
|
46
|
-
name,
|
|
47
|
-
networkOptions: { baseUrl: settings.baseUrl },
|
|
48
|
-
});
|
|
49
44
|
}
|
|
50
45
|
async configure() { }
|
|
51
46
|
getCapabilities() {
|
|
@@ -137,7 +132,7 @@ export class HttpDataSource extends AbstractDataSource {
|
|
|
137
132
|
buildUrl(opts) {
|
|
138
133
|
const { paths, query } = opts;
|
|
139
134
|
this.assertPathsStayUnderBase({ paths });
|
|
140
|
-
const requestUrl =
|
|
135
|
+
const requestUrl = HttpWire.toRequestUrl({ baseUrl: this.settings.baseUrl, paths });
|
|
141
136
|
// A page or a Web Worker has an origin to resolve '/api' against; a server has none.
|
|
142
137
|
const origin = this.isRelativeBaseUrl ? this.resolveLocationOrigin() : undefined;
|
|
143
138
|
if (this.isRelativeBaseUrl && !origin) {
|
|
@@ -175,9 +170,10 @@ export class HttpDataSource extends AbstractDataSource {
|
|
|
175
170
|
const context = { paths: opts.paths, method, url, signal };
|
|
176
171
|
const { payload, isJson, isFormData } = HttpWire.toRequestBody({ body: opts.body });
|
|
177
172
|
// Both hooks run inside `send`, so the retry sends what they answer after the refresh.
|
|
178
|
-
const send = () =>
|
|
179
|
-
|
|
180
|
-
|
|
173
|
+
const send = () =>
|
|
174
|
+
// The platform `fetch` unless the settings name a sender; looked up per call, so a test that swaps the global is heard.
|
|
175
|
+
(this.settings.fetch ?? fetch)(url, {
|
|
176
|
+
method: method.toUpperCase(),
|
|
181
177
|
body: payload,
|
|
182
178
|
signal,
|
|
183
179
|
headers: this.buildHeaders({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datasource.js","sourceRoot":"","sources":["../../../src/http/datasource.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAuB,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6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AM,IAAI,CAAC,eAAe,CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;YAC5E,MAAM,MAAM,CAAC;QACf,CAAC;QAED,gEAAgE;QAChE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QACzE,MAAM,EAAE,KAAK,EAAE,GAAG,kBAAkB,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;QAC5F,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;QAE1C,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QAC3E,MAAM,OAAO,GAAG,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QAExE,OAAO;YACL,IAAI;YACJ,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;gBAC7B,CAAC,CAAC,OAAO;gBACT,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;oBACnB,CAAC,CAAC,IAAI,CAAC,MAAM;oBACb,CAAC,CAAC,IAAI,KAAK,IAAI;wBACb,CAAC,CAAC,CAAC;wBACH,CAAC,CAAC,CAAC;YACT,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { EchoUtility } from '@/common/internal';\nimport { HttpReadShapes, type THttpReadShape } from './common/constants';\nimport { AbstractDataSource } from '@venizia/ignis-kernel/repository';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HttpResponseReader } from './common/readers';\nimport type {\n IAuthToken,\n IHttpCallOptions,\n IHttpDataSourceSettings,\n TExtraRequest,\n IHttpReadResult,\n IHttpRequestContext,\n IHttpWriteResult,\n THttpBody,\n} from './common/types';\nimport { HttpWire } from './common/wire';\n\n/** A scheme and `//` make a URL absolute - `localhost:3000` has neither. Read by pattern: `URL.canParse` needs Safari 17 or Chrome 120, and this runs in pages. */\nconst ABSOLUTE_URL_PATTERN = /^[a-z][a-z\\d+.-]*:\\/\\//i;\n\n/** A backslash is a separator to the URL parser, and a control character (a tab or a newline inside `.<TAB>.`) is dropped by it: neither may hide a dot segment. `%5c` is the encoded backslash. */\nconst UNSAFE_REQUEST_PATH_PATTERN = /[\\p{Cc}\\\\]|%5c/iu;\n\n/** What ends a path segment for the URL parser: a slash, a `?` or a `#` (it ends the path itself, so `..?` is a `..` segment), and the encoded slash, which a server may decode into a separator. */\nconst REQUEST_PATH_SEPARATOR_PATTERN = /[/?#]|%2f/i;\n\n/** The longest part of a refused path an error message copies: a huge path is not copied whole into the error and the log. */\nconst MAX_ECHOED_PATH_LENGTH = 200;\n\n/** A segment that is `.` or `..` once its `%2e` is decoded. */\nconst DOT_SEGMENT_PATTERN = /^(?:\\.|%2e){1,2}$/i;\n\n/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */\nexport class HttpDataSource extends AbstractDataSource<IHttpDataSourceSettings> {\n override name: string;\n override settings: IHttpDataSourceSettings;\n override schema = {} as never;\n\n protected network: NodeFetchNetworkRequest;\n /** Normalised once: every request copies these, never re-parses `settings.headers`. */\n protected configuredHeaders: Array<[string, string]>;\n /** Decided once: a relative baseUrl (`/api`) is resolved against the page origin on every request. */\n protected isRelativeBaseUrl: boolean;\n\n constructor(opts: IHttpDataSourceSettings & { name?: string }) {\n super({ scope: opts.name ?? HttpDataSource.name });\n\n const { name = 'http', ...settings } = opts;\n\n const configured = HttpWire.toHeaderEntries({ headers: settings.headers });\n HttpWire.assertNoRequestCountHeader({ entries: configured, name });\n\n this.isRelativeBaseUrl = !ABSOLUTE_URL_PATTERN.test(settings.baseUrl);\n\n // Against the page, `api` would follow the current route; `localhost:3000` is not a URL at all.\n if (this.isRelativeBaseUrl && !settings.baseUrl.startsWith('/')) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] baseUrl '${settings.baseUrl}' is neither absolute nor a path from the origin | Pass '/api' or an absolute URL such as 'https://api.example.com'`,\n });\n }\n\n // A `?` or `#` in the base would swallow the request paths into the query or the fragment.\n if (/[?#]/.test(settings.baseUrl)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] baseUrl must not carry a query or a fragment: the request paths would end up inside it | Pass the base without '?' or '#', and use the call's query option`,\n });\n }\n\n this.configuredHeaders = configured;\n this.name = name;\n this.settings = settings;\n this.network = new NodeFetchNetworkRequest({\n name,\n networkOptions: { baseUrl: settings.baseUrl },\n });\n }\n\n async configure(): Promise<void> {}\n\n override getCapabilities() {\n return { transactions: false };\n }\n\n protected resolveAuthToken(opts: { context: IHttpRequestContext }): IAuthToken | undefined {\n return this.settings.authToken ?? this.settings.authTokenResolver?.(opts.context);\n }\n\n /** Re-run on every send, so a header the app changed since the last request is the one sent. */\n protected resolveHeaders(opts: { context: IHttpRequestContext }): Array<[string, string]> {\n const resolver = this.settings.headersResolver;\n\n if (!resolver) {\n return [];\n }\n\n const entries = HttpWire.toHeaderEntries({ headers: resolver(opts.context) });\n HttpWire.assertNoRequestCountHeader({ entries, name: this.name });\n\n return entries;\n }\n\n protected buildHeaders(opts: {\n token?: IAuthToken;\n requestHeaders?: Array<[string, string]>;\n isJsonBody?: boolean;\n isFormDataBody?: boolean;\n }): Headers {\n const { token, requestHeaders, isJsonBody, isFormDataBody } = opts;\n const headers = new Headers(this.configuredHeaders);\n\n // A request's own headers win over the configured ones; the connector's below win over both.\n for (const [name, value] of requestHeaders ?? []) {\n headers.set(name, value);\n }\n\n if (isJsonBody && !headers.has(HTTP.Headers.CONTENT_TYPE)) {\n headers.set(HTTP.Headers.CONTENT_TYPE, 'application/json');\n }\n\n // Only `fetch` knows the multipart boundary; any other content-type here would drop it.\n if (isFormDataBody) {\n headers.delete(HTTP.Headers.CONTENT_TYPE);\n }\n\n // Set last: under the envelope a record read answers `{ count, data }`.\n headers.set(HTTP.Headers.REQUEST_COUNT_DATA, 'false');\n\n if (!token) {\n return headers;\n }\n\n headers.set(HTTP.Headers.AUTHORIZATION, `${token.type ?? 'Bearer'} ${token.value}`);\n\n // Unconditionally it would send the string \"undefined\".\n if (token.provider) {\n headers.set('x-auth-provider', token.provider);\n }\n\n return headers;\n }\n\n /** The browser global `location` is not declared for a server build, so it is probed, not assumed. */\n protected resolveLocationOrigin(): string | undefined {\n const location: unknown = Reflect.get(globalThis, 'location');\n\n if (typeof location !== 'object' || location === null || !('origin' in location)) {\n return undefined;\n }\n\n return typeof location.origin === 'string' ? location.origin : undefined;\n }\n\n /** The path as an error message quotes it: cut at 200 characters, with an ellipsis. */\n protected static toEchoedPath(opts: { path: string }): string {\n const { path } = opts;\n\n return path.length > MAX_ECHOED_PATH_LENGTH\n ? `${path.slice(0, MAX_ECHOED_PATH_LENGTH)}…`\n : path;\n }\n\n /** The request paths name a place under the base path, so none may be a dot segment, hide one, or carry a separator the URL parser would read differently from a server. */\n protected assertPathsStayUnderBase(opts: { paths: Array<string> }): void {\n for (const path of opts.paths) {\n const segments = path.split(REQUEST_PATH_SEPARATOR_PATTERN);\n const isEscaping =\n UNSAFE_REQUEST_PATH_PATTERN.test(path) ||\n // A trailing space is stripped from the whole URL by the parser, so `.. ` ends as `..`.\n segments.some((segment) => DOT_SEGMENT_PATTERN.test(segment.trimEnd()));\n\n if (isEscaping) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[${this.name}] A request path must stay under the base path: no dot segment, backslash or control character | path: '${EchoUtility.toSafeEcho({ value: HttpDataSource.toEchoedPath({ path }) })}'`,\n });\n }\n }\n }\n\n /** The resolved URL, whatever built it, is on the base's origin and under its path: the check that holds when the text checks above miss a form. */\n protected assertUnderBase(opts: { url: URL; origin?: string }): void {\n const { url, origin } = opts;\n const base = new URL(this.settings.baseUrl, origin);\n const basePath = base.pathname.replace(/\\/+$/, '');\n const isUnderBase =\n url.origin === base.origin &&\n (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`));\n\n if (!isUnderBase) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[${this.name}] A request path must stay under the base path: the URL left the origin or the base path`,\n });\n }\n }\n\n buildUrl(opts: { paths: Array<string>; query?: Record<string, unknown> }): string {\n const { paths, query } = opts;\n this.assertPathsStayUnderBase({ paths });\n\n const requestUrl = this.network.getRequestUrl({ paths });\n\n // A page or a Web Worker has an origin to resolve '/api' against; a server has none.\n const origin = this.isRelativeBaseUrl ? this.resolveLocationOrigin() : undefined;\n\n if (this.isRelativeBaseUrl && !origin) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${this.name}] Relative baseUrl '${this.settings.baseUrl}' needs a page or worker location to resolve against, and there is none here | Pass an absolute baseUrl such as 'https://api.example.com'`,\n });\n }\n\n const url = new URL(requestUrl, origin);\n this.assertUnderBase({ url, origin });\n\n const parameters = Object.entries(query ?? {});\n\n for (const [key, value] of parameters) {\n if (value === undefined) {\n continue;\n }\n\n url.searchParams.set(\n key,\n typeof value === 'string'\n ? value\n : HttpWire.toJson({ value, label: `[${this.name}] Query parameter '${key}'` }),\n );\n }\n\n return url.toString();\n }\n\n /**\n * The raw `Response`, on any method - for what the repository verbs do not cover, like an export\n * or a PUT to a hand-written route. Auth and the 401 retry apply; the retry resends the same body.\n */\n async request(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n return this.sendRequest({ ...opts, url: this.buildUrl(opts) });\n }\n\n /** `request` on a URL already built: `read` and `write` serialise a long query once, not per use. */\n protected async sendRequest(\n opts: {\n paths: Array<string>;\n url: string;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n const { url, signal } = opts;\n const requestHeaders = HttpWire.toHeaderEntries({ headers: opts.headers });\n HttpWire.assertNoRequestCountHeader({ entries: requestHeaders, name: this.name });\n\n const method = opts.method ?? HTTP.Methods.GET;\n const context: IHttpRequestContext = { paths: opts.paths, method, url, signal };\n const { payload, isJson, isFormData } = HttpWire.toRequestBody({ body: opts.body });\n\n // Both hooks run inside `send`, so the retry sends what they answer after the refresh.\n const send = () =>\n this.network.getNetworkService().send({\n url,\n method: method as never,\n body: payload,\n signal,\n headers: this.buildHeaders({\n token: this.resolveAuthToken({ context }),\n // Resolved first, so the call's own headers win over them.\n requestHeaders: [...this.resolveHeaders({ context }), ...requestHeaders],\n isJsonBody: isJson,\n isFormDataBody: isFormData,\n }),\n });\n\n let response = await send();\n\n if (response.status === HTTP.ResultCodes.RS_4.Unauthorized && this.settings.onUnauthorized) {\n const shouldRetry = await this.settings.onUnauthorized(context);\n\n // A call aborted while the session refreshed is not sent again.\n if (shouldRetry) {\n signal?.throwIfAborted();\n const result = await send();\n response = result;\n }\n }\n\n return response;\n }\n\n /**\n * The body as JSON, `null` when there is none; a body that is not JSON is the server's fault, named\n * as such. Its content stays out of the message, which a relaying server may pass to its clients.\n */\n protected async readJsonBody(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const text = await response.text();\n\n if (!text) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.BadGateway,\n message: `[${this.name}][${verb}] ${response.status} | ${HttpWire.describeUrl({ url, status: response.status })} | The response body is not JSON (${text.length} chars, content-type: ${response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? 'none'})`,\n });\n }\n }\n\n /**\n * A failed response as the error the server threw: its status, code, args and text, and its\n * `extra` with the `requestId` added. `message` adds where it failed, for logs; `normalized.text`\n * stays the server's, for display - `HTTP <status>` when the server sent none. `cause` is the server's `details.cause` - a 422's per-field\n * issues, `{ path, message, code }`.\n */\n protected async toResponseError(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const described = HttpWire.describeUrl({ url, status: response.status });\n\n return HttpResponseReader.toApplicationError({\n response,\n rootKey: this.settings.errorRootKey,\n context: `[${this.name}][${verb}] ${response.status} | ${described}`,\n });\n }\n\n /**\n * Rows plus the total from `Content-Range`, reported absent when the header is. A GET unless told\n * otherwise: `method` and `body` reach a list route a service wrote to take its filter in a body.\n */\n async read<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n shape?: THttpReadShape;\n method?: string;\n body?: THttpBody;\n /** Extras the route offers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n /** The rows alone: every default extra off (`-*`), for a read that only counts or probes. */\n isEveryDefaultOff?: boolean;\n } & IHttpCallOptions,\n ): Promise<IHttpReadResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({\n headers: opts.headers,\n extra: opts.extra,\n isEveryDefaultOff: opts.isEveryDefaultOff,\n });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'read' });\n throw result;\n }\n\n // A 204 or an empty body is no row; a list asked for of it still throws below.\n const parsed = await this.readJsonBody({ response, url, verb: 'read' });\n const { body, extra } = HttpResponseReader.readExtra({\n body: parsed,\n headers: response.headers,\n });\n const contentRange = response.headers.get(HTTP.Headers.CONTENT_RANGE) ?? undefined;\n const range = HttpResponseReader.parseContentRange({ header: contentRange });\n const data = HttpWire.unwrapRows<R>({ body, shape: opts.shape ?? HttpReadShapes.LIST, url });\n\n return {\n data,\n hasRange: range !== undefined,\n contentRange,\n total: range?.total,\n skip: range?.skip,\n dataLength: Array.isArray(data) ? data.length : data === null ? 0 : 1,\n extra,\n };\n }\n\n /**\n * A write, and what it answered: the body as the rows, the count from `x-response-count`. The\n * connector asks for bare rows, so an IGNIS write answers the row or the rows, never the envelope.\n */\n async write<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method: string;\n body?: THttpBody;\n /** Extras the route answers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n } & IHttpCallOptions,\n ): Promise<IHttpWriteResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({ headers: opts.headers, extra: opts.extra });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'write' });\n throw result;\n }\n\n // A 204, or a route that answers nothing, has no body to parse.\n const parsed = await this.readJsonBody({ response, url, verb: 'write' });\n const { extra } = HttpResponseReader.readExtra({ body: parsed, headers: response.headers });\n const data = extra ? parsed.data : parsed;\n\n const countHeader = response.headers.get(HTTP.Headers.RESPONSE_COUNT_DATA);\n const counted = countHeader === null ? Number.NaN : Number(countHeader);\n\n return {\n data,\n count: Number.isFinite(counted)\n ? counted\n : Array.isArray(data)\n ? data.length\n : data === null\n ? 0\n : 1,\n ...(extra ? { extra } : {}),\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"datasource.js","sourceRoot":"","sources":["../../../src/http/datasource.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAuB,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;A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I,CAAC,YAAY,CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QACzE,MAAM,EAAE,KAAK,EAAE,GAAG,kBAAkB,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;QAC5F,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;QAE1C,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QAC3E,MAAM,OAAO,GAAG,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QAExE,OAAO;YACL,IAAI;YACJ,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;gBAC7B,CAAC,CAAC,OAAO;gBACT,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;oBACnB,CAAC,CAAC,IAAI,CAAC,MAAM;oBACb,CAAC,CAAC,IAAI,KAAK,IAAI;wBACb,CAAC,CAAC,CAAC;wBACH,CAAC,CAAC,CAAC;YACT,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { EchoUtility } from '@/common/internal';\nimport { HttpReadShapes, type THttpReadShape } from './common/constants';\nimport { DataSourceRoot } from '@venizia/ignis-kernel/repository';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HttpResponseReader } from './common/readers';\nimport type {\n IAuthToken,\n IHttpCallOptions,\n IHttpDataSourceSettings,\n TExtraRequest,\n IHttpReadResult,\n IHttpRequestContext,\n IHttpWriteResult,\n THttpBody,\n} from './common/types';\nimport { HttpWire } from './common/wire';\n\n/** A scheme and `//` make a URL absolute - `localhost:3000` has neither. Read by pattern: `URL.canParse` needs Safari 17 or Chrome 120, and this runs in pages. */\nconst ABSOLUTE_URL_PATTERN = /^[a-z][a-z\\d+.-]*:\\/\\//i;\n\n/** A backslash is a separator to the URL parser, and a control character (a tab or a newline inside `.<TAB>.`) is dropped by it: neither may hide a dot segment. `%5c` is the encoded backslash. */\nconst UNSAFE_REQUEST_PATH_PATTERN = /[\\p{Cc}\\\\]|%5c/iu;\n\n/** What ends a path segment for the URL parser: a slash, a `?` or a `#` (it ends the path itself, so `..?` is a `..` segment), and the encoded slash, which a server may decode into a separator. */\nconst REQUEST_PATH_SEPARATOR_PATTERN = /[/?#]|%2f/i;\n\n/** The longest part of a refused path an error message copies: a huge path is not copied whole into the error and the log. */\nconst MAX_ECHOED_PATH_LENGTH = 200;\n\n/** A segment that is `.` or `..` once its `%2e` is decoded. */\nconst DOT_SEGMENT_PATTERN = /^(?:\\.|%2e){1,2}$/i;\n\n/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */\nexport class HttpDataSource extends 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 /** Decided once: a relative baseUrl (`/api`) is resolved against the page origin on every request. */\n protected isRelativeBaseUrl: boolean;\n\n constructor(opts: IHttpDataSourceSettings & { name?: string }) {\n super({ scope: opts.name ?? HttpDataSource.name });\n\n const { name = 'http', ...settings } = opts;\n\n const configured = HttpWire.toHeaderEntries({ headers: settings.headers });\n HttpWire.assertNoRequestCountHeader({ entries: configured, name });\n\n this.isRelativeBaseUrl = !ABSOLUTE_URL_PATTERN.test(settings.baseUrl);\n\n // Against the page, `api` would follow the current route; `localhost:3000` is not a URL at all.\n if (this.isRelativeBaseUrl && !settings.baseUrl.startsWith('/')) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] baseUrl '${settings.baseUrl}' is neither absolute nor a path from the origin | Pass '/api' or an absolute URL such as 'https://api.example.com'`,\n });\n }\n\n // A `?` or `#` in the base would swallow the request paths into the query or the fragment.\n if (/[?#]/.test(settings.baseUrl)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${name}] baseUrl must not carry a query or a fragment: the request paths would end up inside it | Pass the base without '?' or '#', and use the call's query option`,\n });\n }\n\n this.configuredHeaders = configured;\n this.name = name;\n this.settings = settings;\n }\n\n async configure(): Promise<void> {}\n\n override getCapabilities() {\n return { transactions: false };\n }\n\n protected resolveAuthToken(opts: { context: IHttpRequestContext }): IAuthToken | undefined {\n return this.settings.authToken ?? this.settings.authTokenResolver?.(opts.context);\n }\n\n /** Re-run on every send, so a header the app changed since the last request is the one sent. */\n protected resolveHeaders(opts: { context: IHttpRequestContext }): Array<[string, string]> {\n const resolver = this.settings.headersResolver;\n\n if (!resolver) {\n return [];\n }\n\n const entries = HttpWire.toHeaderEntries({ headers: resolver(opts.context) });\n HttpWire.assertNoRequestCountHeader({ entries, name: this.name });\n\n return entries;\n }\n\n protected buildHeaders(opts: {\n token?: IAuthToken;\n requestHeaders?: Array<[string, string]>;\n isJsonBody?: boolean;\n isFormDataBody?: boolean;\n }): Headers {\n const { token, requestHeaders, isJsonBody, isFormDataBody } = opts;\n const headers = new Headers(this.configuredHeaders);\n\n // A request's own headers win over the configured ones; the connector's below win over both.\n for (const [name, value] of requestHeaders ?? []) {\n headers.set(name, value);\n }\n\n if (isJsonBody && !headers.has(HTTP.Headers.CONTENT_TYPE)) {\n headers.set(HTTP.Headers.CONTENT_TYPE, 'application/json');\n }\n\n // Only `fetch` knows the multipart boundary; any other content-type here would drop it.\n if (isFormDataBody) {\n headers.delete(HTTP.Headers.CONTENT_TYPE);\n }\n\n // Set last: under the envelope a record read answers `{ count, data }`.\n headers.set(HTTP.Headers.REQUEST_COUNT_DATA, 'false');\n\n if (!token) {\n return headers;\n }\n\n headers.set(HTTP.Headers.AUTHORIZATION, `${token.type ?? 'Bearer'} ${token.value}`);\n\n // Unconditionally it would send the string \"undefined\".\n if (token.provider) {\n headers.set('x-auth-provider', token.provider);\n }\n\n return headers;\n }\n\n /** The browser global `location` is not declared for a server build, so it is probed, not assumed. */\n protected resolveLocationOrigin(): string | undefined {\n const location: unknown = Reflect.get(globalThis, 'location');\n\n if (typeof location !== 'object' || location === null || !('origin' in location)) {\n return undefined;\n }\n\n return typeof location.origin === 'string' ? location.origin : undefined;\n }\n\n /** The path as an error message quotes it: cut at 200 characters, with an ellipsis. */\n protected static toEchoedPath(opts: { path: string }): string {\n const { path } = opts;\n\n return path.length > MAX_ECHOED_PATH_LENGTH\n ? `${path.slice(0, MAX_ECHOED_PATH_LENGTH)}…`\n : path;\n }\n\n /** The request paths name a place under the base path, so none may be a dot segment, hide one, or carry a separator the URL parser would read differently from a server. */\n protected assertPathsStayUnderBase(opts: { paths: Array<string> }): void {\n for (const path of opts.paths) {\n const segments = path.split(REQUEST_PATH_SEPARATOR_PATTERN);\n const isEscaping =\n UNSAFE_REQUEST_PATH_PATTERN.test(path) ||\n // A trailing space is stripped from the whole URL by the parser, so `.. ` ends as `..`.\n segments.some((segment) => DOT_SEGMENT_PATTERN.test(segment.trimEnd()));\n\n if (isEscaping) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[${this.name}] A request path must stay under the base path: no dot segment, backslash or control character | path: '${EchoUtility.toSafeEcho({ value: HttpDataSource.toEchoedPath({ path }) })}'`,\n });\n }\n }\n }\n\n /** The resolved URL, whatever built it, is on the base's origin and under its path: the check that holds when the text checks above miss a form. */\n protected assertUnderBase(opts: { url: URL; origin?: string }): void {\n const { url, origin } = opts;\n const base = new URL(this.settings.baseUrl, origin);\n const basePath = base.pathname.replace(/\\/+$/, '');\n const isUnderBase =\n url.origin === base.origin &&\n (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`));\n\n if (!isUnderBase) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[${this.name}] A request path must stay under the base path: the URL left the origin or the base path`,\n });\n }\n }\n\n buildUrl(opts: { paths: Array<string>; query?: Record<string, unknown> }): string {\n const { paths, query } = opts;\n this.assertPathsStayUnderBase({ paths });\n\n const requestUrl = HttpWire.toRequestUrl({ baseUrl: this.settings.baseUrl, paths });\n\n // A page or a Web Worker has an origin to resolve '/api' against; a server has none.\n const origin = this.isRelativeBaseUrl ? this.resolveLocationOrigin() : undefined;\n\n if (this.isRelativeBaseUrl && !origin) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${this.name}] Relative baseUrl '${this.settings.baseUrl}' needs a page or worker location to resolve against, and there is none here | Pass an absolute baseUrl such as 'https://api.example.com'`,\n });\n }\n\n const url = new URL(requestUrl, origin);\n this.assertUnderBase({ url, origin });\n\n const parameters = Object.entries(query ?? {});\n\n for (const [key, value] of parameters) {\n if (value === undefined) {\n continue;\n }\n\n url.searchParams.set(\n key,\n typeof value === 'string'\n ? value\n : HttpWire.toJson({ value, label: `[${this.name}] Query parameter '${key}'` }),\n );\n }\n\n return url.toString();\n }\n\n /**\n * The raw `Response`, on any method - for what the repository verbs do not cover, like an export\n * or a PUT to a hand-written route. Auth and the 401 retry apply; the retry resends the same body.\n */\n async request(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n return this.sendRequest({ ...opts, url: this.buildUrl(opts) });\n }\n\n /** `request` on a URL already built: `read` and `write` serialise a long query once, not per use. */\n protected async sendRequest(\n opts: {\n paths: Array<string>;\n url: string;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n const { url, signal } = opts;\n const requestHeaders = HttpWire.toHeaderEntries({ headers: opts.headers });\n HttpWire.assertNoRequestCountHeader({ entries: requestHeaders, name: this.name });\n\n const method = opts.method ?? HTTP.Methods.GET;\n const context: IHttpRequestContext = { paths: opts.paths, method, url, signal };\n const { payload, isJson, isFormData } = HttpWire.toRequestBody({ body: opts.body });\n\n // Both hooks run inside `send`, so the retry sends what they answer after the refresh.\n const send = () =>\n // The platform `fetch` unless the settings name a sender; looked up per call, so a test that swaps the global is heard.\n (this.settings.fetch ?? fetch)(url, {\n method: method.toUpperCase(),\n body: payload,\n signal,\n headers: this.buildHeaders({\n token: this.resolveAuthToken({ context }),\n // Resolved first, so the call's own headers win over them.\n requestHeaders: [...this.resolveHeaders({ context }), ...requestHeaders],\n isJsonBody: isJson,\n isFormDataBody: isFormData,\n }),\n });\n\n let response = await send();\n\n if (response.status === HTTP.ResultCodes.RS_4.Unauthorized && this.settings.onUnauthorized) {\n const shouldRetry = await this.settings.onUnauthorized(context);\n\n // A call aborted while the session refreshed is not sent again.\n if (shouldRetry) {\n signal?.throwIfAborted();\n const result = await send();\n response = result;\n }\n }\n\n return response;\n }\n\n /**\n * The body as JSON, `null` when there is none; a body that is not JSON is the server's fault, named\n * as such. Its content stays out of the message, which a relaying server may pass to its clients.\n */\n protected async readJsonBody(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const text = await response.text();\n\n if (!text) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.BadGateway,\n message: `[${this.name}][${verb}] ${response.status} | ${HttpWire.describeUrl({ url, status: response.status })} | The response body is not JSON (${text.length} chars, content-type: ${response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? 'none'})`,\n });\n }\n }\n\n /**\n * A failed response as the error the server threw: its status, code, args and text, and its\n * `extra` with the `requestId` added. `message` adds where it failed, for logs; `normalized.text`\n * stays the server's, for display - `HTTP <status>` when the server sent none. `cause` is the server's `details.cause` - a 422's per-field\n * issues, `{ path, message, code }`.\n */\n protected async toResponseError(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const described = HttpWire.describeUrl({ url, status: response.status });\n\n return HttpResponseReader.toApplicationError({\n response,\n rootKey: this.settings.errorRootKey,\n context: `[${this.name}][${verb}] ${response.status} | ${described}`,\n });\n }\n\n /**\n * Rows plus the total from `Content-Range`, reported absent when the header is. A GET unless told\n * otherwise: `method` and `body` reach a list route a service wrote to take its filter in a body.\n */\n async read<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n shape?: THttpReadShape;\n method?: string;\n body?: THttpBody;\n /** Extras the route offers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n /** The rows alone: every default extra off (`-*`), for a read that only counts or probes. */\n isEveryDefaultOff?: boolean;\n } & IHttpCallOptions,\n ): Promise<IHttpReadResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({\n headers: opts.headers,\n extra: opts.extra,\n isEveryDefaultOff: opts.isEveryDefaultOff,\n });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'read' });\n throw result;\n }\n\n // A 204 or an empty body is no row; a list asked for of it still throws below.\n const parsed = await this.readJsonBody({ response, url, verb: 'read' });\n const { body, extra } = HttpResponseReader.readExtra({\n body: parsed,\n headers: response.headers,\n });\n const contentRange = response.headers.get(HTTP.Headers.CONTENT_RANGE) ?? undefined;\n const range = HttpResponseReader.parseContentRange({ header: contentRange });\n const data = HttpWire.unwrapRows<R>({ body, shape: opts.shape ?? HttpReadShapes.LIST, url });\n\n return {\n data,\n hasRange: range !== undefined,\n contentRange,\n total: range?.total,\n skip: range?.skip,\n dataLength: Array.isArray(data) ? data.length : data === null ? 0 : 1,\n extra,\n };\n }\n\n /**\n * A write, and what it answered: the body as the rows, the count from `x-response-count`. The\n * connector asks for bare rows, so an IGNIS write answers the row or the rows, never the envelope.\n */\n async write<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method: string;\n body?: THttpBody;\n /** Extras the route answers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n } & IHttpCallOptions,\n ): Promise<IHttpWriteResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({ headers: opts.headers, extra: opts.extra });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'write' });\n throw result;\n }\n\n // A 204, or a route that answers nothing, has no body to parse.\n const parsed = await this.readJsonBody({ response, url, verb: 'write' });\n const { extra } = HttpResponseReader.readExtra({ body: parsed, headers: response.headers });\n const data = extra ? parsed.data : parsed;\n\n const countHeader = response.headers.get(HTTP.Headers.RESPONSE_COUNT_DATA);\n const counted = countHeader === null ? Number.NaN : Number(countHeader);\n\n return {\n data,\n count: Number.isFinite(counted)\n ? counted\n : Array.isArray(data)\n ? data.length\n : data === null\n ? 0\n : 1,\n ...(extra ? { extra } : {}),\n };\n }\n}\n"]}
|
|
@@ -7,24 +7,28 @@ import type { Env, Schema } from 'hono';
|
|
|
7
7
|
import type { ReadableSearchRepository } from '../repositories/core/readable.js';
|
|
8
8
|
import type { TSearchScopeResolver } from './scope.js';
|
|
9
9
|
/** Base tier of a generated search controller: the repository handle plus the search / multi-search verbs; SearchControllerFactory returns a thin subclass that only builds route configs and wires them. */
|
|
10
|
-
export declare abstract class AbstractSearchController<TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>, RouteEnv extends Env = Env, RouteSchema extends Schema = {}, BasePath extends string = '/', ConfigurableOptions extends object = {}, TDataObject extends object = TEntityDataObject<TEntity
|
|
10
|
+
export declare abstract class AbstractSearchController<TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>, RouteEnv extends Env = Env, RouteSchema extends Schema = {}, BasePath extends string = '/', ConfigurableOptions extends object = {}, TDataObject extends object = TEntityDataObject<TEntity>, TExtra extends object = {}> extends BaseRestController<RouteEnv, RouteSchema, BasePath, ConfigurableOptions> {
|
|
11
11
|
repository: ReadableSearchRepository<TDataObject>;
|
|
12
|
-
searchScope?: TSearchScopeResolver<RouteEnv>;
|
|
12
|
+
searchScope?: TSearchScopeResolver<RouteEnv, TExtra>;
|
|
13
13
|
/** The `engineParams` names a caller may send, normalised (see {@link SearchEngineParams}). Empty: any `engineParams` is refused. */
|
|
14
14
|
allowedEngineParams: ReadonlySet<string>;
|
|
15
15
|
/** Whether the controller serves `mode: 'raw'` and multi-search over HTTP (`modes.raw.allow`). Closed by default: see {@link SearchRawAccess}. */
|
|
16
16
|
isRawAllowed: boolean;
|
|
17
|
+
/** `request.body.extend` was given: its keys are the scope's to read, and they do not go on to the repository. */
|
|
18
|
+
isBodyExtended: boolean;
|
|
17
19
|
constructor(opts: {
|
|
18
20
|
scope: string;
|
|
19
21
|
isStrict?: boolean;
|
|
20
22
|
repository: ReadableSearchRepository<TDataObject>;
|
|
21
23
|
definitions: AnyType;
|
|
22
24
|
/** Per-request search scope; see {@link TSearchScopeResolver}. */
|
|
23
|
-
searchScope?: TSearchScopeResolver<RouteEnv>;
|
|
25
|
+
searchScope?: TSearchScopeResolver<RouteEnv, TExtra>;
|
|
24
26
|
/** Names from `engineParams.allow`, as `SearchEngineParams.resolveAllowlist` answers them. */
|
|
25
27
|
allowedEngineParams?: ReadonlySet<string>;
|
|
26
28
|
/** `modes.raw.allow`, as `SearchRawAccess.resolve` answers it. */
|
|
27
29
|
isRawAllowed?: boolean;
|
|
30
|
+
/** `request.body.extend` was given. */
|
|
31
|
+
isBodyExtended?: boolean;
|
|
28
32
|
});
|
|
29
33
|
/** POST /search - single-collection keyword/semantic/hybrid/raw search. Carries the list headers of every IGNIS list endpoint; the body keeps `{ found, isFoundExact, hits }` because `isFoundExact` has no place in a `{ count, data }` envelope, and it is the only carrier of "found is an estimate". */
|
|
30
34
|
search(opts: {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BaseRestController, DataRangeUtility } from '@venizia/ignis-kernel';
|
|
2
2
|
import { getError } from '@venizia/ignis-helpers/core';
|
|
3
3
|
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
4
|
-
import { SearchModes } from '../repositories/common/index.js';
|
|
4
|
+
import { SearchInputSchema, SearchModes } from '../repositories/common/index.js';
|
|
5
5
|
import { SearchEngineParams } from './engine-params.js';
|
|
6
6
|
import { SearchRawAccess } from './raw-access.js';
|
|
7
7
|
import { SearchControllerScope } from './scope.js';
|
|
@@ -33,6 +33,7 @@ export class AbstractSearchController extends BaseRestController {
|
|
|
33
33
|
this.searchScope = opts.searchScope;
|
|
34
34
|
this.allowedEngineParams = opts.allowedEngineParams ?? new Set();
|
|
35
35
|
this.isRawAllowed = opts.isRawAllowed ?? false;
|
|
36
|
+
this.isBodyExtended = opts.isBodyExtended ?? false;
|
|
36
37
|
this.definitions = opts.definitions;
|
|
37
38
|
}
|
|
38
39
|
/** POST /search - single-collection keyword/semantic/hybrid/raw search. Carries the list headers of every IGNIS list endpoint; the body keeps `{ found, isFoundExact, hits }` because `isFoundExact` has no place in a `{ count, data }` envelope, and it is the only carrier of "found is an estimate". */
|
|
@@ -55,6 +56,10 @@ export class AbstractSearchController extends BaseRestController {
|
|
|
55
56
|
});
|
|
56
57
|
input = scoped;
|
|
57
58
|
}
|
|
59
|
+
// The scope was the only reader of the extra keys: the base schema drops them, so the repository and the log never see them.
|
|
60
|
+
if (this.isBodyExtended) {
|
|
61
|
+
input = SearchInputSchema.parse(input);
|
|
62
|
+
}
|
|
58
63
|
const rs = await this.measure({
|
|
59
64
|
scope: 'search',
|
|
60
65
|
args: input,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/abstract.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAI7E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACv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IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;gBAC5C,OAAO,EAAE,2EAA2E;aACrF,CAAC,CAAC;QACL,CAAC;QAED,eAAe,CAAC,iBAAiB,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC;QAEpE,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAoB,MAAM,CAAC,CAAC;QAE3D,kBAAkB,CAAC,sBAAsB,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,mBAAmB,EAAE,CAAC,CAAC;QAExF,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC;YAC5B,KAAK,EAAE,aAAa;YACpB,IAAI,EAAE,KAAK;YACX,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,KAAK,CAAC;SAC/C,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF","sourcesContent":["import type { TEntityDataObject, TRouteContext } from '@venizia/ignis-kernel';\nimport { BaseRestController, DataRangeUtility } from '@venizia/ignis-kernel';\nimport type { AbstractEntity } from '@venizia/ignis-kernel';\nimport type { TAnyObjectSchema } from '@venizia/ignis-kernel';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type { TMultiSearchInput, TSearchInput } from '@/search/core/repositories/common';\nimport { SearchModes } from '@/search/core/repositories/common';\nimport type { ReadableSearchRepository } from '../repositories/core/readable';\nimport { SearchEngineParams } from './engine-params';\nimport { SearchRawAccess } from './raw-access';\nimport { SearchControllerScope } from './scope';\nimport type { TSearchScopeResolver } from './scope';\n\n/** Where the page starts, for `Content-Range`. Friendly modes carry `filter.skip` or `filter.offset`; raw mode carries the engine's own `offset`, or a 1-based `page` with `per_page`/`perPage`. A raw request that names a page but no page size is measured against this page's hit count, so only its last page can be off. */\nconst resolveSearchStart = (opts: { input: TSearchInput; hitCount: number }): number => {\n const { input, hitCount } = opts;\n\n if (input.mode !== SearchModes.RAW) {\n // Same precedence as DataRangeUtility.buildDataRange: the repository filter carries skip or offset.\n return input.filter?.skip ?? input.filter?.offset ?? 0;\n }\n\n // Engine wire names are read through string keys only; `params` is an untyped passthrough.\n const params = input.params;\n const offset = params['offset'];\n\n if (typeof offset === 'number') {\n return offset;\n }\n\n const page = params['page'];\n\n if (typeof page !== 'number' || page < 1) {\n return 0;\n }\n\n const pageSize = params['per_page'] ?? params['perPage'];\n\n return (page - 1) * (typeof pageSize === 'number' ? pageSize : hitCount);\n};\n\n/** Base tier of a generated search controller: the repository handle plus the search / multi-search verbs; SearchControllerFactory returns a thin subclass that only builds route configs and wires them. */\nexport abstract class AbstractSearchController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n> extends BaseRestController<RouteEnv, RouteSchema, BasePath, ConfigurableOptions> {\n repository: ReadableSearchRepository<TDataObject>;\n searchScope?: TSearchScopeResolver<RouteEnv>;\n\n /** The `engineParams` names a caller may send, normalised (see {@link SearchEngineParams}). Empty: any `engineParams` is refused. */\n allowedEngineParams: ReadonlySet<string>;\n\n /** Whether the controller serves `mode: 'raw'` and multi-search over HTTP (`modes.raw.allow`). Closed by default: see {@link SearchRawAccess}. */\n isRawAllowed: boolean;\n\n constructor(opts: {\n scope: string;\n isStrict?: boolean;\n repository: ReadableSearchRepository<TDataObject>;\n definitions: AnyType;\n /** Per-request search scope; see {@link TSearchScopeResolver}. */\n searchScope?: TSearchScopeResolver<RouteEnv>;\n /** Names from `engineParams.allow`, as `SearchEngineParams.resolveAllowlist` answers them. */\n allowedEngineParams?: ReadonlySet<string>;\n /** `modes.raw.allow`, as `SearchRawAccess.resolve` answers it. */\n isRawAllowed?: boolean;\n }) {\n super({ scope: opts.scope, isStrict: opts.isStrict });\n this.repository = opts.repository;\n this.searchScope = opts.searchScope;\n this.allowedEngineParams = opts.allowedEngineParams ?? new Set();\n this.isRawAllowed = opts.isRawAllowed ?? false;\n this.definitions = opts.definitions;\n }\n\n /** POST /search - single-collection keyword/semantic/hybrid/raw search. Carries the list headers of every IGNIS list endpoint; the body keeps `{ found, isFoundExact, hits }` because `isFoundExact` has no place in a `{ count, data }` envelope, and it is the only carrier of \"found is an estimate\". */\n async search(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const body = context.req.valid<TSearchInput>('json');\n let input = body;\n\n // Before the scope and on every controller: a caller's raw engine parameters can replace the controller's own filter.\n SearchRawAccess.assertSearchInput({ input: body, isAllowed: this.isRawAllowed });\n SearchEngineParams.assertSearchInput({ input: body, allowed: this.allowedEngineParams });\n\n // The request's own filter cannot name a hidden field (where or order); server code is not held to it.\n if (body.mode !== SearchModes.RAW) {\n this.repository.assertRequestFilter({ filter: body.filter });\n }\n\n if (this.searchScope) {\n const scoped = await SearchControllerScope.applySearchScope({\n resolve: this.searchScope,\n context,\n input: body,\n });\n input = scoped;\n }\n\n const rs = await this.measure({\n scope: 'search',\n args: input,\n task: async () => {\n // `isFoundExact` travels to the caller so an engine whose `found` is an estimate never looks exhaustive across the HTTP boundary.\n const { found, isFoundExact, hits } = await this.repository.search(input);\n\n return { found, isFoundExact, hits: hits ?? [] };\n },\n });\n\n const start = resolveSearchStart({ input, hitCount: rs.hits.length });\n this.setListHeaders({\n context,\n range: DataRangeUtility.buildDataRange({\n offset: start,\n dataLength: rs.hits.length,\n total: rs.found,\n }),\n count: rs.hits.length,\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** POST /multi-search - cross-collection search, forwarded verbatim to the engine. */\n async multiSearch(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n\n // A multi-search entry carries the engine's own `filterBy` string, which a `where` scope cannot\n // be ANDed into: a scoped controller does not serve it.\n if (this.searchScope) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: '[multiSearch] multi-search is not available on a scoped search controller',\n });\n }\n\n SearchRawAccess.assertMultiSearch({ isAllowed: this.isRawAllowed });\n\n const input = context.req.valid<TMultiSearchInput>('json');\n\n SearchEngineParams.assertMultiSearchInput({ input, allowed: this.allowedEngineParams });\n\n const rs = await this.measure({\n scope: 'multiSearch',\n args: input,\n task: () => this.repository.multiSearch(input),\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/abstract.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAI7E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAEnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAGhD,kUAAkU;AAClU,MAAM,kBAAkB,GAAG,CAAC,IAA+C,EAAU,EAAE;IACrF,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IAEjC,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,GAAG,EAAE,CAAC;QACnC,oGAAoG;QACpG,OAAO,KAAK,CAAC,MAAM,EAAE,IAAI,IAAI,KAAK,CAAC,MAAM,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E,IAAI,CAAC,mBAAmB,EAAE,CAAC,CAAC;QAExF,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC;YAC5B,KAAK,EAAE,aAAa;YACpB,IAAI,EAAE,KAAK;YACX,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,KAAK,CAAC;SAC/C,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF","sourcesContent":["import type { TEntityDataObject, TRouteContext } from '@venizia/ignis-kernel';\nimport { BaseRestController, DataRangeUtility } from '@venizia/ignis-kernel';\nimport type { AbstractEntity } from '@venizia/ignis-kernel';\nimport type { TAnyObjectSchema } from '@venizia/ignis-kernel';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type { TMultiSearchInput, TSearchInput } from '@/search/core/repositories/common';\nimport { SearchInputSchema, SearchModes } from '@/search/core/repositories/common';\nimport type { ReadableSearchRepository } from '../repositories/core/readable';\nimport { SearchEngineParams } from './engine-params';\nimport { SearchRawAccess } from './raw-access';\nimport { SearchControllerScope } from './scope';\nimport type { TSearchScopeResolver } from './scope';\n\n/** Where the page starts, for `Content-Range`. Friendly modes carry `filter.skip` or `filter.offset`; raw mode carries the engine's own `offset`, or a 1-based `page` with `per_page`/`perPage`. A raw request that names a page but no page size is measured against this page's hit count, so only its last page can be off. */\nconst resolveSearchStart = (opts: { input: TSearchInput; hitCount: number }): number => {\n const { input, hitCount } = opts;\n\n if (input.mode !== SearchModes.RAW) {\n // Same precedence as DataRangeUtility.buildDataRange: the repository filter carries skip or offset.\n return input.filter?.skip ?? input.filter?.offset ?? 0;\n }\n\n // Engine wire names are read through string keys only; `params` is an untyped passthrough.\n const params = input.params;\n const offset = params['offset'];\n\n if (typeof offset === 'number') {\n return offset;\n }\n\n const page = params['page'];\n\n if (typeof page !== 'number' || page < 1) {\n return 0;\n }\n\n const pageSize = params['per_page'] ?? params['perPage'];\n\n return (page - 1) * (typeof pageSize === 'number' ? pageSize : hitCount);\n};\n\n/** Base tier of a generated search controller: the repository handle plus the search / multi-search verbs; SearchControllerFactory returns a thin subclass that only builds route configs and wires them. */\nexport abstract class AbstractSearchController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TExtra extends object = {},\n> extends BaseRestController<RouteEnv, RouteSchema, BasePath, ConfigurableOptions> {\n repository: ReadableSearchRepository<TDataObject>;\n searchScope?: TSearchScopeResolver<RouteEnv, TExtra>;\n\n /** The `engineParams` names a caller may send, normalised (see {@link SearchEngineParams}). Empty: any `engineParams` is refused. */\n allowedEngineParams: ReadonlySet<string>;\n\n /** Whether the controller serves `mode: 'raw'` and multi-search over HTTP (`modes.raw.allow`). Closed by default: see {@link SearchRawAccess}. */\n isRawAllowed: boolean;\n\n /** `request.body.extend` was given: its keys are the scope's to read, and they do not go on to the repository. */\n isBodyExtended: boolean;\n\n constructor(opts: {\n scope: string;\n isStrict?: boolean;\n repository: ReadableSearchRepository<TDataObject>;\n definitions: AnyType;\n /** Per-request search scope; see {@link TSearchScopeResolver}. */\n searchScope?: TSearchScopeResolver<RouteEnv, TExtra>;\n /** Names from `engineParams.allow`, as `SearchEngineParams.resolveAllowlist` answers them. */\n allowedEngineParams?: ReadonlySet<string>;\n /** `modes.raw.allow`, as `SearchRawAccess.resolve` answers it. */\n isRawAllowed?: boolean;\n /** `request.body.extend` was given. */\n isBodyExtended?: boolean;\n }) {\n super({ scope: opts.scope, isStrict: opts.isStrict });\n this.repository = opts.repository;\n this.searchScope = opts.searchScope;\n this.allowedEngineParams = opts.allowedEngineParams ?? new Set();\n this.isRawAllowed = opts.isRawAllowed ?? false;\n this.isBodyExtended = opts.isBodyExtended ?? false;\n this.definitions = opts.definitions;\n }\n\n /** POST /search - single-collection keyword/semantic/hybrid/raw search. Carries the list headers of every IGNIS list endpoint; the body keeps `{ found, isFoundExact, hits }` because `isFoundExact` has no place in a `{ count, data }` envelope, and it is the only carrier of \"found is an estimate\". */\n async search(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const body = context.req.valid<TSearchInput & TExtra>('json');\n let input: TSearchInput = body;\n\n // Before the scope and on every controller: a caller's raw engine parameters can replace the controller's own filter.\n SearchRawAccess.assertSearchInput({ input: body, isAllowed: this.isRawAllowed });\n SearchEngineParams.assertSearchInput({ input: body, allowed: this.allowedEngineParams });\n\n // The request's own filter cannot name a hidden field (where or order); server code is not held to it.\n if (body.mode !== SearchModes.RAW) {\n this.repository.assertRequestFilter({ filter: body.filter });\n }\n\n if (this.searchScope) {\n const scoped = await SearchControllerScope.applySearchScope({\n resolve: this.searchScope,\n context,\n input: body,\n });\n input = scoped;\n }\n\n // The scope was the only reader of the extra keys: the base schema drops them, so the repository and the log never see them.\n if (this.isBodyExtended) {\n input = SearchInputSchema.parse(input);\n }\n\n const rs = await this.measure({\n scope: 'search',\n args: input,\n task: async () => {\n // `isFoundExact` travels to the caller so an engine whose `found` is an estimate never looks exhaustive across the HTTP boundary.\n const { found, isFoundExact, hits } = await this.repository.search(input);\n\n return { found, isFoundExact, hits: hits ?? [] };\n },\n });\n\n const start = resolveSearchStart({ input, hitCount: rs.hits.length });\n this.setListHeaders({\n context,\n range: DataRangeUtility.buildDataRange({\n offset: start,\n dataLength: rs.hits.length,\n total: rs.found,\n }),\n count: rs.hits.length,\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** POST /multi-search - cross-collection search, forwarded verbatim to the engine. */\n async multiSearch(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n\n // A multi-search entry carries the engine's own `filterBy` string, which a `where` scope cannot\n // be ANDed into: a scoped controller does not serve it.\n if (this.searchScope) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: '[multiSearch] multi-search is not available on a scoped search controller',\n });\n }\n\n SearchRawAccess.assertMultiSearch({ isAllowed: this.isRawAllowed });\n\n const input = context.req.valid<TMultiSearchInput>('json');\n\n SearchEngineParams.assertMultiSearchInput({ input, allowed: this.allowedEngineParams });\n\n const rs = await this.measure({\n scope: 'multiSearch',\n args: input,\n task: () => this.repository.multiSearch(input),\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n"]}
|
|
@@ -14,7 +14,7 @@ export interface ISearchRoutes {
|
|
|
14
14
|
multiSearch?: true;
|
|
15
15
|
}
|
|
16
16
|
/** Configuration options for creating a search controller via SearchControllerFactory.build. */
|
|
17
|
-
export interface ISearchControllerOptions<Repository extends TCrudRepositoryClass = TCrudRepositoryClass> {
|
|
17
|
+
export interface ISearchControllerOptions<Repository extends TCrudRepositoryClass = TCrudRepositoryClass, Shape extends z.ZodRawShape = {}> {
|
|
18
18
|
/** The repository class; its name is the binding the container injects, and its `@repository({ model })` supplies the entity whose SELECT schema drives the `hits[].document` shape in the response. */
|
|
19
19
|
repository: Repository;
|
|
20
20
|
/** When true, /search and /search/ are different routes. @default true */
|
|
@@ -39,7 +39,19 @@ export interface ISearchControllerOptions<Repository extends TCrudRepositoryClas
|
|
|
39
39
|
* multi-search route (leave `routes.multiSearch` out), which `SearchControllerFactory.build` requires.
|
|
40
40
|
* `engineParams` is refused on every controller unless `engineParams.allow` lists it.
|
|
41
41
|
*/
|
|
42
|
-
scope?: TSearchScopeResolver
|
|
42
|
+
scope?: TSearchScopeResolver<Env, z.infer<z.ZodObject<Shape>>>;
|
|
43
|
+
/**
|
|
44
|
+
* Adds keys to the body of `POST /search`, on every `mode`: `request.body.extend` is a Zod shape, and each key is
|
|
45
|
+
* validated with the rest of the body (a bad value is a 400) and shown in the OpenAPI document. The validated body,
|
|
46
|
+
* typed from the shape, reaches `scope` as `input`, so a facet the engine does not know can still narrow the scope
|
|
47
|
+
* (an `ids` list that must all match, say). The extra keys are not search fields: nothing else reads them.
|
|
48
|
+
* A key the base body already has is refused when the controller is built.
|
|
49
|
+
*/
|
|
50
|
+
request?: {
|
|
51
|
+
body?: {
|
|
52
|
+
extend: Shape;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
43
55
|
/**
|
|
44
56
|
* Which engine parameters a caller may send in a request's `engineParams`. Unset or empty, a request that carries
|
|
45
57
|
* `engineParams` is refused with 400, on a scoped and an unscoped controller alike: raw engine parameters can replace
|
|
@@ -66,6 +78,8 @@ export interface ISearchControllerOptions<Repository extends TCrudRepositoryClas
|
|
|
66
78
|
/** Factory for generating turnkey search controllers (single-collection + cross-collection) from entity definitions. */
|
|
67
79
|
export declare class SearchControllerFactory extends BaseHelper {
|
|
68
80
|
constructor();
|
|
81
|
+
/** `SearchInputSchema` with `shape` added to each of its four modes (a discriminated union has no `extend` of its own). */
|
|
82
|
+
private static extendSearchBody;
|
|
69
83
|
static defineRouteConfigs(opts: {
|
|
70
84
|
selectSchema: z.ZodType;
|
|
71
85
|
authenticate?: {
|
|
@@ -73,6 +87,8 @@ export declare class SearchControllerFactory extends BaseHelper {
|
|
|
73
87
|
mode?: TAuthMode;
|
|
74
88
|
};
|
|
75
89
|
authorize?: IAuthorizationSpec | IAuthorizationSpec[];
|
|
90
|
+
/** The keys `request.body.extend` adds to every `mode` of the search body; none leaves `SearchInputSchema` as it is. */
|
|
91
|
+
bodyExtension?: z.ZodRawShape;
|
|
76
92
|
}): {
|
|
77
93
|
readonly SEARCH: {
|
|
78
94
|
readonly method: "post";
|
|
@@ -177,6 +193,14 @@ export declare class SearchControllerFactory extends BaseHelper {
|
|
|
177
193
|
}, z.core.$strip>, z.ZodObject<{
|
|
178
194
|
mode: z.ZodLiteral<"raw">;
|
|
179
195
|
params: z.ZodRecord<z.ZodString, z.ZodAny>;
|
|
196
|
+
}, z.core.$strip>], "mode"> | z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
197
|
+
[x: string]: z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
|
|
198
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
199
|
+
[x: string]: z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
|
|
200
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
201
|
+
[x: string]: z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
|
|
202
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
203
|
+
[x: string]: z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
|
|
180
204
|
}, z.core.$strip>], "mode">;
|
|
181
205
|
};
|
|
182
206
|
};
|
|
@@ -367,16 +391,17 @@ export declare class SearchControllerFactory extends BaseHelper {
|
|
|
367
391
|
};
|
|
368
392
|
};
|
|
369
393
|
/** Creates a search controller with the routes you list: `POST /search` via `repository.search()`, and `POST /multi-search` via `repository.dataSource.multiSearch()`. The path is the `@controller({ path })` of the subclass. */
|
|
370
|
-
static build<Repository extends TCrudRepositoryClass, RouteEnv extends Env = Env, RouteSchema extends Schema = {}, BasePath extends string = '/', ConfigurableOptions extends object = {}, TDataObject extends object = TRepositoryDataObject<InstanceType<Repository
|
|
394
|
+
static build<Repository extends TCrudRepositoryClass, RouteEnv extends Env = Env, RouteSchema extends Schema = {}, BasePath extends string = '/', ConfigurableOptions extends object = {}, TDataObject extends object = TRepositoryDataObject<InstanceType<Repository>>, Shape extends z.ZodRawShape = {}>(opts: ISearchControllerOptions<Repository, Shape>): {
|
|
371
395
|
new (repositoryInstance: ReadableSearchRepository<TDataObject>): {
|
|
372
396
|
/** The routes of a generated controller come from `routes`; a subclass adds its own here. */
|
|
373
397
|
binding(): ValueOrPromise<void>;
|
|
374
398
|
/** Registers each listed route, after the subclass's `binding()`. */
|
|
375
399
|
bindDefaultRoutes(): ValueOrPromise<void>;
|
|
376
400
|
repository: ReadableSearchRepository<TDataObject, import("../index.js").AbstractSearchDataSource<{}>>;
|
|
377
|
-
searchScope?: TSearchScopeResolver<RouteEnv
|
|
401
|
+
searchScope?: TSearchScopeResolver<RouteEnv, z.core.$InferObjectOutput<Shape, {}>> | undefined;
|
|
378
402
|
allowedEngineParams: ReadonlySet<string>;
|
|
379
403
|
isRawAllowed: boolean;
|
|
404
|
+
isBodyExtended: boolean;
|
|
380
405
|
search(opts: {
|
|
381
406
|
context: import("@venizia/ignis-kernel").TRouteContext<RouteEnv>;
|
|
382
407
|
}): Promise<import("@venizia/ignis-kernel").TJsonResponse<unknown, 200>>;
|
|
@@ -13,8 +13,29 @@ export class SearchControllerFactory extends BaseHelper {
|
|
|
13
13
|
constructor() {
|
|
14
14
|
super({ scope: SearchControllerFactory.name });
|
|
15
15
|
}
|
|
16
|
+
/** `SearchInputSchema` with `shape` added to each of its four modes (a discriminated union has no `extend` of its own). */
|
|
17
|
+
static extendSearchBody(opts) {
|
|
18
|
+
const { shape } = opts;
|
|
19
|
+
const [keyword, semantic, hybrid, raw] = SearchInputSchema.options;
|
|
20
|
+
const taken = Object.keys(shape).filter((key) => key in keyword.shape || key in semantic.shape || key in hybrid.shape || key in raw.shape);
|
|
21
|
+
if (taken.length > 0) {
|
|
22
|
+
throw getError({
|
|
23
|
+
message: `[SearchControllerFactory.build] request.body.extend names keys the search body already has | keys: ${taken.join(', ')}`,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
// `extend` drops the `.describe()` of a member, and the OpenAPI document shows it as the name of the mode.
|
|
27
|
+
return z.discriminatedUnion('mode', [
|
|
28
|
+
keyword.extend(shape).describe(keyword.description ?? ''),
|
|
29
|
+
semantic.extend(shape).describe(semantic.description ?? ''),
|
|
30
|
+
hybrid.extend(shape).describe(hybrid.description ?? ''),
|
|
31
|
+
raw.extend(shape).describe(raw.description ?? ''),
|
|
32
|
+
]);
|
|
33
|
+
}
|
|
16
34
|
static defineRouteConfigs(opts) {
|
|
17
|
-
const { selectSchema, authenticate, authorize } = opts;
|
|
35
|
+
const { selectSchema, authenticate, authorize, bodyExtension } = opts;
|
|
36
|
+
const searchBodySchema = bodyExtension
|
|
37
|
+
? SearchControllerFactory.extendSearchBody({ shape: bodyExtension })
|
|
38
|
+
: SearchInputSchema;
|
|
18
39
|
const searchResponseSchema = z.object({
|
|
19
40
|
found: z.number(),
|
|
20
41
|
isFoundExact: z
|
|
@@ -34,7 +55,7 @@ export class SearchControllerFactory extends BaseHelper {
|
|
|
34
55
|
request: {
|
|
35
56
|
body: OpenApiResponses.jsonContent({
|
|
36
57
|
description: 'Search input, discriminated by mode',
|
|
37
|
-
schema:
|
|
58
|
+
schema: searchBodySchema,
|
|
38
59
|
}),
|
|
39
60
|
},
|
|
40
61
|
responses: OpenApiResponses.jsonResponse({
|
|
@@ -94,6 +115,7 @@ export class SearchControllerFactory extends BaseHelper {
|
|
|
94
115
|
selectSchema,
|
|
95
116
|
authenticate,
|
|
96
117
|
authorize,
|
|
118
|
+
bodyExtension: opts.request?.body?.extend,
|
|
97
119
|
});
|
|
98
120
|
const controllerClass = class extends AbstractSearchController {
|
|
99
121
|
constructor(repositoryInstance) {
|
|
@@ -105,6 +127,7 @@ export class SearchControllerFactory extends BaseHelper {
|
|
|
105
127
|
searchScope: scope,
|
|
106
128
|
allowedEngineParams,
|
|
107
129
|
isRawAllowed,
|
|
130
|
+
isBodyExtended: opts.request?.body !== undefined,
|
|
108
131
|
});
|
|
109
132
|
}
|
|
110
133
|
/** The routes of a generated controller come from `routes`; a subclass adds its own here. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/factory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC7F,OAAO,EA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;iBACb,CAAC,CAAC;YACL,CAAC;YAED,6FAA6F;YACpF,OAAO,KAA0B,CAAC;YAE3C,qEAAqE;YAC5D,iBAAiB;gBACxB,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;oBAClB,IAAI,CAAC,WAAW,CAAC;wBACf,OAAO,EAAE,gBAAgB,CAAC,MAAM;wBAChC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;qBACrD,CAAC,CAAC;gBACL,CAAC;gBAED,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;oBACvB,IAAI,CAAC,WAAW,CAAC;wBACf,OAAO,EAAE,gBAAgB,CAAC,YAAY;wBACtC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,OAAO,EAAE,CAAC;qBAC1D,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;SACF,CAAC;QAEF,qBAAqB,CAAC,2BAA2B,CAAC;YAChD,MAAM,EAAE,eAAe;YACvB,WAAW,EAAE,+BAA+B;YAC5C,cAAc,EAAE,UAAU,CAAC,IAAI;SAChC,CAAC,CAAC;QAEH,OAAO,eAAe,CAAC;IACzB,CAAC;CACF","sourcesContent":["import type { TRepositoryDataObject } from '@venizia/ignis-kernel';\nimport type { AbstractEntity } from '@venizia/ignis-kernel';\nimport { CrudControllerFactory, OpenApiResponses, SchemaTypes } from '@venizia/ignis-kernel';\nimport { MetadataRegistry } from '@venizia/ignis-kernel/metadata';\nimport type { TAuthMode, TAuthStrategy } from '@venizia/ignis-kernel';\nimport type { IAuthorizationSpec } from '@venizia/ignis-kernel';\nimport type { TCrudRepositoryClass } from '@venizia/ignis-kernel';\nimport { z } from '@hono/zod-openapi';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport { MultiSearchInputSchema, SearchInputSchema } from '@/search/core/repositories/common';\nimport type { ReadableSearchRepository } from '../repositories/core/readable';\nimport { AbstractSearchController } from './abstract';\nimport { SearchEngineParams } from './engine-params';\nimport { SearchRawAccess } from './raw-access';\nimport type { TSearchScopeResolver } from './scope';\n\n/** The routes of a search controller: only a listed route exists. */\nexport interface ISearchRoutes {\n search?: true;\n multiSearch?: true;\n}\n\n/** Configuration options for creating a search controller via SearchControllerFactory.build. */\nexport interface ISearchControllerOptions<\n Repository extends TCrudRepositoryClass = TCrudRepositoryClass,\n> {\n /** The repository class; its name is the binding the container injects, and its `@repository({ model })` supplies the entity whose SELECT schema drives the `hits[].document` shape in the response. */\n repository: Repository;\n\n /** When true, /search and /search/ are different routes. @default true */\n isStrict?: boolean;\n\n /** Authentication config applied to both generated routes. */\n authenticate?: { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n\n /** Authorization config applied to both generated routes. */\n authorize?: IAuthorizationSpec | IAuthorizationSpec[];\n\n /** The routes to generate. */\n routes: ISearchRoutes;\n\n /**\n * A function of the request context returning the filter this caller may search within. It is\n * ANDed into `input.filter.where` on the server: the client's own `where` can narrow it, never\n * widen or remove it. Fails closed - a scope that is null, undefined or throws refuses the\n * request with 403. Return `ScopeFilters.UNRESTRICTED` to apply none for a trusted caller.\n *\n * `raw` mode hands the engine its own wire parameters, and a multi-search entry carries a raw\n * `filterBy`; neither can take a scope, so a scoped controller refuses `raw` (400) and must disable the\n * multi-search route (leave `routes.multiSearch` out), which `SearchControllerFactory.build` requires.\n * `engineParams` is refused on every controller unless `engineParams.allow` lists it.\n */\n scope?: TSearchScopeResolver;\n\n /**\n * Which engine parameters a caller may send in a request's `engineParams`. Unset or empty, a request that carries\n * `engineParams` is refused with 400, on a scoped and an unscoped controller alike: raw engine parameters can replace\n * the controller's own filter and name fields the model hides. A parameter that selects rows or fields, or orders\n * them (`filter_by`, `include_fields`, `query_by`, `facet_by`, `group_by`, `highlight_fields`, `sort_by`, a\n * `preset`, ...) can never be listed: the definition throws. Server code still passes `engineParams` on the\n * repository call.\n */\n engineParams?: { allow?: string[] };\n\n /**\n * `modes.raw.allow: true` serves `mode: 'raw'` and multi-search over HTTP. Left out, both answer 400: they hand the\n * engine their parameters as they are, so the model's default filter and its hidden fields do not apply to them, and\n * opting in exposes the whole collection to every caller the route admits. A scoped controller cannot opt in. Server\n * code keeps `search({ mode: 'raw' })` and `multiSearch()` on the repository.\n */\n modes?: { raw?: { allow?: boolean } };\n}\n\n/** Factory for generating turnkey search controllers (single-collection + cross-collection) from entity definitions. */\nexport class SearchControllerFactory extends BaseHelper {\n constructor() {\n super({ scope: SearchControllerFactory.name });\n }\n\n static defineRouteConfigs(opts: {\n selectSchema: z.ZodType;\n authenticate?: { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n authorize?: IAuthorizationSpec | IAuthorizationSpec[];\n }) {\n const { selectSchema, authenticate, authorize } = opts;\n\n const searchResponseSchema = z.object({\n found: z.number(),\n isFoundExact: z\n .boolean()\n .openapi({ description: 'False when the engine reports `found` as an estimate.' }),\n hits: z.array(z.object({ document: selectSchema })),\n });\n\n const multiSearchResponseSchema = z.record(z.string(), z.unknown());\n\n const resolvedAuthenticate = authenticate ?? {};\n\n return {\n SEARCH: {\n method: HTTP.Methods.POST,\n path: '/search',\n description: 'Single-collection search (keyword, semantic, hybrid, or raw passthrough)',\n authenticate: resolvedAuthenticate,\n authorize,\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Search input, discriminated by mode',\n schema: SearchInputSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n description: 'Search results',\n schema: searchResponseSchema,\n }),\n },\n\n MULTI_SEARCH: {\n method: HTTP.Methods.POST,\n path: '/multi-search',\n description: 'Cross-collection search, forwarded verbatim to the search engine',\n authenticate: resolvedAuthenticate,\n authorize,\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Multi-search input - one or more per-collection native search params',\n schema: MultiSearchInputSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n description: 'Federated (or, when union is true, merged) search results',\n schema: multiSearchResponseSchema,\n }),\n },\n } as const;\n }\n\n /** Creates a search controller with the routes you list: `POST /search` via `repository.search()`, and `POST /multi-search` via `repository.dataSource.multiSearch()`. The path is the `@controller({ path })` of the subclass. */\n static build<\n Repository extends TCrudRepositoryClass,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TRepositoryDataObject<InstanceType<Repository>>,\n >(opts: ISearchControllerOptions<Repository>) {\n const { repository, authenticate, authorize, routes, scope, isStrict = true } = opts;\n\n const factoryScope = `SearchControllerFactory.build | repository: ${repository.name}`;\n const isRawAllowed = SearchRawAccess.resolve({\n scope: factoryScope,\n modes: opts.modes,\n isScoped: scope !== undefined,\n });\n const allowedEngineParams = SearchEngineParams.resolveAllowlist({\n scope: factoryScope,\n allow: opts.engineParams?.allow,\n });\n\n if (scope && routes.multiSearch) {\n throw getError({\n message: `[SearchControllerFactory.build] A scoped search controller cannot serve multi-search | repository: ${repository.name} | leave routes.multiSearch out`,\n });\n }\n\n const model = MetadataRegistry.getInstance().getRepositoryBinding({\n target: repository,\n })?.model;\n\n if (!model) {\n throw getError({\n message: `[SearchControllerFactory.build] Cannot resolve the entity | repository: ${repository.name} | declare it with @repository({ model })`,\n });\n }\n\n const entityClass: TClass<AbstractEntity> = isClass(model) ? model : model();\n const entityInstance = new entityClass();\n\n const selectSchema = entityInstance.getSchema<z.ZodType>({ type: SchemaTypes.SELECT });\n const routeDefinitions = SearchControllerFactory.defineRouteConfigs({\n selectSchema,\n authenticate,\n authorize,\n });\n\n const controllerClass = class extends AbstractSearchController<\n AbstractEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject\n > {\n constructor(repositoryInstance: ReadableSearchRepository<TDataObject>) {\n super({\n scope: new.target.name,\n isStrict,\n repository: repositoryInstance,\n definitions: routeDefinitions,\n searchScope: scope as TSearchScopeResolver<RouteEnv> | undefined,\n allowedEngineParams,\n isRawAllowed,\n });\n }\n\n /** The routes of a generated controller come from `routes`; a subclass adds its own here. */\n override binding(): ValueOrPromise<void> {}\n\n /** Registers each listed route, after the subclass's `binding()`. */\n override bindDefaultRoutes(): ValueOrPromise<void> {\n if (routes.search) {\n this.defineRoute({\n configs: routeDefinitions.SEARCH,\n handler: async (context) => this.search({ context }),\n });\n }\n\n if (routes.multiSearch) {\n this.defineRoute({\n configs: routeDefinitions.MULTI_SEARCH,\n handler: async (context) => this.multiSearch({ context }),\n });\n }\n }\n };\n\n CrudControllerFactory.registerRepositoryInjection({\n target: controllerClass,\n factoryName: 'SearchControllerFactory.build',\n repositoryName: repository.name,\n });\n\n return controllerClass;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/factory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC7F,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAIlE,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAEnD,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAE9F,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAsE/C,wHAAwH;AACxH,MAAM,OAAO,uBA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CAAC;gBAED,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;oBACvB,IAAI,CAAC,WAAW,CAAC;wBACf,OAAO,EAAE,gBAAgB,CAAC,YAAY;wBACtC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,OAAO,EAAE,CAAC;qBAC1D,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;SACF,CAAC;QAEF,qBAAqB,CAAC,2BAA2B,CAAC;YAChD,MAAM,EAAE,eAAe;YACvB,WAAW,EAAE,+BAA+B;YAC5C,cAAc,EAAE,UAAU,CAAC,IAAI;SAChC,CAAC,CAAC;QAEH,OAAO,eAAe,CAAC;IACzB,CAAC;CACF","sourcesContent":["import type { TRepositoryDataObject } from '@venizia/ignis-kernel';\nimport type { AbstractEntity } from '@venizia/ignis-kernel';\nimport { CrudControllerFactory, OpenApiResponses, SchemaTypes } from '@venizia/ignis-kernel';\nimport { MetadataRegistry } from '@venizia/ignis-kernel/metadata';\nimport type { TAuthMode, TAuthStrategy } from '@venizia/ignis-kernel';\nimport type { IAuthorizationSpec } from '@venizia/ignis-kernel';\nimport type { TCrudRepositoryClass } from '@venizia/ignis-kernel';\nimport { z } from '@hono/zod-openapi';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport { MultiSearchInputSchema, SearchInputSchema } from '@/search/core/repositories/common';\nimport type { ReadableSearchRepository } from '../repositories/core/readable';\nimport { AbstractSearchController } from './abstract';\nimport { SearchEngineParams } from './engine-params';\nimport { SearchRawAccess } from './raw-access';\nimport type { TSearchScopeResolver } from './scope';\n\n/** The routes of a search controller: only a listed route exists. */\nexport interface ISearchRoutes {\n search?: true;\n multiSearch?: true;\n}\n\n/** Configuration options for creating a search controller via SearchControllerFactory.build. */\nexport interface ISearchControllerOptions<\n Repository extends TCrudRepositoryClass = TCrudRepositoryClass,\n Shape extends z.ZodRawShape = {},\n> {\n /** The repository class; its name is the binding the container injects, and its `@repository({ model })` supplies the entity whose SELECT schema drives the `hits[].document` shape in the response. */\n repository: Repository;\n\n /** When true, /search and /search/ are different routes. @default true */\n isStrict?: boolean;\n\n /** Authentication config applied to both generated routes. */\n authenticate?: { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n\n /** Authorization config applied to both generated routes. */\n authorize?: IAuthorizationSpec | IAuthorizationSpec[];\n\n /** The routes to generate. */\n routes: ISearchRoutes;\n\n /**\n * A function of the request context returning the filter this caller may search within. It is\n * ANDed into `input.filter.where` on the server: the client's own `where` can narrow it, never\n * widen or remove it. Fails closed - a scope that is null, undefined or throws refuses the\n * request with 403. Return `ScopeFilters.UNRESTRICTED` to apply none for a trusted caller.\n *\n * `raw` mode hands the engine its own wire parameters, and a multi-search entry carries a raw\n * `filterBy`; neither can take a scope, so a scoped controller refuses `raw` (400) and must disable the\n * multi-search route (leave `routes.multiSearch` out), which `SearchControllerFactory.build` requires.\n * `engineParams` is refused on every controller unless `engineParams.allow` lists it.\n */\n scope?: TSearchScopeResolver<Env, z.infer<z.ZodObject<Shape>>>;\n\n /**\n * Adds keys to the body of `POST /search`, on every `mode`: `request.body.extend` is a Zod shape, and each key is\n * validated with the rest of the body (a bad value is a 400) and shown in the OpenAPI document. The validated body,\n * typed from the shape, reaches `scope` as `input`, so a facet the engine does not know can still narrow the scope\n * (an `ids` list that must all match, say). The extra keys are not search fields: nothing else reads them.\n * A key the base body already has is refused when the controller is built.\n */\n request?: { body?: { extend: Shape } };\n\n /**\n * Which engine parameters a caller may send in a request's `engineParams`. Unset or empty, a request that carries\n * `engineParams` is refused with 400, on a scoped and an unscoped controller alike: raw engine parameters can replace\n * the controller's own filter and name fields the model hides. A parameter that selects rows or fields, or orders\n * them (`filter_by`, `include_fields`, `query_by`, `facet_by`, `group_by`, `highlight_fields`, `sort_by`, a\n * `preset`, ...) can never be listed: the definition throws. Server code still passes `engineParams` on the\n * repository call.\n */\n engineParams?: { allow?: string[] };\n\n /**\n * `modes.raw.allow: true` serves `mode: 'raw'` and multi-search over HTTP. Left out, both answer 400: they hand the\n * engine their parameters as they are, so the model's default filter and its hidden fields do not apply to them, and\n * opting in exposes the whole collection to every caller the route admits. A scoped controller cannot opt in. Server\n * code keeps `search({ mode: 'raw' })` and `multiSearch()` on the repository.\n */\n modes?: { raw?: { allow?: boolean } };\n}\n\n/** Factory for generating turnkey search controllers (single-collection + cross-collection) from entity definitions. */\nexport class SearchControllerFactory extends BaseHelper {\n constructor() {\n super({ scope: SearchControllerFactory.name });\n }\n\n /** `SearchInputSchema` with `shape` added to each of its four modes (a discriminated union has no `extend` of its own). */\n private static extendSearchBody(opts: { shape: z.ZodRawShape }) {\n const { shape } = opts;\n const [keyword, semantic, hybrid, raw] = SearchInputSchema.options;\n const taken = Object.keys(shape).filter(\n (key) =>\n key in keyword.shape || key in semantic.shape || key in hybrid.shape || key in raw.shape,\n );\n\n if (taken.length > 0) {\n throw getError({\n message: `[SearchControllerFactory.build] request.body.extend names keys the search body already has | keys: ${taken.join(', ')}`,\n });\n }\n\n // `extend` drops the `.describe()` of a member, and the OpenAPI document shows it as the name of the mode.\n return z.discriminatedUnion('mode', [\n keyword.extend(shape).describe(keyword.description ?? ''),\n semantic.extend(shape).describe(semantic.description ?? ''),\n hybrid.extend(shape).describe(hybrid.description ?? ''),\n raw.extend(shape).describe(raw.description ?? ''),\n ]);\n }\n\n static defineRouteConfigs(opts: {\n selectSchema: z.ZodType;\n authenticate?: { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n authorize?: IAuthorizationSpec | IAuthorizationSpec[];\n /** The keys `request.body.extend` adds to every `mode` of the search body; none leaves `SearchInputSchema` as it is. */\n bodyExtension?: z.ZodRawShape;\n }) {\n const { selectSchema, authenticate, authorize, bodyExtension } = opts;\n const searchBodySchema = bodyExtension\n ? SearchControllerFactory.extendSearchBody({ shape: bodyExtension })\n : SearchInputSchema;\n\n const searchResponseSchema = z.object({\n found: z.number(),\n isFoundExact: z\n .boolean()\n .openapi({ description: 'False when the engine reports `found` as an estimate.' }),\n hits: z.array(z.object({ document: selectSchema })),\n });\n\n const multiSearchResponseSchema = z.record(z.string(), z.unknown());\n\n const resolvedAuthenticate = authenticate ?? {};\n\n return {\n SEARCH: {\n method: HTTP.Methods.POST,\n path: '/search',\n description: 'Single-collection search (keyword, semantic, hybrid, or raw passthrough)',\n authenticate: resolvedAuthenticate,\n authorize,\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Search input, discriminated by mode',\n schema: searchBodySchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n description: 'Search results',\n schema: searchResponseSchema,\n }),\n },\n\n MULTI_SEARCH: {\n method: HTTP.Methods.POST,\n path: '/multi-search',\n description: 'Cross-collection search, forwarded verbatim to the search engine',\n authenticate: resolvedAuthenticate,\n authorize,\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Multi-search input - one or more per-collection native search params',\n schema: MultiSearchInputSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n description: 'Federated (or, when union is true, merged) search results',\n schema: multiSearchResponseSchema,\n }),\n },\n } as const;\n }\n\n /** Creates a search controller with the routes you list: `POST /search` via `repository.search()`, and `POST /multi-search` via `repository.dataSource.multiSearch()`. The path is the `@controller({ path })` of the subclass. */\n static build<\n Repository extends TCrudRepositoryClass,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TRepositoryDataObject<InstanceType<Repository>>,\n Shape extends z.ZodRawShape = {},\n >(opts: ISearchControllerOptions<Repository, Shape>) {\n const { repository, authenticate, authorize, routes, scope, isStrict = true } = opts;\n\n const factoryScope = `SearchControllerFactory.build | repository: ${repository.name}`;\n const isRawAllowed = SearchRawAccess.resolve({\n scope: factoryScope,\n modes: opts.modes,\n isScoped: scope !== undefined,\n });\n const allowedEngineParams = SearchEngineParams.resolveAllowlist({\n scope: factoryScope,\n allow: opts.engineParams?.allow,\n });\n\n if (scope && routes.multiSearch) {\n throw getError({\n message: `[SearchControllerFactory.build] A scoped search controller cannot serve multi-search | repository: ${repository.name} | leave routes.multiSearch out`,\n });\n }\n\n const model = MetadataRegistry.getInstance().getRepositoryBinding({\n target: repository,\n })?.model;\n\n if (!model) {\n throw getError({\n message: `[SearchControllerFactory.build] Cannot resolve the entity | repository: ${repository.name} | declare it with @repository({ model })`,\n });\n }\n\n const entityClass: TClass<AbstractEntity> = isClass(model) ? model : model();\n const entityInstance = new entityClass();\n\n const selectSchema = entityInstance.getSchema<z.ZodType>({ type: SchemaTypes.SELECT });\n const routeDefinitions = SearchControllerFactory.defineRouteConfigs({\n selectSchema,\n authenticate,\n authorize,\n bodyExtension: opts.request?.body?.extend,\n });\n\n const controllerClass = class extends AbstractSearchController<\n AbstractEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n z.infer<z.ZodObject<Shape>>\n > {\n constructor(repositoryInstance: ReadableSearchRepository<TDataObject>) {\n super({\n scope: new.target.name,\n isStrict,\n repository: repositoryInstance,\n definitions: routeDefinitions,\n searchScope: scope as\n | TSearchScopeResolver<RouteEnv, z.infer<z.ZodObject<Shape>>>\n | undefined,\n allowedEngineParams,\n isRawAllowed,\n isBodyExtended: opts.request?.body !== undefined,\n });\n }\n\n /** The routes of a generated controller come from `routes`; a subclass adds its own here. */\n override binding(): ValueOrPromise<void> {}\n\n /** Registers each listed route, after the subclass's `binding()`. */\n override bindDefaultRoutes(): ValueOrPromise<void> {\n if (routes.search) {\n this.defineRoute({\n configs: routeDefinitions.SEARCH,\n handler: async (context) => this.search({ context }),\n });\n }\n\n if (routes.multiSearch) {\n this.defineRoute({\n configs: routeDefinitions.MULTI_SEARCH,\n handler: async (context) => this.multiSearch({ context }),\n });\n }\n }\n };\n\n CrudControllerFactory.registerRepositoryInjection({\n target: controllerClass,\n factoryName: 'SearchControllerFactory.build',\n repositoryName: repository.name,\n });\n\n return controllerClass;\n }\n}\n"]}
|
|
@@ -8,8 +8,10 @@ import type { TSearchInput } from '../repositories/common/index.js';
|
|
|
8
8
|
* sharing rule). Return a `where`, `ScopeFilters.UNRESTRICTED` to apply none for this call, or
|
|
9
9
|
* null/undefined when the caller's scope is unknown - which refuses the request.
|
|
10
10
|
*/
|
|
11
|
-
export type TSearchScopeResolver<RouteEnv extends Env = Env> = (opts: {
|
|
11
|
+
export type TSearchScopeResolver<RouteEnv extends Env = Env, TExtra extends object = {}> = (opts: {
|
|
12
12
|
context: TRouteContext<RouteEnv>;
|
|
13
|
+
/** The validated request body: the search input, and the keys the controller's `request.body.extend` adds. */
|
|
14
|
+
input: TSearchInput & TExtra;
|
|
13
15
|
}) => ValueOrPromise<TWhere | typeof ScopeFilters.UNRESTRICTED | null | undefined>;
|
|
14
16
|
export declare class SearchControllerScope {
|
|
15
17
|
private static refuse;
|
|
@@ -23,10 +25,10 @@ export declare class SearchControllerScope {
|
|
|
23
25
|
* ANDed into, so a scoped controller refuses it (400). `engineParams` is checked before this, on every controller
|
|
24
26
|
* (`SearchEngineParams`): what a controller allows there never selects rows or fields.
|
|
25
27
|
*/
|
|
26
|
-
static applySearchScope<RouteEnv extends Env = Env>(opts: {
|
|
27
|
-
resolve: TSearchScopeResolver<RouteEnv>;
|
|
28
|
+
static applySearchScope<RouteEnv extends Env = Env, TExtra extends object = {}>(opts: {
|
|
29
|
+
resolve: TSearchScopeResolver<RouteEnv, TExtra>;
|
|
28
30
|
context: TRouteContext<RouteEnv>;
|
|
29
|
-
input: TSearchInput;
|
|
31
|
+
input: TSearchInput & TExtra;
|
|
30
32
|
}): Promise<TSearchInput>;
|
|
31
33
|
}
|
|
32
34
|
//# sourceMappingURL=scope.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAIrD,OAAO,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAIrD,OAAO,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAahE,MAAM,OAAO,qBAAqB;IACxB,MAAM,CAAC,MAAM,CAAC,IAA8D;QAClF,OAAO,QAAQ,CAAC;YACd,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAyD,IAIrF;QACC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEzC,IAAI,KAAkE,CAAC;QAEvE,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YACjD,KAAK,GAAG,MAAM,CAAC;QACjB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,qBAAqB,CAAC,MAAM,CAAC;gBACjC,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS;gBAC3C,OAAO,EAAE,kEAAkE;gBAC3E,KAAK,EAAE,KAAK;aACb,CAAC,CAAC;QACL,CAAC;QAED,IAAI,KAAK,KAAK,YAAY,CAAC,YAAY,EAAE,CAAC;YACxC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YAC1C,MAAM,qBAAqB,CAAC,MAAM,CAAC;gBACjC,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS;gBAC3C,OAAO,EAAE,2CAA2C;aACrD,CAAC,CAAC;QACL,CAAC;QAED,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,GAAG,EAAE,CAAC;YACnC,MAAM,qBAAqB,CAAC,MAAM,CAAC;gBACjC,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;gBAC5C,OAAO,EAAE,oEAAoE;aAC9E,CAAC,CAAC;QACL,CAAC;QAED,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC;QAExC,OAAO;YACL,GAAG,KAAK;YACR,MAAM,EAAE;gBACN,GAAG,KAAK,CAAC,MAAM;gBACf,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAAK,EAAE,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK;aAC3D;SACc,CAAC;IACpB,CAAC;CACF","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { ScopeFilters } from '@venizia/ignis-kernel';\nimport type { TRouteContext, TWhere } from '@venizia/ignis-kernel';\nimport type { Env } from 'hono';\nimport type { TSearchInput } from '@/search/core/repositories/common';\nimport { SearchModes } from '@/search/core/repositories/common';\n\n/**\n * A per-request search scope: the filter the caller is allowed to search within (a merchant, a\n * sharing rule). Return a `where`, `ScopeFilters.UNRESTRICTED` to apply none for this call, or\n * null/undefined when the caller's scope is unknown - which refuses the request.\n */\nexport type TSearchScopeResolver<RouteEnv extends Env = Env, TExtra extends object = {}> = (opts: {\n context: TRouteContext<RouteEnv>;\n /** The validated request body: the search input, and the keys the controller's `request.body.extend` adds. */\n input: TSearchInput & TExtra;\n}) => ValueOrPromise<TWhere | typeof ScopeFilters.UNRESTRICTED | null | undefined>;\n\nexport class SearchControllerScope {\n private static refuse(opts: { statusCode: number; message: string; cause?: unknown }) {\n return getError({\n statusCode: opts.statusCode,\n message: opts.message,\n cause: opts.cause,\n });\n }\n\n /**\n * ANDs the resolved scope into `input.filter.where`, on the server, after the body was validated.\n * The client's own `where` is kept inside the AND, so it can narrow the scope and never widen it.\n *\n * Fails closed:\n * - a scope that is null, undefined, or throws refuses the request (403);\n * - `raw` mode hands the engine its own wire parameters (`filter_by` among them), which a `where` cannot be\n * ANDed into, so a scoped controller refuses it (400). `engineParams` is checked before this, on every controller\n * (`SearchEngineParams`): what a controller allows there never selects rows or fields.\n */\n static async applySearchScope<RouteEnv extends Env = Env, TExtra extends object = {}>(opts: {\n resolve: TSearchScopeResolver<RouteEnv, TExtra>;\n context: TRouteContext<RouteEnv>;\n input: TSearchInput & TExtra;\n }): Promise<TSearchInput> {\n const { resolve, context, input } = opts;\n\n let scope: Awaited<ReturnType<TSearchScopeResolver<RouteEnv, TExtra>>>;\n\n try {\n const result = await resolve({ context, input });\n scope = result;\n } catch (error) {\n throw SearchControllerScope.refuse({\n statusCode: HTTP.ResultCodes.RS_4.Forbidden,\n message: '[search] the search scope could not be resolved for this request',\n cause: error,\n });\n }\n\n if (scope === ScopeFilters.UNRESTRICTED) {\n return input;\n }\n\n if (scope === null || scope === undefined) {\n throw SearchControllerScope.refuse({\n statusCode: HTTP.ResultCodes.RS_4.Forbidden,\n message: '[search] no search scope for this request',\n });\n }\n\n if (input.mode === SearchModes.RAW) {\n throw SearchControllerScope.refuse({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: \"[search] mode 'raw' is not available on a scoped search controller\",\n });\n }\n\n const clientWhere = input.filter?.where;\n\n return {\n ...input,\n filter: {\n ...input.filter,\n where: clientWhere ? { and: [scope, clientWhere] } : scope,\n },\n } as TSearchInput;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@venizia/ignis-connectors",
|
|
3
|
-
"version": "0.4.8-
|
|
3
|
+
"version": "0.4.8-14",
|
|
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": {
|
|
@@ -97,16 +97,16 @@
|
|
|
97
97
|
"force-update": "sh ../../scripts/build/force-update.sh"
|
|
98
98
|
},
|
|
99
99
|
"dependencies": {
|
|
100
|
-
"@venizia/ignis-filter": "0.4.7-
|
|
101
|
-
"@venizia/ignis-helpers": "0.4.8-
|
|
102
|
-
"@venizia/ignis-inversion": "0.4.7-
|
|
103
|
-
"@venizia/ignis-kernel": "0.4.8-
|
|
100
|
+
"@venizia/ignis-filter": "0.4.7-5",
|
|
101
|
+
"@venizia/ignis-helpers": "0.4.8-12",
|
|
102
|
+
"@venizia/ignis-inversion": "0.4.7-4",
|
|
103
|
+
"@venizia/ignis-kernel": "0.4.8-14",
|
|
104
104
|
"zod": "^4.6.7"
|
|
105
105
|
},
|
|
106
106
|
"devDependencies": {
|
|
107
107
|
"@types/bun": "^1.4.3",
|
|
108
108
|
"@types/pg": "^8.23.1",
|
|
109
|
-
"@venizia/dev-configs": "0.4.8-
|
|
109
|
+
"@venizia/dev-configs": "0.4.8-9",
|
|
110
110
|
"eslint": "^10.13.0",
|
|
111
111
|
"oxlint": "1.89.0",
|
|
112
112
|
"oxlint-tsgolint": "7.0.2004",
|