@nikhil-qeas/api-core 0.6.0 → 0.8.0
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/CHANGELOG.md +67 -0
- package/README.md +216 -5
- package/bin/qe-api.js +3 -0
- package/dist/contracts/assertions.d.ts +11 -0
- package/dist/contracts/assertions.js +31 -0
- package/dist/contracts/openapi.d.ts +28 -1
- package/dist/contracts/openapi.js +113 -0
- package/dist/graphql/graphql.d.ts +86 -0
- package/dist/graphql/graphql.js +312 -0
- package/dist/http/api-client.d.ts +20 -0
- package/dist/http/api-client.js +70 -9
- package/dist/http/cookies.d.ts +32 -0
- package/dist/http/cookies.js +116 -0
- package/dist/http/multipart.d.ts +20 -0
- package/dist/http/multipart.js +48 -0
- package/dist/http/trace.d.ts +26 -0
- package/dist/http/trace.js +43 -0
- package/dist/http/types.d.ts +22 -0
- package/dist/index.d.ts +31 -5
- package/dist/index.js +16 -3
- package/dist/integrations/mocha.d.ts +32 -0
- package/dist/integrations/mocha.js +81 -0
- package/dist/reporting/html-report.d.ts +23 -0
- package/dist/reporting/html-report.js +118 -0
- package/dist/reporting/junit.d.ts +11 -2
- package/dist/reporting/junit.js +9 -3
- package/dist/reporting/redaction.d.ts +10 -0
- package/dist/reporting/redaction.js +36 -2
- package/dist/security/authorization-matrix.d.ts +55 -0
- package/dist/security/authorization-matrix.js +102 -0
- package/dist/security/headers.d.ts +21 -0
- package/dist/security/headers.js +45 -0
- package/dist/security/policy.js +3 -2
- package/dist/security/sensitive-data.d.ts +22 -0
- package/dist/security/sensitive-data.js +76 -0
- package/dist/testing/json-path.d.ts +6 -0
- package/dist/testing/json-path.js +97 -0
- package/dist/testing/load.d.ts +85 -0
- package/dist/testing/load.js +134 -0
- package/dist/testing/matchers.d.ts +63 -0
- package/dist/testing/matchers.js +164 -0
- package/dist/testing/spec-cases.d.ts +136 -0
- package/dist/testing/spec-cases.js +1065 -0
- package/dist/testing/wait-for.d.ts +40 -0
- package/dist/testing/wait-for.js +82 -0
- package/package.json +1 -1
- package/templates/project/README.md +80 -5
- package/templates/project/__dot__env.example +4 -0
- package/templates/project/__dot__gitlab-ci.yml +1 -0
- package/templates/project/openapi/openapi.json +476 -19
- package/templates/project/src/clients/api.ts +4 -2
- package/templates/project/src/environment.ts +8 -0
- package/templates/project/src/observability.ts +15 -1
- package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
- package/templates/project/tests/performance/health.spec.ts +22 -0
- package/templates/project/tests/security/authentication.spec.ts +3 -1
- package/templates/project/tests/security/authorization.spec.ts +29 -0
- package/templates/project/tests/security/hygiene.spec.ts +37 -0
- package/templates/project/tests/security/spec-cases.spec.ts +61 -0
- package/templates/project/tests/security/write-protection.spec.ts +2 -2
- package/templates/project/tests/setup/hooks.ts +32 -5
- package/templates/project/tests/smoke/health.spec.ts +3 -3
- package/templates/project/tests/smoke/tracing.spec.ts +48 -0
- package/templates/project/tests/support/approved-writes.ts +27 -0
- package/templates/project/tests/support/identities.ts +24 -0
- package/templates/project/tests/support/mock-api.ts +166 -3
|
@@ -33,6 +33,53 @@ function resolveResponse(doc, raw) {
|
|
|
33
33
|
}
|
|
34
34
|
return current;
|
|
35
35
|
}
|
|
36
|
+
/** Resolves a parameter or request body object, following local `#/components/<bucket>/*` references. Fails closed on anything else. */
|
|
37
|
+
function resolveComponent(doc, raw, bucket, label) {
|
|
38
|
+
const prefix = `#/components/${bucket}/`;
|
|
39
|
+
const seen = new Set();
|
|
40
|
+
let current = object(raw, label);
|
|
41
|
+
while (typeof current.$ref === 'string') {
|
|
42
|
+
const ref = current.$ref;
|
|
43
|
+
if (!ref.startsWith(prefix))
|
|
44
|
+
throw new Error(`Only local component ${label} references are permitted`);
|
|
45
|
+
if (seen.has(ref))
|
|
46
|
+
throw new Error(`Cyclic ${label} reference`);
|
|
47
|
+
seen.add(ref);
|
|
48
|
+
const name = unescapePointer(ref.slice(prefix.length));
|
|
49
|
+
const container = doc.components?.[bucket] ?? {};
|
|
50
|
+
if (!name || !Object.prototype.hasOwnProperty.call(container, name))
|
|
51
|
+
throw new Error(`Unresolved component ${label}`);
|
|
52
|
+
current = object(container[name], label);
|
|
53
|
+
}
|
|
54
|
+
return current;
|
|
55
|
+
}
|
|
56
|
+
/** Query, path and header values arrive as strings; give them the type the schema asks for so "5" can satisfy `type: integer`. */
|
|
57
|
+
function coerceParameter(value, schema) {
|
|
58
|
+
if (Array.isArray(value)) {
|
|
59
|
+
const items = schema.items !== null && typeof schema.items === 'object' && !Array.isArray(schema.items) ? schema.items : {};
|
|
60
|
+
return value.map(entry => coerceParameter(entry, items));
|
|
61
|
+
}
|
|
62
|
+
if (typeof value !== 'string')
|
|
63
|
+
return value;
|
|
64
|
+
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
|
65
|
+
if ((types.includes('integer') || types.includes('number')) && /^-?\d+(\.\d+)?$/.test(value))
|
|
66
|
+
return Number(value);
|
|
67
|
+
if (types.includes('boolean')) {
|
|
68
|
+
if (value === 'true')
|
|
69
|
+
return true;
|
|
70
|
+
if (value === 'false')
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
function asList(value) { return Array.isArray(value) ? value : []; }
|
|
76
|
+
function headerValue(headers, name) {
|
|
77
|
+
const wanted = name.toLowerCase();
|
|
78
|
+
for (const [key, value] of Object.entries(headers ?? {}))
|
|
79
|
+
if (key.toLowerCase() === wanted)
|
|
80
|
+
return value;
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
36
83
|
const SCHEMA_KEYWORDS = ['items', 'additionalProperties', 'additionalItems', 'not', 'contains', 'propertyNames', 'if', 'then', 'else', 'unevaluatedProperties', 'unevaluatedItems'];
|
|
37
84
|
const SCHEMA_LIST_KEYWORDS = ['oneOf', 'anyOf', 'allOf', 'prefixItems'];
|
|
38
85
|
const SCHEMA_MAP_KEYWORDS = ['properties', 'patternProperties', 'dependentSchemas'];
|
|
@@ -120,6 +167,7 @@ export class OpenApiValidator {
|
|
|
120
167
|
doc;
|
|
121
168
|
compiler;
|
|
122
169
|
compiled = new Map();
|
|
170
|
+
requestValidators = new Map();
|
|
123
171
|
errorDetail;
|
|
124
172
|
constructor(doc, compiler, options = {}) {
|
|
125
173
|
this.doc = doc;
|
|
@@ -161,4 +209,69 @@ export class OpenApiValidator {
|
|
|
161
209
|
const valid = validate(check.response.body);
|
|
162
210
|
assert.ok(valid, this.errorDetail === 'schema' ? `${base} Violations: ${describeViolations(validate.errors)}` : `${base} Error details suppressed to protect response data`);
|
|
163
211
|
}
|
|
212
|
+
/**
|
|
213
|
+
* Checks a request against the operation's parameters and request body: required parameters present, values matching
|
|
214
|
+
* their schemas, a body when one is required, a declared content type, and a body matching its schema.
|
|
215
|
+
* Messages name the offending parameter or body and never include the values.
|
|
216
|
+
*/
|
|
217
|
+
assertRequest(check) {
|
|
218
|
+
const label = `${check.method} ${check.path}`;
|
|
219
|
+
const fail = (what, errors) => {
|
|
220
|
+
const detail = this.errorDetail === 'schema' && errors !== undefined ? ` Violations: ${describeViolations(errors)}` : '';
|
|
221
|
+
return assert.fail(`OpenAPI request contract failed (${label}): ${what}.${detail}`);
|
|
222
|
+
};
|
|
223
|
+
const pathItem = object(this.doc.paths[check.path], 'path');
|
|
224
|
+
const op = object(pathItem[check.method.toLowerCase()], 'operation');
|
|
225
|
+
const declared = new Map(); // an operation parameter overrides a path-level one of the same name
|
|
226
|
+
for (const raw of [...asList(pathItem.parameters), ...asList(op.parameters)]) {
|
|
227
|
+
const parameter = resolveComponent(this.doc, raw, 'parameters', 'parameter');
|
|
228
|
+
declared.set(`${String(parameter.in)}:${String(parameter.name)}`, parameter);
|
|
229
|
+
}
|
|
230
|
+
for (const parameter of declared.values()) {
|
|
231
|
+
const { name } = parameter;
|
|
232
|
+
const location = parameter.in;
|
|
233
|
+
if (typeof name !== 'string' || (location !== 'path' && location !== 'query' && location !== 'header'))
|
|
234
|
+
continue; // cookies are not checked
|
|
235
|
+
const value = location === 'path' ? check.pathParams?.[name] : location === 'query' ? check.query?.[name] : headerValue(check.headers, name);
|
|
236
|
+
if (value === undefined) {
|
|
237
|
+
if (parameter.required === true || location === 'path')
|
|
238
|
+
fail(`missing required ${location} parameter "${name}"`);
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (parameter.schema === undefined)
|
|
242
|
+
continue;
|
|
243
|
+
const entry = this.requestValidator(`PARAM|${label}|${location}:${name}`, parameter.schema);
|
|
244
|
+
if (!entry.validate(coerceParameter(value, entry.schema)))
|
|
245
|
+
fail(`${location} parameter "${name}" violates its schema`, entry.validate.errors);
|
|
246
|
+
}
|
|
247
|
+
const body = op.requestBody === undefined ? undefined : resolveComponent(this.doc, op.requestBody, 'requestBodies', 'request body');
|
|
248
|
+
if (check.json === undefined) {
|
|
249
|
+
if (body?.required === true)
|
|
250
|
+
fail('the required request body is missing');
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (!body)
|
|
254
|
+
return fail('the operation declares no request body');
|
|
255
|
+
const content = object(body.content ?? {}, 'request body content');
|
|
256
|
+
const actualType = mediaType(check.contentType ?? 'application/json');
|
|
257
|
+
const selected = content[actualType] ?? (actualType.endsWith('+json') ? content['application/json'] : undefined);
|
|
258
|
+
if (!selected)
|
|
259
|
+
return fail(`the content type ${actualType} is not declared for the request body`);
|
|
260
|
+
const schema = object(selected, 'media type').schema;
|
|
261
|
+
if (schema === undefined)
|
|
262
|
+
return;
|
|
263
|
+
const entry = this.requestValidator(`BODY|${label}|${actualType}`, schema);
|
|
264
|
+
if (!entry.validate(check.json))
|
|
265
|
+
fail('the request body does not match its schema', entry.validate.errors);
|
|
266
|
+
}
|
|
267
|
+
/** Compiles a request-side schema once and remembers its normalized form, which says which types it asks for. */
|
|
268
|
+
requestValidator(key, schema) {
|
|
269
|
+
let entry = this.requestValidators.get(key);
|
|
270
|
+
if (!entry) {
|
|
271
|
+
const normalized = normalizeRoot(this.doc, schema, this.compiler.supportsRefs === true);
|
|
272
|
+
entry = { validate: this.compiler.compile(normalized), schema: normalized };
|
|
273
|
+
this.requestValidators.set(key, entry);
|
|
274
|
+
}
|
|
275
|
+
return entry;
|
|
276
|
+
}
|
|
164
277
|
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { ApiRequest, ApiResult } from '../http/types.js';
|
|
2
|
+
export type OperationKind = 'query' | 'mutation' | 'subscription';
|
|
3
|
+
export interface DocumentOperation {
|
|
4
|
+
kind: OperationKind;
|
|
5
|
+
name?: string | undefined;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The operations a document defines (fragments are not operations), or undefined when the document cannot be read with certainty:
|
|
9
|
+
* unbalanced brackets, an unterminated string, a character GraphQL does not use, or a definition that is not executable.
|
|
10
|
+
* Comments, strings and field names that merely say "mutation" are never mistaken for the keyword.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseOperations(document: string): DocumentOperation[] | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* What running the document would do: the kind of the operation the server will select. 'unknown' when that cannot be told for
|
|
15
|
+
* certain (a document that does not parse, several operations and no matching `operationName`), which callers must treat as a write.
|
|
16
|
+
*/
|
|
17
|
+
export declare function operationKind(document: string, operationName?: string): OperationKind | 'unknown';
|
|
18
|
+
/** Anything that sends requests: an `ApiClient`, or the generated project's policy-enforcing client. */
|
|
19
|
+
export interface GraphQLTransport {
|
|
20
|
+
request<T = unknown>(request: ApiRequest): Promise<ApiResult<T>>;
|
|
21
|
+
}
|
|
22
|
+
export interface GraphQLClientOptions {
|
|
23
|
+
/** The endpoint. Default `/graphql`. */
|
|
24
|
+
path?: string | undefined;
|
|
25
|
+
}
|
|
26
|
+
export interface GraphQLRequest {
|
|
27
|
+
/** The document: one or more operations and fragments. */
|
|
28
|
+
query: string;
|
|
29
|
+
variables?: Record<string, unknown> | undefined;
|
|
30
|
+
/** Required by servers when the document holds several operations. */
|
|
31
|
+
operationName?: string | undefined;
|
|
32
|
+
headers?: Record<string, string> | undefined;
|
|
33
|
+
timeoutMs?: number | undefined;
|
|
34
|
+
/** Send without the client's configured credentials (negative authentication tests). */
|
|
35
|
+
skipAuth?: boolean | undefined;
|
|
36
|
+
}
|
|
37
|
+
export interface GraphQLError {
|
|
38
|
+
message?: string;
|
|
39
|
+
path?: Array<string | number>;
|
|
40
|
+
/** `extensions.code`, when the server sends one. */
|
|
41
|
+
code?: string;
|
|
42
|
+
extensions?: Record<string, unknown>;
|
|
43
|
+
}
|
|
44
|
+
export interface GraphQLResult<T = unknown> {
|
|
45
|
+
/** What the document does, as classified before sending. 'unknown' was treated as a write. */
|
|
46
|
+
operation: OperationKind | 'unknown';
|
|
47
|
+
status: number;
|
|
48
|
+
/** `undefined` when the response has no `data` key (a request error or a non-GraphQL response); `null` when the server sent null. */
|
|
49
|
+
data: T | null | undefined;
|
|
50
|
+
errors: GraphQLError[];
|
|
51
|
+
extensions?: Record<string, unknown> | undefined;
|
|
52
|
+
/** The underlying HTTP response, for header and timing checks. */
|
|
53
|
+
response: ApiResult;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* GraphQL over HTTP on top of an `ApiClient`: sends the document as a POST, classifies it, and reads `data` and `errors`.
|
|
57
|
+
*
|
|
58
|
+
* Because a query is a POST, a read-only execution policy would refuse it. The client marks a request `readOnly` (and safe to
|
|
59
|
+
* retry) only when the document provably is a query. A mutation, a subscription and anything it cannot classify are sent as the
|
|
60
|
+
* writes they may be, so a read-only run refuses them before anything is sent and they are never retried after an ambiguous failure.
|
|
61
|
+
* This trusts the GraphQL convention that a query has no side effects.
|
|
62
|
+
*/
|
|
63
|
+
export declare class GraphQLClient {
|
|
64
|
+
private readonly api;
|
|
65
|
+
private readonly path;
|
|
66
|
+
constructor(api: GraphQLTransport, options?: GraphQLClientOptions);
|
|
67
|
+
execute<T = unknown>(request: GraphQLRequest): Promise<GraphQLResult<T>>;
|
|
68
|
+
}
|
|
69
|
+
export interface GraphQLAssertOptions {
|
|
70
|
+
/** Include the servers' error messages in failures, shortened. Off by default: messages can echo data. */
|
|
71
|
+
showMessages?: boolean | undefined;
|
|
72
|
+
}
|
|
73
|
+
type Judged = Pick<GraphQLResult, 'operation' | 'status' | 'data' | 'errors'>;
|
|
74
|
+
/** Fails unless the response is HTTP 2xx, has no GraphQL errors (partial data with errors is a failure) and carries data. */
|
|
75
|
+
export declare function expectGraphQLSuccess(result: Judged, options?: GraphQLAssertOptions): void;
|
|
76
|
+
export interface ExpectedGraphQLError {
|
|
77
|
+
/** An `extensions.code` one of the errors must have. */
|
|
78
|
+
code?: string | undefined;
|
|
79
|
+
/** A path one of the errors must have: `'user.email'` or `['user', 'email']`. */
|
|
80
|
+
path?: string | readonly (string | number)[] | undefined;
|
|
81
|
+
/** The HTTP status the response must have. */
|
|
82
|
+
status?: number | undefined;
|
|
83
|
+
}
|
|
84
|
+
/** Fails unless the response carries at least one GraphQL error matching the expectation (any error at all when none is given). */
|
|
85
|
+
export declare function expectGraphQLError(result: Judged, expected?: ExpectedGraphQLError, options?: GraphQLAssertOptions): void;
|
|
86
|
+
export {};
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { credentialIn } from '../reporting/redaction.js';
|
|
3
|
+
const CLOSERS = new Map([['{', '}'], ['(', ')'], ['[', ']']]);
|
|
4
|
+
const CLOSING = new Set(CLOSERS.values());
|
|
5
|
+
const PUNCTUATION = new Set(['{', '}', '(', ')', '[', ']', ':', '=', '@', '$', '!', '|', '&']);
|
|
6
|
+
const NAME_START = /[A-Za-z_]/;
|
|
7
|
+
const NAME_PART = /[A-Za-z0-9_]/;
|
|
8
|
+
const NUMBER_PART = /[-+0-9.eE]/;
|
|
9
|
+
const SAFE_NAME = /^[A-Za-z0-9_.:$-]{1,64}$/;
|
|
10
|
+
/** Splits a GraphQL document into names and punctuation, skipping comments and strings. Undefined when it is not well-formed. */
|
|
11
|
+
function tokenize(document) {
|
|
12
|
+
const tokens = [];
|
|
13
|
+
const length = document.length;
|
|
14
|
+
let at = 0;
|
|
15
|
+
while (at < length) {
|
|
16
|
+
const c = document.charAt(at);
|
|
17
|
+
if (c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === ',' || c === '') {
|
|
18
|
+
at += 1;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (c === '#') {
|
|
22
|
+
while (at < length && document.charAt(at) !== '\n' && document.charAt(at) !== '\r')
|
|
23
|
+
at += 1;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (c === '"') {
|
|
27
|
+
if (document.startsWith('"""', at)) {
|
|
28
|
+
at += 3;
|
|
29
|
+
for (;;) {
|
|
30
|
+
if (at >= length)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (document.startsWith('\\"""', at))
|
|
33
|
+
at += 4;
|
|
34
|
+
else if (document.startsWith('"""', at)) {
|
|
35
|
+
at += 3;
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
else
|
|
39
|
+
at += 1;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
at += 1;
|
|
44
|
+
for (;;) {
|
|
45
|
+
if (at >= length)
|
|
46
|
+
return undefined;
|
|
47
|
+
const d = document.charAt(at);
|
|
48
|
+
if (d === '\n' || d === '\r')
|
|
49
|
+
return undefined;
|
|
50
|
+
if (d === '\\')
|
|
51
|
+
at += 2;
|
|
52
|
+
else if (d === '"') {
|
|
53
|
+
at += 1;
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
else
|
|
57
|
+
at += 1;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
tokens.push({ type: 'other' });
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (NAME_START.test(c)) {
|
|
64
|
+
const start = at;
|
|
65
|
+
while (at < length && NAME_PART.test(document.charAt(at)))
|
|
66
|
+
at += 1;
|
|
67
|
+
tokens.push({ type: 'name', value: document.slice(start, at) });
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (c === '-' || (c >= '0' && c <= '9')) {
|
|
71
|
+
while (at < length && NUMBER_PART.test(document.charAt(at)))
|
|
72
|
+
at += 1;
|
|
73
|
+
tokens.push({ type: 'other' });
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (c === '.') {
|
|
77
|
+
while (at < length && document.charAt(at) === '.')
|
|
78
|
+
at += 1;
|
|
79
|
+
tokens.push({ type: 'other' });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (PUNCTUATION.has(c)) {
|
|
83
|
+
tokens.push({ type: 'punct', value: c });
|
|
84
|
+
at += 1;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
return undefined; // a character GraphQL does not use: do not guess
|
|
88
|
+
}
|
|
89
|
+
return tokens;
|
|
90
|
+
}
|
|
91
|
+
/** Index just after the bracket that closes the one at `start`, or -1 when the brackets do not match. */
|
|
92
|
+
function skipBalanced(tokens, start) {
|
|
93
|
+
const expected = [];
|
|
94
|
+
for (let at = start; at < tokens.length; at += 1) {
|
|
95
|
+
const token = tokens[at];
|
|
96
|
+
if (token?.type !== 'punct')
|
|
97
|
+
continue;
|
|
98
|
+
const closer = CLOSERS.get(token.value);
|
|
99
|
+
if (closer !== undefined)
|
|
100
|
+
expected.push(closer);
|
|
101
|
+
else if (CLOSING.has(token.value)) {
|
|
102
|
+
if (expected.pop() !== token.value)
|
|
103
|
+
return -1;
|
|
104
|
+
if (expected.length === 0)
|
|
105
|
+
return at + 1;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return -1;
|
|
109
|
+
}
|
|
110
|
+
/** From the token after `query`, `mutation` or `fragment`: the index of the `{` that opens the body, and how many names (not directives) came first. */
|
|
111
|
+
function headerEnd(tokens, from) {
|
|
112
|
+
let names = 0;
|
|
113
|
+
let afterAt = false;
|
|
114
|
+
for (let at = from; at < tokens.length; at += 1) {
|
|
115
|
+
const token = tokens[at];
|
|
116
|
+
if (token?.type === 'name') {
|
|
117
|
+
if (!afterAt)
|
|
118
|
+
names += 1;
|
|
119
|
+
afterAt = false;
|
|
120
|
+
}
|
|
121
|
+
else if (token?.type === 'punct' && token.value === '{') {
|
|
122
|
+
return { brace: at, names };
|
|
123
|
+
}
|
|
124
|
+
else if (token?.type === 'punct' && token.value === '@') {
|
|
125
|
+
afterAt = true;
|
|
126
|
+
}
|
|
127
|
+
else if (token?.type === 'punct' && token.value === '(') {
|
|
128
|
+
const end = skipBalanced(tokens, at);
|
|
129
|
+
if (end < 0)
|
|
130
|
+
return undefined;
|
|
131
|
+
at = end - 1;
|
|
132
|
+
afterAt = false;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The operations a document defines (fragments are not operations), or undefined when the document cannot be read with certainty:
|
|
142
|
+
* unbalanced brackets, an unterminated string, a character GraphQL does not use, or a definition that is not executable.
|
|
143
|
+
* Comments, strings and field names that merely say "mutation" are never mistaken for the keyword.
|
|
144
|
+
*/
|
|
145
|
+
export function parseOperations(document) {
|
|
146
|
+
const tokens = tokenize(document);
|
|
147
|
+
if (tokens === undefined)
|
|
148
|
+
return undefined;
|
|
149
|
+
const operations = [];
|
|
150
|
+
let at = 0;
|
|
151
|
+
while (at < tokens.length) {
|
|
152
|
+
const token = tokens[at];
|
|
153
|
+
if (token?.type === 'punct' && token.value === '{') { // shorthand for an anonymous query
|
|
154
|
+
const end = skipBalanced(tokens, at);
|
|
155
|
+
if (end < 0)
|
|
156
|
+
return undefined;
|
|
157
|
+
operations.push({ kind: 'query' });
|
|
158
|
+
at = end;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (token?.type !== 'name')
|
|
162
|
+
return undefined;
|
|
163
|
+
const keyword = token.value;
|
|
164
|
+
if (keyword !== 'query' && keyword !== 'mutation' && keyword !== 'subscription' && keyword !== 'fragment')
|
|
165
|
+
return undefined;
|
|
166
|
+
const header = headerEnd(tokens, at + 1);
|
|
167
|
+
if (header === undefined)
|
|
168
|
+
return undefined;
|
|
169
|
+
const end = skipBalanced(tokens, header.brace);
|
|
170
|
+
if (end < 0)
|
|
171
|
+
return undefined;
|
|
172
|
+
if (keyword === 'fragment') {
|
|
173
|
+
if (header.names !== 3)
|
|
174
|
+
return undefined; // fragment Name on Type
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
if (header.names > 1)
|
|
178
|
+
return undefined; // at most the operation's name
|
|
179
|
+
const first = tokens[at + 1];
|
|
180
|
+
operations.push({ kind: keyword, name: header.names === 1 && first?.type === 'name' ? first.value : undefined });
|
|
181
|
+
}
|
|
182
|
+
at = end;
|
|
183
|
+
}
|
|
184
|
+
return operations;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* What running the document would do: the kind of the operation the server will select. 'unknown' when that cannot be told for
|
|
188
|
+
* certain (a document that does not parse, several operations and no matching `operationName`), which callers must treat as a write.
|
|
189
|
+
*/
|
|
190
|
+
export function operationKind(document, operationName) {
|
|
191
|
+
const operations = parseOperations(document);
|
|
192
|
+
if (operations === undefined || operations.length === 0)
|
|
193
|
+
return 'unknown';
|
|
194
|
+
if (operationName !== undefined && operationName !== '') {
|
|
195
|
+
const named = operations.filter(operation => operation.name === operationName);
|
|
196
|
+
const only = named[0];
|
|
197
|
+
return named.length === 1 && only !== undefined ? only.kind : 'unknown';
|
|
198
|
+
}
|
|
199
|
+
const only = operations[0];
|
|
200
|
+
return operations.length === 1 && only !== undefined ? only.kind : 'unknown';
|
|
201
|
+
}
|
|
202
|
+
function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
|
|
203
|
+
function hasHeader(headers, name) {
|
|
204
|
+
return headers !== undefined && Object.keys(headers).some(key => key.toLowerCase() === name);
|
|
205
|
+
}
|
|
206
|
+
function normalizeError(raw) {
|
|
207
|
+
const error = {};
|
|
208
|
+
if (!isRecord(raw))
|
|
209
|
+
return error;
|
|
210
|
+
if (typeof raw.message === 'string')
|
|
211
|
+
error.message = raw.message;
|
|
212
|
+
if (Array.isArray(raw.path) && raw.path.every(part => typeof part === 'string' || typeof part === 'number'))
|
|
213
|
+
error.path = raw.path;
|
|
214
|
+
if (isRecord(raw.extensions)) {
|
|
215
|
+
error.extensions = raw.extensions;
|
|
216
|
+
if (typeof raw.extensions.code === 'string')
|
|
217
|
+
error.code = raw.extensions.code;
|
|
218
|
+
}
|
|
219
|
+
return error;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* GraphQL over HTTP on top of an `ApiClient`: sends the document as a POST, classifies it, and reads `data` and `errors`.
|
|
223
|
+
*
|
|
224
|
+
* Because a query is a POST, a read-only execution policy would refuse it. The client marks a request `readOnly` (and safe to
|
|
225
|
+
* retry) only when the document provably is a query. A mutation, a subscription and anything it cannot classify are sent as the
|
|
226
|
+
* writes they may be, so a read-only run refuses them before anything is sent and they are never retried after an ambiguous failure.
|
|
227
|
+
* This trusts the GraphQL convention that a query has no side effects.
|
|
228
|
+
*/
|
|
229
|
+
export class GraphQLClient {
|
|
230
|
+
api;
|
|
231
|
+
path;
|
|
232
|
+
constructor(api, options = {}) {
|
|
233
|
+
this.api = api;
|
|
234
|
+
this.path = options.path ?? '/graphql';
|
|
235
|
+
}
|
|
236
|
+
async execute(request) {
|
|
237
|
+
if (request.query.trim() === '')
|
|
238
|
+
throw new Error('A GraphQL request needs a query document');
|
|
239
|
+
const operation = operationKind(request.query, request.operationName);
|
|
240
|
+
const headers = { ...request.headers };
|
|
241
|
+
if (!hasHeader(headers, 'accept'))
|
|
242
|
+
headers.Accept = 'application/graphql-response+json, application/json;q=0.9';
|
|
243
|
+
const response = await this.api.request({
|
|
244
|
+
method: 'POST',
|
|
245
|
+
path: this.path,
|
|
246
|
+
json: { query: request.query, ...(request.variables !== undefined ? { variables: request.variables } : {}), ...(request.operationName !== undefined ? { operationName: request.operationName } : {}) },
|
|
247
|
+
headers,
|
|
248
|
+
...(operation === 'query' ? { readOnly: true, idempotent: true } : {}),
|
|
249
|
+
...(request.timeoutMs !== undefined ? { timeoutMs: request.timeoutMs } : {}),
|
|
250
|
+
...(request.skipAuth !== undefined ? { skipAuth: request.skipAuth } : {})
|
|
251
|
+
});
|
|
252
|
+
const envelope = isRecord(response.body) ? response.body : undefined;
|
|
253
|
+
const rawErrors = envelope?.errors;
|
|
254
|
+
return {
|
|
255
|
+
operation,
|
|
256
|
+
status: response.status,
|
|
257
|
+
data: envelope !== undefined && 'data' in envelope ? envelope.data : undefined,
|
|
258
|
+
errors: Array.isArray(rawErrors) ? rawErrors.map(normalizeError) : (rawErrors === undefined || rawErrors === null ? [] : [{}]),
|
|
259
|
+
extensions: isRecord(envelope?.extensions) ? envelope.extensions : undefined,
|
|
260
|
+
response
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function pathText(path) {
|
|
265
|
+
return path.map(part => typeof part === 'number' ? String(part) : (SAFE_NAME.test(part) ? part : '?')).join('.');
|
|
266
|
+
}
|
|
267
|
+
/** What the errors are, without their messages: codes and paths are short identifiers a server has to choose from. */
|
|
268
|
+
function describeErrors(errors, showMessages) {
|
|
269
|
+
const count = `${errors.length} GraphQL error${errors.length === 1 ? '' : 's'}`;
|
|
270
|
+
const codes = [...new Set(errors.map(error => error.code).filter((code) => code !== undefined && SAFE_NAME.test(code)))].slice(0, 5);
|
|
271
|
+
const paths = [...new Set(errors.flatMap(error => error.path === undefined ? [] : [pathText(error.path)]))].slice(0, 5);
|
|
272
|
+
const parts = [count];
|
|
273
|
+
if (codes.length)
|
|
274
|
+
parts.push(`codes: ${codes.join(', ')}`);
|
|
275
|
+
if (paths.length)
|
|
276
|
+
parts.push(`paths: ${paths.join(', ')}`);
|
|
277
|
+
if (showMessages) {
|
|
278
|
+
const messages = errors.slice(0, 3).flatMap(error => error.message === undefined || credentialIn(error.message) !== undefined ? [] : [JSON.stringify(error.message.slice(0, 200))]);
|
|
279
|
+
if (messages.length)
|
|
280
|
+
parts.push(`messages: ${messages.join(', ')}`);
|
|
281
|
+
}
|
|
282
|
+
return `${parts[0]} (${parts.slice(1).join('; ') || 'no codes or paths'})`;
|
|
283
|
+
}
|
|
284
|
+
/** Fails unless the response is HTTP 2xx, has no GraphQL errors (partial data with errors is a failure) and carries data. */
|
|
285
|
+
export function expectGraphQLSuccess(result, options = {}) {
|
|
286
|
+
const problems = [];
|
|
287
|
+
if (result.status < 200 || result.status >= 300)
|
|
288
|
+
problems.push(`HTTP ${result.status}`);
|
|
289
|
+
if (result.errors.length)
|
|
290
|
+
problems.push(describeErrors(result.errors, options.showMessages === true));
|
|
291
|
+
else if (result.data === undefined || result.data === null)
|
|
292
|
+
problems.push('the response has no data');
|
|
293
|
+
if (problems.length)
|
|
294
|
+
assert.fail(`GraphQL ${result.operation === 'unknown' ? 'request' : result.operation} failed: ${problems.join('; ')}`);
|
|
295
|
+
}
|
|
296
|
+
function samePath(actual, expected) {
|
|
297
|
+
if (actual === undefined)
|
|
298
|
+
return false;
|
|
299
|
+
const wanted = typeof expected === 'string' ? expected.split('.') : expected.map(String);
|
|
300
|
+
return actual.length === wanted.length && actual.every((part, index) => String(part) === wanted[index]);
|
|
301
|
+
}
|
|
302
|
+
/** Fails unless the response carries at least one GraphQL error matching the expectation (any error at all when none is given). */
|
|
303
|
+
export function expectGraphQLError(result, expected = {}, options = {}) {
|
|
304
|
+
const wanted = [expected.code !== undefined ? `code "${expected.code}"` : '', expected.path !== undefined ? `path "${typeof expected.path === 'string' ? expected.path : expected.path.join('.')}"` : ''].filter(Boolean).join(' at ');
|
|
305
|
+
if (!result.errors.length)
|
|
306
|
+
assert.fail(`Expected a GraphQL error${wanted ? ` with ${wanted}` : ''}, but the response has none (HTTP ${result.status})`);
|
|
307
|
+
if (expected.status !== undefined && result.status !== expected.status)
|
|
308
|
+
assert.fail(`Expected HTTP ${expected.status} with a GraphQL error, got HTTP ${result.status}`);
|
|
309
|
+
const matches = result.errors.some(error => (expected.code === undefined || error.code === expected.code) && (expected.path === undefined || samePath(error.path, expected.path)));
|
|
310
|
+
if (!matches)
|
|
311
|
+
assert.fail(`Expected a GraphQL error with ${wanted}, but the response has ${describeErrors(result.errors, options.showMessages === true)}`);
|
|
312
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { TokenSource } from '../auth/token-manager.js';
|
|
2
|
+
import { CookieJar } from './cookies.js';
|
|
2
3
|
import type { RetryConfig } from './retry.js';
|
|
4
|
+
import type { TraceConfig } from './trace.js';
|
|
3
5
|
import type { ApiRequest, ApiResult, EventSink, RequestSigner } from './types.js';
|
|
4
6
|
export declare class ApiTransportError extends Error {
|
|
5
7
|
readonly kind: 'network' | 'timeout';
|
|
@@ -23,10 +25,21 @@ export interface ApiAuth {
|
|
|
23
25
|
export interface ApiClientConfig extends RetryConfig {
|
|
24
26
|
baseUrl: string;
|
|
25
27
|
auth?: ApiAuth;
|
|
28
|
+
/** Keep the cookies the server sets and send them back: `true` for a new jar, or pass your own. Off by default. Reach it as `client.cookies`. */
|
|
29
|
+
cookies?: boolean | CookieJar;
|
|
26
30
|
timeoutMs?: number;
|
|
27
31
|
maxSafeRetries?: number;
|
|
28
32
|
signer?: RequestSigner;
|
|
29
33
|
defaultHeaders?: Record<string, string>;
|
|
34
|
+
/**
|
|
35
|
+
* Send a W3C `traceparent` header so the server side can show what each request did (`true` for a new trace per request, or a
|
|
36
|
+
* `TraceConfig`, for example to put all requests of one test in one trace). Every attempt of a retried request gets its own span
|
|
37
|
+
* in the same trace. The trace id comes back as `result.traceId` and on events. Off by default. This propagates context; it does
|
|
38
|
+
* not export spans.
|
|
39
|
+
*/
|
|
40
|
+
trace?: boolean | TraceConfig;
|
|
41
|
+
/** Also send the request's id (the `requestId` on results and events) in this header, e.g. `X-Request-Id`, the same on every attempt. */
|
|
42
|
+
requestIdHeader?: string;
|
|
30
43
|
onEvent?: EventSink;
|
|
31
44
|
fetchImpl?: typeof fetch;
|
|
32
45
|
}
|
|
@@ -37,6 +50,13 @@ export declare class ApiClient {
|
|
|
37
50
|
private readonly url;
|
|
38
51
|
private readonly fetcher;
|
|
39
52
|
private readonly retryPolicy;
|
|
53
|
+
/** The cookie jar, when `cookies` is enabled. */
|
|
54
|
+
readonly cookies: CookieJar | undefined;
|
|
40
55
|
constructor(cfg: ApiClientConfig);
|
|
56
|
+
/**
|
|
57
|
+
* The trace a request joins, and how each attempt announces it. A `traceparent` header the caller set always wins (it is sent as
|
|
58
|
+
* it is, so a deliberately malformed one works for negative tests) and only supplies the trace id reported back.
|
|
59
|
+
*/
|
|
60
|
+
private traceFor;
|
|
41
61
|
request<T = unknown>(req: ApiRequest): Promise<ApiResult<T>>;
|
|
42
62
|
}
|