@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,77 @@
1
+ import type { UrlPath } from "../core/index.js";
2
+ import type { HttpMethod } from "../http/index.js";
3
+ import type { ModuleRequirement } from "../modules/index.js";
4
+ /**
5
+ * A search that finds the stored copy of a record whose identifier the platform assigns, matched by one field.
6
+ *
7
+ * @remarks
8
+ * The paths and the strings of the criteria can contain `${ENV:key}` and `${RECORD:field}` placeholders.
9
+ */
10
+ export interface StoredIdLookup {
11
+ /** The path of the search, such as `/api/shipping/search`. */
12
+ readonly searchPath: UrlPath;
13
+ /** The criteria of the search. */
14
+ readonly criteria: Readonly<Record<string, unknown>>;
15
+ /**
16
+ * The field that a stored record shares with the dataset record, such as `code`. When several stored records match,
17
+ * the first one is used.
18
+ */
19
+ readonly match: string;
20
+ }
21
+ /**
22
+ * Describes how the records of one collection are sent to the platform.
23
+ *
24
+ * @remarks
25
+ * Paths can contain `${ENV:key}` placeholders, filled from the placeholder values of the seed run. `findPath`,
26
+ * `storedIdFrom` and, for collections sent one record at a time, `path` and `ifMatchPath` can also contain
27
+ * `${RECORD:field}` placeholders, filled from the record. Every value is URL-encoded.
28
+ */
29
+ export interface CollectionSpec {
30
+ /** The module, with its range of versions, that the collection needs. Without it, the collection is skipped. */
31
+ readonly module: ModuleRequirement;
32
+ /** The method of the seed request. */
33
+ readonly method: HttpMethod;
34
+ /** The path of the seed request, such as `/api/catalog/catalogs`. */
35
+ readonly path: UrlPath;
36
+ /** Whether to send one request for each record (`each`) or one request with every record (`all`). */
37
+ readonly send: "each" | "all";
38
+ /** The field, or the fields, that name a record without an identifier in logs and errors. */
39
+ readonly key?: string | readonly string[] | undefined;
40
+ /**
41
+ * The path that finds a stored record. A record that the platform already stores is left as it is, so changes to it
42
+ * in the dataset are not sent. A 404 status, an empty body, `null` and an empty array mean that the record is not
43
+ * stored. Without it, every record is sent again, and the seed request replaces the stored one.
44
+ */
45
+ readonly findPath?: UrlPath | undefined;
46
+ /**
47
+ * The path whose `ETag` the seed request sends as `If-Match`, for endpoints that refuse a write without the current
48
+ * version. It is read right before each request. When the path is not found (404) or its response has no `ETag`,
49
+ * none is sent.
50
+ */
51
+ readonly ifMatchPath?: UrlPath | undefined;
52
+ /**
53
+ * A search that finds the stored copy of a record whose identifier the platform assigns, so the record is sent with
54
+ * that identifier and replaces the stored copy instead of adding another.
55
+ */
56
+ readonly storedIdFrom?: StoredIdLookup | undefined;
57
+ /**
58
+ * The field that references a parent record in the same collection, for collections sent one record at a time.
59
+ * Parents are sent before their children.
60
+ */
61
+ readonly parentField?: string | undefined;
62
+ }
63
+ /**
64
+ * The collections of a dataset in seed order, and how each one is sent. The records of a collection are the JSON files
65
+ * in its directory, which is named after the collection in kebab case, such as `product-inventories` for
66
+ * `productInventories`.
67
+ */
68
+ export type Manifest = Readonly<Record<string, CollectionSpec>>;
69
+ /** The name of a collection of a manifest. */
70
+ export type CollectionName<TManifest extends Manifest> = Extract<keyof TManifest, string>;
71
+ /**
72
+ * Returns the directory of a collection: its name in kebab case.
73
+ *
74
+ * @param name - The name of the collection, such as `productInventories`.
75
+ * @returns The directory, such as `product-inventories`.
76
+ */
77
+ export declare function collectionDirectory(name: string): string;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Returns the directory of a collection: its name in kebab case.
3
+ *
4
+ * @param name - The name of the collection, such as `productInventories`.
5
+ * @returns The directory, such as `product-inventories`.
6
+ */
7
+ export function collectionDirectory(name) {
8
+ return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
9
+ }
10
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../src/dataset/manifest.ts"],"names":[],"mappings":"AA2EA;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAY;IAC9C,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import type { UrlPath } from \"@/core\";\nimport type { HttpMethod } from \"@/http\";\nimport type { ModuleRequirement } from \"@/modules\";\n\n/**\n * A search that finds the stored copy of a record whose identifier the platform assigns, matched by one field.\n *\n * @remarks\n * The paths and the strings of the criteria can contain `${ENV:key}` and `${RECORD:field}` placeholders.\n */\nexport interface StoredIdLookup {\n /** The path of the search, such as `/api/shipping/search`. */\n readonly searchPath: UrlPath;\n /** The criteria of the search. */\n readonly criteria: Readonly<Record<string, unknown>>;\n /**\n * The field that a stored record shares with the dataset record, such as `code`. When several stored records match,\n * the first one is used.\n */\n readonly match: string;\n}\n\n/**\n * Describes how the records of one collection are sent to the platform.\n *\n * @remarks\n * Paths can contain `${ENV:key}` placeholders, filled from the placeholder values of the seed run. `findPath`,\n * `storedIdFrom` and, for collections sent one record at a time, `path` and `ifMatchPath` can also contain\n * `${RECORD:field}` placeholders, filled from the record. Every value is URL-encoded.\n */\nexport interface CollectionSpec {\n /** The module, with its range of versions, that the collection needs. Without it, the collection is skipped. */\n readonly module: ModuleRequirement;\n /** The method of the seed request. */\n readonly method: HttpMethod;\n /** The path of the seed request, such as `/api/catalog/catalogs`. */\n readonly path: UrlPath;\n /** Whether to send one request for each record (`each`) or one request with every record (`all`). */\n readonly send: \"each\" | \"all\";\n /** The field, or the fields, that name a record without an identifier in logs and errors. */\n readonly key?: string | readonly string[] | undefined;\n /**\n * The path that finds a stored record. A record that the platform already stores is left as it is, so changes to it\n * in the dataset are not sent. A 404 status, an empty body, `null` and an empty array mean that the record is not\n * stored. Without it, every record is sent again, and the seed request replaces the stored one.\n */\n readonly findPath?: UrlPath | undefined;\n /**\n * The path whose `ETag` the seed request sends as `If-Match`, for endpoints that refuse a write without the current\n * version. It is read right before each request. When the path is not found (404) or its response has no `ETag`,\n * none is sent.\n */\n readonly ifMatchPath?: UrlPath | undefined;\n /**\n * A search that finds the stored copy of a record whose identifier the platform assigns, so the record is sent with\n * that identifier and replaces the stored copy instead of adding another.\n */\n readonly storedIdFrom?: StoredIdLookup | undefined;\n /**\n * The field that references a parent record in the same collection, for collections sent one record at a time.\n * Parents are sent before their children.\n */\n readonly parentField?: string | undefined;\n}\n\n/**\n * The collections of a dataset in seed order, and how each one is sent. The records of a collection are the JSON files\n * in its directory, which is named after the collection in kebab case, such as `product-inventories` for\n * `productInventories`.\n */\nexport type Manifest = Readonly<Record<string, CollectionSpec>>;\n\n/** The name of a collection of a manifest. */\nexport type CollectionName<TManifest extends Manifest> = Extract<keyof TManifest, string>;\n\n/**\n * Returns the directory of a collection: its name in kebab case.\n *\n * @param name - The name of the collection, such as `productInventories`.\n * @returns The directory, such as `product-inventories`.\n */\nexport function collectionDirectory(name: string): string {\n return name.replace(/[A-Z]/g, (letter: string) => `-${letter.toLowerCase()}`);\n}\n"]}
@@ -0,0 +1,66 @@
1
+ import { Secret } from "../core/index.js";
2
+ /** The values of the `${ENV:key}` placeholders of a dataset, by key. A `Secret` is revealed where it is filled in. */
3
+ export type PlaceholderValues = Readonly<Record<string, string | Secret>>;
4
+ /**
5
+ * The functions that return the values of placeholders, by source, such as `ENV` or `RECORD`. A function returns
6
+ * `undefined` or `null` for a key without a value.
7
+ */
8
+ export type PlaceholderSources = Readonly<Record<string, (key: string) => unknown>>;
9
+ /**
10
+ * Returns the placeholder of a value that a seed run or a dataset load fills in from its placeholder values.
11
+ *
12
+ * @example
13
+ * criteria: { storeId: envPlaceholder("STORE_ID") }
14
+ *
15
+ * @param key - The key of the value, such as `STORE_ID`.
16
+ * @returns The placeholder, such as `${ENV:STORE_ID}`.
17
+ * @throws {Error} The key is empty or contains `}`.
18
+ */
19
+ export declare function envPlaceholder<const TKey extends string>(key: TKey): `\${ENV:${TKey}}`;
20
+ /**
21
+ * Returns the placeholder of a field of the record being sent, for the paths and the search criteria of a collection
22
+ * sent one record at a time.
23
+ *
24
+ * @example
25
+ * path: `/api/inventory/products/${recordPlaceholder("productId")}`
26
+ *
27
+ * @param field - The field of the record, such as `code`.
28
+ * @returns The placeholder, such as `${RECORD:code}`.
29
+ * @throws {Error} The field is empty or contains `}`.
30
+ */
31
+ export declare function recordPlaceholder<const TField extends string>(field: TField): `\${RECORD:${TField}}`;
32
+ /**
33
+ * Replaces each placeholder in a text with its value.
34
+ *
35
+ * @remarks
36
+ * The text is read once, so a value that contains a placeholder is not filled in again. A `Secret` value is revealed.
37
+ *
38
+ * @param template - The text with placeholders, such as a path or the content of a data file.
39
+ * @param sources - The functions that return the values, by source.
40
+ * @param encode - Encodes each value for the text, such as `encodeURIComponent` for a path.
41
+ * @returns The text with every placeholder replaced.
42
+ * @throws {Error} A placeholder has an unknown source or no value. The message names the placeholder, not a value.
43
+ */
44
+ export declare function fillPlaceholders(template: string, sources: PlaceholderSources, encode: (value: string) => string): string;
45
+ /**
46
+ * Determines whether a text has a placeholder of a source.
47
+ *
48
+ * @param template - The text, such as a path.
49
+ * @param source - The source, such as `RECORD`.
50
+ * @returns `true` if the text has a placeholder of the source; otherwise, `false`.
51
+ */
52
+ export declare function hasPlaceholder(template: string, source: string): boolean;
53
+ /**
54
+ * Escapes a value as the content of a JSON string, without the quotes, so it can be filled into a JSON text.
55
+ *
56
+ * @param value - The value.
57
+ * @returns The escaped value, such as `say \"hi\"` for `say "hi"`.
58
+ */
59
+ export declare function jsonStringContent(value: string): string;
60
+ /**
61
+ * Returns the source of `${ENV:key}` placeholders for a set of placeholder values.
62
+ *
63
+ * @param values - The placeholder values, by key.
64
+ * @returns A function that returns the value of a key, or `undefined` for an unknown key.
65
+ */
66
+ export declare function envSource(values: PlaceholderValues): (key: string) => unknown;
@@ -0,0 +1,87 @@
1
+ import { Secret } from "../core/index.js";
2
+ const PLACEHOLDER = /\$\{([A-Z]+):([^}]+)\}/g;
3
+ /**
4
+ * Returns the placeholder of a value that a seed run or a dataset load fills in from its placeholder values.
5
+ *
6
+ * @example
7
+ * criteria: { storeId: envPlaceholder("STORE_ID") }
8
+ *
9
+ * @param key - The key of the value, such as `STORE_ID`.
10
+ * @returns The placeholder, such as `${ENV:STORE_ID}`.
11
+ * @throws {Error} The key is empty or contains `}`.
12
+ */
13
+ export function envPlaceholder(key) {
14
+ return `\${ENV:${checkedName(key)}}`;
15
+ }
16
+ /**
17
+ * Returns the placeholder of a field of the record being sent, for the paths and the search criteria of a collection
18
+ * sent one record at a time.
19
+ *
20
+ * @example
21
+ * path: `/api/inventory/products/${recordPlaceholder("productId")}`
22
+ *
23
+ * @param field - The field of the record, such as `code`.
24
+ * @returns The placeholder, such as `${RECORD:code}`.
25
+ * @throws {Error} The field is empty or contains `}`.
26
+ */
27
+ export function recordPlaceholder(field) {
28
+ return `\${RECORD:${checkedName(field)}}`;
29
+ }
30
+ /**
31
+ * Replaces each placeholder in a text with its value.
32
+ *
33
+ * @remarks
34
+ * The text is read once, so a value that contains a placeholder is not filled in again. A `Secret` value is revealed.
35
+ *
36
+ * @param template - The text with placeholders, such as a path or the content of a data file.
37
+ * @param sources - The functions that return the values, by source.
38
+ * @param encode - Encodes each value for the text, such as `encodeURIComponent` for a path.
39
+ * @returns The text with every placeholder replaced.
40
+ * @throws {Error} A placeholder has an unknown source or no value. The message names the placeholder, not a value.
41
+ */
42
+ export function fillPlaceholders(template, sources, encode) {
43
+ return template.replace(PLACEHOLDER, (placeholder, source, key) => {
44
+ const value = sources[source]?.(key);
45
+ if (value === undefined || value === null) {
46
+ throw new Error(`${placeholder} has no value`);
47
+ }
48
+ return encode(value instanceof Secret ? value.reveal() : String(value));
49
+ });
50
+ }
51
+ /**
52
+ * Determines whether a text has a placeholder of a source.
53
+ *
54
+ * @param template - The text, such as a path.
55
+ * @param source - The source, such as `RECORD`.
56
+ * @returns `true` if the text has a placeholder of the source; otherwise, `false`.
57
+ */
58
+ export function hasPlaceholder(template, source) {
59
+ return [...template.matchAll(PLACEHOLDER)].some((match) => match[1] === source);
60
+ }
61
+ /**
62
+ * Escapes a value as the content of a JSON string, without the quotes, so it can be filled into a JSON text.
63
+ *
64
+ * @param value - The value.
65
+ * @returns The escaped value, such as `say \"hi\"` for `say "hi"`.
66
+ */
67
+ export function jsonStringContent(value) {
68
+ return JSON.stringify(value).slice(1, -1);
69
+ }
70
+ /**
71
+ * Returns the source of `${ENV:key}` placeholders for a set of placeholder values.
72
+ *
73
+ * @param values - The placeholder values, by key.
74
+ * @returns A function that returns the value of a key, or `undefined` for an unknown key.
75
+ */
76
+ export function envSource(values) {
77
+ return function placeholderValue(key) {
78
+ return values[key];
79
+ };
80
+ }
81
+ function checkedName(name) {
82
+ if (name === "" || name.includes("}")) {
83
+ throw new Error(`"${name}" cannot be used in a placeholder`);
84
+ }
85
+ return name;
86
+ }
87
+ //# sourceMappingURL=placeholders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"placeholders.js","sourceRoot":"","sources":["../../src/dataset/placeholders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAWhC,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAE9C;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAA4B,GAAS;IACjE,OAAO,UAAU,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC;AACvC,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,iBAAiB,CAA8B,KAAa;IAC1E,OAAO,aAAa,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC;AAC5C,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,gBAAgB,CAC9B,QAAgB,EAChB,OAA2B,EAC3B,MAAiC;IAEjC,OAAO,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,WAAmB,EAAE,MAAc,EAAE,GAAW,EAAE,EAAE;QACxF,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;QACrC,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,GAAG,WAAW,eAAe,CAAC,CAAC;QACjD,CAAC;QACD,OAAO,MAAM,CAAC,KAAK,YAAY,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC1E,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,QAAgB,EAAE,MAAc;IAC7D,OAAO,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC;AAClF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAa;IAC7C,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAC5C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,MAAyB;IACjD,OAAO,SAAS,gBAAgB,CAAC,GAAW;QAC1C,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAmB,IAAO;IAC5C,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CAAC,IAAI,IAAI,mCAAmC,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { Secret } from \"@/core\";\n\n/** The values of the `${ENV:key}` placeholders of a dataset, by key. A `Secret` is revealed where it is filled in. */\nexport type PlaceholderValues = Readonly<Record<string, string | Secret>>;\n\n/**\n * The functions that return the values of placeholders, by source, such as `ENV` or `RECORD`. A function returns\n * `undefined` or `null` for a key without a value.\n */\nexport type PlaceholderSources = Readonly<Record<string, (key: string) => unknown>>;\n\nconst PLACEHOLDER = /\\$\\{([A-Z]+):([^}]+)\\}/g;\n\n/**\n * Returns the placeholder of a value that a seed run or a dataset load fills in from its placeholder values.\n *\n * @example\n * criteria: { storeId: envPlaceholder(\"STORE_ID\") }\n *\n * @param key - The key of the value, such as `STORE_ID`.\n * @returns The placeholder, such as `${ENV:STORE_ID}`.\n * @throws {Error} The key is empty or contains `}`.\n */\nexport function envPlaceholder<const TKey extends string>(key: TKey): `\\${ENV:${TKey}}` {\n return `\\${ENV:${checkedName(key)}}`;\n}\n\n/**\n * Returns the placeholder of a field of the record being sent, for the paths and the search criteria of a collection\n * sent one record at a time.\n *\n * @example\n * path: `/api/inventory/products/${recordPlaceholder(\"productId\")}`\n *\n * @param field - The field of the record, such as `code`.\n * @returns The placeholder, such as `${RECORD:code}`.\n * @throws {Error} The field is empty or contains `}`.\n */\nexport function recordPlaceholder<const TField extends string>(field: TField): `\\${RECORD:${TField}}` {\n return `\\${RECORD:${checkedName(field)}}`;\n}\n\n/**\n * Replaces each placeholder in a text with its value.\n *\n * @remarks\n * The text is read once, so a value that contains a placeholder is not filled in again. A `Secret` value is revealed.\n *\n * @param template - The text with placeholders, such as a path or the content of a data file.\n * @param sources - The functions that return the values, by source.\n * @param encode - Encodes each value for the text, such as `encodeURIComponent` for a path.\n * @returns The text with every placeholder replaced.\n * @throws {Error} A placeholder has an unknown source or no value. The message names the placeholder, not a value.\n */\nexport function fillPlaceholders(\n template: string,\n sources: PlaceholderSources,\n encode: (value: string) => string,\n): string {\n return template.replace(PLACEHOLDER, (placeholder: string, source: string, key: string) => {\n const value = sources[source]?.(key);\n if (value === undefined || value === null) {\n throw new Error(`${placeholder} has no value`);\n }\n return encode(value instanceof Secret ? value.reveal() : String(value));\n });\n}\n\n/**\n * Determines whether a text has a placeholder of a source.\n *\n * @param template - The text, such as a path.\n * @param source - The source, such as `RECORD`.\n * @returns `true` if the text has a placeholder of the source; otherwise, `false`.\n */\nexport function hasPlaceholder(template: string, source: string): boolean {\n return [...template.matchAll(PLACEHOLDER)].some((match) => match[1] === source);\n}\n\n/**\n * Escapes a value as the content of a JSON string, without the quotes, so it can be filled into a JSON text.\n *\n * @param value - The value.\n * @returns The escaped value, such as `say \\\"hi\\\"` for `say \"hi\"`.\n */\nexport function jsonStringContent(value: string): string {\n return JSON.stringify(value).slice(1, -1);\n}\n\n/**\n * Returns the source of `${ENV:key}` placeholders for a set of placeholder values.\n *\n * @param values - The placeholder values, by key.\n * @returns A function that returns the value of a key, or `undefined` for an unknown key.\n */\nexport function envSource(values: PlaceholderValues): (key: string) => unknown {\n return function placeholderValue(key: string): unknown {\n return values[key];\n };\n}\n\nfunction checkedName<T extends string>(name: T): T {\n if (name === \"\" || name.includes(\"}\")) {\n throw new Error(`\"${name}\" cannot be used in a placeholder`);\n }\n return name;\n}\n"]}
@@ -0,0 +1,53 @@
1
+ import type { HttpClient } from "../http/index.js";
2
+ import type { CollectionSpec } from "./manifest.ts";
3
+ import type { PlaceholderValues } from "./placeholders.ts";
4
+ import type { LabeledRecord, PathResolver } from "./seed-requests.ts";
5
+ /** How far the seeding of a collection got: the records sent and stored so far, and the one in progress. */
6
+ export interface Progress {
7
+ /** The number of records that were sent. */
8
+ sent: number;
9
+ /** The number of records that the platform already stored. */
10
+ existing: number;
11
+ /** The record or the request in progress, such as `record "product-1"` or `12 records`. */
12
+ subject: string | undefined;
13
+ }
14
+ /** A collection to seed, with what its requests need. */
15
+ export interface CollectionRun {
16
+ /** The client that sends the requests. */
17
+ readonly http: HttpClient;
18
+ /** The name of the collection. */
19
+ readonly name: string;
20
+ /** The manifest entry of the collection. */
21
+ readonly spec: CollectionSpec;
22
+ /** The values of the `${ENV:key}` placeholders. */
23
+ readonly values: PlaceholderValues;
24
+ /** Fills the placeholders of a path. */
25
+ readonly resolve: PathResolver;
26
+ /** Updated as the records are seeded. */
27
+ readonly progress: Progress;
28
+ }
29
+ /**
30
+ * Seeds the records of one collection, with one request for each record or one request with every record.
31
+ *
32
+ * @remarks
33
+ * A record that the `findPath` of the collection finds is left as it is. The progress is updated as the records are
34
+ * seeded, so it shows how far the collection got when it fails.
35
+ *
36
+ * @param run - The collection, the client and the progress to update.
37
+ * @param entries - The records with their labels, in file order.
38
+ * @throws {Error} A record cannot be sent, or a request fails. The message names the collection and the record, and
39
+ * has secrets masked. The cause is the original error.
40
+ */
41
+ export declare function seedCollection(run: CollectionRun, entries: readonly LabeledRecord[]): Promise<void>;
42
+ /**
43
+ * Runs a step of a seed run, and names the collection and the subject of the step in its error.
44
+ *
45
+ * @param name - The name of the collection.
46
+ * @param label - The subject of the step, such as `record "product-1"` or `finisher`, or `undefined` for the
47
+ * collection.
48
+ * @param work - The step.
49
+ * @returns What the step returns.
50
+ * @throws {Error} The step fails. The message starts with the collection and the subject, and has secrets masked. The
51
+ * cause is the original error.
52
+ */
53
+ export declare function attempt<T>(name: string, label: string | undefined, work: () => T | Promise<T>): Promise<T>;
@@ -0,0 +1,115 @@
1
+ import { array, looseObject, object, string, unknown } from "zod";
2
+ import { errorMessage, maskSecrets } from "../core/index.js";
3
+ import { fieldOf, parentsFirst, requestOf, storedIdSearchOf } from "./seed-requests.js";
4
+ const storedSearchSchema = object({ results: array(looseObject({ id: string().nullish() })).default([]) });
5
+ /**
6
+ * Seeds the records of one collection, with one request for each record or one request with every record.
7
+ *
8
+ * @remarks
9
+ * A record that the `findPath` of the collection finds is left as it is. The progress is updated as the records are
10
+ * seeded, so it shows how far the collection got when it fails.
11
+ *
12
+ * @param run - The collection, the client and the progress to update.
13
+ * @param entries - The records with their labels, in file order.
14
+ * @throws {Error} A record cannot be sent, or a request fails. The message names the collection and the record, and
15
+ * has secrets masked. The cause is the original error.
16
+ */
17
+ export async function seedCollection(run, entries) {
18
+ return run.spec.send === "all" ? seedBatch(run, entries) : seedEach(run, entries);
19
+ }
20
+ /**
21
+ * Runs a step of a seed run, and names the collection and the subject of the step in its error.
22
+ *
23
+ * @param name - The name of the collection.
24
+ * @param label - The subject of the step, such as `record "product-1"` or `finisher`, or `undefined` for the
25
+ * collection.
26
+ * @param work - The step.
27
+ * @returns What the step returns.
28
+ * @throws {Error} The step fails. The message starts with the collection and the subject, and has secrets masked. The
29
+ * cause is the original error.
30
+ */
31
+ export async function attempt(name, label, work) {
32
+ try {
33
+ return await work();
34
+ }
35
+ catch (error) {
36
+ const subject = label === undefined ? name : `${name} ${label}`;
37
+ throw new Error(maskSecrets(`${subject}: ${errorMessage(error)}`), { cause: error });
38
+ }
39
+ }
40
+ async function seedEach(run, entries) {
41
+ const { http, name, spec, resolve, progress } = run;
42
+ const parentField = spec.parentField;
43
+ const ordered = await attempt(name, undefined, () => parentField === undefined ? entries : parentsFirst(entries, parentField));
44
+ for (const { record, label } of ordered) {
45
+ progress.subject = label;
46
+ await attempt(name, label, async () => {
47
+ if (await isFound(run, record)) {
48
+ progress.existing += 1;
49
+ return;
50
+ }
51
+ const body = await withStoredId(run, record);
52
+ await send(http, spec, requestOf(spec, resolve, body, body));
53
+ progress.sent += 1;
54
+ });
55
+ }
56
+ }
57
+ async function seedBatch(run, entries) {
58
+ const { http, name, spec, resolve, progress } = run;
59
+ const toSend = [];
60
+ for (const { record, label } of entries) {
61
+ progress.subject = label;
62
+ await attempt(name, label, async () => {
63
+ if (await isFound(run, record)) {
64
+ progress.existing += 1;
65
+ }
66
+ else {
67
+ toSend.push(await withStoredId(run, record));
68
+ }
69
+ });
70
+ }
71
+ if (toSend.length > 0) {
72
+ const subject = `${toSend.length} records`;
73
+ progress.subject = subject;
74
+ await attempt(name, subject, () => send(http, spec, requestOf(spec, resolve, toSend)));
75
+ progress.sent = toSend.length;
76
+ }
77
+ }
78
+ async function isFound({ http, spec, resolve }, record) {
79
+ if (spec.findPath === undefined) {
80
+ return false;
81
+ }
82
+ const response = await http.get(resolve(spec.findPath, record));
83
+ const body = response.parseOptional(unknown(), { allow404: true });
84
+ return body !== undefined && !(Array.isArray(body) && body.length === 0);
85
+ }
86
+ async function withStoredId({ http, spec, values }, record) {
87
+ const search = storedIdSearchOf(spec, record, values);
88
+ if (search === undefined) {
89
+ return record;
90
+ }
91
+ const { results } = (await http.post(search.path, { json: search.criteria })).parse(storedSearchSchema);
92
+ const wanted = fieldOf(record, search.match);
93
+ const stored = results.find((result) => typeof result.id === "string" && result[search.match] === wanted);
94
+ return stored === undefined ? record : { ...record, id: stored.id };
95
+ }
96
+ async function send(http, spec, request) {
97
+ const eTag = request.ifMatchPath === undefined ? undefined : await currentETag(http, request.ifMatchPath);
98
+ const headers = eTag === undefined ? {} : { "if-match": eTag };
99
+ expectAccepted(await http.send(spec.method, request.path, { json: request.body, headers }));
100
+ }
101
+ async function currentETag(http, path) {
102
+ const response = await http.get(path);
103
+ return response.status === 404 ? undefined : response.expectOk().headers["etag"];
104
+ }
105
+ function expectAccepted(response) {
106
+ response.expectOk();
107
+ if (response.text === "" || !(response.headers["content-type"] ?? "").includes("json")) {
108
+ return;
109
+ }
110
+ const body = response.json();
111
+ if (typeof body === "object" && body !== null && Reflect.get(body, "succeeded") === false) {
112
+ throw response.toError("the platform refused the record");
113
+ }
114
+ }
115
+ //# sourceMappingURL=seed-collection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seed-collection.js","sourceRoot":"","sources":["../../src/dataset/seed-collection.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAElE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAEnD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAExF,MAAM,kBAAkB,GAAG,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AA4B3G;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,GAAkB,EAAE,OAAiC;IACxF,OAAO,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AACpF,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,C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AQ,CAAC,IAAI,EAAE,CAAC;IACtC,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,WAAW,CAAC,KAAK,KAAK,EAAE,CAAC;QAC1F,MAAM,QAAQ,CAAC,OAAO,CAAC,iCAAiC,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC","sourcesContent":["import type { HttpClient, HttpResponse } from \"@/http\";\nimport type { CollectionSpec } from \"./manifest.ts\";\nimport type { PlaceholderValues } from \"./placeholders.ts\";\nimport type { LabeledRecord, PathResolver, SeedRequest } from \"./seed-requests.ts\";\n\nimport { array, looseObject, object, string, unknown } from \"zod\";\n\nimport { errorMessage, maskSecrets } from \"@/core\";\n\nimport { fieldOf, parentsFirst, requestOf, storedIdSearchOf } from \"./seed-requests.ts\";\n\nconst storedSearchSchema = object({ results: array(looseObject({ id: string().nullish() })).default([]) });\n\n/** How far the seeding of a collection got: the records sent and stored so far, and the one in progress. */\nexport interface Progress {\n /** The number of records that were sent. */\n sent: number;\n /** The number of records that the platform already stored. */\n existing: number;\n /** The record or the request in progress, such as `record \"product-1\"` or `12 records`. */\n subject: string | undefined;\n}\n\n/** A collection to seed, with what its requests need. */\nexport interface CollectionRun {\n /** The client that sends the requests. */\n readonly http: HttpClient;\n /** The name of the collection. */\n readonly name: string;\n /** The manifest entry of the collection. */\n readonly spec: CollectionSpec;\n /** The values of the `${ENV:key}` placeholders. */\n readonly values: PlaceholderValues;\n /** Fills the placeholders of a path. */\n readonly resolve: PathResolver;\n /** Updated as the records are seeded. */\n readonly progress: Progress;\n}\n\n/**\n * Seeds the records of one collection, with one request for each record or one request with every record.\n *\n * @remarks\n * A record that the `findPath` of the collection finds is left as it is. The progress is updated as the records are\n * seeded, so it shows how far the collection got when it fails.\n *\n * @param run - The collection, the client and the progress to update.\n * @param entries - The records with their labels, in file order.\n * @throws {Error} A record cannot be sent, or a request fails. The message names the collection and the record, and\n * has secrets masked. The cause is the original error.\n */\nexport async function seedCollection(run: CollectionRun, entries: readonly LabeledRecord[]): Promise<void> {\n return run.spec.send === \"all\" ? seedBatch(run, entries) : seedEach(run, entries);\n}\n\n/**\n * Runs a step of a seed run, and names the collection and the subject of the step in its error.\n *\n * @param name - The name of the collection.\n * @param label - The subject of the step, such as `record \"product-1\"` or `finisher`, or `undefined` for the\n * collection.\n * @param work - The step.\n * @returns What the step returns.\n * @throws {Error} The step fails. The message starts with the collection and the subject, and has secrets masked. The\n * cause is the original error.\n */\nexport async function attempt<T>(name: string, label: string | undefined, work: () => T | Promise<T>): Promise<T> {\n try {\n return await work();\n } catch (error) {\n const subject = label === undefined ? name : `${name} ${label}`;\n throw new Error(maskSecrets(`${subject}: ${errorMessage(error)}`), { cause: error });\n }\n}\n\nasync function seedEach(run: CollectionRun, entries: readonly LabeledRecord[]): Promise<void> {\n const { http, name, spec, resolve, progress } = run;\n const parentField = spec.parentField;\n const ordered = await attempt(name, undefined, () =>\n parentField === undefined ? entries : parentsFirst(entries, parentField),\n );\n for (const { record, label } of ordered) {\n progress.subject = label;\n await attempt(name, label, async () => {\n if (await isFound(run, record)) {\n progress.existing += 1;\n return;\n }\n const body = await withStoredId(run, record);\n await send(http, spec, requestOf(spec, resolve, body, body));\n progress.sent += 1;\n });\n }\n}\n\nasync function seedBatch(run: CollectionRun, entries: readonly LabeledRecord[]): Promise<void> {\n const { http, name, spec, resolve, progress } = run;\n const toSend: object[] = [];\n for (const { record, label } of entries) {\n progress.subject = label;\n await attempt(name, label, async () => {\n if (await isFound(run, record)) {\n progress.existing += 1;\n } else {\n toSend.push(await withStoredId(run, record));\n }\n });\n }\n if (toSend.length > 0) {\n const subject = `${toSend.length} records`;\n progress.subject = subject;\n await attempt(name, subject, () => send(http, spec, requestOf(spec, resolve, toSend)));\n progress.sent = toSend.length;\n }\n}\n\nasync function isFound({ http, spec, resolve }: CollectionRun, record: object): Promise<boolean> {\n if (spec.findPath === undefined) {\n return false;\n }\n const response = await http.get(resolve(spec.findPath, record));\n const body = response.parseOptional(unknown(), { allow404: true });\n return body !== undefined && !(Array.isArray(body) && body.length === 0);\n}\n\nasync function withStoredId({ http, spec, values }: CollectionRun, record: object): Promise<object> {\n const search = storedIdSearchOf(spec, record, values);\n if (search === undefined) {\n return record;\n }\n const { results } = (await http.post(search.path, { json: search.criteria })).parse(storedSearchSchema);\n const wanted = fieldOf(record, search.match);\n const stored = results.find((result) => typeof result.id === \"string\" && result[search.match] === wanted);\n return stored === undefined ? record : { ...record, id: stored.id };\n}\n\nasync function send(http: HttpClient, spec: CollectionSpec, request: SeedRequest): Promise<void> {\n const eTag = request.ifMatchPath === undefined ? undefined : await currentETag(http, request.ifMatchPath);\n const headers = eTag === undefined ? {} : { \"if-match\": eTag };\n expectAccepted(await http.send(spec.method, request.path, { json: request.body, headers }));\n}\n\nasync function currentETag(http: HttpClient, path: string): Promise<string | undefined> {\n const response = await http.get(path);\n return response.status === 404 ? undefined : response.expectOk().headers[\"etag\"];\n}\n\nfunction expectAccepted(response: HttpResponse): void {\n response.expectOk();\n if (response.text === \"\" || !(response.headers[\"content-type\"] ?? \"\").includes(\"json\")) {\n return;\n }\n const body: unknown = response.json();\n if (typeof body === \"object\" && body !== null && Reflect.get(body, \"succeeded\") === false) {\n throw response.toError(\"the platform refused the record\");\n }\n}\n"]}
@@ -0,0 +1,70 @@
1
+ import type { HttpClient } from "../http/index.js";
2
+ import type { InstalledModules } from "../modules/index.js";
3
+ import type { Collection } from "./collection.ts";
4
+ import type { CollectionName, Manifest } from "./manifest.ts";
5
+ import type { PlaceholderValues } from "./placeholders.ts";
6
+ import type { SeedEvent } from "./seed-events.ts";
7
+ import type { SkippedCollection } from "./seed-scope.ts";
8
+ /** Work that follows the seeding of a collection, such as setting the status of the pages just seeded. */
9
+ export type SeedFinisher = () => Promise<void>;
10
+ /** A dataset as the seeder reads it: the records of each collection of a manifest. */
11
+ export type SeedableDataset<TManifest extends Manifest> = {
12
+ readonly [Name in CollectionName<TManifest>]: Collection<object>;
13
+ };
14
+ /** The options of {@link seedDataset}. */
15
+ export interface SeedRun<TManifest extends Manifest> {
16
+ /** The client that sends the seed requests, signed in as a platform administrator. */
17
+ readonly http: HttpClient;
18
+ /** The collections, in seed order, and how each one is sent. */
19
+ readonly manifest: TManifest;
20
+ /** The records to seed. */
21
+ readonly dataset: SeedableDataset<TManifest>;
22
+ /** The modules installed on the platform. A collection whose module does not qualify is skipped. */
23
+ readonly installed: InstalledModules;
24
+ /** The collections to seed, in any order, or `undefined` for every collection. */
25
+ readonly only?: readonly CollectionName<TManifest>[] | undefined;
26
+ /** The values of the `${ENV:key}` placeholders in the paths of the manifest. */
27
+ readonly placeholders?: PlaceholderValues | undefined;
28
+ /** Work to run right after a collection is seeded, by collection. It is skipped with its collection. */
29
+ readonly finishers?: Partial<Readonly<Record<CollectionName<TManifest>, SeedFinisher>>> | undefined;
30
+ /**
31
+ * Receives each step of the run, such as a seeded or a skipped collection. The default discards them. An error that
32
+ * it throws stops the run; it does not replace the failure that it reports.
33
+ */
34
+ readonly onEvent?: ((event: SeedEvent) => void) | undefined;
35
+ }
36
+ /** The result of {@link seedDataset}. */
37
+ export interface SeedSummary<TManifest extends Manifest> {
38
+ /** The collections that were seeded, in seed order. */
39
+ readonly collections: readonly CollectionName<TManifest>[];
40
+ /** The selected collections whose module does not qualify or that have no records, in seed order. */
41
+ readonly skipped: readonly SkippedCollection<TManifest>[];
42
+ /** The number of records that were sent. */
43
+ readonly sent: number;
44
+ /** The number of records that the platform already stored and that were left as they were. */
45
+ readonly existing: number;
46
+ }
47
+ /**
48
+ * Seeds a dataset into the platform, collection by collection in the order of the manifest.
49
+ *
50
+ * @remarks
51
+ * - The run covers every collection, or the ones in `only`, except those whose module is not installed or not in its
52
+ * range of versions. Collections without records are skipped too.
53
+ * - The manifest entries of the collections in the run are checked before the first request. A collection sent in one
54
+ * request cannot have a `parentField` or `${RECORD:field}` placeholders in its `path` and `ifMatchPath`.
55
+ * - A record that the `findPath` of its collection finds is left as it is.
56
+ * - The finisher of a collection runs right after the collection.
57
+ * - The first failure stops the run. A success status with `succeeded: false` in the body also counts as a failure,
58
+ * because some endpoints refuse a record that way.
59
+ * - `onEvent` receives each step, as a {@link SeedEvent}; a failure is reported before it is thrown, and the run
60
+ * always ends with a `finished` event.
61
+ *
62
+ * @param run - The client, the manifest, the dataset, the installed modules and the options.
63
+ * @returns What the run seeded and skipped.
64
+ * @throws {Error} A manifest entry is invalid, the installed version of a module cannot be compared with its range, a
65
+ * record cannot be sent, a request fails, a finisher fails, or `onEvent` fails. The message names the collection and,
66
+ * where there is one, the record, and has secrets masked. The cause is the original error.
67
+ * @throws {AggregateError} The run failed, and `onEvent` failed too while it reported the failure. The errors are the
68
+ * failure of the run, then the failure of `onEvent`.
69
+ */
70
+ export declare function seedDataset<TManifest extends Manifest>(run: SeedRun<TManifest>): Promise<SeedSummary<TManifest>>;