@apifuse/provider-sdk 2.2.0-beta.48 → 2.2.0-beta.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/AUTHORING.md +91 -36
  2. package/CHANGELOG.md +4 -0
  3. package/README.md +11 -9
  4. package/SUBMISSION.md +1 -1
  5. package/bin/apifuse-dev.ts +24 -13
  6. package/bin/apifuse-migrate-operation-declaration.ts +55 -0
  7. package/bin/apifuse-pack-smoke.ts +1 -1
  8. package/bin/apifuse-pack-types.ts +2 -1
  9. package/bin/apifuse-record.ts +30 -16
  10. package/bin/apifuse-submit-check.ts +20 -35
  11. package/dist/cli/commands.d.ts +1 -1
  12. package/dist/cli/commands.js +11 -0
  13. package/dist/cli/migrate-operation-declaration.d.ts +59 -0
  14. package/dist/cli/migrate-operation-declaration.js +1178 -0
  15. package/dist/cli/templates/provider/README.md.tpl +3 -3
  16. package/dist/cli/templates/provider/operations/ping.ts.tpl +2 -0
  17. package/dist/config/loader.d.ts +2 -0
  18. package/dist/config/loader.js +18 -7
  19. package/dist/contract-types.d.ts +11 -5
  20. package/dist/contract.js +21 -10
  21. package/dist/define.d.ts +25 -22
  22. package/dist/define.js +49 -75
  23. package/dist/dev.d.ts +3 -0
  24. package/dist/dev.js +1 -1
  25. package/dist/engine.d.ts +78 -0
  26. package/dist/engine.js +133 -0
  27. package/dist/index.d.ts +3 -2
  28. package/dist/index.js +2 -1
  29. package/dist/lint.d.ts +7 -15
  30. package/dist/lint.js +45 -70
  31. package/dist/provider.d.ts +3 -1
  32. package/dist/provider.js +1 -0
  33. package/dist/runtime/chrome149-header-order.d.ts +58 -0
  34. package/dist/runtime/chrome149-header-order.js +289 -0
  35. package/dist/runtime/env.js +12 -0
  36. package/dist/runtime/executor.d.ts +2 -1
  37. package/dist/runtime/executor.js +3 -36
  38. package/dist/runtime/insights.js +2 -2
  39. package/dist/runtime/otlp.d.ts +71 -2
  40. package/dist/runtime/otlp.js +397 -16
  41. package/dist/runtime/resolver-vendors/capsolver.js +3 -3
  42. package/dist/runtime/resolver.js +3 -3
  43. package/dist/runtime/stealth.d.ts +13 -4
  44. package/dist/runtime/stealth.js +362 -85
  45. package/dist/runtime/trace-config.js +2 -1
  46. package/dist/runtime/trace.d.ts +5 -0
  47. package/dist/runtime/trace.js +43 -10
  48. package/dist/server/self-test.d.ts +1 -3
  49. package/dist/server/self-test.js +2 -12
  50. package/dist/server/serve-implementation.d.ts +6 -1
  51. package/dist/server/serve-implementation.js +55 -40
  52. package/dist/server/trace-output.d.ts +3 -1
  53. package/dist/server/trace-output.js +61 -2
  54. package/dist/stealth/profiles.d.ts +9 -8
  55. package/dist/stealth/profiles.js +123 -286
  56. package/dist/types.d.ts +111 -108
  57. package/package.json +2 -1
  58. package/src/cli/__tests__/fixtures/migrate-operation-declaration/approval-override.ts.txt +6 -0
  59. package/src/cli/__tests__/fixtures/migrate-operation-declaration/codemod-syntax.ts.txt +3 -0
  60. package/src/cli/__tests__/fixtures/migrate-operation-declaration/connection-precedence.ts.txt +10 -0
  61. package/src/cli/__tests__/fixtures/migrate-operation-declaration/docs-conflict.ts.txt +8 -0
  62. package/src/cli/__tests__/fixtures/migrate-operation-declaration/examples-map.ts.txt +5 -0
  63. package/src/cli/__tests__/fixtures/migrate-operation-declaration/examples-operation.ts.txt +16 -0
  64. package/src/cli/__tests__/fixtures/migrate-operation-declaration/factory-map.ts.txt +3 -0
  65. package/src/cli/__tests__/fixtures/migrate-operation-declaration/hoist-all.ts.txt +31 -0
  66. package/src/cli/__tests__/fixtures/migrate-operation-declaration/hoisted-const.ts.txt +11 -0
  67. package/src/cli/__tests__/fixtures/migrate-operation-declaration/imported-spread.ts.txt +11 -0
  68. package/src/cli/__tests__/fixtures/migrate-operation-declaration/inline-map.ts.txt +11 -0
  69. package/src/cli/__tests__/fixtures/migrate-operation-declaration/inline-spread-cast-tail.ts.txt +21 -0
  70. package/src/cli/__tests__/fixtures/migrate-operation-declaration/inline-spread-ekitan.ts.txt +11 -0
  71. package/src/cli/__tests__/fixtures/migrate-operation-declaration/inline-spread-override.ts.txt +14 -0
  72. package/src/cli/__tests__/fixtures/migrate-operation-declaration/missing-english-locale.ts.txt +7 -0
  73. package/src/cli/__tests__/fixtures/migrate-operation-declaration/no-safety.ts.txt +6 -0
  74. package/src/cli/__tests__/fixtures/migrate-operation-declaration/non-literal.ts.txt +7 -0
  75. package/src/cli/__tests__/fixtures/migrate-operation-declaration/redundant-approval.ts.txt +6 -0
  76. package/src/cli/__tests__/fixtures/migrate-operation-declaration/safety-conflict.ts.txt +7 -0
  77. package/src/cli/__tests__/fixtures/migrate-operation-declaration/stream.ts.txt +7 -0
  78. package/src/cli/__tests__/fixtures/migrate-operation-declaration/tool-router-spread.ts.txt +15 -0
  79. package/src/cli/__tests__/fixtures/migrate-operation-declaration/unparseable.ts.txt +4 -0
  80. package/src/cli/__tests__/fixtures/migrate-operation-declaration/verbatim-template.ts.txt +12 -0
  81. package/src/cli/commands.ts +13 -0
  82. package/src/cli/migrate-operation-declaration.ts +1654 -0
  83. package/src/cli/templates/provider/README.md.tpl +3 -3
  84. package/src/cli/templates/provider/operations/ping.ts.tpl +2 -0
  85. package/src/config/loader.ts +31 -6
  86. package/src/contract-types.ts +11 -5
  87. package/src/contract.ts +21 -10
  88. package/src/define.ts +107 -119
  89. package/src/dev.ts +4 -1
  90. package/src/engine.ts +279 -0
  91. package/src/index.ts +13 -5
  92. package/src/lint.ts +58 -92
  93. package/src/provider.ts +25 -3
  94. package/src/runtime/chrome149-header-order.ts +330 -0
  95. package/src/runtime/env.ts +13 -0
  96. package/src/runtime/executor.ts +7 -40
  97. package/src/runtime/insights.ts +2 -2
  98. package/src/runtime/otlp.ts +467 -21
  99. package/src/runtime/resolver-vendors/capsolver.ts +4 -3
  100. package/src/runtime/resolver.ts +3 -3
  101. package/src/runtime/stealth.ts +435 -103
  102. package/src/runtime/trace-config.ts +3 -2
  103. package/src/runtime/trace.ts +57 -17
  104. package/src/server/self-test.ts +2 -9
  105. package/src/server/serve-implementation.ts +89 -72
  106. package/src/server/trace-output.ts +99 -2
  107. package/src/stealth/profiles.ts +169 -327
  108. package/src/types.ts +109 -137
