@virtocommerce/test-automation-framework 0.0.0-stage → 0.1.0-alpha.1

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/.biome/formatter.json +11 -0
  2. package/.biome/imports.json +52 -0
  3. package/.biome/preset.json +4 -0
  4. package/.biome/rules.json +45 -0
  5. package/.claude/agents/qa-automation-expert.md +119 -0
  6. package/.claude/agents/qa-coverage.md +96 -0
  7. package/.claude/agents/qa-explorer.md +112 -0
  8. package/.claude/agents/qa-healer.md +88 -0
  9. package/.claude/agents/qa-judge.md +102 -0
  10. package/.claude/agents/qa-planner.md +104 -0
  11. package/.claude/agents/qa-reviewer.md +121 -0
  12. package/.claude/checks/browser-secrets.mts +107 -0
  13. package/.claude/checks/contract.mts +469 -0
  14. package/.claude/checks/expectation-guard.mts +665 -0
  15. package/.claude/checks/explore-extractors.mts +4 -0
  16. package/.claude/checks/judge-verdict.mts +165 -0
  17. package/.claude/checks/project-facts.mts +491 -0
  18. package/.claude/checks/prove-fails.mts +770 -0
  19. package/.claude/checks/rank-gaps.mts +177 -0
  20. package/.claude/checks/readonly-shell.mts +740 -0
  21. package/.claude/checks/reconcile-run.mts +270 -0
  22. package/.claude/checks/scan-prompts.mts +351 -0
  23. package/.claude/checks/stand.mts +45 -0
  24. package/.claude/checks/test-duration.mts +134 -0
  25. package/.claude/checks/test-shape.mts +224 -0
  26. package/.claude/checks/ticket-card.mts +195 -0
  27. package/.claude/commands/qa-coverage.md +13 -0
  28. package/.claude/commands/qa-explore.md +17 -0
  29. package/.claude/commands/qa-heal.md +44 -0
  30. package/.claude/commands/qa-implement.md +60 -0
  31. package/.claude/commands/qa-plan.md +55 -0
  32. package/.claude/commands/qa-review.md +90 -0
  33. package/.claude/commands/qa.md +156 -0
  34. package/.claude/hooks/readonly-shell.mts +65 -0
  35. package/.claude/settings.json +15 -0
  36. package/.claude/skills/coverage-analysis/SKILL.md +107 -0
  37. package/.claude/skills/create-graphql-layer/SKILL.md +159 -0
  38. package/.claude/skills/create-ui-layer/SKILL.md +189 -0
  39. package/.claude/skills/explore-api/SKILL.md +74 -0
  40. package/.claude/skills/explore-frontend/SKILL.md +85 -0
  41. package/.claude/skills/framework-rules/SKILL.md +189 -0
  42. package/.claude/skills/heal-tests/SKILL.md +197 -0
  43. package/.claude/skills/heal-tests/guard-recipe.md +53 -0
  44. package/.claude/skills/judge-criteria/SKILL.md +40 -0
  45. package/.claude/skills/judge-criteria/coverage.md +9 -0
  46. package/.claude/skills/judge-criteria/expert.md +23 -0
  47. package/.claude/skills/judge-criteria/explorer.md +9 -0
  48. package/.claude/skills/judge-criteria/healer.md +13 -0
  49. package/.claude/skills/judge-criteria/planner.md +12 -0
  50. package/.claude/skills/plan-implementation/SKILL.md +82 -0
  51. package/.claude/skills/plan-implementation/contract-template.md +72 -0
  52. package/.claude/skills/plan-test-strategy/SKILL.md +100 -0
  53. package/.claude/skills/project-facts/SKILL.md +130 -0
  54. package/.claude/skills/read-change/SKILL.md +64 -0
  55. package/.claude/skills/read-ticket/SKILL.md +63 -0
  56. package/.claude/skills/read-ticket/providers.md +58 -0
  57. package/.claude/skills/review-pr/SKILL.md +152 -0
  58. package/.claude/skills/review-test-code/SKILL.md +208 -0
  59. package/.claude/skills/write-e2e-test/SKILL.md +175 -0
  60. package/.claude/skills/write-graphql-test/SKILL.md +158 -0
  61. package/.claude/skills/write-rest-api-test/SKILL.md +182 -0
  62. package/.claude/skills/write-security-test/SKILL.md +253 -0
  63. package/.qa/project.example.json +71 -0
  64. package/CHANGELOG.md +1 -0
  65. package/LICENSE +12 -0
  66. package/README.md +53 -2
  67. package/bin/install-qa-agents.mjs +94 -0
  68. package/dist/auth/credentials.d.ts +10 -0
  69. package/dist/auth/credentials.js +2 -0
  70. package/dist/auth/credentials.js.map +1 -0
  71. package/dist/auth/frontend-browser-sessions.d.ts +71 -0
  72. package/dist/auth/frontend-browser-sessions.js +130 -0
  73. package/dist/auth/frontend-browser-sessions.js.map +1 -0
  74. package/dist/auth/index.d.ts +9 -0
  75. package/dist/auth/index.js +5 -0
  76. package/dist/auth/index.js.map +1 -0
  77. package/dist/auth/platform-browser-sessions.d.ts +47 -0
  78. package/dist/auth/platform-browser-sessions.js +92 -0
  79. package/dist/auth/platform-browser-sessions.js.map +1 -0
  80. package/dist/auth/sign-in-lock.d.ts +14 -0
  81. package/dist/auth/sign-in-lock.js +70 -0
  82. package/dist/auth/sign-in-lock.js.map +1 -0
  83. package/dist/auth/storage-state.d.ts +3 -0
  84. package/dist/auth/storage-state.js +2 -0
  85. package/dist/auth/storage-state.js.map +1 -0
  86. package/dist/auth/token-client.d.ts +82 -0
  87. package/dist/auth/token-client.js +111 -0
  88. package/dist/auth/token-client.js.map +1 -0
  89. package/dist/auth/token-manager.d.ts +67 -0
  90. package/dist/auth/token-manager.js +138 -0
  91. package/dist/auth/token-manager.js.map +1 -0
  92. package/dist/core/default-reporters.d.ts +31 -0
  93. package/dist/core/default-reporters.js +36 -0
  94. package/dist/core/default-reporters.js.map +1 -0
  95. package/dist/core/default-use.d.ts +28 -0
  96. package/dist/core/default-use.js +25 -0
  97. package/dist/core/default-use.js.map +1 -0
  98. package/dist/core/env.d.ts +24 -0
  99. package/dist/core/env.js +33 -0
  100. package/dist/core/env.js.map +1 -0
  101. package/dist/core/error-message.d.ts +10 -0
  102. package/dist/core/error-message.js +13 -0
  103. package/dist/core/error-message.js.map +1 -0
  104. package/dist/core/index.d.ts +16 -0
  105. package/dist/core/index.js +11 -0
  106. package/dist/core/index.js.map +1 -0
  107. package/dist/core/is-ci.d.ts +14 -0
  108. package/dist/core/is-ci.js +18 -0
  109. package/dist/core/is-ci.js.map +1 -0
  110. package/dist/core/parse-env.d.ts +13 -0
  111. package/dist/core/parse-env.js +21 -0
  112. package/dist/core/parse-env.js.map +1 -0
  113. package/dist/core/projects.d.ts +24 -0
  114. package/dist/core/projects.js +33 -0
  115. package/dist/core/projects.js.map +1 -0
  116. package/dist/core/run-options.d.ts +31 -0
  117. package/dist/core/run-options.js +43 -0
  118. package/dist/core/run-options.js.map +1 -0
  119. package/dist/core/secret.d.ts +105 -0
  120. package/dist/core/secret.js +167 -0
  121. package/dist/core/secret.js.map +1 -0
  122. package/dist/core/string-schemas.d.ts +39 -0
  123. package/dist/core/string-schemas.js +56 -0
  124. package/dist/core/string-schemas.js.map +1 -0
  125. package/dist/core/url-path.d.ts +7 -0
  126. package/dist/core/url-path.js +2 -0
  127. package/dist/core/url-path.js.map +1 -0
  128. package/dist/dataset/collection.d.ts +44 -0
  129. package/dist/dataset/collection.js +76 -0
  130. package/dist/dataset/collection.js.map +1 -0
  131. package/dist/dataset/index.d.ts +11 -0
  132. package/dist/dataset/index.js +6 -0
  133. package/dist/dataset/index.js.map +1 -0
  134. package/dist/dataset/load-dataset.d.ts +39 -0
  135. package/dist/dataset/load-dataset.js +62 -0
  136. package/dist/dataset/load-dataset.js.map +1 -0
  137. package/dist/dataset/manifest.d.ts +77 -0
  138. package/dist/dataset/manifest.js +10 -0
  139. package/dist/dataset/manifest.js.map +1 -0
  140. package/dist/dataset/placeholders.d.ts +66 -0
  141. package/dist/dataset/placeholders.js +87 -0
  142. package/dist/dataset/placeholders.js.map +1 -0
  143. package/dist/dataset/seed-collection.d.ts +53 -0
  144. package/dist/dataset/seed-collection.js +115 -0
  145. package/dist/dataset/seed-collection.js.map +1 -0
  146. package/dist/dataset/seed-dataset.d.ts +70 -0
  147. package/dist/dataset/seed-dataset.js +138 -0
  148. package/dist/dataset/seed-dataset.js.map +1 -0
  149. package/dist/dataset/seed-events.d.ts +81 -0
  150. package/dist/dataset/seed-events.js +2 -0
  151. package/dist/dataset/seed-events.js.map +1 -0
  152. package/dist/dataset/seed-requests.d.ts +102 -0
  153. package/dist/dataset/seed-requests.js +160 -0
  154. package/dist/dataset/seed-requests.js.map +1 -0
  155. package/dist/dataset/seed-scope.d.ts +39 -0
  156. package/dist/dataset/seed-scope.js +67 -0
  157. package/dist/dataset/seed-scope.js.map +1 -0
  158. package/dist/fixtures/default-fixtures.d.ts +93 -0
  159. package/dist/fixtures/default-fixtures.js +105 -0
  160. package/dist/fixtures/default-fixtures.js.map +1 -0
  161. package/dist/fixtures/index.d.ts +2 -0
  162. package/dist/fixtures/index.js +2 -0
  163. package/dist/fixtures/index.js.map +1 -0
  164. package/dist/graphql/graphql-client.d.ts +78 -0
  165. package/dist/graphql/graphql-client.js +83 -0
  166. package/dist/graphql/graphql-client.js.map +1 -0
  167. package/dist/graphql/graphql-codegen.d.ts +56 -0
  168. package/dist/graphql/graphql-codegen.js +42 -0
  169. package/dist/graphql/graphql-codegen.js.map +1 -0
  170. package/dist/graphql/graphql-error.d.ts +54 -0
  171. package/dist/graphql/graphql-error.js +74 -0
  172. package/dist/graphql/graphql-error.js.map +1 -0
  173. package/dist/graphql/index.d.ts +6 -0
  174. package/dist/graphql/index.js +4 -0
  175. package/dist/graphql/index.js.map +1 -0
  176. package/dist/http/authentication.d.ts +16 -0
  177. package/dist/http/authentication.js +2 -0
  178. package/dist/http/authentication.js.map +1 -0
  179. package/dist/http/http-client.d.ts +110 -0
  180. package/dist/http/http-client.js +237 -0
  181. package/dist/http/http-client.js.map +1 -0
  182. package/dist/http/http-error.d.ts +26 -0
  183. package/dist/http/http-error.js +34 -0
  184. package/dist/http/http-error.js.map +1 -0
  185. package/dist/http/http-method.d.ts +2 -0
  186. package/dist/http/http-method.js +2 -0
  187. package/dist/http/http-method.js.map +1 -0
  188. package/dist/http/http-response.d.ts +137 -0
  189. package/dist/http/http-response.js +166 -0
  190. package/dist/http/http-response.js.map +1 -0
  191. package/dist/http/index.d.ts +7 -0
  192. package/dist/http/index.js +4 -0
  193. package/dist/http/index.js.map +1 -0
  194. package/dist/http/request-options.d.ts +62 -0
  195. package/dist/http/request-options.js +2 -0
  196. package/dist/http/request-options.js.map +1 -0
  197. package/dist/modules/index.d.ts +2 -0
  198. package/dist/modules/index.js +2 -0
  199. package/dist/modules/index.js.map +1 -0
  200. package/dist/modules/installed-modules.d.ts +86 -0
  201. package/dist/modules/installed-modules.js +135 -0
  202. package/dist/modules/installed-modules.js.map +1 -0
  203. package/docs/README.md +43 -0
  204. package/docs/concepts/areas.md +38 -0
  205. package/docs/concepts/auth.md +92 -0
  206. package/docs/concepts/config.md +102 -0
  207. package/docs/concepts/dataset.md +183 -0
  208. package/docs/concepts/environment.md +54 -0
  209. package/docs/concepts/fixtures.md +109 -0
  210. package/docs/concepts/graphql.md +76 -0
  211. package/docs/concepts/http.md +88 -0
  212. package/docs/concepts/modules.md +63 -0
  213. package/docs/concepts/secrets.md +50 -0
  214. package/docs/contributing/architecture.md +67 -0
  215. package/docs/contributing/conventions.md +39 -0
  216. package/docs/contributing/documentation.md +37 -0
  217. package/docs/contributing/releasing.md +76 -0
  218. package/docs/examples/auth.ts +20 -0
  219. package/docs/examples/config.ts +36 -0
  220. package/docs/examples/dataset.ts +70 -0
  221. package/docs/examples/environment.ts +8 -0
  222. package/docs/examples/fixtures.ts +41 -0
  223. package/docs/examples/getting-started.ts +22 -0
  224. package/docs/examples/graphql-codegen.ts +9 -0
  225. package/docs/examples/graphql.ts +32 -0
  226. package/docs/examples/http.ts +18 -0
  227. package/docs/examples/modules.ts +19 -0
  228. package/docs/examples/secrets.ts +11 -0
  229. package/docs/examples/tsconfig.json +10 -0
  230. package/docs/getting-started.md +106 -0
  231. package/docs/guides/generating-types.md +75 -0
  232. package/docs/guides/qa-agents.md +66 -0
  233. package/package.json +156 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-method.js","sourceRoot":"","sources":["../../src/http/http-method.ts"],"names":[],"mappings":"","sourcesContent":["/** The HTTP methods that an {@link HttpClient} sends. */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n"]}
