@ahoo-wang/wow-client 9.9.0 → 10.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/dsl/descriptor.cjs.map +1 -1
  2. package/dist/dsl/descriptor.d.cts +7 -0
  3. package/dist/dsl/descriptor.d.ts +7 -0
  4. package/dist/dsl/descriptor.es.js.map +1 -1
  5. package/dist/v10/commands.cjs +2 -0
  6. package/dist/v10/commands.cjs.map +1 -0
  7. package/dist/v10/commands.d.cts +105 -0
  8. package/dist/v10/commands.d.ts +105 -0
  9. package/dist/v10/commands.es.js +68 -0
  10. package/dist/v10/commands.es.js.map +1 -0
  11. package/dist/v10/http.cjs +2 -0
  12. package/dist/v10/http.cjs.map +1 -0
  13. package/dist/v10/http.d.cts +87 -0
  14. package/dist/v10/http.d.ts +87 -0
  15. package/dist/v10/http.es.js +73 -0
  16. package/dist/v10/http.es.js.map +1 -0
  17. package/dist/v10/index.d.cts +19 -0
  18. package/dist/v10/index.d.ts +19 -0
  19. package/dist/v10/manifest.cjs +2 -0
  20. package/dist/v10/manifest.cjs.map +1 -0
  21. package/dist/v10/manifest.d.cts +109 -0
  22. package/dist/v10/manifest.d.ts +109 -0
  23. package/dist/v10/manifest.es.js +14 -0
  24. package/dist/v10/manifest.es.js.map +1 -0
  25. package/dist/v10/problem.cjs +2 -0
  26. package/dist/v10/problem.cjs.map +1 -0
  27. package/dist/v10/problem.d.cts +164 -0
  28. package/dist/v10/problem.d.ts +164 -0
  29. package/dist/v10/problem.es.js +119 -0
  30. package/dist/v10/problem.es.js.map +1 -0
  31. package/dist/v10/queries.cjs +2 -0
  32. package/dist/v10/queries.cjs.map +1 -0
  33. package/dist/v10/queries.d.cts +136 -0
  34. package/dist/v10/queries.d.ts +136 -0
  35. package/dist/v10/queries.es.js +88 -0
  36. package/dist/v10/queries.es.js.map +1 -0
  37. package/dist/v10/state.cjs +2 -0
  38. package/dist/v10/state.cjs.map +1 -0
  39. package/dist/v10/state.d.cts +53 -0
  40. package/dist/v10/state.d.ts +53 -0
  41. package/dist/v10/state.es.js +51 -0
  42. package/dist/v10/state.es.js.map +1 -0
  43. package/dist/v10/streams.cjs +2 -0
  44. package/dist/v10/streams.cjs.map +1 -0
  45. package/dist/v10/streams.d.cts +14 -0
  46. package/dist/v10/streams.d.ts +14 -0
  47. package/dist/v10/streams.es.js +22 -0
  48. package/dist/v10/streams.es.js.map +1 -0
  49. package/dist/v10/wait.cjs +2 -0
  50. package/dist/v10/wait.cjs.map +1 -0
  51. package/dist/v10/wait.d.cts +61 -0
  52. package/dist/v10/wait.d.ts +61 -0
  53. package/dist/v10/wait.es.js +44 -0
  54. package/dist/v10/wait.es.js.map +1 -0
  55. package/dist/v10/wire.cjs +2 -0
  56. package/dist/v10/wire.cjs.map +1 -0
  57. package/dist/v10/wire.d.cts +301 -0
  58. package/dist/v10/wire.d.ts +301 -0
  59. package/dist/v10/wire.es.js +10 -0
  60. package/dist/v10/wire.es.js.map +1 -0
  61. package/dist/v10.cjs +1 -0
  62. package/dist/v10.es.js +9 -0
  63. package/package.json +11 -1
