@apifuse/provider-sdk 2.2.0-beta.12 → 2.2.0-beta.13
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/AUTHORING.md +201 -0
- package/CHANGELOG.md +10 -0
- package/README.md +26 -2
- package/bin/apifuse-pack-types.ts +30 -1
- package/bin/apifuse-record.ts +622 -57
- package/bin/apifuse-submit-check.ts +43 -10
- package/dist/define.d.ts +2 -1
- package/dist/define.js +61 -3
- package/dist/fixture-sanitization.d.ts +26 -0
- package/dist/fixture-sanitization.js +216 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/provider.d.ts +2 -1
- package/dist/provider.js +1 -0
- package/dist/runtime/http.js +86 -32
- package/dist/runtime/instrumentation.js +295 -9
- package/dist/runtime/native-network.d.ts +53 -0
- package/dist/runtime/native-network.js +477 -0
- package/dist/runtime/proxy-nodemaven.d.ts +14 -0
- package/dist/runtime/proxy-nodemaven.js +20 -2
- package/dist/runtime/request-options.d.ts +68 -1
- package/dist/runtime/request-options.js +548 -0
- package/dist/runtime/stealth.d.ts +3 -1
- package/dist/runtime/stealth.js +239 -39
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/self-test-input-tokens.d.ts +2 -1
- package/dist/server/self-test-input-tokens.js +18 -14
- package/dist/stream-evidence.d.ts +74 -0
- package/dist/stream-evidence.js +785 -0
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/run.d.ts +32 -2
- package/dist/testing/run.js +451 -19
- package/dist/types.d.ts +162 -0
- package/package.json +2 -1
- package/src/define.ts +81 -3
- package/src/fixture-sanitization.ts +247 -0
- package/src/index.ts +37 -0
- package/src/provider.ts +37 -0
- package/src/runtime/http.ts +144 -38
- package/src/runtime/instrumentation.ts +424 -8
- package/src/runtime/native-network.ts +600 -0
- package/src/runtime/proxy-nodemaven.ts +37 -2
- package/src/runtime/request-options.ts +680 -1
- package/src/runtime/stealth.ts +293 -40
- package/src/server/index.ts +4 -1
- package/src/server/self-test-input-tokens.ts +29 -14
- package/src/stream-evidence.ts +988 -0
- package/src/testing/index.ts +9 -1
- package/src/testing/run.ts +608 -12
- package/src/types.ts +194 -0
package/dist/testing/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { describeTransform, snapshotTransform, toMatchShape } from "./helpers.js";
|
|
2
|
-
export { runStandardTests } from "./run.js";
|
|
2
|
+
export { runStandardTests, type StandardTestsManifest, type StandardTestsOptions, type StandardTestsResult, type StandardTestsUpstreamCall, type StandardTestsUpstreamResponse, type StandardTestsUpstreamStub, } from "./run.js";
|
package/dist/testing/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { describeTransform, snapshotTransform, toMatchShape } from "./helpers.js";
|
|
2
|
-
export { runStandardTests } from "./run.js";
|
|
2
|
+
export { runStandardTests, } from "./run.js";
|
package/dist/testing/run.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AuthMode, ProviderDefinition } from "../types.js";
|
|
1
|
+
import type { AuthMode, ProviderContext, ProviderDefinition } from "../types.js";
|
|
2
2
|
export interface StandardTestsManifest {
|
|
3
3
|
id?: string;
|
|
4
4
|
displayName?: string;
|
|
@@ -22,7 +22,34 @@ export interface StandardTestsOptions {
|
|
|
22
22
|
validateAuthMode?: boolean;
|
|
23
23
|
/** Override inferred __fixtures__ directory for tests generated outside providers/<id>. */
|
|
24
24
|
fixtureDir?: string;
|
|
25
|
+
/** Opt in to real-handler E2E with strict, offline canned upstream responses. */
|
|
26
|
+
upstreamStub?: StandardTestsUpstreamStub;
|
|
27
|
+
/** Require a committed snapshot; missing files fail unless --update-snapshots is passed. */
|
|
28
|
+
requireSnapshot?: boolean;
|
|
25
29
|
}
|
|
30
|
+
export interface StandardTestsUpstreamCall {
|
|
31
|
+
/** Operation whose real handler initiated the call. */
|
|
32
|
+
operationName: string;
|
|
33
|
+
/** ProviderContext transport surface used by the handler. */
|
|
34
|
+
transport: "http" | "stealth" | "browser" | "native";
|
|
35
|
+
method: string;
|
|
36
|
+
url?: string;
|
|
37
|
+
body?: unknown;
|
|
38
|
+
options?: unknown;
|
|
39
|
+
}
|
|
40
|
+
export interface StandardTestsUpstreamResponse {
|
|
41
|
+
status?: number;
|
|
42
|
+
headers?: Readonly<Record<string, string>>;
|
|
43
|
+
/** JSON-compatible values are encoded as JSON; strings and bytes are preserved. */
|
|
44
|
+
body?: unknown;
|
|
45
|
+
}
|
|
46
|
+
export type StandardTestsUpstreamStub = (call: StandardTestsUpstreamCall) => Response | StandardTestsUpstreamResponse | undefined | Promise<Response | StandardTestsUpstreamResponse | undefined>;
|
|
47
|
+
export interface StandardTestsResult {
|
|
48
|
+
warnings: readonly string[];
|
|
49
|
+
}
|
|
50
|
+
export declare function createSnapshotContext(rawFixture: unknown): ProviderContext;
|
|
51
|
+
/** Internal execution seam exported for focused SDK tests; use runStandardTests as public API. */
|
|
52
|
+
export declare function executeStandardTestHandler(provider: ProviderDefinition, operationName: string, upstreamStub: StandardTestsUpstreamStub): Promise<unknown>;
|
|
26
53
|
/**
|
|
27
54
|
* Run standard SDK tests for a provider in one line.
|
|
28
55
|
*
|
|
@@ -31,4 +58,7 @@ export interface StandardTestsOptions {
|
|
|
31
58
|
* import { runStandardTests } from "@apifuse/provider-sdk/testing";
|
|
32
59
|
* runStandardTests(myProvider, rawFixture, manifest, { snapshot: true });
|
|
33
60
|
*/
|
|
34
|
-
export declare function runStandardTests(provider: ProviderDefinition,
|
|
61
|
+
export declare function runStandardTests(provider: ProviderDefinition, options: StandardTestsOptions & {
|
|
62
|
+
upstreamStub: StandardTestsUpstreamStub;
|
|
63
|
+
}): StandardTestsResult;
|
|
64
|
+
export declare function runStandardTests(provider: ProviderDefinition, rawFixture?: unknown, manifest?: StandardTestsManifest, options?: StandardTestsOptions): StandardTestsResult;
|
package/dist/testing/run.js
CHANGED
|
@@ -4,12 +4,15 @@ import { createTestProviderChoiceContext } from "../runtime/choice.js";
|
|
|
4
4
|
import { createMemoryProviderRuntimeState } from "../runtime/state.js";
|
|
5
5
|
import { createUnsupportedSttClient } from "../runtime/stt.js";
|
|
6
6
|
import { safeParseSchemaSync } from "../schema.js";
|
|
7
|
+
import { requestPathForFixture } from "../fixture-sanitization.js";
|
|
8
|
+
import { findStreamCaptureGroup, replayStreamEvidence } from "../stream-evidence.js";
|
|
7
9
|
// Mirrors CONNECTOR_ID_REGEX in ../define.ts, which defineProvider() enforces.
|
|
8
10
|
// A single lowercase segment (no hyphen) is a valid id, so the trailing group
|
|
9
11
|
// is optional (`*`), matching providers like `kakaomap`, `kstartup`, `triple`.
|
|
10
12
|
const CONNECTOR_ID_REGEX = /^[a-z][a-z0-9]*(-[a-z][a-z0-9]*)*$/;
|
|
11
13
|
const VALID_AUTH_MODES = ["none", "platform-managed", "credentials", "oauth2"];
|
|
12
14
|
const UPDATE_SNAPSHOT_ARGS = new Set(["-u", "--update-snapshots"]);
|
|
15
|
+
const snapshotCaptureStates = new WeakMap();
|
|
13
16
|
function isFixtureEnvelope(value) {
|
|
14
17
|
return (value !== null &&
|
|
15
18
|
typeof value === "object" &&
|
|
@@ -74,10 +77,331 @@ function jsonResponse(data) {
|
|
|
74
77
|
bytes: async () => bodyBytes.slice(0),
|
|
75
78
|
};
|
|
76
79
|
}
|
|
80
|
+
function headersToRecord(headers) {
|
|
81
|
+
return Object.fromEntries(headers.entries());
|
|
82
|
+
}
|
|
83
|
+
async function normalizeUpstreamResponse(response) {
|
|
84
|
+
if (response instanceof Response) {
|
|
85
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
86
|
+
const text = new TextDecoder().decode(bytes);
|
|
87
|
+
const headers = headersToRecord(response.headers);
|
|
88
|
+
let data = text;
|
|
89
|
+
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
90
|
+
data = text.length > 0 ? JSON.parse(text) : null;
|
|
91
|
+
}
|
|
92
|
+
return { status: response.status, headers, data, text, bytes };
|
|
93
|
+
}
|
|
94
|
+
const headers = { ...(response.headers ?? {}) };
|
|
95
|
+
const body = response.body ?? null;
|
|
96
|
+
let bytes;
|
|
97
|
+
let text;
|
|
98
|
+
let data;
|
|
99
|
+
if (body instanceof Uint8Array) {
|
|
100
|
+
bytes = body.slice(0);
|
|
101
|
+
text = new TextDecoder().decode(bytes);
|
|
102
|
+
data = text;
|
|
103
|
+
}
|
|
104
|
+
else if (body instanceof ArrayBuffer) {
|
|
105
|
+
bytes = new Uint8Array(body.slice(0));
|
|
106
|
+
text = new TextDecoder().decode(bytes);
|
|
107
|
+
data = text;
|
|
108
|
+
}
|
|
109
|
+
else if (typeof body === "string") {
|
|
110
|
+
text = body;
|
|
111
|
+
bytes = new TextEncoder().encode(text);
|
|
112
|
+
data = body;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
text = JSON.stringify(body);
|
|
116
|
+
bytes = new TextEncoder().encode(text);
|
|
117
|
+
data = body;
|
|
118
|
+
if (!Object.keys(headers).some((name) => name.toLowerCase() === "content-type")) {
|
|
119
|
+
headers["content-type"] = "application/json";
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return { status: response.status ?? 200, headers, data, text, bytes };
|
|
123
|
+
}
|
|
124
|
+
function toHttpResponse(response) {
|
|
125
|
+
return {
|
|
126
|
+
status: response.status,
|
|
127
|
+
ok: response.status >= 200 && response.status < 300,
|
|
128
|
+
headers: response.headers,
|
|
129
|
+
data: response.data,
|
|
130
|
+
json: async () => JSON.parse(response.text),
|
|
131
|
+
text: async () => response.text,
|
|
132
|
+
arrayBuffer: async () => response.bytes.slice(0).buffer,
|
|
133
|
+
bytes: async () => response.bytes.slice(0),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const emptyCookieJar = {
|
|
137
|
+
get: () => undefined,
|
|
138
|
+
getAll: () => ({}),
|
|
139
|
+
toString: () => "",
|
|
140
|
+
};
|
|
141
|
+
function emptyCookieStore() {
|
|
142
|
+
return {
|
|
143
|
+
version: 1,
|
|
144
|
+
jar: { cookies: [] },
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function toStealthResponse(response, url) {
|
|
148
|
+
return {
|
|
149
|
+
status: response.status,
|
|
150
|
+
ok: response.status >= 200 && response.status < 300,
|
|
151
|
+
url,
|
|
152
|
+
redirected: false,
|
|
153
|
+
headers: response.headers,
|
|
154
|
+
rawHeaders: Object.entries(response.headers),
|
|
155
|
+
body: response.text,
|
|
156
|
+
cookies: emptyCookieJar,
|
|
157
|
+
json: async () => JSON.parse(response.text),
|
|
158
|
+
arrayBuffer: async () => response.bytes.slice(0).buffer,
|
|
159
|
+
bytes: async () => response.bytes.slice(0),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function streamFromBytes(bytes) {
|
|
163
|
+
return new ReadableStream({
|
|
164
|
+
start(controller) {
|
|
165
|
+
controller.enqueue(bytes.slice(0));
|
|
166
|
+
controller.close();
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
async function* singleBytes(bytes) {
|
|
171
|
+
yield bytes.slice(0);
|
|
172
|
+
}
|
|
173
|
+
async function* singleText(textValue) {
|
|
174
|
+
yield textValue;
|
|
175
|
+
}
|
|
176
|
+
function createUpstreamContext(provider, operationName, upstreamStub) {
|
|
177
|
+
const credential = {
|
|
178
|
+
mode: "none",
|
|
179
|
+
get: () => undefined,
|
|
180
|
+
getAll: () => ({}),
|
|
181
|
+
getAccessToken: () => undefined,
|
|
182
|
+
getScopes: () => [],
|
|
183
|
+
};
|
|
184
|
+
const request = { headers: {} };
|
|
185
|
+
const state = createMemoryProviderRuntimeState();
|
|
186
|
+
const dispatch = async (call) => {
|
|
187
|
+
const canned = await upstreamStub({ operationName, ...call });
|
|
188
|
+
if (canned === undefined) {
|
|
189
|
+
throw new Error(`Unmatched upstream call for operation "${operationName}": ${call.transport}.${call.method}${call.url ? ` ${call.url}` : ""}. Add a canned response to upstreamStub; live network passthrough is disabled.`);
|
|
190
|
+
}
|
|
191
|
+
return normalizeUpstreamResponse(canned);
|
|
192
|
+
};
|
|
193
|
+
const httpCall = async (method, url, body, options) => toHttpResponse(await dispatch({ transport: "http", method, url, body, options }));
|
|
194
|
+
const stealthCall = async (url, options) => toStealthResponse(await dispatch({
|
|
195
|
+
transport: "stealth",
|
|
196
|
+
method: options?.method?.toUpperCase() ?? "GET",
|
|
197
|
+
url,
|
|
198
|
+
body: options?.body,
|
|
199
|
+
options,
|
|
200
|
+
}), url);
|
|
201
|
+
const createBrowserPage = () => {
|
|
202
|
+
let currentUrl = "about:blank";
|
|
203
|
+
let currentResponse;
|
|
204
|
+
const browserAction = async (method, body) => {
|
|
205
|
+
currentResponse = await dispatch({
|
|
206
|
+
transport: "browser",
|
|
207
|
+
method,
|
|
208
|
+
url: currentUrl,
|
|
209
|
+
body,
|
|
210
|
+
});
|
|
211
|
+
return currentResponse;
|
|
212
|
+
};
|
|
213
|
+
const page = {
|
|
214
|
+
id: `standard-test-${operationName}`,
|
|
215
|
+
url: async () => currentUrl,
|
|
216
|
+
title: async () => currentResponse?.text.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1] ?? "",
|
|
217
|
+
content: async () => currentResponse?.text ?? "",
|
|
218
|
+
evaluate: async (fn) => (await browserAction("evaluate", typeof fn === "string" ? fn : String(fn))).data,
|
|
219
|
+
locator: (selector) => ({
|
|
220
|
+
click: async () => {
|
|
221
|
+
await browserAction("locator.click", { selector });
|
|
222
|
+
},
|
|
223
|
+
fill: async (textValue) => {
|
|
224
|
+
await browserAction("locator.fill", { selector, text: textValue });
|
|
225
|
+
},
|
|
226
|
+
textContent: async () => {
|
|
227
|
+
const value = (await browserAction("locator.textContent", { selector })).data;
|
|
228
|
+
return value === null || value === undefined ? null : String(value);
|
|
229
|
+
},
|
|
230
|
+
waitFor: async (options) => {
|
|
231
|
+
await browserAction("locator.waitFor", { selector, options });
|
|
232
|
+
},
|
|
233
|
+
}),
|
|
234
|
+
close: async () => { },
|
|
235
|
+
fill: async (selector, textValue) => {
|
|
236
|
+
await browserAction("fill", { selector, text: textValue });
|
|
237
|
+
},
|
|
238
|
+
goto: async (url) => {
|
|
239
|
+
currentUrl = url;
|
|
240
|
+
await browserAction("goto");
|
|
241
|
+
},
|
|
242
|
+
screenshot: async (options) => Buffer.from((await browserAction("screenshot", options)).bytes),
|
|
243
|
+
click: async (selector) => {
|
|
244
|
+
await browserAction("click", { selector });
|
|
245
|
+
},
|
|
246
|
+
type: async (selector, textValue) => {
|
|
247
|
+
await browserAction("type", { selector, text: textValue });
|
|
248
|
+
},
|
|
249
|
+
waitForSelector: async (selector, options) => {
|
|
250
|
+
await browserAction("waitForSelector", { selector, options });
|
|
251
|
+
},
|
|
252
|
+
frames: async () => [page],
|
|
253
|
+
withResourcePolicy: async (_policy, run) => run(),
|
|
254
|
+
};
|
|
255
|
+
return page;
|
|
256
|
+
};
|
|
257
|
+
const createStealthSession = () => ({
|
|
258
|
+
fetch: stealthCall,
|
|
259
|
+
cookies: {
|
|
260
|
+
...emptyCookieJar,
|
|
261
|
+
has: () => false,
|
|
262
|
+
setFromCookieStrings: () => { },
|
|
263
|
+
toHeader: () => "",
|
|
264
|
+
snapshot: () => ({}),
|
|
265
|
+
restore: () => { },
|
|
266
|
+
serialize: emptyCookieStore,
|
|
267
|
+
deserialize: () => { },
|
|
268
|
+
clear: () => { },
|
|
269
|
+
},
|
|
270
|
+
redirects: {
|
|
271
|
+
run: async (options) => {
|
|
272
|
+
const final = await stealthCall(options.url, options);
|
|
273
|
+
return {
|
|
274
|
+
final,
|
|
275
|
+
hops: [],
|
|
276
|
+
reason: "completed",
|
|
277
|
+
cookies: {},
|
|
278
|
+
cookieStore: emptyCookieStore(),
|
|
279
|
+
};
|
|
280
|
+
},
|
|
281
|
+
},
|
|
282
|
+
close: () => { },
|
|
283
|
+
});
|
|
284
|
+
return {
|
|
285
|
+
env: { get: () => undefined },
|
|
286
|
+
credential,
|
|
287
|
+
request,
|
|
288
|
+
http: {
|
|
289
|
+
request: (url, options) => httpCall(options?.method?.toUpperCase() ?? "GET", url, options?.body, options),
|
|
290
|
+
get: (url, options) => httpCall("GET", url, undefined, options),
|
|
291
|
+
post: (url, body, options) => httpCall("POST", url, body, options),
|
|
292
|
+
put: (url, body, options) => httpCall("PUT", url, body, options),
|
|
293
|
+
delete: (url, options) => httpCall("DELETE", url, undefined, options),
|
|
294
|
+
stream: async (url, options) => {
|
|
295
|
+
const response = await dispatch({
|
|
296
|
+
transport: "http",
|
|
297
|
+
method: options?.method?.toUpperCase() ?? "GET",
|
|
298
|
+
url,
|
|
299
|
+
body: options?.body,
|
|
300
|
+
options,
|
|
301
|
+
});
|
|
302
|
+
return {
|
|
303
|
+
status: response.status,
|
|
304
|
+
ok: response.status >= 200 && response.status < 300,
|
|
305
|
+
headers: response.headers,
|
|
306
|
+
body: streamFromBytes(response.bytes),
|
|
307
|
+
bytes: () => singleBytes(response.bytes),
|
|
308
|
+
textChunks: () => singleText(response.text),
|
|
309
|
+
lines: () => singleText(response.text),
|
|
310
|
+
};
|
|
311
|
+
},
|
|
312
|
+
sse: async (url, options) => {
|
|
313
|
+
const response = await dispatch({
|
|
314
|
+
transport: "http",
|
|
315
|
+
method: options?.method?.toUpperCase() ?? "GET",
|
|
316
|
+
url,
|
|
317
|
+
body: options?.body,
|
|
318
|
+
options,
|
|
319
|
+
});
|
|
320
|
+
async function* messages() {
|
|
321
|
+
for (const block of response.text.split(/\r?\n\r?\n/)) {
|
|
322
|
+
const data = block
|
|
323
|
+
.split(/\r?\n/)
|
|
324
|
+
.filter((line) => line.startsWith("data:"))
|
|
325
|
+
.map((line) => line.slice(5).trimStart())
|
|
326
|
+
.join("\n");
|
|
327
|
+
if (!data)
|
|
328
|
+
continue;
|
|
329
|
+
yield { event: "message", data, json: () => JSON.parse(data) };
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return messages();
|
|
333
|
+
},
|
|
334
|
+
},
|
|
335
|
+
cache: createProviderCache({ providerId: `standard-test-${operationName}` }),
|
|
336
|
+
state,
|
|
337
|
+
stealth: {
|
|
338
|
+
fetch: stealthCall,
|
|
339
|
+
createSession: createStealthSession,
|
|
340
|
+
},
|
|
341
|
+
browser: {
|
|
342
|
+
engine: "playwright-stealth",
|
|
343
|
+
newPage: async () => createBrowserPage(),
|
|
344
|
+
rawPage: async () => createBrowserPage(),
|
|
345
|
+
withIsolatedContext: async (handler) => handler(createBrowserPage()),
|
|
346
|
+
solveChallenge: async (challenge) => (await dispatch({
|
|
347
|
+
transport: "browser",
|
|
348
|
+
method: "solveChallenge",
|
|
349
|
+
body: challenge,
|
|
350
|
+
})).data,
|
|
351
|
+
},
|
|
352
|
+
...(provider.native
|
|
353
|
+
? {
|
|
354
|
+
native: {
|
|
355
|
+
network: {
|
|
356
|
+
connectTcp: async (options) => createNativeConnection(await dispatch({
|
|
357
|
+
transport: "native",
|
|
358
|
+
method: "connectTcp",
|
|
359
|
+
url: `tcp://${options.host}:${options.port}`,
|
|
360
|
+
options,
|
|
361
|
+
}), dispatch, `tcp://${options.host}:${options.port}`),
|
|
362
|
+
connectTls: async (options) => createNativeConnection(await dispatch({
|
|
363
|
+
transport: "native",
|
|
364
|
+
method: "connectTls",
|
|
365
|
+
url: `tls://${options.host}:${options.port}`,
|
|
366
|
+
options,
|
|
367
|
+
}), dispatch, `tls://${options.host}:${options.port}`),
|
|
368
|
+
grantTcpEgress: () => ({ revoke: () => { } }),
|
|
369
|
+
},
|
|
370
|
+
},
|
|
371
|
+
}
|
|
372
|
+
: {}),
|
|
373
|
+
trace: { span: async (_name, fn) => fn() },
|
|
374
|
+
auth: { requestField: async (name) => unsupported(`ctx.auth.requestField(${name})`) },
|
|
375
|
+
stt: createUnsupportedSttClient("Standard test upstream context does not support ctx.stt.transcribe"),
|
|
376
|
+
choice: createTestProviderChoiceContext({
|
|
377
|
+
providerId: `standard-test-${operationName}`,
|
|
378
|
+
request,
|
|
379
|
+
credential,
|
|
380
|
+
state,
|
|
381
|
+
}),
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
function createNativeConnection(initialResponse, dispatch, url) {
|
|
385
|
+
let unread = initialResponse.bytes.slice(0);
|
|
386
|
+
return {
|
|
387
|
+
read: async () => {
|
|
388
|
+
if (unread.byteLength === 0)
|
|
389
|
+
return null;
|
|
390
|
+
const bytes = unread;
|
|
391
|
+
unread = new Uint8Array();
|
|
392
|
+
return bytes;
|
|
393
|
+
},
|
|
394
|
+
write: async (body) => {
|
|
395
|
+
const response = await dispatch({ transport: "native", method: "write", url, body });
|
|
396
|
+
unread = response.bytes.slice(0);
|
|
397
|
+
},
|
|
398
|
+
close: async () => { },
|
|
399
|
+
};
|
|
400
|
+
}
|
|
77
401
|
function unsupported(name) {
|
|
78
402
|
throw new Error(`Standard test snapshot context does not support ${name}`);
|
|
79
403
|
}
|
|
80
|
-
function createSnapshotContext(rawFixture) {
|
|
404
|
+
export function createSnapshotContext(rawFixture) {
|
|
81
405
|
const credential = {
|
|
82
406
|
mode: "none",
|
|
83
407
|
get: () => undefined,
|
|
@@ -87,17 +411,52 @@ function createSnapshotContext(rawFixture) {
|
|
|
87
411
|
};
|
|
88
412
|
const request = { headers: {} };
|
|
89
413
|
const state = createMemoryProviderRuntimeState();
|
|
90
|
-
|
|
414
|
+
const streamCaptureGroup = findStreamCaptureGroup(rawFixture);
|
|
415
|
+
let nextCaptureItem = 0;
|
|
416
|
+
const replayJsonResponse = () => {
|
|
417
|
+
if (!streamCaptureGroup)
|
|
418
|
+
return jsonResponse(rawFixture);
|
|
419
|
+
const item = streamCaptureGroup.items[nextCaptureItem];
|
|
420
|
+
if (!item) {
|
|
421
|
+
throw new Error(`Stream fixture exhausted: no recorded response exists for ordinary HTTP call ${nextCaptureItem + 1}.`);
|
|
422
|
+
}
|
|
423
|
+
if (item.kind !== "response") {
|
|
424
|
+
throw new Error(`Stream fixture call-order mismatch: expected a stream call at position ${nextCaptureItem + 1}, received an ordinary HTTP call.`);
|
|
425
|
+
}
|
|
426
|
+
nextCaptureItem += 1;
|
|
427
|
+
return jsonResponse(item.value);
|
|
428
|
+
};
|
|
429
|
+
const context = {
|
|
91
430
|
env: { get: () => undefined },
|
|
92
431
|
credential,
|
|
93
432
|
request,
|
|
94
433
|
http: {
|
|
95
|
-
request: async () =>
|
|
96
|
-
get: async () =>
|
|
97
|
-
post: async () =>
|
|
98
|
-
put: async () =>
|
|
99
|
-
delete: async () =>
|
|
100
|
-
stream: async () =>
|
|
434
|
+
request: async () => replayJsonResponse(),
|
|
435
|
+
get: async () => replayJsonResponse(),
|
|
436
|
+
post: async () => replayJsonResponse(),
|
|
437
|
+
put: async () => replayJsonResponse(),
|
|
438
|
+
delete: async () => replayJsonResponse(),
|
|
439
|
+
stream: async (...args) => {
|
|
440
|
+
if (!streamCaptureGroup)
|
|
441
|
+
return unsupported("ctx.http.stream");
|
|
442
|
+
const item = streamCaptureGroup.items[nextCaptureItem];
|
|
443
|
+
if (!item) {
|
|
444
|
+
throw new Error(`Stream fixture exhausted: no recorded evidence exists for stream call ${nextCaptureItem + 1}.`);
|
|
445
|
+
}
|
|
446
|
+
if (item.kind !== "stream") {
|
|
447
|
+
throw new Error(`Stream fixture call-order mismatch: expected an ordinary HTTP call at position ${nextCaptureItem + 1}, received a stream call.`);
|
|
448
|
+
}
|
|
449
|
+
if (item.evidence.request) {
|
|
450
|
+
const expected = item.evidence.request;
|
|
451
|
+
const actualMethod = (args[1]?.method ?? "GET").toUpperCase();
|
|
452
|
+
const actualPath = replayRequestPath(args[0], expected.path);
|
|
453
|
+
if (actualMethod !== expected.method || actualPath !== expected.path) {
|
|
454
|
+
throw new Error(`Stream fixture request mismatch: expected ${expected.method} ${expected.path}, received ${actualMethod} ${actualPath}.`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
nextCaptureItem += 1;
|
|
458
|
+
return replayStreamEvidence(item.evidence);
|
|
459
|
+
},
|
|
101
460
|
sse: async () => unsupported("ctx.http.sse"),
|
|
102
461
|
},
|
|
103
462
|
cache: createProviderCache({ providerId: "standard-test" }),
|
|
@@ -127,15 +486,39 @@ function createSnapshotContext(rawFixture) {
|
|
|
127
486
|
state,
|
|
128
487
|
}),
|
|
129
488
|
};
|
|
489
|
+
snapshotCaptureStates.set(context, {
|
|
490
|
+
assertConsumed() {
|
|
491
|
+
if (streamCaptureGroup && nextCaptureItem !== streamCaptureGroup.items.length) {
|
|
492
|
+
throw new Error(`Stream fixture has ${streamCaptureGroup.items.length - nextCaptureItem} unconsumed capture item${streamCaptureGroup.items.length - nextCaptureItem === 1 ? "" : "s"} after handler completion.`);
|
|
493
|
+
}
|
|
494
|
+
},
|
|
495
|
+
consumed: () => nextCaptureItem,
|
|
496
|
+
});
|
|
497
|
+
return context;
|
|
498
|
+
}
|
|
499
|
+
function replayRequestPath(requestUrl, expectedPath) {
|
|
500
|
+
if (/^[a-z][a-z\d+.-]*:\/\//i.test(requestUrl) || requestUrl.startsWith("/")) {
|
|
501
|
+
return requestPathForFixture(requestUrl);
|
|
502
|
+
}
|
|
503
|
+
return requestPathForFixture(new URL(requestUrl, `https://fixture.invalid${expectedPath}`).toString());
|
|
130
504
|
}
|
|
131
505
|
async function transformSnapshotOutput(provider, rawFixture) {
|
|
132
506
|
const entries = Object.entries(provider.operations);
|
|
133
|
-
const
|
|
507
|
+
const captureStates = [];
|
|
134
508
|
const outputs = await Promise.all(entries.map(async ([operationName, operation]) => {
|
|
509
|
+
const context = createSnapshotContext(rawFixture);
|
|
135
510
|
const request = operation.fixtures?.request ?? {};
|
|
136
511
|
const output = await operation.handler(context, request);
|
|
512
|
+
const captureState = snapshotCaptureStates.get(context);
|
|
513
|
+
if (captureState)
|
|
514
|
+
captureStates.push(captureState);
|
|
515
|
+
if (captureState?.consumed())
|
|
516
|
+
captureState.assertConsumed();
|
|
137
517
|
return [operationName, output];
|
|
138
518
|
}));
|
|
519
|
+
if (findStreamCaptureGroup(rawFixture) && !captureStates.some((state) => state.consumed() > 0)) {
|
|
520
|
+
captureStates[0]?.assertConsumed();
|
|
521
|
+
}
|
|
139
522
|
if (outputs.length === 1) {
|
|
140
523
|
return outputs[0]?.[1];
|
|
141
524
|
}
|
|
@@ -180,16 +563,51 @@ function expectSchemaFixture(operationName, fieldName, fixture, result) {
|
|
|
180
563
|
function parseSchemaFixture(operationName, fieldName, schema, fixture) {
|
|
181
564
|
expectSchemaFixture(operationName, fieldName, fixture, safeParseSchemaSync(schema, fixture, `operations.${operationName}.fixtures.${fieldName}`));
|
|
182
565
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
566
|
+
async function materializeHandlerOutput(output) {
|
|
567
|
+
if (!(output instanceof Response))
|
|
568
|
+
return output;
|
|
569
|
+
const contentType = output.headers.get("content-type") ?? "";
|
|
570
|
+
if (contentType.includes("application/json"))
|
|
571
|
+
return output.json();
|
|
572
|
+
return output.text();
|
|
573
|
+
}
|
|
574
|
+
/** Internal execution seam exported for focused SDK tests; use runStandardTests as public API. */
|
|
575
|
+
export async function executeStandardTestHandler(provider, operationName, upstreamStub) {
|
|
576
|
+
const operation = provider.operations[operationName];
|
|
577
|
+
if (!operation)
|
|
578
|
+
throw new Error(`Unknown operation "${operationName}".`);
|
|
579
|
+
if (operation.fixtures?.request === undefined) {
|
|
580
|
+
throw new Error(`Operation "${operationName}" has no fixtures.request for handler E2E execution.`);
|
|
581
|
+
}
|
|
582
|
+
const context = createUpstreamContext(provider, operationName, upstreamStub);
|
|
583
|
+
const output = await materializeHandlerOutput(await operation.handler(context, operation.fixtures.request));
|
|
584
|
+
const result = safeParseSchemaSync(operation.output, output, `operations.${operationName}.handler.output`);
|
|
585
|
+
if (!result.success) {
|
|
586
|
+
throw new Error([
|
|
587
|
+
`Handler output for operation "${operationName}" failed schema validation.`,
|
|
588
|
+
formatJsonDiff({ valid: false, value: output, error: result.error }, { valid: true, value: output }),
|
|
589
|
+
].join("\n"));
|
|
590
|
+
}
|
|
591
|
+
return output;
|
|
592
|
+
}
|
|
593
|
+
function isOptionsShortcut(value) {
|
|
594
|
+
return (value !== null &&
|
|
595
|
+
typeof value === "object" &&
|
|
596
|
+
!Array.isArray(value) &&
|
|
597
|
+
Object.hasOwn(value, "upstreamStub"));
|
|
598
|
+
}
|
|
599
|
+
export function runStandardTests(provider, rawFixtureOrOptions, manifest, legacyOptions) {
|
|
600
|
+
const shortcut = manifest === undefined && legacyOptions === undefined && isOptionsShortcut(rawFixtureOrOptions);
|
|
601
|
+
const rawFixture = shortcut ? undefined : rawFixtureOrOptions;
|
|
602
|
+
const options = shortcut ? rawFixtureOrOptions : (legacyOptions ?? {});
|
|
192
603
|
const operations = Object.entries(provider.operations);
|
|
604
|
+
const warnings = options.upstreamStub
|
|
605
|
+
? operations
|
|
606
|
+
.filter(([, operation]) => operation.fixtures?.request === undefined)
|
|
607
|
+
.map(([operationName]) => `[provider-sdk] Operation "${provider.id}.${operationName}" has no fixtures.request, so runStandardTests cannot invoke its handler E2E.`)
|
|
608
|
+
: operations.map(([operationName]) => `[provider-sdk] Operation "${provider.id}.${operationName}" has no handler E2E coverage in runStandardTests; configure upstreamStub to invoke the real handler.`);
|
|
609
|
+
for (const warning of warnings)
|
|
610
|
+
console.warn(warning);
|
|
193
611
|
const assertFixtureValidation = () => {
|
|
194
612
|
expect(rawFixture).toBeDefined();
|
|
195
613
|
expect(isJsonCompatible(rawFixture)).toBe(true);
|
|
@@ -289,12 +707,26 @@ export function runStandardTests(provider, rawFixture, manifest, options = {}) {
|
|
|
289
707
|
const actual = await transformSnapshotOutput(provider, rawFixture);
|
|
290
708
|
const serialized = stableStringify(actual);
|
|
291
709
|
const snapshotFile = Bun.file(snapshotPath);
|
|
292
|
-
|
|
710
|
+
const snapshotExists = await snapshotFile.exists();
|
|
711
|
+
if (!snapshotExists && options.requireSnapshot && !shouldUpdateSnapshots()) {
|
|
712
|
+
throw new Error(`Required golden snapshot is missing: ${snapshotPath}. Regenerate it with bun test --update-snapshots.`);
|
|
713
|
+
}
|
|
714
|
+
if (shouldUpdateSnapshots() || !snapshotExists) {
|
|
293
715
|
await Bun.write(snapshotPath, serialized);
|
|
294
716
|
}
|
|
295
717
|
const expected = JSON.parse(await Bun.file(snapshotPath).text());
|
|
296
718
|
expect(actual).toEqual(expected);
|
|
297
719
|
});
|
|
298
720
|
}
|
|
721
|
+
if (options.upstreamStub) {
|
|
722
|
+
for (const [operationName, operation] of operations) {
|
|
723
|
+
if (operation.fixtures?.request === undefined)
|
|
724
|
+
continue;
|
|
725
|
+
it(`invokes the real ${operationName} handler with canned upstream responses`, async () => {
|
|
726
|
+
await executeStandardTestHandler(provider, operationName, options.upstreamStub);
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
}
|
|
299
730
|
});
|
|
731
|
+
return { warnings };
|
|
300
732
|
}
|