@t0.labs/daxta 1.1.8 → 1.2.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.
@@ -0,0 +1,150 @@
1
+ type OpenApiExample = {
2
+ summary?: string;
3
+ description?: string;
4
+ value?: unknown;
5
+ };
6
+ type OpenApiScenario = {
7
+ name: string;
8
+ group?: string;
9
+ status: number;
10
+ pathParams?: Record<string, string>;
11
+ query?: Record<string, string>;
12
+ headers?: Record<string, string>;
13
+ reqBody?: unknown;
14
+ resBody?: unknown;
15
+ };
16
+ type OpenApiOperation = {
17
+ summary?: string;
18
+ description?: string;
19
+ tags?: string[];
20
+ security?: Array<Record<string, unknown[]>>;
21
+ parameters?: Array<{
22
+ name: string;
23
+ in: string;
24
+ required?: boolean;
25
+ example?: unknown;
26
+ }>;
27
+ requestBody?: {
28
+ content?: Record<string, {
29
+ examples?: Record<string, OpenApiExample>;
30
+ }>;
31
+ };
32
+ responses?: Record<string, {
33
+ description?: string;
34
+ content?: Record<string, {
35
+ examples?: Record<string, OpenApiExample>;
36
+ }>;
37
+ }>;
38
+ 'x-tree-segments'?: string[];
39
+ 'x-scenarios'?: OpenApiScenario[];
40
+ 'x-daxta-url-path'?: string;
41
+ };
42
+ type OpenApiSpecLike = {
43
+ info?: {
44
+ title?: string;
45
+ version?: string;
46
+ description?: string;
47
+ 'x-workspace'?: string;
48
+ };
49
+ servers?: Array<{
50
+ url?: string;
51
+ description?: string;
52
+ }>;
53
+ paths?: Record<string, Record<string, OpenApiOperation>>;
54
+ };
55
+ export type PostmanHeader = {
56
+ key: string;
57
+ value: string;
58
+ type?: string;
59
+ };
60
+ export type PostmanRequest = {
61
+ method: string;
62
+ header: PostmanHeader[];
63
+ url: {
64
+ raw: string;
65
+ host: string[];
66
+ path: string[];
67
+ query?: Array<{
68
+ key: string;
69
+ value: string;
70
+ }>;
71
+ variable?: Array<{
72
+ key: string;
73
+ value: string;
74
+ }>;
75
+ };
76
+ body?: {
77
+ mode: 'raw';
78
+ raw: string;
79
+ options: {
80
+ raw: {
81
+ language: 'json';
82
+ };
83
+ };
84
+ };
85
+ description?: string;
86
+ };
87
+ export type PostmanResponseExample = {
88
+ name: string;
89
+ originalRequest: PostmanRequest;
90
+ status: string;
91
+ code: number;
92
+ _postman_previewlanguage: 'json';
93
+ header: Array<{
94
+ key: string;
95
+ value: string;
96
+ }>;
97
+ body: string;
98
+ };
99
+ export type PostmanRequestItem = {
100
+ name: string;
101
+ request: PostmanRequest;
102
+ response: PostmanResponseExample[];
103
+ };
104
+ export type PostmanFolderItem = {
105
+ name: string;
106
+ item: Array<PostmanFolderItem | PostmanRequestItem>;
107
+ };
108
+ export type PostmanCollection = {
109
+ info: {
110
+ _postman_id: string;
111
+ name: string;
112
+ description: string;
113
+ schema: string;
114
+ };
115
+ item: Array<PostmanFolderItem | PostmanRequestItem>;
116
+ };
117
+ export type PostmanEnvironment = {
118
+ id: string;
119
+ name: string;
120
+ values: Array<{
121
+ key: string;
122
+ value: string;
123
+ type: 'default' | 'secret';
124
+ enabled: boolean;
125
+ }>;
126
+ _postman_variable_scope: 'environment';
127
+ _postman_exported_at: string;
128
+ _postman_exported_using: string;
129
+ };
130
+ export declare function buildPostmanCollection(spec: OpenApiSpecLike, options?: {
131
+ useEnvVar?: boolean;
132
+ envName?: string;
133
+ }): {
134
+ collection: PostmanCollection;
135
+ operations: number;
136
+ examples: number;
137
+ };
138
+ export declare function buildPostmanEnvironment(envName?: string): PostmanEnvironment;
139
+ export declare function exportPostmanFiles(options?: {
140
+ out?: string;
141
+ envName?: string;
142
+ includeEnv?: boolean;
143
+ useEnvVar?: boolean;
144
+ }): {
145
+ collectionPath: string;
146
+ environmentPath?: string;
147
+ operations: number;
148
+ examples: number;
149
+ };
150
+ export {};
@@ -0,0 +1,351 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.buildPostmanCollection = buildPostmanCollection;
37
+ exports.buildPostmanEnvironment = buildPostmanEnvironment;
38
+ exports.exportPostmanFiles = exportPostmanFiles;
39
+ const crypto_1 = require("crypto");
40
+ const fs_1 = require("fs");
41
+ const path = __importStar(require("path"));
42
+ const catalog_1 = require("../catalog");
43
+ const config_1 = require("../config");
44
+ const paths_1 = require("../serve/paths");
45
+ const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'options', 'head'];
46
+ function postmanUrl(serverUrl, pathTemplate, pathParams, query) {
47
+ const base = (serverUrl || '{{baseUrl}}').replace(/\/$/, '');
48
+ const cleanPath = pathTemplate.startsWith('/') ? pathTemplate : `/${pathTemplate}`;
49
+ const segments = cleanPath.split('/').filter(Boolean);
50
+ const paramKeys = [...cleanPath.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
51
+ const queryEntries = Object.entries(query ?? {}).map(([key, value]) => ({
52
+ key,
53
+ value: value ?? '',
54
+ }));
55
+ const querySuffix = queryEntries.length
56
+ ? `?${queryEntries.map((q) => `${encodeURIComponent(q.key)}=${encodeURIComponent(q.value)}`).join('&')}`
57
+ : '';
58
+ return {
59
+ raw: `${base}${cleanPath.replace(/\{([^}]+)\}/g, ':$1')}${querySuffix}`,
60
+ host: base.startsWith('{{') ? [base] : [base.replace(/^https?:\/\//, '').split('/')[0]],
61
+ path: segments.map((seg) => (seg.startsWith('{') && seg.endsWith('}') ? `:${seg.slice(1, -1)}` : seg)),
62
+ ...(queryEntries.length ? { query: queryEntries } : {}),
63
+ ...(paramKeys.length
64
+ ? { variable: paramKeys.map((key) => ({ key, value: pathParams?.[key] ?? '' })) }
65
+ : {}),
66
+ };
67
+ }
68
+ function resolveConfiguredHeaderValue(key) {
69
+ const config = (0, config_1.getConfig)();
70
+ const lower = key.toLowerCase();
71
+ const fromFn = config.headerVariable?.(lower) ?? config.headerVariable?.(key);
72
+ if (fromFn)
73
+ return fromFn;
74
+ const map = config.headerVariables ?? {};
75
+ for (const [k, v] of Object.entries(map)) {
76
+ if (k.toLowerCase() === lower)
77
+ return v;
78
+ }
79
+ return undefined;
80
+ }
81
+ function buildHeaders(operation, scenarioHeaders, hasBody) {
82
+ const byLower = new Map();
83
+ const add = (key, value) => {
84
+ const lower = key.toLowerCase();
85
+ if (lower === 'host' || lower === 'content-length')
86
+ return;
87
+ const configured = lower === 'content-type' ? undefined : resolveConfiguredHeaderValue(key);
88
+ byLower.set(lower, { key, value: configured ?? value, type: 'text' });
89
+ };
90
+ for (const param of operation.parameters ?? []) {
91
+ if (param.in === 'header' && param.name) {
92
+ add(param.name, param.example != null ? String(param.example) : '');
93
+ }
94
+ }
95
+ for (const sec of operation.security ?? []) {
96
+ if ('bearerAuth' in sec && !byLower.has('authorization')) {
97
+ add('Authorization', 'Bearer {{authToken}}');
98
+ }
99
+ }
100
+ for (const [key, value] of Object.entries(scenarioHeaders ?? {})) {
101
+ add(key, value);
102
+ }
103
+ if (hasBody && !byLower.has('content-type')) {
104
+ add('Content-Type', 'application/json');
105
+ }
106
+ return [...byLower.values()];
107
+ }
108
+ function stringifyJson(value) {
109
+ if (value === undefined || value === null)
110
+ return '';
111
+ return typeof value === 'string' ? value : JSON.stringify(value, null, 2);
112
+ }
113
+ function folderSegmentsForOperation(urlPath, operation) {
114
+ const fromTree = operation['x-tree-segments'];
115
+ const parts = Array.isArray(fromTree) && fromTree.length ? fromTree.map(String) : urlPath.split('/').filter(Boolean);
116
+ const named = parts.filter((part) => part && !part.startsWith('{'));
117
+ return named.length ? named : ['API'];
118
+ }
119
+ function pushIntoFolderTree(root, segments, requestItem) {
120
+ let level = root;
121
+ for (let i = 0; i < segments.length; i += 1) {
122
+ const name = segments[i];
123
+ let folder = level.find((entry) => entry.name === name && 'item' in entry && !('request' in entry));
124
+ if (!folder) {
125
+ folder = { name, item: [] };
126
+ level.push(folder);
127
+ }
128
+ if (i === segments.length - 1)
129
+ folder.item.push(requestItem);
130
+ else
131
+ level = folder.item;
132
+ }
133
+ }
134
+ function sortCollectionTree(items) {
135
+ const folders = items.filter((entry) => 'item' in entry && !('request' in entry));
136
+ const requests = items.filter((entry) => 'request' in entry);
137
+ folders.sort((a, b) => a.name.localeCompare(b.name));
138
+ for (const folder of folders)
139
+ folder.item = sortCollectionTree(folder.item);
140
+ requests.sort((a, b) => a.name.localeCompare(b.name));
141
+ return [...folders, ...requests];
142
+ }
143
+ function resolveEnvPreset(envName) {
144
+ const config = (0, config_1.getConfig)();
145
+ const presets = config.envPresets ?? {};
146
+ if (envName && presets[envName])
147
+ return { name: envName, preset: presets[envName] };
148
+ const firstKey = Object.keys(presets)[0];
149
+ if (firstKey)
150
+ return { name: firstKey, preset: presets[firstKey] };
151
+ return { name: 'local', preset: { baseUrl: config.baseUrl, baseUrlKey: 'baseUrl' } };
152
+ }
153
+ function buildPostmanCollection(spec, options = {}) {
154
+ const useEnvVar = options.useEnvVar !== false;
155
+ const { preset } = resolveEnvPreset(options.envName);
156
+ const baseUrlKey = preset.baseUrlKey || 'baseUrl';
157
+ const serverUrl = useEnvVar ? `{{${baseUrlKey}}}` : spec.servers?.[0]?.url || preset.baseUrl;
158
+ const root = [];
159
+ let operations = 0;
160
+ let totalExamples = 0;
161
+ for (const [urlPath, pathItem] of Object.entries(spec.paths ?? {})) {
162
+ if (!pathItem || typeof pathItem !== 'object')
163
+ continue;
164
+ for (const method of HTTP_METHODS) {
165
+ const operation = pathItem[method];
166
+ if (!operation || typeof operation !== 'object')
167
+ continue;
168
+ operations += 1;
169
+ const requestPath = operation['x-daxta-url-path'] || urlPath;
170
+ const scenarios = Array.isArray(operation['x-scenarios']) ? operation['x-scenarios'] : [];
171
+ const primaryScenario = scenarios.find((s) => s.status >= 200 && s.status < 300) ?? scenarios[0];
172
+ const reqExamples = operation.requestBody?.content?.['application/json']?.examples ?? {};
173
+ const firstReqExample = Object.values(reqExamples)[0];
174
+ const defaultReqBody = primaryScenario?.reqBody !== undefined ? primaryScenario.reqBody : firstReqExample?.value;
175
+ const hasDefaultBody = defaultReqBody !== undefined;
176
+ const baseRequest = {
177
+ method: method.toUpperCase(),
178
+ header: buildHeaders(operation, primaryScenario?.headers, hasDefaultBody),
179
+ url: postmanUrl(serverUrl, requestPath, primaryScenario?.pathParams, primaryScenario?.query),
180
+ description: operation.summary || operation.description || '',
181
+ ...(hasDefaultBody
182
+ ? {
183
+ body: {
184
+ mode: 'raw',
185
+ raw: stringifyJson(defaultReqBody),
186
+ options: { raw: { language: 'json' } },
187
+ },
188
+ }
189
+ : {}),
190
+ };
191
+ const responses = [];
192
+ if (scenarios.length) {
193
+ for (const scenario of scenarios) {
194
+ const hasBody = scenario.reqBody !== undefined;
195
+ const originalRequest = {
196
+ method: method.toUpperCase(),
197
+ header: buildHeaders(operation, scenario.headers, hasBody),
198
+ url: postmanUrl(serverUrl, requestPath, scenario.pathParams, scenario.query),
199
+ description: operation.summary || '',
200
+ ...(hasBody
201
+ ? {
202
+ body: {
203
+ mode: 'raw',
204
+ raw: stringifyJson(scenario.reqBody),
205
+ options: { raw: { language: 'json' } },
206
+ },
207
+ }
208
+ : {}),
209
+ };
210
+ const code = Number(scenario.status) || 0;
211
+ responses.push({
212
+ name: scenario.name,
213
+ originalRequest,
214
+ status: catalog_1.STATUS_TEXT[String(code)] ?? String(code),
215
+ code,
216
+ _postman_previewlanguage: 'json',
217
+ header: [{ key: 'Content-Type', value: 'application/json' }],
218
+ body: stringifyJson(scenario.resBody),
219
+ });
220
+ }
221
+ }
222
+ else {
223
+ for (const [status, response] of Object.entries(operation.responses ?? {})) {
224
+ const examples = response?.content?.['application/json']?.examples ?? {};
225
+ const entries = Object.entries(examples);
226
+ const code = Number(status) || 0;
227
+ if (!entries.length) {
228
+ responses.push({
229
+ name: response.description || catalog_1.STATUS_TEXT[status] || status,
230
+ originalRequest: baseRequest,
231
+ status: catalog_1.STATUS_TEXT[status] || response.description || status,
232
+ code,
233
+ _postman_previewlanguage: 'json',
234
+ header: [{ key: 'Content-Type', value: 'application/json' }],
235
+ body: '',
236
+ });
237
+ continue;
238
+ }
239
+ for (const [exKey, example] of entries) {
240
+ const name = example.summary || example.description || exKey;
241
+ const reqMatch = reqExamples[exKey] || reqExamples[name] || firstReqExample;
242
+ const hasBody = reqMatch?.value !== undefined;
243
+ const originalRequest = {
244
+ ...baseRequest,
245
+ header: buildHeaders(operation, undefined, hasBody),
246
+ ...(hasBody
247
+ ? {
248
+ body: {
249
+ mode: 'raw',
250
+ raw: stringifyJson(reqMatch.value),
251
+ options: { raw: { language: 'json' } },
252
+ },
253
+ }
254
+ : {}),
255
+ };
256
+ responses.push({
257
+ name,
258
+ originalRequest,
259
+ status: catalog_1.STATUS_TEXT[status] || status,
260
+ code,
261
+ _postman_previewlanguage: 'json',
262
+ header: [{ key: 'Content-Type', value: 'application/json' }],
263
+ body: stringifyJson(example.value),
264
+ });
265
+ }
266
+ }
267
+ }
268
+ totalExamples += responses.length;
269
+ pushIntoFolderTree(root, folderSegmentsForOperation(urlPath, operation), {
270
+ name: operation.summary || `${method.toUpperCase()} ${requestPath}`,
271
+ request: baseRequest,
272
+ response: responses,
273
+ });
274
+ }
275
+ }
276
+ const collection = {
277
+ info: {
278
+ _postman_id: (0, crypto_1.randomUUID)(),
279
+ name: spec.info?.title || spec.info?.['x-workspace'] || (0, config_1.getConfig)().workspace || 'API',
280
+ description: spec.info?.description || 'Generated by DAxTA from observed test execution.',
281
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
282
+ },
283
+ item: sortCollectionTree(root),
284
+ };
285
+ return { collection, operations, examples: totalExamples };
286
+ }
287
+ function buildPostmanEnvironment(envName) {
288
+ const { name, preset } = resolveEnvPreset(envName);
289
+ const baseUrlKey = preset.baseUrlKey || 'baseUrl';
290
+ const values = [
291
+ { key: baseUrlKey, value: preset.baseUrl, type: 'default', enabled: true },
292
+ ];
293
+ const known = new Set([baseUrlKey]);
294
+ for (const [key, value] of Object.entries(preset.variables ?? {})) {
295
+ if (key === baseUrlKey)
296
+ continue;
297
+ known.add(key);
298
+ values.push({
299
+ key,
300
+ value: String(value ?? ''),
301
+ type: /token|secret|key|password/i.test(key) ? 'secret' : 'default',
302
+ enabled: true,
303
+ });
304
+ }
305
+ for (const tmpl of Object.values((0, config_1.getConfig)().headerVariables ?? {})) {
306
+ for (const match of String(tmpl).matchAll(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g)) {
307
+ if (known.has(match[1]))
308
+ continue;
309
+ known.add(match[1]);
310
+ values.push({
311
+ key: match[1],
312
+ value: '',
313
+ type: /token|secret|key|password/i.test(match[1]) ? 'secret' : 'default',
314
+ enabled: true,
315
+ });
316
+ }
317
+ }
318
+ return {
319
+ id: (0, crypto_1.randomUUID)(),
320
+ name: `${(0, config_1.getConfig)().workspace || 'API'} (${name})`,
321
+ values,
322
+ _postman_variable_scope: 'environment',
323
+ _postman_exported_at: new Date().toISOString(),
324
+ _postman_exported_using: 'DAxTA',
325
+ };
326
+ }
327
+ function exportPostmanFiles(options = {}) {
328
+ const specPath = (0, paths_1.getSpecJsonPath)();
329
+ if (!(0, fs_1.existsSync)(specPath)) {
330
+ throw new Error(`OpenAPI spec not found at ${specPath}. Run \`daxta generate\` or your tests first.`);
331
+ }
332
+ const spec = JSON.parse((0, fs_1.readFileSync)(specPath, 'utf8'));
333
+ const { collection, operations, examples } = buildPostmanCollection(spec, {
334
+ useEnvVar: options.useEnvVar,
335
+ envName: options.envName,
336
+ });
337
+ const outDir = (0, paths_1.getOutDir)();
338
+ const collectionPath = options.out
339
+ ? path.resolve(options.out.endsWith('.json') ? options.out : path.join(options.out, 'postman_collection.json'))
340
+ : path.join(outDir, 'postman_collection.json');
341
+ (0, fs_1.mkdirSync)(path.dirname(collectionPath), { recursive: true });
342
+ (0, fs_1.writeFileSync)(collectionPath, `${JSON.stringify(collection, null, 2)}\n`);
343
+ let environmentPath;
344
+ if (options.includeEnv !== false) {
345
+ const envDir = path.dirname(collectionPath);
346
+ const baseName = path.basename(collectionPath).replace(/\.postman_collection\.json$|\.json$/i, '');
347
+ environmentPath = path.join(envDir, `${baseName}.postman_environment.json`);
348
+ (0, fs_1.writeFileSync)(environmentPath, `${JSON.stringify(buildPostmanEnvironment(options.envName), null, 2)}\n`);
349
+ }
350
+ return { collectionPath, environmentPath, operations, examples };
351
+ }
@@ -49,7 +49,7 @@ class DaxtaJestReporter {
49
49
  require('reflect-metadata');
50
50
  // eslint-disable-next-line @typescript-eslint/no-var-requires
51
51
  const { rebuildFromDisk } = require('../build/incremental');
52
- const result = rebuildFromDisk({ silent: true, force: true, html: true });
52
+ const result = rebuildFromDisk({ silent: true, force: true, html: true, clearWorkers: true });
53
53
  if (result && !result.skipped) {
54
54
  printDocsReady(result.hits ?? 0, result.operations ?? 0);
55
55
  return;
@@ -70,7 +70,7 @@ function pickHeaders(request) {
70
70
  const name = rawName.toLowerCase();
71
71
  if (SKIP_HEADERS.has(name))
72
72
  continue;
73
- if (name !== 'content-type' && !name.startsWith('x-'))
73
+ if (name !== 'content-type' && name !== 'authorization' && !name.startsWith('x-'))
74
74
  continue;
75
75
  if (rawValue == null || rawValue === '')
76
76
  continue;
@@ -78,27 +78,102 @@ function pickHeaders(request) {
78
78
  }
79
79
  return Object.keys(headers).length ? headers : undefined;
80
80
  }
81
- function recordFromSuperagent(request, res) {
82
- const rawUrl = request.url || '';
83
- const url = new URL(rawUrl, 'http://localhost');
81
+ function pickFetchHeaders(initHeaders) {
82
+ if (!initHeaders)
83
+ return undefined;
84
+ const headerObj = {};
85
+ if (typeof initHeaders.forEach === 'function') {
86
+ initHeaders.forEach((val, key) => {
87
+ headerObj[key] = val;
88
+ });
89
+ }
90
+ else if (Array.isArray(initHeaders)) {
91
+ for (const pair of initHeaders) {
92
+ if (Array.isArray(pair) && pair.length >= 2)
93
+ headerObj[String(pair[0])] = pair[1];
94
+ }
95
+ }
96
+ else if (typeof initHeaders === 'object') {
97
+ Object.assign(headerObj, initHeaders);
98
+ }
99
+ return pickHeaders({ header: headerObj });
100
+ }
101
+ function tryParseJson(raw) {
102
+ if (!raw)
103
+ return undefined;
104
+ try {
105
+ return JSON.parse(raw);
106
+ }
107
+ catch {
108
+ return raw;
109
+ }
110
+ }
111
+ function recordHttpHit(params) {
112
+ const url = new URL(params.rawUrl, 'http://localhost');
84
113
  const test = currentTestName();
85
- const pathTemplate = (0, path_util_1.templatize)(url.pathname, test, (request.method || 'GET').toLowerCase());
114
+ const method = (params.method || 'GET').toLowerCase();
115
+ const pathTemplate = (0, path_util_1.templatize)(url.pathname, test, method);
86
116
  if (!pathTemplate)
87
117
  return;
88
118
  const query = Object.fromEntries(url.searchParams.entries());
89
119
  const pathParams = (0, path_util_1.extractPathParams)(pathTemplate, url.pathname);
90
120
  hits.push({
91
- method: (request.method || 'GET').toLowerCase(),
121
+ method,
92
122
  path: pathTemplate,
123
+ status: params.status ?? 0,
124
+ reqBody: params.reqBody,
125
+ resBody: params.resBody,
126
+ query: Object.keys(query).length ? query : undefined,
127
+ pathParams: Object.keys(pathParams).length ? pathParams : undefined,
128
+ headers: params.headers,
129
+ test,
130
+ });
131
+ }
132
+ function recordFromSuperagent(request, res) {
133
+ recordHttpHit({
134
+ method: request.method || 'GET',
135
+ rawUrl: request.url || '',
93
136
  status: res.status ?? 0,
94
137
  reqBody: request._data,
95
138
  resBody: res.body,
96
- query: Object.keys(query).length ? query : undefined,
97
- pathParams: Object.keys(pathParams).length ? pathParams : undefined,
98
139
  headers: pickHeaders(request),
99
- test,
100
140
  });
101
141
  }
142
+ function patchFetch() {
143
+ if (g.__DAXTA_FETCH_PATCHED__ || typeof globalThis.fetch !== 'function')
144
+ return;
145
+ g.__DAXTA_FETCH_PATCHED__ = true;
146
+ const originalFetch = globalThis.fetch;
147
+ globalThis.fetch = async function daxtaFetch(input, init) {
148
+ const response = await originalFetch.call(this, input, init);
149
+ try {
150
+ const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
151
+ const method = init?.method || (typeof input === 'object' && input !== null && 'method' in input ? input.method : 'GET');
152
+ const reqBody = typeof init?.body === 'string' ? tryParseJson(init.body) : undefined;
153
+ const headers = pickFetchHeaders(init?.headers ?? (typeof input === 'object' && input !== null && 'headers' in input ? input.headers : undefined));
154
+ let resBody;
155
+ try {
156
+ const text = await response.clone().text();
157
+ resBody = text ? tryParseJson(text) : undefined;
158
+ }
159
+ catch {
160
+ // ignore unread/uncloneable body
161
+ }
162
+ recordHttpHit({
163
+ method,
164
+ rawUrl,
165
+ status: response.status,
166
+ reqBody,
167
+ resBody,
168
+ headers,
169
+ });
170
+ }
171
+ catch {
172
+ // recording must never fail a test
173
+ }
174
+ return response;
175
+ };
176
+ }
102
177
  function patchSuperagent(superagent) {
103
178
  const proto = superagent.Request?.prototype;
104
179
  if (!proto?.end || proto.__daxtaPatched)
@@ -143,6 +218,7 @@ function install() {
143
218
  // ignore
144
219
  }
145
220
  }
221
+ patchFetch();
146
222
  if (!g.__DAXTA_FLUSH_HOOK__) {
147
223
  g.__DAXTA_FLUSH_HOOK__ = true;
148
224
  const flushSafe = () => {
package/dist/setup.js CHANGED
@@ -1,7 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const incremental_1 = require("./build/incremental");
4
+ const config_1 = require("./config");
3
5
  const recorder_1 = require("./recorder");
4
6
  (0, recorder_1.install)();
5
7
  afterAll(() => {
8
+ if ((0, config_1.getConfig)().writeMode === 'incremental') {
9
+ (0, incremental_1.flushAndRebuild)({ silent: true, html: true });
10
+ return;
11
+ }
6
12
  (0, recorder_1.flush)();
7
13
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t0.labs/daxta",
3
- "version": "1.1.8",
3
+ "version": "1.2.0",
4
4
  "description": "DAxTA — Tested behavior. Trusted API docs. Generate API documentation from observed test execution.",
5
5
  "license": "MIT",
6
6
  "author": {