@apifuse/provider-sdk 2.2.0-beta.10 → 2.2.0-beta.12

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 (83) hide show
  1. package/AUTHORING.md +37 -0
  2. package/CHANGELOG.md +8 -0
  3. package/README.md +18 -0
  4. package/bin/apifuse-pack-smoke.ts +14 -0
  5. package/bin/apifuse-pack-types.ts +11 -1
  6. package/dist/config/loader.d.ts +9 -1
  7. package/dist/config/loader.js +9 -0
  8. package/dist/errors.d.ts +5 -0
  9. package/dist/errors.js +15 -0
  10. package/dist/index.d.ts +3 -3
  11. package/dist/index.js +1 -1
  12. package/dist/runtime/stealth.js +113 -47
  13. package/dist/server/index.d.ts +1 -1
  14. package/dist/server/index.js +1 -1
  15. package/dist/server/serve.d.ts +98 -2
  16. package/dist/server/serve.js +485 -23
  17. package/dist/stateful/errors.d.ts +14 -0
  18. package/dist/stateful/errors.js +14 -0
  19. package/dist/stateful/http-provider-event-emitter.d.ts +40 -0
  20. package/dist/stateful/http-provider-event-emitter.js +237 -0
  21. package/dist/stateful/http-session-owner-registry.d.ts +44 -0
  22. package/dist/stateful/http-session-owner-registry.js +210 -0
  23. package/dist/stateful/index.d.ts +18 -0
  24. package/dist/stateful/index.js +18 -0
  25. package/dist/stateful/provider-event-delivery-failures.d.ts +32 -0
  26. package/dist/stateful/provider-event-delivery-failures.js +43 -0
  27. package/dist/stateful/provider-event-pipeline-metrics.d.ts +46 -0
  28. package/dist/stateful/provider-event-pipeline-metrics.js +48 -0
  29. package/dist/stateful/provider-event-pipeline.d.ts +50 -0
  30. package/dist/stateful/provider-event-pipeline.js +1 -0
  31. package/dist/stateful/provider-events.d.ts +101 -0
  32. package/dist/stateful/provider-events.js +289 -0
  33. package/dist/stateful/session-key.d.ts +15 -0
  34. package/dist/stateful/session-key.js +86 -0
  35. package/dist/stateful/stateful-provider-adapter-context.d.ts +5 -0
  36. package/dist/stateful/stateful-provider-adapter-context.js +42 -0
  37. package/dist/stateful/stateful-provider-adapter-metrics.d.ts +15 -0
  38. package/dist/stateful/stateful-provider-adapter-metrics.js +21 -0
  39. package/dist/stateful/stateful-provider-adapter.d.ts +98 -0
  40. package/dist/stateful/stateful-provider-adapter.js +287 -0
  41. package/dist/stateful/stateful-provider-observability.d.ts +62 -0
  42. package/dist/stateful/stateful-provider-observability.js +161 -0
  43. package/dist/stateful/stateful-provider-owner-forwarder.d.ts +41 -0
  44. package/dist/stateful/stateful-provider-owner-forwarder.js +207 -0
  45. package/dist/stateful/stateful-provider-runtime-context.d.ts +32 -0
  46. package/dist/stateful/stateful-provider-runtime-context.js +60 -0
  47. package/dist/stateful/stateful-provider-runtime-executor.d.ts +34 -0
  48. package/dist/stateful/stateful-provider-runtime-executor.js +52 -0
  49. package/dist/stateful/stateful-provider-session-routing.d.ts +71 -0
  50. package/dist/stateful/stateful-provider-session-routing.js +353 -0
  51. package/dist/stateful/stateful-provider-session-runtime.d.ts +98 -0
  52. package/dist/stateful/stateful-provider-session-runtime.js +245 -0
  53. package/dist/stateful-signing.d.ts +18 -0
  54. package/dist/stateful-signing.js +27 -0
  55. package/dist/types.d.ts +39 -7
  56. package/package.json +7 -1
  57. package/src/config/loader.ts +22 -1
  58. package/src/errors.ts +15 -0
  59. package/src/index.ts +8 -1
  60. package/src/runtime/stealth.ts +127 -48
  61. package/src/server/index.ts +13 -1
  62. package/src/server/serve.ts +691 -25
  63. package/src/stateful/README.md +146 -0
  64. package/src/stateful/errors.ts +23 -0
  65. package/src/stateful/http-provider-event-emitter.ts +314 -0
  66. package/src/stateful/http-session-owner-registry.ts +306 -0
  67. package/src/stateful/index.ts +18 -0
  68. package/src/stateful/provider-event-delivery-failures.ts +80 -0
  69. package/src/stateful/provider-event-pipeline-metrics.ts +95 -0
  70. package/src/stateful/provider-event-pipeline.ts +61 -0
  71. package/src/stateful/provider-events.ts +462 -0
  72. package/src/stateful/session-key.ts +111 -0
  73. package/src/stateful/stateful-provider-adapter-context.ts +59 -0
  74. package/src/stateful/stateful-provider-adapter-metrics.ts +48 -0
  75. package/src/stateful/stateful-provider-adapter.ts +562 -0
  76. package/src/stateful/stateful-provider-observability.ts +261 -0
  77. package/src/stateful/stateful-provider-owner-forwarder.ts +279 -0
  78. package/src/stateful/stateful-provider-runtime-context.ts +92 -0
  79. package/src/stateful/stateful-provider-runtime-executor.ts +96 -0
  80. package/src/stateful/stateful-provider-session-routing.ts +555 -0
  81. package/src/stateful/stateful-provider-session-runtime.ts +403 -0
  82. package/src/stateful-signing.ts +46 -0
  83. package/src/types.ts +41 -7
