@ahoo-wang/wow-client 10.0.0-beta.1 → 10.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/README.md +4 -2
  2. package/README.zh-CN.md +1 -1
  3. package/dist/commands.cjs +1 -1
  4. package/dist/commands.cjs.map +1 -1
  5. package/dist/commands.d.cts +1 -8
  6. package/dist/commands.d.ts +1 -8
  7. package/dist/commands.es.js +45 -51
  8. package/dist/commands.es.js.map +1 -1
  9. package/dist/dsl/aggregation/admit.cjs +1 -1
  10. package/dist/dsl/aggregation/admit.cjs.map +1 -1
  11. package/dist/dsl/aggregation/admit.es.js +73 -69
  12. package/dist/dsl/aggregation/admit.es.js.map +1 -1
  13. package/dist/dsl/aggregation/aliases.cjs +2 -0
  14. package/dist/dsl/aggregation/aliases.cjs.map +1 -0
  15. package/dist/dsl/aggregation/aliases.d.cts +2 -0
  16. package/dist/dsl/aggregation/aliases.d.ts +2 -0
  17. package/dist/dsl/aggregation/aliases.es.js +13 -0
  18. package/dist/dsl/aggregation/aliases.es.js.map +1 -0
  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 +17 -243
  22. package/dist/dsl/aggregation/builders.d.ts +17 -243
  23. package/dist/dsl/aggregation/builders.es.js +36 -171
  24. package/dist/dsl/aggregation/builders.es.js.map +1 -1
  25. package/dist/dsl/aggregation/derived.cjs +1 -1
  26. package/dist/dsl/aggregation/derived.cjs.map +1 -1
  27. package/dist/dsl/aggregation/derived.d.cts +123 -1
  28. package/dist/dsl/aggregation/derived.d.ts +123 -1
  29. package/dist/dsl/aggregation/derived.es.js +43 -28
  30. package/dist/dsl/aggregation/derived.es.js.map +1 -1
  31. package/dist/dsl/aggregation/groups.cjs +2 -0
  32. package/dist/dsl/aggregation/groups.cjs.map +1 -0
  33. package/dist/dsl/aggregation/groups.d.cts +325 -0
  34. package/dist/dsl/aggregation/groups.d.ts +325 -0
  35. package/dist/dsl/aggregation/groups.es.js +80 -0
  36. package/dist/dsl/aggregation/groups.es.js.map +1 -0
  37. package/dist/dsl/aggregation/having.cjs +1 -1
  38. package/dist/dsl/aggregation/having.cjs.map +1 -1
  39. package/dist/dsl/aggregation/having.d.cts +63 -1
  40. package/dist/dsl/aggregation/having.d.ts +63 -1
  41. package/dist/dsl/aggregation/having.es.js +33 -30
  42. package/dist/dsl/aggregation/having.es.js.map +1 -1
  43. package/dist/dsl/aggregation/index.d.cts +4 -2
  44. package/dist/dsl/aggregation/index.d.ts +4 -2
  45. package/dist/dsl/aggregation/metrics.cjs +2 -0
  46. package/dist/dsl/aggregation/metrics.cjs.map +1 -0
  47. package/dist/dsl/aggregation/metrics.d.cts +279 -0
  48. package/dist/dsl/aggregation/metrics.d.ts +279 -0
  49. package/dist/dsl/aggregation/metrics.es.js +75 -0
  50. package/dist/dsl/aggregation/metrics.es.js.map +1 -0
  51. package/dist/dsl/aggregation/types.cjs +1 -1
  52. package/dist/dsl/aggregation/types.cjs.map +1 -1
  53. package/dist/dsl/aggregation/types.d.cts +4 -524
  54. package/dist/dsl/aggregation/types.d.ts +4 -524
  55. package/dist/dsl/aggregation/types.es.js +5 -25
  56. package/dist/dsl/aggregation/types.es.js.map +1 -1
  57. package/dist/dsl/cursorQuery.cjs +1 -1
  58. package/dist/dsl/cursorQuery.cjs.map +1 -1
  59. package/dist/dsl/cursorQuery.d.cts +18 -7
  60. package/dist/dsl/cursorQuery.d.ts +18 -7
  61. package/dist/dsl/cursorQuery.es.js +13 -12
  62. package/dist/dsl/cursorQuery.es.js.map +1 -1
  63. package/dist/dsl/descriptor.cjs +1 -1
  64. package/dist/dsl/descriptor.cjs.map +1 -1
  65. package/dist/dsl/descriptor.d.cts +17 -379
  66. package/dist/dsl/descriptor.d.ts +17 -379
  67. package/dist/dsl/descriptor.es.js +4 -31
  68. package/dist/dsl/descriptor.es.js.map +1 -1
  69. package/dist/dsl/fieldDescriptor.cjs +2 -0
  70. package/dist/dsl/fieldDescriptor.cjs.map +1 -0
  71. package/dist/dsl/fieldDescriptor.d.cts +246 -0
  72. package/dist/dsl/fieldDescriptor.d.ts +246 -0
  73. package/dist/dsl/fieldDescriptor.es.js +24 -0
  74. package/dist/dsl/fieldDescriptor.es.js.map +1 -0
  75. package/dist/dsl/filter/builders.cjs +1 -1
  76. package/dist/dsl/filter/builders.cjs.map +1 -1
  77. package/dist/dsl/filter/builders.d.cts +7 -949
  78. package/dist/dsl/filter/builders.d.ts +7 -949
  79. package/dist/dsl/filter/builders.es.js +14 -285
  80. package/dist/dsl/filter/builders.es.js.map +1 -1
  81. package/dist/dsl/filter/expressionFilter.cjs +2 -0
  82. package/dist/dsl/filter/expressionFilter.cjs.map +1 -0
  83. package/dist/dsl/filter/expressionFilter.d.cts +35 -0
  84. package/dist/dsl/filter/expressionFilter.d.ts +35 -0
  85. package/dist/dsl/filter/expressionFilter.es.js +18 -0
  86. package/dist/dsl/filter/expressionFilter.es.js.map +1 -0
  87. package/dist/dsl/filter/fieldFilters.cjs +2 -0
  88. package/dist/dsl/filter/fieldFilters.cjs.map +1 -0
  89. package/dist/dsl/filter/fieldFilters.d.cts +297 -0
  90. package/dist/dsl/filter/fieldFilters.d.ts +297 -0
  91. package/dist/dsl/filter/fieldFilters.es.js +110 -0
  92. package/dist/dsl/filter/fieldFilters.es.js.map +1 -0
  93. package/dist/dsl/filter/index.d.cts +2 -1
  94. package/dist/dsl/filter/index.d.ts +2 -1
  95. package/dist/dsl/filter/logicalFilters.cjs +2 -0
  96. package/dist/dsl/filter/logicalFilters.cjs.map +1 -0
  97. package/dist/dsl/filter/logicalFilters.d.cts +109 -0
  98. package/dist/dsl/filter/logicalFilters.d.ts +109 -0
  99. package/dist/dsl/filter/logicalFilters.es.js +36 -0
  100. package/dist/dsl/filter/logicalFilters.es.js.map +1 -0
  101. package/dist/dsl/filter/metadataFilters.cjs +2 -0
  102. package/dist/dsl/filter/metadataFilters.cjs.map +1 -0
  103. package/dist/dsl/filter/metadataFilters.d.cts +132 -0
  104. package/dist/dsl/filter/metadataFilters.d.ts +132 -0
  105. package/dist/dsl/filter/metadataFilters.es.js +56 -0
  106. package/dist/dsl/filter/metadataFilters.es.js.map +1 -0
  107. package/dist/dsl/filter/operator.cjs +1 -1
  108. package/dist/dsl/filter/operator.cjs.map +1 -1
  109. package/dist/dsl/filter/operator.d.cts +11 -9
  110. package/dist/dsl/filter/operator.d.ts +11 -9
  111. package/dist/dsl/filter/operator.es.js +1 -1
  112. package/dist/dsl/filter/operator.es.js.map +1 -1
  113. package/dist/dsl/filter/searchFilter.cjs +2 -0
  114. package/dist/dsl/filter/searchFilter.cjs.map +1 -0
  115. package/dist/dsl/filter/searchFilter.d.cts +39 -0
  116. package/dist/dsl/filter/searchFilter.d.ts +39 -0
  117. package/dist/dsl/filter/searchFilter.es.js +19 -0
  118. package/dist/dsl/filter/searchFilter.es.js.map +1 -0
  119. package/dist/dsl/filter/timeFilters.cjs +2 -0
  120. package/dist/dsl/filter/timeFilters.cjs.map +1 -0
  121. package/dist/dsl/filter/timeFilters.d.cts +290 -0
  122. package/dist/dsl/filter/timeFilters.d.ts +290 -0
  123. package/dist/dsl/filter/timeFilters.es.js +89 -0
  124. package/dist/dsl/filter/timeFilters.es.js.map +1 -0
  125. package/dist/dsl/filter/types.d.cts +4 -14
  126. package/dist/dsl/filter/types.d.ts +4 -14
  127. package/dist/dsl/filter/validate.cjs +1 -1
  128. package/dist/dsl/filter/validate.cjs.map +1 -1
  129. package/dist/dsl/filter/validate.d.cts +2 -4
  130. package/dist/dsl/filter/validate.d.ts +2 -4
  131. package/dist/dsl/filter/validate.es.js +25 -31
  132. package/dist/dsl/filter/validate.es.js.map +1 -1
  133. package/dist/dsl/queryErrorCodes.cjs +1 -1
  134. package/dist/dsl/queryErrorCodes.cjs.map +1 -1
  135. package/dist/dsl/queryErrorCodes.d.cts +0 -2
  136. package/dist/dsl/queryErrorCodes.d.ts +0 -2
  137. package/dist/dsl/queryErrorCodes.es.js +0 -1
  138. package/dist/dsl/queryErrorCodes.es.js.map +1 -1
  139. package/dist/dsl/queryFilter.cjs +2 -0
  140. package/dist/dsl/queryFilter.cjs.map +1 -0
  141. package/dist/dsl/queryFilter.d.cts +3 -0
  142. package/dist/dsl/queryFilter.d.ts +3 -0
  143. package/dist/dsl/queryFilter.es.js +9 -0
  144. package/dist/dsl/queryFilter.es.js.map +1 -0
  145. package/dist/dsl/queryable.cjs +1 -1
  146. package/dist/dsl/queryable.cjs.map +1 -1
  147. package/dist/dsl/queryable.es.js +12 -16
  148. package/dist/dsl/queryable.es.js.map +1 -1
  149. package/dist/dsl/semanticTypes.cjs +2 -0
  150. package/dist/dsl/semanticTypes.cjs.map +1 -0
  151. package/dist/dsl/semanticTypes.d.cts +128 -0
  152. package/dist/dsl/semanticTypes.d.ts +128 -0
  153. package/dist/dsl/semanticTypes.es.js +13 -0
  154. package/dist/dsl/semanticTypes.es.js.map +1 -0
  155. package/dist/dsl.cjs +1 -1
  156. package/dist/dsl.d.cts +2 -0
  157. package/dist/dsl.d.ts +2 -0
  158. package/dist/dsl.es.js +14 -8
  159. package/dist/exactJson.cjs +2 -2
  160. package/dist/exactJson.cjs.map +1 -1
  161. package/dist/exactJson.d.cts +41 -16
  162. package/dist/exactJson.d.ts +41 -16
  163. package/dist/exactJson.es.js +104 -102
  164. package/dist/exactJson.es.js.map +1 -1
  165. package/dist/frameworkErrors.cjs.map +1 -1
  166. package/dist/frameworkErrors.d.cts +4 -4
  167. package/dist/frameworkErrors.d.ts +4 -4
  168. package/dist/frameworkErrors.es.js.map +1 -1
  169. package/dist/http.cjs +1 -1
  170. package/dist/http.cjs.map +1 -1
  171. package/dist/http.d.cts +29 -9
  172. package/dist/http.d.ts +29 -9
  173. package/dist/http.es.js +24 -19
  174. package/dist/http.es.js.map +1 -1
  175. package/dist/index.cjs +1 -1
  176. package/dist/index.d.cts +3 -3
  177. package/dist/index.d.ts +3 -3
  178. package/dist/index.es.js +12 -12
  179. package/dist/manifest.cjs +1 -1
  180. package/dist/manifest.cjs.map +1 -1
  181. package/dist/manifest.d.cts +24 -0
  182. package/dist/manifest.d.ts +24 -0
  183. package/dist/manifest.es.js +34 -6
  184. package/dist/manifest.es.js.map +1 -1
  185. package/dist/manifestTypes.d.cts +16 -1
  186. package/dist/manifestTypes.d.ts +16 -1
  187. package/dist/queries.cjs +1 -1
  188. package/dist/queries.cjs.map +1 -1
  189. package/dist/queries.d.cts +18 -8
  190. package/dist/queries.d.ts +18 -8
  191. package/dist/queries.es.js +46 -35
  192. package/dist/queries.es.js.map +1 -1
  193. package/dist/routes.cjs +1 -1
  194. package/dist/routes.cjs.map +1 -1
  195. package/dist/routes.d.cts +16 -3
  196. package/dist/routes.d.ts +16 -3
  197. package/dist/routes.es.js +24 -25
  198. package/dist/routes.es.js.map +1 -1
  199. package/dist/state.cjs +1 -1
  200. package/dist/state.cjs.map +1 -1
  201. package/dist/state.d.cts +21 -19
  202. package/dist/state.d.ts +21 -19
  203. package/dist/state.es.js +27 -22
  204. package/dist/state.es.js.map +1 -1
  205. package/dist/streams.cjs +1 -1
  206. package/dist/streams.cjs.map +1 -1
  207. package/dist/streams.d.cts +14 -7
  208. package/dist/streams.d.ts +14 -7
  209. package/dist/streams.es.js +65 -50
  210. package/dist/streams.es.js.map +1 -1
  211. package/dist/testing/wire.cjs +1 -1
  212. package/dist/testing/wire.cjs.map +1 -1
  213. package/dist/testing/wire.es.js +1 -1
  214. package/dist/testing/wire.es.js.map +1 -1
  215. package/dist/wait.cjs +1 -1
  216. package/dist/wait.cjs.map +1 -1
  217. package/dist/wait.d.cts +17 -4
  218. package/dist/wait.d.ts +17 -4
  219. package/dist/wait.es.js +36 -34
  220. package/dist/wait.es.js.map +1 -1
  221. package/dist/wire.cjs +1 -1
  222. package/dist/wire.cjs.map +1 -1
  223. package/dist/wire.d.cts +75 -31
  224. package/dist/wire.d.ts +75 -31
  225. package/dist/wire.es.js +1 -3
  226. package/dist/wire.es.js.map +1 -1
  227. package/package.json +5 -5
  228. package/dist/dsl/filter/datePattern.cjs +0 -2
  229. package/dist/dsl/filter/datePattern.cjs.map +0 -1
  230. package/dist/dsl/filter/datePattern.d.cts +0 -8
  231. package/dist/dsl/filter/datePattern.d.ts +0 -8
  232. package/dist/dsl/filter/datePattern.es.js +0 -96
  233. package/dist/dsl/filter/datePattern.es.js.map +0 -1
