@ahoo-wang/wow-client 9.8.0 → 10.0.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/query/dataset/datasetDescriptorEndpoint.cjs +2 -0
- package/dist/client/query/dataset/datasetDescriptorEndpoint.cjs.map +1 -0
- package/dist/client/query/dataset/datasetDescriptorEndpoint.d.cts +8 -0
- package/dist/client/query/dataset/datasetDescriptorEndpoint.d.ts +8 -0
- package/dist/client/query/dataset/datasetDescriptorEndpoint.es.js +34 -0
- package/dist/client/query/dataset/datasetDescriptorEndpoint.es.js.map +1 -0
- package/dist/client/query/dataset/datasetDirectoryClient.cjs +2 -0
- package/dist/client/query/dataset/datasetDirectoryClient.cjs.map +1 -0
- package/dist/client/query/dataset/datasetDirectoryClient.d.cts +29 -0
- package/dist/client/query/dataset/datasetDirectoryClient.d.ts +29 -0
- package/dist/client/query/dataset/datasetDirectoryClient.es.js +25 -0
- package/dist/client/query/dataset/datasetDirectoryClient.es.js.map +1 -0
- package/dist/client/query/dataset/datasetQueryApi.d.cts +40 -0
- package/dist/client/query/dataset/datasetQueryApi.d.ts +40 -0
- package/dist/client/query/dataset/datasetQueryClient.cjs +2 -0
- package/dist/client/query/dataset/datasetQueryClient.cjs.map +1 -0
- package/dist/client/query/dataset/datasetQueryClient.d.cts +57 -0
- package/dist/client/query/dataset/datasetQueryClient.d.ts +57 -0
- package/dist/client/query/dataset/datasetQueryClient.es.js +154 -0
- package/dist/client/query/dataset/datasetQueryClient.es.js.map +1 -0
- package/dist/client/query/dataset/endpointPaths.cjs +2 -0
- package/dist/client/query/dataset/endpointPaths.cjs.map +1 -0
- package/dist/client/query/dataset/endpointPaths.d.cts +9 -0
- package/dist/client/query/dataset/endpointPaths.d.ts +9 -0
- package/dist/client/query/dataset/endpointPaths.es.js +14 -0
- package/dist/client/query/dataset/endpointPaths.es.js.map +1 -0
- package/dist/client/query/dataset/index.d.cts +3 -0
- package/dist/client/query/dataset/index.d.ts +3 -0
- package/dist/client/query/event/eventStreamQueryApi.d.cts +1 -1
- package/dist/client/query/event/eventStreamQueryApi.d.ts +1 -1
- package/dist/client/query/event/eventStreamQueryClient.cjs.map +1 -1
- package/dist/client/query/event/eventStreamQueryClient.d.cts +4 -1
- package/dist/client/query/event/eventStreamQueryClient.d.ts +4 -1
- package/dist/client/query/event/eventStreamQueryClient.es.js.map +1 -1
- package/dist/client/query/event/index.d.cts +0 -1
- package/dist/client/query/event/index.d.ts +0 -1
- package/dist/client/query/index.d.cts +1 -0
- package/dist/client/query/index.d.ts +1 -0
- package/dist/client/query/snapshot/index.d.cts +0 -1
- package/dist/client/query/snapshot/index.d.ts +0 -1
- package/dist/client/query/snapshot/snapshotQueryApi.d.cts +1 -1
- package/dist/client/query/snapshot/snapshotQueryApi.d.ts +1 -1
- package/dist/client/query/snapshot/snapshotQueryClient.cjs.map +1 -1
- package/dist/client/query/snapshot/snapshotQueryClient.d.cts +4 -1
- package/dist/client/query/snapshot/snapshotQueryClient.d.ts +4 -1
- package/dist/client/query/snapshot/snapshotQueryClient.es.js.map +1 -1
- package/dist/client/routing.cjs.map +1 -1
- package/dist/client/routing.d.cts +2 -2
- package/dist/client/routing.d.ts +2 -2
- package/dist/client/routing.es.js.map +1 -1
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +84 -65
- package/dist/dsl/aggregation/admit.es.js.map +1 -1
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.d.cts +16 -4
- package/dist/dsl/aggregation/builders.d.ts +16 -4
- package/dist/dsl/aggregation/builders.es.js +89 -78
- package/dist/dsl/aggregation/builders.es.js.map +1 -1
- package/dist/dsl/aggregation/derived.cjs +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.d.cts +32 -1
- package/dist/dsl/aggregation/derived.d.ts +32 -1
- package/dist/dsl/aggregation/derived.es.js +23 -1
- package/dist/dsl/aggregation/derived.es.js.map +1 -1
- package/dist/dsl/aggregation/types.cjs +1 -1
- package/dist/dsl/aggregation/types.cjs.map +1 -1
- package/dist/dsl/aggregation/types.d.cts +112 -7
- package/dist/dsl/aggregation/types.d.ts +112 -7
- package/dist/dsl/aggregation/types.es.js +19 -12
- package/dist/dsl/aggregation/types.es.js.map +1 -1
- package/dist/dsl/descriptor.cjs +1 -1
- package/dist/dsl/descriptor.cjs.map +1 -1
- package/dist/dsl/descriptor.d.cts +23 -1
- package/dist/dsl/descriptor.d.ts +23 -1
- package/dist/dsl/descriptor.es.js +2 -1
- package/dist/dsl/descriptor.es.js.map +1 -1
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.d.cts +2 -2
- package/dist/dsl.d.ts +2 -2
- package/dist/dsl.es.js +13 -13
- package/dist/error/headers.cjs.map +1 -1
- package/dist/error/headers.d.cts +3 -2
- package/dist/error/headers.d.ts +3 -2
- package/dist/error/headers.es.js.map +1 -1
- package/dist/error/queryErrorCodes.cjs +1 -1
- package/dist/error/queryErrorCodes.cjs.map +1 -1
- package/dist/error/queryErrorCodes.d.cts +7 -0
- package/dist/error/queryErrorCodes.d.ts +7 -0
- package/dist/error/queryErrorCodes.es.js +2 -1
- package/dist/error/queryErrorCodes.es.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.es.js +35 -33
- package/dist/model/domainEventStream.cjs.map +1 -0
- package/dist/{client/query/event → model}/domainEventStream.d.cts +5 -1
- package/dist/{client/query/event → model}/domainEventStream.d.ts +5 -1
- package/dist/{client/query/event → model}/domainEventStream.es.js +1 -1
- package/dist/model/domainEventStream.es.js.map +1 -0
- package/dist/model/index.d.cts +2 -0
- package/dist/model/index.d.ts +2 -0
- package/dist/model/snapshot.cjs.map +1 -0
- package/dist/{client/query/snapshot → model}/snapshot.d.cts +3 -1
- package/dist/{client/query/snapshot → model}/snapshot.d.ts +3 -1
- package/dist/{client/query/snapshot → model}/snapshot.es.js +1 -1
- package/dist/model/snapshot.es.js.map +1 -0
- package/dist/transport/eventStreams.cjs +1 -1
- package/dist/transport/eventStreams.cjs.map +1 -1
- package/dist/transport/eventStreams.d.cts +3 -1
- package/dist/transport/eventStreams.d.ts +3 -1
- package/dist/transport/eventStreams.es.js +7 -4
- package/dist/transport/eventStreams.es.js.map +1 -1
- package/dist/v10/commands.cjs +2 -0
- package/dist/v10/commands.cjs.map +1 -0
- package/dist/v10/commands.d.cts +105 -0
- package/dist/v10/commands.d.ts +105 -0
- package/dist/v10/commands.es.js +68 -0
- package/dist/v10/commands.es.js.map +1 -0
- package/dist/v10/http.cjs +2 -0
- package/dist/v10/http.cjs.map +1 -0
- package/dist/v10/http.d.cts +87 -0
- package/dist/v10/http.d.ts +87 -0
- package/dist/v10/http.es.js +73 -0
- package/dist/v10/http.es.js.map +1 -0
- package/dist/v10/index.d.cts +19 -0
- package/dist/v10/index.d.ts +19 -0
- package/dist/v10/manifest.cjs +2 -0
- package/dist/v10/manifest.cjs.map +1 -0
- package/dist/v10/manifest.d.cts +109 -0
- package/dist/v10/manifest.d.ts +109 -0
- package/dist/v10/manifest.es.js +14 -0
- package/dist/v10/manifest.es.js.map +1 -0
- package/dist/v10/problem.cjs +2 -0
- package/dist/v10/problem.cjs.map +1 -0
- package/dist/v10/problem.d.cts +164 -0
- package/dist/v10/problem.d.ts +164 -0
- package/dist/v10/problem.es.js +119 -0
- package/dist/v10/problem.es.js.map +1 -0
- package/dist/v10/queries.cjs +2 -0
- package/dist/v10/queries.cjs.map +1 -0
- package/dist/v10/queries.d.cts +136 -0
- package/dist/v10/queries.d.ts +136 -0
- package/dist/v10/queries.es.js +88 -0
- package/dist/v10/queries.es.js.map +1 -0
- package/dist/v10/state.cjs +2 -0
- package/dist/v10/state.cjs.map +1 -0
- package/dist/v10/state.d.cts +53 -0
- package/dist/v10/state.d.ts +53 -0
- package/dist/v10/state.es.js +51 -0
- package/dist/v10/state.es.js.map +1 -0
- package/dist/v10/streams.cjs +2 -0
- package/dist/v10/streams.cjs.map +1 -0
- package/dist/v10/streams.d.cts +14 -0
- package/dist/v10/streams.d.ts +14 -0
- package/dist/v10/streams.es.js +22 -0
- package/dist/v10/streams.es.js.map +1 -0
- package/dist/v10/wait.cjs +2 -0
- package/dist/v10/wait.cjs.map +1 -0
- package/dist/v10/wait.d.cts +61 -0
- package/dist/v10/wait.d.ts +61 -0
- package/dist/v10/wait.es.js +44 -0
- package/dist/v10/wait.es.js.map +1 -0
- package/dist/v10/wire.cjs +2 -0
- package/dist/v10/wire.cjs.map +1 -0
- package/dist/v10/wire.d.cts +301 -0
- package/dist/v10/wire.d.ts +301 -0
- package/dist/v10/wire.es.js +10 -0
- package/dist/v10/wire.es.js.map +1 -0
- package/dist/v10.cjs +1 -0
- package/dist/v10.es.js +9 -0
- package/package.json +12 -2
- package/dist/client/query/event/domainEventStream.cjs.map +0 -1
- package/dist/client/query/event/domainEventStream.es.js.map +0 -1
- package/dist/client/query/snapshot/snapshot.cjs.map +0 -1
- package/dist/client/query/snapshot/snapshot.es.js.map +0 -1
- /package/dist/{client/query/event → model}/domainEventStream.cjs +0 -0
- /package/dist/{client/query/snapshot → model}/snapshot.cjs +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshotQueryClient.es.js","names":["_decorate","_decorateParam","_decorateMetadata","__decorateMetadata","__decorateParam","__decorate","SnapshotQueryClient","apiMetadata","bindMethods","autoGeneratedError","query","attributes","abort","filter","listQuery","pagedQuery","singleQuery","id","ids","post","SnapshotQueryEndpointPaths","body","attribute","QUERY_STREAM_ENDPOINT","api"],"sources":["../../../../src/client/query/snapshot/snapshotQueryClient.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { SnapshotQueryApi } from './snapshotQueryApi.js';\nimport { SnapshotQueryEndpointPaths } from './endpointPaths.js';\nimport type { AggregationQuery } from '../../../dsl/aggregation/index.js';\nimport { filter, type FilterExpression } from '../../../dsl/filter/index.js';\nimport type {\n Condition,\n ListQueryRequest,\n PagedQueryRequest,\n SingleQueryRequest,\n} from '../requests.js';\nimport {\n listQuery,\n type PagedList,\n singleQuery,\n} from '../../../dsl/queryable.js';\nimport type { MaterializedSnapshot } from './snapshot.js';\nimport type { DynamicDocument } from '../../../dsl/documents.js';\nimport type { CursorPage, CursorQuery } from '../../../dsl/cursorQuery.js';\nimport { QUERY_STREAM_ENDPOINT } from '../../../transport/endpoints.js';\nimport type {\n ApiMetadata,\n ApiMetadataCapable,\n} from '@ahoo-wang/fetcher-decorator';\nimport {\n api,\n attribute,\n autoGeneratedError,\n body,\n post,\n} from '@ahoo-wang/fetcher-decorator';\nimport { bindMethods } from '../../bindMethods.js';\n\n/**\n * A client for querying snapshot data through HTTP endpoints.\n * Provides methods for various query operations such as counting, listing, paging, and retrieving single snapshots.\n *\n * @example\n * ```typescript\n * // Define the state interface\n * interface CartItem {\n * productId: string;\n * quantity: number;\n * }\n *\n * interface CartState {\n * items: CartItem[];\n * }\n *\n * // Create client options configuration\n * const clientOptions: ApiMetadata = {\n * fetcher: new Fetcher({ baseURL: 'http://localhost:8080/' }),\n * basePath: 'owner/{ownerId}/cart'\n * };\n *\n * // Create a snapshot query client instance\n * const snapshotQueryClient = new SnapshotQueryClient<CartState>(clientOptions);\n *\n * // Count snapshots\n * const count = await snapshotQueryClient.count(filter.matchAll());\n *\n * // List snapshots\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const list = await snapshotQueryClient.list(listQuery);\n *\n * // List snapshots as stream\n * const listStream = await snapshotQueryClient.listStream(listQuery);\n * for await (const snapshot of listStream) {\n * console.log('Received:', snapshot);\n * }\n *\n * // List snapshot states\n * const stateList = await snapshotQueryClient.listState(listQuery);\n *\n * // List snapshot states as stream\n * const stateListStream = await snapshotQueryClient.listStateStream(listQuery);\n * for await (const state of stateListStream) {\n * console.log('Received state:', state);\n * }\n *\n * // Paged snapshots\n * const pagedQuery: FilterPagedQuery = {\n * filter: filter.matchAll(),\n * pagination: { index: 1, size: 10 }\n * };\n * const paged = await snapshotQueryClient.paged(pagedQuery);\n *\n * // Paged snapshot states\n * const pagedState = await snapshotQueryClient.pagedState(pagedQuery);\n *\n * // Single snapshot\n * const singleQuery: FilterSingleQuery = {\n * filter: filter.matchAll()\n * };\n * const single = await snapshotQueryClient.single(singleQuery);\n *\n * // Single snapshot state\n * const singleState = await snapshotQueryClient.singleState(singleQuery);\n * ```\n *\n * @template S The type of the snapshot state\n */\n@api()\nexport class SnapshotQueryClient<S, FIELDS extends string = string>\n implements SnapshotQueryApi<S, FIELDS>, ApiMetadataCapable\n{\n /**\n * Creates a new SnapshotQueryClient instance.\n */\n constructor(public readonly apiMetadata?: ApiMetadata) {\n bindMethods(this);\n }\n\n /** Runs a snapshot aggregation and returns all result rows. */\n @post(SnapshotQueryEndpointPaths.AGGREGATION)\n /* v8 ignore start */\n aggregate<\n Row extends object = DynamicDocument,\n AGGREGATION_FIELDS extends string = string,\n >(\n @body() query: AggregationQuery<FIELDS, AGGREGATION_FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<Row[]> {\n throw autoGeneratedError(query, attributes, abort);\n }\n /* v8 ignore stop */\n\n /** Runs a snapshot aggregation and streams the result rows, one per server-sent event. */\n @post(SnapshotQueryEndpointPaths.AGGREGATION, QUERY_STREAM_ENDPOINT)\n /* v8 ignore start */\n aggregateStream<\n Row extends object = DynamicDocument,\n AGGREGATION_FIELDS extends string = string,\n >(\n @body() query: AggregationQuery<FIELDS, AGGREGATION_FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<ReadableStream<Row>> {\n throw autoGeneratedError(query, attributes, abort);\n }\n /* v8 ignore stop */\n\n /** Retrieves the next cursor page of materialized snapshots. */\n @post(SnapshotQueryEndpointPaths.CURSOR)\n /* v8 ignore start */\n cursor<T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>>(\n @body() query: CursorQuery<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<CursorPage<T>> {\n throw autoGeneratedError(query, attributes, abort);\n }\n /* v8 ignore stop */\n\n /** Retrieves the next cursor page of snapshot states. */\n @post(SnapshotQueryEndpointPaths.CURSOR_STATE)\n /* v8 ignore start */\n cursorState<T extends Partial<S> = S>(\n @body() query: CursorQuery<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<CursorPage<T>> {\n throw autoGeneratedError(query, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Counts the number of snapshots that match the given filter.\n *\n * @param filter - The filter expression or legacy condition\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to the count of matching snapshots\n *\n * @example\n * ```typescript\n * const count = await snapshotQueryClient.count(filter.matchAll());\n * console.log('Total snapshots:', count);\n * ```\n */\n @post(SnapshotQueryEndpointPaths.COUNT)\n /* v8 ignore start */\n count(\n // compat(wow<9): accepts the deprecated Condition, which Wow < 8.11 needs; narrow to FilterExpression in v10.\n @body() filter: FilterExpression<FIELDS> | Condition<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<number> {\n throw autoGeneratedError(filter, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a list of materialized snapshots based on the provided query parameters.\n *\n * @param listQuery - The query parameters for listing snapshots\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to an array of partial materialized snapshots\n *\n * @example\n * ```typescript\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const list = await snapshotQueryClient.list(listQuery);\n * for (const snapshot of list) {\n * console.log('Snapshot:', snapshot);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.LIST)\n /* v8 ignore start */\n list<T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>>(\n @body() listQuery: ListQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<T[]> {\n throw autoGeneratedError(listQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a stream of materialized snapshots based on the provided query parameters.\n *\n * @param listQuery - The query parameters for listing snapshots\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a readable stream of partial materialized snapshots\n *\n * @example\n * ```typescript\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const listStream = await snapshotQueryClient.listStream(listQuery);\n * for await (const snapshot of listStream) {\n * console.log('Received snapshot:', snapshot);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.LIST, QUERY_STREAM_ENDPOINT)\n /* v8 ignore start */\n listStream<\n T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>,\n >(\n @body() listQuery: ListQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<ReadableStream<T>> {\n throw autoGeneratedError(listQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a list of snapshot states based on the provided query parameters.\n *\n * @param listQuery - The query parameters for listing snapshot states\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to an array of partial snapshot states\n *\n * @example\n * ```typescript\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const list = await snapshotQueryClient.listState(listQuery);\n * for (const state of list) {\n * console.log('State:', state);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.LIST_STATE)\n /* v8 ignore start */\n listState<T extends Partial<S> = S>(\n @body() listQuery: ListQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<T[]> {\n throw autoGeneratedError(listQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a stream of snapshot states based on the provided query parameters.\n *\n * @param listQuery - The query parameters for listing snapshot states\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a readable stream of partial snapshot states\n *\n * @example\n * ```typescript\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const listStream = await snapshotQueryClient.listStateStream(listQuery);\n * for await (const state of listStream) {\n * console.log('Received state:', state);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.LIST_STATE, QUERY_STREAM_ENDPOINT)\n /* v8 ignore start */\n listStateStream<T extends Partial<S> = S>(\n @body() listQuery: ListQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<ReadableStream<T>> {\n throw autoGeneratedError(listQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a paged list of materialized snapshots based on the provided query parameters.\n *\n * @param pagedQuery - The query parameters for paging snapshots\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a paged list of partial materialized snapshots\n *\n * @example\n * ```typescript\n * const pagedQuery: FilterPagedQuery = {\n * filter: filter.matchAll(),\n * pagination: { index: 1, size: 10 }\n * };\n * const paged = await snapshotQueryClient.paged(pagedQuery);\n * console.log('Total:', paged.total);\n * for (const snapshot of paged.list) {\n * console.log('Snapshot:', snapshot);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.PAGED)\n /* v8 ignore start */\n paged<T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>>(\n @body() pagedQuery: PagedQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<PagedList<T>> {\n throw autoGeneratedError(pagedQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a paged list of snapshot states based on the provided query parameters.\n *\n * @param pagedQuery - The query parameters for paging snapshot states\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a paged list of partial snapshot states\n *\n * @example\n * ```typescript\n * const pagedQuery: FilterPagedQuery = {\n * filter: filter.matchAll(),\n * pagination: { index: 1, size: 10 }\n * };\n * const pagedState = await snapshotQueryClient.pagedState(pagedQuery);\n * for (const state of pagedState.list) {\n * console.log('State:', state);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.PAGED_STATE)\n /* v8 ignore start */\n pagedState<T extends Partial<S> = S>(\n @body() pagedQuery: PagedQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<PagedList<T>> {\n throw autoGeneratedError(pagedQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a single materialized snapshot based on the provided query parameters.\n *\n * @param singleQuery - The query parameters for retrieving a single snapshot\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a partial materialized snapshot\n *\n * @example\n * ```typescript\n * const singleQuery: FilterSingleQuery = {\n * filter: filter.matchAll()\n * };\n * const single = await snapshotQueryClient.single(singleQuery);\n * console.log('Snapshot:', single);\n * ```\n */\n @post(SnapshotQueryEndpointPaths.SINGLE)\n /* v8 ignore start */\n single<T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>>(\n @body() singleQuery: SingleQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<T> {\n throw autoGeneratedError(singleQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a single snapshot state based on the provided query parameters.\n *\n * @param singleQuery - The query parameters for retrieving a single snapshot state\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a partial snapshot state\n *\n * @example\n * ```typescript\n * const singleQuery: FilterSingleQuery = {\n * filter: filter.matchAll()\n * };\n * const singleState = await snapshotQueryClient.singleState(singleQuery);\n * console.log('State:', singleState);\n * ```\n */\n @post(SnapshotQueryEndpointPaths.SINGLE_STATE)\n /* v8 ignore start */\n singleState<T extends Partial<S> = S>(\n @body() singleQuery: SingleQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<T> {\n throw autoGeneratedError(singleQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a single materialized snapshot by its ID.\n *\n * @param id - The unique identifier of the snapshot to retrieve\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to the materialized snapshot with the specified ID\n *\n * @example\n * ```typescript\n * const snapshot = await snapshotQueryClient.getById('snapshot-123');\n * console.log('Snapshot:', snapshot);\n * ```\n */\n getById(\n id: string,\n attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<MaterializedSnapshot<S>> {\n const query = singleQuery<FIELDS>({ filter: filter.aggregateId(id) });\n return this.single(query, attributes, abort);\n }\n\n /**\n * Retrieves a single snapshot state by its ID.\n *\n * @param id - The unique identifier of the snapshot whose state to retrieve\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to the snapshot state with the specified ID\n *\n * @example\n * ```typescript\n * const state = await snapshotQueryClient.getStateById('snapshot-123');\n * console.log('State:', state);\n * ```\n */\n getStateById(\n id: string,\n attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<S> {\n const query = singleQuery<FIELDS>({ filter: filter.aggregateId(id) });\n return this.singleState(query, attributes, abort);\n }\n\n /**\n * Retrieves multiple materialized snapshots by their IDs.\n *\n * One request, filtered by `filter.aggregateIds(ids)` with `limit` set to\n * the number of ids; an empty `ids` sends nothing and resolves to `[]`. The\n * server refuses more ids than its filter value limit and its maximum list\n * size (1000 each by default), so split a larger set into batches.\n *\n * @param ids - An array of unique identifiers of the snapshots to retrieve\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to an array of materialized snapshots with the specified IDs\n *\n * @example\n * ```typescript\n * const snapshots = await snapshotQueryClient.getByIds(['snapshot-123', 'snapshot-456']);\n * for (const snapshot of snapshots) {\n * console.log('Snapshot:', snapshot);\n * }\n * ```\n */\n getByIds(\n ids: string[],\n attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<MaterializedSnapshot<S>[]> {\n if (ids.length === 0) return Promise.resolve([]);\n const query = listQuery<FIELDS>({\n filter: filter.aggregateIds(ids),\n limit: ids.length,\n });\n return this.list(query, attributes, abort);\n }\n\n /**\n * Retrieves multiple snapshot states by their IDs.\n *\n * One request, filtered by `filter.aggregateIds(ids)` with `limit` set to\n * the number of ids; an empty `ids` sends nothing and resolves to `[]`. The\n * server refuses more ids than its filter value limit and its maximum list\n * size (1000 each by default), so split a larger set into batches.\n *\n * @param ids - An array of unique identifiers of the snapshots whose states to retrieve\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to an array of snapshot states with the specified IDs\n *\n * @example\n * ```typescript\n * const states = await snapshotQueryClient.getStateByIds(['snapshot-123', 'snapshot-456']);\n * for (const state of states) {\n * console.log('State:', state);\n * }\n * ```\n */\n getStateByIds(\n ids: string[],\n attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<S[]> {\n if (ids.length === 0) return Promise.resolve([]);\n const query = listQuery<FIELDS>({\n filter: filter.aggregateIds(ids),\n limit: ids.length,\n });\n return this.listState(query, attributes, abort);\n }\n}\n"],"mappings":";;;;;;;;;;AAqHO,IAAMM,IAAN,MAEP;CAIE,YAAY,GAA2C;EACrD,AAD0B,KAAA,cAAAC,GAC1BC,EAAY,IAAI;CAClB;CAGA,UAME,GACA,GACA,GACgB;EAChB,MAAMC,EAAmBC,GAAOC,GAAYC,CAAK;CACnD;;CAIA,gBAME,GACA,GACA,GAC8B;EAC9B,MAAMH,EAAmBC,GAAOC,GAAYC,CAAK;CACnD;;CAIA,OAGE,GACA,GACA,GACwB;EACxB,MAAMH,EAAmBC,GAAOC,GAAYC,CAAK;CACnD;;CAIA,YAGE,GACA,GACA,GACwB;EACxB,MAAMH,EAAmBC,GAAOC,GAAYC,CAAK;CACnD;;CAmBA,MAIE,GACA,GACA,GACiB;EACjB,MAAMH,EAAmBI,GAAQF,GAAYC,CAAK;CACpD;;CAwBA,KAGE,GACA,GACA,GACc;EACd,MAAMH,EAAmBK,GAAWH,GAAYC,CAAK;CACvD;;CAwBA,WAKE,GACA,GACA,GAC4B;EAC5B,MAAMH,EAAmBK,GAAWH,GAAYC,CAAK;CACvD;;CAwBA,UAGE,GACA,GACA,GACc;EACd,MAAMH,EAAmBK,GAAWH,GAAYC,CAAK;CACvD;;CAwBA,gBAGE,GACA,GACA,GAC4B;EAC5B,MAAMH,EAAmBK,GAAWH,GAAYC,CAAK;CACvD;;CA0BA,MAGE,GACA,GACA,GACuB;EACvB,MAAMH,EAAmBM,GAAYJ,GAAYC,CAAK;CACxD;;CAyBA,WAGE,GACA,GACA,GACuB;EACvB,MAAMH,EAAmB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AAA,CAAA,GAAAI,CAAA"}
|
|
1
|
+
{"version":3,"file":"snapshotQueryClient.es.js","names":["_decorate","_decorateParam","_decorateMetadata","__decorateMetadata","__decorateParam","__decorate","SnapshotQueryClient","apiMetadata","bindMethods","autoGeneratedError","query","attributes","abort","filter","listQuery","pagedQuery","singleQuery","id","ids","post","SnapshotQueryEndpointPaths","body","attribute","QUERY_STREAM_ENDPOINT","api"],"sources":["../../../../src/client/query/snapshot/snapshotQueryClient.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { SnapshotQueryApi } from './snapshotQueryApi.js';\nimport { SnapshotQueryEndpointPaths } from './endpointPaths.js';\nimport type { AggregationQuery } from '../../../dsl/aggregation/index.js';\nimport { filter, type FilterExpression } from '../../../dsl/filter/index.js';\nimport type {\n Condition,\n ListQueryRequest,\n PagedQueryRequest,\n SingleQueryRequest,\n} from '../requests.js';\nimport {\n listQuery,\n type PagedList,\n singleQuery,\n} from '../../../dsl/queryable.js';\nimport type { MaterializedSnapshot } from '../../../model/snapshot.js';\nimport type { DynamicDocument } from '../../../dsl/documents.js';\nimport type { CursorPage, CursorQuery } from '../../../dsl/cursorQuery.js';\nimport { QUERY_STREAM_ENDPOINT } from '../../../transport/endpoints.js';\nimport type {\n ApiMetadata,\n ApiMetadataCapable,\n} from '@ahoo-wang/fetcher-decorator';\nimport {\n api,\n attribute,\n autoGeneratedError,\n body,\n post,\n} from '@ahoo-wang/fetcher-decorator';\nimport { bindMethods } from '../../bindMethods.js';\n\n/**\n * A client for querying snapshot data through HTTP endpoints.\n * Provides methods for various query operations such as counting, listing, paging, and retrieving single snapshots.\n *\n * @example\n * ```typescript\n * import { Fetcher } from '@ahoo-wang/fetcher';\n * import type { ApiMetadata } from '@ahoo-wang/fetcher-decorator';\n *\n * // Define the state interface\n * interface CartItem {\n * productId: string;\n * quantity: number;\n * }\n *\n * interface CartState {\n * items: CartItem[];\n * }\n *\n * // Create client options configuration\n * const clientOptions: ApiMetadata = {\n * fetcher: new Fetcher({ baseURL: 'http://localhost:8080/' }),\n * basePath: 'owner/{ownerId}/cart'\n * };\n *\n * // Create a snapshot query client instance\n * const snapshotQueryClient = new SnapshotQueryClient<CartState>(clientOptions);\n *\n * // Count snapshots\n * const count = await snapshotQueryClient.count(filter.matchAll());\n *\n * // List snapshots\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const list = await snapshotQueryClient.list(listQuery);\n *\n * // List snapshots as stream\n * const listStream = await snapshotQueryClient.listStream(listQuery);\n * for await (const snapshot of listStream) {\n * console.log('Received:', snapshot);\n * }\n *\n * // List snapshot states\n * const stateList = await snapshotQueryClient.listState(listQuery);\n *\n * // List snapshot states as stream\n * const stateListStream = await snapshotQueryClient.listStateStream(listQuery);\n * for await (const state of stateListStream) {\n * console.log('Received state:', state);\n * }\n *\n * // Paged snapshots\n * const pagedQuery: FilterPagedQuery = {\n * filter: filter.matchAll(),\n * pagination: { index: 1, size: 10 }\n * };\n * const paged = await snapshotQueryClient.paged(pagedQuery);\n *\n * // Paged snapshot states\n * const pagedState = await snapshotQueryClient.pagedState(pagedQuery);\n *\n * // Single snapshot\n * const singleQuery: FilterSingleQuery = {\n * filter: filter.matchAll()\n * };\n * const single = await snapshotQueryClient.single(singleQuery);\n *\n * // Single snapshot state\n * const singleState = await snapshotQueryClient.singleState(singleQuery);\n * ```\n *\n * @template S The type of the snapshot state\n */\n@api()\nexport class SnapshotQueryClient<S, FIELDS extends string = string>\n implements SnapshotQueryApi<S, FIELDS>, ApiMetadataCapable\n{\n /**\n * Creates a new SnapshotQueryClient instance.\n */\n constructor(public readonly apiMetadata?: ApiMetadata) {\n bindMethods(this);\n }\n\n /** Runs a snapshot aggregation and returns all result rows. */\n @post(SnapshotQueryEndpointPaths.AGGREGATION)\n /* v8 ignore start */\n aggregate<\n Row extends object = DynamicDocument,\n AGGREGATION_FIELDS extends string = string,\n >(\n @body() query: AggregationQuery<FIELDS, AGGREGATION_FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<Row[]> {\n throw autoGeneratedError(query, attributes, abort);\n }\n /* v8 ignore stop */\n\n /** Runs a snapshot aggregation and streams the result rows, one per server-sent event. */\n @post(SnapshotQueryEndpointPaths.AGGREGATION, QUERY_STREAM_ENDPOINT)\n /* v8 ignore start */\n aggregateStream<\n Row extends object = DynamicDocument,\n AGGREGATION_FIELDS extends string = string,\n >(\n @body() query: AggregationQuery<FIELDS, AGGREGATION_FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<ReadableStream<Row>> {\n throw autoGeneratedError(query, attributes, abort);\n }\n /* v8 ignore stop */\n\n /** Retrieves the next cursor page of materialized snapshots. */\n @post(SnapshotQueryEndpointPaths.CURSOR)\n /* v8 ignore start */\n cursor<T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>>(\n @body() query: CursorQuery<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<CursorPage<T>> {\n throw autoGeneratedError(query, attributes, abort);\n }\n /* v8 ignore stop */\n\n /** Retrieves the next cursor page of snapshot states. */\n @post(SnapshotQueryEndpointPaths.CURSOR_STATE)\n /* v8 ignore start */\n cursorState<T extends Partial<S> = S>(\n @body() query: CursorQuery<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<CursorPage<T>> {\n throw autoGeneratedError(query, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Counts the number of snapshots that match the given filter.\n *\n * @param filter - The filter expression or legacy condition\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to the count of matching snapshots\n *\n * @example\n * ```typescript\n * const count = await snapshotQueryClient.count(filter.matchAll());\n * console.log('Total snapshots:', count);\n * ```\n */\n @post(SnapshotQueryEndpointPaths.COUNT)\n /* v8 ignore start */\n count(\n // compat(wow<9): accepts the deprecated Condition, which Wow < 8.11 needs; narrow to FilterExpression in v10.\n @body() filter: FilterExpression<FIELDS> | Condition<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<number> {\n throw autoGeneratedError(filter, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a list of materialized snapshots based on the provided query parameters.\n *\n * @param listQuery - The query parameters for listing snapshots\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to an array of partial materialized snapshots\n *\n * @example\n * ```typescript\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const list = await snapshotQueryClient.list(listQuery);\n * for (const snapshot of list) {\n * console.log('Snapshot:', snapshot);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.LIST)\n /* v8 ignore start */\n list<T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>>(\n @body() listQuery: ListQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<T[]> {\n throw autoGeneratedError(listQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a stream of materialized snapshots based on the provided query parameters.\n *\n * @param listQuery - The query parameters for listing snapshots\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a readable stream of partial materialized snapshots\n *\n * @example\n * ```typescript\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const listStream = await snapshotQueryClient.listStream(listQuery);\n * for await (const snapshot of listStream) {\n * console.log('Received snapshot:', snapshot);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.LIST, QUERY_STREAM_ENDPOINT)\n /* v8 ignore start */\n listStream<\n T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>,\n >(\n @body() listQuery: ListQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<ReadableStream<T>> {\n throw autoGeneratedError(listQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a list of snapshot states based on the provided query parameters.\n *\n * @param listQuery - The query parameters for listing snapshot states\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to an array of partial snapshot states\n *\n * @example\n * ```typescript\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const list = await snapshotQueryClient.listState(listQuery);\n * for (const state of list) {\n * console.log('State:', state);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.LIST_STATE)\n /* v8 ignore start */\n listState<T extends Partial<S> = S>(\n @body() listQuery: ListQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<T[]> {\n throw autoGeneratedError(listQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a stream of snapshot states based on the provided query parameters.\n *\n * @param listQuery - The query parameters for listing snapshot states\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a readable stream of partial snapshot states\n *\n * @example\n * ```typescript\n * const listQuery: FilterListQuery = {\n * filter: filter.matchAll()\n * };\n * const listStream = await snapshotQueryClient.listStateStream(listQuery);\n * for await (const state of listStream) {\n * console.log('Received state:', state);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.LIST_STATE, QUERY_STREAM_ENDPOINT)\n /* v8 ignore start */\n listStateStream<T extends Partial<S> = S>(\n @body() listQuery: ListQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<ReadableStream<T>> {\n throw autoGeneratedError(listQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a paged list of materialized snapshots based on the provided query parameters.\n *\n * @param pagedQuery - The query parameters for paging snapshots\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a paged list of partial materialized snapshots\n *\n * @example\n * ```typescript\n * const pagedQuery: FilterPagedQuery = {\n * filter: filter.matchAll(),\n * pagination: { index: 1, size: 10 }\n * };\n * const paged = await snapshotQueryClient.paged(pagedQuery);\n * console.log('Total:', paged.total);\n * for (const snapshot of paged.list) {\n * console.log('Snapshot:', snapshot);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.PAGED)\n /* v8 ignore start */\n paged<T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>>(\n @body() pagedQuery: PagedQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<PagedList<T>> {\n throw autoGeneratedError(pagedQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a paged list of snapshot states based on the provided query parameters.\n *\n * @param pagedQuery - The query parameters for paging snapshot states\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a paged list of partial snapshot states\n *\n * @example\n * ```typescript\n * const pagedQuery: FilterPagedQuery = {\n * filter: filter.matchAll(),\n * pagination: { index: 1, size: 10 }\n * };\n * const pagedState = await snapshotQueryClient.pagedState(pagedQuery);\n * for (const state of pagedState.list) {\n * console.log('State:', state);\n * }\n * ```\n */\n @post(SnapshotQueryEndpointPaths.PAGED_STATE)\n /* v8 ignore start */\n pagedState<T extends Partial<S> = S>(\n @body() pagedQuery: PagedQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<PagedList<T>> {\n throw autoGeneratedError(pagedQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a single materialized snapshot based on the provided query parameters.\n *\n * @param singleQuery - The query parameters for retrieving a single snapshot\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a partial materialized snapshot\n *\n * @example\n * ```typescript\n * const singleQuery: FilterSingleQuery = {\n * filter: filter.matchAll()\n * };\n * const single = await snapshotQueryClient.single(singleQuery);\n * console.log('Snapshot:', single);\n * ```\n */\n @post(SnapshotQueryEndpointPaths.SINGLE)\n /* v8 ignore start */\n single<T extends Partial<MaterializedSnapshot<S>> = MaterializedSnapshot<S>>(\n @body() singleQuery: SingleQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<T> {\n throw autoGeneratedError(singleQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a single snapshot state based on the provided query parameters.\n *\n * @param singleQuery - The query parameters for retrieving a single snapshot state\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to a partial snapshot state\n *\n * @example\n * ```typescript\n * const singleQuery: FilterSingleQuery = {\n * filter: filter.matchAll()\n * };\n * const singleState = await snapshotQueryClient.singleState(singleQuery);\n * console.log('State:', singleState);\n * ```\n */\n @post(SnapshotQueryEndpointPaths.SINGLE_STATE)\n /* v8 ignore start */\n singleState<T extends Partial<S> = S>(\n @body() singleQuery: SingleQueryRequest<FIELDS>,\n @attribute() attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<T> {\n throw autoGeneratedError(singleQuery, attributes, abort);\n }\n /* v8 ignore stop */\n\n /**\n * Retrieves a single materialized snapshot by its ID.\n *\n * @param id - The unique identifier of the snapshot to retrieve\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to the materialized snapshot with the specified ID\n *\n * @example\n * ```typescript\n * const snapshot = await snapshotQueryClient.getById('snapshot-123');\n * console.log('Snapshot:', snapshot);\n * ```\n */\n getById(\n id: string,\n attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<MaterializedSnapshot<S>> {\n const query = singleQuery<FIELDS>({ filter: filter.aggregateId(id) });\n return this.single(query, attributes, abort);\n }\n\n /**\n * Retrieves a single snapshot state by its ID.\n *\n * @param id - The unique identifier of the snapshot whose state to retrieve\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to the snapshot state with the specified ID\n *\n * @example\n * ```typescript\n * const state = await snapshotQueryClient.getStateById('snapshot-123');\n * console.log('State:', state);\n * ```\n */\n getStateById(\n id: string,\n attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<S> {\n const query = singleQuery<FIELDS>({ filter: filter.aggregateId(id) });\n return this.singleState(query, attributes, abort);\n }\n\n /**\n * Retrieves multiple materialized snapshots by their IDs.\n *\n * One request, filtered by `filter.aggregateIds(ids)` with `limit` set to\n * the number of ids; an empty `ids` sends nothing and resolves to `[]`. The\n * server refuses more ids than its filter value limit and its maximum list\n * size (1000 each by default), so split a larger set into batches.\n *\n * @param ids - An array of unique identifiers of the snapshots to retrieve\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to an array of materialized snapshots with the specified IDs\n *\n * @example\n * ```typescript\n * const snapshots = await snapshotQueryClient.getByIds(['snapshot-123', 'snapshot-456']);\n * for (const snapshot of snapshots) {\n * console.log('Snapshot:', snapshot);\n * }\n * ```\n */\n getByIds(\n ids: string[],\n attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<MaterializedSnapshot<S>[]> {\n if (ids.length === 0) return Promise.resolve([]);\n const query = listQuery<FIELDS>({\n filter: filter.aggregateIds(ids),\n limit: ids.length,\n });\n return this.list(query, attributes, abort);\n }\n\n /**\n * Retrieves multiple snapshot states by their IDs.\n *\n * One request, filtered by `filter.aggregateIds(ids)` with `limit` set to\n * the number of ids; an empty `ids` sends nothing and resolves to `[]`. The\n * server refuses more ids than its filter value limit and its maximum list\n * size (1000 each by default), so split a larger set into batches.\n *\n * @param ids - An array of unique identifiers of the snapshots whose states to retrieve\n * @param attributes - Optional shared attributes that can be accessed by interceptors\n * throughout the request lifecycle. These attributes allow passing\n * custom data between different interceptors.\n * @param abort - Cancels the request: an `AbortController`, or an `AbortSignal` such as `AbortSignal.timeout(ms)` or the `signal` a data-fetching library passes.\n * @returns A promise that resolves to an array of snapshot states with the specified IDs\n *\n * @example\n * ```typescript\n * const states = await snapshotQueryClient.getStateByIds(['snapshot-123', 'snapshot-456']);\n * for (const state of states) {\n * console.log('State:', state);\n * }\n * ```\n */\n getStateByIds(\n ids: string[],\n attributes?: Record<string, unknown>,\n abort?: AbortController | AbortSignal,\n ): Promise<S[]> {\n if (ids.length === 0) return Promise.resolve([]);\n const query = listQuery<FIELDS>({\n filter: filter.aggregateIds(ids),\n limit: ids.length,\n });\n return this.listState(query, attributes, abort);\n }\n}\n"],"mappings":";;;;;;;;;;AAwHO,IAAMM,IAAN,MAEP;CAIE,YAAY,GAA2C;EACrD,AAD0B,KAAA,cAAAC,GAC1BC,EAAY,IAAI;CAClB;CAGA,UAME,GACA,GACA,GACgB;EAChB,MAAMC,EAAmBC,GAAOC,GAAYC,CAAK;CACnD;;CAIA,gBAME,GACA,GACA,GAC8B;EAC9B,MAAMH,EAAmBC,GAAOC,GAAYC,CAAK;CACnD;;CAIA,OAGE,GACA,GACA,GACwB;EACxB,MAAMH,EAAmBC,GAAOC,GAAYC,CAAK;CACnD;;CAIA,YAGE,GACA,GACA,GACwB;EACxB,MAAMH,EAAmBC,GAAOC,GAAYC,CAAK;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,EAAU,CAAA;;;;;;;;;CA8BZH,EAAKC,EAA2B,KAAK;CAGnCnB,EAAA,GAAAoB,EAAK,CAAA;CACLpB,EAAA,GAAAqB,EAAU,CAAA;;;;;;;;;CA6BZH,EAAKC,EAA2B,WAAW;CAGzCnB,EAAA,GAAAoB,EAAK,CAAA;CACLpB,EAAA,GAAAqB,EAAU,CAAA;;;;;;;;;CA0BZH,EAAKC,EAA2B,MAAM;CAGpCnB,EAAA,GAAAoB,EAAK,CAAA;CACLpB,EAAA,GAAAqB,EAAU,CAAA;;;;;;;;;CA0BZH,EAAKC,EAA2B,YAAY;CAG1CnB,EAAA,GAAAoB,EAAK,CAAA;CACLpB,EAAA,GAAAqB,EAAU,CAAA;;;;;;;;sCAvVd,IAAAtB,EAAA,CAAAwB,EAAI,GAAAtB,EAAA,qBAAA,CAAA,MAAA,CAAA,CAAA,GAAAI,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routing.cjs","names":["ResourceAttributionPathSpec","\"NONE\"","\"TENANT\"","\"OWNER\"","\"TENANT_OWNER\""],"sources":["../../src/client/routing.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for path parameters used in URL construction.\n * Defines common path parameters and allows for additional custom parameters.\n * This interface is used to provide path variables for URL templating.\n */\nexport interface UrlPathParams {\n /**\n * Tenant identifier parameter.\n * Used in multi-tenant applications to identify the tenant context.\n */\n tenantId?: string;\n /**\n * Owner identifier parameter.\n * Used to identify the owner or user context for the resource.\n */\n ownerId?: string;\n /**\n * Generic identifier parameter.\n * Used as a general purpose ID for resources when tenantId or ownerId are not appropriate.\n */\n id?: string;\n\n /**\n * Index signature for additional custom path parameters.\n * Allows for any additional string key-value pairs to be included as path parameters.\n */\n [key: string]: string | undefined;\n}\n\n/**\n * Enumeration of resource attribution path specifications.\n * Defines standard path patterns for accessing resources with different attribution scopes.\n * These paths are used to construct URLs that include tenant and/or owner identifiers.\n *\n * @example\n * ```typescript\n * // Using TENANT path spec\n * const
|
|
1
|
+
{"version":3,"file":"routing.cjs","names":["ResourceAttributionPathSpec","\"NONE\"","\"TENANT\"","\"OWNER\"","\"TENANT_OWNER\""],"sources":["../../src/client/routing.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for path parameters used in URL construction.\n * Defines common path parameters and allows for additional custom parameters.\n * This interface is used to provide path variables for URL templating.\n */\nexport interface UrlPathParams {\n /**\n * Tenant identifier parameter.\n * Used in multi-tenant applications to identify the tenant context.\n */\n tenantId?: string;\n /**\n * Owner identifier parameter.\n * Used to identify the owner or user context for the resource.\n */\n ownerId?: string;\n /**\n * Generic identifier parameter.\n * Used as a general purpose ID for resources when tenantId or ownerId are not appropriate.\n */\n id?: string;\n\n /**\n * Index signature for additional custom path parameters.\n * Allows for any additional string key-value pairs to be included as path parameters.\n */\n [key: string]: string | undefined;\n}\n\n/**\n * Enumeration of resource attribution path specifications.\n * Defines standard path patterns for accessing resources with different attribution scopes.\n * These paths are used to construct URLs that include tenant and/or owner identifiers.\n *\n * @example\n * ```typescript\n * // Using TENANT path spec\n * const tenantPath = ResourceAttributionPathSpec.TENANT; // '/tenant/{tenantId}'\n *\n * // Using TENANT_OWNER path spec\n * const tenantOwnerPath = ResourceAttributionPathSpec.TENANT_OWNER; // '/tenant/{tenantId}/owner/{ownerId}'\n * ```\n */\nexport enum ResourceAttributionPathSpec {\n NONE = '',\n TENANT = '/tenant/{tenantId}',\n OWNER = '/owner/{ownerId}',\n TENANT_OWNER = '/tenant/{tenantId}/owner/{ownerId}',\n}\n"],"mappings":"AAwDA,IAAYA,EAAL,SAAA,EAAA,OACL,GAAAC,KAAA,GACA,EAAAC,OAAA,qBACA,EAAAC,MAAA,mBACA,EAAAC,aAAA,sCACF,EAAA,CAAA,CAAA"}
|
|
@@ -33,10 +33,10 @@ export interface UrlPathParams {
|
|
|
33
33
|
* @example
|
|
34
34
|
* ```typescript
|
|
35
35
|
* // Using TENANT path spec
|
|
36
|
-
* const
|
|
36
|
+
* const tenantPath = ResourceAttributionPathSpec.TENANT; // '/tenant/{tenantId}'
|
|
37
37
|
*
|
|
38
38
|
* // Using TENANT_OWNER path spec
|
|
39
|
-
* const
|
|
39
|
+
* const tenantOwnerPath = ResourceAttributionPathSpec.TENANT_OWNER; // '/tenant/{tenantId}/owner/{ownerId}'
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
42
|
export declare enum ResourceAttributionPathSpec {
|
package/dist/client/routing.d.ts
CHANGED
|
@@ -33,10 +33,10 @@ export interface UrlPathParams {
|
|
|
33
33
|
* @example
|
|
34
34
|
* ```typescript
|
|
35
35
|
* // Using TENANT path spec
|
|
36
|
-
* const
|
|
36
|
+
* const tenantPath = ResourceAttributionPathSpec.TENANT; // '/tenant/{tenantId}'
|
|
37
37
|
*
|
|
38
38
|
* // Using TENANT_OWNER path spec
|
|
39
|
-
* const
|
|
39
|
+
* const tenantOwnerPath = ResourceAttributionPathSpec.TENANT_OWNER; // '/tenant/{tenantId}/owner/{ownerId}'
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
42
|
export declare enum ResourceAttributionPathSpec {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routing.es.js","names":["ResourceAttributionPathSpec","\"NONE\"","\"TENANT\"","\"OWNER\"","\"TENANT_OWNER\""],"sources":["../../src/client/routing.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for path parameters used in URL construction.\n * Defines common path parameters and allows for additional custom parameters.\n * This interface is used to provide path variables for URL templating.\n */\nexport interface UrlPathParams {\n /**\n * Tenant identifier parameter.\n * Used in multi-tenant applications to identify the tenant context.\n */\n tenantId?: string;\n /**\n * Owner identifier parameter.\n * Used to identify the owner or user context for the resource.\n */\n ownerId?: string;\n /**\n * Generic identifier parameter.\n * Used as a general purpose ID for resources when tenantId or ownerId are not appropriate.\n */\n id?: string;\n\n /**\n * Index signature for additional custom path parameters.\n * Allows for any additional string key-value pairs to be included as path parameters.\n */\n [key: string]: string | undefined;\n}\n\n/**\n * Enumeration of resource attribution path specifications.\n * Defines standard path patterns for accessing resources with different attribution scopes.\n * These paths are used to construct URLs that include tenant and/or owner identifiers.\n *\n * @example\n * ```typescript\n * // Using TENANT path spec\n * const
|
|
1
|
+
{"version":3,"file":"routing.es.js","names":["ResourceAttributionPathSpec","\"NONE\"","\"TENANT\"","\"OWNER\"","\"TENANT_OWNER\""],"sources":["../../src/client/routing.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for path parameters used in URL construction.\n * Defines common path parameters and allows for additional custom parameters.\n * This interface is used to provide path variables for URL templating.\n */\nexport interface UrlPathParams {\n /**\n * Tenant identifier parameter.\n * Used in multi-tenant applications to identify the tenant context.\n */\n tenantId?: string;\n /**\n * Owner identifier parameter.\n * Used to identify the owner or user context for the resource.\n */\n ownerId?: string;\n /**\n * Generic identifier parameter.\n * Used as a general purpose ID for resources when tenantId or ownerId are not appropriate.\n */\n id?: string;\n\n /**\n * Index signature for additional custom path parameters.\n * Allows for any additional string key-value pairs to be included as path parameters.\n */\n [key: string]: string | undefined;\n}\n\n/**\n * Enumeration of resource attribution path specifications.\n * Defines standard path patterns for accessing resources with different attribution scopes.\n * These paths are used to construct URLs that include tenant and/or owner identifiers.\n *\n * @example\n * ```typescript\n * // Using TENANT path spec\n * const tenantPath = ResourceAttributionPathSpec.TENANT; // '/tenant/{tenantId}'\n *\n * // Using TENANT_OWNER path spec\n * const tenantOwnerPath = ResourceAttributionPathSpec.TENANT_OWNER; // '/tenant/{tenantId}/owner/{ownerId}'\n * ```\n */\nexport enum ResourceAttributionPathSpec {\n NONE = '',\n TENANT = '/tenant/{tenantId}',\n OWNER = '/owner/{ownerId}',\n TENANT_OWNER = '/tenant/{tenantId}/owner/{ownerId}',\n}\n"],"mappings":";AAwDA,IAAYA,IAAL,yBAAA,GAAA;QACL,EAAAC,OAAA,IACA,EAAAC,SAAA,sBACA,EAAAC,QAAA,oBACA,EAAAC,eAAA;AACF,EAAA,CAAA,CAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../filter/operator.cjs"),t=require("./types.cjs"),n=require("./expressionTrees.cjs"),r=require("./sort.cjs");function i(e,t,n,r){if(n.length>r)throw TypeError(`${e} must contain at most ${r} ${t}.`)}function a(t){switch(t.op){case e.FilterOperator.SEARCH:throw TypeError(`Aggregation metric filters do not support search filters.`);case e.FilterOperator.ELEMENT_MATCH:throw TypeError(`Aggregation metric filters do not support [ELEMENT_MATCH].`);case e.FilterOperator.AND:case e.FilterOperator.OR:case e.FilterOperator.NOR:t.operands.forEach(a)}}function o(e,r){n.requireValidExpressionTrees(e.flatMap(e=>e.type===t.AggregationMetricType.NUMERIC||e.type===t.AggregationMetricType.DISTINCT_COUNT||e.type===t.AggregationMetricType.PERCENTILE?[e.expression]:[])),r.forEach(e=>{if(e.type===t.AggregationGroupType.TERMS||e.type===t.AggregationGroupType.HISTOGRAM){if(e.field===void 0==(e.expression===void 0))throw TypeError(`${e.type} group requires exactly one of field and expression.`);if(e.expression&&n.requireValidExpressionTrees([e.expression]),e.type===t.AggregationGroupType.TERMS&&e.missingKey!==void 0&&e.expression)throw TypeError(`terms missingKey requires a field input.`)}})}var s=new Set([t.AggregationMetricType.ANY,t.AggregationMetricType.FIRST,t.AggregationMetricType.LAST]);function c(e){let n=new Map,r=0;e.forEach(e=>{e.type===t.AggregationMetricType.DERIVED&&(
|
|
1
|
+
const e=require("../filter/operator.cjs"),t=require("./types.cjs"),n=require("./expressionTrees.cjs"),r=require("./sort.cjs");function i(e,t,n,r){if(n.length>r)throw TypeError(`${e} must contain at most ${r} ${t}.`)}function a(t){switch(t.op){case e.FilterOperator.SEARCH:throw TypeError(`Aggregation metric filters do not support search filters.`);case e.FilterOperator.ELEMENT_MATCH:throw TypeError(`Aggregation metric filters do not support [ELEMENT_MATCH].`);case e.FilterOperator.AND:case e.FilterOperator.OR:case e.FilterOperator.NOR:t.operands.forEach(a)}}function o(e,r){n.requireValidExpressionTrees(e.flatMap(e=>e.type===t.AggregationMetricType.NUMERIC||e.type===t.AggregationMetricType.DISTINCT_COUNT||e.type===t.AggregationMetricType.PERCENTILE?[e.expression]:[])),r.forEach(e=>{if(e.type===t.AggregationGroupType.TERMS||e.type===t.AggregationGroupType.HISTOGRAM){if(e.field===void 0==(e.expression===void 0))throw TypeError(`${e.type} group requires exactly one of field and expression.`);if(e.expression&&n.requireValidExpressionTrees([e.expression]),e.type===t.AggregationGroupType.TERMS&&e.missingKey!==void 0&&e.expression)throw TypeError(`terms missingKey requires a field input.`);if(e.scope===t.AggregationGroupScope.ROOT&&e.expression)throw TypeError(`${e.type} with a ROOT scope requires a field input.`)}})}var s=new Set([t.AggregationMetricType.ANY,t.AggregationMetricType.FIRST,t.AggregationMetricType.LAST]);function c(e){let n=new Map,r=new Set,i={nodes:0,windows:0};e.forEach(e=>{e.type===t.AggregationMetricType.DERIVED&&(l(e,n,r,i),r.add(e.alias)),n.set(e.alias,s.has(e.type)?e.type:void 0)})}function l(e,n,r,i){let a=[{expression:e.expression,depth:1}];for(;a.length>0;){let{expression:o,depth:s}=a.pop();if(s>t.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH)throw TypeError(`derived expression depth must be at most ${t.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`);if(i.nodes++,i.nodes>t.AGGREGATION_LIMITS.MAX_EXPRESSION_NODES)throw TypeError(`derived expressions must contain at most ${t.AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`);switch(o.type){case t.DerivedExpressionType.METRIC_REF:{let t=o.metric;if(!n.has(t))throw TypeError(`derived metric [${e.alias}] must reference a metric declared before it, but was [${t}].`);let r=n.get(t);if(r!==void 0)throw TypeError(`derived metric [${e.alias}] cannot reference ${r} metric [${t}].`);break}case t.DerivedExpressionType.CONSTANT:if(!Number.isFinite(o.value))throw TypeError(`derived constant must be finite.`);break;case t.DerivedExpressionType.BINARY:a.push({expression:o.left,depth:s+1}),a.push({expression:o.right,depth:s+1});break;case t.DerivedExpressionType.TOTAL:case t.DerivedExpressionType.RUNNING:case t.DerivedExpressionType.PREVIOUS:case t.DerivedExpressionType.RANK:if(i.windows++,i.windows>t.AGGREGATION_LIMITS.MAX_WINDOWS)throw TypeError(`an aggregation must compute at most ${t.AGGREGATION_LIMITS.MAX_WINDOWS} windows.`);u(e.alias,o,n,r);break;default:throw TypeError(`Unsupported derived expression: ${String(o.type)}.`)}}}function u(e,t,n,r){let i=t.metric;if(!n.has(i))throw TypeError(`${t.type} window of derived metric [${e}] must read a metric declared before it, but was [${i}].`);if(n.get(i)!==void 0||r.has(i))throw TypeError(`${t.type} window of derived metric [${e}] must read a non-derived numeric metric, but was [${i}].`)}function d(e,t,n,r){if(!t.has(e))throw TypeError(`having condition [${e}] must reference a declared metric alias.`);if(n.has(e))throw TypeError(`having condition [${e}] cannot reference ANY metric.`);if(r.has(e))throw TypeError(`having condition [${e}] cannot reference FIRST or LAST metric.`)}function f(e,n,r){if(e===void 0)return;if(n.length===0)throw TypeError(`having requires at least one groupBy.`);let i=new Set(r.map(e=>e.alias)),a=new Set(r.filter(e=>e.type===t.AggregationMetricType.ANY).map(e=>e.alias)),o=new Set(r.filter(e=>e.type===t.AggregationMetricType.FIRST||e.type===t.AggregationMetricType.LAST).map(e=>e.alias)),s=[{expression:e,depth:1}];for(;s.length>0;){let{expression:e,depth:n}=s.pop();if(n>t.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH)throw TypeError(`having expression depth must be at most ${t.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`);switch(e.type){case t.HavingExpressionType.CONDITION:if(d(e.metric,i,a,o),!Number.isFinite(e.value))throw TypeError(`having condition [${e.metric}] value must be finite.`);break;case t.HavingExpressionType.BETWEEN:if(d(e.metric,i,a,o),!Number.isFinite(e.lower)||!Number.isFinite(e.upper))throw TypeError(`having between [${e.metric}] bounds must be finite.`);if(e.lower>e.upper)throw TypeError(`having between [${e.metric}] lower bound must not exceed upper bound.`);break;case t.HavingExpressionType.IN:if(d(e.metric,i,a,o),e.values.length===0)throw TypeError(`having in [${e.metric}] values must not be empty.`);if(!e.values.every(Number.isFinite))throw TypeError(`having in [${e.metric}] values must be finite.`);break;case t.HavingExpressionType.IS_NULL:d(e.metric,i,a,o);break;case t.HavingExpressionType.AND:case t.HavingExpressionType.OR:if(e.operands.length===0)throw TypeError(`having ${e.type} operands must not be empty.`);e.operands.forEach(e=>s.push({expression:e,depth:n+1}));break;default:throw TypeError(`Unsupported having expression: ${String(e.type)}.`)}}}function p(e,n,a){if(i(`sort`,`fields`,e,t.AGGREGATION_LIMITS.MAX_SORT_FIELDS),n.length===0&&e.length>0)throw TypeError(`sort requires at least one groupBy.`);let o=e.map(e=>e.field);if(new Set(o).size!==o.length)throw TypeError(`sort fields must be unique.`);if(!o.every(e=>a.includes(e)))throw TypeError(`sort fields must reference aggregation aliases.`);i(`effective sort`,`fields`,r.effectiveSort({groupBy:[...n],sort:[...e]}),t.AGGREGATION_LIMITS.MAX_SORT_FIELDS)}function m(e){let n=new Map((e.groupBy??[]).map(e=>[e.alias,e.scope===t.AggregationGroupScope.ROOT])),i=r.effectiveSort(e).flatMap(e=>n.has(e.field)?[n.get(e.field)]:[]),a=i.indexOf(!1);if(a>=0&&i.slice(a).includes(!0))throw TypeError(`groups with a ROOT scope must sort before the element groups.`)}function h(e){let n=e.elements??[],r=e.groupBy??[],s=e.metrics,l=e.sort??[];if(i(`elements`,`paths`,n,t.AGGREGATION_LIMITS.MAX_ELEMENTS),i(`groupBy`,`dimensions`,r,t.AGGREGATION_LIMITS.MAX_GROUPS),!Array.isArray(s)||s.length===0)throw TypeError(`metrics must not be empty.`);if(i(`metrics`,`entries`,s,t.AGGREGATION_LIMITS.MAX_METRICS),e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t.AGGREGATION_LIMITS.MAX_LIMIT))throw TypeError(`limit must be between 1 and ${t.AGGREGATION_LIMITS.MAX_LIMIT}.`);o(s,r),c(s),f(e.having,r,s),s.forEach(e=>{`filter`in e&&e.filter&&a(e.filter)}),r.forEach(e=>{if((e.type===t.AggregationGroupType.DATE_HISTOGRAM||e.type===t.AggregationGroupType.DATE_PART)&&e.dense===!0&&r.length!==1)throw TypeError(`dense requires ${e.type} to be the only groupBy.`)});let u=[...r.map(e=>e.alias),...s.map(e=>e.alias)];if(new Set(u).size!==u.length)throw TypeError(`aggregation aliases must be unique.`);return p(l,r,u),n.length>0&&m(e),{...e,metrics:[...s]}}exports.admitAggregationQuery=h;
|
|
2
2
|
//# sourceMappingURL=admit.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admit.cjs","names":["FilterOperator","AggregationMetricType","AggregationGroupType","AGGREGATION_LIMITS","DerivedExpressionType","HavingExpressionType","effectiveSort","require_operator","require_types","require_expressionTrees","require_sort","requireAtMost","items","max","name","noun","validateMetricFilter","filter","validateExpressions","metrics","metric","groupBy","group","NON_NUMERIC","validateDerivedMetrics","declared","nodes","validateDerivedExpression","pending","visitedNodes","depth","expression","reference","nonNumeric","requireValidHavingMetric","metricAliases","anyAliases","edgeAliases","validateHaving","having","operand","validateSort","sort","fields","entry","aliases","field","admitAggregationQuery","elements","query"],"sources":["../../../src/dsl/aggregation/admit.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FilterOperator, type FilterExpression } from '../filter/index.js';\nimport type { FieldSort } from '../sort.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { effectiveSort } from './sort.js';\nimport {\n AGGREGATION_LIMITS,\n AggregationGroupType,\n AggregationMetricType,\n DerivedExpressionType,\n HavingExpressionType,\n type AggregationGroup,\n type AggregationMetric,\n type AggregationQuery,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type HavingExpression,\n} from './types.js';\n\n// Internal: the rules `aggregation.query()` checks across the parts of a\n// query. index.ts does not re-export this file.\n\nfunction requireAtMost(\n name: string,\n noun: string,\n items: readonly unknown[],\n max: number,\n): void {\n if (items.length > max) {\n throw new TypeError(`${name} must contain at most ${max} ${noun}.`);\n }\n}\n\n/**\n * Refuses the filters a metric cannot carry, whatever the aggregate holds.\n *\n * A metric filter is a whole-value predicate on one record — MongoDB turns it\n * into a `$cond` guard and Elasticsearch into a filter aggregation — and\n * element matching and full text have no whole-value reading. Both backends\n * refuse them before touching a schema, so the shape alone settles it. What a\n * schema would add, refusing an array-valued field, stays on the server.\n */\nfunction validateMetricFilter(filter: FilterExpression): void {\n switch (filter.op) {\n case FilterOperator.SEARCH:\n throw new TypeError(\n 'Aggregation metric filters do not support search filters.',\n );\n case FilterOperator.ELEMENT_MATCH:\n throw new TypeError(\n 'Aggregation metric filters do not support [ELEMENT_MATCH].',\n );\n case FilterOperator.AND:\n case FilterOperator.OR:\n case FilterOperator.NOR:\n filter.operands.forEach(validateMetricFilter);\n break;\n }\n}\n\n/**\n * Walks the arithmetic of every metric that carries an expression, as one\n * budget, and of each expression group on its own, as Wow does.\n */\nfunction validateExpressions(\n metrics: readonly AggregationMetric[],\n groupBy: readonly AggregationGroup[],\n): void {\n requireValidExpressionTrees(\n metrics.flatMap(metric =>\n metric.type === AggregationMetricType.NUMERIC ||\n metric.type === AggregationMetricType.DISTINCT_COUNT ||\n metric.type === AggregationMetricType.PERCENTILE\n ? [metric.expression]\n : [],\n ),\n );\n groupBy.forEach(group => {\n if (\n group.type !== AggregationGroupType.TERMS &&\n group.type !== AggregationGroupType.HISTOGRAM\n )\n return;\n if ((group.field === undefined) === (group.expression === undefined)) {\n throw new TypeError(\n `${group.type} group requires exactly one of field and expression.`,\n );\n }\n if (group.expression) requireValidExpressionTrees([group.expression]);\n if (\n group.type === AggregationGroupType.TERMS &&\n group.missingKey !== undefined &&\n group.expression\n ) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n });\n}\n\n/** The metric types whose value is not a number: derived and having refuse them. */\nconst NON_NUMERIC: ReadonlySet<string> = new Set([\n AggregationMetricType.ANY,\n AggregationMetricType.FIRST,\n AggregationMetricType.LAST,\n]);\n\n/**\n * Admits the derived metrics against what was declared before each of them.\n *\n * Derived arithmetic runs after the aggregation, over values the query has\n * already produced, so a reference may only name a metric declared earlier —\n * that is what makes the list evaluable in one pass — and never an `ANY`,\n * `FIRST` or `LAST` metric, whose value is a field's value rather than a\n * number.\n */\nfunction validateDerivedMetrics(metrics: readonly AggregationMetric[]): void {\n // Each earlier alias, with its type when that is not a number.\n const declared = new Map<string, string | undefined>();\n let nodes = 0;\n metrics.forEach(metric => {\n if (metric.type === AggregationMetricType.DERIVED) {\n nodes = validateDerivedExpression(metric, declared, nodes);\n }\n declared.set(\n metric.alias,\n NON_NUMERIC.has(metric.type) ? metric.type : undefined,\n );\n });\n}\n\nfunction validateDerivedExpression(\n metric: DerivedAggregationMetric,\n declared: ReadonlyMap<string, string | undefined>,\n visitedNodes: number,\n): number {\n const pending: { expression: DerivedExpression; depth: number }[] = [\n { expression: metric.expression, depth: 1 },\n ];\n let nodes = visitedNodes;\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `derived expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n nodes++;\n if (nodes > AGGREGATION_LIMITS.MAX_EXPRESSION_NODES) {\n throw new TypeError(\n `derived expressions must contain at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`,\n );\n }\n switch (expression.type) {\n case DerivedExpressionType.METRIC_REF: {\n const reference = expression.metric;\n if (!declared.has(reference)) {\n throw new TypeError(\n `derived metric [${metric.alias}] must reference a metric declared before it, but was [${reference}].`,\n );\n }\n const nonNumeric = declared.get(reference);\n if (nonNumeric !== undefined) {\n throw new TypeError(\n `derived metric [${metric.alias}] cannot reference ${nonNumeric} metric [${reference}].`,\n );\n }\n break;\n }\n case DerivedExpressionType.CONSTANT:\n if (!Number.isFinite(expression.value)) {\n throw new TypeError('derived constant must be finite.');\n }\n break;\n case DerivedExpressionType.BINARY:\n pending.push({ expression: expression.left, depth: depth + 1 });\n pending.push({ expression: expression.right, depth: depth + 1 });\n break;\n default:\n throw new TypeError(\n `Unsupported derived expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n return nodes;\n}\n\nfunction requireValidHavingMetric(\n metric: string,\n metricAliases: ReadonlySet<string>,\n anyAliases: ReadonlySet<string>,\n edgeAliases: ReadonlySet<string>,\n): void {\n if (!metricAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] must reference a declared metric alias.`,\n );\n }\n if (anyAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference ANY metric.`,\n );\n }\n if (edgeAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference FIRST or LAST metric.`,\n );\n }\n}\n\n/**\n * `having` filters the grouped rows, so it needs rows to filter: a query with\n * no `groupBy` produces one row and has nothing to select from.\n */\nfunction validateHaving(\n having: HavingExpression | undefined,\n groupBy: readonly AggregationGroup[],\n metrics: readonly AggregationMetric[],\n): void {\n if (having === undefined) return;\n if (groupBy.length === 0) {\n throw new TypeError('having requires at least one groupBy.');\n }\n const metricAliases = new Set(metrics.map(metric => metric.alias));\n const anyAliases = new Set(\n metrics\n .filter(metric => metric.type === AggregationMetricType.ANY)\n .map(metric => metric.alias),\n );\n const edgeAliases = new Set(\n metrics\n .filter(\n metric =>\n metric.type === AggregationMetricType.FIRST ||\n metric.type === AggregationMetricType.LAST,\n )\n .map(metric => metric.alias),\n );\n\n const pending: { expression: HavingExpression; depth: number }[] = [\n { expression: having, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `having expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n switch (expression.type) {\n case HavingExpressionType.CONDITION:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (!Number.isFinite(expression.value)) {\n throw new TypeError(\n `having condition [${expression.metric}] value must be finite.`,\n );\n }\n break;\n case HavingExpressionType.BETWEEN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (\n !Number.isFinite(expression.lower) ||\n !Number.isFinite(expression.upper)\n ) {\n throw new TypeError(\n `having between [${expression.metric}] bounds must be finite.`,\n );\n }\n if (expression.lower > expression.upper) {\n throw new TypeError(\n `having between [${expression.metric}] lower bound must not exceed upper bound.`,\n );\n }\n break;\n case HavingExpressionType.IN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (expression.values.length === 0) {\n throw new TypeError(\n `having in [${expression.metric}] values must not be empty.`,\n );\n }\n if (!expression.values.every(Number.isFinite)) {\n throw new TypeError(\n `having in [${expression.metric}] values must be finite.`,\n );\n }\n break;\n case HavingExpressionType.IS_NULL:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n break;\n case HavingExpressionType.AND:\n case HavingExpressionType.OR:\n if (expression.operands.length === 0) {\n throw new TypeError(\n `having ${expression.type} operands must not be empty.`,\n );\n }\n expression.operands.forEach(operand =>\n pending.push({ expression: operand, depth: depth + 1 }),\n );\n break;\n default:\n throw new TypeError(\n `Unsupported having expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\nfunction validateSort(\n sort: readonly FieldSort[],\n groupBy: readonly AggregationGroup[],\n aliases: readonly string[],\n): void {\n requireAtMost('sort', 'fields', sort, AGGREGATION_LIMITS.MAX_SORT_FIELDS);\n if (groupBy.length === 0 && sort.length > 0) {\n throw new TypeError('sort requires at least one groupBy.');\n }\n const fields = sort.map(entry => entry.field);\n if (new Set(fields).size !== fields.length) {\n throw new TypeError('sort fields must be unique.');\n }\n if (!fields.every(field => aliases.includes(field))) {\n throw new TypeError('sort fields must reference aggregation aliases.');\n }\n requireAtMost(\n 'effective sort',\n 'fields',\n effectiveSort({ groupBy: [...groupBy], sort: [...sort] }),\n AGGREGATION_LIMITS.MAX_SORT_FIELDS,\n );\n}\n\n/**\n * Admits a whole aggregation query against the rules Wow enforces on arrival;\n * {@link aggregation.query} is its public face.\n */\nexport function admitAggregationQuery<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n>(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n const elements = query.elements ?? [];\n const groupBy = query.groupBy ?? [];\n const metrics = query.metrics;\n const sort = query.sort ?? [];\n\n requireAtMost('elements', 'paths', elements, AGGREGATION_LIMITS.MAX_ELEMENTS);\n requireAtMost(\n 'groupBy',\n 'dimensions',\n groupBy,\n AGGREGATION_LIMITS.MAX_GROUPS,\n );\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new TypeError('metrics must not be empty.');\n }\n requireAtMost('metrics', 'entries', metrics, AGGREGATION_LIMITS.MAX_METRICS);\n if (query.limit !== undefined) {\n if (\n !Number.isInteger(query.limit) ||\n query.limit < 1 ||\n query.limit > AGGREGATION_LIMITS.MAX_LIMIT\n ) {\n throw new TypeError(\n `limit must be between 1 and ${AGGREGATION_LIMITS.MAX_LIMIT}.`,\n );\n }\n }\n\n validateExpressions(metrics, groupBy);\n validateDerivedMetrics(metrics);\n validateHaving(query.having, groupBy, metrics);\n metrics.forEach(metric => {\n if ('filter' in metric && metric.filter)\n validateMetricFilter(metric.filter);\n });\n\n // A dense DATE_HISTOGRAM fills in the buckets its range implies, and a\n // dense DATE_PART every key of its part's domain, rather than only the ones\n // with rows; a second dimension would multiply that filling out across\n // every one of its own keys.\n groupBy.forEach(group => {\n if (\n (group.type === AggregationGroupType.DATE_HISTOGRAM ||\n group.type === AggregationGroupType.DATE_PART) &&\n group.dense === true &&\n groupBy.length !== 1\n ) {\n throw new TypeError(\n `dense requires ${group.type} to be the only groupBy.`,\n );\n }\n });\n\n const aliases = [\n ...groupBy.map(group => group.alias),\n ...metrics.map(metric => metric.alias),\n ];\n if (new Set(aliases).size !== aliases.length) {\n throw new TypeError('aggregation aliases must be unique.');\n }\n validateSort(sort, groupBy, aliases);\n\n return {\n ...query,\n metrics: [...metrics] as typeof query.metrics,\n };\n}\n"],"mappings":"8HAkCA,SAASW,EACP,EACA,EACA,EACA,EACM,CACN,GAAIC,EAAM,OAASC,EACjB,MAAU,UAAU,GAAGC,EAAK,wBAAwBD,EAAI,GAAGE,EAAK,EAAE,CAEtE,CAWA,SAASC,EAAqB,EAAgC,CAC5D,OAAQC,EAAO,GAAf,CACE,KAAKjB,EAAAA,eAAe,OAClB,MAAU,UACR,2DACF,EACF,KAAKA,EAAAA,eAAe,cAClB,MAAU,UACR,4DACF,EACF,KAAKA,EAAAA,eAAe,IACpB,KAAKA,EAAAA,eAAe,GACpB,KAAKA,EAAAA,eAAe,IAClBiB,EAAO,SAAS,QAAQD,CAAoB,CAEhD,CACF,CAMA,SAASE,EACP,EACA,EACM,CACNT,EAAA,4BACEU,EAAQ,QAAQ,GACdC,EAAO,OAASnB,EAAAA,sBAAsB,SACtCmB,EAAO,OAASnB,EAAAA,sBAAsB,gBACtCmB,EAAO,OAASnB,EAAAA,sBAAsB,WAClC,CAACmB,EAAO,UAAU,EAClB,CAAC,CACP,CACF,EACAC,EAAQ,QAAQ,GAAS,CACvB,GACEC,EAAM,OAASpB,EAAAA,qBAAqB,OACpCoB,EAAM,OAASpB,EAAAA,qBAAqB,UAGtC,IAAKoB,EAAM,QAAU,IAAA,KAA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MAAQ9C,EAAAA,mBAAmB,WAEjC,MAAU,UACR,+BAA+BA,EAAAA,mBAAmB,UAAU,EAC9D,EAIJe,EAAoBC,EAASE,CAAO,EACpCG,EAAuBL,CAAO,EAC9BmB,EAAeW,EAAM,OAAQ5B,EAASF,CAAO,EAC7CA,EAAQ,QAAQ,GAAU,CACpB,WAAYC,GAAUA,EAAO,QAC/BJ,EAAqBI,EAAO,MAAM,CACtC,CAAC,EAMDC,EAAQ,QAAQ,GAAS,CACvB,IACGC,EAAM,OAASpB,EAAAA,qBAAqB,gBACnCoB,EAAM,OAASpB,EAAAA,qBAAqB,YACtCoB,EAAM,QAAU,IAChBD,EAAQ,SAAW,EAEnB,MAAU,UACR,kBAAkBC,EAAM,KAAK,yBAC/B,CAEJ,CAAC,EAED,IAAMuB,EAAU,CACd,GAAGxB,EAAQ,IAAI,GAASC,EAAM,KAAK,EACnC,GAAGH,EAAQ,IAAI,GAAUC,EAAO,KAAK,CACvC,EACA,GAAI,IAAI,IAAIyB,CAAO,CAAC,CAAC,OAASA,EAAQ,OACpC,MAAU,UAAU,qCAAqC,EAI3D,OAFAJ,EAAaC,EAAMrB,EAASwB,CAAO,EAE5B,CACL,GAAGI,EACH,QAAS,CAAC,GAAG9B,CAAO,CACtB,CACF"}
|
|
1
|
+
{"version":3,"file":"admit.cjs","names":["FilterOperator","AggregationMetricType","AggregationGroupType","AggregationGroupScope","AGGREGATION_LIMITS","DerivedExpressionType","HavingExpressionType","effectiveSort","require_operator","require_types","require_expressionTrees","require_sort","requireAtMost","items","max","name","noun","validateMetricFilter","filter","validateExpressions","metrics","metric","groupBy","group","NON_NUMERIC","validateDerivedMetrics","declared","derived","counter","validateDerivedExpression","pending","depth","expression","reference","nonNumeric","requireWindowMetric","target","window","alias","requireValidHavingMetric","metricAliases","anyAliases","edgeAliases","validateHaving","having","operand","validateSort","sort","fields","entry","aliases","field","requireRootGroupsFirst","root","query","order","firstElement","admitAggregationQuery","elements"],"sources":["../../../src/dsl/aggregation/admit.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FilterOperator, type FilterExpression } from '../filter/index.js';\nimport type { FieldSort } from '../sort.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { effectiveSort } from './sort.js';\nimport {\n AGGREGATION_LIMITS,\n AggregationGroupScope,\n AggregationGroupType,\n AggregationMetricType,\n DerivedExpressionType,\n HavingExpressionType,\n type AggregationGroup,\n type AggregationMetric,\n type AggregationQuery,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type DerivedWindow,\n type HavingExpression,\n} from './types.js';\n\n// Internal: the rules `aggregation.query()` checks across the parts of a\n// query. index.ts does not re-export this file.\n\nfunction requireAtMost(\n name: string,\n noun: string,\n items: readonly unknown[],\n max: number,\n): void {\n if (items.length > max) {\n throw new TypeError(`${name} must contain at most ${max} ${noun}.`);\n }\n}\n\n/**\n * Refuses the filters a metric cannot carry, whatever the aggregate holds.\n *\n * A metric filter is a whole-value predicate on one record — MongoDB turns it\n * into a `$cond` guard and Elasticsearch into a filter aggregation — and\n * element matching and full text have no whole-value reading. Both backends\n * refuse them before touching a schema, so the shape alone settles it. What a\n * schema would add, refusing an array-valued field, stays on the server.\n */\nfunction validateMetricFilter(filter: FilterExpression): void {\n switch (filter.op) {\n case FilterOperator.SEARCH:\n throw new TypeError(\n 'Aggregation metric filters do not support search filters.',\n );\n case FilterOperator.ELEMENT_MATCH:\n throw new TypeError(\n 'Aggregation metric filters do not support [ELEMENT_MATCH].',\n );\n case FilterOperator.AND:\n case FilterOperator.OR:\n case FilterOperator.NOR:\n filter.operands.forEach(validateMetricFilter);\n break;\n }\n}\n\n/**\n * Walks the arithmetic of every metric that carries an expression, as one\n * budget, and of each expression group on its own, as Wow does.\n */\nfunction validateExpressions(\n metrics: readonly AggregationMetric[],\n groupBy: readonly AggregationGroup[],\n): void {\n requireValidExpressionTrees(\n metrics.flatMap(metric =>\n metric.type === AggregationMetricType.NUMERIC ||\n metric.type === AggregationMetricType.DISTINCT_COUNT ||\n metric.type === AggregationMetricType.PERCENTILE\n ? [metric.expression]\n : [],\n ),\n );\n groupBy.forEach(group => {\n if (\n group.type !== AggregationGroupType.TERMS &&\n group.type !== AggregationGroupType.HISTOGRAM\n )\n return;\n if ((group.field === undefined) === (group.expression === undefined)) {\n throw new TypeError(\n `${group.type} group requires exactly one of field and expression.`,\n );\n }\n if (group.expression) requireValidExpressionTrees([group.expression]);\n if (\n group.type === AggregationGroupType.TERMS &&\n group.missingKey !== undefined &&\n group.expression\n ) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n if (group.scope === AggregationGroupScope.ROOT && group.expression) {\n throw new TypeError(\n `${group.type} with a ROOT scope requires a field input.`,\n );\n }\n });\n}\n\n/** The metric types whose value is not a number: derived and having refuse them. */\nconst NON_NUMERIC: ReadonlySet<string> = new Set([\n AggregationMetricType.ANY,\n AggregationMetricType.FIRST,\n AggregationMetricType.LAST,\n]);\n\n/**\n * Admits the derived metrics against what was declared before each of them.\n *\n * Derived arithmetic runs after the aggregation, over values the query has\n * already produced, so a reference may only name a metric declared earlier —\n * that is what makes the list evaluable in one pass — and never an `ANY`,\n * `FIRST` or `LAST` metric, whose value is a field's value rather than a\n * number.\n */\nfunction validateDerivedMetrics(metrics: readonly AggregationMetric[]): void {\n // Each earlier alias, with its type when that is not a number.\n const declared = new Map<string, string | undefined>();\n const derived = new Set<string>();\n const counter = { nodes: 0, windows: 0 };\n metrics.forEach(metric => {\n if (metric.type === AggregationMetricType.DERIVED) {\n validateDerivedExpression(metric, declared, derived, counter);\n derived.add(metric.alias);\n }\n declared.set(\n metric.alias,\n NON_NUMERIC.has(metric.type) ? metric.type : undefined,\n );\n });\n}\n\nfunction validateDerivedExpression(\n metric: DerivedAggregationMetric,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n counter: { nodes: number; windows: number },\n): void {\n const pending: { expression: DerivedExpression; depth: number }[] = [\n { expression: metric.expression, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `derived expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n counter.nodes++;\n if (counter.nodes > AGGREGATION_LIMITS.MAX_EXPRESSION_NODES) {\n throw new TypeError(\n `derived expressions must contain at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`,\n );\n }\n switch (expression.type) {\n case DerivedExpressionType.METRIC_REF: {\n const reference = expression.metric;\n if (!declared.has(reference)) {\n throw new TypeError(\n `derived metric [${metric.alias}] must reference a metric declared before it, but was [${reference}].`,\n );\n }\n const nonNumeric = declared.get(reference);\n if (nonNumeric !== undefined) {\n throw new TypeError(\n `derived metric [${metric.alias}] cannot reference ${nonNumeric} metric [${reference}].`,\n );\n }\n break;\n }\n case DerivedExpressionType.CONSTANT:\n if (!Number.isFinite(expression.value)) {\n throw new TypeError('derived constant must be finite.');\n }\n break;\n case DerivedExpressionType.BINARY:\n pending.push({ expression: expression.left, depth: depth + 1 });\n pending.push({ expression: expression.right, depth: depth + 1 });\n break;\n case DerivedExpressionType.TOTAL:\n case DerivedExpressionType.RUNNING:\n case DerivedExpressionType.PREVIOUS:\n case DerivedExpressionType.RANK:\n counter.windows++;\n if (counter.windows > AGGREGATION_LIMITS.MAX_WINDOWS) {\n throw new TypeError(\n `an aggregation must compute at most ${AGGREGATION_LIMITS.MAX_WINDOWS} windows.`,\n );\n }\n requireWindowMetric(metric.alias, expression, declared, derived);\n break;\n default:\n throw new TypeError(\n `Unsupported derived expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\n/**\n * A window reads a non-derived numeric metric declared before the derived\n * one; the rest of its rules (which metrics add up, which groups it names)\n * the server checks against the whole query.\n */\nfunction requireWindowMetric(\n alias: string,\n window: DerivedWindow,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n): void {\n const target = window.metric;\n if (!declared.has(target)) {\n throw new TypeError(\n `${window.type} window of derived metric [${alias}] must read a metric declared before it, but was [${target}].`,\n );\n }\n if (declared.get(target) !== undefined || derived.has(target)) {\n throw new TypeError(\n `${window.type} window of derived metric [${alias}] must read a non-derived numeric metric, but was [${target}].`,\n );\n }\n}\n\nfunction requireValidHavingMetric(\n metric: string,\n metricAliases: ReadonlySet<string>,\n anyAliases: ReadonlySet<string>,\n edgeAliases: ReadonlySet<string>,\n): void {\n if (!metricAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] must reference a declared metric alias.`,\n );\n }\n if (anyAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference ANY metric.`,\n );\n }\n if (edgeAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference FIRST or LAST metric.`,\n );\n }\n}\n\n/**\n * `having` filters the grouped rows, so it needs rows to filter: a query with\n * no `groupBy` produces one row and has nothing to select from.\n */\nfunction validateHaving(\n having: HavingExpression | undefined,\n groupBy: readonly AggregationGroup[],\n metrics: readonly AggregationMetric[],\n): void {\n if (having === undefined) return;\n if (groupBy.length === 0) {\n throw new TypeError('having requires at least one groupBy.');\n }\n const metricAliases = new Set(metrics.map(metric => metric.alias));\n const anyAliases = new Set(\n metrics\n .filter(metric => metric.type === AggregationMetricType.ANY)\n .map(metric => metric.alias),\n );\n const edgeAliases = new Set(\n metrics\n .filter(\n metric =>\n metric.type === AggregationMetricType.FIRST ||\n metric.type === AggregationMetricType.LAST,\n )\n .map(metric => metric.alias),\n );\n\n const pending: { expression: HavingExpression; depth: number }[] = [\n { expression: having, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `having expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n switch (expression.type) {\n case HavingExpressionType.CONDITION:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (!Number.isFinite(expression.value)) {\n throw new TypeError(\n `having condition [${expression.metric}] value must be finite.`,\n );\n }\n break;\n case HavingExpressionType.BETWEEN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (\n !Number.isFinite(expression.lower) ||\n !Number.isFinite(expression.upper)\n ) {\n throw new TypeError(\n `having between [${expression.metric}] bounds must be finite.`,\n );\n }\n if (expression.lower > expression.upper) {\n throw new TypeError(\n `having between [${expression.metric}] lower bound must not exceed upper bound.`,\n );\n }\n break;\n case HavingExpressionType.IN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (expression.values.length === 0) {\n throw new TypeError(\n `having in [${expression.metric}] values must not be empty.`,\n );\n }\n if (!expression.values.every(Number.isFinite)) {\n throw new TypeError(\n `having in [${expression.metric}] values must be finite.`,\n );\n }\n break;\n case HavingExpressionType.IS_NULL:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n break;\n case HavingExpressionType.AND:\n case HavingExpressionType.OR:\n if (expression.operands.length === 0) {\n throw new TypeError(\n `having ${expression.type} operands must not be empty.`,\n );\n }\n expression.operands.forEach(operand =>\n pending.push({ expression: operand, depth: depth + 1 }),\n );\n break;\n default:\n throw new TypeError(\n `Unsupported having expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\nfunction validateSort(\n sort: readonly FieldSort[],\n groupBy: readonly AggregationGroup[],\n aliases: readonly string[],\n): void {\n requireAtMost('sort', 'fields', sort, AGGREGATION_LIMITS.MAX_SORT_FIELDS);\n if (groupBy.length === 0 && sort.length > 0) {\n throw new TypeError('sort requires at least one groupBy.');\n }\n const fields = sort.map(entry => entry.field);\n if (new Set(fields).size !== fields.length) {\n throw new TypeError('sort fields must be unique.');\n }\n if (!fields.every(field => aliases.includes(field))) {\n throw new TypeError('sort fields must reference aggregation aliases.');\n }\n requireAtMost(\n 'effective sort',\n 'fields',\n effectiveSort({ groupBy: [...groupBy], sort: [...sort] }),\n AGGREGATION_LIMITS.MAX_SORT_FIELDS,\n );\n}\n\n/**\n * With elements, the groups of a ROOT scope lead the effective sort: a storage\n * reads the root records' keys before the keys of their elements.\n */\nfunction requireRootGroupsFirst(\n query: Pick<AggregationQuery<string, string>, 'groupBy' | 'sort'>,\n): void {\n const root = new Map(\n (query.groupBy ?? []).map(group => [\n group.alias,\n group.scope === AggregationGroupScope.ROOT,\n ]),\n );\n const order = effectiveSort(query).flatMap(entry =>\n root.has(entry.field) ? [root.get(entry.field)] : [],\n );\n const firstElement = order.indexOf(false);\n if (firstElement >= 0 && order.slice(firstElement).includes(true)) {\n throw new TypeError(\n 'groups with a ROOT scope must sort before the element groups.',\n );\n }\n}\n\n/**\n * Admits a whole aggregation query against the rules Wow enforces on arrival;\n * {@link aggregation.query} is its public face.\n */\nexport function admitAggregationQuery<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n>(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n const elements = query.elements ?? [];\n const groupBy = query.groupBy ?? [];\n const metrics = query.metrics;\n const sort = query.sort ?? [];\n\n requireAtMost('elements', 'paths', elements, AGGREGATION_LIMITS.MAX_ELEMENTS);\n requireAtMost(\n 'groupBy',\n 'dimensions',\n groupBy,\n AGGREGATION_LIMITS.MAX_GROUPS,\n );\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new TypeError('metrics must not be empty.');\n }\n requireAtMost('metrics', 'entries', metrics, AGGREGATION_LIMITS.MAX_METRICS);\n if (query.limit !== undefined) {\n if (\n !Number.isInteger(query.limit) ||\n query.limit < 1 ||\n query.limit > AGGREGATION_LIMITS.MAX_LIMIT\n ) {\n throw new TypeError(\n `limit must be between 1 and ${AGGREGATION_LIMITS.MAX_LIMIT}.`,\n );\n }\n }\n\n validateExpressions(metrics, groupBy);\n validateDerivedMetrics(metrics);\n validateHaving(query.having, groupBy, metrics);\n metrics.forEach(metric => {\n if ('filter' in metric && metric.filter)\n validateMetricFilter(metric.filter);\n });\n\n // A dense DATE_HISTOGRAM fills in the buckets its range implies, and a\n // dense DATE_PART every key of its part's domain, rather than only the ones\n // with rows; a second dimension would multiply that filling out across\n // every one of its own keys.\n groupBy.forEach(group => {\n if (\n (group.type === AggregationGroupType.DATE_HISTOGRAM ||\n group.type === AggregationGroupType.DATE_PART) &&\n group.dense === true &&\n groupBy.length !== 1\n ) {\n throw new TypeError(\n `dense requires ${group.type} to be the only groupBy.`,\n );\n }\n });\n\n const aliases = [\n ...groupBy.map(group => group.alias),\n ...metrics.map(metric => metric.alias),\n ];\n if (new Set(aliases).size !== aliases.length) {\n throw new TypeError('aggregation aliases must be unique.');\n }\n validateSort(sort, groupBy, aliases);\n if (elements.length > 0) requireRootGroupsFirst(query);\n\n return {\n ...query,\n metrics: [...metrics] as typeof query.metrics,\n };\n}\n"],"mappings":"8HAoCA,SAASY,EACP,EACA,EACA,EACA,EACM,CACN,GAAIC,EAAM,OAASC,EACjB,MAAU,UAAU,GAAGC,EAAK,wBAAwBD,EAAI,GAAGE,EAAK,EAAE,CAEtE,CAWA,SAASC,EAAqB,EAAgC,CAC5D,OAAQC,EAAO,GAAf,CACE,KAAKlB,EAAAA,eAAe,OAClB,MAAU,UACR,2DACF,EACF,KAAKA,EAAAA,eAAe,cAClB,MAAU,UACR,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,EAAS,OAAS,GAAGN,EAAuBE,CAAK,EAE9C,CACL,GAAGA,EACH,QAAS,CAAC,GAAGlC,CAAO,CACtB,CACF"}
|
|
@@ -1,82 +1,97 @@
|
|
|
1
1
|
import { FilterOperator as e } from "../filter/operator.es.js";
|
|
2
|
-
import { AGGREGATION_LIMITS as t,
|
|
3
|
-
import { requireValidExpressionTrees as
|
|
4
|
-
import { effectiveSort as
|
|
2
|
+
import { AGGREGATION_LIMITS as t, AggregationGroupScope as n, AggregationGroupType as r, AggregationMetricType as i, DerivedExpressionType as a, HavingExpressionType as o } from "./types.es.js";
|
|
3
|
+
import { requireValidExpressionTrees as s } from "./expressionTrees.es.js";
|
|
4
|
+
import { effectiveSort as c } from "./sort.es.js";
|
|
5
5
|
//#region src/dsl/aggregation/admit.ts
|
|
6
|
-
function
|
|
6
|
+
function l(e, t, n, r) {
|
|
7
7
|
if (n.length > r) throw TypeError(`${e} must contain at most ${r} ${t}.`);
|
|
8
8
|
}
|
|
9
|
-
function
|
|
9
|
+
function u(t) {
|
|
10
10
|
switch (t.op) {
|
|
11
11
|
case e.SEARCH: throw TypeError("Aggregation metric filters do not support search filters.");
|
|
12
12
|
case e.ELEMENT_MATCH: throw TypeError("Aggregation metric filters do not support [ELEMENT_MATCH].");
|
|
13
13
|
case e.AND:
|
|
14
14
|
case e.OR:
|
|
15
|
-
case e.NOR: t.operands.forEach(
|
|
15
|
+
case e.NOR: t.operands.forEach(u);
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
|
-
function
|
|
19
|
-
|
|
20
|
-
if (e.type ===
|
|
18
|
+
function d(e, t) {
|
|
19
|
+
s(e.flatMap((e) => e.type === i.NUMERIC || e.type === i.DISTINCT_COUNT || e.type === i.PERCENTILE ? [e.expression] : [])), t.forEach((e) => {
|
|
20
|
+
if (e.type === r.TERMS || e.type === r.HISTOGRAM) {
|
|
21
21
|
if (e.field === void 0 == (e.expression === void 0)) throw TypeError(`${e.type} group requires exactly one of field and expression.`);
|
|
22
|
-
if (e.expression &&
|
|
22
|
+
if (e.expression && s([e.expression]), e.type === r.TERMS && e.missingKey !== void 0 && e.expression) throw TypeError("terms missingKey requires a field input.");
|
|
23
|
+
if (e.scope === n.ROOT && e.expression) throw TypeError(`${e.type} with a ROOT scope requires a field input.`);
|
|
23
24
|
}
|
|
24
25
|
});
|
|
25
26
|
}
|
|
26
|
-
var
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
var f = /* @__PURE__ */ new Set([
|
|
28
|
+
i.ANY,
|
|
29
|
+
i.FIRST,
|
|
30
|
+
i.LAST
|
|
30
31
|
]);
|
|
31
|
-
function
|
|
32
|
-
let t = /* @__PURE__ */ new Map(), n =
|
|
32
|
+
function p(e) {
|
|
33
|
+
let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Set(), r = {
|
|
34
|
+
nodes: 0,
|
|
35
|
+
windows: 0
|
|
36
|
+
};
|
|
33
37
|
e.forEach((e) => {
|
|
34
|
-
e.type ===
|
|
38
|
+
e.type === i.DERIVED && (m(e, t, n, r), n.add(e.alias)), t.set(e.alias, f.has(e.type) ? e.type : void 0);
|
|
35
39
|
});
|
|
36
40
|
}
|
|
37
|
-
function
|
|
38
|
-
let
|
|
41
|
+
function m(e, n, r, i) {
|
|
42
|
+
let o = [{
|
|
39
43
|
expression: e.expression,
|
|
40
44
|
depth: 1
|
|
41
|
-
}]
|
|
42
|
-
for (;
|
|
43
|
-
let { expression:
|
|
44
|
-
if (
|
|
45
|
-
if (
|
|
46
|
-
switch (
|
|
47
|
-
case
|
|
48
|
-
let t =
|
|
45
|
+
}];
|
|
46
|
+
for (; o.length > 0;) {
|
|
47
|
+
let { expression: s, depth: c } = o.pop();
|
|
48
|
+
if (c > t.MAX_EXPRESSION_DEPTH) throw TypeError(`derived expression depth must be at most ${t.MAX_EXPRESSION_DEPTH}.`);
|
|
49
|
+
if (i.nodes++, i.nodes > t.MAX_EXPRESSION_NODES) throw TypeError(`derived expressions must contain at most ${t.MAX_EXPRESSION_NODES} nodes.`);
|
|
50
|
+
switch (s.type) {
|
|
51
|
+
case a.METRIC_REF: {
|
|
52
|
+
let t = s.metric;
|
|
49
53
|
if (!n.has(t)) throw TypeError(`derived metric [${e.alias}] must reference a metric declared before it, but was [${t}].`);
|
|
50
|
-
let
|
|
51
|
-
if (
|
|
54
|
+
let r = n.get(t);
|
|
55
|
+
if (r !== void 0) throw TypeError(`derived metric [${e.alias}] cannot reference ${r} metric [${t}].`);
|
|
52
56
|
break;
|
|
53
57
|
}
|
|
54
|
-
case
|
|
55
|
-
if (!Number.isFinite(
|
|
58
|
+
case a.CONSTANT:
|
|
59
|
+
if (!Number.isFinite(s.value)) throw TypeError("derived constant must be finite.");
|
|
56
60
|
break;
|
|
57
|
-
case
|
|
58
|
-
|
|
59
|
-
expression:
|
|
60
|
-
depth:
|
|
61
|
-
}),
|
|
62
|
-
expression:
|
|
63
|
-
depth:
|
|
61
|
+
case a.BINARY:
|
|
62
|
+
o.push({
|
|
63
|
+
expression: s.left,
|
|
64
|
+
depth: c + 1
|
|
65
|
+
}), o.push({
|
|
66
|
+
expression: s.right,
|
|
67
|
+
depth: c + 1
|
|
64
68
|
});
|
|
65
69
|
break;
|
|
66
|
-
|
|
70
|
+
case a.TOTAL:
|
|
71
|
+
case a.RUNNING:
|
|
72
|
+
case a.PREVIOUS:
|
|
73
|
+
case a.RANK:
|
|
74
|
+
if (i.windows++, i.windows > t.MAX_WINDOWS) throw TypeError(`an aggregation must compute at most ${t.MAX_WINDOWS} windows.`);
|
|
75
|
+
h(e.alias, s, n, r);
|
|
76
|
+
break;
|
|
77
|
+
default: throw TypeError(`Unsupported derived expression: ${String(s.type)}.`);
|
|
67
78
|
}
|
|
68
79
|
}
|
|
69
|
-
return o;
|
|
70
80
|
}
|
|
71
|
-
function
|
|
81
|
+
function h(e, t, n, r) {
|
|
82
|
+
let i = t.metric;
|
|
83
|
+
if (!n.has(i)) throw TypeError(`${t.type} window of derived metric [${e}] must read a metric declared before it, but was [${i}].`);
|
|
84
|
+
if (n.get(i) !== void 0 || r.has(i)) throw TypeError(`${t.type} window of derived metric [${e}] must read a non-derived numeric metric, but was [${i}].`);
|
|
85
|
+
}
|
|
86
|
+
function g(e, t, n, r) {
|
|
72
87
|
if (!t.has(e)) throw TypeError(`having condition [${e}] must reference a declared metric alias.`);
|
|
73
88
|
if (n.has(e)) throw TypeError(`having condition [${e}] cannot reference ANY metric.`);
|
|
74
89
|
if (r.has(e)) throw TypeError(`having condition [${e}] cannot reference FIRST or LAST metric.`);
|
|
75
90
|
}
|
|
76
|
-
function
|
|
91
|
+
function _(e, n, r) {
|
|
77
92
|
if (e === void 0) return;
|
|
78
93
|
if (n.length === 0) throw TypeError("having requires at least one groupBy.");
|
|
79
|
-
let
|
|
94
|
+
let a = new Set(r.map((e) => e.alias)), s = new Set(r.filter((e) => e.type === i.ANY).map((e) => e.alias)), c = new Set(r.filter((e) => e.type === i.FIRST || e.type === i.LAST).map((e) => e.alias)), l = [{
|
|
80
95
|
expression: e,
|
|
81
96
|
depth: 1
|
|
82
97
|
}];
|
|
@@ -84,22 +99,22 @@ function h(e, n, i) {
|
|
|
84
99
|
let { expression: e, depth: n } = l.pop();
|
|
85
100
|
if (n > t.MAX_EXPRESSION_DEPTH) throw TypeError(`having expression depth must be at most ${t.MAX_EXPRESSION_DEPTH}.`);
|
|
86
101
|
switch (e.type) {
|
|
87
|
-
case
|
|
88
|
-
if (
|
|
102
|
+
case o.CONDITION:
|
|
103
|
+
if (g(e.metric, a, s, c), !Number.isFinite(e.value)) throw TypeError(`having condition [${e.metric}] value must be finite.`);
|
|
89
104
|
break;
|
|
90
|
-
case
|
|
91
|
-
if (
|
|
105
|
+
case o.BETWEEN:
|
|
106
|
+
if (g(e.metric, a, s, c), !Number.isFinite(e.lower) || !Number.isFinite(e.upper)) throw TypeError(`having between [${e.metric}] bounds must be finite.`);
|
|
92
107
|
if (e.lower > e.upper) throw TypeError(`having between [${e.metric}] lower bound must not exceed upper bound.`);
|
|
93
108
|
break;
|
|
94
|
-
case
|
|
95
|
-
if (
|
|
109
|
+
case o.IN:
|
|
110
|
+
if (g(e.metric, a, s, c), e.values.length === 0) throw TypeError(`having in [${e.metric}] values must not be empty.`);
|
|
96
111
|
if (!e.values.every(Number.isFinite)) throw TypeError(`having in [${e.metric}] values must be finite.`);
|
|
97
112
|
break;
|
|
98
|
-
case
|
|
99
|
-
|
|
113
|
+
case o.IS_NULL:
|
|
114
|
+
g(e.metric, a, s, c);
|
|
100
115
|
break;
|
|
101
|
-
case
|
|
102
|
-
case
|
|
116
|
+
case o.AND:
|
|
117
|
+
case o.OR:
|
|
103
118
|
if (e.operands.length === 0) throw TypeError(`having ${e.type} operands must not be empty.`);
|
|
104
119
|
e.operands.forEach((e) => l.push({
|
|
105
120
|
expression: e,
|
|
@@ -110,33 +125,37 @@ function h(e, n, i) {
|
|
|
110
125
|
}
|
|
111
126
|
}
|
|
112
127
|
}
|
|
113
|
-
function
|
|
114
|
-
if (
|
|
128
|
+
function v(e, n, r) {
|
|
129
|
+
if (l("sort", "fields", e, t.MAX_SORT_FIELDS), n.length === 0 && e.length > 0) throw TypeError("sort requires at least one groupBy.");
|
|
115
130
|
let i = e.map((e) => e.field);
|
|
116
131
|
if (new Set(i).size !== i.length) throw TypeError("sort fields must be unique.");
|
|
117
132
|
if (!i.every((e) => r.includes(e))) throw TypeError("sort fields must reference aggregation aliases.");
|
|
118
|
-
|
|
133
|
+
l("effective sort", "fields", c({
|
|
119
134
|
groupBy: [...n],
|
|
120
135
|
sort: [...e]
|
|
121
136
|
}), t.MAX_SORT_FIELDS);
|
|
122
137
|
}
|
|
123
|
-
function
|
|
124
|
-
let
|
|
125
|
-
if (
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
138
|
+
function y(e) {
|
|
139
|
+
let t = new Map((e.groupBy ?? []).map((e) => [e.alias, e.scope === n.ROOT])), r = c(e).flatMap((e) => t.has(e.field) ? [t.get(e.field)] : []), i = r.indexOf(!1);
|
|
140
|
+
if (i >= 0 && r.slice(i).includes(!0)) throw TypeError("groups with a ROOT scope must sort before the element groups.");
|
|
141
|
+
}
|
|
142
|
+
function b(e) {
|
|
143
|
+
let n = e.elements ?? [], i = e.groupBy ?? [], a = e.metrics, o = e.sort ?? [];
|
|
144
|
+
if (l("elements", "paths", n, t.MAX_ELEMENTS), l("groupBy", "dimensions", i, t.MAX_GROUPS), !Array.isArray(a) || a.length === 0) throw TypeError("metrics must not be empty.");
|
|
145
|
+
if (l("metrics", "entries", a, t.MAX_METRICS), e.limit !== void 0 && (!Number.isInteger(e.limit) || e.limit < 1 || e.limit > t.MAX_LIMIT)) throw TypeError(`limit must be between 1 and ${t.MAX_LIMIT}.`);
|
|
146
|
+
d(a, i), p(a), _(e.having, i, a), a.forEach((e) => {
|
|
147
|
+
"filter" in e && e.filter && u(e.filter);
|
|
129
148
|
}), i.forEach((e) => {
|
|
130
|
-
if ((e.type ===
|
|
149
|
+
if ((e.type === r.DATE_HISTOGRAM || e.type === r.DATE_PART) && e.dense === !0 && i.length !== 1) throw TypeError(`dense requires ${e.type} to be the only groupBy.`);
|
|
131
150
|
});
|
|
132
151
|
let s = [...i.map((e) => e.alias), ...a.map((e) => e.alias)];
|
|
133
152
|
if (new Set(s).size !== s.length) throw TypeError("aggregation aliases must be unique.");
|
|
134
|
-
return
|
|
153
|
+
return v(o, i, s), n.length > 0 && y(e), {
|
|
135
154
|
...e,
|
|
136
155
|
metrics: [...a]
|
|
137
156
|
};
|
|
138
157
|
}
|
|
139
158
|
//#endregion
|
|
140
|
-
export {
|
|
159
|
+
export { b as admitAggregationQuery };
|
|
141
160
|
|
|
142
161
|
//# sourceMappingURL=admit.es.js.map
|