@@ -0,0 +1,403 @@
1
+ import type { SessionKey } from "./session-key.js";
2
+
3
+ /** @deprecated Use SessionKey from session-key.ts. */
4
+ export type StatefulProviderSessionKey = SessionKey;
5
+ export type SessionOwnerStatus = "acquiring" | "connected" | "draining" | "expired";
6
+
7
+ export interface SessionOwnerRecord {
8
+ /** Runtime-decoded key; registry inputs use the opaque SessionKey type. */
9
+ readonly sessionKey: string;
10
+ readonly ownerPodId: string;
11
+ readonly ownerEndpoint: string;
12
+ readonly generation: number;
13
+ readonly leaseExpiresAt: string;
14
+ readonly status: SessionOwnerStatus;
15
+ readonly lastUsedAt: string;
16
+ }
17
+
18
+ export interface AcquireSessionOwnerInput {
19
+ readonly sessionKey: SessionKey;
20
+ readonly ownerPodId: string;
21
+ readonly ownerEndpoint: string;
22
+ readonly leaseDurationMs: number;
23
+ readonly status?: Exclude<SessionOwnerStatus, "expired">;
24
+ readonly now?: Date;
25
+ }
26
+
27
+ export interface AcquireSessionOwnerResult {
28
+ readonly record: SessionOwnerRecord;
29
+ readonly acquired: boolean;
30
+ }
31
+
32
+ export interface RenewSessionOwnerInput {
33
+ readonly sessionKey: SessionKey;
34
+ readonly ownerPodId: string;
35
+ readonly generation: number;
36
+ readonly leaseDurationMs: number;
37
+ readonly status?: Exclude<SessionOwnerStatus, "expired">;
38
+ readonly now?: Date;
39
+ }
40
+
41
+ export interface ReleaseSessionOwnerInput {
42
+ readonly sessionKey: SessionKey;
43
+ readonly ownerPodId: string;
44
+ readonly generation: number;
45
+ }
46
+
47
+ /**
48
+ * A session-owner registry is a fencing authority. Generations MUST be positive integers and
49
+ * strictly increase for each successful takeover of a session key, including after expiry or
50
+ * release. Implementations must retain a high-water mark (a tombstone) for at least the registry's
51
+ * lifetime; generation values must never be reused.
52
+ */
53
+ export interface SessionOwnerRegistry {
54
+ resolve(
55
+ sessionKey: SessionKey,
56
+ now?: Date,
57
+ signal?: AbortSignal,
58
+ ): Promise<SessionOwnerRecord | null>;
59
+ acquire(
60
+ input: AcquireSessionOwnerInput,
61
+ signal?: AbortSignal,
62
+ ): Promise<AcquireSessionOwnerResult>;
63
+ renew(input: RenewSessionOwnerInput, signal?: AbortSignal): Promise<SessionOwnerRecord | null>;
64
+ release(input: ReleaseSessionOwnerInput, signal?: AbortSignal): Promise<boolean>;
65
+ }
66
+
67
+ export interface SessionPoolPolicy {
68
+ readonly maxSessions: number;
69
+ /** Disable idle eviction for connection-owned listeners with `"unlimited"`. */
70
+ readonly idleTimeoutMs: number | "unlimited";
71
+ /** Disable age-based recycling for expensive healthy sessions with `"unlimited"`. */
72
+ readonly maxLifetimeMs: number | "unlimited";
73
+ }
74
+
75
+ export interface ManagedSessionIdentity {
76
+ readonly connectionId: string;
77
+ readonly serviceAccountId: string;
78
+ readonly ownerPodId: string;
79
+ readonly ownerEndpoint: string;
80
+ readonly ownerStatus: SessionOwnerStatus;
81
+ }
82
+
83
+ export interface ManagedSession<T> {
84
+ readonly sessionKey: string;
85
+ readonly generation: number;
86
+ readonly value: T;
87
+ readonly createdAt: string;
88
+ readonly lastUsedAt: string;
89
+ readonly identity?: ManagedSessionIdentity;
90
+ }
91
+
92
+ type SessionFactory<T> = () => T | Promise<T>;
93
+ type SessionCloseHook<T> = (session: ManagedSession<T>, reason: string) => void | Promise<void>;
94
+ export class InMemorySessionOwnerRegistry implements SessionOwnerRegistry {
95
+ readonly #owners = new Map<SessionKey, SessionOwnerRecord>();
96
+ readonly #generationHighWater = new Map<SessionKey, number>();
97
+
98
+ async resolve(
99
+ sessionKey: SessionKey,
100
+ now: Date = new Date(),
101
+ signal?: AbortSignal,
102
+ ): Promise<SessionOwnerRecord | null> {
103
+ signal?.throwIfAborted();
104
+ const current = this.#owners.get(sessionKey);
105
+ if (!current || isLeaseExpired(current, now)) return null;
106
+ validateGeneration(current.generation);
107
+ return current;
108
+ }
109
+
110
+ async acquire(
111
+ input: AcquireSessionOwnerInput,
112
+ signal?: AbortSignal,
113
+ ): Promise<AcquireSessionOwnerResult> {
114
+ signal?.throwIfAborted();
115
+ validateLeaseDuration(input.leaseDurationMs);
116
+ const now = input.now ?? new Date();
117
+ const current = this.#owners.get(input.sessionKey);
118
+ if (current && !isLeaseExpired(current, now)) {
119
+ validateGeneration(current.generation);
120
+ if (current.ownerPodId !== input.ownerPodId) {
121
+ return { record: current, acquired: false };
122
+ }
123
+ const record = makeOwnerRecord(input, current.generation, now);
124
+ this.#owners.set(input.sessionKey, record);
125
+ return { record, acquired: true };
126
+ }
127
+
128
+ const generation =
129
+ Math.max(current?.generation ?? 0, this.#generationHighWater.get(input.sessionKey) ?? 0) + 1;
130
+ const record = makeOwnerRecord(input, generation, now);
131
+ this.#owners.set(input.sessionKey, record);
132
+ this.#generationHighWater.set(input.sessionKey, generation);
133
+ return { record, acquired: true };
134
+ }
135
+
136
+ async renew(
137
+ input: RenewSessionOwnerInput,
138
+ signal?: AbortSignal,
139
+ ): Promise<SessionOwnerRecord | null> {
140
+ signal?.throwIfAborted();
141
+ validateGeneration(input.generation);
142
+ validateLeaseDuration(input.leaseDurationMs);
143
+ const now = input.now ?? new Date();
144
+ const current = this.#owners.get(input.sessionKey);
145
+ if (
146
+ !current ||
147
+ current.ownerPodId !== input.ownerPodId ||
148
+ current.generation !== input.generation ||
149
+ isLeaseExpired(current, now)
150
+ ) {
151
+ return null;
152
+ }
153
+
154
+ const record: SessionOwnerRecord = {
155
+ ...current,
156
+ leaseExpiresAt: addMs(now, input.leaseDurationMs).toISOString(),
157
+ status: input.status ?? current.status,
158
+ lastUsedAt: now.toISOString(),
159
+ };
160
+ this.#owners.set(input.sessionKey, record);
161
+ return record;
162
+ }
163
+
164
+ async release(input: ReleaseSessionOwnerInput, signal?: AbortSignal): Promise<boolean> {
165
+ signal?.throwIfAborted();
166
+ validateGeneration(input.generation);
167
+ const current = this.#owners.get(input.sessionKey);
168
+ if (
169
+ !current ||
170
+ current.ownerPodId !== input.ownerPodId ||
171
+ current.generation !== input.generation
172
+ ) {
173
+ return false;
174
+ }
175
+ this.#generationHighWater.set(
176
+ input.sessionKey,
177
+ Math.max(this.#generationHighWater.get(input.sessionKey) ?? 0, current.generation),
178
+ );
179
+ this.#owners.delete(input.sessionKey);
180
+ return true;
181
+ }
182
+ }
183
+
184
+ export class PodLocalSessionPool<T> {
185
+ readonly #sessions = new Map<string, ManagedSession<T>>();
186
+ readonly #queues = new Map<string, Promise<void>>();
187
+ readonly #creates = new Map<string, Promise<ManagedSession<T>>>();
188
+ #closed = false;
189
+
190
+ constructor(
191
+ private readonly policy: SessionPoolPolicy,
192
+ private readonly closeSession: SessionCloseHook<T>,
193
+ ) {
194
+ validatePoolPolicy(policy);
195
+ }
196
+
197
+ async getOrCreate(
198
+ sessionKey: string,
199
+ generation: number,
200
+ factory: SessionFactory<T>,
201
+ now: Date = new Date(),
202
+ identity?: ManagedSessionIdentity,
203
+ ): Promise<ManagedSession<T>> {
204
+ validateGeneration(generation);
205
+ this.assertOpen(sessionKey);
206
+ const existingCreate = this.#creates.get(sessionKey);
207
+ if (existingCreate) {
208
+ try {
209
+ await existingCreate;
210
+ } catch {}
211
+ this.assertOpen(sessionKey);
212
+ }
213
+ const create = this.getOrCreateUnlocked(sessionKey, generation, factory, now, identity);
214
+ this.#creates.set(sessionKey, create);
215
+ try {
216
+ const session = await create;
217
+ this.assertOpen(sessionKey);
218
+ return session;
219
+ } finally {
220
+ if (this.#creates.get(sessionKey) === create) this.#creates.delete(sessionKey);
221
+ }
222
+ }
223
+
224
+ private async getOrCreateUnlocked(
225
+ sessionKey: string,
226
+ generation: number,
227
+ factory: SessionFactory<T>,
228
+ now: Date,
229
+ identity?: ManagedSessionIdentity,
230
+ ): Promise<ManagedSession<T>> {
231
+ await this.evictExpired(now);
232
+
233
+ const current = this.#sessions.get(sessionKey);
234
+ if (current && current.generation === generation) {
235
+ const touched = { ...current, lastUsedAt: now.toISOString() };
236
+ this.#sessions.delete(sessionKey);
237
+ this.#sessions.set(sessionKey, touched);
238
+ return touched;
239
+ }
240
+ if (current) await this.closeOne(sessionKey, "generation-changed");
241
+
242
+ const session: ManagedSession<T> = {
243
+ sessionKey,
244
+ generation,
245
+ value: await factory(),
246
+ createdAt: now.toISOString(),
247
+ lastUsedAt: now.toISOString(),
248
+ ...(identity ? { identity } : {}),
249
+ };
250
+ this.#sessions.set(sessionKey, session);
251
+ await this.evictOverCapacity();
252
+ return session;
253
+ }
254
+
255
+ async closeAll(reason: string): Promise<void> {
256
+ this.#closed = true;
257
+ const errors: unknown[] = [];
258
+ await Promise.all(
259
+ [...this.#creates.values()].map(async (create) => {
260
+ let session: ManagedSession<T>;
261
+ try {
262
+ session = await create;
263
+ } catch {
264
+ return;
265
+ }
266
+ try {
267
+ await this.closeOne(session.sessionKey, reason);
268
+ } catch (error) {
269
+ errors.push(error);
270
+ }
271
+ }),
272
+ );
273
+ for (const sessionKey of [...this.#sessions.keys()]) {
274
+ try {
275
+ await this.closeOne(sessionKey, reason);
276
+ } catch (error) {
277
+ errors.push(error);
278
+ }
279
+ }
280
+ if (errors.length > 0) {
281
+ throw new AggregateError(errors, `Failed to close ${errors.length} stateful session(s).`);
282
+ }
283
+ }
284
+
285
+ async invalidate(sessionKey: string, reason: string): Promise<void> {
286
+ await this.closeOne(sessionKey, reason);
287
+ }
288
+
289
+ async runExclusive<R>(sessionKey: string, task: () => R | Promise<R>): Promise<R> {
290
+ const previous = this.#queues.get(sessionKey) ?? Promise.resolve();
291
+ const next = previous.then(task, task);
292
+ const settled = next.then(
293
+ () => undefined,
294
+ () => undefined,
295
+ );
296
+ this.#queues.set(sessionKey, settled);
297
+ await settled.finally(() => {
298
+ if (this.#queues.get(sessionKey) === settled) {
299
+ this.#queues.delete(sessionKey);
300
+ }
301
+ });
302
+ return next;
303
+ }
304
+
305
+ private async evictExpired(now: Date): Promise<void> {
306
+ for (const [sessionKey, session] of this.#sessions) {
307
+ if (isSessionExpired(session, this.policy, now)) {
308
+ await this.closeOne(sessionKey, "expired");
309
+ }
310
+ }
311
+ }
312
+
313
+ private async evictOverCapacity(): Promise<void> {
314
+ while (this.#sessions.size > this.policy.maxSessions) {
315
+ const lruKey = this.#sessions.keys().next().value;
316
+ if (lruKey === undefined) return;
317
+ await this.closeOne(lruKey, "capacity");
318
+ }
319
+ }
320
+
321
+ private async closeOne(sessionKey: string, reason: string): Promise<void> {
322
+ const session = this.#sessions.get(sessionKey);
323
+ if (!session) return;
324
+ this.#sessions.delete(sessionKey);
325
+ await this.closeSession(session, reason);
326
+ }
327
+
328
+ private assertOpen(sessionKey: string): void {
329
+ if (!this.#closed) return;
330
+ throw new Error(
331
+ `Pod-local session pool is closed; cannot get or create session "${sessionKey}".`,
332
+ );
333
+ }
334
+ }
335
+
336
+ function makeOwnerRecord(
337
+ input: AcquireSessionOwnerInput,
338
+ generation: number,
339
+ now: Date,
340
+ ): SessionOwnerRecord {
341
+ validateGeneration(generation);
342
+ return {
343
+ sessionKey: input.sessionKey,
344
+ ownerPodId: input.ownerPodId,
345
+ ownerEndpoint: input.ownerEndpoint,
346
+ generation,
347
+ leaseExpiresAt: addMs(now, input.leaseDurationMs).toISOString(),
348
+ status: input.status ?? "acquiring",
349
+ lastUsedAt: now.toISOString(),
350
+ };
351
+ }
352
+
353
+ function isLeaseExpired(record: SessionOwnerRecord, now: Date): boolean {
354
+ return Date.parse(record.leaseExpiresAt) <= now.getTime();
355
+ }
356
+
357
+ function isSessionExpired<T>(
358
+ session: ManagedSession<T>,
359
+ policy: SessionPoolPolicy,
360
+ now: Date,
361
+ ): boolean {
362
+ const nowMs = now.getTime();
363
+ return (
364
+ (policy.idleTimeoutMs !== "unlimited" &&
365
+ nowMs - Date.parse(session.lastUsedAt) >= policy.idleTimeoutMs) ||
366
+ (policy.maxLifetimeMs !== "unlimited" &&
367
+ nowMs - Date.parse(session.createdAt) >= policy.maxLifetimeMs)
368
+ );
369
+ }
370
+
371
+ function validateLeaseDuration(leaseDurationMs: number): void {
372
+ if (!Number.isFinite(leaseDurationMs) || leaseDurationMs <= 0) {
373
+ throw new Error("Session owner leaseDurationMs must be a positive finite number.");
374
+ }
375
+ }
376
+
377
+ function validateGeneration(generation: number): void {
378
+ if (!Number.isInteger(generation) || generation <= 0) {
379
+ throw new Error("Session owner generation must be a positive integer.");
380
+ }
381
+ }
382
+
383
+ function validatePoolPolicy(policy: SessionPoolPolicy): void {
384
+ if (!Number.isInteger(policy.maxSessions) || policy.maxSessions <= 0) {
385
+ throw new Error("Session pool maxSessions must be a positive integer.");
386
+ }
387
+ if (
388
+ policy.idleTimeoutMs !== "unlimited" &&
389
+ (!Number.isFinite(policy.idleTimeoutMs) || policy.idleTimeoutMs <= 0)
390
+ ) {
391
+ throw new Error('Session pool idleTimeoutMs must be a positive finite number or "unlimited".');
392
+ }
393
+ if (
394
+ policy.maxLifetimeMs !== "unlimited" &&
395
+ (!Number.isFinite(policy.maxLifetimeMs) || policy.maxLifetimeMs <= 0)
396
+ ) {
397
+ throw new Error('Session pool maxLifetimeMs must be a positive finite number or "unlimited".');
398
+ }
399
+ }
400
+
401
+ function addMs(date: Date, ms: number): Date {
402
+ return new Date(date.getTime() + ms);
403
+ }
@@ -0,0 +1,46 @@
1
+ import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
2
+
3
+ export const STATEFUL_SIGNATURE_HEADER = "x-apifuse-stateful-signature";
4
+ export const STATEFUL_TIMESTAMP_HEADER = "x-apifuse-stateful-timestamp";
5
+ export const STATEFUL_NONCE_HEADER = "x-apifuse-stateful-nonce";
6
+
7
+ export type StatefulSigningInput = {
8
+ readonly secret: string;
9
+ readonly timestamp: string;
10
+ readonly rawBody: string;
11
+ readonly method: string;
12
+ readonly path: string;
13
+ readonly nonce: string;
14
+ };
15
+
16
+ export function signStatefulRequestBody(input: StatefulSigningInput): string {
17
+ return `v1=${createHmac("sha256", input.secret)
18
+ .update(
19
+ `v1:${input.method.toUpperCase()}:${input.path}:${input.timestamp}:${input.nonce}.${input.rawBody}`,
20
+ )
21
+ .digest("hex")}`;
22
+ }
23
+
24
+ export function verifyStatefulRequestSignature(
25
+ input: StatefulSigningInput & { readonly signature: string },
26
+ ): boolean {
27
+ return safeEqualAscii(input.signature, signStatefulRequestBody(input));
28
+ }
29
+
30
+ export function statefulSignedHeaders(
31
+ input: Omit<StatefulSigningInput, "nonce"> & { readonly nonce?: string },
32
+ ): Record<string, string> {
33
+ const nonce = input.nonce ?? randomUUID();
34
+ return {
35
+ [STATEFUL_SIGNATURE_HEADER]: signStatefulRequestBody({ ...input, nonce }),
36
+ [STATEFUL_TIMESTAMP_HEADER]: input.timestamp,
37
+ [STATEFUL_NONCE_HEADER]: nonce,
38
+ };
39
+ }
40
+
41
+ function safeEqualAscii(actual: string, expected: string): boolean {
42
+ const actualBytes = Buffer.from(actual);
43
+ const expectedBytes = Buffer.from(expected);
44
+ if (actualBytes.byteLength !== expectedBytes.byteLength) return false;
45
+ return timingSafeEqual(actualBytes, expectedBytes);
46
+ }
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type ms from "ms";
2
+ import type { SerializedCookieJar } from "tough-cookie";
2
3
 
3
4
  import type { infer as ZodInfer, ZodType } from "zod";
4
5
 
@@ -1051,18 +1052,45 @@ export interface StealthFetchOptions extends RequestOptions {
1051
1052
  }
1052
1053
 
1053
1054
  export interface CookieJar {
1054
- get(name: string): string | undefined;
1055
- getAll(): Record<string, string>;
1056
- toString(): string;
1057
- find?(predicate: (cookie: string) => boolean): string | undefined;
1055
+ /** URL-less reads use the jar's response URL or session base URL. */
1056
+ get(name: string, url?: string): string | undefined;
1057
+ getAll(url?: string): Record<string, string>;
1058
+ toString(url?: string): string;
1059
+ find?(predicate: (cookie: string) => boolean, url?: string): string | undefined;
1060
+ }
1061
+
1062
+ /**
1063
+ * Version 1 of the JSON-safe, attribute-preserving stealth cookie store.
1064
+ * The nested jar is tough-cookie's serialized form and retains cookie origin,
1065
+ * Path, Secure, expiry, host-only, and other RFC attributes.
1066
+ */
1067
+ export interface StealthCookieStoreV1 {
1068
+ readonly version: 1;
1069
+ readonly jar: SerializedCookieJar;
1058
1070
  }
1059
1071
 
1072
+ /** Cookie persistence formats understood by this SDK version. */
1073
+ export type StealthCookieStore = StealthCookieStoreV1;
1074
+
1060
1075
  export interface StealthSessionCookies extends CookieJar {
1061
- has(name: string): boolean;
1062
- setFromCookieStrings(cookieStrings: readonly string[]): void;
1063
- toHeader(): string;
1076
+ has(name: string, url?: string): boolean;
1077
+ /** URL-less writes are scoped to the session base URL. */
1078
+ setFromCookieStrings(cookieStrings: readonly string[], url?: string): void;
1079
+ toHeader(url?: string): string;
1080
+ /**
1081
+ * Returns every cookie as a flat name/value map, collapsing duplicate names.
1082
+ * @deprecated Use serialize() for lossless, attribute-preserving persistence.
1083
+ */
1064
1084
  snapshot(): Record<string, string>;
1085
+ /**
1086
+ * Restores flat values as host-only, Path=/ cookies on the session base URL.
1087
+ * @deprecated Use deserialize() with state produced by serialize().
1088
+ */
1065
1089
  restore(cookies: Record<string, string>): void;
1090
+ /** Returns a versioned, JSON-safe, attribute-preserving representation of every cookie. */
1091
+ serialize(): StealthCookieStoreV1;
1092
+ /** Replaces the jar with a previously serialized, attribute-preserving cookie store. */
1093
+ deserialize(state: StealthCookieStore): void;
1066
1094
  clear(): void;
1067
1095
  }
1068
1096
 
@@ -1108,7 +1136,13 @@ export interface StealthRedirectRunResult {
1108
1136
  final: StealthResponse;
1109
1137
  hops: StealthRedirectHop[];
1110
1138
  reason: "completed" | "stopped" | "max_hops" | "missing_location" | "loop";
1139
+ /**
1140
+ * Complete flat view across all redirect hosts. Attributes and duplicate names are lost.
1141
+ * @deprecated Use cookieStore for lossless persistence.
1142
+ */
1111
1143
  cookies: Record<string, string>;
1144
+ /** Versioned, attribute-preserving cookie state accumulated across the redirect chain. */
1145
+ cookieStore: StealthCookieStoreV1;
1112
1146
  }
1113
1147
 
1114
1148
  export interface StealthSession {