@@ -0,0 +1,137 @@
1
+ import type { output, ZodType } from "zod";
2
+ import type { HttpMethod } from "./http-method.ts";
3
+ import { HttpError } from "./http-error.ts";
4
+ /** The options of {@link HttpResponse.optionalJson} and {@link HttpResponse.parseOptional}. */
5
+ export interface OptionalBodyOptions {
6
+ /**
7
+ * Whether a 404 status also means that there is no body, for a server that answers a missing record with 404. The
8
+ * default is `false`, because a server also returns 404 for an unknown route.
9
+ */
10
+ readonly allow404?: boolean | undefined;
11
+ }
12
+ /** The data that an {@link HttpResponse} is created from. */
13
+ export type HttpResponseInit = {
14
+ /** The HTTP method of the request. */
15
+ readonly method: HttpMethod;
16
+ /** The URL that was requested, with secrets masked. */
17
+ readonly url: string;
18
+ /** The status of the response, such as 200. */
19
+ readonly status: number;
20
+ /** The status text of the response, such as `OK`. It can be empty. */
21
+ readonly statusText: string;
22
+ /** The response headers by lowercase name, such as `content-type`. */
23
+ readonly headers: Readonly<Record<string, string>>;
24
+ /** The response body as text. */
25
+ readonly text: string;
26
+ };
27
+ /**
28
+ * Represents a response whose body has already been read.
29
+ *
30
+ * @remarks
31
+ * {@link HttpResponse.json} and {@link HttpResponse.parse} require a success status (2xx), and
32
+ * {@link HttpResponse.errorJson} requires any other status, so a missed status check cannot hide a failure. Each
33
+ * failure is an {@link HttpError} that quotes the body with secrets masked.
34
+ *
35
+ * @example
36
+ * const store = response.parse(StoreSchema);
37
+ * expect(rejected.status).toBe(400);
38
+ * expect(rejected.errorJson()).toMatchObject({ errors: [expect.anything()] });
39
+ */
40
+ export declare class HttpResponse implements HttpResponseInit {
41
+ #private;
42
+ /** The HTTP method of the request. */
43
+ readonly method: HttpMethod;
44
+ /** The URL that was requested, with secrets masked. */
45
+ readonly url: string;
46
+ /** The status of the response, such as 200. */
47
+ readonly status: number;
48
+ /** The status text of the response, such as `OK`. It can be empty. */
49
+ readonly statusText: string;
50
+ /** The response headers by lowercase name, such as `content-type`. */
51
+ readonly headers: Readonly<Record<string, string>>;
52
+ /** The response body as text. */
53
+ readonly text: string;
54
+ /**
55
+ * Creates a response from data that has already been read.
56
+ *
57
+ * @param init - The request method and URL, and the status, headers and body of the response.
58
+ */
59
+ constructor(init: HttpResponseInit);
60
+ /** Gets a value that indicates whether the status is a success status (2xx). */
61
+ get ok(): boolean;
62
+ /**
63
+ * Ensures that the status is a success status (2xx). Use it for responses whose body does not matter.
64
+ *
65
+ * @returns This response.
66
+ * @throws {HttpError} The status is not a success status.
67
+ */
68
+ expectOk(): this;
69
+ /**
70
+ * Returns the body of a success response, parsed as JSON.
71
+ *
72
+ * @remarks
73
+ * `T` is not checked at run time. To validate the body, use {@link HttpResponse.parse}.
74
+ *
75
+ * @returns The parsed body.
76
+ * @throws {HttpError} The status is not a success status (2xx), or the body is not valid JSON.
77
+ */
78
+ json<T = unknown>(): T;
79
+ /**
80
+ * Returns the body of a success response, validated by a schema, with the schema's defaults and transformations
81
+ * applied.
82
+ *
83
+ * @param schema - The schema that describes the body.
84
+ * @returns The validated body.
85
+ * @throws {HttpError} The status is not a success status (2xx), the body is not valid JSON, or the body does not
86
+ * match the schema. The message lists every mismatch.
87
+ */
88
+ parse<S extends ZodType>(schema: S): output<S>;
89
+ /**
90
+ * Returns the body of a success response, parsed as JSON, or `undefined` when there is no body: the body is empty or
91
+ * `null`, or, with `allow404`, the status is 404.
92
+ *
93
+ * @remarks
94
+ * `T` is not checked at run time. To validate the body, use {@link HttpResponse.parseOptional}.
95
+ *
96
+ * @example
97
+ * const order = (await client.get(`/api/orders/${id}`)).optionalJson<Order>({ allow404: true });
98
+ *
99
+ * @param options - Whether a 404 status means that there is no body.
100
+ * @returns The parsed body, or `undefined` when there is none.
101
+ * @throws {HttpError} The status is not a success status (2xx), or the body is not valid JSON.
102
+ */
103
+ optionalJson<T = unknown>(options?: OptionalBodyOptions): T | undefined;
104
+ /**
105
+ * Returns the body of a success response validated by a schema, or `undefined` when there is no body: the body is
106
+ * empty or `null`, or, with `allow404`, the status is 404.
107
+ *
108
+ * @param schema - The schema that describes the body.
109
+ * @param options - Whether a 404 status means that there is no body.
110
+ * @returns The validated body, or `undefined` when there is none.
111
+ * @throws {HttpError} The status is not a success status (2xx), the body is not valid JSON, or the body does not
112
+ * match the schema. The message lists every mismatch.
113
+ */
114
+ parseOptional<S extends ZodType>(schema: S, options?: OptionalBodyOptions): output<S> | undefined;
115
+ /**
116
+ * Returns the body of an error response, parsed as JSON. Use it in negative tests.
117
+ *
118
+ * @remarks
119
+ * `T` is not checked at run time.
120
+ *
121
+ * @returns The parsed body.
122
+ * @throws {HttpError} The status is a success status (2xx), or the body is not valid JSON.
123
+ */
124
+ errorJson<T = unknown>(): T;
125
+ /**
126
+ * Creates an error that describes this response, for a check that the response methods do not make, such as a
127
+ * success response whose body reports a failure.
128
+ *
129
+ * @remarks
130
+ * The message has the method, the URL without its query, the status, the reason and the body, shortened to 1,000
131
+ * characters. Secrets are masked.
132
+ *
133
+ * @param reason - Why the response is not what the caller expected.
134
+ * @returns The error, to throw.
135
+ */
136
+ toError(reason?: string): HttpError;
137
+ }
@@ -0,0 +1,166 @@
1
+ import { prettifyError } from "zod";
2
+ import { maskSecrets } from "../core/index.js";
3
+ import { HttpError } from "./http-error.js";
4
+ const MAX_BODY_LENGTH = 1_000;
5
+ /**
6
+ * Represents a response whose body has already been read.
7
+ *
8
+ * @remarks
9
+ * {@link HttpResponse.json} and {@link HttpResponse.parse} require a success status (2xx), and
10
+ * {@link HttpResponse.errorJson} requires any other status, so a missed status check cannot hide a failure. Each
11
+ * failure is an {@link HttpError} that quotes the body with secrets masked.
12
+ *
13
+ * @example
14
+ * const store = response.parse(StoreSchema);
15
+ * expect(rejected.status).toBe(400);
16
+ * expect(rejected.errorJson()).toMatchObject({ errors: [expect.anything()] });
17
+ */
18
+ export class HttpResponse {
19
+ /** The HTTP method of the request. */
20
+ method;
21
+ /** The URL that was requested, with secrets masked. */
22
+ url;
23
+ /** The status of the response, such as 200. */
24
+ status;
25
+ /** The status text of the response, such as `OK`. It can be empty. */
26
+ statusText;
27
+ /** The response headers by lowercase name, such as `content-type`. */
28
+ headers;
29
+ /** The response body as text. */
30
+ text;
31
+ /**
32
+ * Creates a response from data that has already been read.
33
+ *
34
+ * @param init - The request method and URL, and the status, headers and body of the response.
35
+ */
36
+ constructor(init) {
37
+ this.method = init.method;
38
+ this.url = init.url;
39
+ this.status = init.status;
40
+ this.statusText = init.statusText;
41
+ this.headers = init.headers;
42
+ this.text = init.text;
43
+ }
44
+ /** Gets a value that indicates whether the status is a success status (2xx). */
45
+ get ok() {
46
+ return this.status >= 200 && this.status < 300;
47
+ }
48
+ /**
49
+ * Ensures that the status is a success status (2xx). Use it for responses whose body does not matter.
50
+ *
51
+ * @returns This response.
52
+ * @throws {HttpError} The status is not a success status.
53
+ */
54
+ expectOk() {
55
+ if (!this.ok) {
56
+ throw this.toError();
57
+ }
58
+ return this;
59
+ }
60
+ /**
61
+ * Returns the body of a success response, parsed as JSON.
62
+ *
63
+ * @remarks
64
+ * `T` is not checked at run time. To validate the body, use {@link HttpResponse.parse}.
65
+ *
66
+ * @returns The parsed body.
67
+ * @throws {HttpError} The status is not a success status (2xx), or the body is not valid JSON.
68
+ */
69
+ json() {
70
+ return this.expectOk().#parseText();
71
+ }
72
+ /**
73
+ * Returns the body of a success response, validated by a schema, with the schema's defaults and transformations
74
+ * applied.
75
+ *
76
+ * @param schema - The schema that describes the body.
77
+ * @returns The validated body.
78
+ * @throws {HttpError} The status is not a success status (2xx), the body is not valid JSON, or the body does not
79
+ * match the schema. The message lists every mismatch.
80
+ */
81
+ parse(schema) {
82
+ const result = schema.safeParse(this.json());
83
+ if (!result.success) {
84
+ throw this.toError(`unexpected response body:\n${prettifyError(result.error)}`);
85
+ }
86
+ return result.data;
87
+ }
88
+ /**
89
+ * Returns the body of a success response, parsed as JSON, or `undefined` when there is no body: the body is empty or
90
+ * `null`, or, with `allow404`, the status is 404.
91
+ *
92
+ * @remarks
93
+ * `T` is not checked at run time. To validate the body, use {@link HttpResponse.parseOptional}.
94
+ *
95
+ * @example
96
+ * const order = (await client.get(`/api/orders/${id}`)).optionalJson<Order>({ allow404: true });
97
+ *
98
+ * @param options - Whether a 404 status means that there is no body.
99
+ * @returns The parsed body, or `undefined` when there is none.
100
+ * @throws {HttpError} The status is not a success status (2xx), or the body is not valid JSON.
101
+ */
102
+ optionalJson(options = {}) {
103
+ return this.#hasNoBody(options) ? undefined : this.json();
104
+ }
105
+ /**
106
+ * Returns the body of a success response validated by a schema, or `undefined` when there is no body: the body is
107
+ * empty or `null`, or, with `allow404`, the status is 404.
108
+ *
109
+ * @param schema - The schema that describes the body.
110
+ * @param options - Whether a 404 status means that there is no body.
111
+ * @returns The validated body, or `undefined` when there is none.
112
+ * @throws {HttpError} The status is not a success status (2xx), the body is not valid JSON, or the body does not
113
+ * match the schema. The message lists every mismatch.
114
+ */
115
+ parseOptional(schema, options = {}) {
116
+ return this.#hasNoBody(options) ? undefined : this.parse(schema);
117
+ }
118
+ /**
119
+ * Returns the body of an error response, parsed as JSON. Use it in negative tests.
120
+ *
121
+ * @remarks
122
+ * `T` is not checked at run time.
123
+ *
124
+ * @returns The parsed body.
125
+ * @throws {HttpError} The status is a success status (2xx), or the body is not valid JSON.
126
+ */
127
+ errorJson() {
128
+ if (this.ok) {
129
+ throw this.toError("expected an error response");
130
+ }
131
+ return this.#parseText();
132
+ }
133
+ /**
134
+ * Creates an error that describes this response, for a check that the response methods do not make, such as a
135
+ * success response whose body reports a failure.
136
+ *
137
+ * @remarks
138
+ * The message has the method, the URL without its query, the status, the reason and the body, shortened to 1,000
139
+ * characters. Secrets are masked.
140
+ *
141
+ * @param reason - Why the response is not what the caller expected.
142
+ * @returns The error, to throw.
143
+ */
144
+ toError(reason) {
145
+ const summary = `${this.method} ${pathOf(this.url)} → ${this.status} ${this.statusText}`.trimEnd();
146
+ const text = maskSecrets(this.text);
147
+ const body = text.length > MAX_BODY_LENGTH ? `${text.slice(0, MAX_BODY_LENGTH)}... (${text.length} chars)` : text;
148
+ return new HttpError([reason ? `${summary}: ${reason}` : summary, body].filter(Boolean).join("\n"), this.status, this.text);
149
+ }
150
+ #hasNoBody({ allow404 = false }) {
151
+ return (allow404 && this.status === 404) || (this.ok && (this.text === "" || this.text === "null"));
152
+ }
153
+ #parseText() {
154
+ try {
155
+ return JSON.parse(this.text);
156
+ }
157
+ catch {
158
+ throw this.toError("response body is not valid JSON");
159
+ }
160
+ }
161
+ }
162
+ function pathOf(url) {
163
+ const parsed = URL.parse(url);
164
+ return parsed === null ? (url.split(/[?#]/)[0] ?? url) : `${parsed.origin}${parsed.pathname}`;
165
+ }
166
+ //# sourceMappingURL=http-response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-response.js","sourceRoot":"","sources":["../../src/http/http-response.ts"],"names":[],"mappings":"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","sourcesContent":["import type { output, ZodType } from \"zod\";\nimport type { HttpMethod } from \"./http-method.ts\";\n\nimport { prettifyError } from \"zod\";\n\nimport { maskSecrets } from \"@/core\";\n\nimport { HttpError } from \"./http-error.ts\";\n\nconst MAX_BODY_LENGTH = 1_000;\n\n/** The options of {@link HttpResponse.optionalJson} and {@link HttpResponse.parseOptional}. */\nexport interface OptionalBodyOptions {\n /**\n * Whether a 404 status also means that there is no body, for a server that answers a missing record with 404. The\n * default is `false`, because a server also returns 404 for an unknown route.\n */\n readonly allow404?: boolean | undefined;\n}\n\n/** The data that an {@link HttpResponse} is created from. */\nexport type HttpResponseInit = {\n /** The HTTP method of the request. */\n readonly method: HttpMethod;\n /** The URL that was requested, with secrets masked. */\n readonly url: string;\n /** The status of the response, such as 200. */\n readonly status: number;\n /** The status text of the response, such as `OK`. It can be empty. */\n readonly statusText: string;\n /** The response headers by lowercase name, such as `content-type`. */\n readonly headers: Readonly<Record<string, string>>;\n /** The response body as text. */\n readonly text: string;\n};\n\n/**\n * Represents a response whose body has already been read.\n *\n * @remarks\n * {@link HttpResponse.json} and {@link HttpResponse.parse} require a success status (2xx), and\n * {@link HttpResponse.errorJson} requires any other status, so a missed status check cannot hide a failure. Each\n * failure is an {@link HttpError} that quotes the body with secrets masked.\n *\n * @example\n * const store = response.parse(StoreSchema);\n * expect(rejected.status).toBe(400);\n * expect(rejected.errorJson()).toMatchObject({ errors: [expect.anything()] });\n */\nexport class HttpResponse implements HttpResponseInit {\n /** The HTTP method of the request. */\n readonly method: HttpMethod;\n /** The URL that was requested, with secrets masked. */\n readonly url: string;\n /** The status of the response, such as 200. */\n readonly status: number;\n /** The status text of the response, such as `OK`. It can be empty. */\n readonly statusText: string;\n /** The response headers by lowercase name, such as `content-type`. */\n readonly headers: Readonly<Record<string, string>>;\n /** The response body as text. */\n readonly text: string;\n\n /**\n * Creates a response from data that has already been read.\n *\n * @param init - The request method and URL, and the status, headers and body of the response.\n */\n constructor(init: HttpResponseInit) {\n this.method = init.method;\n this.url = init.url;\n this.status = init.status;\n this.statusText = init.statusText;\n this.headers = init.headers;\n this.text = init.text;\n }\n\n /** Gets a value that indicates whether the status is a success status (2xx). */\n get ok(): boolean {\n return this.status >= 200 && this.status < 300;\n }\n\n /**\n * Ensures that the status is a success status (2xx). Use it for responses whose body does not matter.\n *\n * @returns This response.\n * @throws {HttpError} The status is not a success status.\n */\n expectOk(): this {\n if (!this.ok) {\n throw this.toError();\n }\n return this;\n }\n\n /**\n * Returns the body of a success response, parsed as JSON.\n *\n * @remarks\n * `T` is not checked at run time. To validate the body, use {@link HttpResponse.parse}.\n *\n * @returns The parsed body.\n * @throws {HttpError} The status is not a success status (2xx), or the body is not valid JSON.\n */\n json<T = unknown>(): T {\n return this.expectOk().#parseText<T>();\n }\n\n /**\n * Returns the body of a success response, validated by a schema, with the schema's defaults and transformations\n * applied.\n *\n * @param schema - The schema that describes the body.\n * @returns The validated body.\n * @throws {HttpError} The status is not a success status (2xx), the body is not valid JSON, or the body does not\n * match the schema. The message lists every mismatch.\n */\n parse<S extends ZodType>(schema: S): output<S> {\n const result = schema.safeParse(this.json());\n if (!result.success) {\n throw this.toError(`unexpected response body:\\n${prettifyError(result.error)}`);\n }\n return result.data;\n }\n\n /**\n * Returns the body of a success response, parsed as JSON, or `undefined` when there is no body: the body is empty or\n * `null`, or, with `allow404`, the status is 404.\n *\n * @remarks\n * `T` is not checked at run time. To validate the body, use {@link HttpResponse.parseOptional}.\n *\n * @example\n * const order = (await client.get(`/api/orders/${id}`)).optionalJson<Order>({ allow404: true });\n *\n * @param options - Whether a 404 status means that there is no body.\n * @returns The parsed body, or `undefined` when there is none.\n * @throws {HttpError} The status is not a success status (2xx), or the body is not valid JSON.\n */\n optionalJson<T = unknown>(options: OptionalBodyOptions = {}): T | undefined {\n return this.#hasNoBody(options) ? undefined : this.json<T>();\n }\n\n /**\n * Returns the body of a success response validated by a schema, or `undefined` when there is no body: the body is\n * empty or `null`, or, with `allow404`, the status is 404.\n *\n * @param schema - The schema that describes the body.\n * @param options - Whether a 404 status means that there is no body.\n * @returns The validated body, or `undefined` when there is none.\n * @throws {HttpError} The status is not a success status (2xx), the body is not valid JSON, or the body does not\n * match the schema. The message lists every mismatch.\n */\n parseOptional<S extends ZodType>(schema: S, options: OptionalBodyOptions = {}): output<S> | undefined {\n return this.#hasNoBody(options) ? undefined : this.parse(schema);\n }\n\n /**\n * Returns the body of an error response, parsed as JSON. Use it in negative tests.\n *\n * @remarks\n * `T` is not checked at run time.\n *\n * @returns The parsed body.\n * @throws {HttpError} The status is a success status (2xx), or the body is not valid JSON.\n */\n errorJson<T = unknown>(): T {\n if (this.ok) {\n throw this.toError(\"expected an error response\");\n }\n return this.#parseText<T>();\n }\n\n /**\n * Creates an error that describes this response, for a check that the response methods do not make, such as a\n * success response whose body reports a failure.\n *\n * @remarks\n * The message has the method, the URL without its query, the status, the reason and the body, shortened to 1,000\n * characters. Secrets are masked.\n *\n * @param reason - Why the response is not what the caller expected.\n * @returns The error, to throw.\n */\n toError(reason?: string): HttpError {\n const summary = `${this.method} ${pathOf(this.url)} → ${this.status} ${this.statusText}`.trimEnd();\n const text = maskSecrets(this.text);\n const body = text.length > MAX_BODY_LENGTH ? `${text.slice(0, MAX_BODY_LENGTH)}... (${text.length} chars)` : text;\n return new HttpError(\n [reason ? `${summary}: ${reason}` : summary, body].filter(Boolean).join(\"\\n\"),\n this.status,\n this.text,\n );\n }\n\n #hasNoBody({ allow404 = false }: OptionalBodyOptions): boolean {\n return (allow404 && this.status === 404) || (this.ok && (this.text === \"\" || this.text === \"null\"));\n }\n\n #parseText<T>(): T {\n try {\n return JSON.parse(this.text) as T;\n } catch {\n throw this.toError(\"response body is not valid JSON\");\n }\n }\n}\n\nfunction pathOf(url: string): string {\n const parsed = URL.parse(url);\n return parsed === null ? (url.split(/[?#]/)[0] ?? url) : `${parsed.origin}${parsed.pathname}`;\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export type { Authentication } from "./authentication.ts";
2
+ export type { HttpMethod } from "./http-method.ts";
3
+ export type { HttpResponseInit, OptionalBodyOptions } from "./http-response.ts";
4
+ export type { FormBody, HeaderProvider, JsonBody, MultipartBody, MultipartFile, QueryParams, QueryValue, RequestBase, RequestHeaders, RequestOptions, } from "./request-options.ts";
5
+ export { HttpClient } from "./http-client.ts";
6
+ export { HttpError } from "./http-error.ts";
7
+ export { HttpResponse } from "./http-response.ts";
@@ -0,0 +1,4 @@
1
+ export { HttpClient } from "./http-client.js";
2
+ export { HttpError } from "./http-error.js";
3
+ export { HttpResponse } from "./http-response.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/http/index.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["export type { Authentication } from \"./authentication.ts\";\nexport type { HttpMethod } from \"./http-method.ts\";\nexport type { HttpResponseInit, OptionalBodyOptions } from \"./http-response.ts\";\nexport type {\n FormBody,\n HeaderProvider,\n JsonBody,\n MultipartBody,\n MultipartFile,\n QueryParams,\n QueryValue,\n RequestBase,\n RequestHeaders,\n RequestOptions,\n} from \"./request-options.ts\";\n\nexport { HttpClient } from \"./http-client.ts\";\nexport { HttpError } from \"./http-error.ts\";\nexport { HttpResponse } from \"./http-response.ts\";\n"]}
@@ -0,0 +1,62 @@
1
+ import type { Secret } from "../core/index.js";
2
+ /** A value of a query parameter. A {@link Secret} is revealed only when the request is sent. */
3
+ export type QueryValue = string | number | boolean | Secret;
4
+ /** The query parameters of a request. An array repeats the parameter, and `undefined` leaves it out. */
5
+ export type QueryParams = Readonly<Record<string, QueryValue | readonly QueryValue[] | undefined>>;
6
+ /** The headers of a request. Header names are case-insensitive, and each {@link Secret} is revealed only when sent. */
7
+ export type RequestHeaders = Readonly<Record<string, string | Secret>>;
8
+ /**
9
+ * Returns request headers. It is called for each request, so values that change, such as a renewed token, are picked
10
+ * up. Return tokens as {@link Secret} values to keep them masked.
11
+ */
12
+ export type HeaderProvider = () => Promise<RequestHeaders>;
13
+ /** A file in a multipart body. */
14
+ export interface MultipartFile {
15
+ /** The file name. */
16
+ readonly name: string;
17
+ /** The media type of the file, such as `text/plain`. */
18
+ readonly mimeType: string;
19
+ /** The content of the file. */
20
+ readonly buffer: Buffer;
21
+ }
22
+ /** The options that every request accepts, whatever its body. */
23
+ export interface RequestBase {
24
+ /** The query parameters, appended to the query of the path. */
25
+ readonly query?: QueryParams;
26
+ /** The headers of this request. They replace headers of the same name from the client. */
27
+ readonly headers?: RequestHeaders;
28
+ /** The time to wait for a response, in milliseconds. */
29
+ readonly timeoutMs?: number;
30
+ }
31
+ /** The options of a request with a JSON body, or with no body. */
32
+ export interface JsonBody {
33
+ /** A body sent as JSON, with the `application/json` content type. */
34
+ readonly json?: unknown;
35
+ /** Not allowed, because a request has at most one body. */
36
+ readonly form?: never;
37
+ /** Not allowed, because a request has at most one body. */
38
+ readonly multipart?: never;
39
+ }
40
+ /** The options of a request with a URL-encoded form body. */
41
+ export interface FormBody {
42
+ /** A body sent as URL-encoded form fields. */
43
+ readonly form: Readonly<Record<string, string | number | boolean | Secret>>;
44
+ /** Not allowed, because a request has at most one body. */
45
+ readonly json?: never;
46
+ /** Not allowed, because a request has at most one body. */
47
+ readonly multipart?: never;
48
+ }
49
+ /** The options of a request with a multipart body. */
50
+ export interface MultipartBody {
51
+ /** A body sent as multipart form data, with text fields and files. */
52
+ readonly multipart: Readonly<Record<string, string | MultipartFile | Secret>>;
53
+ /** Not allowed, because a request has at most one body. */
54
+ readonly json?: never;
55
+ /** Not allowed, because a request has at most one body. */
56
+ readonly form?: never;
57
+ }
58
+ /**
59
+ * The options of a request. A request has at most one body: `json`, `form` or `multipart`. Each {@link Secret} is
60
+ * revealed only when the request is sent.
61
+ */
62
+ export type RequestOptions = RequestBase & (JsonBody | FormBody | MultipartBody);
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=request-options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-options.js","sourceRoot":"","sources":["../../src/http/request-options.ts"],"names":[],"mappings":"","sourcesContent":["import type { Secret } from \"@/core\";\n\n/** A value of a query parameter. A {@link Secret} is revealed only when the request is sent. */\nexport type QueryValue = string | number | boolean | Secret;\n\n/** The query parameters of a request. An array repeats the parameter, and `undefined` leaves it out. */\nexport type QueryParams = Readonly<Record<string, QueryValue | readonly QueryValue[] | undefined>>;\n\n/** The headers of a request. Header names are case-insensitive, and each {@link Secret} is revealed only when sent. */\nexport type RequestHeaders = Readonly<Record<string, string | Secret>>;\n\n/**\n * Returns request headers. It is called for each request, so values that change, such as a renewed token, are picked\n * up. Return tokens as {@link Secret} values to keep them masked.\n */\nexport type HeaderProvider = () => Promise<RequestHeaders>;\n\n/** A file in a multipart body. */\nexport interface MultipartFile {\n /** The file name. */\n readonly name: string;\n /** The media type of the file, such as `text/plain`. */\n readonly mimeType: string;\n /** The content of the file. */\n readonly buffer: Buffer;\n}\n\n/** The options that every request accepts, whatever its body. */\nexport interface RequestBase {\n /** The query parameters, appended to the query of the path. */\n readonly query?: QueryParams;\n /** The headers of this request. They replace headers of the same name from the client. */\n readonly headers?: RequestHeaders;\n /** The time to wait for a response, in milliseconds. */\n readonly timeoutMs?: number;\n}\n\n/** The options of a request with a JSON body, or with no body. */\nexport interface JsonBody {\n /** A body sent as JSON, with the `application/json` content type. */\n readonly json?: unknown;\n /** Not allowed, because a request has at most one body. */\n readonly form?: never;\n /** Not allowed, because a request has at most one body. */\n readonly multipart?: never;\n}\n\n/** The options of a request with a URL-encoded form body. */\nexport interface FormBody {\n /** A body sent as URL-encoded form fields. */\n readonly form: Readonly<Record<string, string | number | boolean | Secret>>;\n /** Not allowed, because a request has at most one body. */\n readonly json?: never;\n /** Not allowed, because a request has at most one body. */\n readonly multipart?: never;\n}\n\n/** The options of a request with a multipart body. */\nexport interface MultipartBody {\n /** A body sent as multipart form data, with text fields and files. */\n readonly multipart: Readonly<Record<string, string | MultipartFile | Secret>>;\n /** Not allowed, because a request has at most one body. */\n readonly json?: never;\n /** Not allowed, because a request has at most one body. */\n readonly form?: never;\n}\n\n/**\n * The options of a request. A request has at most one body: `json`, `form` or `multipart`. Each {@link Secret} is\n * revealed only when the request is sent.\n */\nexport type RequestOptions = RequestBase & (JsonBody | FormBody | MultipartBody);\n"]}
@@ -0,0 +1,2 @@
1
+ export type { ModuleRequirement } from "./installed-modules.ts";
2
+ export { compareModuleVersions, InstalledModules } from "./installed-modules.ts";
@@ -0,0 +1,2 @@
1
+ export { compareModuleVersions, InstalledModules } from "./installed-modules.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/modules/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC","sourcesContent":["export type { ModuleRequirement } from \"./installed-modules.ts\";\n\nexport { compareModuleVersions, InstalledModules } from \"./installed-modules.ts\";\n"]}
@@ -0,0 +1,86 @@
1
+ import type { HttpClient } from "../http/index.js";
2
+ /**
3
+ * A platform module that a test or a dataset collection needs, with an optional range of versions.
4
+ *
5
+ * @remarks
6
+ * Without a range, any installed version meets the requirement. Set `minVersion` when the code relies on a fix or a
7
+ * feature of that version, and `beforeVersion` when a later version changes the behaviour that the code checks.
8
+ */
9
+ export interface ModuleRequirement {
10
+ /** The identifier of the module, such as `VirtoCommerce.Catalog`. */
11
+ readonly id: string;
12
+ /** The oldest version that meets the requirement, inclusive. */
13
+ readonly minVersion?: string | undefined;
14
+ /** The first version that no longer meets the requirement, exclusive. */
15
+ readonly beforeVersion?: string | undefined;
16
+ }
17
+ /** Represents the modules installed on a platform, with their versions. */
18
+ export declare class InstalledModules {
19
+ #private;
20
+ /**
21
+ * Creates a set of installed modules.
22
+ *
23
+ * @remarks
24
+ * A version is checked only when a requirement with a range of versions compares it, so a module whose version is in
25
+ * another form fails only the requirements on that module.
26
+ *
27
+ * @param versions - The version of each module by module identifier.
28
+ */
29
+ constructor(versions: Readonly<Record<string, string>>);
30
+ /**
31
+ * Reads the modules installed on a platform.
32
+ *
33
+ * @param httpClient - A client signed in as a platform administrator.
34
+ * @returns The installed modules. Modules that the platform knows but has not installed are left out.
35
+ * @throws {HttpError} The platform rejects the request, or the response is not a list of modules.
36
+ */
37
+ static read(httpClient: HttpClient): Promise<InstalledModules>;
38
+ /** Gets the number of installed modules. */
39
+ get count(): number;
40
+ /**
41
+ * Returns the installed version of a module.
42
+ *
43
+ * @param id - The identifier of the module.
44
+ * @returns The version, or `undefined` when the module is not installed.
45
+ */
46
+ versionOf(id: string): string | undefined;
47
+ /**
48
+ * Returns why the installed modules do not meet a requirement.
49
+ *
50
+ * @param requirement - The module and the range of versions that are needed.
51
+ * @returns The reason, such as `VirtoCommerce.Quote 3.1010.0 is older than 3.1020.0`, or `undefined` when the
52
+ * requirement is met.
53
+ * @throws {Error} The requirement has a range of versions, and the installed version or a version of the range is not
54
+ * in the form `major[.minor[.patch]][-suffix][+metadata]`. The message names the module.
55
+ */
56
+ unmetReason(requirement: ModuleRequirement): string | undefined;
57
+ /**
58
+ * Returns why the installed modules do not meet several requirements.
59
+ *
60
+ * @param requirements - The requirements to check.
61
+ * @returns The reason of each unmet requirement, in the order of `requirements`. It is empty when all are met.
62
+ * @throws {Error} A version cannot be compared, as for {@link InstalledModules.unmetReason}.
63
+ */
64
+ unmetReasons(requirements: readonly ModuleRequirement[]): string[];
65
+ /**
66
+ * Returns the version of each module by module identifier, so the set can be saved and read again in another
67
+ * process with the constructor.
68
+ *
69
+ * @returns The versions by module identifier.
70
+ */
71
+ toJSON(): Record<string, string>;
72
+ }
73
+ /**
74
+ * Compares two module versions, such as `3.1034.0` and `3.1012.1`.
75
+ *
76
+ * @remarks
77
+ * The parts are compared as numbers, so `3.1034.0` is newer than `3.1012.1`. A missing part counts as 0. A build
78
+ * with a suffix, such as `3.1035.0-pr-12`, comes before the release of the same version. Build metadata after `+`,
79
+ * such as `3.1035.0+sha.5114f85`, is ignored.
80
+ *
81
+ * @param left - The first version.
82
+ * @param right - The second version.
83
+ * @returns A negative number when `left` is older, a positive number when it is newer, and 0 when they are equal.
84
+ * @throws {Error} A version is not in the form `major[.minor[.patch]][-suffix][+metadata]`.
85
+ */
86
+ export declare function compareModuleVersions(left: string, right: string): number;
@@ -0,0 +1,135 @@
1
+ import { array, boolean, object, string } from "zod";
2
+ import { errorMessage, nonBlankString } from "../core/index.js";
3
+ const MODULES_PATH = "/api/platform/modules";
4
+ const VERSION_PATTERN = /^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([^+]+))?(?:\+.+)?$/;
5
+ const moduleDescriptorsSchema = array(object({
6
+ id: nonBlankString,
7
+ version: string(),
8
+ isInstalled: boolean(),
9
+ }));
10
+ /** Represents the modules installed on a platform, with their versions. */
11
+ export class InstalledModules {
12
+ #versions;
13
+ /**
14
+ * Creates a set of installed modules.
15
+ *
16
+ * @remarks
17
+ * A version is checked only when a requirement with a range of versions compares it, so a module whose version is in
18
+ * another form fails only the requirements on that module.
19
+ *
20
+ * @param versions - The version of each module by module identifier.
21
+ */
22
+ constructor(versions) {
23
+ this.#versions = new Map(Object.entries(versions));
24
+ }
25
+ /**
26
+ * Reads the modules installed on a platform.
27
+ *
28
+ * @param httpClient - A client signed in as a platform administrator.
29
+ * @returns The installed modules. Modules that the platform knows but has not installed are left out.
30
+ * @throws {HttpError} The platform rejects the request, or the response is not a list of modules.
31
+ */
32
+ static async read(httpClient) {
33
+ const modules = (await httpClient.get(MODULES_PATH)).parse(moduleDescriptorsSchema);
34
+ return new InstalledModules(Object.fromEntries(modules.filter((module) => module.isInstalled).map((module) => [module.id, module.version])));
35
+ }
36
+ /** Gets the number of installed modules. */
37
+ get count() {
38
+ return this.#versions.size;
39
+ }
40
+ /**
41
+ * Returns the installed version of a module.
42
+ *
43
+ * @param id - The identifier of the module.
44
+ * @returns The version, or `undefined` when the module is not installed.
45
+ */
46
+ versionOf(id) {
47
+ return this.#versions.get(id);
48
+ }
49
+ /**
50
+ * Returns why the installed modules do not meet a requirement.
51
+ *
52
+ * @param requirement - The module and the range of versions that are needed.
53
+ * @returns The reason, such as `VirtoCommerce.Quote 3.1010.0 is older than 3.1020.0`, or `undefined` when the
54
+ * requirement is met.
55
+ * @throws {Error} The requirement has a range of versions, and the installed version or a version of the range is not
56
+ * in the form `major[.minor[.patch]][-suffix][+metadata]`. The message names the module.
57
+ */
58
+ unmetReason(requirement) {
59
+ const { id, minVersion, beforeVersion } = requirement;
60
+ const version = this.versionOf(id);
61
+ if (version === undefined) {
62
+ return `${id} is not installed`;
63
+ }
64
+ try {
65
+ if (minVersion !== undefined && compareModuleVersions(version, minVersion) < 0) {
66
+ return `${id} ${version} is older than ${minVersion}`;
67
+ }
68
+ if (beforeVersion !== undefined && compareModuleVersions(version, beforeVersion) >= 0) {
69
+ return `${id} ${version} is not older than ${beforeVersion}`;
70
+ }
71
+ }
72
+ catch (error) {
73
+ throw new Error(`${id}: ${errorMessage(error)}`, { cause: error });
74
+ }
75
+ return undefined;
76
+ }
77
+ /**
78
+ * Returns why the installed modules do not meet several requirements.
79
+ *
80
+ * @param requirements - The requirements to check.
81
+ * @returns The reason of each unmet requirement, in the order of `requirements`. It is empty when all are met.
82
+ * @throws {Error} A version cannot be compared, as for {@link InstalledModules.unmetReason}.
83
+ */
84
+ unmetReasons(requirements) {
85
+ return requirements.flatMap((requirement) => this.unmetReason(requirement) ?? []);
86
+ }
87
+ /**
88
+ * Returns the version of each module by module identifier, so the set can be saved and read again in another
89
+ * process with the constructor.
90
+ *
91
+ * @returns The versions by module identifier.
92
+ */
93
+ toJSON() {
94
+ return Object.fromEntries(this.#versions);
95
+ }
96
+ }
97
+ /**
98
+ * Compares two module versions, such as `3.1034.0` and `3.1012.1`.
99
+ *
100
+ * @remarks
101
+ * The parts are compared as numbers, so `3.1034.0` is newer than `3.1012.1`. A missing part counts as 0. A build
102
+ * with a suffix, such as `3.1035.0-pr-12`, comes before the release of the same version. Build metadata after `+`,
103
+ * such as `3.1035.0+sha.5114f85`, is ignored.
104
+ *
105
+ * @param left - The first version.
106
+ * @param right - The second version.
107
+ * @returns A negative number when `left` is older, a positive number when it is newer, and 0 when they are equal.
108
+ * @throws {Error} A version is not in the form `major[.minor[.patch]][-suffix][+metadata]`.
109
+ */
110
+ export function compareModuleVersions(left, right) {
111
+ const [leftParts, leftSuffix] = parseVersion(left);
112
+ const [rightParts, rightSuffix] = parseVersion(right);
113
+ for (const [index, part] of leftParts.entries()) {
114
+ const difference = part - (rightParts[index] ?? 0);
115
+ if (difference !== 0) {
116
+ return difference;
117
+ }
118
+ }
119
+ if (leftSuffix === rightSuffix) {
120
+ return 0;
121
+ }
122
+ if (leftSuffix === undefined || rightSuffix === undefined) {
123
+ return leftSuffix === undefined ? 1 : -1;
124
+ }
125
+ return leftSuffix.localeCompare(rightSuffix, "en", { numeric: true });
126
+ }
127
+ function parseVersion(version) {
128
+ const match = VERSION_PATTERN.exec(version.trim());
129
+ if (match === null) {
130
+ throw new Error(`"${version}" is not a module version in the form major[.minor[.patch]][-suffix][+metadata]`);
131
+ }
132
+ const [, major, minor, patch, suffix] = match;
133
+ return [[Number(major), Number(minor ?? 0), Number(patch ?? 0)], suffix];
134
+ }
135
+ //# sourceMappingURL=installed-modules.js.map