@bedrock-rbx/ocale 0.1.3 → 0.1.4
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/dist/badges.d.mts +21 -6
- package/dist/badges.d.mts.map +1 -1
- package/dist/badges.mjs +10 -11
- package/dist/badges.mjs.map +1 -1
- package/dist/developer-products.d.mts +22 -11
- package/dist/developer-products.d.mts.map +1 -1
- package/dist/developer-products.mjs +21 -20
- package/dist/developer-products.mjs.map +1 -1
- package/dist/game-passes.d.mts +5 -5
- package/dist/game-passes.mjs +18 -20
- package/dist/game-passes.mjs.map +1 -1
- package/dist/index.d.mts +9 -5
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/luau-execution.d.mts +5 -3
- package/dist/luau-execution.d.mts.map +1 -1
- package/dist/luau-execution.mjs +22 -18
- package/dist/luau-execution.mjs.map +1 -1
- package/dist/places.d.mts +2 -2
- package/dist/places.d.mts.map +1 -1
- package/dist/places.mjs +31 -31
- package/dist/places.mjs.map +1 -1
- package/dist/{poll-timeout-BfxUWWCZ.mjs → poll-timeout-DXfJVZzR.mjs} +2 -2
- package/dist/{poll-timeout-BfxUWWCZ.mjs.map → poll-timeout-DXfJVZzR.mjs.map} +1 -1
- package/dist/{polling-rj0dGREg.d.mts → polling-CG12rHaz.d.mts} +29 -11
- package/dist/polling-CG12rHaz.d.mts.map +1 -0
- package/dist/{polling-helpers-DkJcWZpp.mjs → polling-helpers-SBN188o5.mjs} +47 -53
- package/dist/polling-helpers-SBN188o5.mjs.map +1 -0
- package/dist/{price-information-ClGhSmgI.mjs → price-information-DziMfTQ6.mjs} +2 -2
- package/dist/{price-information-ClGhSmgI.mjs.map → price-information-DziMfTQ6.mjs.map} +1 -1
- package/dist/{rate-limit-Dh2leqaB.mjs → rate-limit-B20REZEY.mjs} +6 -4
- package/dist/{rate-limit-Dh2leqaB.mjs.map → rate-limit-B20REZEY.mjs.map} +1 -1
- package/dist/{resource-client-CsbYSKwf.mjs → resource-client-rQ9bBn4L.mjs} +138 -62
- package/dist/resource-client-rQ9bBn4L.mjs.map +1 -0
- package/dist/{retry-BEh37aK2.d.mts → retry-DGY51INM.d.mts} +14 -12
- package/dist/{retry-BEh37aK2.d.mts.map → retry-DGY51INM.d.mts.map} +1 -1
- package/dist/{retry-CMzwdn1c.mjs → retry-PmpgEwFN.mjs} +21 -19
- package/dist/retry-PmpgEwFN.mjs.map +1 -0
- package/dist/storage.d.mts +33 -8
- package/dist/storage.d.mts.map +1 -1
- package/dist/storage.mjs +24 -33
- package/dist/storage.mjs.map +1 -1
- package/dist/testing.d.mts +50 -16
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +5 -3
- package/dist/testing.mjs.map +1 -1
- package/dist/{types-CRiJg5EQ.d.mts → types-DXai6-hU.d.mts} +5 -3
- package/dist/{types-CRiJg5EQ.d.mts.map → types-DXai6-hU.d.mts.map} +1 -1
- package/dist/universes.d.mts +7 -4
- package/dist/universes.d.mts.map +1 -1
- package/dist/universes.mjs +20 -25
- package/dist/universes.mjs.map +1 -1
- package/dist/{validation-xJZRa8tX.mjs → validation-BXhEM3OP.mjs} +2 -2
- package/dist/{validation-xJZRa8tX.mjs.map → validation-BXhEM3OP.mjs.map} +1 -1
- package/package.json +4 -3
- package/dist/polling-helpers-DkJcWZpp.mjs.map +0 -1
- package/dist/polling-rj0dGREg.d.mts.map +0 -1
- package/dist/resource-client-CsbYSKwf.mjs.map +0 -1
- package/dist/retry-CMzwdn1c.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as NetworkError, r as ApiError, t as RateLimitError } from "./rate-limit-
|
|
2
|
-
import { a as computeRetryWaitMs, c as shouldRetry, n as IDEMPOTENT_METHOD_DEFAULTS, o as defaultRetryDelay, s as mergeConfig, u as PermissionError } from "./retry-
|
|
1
|
+
import { n as NetworkError, r as ApiError, t as RateLimitError } from "./rate-limit-B20REZEY.mjs";
|
|
2
|
+
import { a as computeRetryWaitMs, c as shouldRetry, n as IDEMPOTENT_METHOD_DEFAULTS, o as defaultRetryDelay, s as mergeConfig, u as PermissionError } from "./retry-PmpgEwFN.mjs";
|
|
3
3
|
import { setTimeout } from "node:timers/promises";
|
|
4
4
|
//#region src/internal/utils/is-date-time-string.ts
|
|
5
5
|
/**
|
|
@@ -32,6 +32,52 @@ function isRecord(value) {
|
|
|
32
32
|
return Object.prototype.toString.call(value) === "[object Object]";
|
|
33
33
|
}
|
|
34
34
|
//#endregion
|
|
35
|
+
//#region src/internal/utils/to-json-details.ts
|
|
36
|
+
/**
|
|
37
|
+
* Narrows an untyped response body to the `JSONValue` accepted by
|
|
38
|
+
* `ApiError.details`. `HttpResponse.body` is `unknown` because a transport may
|
|
39
|
+
* hand back anything, but only a JSON graph is safe to retain on an error for
|
|
40
|
+
* diagnostics. Anything else — functions, symbols, bigints, class instances,
|
|
41
|
+
* or a cyclic graph — is dropped rather than asserted through.
|
|
42
|
+
*
|
|
43
|
+
* @param value - The parsed response body, or `undefined` for an empty body.
|
|
44
|
+
* @returns The value as a `JSONValue`, or `undefined` when it is absent or not
|
|
45
|
+
* JSON-representable.
|
|
46
|
+
*/
|
|
47
|
+
function toJsonDetails(value) {
|
|
48
|
+
return asJsonValue(value, /* @__PURE__ */ new Set());
|
|
49
|
+
}
|
|
50
|
+
function asJsonValue(value, seen) {
|
|
51
|
+
if (value === null) return null;
|
|
52
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
|
|
53
|
+
if (Array.isArray(value)) return asJsonArray(value, seen);
|
|
54
|
+
if (isRecord(value)) return asJsonObject(value, seen);
|
|
55
|
+
}
|
|
56
|
+
function asJsonArray(value, seen) {
|
|
57
|
+
if (seen.has(value)) return;
|
|
58
|
+
seen.add(value);
|
|
59
|
+
const items = [];
|
|
60
|
+
for (const item of value) {
|
|
61
|
+
const converted = asJsonValue(item, seen);
|
|
62
|
+
if (converted === void 0) return;
|
|
63
|
+
items.push(converted);
|
|
64
|
+
}
|
|
65
|
+
seen.delete(value);
|
|
66
|
+
return items;
|
|
67
|
+
}
|
|
68
|
+
function asJsonObject(value, seen) {
|
|
69
|
+
if (seen.has(value)) return;
|
|
70
|
+
seen.add(value);
|
|
71
|
+
const entries = [];
|
|
72
|
+
for (const [key, item] of Object.entries(value)) {
|
|
73
|
+
const converted = asJsonValue(item, seen);
|
|
74
|
+
if (converted === void 0) return;
|
|
75
|
+
entries.push([key, converted]);
|
|
76
|
+
}
|
|
77
|
+
seen.delete(value);
|
|
78
|
+
return Object.fromEntries(entries);
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
35
81
|
//#region src/internal/http/budget-tracker.ts
|
|
36
82
|
const MS_PER_SECOND = 1e3;
|
|
37
83
|
/**
|
|
@@ -131,10 +177,10 @@ var BudgetGate = class {
|
|
|
131
177
|
*
|
|
132
178
|
* @param scope - The scope key to gate on (the effective API key).
|
|
133
179
|
*/
|
|
134
|
-
async
|
|
180
|
+
async gateAsync(scope) {
|
|
135
181
|
const previous = this.#chains.get(scope) ?? Promise.resolve();
|
|
136
|
-
const
|
|
137
|
-
const mine = previous.then(
|
|
182
|
+
const runGateAsync = async () => this.#gateOnce(scope);
|
|
183
|
+
const mine = previous.then(runGateAsync, runGateAsync);
|
|
138
184
|
this.#chains.set(scope, mine);
|
|
139
185
|
await mine;
|
|
140
186
|
}
|
|
@@ -143,7 +189,7 @@ var BudgetGate = class {
|
|
|
143
189
|
* sample (headers absent or non-numeric) is ignored, leaving the scope on
|
|
144
190
|
* static pacing.
|
|
145
191
|
*
|
|
146
|
-
* @param scope - The same scope key passed to {@link
|
|
192
|
+
* @param scope - The same scope key passed to {@link gateAsync}.
|
|
147
193
|
* @param sample - Parsed sample, or `undefined` when none was reported.
|
|
148
194
|
*/
|
|
149
195
|
observe(scope, sample) {
|
|
@@ -177,13 +223,12 @@ var BudgetGate = class {
|
|
|
177
223
|
* @param options - The transport callback, resolved config, hooks, and sleep.
|
|
178
224
|
* @returns The first success, or the final error after retries are exhausted.
|
|
179
225
|
*/
|
|
180
|
-
async function
|
|
181
|
-
|
|
182
|
-
async function attempt() {
|
|
226
|
+
async function executeWithRetryAsync(request, { config, hooks, send, sleep }) {
|
|
227
|
+
async function attemptAsync() {
|
|
183
228
|
hooks.onRequest?.(request);
|
|
184
229
|
return send(request);
|
|
185
230
|
}
|
|
186
|
-
let result = await
|
|
231
|
+
let result = await attemptAsync();
|
|
187
232
|
for (let retry = 0; retry < config.maxRetries; retry++) {
|
|
188
233
|
if (result.success || !shouldRetry(result.err, config)) return result;
|
|
189
234
|
const { err } = result;
|
|
@@ -194,7 +239,7 @@ async function executeWithRetry(request, options) {
|
|
|
194
239
|
});
|
|
195
240
|
hooks.onRateLimit?.(waitMs);
|
|
196
241
|
await sleep(waitMs);
|
|
197
|
-
result = await
|
|
242
|
+
result = await attemptAsync();
|
|
198
243
|
}
|
|
199
244
|
return result;
|
|
200
245
|
}
|
|
@@ -229,8 +274,12 @@ function reduceRateLimitTokens(headerValue, combine) {
|
|
|
229
274
|
* @returns The parsed sample, or `undefined` when the budget cannot be read.
|
|
230
275
|
*/
|
|
231
276
|
function parseRateLimitHeaders(headers) {
|
|
232
|
-
const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) =>
|
|
233
|
-
|
|
277
|
+
const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
|
|
278
|
+
return Math.min(a, b);
|
|
279
|
+
});
|
|
280
|
+
const resetSeconds = reduceRateLimitTokens(headers["x-ratelimit-reset"], (a, b) => {
|
|
281
|
+
return Math.max(a, b);
|
|
282
|
+
});
|
|
234
283
|
if (remaining === void 0 || resetSeconds === void 0) return;
|
|
235
284
|
return {
|
|
236
285
|
remaining,
|
|
@@ -262,12 +311,16 @@ function rateLimitSampleFromResult(result) {
|
|
|
262
311
|
/**
|
|
263
312
|
* Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every
|
|
264
313
|
* call to `acquire` consumes one token; when the bucket is empty the call
|
|
265
|
-
* waits until a token regenerates before invoking the task.
|
|
266
|
-
*
|
|
314
|
+
* waits until a token regenerates before invoking the task. Tokens refill at
|
|
315
|
+
* `maxPerSecond` per second, up to the operation's `burstCapacity`.
|
|
267
316
|
*
|
|
268
317
|
* Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`
|
|
269
318
|
* advances by `waitMs` after every sleep so the algorithm stays correct
|
|
270
|
-
* whether or not the injected sleep moves `Date.now()` forward.
|
|
319
|
+
* whether or not the injected sleep moves `Date.now()` forward. `#bucketLevel`
|
|
320
|
+
* and `#maxBucketLevel` are both ms of drain debt, so the ceiling is the burst
|
|
321
|
+
* expressed in that unit: `burstCapacity` refill intervals. Deriving it any
|
|
322
|
+
* other way (notably `maxPerSecond * intervalMs`, whose units cancel to a
|
|
323
|
+
* constant 1000) starves every operation slower than one request per second.
|
|
271
324
|
*/
|
|
272
325
|
var RateLimitQueue = class {
|
|
273
326
|
#hooks;
|
|
@@ -287,7 +340,8 @@ var RateLimitQueue = class {
|
|
|
287
340
|
*/
|
|
288
341
|
constructor(limit, hooks, sleep) {
|
|
289
342
|
this.#intervalMs = 1e3 / limit.maxPerSecond;
|
|
290
|
-
|
|
343
|
+
const burstCapacity = limit.burstCapacity ?? Math.max(1, limit.maxPerSecond);
|
|
344
|
+
this.#maxBucketLevel = burstCapacity * this.#intervalMs;
|
|
291
345
|
this.#hooks = hooks;
|
|
292
346
|
this.#sleep = sleep;
|
|
293
347
|
}
|
|
@@ -300,7 +354,7 @@ var RateLimitQueue = class {
|
|
|
300
354
|
* @param task - The request to run once a token is available.
|
|
301
355
|
* @returns The value produced by `task`.
|
|
302
356
|
*/
|
|
303
|
-
async
|
|
357
|
+
async acquireAsync(task) {
|
|
304
358
|
const myTurn = this.#chain.then(async () => this.#waitForToken());
|
|
305
359
|
this.#chain = myTurn;
|
|
306
360
|
await myTurn;
|
|
@@ -330,7 +384,7 @@ var RateLimitQueue = class {
|
|
|
330
384
|
* @param promise - The promise to wrap.
|
|
331
385
|
* @returns A Result containing the resolved value or the rejection error.
|
|
332
386
|
*/
|
|
333
|
-
async function
|
|
387
|
+
async function tryCatchAsync(promise) {
|
|
334
388
|
try {
|
|
335
389
|
return {
|
|
336
390
|
data: await promise,
|
|
@@ -352,9 +406,9 @@ const DIAGNOSTIC_HEADER_ALLOWLIST = new Set([
|
|
|
352
406
|
"x-request-id"
|
|
353
407
|
]);
|
|
354
408
|
const DIAGNOSTIC_HEADER_PREFIX = "x-roblox-";
|
|
355
|
-
const
|
|
356
|
-
const
|
|
357
|
-
const TAG_PATTERN = /<[
|
|
409
|
+
const TITLE_OPEN_PATTERN = /<title[^>]*>/i;
|
|
410
|
+
const H1_OPEN_PATTERN = /<h1[^>]*>/i;
|
|
411
|
+
const TAG_PATTERN = /<[^<>]*>/g;
|
|
358
412
|
const WHITESPACE_PATTERN = /\s+/g;
|
|
359
413
|
/**
|
|
360
414
|
* Extracts a one-line human summary from an HTML gateway error page, or returns
|
|
@@ -373,7 +427,13 @@ const WHITESPACE_PATTERN = /\s+/g;
|
|
|
373
427
|
*/
|
|
374
428
|
function extractGatewaySummary(contentType, rawText) {
|
|
375
429
|
if (!isHtmlBody(contentType, rawText)) return;
|
|
376
|
-
return firstTagText(rawText,
|
|
430
|
+
return firstTagText(rawText, {
|
|
431
|
+
close: "</title>",
|
|
432
|
+
open: TITLE_OPEN_PATTERN
|
|
433
|
+
}) ?? firstTagText(rawText, {
|
|
434
|
+
close: "</h1>",
|
|
435
|
+
open: H1_OPEN_PATTERN
|
|
436
|
+
});
|
|
377
437
|
}
|
|
378
438
|
/**
|
|
379
439
|
* Filters a lowercased header record down to the diagnostic allowlist: a few
|
|
@@ -388,10 +448,13 @@ function pickDiagnosticHeaders(headers) {
|
|
|
388
448
|
for (const [name, value] of Object.entries(headers)) if (DIAGNOSTIC_HEADER_ALLOWLIST.has(name) || name.startsWith(DIAGNOSTIC_HEADER_PREFIX)) picked[name] = value;
|
|
389
449
|
return picked;
|
|
390
450
|
}
|
|
391
|
-
function firstTagText(html,
|
|
392
|
-
const
|
|
393
|
-
if (
|
|
394
|
-
const
|
|
451
|
+
function firstTagText(html, tag) {
|
|
452
|
+
const open = tag.open.exec(html);
|
|
453
|
+
if (open === null) return;
|
|
454
|
+
const start = open.index + open[0].length;
|
|
455
|
+
const end = html.toLowerCase().indexOf(tag.close, start);
|
|
456
|
+
if (end === -1) return;
|
|
457
|
+
const text = html.slice(start, end).replace(TAG_PATTERN, " ").replace(WHITESPACE_PATTERN, " ").trim();
|
|
395
458
|
return text === "" ? void 0 : text;
|
|
396
459
|
}
|
|
397
460
|
function isHtmlBody(contentType, rawText) {
|
|
@@ -411,6 +474,18 @@ function isHtmlBody(contentType, rawText) {
|
|
|
411
474
|
*/
|
|
412
475
|
const GLOBAL_DISPATCHER_KEYS = Object.freeze(["undici.globalDispatcher.2", "undici.globalDispatcher.1"]);
|
|
413
476
|
/**
|
|
477
|
+
* Narrow a value read off the global dispatcher to something
|
|
478
|
+
* `Reflect.construct` accepts. Exported so the narrowing is unit-testable: at
|
|
479
|
+
* the call site every rejected shape funnels into the same `undefined`, which
|
|
480
|
+
* makes the branch unobservable from `createHttp1Dispatcher` alone.
|
|
481
|
+
*
|
|
482
|
+
* @param value - The candidate `constructor` read off the global dispatcher.
|
|
483
|
+
* @returns Whether the value can be constructed.
|
|
484
|
+
*/
|
|
485
|
+
function isAgentConstructor(value) {
|
|
486
|
+
return typeof value === "function";
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
414
489
|
* Builds a request dispatcher that negotiates HTTP/1.1 only, by reusing the
|
|
415
490
|
* class of the runtime's own global dispatcher.
|
|
416
491
|
*
|
|
@@ -458,6 +533,7 @@ function createHttp1Dispatcher(scope = globalThis) {
|
|
|
458
533
|
function constructHttp1(agent) {
|
|
459
534
|
try {
|
|
460
535
|
const agentClass = Reflect.get(agent, "constructor");
|
|
536
|
+
if (!isAgentConstructor(agentClass)) return;
|
|
461
537
|
const dispatcher = Reflect.construct(agentClass, [{ allowH2: false }]);
|
|
462
538
|
return typeof Reflect.get(dispatcher, "dispatch") === "function" ? dispatcher : void 0;
|
|
463
539
|
} catch {
|
|
@@ -527,11 +603,11 @@ function extractErrorMessage(body) {
|
|
|
527
603
|
return extractLegacyMessage(body);
|
|
528
604
|
}
|
|
529
605
|
/**
|
|
530
|
-
* Parses the `x-ratelimit-reset` header value into seconds. On a 429 the
|
|
531
|
-
* is a comma-separated list of per-window reset times (e.g. `"22, 0"`,
|
|
532
|
-
* per rate-limit window); the largest value is the longest-resetting
|
|
533
|
-
* the only safe wait that won't retry into a still-exhausted
|
|
534
|
-
* value is treated as a one-element list.
|
|
606
|
+
* Parses the `x-ratelimit-reset` header value into seconds. On a 429 the
|
|
607
|
+
* header is a comma-separated list of per-window reset times (e.g. `"22, 0"`,
|
|
608
|
+
* one entry per rate-limit window); the largest value is the longest-resetting
|
|
609
|
+
* window and the only safe wait that won't retry into a still-exhausted
|
|
610
|
+
* window. A single value is treated as a one-element list.
|
|
535
611
|
*
|
|
536
612
|
* @param headerValue - The raw header value, or `undefined` if missing.
|
|
537
613
|
* @returns The number of seconds to wait, or 0 if missing/invalid.
|
|
@@ -582,8 +658,7 @@ function buildFetchOptions(request, config) {
|
|
|
582
658
|
* depend on wall-clock time or on the runtime's global dispatcher.
|
|
583
659
|
* @returns An HttpClient that classifies responses into typed Results.
|
|
584
660
|
*/
|
|
585
|
-
function createFetchHttpClient(fetchFunc =
|
|
586
|
-
const { createDispatcher = createHttp1Dispatcher, now = Date.now } = seams;
|
|
661
|
+
function createFetchHttpClient(fetchFunc = fetch, { createDispatcher = createHttp1Dispatcher, now = Date.now } = {}) {
|
|
587
662
|
const dispatcherFor = createUploadDispatcherCache(createDispatcher);
|
|
588
663
|
return { async request(httpRequest, config) {
|
|
589
664
|
const url = buildUrl(httpRequest, config);
|
|
@@ -593,7 +668,9 @@ function createFetchHttpClient(fetchFunc = globalThis.fetch, seams = {}) {
|
|
|
593
668
|
method: httpRequest.method,
|
|
594
669
|
url
|
|
595
670
|
};
|
|
596
|
-
const { elapsedMs, fetchResult } = await
|
|
671
|
+
const { elapsedMs, fetchResult } = await timedFetchAsync(now, async () => {
|
|
672
|
+
return fetchFunc(url, options);
|
|
673
|
+
});
|
|
597
674
|
if (!fetchResult.success) return {
|
|
598
675
|
err: networkError(fetchResult.err, target),
|
|
599
676
|
success: false
|
|
@@ -603,7 +680,7 @@ function createFetchHttpClient(fetchFunc = globalThis.fetch, seams = {}) {
|
|
|
603
680
|
method: target.method,
|
|
604
681
|
url: target.url
|
|
605
682
|
};
|
|
606
|
-
const classified = await
|
|
683
|
+
const classified = await tryCatchAsync(classifyResponseAsync(fetchResult.data, context));
|
|
607
684
|
if (!classified.success) return {
|
|
608
685
|
err: networkError(classified.err, target),
|
|
609
686
|
success: false
|
|
@@ -679,9 +756,9 @@ function createUploadDispatcherCache(createDispatcher) {
|
|
|
679
756
|
* @param send - A thunk that issues the fetch.
|
|
680
757
|
* @returns The fetch Result and the elapsed milliseconds.
|
|
681
758
|
*/
|
|
682
|
-
async function
|
|
759
|
+
async function timedFetchAsync(now, send) {
|
|
683
760
|
const start = now();
|
|
684
|
-
const fetchResult = await
|
|
761
|
+
const fetchResult = await tryCatchAsync(send());
|
|
685
762
|
return {
|
|
686
763
|
elapsedMs: Math.max(0, now() - start),
|
|
687
764
|
fetchResult
|
|
@@ -694,8 +771,7 @@ function networkError(cause, target) {
|
|
|
694
771
|
url: target.url
|
|
695
772
|
});
|
|
696
773
|
}
|
|
697
|
-
function formatApiErrorMessage(
|
|
698
|
-
const { code, message, status } = parts;
|
|
774
|
+
function formatApiErrorMessage({ code, message, status }) {
|
|
699
775
|
const base = `HTTP ${status}`;
|
|
700
776
|
if (message === void 0 && code === void 0) return base;
|
|
701
777
|
if (message === void 0) return `${base} (code ${code})`;
|
|
@@ -707,7 +783,7 @@ function formatApiErrorMessage(parts) {
|
|
|
707
783
|
* it parsed, otherwise the raw text truncated to {@link MAX_DETAIL_LENGTH}.
|
|
708
784
|
*
|
|
709
785
|
* @param text - The raw response body text.
|
|
710
|
-
* @param parsed - The best-effort parse result from {@link
|
|
786
|
+
* @param parsed - The best-effort parse result from {@link readResponseBodyAsync}.
|
|
711
787
|
* @returns The parsed body, or the truncated raw text on a parse failure.
|
|
712
788
|
*/
|
|
713
789
|
function bodyDetail(text, parsed) {
|
|
@@ -743,7 +819,8 @@ function createApiError(args) {
|
|
|
743
819
|
}
|
|
744
820
|
/**
|
|
745
821
|
* Parses response text as JSON, returning the underlying `SyntaxError` on
|
|
746
|
-
* failure rather than throwing. The synchronous sibling of {@link
|
|
822
|
+
* failure rather than throwing. The synchronous sibling of {@link
|
|
823
|
+
* tryCatchAsync}.
|
|
747
824
|
*
|
|
748
825
|
* @param text - The raw response body text.
|
|
749
826
|
* @returns A Result wrapping the parsed value, or the parse error.
|
|
@@ -771,7 +848,7 @@ function parseJson(text) {
|
|
|
771
848
|
* @param response - The Response whose body to read.
|
|
772
849
|
* @returns The parse result and the raw text.
|
|
773
850
|
*/
|
|
774
|
-
async function
|
|
851
|
+
async function readResponseBodyAsync(response) {
|
|
775
852
|
const text = await response.text();
|
|
776
853
|
return {
|
|
777
854
|
parsed: text === "" ? {
|
|
@@ -781,12 +858,14 @@ async function readResponseBody(response) {
|
|
|
781
858
|
text
|
|
782
859
|
};
|
|
783
860
|
}
|
|
784
|
-
async function
|
|
861
|
+
async function createRateLimitErrorAsync(response) {
|
|
785
862
|
const headers = headersToRecord(response.headers);
|
|
786
|
-
const { parsed, text } = await
|
|
863
|
+
const { parsed, text } = await readResponseBodyAsync(response);
|
|
787
864
|
return new RateLimitError("Rate limited", {
|
|
788
865
|
details: bodyDetail(text, parsed),
|
|
789
|
-
remaining: reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) =>
|
|
866
|
+
remaining: reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
|
|
867
|
+
return Math.min(a, b);
|
|
868
|
+
}),
|
|
790
869
|
retryAfterSeconds: parseRetryAfterSeconds(headers["x-ratelimit-reset"]),
|
|
791
870
|
statusCode: response.status
|
|
792
871
|
});
|
|
@@ -820,12 +899,12 @@ function parseFailureError({ cause, response, text }) {
|
|
|
820
899
|
* onto any {@link ApiError} built for an error response.
|
|
821
900
|
* @returns A Result containing an HttpResponse on success or an OpenCloudError on failure.
|
|
822
901
|
*/
|
|
823
|
-
async function
|
|
902
|
+
async function classifyResponseAsync(response, context) {
|
|
824
903
|
if (response.status === 429) return {
|
|
825
|
-
err: await
|
|
904
|
+
err: await createRateLimitErrorAsync(response),
|
|
826
905
|
success: false
|
|
827
906
|
};
|
|
828
|
-
const { parsed, text } = await
|
|
907
|
+
const { parsed, text } = await readResponseBodyAsync(response);
|
|
829
908
|
if (response.status >= 300) return {
|
|
830
909
|
err: createApiError({
|
|
831
910
|
context,
|
|
@@ -915,7 +994,7 @@ const CLIENT_DEFAULTS = Object.freeze({
|
|
|
915
994
|
* the frozen client config, observability hooks, injected HTTP client and
|
|
916
995
|
* sleep, and the per-effective-key rate-limit queue registry. Resource
|
|
917
996
|
* classes compose one instance and dispatch every public method through
|
|
918
|
-
* {@link ResourceClient.
|
|
997
|
+
* {@link ResourceClient.executeAsync} with a per-method {@link ResourceMethodSpec}.
|
|
919
998
|
* Not exported from any package subpath; reachable only via sibling
|
|
920
999
|
* `src/resources/**` modules in this package.
|
|
921
1000
|
*/
|
|
@@ -934,8 +1013,7 @@ var ResourceClient = class {
|
|
|
934
1013
|
* @param options - Client-level configuration including the API key
|
|
935
1014
|
* and optional construction-time test seams.
|
|
936
1015
|
*/
|
|
937
|
-
constructor(
|
|
938
|
-
const { apiKey, hooks, httpClient, sleep, ...overrides } = options;
|
|
1016
|
+
constructor({ apiKey, hooks, httpClient, sleep, ...overrides }) {
|
|
939
1017
|
const resolved = resolveDependencies({
|
|
940
1018
|
httpClient,
|
|
941
1019
|
sleep
|
|
@@ -962,8 +1040,7 @@ var ResourceClient = class {
|
|
|
962
1040
|
* @returns The parsed success payload or the {@link OpenCloudError} that
|
|
963
1041
|
* caused the request to fail. Never throws.
|
|
964
1042
|
*/
|
|
965
|
-
async
|
|
966
|
-
const { options, parameters, spec } = call;
|
|
1043
|
+
async executeAsync({ options, parameters, spec }) {
|
|
967
1044
|
const merged = mergeConfig(this.#config, {
|
|
968
1045
|
methodDefaults: spec.methodDefaults,
|
|
969
1046
|
methodKind: spec.methodKind,
|
|
@@ -976,8 +1053,8 @@ var ResourceClient = class {
|
|
|
976
1053
|
options,
|
|
977
1054
|
request: requestResult.data
|
|
978
1055
|
});
|
|
979
|
-
const httpResult = await this.#getQueue(merged.apiKey, spec.operationLimit).
|
|
980
|
-
return
|
|
1056
|
+
const httpResult = await this.#getQueue(merged.apiKey, spec.operationLimit).acquireAsync(async () => {
|
|
1057
|
+
return executeWithRetryAsync(requestResult.data, {
|
|
981
1058
|
config: merged,
|
|
982
1059
|
hooks: this.#hooks,
|
|
983
1060
|
send: this.#gatedSend(merged.apiKey, requestConfig),
|
|
@@ -1006,11 +1083,11 @@ var ResourceClient = class {
|
|
|
1006
1083
|
*
|
|
1007
1084
|
* @param apiKey - The effective API key to gate on.
|
|
1008
1085
|
* @param requestConfig - The resolved per-request transport config.
|
|
1009
|
-
* @returns A send callback for {@link
|
|
1086
|
+
* @returns A send callback for {@link executeWithRetryAsync}.
|
|
1010
1087
|
*/
|
|
1011
1088
|
#gatedSend(apiKey, requestConfig) {
|
|
1012
1089
|
return async (toSend) => {
|
|
1013
|
-
await this.#budgets.
|
|
1090
|
+
await this.#budgets.gateAsync(apiKey);
|
|
1014
1091
|
const sendResult = await this.#httpClient.request(toSend, requestConfig);
|
|
1015
1092
|
this.#budgets.observe(apiKey, rateLimitSampleFromResult(sendResult));
|
|
1016
1093
|
return sendResult;
|
|
@@ -1036,8 +1113,7 @@ var ResourceClient = class {
|
|
|
1036
1113
|
* @returns The config to hand to the transport, with `timeout` omitted when
|
|
1037
1114
|
* no client-side deadline should apply.
|
|
1038
1115
|
*/
|
|
1039
|
-
function buildRequestConfig(
|
|
1040
|
-
const { merged, options, request } = inputs;
|
|
1116
|
+
function buildRequestConfig({ merged, options, request }) {
|
|
1041
1117
|
const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
|
|
1042
1118
|
return {
|
|
1043
1119
|
apiKey: merged.apiKey,
|
|
@@ -1060,6 +1136,6 @@ function enrichPermissionError(err, spec) {
|
|
|
1060
1136
|
});
|
|
1061
1137
|
}
|
|
1062
1138
|
//#endregion
|
|
1063
|
-
export {
|
|
1139
|
+
export { isRecord as a, toJsonDetails as i, okRequest as n, isDateTimeString as o, parseEmptyResponse as r, ResourceClient as t };
|
|
1064
1140
|
|
|
1065
|
-
//# sourceMappingURL=resource-client-
|
|
1141
|
+
//# sourceMappingURL=resource-client-rQ9bBn4L.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-client-rQ9bBn4L.mjs","names":["#window","#lastAllowedAt","#chains","#sleep","#trackers","#gateOnce","#tracker","#hooks","#intervalMs","#maxBucketLevel","#sleep","#chain","#waitForToken","#lastCheck","#bucketLevel","#budgets","#config","#hooks","#httpClient","#queues","#sleep","#getQueue","#gatedSend"],"sources":["../src/internal/utils/is-date-time-string.ts","../src/internal/utils/is-record.ts","../src/internal/utils/to-json-details.ts","../src/internal/http/budget-tracker.ts","../src/internal/http/budget-gate.ts","../src/internal/http/execute.ts","../src/internal/http/rate-limit-sample.ts","../src/internal/http/rate-limit-observation.ts","../src/internal/http/rate-limit-queue.ts","../src/internal/utils/try-catch.ts","../src/internal/http/diagnostics.ts","../src/internal/http/http1-dispatcher.ts","../src/internal/http/upload-request.ts","../src/internal/http/fetch-client.ts","../src/internal/http/resolve-dependencies.ts","../src/internal/resource-client.ts"],"sourcesContent":["/**\n * Narrows `value` to a string that parses to a real {@link Date} via the\n * `Date(string)` constructor. Used by resource parsers to gate\n * `format: date-time` wire fields before handing them to `new Date(...)`,\n * which silently produces an `Invalid Date` for invalid input.\n *\n * @param value - The unknown wire value to validate.\n * @returns `true` when `value` is a string and `new Date(value).getTime()`\n * is not `NaN`.\n */\nexport function isDateTimeString(value: unknown): value is string {\n\tif (typeof value !== \"string\") {\n\t\treturn false;\n\t}\n\n\tconst parsed = new Date(value);\n\treturn !Number.isNaN(parsed.getTime());\n}\n","/**\n * Narrows `value` to a plain JSON-style record. Excludes arrays, class\n * instances, primitives, and `null`/`undefined`. Used by resource\n * parsers to gate property access on wire bodies whose shape isn't\n * known at compile time.\n *\n * @param value - The unknown value to narrow.\n * @returns `true` when `value` is a plain `[object Object]`.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn Object.prototype.toString.call(value) === \"[object Object]\";\n}\n","import { isRecord } from \"./is-record.ts\";\n\n/**\n * Narrows an untyped response body to the `JSONValue` accepted by\n * `ApiError.details`. `HttpResponse.body` is `unknown` because a transport may\n * hand back anything, but only a JSON graph is safe to retain on an error for\n * diagnostics. Anything else — functions, symbols, bigints, class instances,\n * or a cyclic graph — is dropped rather than asserted through.\n *\n * @param value - The parsed response body, or `undefined` for an empty body.\n * @returns The value as a `JSONValue`, or `undefined` when it is absent or not\n * JSON-representable.\n */\nexport function toJsonDetails(value: unknown): JSONValue | undefined {\n\treturn asJsonValue(value, new Set());\n}\n\nfunction asJsonValue(value: unknown, seen: Set<object>): JSONValue | undefined {\n\tif (value === null) {\n\t\t// eslint-disable-next-line unicorn/no-null -- JSON null is a JSONValue; the repo's undefined-only rule stops at this wire boundary\n\t\treturn null;\n\t}\n\n\tif (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n\t\treturn value;\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn asJsonArray(value, seen);\n\t}\n\n\tif (isRecord(value)) {\n\t\treturn asJsonObject(value, seen);\n\t}\n\n\treturn undefined;\n}\n\nfunction asJsonArray(value: ReadonlyArray<unknown>, seen: Set<object>): JSONValue | undefined {\n\tif (seen.has(value)) {\n\t\treturn undefined;\n\t}\n\n\tseen.add(value);\n\tconst items: Array<JSONValue> = [];\n\tfor (const item of value) {\n\t\tconst converted = asJsonValue(item, seen);\n\t\tif (converted === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\titems.push(converted);\n\t}\n\n\tseen.delete(value);\n\treturn items;\n}\n\nfunction asJsonObject(value: Record<string, unknown>, seen: Set<object>): JSONValue | undefined {\n\tif (seen.has(value)) {\n\t\treturn undefined;\n\t}\n\n\tseen.add(value);\n\tconst entries: Array<[string, JSONValue]> = [];\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tconst converted = asJsonValue(item, seen);\n\t\tif (converted === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tentries.push([key, converted]);\n\t}\n\n\tseen.delete(value);\n\treturn Object.fromEntries(entries);\n}\n","import type { RateLimitSample } from \"./rate-limit-sample.ts\";\n\nconst MS_PER_SECOND = 1000;\n\n/** Live window state for one scope: budget left and when it resets. */\ninterface WindowState {\n\t/** Best estimate of requests still allowed before the window resets. */\n\treadonly predictedRemaining: number;\n\t/** Absolute time (ms) the window resets to full. */\n\treadonly resetAt: number;\n}\n\n/**\n * Tracks the live rate-limit budget for a single scope. Primed by `observe`\n * from response headers and drawn down by `reserve` as requests leave, so\n * `waitMs` can pace requests across the window.\n *\n * Pacing has two regimes. While budget remains, requests are spread evenly over\n * the time left in the window (`timeLeft / remaining`), so a burst does not\n * spend the whole window's budget up front and then stall. Once the budget is\n * spent, requests hold until the window resets. Budget and reset time move\n * together as one window, so the tracker is either unprimed or fully primed,\n * never half-known.\n */\nexport class BudgetTracker {\n\t/** Time (ms) the most recent request was allowed out, for spacing. */\n\t#lastAllowedAt: number | undefined = undefined;\n\t#window: undefined | WindowState = undefined;\n\n\t/**\n\t * Folds a fresh server reading in, replacing any prior window. The latest\n\t * reading wins: observe time is monotonic, so the most recently resolved\n\t * response is the best current estimate. The spacing reference is left\n\t * untouched so a window refresh does not reset pacing mid-stream.\n\t *\n\t * @param sample - Parsed `remaining`/`resetSeconds` from a response.\n\t * @param now - The current time in ms.\n\t */\n\tpublic observe(sample: RateLimitSample, now: number): void {\n\t\tthis.#window = {\n\t\t\tpredictedRemaining: sample.remaining,\n\t\t\tresetAt: now + sample.resetSeconds * MS_PER_SECOND,\n\t\t};\n\t}\n\n\t/**\n\t * Accounts for one request leaving at `now`: records the spacing reference\n\t * and decrements the prediction. A no-op on the prediction while unprimed.\n\t *\n\t * @param now - The time the request was allowed out, in ms.\n\t */\n\tpublic reserve(now: number): void {\n\t\tthis.#lastAllowedAt = now;\n\t\tif (this.#window !== undefined) {\n\t\t\tthis.#window = {\n\t\t\t\t...this.#window,\n\t\t\t\tpredictedRemaining: this.#window.predictedRemaining - 1,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Milliseconds to wait before the next request is allowed.\n\t *\n\t * @param now - The current time in ms.\n\t * @returns `0` when a request may go now (unprimed, or the first paced send);\n\t * the time until reset when the budget is spent; otherwise the time until\n\t * this request's evenly-spaced slot.\n\t */\n\tpublic waitMs(now: number): number {\n\t\tif (this.#window === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst { predictedRemaining, resetAt } = this.#window;\n\t\tif (predictedRemaining <= 0) {\n\t\t\treturn Math.max(0, resetAt - now);\n\t\t}\n\n\t\tif (this.#lastAllowedAt === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst interval = (resetAt - now) / predictedRemaining;\n\t\treturn Math.max(0, this.#lastAllowedAt + interval - now);\n\t}\n}\n","import type { SleepFunc } from \"../utils/sleep.ts\";\nimport { BudgetTracker } from \"./budget-tracker.ts\";\nimport type { RateLimitSample } from \"./rate-limit-sample.ts\";\n\n/**\n * Header-primed rate-limit gate shared across a client. Holds one\n * {@link BudgetTracker} per API key, since the tightest Roblox window is the\n * per-key one shared across every operation. Before each request the caller\n * gates on the request's key (sleeping if its budget is spent), and after each\n * response folds the parsed sample back in, so a sibling operation on the same\n * key can head off a 429 the static per-operation token bucket cannot foresee.\n * A per-operation tracker is deliberately not kept: every operation reports the\n * same most-constrained `remaining`, so a per-key tracker (drawn down by all\n * operations) is always the binding constraint.\n *\n * Gating is serialized per scope through a promise chain so concurrent\n * requests on one key cannot read the same budget and reserve the same slot;\n * each waits for the prior gate's reserve before computing its own.\n */\nexport class BudgetGate {\n\treadonly #chains = new Map<string, Promise<void>>();\n\treadonly #sleep: SleepFunc;\n\treadonly #trackers = new Map<string, BudgetTracker>();\n\n\t/**\n\t * Creates a gate bound to an injectable sleep.\n\t *\n\t * @param sleep - Injectable sleep (tests pass a fake clock).\n\t */\n\tconstructor(sleep: SleepFunc) {\n\t\tthis.#sleep = sleep;\n\t}\n\n\t/**\n\t * Holds until the scope's budget permits a send, then reserves one slot.\n\t * Runs after the prior gate on the same scope settles, whether it resolved\n\t * or rejected, so one failed attempt cannot poison later gates on the key.\n\t *\n\t * @param scope - The scope key to gate on (the effective API key).\n\t */\n\tpublic async gateAsync(scope: string): Promise<void> {\n\t\tconst previous = this.#chains.get(scope) ?? Promise.resolve();\n\t\tconst runGateAsync = async (): Promise<void> => this.#gateOnce(scope);\n\t\t// The gate runs whether the previous link settled or rejected, so a\n\t\t// failed wait never strands the scope's chain.\n\t\t// Both handlers are the same function on purpose: this gate must run\n\t\t// whether the previous link settled or rejected, so a failed wait never\n\t\t// strands the scope's queue. `.then(...).catch(...)` would instead run\n\t\t// the gate a second time when the gate itself rejects.\n\t\t// eslint-disable-next-line unicorn/prefer-then-catch -- see above\n\t\tconst mine = previous.then(runGateAsync, runGateAsync);\n\t\tthis.#chains.set(scope, mine);\n\t\tawait mine;\n\t}\n\n\t/**\n\t * Folds a response's parsed budget back onto the scope. A `undefined`\n\t * sample (headers absent or non-numeric) is ignored, leaving the scope on\n\t * static pacing.\n\t *\n\t * @param scope - The same scope key passed to {@link gateAsync}.\n\t * @param sample - Parsed sample, or `undefined` when none was reported.\n\t */\n\tpublic observe(scope: string, sample: RateLimitSample | undefined): void {\n\t\tif (sample === undefined) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#tracker(scope).observe(sample, Date.now());\n\t}\n\n\tasync #gateOnce(scope: string): Promise<void> {\n\t\tconst tracker = this.#tracker(scope);\n\t\tconst waitMs = tracker.waitMs(Date.now());\n\t\tif (waitMs > 0) {\n\t\t\tawait this.#sleep(waitMs);\n\t\t}\n\n\t\ttracker.reserve(Date.now());\n\t}\n\n\t#tracker(scope: string): BudgetTracker {\n\t\tconst existing = this.#trackers.get(scope);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst tracker = new BudgetTracker();\n\t\tthis.#trackers.set(scope, tracker);\n\t\treturn tracker;\n\t}\n}\n","import type { OpenCloudError } from \"../../errors/base.ts\";\nimport type { Result } from \"../../types.ts\";\nimport type { SleepFunc } from \"../utils/sleep.ts\";\nimport { computeRetryWaitMs, type RetryResolvable, shouldRetry } from \"./retry.ts\";\nimport type { HttpRequest, HttpResponse, OpenCloudHooks } from \"./types.ts\";\n\n/** A transport callback: takes a request, returns a classified Result. */\ntype SendFunc = (request: HttpRequest) => Promise<Result<HttpResponse, OpenCloudError>>;\n\n/**\n * Inputs to {@link executeWithRetryAsync} bundled as an options object to keep\n * the function signature narrow.\n */\ninterface ExecuteOptions {\n\t/** Fully-resolved retry config (post-merge). */\n\treadonly config: RetryResolvable;\n\t/** Client-level observability hooks. */\n\treadonly hooks: OpenCloudHooks;\n\t/** Transport callback. May be pre-wrapped by a rate-limit queue. */\n\treadonly send: SendFunc;\n\t/** Injectable sleep (tests pass a fake). */\n\treadonly sleep: SleepFunc;\n}\n\n/**\n * Retry-aware orchestration loop. Coordinates a single logical request,\n * looping over `options.send` until it succeeds, the error is non-retryable,\n * or `options.config.maxRetries` is exhausted. Fires observability hooks\n * at each transition. Domain- and queue-agnostic: `send` may be any\n * callback, including one wrapped by a rate-limit queue.\n *\n * @param request - The immutable request to send.\n * @param options - The transport callback, resolved config, hooks, and sleep.\n * @returns The first success, or the final error after retries are exhausted.\n */\nexport async function executeWithRetryAsync(\n\trequest: HttpRequest,\n\t{ config, hooks, send, sleep }: ExecuteOptions,\n): Promise<Result<HttpResponse, OpenCloudError>> {\n\tasync function attemptAsync(): Promise<Result<HttpResponse, OpenCloudError>> {\n\t\thooks.onRequest?.(request);\n\t\treturn send(request);\n\t}\n\n\tlet result = await attemptAsync();\n\n\tfor (let retry = 0; retry < config.maxRetries; retry++) {\n\t\tif (result.success || !shouldRetry(result.err, config)) {\n\t\t\treturn result;\n\t\t}\n\n\t\tconst { err } = result;\n\t\thooks.onRetry?.(retry + 1, err);\n\t\tconst waitMs = computeRetryWaitMs(err, { attempt: retry, retryDelay: config.retryDelay });\n\t\thooks.onRateLimit?.(waitMs);\n\t\tawait sleep(waitMs);\n\n\t\tresult = await attemptAsync();\n\t}\n\n\treturn result;\n}\n","/**\n * A point-in-time rate-limit budget reading parsed from Roblox Open Cloud\n * response headers. Both fields are non-negative integers.\n */\nexport interface RateLimitSample {\n\t/**\n\t * Requests still allowed in the current window (the most-constrained one).\n\t */\n\treadonly remaining: number;\n\t/** Seconds until the most-constrained window resets to full. */\n\treadonly resetSeconds: number;\n}\n\n/**\n * Reduces a comma-separated rate-limit header value (e.g. `\"0, 70000\"`) to a\n * single non-negative integer via `combine`. Tokens are trimmed; blank and\n * non-finite tokens (`\"\"`, `\"Infinity\"`, `\"abc\"`) are dropped so a stray value\n * cannot corrupt the result. Returns `undefined` when the header is absent or\n * has no finite tokens.\n *\n * @param headerValue - The raw header value, or `undefined` if missing.\n * @param combine - Pairwise reducer, `Math.min` for remaining, `Math.max` for reset.\n * @returns The reduced, floored, clamped value, or `undefined`.\n */\nexport function reduceRateLimitTokens(\n\theaderValue: string | undefined,\n\tcombine: (a: number, b: number) => number,\n): number | undefined {\n\tif (headerValue === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst tokens = headerValue\n\t\t.split(\",\")\n\t\t.map((part) => part.trim())\n\t\t.filter((part) => part !== \"\")\n\t\t.map((part) => Number(part))\n\t\t.filter((value) => Number.isFinite(value));\n\tif (tokens.length === 0) {\n\t\treturn undefined;\n\t}\n\n\treturn Math.max(0, Math.floor(tokens.reduce(combine)));\n}\n\n/**\n * Parses the `x-ratelimit-remaining` and `x-ratelimit-reset` response headers\n * into a {@link RateLimitSample}. Each header may carry a comma-separated list\n * of per-window values; `remaining` takes the smallest (most constrained) and\n * `resetSeconds` takes the largest (longest wait), symmetric to how a 429's\n * retry delay is reduced. Returns `undefined` when either header is missing or\n * has no finite numeric tokens, so a caller can fall back to static pacing.\n *\n * @param headers - Response headers with lowercased keys.\n * @returns The parsed sample, or `undefined` when the budget cannot be read.\n */\nexport function parseRateLimitHeaders(\n\theaders: Readonly<Record<string, string>>,\n): RateLimitSample | undefined {\n\tconst remaining = reduceRateLimitTokens(headers[\"x-ratelimit-remaining\"], (a, b) => {\n\t\treturn Math.min(a, b);\n\t});\n\tconst resetSeconds = reduceRateLimitTokens(headers[\"x-ratelimit-reset\"], (a, b) => {\n\t\treturn Math.max(a, b);\n\t});\n\tif (remaining === undefined || resetSeconds === undefined) {\n\t\treturn undefined;\n\t}\n\n\treturn { remaining, resetSeconds };\n}\n","import type { OpenCloudError } from \"../../errors/base.ts\";\nimport { RateLimitError } from \"../../errors/rate-limit.ts\";\nimport type { Result } from \"../../types.ts\";\nimport type { RateLimitSample } from \"./rate-limit-sample.ts\";\nimport { parseRateLimitHeaders } from \"./rate-limit-sample.ts\";\nimport type { HttpResponse } from \"./types.ts\";\n\n/**\n * Extracts a {@link RateLimitSample} from a transport result so the budget gate\n * can be fed from every attempt. A 2xx carries the budget in its headers; a 429\n * carries it on the {@link RateLimitError} (the raw headers are dropped before\n * this point). Any other error, or a response that reported no budget, yields\n * `undefined` and leaves the gate on static pacing.\n *\n * @param result - The classified transport result for one attempt.\n * @returns The parsed sample, or `undefined` when none was reported.\n */\nexport function rateLimitSampleFromResult(\n\tresult: Result<HttpResponse, OpenCloudError>,\n): RateLimitSample | undefined {\n\tif (result.success) {\n\t\treturn parseRateLimitHeaders(result.data.headers);\n\t}\n\n\tconst { err } = result;\n\tif (err instanceof RateLimitError && err.remaining !== undefined) {\n\t\treturn { remaining: err.remaining, resetSeconds: err.retryAfterSeconds };\n\t}\n\n\treturn undefined;\n}\n","import type { SleepFunc } from \"../utils/sleep.ts\";\nimport type { OpenCloudHooks } from \"./types.ts\";\n\n/**\n * Identifies and bounds a single Roblox Open Cloud operation for rate\n * limiting, e.g. `{ operationKey: \"game-passes.create\", maxPerSecond: 5 }`.\n */\nexport interface OperationLimit {\n\t/**\n\t * How many requests may be issued back to back before pacing begins,\n\t * as a whole number of requests. Defaults to `max(1, maxPerSecond)`,\n\t * which leaves operations at or above 1/s paced exactly as their\n\t * sustained rate allows while still granting a slower operation one\n\t * request after it has idled. Set this to the allowance the schema\n\t * documents (e.g. 5 per minute) to grant the burst the server permits.\n\t */\n\treadonly burstCapacity?: number;\n\t/** Maximum sustained request rate in requests per second. */\n\treadonly maxPerSecond: number;\n\t/**\n\t * Stable identifier for the operation (e.g. \"game-passes.create\"). Not\n\t * consumed by the queue itself; callers use it to key per-operation\n\t * queues in a registry (see GamePassesClient).\n\t */\n\treadonly operationKey: string;\n}\n\n/**\n * Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every\n * call to `acquire` consumes one token; when the bucket is empty the call\n * waits until a token regenerates before invoking the task. Tokens refill at\n * `maxPerSecond` per second, up to the operation's `burstCapacity`.\n *\n * Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`\n * advances by `waitMs` after every sleep so the algorithm stays correct\n * whether or not the injected sleep moves `Date.now()` forward. `#bucketLevel`\n * and `#maxBucketLevel` are both ms of drain debt, so the ceiling is the burst\n * expressed in that unit: `burstCapacity` refill intervals. Deriving it any\n * other way (notably `maxPerSecond * intervalMs`, whose units cancel to a\n * constant 1000) starves every operation slower than one request per second.\n */\nexport class RateLimitQueue {\n\treadonly #hooks: OpenCloudHooks;\n\treadonly #intervalMs: number;\n\treadonly #maxBucketLevel: number;\n\treadonly #sleep: SleepFunc;\n\n\t#bucketLevel = 0;\n\t#chain: Promise<void> = Promise.resolve();\n\t#lastCheck: number = Date.now();\n\n\t/**\n\t * Creates a rate-limit queue bound to a single operation.\n\t *\n\t * @param limit - The operation key and its per-second request ceiling.\n\t * @param hooks - Observability callbacks; `onRateLimit` fires when the\n\t * bucket is empty and a sleep is about to start.\n\t * @param sleep - Injectable sleep (tests pass a fake).\n\t */\n\tconstructor(limit: OperationLimit, hooks: OpenCloudHooks, sleep: SleepFunc) {\n\t\tthis.#intervalMs = 1000 / limit.maxPerSecond;\n\t\tconst burstCapacity = limit.burstCapacity ?? Math.max(1, limit.maxPerSecond);\n\t\tthis.#maxBucketLevel = burstCapacity * this.#intervalMs;\n\t\tthis.#hooks = hooks;\n\t\tthis.#sleep = sleep;\n\t}\n\n\t/**\n\t * Waits for a token — sleeping and firing `hooks.onRateLimit` if the\n\t * bucket is empty — then executes `task`. Concurrent callers are\n\t * serialized at token acquisition; tasks themselves run independently\n\t * once their token is secured.\n\t *\n\t * @param task - The request to run once a token is available.\n\t * @returns The value produced by `task`.\n\t */\n\tpublic async acquireAsync<T>(task: () => Promise<T>): Promise<T> {\n\t\tconst myTurn = this.#chain.then(async () => this.#waitForToken());\n\t\tthis.#chain = myTurn;\n\t\tawait myTurn;\n\t\treturn task();\n\t}\n\n\tasync #waitForToken(): Promise<void> {\n\t\tconst now = Math.max(Date.now(), this.#lastCheck);\n\t\tconst drained = Math.max(0, this.#bucketLevel - (now - this.#lastCheck));\n\t\tthis.#lastCheck = now;\n\n\t\tif (drained + this.#intervalMs <= this.#maxBucketLevel) {\n\t\t\tthis.#bucketLevel = drained + this.#intervalMs;\n\t\t\treturn;\n\t\t}\n\n\t\tconst waitMs = drained + this.#intervalMs - this.#maxBucketLevel;\n\t\tthis.#hooks.onRateLimit?.(waitMs);\n\t\tawait this.#sleep(waitMs);\n\t\tthis.#bucketLevel = this.#maxBucketLevel;\n\t\tthis.#lastCheck = now + waitMs;\n\t}\n}\n","import type { Result } from \"../../types.ts\";\n\n/**\n * Wraps a promise into a {@link Result}, catching rejections.\n *\n * @template T - The resolved value type.\n * @param promise - The promise to wrap.\n * @returns A Result containing the resolved value or the rejection error.\n */\nexport async function tryCatchAsync<T>(promise: Promise<T>): Promise<Result<T>> {\n\ttry {\n\t\tconst data = await promise;\n\t\treturn { data, success: true };\n\t} catch (err) {\n\t\treturn { err: err instanceof Error ? err : new Error(String(err)), success: false };\n\t}\n}\n","// A small allowlist of response headers worth retaining on an ApiError for\n// diagnosis and escalation to Roblox. apis.roblox.com returns `server` (e.g.\n// `public-gateway`, or `haproxy` on a load-balancer error page) and\n// `x-roblox-edge` on every response; `via`, `x-request-id`, and `cf-ray` are\n// standard proxy/CDN request-id headers kept in case an edge adds them. The\n// full header set is never retained, to avoid surfacing anything sensitive.\nconst DIAGNOSTIC_HEADER_ALLOWLIST: ReadonlySet<string> = new Set([\n\t\"cf-ray\",\n\t\"server\",\n\t\"via\",\n\t\"x-request-id\",\n]);\n\nconst DIAGNOSTIC_HEADER_PREFIX = \"x-roblox-\";\n\n// Only the opening tag is matched; the closing tag is located with indexOf so\n// the inner text needs no unbounded pattern, which would backtrack\n// super-linearly on a hostile error page.\nconst TITLE_OPEN_PATTERN = /<title[^>]*>/i;\nconst H1_OPEN_PATTERN = /<h1[^>]*>/i;\nconst TAG_PATTERN = /<[^<>]*>/g;\nconst WHITESPACE_PATTERN = /\\s+/g;\n\n/**\n * Extracts a one-line human summary from an HTML gateway error page, or returns\n * `undefined` when the body is not such a page. A load balancer (HAProxy-style)\n * rejects a request before it reaches Open Cloud and answers with an HTML page,\n * not a JSON Open Cloud error; dumping that HTML whole is noise. The body is\n * treated as HTML when the content-type is `text/html` or the trimmed body is\n * tag-led (`<html`/`<!doctype html`), and the summary is taken from the\n * `<title>` (falling back to the first `<h1>`), tags stripped and whitespace\n * collapsed.\n *\n * @param contentType - The response `content-type` header, if present.\n * @param rawText - The raw response body text.\n * @returns The extracted summary, or `undefined` when the body is not an HTML\n * gateway page (or carries no title/h1 text).\n */\nexport function extractGatewaySummary(\n\tcontentType: string | undefined,\n\trawText: string,\n): string | undefined {\n\tif (!isHtmlBody(contentType, rawText)) {\n\t\treturn undefined;\n\t}\n\n\treturn (\n\t\tfirstTagText(rawText, { close: \"</title>\", open: TITLE_OPEN_PATTERN }) ??\n\t\tfirstTagText(rawText, { close: \"</h1>\", open: H1_OPEN_PATTERN })\n\t);\n}\n\n/**\n * Filters a lowercased header record down to the diagnostic allowlist: a few\n * named escalation headers plus any `x-roblox-*` header. Keeps errors light and\n * avoids retaining anything sensitive from the full response header set.\n *\n * @param headers - The full header record (lowercased keys).\n * @returns A record containing only the allowlisted headers that were present.\n */\nexport function pickDiagnosticHeaders(headers: Record<string, string>): Record<string, string> {\n\tconst picked: Record<string, string> = {};\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tif (DIAGNOSTIC_HEADER_ALLOWLIST.has(name) || name.startsWith(DIAGNOSTIC_HEADER_PREFIX)) {\n\t\t\tpicked[name] = value;\n\t\t}\n\t}\n\n\treturn picked;\n}\n\nfunction firstTagText(html: string, tag: { close: string; open: RegExp }): string | undefined {\n\tconst open = tag.open.exec(html);\n\tif (open === null) {\n\t\treturn undefined;\n\t}\n\n\tconst start = open.index + open[0].length;\n\tconst end = html.toLowerCase().indexOf(tag.close, start);\n\tif (end === -1) {\n\t\treturn undefined;\n\t}\n\n\tconst inner = html.slice(start, end);\n\n\tconst text = inner.replace(TAG_PATTERN, \" \").replace(WHITESPACE_PATTERN, \" \").trim();\n\treturn text === \"\" ? undefined : text;\n}\n\nfunction isHtmlBody(contentType: string | undefined, rawText: string): boolean {\n\tif (contentType?.toLowerCase().includes(\"text/html\") === true) {\n\t\treturn true;\n\t}\n\n\tconst head = rawText.trimStart().toLowerCase();\n\treturn head.startsWith(\"<html\") || head.startsWith(\"<!doctype html\");\n}\n","/** The shape the global dispatcher's class is assumed to have. */\ntype AgentConstructor = new (options: { allowH2: boolean }) => object;\n\n/**\n * Well-known globals under which undici publishes its global dispatcher,\n * newest first. The suffix is undici's own contract version: it moved from\n * `.1` to `.2` in undici 8, so a future major may move it again. Both are\n * probed, and {@link createHttp1Dispatcher} degrades to `undefined` when\n * neither is present — which is also the Bun path, since Bun's `fetch` is not\n * undici-backed and never publishes these.\n */\nconst GLOBAL_DISPATCHER_KEYS: ReadonlyArray<string> = Object.freeze([\n\t\"undici.globalDispatcher.2\",\n\t\"undici.globalDispatcher.1\",\n]);\n\n/**\n * Narrow a value read off the global dispatcher to something\n * `Reflect.construct` accepts. Exported so the narrowing is unit-testable: at\n * the call site every rejected shape funnels into the same `undefined`, which\n * makes the branch unobservable from `createHttp1Dispatcher` alone.\n *\n * @param value - The candidate `constructor` read off the global dispatcher.\n * @returns Whether the value can be constructed.\n */\nexport function isAgentConstructor(value: unknown): value is AgentConstructor {\n\treturn typeof value === \"function\";\n}\n\n/**\n * Builds a request dispatcher that negotiates HTTP/1.1 only, by reusing the\n * class of the runtime's own global dispatcher.\n *\n * From Node 26 (undici 8) `fetch` offers h2 in ALPN, which defeats the\n * `connection: close` an upload sets: `connection` is a connection-specific\n * header, so an h2 transport drops it before the wire and pools every upload\n * onto one multiplexed session. One session death then fails every upload in\n * flight. Constructing the same agent with `allowH2: false` restores the\n * per-upload connection the directive was written for.\n *\n * There is no standard `fetch` option for this, so the agent is reached\n * through undici's versioned global symbol and its class rather than through\n * an import — which keeps the package dependency-free. The contract is\n * internal, so every step is guarded: an absent symbol, a non-constructible\n * value, or a constructor that throws all yield `undefined`, and the caller\n * sends the request unmodified.\n *\n * @param scope - The object to read the global dispatcher from. Defaults to\n * `globalThis`; injectable so tests need not mutate the real global.\n * @returns A dispatcher restricted to HTTP/1.1, or `undefined` when this\n * runtime offers no reachable one.\n */\nexport function createHttp1Dispatcher(scope: object = globalThis): object | undefined {\n\tfor (const key of GLOBAL_DISPATCHER_KEYS) {\n\t\tconst dispatcher = constructHttp1(Reflect.get(scope, Symbol.for(key)));\n\t\tif (dispatcher !== undefined) {\n\t\t\treturn dispatcher;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Reconstructs `agent`'s class with h2 disabled.\n *\n * Most ways `agent` can be wrong already throw: `Reflect.get` rejects a\n * primitive, `null`, and an absent key, and `Reflect.construct` rejects a\n * `constructor` that is not one, or that refuses the options. One shape gets\n * through — a plain object, whose `constructor` is `Object`, so constructing\n * it hands back the options bag. The result is therefore checked against the\n * one part of undici's surface that is public and stable: a `Dispatcher`\n * exposes `dispatch`.\n *\n * @param agent - The candidate global dispatcher; any value, since it comes\n * from an undocumented global.\n * @returns The new dispatcher, or `undefined` when `agent` is not an object\n * whose constructor accepts undici's agent options.\n */\nfunction constructHttp1(agent: unknown): object | undefined {\n\ttry {\n\t\t// No shape guard ahead of this: `Reflect.get` already rejects a\n\t\t// primitive, `null`, and an absent key, so every malformed value lands\n\t\t// in the same catch.\n\t\tconst agentClass = Reflect.get(agent, \"constructor\");\n\t\tif (!isAgentConstructor(agentClass)) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst dispatcher = Reflect.construct(agentClass, [{ allowH2: false }]);\n\t\treturn typeof Reflect.get(dispatcher, \"dispatch\") === \"function\" ? dispatcher : undefined;\n\t} catch {\n\t\t// An internal contract that moved under us is not worth failing a\n\t\t// deploy over: fall back to the runtime's default transport.\n\t\treturn undefined;\n\t}\n}\n","import type { HttpRequest } from \"../../client/types.ts\";\n\n/**\n * Reports whether a request is an upload: its body is `FormData`\n * (multipart) or `Uint8Array` (raw binary). Upload latency is\n * bandwidth-bound rather than compute-bound, so the SDK applies no default\n * request timeout to these requests; a sensible wall-clock budget depends on\n * payload size and link quality the SDK cannot know.\n *\n * @param request - The built request to classify.\n * @returns `true` when the body is `FormData` or `Uint8Array`.\n */\nexport function isUploadRequest(request: HttpRequest): boolean {\n\treturn request.body instanceof FormData || request.body instanceof Uint8Array;\n}\n","import { ApiError } from \"../../errors/api-error.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { NetworkError } from \"../../errors/network-error.ts\";\nimport { RateLimitError } from \"../../errors/rate-limit.ts\";\nimport type { Result } from \"../../types.ts\";\nimport { tryCatchAsync } from \"../utils/try-catch.ts\";\nimport { extractGatewaySummary, pickDiagnosticHeaders } from \"./diagnostics.ts\";\nimport { createHttp1Dispatcher } from \"./http1-dispatcher.ts\";\nimport { reduceRateLimitTokens } from \"./rate-limit-sample.ts\";\nimport type { HttpClient, HttpRequest, HttpResponse, RequestConfig } from \"./types.ts\";\nimport { isUploadRequest } from \"./upload-request.ts\";\n\n// Caps the raw body retained when a response cannot be parsed, so a multi-KB\n// HTML error page is not surfaced or logged whole.\nconst MAX_DETAIL_LENGTH = 500;\n\nconst CONTENT_TYPE_HEADER = \"content-type\";\n\n// Uploads opt out of keep-alive reuse. Roblox's edge gateway discards idle\n// pooled connections faster than a pooling `fetch` expects, and a request\n// written into a discarded connection never reaches Open Cloud: it surfaces as\n// a gateway error page or a socket reset, minutes later, having done nothing.\n// An upload holds a connection far longer than a JSON call, so it is the shape\n// that loses this race. The cost is a fresh handshake and a cold congestion\n// window per upload (real for a multi-megabyte body, and paid again on each\n// retry), but cheaper than a lost write. Small, frequent calls keep pooling.\nconst CONNECTION_HEADER = \"connection\";\n\n/**\n * `RequestInit` plus undici's non-standard `dispatcher`, the only way to\n * select a transport from `fetch`. Declared locally because it is absent from\n * the DOM lib and runtimes that do not understand it ignore it.\n */\ninterface FetchOptions extends RequestInit {\n\tdispatcher?: object | undefined;\n}\n\n/**\n * Collaborators of {@link createFetchHttpClient}, bundled so the factory keeps\n * a two-argument signature as they accumulate. Both have production defaults;\n * both are overridable, which is also what makes them testable.\n */\ninterface FetchHttpClientSeams {\n\t/**\n\t * Builds the HTTP/1.1-only transport uploads use, so the\n\t * `connection: close` directive is not dropped by an h2 transport.\n\t */\n\treadonly createDispatcher?: () => object | undefined;\n\t/** Monotonic-ish clock used to measure request elapsed time. */\n\treadonly now?: () => number;\n}\n\ninterface ParseFailureArgs {\n\treadonly cause: Error;\n\treadonly response: Response;\n\treadonly text: string;\n}\n\n/**\n * The request-level context threaded from the transport into error\n * construction: which call failed and how long it was in flight.\n */\ninterface RequestContext {\n\treadonly elapsedMs: number;\n\treadonly method: string;\n\treadonly url: string;\n}\n\ninterface ErrorResponseArgs {\n\treadonly context: RequestContext;\n\treadonly parsed: Result<JSONValue | undefined>;\n\treadonly rawText: string;\n\treadonly response: Response;\n}\n\ninterface ApiErrorMessageParts {\n\treadonly code: string | undefined;\n\treadonly message: string | undefined;\n\treadonly status: number;\n}\n\n/**\n * Converts a `Headers` object to a plain record with lowercased keys.\n *\n * @param headers - The `Headers` instance to convert.\n * @returns A record mapping lowercased header names to their values.\n */\nexport function headersToRecord(headers: Headers): Record<string, string> {\n\treturn Object.fromEntries(headers);\n}\n\n/**\n * Permissively extracts a machine-readable error code from a response body.\n *\n * Modern Open Cloud responses use `{ errorCode: string, message: string }`;\n * the legacy game-internationalization endpoints use\n * `{ errors: [{ code: number, message: string }, ...] }`. Both shapes are\n * checked; numeric legacy codes are returned as strings so callers see one\n * consistent type.\n *\n * @param body - The parsed response body (unknown shape).\n * @returns The error code if present, otherwise `undefined`.\n */\nexport function extractErrorCode(body: unknown): string | undefined {\n\tif (body === null || typeof body !== \"object\") {\n\t\treturn undefined;\n\t}\n\n\tconst errorCode = Reflect.get(body, \"errorCode\");\n\tif (typeof errorCode === \"string\") {\n\t\treturn errorCode;\n\t}\n\n\treturn extractLegacyCode(body);\n}\n\n/**\n * Permissively extracts a human-readable error message from a response body.\n *\n * Modern Open Cloud responses expose `message` at the top level; the legacy\n * game-internationalization endpoints nest it under `errors[0].message`.\n *\n * @param body - The parsed response body (unknown shape).\n * @returns The message if present, otherwise `undefined`.\n */\nexport function extractErrorMessage(body: unknown): string | undefined {\n\tif (body === null || typeof body !== \"object\") {\n\t\treturn undefined;\n\t}\n\n\tconst message = Reflect.get(body, \"message\");\n\tif (typeof message === \"string\") {\n\t\treturn message;\n\t}\n\n\treturn extractLegacyMessage(body);\n}\n\n/**\n * Parses the `x-ratelimit-reset` header value into seconds. On a 429 the\n * header is a comma-separated list of per-window reset times (e.g. `\"22, 0\"`,\n * one entry per rate-limit window); the largest value is the longest-resetting\n * window and the only safe wait that won't retry into a still-exhausted\n * window. A single value is treated as a one-element list.\n *\n * @param headerValue - The raw header value, or `undefined` if missing.\n * @returns The number of seconds to wait, or 0 if missing/invalid.\n */\nexport function parseRetryAfterSeconds(headerValue: string | undefined): number {\n\treturn reduceRateLimitTokens(headerValue, (a, b) => Math.max(a, b)) ?? 0;\n}\n\n/**\n * Joins the base URL from config with the relative path from the request.\n *\n * @param request - The HTTP request containing the relative URL.\n * @param config - The request config containing the base URL.\n * @returns The fully-qualified URL string.\n */\nexport function buildUrl(request: HttpRequest, config: RequestConfig): string {\n\tconst base = config.baseUrl.endsWith(\"/\") ? config.baseUrl.slice(0, -1) : config.baseUrl;\n\treturn `${base}${request.url}`;\n}\n\n/**\n * Constructs the `RequestInit` options for a `fetch` call.\n *\n * @param request - The HTTP request to build options for.\n * @param config - The request config containing API key and timeout.\n * @returns A `RequestInit` object ready for `fetch`.\n */\nexport function buildFetchOptions(request: HttpRequest, config: RequestConfig): FetchOptions {\n\tconst headers = new Headers({\n\t\t\"x-api-key\": config.apiKey,\n\t});\n\n\tconst options: FetchOptions = {\n\t\theaders,\n\t\tmethod: request.method,\n\t};\n\n\tif (request.body instanceof FormData) {\n\t\toptions.body = request.body;\n\t} else if (request.body instanceof Uint8Array) {\n\t\theaders.set(CONTENT_TYPE_HEADER, \"application/octet-stream\");\n\t\toptions.body = request.body;\n\t} else if (request.body !== undefined) {\n\t\theaders.set(CONTENT_TYPE_HEADER, \"application/json\");\n\t\toptions.body = JSON.stringify(request.body);\n\t}\n\n\tapplyRequestHeaders(headers, request);\n\n\tif (config.timeout !== undefined) {\n\t\toptions.signal = AbortSignal.timeout(config.timeout);\n\t}\n\n\treturn options;\n}\n\n/**\n * Creates an {@link HttpClient} backed by the Fetch API.\n *\n * @param fetchFunc - The fetch implementation to use. Defaults to `globalThis.fetch`.\n * @param seams - Injectable clock and dispatcher factory, so tests need not\n * depend on wall-clock time or on the runtime's global dispatcher.\n * @returns An HttpClient that classifies responses into typed Results.\n */\nexport function createFetchHttpClient(\n\tfetchFunc: (url: string, init: RequestInit) => Promise<Response> = fetch,\n\t{ createDispatcher = createHttp1Dispatcher, now = Date.now }: FetchHttpClientSeams = {},\n): HttpClient {\n\tconst dispatcherFor = createUploadDispatcherCache(createDispatcher);\n\n\treturn {\n\t\tasync request(\n\t\t\thttpRequest: HttpRequest,\n\t\t\tconfig: RequestConfig,\n\t\t): Promise<Result<HttpResponse, OpenCloudError>> {\n\t\t\tconst url = buildUrl(httpRequest, config);\n\t\t\tconst options = buildFetchOptions(httpRequest, config);\n\t\t\t// Undefined is how `fetch` spells \"use the runtime's own\n\t\t\t// transport\", so this is safe to assign unconditionally.\n\t\t\toptions.dispatcher = dispatcherFor(httpRequest);\n\t\t\tconst target = { method: httpRequest.method, url };\n\n\t\t\tconst { elapsedMs, fetchResult } = await timedFetchAsync(now, async () => {\n\t\t\t\treturn fetchFunc(url, options);\n\t\t\t});\n\t\t\tif (!fetchResult.success) {\n\t\t\t\treturn { err: networkError(fetchResult.err, target), success: false };\n\t\t\t}\n\n\t\t\t// Reading and classifying the body can itself throw (an aborted or\n\t\t\t// undecodable body stream rejects `response.text()`); keep the\n\t\t\t// Result contract by mapping any such throw to a NetworkError.\n\t\t\tconst context: RequestContext = { elapsedMs, method: target.method, url: target.url };\n\t\t\tconst classified = await tryCatchAsync(\n\t\t\t\tclassifyResponseAsync(fetchResult.data, context),\n\t\t\t);\n\t\t\tif (!classified.success) {\n\t\t\t\treturn { err: networkError(classified.err, target), success: false };\n\t\t\t}\n\n\t\t\treturn classified.data;\n\t\t},\n\t};\n}\n\nfunction readLegacyErrorEntry(body: object): object | undefined {\n\tconst errors = Reflect.get(body, \"errors\");\n\tif (!Array.isArray(errors)) {\n\t\treturn undefined;\n\t}\n\n\tconst [first] = errors;\n\tif (typeof first !== \"object\" || first === null) {\n\t\treturn undefined;\n\t}\n\n\treturn first;\n}\n\nfunction extractLegacyCode(body: object): string | undefined {\n\tconst first = readLegacyErrorEntry(body);\n\tif (first === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst code = Reflect.get(first, \"code\");\n\tif (typeof code === \"string\") {\n\t\treturn code;\n\t}\n\n\treturn typeof code === \"number\" ? String(code) : undefined;\n}\n\nfunction extractLegacyMessage(body: object): string | undefined {\n\tconst first = readLegacyErrorEntry(body);\n\tif (first === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst message = Reflect.get(first, \"message\");\n\treturn typeof message === \"string\" ? message : undefined;\n}\n\n/**\n * Merges the request's own headers onto the transport's, then applies the\n * transport-owned connection directive. `x-api-key` is skipped so a request\n * cannot override the configured credential, and the upload directive is set\n * last so a request header cannot silently re-enable pooling for an upload.\n *\n * @param headers - The headers being built for the fetch call. Mutated.\n * @param request - The request whose headers and body shape drive the merge.\n */\nfunction applyRequestHeaders(headers: Headers, request: HttpRequest): void {\n\tconst requestHeaders = request.headers ?? {};\n\tfor (const [name, value] of Object.entries(requestHeaders)) {\n\t\tif (name.toLowerCase() === \"x-api-key\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\theaders.set(name, value);\n\t}\n\n\tif (isUploadRequest(request)) {\n\t\theaders.set(CONNECTION_HEADER, \"close\");\n\t}\n}\n\n/**\n * Wraps a dispatcher factory in the caching policy uploads need.\n *\n * Resolution happens on the first upload rather than at construction: undici\n * publishes its global dispatcher lazily, so before a process's first `fetch`\n * there is nothing to read. A resolved dispatcher is kept, and an unresolved\n * one is retried on the next upload — so a runtime that publishes late is\n * still picked up, and the first request of a process, which has no pooled\n * connection to lose, is safe either way.\n *\n * @param createDispatcher - Builds the HTTP/1.1-only transport.\n * @returns A function yielding the dispatcher for a request, or `undefined`\n * when the request is not an upload or no dispatcher is available.\n */\nfunction createUploadDispatcherCache(\n\tcreateDispatcher: () => object | undefined,\n): (request: HttpRequest) => object | undefined {\n\tlet cached: object | undefined;\n\treturn (request) => {\n\t\tif (!isUploadRequest(request)) {\n\t\t\treturn;\n\t\t}\n\n\t\tcached ??= createDispatcher();\n\t\treturn cached;\n\t};\n}\n\n/**\n * Runs `send` and reports both its Result and how long it was in flight,\n * measured with `now`. Isolated so the timing start need not sit in the request\n * body ahead of the transport-failure early return.\n *\n * @param now - The clock used to bound the call.\n * @param send - A thunk that issues the fetch.\n * @returns The fetch Result and the elapsed milliseconds.\n */\nasync function timedFetchAsync(\n\tnow: () => number,\n\tsend: () => Promise<Response>,\n): Promise<{ elapsedMs: number; fetchResult: Result<Response> }> {\n\tconst start = now();\n\tconst fetchResult = await tryCatchAsync(send());\n\t// Clamp to zero: `Date.now` is wall-clock, so an NTP adjustment mid-request\n\t// could otherwise report a negative \"after -0.1s\".\n\treturn { elapsedMs: Math.max(0, now() - start), fetchResult };\n}\n\nfunction networkError(cause: Error, target: { method: string; url: string }): NetworkError {\n\treturn new NetworkError(\"Network request failed\", {\n\t\tcause,\n\t\tmethod: target.method,\n\t\turl: target.url,\n\t});\n}\n\nfunction formatApiErrorMessage({ code, message, status }: ApiErrorMessageParts): string {\n\tconst base = `HTTP ${status}`;\n\tif (message === undefined && code === undefined) {\n\t\treturn base;\n\t}\n\n\tif (message === undefined) {\n\t\treturn `${base} (code ${code})`;\n\t}\n\n\tif (code === undefined) {\n\t\treturn `${base}: ${message}`;\n\t}\n\n\treturn `${base}: ${message} (code ${code})`;\n}\n\n/**\n * Projects a read body to the detail carried on an error: the parsed JSON when\n * it parsed, otherwise the raw text truncated to {@link MAX_DETAIL_LENGTH}.\n *\n * @param text - The raw response body text.\n * @param parsed - The best-effort parse result from {@link readResponseBodyAsync}.\n * @returns The parsed body, or the truncated raw text on a parse failure.\n */\nfunction bodyDetail(text: string, parsed: Result<JSONValue | undefined>): JSONValue | undefined {\n\treturn parsed.success ? parsed.data : text.slice(0, MAX_DETAIL_LENGTH);\n}\n\nfunction createApiError(args: ErrorResponseArgs): ApiError {\n\tconst { context, rawText, response } = args;\n\tconst { status } = response;\n\tconst headers = headersToRecord(response.headers);\n\tconst requestContext = {\n\t\telapsedMs: context.elapsedMs,\n\t\tmethod: context.method,\n\t\tresponseHeaders: pickDiagnosticHeaders(headers),\n\t\tstatusCode: status,\n\t\turl: context.url,\n\t};\n\n\t// An HTML body is a load-balancer error page, not an Open Cloud response;\n\t// summarize it rather than retaining the raw HTML on `details`.\n\tconst gatewaySummary = extractGatewaySummary(headers[CONTENT_TYPE_HEADER], rawText);\n\tif (gatewaySummary !== undefined) {\n\t\treturn new ApiError(`HTTP ${status}`, { ...requestContext, gatewaySummary });\n\t}\n\n\tconst body = bodyDetail(rawText, args.parsed);\n\tconst code = extractErrorCode(body);\n\tconst message = extractErrorMessage(body);\n\treturn new ApiError(formatApiErrorMessage({ code, message, status }), {\n\t\t...requestContext,\n\t\tcode,\n\t\tdetails: body,\n\t});\n}\n\n/**\n * Parses response text as JSON, returning the underlying `SyntaxError` on\n * failure rather than throwing. The synchronous sibling of {@link\n * tryCatchAsync}.\n *\n * @param text - The raw response body text.\n * @returns A Result wrapping the parsed value, or the parse error.\n */\nfunction parseJson(text: string): Result<JSONValue> {\n\ttry {\n\t\treturn { data: JSON.parse(text), success: true };\n\t} catch (err) {\n\t\treturn { err: err instanceof Error ? err : new Error(String(err)), success: false };\n\t}\n}\n\n/**\n * Reads a response body once and parses it best-effort: an empty body is a\n * successful `undefined`, otherwise the JSON parse result (which carries the\n * `SyntaxError` on failure). Returns the raw `text` alongside so callers that\n * need the original bytes (parse-failure diagnostics) do not re-read the\n * consumed stream.\n *\n * @param response - The Response whose body to read.\n * @returns The parse result and the raw text.\n */\nasync function readResponseBodyAsync(\n\tresponse: Response,\n): Promise<{ parsed: Result<JSONValue | undefined>; text: string }> {\n\tconst text = await response.text();\n\treturn {\n\t\tparsed: text === \"\" ? { data: undefined, success: true } : parseJson(text),\n\t\ttext,\n\t};\n}\n\nasync function createRateLimitErrorAsync(response: Response): Promise<RateLimitError> {\n\tconst headers = headersToRecord(response.headers);\n\tconst { parsed, text } = await readResponseBodyAsync(response);\n\treturn new RateLimitError(\"Rate limited\", {\n\t\tdetails: bodyDetail(text, parsed),\n\t\tremaining: reduceRateLimitTokens(headers[\"x-ratelimit-remaining\"], (a, b) => {\n\t\t\treturn Math.min(a, b);\n\t\t}),\n\t\tretryAfterSeconds: parseRetryAfterSeconds(headers[\"x-ratelimit-reset\"]),\n\t\tstatusCode: response.status,\n\t});\n}\n\n/**\n * Builds the error for a 2xx response whose body could not be parsed as JSON,\n * preserving the parse `cause`, the (truncated) raw body, and the declared\n * content-type so the failure can be diagnosed after the fact.\n *\n * @param args - The Response, raw body text, and underlying parse error.\n * @returns An ApiError carrying the diagnostic context.\n */\nfunction parseFailureError({ cause, response, text }: ParseFailureArgs): ApiError {\n\tconst contentType = response.headers.get(CONTENT_TYPE_HEADER) ?? \"unknown\";\n\treturn new ApiError(`Failed to parse response body (content-type: ${contentType})`, {\n\t\tcause,\n\t\tdetails: text.slice(0, MAX_DETAIL_LENGTH),\n\t\tstatusCode: response.status,\n\t});\n}\n\n/**\n * Classifies a fetch `Response` into a typed `Result`.\n *\n * The body is read once and parsed best-effort. Error responses (status >= 300)\n * never require valid JSON: an error body that is not valid JSON degrades to a\n * status-based {@link ApiError} carrying the raw text, and an HTML gateway page\n * is summarized rather than dumped. A parse failure is only fatal on a 2xx,\n * where a parseable body is part of the contract.\n *\n * @param response - The raw fetch Response to classify.\n * @param context - The request context (method, url, elapsed time) threaded\n * onto any {@link ApiError} built for an error response.\n * @returns A Result containing an HttpResponse on success or an OpenCloudError on failure.\n */\nasync function classifyResponseAsync(\n\tresponse: Response,\n\tcontext: RequestContext,\n): Promise<Result<HttpResponse, OpenCloudError>> {\n\tif (response.status === 429) {\n\t\treturn { err: await createRateLimitErrorAsync(response), success: false };\n\t}\n\n\tconst { parsed, text } = await readResponseBodyAsync(response);\n\n\tif (response.status >= 300) {\n\t\treturn {\n\t\t\terr: createApiError({ context, parsed, rawText: text, response }),\n\t\t\tsuccess: false,\n\t\t};\n\t}\n\n\tif (!parsed.success) {\n\t\treturn { err: parseFailureError({ cause: parsed.err, response, text }), success: false };\n\t}\n\n\treturn {\n\t\tdata: {\n\t\t\tbody: parsed.data,\n\t\t\theaders: headersToRecord(response.headers),\n\t\t\tstatus: response.status,\n\t\t},\n\t\tsuccess: true,\n\t};\n}\n","import { setTimeout } from \"node:timers/promises\";\n\nimport type { HttpClient, SleepFunc } from \"../../client/types.ts\";\nimport { createFetchHttpClient } from \"./fetch-client.ts\";\n\n/**\n * Options accepted by {@link resolveDependencies}. Mirrors the test-seam\n * subset of the public client options.\n */\ninterface ResolveDependenciesOptions {\n\t/**\n\t * Test seam: custom {@link HttpClient}. Defaults to a fetch-backed client.\n\t */\n\treadonly httpClient?: HttpClient | undefined;\n\t/**\n\t * Test seam: custom {@link SleepFunc}. Defaults to a `setTimeout`-backed\n\t * sleep.\n\t */\n\treadonly sleep?: SleepFunc | undefined;\n}\n\n/**\n * Fully-populated dependency set consumed by resource client constructors.\n */\ninterface ResolvedDependencies {\n\t/** Concrete {@link HttpClient} implementation. */\n\treadonly httpClient: HttpClient;\n\t/** Concrete {@link SleepFunc} implementation. */\n\treadonly sleep: SleepFunc;\n}\n\n/**\n * Resolves the concrete HTTP client and sleep implementation a resource\n * client should use. Falls back to the fetch-backed HTTP client and the\n * default `setTimeout`-based sleep when the caller omits the test seams.\n *\n * Extracted so resource client constructors can keep their dependency\n * resolution logic in a single, unit-testable place; this makes the\n * default branches easy to cover without stubbing globals like `fetch`.\n *\n * @param options - Optional {@link HttpClient} and {@link SleepFunc} test seams.\n * @returns A {@link ResolvedDependencies} with defaults applied.\n */\nexport function resolveDependencies(options: ResolveDependenciesOptions): ResolvedDependencies {\n\treturn {\n\t\thttpClient: options.httpClient ?? createFetchHttpClient(),\n\t\tsleep: options.sleep ?? setTimeout,\n\t};\n}\n","import type { Except } from \"type-fest\";\n\nimport type {\n\tHttpClient,\n\tHttpRequest,\n\tHttpResponse,\n\tOpenCloudClientOptions,\n\tOpenCloudHooks,\n\tRequestConfig,\n\tRequestOptions,\n\tSleepFunc,\n} from \"../client/types.ts\";\nimport { ApiError } from \"../errors/api-error.ts\";\nimport type { OpenCloudError } from \"../errors/base.ts\";\nimport { PermissionError } from \"../errors/permission-error.ts\";\nimport type { Result } from \"../types.ts\";\nimport { BudgetGate } from \"./http/budget-gate.ts\";\nimport { executeWithRetryAsync } from \"./http/execute.ts\";\nimport { rateLimitSampleFromResult } from \"./http/rate-limit-observation.ts\";\nimport { type OperationLimit, RateLimitQueue } from \"./http/rate-limit-queue.ts\";\nimport { resolveDependencies } from \"./http/resolve-dependencies.ts\";\nimport {\n\tdefaultRetryDelay,\n\tIDEMPOTENT_METHOD_DEFAULTS,\n\tmergeConfig,\n\ttype MethodKind,\n\ttype RetryResolvable,\n} from \"./http/retry.ts\";\nimport { isUploadRequest } from \"./http/upload-request.ts\";\n\n/**\n * Describes a single resource method's shape for dispatch through\n * `ResourceClient.execute`. Each resource client declares one module-level\n * constant per public method; that constant binds the four resource-specific\n * values (request builder, response parser, retry-policy method kind,\n * operation-level rate limit) and flows through `execute` uniformly.\n *\n * @template P - The resource-specific parameter shape the builder\n * accepts.\n * @template T - The resource-specific parsed success type the parser\n * produces.\n */\nexport interface ResourceMethodSpec<P, T> {\n\t/**\n\t * Builds the pure {@link HttpRequest} for a single call. Returns a\n\t * {@link Result} so a builder can short-circuit with a local error\n\t * (typically a {@link OpenCloudError} subclass such as `ValidationError`)\n\t * before any HTTP, queue, or retry work happens. Builders that cannot\n\t * fail wrap their return as `{ data: request, success: true }`.\n\t */\n\treadonly buildRequest: (parameters: P) => Result<HttpRequest, OpenCloudError>;\n\t/** Method-level retry defaults merged into the resolved config. */\n\treadonly methodDefaults: Partial<RetryResolvable>;\n\t/**\n\t * Method kind, controlling merge precedence: `\"create\"` lets method\n\t * defaults win over client config so create safety cannot be relaxed\n\t * silently; `\"idempotent\"` lets client config win over method defaults\n\t * so consumers can loosen retry globally.\n\t */\n\treadonly methodKind: MethodKind;\n\t/**\n\t * Operation-level rate limit, keyed into the client's per-key queue map.\n\t */\n\treadonly operationLimit: OperationLimit;\n\t/**\n\t * Converts the full {@link HttpResponse} into the resource-specific\n\t * parsed shape. Takes the whole response (body, status, headers) so\n\t * future parsers can read headers without widening the signature.\n\t */\n\treadonly parse: (response: HttpResponse) => Result<T, OpenCloudError>;\n\t/**\n\t * Open Cloud scopes the API key or OAuth token must carry for this\n\t * method, sourced from the vendored OpenAPI schema's `x-roblox-scopes`.\n\t * When set, a 401 or 403 ApiError from the upstream call is upgraded to\n\t * a {@link PermissionError} carrying these scopes alongside\n\t * {@link OperationLimit.operationKey}, so callers can name the missing\n\t * scope instead of just the HTTP status. Optional so test specs and\n\t * not-yet-wired resources can opt out.\n\t */\n\treadonly requiredScopes?: ReadonlyArray<string>;\n}\n\n/**\n * Single-argument bundle consumed by `ResourceClient.execute`: the per-method\n * spec, the resource-specific parameters, and optional per-request config\n * overrides.\n *\n * @template P - The resource-specific parameter shape the builder accepts.\n * @template T - The resource-specific parsed success type the parser produces.\n */\ninterface ExecuteCall<P, T> {\n\t/** Optional per-request config overrides. */\n\treadonly options?: RequestOptions | undefined;\n\t/** Resource-specific request parameters. */\n\treadonly parameters: P;\n\t/**\n\t * Per-method binding of builder, parser, method kind, and operation limit.\n\t */\n\treadonly spec: ResourceMethodSpec<P, T>;\n}\n\n/**\n * Wraps an infallible request build as a {@link Result}-returning\n * `buildRequest` callback compatible with {@link ResourceMethodSpec}.\n * Use from a resource client whose builder cannot fail; resource clients\n * with local validation should construct the {@link Result} directly.\n *\n * @param request - The pre-built {@link HttpRequest}.\n * @returns A success Result wrapping the request.\n */\nexport function okRequest(request: HttpRequest): Result<HttpRequest, OpenCloudError> {\n\treturn { data: request, success: true };\n}\n\n/**\n * A {@link ResourceMethodSpec.parse} implementation for endpoints that return\n * no business payload on success (such as `DELETE` and reorder operations).\n * Surfaces `undefined` data and never inspects the response body.\n *\n * @returns A success Result with `undefined` data.\n */\nexport function parseEmptyResponse(): Result<undefined, OpenCloudError> {\n\treturn { data: undefined, success: true };\n}\n\nconst CLIENT_DEFAULTS = Object.freeze({\n\tbaseUrl: \"https://apis.roblox.com\",\n\tmaxRetries: 3,\n\tretryableStatuses: IDEMPOTENT_METHOD_DEFAULTS.retryableStatuses,\n\tretryableTransportCodes: IDEMPOTENT_METHOD_DEFAULTS.retryableTransportCodes,\n\tretryDelay: defaultRetryDelay,\n\ttimeout: 30_000,\n} satisfies Except<RetryResolvable, \"apiKey\">);\n\n/**\n * Inputs to {@link buildRequestConfig}, bundled to keep the signature narrow.\n */\ninterface RequestConfigInputs {\n\t/** The resolved config for this call. */\n\treadonly merged: RetryResolvable;\n\t/** The caller's per-request overrides, if any. */\n\treadonly options: RequestOptions | undefined;\n\t/** The built request, inspected for an upload body. */\n\treadonly request: HttpRequest;\n}\n\n/**\n * Internal orchestrator shared by every Open Cloud resource client. Holds\n * the frozen client config, observability hooks, injected HTTP client and\n * sleep, and the per-effective-key rate-limit queue registry. Resource\n * classes compose one instance and dispatch every public method through\n * {@link ResourceClient.executeAsync} with a per-method {@link ResourceMethodSpec}.\n * Not exported from any package subpath; reachable only via sibling\n * `src/resources/**` modules in this package.\n */\nexport class ResourceClient {\n\treadonly #budgets: BudgetGate;\n\treadonly #config: Readonly<RetryResolvable>;\n\treadonly #hooks: OpenCloudHooks;\n\treadonly #httpClient: HttpClient;\n\treadonly #queues = new Map<string, RateLimitQueue>();\n\treadonly #sleep: SleepFunc;\n\n\t/**\n\t * Creates a new {@link ResourceClient}. Resolves the injected HTTP\n\t * client and sleep (defaulting to fetch + `setTimeout`) and freezes the\n\t * merged client config so subsequent calls cannot mutate it.\n\t *\n\t * @param options - Client-level configuration including the API key\n\t * and optional construction-time test seams.\n\t */\n\tconstructor({ apiKey, hooks, httpClient, sleep, ...overrides }: OpenCloudClientOptions) {\n\t\tconst resolved = resolveDependencies({ httpClient, sleep });\n\t\tthis.#httpClient = resolved.httpClient;\n\t\tthis.#sleep = resolved.sleep;\n\t\tthis.#budgets = new BudgetGate(this.#sleep);\n\t\tthis.#hooks = hooks ?? {};\n\t\tthis.#config = Object.freeze({\n\t\t\t...CLIENT_DEFAULTS,\n\t\t\tapiKey,\n\t\t\t...overrides,\n\t\t});\n\t}\n\n\t/**\n\t * Dispatches a single resource-method call. Merges the frozen client\n\t * config with the method's `methodDefaults` and the caller's optional\n\t * per-request `options`, routes through the effective-apiKey rate-limit\n\t * queue, runs the retry loop, and finally parses the response with the\n\t * spec's parser.\n\t *\n\t * @param call - The per-method spec, resource-specific parameters, and\n\t * optional per-request overrides.\n\t * @returns The parsed success payload or the {@link OpenCloudError} that\n\t * caused the request to fail. Never throws.\n\t */\n\tpublic async executeAsync<P, T>({\n\t\toptions,\n\t\tparameters,\n\t\tspec,\n\t}: ExecuteCall<P, T>): Promise<Result<T, OpenCloudError>> {\n\t\tconst merged = mergeConfig(this.#config, {\n\t\t\tmethodDefaults: spec.methodDefaults,\n\t\t\tmethodKind: spec.methodKind,\n\t\t\trequestOptions: options ?? {},\n\t\t});\n\t\tconst requestResult = spec.buildRequest(parameters);\n\t\tif (!requestResult.success) {\n\t\t\treturn requestResult;\n\t\t}\n\n\t\tconst requestConfig = buildRequestConfig({ merged, options, request: requestResult.data });\n\t\tconst queue = this.#getQueue(merged.apiKey, spec.operationLimit);\n\t\tconst httpResult = await queue.acquireAsync(async () => {\n\t\t\treturn executeWithRetryAsync(requestResult.data, {\n\t\t\t\tconfig: merged,\n\t\t\t\thooks: this.#hooks,\n\t\t\t\tsend: this.#gatedSend(merged.apiKey, requestConfig),\n\t\t\t\tsleep: this.#sleep,\n\t\t\t});\n\t\t});\n\t\tif (!httpResult.success) {\n\t\t\treturn { err: enrichPermissionError(httpResult.err, spec), success: false };\n\t\t}\n\n\t\treturn spec.parse(httpResult.data);\n\t}\n\n\t/**\n\t * Returns the sleep function used by this client instance.\n\t *\n\t * @returns The sleep function injected at construction time.\n\t */\n\tpublic get sleep(): SleepFunc {\n\t\treturn this.#sleep;\n\t}\n\n\t/**\n\t * Builds the transport callback for one logical call, wrapping the HTTP\n\t * client with the budget gate: each attempt waits on the API key's budget\n\t * before sending, then folds the response's reported budget back in so the\n\t * next attempt (or a sibling operation on the same key) can head off a 429.\n\t *\n\t * @param apiKey - The effective API key to gate on.\n\t * @param requestConfig - The resolved per-request transport config.\n\t * @returns A send callback for {@link executeWithRetryAsync}.\n\t */\n\t#gatedSend(\n\t\tapiKey: string,\n\t\trequestConfig: RequestConfig,\n\t): (request: HttpRequest) => Promise<Result<HttpResponse, OpenCloudError>> {\n\t\treturn async (toSend) => {\n\t\t\tawait this.#budgets.gateAsync(apiKey);\n\t\t\tconst sendResult = await this.#httpClient.request(toSend, requestConfig);\n\t\t\tthis.#budgets.observe(apiKey, rateLimitSampleFromResult(sendResult));\n\t\t\treturn sendResult;\n\t\t};\n\t}\n\n\t#getQueue(apiKey: string, limit: OperationLimit): RateLimitQueue {\n\t\tconst key = `${apiKey}::${limit.operationKey}`;\n\t\tconst existing = this.#queues.get(key);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);\n\t\tthis.#queues.set(key, queue);\n\t\treturn queue;\n\t}\n}\n\n/**\n * Resolves the per-request {@link RequestConfig}. Upload requests\n * ({@link isUploadRequest}) carry no default timeout: a multi-megabyte place\n * file over a slow link is bandwidth-bound, so a client-side deadline only\n * fires spuriously. An explicit `options.timeout` still applies to any\n * request; every non-upload request keeps the merged default.\n *\n * @param inputs - The merged config, the built request, and per-request overrides.\n * @returns The config to hand to the transport, with `timeout` omitted when\n * no client-side deadline should apply.\n */\nfunction buildRequestConfig({ merged, options, request }: RequestConfigInputs): RequestConfig {\n\tconst shouldOmitDefaultTimeout = options?.timeout === undefined && isUploadRequest(request);\n\treturn {\n\t\tapiKey: merged.apiKey,\n\t\tbaseUrl: merged.baseUrl,\n\t\t...(shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }),\n\t};\n}\n\nfunction enrichPermissionError<P, T>(\n\terr: OpenCloudError,\n\tspec: ResourceMethodSpec<P, T>,\n): OpenCloudError {\n\tif (spec.requiredScopes === undefined) {\n\t\treturn err;\n\t}\n\n\tif (err instanceof PermissionError) {\n\t\treturn err;\n\t}\n\n\tif (!(err instanceof ApiError)) {\n\t\treturn err;\n\t}\n\n\tif (err.statusCode !== 401 && err.statusCode !== 403) {\n\t\treturn err;\n\t}\n\n\treturn new PermissionError(err.message, {\n\t\tcause: err.cause,\n\t\tcode: err.code,\n\t\tdetails: err.details,\n\t\toperationKey: spec.operationLimit.operationKey,\n\t\trequiredScopes: spec.requiredScopes,\n\t\tstatusCode: err.statusCode,\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,iBAAiB,OAAiC;CACjE,IAAI,OAAO,UAAU,UACpB,OAAO;CAGR,MAAM,SAAS,IAAI,KAAK,KAAK;CAC7B,OAAO,CAAC,OAAO,MAAM,OAAO,QAAQ,CAAC;AACtC;;;;;;;;;;;;ACRA,SAAgB,SAAS,OAAkD;CAC1E,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AAClD;;;;;;;;;;;;;;ACEA,SAAgB,cAAc,OAAuC;CACpE,OAAO,YAAY,uBAAO,IAAI,IAAI,CAAC;AACpC;AAEA,SAAS,YAAY,OAAgB,MAA0C;CAC9E,IAAI,UAAU,MAEb,OAAO;CAGR,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAC9E,OAAO;CAGR,IAAI,MAAM,QAAQ,KAAK,GACtB,OAAO,YAAY,OAAO,IAAI;CAG/B,IAAI,SAAS,KAAK,GACjB,OAAO,aAAa,OAAO,IAAI;AAIjC;AAEA,SAAS,YAAY,OAA+B,MAA0C;CAC7F,IAAI,KAAK,IAAI,KAAK,GACjB;CAGD,KAAK,IAAI,KAAK;CACd,MAAM,QAA0B,CAAC;CACjC,KAAK,M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