@@ -1 +1 @@
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, E>> {\n return this.traceAt(undefined, options);\n }\n}\n"],"mappings":"A,yHA0FA,IAAaW,EAAb,KAGE,CAKA,YACE,EACA,EAAoC,CAAC,EACrC,CAFS,KAAA,KAAAC,EACA,KAAA,OAAAC,CACR,CAGH,KACE,EACA,EAA4B,CAAC,EACA,CAC7B,OAAO,KAAK,OAAOC,EAAIC,CAAO,CAChC,CAGA,IACE,EACA,EAAiD,CAAC,EAC5B,CACtB,OAAO,KAAK,MAAMD,EAAIC,CAAO,CAC/B,CAQA,KACE,EACA,EAAiD,CAAC,EAChB,CAClC,OAAO,KAAK,OAAOD,EAAIC,CAAO,CAChC,CAGA,MACE,EACA,EAA6B,CAAC,EACH,CAC3B,OAAO,KAAK,QAAQD,EAAIC,CAAO,CACjC,CAMA,MAAgB,OACd,EACA,EAC6B,CAC7B,IAAMC,EACJD,EAAQ,cAAc,KAAOA,EAAQ,GAAG,YAAY,EAAIA,EAAQ,GAC5DE,EAAW,MAAMjB,EAAAA,KAAK,KAAK,OAAQ,CACvC,OAAQ,MACR,KAAM,KAAK,UAAUc,CAAE,EACvB,MAAO,CAAE,QAASC,EAAQ,QAAS,KAAI,WAAYA,EAAQ,UAAW,EACtE,QAAS,EACNd,EAAAA,WAAW,eACVc,EAAQ,cAAgB,IAAA,GACpB,IAAA,GACA,IAAIA,EAAQ,YAAY,EAChC,EACA,UACA,YAAa,EACf,CAAC,EACD,GAAIE,EAAS,SAAW,IAAK,CAC3B,IAAMC,EAAOhB,EAAAA,UAAUe,CAAQ,GAAKF,EAAQ,aAAe,GA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AE,IAAKA,CAAO,CAAE,CAC5D,CACF,CACF,CACF,CAEA,UAAkB,EAAgC,CAChD,IAAMC,EAAO,IAAI,KAAK,KAAK,QAAQ,GAAG,KAAK,KAAK,OAChD,OAAOT,IAAO,IAAA,GACV,GAAGS,EAAK,QACR,GAAGA,EAAK,GAAG,mBAAmBT,CAAE,EAAE,OACxC,CACF,EAcaU,EAAb,cAGUb,CAAkB,CAE1B,QAAQ,EAA4B,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"}
1
+ {"version":3,"file":"state.cjs","names":["send","WowHeaders","entityTag","WowProblemError","FrameworkErrorCodes","recordNumbers","eventNumbers","require_exactJson","require_frameworkErrors","require_problem","require_http","StateClient","type","client","id","options","at","answer","response","etag","result","error","events","commit","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 type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport { eventNumbers, recordNumbers, type TextNumbers } from './exactJson.js';\nimport { FrameworkErrorCodes, WowProblemError } from './problem.js';\nimport type {\n AccessValues,\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, A = AccessValues> =\n | {\n readonly notModified: false;\n readonly snapshot: Snapshot<S, A>;\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 * @typeParam A - The aggregate's access attributes.\n */\nexport class StateClient<\n S = unknown,\n E extends CommittedEvent = CommittedEvent,\n A = AccessValues,\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, A>> {\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, A>> {\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, A> | 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, A>> {\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, A>> {\n const at =\n options.at instanceof Date ? options.at.toISOString() : options.at;\n const answer = 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 numbers: { answer: this.stateNumbers },\n options,\n notModified: true,\n });\n const response = answer.response;\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 answer.json<Snapshot<S, A>>(),\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, A>> {\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, A> | 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, A>> {\n const answer = 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 numbers: { answer: this.traceNumbers },\n options,\n });\n return answer.json<StateTrace<S, E, A>>();\n }\n\n /** The exact numbers of a state read: its state's and its access attributes'. */\n private get stateNumbers(): TextNumbers | undefined {\n return recordNumbers({\n state: this.type.textNumbers?.state,\n access: this.type.textNumbers?.access,\n });\n }\n\n /** The exact numbers of a trace: each commit's state, events and access attributes. */\n private get traceNumbers(): TextNumbers | undefined {\n const events = eventNumbers(this.type);\n const commit = recordNumbers({\n state: this.type.textNumbers?.state,\n events: events === undefined ? undefined : { '*': events },\n access: this.type.textNumbers?.access,\n });\n return commit === undefined ? undefined : { commits: { '*': commit } };\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 * @typeParam A - The aggregate's access attributes.\n */\nexport class OwnStateClient<\n S = unknown,\n E extends CommittedEvent = CommittedEvent,\n A = AccessValues,\n> extends StateClient<S, E, A> {\n /** {@link StateClient.read} of the caller's own aggregate. */\n readOwn(options: StateReadOptions = {}): Promise<StateReadResult<S, A>> {\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, A>> {\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, A> | 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, E, A>> {\n return this.traceAt(undefined, options);\n }\n}\n"],"mappings":"A,yHA2FA,IAAaW,EAAb,KAIE,CAKA,YACE,EACA,EAAoC,CAAC,EACrC,CAFS,KAAA,KAAAC,EACA,KAAA,OAAAC,CACR,CAGH,KACE,EACA,EAA4B,CAAC,EACG,CAChC,OAAO,KAAK,OAAOC,EAAIC,CAAO,CAChC,CAGA,IACE,EACA,EAAiD,CAAC,EACzB,CACzB,OAAO,KAAK,MAAMD,EAAIC,CAAO,CAC/B,CAQA,KACE,EACA,EAAiD,CAAC,EACb,CACrC,OAAO,KAAK,OAAOD,EAAIC,CAAO,CAChC,CAGA,MACE,EACA,EAA6B,CAAC,EACA,CAC9B,OAAO,KAAK,QAAQD,E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s';
2
- import { AggregateType, CommittedEvent, StateTrace, Snapshot } from './wire.cjs';
2
+ import { AccessValues, 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. */
@@ -26,9 +26,9 @@ export interface StateReadOptions extends RequestOptions {
26
26
  * A state read: the snapshot and its entity tag, or `notModified` when the
27
27
  * state held is current, with its tag and the version the tag names.
28
28
  */
29
- export type StateReadResult<S> = {
29
+ export type StateReadResult<S, A = AccessValues> = {
30
30
  readonly notModified: false;
31
- readonly snapshot: Snapshot<S>;
31
+ readonly snapshot: Snapshot<S, A>;
32
32
  readonly etag?: string;
33
33
  } | {
34
34
  readonly notModified: true;
@@ -54,8 +54,9 @@ export interface StateTraceOptions extends RequestOptions {
54
54
  *
55
55
  * @typeParam S - The state's type.
56
56
  * @typeParam E - The events' type of a trace.
57
+ * @typeParam A - The aggregate's access attributes.
57
58
  */
58
- export declare class StateClient<S = unknown, E extends CommittedEvent = CommittedEvent> {
59
+ export declare class StateClient<S = unknown, E extends CommittedEvent = CommittedEvent, A = AccessValues> {
59
60
  readonly type: AggregateType;
60
61
  readonly client: WowClientOptions;
61
62
  /**
@@ -64,32 +65,32 @@ export declare class StateClient<S = unknown, E extends CommittedEvent = Committ
64
65
  */
65
66
  constructor(type: AggregateType, client?: WowClientOptions);
66
67
  /** The state the options ask for. */
67
- read(id: string, options?: StateReadOptions): Promise<StateReadResult<S>>;
68
+ read(id: string, options?: StateReadOptions): Promise<StateReadResult<S, A>>;
68
69
  /** The latest state, or the one the options ask for, without a cache. */
69
- get(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
70
+ get(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A>>;
70
71
  /**
71
72
  * The latest state, or the one the options ask for, or `undefined` when the
72
73
  * aggregate does not exist (404 `wow.aggregate.not-found`), as Kotlin's
73
74
  * `SnapshotQueries.state` answers null. Any other 404, such as a route that
74
75
  * does not exist, rejects.
75
76
  */
76
- find(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
77
+ find(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A> | undefined>;
77
78
  /** The commits from `from` to `to`, each with its events and the state after it. */
78
- trace(id: string, options?: StateTraceOptions): Promise<StateTrace<S, E>>;
79
+ trace(id: string, options?: StateTraceOptions): Promise<StateTrace<S, E, A>>;
79
80
  /**
80
81
  * {@link StateClient.read} of the aggregate `id`, or by no id of the
81
82
  * caller's own ({@link OwnStateClient}).
82
83
  */
83
- protected readAt(id: string | undefined, options: StateReadOptions): Promise<StateReadResult<S>>;
84
+ protected readAt(id: string | undefined, options: StateReadOptions): Promise<StateReadResult<S, A>>;
84
85
  /** {@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
+ protected getAt(id: string | undefined, options: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A>>;
86
87
  /** {@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
+ protected findAt(id: string | undefined, options: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A> | undefined>;
88
89
  /** {@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. */
90
+ protected traceAt(id: string | undefined, options: StateTraceOptions): Promise<StateTrace<S, E, A>>;
91
+ /** The exact numbers of a state read: its state's and its access attributes'. */
91
92
  private get stateNumbers();
92
- /** The exact numbers of a trace: each commit's state and events. */
93
+ /** The exact numbers of a trace: each commit's state, events and access attributes. */
93
94
  private get traceNumbers();
94
95
  private statePath;
95
96
  }
@@ -104,17 +105,18 @@ export declare class StateClient<S = unknown, E extends CommittedEvent = Committ
104
105
  *
105
106
  * @typeParam S - The state's type.
106
107
  * @typeParam E - The events' type of a trace.
108
+ * @typeParam A - The aggregate's access attributes.
107
109
  */
108
- export declare class OwnStateClient<S = unknown, E extends CommittedEvent = CommittedEvent> extends StateClient<S, E> {
110
+ export declare class OwnStateClient<S = unknown, E extends CommittedEvent = CommittedEvent, A = AccessValues> extends StateClient<S, E, A> {
109
111
  /** {@link StateClient.read} of the caller's own aggregate. */
110
- readOwn(options?: StateReadOptions): Promise<StateReadResult<S>>;
112
+ readOwn(options?: StateReadOptions): Promise<StateReadResult<S, A>>;
111
113
  /** {@link StateClient.get} of the caller's own aggregate. */
112
- getOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
114
+ getOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A>>;
113
115
  /**
114
116
  * {@link StateClient.find} of the caller's own aggregate: `undefined` until
115
117
  * the caller's first command creates it.
116
118
  */
117
- findOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
119
+ findOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A> | undefined>;
118
120
  /** {@link StateClient.trace} of the caller's own aggregate. */
119
- traceOwn(options?: StateTraceOptions): Promise<StateTrace<S, E>>;
121
+ traceOwn(options?: StateTraceOptions): Promise<StateTrace<S, E, A>>;
120
122
  }
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { RequestOptions, WowClientOptions } from './http.js';
2
- import { AggregateType, CommittedEvent, StateTrace, Snapshot } from './wire.js';
2
+ import { AccessValues, 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. */
@@ -26,9 +26,9 @@ export interface StateReadOptions extends RequestOptions {
26
26
  * A state read: the snapshot and its entity tag, or `notModified` when the
27
27
  * state held is current, with its tag and the version the tag names.
28
28
  */
29
- export type StateReadResult<S> = {
29
+ export type StateReadResult<S, A = AccessValues> = {
30
30
  readonly notModified: false;
31
- readonly snapshot: Snapshot<S>;
31
+ readonly snapshot: Snapshot<S, A>;
32
32
  readonly etag?: string;
33
33
  } | {
34
34
  readonly notModified: true;
@@ -54,8 +54,9 @@ export interface StateTraceOptions extends RequestOptions {
54
54
  *
55
55
  * @typeParam S - The state's type.
56
56
  * @typeParam E - The events' type of a trace.
57
+ * @typeParam A - The aggregate's access attributes.
57
58
  */
58
- export declare class StateClient<S = unknown, E extends CommittedEvent = CommittedEvent> {
59
+ export declare class StateClient<S = unknown, E extends CommittedEvent = CommittedEvent, A = AccessValues> {
59
60
  readonly type: AggregateType;
60
61
  readonly client: WowClientOptions;
61
62
  /**
@@ -64,32 +65,32 @@ export declare class StateClient<S = unknown, E extends CommittedEvent = Committ
64
65
  */
65
66
  constructor(type: AggregateType, client?: WowClientOptions);
66
67
  /** The state the options ask for. */
67
- read(id: string, options?: StateReadOptions): Promise<StateReadResult<S>>;
68
+ read(id: string, options?: StateReadOptions): Promise<StateReadResult<S, A>>;
68
69
  /** The latest state, or the one the options ask for, without a cache. */
69
- get(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
70
+ get(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A>>;
70
71
  /**
71
72
  * The latest state, or the one the options ask for, or `undefined` when the
72
73
  * aggregate does not exist (404 `wow.aggregate.not-found`), as Kotlin's
73
74
  * `SnapshotQueries.state` answers null. Any other 404, such as a route that
74
75
  * does not exist, rejects.
75
76
  */
76
- find(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
77
+ find(id: string, options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A> | undefined>;
77
78
  /** The commits from `from` to `to`, each with its events and the state after it. */
78
- trace(id: string, options?: StateTraceOptions): Promise<StateTrace<S, E>>;
79
+ trace(id: string, options?: StateTraceOptions): Promise<StateTrace<S, E, A>>;
79
80
  /**
80
81
  * {@link StateClient.read} of the aggregate `id`, or by no id of the
81
82
  * caller's own ({@link OwnStateClient}).
82
83
  */
83
- protected readAt(id: string | undefined, options: StateReadOptions): Promise<StateReadResult<S>>;
84
+ protected readAt(id: string | undefined, options: StateReadOptions): Promise<StateReadResult<S, A>>;
84
85
  /** {@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
+ protected getAt(id: string | undefined, options: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A>>;
86
87
  /** {@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
+ protected findAt(id: string | undefined, options: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A> | undefined>;
88
89
  /** {@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. */
90
+ protected traceAt(id: string | undefined, options: StateTraceOptions): Promise<StateTrace<S, E, A>>;
91
+ /** The exact numbers of a state read: its state's and its access attributes'. */
91
92
  private get stateNumbers();
92
- /** The exact numbers of a trace: each commit's state and events. */
93
+ /** The exact numbers of a trace: each commit's state, events and access attributes. */
93
94
  private get traceNumbers();
94
95
  private statePath;
95
96
  }
@@ -104,17 +105,18 @@ export declare class StateClient<S = unknown, E extends CommittedEvent = Committ
104
105
  *
105
106
  * @typeParam S - The state's type.
106
107
  * @typeParam E - The events' type of a trace.
108
+ * @typeParam A - The aggregate's access attributes.
107
109
  */
108
- export declare class OwnStateClient<S = unknown, E extends CommittedEvent = CommittedEvent> extends StateClient<S, E> {
110
+ export declare class OwnStateClient<S = unknown, E extends CommittedEvent = CommittedEvent, A = AccessValues> extends StateClient<S, E, A> {
109
111
  /** {@link StateClient.read} of the caller's own aggregate. */
110
- readOwn(options?: StateReadOptions): Promise<StateReadResult<S>>;
112
+ readOwn(options?: StateReadOptions): Promise<StateReadResult<S, A>>;
111
113
  /** {@link StateClient.get} of the caller's own aggregate. */
112
- getOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S>>;
114
+ getOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A>>;
113
115
  /**
114
116
  * {@link StateClient.find} of the caller's own aggregate: `undefined` until
115
117
  * the caller's first command creates it.
116
118
  */
117
- findOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S> | undefined>;
119
+ findOwn(options?: Omit<StateReadOptions, 'ifNoneMatch'>): Promise<Snapshot<S, A> | undefined>;
118
120
  /** {@link StateClient.trace} of the caller's own aggregate. */
119
- traceOwn(options?: StateTraceOptions): Promise<StateTrace<S, E>>;
121
+ traceOwn(options?: StateTraceOptions): Promise<StateTrace<S, E, A>>;
120
122
  }
package/dist/state.es.js CHANGED
@@ -1,7 +1,7 @@
1
- import { eventNumbers as e } from "./exactJson.es.js";
2
- import { FrameworkErrorCodes as t } from "./frameworkErrors.es.js";
3
- import { WowProblemError as n } from "./problem.es.js";
4
- import { WowHeaders as r, entityTag as i, json as a, send as o } from "./http.es.js";
1
+ import { eventNumbers as e, recordNumbers as t } from "./exactJson.es.js";
2
+ import { FrameworkErrorCodes as n } from "./frameworkErrors.es.js";
3
+ import { WowProblemError as r } from "./problem.es.js";
4
+ import { WowHeaders as i, entityTag as a, send as o } from "./http.es.js";
5
5
  // src/state.ts
6
6
  var s = class {
7
7
  constructor(e, t = {}) {
@@ -20,7 +20,7 @@ var s = class {
20
20
  return this.traceAt(e, t);
21
21
  }
22
22
  async readAt(e, t) {
23
- let n = t.at instanceof Date ? t.at.toISOString() : t.at, s = await o(this.client, {
23
+ let n = t.at instanceof Date ? t.at.toISOString() : t.at, r = await o(this.client, {
24
24
  method: "GET",
25
25
  path: this.statePath(e),
26
26
  query: {
@@ -28,12 +28,13 @@ var s = class {
28
28
  at: n,
29
29
  minVersion: t.minVersion
30
30
  },
31
- headers: { [r.IF_NONE_MATCH]: t.ifNoneMatch === void 0 ? void 0 : `"${t.ifNoneMatch}"` },
31
+ headers: { [i.IF_NONE_MATCH]: t.ifNoneMatch === void 0 ? void 0 : `"${t.ifNoneMatch}"` },
32
+ numbers: { answer: this.stateNumbers },
32
33
  options: t,
33
34
  notModified: !0
34
- });
35
+ }), s = r.response;
35
36
  if (s.status === 304) {
36
- let e = i(s) ?? t.ifNoneMatch ?? "";
37
+ let e = a(s) ?? t.ifNoneMatch ?? "";
37
38
  return {
38
39
  notModified: !0,
39
40
  version: Number.parseInt(e, 10),
@@ -42,8 +43,8 @@ var s = class {
42
43
  }
43
44
  return {
44
45
  notModified: !1,
45
- snapshot: await a(s, this.stateNumbers),
46
- etag: i(s)
46
+ snapshot: await r.json(),
47
+ etag: a(s)
47
48
  };
48
49
  }
49
50
  async getAt(e, t) {
@@ -51,16 +52,16 @@ var s = class {
51
52
  if (n.notModified) throw Error("A read without If-None-Match was answered 304.");
52
53
  return n.snapshot;
53
54
  }
54
- async findAt(e, r) {
55
+ async findAt(e, t) {
55
56
  try {
56
- return await this.getAt(e, r);
57
+ return await this.getAt(e, t);
57
58
  } catch (e) {
58
- if (e instanceof n && e.status === 404 && e.code === t.AGGREGATE_NOT_FOUND) return;
59
+ if (e instanceof r && e.status === 404 && e.code === n.AGGREGATE_NOT_FOUND) return;
59
60
  throw e;
60
61
  }
61
62
  }
62
63
  async traceAt(e, t) {
63
- return a(await o(this.client, {
64
+ return (await o(this.client, {
64
65
  method: "GET",
65
66
  path: `${this.statePath(e)}/trace`,
66
67
  query: {
@@ -68,19 +69,23 @@ var s = class {
68
69
  to: t.to,
69
70
  limit: t.limit
70
71
  },
72
+ numbers: { answer: this.traceNumbers },
71
73
  options: t
72
- }), this.traceNumbers);
74
+ })).json();
73
75
  }
74
76
  get stateNumbers() {
75
- let e = this.type.textNumbers?.state;
76
- return e === void 0 ? void 0 : { state: e };
77
+ return t({
78
+ state: this.type.textNumbers?.state,
79
+ access: this.type.textNumbers?.access
80
+ });
77
81
  }
78
82
  get traceNumbers() {
79
- let t = this.type.textNumbers?.state, n = e(this.type);
80
- if (t !== void 0 || n !== void 0) return { commits: { "*": {
81
- ...t === void 0 ? {} : { state: t },
82
- ...n === void 0 ? {} : { events: { "*": n } }
83
- } } };
83
+ let n = e(this.type), r = t({
84
+ state: this.type.textNumbers?.state,
85
+ events: n === void 0 ? void 0 : { "*": n },
86
+ access: this.type.textNumbers?.access
87
+ });
88
+ return r === void 0 ? void 0 : { commits: { "*": r } };
84
89
  }
85
90
  statePath(e) {
86
91
  let t = `/${this.type.context}/${this.type.name}`;
@@ -1 +1 @@
1
- {"version":3,"file":"state.es.js","names":["StateClient","type","client","id","options","at","response","send","WowHeaders","etag","entityTag","json","result","error","WowProblemError","FrameworkErrorCodes","state","events","eventNumbers","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, E>> {\n return this.traceAt(undefined, options);\n }\n}\n"],"mappings":";;;;;AA0FA,IAAaA,IAAb,MAGE;CAKA,YACE,GACA,IAAoC,CAAC,GACrC;EADS,AADA,KAAA,OAAAC,GACA,KAAA,SAAAC;CACR;CAGH,KACE,GACA,IAA4B,CAAC,GACA;EAC7B,OAAO,KAAK,OAAOC,GAAIC,CAAO;CAChC;CAGA,IACE,GACA,IAAiD,CAAC,GAC5B;EACtB,OAAO,KAAK,MAAMD,GAAIC,CAAO;CAC/B;CAQA,KACE,GACA,IAAiD,CAAC,GAChB;EAClC,OAAO,KAAK,OAAOD,GAAIC,CAAO;CAChC;CAGA,MACE,GACA,IAA6B,CAAC,GACH;EAC3B,OAAO,KAAK,QAAQD,GAAIC,CAAO;CACjC;CAMA,MAAgB,OACd,GACA,GAC6B;EAC7B,IAAMC,IACJD,EAAQ,cAAc,OAAOA,EAAQ,GAAG,YAAY,IAAIA,EAAQ,IAC5D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A,IAAY,EAAE,SAAM;CACnD;CAGA,IAAY,eAAwC;EAClD,IAAMA,IAAQ,KAAK,KAAK,aAAa,OAC/BC,IAASC,EAAa,KAAK,IAAI;EACrC,IAAIF,MAAU,KAAA,KAAaC,MAAW,KAAA,GACtC,OAAO,EACL,SAAS,EACP,KAAK;GACH,GAAID,MAAU,KAAA,IAAY,CAAC,IAAI,EAAE,SAAM;GACvC,GAAIC,MAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAKA,EAAO,EAAE;EAC5D,EACF,EACF;CACF;CAEA,UAAkB,GAAgC;EAChD,IAAME,IAAO,IAAI,KAAK,KAAK,QAAQ,GAAG,KAAK,KAAK;EAChD,OAAOhB,MAAO,KAAA,IACV,GAAGgB,EAAK,UACR,GAAGA,EAAK,GAAG,mBAAmBhB,CAAE,EAAE;CACxC;AACF,GAcaiB,IAAb,cAGUpB,EAAkB;CAE1B,QAAQ,IAA4B,CAAC,GAAgC;EACnE,OAAO,KAAK,OAAO,KAAA,GAAWI,CAAO;CACvC;CAGA,OACE,IAAiD,CAAC,GAC5B;EACtB,OAAO,KAAK,MAAM,KAAA,GAAWA,CAAO;CACtC;CAMA,QACE,IAAiD,CAAC,GAChB;EAClC,OAAO,KAAK,OAAO,KAAA,GAAWA,CAAO;CACvC;CAGA,SAAS,IAA6B,CAAC,GAA8B;EACnE,OAAO,KAAK,QAAQ,KAAA,GAAWA,CAAO;CACxC;AACF"}
1
+ {"version":3,"file":"state.es.js","names":["StateClient","type","client","id","options","at","answer","send","WowHeaders","response","etag","entityTag","result","error","WowProblemError","FrameworkErrorCodes","recordNumbers","events","eventNumbers","commit","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 type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport { eventNumbers, recordNumbers, type TextNumbers } from './exactJson.js';\nimport { FrameworkErrorCodes, WowProblemError } from './problem.js';\nimport type {\n AccessValues,\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, A = AccessValues> =\n | {\n readonly notModified: false;\n readonly snapshot: Snapshot<S, A>;\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 * @typeParam A - The aggregate's access attributes.\n */\nexport class StateClient<\n S = unknown,\n E extends CommittedEvent = CommittedEvent,\n A = AccessValues,\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, A>> {\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, A>> {\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, A> | 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, A>> {\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, A>> {\n const at =\n options.at instanceof Date ? options.at.toISOString() : options.at;\n const answer = 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 numbers: { answer: this.stateNumbers },\n options,\n notModified: true,\n });\n const response = answer.response;\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 answer.json<Snapshot<S, A>>(),\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, A>> {\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, A> | 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, A>> {\n const answer = 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 numbers: { answer: this.traceNumbers },\n options,\n });\n return answer.json<StateTrace<S, E, A>>();\n }\n\n /** The exact numbers of a state read: its state's and its access attributes'. */\n private get stateNumbers(): TextNumbers | undefined {\n return recordNumbers({\n state: this.type.textNumbers?.state,\n access: this.type.textNumbers?.access,\n });\n }\n\n /** The exact numbers of a trace: each commit's state, events and access attributes. */\n private get traceNumbers(): TextNumbers | undefined {\n const events = eventNumbers(this.type);\n const commit = recordNumbers({\n state: this.type.textNumbers?.state,\n events: events === undefined ? undefined : { '*': events },\n access: this.type.textNumbers?.access,\n });\n return commit === undefined ? undefined : { commits: { '*': commit } };\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 * @typeParam A - The aggregate's access attributes.\n */\nexport class OwnStateClient<\n S = unknown,\n E extends CommittedEvent = CommittedEvent,\n A = AccessValues,\n> extends StateClient<S, E, A> {\n /** {@link StateClient.read} of the caller's own aggregate. */\n readOwn(options: StateReadOptions = {}): Promise<StateReadResult<S, A>> {\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, A>> {\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, A> | 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, E, A>> {\n return this.traceAt(undefined, options);\n }\n}\n"],"mappings":";;;;;AA2FA,IAAaA,IAAb,MAIE;CAKA,YACE,GACA,IAAoC,CAAC,GACrC;EADS,AADA,KAAA,OAAAC,GACA,KAAA,SAAAC;CACR;CAGH,KACE,GACA,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AO,KAAK,OAAO,KAAA,GAAWA,CAAO;CACvC;CAGA,SAAS,IAA6B,CAAC,GAAiC;EACtE,OAAO,KAAK,QAAQ,KAAA,GAAWA,CAAO;CACxC;AACF"}
package/dist/streams.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./exactJson.cjs"),t=require("./frameworkErrors.cjs"),n=require("./problem.cjs");let r=require("@ahoo-wang/fetcher-eventstream");var i=`row`,a=`error`,o=`end`,s=`message`;function c(e){return(0,r.toJsonServerSentEventStream)((0,r.toServerSentEventStream)(e)).pipeThrough(new TransformStream({transform(e,t){t.enqueue(e.data)}}))}var l=`hold-expired`,u=`complete`;function d(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i)})}function f(e){return new n.WowProblemError(n.isProblem(e)?e:{type:`about:blank`,title:`Query failed`,status:500})}function p(c,p,m={}){let{maxRetries:h=t.DEFAULT_RETRY.attempts-1,initialDelayMs:g=t.DEFAULT_RETRY.backoffMs,maxDelayMs:_=t.DEFAULT_RETRY.maxWaitMs,signal:v}=m,y=m.numbers,b=t=>(e.marksNothing(y)?(0,r.toJsonServerSentEventStream)((0,r.toServerSentEventStream)(t)):(0,r.toServerSentEventStream)(t).pipeThrough(new TransformStream({transform(t,n){let r=t.event===i||t.event===s;n.enqueue({...t,data:e.parseJson(t.data,r?y:void 0)})}}))).getReader(),x=b(c),S=m.lastEventId,C=0,w=0,T=!1;async function E(e,t){for(;;){if(v?.aborted)throw v.reason;if(w++>=h)throw e;let r=t??Math.min(_,g*2**(w-1));r>0&&await d(r,v);try{let e=await p(S,C);return e&&(x=b(e)),e!==void 0}catch(r){if(v?.aborted||r instanceof n.WowProblemError&&r.retry===`none`)throw r;t=r.retryAfterMs,e=r}}}return new ReadableStream({async pull(e){for(;;){let t,r;try{let n=await x.read();if(n.done)t=TypeError(`The query stream was cut off.`);else{let{event:c,id:d,data:p}=n.value;if(c===i||c===s){d&&(S=d),C++,w=0,e.enqueue(d?{row:p,position:d}:{row:p});return}if(c===o){let n=p;if(n.reason===u){e.close();return}if(t=TypeError(`The query stream ended: ${n.reason}.`),!n.resumable)throw t;n.reason===l&&(r=0)}else if(c===a){let e=f(p);if(e.retry===`none`)throw e;t=e,r=e.retryAfterMs}else continue}}catch(e){if(e===t||e instanceof n.WowProblemError)throw e;t=e}if(T)return;if(v?.aborted)throw v.reason;if(S===void 0&&C>0)throw t;if(!await E(t,r)){e.close();return}}},cancel(e){return T=!0,x.cancel(e)}})}exports.commandResults=c,exports.resumableQueryRows=p;
1
+ const e=require("./exactJson.cjs"),t=require("./frameworkErrors.cjs"),n=require("./problem.cjs");let r=require("@ahoo-wang/fetcher-eventstream");var i=`row`,a=`error`,o=`end`,s=`message`;function c(t,n){return(0,r.toServerSentEventStream)(t.response).pipeThrough(new TransformStream({transform(r,i){i.enqueue({...r,data:e.parseJson(r.data,n(r.event)?t.numbers:void 0)})}})).getReader()}function l(e,t){let r=c(e,()=>!0);return new ReadableStream({async pull(e){let i;try{i=await r.read()}catch(e){throw n.rememberRequestId(e,t),e}i.done?e.close():e.enqueue(i.value.data)},cancel(e){return r.cancel(e)}})}var u=`hold-expired`,d=`complete`;function f(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i)})}function p(e){return new n.WowProblemError(n.isProblem(e)?e:{type:`about:blank`,title:`Query failed`,status:500})}function m(e,r,l={}){let{maxRetries:m=t.DEFAULT_RETRY.attempts-1,initialDelayMs:h=t.DEFAULT_RETRY.backoffMs,maxDelayMs:g=t.DEFAULT_RETRY.maxWaitMs,signal:_}=l,v=e=>c(e,e=>e===i||e===s),y=v(e),b=l.lastEventId,x=0,S=0,C=new AbortController,w=_===void 0?C.signal:AbortSignal.any([_,C.signal]);async function T(e,t){for(;;){if(w.aborted)throw w.reason;if(S++>=m)throw e;let i=t??Math.min(g,h*2**(S-1));i>0&&await f(i,w);try{let e=await r(b,x,w);if(w.aborted)throw await e?.response.body?.cancel(w.reason),w.reason;return e&&(y=v(e)),e!==void 0}catch(r){if(w.aborted||r instanceof n.WowProblemError&&r.retry===`none`)throw r;t=r.retryAfterMs,e=r}}}return new ReadableStream({async pull(e){for(;;){let t,r;try{let n=await y.read();if(n.done)t=TypeError(`The query stream was cut off.`);else{let{event:c,id:l,data:f}=n.value;if(c===i||c===s){l&&(b=l),x++,S=0,e.enqueue(l?{row:f,position:l}:{row:f});return}if(c===o){let n=f;if(n.reason===d){e.close();return}if(t=TypeError(`The query stream ended: ${n.reason}.`),!n.resumable)throw t;n.reason===u&&(r=0)}else if(c===a){let e=p(f);if(e.retry===`none`)throw e;t=e,r=e.retryAfterMs}else continue}}catch(e){if(e===t||e instanceof n.WowProblemError)throw e;t=e}if(C.signal.aborted)return;if(_?.aborted)throw _.reason;if(b===void 0&&x>0)throw t;if(!await T(t,r)){e.close();return}}},cancel(e){return C.abort(e),y.cancel(e)}})}exports.commandResults=l,exports.resumableQueryRows=m;
2
2
  //# sourceMappingURL=streams.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"streams.cjs","names":["toJsonServerSentEventStream","toServerSentEventStream","WowProblemError","isProblem","DEFAULT_RETRY","marksNothing","parseJson","require_exactJson","require_frameworkErrors","require_problem","_ahoo_wang_fetcher_eventstream","ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","response","controller","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","data","resumableQueryRows","options","numbers","events","from","row","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","end","reason"],"sources":["../src/streams.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 type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { DEFAULT_RETRY } from './frameworkErrors.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended: `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One row of a streamed list, with its position. Kotlin's `Positioned`. */\nexport interface Positioned<T> {\n /** The row. */\n readonly row: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes. A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link Positioned.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; by default one fewer than\n * the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0\n * never resumes.\n */\n readonly maxRetries?: number;\n /**\n * The wait before the first such retry, doubled for each next; the\n * catalog's backoff by default ({@link DEFAULT_RETRY}).\n */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list, read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<Positioned<T>> {\n const {\n maxRetries = DEFAULT_RETRY.attempts - 1,\n initialDelayMs = DEFAULT_RETRY.backoffMs,\n maxDelayMs = DEFAULT_RETRY.maxWaitMs,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && error.retry === 'none')\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retryAfterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<Positioned<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id ? { row: data as T, position: id } : { row: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (error.retry === 'none') throw error;\n stop = error;\n delayMs = error.retryAfterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":"A,iJAyBA,IAAMW,EAAY,MAGZC,EAAc,QAGdC,EAAY,MAGZC,EAAgB,UAYtB,SAAgBC,EAAkB,EAA4C,CAC5E,OAAA,EAAOf,EAAAA,4BAAAA,EAAAA,EACLC,EAAAA,wBAAAA,CAAwBe,CAAQ,CAClC,CAAC,CAAC,YACA,IAAI,gBAGF,CACA,UAAU,EAAO,EAAY,CAC3BC,EAAW,QAAQC,EAAM,IAAI,CAC/B,CACF,CAAC,CACH,CACF,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EAAM,YAClB,MACE,QAEJ,CACF,OAASA,EAAO,CACd,GAAIA,IAAUC,GAAQD,aAAiBhD,EAAAA,gBAAiB,MAAMgD,EAC9D,EAAOA,CACT,CACA,GAAIV,EAAW,OAEf,GAAIf,GAAQ,QAAS,MAAMA,EAAO,OAClC,GAAIY,IAAgB,IAAA,IAAaC,EAAW,EAAG,MAAMa,EACrD,GAAI,CAAE,MAAMV,EAAOU,EAAMN,CAAO,EAAI,CAClC5B,EAAW,MAAM,EACjB,MACF,CACF,CACF,EACA,OAAO,EAAQ,CAEb,MADA,GAAY,GACLmB,EAAO,OAAOkB,CAAM,CAC7B,CACF,CAAC,CACH,C"}
1
+ {"version":3,"file":"streams.cjs","names":["toServerSentEventStream","parseJson","WowProblemError","isProblem","DEFAULT_RETRY","require_exactJson","require_frameworkErrors","require_problem","_ahoo_wang_fetcher_eventstream","ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","eventsOf","answer","controller","event","marked","commandResults","reader","next","error","requestId","reason","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","data","resumableQueryRows","options","events","from","lastEventId","received","failures","cancelling","halted","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","reopen","stop","id","end"],"sources":["../src/streams.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 type JsonServerSentEvent,\n type ServerSentEvent,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { parseJson } from './exactJson.js';\nimport type { Answer } from './http.js';\nimport type { CommandResult } from './wire.js';\nimport { DEFAULT_RETRY } from './frameworkErrors.js';\nimport { isProblem, rememberRequestId, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/**\n * The events of `answer`'s server-sent event stream, each event's data read\n * as JSON: with the answer's exact numbers for an event `marked` names.\n */\nfunction eventsOf(\n answer: Answer,\n marked: (event: string | undefined) => boolean,\n): ReadableStreamDefaultReader<JsonServerSentEvent<unknown>> {\n return toServerSentEventStream(answer.response)\n .pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n controller.enqueue({\n ...event,\n data: parseJson(\n event.data,\n marked(event.event) ? answer.numbers : undefined,\n ),\n });\n },\n }),\n )\n .getReader();\n}\n\n/**\n * The data of each event of `answer`'s server-sent event stream, the\n * results of the command sent with `requestId`. A read that fails, such as a\n * connection lost after the response began, fails with an error that carries\n * `requestId` (`requestIdOf`): the command may have been committed, and\n * a retry with the same id is answered as its duplicate.\n */\nexport function commandResults<R>(\n answer: Answer,\n requestId: string,\n): CommandResultStream<R> {\n const reader = eventsOf(answer, () => true);\n return new ReadableStream<CommandResult<R>>({\n async pull(controller) {\n let next: ReadableStreamReadResult<JsonServerSentEvent<unknown>>;\n try {\n next = await reader.read();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n if (next.done) controller.close();\n else controller.enqueue(next.value.data as CommandResult<R>);\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Why a resumable streamed list ended: `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One row of a streamed list, with its position. Kotlin's `Positioned`. */\nexport interface Positioned<T> {\n /** The row. */\n readonly row: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes. A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link Positioned.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; by default one fewer than\n * the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0\n * never resumes.\n */\n readonly maxRetries?: number;\n /**\n * The wait before the first such retry, doubled for each next; the\n * catalog's backoff by default ({@link DEFAULT_RETRY}).\n */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list, read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream. The signal `reopen` is given aborts once `signal` does or\n * the stream's reader cancels it: a cancel during a wait to resume, or while\n * the stream is asked for again, sends nothing more and leaves no response\n * open.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n answer: Answer,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n signal: AbortSignal,\n ) => Promise<Answer | undefined>,\n options: StreamResumeOptions & { readonly signal?: AbortSignal } = {},\n): ReadableStream<Positioned<T>> {\n const {\n maxRetries = DEFAULT_RETRY.attempts - 1,\n initialDelayMs = DEFAULT_RETRY.backoffMs,\n maxDelayMs = DEFAULT_RETRY.maxWaitMs,\n signal,\n } = options;\n // A record's exact numbers are its answer's (review R4-Q, Q-9).\n const events = (from: Answer) =>\n eventsOf(from, event => event === ROW_EVENT || event === UNNAMED_EVENT);\n let reader = events(answer);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Aborted once the reader cancels: a read in flight then ends, and must not\n // be taken for a cut-off stream to ask for again. `halted` aborts with it or\n // with `signal`, and a wait to resume, or a request to, ends with `halted`\n // (`AbortSignal.any`: Node 20.3, Chrome 116, Firefox 124, Safari 17.4, all\n // within the runtimes the compatibility page states).\n const cancelling = new AbortController();\n const halted =\n signal === undefined\n ? cancelling.signal\n : AbortSignal.any([signal, cancelling.signal]);\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (halted.aborted) throw halted.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, halted);\n try {\n const next = await reopen(lastEventId, received, halted);\n if (halted.aborted) {\n // Answered as it was cancelled: nothing reads this response.\n await next?.response.body?.cancel(halted.reason);\n throw halted.reason;\n }\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n halted.aborted ||\n (error instanceof WowProblemError && error.retry === 'none')\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retryAfterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<Positioned<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id ? { row: data as T, position: id } : { row: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (error.retry === 'none') throw error;\n stop = error;\n delayMs = error.retryAfterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelling.signal.aborted) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelling.abort(reason);\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":"A,iJAyBA,IAAMS,EAAY,MAGZC,EAAc,QAGdC,EAAY,MAGZC,EAAgB,UAetB,SAASC,EACP,EACA,EAC2D,CAC3D,OAAA,EAAOb,EAAAA,wBAAAA,CAAwBc,EAAO,QAAQ,CAAC,CAC5C,YACC,IAAI,gBAA+D,CACjE,UAAU,EAAO,EAAY,CAC3BC,EAAW,QAAQ,CACjB,GAAGC,EACH,KAAMf,EAAAA,UACJe,EAAM,KACNC,EAAOD,EAAM,KAAK,EAAIF,EAAO,QAAU,IAAA,EACzC,CACF,CAAC,CACH,CACF,CAAC,CACH,CAAC,CACA,UAAU,CACf,CASA,SAAgBI,EACd,EACA,EACwB,CACxB,IAAMC,EAASN,EAASC,MAAc,EAAI,EAC1C,OAAO,IAAI,eAAiC,CAC1C,MAAM,KAAK,EAAY,CACrB,IAAIM,EACJ,GAAI,CACF,EAAO,MAAMD,EAAO,KAAK,CAC3B,OAASE,EAAO,CAEd,MADAd,EAAA,kBAAkBc,EAAOC,CAAS,EAC5BD,CACR,CACID,EAAK,KAAML,EAAW,MAAM,EAC3BA,EAAW,QAAQK,EAAK,MAAM,IAAwB,CAC7D,EACA,OAAO,EAAQ,CACb,OAAOD,EAAO,OAAOI,CAAM,CAC7B,CACF,CAAC,CACH,CAyDA,IAAMC,EAAgC,eAChCC,EAA4B,WAGlC,SAASC,EAAM,EAAY,EAAqC,CAC9D,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,IAAMC,MAAc,CAClB,aAAaC,CAAK,EAClBC,EAAOC,GAAQ,MAAM,CACvB,EACMF,EAAQ,eAAiB,CAC7BE,GAAQ,oBAAoB,QAASH,CAAK,EAC1CI,EAAQ,CACV,EAAGC,CAAE,EACLF,GAAQ,iBAAiB,QAASH,CAAK,CACzC,CAAC,CACH,CAEA,SAASM,EAAU,EAAgC,CACjD,OAAO,IAAI/B,EAAAA,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AMD,EAAO,KAAK,EAC/B,GAAIC,EAAK,KAEP,EAAW,UAAU,+BAA+B,MAC/C,CACL,GAAM,CAAE,QAAO,KAAI,QAASA,EAAK,MACjC,GAAIJ,IAAUP,GAAaO,IAAUJ,EAAe,CAC9CyC,IAAI,EAAcA,GACtB,IACA,EAAW,EACXtC,EAAW,QACTsC,EAAK,CAAE,IAAKnB,EAAW,SAAUmB,CAAG,EAAI,CAAE,IAAKnB,CAAU,CAC3D,EACA,MACF,CACA,GAAIlB,IAAUL,EAAW,CACvB,IAAM2C,EAAMpB,EACZ,GAAIoB,EAAI,SAAW7B,EAAU,CAC3BV,EAAW,MAAM,EACjB,MACF,CAEA,GADA,EAAW,UAAU,2BAA2BuC,EAAI,OAAO,EAAE,EACzD,CAACA,EAAI,UAAW,MAAMF,EACtBE,EAAI,SAAW9B,IAAc,EAAU,EAC7C,MAAO,GAAIR,IAAUN,EAAa,CAChC,IAAMW,EAAQY,EAAUC,CAAI,EAC5B,GAAIb,EAAM,QAAU,OAAQ,MAAMA,EAClC,EAAOA,EACP,EAAUA,EAAM,YAClB,MACE,QAEJ,CACF,OAASA,EAAO,CACd,GAAIA,IAAU+B,GAAQ/B,aAAiBnB,EAAAA,gBAAiB,MAAMmB,EAC9D,EAAOA,CACT,CACA,GAAIqB,EAAW,OAAO,QAAS,OAE/B,GAAIZ,GAAQ,QAAS,MAAMA,EAAO,OAClC,GAAIS,IAAgB,IAAA,IAAaC,EAAW,EAAG,MAAMY,EACrD,GAAI,CAAE,MAAMR,EAAOQ,EAAMJ,CAAO,EAAI,CAClCjC,EAAW,MAAM,EACjB,MACF,CACF,CACF,EACA,OAAO,EAAQ,CAEb,OADA2B,EAAW,MAAMnB,CAAM,EAChBJ,EAAO,OAAOI,CAAM,CAC7B,CACF,CAAC,CACH,C"}
@@ -1,4 +1,4 @@
1
- import { TextNumbers } from './exactJson.cjs';
1
+ import { Answer } from './http.cjs';
2
2
  import { CommandResult } from './wire.cjs';
3
3
  /**
4
4
  * The results of a command's event stream (`Accept: text/event-stream`), one
@@ -6,8 +6,14 @@ import { CommandResult } from './wire.cjs';
6
6
  * admission is the stream's last result, not an error.
7
7
  */
8
8
  export type CommandResultStream<R = Record<string, unknown>> = ReadableStream<CommandResult<R>>;
9
- /** The data of each event of `response`'s server-sent event stream. */
10
- export declare function commandResults<R>(response: Response): CommandResultStream<R>;
9
+ /**
10
+ * The data of each event of `answer`'s server-sent event stream, the
11
+ * results of the command sent with `requestId`. A read that fails, such as a
12
+ * connection lost after the response began, fails with an error that carries
13
+ * `requestId` (`requestIdOf`): the command may have been committed, and
14
+ * a retry with the same id is answered as its duplicate.
15
+ */
16
+ export declare function commandResults<R>(answer: Answer, requestId: string): CommandResultStream<R>;
11
17
  /**
12
18
  * Why a resumable streamed list ended: `complete` once every
13
19
  * record was sent; the others are the server's, and resumable: the stream ran
@@ -65,14 +71,15 @@ export interface StreamResumeOptions {
65
71
  * with how many records were read so far: `undefined` when no more are
66
72
  * wanted. Each record comes with its position. An `error` event that is not
67
73
  * retryable, a failure `reopen` cannot get past, and an abort of `signal`
68
- * error the stream.
74
+ * error the stream. The signal `reopen` is given aborts once `signal` does or
75
+ * the stream's reader cancels it: a cancel during a wait to resume, or while
76
+ * the stream is asked for again, sends nothing more and leaves no response
77
+ * open.
69
78
  *
70
79
  * @param response - The first response
71
80
  * @param reopen - Asks for the stream again after a position
72
81
  * @param options - How the stream resumes, and what cancels it
73
82
  */
74
- export declare function resumableQueryRows<T>(response: Response, reopen: (lastEventId: string | undefined, received: number) => Promise<Response | undefined>, options?: StreamResumeOptions & {
83
+ export declare function resumableQueryRows<T>(answer: Answer, reopen: (lastEventId: string | undefined, received: number, signal: AbortSignal) => Promise<Answer | undefined>, options?: StreamResumeOptions & {
75
84
  readonly signal?: AbortSignal;
76
- /** The numbers of each record read as their exact text (review R4-Q, Q-9). */
77
- readonly numbers?: TextNumbers;
78
85
  }): ReadableStream<Positioned<T>>;
package/dist/streams.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { TextNumbers } from './exactJson.js';
1
+ import { Answer } from './http.js';
2
2
  import { CommandResult } from './wire.js';
3
3
  /**
4
4
  * The results of a command's event stream (`Accept: text/event-stream`), one
@@ -6,8 +6,14 @@ import { CommandResult } from './wire.js';
6
6
  * admission is the stream's last result, not an error.
7
7
  */
8
8
  export type CommandResultStream<R = Record<string, unknown>> = ReadableStream<CommandResult<R>>;
9
- /** The data of each event of `response`'s server-sent event stream. */
10
- export declare function commandResults<R>(response: Response): CommandResultStream<R>;
9
+ /**
10
+ * The data of each event of `answer`'s server-sent event stream, the
11
+ * results of the command sent with `requestId`. A read that fails, such as a
12
+ * connection lost after the response began, fails with an error that carries
13
+ * `requestId` (`requestIdOf`): the command may have been committed, and
14
+ * a retry with the same id is answered as its duplicate.
15
+ */
16
+ export declare function commandResults<R>(answer: Answer, requestId: string): CommandResultStream<R>;
11
17
  /**
12
18
  * Why a resumable streamed list ended: `complete` once every
13
19
  * record was sent; the others are the server's, and resumable: the stream ran
@@ -65,14 +71,15 @@ export interface StreamResumeOptions {
65
71
  * with how many records were read so far: `undefined` when no more are
66
72
  * wanted. Each record comes with its position. An `error` event that is not
67
73
  * retryable, a failure `reopen` cannot get past, and an abort of `signal`
68
- * error the stream.
74
+ * error the stream. The signal `reopen` is given aborts once `signal` does or
75
+ * the stream's reader cancels it: a cancel during a wait to resume, or while
76
+ * the stream is asked for again, sends nothing more and leaves no response
77
+ * open.
69
78
  *
70
79
  * @param response - The first response
71
80
  * @param reopen - Asks for the stream again after a position
72
81
  * @param options - How the stream resumes, and what cancels it
73
82
  */
74
- export declare function resumableQueryRows<T>(response: Response, reopen: (lastEventId: string | undefined, received: number) => Promise<Response | undefined>, options?: StreamResumeOptions & {
83
+ export declare function resumableQueryRows<T>(answer: Answer, reopen: (lastEventId: string | undefined, received: number, signal: AbortSignal) => Promise<Answer | undefined>, options?: StreamResumeOptions & {
75
84
  readonly signal?: AbortSignal;
76
- /** The numbers of each record read as their exact text (review R4-Q, Q-9). */
77
- readonly numbers?: TextNumbers;
78
85
  }): ReadableStream<Positioned<T>>;