@@ -0,0 +1,330 @@
1
+ const U64_MASK = (1n << 64n) - 1n;
2
+ const RAPID_SEED = 0xbdd89aa982704029n;
3
+ const RAPID_SECRET = [0x2d358dccaa6c78a5n, 0x8bb84b93962eacc9n, 0x4b33a62ed433d4a3n] as const;
4
+
5
+ interface HashReader {
6
+ readonly compressionFactor: number;
7
+ readonly expansionFactor: number;
8
+ read64(offset: number): bigint;
9
+ read32(offset: number): bigint;
10
+ readSmall(offset: number, length: number): bigint;
11
+ }
12
+
13
+ function latin1CaseFold(character: number): number {
14
+ if (character >= 0x41 && character <= 0x5a) return character + 0x20;
15
+ if (character === 0xb5) return 0x03bc;
16
+ if ((character >= 0xc0 && character <= 0xd6) || (character >= 0xd8 && character <= 0xde))
17
+ return character + 0x20;
18
+ return character;
19
+ }
20
+
21
+ function multiply128(a: bigint, b: bigint): [low: bigint, high: bigint] {
22
+ const product = (a & U64_MASK) * (b & U64_MASK);
23
+ return [product & U64_MASK, (product >> 64n) & U64_MASK];
24
+ }
25
+
26
+ function rapidMix(a: bigint, b: bigint): bigint {
27
+ const [low, high] = multiply128(a, b);
28
+ return low ^ high;
29
+ }
30
+
31
+ class PlainByteHashReader implements HashReader {
32
+ readonly compressionFactor = 1;
33
+ readonly expansionFactor = 1;
34
+
35
+ constructor(private readonly bytes: readonly number[]) {}
36
+
37
+ read64(offset: number): bigint {
38
+ let result = 0n;
39
+ for (let index = 0; index < 8; index += 1) {
40
+ result |= BigInt(this.bytes[offset + index] ?? 0) << BigInt(index * 8);
41
+ }
42
+ return result;
43
+ }
44
+
45
+ read32(offset: number): bigint {
46
+ let result = 0n;
47
+ for (let index = 0; index < 4; index += 1) {
48
+ result |= BigInt(this.bytes[offset + index] ?? 0) << BigInt(index * 8);
49
+ }
50
+ return result;
51
+ }
52
+
53
+ readSmall(offset: number, length: number): bigint {
54
+ return (
55
+ (BigInt(this.bytes[offset] ?? 0) << 56n) |
56
+ (BigInt(this.bytes[offset + (length >> 1)] ?? 0) << 32n) |
57
+ BigInt(this.bytes[offset + length - 1] ?? 0)
58
+ );
59
+ }
60
+ }
61
+
62
+ class CaseFoldingLatin1HashReader implements HashReader {
63
+ readonly compressionFactor = 1;
64
+ readonly expansionFactor = 2;
65
+
66
+ constructor(private readonly input: string) {}
67
+
68
+ private fold(offset: number): bigint {
69
+ return BigInt(latin1CaseFold(this.input.charCodeAt(offset)));
70
+ }
71
+
72
+ read64(offset: number): bigint {
73
+ return (
74
+ this.fold(offset) |
75
+ (this.fold(offset + 1) << 16n) |
76
+ (this.fold(offset + 2) << 32n) |
77
+ (this.fold(offset + 3) << 48n)
78
+ );
79
+ }
80
+
81
+ read32(offset: number): bigint {
82
+ return this.fold(offset) | (this.fold(offset + 1) << 16n);
83
+ }
84
+
85
+ readSmall(offset: number, length: number): bigint {
86
+ if (length !== 2) {
87
+ throw new Error(`CaseFoldingHashReader<LChar> received length ${length}; expected 2.`);
88
+ }
89
+ return this.fold(offset);
90
+ }
91
+ }
92
+
93
+ function rapidHash(reader: HashReader, producedLength: number): bigint {
94
+ const x = reader.compressionFactor;
95
+ const y = reader.expansionFactor;
96
+ if (producedLength % y !== 0) throw new Error("Invalid rapidhash reader length.");
97
+
98
+ let seed = RAPID_SEED;
99
+ seed ^= rapidMix(seed ^ RAPID_SECRET[0], RAPID_SECRET[1]) ^ BigInt(producedLength);
100
+ seed &= U64_MASK;
101
+ let offset = 0;
102
+ let a: bigint;
103
+ let b: bigint;
104
+
105
+ if (producedLength <= 16) {
106
+ if (producedLength >= 4) {
107
+ const last = offset + Math.trunc(((producedLength - 4) * x) / y);
108
+ a = (reader.read32(offset) << 32n) | reader.read32(last);
109
+ const delta = Math.trunc((((producedLength & 24) >> (producedLength >> 3)) * x) / y);
110
+ b = (reader.read32(offset + delta) << 32n) | reader.read32(last - delta);
111
+ } else if (producedLength > 0) {
112
+ a = reader.readSmall(offset, producedLength);
113
+ b = 0n;
114
+ } else {
115
+ a = 0n;
116
+ b = 0n;
117
+ }
118
+ } else {
119
+ let remaining = producedLength;
120
+ if (remaining > 48) {
121
+ let see1 = seed;
122
+ let see2 = seed;
123
+ do {
124
+ seed = rapidMix(
125
+ reader.read64(offset) ^ RAPID_SECRET[0],
126
+ reader.read64(offset + Math.trunc((8 * x) / y)) ^ seed,
127
+ );
128
+ see1 = rapidMix(
129
+ reader.read64(offset + Math.trunc((16 * x) / y)) ^ RAPID_SECRET[1],
130
+ reader.read64(offset + Math.trunc((24 * x) / y)) ^ see1,
131
+ );
132
+ see2 = rapidMix(
133
+ reader.read64(offset + Math.trunc((32 * x) / y)) ^ RAPID_SECRET[2],
134
+ reader.read64(offset + Math.trunc((40 * x) / y)) ^ see2,
135
+ );
136
+ offset += Math.trunc((48 * x) / y);
137
+ remaining -= 48;
138
+ } while (remaining >= 48);
139
+ seed ^= see1 ^ see2;
140
+ }
141
+ if (remaining > 16) {
142
+ seed = rapidMix(
143
+ reader.read64(offset) ^ RAPID_SECRET[2],
144
+ reader.read64(offset + Math.trunc((8 * x) / y)) ^ seed ^ RAPID_SECRET[1],
145
+ );
146
+ if (remaining > 32) {
147
+ seed = rapidMix(
148
+ reader.read64(offset + Math.trunc((16 * x) / y)) ^ RAPID_SECRET[2],
149
+ reader.read64(offset + Math.trunc((24 * x) / y)) ^ seed,
150
+ );
151
+ }
152
+ }
153
+ a = reader.read64(offset + Math.trunc(((remaining - 16) * x) / y));
154
+ b = reader.read64(offset + Math.trunc(((remaining - 8) * x) / y));
155
+ }
156
+
157
+ a ^= RAPID_SECRET[1];
158
+ b ^= seed;
159
+ [a, b] = multiply128(a, b);
160
+ return rapidMix(a ^ RAPID_SECRET[0] ^ BigInt(producedLength), b ^ RAPID_SECRET[1]);
161
+ }
162
+
163
+ function maskTopEightBits(hash: bigint): number {
164
+ const masked = Number(hash & 0xffffffn);
165
+ return masked === 0 ? 0x800000 : masked;
166
+ }
167
+
168
+ /** @internal Chromium 149 DeprecatedCaseFoldingHash for an LChar string. */
169
+ export function chrome149CaseFoldingHash(name: string): number {
170
+ const reader = new CaseFoldingLatin1HashReader(name);
171
+ return maskTopEightBits(rapidHash(reader, name.length * reader.expansionFactor));
172
+ }
173
+
174
+ /** @internal Numeric rapidhash fixture from Chromium's string_hasher_test.cc. */
175
+ export function chrome149RapidhashFixture(): { full: bigint; masked: number } {
176
+ const fixture = [0x41, 0x95, 0xff, 0x50, 0x01];
177
+ const full = rapidHash(new PlainByteHashReader(fixture), fixture.length);
178
+ return { full, masked: maskTopEightBits(full) };
179
+ }
180
+
181
+ function asciiCaseKey(name: string): string {
182
+ let result = "";
183
+ for (let index = 0; index < name.length; index += 1) {
184
+ const character = name.charCodeAt(index);
185
+ result += String.fromCharCode(
186
+ character >= 0x41 && character <= 0x5a ? character + 0x20 : character,
187
+ );
188
+ }
189
+ return result;
190
+ }
191
+
192
+ class WtfHeaderHashMap {
193
+ private table: Array<string | undefined> = [];
194
+ private keyCount = 0;
195
+
196
+ private insertWithoutExpansion(key: string): boolean {
197
+ const mask = this.table.length - 1;
198
+ let index = chrome149CaseFoldingHash(key) & mask;
199
+ let probeCount = 0;
200
+ const keyCaseFolded = asciiCaseKey(key);
201
+ for (;;) {
202
+ const stored = this.table[index];
203
+ if (stored === undefined) {
204
+ this.table[index] = key;
205
+ this.keyCount += 1;
206
+ return true;
207
+ }
208
+ if (asciiCaseKey(stored) === keyCaseFolded) return false;
209
+ probeCount += 1;
210
+ index = (index + probeCount) & mask;
211
+ }
212
+ }
213
+
214
+ private rehash(newSize: number): void {
215
+ const oldTable = this.table;
216
+ this.table = Array<string | undefined>(newSize);
217
+ this.keyCount = 0;
218
+ for (const key of oldTable) {
219
+ if (key !== undefined) this.insertWithoutExpansion(key);
220
+ }
221
+ }
222
+
223
+ insert(key: string): void {
224
+ if (this.table.length === 0) this.table = Array<string | undefined>(8);
225
+ if (!this.insertWithoutExpansion(key)) return;
226
+ if (this.keyCount * 2 >= this.table.length) this.rehash(this.table.length * 2);
227
+ }
228
+
229
+ iterationOrder(): string[] {
230
+ return this.table.filter((key): key is string => key !== undefined);
231
+ }
232
+ }
233
+
234
+ /**
235
+ * HTTPHeaderMap insertion sequence of the fixed headers in a real Chrome
236
+ * 149.0.7827.155 page fetch/XHR (insertion order, not bucket order). Caller
237
+ * headers precede all of these (core/fetch/fetch_manager.cc:1128-1130).
238
+ *
239
+ * platform/loader/fetch/resource_request_utils.cc:146 UpgradeResourceRequestForLoader
240
+ * :166 context.UpgradeResourceRequestForLoader
241
+ * -> core/loader/frame_fetch_context.cc:1000 AddClientHintsIfNecessary
242
+ * Set sec-ch-ua @737, sec-ch-ua-mobile @748, sec-ch-ua-platform @761
243
+ * -> :1001 AddReducedAcceptLanguageIfNecessary is a no-op
244
+ * (kReduceAcceptLanguage[HTTP] are FEATURE_DISABLED_BY_DEFAULT,
245
+ * services/network/public/cpp/features.cc:204,214)
246
+ * :214 context.PrepareRequest
247
+ * -> core/loader/frame_fetch_context.cc:419 SetHTTPUserAgent
248
+ * -> :455 probe::PrepareRequest, which only touches the map when a
249
+ * DevTools session has set an Accept-Language override:
250
+ * InspectorEmulationAgent::PrepareRequest (inspector_emulation_agent.cc
251
+ * :626-636, Emulation.setUserAgentOverride acceptLanguage; skips a key
252
+ * the page already set) or InspectorNetworkAgent::PrepareRequest
253
+ * (inspector_network_agent.cc:1524-1547, Network.setExtraHTTPHeaders;
254
+ * overwrites)
255
+ *
256
+ * Accept-Language is therefore NOT a map key in real Chrome. //net appends it
257
+ * in URLRequestHttpJob::AddExtraHeaders (net/url_request/url_request_http_job.cc
258
+ * :784-797) after Accept-Encoding, and only when the request does not already
259
+ * carry one (SetHeaderIfMissing), which is why a caller-supplied Accept-Language
260
+ * stays at its map bucket and is never emitted twice. al-placement-capture.json
261
+ * (B: no locale, C: --accept-lang=ja) confirms both the four-key map and the
262
+ * downstream slot.
263
+ *
264
+ * Every earlier corpus (placement-rule-sweep, expansion-sweep, holdout-capture,
265
+ * m1-capture) was captured through Playwright `newContext({ locale })`, which
266
+ * sets that override (Emulation.setUserAgentOverride acceptLanguage) and so
267
+ * inserts Accept-Language into the map as a fifth fixed key. Those fixtures still
268
+ * validate the hash and table mechanics;
269
+ * the tests interpret them through that harness insertion list. No production
270
+ * path uses it.
271
+ */
272
+ export const CHROME149_FIXED_MAP_INSERTION = [
273
+ "sec-ch-ua",
274
+ "sec-ch-ua-mobile",
275
+ "sec-ch-ua-platform",
276
+ "User-Agent",
277
+ ] as const;
278
+
279
+ /**
280
+ * Appended after PopulateResourceRequest has iterated the map: Fetch Metadata
281
+ * and Referer by the network service, then //net's Accept-Encoding and
282
+ * Accept-Language, then the HTTP/2 Priority header (net/spdy/spdy_http_utils.cc).
283
+ */
284
+ const DOWNSTREAM_SUFFIX = [
285
+ "sec-fetch-site",
286
+ "sec-fetch-mode",
287
+ "sec-fetch-dest",
288
+ "referer",
289
+ ] as const;
290
+
291
+ /**
292
+ * @internal Header-name order model parameterised by the fixed map insertion
293
+ * sequence. Production always passes {@link CHROME149_FIXED_MAP_INSERTION};
294
+ * tests pass the DevTools-harness sequence to validate corpora captured through
295
+ * Playwright's `locale` option.
296
+ */
297
+ export function chrome149HeaderOrderForMapInsertion(
298
+ callerNames: Iterable<string>,
299
+ fixedMapInsertion: readonly string[],
300
+ ): string[] {
301
+ const unique = new Map<string, string>();
302
+ for (const name of callerNames) {
303
+ const key = asciiCaseKey(name);
304
+ if (!unique.has(key)) unique.set(key, name);
305
+ }
306
+
307
+ const headerMap = new WtfHeaderHashMap();
308
+ for (const key of [...unique.keys()].sort()) headerMap.insert(unique.get(key) as string);
309
+ for (const name of fixedMapInsertion) headerMap.insert(name);
310
+
311
+ const order = headerMap.iterationOrder().map((name) => name.toLowerCase());
312
+ // SetAcceptHeader adds */* only when the caller Accept was absent.
313
+ if (!order.includes("accept")) order.push("accept");
314
+ order.push(...DOWNSTREAM_SUFFIX);
315
+ // URLRequestHttpJob::AddExtraHeaders: Accept-Encoding, then Accept-Language,
316
+ // each only if the request does not already carry it.
317
+ if (!order.includes("accept-encoding")) order.push("accept-encoding");
318
+ if (!order.includes("accept-language")) order.push("accept-language");
319
+ // CreateSpdyHeadersFromHttpRequest appends the default Priority only if absent.
320
+ if (!order.includes("priority")) order.push("priority");
321
+ return order;
322
+ }
323
+
324
+ /**
325
+ * @internal Predict real Chrome 149's non-pseudo HTTP/2 fetch/XHR header-name
326
+ * order for the given caller header names (no DevTools session attached).
327
+ */
328
+ export function chrome149HeaderOrder(callerNames: Iterable<string>): string[] {
329
+ return chrome149HeaderOrderForMapInsertion(callerNames, CHROME149_FIXED_MAP_INSERTION);
330
+ }
@@ -1,11 +1,24 @@
1
+ import { isEngineOwnedEnvName } from "../engine.js";
1
2
  import type { EnvContext } from "../types.js";
