@ahoo-wang/wow-client 10.0.0-alpha.6 → 10.0.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +76 -23
  2. package/README.zh-CN.md +66 -19
  3. package/dist/commands.cjs +1 -1
  4. package/dist/commands.cjs.map +1 -1
  5. package/dist/commands.d.cts +131 -61
  6. package/dist/commands.d.ts +131 -61
  7. package/dist/commands.es.js +117 -59
  8. package/dist/commands.es.js.map +1 -1
  9. package/dist/developmentCaller.cjs +2 -0
  10. package/dist/developmentCaller.cjs.map +1 -0
  11. package/dist/developmentCaller.d.cts +61 -0
  12. package/dist/developmentCaller.d.ts +61 -0
  13. package/dist/developmentCaller.es.js +26 -0
  14. package/dist/developmentCaller.es.js.map +1 -0
  15. package/dist/dsl/aggregation/admit.cjs +1 -1
  16. package/dist/dsl/aggregation/admit.cjs.map +1 -1
  17. package/dist/dsl/aggregation/admit.es.js +93 -93
  18. package/dist/dsl/aggregation/admit.es.js.map +1 -1
  19. package/dist/dsl/aggregation/builders.cjs +1 -1
  20. package/dist/dsl/aggregation/builders.cjs.map +1 -1
  21. package/dist/dsl/aggregation/builders.d.cts +20 -20
  22. package/dist/dsl/aggregation/builders.d.ts +20 -20
  23. package/dist/dsl/aggregation/builders.es.js +88 -88
  24. package/dist/dsl/aggregation/builders.es.js.map +1 -1
  25. package/dist/dsl/aggregation/derived.cjs.map +1 -1
  26. package/dist/dsl/aggregation/derived.d.cts +8 -8
  27. package/dist/dsl/aggregation/derived.d.ts +8 -8
  28. package/dist/dsl/aggregation/derived.es.js +1 -2
  29. package/dist/dsl/aggregation/derived.es.js.map +1 -1
  30. package/dist/dsl/aggregation/expressionTrees.cjs.map +1 -1
  31. package/dist/dsl/aggregation/expressionTrees.es.js +1 -2
  32. package/dist/dsl/aggregation/having.cjs +1 -1
  33. package/dist/dsl/aggregation/having.cjs.map +1 -1
  34. package/dist/dsl/aggregation/having.d.cts +12 -12
  35. package/dist/dsl/aggregation/having.d.ts +12 -12
  36. package/dist/dsl/aggregation/having.es.js +33 -33
  37. package/dist/dsl/aggregation/having.es.js.map +1 -1
  38. package/dist/dsl/aggregation/sort.cjs.map +1 -1
  39. package/dist/dsl/aggregation/sort.es.js +1 -2
  40. package/dist/dsl/aggregation/types.cjs +1 -1
  41. package/dist/dsl/aggregation/types.cjs.map +1 -1
  42. package/dist/dsl/aggregation/types.d.cts +69 -69
  43. package/dist/dsl/aggregation/types.d.ts +69 -69
  44. package/dist/dsl/aggregation/types.es.js +15 -16
  45. package/dist/dsl/aggregation/types.es.js.map +1 -1
  46. package/dist/dsl/constantName.cjs +2 -0
  47. package/dist/dsl/constantName.cjs.map +1 -0
  48. package/dist/dsl/constantName.d.cts +9 -0
  49. package/dist/dsl/constantName.d.ts +9 -0
  50. package/dist/dsl/constantName.es.js +7 -0
  51. package/dist/dsl/constantName.es.js.map +1 -0
  52. package/dist/dsl/cursorQuery.cjs.map +1 -1
  53. package/dist/dsl/cursorQuery.es.js +1 -2
  54. package/dist/dsl/deletionState.cjs +1 -1
  55. package/dist/dsl/deletionState.cjs.map +1 -1
  56. package/dist/dsl/deletionState.d.cts +3 -3
  57. package/dist/dsl/deletionState.d.ts +3 -3
  58. package/dist/dsl/deletionState.es.js +2 -3
  59. package/dist/dsl/deletionState.es.js.map +1 -1
  60. package/dist/dsl/descriptor.cjs +1 -1
  61. package/dist/dsl/descriptor.cjs.map +1 -1
  62. package/dist/dsl/descriptor.d.cts +92 -42
  63. package/dist/dsl/descriptor.d.ts +92 -42
  64. package/dist/dsl/descriptor.es.js +36 -29
  65. package/dist/dsl/descriptor.es.js.map +1 -1
  66. package/dist/dsl/field.cjs.map +1 -1
  67. package/dist/dsl/field.es.js +1 -2
  68. package/dist/dsl/filter/builders.cjs +1 -1
  69. package/dist/dsl/filter/builders.cjs.map +1 -1
  70. package/dist/dsl/filter/builders.d.cts +53 -53
  71. package/dist/dsl/filter/builders.d.ts +53 -53
  72. package/dist/dsl/filter/builders.es.js +111 -111
  73. package/dist/dsl/filter/builders.es.js.map +1 -1
  74. package/dist/dsl/filter/datePattern.cjs.map +1 -1
  75. package/dist/dsl/filter/datePattern.es.js +1 -2
  76. package/dist/dsl/filter/operator.cjs +1 -1
  77. package/dist/dsl/filter/operator.cjs.map +1 -1
  78. package/dist/dsl/filter/operator.d.cts +57 -57
  79. package/dist/dsl/filter/operator.d.ts +57 -57
  80. package/dist/dsl/filter/operator.es.js +4 -5
  81. package/dist/dsl/filter/operator.es.js.map +1 -1
  82. package/dist/dsl/filter/scope.cjs +1 -1
  83. package/dist/dsl/filter/scope.cjs.map +1 -1
  84. package/dist/dsl/filter/scope.es.js +12 -12
  85. package/dist/dsl/filter/scope.es.js.map +1 -1
  86. package/dist/dsl/filter/validate.cjs +1 -1
  87. package/dist/dsl/filter/validate.cjs.map +1 -1
  88. package/dist/dsl/filter/validate.es.js +23 -23
  89. package/dist/dsl/filter/validate.es.js.map +1 -1
  90. package/dist/dsl/pagination.cjs.map +1 -1
  91. package/dist/dsl/pagination.es.js +1 -2
  92. package/dist/dsl/projection.cjs.map +1 -1
  93. package/dist/dsl/projection.d.cts +1 -1
  94. package/dist/dsl/projection.d.ts +1 -1
  95. package/dist/dsl/projection.es.js +1 -2
  96. package/dist/dsl/projection.es.js.map +1 -1
  97. package/dist/dsl/queryErrorCodes.cjs +1 -1
  98. package/dist/dsl/queryErrorCodes.cjs.map +1 -1
  99. package/dist/dsl/queryErrorCodes.d.cts +59 -48
  100. package/dist/dsl/queryErrorCodes.d.ts +59 -48
  101. package/dist/dsl/queryErrorCodes.es.js +51 -50
  102. package/dist/dsl/queryErrorCodes.es.js.map +1 -1
  103. package/dist/dsl/queryable.cjs +1 -1
  104. package/dist/dsl/queryable.cjs.map +1 -1
  105. package/dist/dsl/queryable.d.cts +25 -21
  106. package/dist/dsl/queryable.d.ts +25 -21
  107. package/dist/dsl/queryable.es.js +5 -5
  108. package/dist/dsl/queryable.es.js.map +1 -1
  109. package/dist/dsl/sort.cjs +1 -1
  110. package/dist/dsl/sort.cjs.map +1 -1
  111. package/dist/dsl/sort.d.cts +2 -2
  112. package/dist/dsl/sort.d.ts +2 -2
  113. package/dist/dsl/sort.es.js +4 -5
  114. package/dist/dsl/sort.es.js.map +1 -1
  115. package/dist/dsl.cjs +1 -1
  116. package/dist/dsl.es.js +3 -3
  117. package/dist/exactJson.cjs.map +1 -1
  118. package/dist/exactJson.d.cts +4 -4
  119. package/dist/exactJson.d.ts +4 -4
  120. package/dist/exactJson.es.js +1 -2
  121. package/dist/exactJson.es.js.map +1 -1
  122. package/dist/frameworkErrors.cjs +2 -0
  123. package/dist/frameworkErrors.cjs.map +1 -0
  124. package/dist/frameworkErrors.d.cts +121 -0
  125. package/dist/frameworkErrors.d.ts +121 -0
  126. package/dist/frameworkErrors.es.js +95 -0
  127. package/dist/frameworkErrors.es.js.map +1 -0
  128. package/dist/http.cjs +1 -1
  129. package/dist/http.cjs.map +1 -1
  130. package/dist/http.d.cts +4 -7
  131. package/dist/http.d.ts +4 -7
  132. package/dist/http.es.js +12 -20
  133. package/dist/http.es.js.map +1 -1
  134. package/dist/index.cjs +1 -1
  135. package/dist/index.d.cts +9 -7
  136. package/dist/index.d.ts +9 -7
  137. package/dist/index.es.js +11 -9
  138. package/dist/manifest.cjs +1 -1
  139. package/dist/manifest.cjs.map +1 -1
  140. package/dist/manifest.d.cts +33 -95
  141. package/dist/manifest.d.ts +33 -95
  142. package/dist/manifest.es.js +12 -7
  143. package/dist/manifest.es.js.map +1 -1
  144. package/dist/manifestTypes.d.cts +193 -0
  145. package/dist/manifestTypes.d.ts +193 -0
  146. package/dist/problem.cjs +1 -1
  147. package/dist/problem.cjs.map +1 -1
  148. package/dist/problem.d.cts +76 -115
  149. package/dist/problem.d.ts +76 -115
  150. package/dist/problem.es.js +45 -80
  151. package/dist/problem.es.js.map +1 -1
  152. package/dist/queries.cjs +1 -1
  153. package/dist/queries.cjs.map +1 -1
  154. package/dist/queries.d.cts +28 -51
  155. package/dist/queries.d.ts +28 -51
  156. package/dist/queries.es.js +49 -40
  157. package/dist/queries.es.js.map +1 -1
  158. package/dist/routes.cjs +2 -0
  159. package/dist/routes.cjs.map +1 -0
  160. package/dist/routes.d.cts +49 -0
  161. package/dist/routes.d.ts +49 -0
  162. package/dist/routes.es.js +33 -0
  163. package/dist/routes.es.js.map +1 -0
  164. package/dist/state.cjs +1 -1
  165. package/dist/state.cjs.map +1 -1
  166. package/dist/state.d.cts +56 -11
  167. package/dist/state.d.ts +56 -11
  168. package/dist/state.es.js +56 -21
  169. package/dist/state.es.js.map +1 -1
  170. package/dist/streams.cjs +1 -1
  171. package/dist/streams.cjs.map +1 -1
  172. package/dist/streams.d.cts +17 -13
  173. package/dist/streams.d.ts +17 -13
  174. package/dist/streams.es.js +50 -50
  175. package/dist/streams.es.js.map +1 -1
  176. package/dist/testing/wire.cjs +2 -0
  177. package/dist/testing/wire.cjs.map +1 -0
  178. package/dist/testing/wire.d.cts +29 -0
  179. package/dist/testing/wire.d.ts +29 -0
  180. package/dist/testing/wire.es.js +88 -0
  181. package/dist/testing/wire.es.js.map +1 -0
  182. package/dist/testing.cjs +1 -0
  183. package/dist/testing.d.cts +12 -0
  184. package/dist/testing.d.ts +12 -0
  185. package/dist/testing.es.js +3 -0
  186. package/dist/wait.cjs +1 -1
  187. package/dist/wait.cjs.map +1 -1
  188. package/dist/wait.d.cts +67 -18
  189. package/dist/wait.d.ts +67 -18
  190. package/dist/wait.es.js +59 -12
  191. package/dist/wait.es.js.map +1 -1
  192. package/dist/wire.cjs +1 -1
  193. package/dist/wire.cjs.map +1 -1
  194. package/dist/wire.d.cts +100 -50
  195. package/dist/wire.d.ts +100 -50
  196. package/dist/wire.es.js +17 -6
  197. package/dist/wire.es.js.map +1 -1
  198. package/package.json +23 -3