@@ -0,0 +1,68 @@
1
+ import { WowProblemError as e } from "./problem.es.js";
2
+ import { WowV10Headers as t, expandPath as n, json as r, send as i } from "./http.es.js";
3
+ import { commandResults as a } from "./streams.es.js";
4
+ import { formatWaitPlan as o, formatWaitTimeout as s } from "./wait.es.js";
5
+ //#region src/v10/commands.ts
6
+ var c = {
7
+ DELETE_AGGREGATE: "wow.lifecycle.DeleteAggregate",
8
+ RESTORE_AGGREGATE: "wow.lifecycle.RestoreAggregate",
9
+ TRANSFER_OWNER: "wow.lifecycle.TransferOwner",
10
+ TRANSFER_SPACE: "wow.lifecycle.TransferSpace",
11
+ APPLY_TAGS: "wow.lifecycle.ApplyTags"
12
+ };
13
+ function l(e) {
14
+ return e.replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[_\s]+/g, "-").toLowerCase();
15
+ }
16
+ function u(e, n) {
17
+ let r = e.wait;
18
+ return {
19
+ [t.REQUEST_ID]: e.requestId,
20
+ [t.WAIT]: r?.plan === void 0 ? void 0 : o(r.plan),
21
+ [t.WAIT_TIMEOUT]: r?.timeout === void 0 ? void 0 : s(r.timeout),
22
+ [t.IF_MATCH]: e.expectedVersion === void 0 ? void 0 : `"${e.expectedVersion}"`,
23
+ Accept: n
24
+ };
25
+ }
26
+ var d = class {
27
+ constructor(e = {}) {
28
+ this.client = e;
29
+ }
30
+ async send(t, n, i = {}) {
31
+ try {
32
+ let e = await this.post(t, n, i);
33
+ return await r(e);
34
+ } catch (t) {
35
+ if (i.resolveRejected && t instanceof e && t.result !== void 0) return t.result;
36
+ throw t;
37
+ }
38
+ }
39
+ async stream(e, t, n = {}) {
40
+ return a(await this.post(e, t, n, "text/event-stream"));
41
+ }
42
+ async lifecycle(e, t, n, a, o = {}) {
43
+ let s = `${e}/${encodeURIComponent(t)}`;
44
+ if (n === c.DELETE_AGGREGATE) {
45
+ let e = await i(this.client, {
46
+ method: "DELETE",
47
+ path: s,
48
+ headers: u(o),
49
+ options: o
50
+ });
51
+ return r(e);
52
+ }
53
+ return this.send(`${s}/${l(n)}`, a ?? {}, o);
54
+ }
55
+ post(e, t, r, a) {
56
+ return i(this.client, {
57
+ method: "POST",
58
+ path: e.includes("{id}") ? n(e, { id: r.id ?? "" }) : e,
59
+ headers: u(r, a),
60
+ body: t ?? {},
61
+ options: r
62
+ });
63
+ }
64
+ };
65
+ //#endregion
66
+ export { d as CommandGateway, c as LifecycleCommands, l as commandSegment };
67
+
68
+ //# sourceMappingURL=commands.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commands.es.js","names":["LifecycleCommands","commandSegment","name","commandHeaders","wait","options","WowV10Headers","formatWaitPlan","formatWaitTimeout","accept","CommandGateway","client","response","path","body","json","error","WowProblemError","commandResults","base","aggregatePath","id","command","send","expandPath"],"sources":["../../src/v10/commands.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 expandPath,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowV10Headers,\n} from './http.js';\nimport type { CommandResult } from './wire.js';\nimport { WowProblemError } from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, type WaitOptions } from './wait.js';\n\n/** What a command request carries beside its body (decisions D95–D99). */\nexport interface CommandOptions extends RequestOptions {\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate.\n */\n readonly requestId?: string;\n /** What to wait for, and for how long. */\n readonly wait?: WaitOptions;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n /**\n * Resolve a result that did not succeed instead of rejecting with its\n * {@link WowProblemError}; `false` by default.\n */\n readonly resolveRejected?: boolean;\n}\n\n/** The options of a command whose route may name the aggregate id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list (decision D113). */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n APPLY_TAGS: 'wow.lifecycle.ApplyTags',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */\nexport interface ApplyTags {\n readonly tags: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * The route segment of a command name, as the server derives it: kebab case,\n * dots kept (`AddCartItem` → `add-cart-item`,\n * `wow.lifecycle.RestoreAggregate` → `wow.lifecycle.restore-aggregate`).\n *\n * @param name - The command's name\n */\nexport function commandSegment(name: string): string {\n return name\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/[_\\s]+/g, '-')\n .toLowerCase();\n}\n\nfunction commandHeaders(\n options: CommandOptions,\n accept?: string,\n): Record<string, string | undefined> {\n const wait = options.wait;\n return {\n [WowV10Headers.REQUEST_ID]: options.requestId,\n [WowV10Headers.WAIT]:\n wait?.plan === undefined ? undefined : formatWaitPlan(wait.plan),\n [WowV10Headers.WAIT_TIMEOUT]:\n wait?.timeout === undefined ? undefined : formatWaitTimeout(wait.timeout),\n [WowV10Headers.IF_MATCH]:\n options.expectedVersion === undefined\n ? undefined\n : `\"${options.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/**\n * Sends commands to the command routes of a Wow V10 service\n * (`POST /{context}/{aggregate}/{id}/{command}`, and without `{id}` for a\n * command that may create its aggregate). Generated aggregate clients build\n * on it; it serves any route too.\n *\n * A command that did not succeed rejects with a {@link WowProblemError}\n * holding its result, unless the options resolve it.\n */\nexport class CommandGateway {\n /** @param client - How the service is reached */\n constructor(readonly client: WowClientOptions = {}) {}\n\n /**\n * Sends a command and answers the result its wait ends with: 200, or 202\n * for a plan that ends at `accepted`.\n *\n * @param path - The route, `{id}` filled from `id`\n * @param body - The command's body; `{}` when absent\n * @param options - Headers, wait and the aggregate id\n */\n async send<R = Record<string, unknown>>(\n path: string,\n body?: object,\n options: CreateCommandOptions = {},\n ): Promise<CommandResult<R>> {\n try {\n const response = await this.post(path, body, options);\n return await json<CommandResult<R>>(response);\n } catch (error) {\n if (\n options.resolveRejected &&\n error instanceof WowProblemError &&\n error.result !== undefined\n ) {\n return error.result as CommandResult<R>;\n }\n throw error;\n }\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances. An admission refusal rejects with its\n * problem; a rejection after admission is the stream's last result.\n *\n * @param path - The route, `{id}` filled from `id`\n * @param body - The command's body; `{}` when absent\n * @param options - Headers, wait and the aggregate id\n */\n async stream<R = Record<string, unknown>>(\n path: string,\n body?: object,\n options: CreateCommandOptions = {},\n ): Promise<CommandResultStream<R>> {\n return commandResults<R>(\n await this.post(path, body, options, 'text/event-stream'),\n );\n }\n\n /**\n * Sends a lifecycle command an aggregate lists: `DELETE\n * /{context}/{aggregate}/{id}` for `DeleteAggregate`, `POST\n * …/{id}/wow.lifecycle.<kebab>` for the others.\n *\n * @param aggregatePath - `/{context}/{aggregate}`\n * @param id - The aggregate's id\n * @param command - The lifecycle command\n * @param body - Its body, for the commands that have one\n * @param options - Headers and wait\n */\n async lifecycle<R = Record<string, unknown>>(\n aggregatePath: string,\n id: string,\n command: LifecycleCommand,\n body?: TransferOwner | TransferSpace | ApplyTags,\n options: CommandOptions = {},\n ): Promise<CommandResult<R>> {\n const base = `${aggregatePath}/${encodeURIComponent(id)}`;\n if (command === LifecycleCommands.DELETE_AGGREGATE) {\n const response = await send(this.client, {\n method: 'DELETE',\n path: base,\n headers: commandHeaders(options),\n options,\n });\n return json<CommandResult<R>>(response);\n }\n return this.send<R>(\n `${base}/${commandSegment(command)}`,\n body ?? {},\n options,\n );\n }\n\n private post(\n path: string,\n body: object | undefined,\n options: CreateCommandOptions,\n accept?: string,\n ): Promise<Response> {\n return send(this.client, {\n method: 'POST',\n path: path.includes('{id}')\n ? expandPath(path, { id: options.id ?? '' })\n : path,\n headers: commandHeaders(options, accept),\n body: body ?? {},\n options,\n });\n }\n}\n"],"mappings":";;;;;AAsDA,IAAaA,IAAoB;CAC/B,kBAAkB;CAClB,mBAAmB;CACnB,gBAAgB;CAChB,gBAAgB;CAChB,YAAY;AACd;AA4BA,SAAgBC,EAAe,GAAsB;CACnD,OAAOC,EACJ,QAAQ,yBAAyB,OAAO,CAAC,CACzC,QAAQ,sBAAsB,OAAO,CAAC,CACtC,QAAQ,WAAW,GAAG,CAAC,CACvB,YAAY;AACjB;AAEA,SAASC,EACP,GACA,GACoC;CACpC,IAAMC,IAAOC,EAAQ;CACrB,OAAO;GACJC,EAAc,aAAaD,EAAQ;GACnCC,EAAc,OACbF,GAAM,SAAS,KAAA,IAAY,KAAA,IAAYG,EAAeH,EAAK,IAAI;GAChEE,EAAc,eACbF,GAAM,YAAY,KAAA,IAAY,KAAA,IAAYI,EAAkBJ,EAAK,OAAO;GACzEE,EAAc,WACbD,EAAQ,oBAAoB,KAAA,IACxB,KAAA,IACA,IAAIA,EAAQ,gBAAgB;EAClC,QAAQI;CACV;AACF;AAWA,IAAaC,IAAb,MAA4B;CAE1B,YAAY,IAAoC,CAAC,GAAG;EAA/B,KAAA,SAAAC;CAAgC;CAUrD,MAAM,KACJ,GACA,GACA,IAAgC,CAAC,GACN;EAC3B,IAAI;GACF,IAAMC,IAAW,MAAM,KAAK,KAAKC,GAAMC,GAAMT,CAAO;GACpD,OAAO,MAAMU,EAAuBH,CAAQ;EAC9C,SAASI,GAAO;GACd,IACEX,EAAQ,mBACRW,aAAiBC,KACjBD,EAAM,WAAW,KAAA,GAEjB,OAAOA,EAAM;GAEf,MAAMA;EACR;CACF;CAWA,MAAM,OACJ,GACA,GACA,IAAgC,CAAC,GACA;EACjC,OAAOE,EACL,MAAM,KAAK,KAAKL,GAAMC,GAAMT,GAAS,mBAAmB,CAC1D;CACF;CAaA,MAAM,UACJ,GACA,GACA,GACA,GACA,IAA0B,CAAC,GACA;EAC3B,IAAMc,IAAO,GAAGC,EAAc,GAAG,mBAAmBC,CAAE;EACtD,IAAIC,MAAYtB,EAAkB,kBAAkB;GAClD,IAAMY,IAAW,MAAMW,EAAK,KAAK,QAAQ;IACvC,QAAQ;IACR,MAAMJ;IACN,SAAShB,EAAeE,CAAO;IAC/B;GACF,CAAC;GACD,OAAOU,EAAuBH,CAAQ;EACxC;EACA,OAAO,KAAK,KACV,GAAGO,EAAK,GAAGlB,EAAeqB,CAAO,KACjCR,KAAQ,CAAC,GACTT,CACF;CACF;CAEA,KACE,GACA,GACA,GACA,GACmB;EACnB,OAAOkB,EAAK,KAAK,QAAQ;GACvB,QAAQ;GACR,MAAMV,EAAK,SAAS,MAAM,IACtBW,EAAWX,GAAM,EAAE,IAAIR,EAAQ,MAAM,GAAG,CAAC,IACzCQ;GACJ,SAASV,EAAeE,GAASI,CAAM;GACvC,MAAMK,KAAQ,CAAC;GACf;EACF,CAAC;CACH;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./problem.cjs");let t=require("@ahoo-wang/fetcher");var n={REQUEST_ID:`Wow-Request-Id`,WAIT:`Wow-Wait`,WAIT_TIMEOUT:`Wow-Wait-Timeout`,SCOPE:`Wow-Scope`,SPACE:`Wow-Space`,IF_MATCH:`If-Match`,IF_NONE_MATCH:`If-None-Match`,ETAG:`ETag`,RETRY_AFTER:`Retry-After`};function r(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function i(e){let t=[e.tenantId===void 0?void 0:`tenant=${r(e.tenantId)}`,e.ownerId===void 0?void 0:`owner=${r(e.ownerId)}`,e.spaceId===void 0?void 0:`space=${r(e.spaceId)}`].filter(e=>e!==void 0);if(t.length===0)throw TypeError(`Wow-Scope names a tenant, an owner or a space.`);return t.join(`, `)}function a(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>{let i=t[r];if(i===void 0||i===``)throw TypeError(`The path ${e} needs ${r}.`);return encodeURIComponent(i)})}function o(e){if(!e)return``;let t=new URLSearchParams;for(let[n,r]of Object.entries(e))r!==void 0&&t.append(n,String(r));let n=t.toString();return n?`?${n}`:``}async function s(r,a){let s=a.options??{},c={};for(let[e,t]of Object.entries({...a.headers,...s.scope===void 0?{}:{[n.SCOPE]:i(s.scope)},...s.space===void 0?{}:{[n.SPACE]:s.space},...s.headers}))t!==void 0&&(c[e]=t);let l=`${r.basePath??``}${a.path}${o(a.query)}`;try{return await(r.fetcher??t.fetcher).fetch(l,{method:a.method,headers:c,...a.body===void 0?{}:{body:a.body},...s.signal===void 0?{}:{signal:s.signal}})}catch(t){let n=t?.exchange?.response;if(a.notModified&&n?.status===304)return n;throw await e.toWowProblemError(t)??t}}async function c(e){return await e.json()}function l(e){let t=e.headers.get(n.ETAG);return t===null?void 0:t.replace(/^W\//,``).replace(/"/g,``)}exports.WowV10Headers=n,exports.entityTag=l,exports.expandPath=a,exports.formatScope=i,exports.json=c,exports.send=s;
2
+ //# sourceMappingURL=http.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.cjs","names":["defaultFetcher","toWowProblemError","require_problem","_ahoo_wang_fetcher","WowV10Headers","quote","value","formatScope","members","scope","member","expandPath","path","params","name","queryString","query","text","send","options","call","headers","url","client","error","response","json","entityTag","tag"],"sources":["../../src/v10/http.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type Fetcher, fetcher as defaultFetcher } from '@ahoo-wang/fetcher';\nimport { toWowProblemError } from './problem.js';\n\n/**\n * The request headers of a Wow V10 service's public port (decisions D95,\n * D96, D98, D99).\n */\nexport const WowV10Headers = {\n /** The caller's id of the request: a retry with the same one is deduplicated. */\n REQUEST_ID: 'Wow-Request-Id',\n /** The wait plan (decision D99). */\n WAIT: 'Wow-Wait',\n /** How long to wait: `500ms`, `10s` or an ISO-8601 duration. */\n WAIT_TIMEOUT: 'Wow-Wait-Timeout',\n /** The scope to act in, for a caller allowed to act across scopes (decision D95). */\n SCOPE: 'Wow-Scope',\n /** The space, among the caller's own, to act in (decision D96). */\n SPACE: 'Wow-Space',\n /** The expected version of the aggregate, as an entity tag. */\n IF_MATCH: 'If-Match',\n /** The version, or descriptor version, a read already holds. */\n IF_NONE_MATCH: 'If-None-Match',\n /** The version of a state read, or of a query descriptor. */\n ETAG: 'ETag',\n /** The seconds after which a failed request may be retried. */\n RETRY_AFTER: 'Retry-After',\n} as const;\n\n/** How a V10 client reaches its service. */\nexport interface WowClientOptions {\n /**\n * The fetcher requests go through, with its base URL and interceptors\n * (authentication, say); the default fetcher when absent.\n */\n readonly fetcher?: Fetcher;\n /** A path put before every route, such as a gateway's prefix. */\n readonly basePath?: string;\n}\n\n/**\n * The scope a caller allowed to act across scopes acts in: the `Wow-Scope`\n * header (decision D95).\n */\nexport interface TargetScope {\n readonly tenantId?: string;\n readonly ownerId?: string;\n readonly spaceId?: string;\n}\n\nfunction quote(value: string): string {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * A target scope as the `Wow-Scope` header spells it, an RFC 8941\n * dictionary: `tenant=\"t1\", owner=\"u1\", space=\"s1\"`.\n *\n * @param scope - The scope; at least one of its members is set\n */\nexport function formatScope(scope: TargetScope): string {\n const members = [\n scope.tenantId === undefined\n ? undefined\n : `tenant=${quote(scope.tenantId)}`,\n scope.ownerId === undefined ? undefined : `owner=${quote(scope.ownerId)}`,\n scope.spaceId === undefined ? undefined : `space=${quote(scope.spaceId)}`,\n ].filter(member => member !== undefined);\n if (members.length === 0) {\n throw new TypeError('Wow-Scope names a tenant, an owner or a space.');\n }\n return members.join(', ');\n}\n\n/** What every V10 request may carry beside its own parameters. */\nexport interface RequestOptions {\n /** The scope to act in (`Wow-Scope`), for a caller allowed to. */\n readonly scope?: TargetScope;\n /** The space to act in (`Wow-Space`), among the caller's own. */\n readonly space?: string;\n /** More headers: the request facts the service records, say. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Cancels the request. */\n readonly signal?: AbortSignal;\n}\n\n/** One request of a V10 client. */\nexport interface Call {\n readonly method: 'GET' | 'POST' | 'DELETE';\n readonly path: string;\n readonly query?: Readonly<Record<string, string | number | undefined>>;\n readonly headers?: Readonly<Record<string, string | undefined>>;\n readonly body?: unknown;\n readonly options?: RequestOptions;\n /** Answers a 304 rather than rejecting with it. */\n readonly notModified?: boolean;\n}\n\n/** `{name}` segments of `path` filled from `params`, each encoded. */\nexport function expandPath(\n path: string,\n params: Readonly<Record<string, string>>,\n): string {\n return path.replace(/\\{([^}]+)\\}/g, (segment, name: string) => {\n const value = params[name];\n if (value === undefined || value === '') {\n throw new TypeError(`The path ${path} needs ${name}.`);\n }\n return encodeURIComponent(value);\n });\n}\n\nfunction queryString(\n query: Readonly<Record<string, string | number | undefined>> | undefined,\n): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [name, value] of Object.entries(query)) {\n if (value !== undefined) params.append(name, String(value));\n }\n const text = params.toString();\n return text ? `?${text}` : '';\n}\n\n/**\n * Sends one request through the client's fetcher and answers its response;\n * a response that is not 2xx rejects with a {@link WowProblemError}.\n *\n * @param client - The client's options\n * @param call - The request\n */\nexport async function send(\n client: WowClientOptions,\n call: Call,\n): Promise<Response> {\n const options = call.options ?? {};\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries({\n ...call.headers,\n ...(options.scope === undefined\n ? {}\n : { [WowV10Headers.SCOPE]: formatScope(options.scope) }),\n ...(options.space === undefined\n ? {}\n : { [WowV10Headers.SPACE]: options.space }),\n ...options.headers,\n })) {\n if (value !== undefined) headers[name] = value;\n }\n const url = `${client.basePath ?? ''}${call.path}${queryString(call.query)}`;\n try {\n return await (client.fetcher ?? defaultFetcher).fetch(url, {\n method: call.method,\n headers,\n ...(call.body === undefined ? {} : { body: call.body as object }),\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n });\n } catch (error) {\n const response = (error as { exchange?: { response?: Response } })?.exchange\n ?.response;\n if (call.notModified && response?.status === 304) return response;\n throw (await toWowProblemError(error)) ?? error;\n }\n}\n\n/** The JSON body of a 2xx response. */\nexport async function json<T>(response: Response): Promise<T> {\n return (await response.json()) as T;\n}\n\n/** The entity tag of a response without its quotes or weak marker. */\nexport function entityTag(response: Response): string | undefined {\n const tag = response.headers.get(WowV10Headers.ETAG);\n return tag === null ? undefined : tag.replace(/^W\\//, '').replace(/\"/g, '');\n}\n"],"mappings":"qEAoBA,IAAaI,EAAgB,CAE3B,WAAY,iBAEZ,KAAM,WAEN,aAAc,mBAEd,MAAO,YAEP,MAAO,YAEP,SAAU,WAEV,cAAe,gBAEf,KAAM,OAEN,YAAa,aACf,EAuBA,SAASC,EAAM,EAAuB,CACpC,MAAO,IAAIC,EAAM,QAAQ,MAAO,MAAM,CAAC,CAAC,QAAQ,KAAM,KAAK,EAAE,EAC/D,CAQA,SAAgBC,EAAY,EAA4B,CACtD,IAAMC,EAAU,CACdC,EAAM,WAAa,IAAA,GACf,IAAA,GACA,UAAUJ,EAAMI,EAAM,QAAQ,IAClCA,EAAM,UAAY,IAAA,GAAY,IAAA,GAAY,SAASJ,EAAMI,EAAM,OAAO,IACtEA,EAAM,UAAY,IAAA,GAAY,IAAA,GAAY,SAASJ,EAAMI,EAAM,OAAO,GACxE,CAAC,CAAC,OAAO,GAAUC,IAAW,IAAA,EAAS,EACvC,GAAIF,EAAQ,SAAW,EACrB,MAAU,UAAU,gDAAgD,EAEtE,OAAOA,EAAQ,KAAK,IAAI,CAC1B,CA2BA,SAAgBG,EACd,EACA,EACQ,CACR,OAAOC,EAAK,QAAQ,gBAAiB,EAAS,IAAiB,CAC7D,IAAMN,EAAQO,EAAOC,GACrB,GAAIR,IAAU,IAAA,IAAaA,IAAU,GACnC,MAAU,UAAU,YAAYM,EAAK,SAASE,EAAK,EAAE,EAEvD,OAAO,mBAAmBR,CAAK,CACjC,CAAC,CACH,CAEA,SAASS,EACP,EACQ,CACR,GAAI,CAACC,EAAO,MAAO,GACnB,IAAMH,EAAS,IAAI,gBACnB,IAAK,GAAM,CAACC,EAAMR,KAAU,OAAO,QAAQU,CAAK,EAC1CV,IAAU,IAAA,IAAWO,EAAO,OAAOC,EAAM,OAAOR,CAAK,CAAC,EAE5D,IAAMW,EAAOJ,EAAO,SAAS,EAC7B,OAAOI,EAAO,IAAIA,IAAS,EAC7B,CASA,eAAsBC,EACpB,EACA,EACmB,CACnB,IAAMC,EAAUC,EAAK,SAAW,CAAC,EAC3BC,EAAkC,CAAC,EACzC,IAAK,GAAM,CAACP,EAAMR,KAAU,OAAO,QAAQ,CACzC,GAAGc,EAAK,QACR,GAAID,EAAQ,QAAU,IAAA,GAClB,CAAC,EACD,EAAGf,EAAc,OAAQG,EAAYY,EAAQ,KAAK,CAAE,EACxD,GAAIA,EAAQ,QAAU,IAAA,GAClB,CAAC,EACD,EAAGf,EAAc,OAAQe,EAAQ,KAAM,EAC3C,GAAGA,EAAQ,OACb,CAAC,EACKb,IAAU,IAAA,KAAW,EAAQQ,GAAQR,GAE3C,IAAMgB,EAAM,GAAGC,EAAO,UAAY,KAAKH,EAAK,OAAOL,EAAYK,EAAK,KAAK,IACzE,GAAI,CACF,OAAO,MAAOG,EAAO,SAAWvB,EAAAA,QAAAA,CAAgB,MAAMsB,EAAK,CACzD,OAAQF,EAAK,OACb,UACA,GAAIA,EAAK,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAK,IAAe,EAC/D,GAAID,EAAQ,SAAW,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQA,EAAQ,MAAO,CACnE,CAAC,CACH,OAASK,EAAO,CACd,IAAMC,EAAYD,GAAkD,UAChE,SACJ,GAAIJ,EAAK,aAAeK,GAAU,SAAW,IAAK,OAAOA,EACzD,MAAO,MAAMxB,EAAAA,kBAAkBuB,CAAK,GAAMA,CAC5C,CACF,CAGA,eAAsBE,EAAQ,EAAgC,CAC5D,OAAQ,MAAMD,EAAS,KAAK,CAC9B,CAGA,SAAgBE,EAAU,EAAwC,CAChE,IAAMC,EAAMH,EAAS,QAAQ,IAAIrB,EAAc,IAAI,EACnD,OAAOwB,IAAQ,KAAO,IAAA,GAAYA,EAAI,QAAQ,OAAQ,EAAE,CAAC,CAAC,QAAQ,KAAM,EAAE,CAC5E"}
@@ -0,0 +1,87 @@
1
+ import { Fetcher } from '@ahoo-wang/fetcher';
2
+ /**
3
+ * The request headers of a Wow V10 service's public port (decisions D95,
4
+ * D96, D98, D99).
5
+ */
6
+ export declare const WowV10Headers: {
7
+ /** The caller's id of the request: a retry with the same one is deduplicated. */
8
+ readonly REQUEST_ID: "Wow-Request-Id";
9
+ /** The wait plan (decision D99). */
10
+ readonly WAIT: "Wow-Wait";
11
+ /** How long to wait: `500ms`, `10s` or an ISO-8601 duration. */
12
+ readonly WAIT_TIMEOUT: "Wow-Wait-Timeout";
13
+ /** The scope to act in, for a caller allowed to act across scopes (decision D95). */
14
+ readonly SCOPE: "Wow-Scope";
15
+ /** The space, among the caller's own, to act in (decision D96). */
16
+ readonly SPACE: "Wow-Space";
17
+ /** The expected version of the aggregate, as an entity tag. */
18
+ readonly IF_MATCH: "If-Match";
19
+ /** The version, or descriptor version, a read already holds. */
20
+ readonly IF_NONE_MATCH: "If-None-Match";
21
+ /** The version of a state read, or of a query descriptor. */
22
+ readonly ETAG: "ETag";
23
+ /** The seconds after which a failed request may be retried. */
24
+ readonly RETRY_AFTER: "Retry-After";
25
+ };
26
+ /** How a V10 client reaches its service. */
27
+ export interface WowClientOptions {
28
+ /**
29
+ * The fetcher requests go through, with its base URL and interceptors
30
+ * (authentication, say); the default fetcher when absent.
31
+ */
32
+ readonly fetcher?: Fetcher;
33
+ /** A path put before every route, such as a gateway's prefix. */
34
+ readonly basePath?: string;
35
+ }
36
+ /**
37
+ * The scope a caller allowed to act across scopes acts in: the `Wow-Scope`
38
+ * header (decision D95).
39
+ */
40
+ export interface TargetScope {
41
+ readonly tenantId?: string;
42
+ readonly ownerId?: string;
43
+ readonly spaceId?: string;
44
+ }
45
+ /**
46
+ * A target scope as the `Wow-Scope` header spells it, an RFC 8941
47
+ * dictionary: `tenant="t1", owner="u1", space="s1"`.
48
+ *
49
+ * @param scope - The scope; at least one of its members is set
50
+ */
51
+ export declare function formatScope(scope: TargetScope): string;
52
+ /** What every V10 request may carry beside its own parameters. */
53
+ export interface RequestOptions {
54
+ /** The scope to act in (`Wow-Scope`), for a caller allowed to. */
55
+ readonly scope?: TargetScope;
56
+ /** The space to act in (`Wow-Space`), among the caller's own. */
57
+ readonly space?: string;
58
+ /** More headers: the request facts the service records, say. */
59
+ readonly headers?: Readonly<Record<string, string>>;
60
+ /** Cancels the request. */
61
+ readonly signal?: AbortSignal;
62
+ }
63
+ /** One request of a V10 client. */
64
+ export interface Call {
65
+ readonly method: 'GET' | 'POST' | 'DELETE';
66
+ readonly path: string;
67
+ readonly query?: Readonly<Record<string, string | number | undefined>>;
68
+ readonly headers?: Readonly<Record<string, string | undefined>>;
69
+ readonly body?: unknown;
70
+ readonly options?: RequestOptions;
71
+ /** Answers a 304 rather than rejecting with it. */
72
+ readonly notModified?: boolean;
73
+ }
74
+ /** `{name}` segments of `path` filled from `params`, each encoded. */
75
+ export declare function expandPath(path: string, params: Readonly<Record<string, string>>): string;
76
+ /**
77
+ * Sends one request through the client's fetcher and answers its response;
78
+ * a response that is not 2xx rejects with a {@link WowProblemError}.
79
+ *
80
+ * @param client - The client's options
81
+ * @param call - The request
82
+ */
83
+ export declare function send(client: WowClientOptions, call: Call): Promise<Response>;
84
+ /** The JSON body of a 2xx response. */
85
+ export declare function json<T>(response: Response): Promise<T>;
86
+ /** The entity tag of a response without its quotes or weak marker. */
87
+ export declare function entityTag(response: Response): string | undefined;
@@ -0,0 +1,87 @@
1
+ import { Fetcher } from '@ahoo-wang/fetcher';
2
+ /**
3
+ * The request headers of a Wow V10 service's public port (decisions D95,
4
+ * D96, D98, D99).
5
+ */
6
+ export declare const WowV10Headers: {
7
+ /** The caller's id of the request: a retry with the same one is deduplicated. */
8
+ readonly REQUEST_ID: "Wow-Request-Id";
9
+ /** The wait plan (decision D99). */
10
+ readonly WAIT: "Wow-Wait";
11
+ /** How long to wait: `500ms`, `10s` or an ISO-8601 duration. */
12
+ readonly WAIT_TIMEOUT: "Wow-Wait-Timeout";
13
+ /** The scope to act in, for a caller allowed to act across scopes (decision D95). */
14
+ readonly SCOPE: "Wow-Scope";
15
+ /** The space, among the caller's own, to act in (decision D96). */
16
+ readonly SPACE: "Wow-Space";
17
+ /** The expected version of the aggregate, as an entity tag. */
18
+ readonly IF_MATCH: "If-Match";
19
+ /** The version, or descriptor version, a read already holds. */
20
+ readonly IF_NONE_MATCH: "If-None-Match";
21
+ /** The version of a state read, or of a query descriptor. */
22
+ readonly ETAG: "ETag";
23
+ /** The seconds after which a failed request may be retried. */
24
+ readonly RETRY_AFTER: "Retry-After";
25
+ };
26
+ /** How a V10 client reaches its service. */
27
+ export interface WowClientOptions {
28
+ /**
29
+ * The fetcher requests go through, with its base URL and interceptors
30
+ * (authentication, say); the default fetcher when absent.
31
+ */
32
+ readonly fetcher?: Fetcher;
33
+ /** A path put before every route, such as a gateway's prefix. */
34
+ readonly basePath?: string;
35
+ }
36
+ /**
37
+ * The scope a caller allowed to act across scopes acts in: the `Wow-Scope`
38
+ * header (decision D95).
39
+ */
40
+ export interface TargetScope {
41
+ readonly tenantId?: string;
42
+ readonly ownerId?: string;
43
+ readonly spaceId?: string;
44
+ }
45
+ /**
46
+ * A target scope as the `Wow-Scope` header spells it, an RFC 8941
47
+ * dictionary: `tenant="t1", owner="u1", space="s1"`.
48
+ *
49
+ * @param scope - The scope; at least one of its members is set
50
+ */
51
+ export declare function formatScope(scope: TargetScope): string;
52
+ /** What every V10 request may carry beside its own parameters. */
53
+ export interface RequestOptions {
54
+ /** The scope to act in (`Wow-Scope`), for a caller allowed to. */
55
+ readonly scope?: TargetScope;
56
+ /** The space to act in (`Wow-Space`), among the caller's own. */
57
+ readonly space?: string;
58
+ /** More headers: the request facts the service records, say. */
59
+ readonly headers?: Readonly<Record<string, string>>;
60
+ /** Cancels the request. */
61
+ readonly signal?: AbortSignal;
62
+ }
63
+ /** One request of a V10 client. */
64
+ export interface Call {
65
+ readonly method: 'GET' | 'POST' | 'DELETE';
66
+ readonly path: string;
67
+ readonly query?: Readonly<Record<string, string | number | undefined>>;
68
+ readonly headers?: Readonly<Record<string, string | undefined>>;
69
+ readonly body?: unknown;
70
+ readonly options?: RequestOptions;
71
+ /** Answers a 304 rather than rejecting with it. */
72
+ readonly notModified?: boolean;
73
+ }
74
+ /** `{name}` segments of `path` filled from `params`, each encoded. */
75
+ export declare function expandPath(path: string, params: Readonly<Record<string, string>>): string;
76
+ /**
77
+ * Sends one request through the client's fetcher and answers its response;
78
+ * a response that is not 2xx rejects with a {@link WowProblemError}.
79
+ *
80
+ * @param client - The client's options
81
+ * @param call - The request
82
+ */
83
+ export declare function send(client: WowClientOptions, call: Call): Promise<Response>;
84
+ /** The JSON body of a 2xx response. */
85
+ export declare function json<T>(response: Response): Promise<T>;
86
+ /** The entity tag of a response without its quotes or weak marker. */
87
+ export declare function entityTag(response: Response): string | undefined;
@@ -0,0 +1,73 @@
1
+ import { toWowProblemError as e } from "./problem.es.js";
2
+ import { fetcher as t } from "@ahoo-wang/fetcher";
3
+ //#region src/v10/http.ts
4
+ var n = {
5
+ REQUEST_ID: "Wow-Request-Id",
6
+ WAIT: "Wow-Wait",
7
+ WAIT_TIMEOUT: "Wow-Wait-Timeout",
8
+ SCOPE: "Wow-Scope",
9
+ SPACE: "Wow-Space",
10
+ IF_MATCH: "If-Match",
11
+ IF_NONE_MATCH: "If-None-Match",
12
+ ETAG: "ETag",
13
+ RETRY_AFTER: "Retry-After"
14
+ };
15
+ function r(e) {
16
+ return `"${e.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
17
+ }
18
+ function i(e) {
19
+ let t = [
20
+ e.tenantId === void 0 ? void 0 : `tenant=${r(e.tenantId)}`,
21
+ e.ownerId === void 0 ? void 0 : `owner=${r(e.ownerId)}`,
22
+ e.spaceId === void 0 ? void 0 : `space=${r(e.spaceId)}`
23
+ ].filter((e) => e !== void 0);
24
+ if (t.length === 0) throw TypeError("Wow-Scope names a tenant, an owner or a space.");
25
+ return t.join(", ");
26
+ }
27
+ function a(e, t) {
28
+ return e.replace(/\{([^}]+)\}/g, (n, r) => {
29
+ let i = t[r];
30
+ if (i === void 0 || i === "") throw TypeError(`The path ${e} needs ${r}.`);
31
+ return encodeURIComponent(i);
32
+ });
33
+ }
34
+ function o(e) {
35
+ if (!e) return "";
36
+ let t = new URLSearchParams();
37
+ for (let [n, r] of Object.entries(e)) r !== void 0 && t.append(n, String(r));
38
+ let n = t.toString();
39
+ return n ? `?${n}` : "";
40
+ }
41
+ async function s(r, a) {
42
+ let s = a.options ?? {}, c = {};
43
+ for (let [e, t] of Object.entries({
44
+ ...a.headers,
45
+ ...s.scope === void 0 ? {} : { [n.SCOPE]: i(s.scope) },
46
+ ...s.space === void 0 ? {} : { [n.SPACE]: s.space },
47
+ ...s.headers
48
+ })) t !== void 0 && (c[e] = t);
49
+ let l = `${r.basePath ?? ""}${a.path}${o(a.query)}`;
50
+ try {
51
+ return await (r.fetcher ?? t).fetch(l, {
52
+ method: a.method,
53
+ headers: c,
54
+ ...a.body === void 0 ? {} : { body: a.body },
55
+ ...s.signal === void 0 ? {} : { signal: s.signal }
56
+ });
57
+ } catch (t) {
58
+ let n = t?.exchange?.response;
59
+ if (a.notModified && n?.status === 304) return n;
60
+ throw await e(t) ?? t;
61
+ }
62
+ }
63
+ async function c(e) {
64
+ return await e.json();
65
+ }
66
+ function l(e) {
67
+ let t = e.headers.get(n.ETAG);
68
+ return t === null ? void 0 : t.replace(/^W\//, "").replace(/"/g, "");
69
+ }
70
+ //#endregion
71
+ export { n as WowV10Headers, l as entityTag, a as expandPath, i as formatScope, c as json, s as send };
72
+
73
+ //# sourceMappingURL=http.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.es.js","names":["defaultFetcher","WowV10Headers","quote","value","formatScope","members","scope","member","expandPath","path","params","name","queryString","query","text","send","options","call","headers","url","client","fetcher","error","response","toWowProblemError","json","entityTag","tag"],"sources":["../../src/v10/http.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type Fetcher, fetcher as defaultFetcher } from '@ahoo-wang/fetcher';\nimport { toWowProblemError } from './problem.js';\n\n/**\n * The request headers of a Wow V10 service's public port (decisions D95,\n * D96, D98, D99).\n */\nexport const WowV10Headers = {\n /** The caller's id of the request: a retry with the same one is deduplicated. */\n REQUEST_ID: 'Wow-Request-Id',\n /** The wait plan (decision D99). */\n WAIT: 'Wow-Wait',\n /** How long to wait: `500ms`, `10s` or an ISO-8601 duration. */\n WAIT_TIMEOUT: 'Wow-Wait-Timeout',\n /** The scope to act in, for a caller allowed to act across scopes (decision D95). */\n SCOPE: 'Wow-Scope',\n /** The space, among the caller's own, to act in (decision D96). */\n SPACE: 'Wow-Space',\n /** The expected version of the aggregate, as an entity tag. */\n IF_MATCH: 'If-Match',\n /** The version, or descriptor version, a read already holds. */\n IF_NONE_MATCH: 'If-None-Match',\n /** The version of a state read, or of a query descriptor. */\n ETAG: 'ETag',\n /** The seconds after which a failed request may be retried. */\n RETRY_AFTER: 'Retry-After',\n} as const;\n\n/** How a V10 client reaches its service. */\nexport interface WowClientOptions {\n /**\n * The fetcher requests go through, with its base URL and interceptors\n * (authentication, say); the default fetcher when absent.\n */\n readonly fetcher?: Fetcher;\n /** A path put before every route, such as a gateway's prefix. */\n readonly basePath?: string;\n}\n\n/**\n * The scope a caller allowed to act across scopes acts in: the `Wow-Scope`\n * header (decision D95).\n */\nexport interface TargetScope {\n readonly tenantId?: string;\n readonly ownerId?: string;\n readonly spaceId?: string;\n}\n\nfunction quote(value: string): string {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * A target scope as the `Wow-Scope` header spells it, an RFC 8941\n * dictionary: `tenant=\"t1\", owner=\"u1\", space=\"s1\"`.\n *\n * @param scope - The scope; at least one of its members is set\n */\nexport function formatScope(scope: TargetScope): string {\n const members = [\n scope.tenantId === undefined\n ? undefined\n : `tenant=${quote(scope.tenantId)}`,\n scope.ownerId === undefined ? undefined : `owner=${quote(scope.ownerId)}`,\n scope.spaceId === undefined ? undefined : `space=${quote(scope.spaceId)}`,\n ].filter(member => member !== undefined);\n if (members.length === 0) {\n throw new TypeError('Wow-Scope names a tenant, an owner or a space.');\n }\n return members.join(', ');\n}\n\n/** What every V10 request may carry beside its own parameters. */\nexport interface RequestOptions {\n /** The scope to act in (`Wow-Scope`), for a caller allowed to. */\n readonly scope?: TargetScope;\n /** The space to act in (`Wow-Space`), among the caller's own. */\n readonly space?: string;\n /** More headers: the request facts the service records, say. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Cancels the request. */\n readonly signal?: AbortSignal;\n}\n\n/** One request of a V10 client. */\nexport interface Call {\n readonly method: 'GET' | 'POST' | 'DELETE';\n readonly path: string;\n readonly query?: Readonly<Record<string, string | number | undefined>>;\n readonly headers?: Readonly<Record<string, string | undefined>>;\n readonly body?: unknown;\n readonly options?: RequestOptions;\n /** Answers a 304 rather than rejecting with it. */\n readonly notModified?: boolean;\n}\n\n/** `{name}` segments of `path` filled from `params`, each encoded. */\nexport function expandPath(\n path: string,\n params: Readonly<Record<string, string>>,\n): string {\n return path.replace(/\\{([^}]+)\\}/g, (segment, name: string) => {\n const value = params[name];\n if (value === undefined || value === '') {\n throw new TypeError(`The path ${path} needs ${name}.`);\n }\n return encodeURIComponent(value);\n });\n}\n\nfunction queryString(\n query: Readonly<Record<string, string | number | undefined>> | undefined,\n): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [name, value] of Object.entries(query)) {\n if (value !== undefined) params.append(name, String(value));\n }\n const text = params.toString();\n return text ? `?${text}` : '';\n}\n\n/**\n * Sends one request through the client's fetcher and answers its response;\n * a response that is not 2xx rejects with a {@link WowProblemError}.\n *\n * @param client - The client's options\n * @param call - The request\n */\nexport async function send(\n client: WowClientOptions,\n call: Call,\n): Promise<Response> {\n const options = call.options ?? {};\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries({\n ...call.headers,\n ...(options.scope === undefined\n ? {}\n : { [WowV10Headers.SCOPE]: formatScope(options.scope) }),\n ...(options.space === undefined\n ? {}\n : { [WowV10Headers.SPACE]: options.space }),\n ...options.headers,\n })) {\n if (value !== undefined) headers[name] = value;\n }\n const url = `${client.basePath ?? ''}${call.path}${queryString(call.query)}`;\n try {\n return await (client.fetcher ?? defaultFetcher).fetch(url, {\n method: call.method,\n headers,\n ...(call.body === undefined ? {} : { body: call.body as object }),\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n });\n } catch (error) {\n const response = (error as { exchange?: { response?: Response } })?.exchange\n ?.response;\n if (call.notModified && response?.status === 304) return response;\n throw (await toWowProblemError(error)) ?? error;\n }\n}\n\n/** The JSON body of a 2xx response. */\nexport async function json<T>(response: Response): Promise<T> {\n return (await response.json()) as T;\n}\n\n/** The entity tag of a response without its quotes or weak marker. */\nexport function entityTag(response: Response): string | undefined {\n const tag = response.headers.get(WowV10Headers.ETAG);\n return tag === null ? undefined : tag.replace(/^W\\//, '').replace(/\"/g, '');\n}\n"],"mappings":";;;AAoBA,IAAaC,IAAgB;CAE3B,YAAY;CAEZ,MAAM;CAEN,cAAc;CAEd,OAAO;CAEP,OAAO;CAEP,UAAU;CAEV,eAAe;CAEf,MAAM;CAEN,aAAa;AACf;AAuBA,SAASC,EAAM,GAAuB;CACpC,OAAO,IAAIC,EAAM,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAK,EAAE;AAC/D;AAQA,SAAgBC,EAAY,GAA4B;CACtD,IAAMC,IAAU;EACdC,EAAM,aAAa,KAAA,IACf,KAAA,IACA,UAAUJ,EAAMI,EAAM,QAAQ;EAClCA,EAAM,YAAY,KAAA,IAAY,KAAA,IAAY,SAASJ,EAAMI,EAAM,OAAO;EACtEA,EAAM,YAAY,KAAA,IAAY,KAAA,IAAY,SAASJ,EAAMI,EAAM,OAAO;CACxE,CAAC,CAAC,QAAO,MAAUC,MAAW,KAAA,CAAS;CACvC,IAAIF,EAAQ,WAAW,GACrB,MAAU,UAAU,gDAAgD;CAEtE,OAAOA,EAAQ,KAAK,IAAI;AAC1B;AA2BA,SAAgBG,EACd,GACA,GACQ;CACR,OAAOC,EAAK,QAAQ,iBAAiB,GAAS,MAAiB;EAC7D,IAAMN,IAAQO,EAAOC;EACrB,IAAIR,MAAU,KAAA,KAAaA,MAAU,IACnC,MAAU,UAAU,YAAYM,EAAK,SAASE,EAAK,EAAE;EAEvD,OAAO,mBAAmBR,CAAK;CACjC,CAAC;AACH;AAEA,SAASS,EACP,GACQ;CACR,IAAI,CAACC,GAAO,OAAO;CACnB,IAAMH,IAAS,IAAI,gBAAgB;CACnC,KAAK,IAAM,CAACC,GAAMR,MAAU,OAAO,QAAQU,CAAK,GAC9C,AAAIV,MAAU,KAAA,KAAWO,EAAO,OAAOC,GAAM,OAAOR,CAAK,CAAC;CAE5D,IAAMW,IAAOJ,EAAO,SAAS;CAC7B,OAAOI,IAAO,IAAIA,MAAS;AAC7B;AASA,eAAsBC,EACpB,GACA,GACmB;CACnB,IAAMC,IAAUC,EAAK,WAAW,CAAC,GAC3BC,IAAkC,CAAC;CACzC,KAAK,IAAM,CAACP,GAAMR,MAAU,OAAO,QAAQ;EACzC,GAAGc,EAAK;EACR,GAAID,EAAQ,UAAU,KAAA,IAClB,CAAC,IACD,GAAGf,EAAc,QAAQG,EAAYY,EAAQ,KAAK,EAAE;EACxD,GAAIA,EAAQ,UAAU,KAAA,IAClB,CAAC,IACD,GAAGf,EAAc,QAAQe,EAAQ,MAAM;EAC3C,GAAGA,EAAQ;CACb,CAAC,GACC,AAAIb,MAAU,KAAA,MAAW,EAAQQ,KAAQR;CAE3C,IAAMgB,IAAM,GAAGC,EAAO,YAAY,KAAKH,EAAK,OAAOL,EAAYK,EAAK,KAAK;CACzE,IAAI;EACF,OAAO,OAAOG,EAAO,WAAWpB,EAAAA,CAAgB,MAAMmB,GAAK;GACzD,QAAQF,EAAK;GACb;GACA,GAAIA,EAAK,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAMA,EAAK,KAAe;GAC/D,GAAID,EAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQA,EAAQ,OAAO;EACnE,CAAC;CACH,SAASM,GAAO;EACd,IAAMC,IAAYD,GAAkD,UAChE;EACJ,IAAIL,EAAK,eAAeM,GAAU,WAAW,KAAK,OAAOA;EACzD,MAAO,MAAMC,EAAkBF,CAAK,KAAMA;CAC5C;AACF;AAGA,eAAsBG,EAAQ,GAAgC;CAC5D,OAAQ,MAAMF,EAAS,KAAK;AAC9B;AAGA,SAAgBG,EAAU,GAAwC;CAChE,IAAMC,IAAMJ,EAAS,QAAQ,IAAItB,EAAc,IAAI;CACnD,OAAO0B,MAAQ,OAAO,KAAA,IAAYA,EAAI,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,MAAM,EAAE;AAC5E"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@ahoo-wang/wow-client/v10`: the client of a Wow V10 service's public
3
+ * routes — commands with `Wow-Wait` and their event streams, state reads and
4
+ * traces, the snapshot, event and dataset query routes, the Manifest, and
5
+ * RFC 9457 problems as {@link WowProblemError}s with retry hints. Code
6
+ * `wow-generator` generates from a Manifest builds on it.
7
+ *
8
+ * It is additive: the root entry keeps serving Wow 9.x services. Build
9
+ * queries with the DSL of `@ahoo-wang/wow-client/dsl`.
10
+ */
11
+ export { type ApplyTags, CommandGateway, type CommandOptions, commandSegment, type CreateCommandOptions, type LifecycleCommand, LifecycleCommands, type TransferOwner, type TransferSpace, } from './commands.cjs';
12
+ export { formatScope, type RequestOptions, type TargetScope, type WowClientOptions, WowV10Headers, } from './http.cjs';
13
+ export { type AggregateManifest, type CommandManifest, type ContextManifest, type Creation, type ErrorManifest, type EventManifest, fetchManifest, type Manifest, MANIFEST_FORMAT, type QueryManifest, type RouteManifest, type SubscriptionManifest, } from './manifest.cjs';
14
+ export * from './wire.cjs';
15
+ export { FRAMEWORK_ERROR_PREFIX, type FrameworkErrorCode, FrameworkErrorCodes, isProblem, parseRetryAfter, type Problem, PROBLEM_TYPE_PREFIX, readProblem, type RetryHint, retryHintOf, toWowProblemError, WowProblemError, } from './problem.cjs';
16
+ export { type CountQuery, type CountResult, DatasetClient, type DescriptorResult, EventQueryClient, type PagedQuery, type PagedResult, QueryModelClient, queryPath, SnapshotQueryClient, type TotalMode, } from './queries.cjs';
17
+ export { StateClient, type StateReadOptions, type StateReadResult, type StateTraceOptions, } from './state.cjs';
18
+ export { type CommandResultStream } from './streams.cjs';
19
+ export { formatHop, formatWaitPlan, formatWaitTimeout, SNAPSHOT_SUBSCRIPTION, wait, type WaitOptions, } from './wait.cjs';
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@ahoo-wang/wow-client/v10`: the client of a Wow V10 service's public
3
+ * routes — commands with `Wow-Wait` and their event streams, state reads and
4
+ * traces, the snapshot, event and dataset query routes, the Manifest, and
5
+ * RFC 9457 problems as {@link WowProblemError}s with retry hints. Code
6
+ * `wow-generator` generates from a Manifest builds on it.
7
+ *
8
+ * It is additive: the root entry keeps serving Wow 9.x services. Build
9
+ * queries with the DSL of `@ahoo-wang/wow-client/dsl`.
10
+ */
11
+ export { type ApplyTags, CommandGateway, type CommandOptions, commandSegment, type CreateCommandOptions, type LifecycleCommand, LifecycleCommands, type TransferOwner, type TransferSpace, } from './commands.js';
12
+ export { formatScope, type RequestOptions, type TargetScope, type WowClientOptions, WowV10Headers, } from './http.js';
13
+ export { type AggregateManifest, type CommandManifest, type ContextManifest, type Creation, type ErrorManifest, type EventManifest, fetchManifest, type Manifest, MANIFEST_FORMAT, type QueryManifest, type RouteManifest, type SubscriptionManifest, } from './manifest.js';
14
+ export * from './wire.js';
15
+ export { FRAMEWORK_ERROR_PREFIX, type FrameworkErrorCode, FrameworkErrorCodes, isProblem, parseRetryAfter, type Problem, PROBLEM_TYPE_PREFIX, readProblem, type RetryHint, retryHintOf, toWowProblemError, WowProblemError, } from './problem.js';
16
+ export { type CountQuery, type CountResult, DatasetClient, type DescriptorResult, EventQueryClient, type PagedQuery, type PagedResult, QueryModelClient, queryPath, SnapshotQueryClient, type TotalMode, } from './queries.js';
17
+ export { StateClient, type StateReadOptions, type StateReadResult, type StateTraceOptions, } from './state.js';
18
+ export { type CommandResultStream } from './streams.js';
19
+ export { formatHop, formatWaitPlan, formatWaitTimeout, SNAPSHOT_SUBSCRIPTION, wait, type WaitOptions, } from './wait.js';
@@ -0,0 +1,2 @@
1
+ const e=require("./http.cjs");var t=1;async function n(t={},n){return e.json(await e.send(t,{method:`GET`,path:`/wow/manifest`,options:n}))}exports.MANIFEST_FORMAT=t,exports.fetchManifest=n;
2
+ //# sourceMappingURL=manifest.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.cjs","names":["json","send","require_http","MANIFEST_FORMAT","fetchManifest","client"],"sources":["../../src/v10/manifest.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 json,\n type RequestOptions,\n send,\n type WowClientOptions,\n} from './http.js';\nimport type { Ownership } from './wire.js';\n\n/** A route of the Manifest: a method and a path, `{id}` the aggregate id. */\nexport interface RouteManifest {\n readonly method: string;\n readonly path: string;\n}\n\n/** Whether a command creates its aggregate. */\nexport type Creation = 'NONE' | 'REQUIRED' | 'ALLOWED';\n\n/** A command of an aggregate (decisions D104, D176, D182). */\nexport interface CommandManifest {\n readonly name: string;\n readonly aliases?: readonly string[];\n /** `#/$defs/<key>`. */\n readonly schema: string;\n readonly creation?: Creation;\n readonly produces?: readonly string[];\n readonly routes?: readonly RouteManifest[];\n readonly mounted?: boolean;\n readonly transformsTo?: readonly string[];\n}\n\n/** An event of an aggregate and its revision. */\nexport interface EventManifest {\n readonly name: string;\n readonly aliases?: readonly string[];\n readonly revision?: number;\n readonly schema: string;\n}\n\n/** A query model of an aggregate: `snapshot` or `events` (decision D128). */\nexport interface QueryManifest {\n readonly model: string;\n readonly routes?: readonly RouteManifest[];\n}\n\n/** An aggregate of a bounded context. */\nexport interface AggregateManifest {\n readonly name: string;\n readonly description?: string;\n readonly state: { readonly schema: string; readonly fingerprint?: string };\n readonly snapshot?: { readonly enabled?: boolean };\n readonly commands?: readonly CommandManifest[];\n readonly events?: readonly EventManifest[];\n readonly lifecycle?: readonly string[];\n readonly queries?: readonly QueryManifest[];\n readonly schedules?: readonly string[];\n readonly ownership?: Ownership;\n}\n\n/** A subscription of a bounded context (design 04 §1). */\nexport interface SubscriptionManifest {\n /** `processor.function`, as a `handled` hop names it. */\n readonly name: string;\n readonly kind: 'PROJECTION' | 'REACTOR' | 'SAGA';\n readonly source: {\n readonly context?: string;\n readonly aggregates?: readonly string[];\n readonly events?: readonly string[];\n };\n readonly derives?: readonly string[];\n readonly rejected?: readonly string[];\n readonly committed?: readonly string[];\n readonly [property: string]: unknown;\n}\n\n/** An error code and the HTTP status it is answered with. */\nexport interface ErrorManifest {\n readonly code: string;\n readonly status: number;\n readonly description?: string;\n}\n\n/** A bounded context of the Manifest. */\nexport interface ContextManifest {\n readonly name: string;\n readonly description?: string;\n readonly aggregates?: readonly AggregateManifest[];\n readonly subscriptions?: readonly SubscriptionManifest[];\n readonly published?: readonly {\n readonly aggregate: string;\n readonly topic: string;\n readonly includeState?: boolean;\n }[];\n readonly errors?: readonly ErrorManifest[];\n}\n\n/**\n * A service's Manifest (decisions D17, D73–D76): its contexts, aggregates,\n * commands, events, routes and error codes, and the JSON Schemas they refer\n * to under `$defs`. `wow-generator` generates typed clients from it.\n */\nexport interface Manifest {\n readonly format: number;\n readonly service?: { readonly name: string; readonly version?: string };\n readonly contexts: readonly ContextManifest[];\n readonly errors?: readonly ErrorManifest[];\n readonly $defs?: Readonly<Record<string, unknown>>;\n}\n\n/** The format of the Manifest this client reads. */\nexport const MANIFEST_FORMAT = 1;\n\n/**\n * The service's Manifest, `GET /wow/manifest`, authorized as any API.\n *\n * @param client - How the service is reached\n * @param options - Headers and cancellation\n */\nexport async function fetchManifest(\n client: WowClientOptions = {},\n options?: RequestOptions,\n): Promise<Manifest> {\n return json<Manifest>(\n await send(client, { method: 'GET', path: '/wow/manifest', options }),\n );\n}\n"],"mappings":"8BA0HA,IAAaG,EAAkB,EAQ/B,eAAsBC,EACpB,EAA2B,CAAC,EAC5B,EACmB,CACnB,OAAOJ,EAAAA,KACL,MAAMC,EAAAA,KAAKI,EAAQ,CAAE,OAAQ,MAAO,KAAM,gBAAiB,SAAQ,CAAC,CACtE,CACF"}
@@ -0,0 +1,109 @@
1
+ import { RequestOptions, WowClientOptions } from './http.cjs';
2
+ import { Ownership } from './wire.cjs';
3
+ /** A route of the Manifest: a method and a path, `{id}` the aggregate id. */
4
+ export interface RouteManifest {
5
+ readonly method: string;
6
+ readonly path: string;
7
+ }
8
+ /** Whether a command creates its aggregate. */
9
+ export type Creation = 'NONE' | 'REQUIRED' | 'ALLOWED';
10
+ /** A command of an aggregate (decisions D104, D176, D182). */
11
+ export interface CommandManifest {
12
+ readonly name: string;
13
+ readonly aliases?: readonly string[];
14
+ /** `#/$defs/<key>`. */
15
+ readonly schema: string;
16
+ readonly creation?: Creation;
17
+ readonly produces?: readonly string[];
18
+ readonly routes?: readonly RouteManifest[];
19
+ readonly mounted?: boolean;
20
+ readonly transformsTo?: readonly string[];
21
+ }
22
+ /** An event of an aggregate and its revision. */
23
+ export interface EventManifest {
24
+ readonly name: string;
25
+ readonly aliases?: readonly string[];
26
+ readonly revision?: number;
27
+ readonly schema: string;
28
+ }
29
+ /** A query model of an aggregate: `snapshot` or `events` (decision D128). */
30
+ export interface QueryManifest {
31
+ readonly model: string;
32
+ readonly routes?: readonly RouteManifest[];
33
+ }
34
+ /** An aggregate of a bounded context. */
35
+ export interface AggregateManifest {
36
+ readonly name: string;
37
+ readonly description?: string;
38
+ readonly state: {
39
+ readonly schema: string;
40
+ readonly fingerprint?: string;
41
+ };
42
+ readonly snapshot?: {
43
+ readonly enabled?: boolean;
44
+ };
45
+ readonly commands?: readonly CommandManifest[];
46
+ readonly events?: readonly EventManifest[];
47
+ readonly lifecycle?: readonly string[];
48
+ readonly queries?: readonly QueryManifest[];
49
+ readonly schedules?: readonly string[];
50
+ readonly ownership?: Ownership;
51
+ }
52
+ /** A subscription of a bounded context (design 04 §1). */
53
+ export interface SubscriptionManifest {
54
+ /** `processor.function`, as a `handled` hop names it. */
55
+ readonly name: string;
56
+ readonly kind: 'PROJECTION' | 'REACTOR' | 'SAGA';
57
+ readonly source: {
58
+ readonly context?: string;
59
+ readonly aggregates?: readonly string[];
60
+ readonly events?: readonly string[];
61
+ };
62
+ readonly derives?: readonly string[];
63
+ readonly rejected?: readonly string[];
64
+ readonly committed?: readonly string[];
65
+ readonly [property: string]: unknown;
66
+ }
67
+ /** An error code and the HTTP status it is answered with. */
68
+ export interface ErrorManifest {
69
+ readonly code: string;
70
+ readonly status: number;
71
+ readonly description?: string;
72
+ }
73
+ /** A bounded context of the Manifest. */
74
+ export interface ContextManifest {
75
+ readonly name: string;
76
+ readonly description?: string;
77
+ readonly aggregates?: readonly AggregateManifest[];
78
+ readonly subscriptions?: readonly SubscriptionManifest[];
79
+ readonly published?: readonly {
80
+ readonly aggregate: string;
81
+ readonly topic: string;
82
+ readonly includeState?: boolean;
83
+ }[];
84
+ readonly errors?: readonly ErrorManifest[];
85
+ }
86
+ /**
87
+ * A service's Manifest (decisions D17, D73–D76): its contexts, aggregates,
88
+ * commands, events, routes and error codes, and the JSON Schemas they refer
89
+ * to under `$defs`. `wow-generator` generates typed clients from it.
90
+ */
91
+ export interface Manifest {
92
+ readonly format: number;
93
+ readonly service?: {
94
+ readonly name: string;
95
+ readonly version?: string;
96
+ };
97
+ readonly contexts: readonly ContextManifest[];
98
+ readonly errors?: readonly ErrorManifest[];
99
+ readonly $defs?: Readonly<Record<string, unknown>>;
100
+ }
101
+ /** The format of the Manifest this client reads. */
102
+ export declare const MANIFEST_FORMAT = 1;
103
+ /**
104
+ * The service's Manifest, `GET /wow/manifest`, authorized as any API.
105
+ *
106
+ * @param client - How the service is reached
107
+ * @param options - Headers and cancellation
108
+ */
109
+ export declare function fetchManifest(client?: WowClientOptions, options?: RequestOptions): Promise<Manifest>;