2
3
 
4
+ /**
5
+ * A mixed-case spelling of an engine-owned name is an alias: on Windows it resolves to the
6
+ * engine's variable while evading an exact-name allowlist. Only the exact (upper-case) name,
7
+ * which engine-internal contexts allowlist explicitly, may read those values.
8
+ */
9
+ function isEngineOwnedEnvAlias(key: string): boolean {
10
+ return isEngineOwnedEnvName(key) && key !== key.toUpperCase();
11
+ }
12
+
3
13
  export function createEnvContext(allowedKeys?: string[]): EnvContext {
4
14
  return {
5
15
  get(key: string): string | undefined {
6
16
  if (allowedKeys && !allowedKeys.includes(key)) {
7
17
  return undefined;
8
18
  }
19
+ if (isEngineOwnedEnvAlias(key)) {
20
+ return undefined;
21
+ }
9
22
 
10
23
  return process.env[key];
11
24
  },
@@ -1,15 +1,11 @@
1
- import { safeProviderErrorObservability } from "../error-observability.js";
2
1
  import {
3
- isSessionExpiredError,
4
2
  isValidationError,
5
3
  ProviderError,
6
- type ProviderErrorOptions,
7
- SessionExpiredError,
8
4
  ValidationError,
9
5
  } from "../errors.js";
10
6
  import { z } from "zod";
11
7
  import { parseSchema } from "../schema.js";
12
- import type { ProviderDefinition } from "../types.js";
8
+ import type { EnvContext, ProviderDefinition } from "../types.js";
13
9
  import { assertRequiredSecretsPresent } from "./secrets.js";
14
10
 
15
11
  export function isStreamingOperation(provider: ProviderDefinition, operationId: string): boolean {
@@ -17,13 +13,6 @@ export function isStreamingOperation(provider: ProviderDefinition, operationId:
17
13
  return kind !== "json";
18
14
  }
19
15
 
20
- function preservedSessionExpiredOptions(error: unknown): ProviderErrorOptions {
21
- const observability = safeProviderErrorObservability(error);
22
- return observability
23
- ? { observability, retryable: true }
24
- : { retryable: true };
25
- }
26
-
27
16
  /**
28
17
  * Execute a provider operation by calling its handler.
29
18
  *
@@ -43,7 +32,7 @@ export async function executeOperation<
43
32
  operationId: TOperationId,
44
33
  ctx: NoInfer<Parameters<TProvider["operations"][TOperationId]["handler"]>[0]>,
45
34
  input: unknown,
46
- _options?: { skipAuth?: boolean },
35
+ _options?: { skipAuth?: boolean; env?: EnvContext },
47
36
  ): Promise<unknown> {
48
37
  const operation = provider.operations[operationId];
49
38
 
@@ -60,7 +49,10 @@ export async function executeOperation<
60
49
  // record) fails with the same structured MISSING_SECRET error instead of a
61
50
  // handler-specific crash. Providers must not re-check presence locally.
62
51
  if (provider.secrets?.some((secret) => secret.required === true)) {
63
- assertRequiredSecretsPresent(provider, "env" in ctx ? ctx.env : { get: () => undefined });
52
+ assertRequiredSecretsPresent(
53
+ provider,
54
+ _options?.env ?? ("env" in ctx ? ctx.env : { get: () => undefined }),
55
+ );
64
56
  }
65
57
 
66
58
  const validatedInput = await parseSchema(
@@ -74,32 +66,7 @@ export async function executeOperation<
74
66
  Promise.resolve(operation.handler(ctx, validatedInput)),
75
67
  );
76
68
 
77
- let result: unknown;
78
- try {
79
- result = await execute();
80
- } catch (error) {
81
- // Session expiry is renewed by Credential Service via the /auth/refresh
82
- // route, NOT in-process here: this executor cannot mutate ctx.credential,
83
- // so an in-process retry would just repeat the call with the same stale
84
- // credential (and risk repeating partial side-effects). Instead we surface
85
- // the expiry so Credential Service refreshes and re-drives the operation
86
- // with a fresh credential. `retryOnAuthRefresh` declares that this
87
- // operation is safe to re-drive after refresh, which we signal by marking
88
- // the surfaced error retryable; non-idempotent operations (the default)
89
- // stay non-retryable so they are not auto-re-driven. See design.md §4.3 D3.
90
- // Use the branded guard, not `instanceof`: a handler loaded through a
91
- // duplicate/published SDK module can throw a correctly branded
92
- // SessionExpiredError whose constructor identity differs from this
93
- // executor's, which `instanceof` would miss — dropping the retryable
94
- // upgrade and stranding an operation that opted into auth refresh.
95
- if (isSessionExpiredError(error) && operation.retryOnAuthRefresh) {
96
- // Preserve provider-authored safe metadata while forcing the retry signal.
97
- // `cause` intentionally remains dropped, matching the pre-existing
98
- // reconstruction semantics.
99
- throw new SessionExpiredError(error.message, preservedSessionExpiredOptions(error));
100
- }
101
- throw error;
102
- }
69
+ const result: unknown = await execute();
103
70
 
104
71
  if (isStreamingOperation(provider, operationId)) {
105
72
  return result;
@@ -27,7 +27,7 @@ const DNS_WARN_MS = 5;
27
27
  const BROWSER_IDLE_MS = 5_000;
28
28
  const REFRESH_WARN_RATE = 0.1;
29
29
 
30
- const TLS_REUSE_FIX = `const session = ctx.stealth.createSession({ profile: 'chrome-desktop' });
30
+ const TLS_REUSE_FIX = `const session = ctx.stealth.createSession({ stealth: { browser: 'chrome', os: 'macos' } });
31
31
  const resp = await session.fetch(url, opts);`;
32
32
 
33
33
  const TRANSFORM_FIX = `transformResponse: (raw) => {
@@ -39,7 +39,7 @@ const LARGE_RESPONSE_FIX = `const resp = await ctx.http.get('/items', {
39
39
  });`;
40
40
 
41
41
  const DNS_FIX = `// Enable DNS caching or reuse a long-lived session per host.
42
- const session = ctx.stealth.createSession({ profile: 'chrome-desktop' });
42
+ const session = ctx.stealth.createSession({ stealth: { browser: 'chrome', os: 'macos' } });
43
43
  await session.fetch(url, opts);`;
44
44
 
45
45
  const PROXY_FIX = `// Re-check whether this operation really needs a proxy.