@@ -1 +1 @@
1
- {"version":3,"file":"queries.es.js","names":["QueryModelClient","path","client","numbers","json","query","options","row","resume","limit","open","received","lastEventId","first","resumableQueryRows","response","send","WowHeaders","version","tag","entityTag","accept","queryPath","type","model","SnapshotQueryClient","EventQueryClient","events","eventNumbers","DatasetClient","context","dataset"],"sources":["../src/queries.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 { AggregationQuery } from './dsl/aggregation/index.js';\nimport type { CursorPage, CursorQuery } from './dsl/cursorQuery.js';\nimport type { Projected } from './dsl/projection.js';\nimport { eventNumbers, type TextNumbers } from './exactJson.js';\nimport type { QueryModelDescriptor } from './dsl/descriptor.js';\nimport type { FilterCapable } from './dsl/filter/index.js';\nimport type {\n FilterListQuery,\n FilterPagedQuery,\n FilterSingleQuery,\n} from './dsl/queryable.js';\nimport {\n entityTag,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport type {\n AggregateType,\n DatasetEntry,\n EventStreamField,\n EventStreamRecord,\n EventView,\n SnapshotRecord,\n SnapshotSystemField,\n} from './wire.js';\nimport {\n resumableQueryRows,\n type StreamedRow,\n type StreamResumeOptions,\n} from './streams.js';\n\n/** How a list is streamed: the request's options, and how it resumes. */\nexport interface ListStreamOptions extends RequestOptions {\n /** How the stream resumes (decision D253); `false` never resumes it. */\n readonly resume?: StreamResumeOptions | false;\n}\n\n/** How a paged query counts its total (`TotalMode`, decision D150). */\nexport type TotalMode = 'EXACT' | 'BOUNDED' | 'NONE';\n\n/** A paged query of a query route: a page, and how its total is counted. */\nexport interface PagedQuery<\n FIELDS extends string = string,\n> extends FilterPagedQuery<FIELDS> {\n /** `BOUNDED` (the server's default) counts up to the budget's limit. */\n total?: TotalMode;\n}\n\n/** A count of a query route (decision D150). */\nexport interface CountQuery<\n FIELDS extends string = string,\n> extends FilterCapable<FIELDS> {\n /** The most matches to count; the budget's default when absent. */\n limit?: number;\n}\n\n/** What a count answers: exact below its limit, else the limit itself. */\nexport interface CountResult {\n readonly count: number;\n readonly exact: boolean;\n}\n\n/**\n * A page of a paged query: `total` is exact when `exact`, a lower bound\n * otherwise, and null for `TotalMode.NONE`.\n */\nexport interface PagedResult<T> {\n readonly total: number | null;\n readonly exact: boolean;\n readonly list: readonly T[];\n}\n\n/**\n * A query model's capability descriptor and its version, the `ETag` of\n * `GET …/query`; `notModified` when the version given is still current.\n */\nexport type DescriptorResult =\n | {\n readonly notModified: false;\n readonly version?: string;\n readonly descriptor: QueryModelDescriptor;\n }\n | { readonly notModified: true; readonly version: string };\n\n/**\n * Queries one query model of a Wow service: `POST {path}` with a body\n * whose `kind` names the operation, `GET {path}` for the capability\n * descriptor (decisions D127, D145). A query written with literal `include`\n * paths answers records narrowed to them ({@link Projected}, review R4-Q,\n * Q-14).\n *\n * @typeParam R - The record's type.\n * @typeParam FIELDS - The field paths a filter, sort or projection takes.\n */\nexport class QueryModelClient<R, FIELDS extends string = string> {\n /**\n * @param path - The query route, `/{context}/{aggregate}/{model}/query`\n * @param client - How the service is reached\n * @param numbers - The numbers of each record read as their exact text\n * (review R4-Q, Q-9)\n */\n constructor(\n readonly path: string,\n readonly client: WowClientOptions = {},\n readonly numbers?: TextNumbers,\n ) {}\n\n /** The marks of a list of records. */\n private get listNumbers(): TextNumbers | undefined {\n return this.numbers === undefined ? undefined : { '*': this.numbers };\n }\n\n /** The marks of a page of records. */\n private get pageNumbers(): TextNumbers | undefined {\n return this.numbers === undefined\n ? undefined\n : { list: { '*': this.numbers } };\n }\n\n /** The records that match, at most `limit` (the server's default when absent). */\n list<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<Projected<R, INCLUDE>[]>;\n list(query: FilterListQuery<FIELDS>, options?: RequestOptions): Promise<R[]>;\n async list(\n query: FilterListQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<R[]>(await this.post('list', query, options), this.listNumbers);\n }\n\n /**\n * The records that match, as server-sent events read one at a time; a\n * failure after the first record errors the stream with its problem. The\n * stream resumes where it stopped (decision D253) when the server ends it\n * to be resumed, when it is cut off and when it fails with a retryable\n * problem: see {@link StreamResumeOptions}. A `limit` counts every record\n * read, resumed or not.\n */\n listStream<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: ListStreamOptions,\n ): Promise<ReadableStream<Projected<R, INCLUDE>>>;\n listStream(\n query: FilterListQuery<FIELDS>,\n options?: ListStreamOptions,\n ): Promise<ReadableStream<R>>;\n async listStream(\n query: FilterListQuery<FIELDS>,\n options?: ListStreamOptions,\n ): Promise<unknown> {\n return (await this.listStreamRows(query, options)).pipeThrough(\n new TransformStream<StreamedRow<R>, R>({\n transform(row, controller) {\n controller.enqueue(row.record);\n },\n }),\n );\n }\n\n /**\n * The records that match as {@link listStream} reads them, each with its\n * position: keep the last one read to resume the stream later\n * ({@link StreamResumeOptions.lastEventId}), on another page or after a\n * restart.\n */\n listStreamRows<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: ListStreamOptions,\n ): Promise<ReadableStream<StreamedRow<Projected<R, INCLUDE>>>>;\n listStreamRows(\n query: FilterListQuery<FIELDS>,\n options?: ListStreamOptions,\n ): Promise<ReadableStream<StreamedRow<R>>>;\n async listStreamRows(\n query: FilterListQuery<FIELDS>,\n options: ListStreamOptions = {},\n ): Promise<ReadableStream<StreamedRow<R>>> {\n const resume =\n options.resume === false ? { maxRetries: 0 } : options.resume;\n const limit = query.limit ?? 0;\n const open = (lastEventId: string | undefined, received: number) => {\n return this.post(\n 'list',\n limit > 0 ? { ...query, limit: limit - received } : query,\n options,\n 'text/event-stream',\n lastEventId,\n );\n };\n const first = await open(resume?.lastEventId, 0);\n return resumableQueryRows<R>(\n first,\n (lastEventId, received) =>\n limit > 0 && received >= limit\n ? Promise.resolve(undefined)\n : open(lastEventId, received),\n {\n ...resume,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(this.numbers === undefined ? {} : { numbers: this.numbers }),\n },\n );\n }\n\n /** One page of the records that match, and their total. */\n paged<const INCLUDE extends FIELDS>(\n query: Including<PagedQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<PagedResult<Projected<R, INCLUDE>>>;\n paged(\n query: PagedQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<PagedResult<R>>;\n async paged(\n query: PagedQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<PagedResult<R>>(\n await this.post('paged', query, options),\n this.pageNumbers,\n );\n }\n\n /** One page of a forward-only cursor over the records that match. */\n cursor<const INCLUDE extends FIELDS>(\n query: Including<CursorQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<CursorPage<Projected<R, INCLUDE>>>;\n cursor(\n query: CursorQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<CursorPage<R>>;\n async cursor(\n query: CursorQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<CursorPage<R>>(\n await this.post('cursor', query, options),\n this.pageNumbers,\n );\n }\n\n /** The first record that matches; rejects with 404 `wow.query.not-found` when none does. */\n single<const INCLUDE extends FIELDS>(\n query: Including<FilterSingleQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<Projected<R, INCLUDE>>;\n single(\n query: FilterSingleQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<R>;\n async single(\n query: FilterSingleQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<R>(await this.post('single', query, options), this.numbers);\n }\n\n /** How many records match, bounded by the count's limit. */\n async count(\n query: CountQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<CountResult> {\n return json<CountResult>(await this.post('count', query, options));\n }\n\n /** The groups and metrics of an aggregation, one row per group. */\n async aggregate<ROW = Record<string, unknown>>(\n query: AggregationQuery<FIELDS, string>,\n options?: RequestOptions,\n ): Promise<ROW[]> {\n return json<ROW[]>(await this.post('aggregate', query, options));\n }\n\n /**\n * The model's capability descriptor; with the `version` already held, a\n * 304 answers `notModified`.\n */\n async describe(\n version?: string,\n options?: RequestOptions,\n ): Promise<DescriptorResult> {\n const response = await send(this.client, {\n method: 'GET',\n path: this.path,\n headers: {\n [WowHeaders.IF_NONE_MATCH]:\n version === undefined ? undefined : `\"${version}\"`,\n },\n options,\n notModified: true,\n });\n const tag = entityTag(response);\n if (response.status === 304) {\n return { notModified: true, version: tag ?? version ?? '' };\n }\n return {\n notModified: false,\n ...(tag === undefined ? {} : { version: tag }),\n descriptor: await json<QueryModelDescriptor>(response),\n };\n }\n\n private post(\n kind: string,\n query: object,\n options?: RequestOptions,\n accept?: string,\n lastEventId?: string,\n ): Promise<Response> {\n return send(this.client, {\n method: 'POST',\n path: this.path,\n headers: { Accept: accept, [WowHeaders.LAST_EVENT_ID]: lastEventId },\n body: { ...query, kind },\n options,\n });\n }\n}\n\n/**\n * A query whose projection includes the literal paths `INCLUDE`: a query\n * client narrows its records to them ({@link Projected}).\n */\nexport type Including<Q, INCLUDE extends string> = Q & {\n readonly projection: { readonly include: readonly INCLUDE[] };\n};\n\n/** The query route of a model of an aggregate type. */\nexport function queryPath(type: AggregateType, model: string): string {\n return `/${type.context}/${type.name}/${model}/query`;\n}\n\n/**\n * Queries an aggregate type's snapshots (decision D128), the default read\n * model; only where the aggregate keeps them.\n *\n * @typeParam S - The state's type.\n * @typeParam STATE_FIELDS - The `state.*` paths of the state.\n */\nexport class SnapshotQueryClient<\n S = unknown,\n STATE_FIELDS extends string = `state.${string}`,\n> extends QueryModelClient<\n SnapshotRecord<S>,\n SnapshotSystemField | STATE_FIELDS\n> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n client?: WowClientOptions,\n ) {\n super(\n queryPath(type, 'snapshot'),\n client,\n type.textNumbers?.state === undefined\n ? undefined\n : { state: type.textNumbers.state },\n );\n }\n}\n\n/**\n * Queries an aggregate type's event streams (decision D235) on the same\n * engine as its snapshots: one record per commit, `count` counts commits, a\n * condition on an event is an `elementMatch` on `events`, and per-event\n * analytics expand `events` in an aggregation (`elements`). A filter need\n * not name the aggregate, but one that does not reads the log the service\n * appends to: the budget bounds it.\n *\n * @typeParam E - The events' type.\n */\nexport class EventQueryClient<\n E extends EventView = EventView,\n> extends QueryModelClient<EventStreamRecord<E>, EventStreamField> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n client?: WowClientOptions,\n ) {\n const events = eventNumbers(type);\n super(\n queryPath(type, 'events'),\n client,\n events === undefined ? undefined : { events: { '*': events } },\n );\n }\n}\n\n/**\n * The datasets of a Wow service (decisions D75, D145): registered at run\n * time, so not in the Manifest. Lists those the caller sees and queries\n * each as a snapshot model is queried.\n */\nexport class DatasetClient {\n /** @param client - How the service is reached */\n constructor(readonly client: WowClientOptions = {}) {}\n\n /** The datasets the caller sees, by name. */\n async list(options?: RequestOptions): Promise<DatasetEntry[]> {\n return json<DatasetEntry[]>(\n await send(this.client, { method: 'GET', path: '/wow/dataset', options }),\n );\n }\n\n /**\n * The query client of the dataset `context.dataset`.\n *\n * @typeParam R - The row's type.\n * @typeParam FIELDS - The dataset's field paths.\n */\n dataset<R = Record<string, unknown>, FIELDS extends string = string>(\n context: string,\n dataset: string,\n ): QueryModelClient<R, FIELDS> {\n return new QueryModelClient<R, FIELDS>(\n `/wow/dataset/${encodeURIComponent(context)}/${encodeURIComponent(dataset)}/query`,\n this.client,\n );\n }\n}\n"],"mappings":";;;;AA8GA,IAAaA,IAAb,MAAiE;CAO/D,YACE,GACA,IAAoC,CAAC,GACrC,G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,EAAK,KAAK,GAAGC,EAAM;AAChD;AASA,IAAaC,IAAb,cAGUzB,EAGR;CAKA,YACE,GACA,GACA;EAFS,AAGT,MACEsB,EAAUC,GAAM,UAAU,GAC1BrB,GACAqB,EAAK,aAAa,UAAU,KAAA,IACxB,KAAA,IACA,EAAE,OAAOA,EAAK,YAAY,MAAM,CACtC,GATS,KAAA,OAAAA;CAUX;AACF,GAYaG,IAAb,cAEU1B,EAAyD;CAKjE,YACE,GACA,GACA;EACA,IAAM2B,IAASC,EAAaL,CAAI;EAHvB,AAIT,MACED,EAAUC,GAAM,QAAQ,GACxBrB,GACAyB,MAAW,KAAA,IAAY,KAAA,IAAY,EAAE,QAAQ,EAAE,KAAKA,EAAO,EAAE,CAC/D,GARS,KAAA,OAAAJ;CASX;AACF,GAOaM,IAAb,MAA2B;CAEzB,YAAY,IAAoC,CAAC,GAAG;EAA/B,KAAA,SAAA3B;CAAgC;CAGrD,MAAM,KAAK,GAAmD;EAC5D,OAAOE,EACL,MAAMY,EAAK,KAAK,QAAQ;GAAE,QAAQ;GAAO,MAAM;GAAgB;EAAQ,CAAC,CAC1E;CACF;CAQA,QACE,GACA,GAC6B;EAC7B,OAAO,IAAIhB,EACT,gBAAgB,mBAAmB8B,CAAO,EAAE,GAAG,mBAAmBC,CAAO,EAAE,SAC3E,KAAK,MACP;CACF;AACF"}
1
+ {"version":3,"file":"queries.es.js","names":["QueryModelClient","path","client","numbers","json","query","options","positioned","resume","limit","open","received","lastEventId","first","resumableQueryRows","error","isNoMatch","response","send","WowHeaders","version","tag","entityTag","accept","WowProblemError","FrameworkErrorCodes","queryPath","type","model","SnapshotQueryClient","EventQueryClient","events","eventNumbers","DatasetClient","context","dataset"],"sources":["../src/queries.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 { AggregationQuery } from './dsl/aggregation/index.js';\nimport type { CursorPage, CursorQuery } from './dsl/cursorQuery.js';\nimport type { Projected } from './dsl/projection.js';\nimport { eventNumbers, type TextNumbers } from './exactJson.js';\nimport type {\n DescriptorResult,\n QueryModelDescriptor,\n} from './dsl/descriptor.js';\nimport type { FilterCapable } from './dsl/filter/index.js';\nimport { FrameworkErrorCodes, WowProblemError } from './problem.js';\nimport type {\n FilterListQuery,\n FilterSingleQuery,\n PagedQuery,\n PagedList,\n} from './dsl/queryable.js';\nimport {\n entityTag,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport type {\n AggregateType,\n DatasetEntry,\n EventStreamField,\n EventStream,\n CommittedEvent,\n Snapshot,\n SnapshotSystemField,\n} from './wire.js';\nimport {\n resumableQueryRows,\n type Positioned,\n type StreamResumeOptions,\n} from './streams.js';\n\n/** How a list is streamed: the request's options, and how it resumes. */\nexport interface StreamOptions extends RequestOptions {\n /** How the stream resumes (decision D253); `false` never resumes it. */\n readonly resume?: StreamResumeOptions | false;\n}\n\n/** A count of a query route. */\nexport interface CountQuery<\n FIELDS extends string = string,\n> extends FilterCapable<FIELDS> {\n /** The most matches to count; the budget's default when absent. */\n limit?: number;\n}\n\n/** What a count answers: exact below its limit, else the limit itself. */\nexport interface CountResult {\n readonly count: number;\n readonly exact: boolean;\n}\n\n/**\n * Queries one query model of a Wow service: `POST {path}` with a body\n * whose `kind` names the operation, `GET {path}` for the capability\n * descriptor. A query written with literal `include`\n * paths answers records narrowed to them ({@link Projected}, review R4-Q,\n * Q-14).\n *\n * @typeParam R - The record's type.\n * @typeParam FIELDS - The field paths a filter, sort or projection takes.\n */\nexport class QueryModelClient<R, FIELDS extends string = string> {\n /**\n * @param path - The query route, `/{context}/{aggregate}/{model}/query`\n * @param client - How the service is reached\n * @param numbers - The numbers of each record read as their exact text\n * (review R4-Q, Q-9)\n */\n constructor(\n readonly path: string,\n readonly client: WowClientOptions = {},\n readonly numbers?: TextNumbers,\n ) {}\n\n /** The marks of a list of records. */\n private get listNumbers(): TextNumbers | undefined {\n return this.numbers === undefined ? undefined : { '*': this.numbers };\n }\n\n /** The marks of a page of records. */\n private get pageNumbers(): TextNumbers | undefined {\n return this.numbers === undefined\n ? undefined\n : { list: { '*': this.numbers } };\n }\n\n /** The records that match, at most `limit` (the server's default when absent). */\n list<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<Projected<R, INCLUDE>[]>;\n list(query: FilterListQuery<FIELDS>, options?: RequestOptions): Promise<R[]>;\n async list(\n query: FilterListQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<R[]>(await this.post('list', query, options), this.listNumbers);\n }\n\n /**\n * The records that match, as server-sent events read one at a time; a\n * failure after the first record errors the stream with its problem. The\n * stream resumes where it stopped (decision D253) when the server ends it\n * to be resumed, when it is cut off and when it fails with a retryable\n * problem: see {@link StreamResumeOptions}. A `limit` counts every record\n * read, resumed or not.\n */\n stream<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: StreamOptions,\n ): Promise<ReadableStream<Projected<R, INCLUDE>>>;\n stream(\n query: FilterListQuery<FIELDS>,\n options?: StreamOptions,\n ): Promise<ReadableStream<R>>;\n async stream(\n query: FilterListQuery<FIELDS>,\n options?: StreamOptions,\n ): Promise<unknown> {\n return (await this.streamRows(query, options)).pipeThrough(\n new TransformStream<Positioned<R>, R>({\n transform(positioned, controller) {\n controller.enqueue(positioned.row);\n },\n }),\n );\n }\n\n /**\n * The records that match as {@link stream} reads them, each with its\n * position: keep the last one read to resume the stream later\n * ({@link StreamResumeOptions.lastEventId}), on another page or after a\n * restart. Kotlin's `RowQueries.stream` answers these rows (`Positioned`).\n */\n streamRows<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: StreamOptions,\n ): Promise<ReadableStream<Positioned<Projected<R, INCLUDE>>>>;\n streamRows(\n query: FilterListQuery<FIELDS>,\n options?: StreamOptions,\n ): Promise<ReadableStream<Positioned<R>>>;\n async streamRows(\n query: FilterListQuery<FIELDS>,\n options: StreamOptions = {},\n ): Promise<ReadableStream<Positioned<R>>> {\n const resume =\n options.resume === false ? { maxRetries: 0 } : options.resume;\n const limit = query.limit;\n const open = (lastEventId: string | undefined, received: number) => {\n return this.post(\n 'list',\n limit === undefined ? query : { ...query, limit: limit - received },\n options,\n 'text/event-stream',\n lastEventId,\n );\n };\n const first = await open(resume?.lastEventId, 0);\n return resumableQueryRows<R>(\n first,\n (lastEventId, received) =>\n limit !== undefined && received >= limit\n ? Promise.resolve(undefined)\n : open(lastEventId, received),\n {\n ...resume,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(this.numbers === undefined ? {} : { numbers: this.numbers }),\n },\n );\n }\n\n /** One page of the records that match, and their total. */\n paged<const INCLUDE extends FIELDS>(\n query: Including<PagedQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<PagedList<Projected<R, INCLUDE>>>;\n paged(\n query: PagedQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<PagedList<R>>;\n async paged(\n query: PagedQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<PagedList<R>>(\n await this.post('paged', query, options),\n this.pageNumbers,\n );\n }\n\n /** One page of a forward-only cursor over the records that match. */\n cursor<const INCLUDE extends FIELDS>(\n query: Including<CursorQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<CursorPage<Projected<R, INCLUDE>>>;\n cursor(\n query: CursorQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<CursorPage<R>>;\n async cursor(\n query: CursorQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<CursorPage<R>>(\n await this.post('cursor', query, options),\n this.pageNumbers,\n );\n }\n\n /**\n * The first record that matches, or `undefined` when none does: the\n * service's 404 `wow.query.not-found`, as Kotlin's `QueryApi.single`\n * answers `null`. Any other 404, of a dataset or a route that does not\n * exist, still rejects.\n */\n single<const INCLUDE extends FIELDS>(\n query: Including<FilterSingleQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<Projected<R, INCLUDE> | undefined>;\n single(\n query: FilterSingleQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<R | undefined>;\n async single(\n query: FilterSingleQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n try {\n return json<R>(await this.post('single', query, options), this.numbers);\n } catch (error) {\n if (isNoMatch(error)) return undefined;\n throw error;\n }\n }\n\n /** How many records match, bounded by the count's limit. */\n async count(\n query: CountQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<CountResult> {\n return json<CountResult>(await this.post('count', query, options));\n }\n\n /** The groups and metrics of an aggregation, one row per group. */\n async aggregate<ROW = Record<string, unknown>>(\n query: AggregationQuery<FIELDS, string>,\n options?: RequestOptions,\n ): Promise<ROW[]> {\n return json<ROW[]>(await this.post('aggregate', query, options));\n }\n\n /**\n * The model's capability descriptor; with the `version` already held, a\n * 304 answers `notModified`.\n */\n async describe(\n version?: string,\n options?: RequestOptions,\n ): Promise<DescriptorResult> {\n const response = await send(this.client, {\n method: 'GET',\n path: this.path,\n headers: {\n [WowHeaders.IF_NONE_MATCH]:\n version === undefined ? undefined : `\"${version}\"`,\n },\n options,\n notModified: true,\n });\n const tag = entityTag(response);\n if (response.status === 304) {\n return { notModified: true, version: tag ?? version ?? '' };\n }\n return {\n notModified: false,\n ...(tag === undefined ? {} : { version: tag }),\n descriptor: await json<QueryModelDescriptor>(response),\n };\n }\n\n private post(\n kind: string,\n query: object,\n options?: RequestOptions,\n accept?: string,\n lastEventId?: string,\n ): Promise<Response> {\n return send(this.client, {\n method: 'POST',\n path: this.path,\n headers: { Accept: accept, [WowHeaders.LAST_EVENT_ID]: lastEventId },\n body: { ...query, kind },\n options,\n });\n }\n}\n\n/**\n * Whether `error` is a 404 that answers \"no match\": a query that found no\n * record, or an aggregate that does not exist. A 404 of another code, or of\n * none (a route that does not exist), is a mistake the caller must hear of.\n */\nfunction isNoMatch(error: unknown): boolean {\n return (\n error instanceof WowProblemError &&\n error.status === 404 &&\n (error.code === FrameworkErrorCodes.QUERY_NOT_FOUND ||\n error.code === FrameworkErrorCodes.AGGREGATE_NOT_FOUND)\n );\n}\n\n/**\n * A query whose projection includes the literal paths `INCLUDE`: a query\n * client narrows its records to them ({@link Projected}).\n */\nexport type Including<Q, INCLUDE extends string> = Q & {\n readonly projection: { readonly include: readonly INCLUDE[] };\n};\n\n/** The query route of a model of an aggregate type. */\nexport function queryPath(type: AggregateType, model: string): string {\n return `/${type.context}/${type.name}/${model}/query`;\n}\n\n/**\n * Queries an aggregate type's snapshots, the default read\n * model; only where the aggregate keeps them.\n *\n * @typeParam S - The state's type.\n * @typeParam STATE_FIELDS - The `state.*` paths of the state.\n */\nexport class SnapshotQueryClient<\n S = unknown,\n STATE_FIELDS extends string = `state.${string}`,\n> extends QueryModelClient<Snapshot<S>, SnapshotSystemField | STATE_FIELDS> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n client?: WowClientOptions,\n ) {\n super(\n queryPath(type, 'snapshot'),\n client,\n type.textNumbers?.state === undefined\n ? undefined\n : { state: type.textNumbers.state },\n );\n }\n}\n\n/**\n * Queries an aggregate type's event streams on the same\n * engine as its snapshots: one record per commit, `count` counts commits, a\n * condition on an event is an `elementMatch` on `events`, and per-event\n * analytics expand `events` in an aggregation (`elements`). A filter need\n * not name the aggregate, but one that does not reads the log the service\n * appends to: the budget bounds it.\n *\n * @typeParam E - The events' type.\n */\nexport class EventQueryClient<\n E extends CommittedEvent = CommittedEvent,\n> extends QueryModelClient<EventStream<E>, EventStreamField> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n client?: WowClientOptions,\n ) {\n const events = eventNumbers(type);\n super(\n queryPath(type, 'events'),\n client,\n events === undefined ? undefined : { events: { '*': events } },\n );\n }\n}\n\n/**\n * The datasets of a Wow service: registered at run\n * time, so not in the Manifest. Lists those the caller sees and queries\n * each as a snapshot model is queried.\n */\nexport class DatasetClient {\n /** @param client - How the service is reached */\n constructor(readonly client: WowClientOptions = {}) {}\n\n /** The datasets the caller sees, by name. */\n async list(options?: RequestOptions): Promise<DatasetEntry[]> {\n return json<DatasetEntry[]>(\n await send(this.client, { method: 'GET', path: '/wow/dataset', options }),\n );\n }\n\n /**\n * The query client of the dataset `context.dataset`.\n *\n * @typeParam R - The row's type.\n * @typeParam FIELDS - The dataset's field paths.\n */\n dataset<R = Record<string, unknown>, FIELDS extends string = string>(\n context: string,\n dataset: string,\n ): QueryModelClient<R, FIELDS> {\n return new QueryModelClient<R, FIELDS>(\n `/wow/dataset/${encodeURIComponent(context)}/${encodeURIComponent(dataset)}/query`,\n this.client,\n );\n }\n}\n"],"mappings":";;;;;;AAkFA,IAAaA,IAAb,MAAiE;CAO/D,YACE,GACA,IAAoC,CAAC,GACrC,GACA;EADS,AAFA,KAAA,OAAAC,GACA,KAAA,SAAAC,GACA,KAAA,UAAAC;CACR;CAGH,IAAY,cAAuC;EACjD,OAAO,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,EAAE,KAAK,KAAK,QAAQ;CACtE;CAGA,IAAY,cAAuC;EACjD,OAAO,KAAK,YAAY,KAAA,IACpB,KAAA,IACA,EAAE,MAAM,EAAE,KAAK,KAAK,QAAQ,EAAE;CACpC;CAQA,MAAM,KACJ,GACA,GACkB;EAClB,OAAOC,EAAU,MAAM,KAAK,KAAK,QAAQC,GAAOC,CAAO,GAAG,KAAK,WAAW;CAC5E;CAkBA,M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AOA,EAAK,YAAY,MAAM,CACtC,GATS,KAAA,OAAAA;CAUX;AACF,GAYaG,IAAb,cAEU9B,EAAmD;CAK3D,YACE,GACA,GACA;EACA,IAAM+B,IAASC,EAAaL,CAAI;EAHvB,AAIT,MACED,EAAUC,GAAM,QAAQ,GACxBzB,GACA6B,MAAW,KAAA,IAAY,KAAA,IAAY,EAAE,QAAQ,EAAE,KAAKA,EAAO,EAAE,CAC/D,GARS,KAAA,OAAAJ;CASX;AACF,GAOaM,IAAb,MAA2B;CAEzB,YAAY,IAAoC,CAAC,GAAG;EAA/B,KAAA,SAAA/B;CAAgC;CAGrD,MAAM,KAAK,GAAmD;EAC5D,OAAOE,EACL,MAAMc,EAAK,KAAK,QAAQ;GAAE,QAAQ;GAAO,MAAM;GAAgB;EAAQ,CAAC,CAC1E;CACF;CAQA,QACE,GACA,GAC6B;EAC7B,OAAO,IAAIlB,EACT,gBAAgB,mBAAmBkC,CAAO,EAAE,GAAG,mBAAmBC,CAAO,EAAE,SAC3E,KAAK,MACP;CACF;AACF"}
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./http.cjs"),t=require("./manifest.cjs");var n=/\{([A-Za-z][A-Za-z0-9]*)}/g,r=class{constructor(e={},n={}){this.client=e,this.manifest=n.manifest===void 0?void 0:Promise.resolve(t.checkManifest(n.manifest))}async call(t,r,i={},a={}){let o=(await this.manifestOf()).contexts.find(e=>e.name===t)?.routes?.find(e=>e.name===r)?.route;if(o===void 0)throw TypeError(`The Manifest lists no service route ${r} of ${t}.`);let s=o.path.replace(n,(e,n)=>{let a=i.path?.[n];if(a===void 0)throw TypeError(`The service route ${t}.${r} needs its path variable ${n}.`);return encodeURIComponent(String(a))}),c=i.query?Object.fromEntries(Object.entries(i.query).map(([e,t])=>[e,t===void 0?void 0:String(t)])):void 0,l=await e.send(this.client,{method:o.method,path:s,...c===void 0?{}:{query:c},...i.body===void 0?{}:{body:i.body},...i.requestId===void 0?{}:{headers:{[e.WowHeaders.REQUEST_ID]:i.requestId}},options:a});return l.status===204?void 0:e.json(l)}manifestOf(){return this.manifest??=t.fetchManifest(this.client).catch(e=>{throw this.manifest=void 0,e}),this.manifest}};exports.ServiceRoutes=r;
2
+ //# sourceMappingURL=routes.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.cjs","names":["checkManifest","send","WowHeaders","json","fetchManifest","require_http","require_manifest","VARIABLE","ServiceRoutes","client","options","route","item","context","name","path","value","call","variable","query","key","response","error"],"sources":["../src/routes.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 * The client of a service's own routes: routes whose handler is the service's\n * code, neither a command nor a query, listed in its Manifest with their\n * parameters and schemas. A generated client (`routes.ts`) calls each by its\n * name with typed parameters; a hand-written one calls {@link ServiceRoutes.call}.\n *\n * @packageDocumentation\n */\n\nimport {\n type Call,\n type RequestOptions,\n send,\n json,\n WowHeaders,\n type WowClientOptions,\n} from './http.js';\nimport {\n checkManifest,\n fetchManifest,\n type RoutingManifest,\n} from './manifest.js';\n\n/** What a call of a service route sends, besides its route. */\nexport interface ServiceRouteCall {\n /** The path's variables, by name: each of the route's `{name}`. */\n readonly path?: Readonly<Record<string, string | number | boolean>>;\n /** The query parameters, by name; one left undefined is not sent. */\n readonly query?: Readonly<\n Record<string, string | number | boolean | undefined>\n >;\n /** The body, for a route that takes one. */\n readonly body?: unknown;\n /** The request's id (`Wow-Request-Id`); the service makes one without it. */\n readonly requestId?: string;\n}\n\n/** Options of a {@link ServiceRoutes}. */\nexport interface ServiceRoutesOptions {\n /**\n * The service's Manifest, or the part of it that lists the routes; without\n * it the client reads the service's (`GET /wow/manifest`) once.\n */\n readonly manifest?: RoutingManifest;\n}\n\nconst VARIABLE = /\\{([A-Za-z][A-Za-z0-9]*)}/g;\n\n/**\n * Calls a service's routes by the names its Manifest gives them. The answer\n * is the route's JSON, `undefined` for one that answers `204 No Content`; a\n * refusal rejects with the {@link WowProblemError} of its code, a parameter\n * that does not read with `wow.route.malformed`.\n */\nexport class ServiceRoutes {\n private manifest: Promise<RoutingManifest> | undefined;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: ServiceRoutesOptions = {},\n ) {\n this.manifest =\n options.manifest === undefined\n ? undefined\n : Promise.resolve(checkManifest(options.manifest));\n }\n\n /**\n * Calls the route `name` of `context` and answers what it answers.\n *\n * @param context - The bounded context whose route it is\n * @param name - The route's name in the Manifest\n * @param call - Its path variables, query parameters and body\n * @param options - The scope or space to act in, headers and cancellation\n * @throws TypeError when the Manifest lists no such route, or a path\n * variable is missing\n */\n async call<T = unknown>(\n context: string,\n name: string,\n call: ServiceRouteCall = {},\n options: RequestOptions = {},\n ): Promise<T | undefined> {\n const route = (await this.manifestOf()).contexts\n .find(item => item.name === context)\n ?.routes?.find(item => item.name === name)?.route;\n if (route === undefined) {\n throw new TypeError(\n `The Manifest lists no service route ${name} of ${context}.`,\n );\n }\n const path = route.path.replace(VARIABLE, (_, variable: string) => {\n const value = call.path?.[variable];\n if (value === undefined) {\n throw new TypeError(\n `The service route ${context}.${name} needs its path variable ${variable}.`,\n );\n }\n return encodeURIComponent(String(value));\n });\n const query = call.query\n ? Object.fromEntries(\n Object.entries(call.query).map(([key, value]) => [\n key,\n value === undefined ? undefined : String(value),\n ]),\n )\n : undefined;\n const response = await send(this.client, {\n method: route.method as Call['method'],\n path,\n ...(query === undefined ? {} : { query }),\n ...(call.body === undefined ? {} : { body: call.body }),\n ...(call.requestId === undefined\n ? {}\n : { headers: { [WowHeaders.REQUEST_ID]: call.requestId } }),\n options,\n });\n return response.status === 204 ? undefined : json<T>(response);\n }\n\n /** The Manifest given, or the service's, fetched once (again after a failure). */\n private manifestOf(): Promise<RoutingManifest> {\n this.manifest ??= fetchManifest(this.client).catch((error: unknown) => {\n this.manifest = undefined;\n throw error;\n });\n return this.manifest;\n }\n}\n"],"mappings":"A,6HA2DA,IAAMO,EAAW,6BAQJC,EAAb,KAA2B,CAOzB,YACE,EAAoC,CAAC,EACrC,EAAgC,CAAC,EACjC,CAFS,KAAA,OAAAC,EAGT,KAAK,SACHC,EAAQ,WAAa,IAAA,GACjB,IAAA,GACA,QAAQ,QAAQV,EAAAA,cAAcU,EAAQ,QAAQ,CAAC,CACvD,CAYA,MAAM,KACJ,EACA,EACA,EAAyB,CAAC,EAC1B,EAA0B,CAAC,EACH,CACxB,IAAMC,GAAS,MAAM,KAAK,WAAW,EAAA,CAAG,SACrC,KAAK,GAAQC,EAAK,OAASC,CAAO,CAAC,EAClC,QAAQ,KAAK,GAAQD,EAAK,OAASE,CAAI,CAAC,EAAE,MAC9C,GAAIH,IAAU,IAAA,GACZ,MAAU,UACR,uCAAuCG,EAAK,MAAMD,EAAQ,EAC5D,EAEF,IAAME,EAAOJ,EAAM,KAAK,QAAQJ,GAAW,EAAG,IAAqB,CACjE,IAAMS,EAAQC,EAAK,OAAOC,GAC1B,GAAIF,IAAU,IAAA,GACZ,MAAU,UACR,qBAAqBH,EAAQ,GAAGC,EAAK,2BAA2BI,EAAS,EAC3E,EAEF,OAAO,mBAAmB,OAAOF,CAAK,CAAC,CACzC,CAAC,EACKG,EAAQF,EAAK,MACf,OAAO,YACL,OAAO,QAAQA,EAAK,KAAK,CAAC,CAAC,KAAK,CAACG,EAAKJ,KAAW,CAC/CI,EACAJ,IAAU,IAAA,GAAY,IAAA,GAAY,OAAOA,CAAK,CAChD,CAAC,CACH,EACA,IAAA,GACEK,EAAW,MAAMpB,EAAAA,KAAK,KAAK,OAAQ,CACvC,OAAQU,EAAM,OACd,OACA,GAAIQ,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,OAAM,EACvC,GAAIF,EAAK,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAK,IAAK,EACrD,GAAIA,EAAK,YAAc,IAAA,GACnB,CAAC,EACD,CAAE,QAAS,EAAGf,EAAAA,WAAW,YAAae,EAAK,SAAU,CAAE,EAC3D,SACF,CAAC,EACD,OAAOI,EAAS,SAAW,IAAM,IAAA,GAAYlB,EAAAA,KAAQkB,CAAQ,CAC/D,CAGA,YAA+C,CAK7C,MAJA,MAAK,WAAajB,EAAAA,cAAc,KAAK,MAAM,CAAC,CAAC,MAAO,GAAmB,CAErE,KADA,MAAK,SAAW,IAAA,GACVkB,CACR,CAAC,EACM,KAAK,QACd,CACF,E"}
@@ -0,0 +1,49 @@
1
+ import { RequestOptions, WowClientOptions } from './http.cjs';
2
+ import { RoutingManifest } from './manifest.cjs';
3
+ /** What a call of a service route sends, besides its route. */
4
+ export interface ServiceRouteCall {
5
+ /** The path's variables, by name: each of the route's `{name}`. */
6
+ readonly path?: Readonly<Record<string, string | number | boolean>>;
7
+ /** The query parameters, by name; one left undefined is not sent. */
8
+ readonly query?: Readonly<Record<string, string | number | boolean | undefined>>;
9
+ /** The body, for a route that takes one. */
10
+ readonly body?: unknown;
11
+ /** The request's id (`Wow-Request-Id`); the service makes one without it. */
12
+ readonly requestId?: string;
13
+ }
14
+ /** Options of a {@link ServiceRoutes}. */
15
+ export interface ServiceRoutesOptions {
16
+ /**
17
+ * The service's Manifest, or the part of it that lists the routes; without
18
+ * it the client reads the service's (`GET /wow/manifest`) once.
19
+ */
20
+ readonly manifest?: RoutingManifest;
21
+ }
22
+ /**
23
+ * Calls a service's routes by the names its Manifest gives them. The answer
24
+ * is the route's JSON, `undefined` for one that answers `204 No Content`; a
25
+ * refusal rejects with the {@link WowProblemError} of its code, a parameter
26
+ * that does not read with `wow.route.malformed`.
27
+ */
28
+ export declare class ServiceRoutes {
29
+ readonly client: WowClientOptions;
30
+ private manifest;
31
+ /**
32
+ * @param client - How the service is reached
33
+ * @param options - The service's Manifest
34
+ */
35
+ constructor(client?: WowClientOptions, options?: ServiceRoutesOptions);
36
+ /**
37
+ * Calls the route `name` of `context` and answers what it answers.
38
+ *
39
+ * @param context - The bounded context whose route it is
40
+ * @param name - The route's name in the Manifest
41
+ * @param call - Its path variables, query parameters and body
42
+ * @param options - The scope or space to act in, headers and cancellation
43
+ * @throws TypeError when the Manifest lists no such route, or a path
44
+ * variable is missing
45
+ */
46
+ call<T = unknown>(context: string, name: string, call?: ServiceRouteCall, options?: RequestOptions): Promise<T | undefined>;
47
+ /** The Manifest given, or the service's, fetched once (again after a failure). */
48
+ private manifestOf;
49
+ }
@@ -0,0 +1,49 @@
1
+ import { RequestOptions, WowClientOptions } from './http.js';
2
+ import { RoutingManifest } from './manifest.js';
3
+ /** What a call of a service route sends, besides its route. */
4
+ export interface ServiceRouteCall {
5
+ /** The path's variables, by name: each of the route's `{name}`. */
6
+ readonly path?: Readonly<Record<string, string | number | boolean>>;
7
+ /** The query parameters, by name; one left undefined is not sent. */
8
+ readonly query?: Readonly<Record<string, string | number | boolean | undefined>>;
9
+ /** The body, for a route that takes one. */
10
+ readonly body?: unknown;
11
+ /** The request's id (`Wow-Request-Id`); the service makes one without it. */
12
+ readonly requestId?: string;
13
+ }
14
+ /** Options of a {@link ServiceRoutes}. */
15
+ export interface ServiceRoutesOptions {
16
+ /**
17
+ * The service's Manifest, or the part of it that lists the routes; without
18
+ * it the client reads the service's (`GET /wow/manifest`) once.
19
+ */
20
+ readonly manifest?: RoutingManifest;
21
+ }
22
+ /**
23
+ * Calls a service's routes by the names its Manifest gives them. The answer
24
+ * is the route's JSON, `undefined` for one that answers `204 No Content`; a
25
+ * refusal rejects with the {@link WowProblemError} of its code, a parameter
26
+ * that does not read with `wow.route.malformed`.
27
+ */
28
+ export declare class ServiceRoutes {
29
+ readonly client: WowClientOptions;
30
+ private manifest;
31
+ /**
32
+ * @param client - How the service is reached
33
+ * @param options - The service's Manifest
34
+ */
35
+ constructor(client?: WowClientOptions, options?: ServiceRoutesOptions);
36
+ /**
37
+ * Calls the route `name` of `context` and answers what it answers.
38
+ *
39
+ * @param context - The bounded context whose route it is
40
+ * @param name - The route's name in the Manifest
41
+ * @param call - Its path variables, query parameters and body
42
+ * @param options - The scope or space to act in, headers and cancellation
43
+ * @throws TypeError when the Manifest lists no such route, or a path
44
+ * variable is missing
45
+ */
46
+ call<T = unknown>(context: string, name: string, call?: ServiceRouteCall, options?: RequestOptions): Promise<T | undefined>;
47
+ /** The Manifest given, or the service's, fetched once (again after a failure). */
48
+ private manifestOf;
49
+ }
@@ -0,0 +1,33 @@
1
+ import { WowHeaders as e, json as t, send as n } from "./http.es.js";
2
+ import { checkManifest as r, fetchManifest as i } from "./manifest.es.js";
3
+ // src/routes.ts
4
+ var a = /\{([A-Za-z][A-Za-z0-9]*)}/g, o = class {
5
+ constructor(e = {}, t = {}) {
6
+ this.client = e, this.manifest = t.manifest === void 0 ? void 0 : Promise.resolve(r(t.manifest));
7
+ }
8
+ async call(r, i, o = {}, s = {}) {
9
+ let c = (await this.manifestOf()).contexts.find((e) => e.name === r)?.routes?.find((e) => e.name === i)?.route;
10
+ if (c === void 0) throw TypeError(`The Manifest lists no service route ${i} of ${r}.`);
11
+ let l = c.path.replace(a, (e, t) => {
12
+ let n = o.path?.[t];
13
+ if (n === void 0) throw TypeError(`The service route ${r}.${i} needs its path variable ${t}.`);
14
+ return encodeURIComponent(String(n));
15
+ }), u = o.query ? Object.fromEntries(Object.entries(o.query).map(([e, t]) => [e, t === void 0 ? void 0 : String(t)])) : void 0, d = await n(this.client, {
16
+ method: c.method,
17
+ path: l,
18
+ ...u === void 0 ? {} : { query: u },
19
+ ...o.body === void 0 ? {} : { body: o.body },
20
+ ...o.requestId === void 0 ? {} : { headers: { [e.REQUEST_ID]: o.requestId } },
21
+ options: s
22
+ });
23
+ return d.status === 204 ? void 0 : t(d);
24
+ }
25
+ manifestOf() {
26
+ return this.manifest ??= i(this.client).catch((e) => {
27
+ throw this.manifest = void 0, e;
28
+ }), this.manifest;
29
+ }
30
+ };
31
+ export { o as ServiceRoutes };
32
+
33
+ //# sourceMappingURL=routes.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.es.js","names":["VARIABLE","ServiceRoutes","client","options","checkManifest","route","item","context","name","path","value","call","variable","query","key","response","send","WowHeaders","json","fetchManifest","error"],"sources":["../src/routes.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 * The client of a service's own routes: routes whose handler is the service's\n * code, neither a command nor a query, listed in its Manifest with their\n * parameters and schemas. A generated client (`routes.ts`) calls each by its\n * name with typed parameters; a hand-written one calls {@link ServiceRoutes.call}.\n *\n * @packageDocumentation\n */\n\nimport {\n type Call,\n type RequestOptions,\n send,\n json,\n WowHeaders,\n type WowClientOptions,\n} from './http.js';\nimport {\n checkManifest,\n fetchManifest,\n type RoutingManifest,\n} from './manifest.js';\n\n/** What a call of a service route sends, besides its route. */\nexport interface ServiceRouteCall {\n /** The path's variables, by name: each of the route's `{name}`. */\n readonly path?: Readonly<Record<string, string | number | boolean>>;\n /** The query parameters, by name; one left undefined is not sent. */\n readonly query?: Readonly<\n Record<string, string | number | boolean | undefined>\n >;\n /** The body, for a route that takes one. */\n readonly body?: unknown;\n /** The request's id (`Wow-Request-Id`); the service makes one without it. */\n readonly requestId?: string;\n}\n\n/** Options of a {@link ServiceRoutes}. */\nexport interface ServiceRoutesOptions {\n /**\n * The service's Manifest, or the part of it that lists the routes; without\n * it the client reads the service's (`GET /wow/manifest`) once.\n */\n readonly manifest?: RoutingManifest;\n}\n\nconst VARIABLE = /\\{([A-Za-z][A-Za-z0-9]*)}/g;\n\n/**\n * Calls a service's routes by the names its Manifest gives them. The answer\n * is the route's JSON, `undefined` for one that answers `204 No Content`; a\n * refusal rejects with the {@link WowProblemError} of its code, a parameter\n * that does not read with `wow.route.malformed`.\n */\nexport class ServiceRoutes {\n private manifest: Promise<RoutingManifest> | undefined;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: ServiceRoutesOptions = {},\n ) {\n this.manifest =\n options.manifest === undefined\n ? undefined\n : Promise.resolve(checkManifest(options.manifest));\n }\n\n /**\n * Calls the route `name` of `context` and answers what it answers.\n *\n * @param context - The bounded context whose route it is\n * @param name - The route's name in the Manifest\n * @param call - Its path variables, query parameters and body\n * @param options - The scope or space to act in, headers and cancellation\n * @throws TypeError when the Manifest lists no such route, or a path\n * variable is missing\n */\n async call<T = unknown>(\n context: string,\n name: string,\n call: ServiceRouteCall = {},\n options: RequestOptions = {},\n ): Promise<T | undefined> {\n const route = (await this.manifestOf()).contexts\n .find(item => item.name === context)\n ?.routes?.find(item => item.name === name)?.route;\n if (route === undefined) {\n throw new TypeError(\n `The Manifest lists no service route ${name} of ${context}.`,\n );\n }\n const path = route.path.replace(VARIABLE, (_, variable: string) => {\n const value = call.path?.[variable];\n if (value === undefined) {\n throw new TypeError(\n `The service route ${context}.${name} needs its path variable ${variable}.`,\n );\n }\n return encodeURIComponent(String(value));\n });\n const query = call.query\n ? Object.fromEntries(\n Object.entries(call.query).map(([key, value]) => [\n key,\n value === undefined ? undefined : String(value),\n ]),\n )\n : undefined;\n const response = await send(this.client, {\n method: route.method as Call['method'],\n path,\n ...(query === undefined ? {} : { query }),\n ...(call.body === undefined ? {} : { body: call.body }),\n ...(call.requestId === undefined\n ? {}\n : { headers: { [WowHeaders.REQUEST_ID]: call.requestId } }),\n options,\n });\n return response.status === 204 ? undefined : json<T>(response);\n }\n\n /** The Manifest given, or the service's, fetched once (again after a failure). */\n private manifestOf(): Promise<RoutingManifest> {\n this.manifest ??= fetchManifest(this.client).catch((error: unknown) => {\n this.manifest = undefined;\n throw error;\n });\n return this.manifest;\n }\n}\n"],"mappings":";;;AA2DA,IAAMA,IAAW,8BAQJC,IAAb,MAA2B;CAOzB,YACE,IAAoC,CAAC,GACrC,IAAgC,CAAC,GACjC;EACA,AAHS,KAAA,SAAAC,GAGT,KAAK,WACHC,EAAQ,aAAa,KAAA,IACjB,KAAA,IACA,QAAQ,QAAQC,EAAcD,EAAQ,QAAQ,CAAC;CACvD;CAYA,MAAM,KACJ,GACA,GACA,IAAyB,CAAC,GAC1B,IAA0B,CAAC,GACH;EACxB,IAAME,KAAS,MAAM,KAAK,WAAW,EAAA,CAAG,SACrC,MAAK,MAAQC,EAAK,SAASC,CAAO,CAAC,EAClC,QAAQ,MAAK,MAAQD,EAAK,SAASE,CAAI,CAAC,EAAE;EAC9C,IAAIH,MAAU,KAAA,GACZ,MAAU,UACR,uCAAuCG,EAAK,MAAMD,EAAQ,EAC5D;EAEF,IAAME,IAAOJ,EAAM,KAAK,QAAQL,IAAW,GAAG,MAAqB;GACjE,IAAMU,IAAQC,EAAK,OAAOC;GAC1B,IAAIF,MAAU,KAAA,GACZ,MAAU,UACR,qBAAqBH,EAAQ,GAAGC,EAAK,2BAA2BI,EAAS,EAC3E;GAEF,OAAO,mBAAmB,OAAOF,CAAK,CAAC;EACzC,CAAC,GACKG,IAAQF,EAAK,QACf,OAAO,YACL,OAAO,QAAQA,EAAK,KAAK,CAAC,CAAC,KAAK,CAACG,GAAKJ,OAAW,CAC/CI,GACAJ,MAAU,KAAA,IAAY,KAAA,IAAY,OAAOA,CAAK,CAChD,CAAC,CACH,IACA,KAAA,GACEK,IAAW,MAAMC,EAAK,KAAK,QAAQ;GACvC,QAAQX,EAAM;GACd;GACA,GAAIQ,MAAU,KAAA,IAAY,CAAC,IAAI,EAAE,SAAM;GACvC,GAAIF,EAAK,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAMA,EAAK,KAAK;GACrD,GAAIA,EAAK,cAAc,KAAA,IACnB,CAAC,IACD,EAAE,SAAS,GAAGM,EAAW,aAAaN,EAAK,UAAU,EAAE;GAC3D;EACF,CAAC;EACD,OAAOI,EAAS,WAAW,MAAM,KAAA,IAAYG,EAAQH,CAAQ;CAC/D;CAGA,aAA+C;EAK7C,OAJA,KAAK,aAAaI,EAAc,KAAK,MAAM,CAAC,CAAC,OAAO,MAAmB;GAErE,MADA,KAAK,WAAW,KAAA,GACVC;EACR,CAAC,GACM,KAAK;CACd;AACF"}
package/dist/state.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./exactJson.cjs"),t=require("./http.cjs");var n=class{constructor(e,t={}){this.type=e,this.client=t}async read(e,n={}){let r=n.at instanceof Date?n.at.toISOString():n.at,i=await t.send(this.client,{method:`GET`,path:this.statePath(e),query:{version:n.version,at:r,minVersion:n.minVersion},headers:{[t.WowHeaders.IF_NONE_MATCH]:n.ifNoneMatch===void 0?void 0:`"${n.ifNoneMatch}"`},options:n,notModified:!0});if(i.status===304){let e=t.entityTag(i)??n.ifNoneMatch??``;return{notModified:!0,version:Number.parseInt(e,10),etag:e}}return{notModified:!1,view:await t.json(i,this.stateNumbers),etag:t.entityTag(i)}}async get(e,t={}){let n=await this.read(e,t);if(n.notModified)throw Error(`A read without If-None-Match was answered 304.`);return n.view}async trace(e,n={}){return t.json(await t.send(this.client,{method:`GET`,path:`${this.statePath(e)}/trace`,query:{from:n.from,to:n.to,limit:n.limit},options:n}),this.traceNumbers)}get stateNumbers(){let e=this.type.textNumbers?.state;return e===void 0?void 0:{state:e}}get traceNumbers(){let t=this.type.textNumbers?.state,n=e.eventNumbers(this.type);if(t!==void 0||n!==void 0)return{commits:{"*":{...t===void 0?{}:{state:t},...n===void 0?{}:{events:{"*":n}}}}}}statePath(e){return`/${this.type.context}/${this.type.name}/${encodeURIComponent(e)}/state`}};exports.StateClient=n;
1
+ const e=require("./exactJson.cjs"),t=require("./frameworkErrors.cjs"),n=require("./problem.cjs"),r=require("./http.cjs");var i=class{constructor(e,t={}){this.type=e,this.client=t}read(e,t={}){return this.readAt(e,t)}get(e,t={}){return this.getAt(e,t)}find(e,t={}){return this.findAt(e,t)}trace(e,t={}){return this.traceAt(e,t)}async readAt(e,t){let n=t.at instanceof Date?t.at.toISOString():t.at,i=await r.send(this.client,{method:`GET`,path:this.statePath(e),query:{version:t.version,at:n,minVersion:t.minVersion},headers:{[r.WowHeaders.IF_NONE_MATCH]:t.ifNoneMatch===void 0?void 0:`"${t.ifNoneMatch}"`},options:t,notModified:!0});if(i.status===304){let e=r.entityTag(i)??t.ifNoneMatch??``;return{notModified:!0,version:Number.parseInt(e,10),etag:e}}return{notModified:!1,snapshot:await r.json(i,this.stateNumbers),etag:r.entityTag(i)}}async getAt(e,t){let n=await this.readAt(e,t);if(n.notModified)throw Error(`A read without If-None-Match was answered 304.`);return n.snapshot}async findAt(e,r){try{return await this.getAt(e,r)}catch(e){if(e instanceof n.WowProblemError&&e.status===404&&e.code===t.FrameworkErrorCodes.AGGREGATE_NOT_FOUND)return;throw e}}async traceAt(e,t){return r.json(await r.send(this.client,{method:`GET`,path:`${this.statePath(e)}/trace`,query:{from:t.from,to:t.to,limit:t.limit},options:t}),this.traceNumbers)}get stateNumbers(){let e=this.type.textNumbers?.state;return e===void 0?void 0:{state:e}}get traceNumbers(){let t=this.type.textNumbers?.state,n=e.eventNumbers(this.type);if(t!==void 0||n!==void 0)return{commits:{"*":{...t===void 0?{}:{state:t},...n===void 0?{}:{events:{"*":n}}}}}}statePath(e){let t=`/${this.type.context}/${this.type.name}`;return e===void 0?`${t}/state`:`${t}/${encodeURIComponent(e)}/state`}},a=class extends i{readOwn(e={}){return this.readAt(void 0,e)}getOwn(e={}){return this.getAt(void 0,e)}findOwn(e={}){return this.findAt(void 0,e)}traceOwn(e={}){return this.traceAt(void 0,e)}};exports.OwnStateClient=a,exports.StateClient=i;
2
2
  //# sourceMappingURL=state.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"state.cjs","names":["send","WowHeaders","entityTag","json","eventNumbers","require_exactJson","require_http","StateClient","type","client","at","options","response","id","etag","result","state","events"],"sources":["../src/state.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 {\n entityTag,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport { eventNumbers, type TextNumbers } from './exactJson.js';\nimport type {\n AggregateType,\n EventView,\n StateTrace,\n StateView,\n} from './wire.js';\n\n/** Which state a read asks for: the latest, at a version or as of a time. */\nexport interface StateReadOptions extends RequestOptions {\n /** The committed state at this version. */\n readonly version?: number;\n /** The committed state as of this instant (ISO-8601, or a `Date`). */\n readonly at?: string | Date;\n /**\n * The latest state at this version or later (review R4-Q, Q-13: read your\n * writes), such as the `version` of a command's result: a lagging snapshot is\n * caught up with the log. Not with `version` or `at`. One not reached within\n * the server's wait rejects with 409 `wow.query.min-version-not-reached`,\n * whose `version` is the current one.\n */\n readonly minVersion?: number;\n /**\n * The entity tag of the state already held, as a read answered it\n * (`etag`): a 304 then answers `notModified`. The tag is the version and a\n * digest of the body (`3-<digest>`), so it changes whenever what is read\n * does, not only with the version.\n */\n readonly ifNoneMatch?: string;\n}\n\n/**\n * A state read: the view and its entity tag, or `notModified` when the state\n * held is current, with its tag and the version the tag names.\n */\nexport type StateReadResult<S> =\n | {\n readonly notModified: false;\n readonly view: StateView<S>;\n readonly etag?: string;\n }\n | {\n readonly notModified: true;\n readonly version: number;\n readonly etag: string;\n };\n\n/** Which commits a trace reads (decision D40). */\nexport interface StateTraceOptions extends RequestOptions {\n /** The first version; 1 when absent. */\n readonly from?: number;\n /** The last version; the latest when absent. */\n readonly to?: number;\n /** The most commits, at most 1000; 100 when absent. */\n readonly limit?: number;\n}\n\n/**\n * Reads an aggregate type's states (decisions D40, D112):\n * `GET /{context}/{aggregate}/{id}/state` with `?version=`, `?at=` or `?minVersion=`, and\n * its trace, `…/state/trace`. A state that does not exist rejects with 404\n * `wow.aggregate.not-found`.\n *\n * @typeParam S - The state's type.\n * @typeParam E - The events' type of a trace.\n */\nexport class StateClient<S = unknown, E extends EventView = EventView> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n readonly client: WowClientOptions = {},\n ) {}\n\n /** The state the options ask for. */\n async read(\n id: string,\n options: StateReadOptions = {},\n ): Promise<StateReadResult<S>> {\n const at =\n options.at instanceof Date ? options.at.toISOString() : options.at;\n const response = await send(this.client, {\n method: 'GET',\n path: this.statePath(id),\n query: { version: options.version, at, minVersion: options.minVersion },\n headers: {\n [WowHeaders.IF_NONE_MATCH]:\n options.ifNoneMatch === undefined\n ? undefined\n : `\"${options.ifNoneMatch}\"`,\n },\n options,\n notModified: true,\n });\n if (response.status === 304) {\n const etag = entityTag(response) ?? options.ifNoneMatch ?? '';\n return {\n notModified: true,\n version: Number.parseInt(etag, 10),\n etag,\n };\n }\n return {\n notModified: false,\n view: await json<StateView<S>>(response, this.stateNumbers),\n etag: entityTag(response),\n };\n }\n\n /** The latest state, or the one the options ask for, without a cache. */\n async get(\n id: string,\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<StateView<S>> {\n const result = await this.read(id, options);\n if (result.notModified) {\n throw new Error('A read without If-None-Match was answered 304.');\n }\n return result.view;\n }\n\n /** The commits from `from` to `to`, each with its events and the state after it. */\n async trace(\n id: string,\n options: StateTraceOptions = {},\n ): Promise<StateTrace<S, E>> {\n return json<StateTrace<S, E>>(\n await send(this.client, {\n method: 'GET',\n path: `${this.statePath(id)}/trace`,\n query: { from: options.from, to: options.to, limit: options.limit },\n options,\n }),\n this.traceNumbers,\n );\n }\n\n /** The exact numbers of a state view: its state's. */\n private get stateNumbers(): TextNumbers | undefined {\n const state = this.type.textNumbers?.state;\n return state === undefined ? undefined : { state };\n }\n\n /** The exact numbers of a trace: each commit's state and events. */\n private get traceNumbers(): TextNumbers | undefined {\n const state = this.type.textNumbers?.state;\n const events = eventNumbers(this.type);\n if (state === undefined && events === undefined) return undefined;\n return {\n commits: {\n '*': {\n ...(state === undefined ? {} : { state }),\n ...(events === undefined ? {} : { events: { '*': events } }),\n },\n },\n };\n }\n\n private statePath(id: string): string {\n return `/${this.type.context}/${this.type.name}/${encodeURIComponent(id)}/state`;\n }\n}\n"],"mappings":"2DAuFA,IAAaO,EAAb,KAAuE,CAKrE,YACE,EACA,EAAoC,CAAC,EACrC,CAFS,KAAA,KAAAC,EACA,KAAA,OAAAC,CACR,CAGH,MAAM,KACJ,EACA,EAA4B,CAAC,EACA,CAC7B,IAAMC,EACJC,EAAQ,cAAc,KAAOA,EAAQ,GAAG,YAAY,EAAIA,EAAQ,GAC5DC,EAAW,MAAMZ,EAAAA,KAAK,KAAK,OAAQ,CACvC,OAAQ,MACR,KAAM,KAAK,UAAUa,CAAE,EACvB,MAAO,CAAE,QAASF,EAAQ,QAAS,KAAI,WAAYA,EAAQ,UAAW,EACtE,QAAS,EACNV,EAAAA,WAAW,eACVU,EAAQ,cAAgB,IAAA,GACpB,IAAA,GACA,IAAIA,EAAQ,YAAY,EAChC,EACA,UACA,YAAa,EACf,CAAC,EACD,GAAIC,EAAS,SAAW,IAAK,CAC3B,IAAME,EAAOZ,EAAAA,UAA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C3E,CACF"}
