@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.
- package/.biome/formatter.json +11 -0
- package/.biome/imports.json +52 -0
- package/.biome/preset.json +4 -0
- package/.biome/rules.json +45 -0
- package/.claude/agents/qa-automation-expert.md +119 -0
- package/.claude/agents/qa-coverage.md +96 -0
- package/.claude/agents/qa-explorer.md +112 -0
- package/.claude/agents/qa-healer.md +88 -0
- package/.claude/agents/qa-judge.md +102 -0
- package/.claude/agents/qa-planner.md +104 -0
- package/.claude/agents/qa-reviewer.md +121 -0
- package/.claude/checks/browser-secrets.mts +107 -0
- package/.claude/checks/contract.mts +469 -0
- package/.claude/checks/expectation-guard.mts +665 -0
- package/.claude/checks/explore-extractors.mts +4 -0
- package/.claude/checks/judge-verdict.mts +165 -0
- package/.claude/checks/project-facts.mts +491 -0
- package/.claude/checks/prove-fails.mts +770 -0
- package/.claude/checks/rank-gaps.mts +177 -0
- package/.claude/checks/readonly-shell.mts +740 -0
- package/.claude/checks/reconcile-run.mts +270 -0
- package/.claude/checks/scan-prompts.mts +351 -0
- package/.claude/checks/stand.mts +45 -0
- package/.claude/checks/test-duration.mts +134 -0
- package/.claude/checks/test-shape.mts +224 -0
- package/.claude/checks/ticket-card.mts +195 -0
- package/.claude/commands/qa-coverage.md +13 -0
- package/.claude/commands/qa-explore.md +17 -0
- package/.claude/commands/qa-heal.md +44 -0
- package/.claude/commands/qa-implement.md +60 -0
- package/.claude/commands/qa-plan.md +55 -0
- package/.claude/commands/qa-review.md +90 -0
- package/.claude/commands/qa.md +156 -0
- package/.claude/hooks/readonly-shell.mts +65 -0
- package/.claude/settings.json +15 -0
- package/.claude/skills/coverage-analysis/SKILL.md +107 -0
- package/.claude/skills/create-graphql-layer/SKILL.md +159 -0
- package/.claude/skills/create-ui-layer/SKILL.md +189 -0
- package/.claude/skills/explore-api/SKILL.md +74 -0
- package/.claude/skills/explore-frontend/SKILL.md +85 -0
- package/.claude/skills/framework-rules/SKILL.md +189 -0
- package/.claude/skills/heal-tests/SKILL.md +197 -0
- package/.claude/skills/heal-tests/guard-recipe.md +53 -0
- package/.claude/skills/judge-criteria/SKILL.md +40 -0
- package/.claude/skills/judge-criteria/coverage.md +9 -0
- package/.claude/skills/judge-criteria/expert.md +23 -0
- package/.claude/skills/judge-criteria/explorer.md +9 -0
- package/.claude/skills/judge-criteria/healer.md +13 -0
- package/.claude/skills/judge-criteria/planner.md +12 -0
- package/.claude/skills/plan-implementation/SKILL.md +82 -0
- package/.claude/skills/plan-implementation/contract-template.md +72 -0
- package/.claude/skills/plan-test-strategy/SKILL.md +100 -0
- package/.claude/skills/project-facts/SKILL.md +130 -0
- package/.claude/skills/read-change/SKILL.md +64 -0
- package/.claude/skills/read-ticket/SKILL.md +63 -0
- package/.claude/skills/read-ticket/providers.md +58 -0
- package/.claude/skills/review-pr/SKILL.md +152 -0
- package/.claude/skills/review-test-code/SKILL.md +208 -0
- package/.claude/skills/write-e2e-test/SKILL.md +175 -0
- package/.claude/skills/write-graphql-test/SKILL.md +158 -0
- package/.claude/skills/write-rest-api-test/SKILL.md +182 -0
- package/.claude/skills/write-security-test/SKILL.md +253 -0
- package/.qa/project.example.json +71 -0
- package/CHANGELOG.md +1 -0
- package/LICENSE +12 -0
- package/README.md +53 -2
- package/bin/install-qa-agents.mjs +94 -0
- package/dist/auth/credentials.d.ts +10 -0
- package/dist/auth/credentials.js +2 -0
- package/dist/auth/credentials.js.map +1 -0
- package/dist/auth/frontend-browser-sessions.d.ts +71 -0
- package/dist/auth/frontend-browser-sessions.js +130 -0
- package/dist/auth/frontend-browser-sessions.js.map +1 -0
- package/dist/auth/index.d.ts +9 -0
- package/dist/auth/index.js +5 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/auth/platform-browser-sessions.d.ts +47 -0
- package/dist/auth/platform-browser-sessions.js +92 -0
- package/dist/auth/platform-browser-sessions.js.map +1 -0
- package/dist/auth/sign-in-lock.d.ts +14 -0
- package/dist/auth/sign-in-lock.js +70 -0
- package/dist/auth/sign-in-lock.js.map +1 -0
- package/dist/auth/storage-state.d.ts +3 -0
- package/dist/auth/storage-state.js +2 -0
- package/dist/auth/storage-state.js.map +1 -0
- package/dist/auth/token-client.d.ts +82 -0
- package/dist/auth/token-client.js +111 -0
- package/dist/auth/token-client.js.map +1 -0
- package/dist/auth/token-manager.d.ts +67 -0
- package/dist/auth/token-manager.js +138 -0
- package/dist/auth/token-manager.js.map +1 -0
- package/dist/core/default-reporters.d.ts +31 -0
- package/dist/core/default-reporters.js +36 -0
- package/dist/core/default-reporters.js.map +1 -0
- package/dist/core/default-use.d.ts +28 -0
- package/dist/core/default-use.js +25 -0
- package/dist/core/default-use.js.map +1 -0
- package/dist/core/env.d.ts +24 -0
- package/dist/core/env.js +33 -0
- package/dist/core/env.js.map +1 -0
- package/dist/core/error-message.d.ts +10 -0
- package/dist/core/error-message.js +13 -0
- package/dist/core/error-message.js.map +1 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +11 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/is-ci.d.ts +14 -0
- package/dist/core/is-ci.js +18 -0
- package/dist/core/is-ci.js.map +1 -0
- package/dist/core/parse-env.d.ts +13 -0
- package/dist/core/parse-env.js +21 -0
- package/dist/core/parse-env.js.map +1 -0
- package/dist/core/projects.d.ts +24 -0
- package/dist/core/projects.js +33 -0
- package/dist/core/projects.js.map +1 -0
- package/dist/core/run-options.d.ts +31 -0
- package/dist/core/run-options.js +43 -0
- package/dist/core/run-options.js.map +1 -0
- package/dist/core/secret.d.ts +105 -0
- package/dist/core/secret.js +167 -0
- package/dist/core/secret.js.map +1 -0
- package/dist/core/string-schemas.d.ts +39 -0
- package/dist/core/string-schemas.js +56 -0
- package/dist/core/string-schemas.js.map +1 -0
- package/dist/core/url-path.d.ts +7 -0
- package/dist/core/url-path.js +2 -0
- package/dist/core/url-path.js.map +1 -0
- package/dist/dataset/collection.d.ts +44 -0
- package/dist/dataset/collection.js +76 -0
- package/dist/dataset/collection.js.map +1 -0
- package/dist/dataset/index.d.ts +11 -0
- package/dist/dataset/index.js +6 -0
- package/dist/dataset/index.js.map +1 -0
- package/dist/dataset/load-dataset.d.ts +39 -0
- package/dist/dataset/load-dataset.js +62 -0
- package/dist/dataset/load-dataset.js.map +1 -0
- package/dist/dataset/manifest.d.ts +77 -0
- package/dist/dataset/manifest.js +10 -0
- package/dist/dataset/manifest.js.map +1 -0
- package/dist/dataset/placeholders.d.ts +66 -0
- package/dist/dataset/placeholders.js +87 -0
- package/dist/dataset/placeholders.js.map +1 -0
- package/dist/dataset/seed-collection.d.ts +53 -0
- package/dist/dataset/seed-collection.js +115 -0
- package/dist/dataset/seed-collection.js.map +1 -0
- package/dist/dataset/seed-dataset.d.ts +70 -0
- package/dist/dataset/seed-dataset.js +138 -0
- package/dist/dataset/seed-dataset.js.map +1 -0
- package/dist/dataset/seed-events.d.ts +81 -0
- package/dist/dataset/seed-events.js +2 -0
- package/dist/dataset/seed-events.js.map +1 -0
- package/dist/dataset/seed-requests.d.ts +102 -0
- package/dist/dataset/seed-requests.js +160 -0
- package/dist/dataset/seed-requests.js.map +1 -0
- package/dist/dataset/seed-scope.d.ts +39 -0
- package/dist/dataset/seed-scope.js +67 -0
- package/dist/dataset/seed-scope.js.map +1 -0
- package/dist/fixtures/default-fixtures.d.ts +93 -0
- package/dist/fixtures/default-fixtures.js +105 -0
- package/dist/fixtures/default-fixtures.js.map +1 -0
- package/dist/fixtures/index.d.ts +2 -0
- package/dist/fixtures/index.js +2 -0
- package/dist/fixtures/index.js.map +1 -0
- package/dist/graphql/graphql-client.d.ts +78 -0
- package/dist/graphql/graphql-client.js +83 -0
- package/dist/graphql/graphql-client.js.map +1 -0
- package/dist/graphql/graphql-codegen.d.ts +56 -0
- package/dist/graphql/graphql-codegen.js +42 -0
- package/dist/graphql/graphql-codegen.js.map +1 -0
- package/dist/graphql/graphql-error.d.ts +54 -0
- package/dist/graphql/graphql-error.js +74 -0
- package/dist/graphql/graphql-error.js.map +1 -0
- package/dist/graphql/index.d.ts +6 -0
- package/dist/graphql/index.js +4 -0
- package/dist/graphql/index.js.map +1 -0
- package/dist/http/authentication.d.ts +16 -0
- package/dist/http/authentication.js +2 -0
- package/dist/http/authentication.js.map +1 -0
- package/dist/http/http-client.d.ts +110 -0
- package/dist/http/http-client.js +237 -0
- package/dist/http/http-client.js.map +1 -0
- package/dist/http/http-error.d.ts +26 -0
- package/dist/http/http-error.js +34 -0
- package/dist/http/http-error.js.map +1 -0
- package/dist/http/http-method.d.ts +2 -0
- package/dist/http/http-method.js +2 -0
- package/dist/http/http-method.js.map +1 -0
- package/dist/http/http-response.d.ts +137 -0
- package/dist/http/http-response.js +166 -0
- package/dist/http/http-response.js.map +1 -0
- package/dist/http/index.d.ts +7 -0
- package/dist/http/index.js +4 -0
- package/dist/http/index.js.map +1 -0
- package/dist/http/request-options.d.ts +62 -0
- package/dist/http/request-options.js +2 -0
- package/dist/http/request-options.js.map +1 -0
- package/dist/modules/index.d.ts +2 -0
- package/dist/modules/index.js +2 -0
- package/dist/modules/index.js.map +1 -0
- package/dist/modules/installed-modules.d.ts +86 -0
- package/dist/modules/installed-modules.js +135 -0
- package/dist/modules/installed-modules.js.map +1 -0
- package/docs/README.md +43 -0
- package/docs/concepts/areas.md +38 -0
- package/docs/concepts/auth.md +92 -0
- package/docs/concepts/config.md +102 -0
- package/docs/concepts/dataset.md +183 -0
- package/docs/concepts/environment.md +54 -0
- package/docs/concepts/fixtures.md +109 -0
- package/docs/concepts/graphql.md +76 -0
- package/docs/concepts/http.md +88 -0
- package/docs/concepts/modules.md +63 -0
- package/docs/concepts/secrets.md +50 -0
- package/docs/contributing/architecture.md +67 -0
- package/docs/contributing/conventions.md +39 -0
- package/docs/contributing/documentation.md +37 -0
- package/docs/contributing/releasing.md +76 -0
- package/docs/examples/auth.ts +20 -0
- package/docs/examples/config.ts +36 -0
- package/docs/examples/dataset.ts +70 -0
- package/docs/examples/environment.ts +8 -0
- package/docs/examples/fixtures.ts +41 -0
- package/docs/examples/getting-started.ts +22 -0
- package/docs/examples/graphql-codegen.ts +9 -0
- package/docs/examples/graphql.ts +32 -0
- package/docs/examples/http.ts +18 -0
- package/docs/examples/modules.ts +19 -0
- package/docs/examples/secrets.ts +11 -0
- package/docs/examples/tsconfig.json +10 -0
- package/docs/getting-started.md +106 -0
- package/docs/guides/generating-types.md +75 -0
- package/docs/guides/qa-agents.md +66 -0
- package/package.json +156 -4
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { inspect } from "node:util";
|
|
2
|
+
/** The text that replaces a secret value in string conversion, JSON serialization, console output and masked text. */
|
|
3
|
+
export const MASKED = "[SECRET]";
|
|
4
|
+
/** The minimum length of a secret value. A shorter value cannot be masked without also masking ordinary text. */
|
|
5
|
+
export const SECRET_MIN_LENGTH = 4;
|
|
6
|
+
const maskedValues = new Set();
|
|
7
|
+
let maskPattern;
|
|
8
|
+
/**
|
|
9
|
+
* Represents a password, token or key whose value never appears in output. String conversion, JSON serialization and
|
|
10
|
+
* console output produce {@link MASKED}.
|
|
11
|
+
*
|
|
12
|
+
* @remarks
|
|
13
|
+
* Each value created by {@link Secret.of} is registered for {@link maskSecrets} for the lifetime of the process.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* const password = Secret.of("Password1!");
|
|
17
|
+
* `${password}`; // "[SECRET]"
|
|
18
|
+
* JSON.stringify({ password }); // '{"password":"[SECRET]"}'
|
|
19
|
+
* password.reveal(); // "Password1!"
|
|
20
|
+
* maskSecrets("password=Password1%21"); // "password=[SECRET]"
|
|
21
|
+
*/
|
|
22
|
+
export class Secret {
|
|
23
|
+
#value;
|
|
24
|
+
constructor(value) {
|
|
25
|
+
this.#value = value;
|
|
26
|
+
Object.freeze(this);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Creates a secret and registers its value for {@link maskSecrets} in plain, URI-encoded, form-encoded and
|
|
30
|
+
* JSON-escaped forms.
|
|
31
|
+
*
|
|
32
|
+
* @param value - The plain value.
|
|
33
|
+
* @returns The secret that holds the value.
|
|
34
|
+
* @throws {RangeError} The value is shorter than {@link SECRET_MIN_LENGTH}. The message does not contain the value.
|
|
35
|
+
*/
|
|
36
|
+
static of(value) {
|
|
37
|
+
if (value.length < SECRET_MIN_LENGTH) {
|
|
38
|
+
throw new RangeError(`A secret must have at least ${SECRET_MIN_LENGTH} characters`);
|
|
39
|
+
}
|
|
40
|
+
const registered = maskedValues.size;
|
|
41
|
+
for (const encoded of encodingsOf(value)) {
|
|
42
|
+
maskedValues.add(encoded);
|
|
43
|
+
}
|
|
44
|
+
if (maskedValues.size !== registered) {
|
|
45
|
+
maskPattern = undefined;
|
|
46
|
+
}
|
|
47
|
+
return new Secret(value);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Determines whether this secret and another secret hold the same value, without revealing either value.
|
|
51
|
+
*
|
|
52
|
+
* @param other - The secret to compare with.
|
|
53
|
+
* @returns `true` if the values are equal; otherwise, `false`.
|
|
54
|
+
*/
|
|
55
|
+
equals(other) {
|
|
56
|
+
return this.#value === other.#value;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Returns a secret that holds a prefix followed by this value, such as the value of an `Authorization` header.
|
|
60
|
+
*
|
|
61
|
+
* @remarks
|
|
62
|
+
* The new value is not registered for {@link maskSecrets}, because this value already is, and it is masked as a whole
|
|
63
|
+
* token when the prefix ends with a character other than a letter or a digit, such as a space.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* accessToken.withPrefix("Bearer "); // the secret "Bearer <token>"
|
|
67
|
+
*
|
|
68
|
+
* @param prefix - The text before the value, such as `Bearer `.
|
|
69
|
+
* @returns The new secret.
|
|
70
|
+
*/
|
|
71
|
+
withPrefix(prefix) {
|
|
72
|
+
return new Secret(prefix + this.#value);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Returns the plain value.
|
|
76
|
+
*
|
|
77
|
+
* @remarks
|
|
78
|
+
* Call this method only where the value is sent or stored. Keep the result out of messages, logs and assertions.
|
|
79
|
+
*/
|
|
80
|
+
reveal() {
|
|
81
|
+
return this.#value;
|
|
82
|
+
}
|
|
83
|
+
/** Returns {@link MASKED} instead of the value. */
|
|
84
|
+
toString() {
|
|
85
|
+
return MASKED;
|
|
86
|
+
}
|
|
87
|
+
/** Returns {@link MASKED} instead of the value. It is called during JSON serialization. */
|
|
88
|
+
toJSON() {
|
|
89
|
+
return MASKED;
|
|
90
|
+
}
|
|
91
|
+
/** Returns {@link MASKED} instead of the value. It is called when the secret is printed to the console. */
|
|
92
|
+
[inspect.custom]() {
|
|
93
|
+
return MASKED;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Replaces each registered secret value in a text with {@link MASKED}.
|
|
98
|
+
*
|
|
99
|
+
* @remarks
|
|
100
|
+
* A value is replaced only where it stands as a whole token: `admin` is masked in `password=admin`, but not in
|
|
101
|
+
* `administrator`. Use this function for error messages and logs that can contain requests or responses.
|
|
102
|
+
*
|
|
103
|
+
* @param text - The text to mask.
|
|
104
|
+
* @returns The text in which each registered secret value is replaced with {@link MASKED}.
|
|
105
|
+
*/
|
|
106
|
+
export function maskSecrets(text) {
|
|
107
|
+
if (maskedValues.size === 0) {
|
|
108
|
+
return text;
|
|
109
|
+
}
|
|
110
|
+
maskPattern ??= buildMaskPattern();
|
|
111
|
+
return text.replace(maskPattern, MASKED);
|
|
112
|
+
}
|
|
113
|
+
function buildMaskPattern() {
|
|
114
|
+
const alternatives = [...maskedValues]
|
|
115
|
+
.sort((left, right) => right.length - left.length)
|
|
116
|
+
.map(escapeRegExp)
|
|
117
|
+
.join("|");
|
|
118
|
+
return new RegExp(`(?<![\\p{L}\\p{N}])(?:${alternatives})(?![\\p{L}\\p{N}])`, "gu");
|
|
119
|
+
}
|
|
120
|
+
function encodingsOf(value) {
|
|
121
|
+
return [
|
|
122
|
+
value,
|
|
123
|
+
encodeURIComponent(value),
|
|
124
|
+
new URLSearchParams({ value }).toString().slice("value=".length),
|
|
125
|
+
JSON.stringify(value).slice(1, -1),
|
|
126
|
+
];
|
|
127
|
+
}
|
|
128
|
+
function escapeRegExp(text) {
|
|
129
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Returns a copy of fields such as headers or form values with each {@link Secret} replaced by its value.
|
|
133
|
+
*
|
|
134
|
+
* @remarks
|
|
135
|
+
* Call this function only where the values are sent. Keep the result out of messages, logs and assertions.
|
|
136
|
+
*
|
|
137
|
+
* @param fields - The fields to reveal.
|
|
138
|
+
* @returns A copy of the fields in which each {@link Secret} is replaced by its value.
|
|
139
|
+
*/
|
|
140
|
+
export function revealedFields(fields) {
|
|
141
|
+
return Object.fromEntries(Object.entries(fields).map(([name, value]) => [
|
|
142
|
+
name,
|
|
143
|
+
value instanceof Secret ? value.reveal() : value,
|
|
144
|
+
]));
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Serializes a value to JSON with each {@link Secret}, at any depth, written as its value.
|
|
148
|
+
*
|
|
149
|
+
* @remarks
|
|
150
|
+
* Call this function only where the JSON is sent. Keep the result out of messages, logs and assertions.
|
|
151
|
+
*
|
|
152
|
+
* @param value - The value to serialize.
|
|
153
|
+
* @returns The JSON text.
|
|
154
|
+
* @throws {TypeError} The value is `undefined`, a function or a symbol.
|
|
155
|
+
*/
|
|
156
|
+
export function revealedJson(value) {
|
|
157
|
+
const json = JSON.stringify(value, revealSecrets);
|
|
158
|
+
if (json === undefined) {
|
|
159
|
+
throw new TypeError("The value cannot be serialized to JSON");
|
|
160
|
+
}
|
|
161
|
+
return json;
|
|
162
|
+
}
|
|
163
|
+
function revealSecrets(key, value) {
|
|
164
|
+
const original = this[key];
|
|
165
|
+
return original instanceof Secret ? original.reveal() : value;
|
|
166
|
+
}
|
|
167
|
+
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AAE,CAAC,CAAC,CAAC;KACnC,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,IAAY;IAChC,OAAO,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,cAAc,CAAI,MAA4C;IAC5E,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAuB,EAAE,EAAE,CAAC;QAClE,IAAI;QACJ,KAAK,YAAY,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,KAAK;KACjD,CAAC,CACH,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;IAClD,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,MAAM,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC;IAChE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,aAAa,CAAgB,GAAW,EAAE,KAAc;IAC/D,MAAM,QAAQ,GAAI,IAA0C,CAAC,GAAG,CAAC,CAAC;IAClE,OAAO,QAAQ,YAAY,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;AAChE,CAAC","sourcesContent":["import { inspect } from \"node:util\";\n\n/** The text that replaces a secret value in string conversion, JSON serialization, console output and masked text. */\nexport const MASKED = \"[SECRET]\";\n\n/** The minimum length of a secret value. A shorter value cannot be masked without also masking ordinary text. */\nexport const SECRET_MIN_LENGTH = 4;\n\n/**\n * A type in which every string can also be a {@link Secret}. It describes plain JSON values that are revealed only when\n * sent, such as request bodies and GraphQL variables.\n */\nexport type SecretsAllowed<T> = T extends string\n ? T | Secret\n : T extends readonly (infer Item)[]\n ? readonly SecretsAllowed<Item>[]\n : T extends object\n ? { readonly [K in keyof T]: SecretsAllowed<T[K]> }\n : T;\n\nconst maskedValues = new Set<string>();\nlet maskPattern: RegExp | undefined;\n\n/**\n * Represents a password, token or key whose value never appears in output. String conversion, JSON serialization and\n * console output produce {@link MASKED}.\n *\n * @remarks\n * Each value created by {@link Secret.of} is registered for {@link maskSecrets} for the lifetime of the process.\n *\n * @example\n * const password = Secret.of(\"Password1!\");\n * `${password}`; // \"[SECRET]\"\n * JSON.stringify({ password }); // '{\"password\":\"[SECRET]\"}'\n * password.reveal(); // \"Password1!\"\n * maskSecrets(\"password=Password1%21\"); // \"password=[SECRET]\"\n */\nexport class Secret {\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n Object.freeze(this);\n }\n\n /**\n * Creates a secret and registers its value for {@link maskSecrets} in plain, URI-encoded, form-encoded and\n * JSON-escaped forms.\n *\n * @param value - The plain value.\n * @returns The secret that holds the value.\n * @throws {RangeError} The value is shorter than {@link SECRET_MIN_LENGTH}. The message does not contain the value.\n */\n static of(value: string): Secret {\n if (value.length < SECRET_MIN_LENGTH) {\n throw new RangeError(`A secret must have at least ${SECRET_MIN_LENGTH} characters`);\n }\n const registered = maskedValues.size;\n for (const encoded of encodingsOf(value)) {\n maskedValues.add(encoded);\n }\n if (maskedValues.size !== registered) {\n maskPattern = undefined;\n }\n return new Secret(value);\n }\n\n /**\n * Determines whether this secret and another secret hold the same value, without revealing either value.\n *\n * @param other - The secret to compare with.\n * @returns `true` if the values are equal; otherwise, `false`.\n */\n equals(other: Secret): boolean {\n return this.#value === other.#value;\n }\n\n /**\n * Returns a secret that holds a prefix followed by this value, such as the value of an `Authorization` header.\n *\n * @remarks\n * The new value is not registered for {@link maskSecrets}, because this value already is, and it is masked as a whole\n * token when the prefix ends with a character other than a letter or a digit, such as a space.\n *\n * @example\n * accessToken.withPrefix(\"Bearer \"); // the secret \"Bearer <token>\"\n *\n * @param prefix - The text before the value, such as `Bearer `.\n * @returns The new secret.\n */\n withPrefix(prefix: string): Secret {\n return new Secret(prefix + this.#value);\n }\n\n /**\n * Returns the plain value.\n *\n * @remarks\n * Call this method only where the value is sent or stored. Keep the result out of messages, logs and assertions.\n */\n reveal(): string {\n return this.#value;\n }\n\n /** Returns {@link MASKED} instead of the value. */\n toString(): string {\n return MASKED;\n }\n\n /** Returns {@link MASKED} instead of the value. It is called during JSON serialization. */\n toJSON(): string {\n return MASKED;\n }\n\n /** Returns {@link MASKED} instead of the value. It is called when the secret is printed to the console. */\n [inspect.custom](): string {\n return MASKED;\n }\n}\n\n/**\n * Replaces each registered secret value in a text with {@link MASKED}.\n *\n * @remarks\n * A value is replaced only where it stands as a whole token: `admin` is masked in `password=admin`, but not in\n * `administrator`. Use this function for error messages and logs that can contain requests or responses.\n *\n * @param text - The text to mask.\n * @returns The text in which each registered secret value is replaced with {@link MASKED}.\n */\nexport function maskSecrets(text: string): string {\n if (maskedValues.size === 0) {\n return text;\n }\n maskPattern ??= buildMaskPattern();\n return text.replace(maskPattern, MASKED);\n}\n\nfunction buildMaskPattern(): RegExp {\n const alternatives = [...maskedValues]\n .sort((left: string, right: string) => right.length - left.length)\n .map(escapeRegExp)\n .join(\"|\");\n return new RegExp(`(?<![\\\\p{L}\\\\p{N}])(?:${alternatives})(?![\\\\p{L}\\\\p{N}])`, \"gu\");\n}\n\nfunction encodingsOf(value: string): string[] {\n return [\n value,\n encodeURIComponent(value),\n new URLSearchParams({ value }).toString().slice(\"value=\".length),\n JSON.stringify(value).slice(1, -1),\n ];\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Returns a copy of fields such as headers or form values with each {@link Secret} replaced by its value.\n *\n * @remarks\n * Call this function only where the values are sent. Keep the result out of messages, logs and assertions.\n *\n * @param fields - The fields to reveal.\n * @returns A copy of the fields in which each {@link Secret} is replaced by its value.\n */\nexport function revealedFields<V>(fields: Readonly<Record<string, V | Secret>>): Record<string, V | string> {\n return Object.fromEntries(\n Object.entries(fields).map(([name, value]: [string, V | Secret]) => [\n name,\n value instanceof Secret ? value.reveal() : value,\n ]),\n );\n}\n\n/**\n * Serializes a value to JSON with each {@link Secret}, at any depth, written as its value.\n *\n * @remarks\n * Call this function only where the JSON is sent. Keep the result out of messages, logs and assertions.\n *\n * @param value - The value to serialize.\n * @returns The JSON text.\n * @throws {TypeError} The value is `undefined`, a function or a symbol.\n */\nexport function revealedJson(value: unknown): string {\n const json = JSON.stringify(value, revealSecrets);\n if (json === undefined) {\n throw new TypeError(\"The value cannot be serialized to JSON\");\n }\n return json;\n}\n\nfunction revealSecrets(this: unknown, key: string, value: unknown): unknown {\n const original = (this as Readonly<Record<string, unknown>>)[key];\n return original instanceof Secret ? original.reveal() : value;\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Secret } from "./secret.ts";
|
|
2
|
+
/**
|
|
3
|
+
* A string that has at least one character other than whitespace. The string is not trimmed, so `" pass word "`
|
|
4
|
+
* stays as given.
|
|
5
|
+
*/
|
|
6
|
+
export declare const nonBlankString: import("zod").ZodString;
|
|
7
|
+
/**
|
|
8
|
+
* An absolute HTTP or HTTPS URL without a user name or password, because URLs can appear in error messages.
|
|
9
|
+
*/
|
|
10
|
+
export declare const absoluteUrl: import("zod").ZodURL;
|
|
11
|
+
/**
|
|
12
|
+
* An {@link absoluteUrl} without a path, query or fragment, returned as its canonical origin so that origins can be
|
|
13
|
+
* compared with `===`.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* A URL with a path is rejected rather than shortened, because requests resolve against the origin only: with
|
|
17
|
+
* `http://host/platform`, a request to `api/x` would go to `http://host/api/x`.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* originUrl.parse("HTTPS://Host:443/"); // "https://host"
|
|
21
|
+
*/
|
|
22
|
+
export declare const originUrl: import("zod").ZodPipe<import("zod").ZodURL, import("zod").ZodTransform<string, string>>;
|
|
23
|
+
/**
|
|
24
|
+
* A positive integer written in decimal digits, returned as a number. It is meant for environment variables, not for
|
|
25
|
+
* JSON values.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* positiveInt.parse("5000"); // 5000
|
|
29
|
+
*/
|
|
30
|
+
export declare const positiveInt: import("zod").ZodPipe<import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodTransform<number, string>>, import("zod").ZodNumber>;
|
|
31
|
+
/**
|
|
32
|
+
* The string `"true"` or `"false"`, returned as a boolean. Any other value, such as `"1"` or `"yes"`, is rejected.
|
|
33
|
+
*/
|
|
34
|
+
export declare const booleanString: import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodTransform<boolean, string>>;
|
|
35
|
+
/**
|
|
36
|
+
* A string of at least {@link SECRET_MIN_LENGTH} characters, returned as a {@link Secret}. Error messages do not
|
|
37
|
+
* contain the value.
|
|
38
|
+
*/
|
|
39
|
+
export declare const secretString: import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodTransform<Secret, string>>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { number, string, url } from "zod";
|
|
2
|
+
import { SECRET_MIN_LENGTH, Secret } from "./secret.js";
|
|
3
|
+
/**
|
|
4
|
+
* A string that has at least one character other than whitespace. The string is not trimmed, so `" pass word "`
|
|
5
|
+
* stays as given.
|
|
6
|
+
*/
|
|
7
|
+
export const nonBlankString = string().regex(/\S/, "must not be blank");
|
|
8
|
+
/**
|
|
9
|
+
* An absolute HTTP or HTTPS URL without a user name or password, because URLs can appear in error messages.
|
|
10
|
+
*/
|
|
11
|
+
export const absoluteUrl = url({ protocol: /^https?$/ }).refine((value) => {
|
|
12
|
+
const parsed = URL.parse(value);
|
|
13
|
+
return parsed === null || (parsed.username === "" && parsed.password === "");
|
|
14
|
+
}, "must not contain credentials");
|
|
15
|
+
/**
|
|
16
|
+
* An {@link absoluteUrl} without a path, query or fragment, returned as its canonical origin so that origins can be
|
|
17
|
+
* compared with `===`.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* A URL with a path is rejected rather than shortened, because requests resolve against the origin only: with
|
|
21
|
+
* `http://host/platform`, a request to `api/x` would go to `http://host/api/x`.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* originUrl.parse("HTTPS://Host:443/"); // "https://host"
|
|
25
|
+
*/
|
|
26
|
+
export const originUrl = absoluteUrl
|
|
27
|
+
.refine((value) => {
|
|
28
|
+
const parsed = URL.parse(value);
|
|
29
|
+
return parsed === null || (parsed.pathname === "/" && parsed.search === "" && parsed.hash === "");
|
|
30
|
+
}, "must be an origin without a path, query or fragment, such as http://localhost:8090")
|
|
31
|
+
.transform((value) => new URL(value).origin);
|
|
32
|
+
/**
|
|
33
|
+
* A positive integer written in decimal digits, returned as a number. It is meant for environment variables, not for
|
|
34
|
+
* JSON values.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* positiveInt.parse("5000"); // 5000
|
|
38
|
+
*/
|
|
39
|
+
export const positiveInt = string()
|
|
40
|
+
.regex(/^\d+$/, "must be decimal digits")
|
|
41
|
+
.transform(Number)
|
|
42
|
+
.pipe(number().int().positive());
|
|
43
|
+
/**
|
|
44
|
+
* The string `"true"` or `"false"`, returned as a boolean. Any other value, such as `"1"` or `"yes"`, is rejected.
|
|
45
|
+
*/
|
|
46
|
+
export const booleanString = string()
|
|
47
|
+
.regex(/^(true|false)$/, "must be true or false")
|
|
48
|
+
.transform((value) => value === "true");
|
|
49
|
+
/**
|
|
50
|
+
* A string of at least {@link SECRET_MIN_LENGTH} characters, returned as a {@link Secret}. Error messages do not
|
|
51
|
+
* contain the value.
|
|
52
|
+
*/
|
|
53
|
+
export const secretString = string()
|
|
54
|
+
.min(SECRET_MIN_LENGTH, `must have at least ${SECRET_MIN_LENGTH} characters`)
|
|
55
|
+
.transform((value) => Secret.of(value));
|
|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;;GAMG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,MAAM,EAAE;KAChC,KAAK,CAAC,OAAO,EAAE,wBAAwB,CAAC;KACxC,SAAS,CAAC,MAAM,CAAC;KACjB,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;AAEnC;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,EAAE;KAClC,KAAK,CAAC,gBAAgB,EAAE,uBAAuB,CAAC;KAChD,SAAS,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,KAAK,KAAK,MAAM,CAAC,CAAC;AAElD;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,EAAE;KACjC,GAAG,CAAC,iBAAiB,EAAE,sBAAsB,iBAAiB,aAAa,CAAC;KAC5E,SAAS,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC","sourcesContent":["import { number, string, url } from \"zod\";\n\nimport { SECRET_MIN_LENGTH, Secret } from \"./secret.ts\";\n\n/**\n * A string that has at least one character other than whitespace. The string is not trimmed, so `\" pass word \"`\n * stays as given.\n */\nexport const nonBlankString = string().regex(/\\S/, \"must not be blank\");\n\n/**\n * An absolute HTTP or HTTPS URL without a user name or password, because URLs can appear in error messages.\n */\nexport const absoluteUrl = url({ protocol: /^https?$/ }).refine((value: string) => {\n const parsed = URL.parse(value);\n return parsed === null || (parsed.username === \"\" && parsed.password === \"\");\n}, \"must not contain credentials\");\n\n/**\n * An {@link absoluteUrl} without a path, query or fragment, returned as its canonical origin so that origins can be\n * compared with `===`.\n *\n * @remarks\n * A URL with a path is rejected rather than shortened, because requests resolve against the origin only: with\n * `http://host/platform`, a request to `api/x` would go to `http://host/api/x`.\n *\n * @example\n * originUrl.parse(\"HTTPS://Host:443/\"); // \"https://host\"\n */\nexport const originUrl = absoluteUrl\n .refine((value: string) => {\n const parsed = URL.parse(value);\n return parsed === null || (parsed.pathname === \"/\" && parsed.search === \"\" && parsed.hash === \"\");\n }, \"must be an origin without a path, query or fragment, such as http://localhost:8090\")\n .transform((value: string) => new URL(value).origin);\n\n/**\n * A positive integer written in decimal digits, returned as a number. It is meant for environment variables, not for\n * JSON values.\n *\n * @example\n * positiveInt.parse(\"5000\"); // 5000\n */\nexport const positiveInt = string()\n .regex(/^\\d+$/, \"must be decimal digits\")\n .transform(Number)\n .pipe(number().int().positive());\n\n/**\n * The string `\"true\"` or `\"false\"`, returned as a boolean. Any other value, such as `\"1\"` or `\"yes\"`, is rejected.\n */\nexport const booleanString = string()\n .regex(/^(true|false)$/, \"must be true or false\")\n .transform((value: string) => value === \"true\");\n\n/**\n * A string of at least {@link SECRET_MIN_LENGTH} characters, returned as a {@link Secret}. Error messages do not\n * contain the value.\n */\nexport const secretString = string()\n .min(SECRET_MIN_LENGTH, `must have at least ${SECRET_MIN_LENGTH} characters`)\n .transform((value: string) => Secret.of(value));\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A URL path that starts with `/`, such as `/api/catalog/catalogs`, resolved against the base URL of a client.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* The type only checks the leading `/`. A client still refuses a path that resolves to another origin.
|
|
6
|
+
*/
|
|
7
|
+
export type UrlPath = `/${string}`;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"url-path.js","sourceRoot":"","sources":["../../src/core/url-path.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * A URL path that starts with `/`, such as `/api/catalog/catalogs`, resolved against the base URL of a client.\n *\n * @remarks\n * The type only checks the leading `/`. A client still refuses a path that resolves to another origin.\n */\nexport type UrlPath = `/${string}`;\n"]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Represents the records of one dataset collection, with lookups by identifier.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* The records are frozen. Copy a record to build a request body instead of changing it.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const laptop = dataset.products.get("product-laptop-acer-swift-go-14");
|
|
9
|
+
*/
|
|
10
|
+
export declare class Collection<T extends object> {
|
|
11
|
+
#private;
|
|
12
|
+
/** The name of the collection in the manifest. */
|
|
13
|
+
readonly name: string;
|
|
14
|
+
/**
|
|
15
|
+
* Creates a collection.
|
|
16
|
+
*
|
|
17
|
+
* @param name - The name of the collection.
|
|
18
|
+
* @param records - The records, in the order of their files.
|
|
19
|
+
*/
|
|
20
|
+
constructor(name: string, records: readonly T[]);
|
|
21
|
+
/** Gets the number of records. */
|
|
22
|
+
get count(): number;
|
|
23
|
+
/**
|
|
24
|
+
* Returns every record.
|
|
25
|
+
*
|
|
26
|
+
* @returns The records, in the order of their files.
|
|
27
|
+
*/
|
|
28
|
+
all(): readonly T[];
|
|
29
|
+
/**
|
|
30
|
+
* Returns the record with an identifier.
|
|
31
|
+
*
|
|
32
|
+
* @param id - The `id` of the record.
|
|
33
|
+
* @returns The record.
|
|
34
|
+
* @throws {Error} No record has the identifier, or two records share an identifier.
|
|
35
|
+
*/
|
|
36
|
+
get(id: string): T;
|
|
37
|
+
/**
|
|
38
|
+
* Returns the records that match a condition.
|
|
39
|
+
*
|
|
40
|
+
* @param predicate - The condition.
|
|
41
|
+
* @returns The matching records, in the order of their files.
|
|
42
|
+
*/
|
|
43
|
+
filter(predicate: (record: T) => boolean): T[];
|
|
44
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Represents the records of one dataset collection, with lookups by identifier.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* The records are frozen. Copy a record to build a request body instead of changing it.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const laptop = dataset.products.get("product-laptop-acer-swift-go-14");
|
|
9
|
+
*/
|
|
10
|
+
export class Collection {
|
|
11
|
+
/** The name of the collection in the manifest. */
|
|
12
|
+
name;
|
|
13
|
+
#records;
|
|
14
|
+
#byId;
|
|
15
|
+
/**
|
|
16
|
+
* Creates a collection.
|
|
17
|
+
*
|
|
18
|
+
* @param name - The name of the collection.
|
|
19
|
+
* @param records - The records, in the order of their files.
|
|
20
|
+
*/
|
|
21
|
+
constructor(name, records) {
|
|
22
|
+
this.name = name;
|
|
23
|
+
this.#records = Object.freeze([...records]);
|
|
24
|
+
}
|
|
25
|
+
/** Gets the number of records. */
|
|
26
|
+
get count() {
|
|
27
|
+
return this.#records.length;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Returns every record.
|
|
31
|
+
*
|
|
32
|
+
* @returns The records, in the order of their files.
|
|
33
|
+
*/
|
|
34
|
+
all() {
|
|
35
|
+
return this.#records;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Returns the record with an identifier.
|
|
39
|
+
*
|
|
40
|
+
* @param id - The `id` of the record.
|
|
41
|
+
* @returns The record.
|
|
42
|
+
* @throws {Error} No record has the identifier, or two records share an identifier.
|
|
43
|
+
*/
|
|
44
|
+
get(id) {
|
|
45
|
+
this.#byId ??= indexById(this.name, this.#records);
|
|
46
|
+
const record = this.#byId.get(id);
|
|
47
|
+
if (record === undefined) {
|
|
48
|
+
throw new Error(`The dataset collection ${this.name} has no record "${id}"`);
|
|
49
|
+
}
|
|
50
|
+
return record;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Returns the records that match a condition.
|
|
54
|
+
*
|
|
55
|
+
* @param predicate - The condition.
|
|
56
|
+
* @returns The matching records, in the order of their files.
|
|
57
|
+
*/
|
|
58
|
+
filter(predicate) {
|
|
59
|
+
return this.#records.filter(predicate);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function indexById(name, records) {
|
|
63
|
+
const byId = new Map();
|
|
64
|
+
for (const record of records) {
|
|
65
|
+
const id = Reflect.get(record, "id");
|
|
66
|
+
if (typeof id !== "string") {
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (byId.has(id)) {
|
|
70
|
+
throw new Error(`The dataset collection ${name} has more than one record "${id}"`);
|
|
71
|
+
}
|
|
72
|
+
byId.set(id, record);
|
|
73
|
+
}
|
|
74
|
+
return byId;
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=collection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collection.js","sourceRoot":"","sources":["../../src/dataset/collection.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,OAAO,UAAU;IACrB,kDAAkD;IACzC,IAAI,CAAS;IACb,QAAQ,CAAe;IAChC,KAAK,CAAqC;IAE1C;;;;;OAKG;IACH,YAAY,IAAY,EAAE,OAAqB;QAC7C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAC9C,CAAC;IAED,kCAAkC;IAClC,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;IAC9B,CAAC;IAED;;;;OAIG;IACH,GAAG;QACD,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;;;;;OAMG;IACH,GAAG,CAAC,EAAU;QACZ,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAClC,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,0BAA0B,IAAI,CAAC,IAAI,mBAAmB,EAAE,GAAG,CAAC,CAAC;QAC/E,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,SAAiC;QACtC,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACzC,CAAC;CACF;AAED,SAAS,SAAS,CAAmB,IAAY,EAAE,OAAqB;IACtE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAa,CAAC;IAClC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,EAAE,GAAY,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC9C,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE,CAAC;YAC3B,SAAS;QACX,CAAC;QACD,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,0BAA0B,IAAI,8BAA8B,EAAE,GAAG,CAAC,CAAC;QACrF,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Represents the records of one dataset collection, with lookups by identifier.\n *\n * @remarks\n * The records are frozen. Copy a record to build a request body instead of changing it.\n *\n * @example\n * const laptop = dataset.products.get(\"product-laptop-acer-swift-go-14\");\n */\nexport class Collection<T extends object> {\n /** The name of the collection in the manifest. */\n readonly name: string;\n readonly #records: readonly T[];\n #byId: ReadonlyMap<string, T> | undefined;\n\n /**\n * Creates a collection.\n *\n * @param name - The name of the collection.\n * @param records - The records, in the order of their files.\n */\n constructor(name: string, records: readonly T[]) {\n this.name = name;\n this.#records = Object.freeze([...records]);\n }\n\n /** Gets the number of records. */\n get count(): number {\n return this.#records.length;\n }\n\n /**\n * Returns every record.\n *\n * @returns The records, in the order of their files.\n */\n all(): readonly T[] {\n return this.#records;\n }\n\n /**\n * Returns the record with an identifier.\n *\n * @param id - The `id` of the record.\n * @returns The record.\n * @throws {Error} No record has the identifier, or two records share an identifier.\n */\n get(id: string): T {\n this.#byId ??= indexById(this.name, this.#records);\n const record = this.#byId.get(id);\n if (record === undefined) {\n throw new Error(`The dataset collection ${this.name} has no record \"${id}\"`);\n }\n return record;\n }\n\n /**\n * Returns the records that match a condition.\n *\n * @param predicate - The condition.\n * @returns The matching records, in the order of their files.\n */\n filter(predicate: (record: T) => boolean): T[] {\n return this.#records.filter(predicate);\n }\n}\n\nfunction indexById<T extends object>(name: string, records: readonly T[]): ReadonlyMap<string, T> {\n const byId = new Map<string, T>();\n for (const record of records) {\n const id: unknown = Reflect.get(record, \"id\");\n if (typeof id !== \"string\") {\n continue;\n }\n if (byId.has(id)) {\n throw new Error(`The dataset collection ${name} has more than one record \"${id}\"`);\n }\n byId.set(id, record);\n }\n return byId;\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type { Dataset, DatasetRecord, LoadDatasetOptions } from "./load-dataset.ts";
|
|
2
|
+
export type { CollectionName, CollectionSpec, Manifest, StoredIdLookup } from "./manifest.ts";
|
|
3
|
+
export type { PlaceholderValues } from "./placeholders.ts";
|
|
4
|
+
export type { SeedableDataset, SeedFinisher, SeedRun, SeedSummary } from "./seed-dataset.ts";
|
|
5
|
+
export type { SeedCollectionFailed, SeedCounts, SeedEvent, SeedFinished, SeedManifestFailed, SeedSeeded, SeedSkipped, SeedStarted, } from "./seed-events.ts";
|
|
6
|
+
export type { SkippedCollection } from "./seed-scope.ts";
|
|
7
|
+
export { Collection } from "./collection.ts";
|
|
8
|
+
export { loadDataset } from "./load-dataset.ts";
|
|
9
|
+
export { envPlaceholder, recordPlaceholder } from "./placeholders.ts";
|
|
10
|
+
export { seedDataset } from "./seed-dataset.ts";
|
|
11
|
+
export { parseCollectionNames } from "./seed-scope.ts";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { Collection } from "./collection.js";
|
|
2
|
+
export { loadDataset } from "./load-dataset.js";
|
|
3
|
+
export { envPlaceholder, recordPlaceholder } from "./placeholders.js";
|
|
4
|
+
export { seedDataset } from "./seed-dataset.js";
|
|
5
|
+
export { parseCollectionNames } from "./seed-scope.js";
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/dataset/index.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC","sourcesContent":["export type { Dataset, DatasetRecord, LoadDatasetOptions } from \"./load-dataset.ts\";\nexport type { CollectionName, CollectionSpec, Manifest, StoredIdLookup } from \"./manifest.ts\";\nexport type { PlaceholderValues } from \"./placeholders.ts\";\nexport type { SeedableDataset, SeedFinisher, SeedRun, SeedSummary } from \"./seed-dataset.ts\";\nexport type {\n SeedCollectionFailed,\n SeedCounts,\n SeedEvent,\n SeedFinished,\n SeedManifestFailed,\n SeedSeeded,\n SeedSkipped,\n SeedStarted,\n} from \"./seed-events.ts\";\nexport type { SkippedCollection } from \"./seed-scope.ts\";\n\nexport { Collection } from \"./collection.ts\";\nexport { loadDataset } from \"./load-dataset.ts\";\nexport { envPlaceholder, recordPlaceholder } from \"./placeholders.ts\";\nexport { seedDataset } from \"./seed-dataset.ts\";\nexport { parseCollectionNames } from \"./seed-scope.ts\";\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { CollectionName, Manifest } from "./manifest.ts";
|
|
2
|
+
import type { PlaceholderValues } from "./placeholders.ts";
|
|
3
|
+
import { Collection } from "./collection.ts";
|
|
4
|
+
/** A record without a known type: a JSON object. */
|
|
5
|
+
export type DatasetRecord = Readonly<Record<string, unknown>>;
|
|
6
|
+
/**
|
|
7
|
+
* A loaded dataset: one {@link Collection} for each collection of a manifest.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* `TRecords` gives the record type of collections by name, such as the types generated from the platform. Collections
|
|
11
|
+
* that it does not name hold {@link DatasetRecord} values.
|
|
12
|
+
*/
|
|
13
|
+
export type Dataset<TManifest extends Manifest, TRecords extends object = object> = {
|
|
14
|
+
readonly [Name in CollectionName<TManifest>]: Collection<Name extends keyof TRecords ? Extract<TRecords[Name], object> : DatasetRecord>;
|
|
15
|
+
};
|
|
16
|
+
/** The options of {@link loadDataset}. */
|
|
17
|
+
export interface LoadDatasetOptions<TManifest extends Manifest> {
|
|
18
|
+
/** The collections to load. */
|
|
19
|
+
readonly manifest: TManifest;
|
|
20
|
+
/** The directory that holds one directory for each collection. */
|
|
21
|
+
readonly dataDir: string;
|
|
22
|
+
/** The values of the `${ENV:key}` placeholders in the data files. */
|
|
23
|
+
readonly placeholders?: PlaceholderValues | undefined;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Loads a dataset from JSON files.
|
|
27
|
+
*
|
|
28
|
+
* @remarks
|
|
29
|
+
* Each collection reads the `.json` files in its directory and its subdirectories, in the order of their paths with `/`
|
|
30
|
+
* as the separator, so the order is the same on every operating system. The `${ENV:key}`
|
|
31
|
+
* placeholders in the files are filled in, and the records are frozen. A collection without a directory is empty. The
|
|
32
|
+
* record types are not checked at run time.
|
|
33
|
+
*
|
|
34
|
+
* @param options - The manifest, the data directory and the placeholder values.
|
|
35
|
+
* @returns The dataset.
|
|
36
|
+
* @throws {Error} A file is not valid JSON, does not hold a JSON object, or has a placeholder without a value. The
|
|
37
|
+
* message names the file and has secrets masked.
|
|
38
|
+
*/
|
|
39
|
+
export declare function loadDataset<TManifest extends Manifest, TRecords extends object = object>(options: LoadDatasetOptions<TManifest>): Dataset<TManifest, TRecords>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join, relative, sep } from "node:path";
|
|
3
|
+
import { errorMessage, maskSecrets } from "../core/index.js";
|
|
4
|
+
import { Collection } from "./collection.js";
|
|
5
|
+
import { collectionDirectory } from "./manifest.js";
|
|
6
|
+
import { envSource, fillPlaceholders, jsonStringContent } from "./placeholders.js";
|
|
7
|
+
/**
|
|
8
|
+
* Loads a dataset from JSON files.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* Each collection reads the `.json` files in its directory and its subdirectories, in the order of their paths with `/`
|
|
12
|
+
* as the separator, so the order is the same on every operating system. The `${ENV:key}`
|
|
13
|
+
* placeholders in the files are filled in, and the records are frozen. A collection without a directory is empty. The
|
|
14
|
+
* record types are not checked at run time.
|
|
15
|
+
*
|
|
16
|
+
* @param options - The manifest, the data directory and the placeholder values.
|
|
17
|
+
* @returns The dataset.
|
|
18
|
+
* @throws {Error} A file is not valid JSON, does not hold a JSON object, or has a placeholder without a value. The
|
|
19
|
+
* message names the file and has secrets masked.
|
|
20
|
+
*/
|
|
21
|
+
export function loadDataset(options) {
|
|
22
|
+
const values = options.placeholders ?? {};
|
|
23
|
+
const collections = {};
|
|
24
|
+
for (const name of Object.keys(options.manifest)) {
|
|
25
|
+
const dir = join(options.dataDir, collectionDirectory(name));
|
|
26
|
+
collections[name] = new Collection(name, readRecords(dir, options.dataDir, values));
|
|
27
|
+
}
|
|
28
|
+
return collections;
|
|
29
|
+
}
|
|
30
|
+
function readRecords(dir, dataDir, values) {
|
|
31
|
+
if (!existsSync(dir)) {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
return readdirSync(dir, { withFileTypes: true, recursive: true })
|
|
35
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
|
|
36
|
+
.map((entry) => relative(dataDir, join(entry.parentPath, entry.name)).split(sep).join("/"))
|
|
37
|
+
.sort()
|
|
38
|
+
.map((name) => readRecord(join(dataDir, name), name, values));
|
|
39
|
+
}
|
|
40
|
+
function readRecord(path, name, values) {
|
|
41
|
+
try {
|
|
42
|
+
const text = fillPlaceholders(readFileSync(path, "utf8"), { ENV: envSource(values) }, jsonStringContent);
|
|
43
|
+
const record = JSON.parse(text);
|
|
44
|
+
if (typeof record !== "object" || record === null || Array.isArray(record)) {
|
|
45
|
+
throw new Error("the file does not hold a JSON object");
|
|
46
|
+
}
|
|
47
|
+
return deepFreeze(record);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
throw new Error(maskSecrets(`The dataset file ${name}: ${errorMessage(error)}`));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function deepFreeze(value) {
|
|
54
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
55
|
+
for (const item of Object.values(value)) {
|
|
56
|
+
deepFreeze(item);
|
|
57
|
+
}
|
|
58
|
+
Object.freeze(value);
|
|
59
|
+
}
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=load-dataset.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-dataset.js","sourceRoot":"","sources":["../../src/dataset/load-dataset.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAEnD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AA4BnF;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,WAAW,CACzB,OAAsC;IAEtC,MAAM,MAAM,GAAG,OAAO,CAAC,YAAY,IAAI,EAAE,CAAC;IAC1C,MAAM,WAAW,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AAI,GAAG,gBAAgB,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,EAAE,GAAG,EAAE,SAAS,CAAC,MAAM,CAAC,EAAE,EAAE,iBAAiB,CAAC,CAAC;QACzG,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YAC3E,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,oBAAoB,IAAI,KAAK,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;IACnF,CAAC;AACH,CAAC;AAED,SAAS,UAAU,CAAI,KAAQ;IAC7B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3E,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YACxC,UAAU,CAAC,IAAI,CAAC,CAAC;QACnB,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { CollectionName, Manifest } from \"./manifest.ts\";\nimport type { PlaceholderValues } from \"./placeholders.ts\";\n\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\n\nimport { errorMessage, maskSecrets } from \"@/core\";\n\nimport { Collection } from \"./collection.ts\";\nimport { collectionDirectory } from \"./manifest.ts\";\nimport { envSource, fillPlaceholders, jsonStringContent } from \"./placeholders.ts\";\n\n/** A record without a known type: a JSON object. */\nexport type DatasetRecord = Readonly<Record<string, unknown>>;\n\n/**\n * A loaded dataset: one {@link Collection} for each collection of a manifest.\n *\n * @remarks\n * `TRecords` gives the record type of collections by name, such as the types generated from the platform. Collections\n * that it does not name hold {@link DatasetRecord} values.\n */\nexport type Dataset<TManifest extends Manifest, TRecords extends object = object> = {\n readonly [Name in CollectionName<TManifest>]: Collection<\n Name extends keyof TRecords ? Extract<TRecords[Name], object> : DatasetRecord\n >;\n};\n\n/** The options of {@link loadDataset}. */\nexport interface LoadDatasetOptions<TManifest extends Manifest> {\n /** The collections to load. */\n readonly manifest: TManifest;\n /** The directory that holds one directory for each collection. */\n readonly dataDir: string;\n /** The values of the `${ENV:key}` placeholders in the data files. */\n readonly placeholders?: PlaceholderValues | undefined;\n}\n\n/**\n * Loads a dataset from JSON files.\n *\n * @remarks\n * Each collection reads the `.json` files in its directory and its subdirectories, in the order of their paths with `/`\n * as the separator, so the order is the same on every operating system. The `${ENV:key}`\n * placeholders in the files are filled in, and the records are frozen. A collection without a directory is empty. The\n * record types are not checked at run time.\n *\n * @param options - The manifest, the data directory and the placeholder values.\n * @returns The dataset.\n * @throws {Error} A file is not valid JSON, does not hold a JSON object, or has a placeholder without a value. The\n * message names the file and has secrets masked.\n */\nexport function loadDataset<TManifest extends Manifest, TRecords extends object = object>(\n options: LoadDatasetOptions<TManifest>,\n): Dataset<TManifest, TRecords> {\n const values = options.placeholders ?? {};\n const collections: Record<string, Collection<object>> = {};\n for (const name of Object.keys(options.manifest)) {\n const dir = join(options.dataDir, collectionDirectory(name));\n collections[name] = new Collection(name, readRecords(dir, options.dataDir, values));\n }\n return collections as Dataset<TManifest, TRecords>;\n}\n\nfunction readRecords(dir: string, dataDir: string, values: PlaceholderValues): object[] {\n if (!existsSync(dir)) {\n return [];\n }\n return readdirSync(dir, { withFileTypes: true, recursive: true })\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .map((entry) => relative(dataDir, join(entry.parentPath, entry.name)).split(sep).join(\"/\"))\n .sort()\n .map((name) => readRecord(join(dataDir, name), name, values));\n}\n\nfunction readRecord(path: string, name: string, values: PlaceholderValues): object {\n try {\n const text = fillPlaceholders(readFileSync(path, \"utf8\"), { ENV: envSource(values) }, jsonStringContent);\n const record: unknown = JSON.parse(text);\n if (typeof record !== \"object\" || record === null || Array.isArray(record)) {\n throw new Error(\"the file does not hold a JSON object\");\n }\n return deepFreeze(record);\n } catch (error) {\n throw new Error(maskSecrets(`The dataset file ${name}: ${errorMessage(error)}`));\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value === \"object\" && value !== null && !Object.isFrozen(value)) {\n for (const item of Object.values(value)) {\n deepFreeze(item);\n }\n Object.freeze(value);\n }\n return value;\n}\n"]}
|