1
+ {"version":3,"file":"state.cjs","names":["send","WowHeaders","entityTag","json","WowProblemError","FrameworkErrorCodes","eventNumbers","require_exactJson","require_frameworkErrors","require_problem","require_http","StateClient","type","client","id","options","at","response","etag","result","error","state","events","base","OwnStateClient"],"sources":["../src/state.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 {\n entityTag,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport { eventNumbers, type TextNumbers } from './exactJson.js';\nimport { FrameworkErrorCodes, WowProblemError } from './problem.js';\nimport type {\n AggregateType,\n CommittedEvent,\n StateTrace,\n Snapshot,\n} from './wire.js';\n\n/** Which state a read asks for: the latest, at a version or as of a time. */\nexport interface StateReadOptions extends RequestOptions {\n /** The committed state at this version. */\n readonly version?: number;\n /** The committed state as of this instant (ISO-8601, or a `Date`). */\n readonly at?: string | Date;\n /**\n * The latest state at this version or later (review R4-Q, Q-13: read your\n * writes), such as the `version` of a command's result: a lagging snapshot is\n * caught up with the log. Not with `version` or `at`. One not reached within\n * the server's wait rejects with 409 `wow.query.min-version-not-reached`,\n * whose `version` is the current one.\n */\n readonly minVersion?: number;\n /**\n * The entity tag of the state already held, as a read answered it\n * (`etag`): a 304 then answers `notModified`. The tag is the version and a\n * digest of the body (`3-<digest>`), so it changes whenever what is read\n * does, not only with the version.\n */\n readonly ifNoneMatch?: string;\n}\n\n/**\n * A state read: the snapshot and its entity tag, or `notModified` when the\n * state held is current, with its tag and the version the tag names.\n */\nexport type StateReadResult<S> =\n | {\n readonly notModified: false;\n readonly snapshot: Snapshot<S>;\n readonly etag?: string;\n }\n | {\n readonly notModified: true;\n readonly version: number;\n readonly etag: string;\n };\n\n/** Which commits a trace reads. */\nexport interface StateTraceOptions extends RequestOptions {\n /** The first version; 1 when absent. */\n readonly from?: number;\n /** The last version; the latest when absent. */\n readonly to?: number;\n /** The most commits, at most 1000; 100 when absent. */\n readonly limit?: number;\n}\n\n/**\n * Reads an aggregate type's states:\n * `GET /{context}/{aggregate}/{id}/state` with `?version=`, `?at=` or `?minVersion=`, and\n * its trace, `…/state/trace`; {@link OwnStateClient} reads the caller's own\n * of a type whose id is its owner's. A state that does not exist rejects with 404\n * `wow.aggregate.not-found`, except through {@link StateClient.find}, which\n * answers `undefined`.\n *\n * @typeParam S - The state's type.\n * @typeParam E - The events' type of a trace.\n */\nexport class StateClient<\n S = unknown,\n E extends CommittedEvent = CommittedEvent,\n> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n readonly client: WowClientOptions = {},\n ) {}\n\n /** The state the options ask for. */\n read(\n id: string,\n options: StateReadOptions = {},\n ): Promise<StateReadResult<S>> {\n return this.readAt(id, options);\n }\n\n /** The latest state, or the one the options ask for, without a cache. */\n get(\n id: string,\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<Snapshot<S>> {\n return this.getAt(id, options);\n }\n\n /**\n * The latest state, or the one the options ask for, or `undefined` when the\n * aggregate does not exist (404 `wow.aggregate.not-found`), as Kotlin's\n * `SnapshotQueries.state` answers null. Any other 404, such as a route that\n * does not exist, rejects.\n */\n find(\n id: string,\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<Snapshot<S> | undefined> {\n return this.findAt(id, options);\n }\n\n /** The commits from `from` to `to`, each with its events and the state after it. */\n trace(\n id: string,\n options: StateTraceOptions = {},\n ): Promise<StateTrace<S, E>> {\n return this.traceAt(id, options);\n }\n\n /**\n * {@link StateClient.read} of the aggregate `id`, or by no id of the\n * caller's own ({@link OwnStateClient}).\n */\n protected async readAt(\n id: string | undefined,\n options: StateReadOptions,\n ): Promise<StateReadResult<S>> {\n const at =\n options.at instanceof Date ? options.at.toISOString() : options.at;\n const response = await send(this.client, {\n method: 'GET',\n path: this.statePath(id),\n query: { version: options.version, at, minVersion: options.minVersion },\n headers: {\n [WowHeaders.IF_NONE_MATCH]:\n options.ifNoneMatch === undefined\n ? undefined\n : `\"${options.ifNoneMatch}\"`,\n },\n options,\n notModified: true,\n });\n if (response.status === 304) {\n const etag = entityTag(response) ?? options.ifNoneMatch ?? '';\n return {\n notModified: true,\n version: Number.parseInt(etag, 10),\n etag,\n };\n }\n return {\n notModified: false,\n snapshot: await json<Snapshot<S>>(response, this.stateNumbers),\n etag: entityTag(response),\n };\n }\n\n /** {@link StateClient.get} of the aggregate `id`, or of the caller's own. */\n protected async getAt(\n id: string | undefined,\n options: Omit<StateReadOptions, 'ifNoneMatch'>,\n ): Promise<Snapshot<S>> {\n const result = await this.readAt(id, options);\n if (result.notModified) {\n throw new Error('A read without If-None-Match was answered 304.');\n }\n return result.snapshot;\n }\n\n /** {@link StateClient.find} of the aggregate `id`, or of the caller's own. */\n protected async findAt(\n id: string | undefined,\n options: Omit<StateReadOptions, 'ifNoneMatch'>,\n ): Promise<Snapshot<S> | undefined> {\n try {\n return await this.getAt(id, options);\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.status === 404 &&\n error.code === FrameworkErrorCodes.AGGREGATE_NOT_FOUND\n ) {\n return undefined;\n }\n throw error;\n }\n }\n\n /** {@link StateClient.trace} of the aggregate `id`, or of the caller's own. */\n protected async traceAt(\n id: string | undefined,\n options: StateTraceOptions,\n ): Promise<StateTrace<S, E>> {\n return json<StateTrace<S, E>>(\n await send(this.client, {\n method: 'GET',\n path: `${this.statePath(id)}/trace`,\n query: { from: options.from, to: options.to, limit: options.limit },\n options,\n }),\n this.traceNumbers,\n );\n }\n\n /** The exact numbers of a state read: its state's. */\n private get stateNumbers(): TextNumbers | undefined {\n const state = this.type.textNumbers?.state;\n return state === undefined ? undefined : { state };\n }\n\n /** The exact numbers of a trace: each commit's state and events. */\n private get traceNumbers(): TextNumbers | undefined {\n const state = this.type.textNumbers?.state;\n const events = eventNumbers(this.type);\n if (state === undefined && events === undefined) return undefined;\n return {\n commits: {\n '*': {\n ...(state === undefined ? {} : { state }),\n ...(events === undefined ? {} : { events: { '*': events } }),\n },\n },\n };\n }\n\n private statePath(id: string | undefined): string {\n const base = `/${this.type.context}/${this.type.name}`;\n return id === undefined\n ? `${base}/state`\n : `${base}/${encodeURIComponent(id)}/state`;\n }\n}\n\n/**\n * Reads the states of an aggregate type whose id is its owner's\n * (`@AggregateRoot(idSource = OWNER)`, the Manifest's `idSource: \"owner\"`):\n * by id as {@link StateClient} does, for a caller with no owner, and the\n * caller's own by no id, `GET /{context}/{aggregate}/state` and\n * `…/state/trace`, its id the owner the caller reads as. An unauthenticated\n * caller is refused with 401 `wow.auth.unauthenticated`, one with no owner\n * with 400 `wow.query.malformed`.\n *\n * @typeParam S - The state's type.\n * @typeParam E - The events' type of a trace.\n */\nexport class OwnStateClient<\n S = unknown,\n E extends CommittedEvent = CommittedEvent,\n> extends StateClient<S, E> {\n /** {@link StateClient.read} of the caller's own aggregate. */\n readOwn(options: StateReadOptions = {}): Promise<StateReadResult<S>> {\n return this.readAt(undefined, options);\n }\n\n /** {@link StateClient.get} of the caller's own aggregate. */\n getOwn(\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<Snapshot<S>> {\n return this.getAt(undefined, options);\n }\n\n /**\n * {@link StateClient.find} of the caller's own aggregate: `undefined` until\n * the caller's first command creates it.\n */\n findOwn(\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<Snapshot<S> | undefined> {\n return this.findAt(undefined, options);\n }\n\n /** {@link StateClient.trace} of the caller's own aggregate. */\n traceOwn(options: StateTraceOptions = {}): Promise<StateTrace<S,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,CAAC,EAAgC,CACnE,OAAO,KAAK,OAAO,IAAA,GAAWI,CAAO,CACvC,CAGA,OACE,EAAiD,CAAC,EAC5B,CACtB,OAAO,KAAK,MAAM,IAAA,GAAWA,CAAO,CACtC,CAMA,QACE,EAAiD,CAAC,EAChB,CAClC,OAAO,KAAK,OAAO,IAAA,GAAWA,CAAO,CACvC,CAGA,SAAS,EAA6B,CAAC,EAA8B,CACnE,OAAO,KAAK,QAAQ,IAAA,GAAWA,CAAO,CACxC,CACF,E"}
package/dist/state.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { RequestOptions, WowClientOptions } from './http.cjs';
2
- import { AggregateType, EventView, StateTrace, StateView } from './wire.cjs';
2
+ import { AggregateType, CommittedEvent, StateTrace, Snapshot } from './wire.cjs';
3
3
  /** Which state a read asks for: the latest, at a version or as of a time. */
4
4
  export interface StateReadOptions extends RequestOptions {
5
5
  /** The committed state at this version. */
@@ -23,19 +23,19 @@ export interface StateReadOptions extends RequestOptions {
23
23
  readonly ifNoneMatch?: string;
24
24
  }
25
25
  /**
26
- * A state read: the view and its entity tag, or `notModified` when the state
27
- * held is current, with its tag and the version the tag names.
26
+ * A state read: the snapshot and its entity tag, or `notModified` when the
27
+ * state held is current, with its tag and the version the tag names.
28
28
  */
29
29
  export type StateReadResult<S> = {
30
30
  readonly notModified: false;
31
- readonly view: StateView<S>;
31
+ readonly snapshot: Snapshot<S>;
32
32
  readonly etag?: string;
33
33
  } | {
34
34
  readonly notModified: true;
35
35
  readonly version: number;
36
36
  readonly etag: string;
37
37
  };
38
- /** Which commits a trace reads (decision D40). */
38
+ /** Which commits a trace reads. */
39
39
  export interface StateTraceOptions extends RequestOptions {
40
40
  /** The first version; 1 when absent. */
41
41
  readonly from?: number;
@@ -45,15 +45,17 @@ export interface StateTraceOptions extends RequestOptions {
45
45
  readonly limit?: number;
46
46
  }
47
47
  /**
48
- * Reads an aggregate type's states (decisions D40, D112):
48
+ * Reads an aggregate type's states:
49
49
  * `GET /{context}/{aggregate}/{id}/state` with `?version=`, `?at=` or `?minVersion=`, and
50
- * its trace, `…/state/trace`. A state that does not exist rejects with 404
51
- * `wow.aggregate.not-found`.
50
+ * its trace, `…/state/trace`; {@link OwnStateClient} reads the caller's own
51
+ * of a type whose id is its owner's. A state that does not exist rejects with 404
52
+ * `wow.aggregate.not-found`, except through {@link StateClient.find}, which
53
+ * answers `undefined`.
52
54
  *
53
55
  * @typeParam S - The state's type.
54
56
  * @typeParam E - The events' type of a trace.
55
57
  */
56
- export declare class StateClient<S = unknown, E extends EventView = EventView> {
58
+ export declare class StateClient<S = unknown, E extends CommittedEvent = CommittedEvent> {
57
59
  readonly type: AggregateType;
58
60
  readonly client: WowClientOptions;
59
61
  /**
@@ -64,12 +66,55 @@ export declare class StateClient<S = unknown, E extends EventView = EventView> {
64
66
  /** The state the options ask for. */
65
67
  read(id: string, options?: StateReadOptions): Promise<StateReadResult<S>>;
66
68
  /** The latest state, or the one the options ask for, without a cache. */
67
- get(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<StateView<S>>;
69
+ get(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
70
+ /**
71
+ * The latest state, or the one the options ask for, or `undefined` when the
72
+ * aggregate does not exist (404 `wow.aggregate.not-found`), as Kotlin's
73
+ * `SnapshotQueries.state` answers null. Any other 404, such as a route that
74
+ * does not exist, rejects.
75
+ */
76
+ find(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
68
77
  /** The commits from `from` to `to`, each with its events and the state after it. */
69
78
  trace(id: string, options?: StateTraceOptions): Promise<StateTrace<S, E>>;
70
- /** The exact numbers of a state view: its state's. */
79
+ /**
80
+ * {@link StateClient.read} of the aggregate `id`, or by no id of the
81
+ * caller's own ({@link OwnStateClient}).
82
+ */
83
+ protected readAt(id: string | undefined, options: StateReadOptions): Promise<StateReadResult<S>>;
84
+ /** {@link StateClient.get} of the aggregate `id`, or of the caller's own. */
85
+ protected getAt(id: string | undefined, options: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
86
+ /** {@link StateClient.find} of the aggregate `id`, or of the caller's own. */
87
+ protected findAt(id: string | undefined, options: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
88
+ /** {@link StateClient.trace} of the aggregate `id`, or of the caller's own. */
89
+ protected traceAt(id: string | undefined, options: StateTraceOptions): Promise<StateTrace<S, E>>;
90
+ /** The exact numbers of a state read: its state's. */
71
91
  private get stateNumbers();
72
92
  /** The exact numbers of a trace: each commit's state and events. */
73
93
  private get traceNumbers();
74
94
  private statePath;
75
95
  }
96
+ /**
97
+ * Reads the states of an aggregate type whose id is its owner's
98
+ * (`@AggregateRoot(idSource = OWNER)`, the Manifest's `idSource: "owner"`):
99
+ * by id as {@link StateClient} does, for a caller with no owner, and the
100
+ * caller's own by no id, `GET /{context}/{aggregate}/state` and
101
+ * `…/state/trace`, its id the owner the caller reads as. An unauthenticated
102
+ * caller is refused with 401 `wow.auth.unauthenticated`, one with no owner
103
+ * with 400 `wow.query.malformed`.
104
+ *
105
+ * @typeParam S - The state's type.
106
+ * @typeParam E - The events' type of a trace.
107
+ */
108
+ export declare class OwnStateClient<S = unknown, E extends CommittedEvent = CommittedEvent> extends StateClient<S, E> {
109
+ /** {@link StateClient.read} of the caller's own aggregate. */
110
+ readOwn(options?: StateReadOptions): Promise<StateReadResult<S>>;
111
+ /** {@link StateClient.get} of the caller's own aggregate. */
112
+ getOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
113
+ /**
114
+ * {@link StateClient.find} of the caller's own aggregate: `undefined` until
115
+ * the caller's first command creates it.
116
+ */
117
+ findOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
118
+ /** {@link StateClient.trace} of the caller's own aggregate. */
119
+ traceOwn(options?: StateTraceOptions): Promise<StateTrace<S, E>>;
120
+ }
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { RequestOptions, WowClientOptions } from './http.js';
2
- import { AggregateType, EventView, StateTrace, StateView } from './wire.js';
2
+ import { AggregateType, CommittedEvent, StateTrace, Snapshot } from './wire.js';
3
3
  /** Which state a read asks for: the latest, at a version or as of a time. */
4
4
  export interface StateReadOptions extends RequestOptions {
5
5
  /** The committed state at this version. */
@@ -23,19 +23,19 @@ export interface StateReadOptions extends RequestOptions {
23
23
  readonly ifNoneMatch?: string;
24
24
  }
25
25
  /**
26
- * A state read: the view and its entity tag, or `notModified` when the state
27
- * held is current, with its tag and the version the tag names.
26
+ * A state read: the snapshot and its entity tag, or `notModified` when the
27
+ * state held is current, with its tag and the version the tag names.
28
28
  */
29
29
  export type StateReadResult<S> = {
30
30
  readonly notModified: false;
31
- readonly view: StateView<S>;
31
+ readonly snapshot: Snapshot<S>;
32
32
  readonly etag?: string;
33
33
  } | {
34
34
  readonly notModified: true;
35
35
  readonly version: number;
36
36
  readonly etag: string;
37
37
  };
38
- /** Which commits a trace reads (decision D40). */
38
+ /** Which commits a trace reads. */
39
39
  export interface StateTraceOptions extends RequestOptions {
40
40
  /** The first version; 1 when absent. */
41
41
  readonly from?: number;
@@ -45,15 +45,17 @@ export interface StateTraceOptions extends RequestOptions {
45
45
  readonly limit?: number;
46
46
  }
47
47
  /**
48
- * Reads an aggregate type's states (decisions D40, D112):
48
+ * Reads an aggregate type's states:
49
49
  * `GET /{context}/{aggregate}/{id}/state` with `?version=`, `?at=` or `?minVersion=`, and
50
- * its trace, `…/state/trace`. A state that does not exist rejects with 404
51
- * `wow.aggregate.not-found`.
50
+ * its trace, `…/state/trace`; {@link OwnStateClient} reads the caller's own
51
+ * of a type whose id is its owner's. A state that does not exist rejects with 404
52
+ * `wow.aggregate.not-found`, except through {@link StateClient.find}, which
53
+ * answers `undefined`.
52
54
  *
53
55
  * @typeParam S - The state's type.
54
56
  * @typeParam E - The events' type of a trace.
55
57
  */
56
- export declare class StateClient<S = unknown, E extends EventView = EventView> {
58
+ export declare class StateClient<S = unknown, E extends CommittedEvent = CommittedEvent> {
57
59
  readonly type: AggregateType;
58
60
  readonly client: WowClientOptions;
59
61
  /**
@@ -64,12 +66,55 @@ export declare class StateClient<S = unknown, E extends EventView = EventView> {
64
66
  /** The state the options ask for. */
65
67
  read(id: string, options?: StateReadOptions): Promise<StateReadResult<S>>;
66
68
  /** The latest state, or the one the options ask for, without a cache. */
67
- get(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<StateView<S>>;
69
+ get(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
70
+ /**
71
+ * The latest state, or the one the options ask for, or `undefined` when the
72
+ * aggregate does not exist (404 `wow.aggregate.not-found`), as Kotlin's
73
+ * `SnapshotQueries.state` answers null. Any other 404, such as a route that
74
+ * does not exist, rejects.
75
+ */
76
+ find(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
68
77
  /** The commits from `from` to `to`, each with its events and the state after it. */
69
78
  trace(id: string, options?: StateTraceOptions): Promise<StateTrace<S, E>>;
70
- /** The exact numbers of a state view: its state's. */
79
+ /**
80
+ * {@link StateClient.read} of the aggregate `id`, or by no id of the
81
+ * caller's own ({@link OwnStateClient}).
82
+ */
83
+ protected readAt(id: string | undefined, options: StateReadOptions): Promise<StateReadResult<S>>;
84
+ /** {@link StateClient.get} of the aggregate `id`, or of the caller's own. */
85
+ protected getAt(id: string | undefined, options: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
86
+ /** {@link StateClient.find} of the aggregate `id`, or of the caller's own. */
87
+ protected findAt(id: string | undefined, options: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
88
+ /** {@link StateClient.trace} of the aggregate `id`, or of the caller's own. */
89
+ protected traceAt(id: string | undefined, options: StateTraceOptions): Promise<StateTrace<S, E>>;
90
+ /** The exact numbers of a state read: its state's. */
71
91
  private get stateNumbers();
72
92
  /** The exact numbers of a trace: each commit's state and events. */
73
93
  private get traceNumbers();
74
94
  private statePath;
75
95
  }
96
+ /**
97
+ * Reads the states of an aggregate type whose id is its owner's
98
+ * (`@AggregateRoot(idSource = OWNER)`, the Manifest's `idSource: "owner"`):
99
+ * by id as {@link StateClient} does, for a caller with no owner, and the
100
+ * caller's own by no id, `GET /{context}/{aggregate}/state` and
101
+ * `…/state/trace`, its id the owner the caller reads as. An unauthenticated
102
+ * caller is refused with 401 `wow.auth.unauthenticated`, one with no owner
103
+ * with 400 `wow.query.malformed`.
104
+ *
105
+ * @typeParam S - The state's type.
106
+ * @typeParam E - The events' type of a trace.
107
+ */
108
+ export declare class OwnStateClient<S = unknown, E extends CommittedEvent = CommittedEvent> extends StateClient<S, E> {
109
+ /** {@link StateClient.read} of the caller's own aggregate. */
110
+ readOwn(options?: StateReadOptions): Promise<StateReadResult<S>>;
111
+ /** {@link StateClient.get} of the caller's own aggregate. */
112
+ getOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
113
+ /**
114
+ * {@link StateClient.find} of the caller's own aggregate: `undefined` until
115
+ * the caller's first command creates it.
116
+ */
117
+ findOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
118
+ /** {@link StateClient.trace} of the caller's own aggregate. */
119
+ traceOwn(options?: StateTraceOptions): Promise<StateTrace<S, E>>;
120
+ }