@bedrock-rbx/ocale 0.3.0 → 0.3.1

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 (51) hide show
  1. package/dist/badges.d.mts +1 -1
  2. package/dist/badges.mjs +3 -3
  3. package/dist/developer-products.d.mts +1 -1
  4. package/dist/developer-products.mjs +4 -4
  5. package/dist/game-passes.d.mts +1 -1
  6. package/dist/game-passes.mjs +4 -4
  7. package/dist/index.d.mts +108 -3
  8. package/dist/index.d.mts.map +1 -1
  9. package/dist/index.mjs +70 -5
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/luau-execution.d.mts +2 -2
  12. package/dist/luau-execution.mjs +4 -4
  13. package/dist/{rate-limit-Df55K34f.mjs → network-error-DmNy_j-u.mjs} +50 -30
  14. package/dist/network-error-DmNy_j-u.mjs.map +1 -0
  15. package/dist/places.d.mts +2 -2
  16. package/dist/places.mjs +5 -5
  17. package/dist/{poll-timeout-DpEY-gAc.mjs → poll-timeout-wrPTnGl_.mjs} +2 -2
  18. package/dist/{poll-timeout-DpEY-gAc.mjs.map → poll-timeout-wrPTnGl_.mjs.map} +1 -1
  19. package/dist/{polling-Bs0GDvEa.d.mts → polling-0t1wQyVY.d.mts} +20 -13
  20. package/dist/polling-0t1wQyVY.d.mts.map +1 -0
  21. package/dist/{polling-helpers-BjFXyaOm.mjs → polling-helpers-CzdT2FS5.mjs} +32 -52
  22. package/dist/polling-helpers-CzdT2FS5.mjs.map +1 -0
  23. package/dist/{price-information-Brs8ebsh.mjs → price-information-Czs5cWR1.mjs} +2 -2
  24. package/dist/{price-information-Brs8ebsh.mjs.map → price-information-Czs5cWR1.mjs.map} +1 -1
  25. package/dist/resource-client-aqk_V4TD.mjs +717 -0
  26. package/dist/resource-client-aqk_V4TD.mjs.map +1 -0
  27. package/dist/{retry-CdpA3z4A.d.mts → retry-Cj5OXCdL.d.mts} +5 -5
  28. package/dist/{retry-CdpA3z4A.d.mts.map → retry-Cj5OXCdL.d.mts.map} +1 -1
  29. package/dist/retry-DIK_T_oF.mjs +1322 -0
  30. package/dist/retry-DIK_T_oF.mjs.map +1 -0
  31. package/dist/storage.d.mts +3 -2
  32. package/dist/storage.d.mts.map +1 -1
  33. package/dist/storage.mjs +3 -3
  34. package/dist/testing.d.mts +9 -17
  35. package/dist/testing.d.mts.map +1 -1
  36. package/dist/testing.mjs +1 -1
  37. package/dist/{types-mhEalVsR.d.mts → types-D_njb3qW.d.mts} +74 -4
  38. package/dist/types-D_njb3qW.d.mts.map +1 -0
  39. package/dist/universes.d.mts +1 -1
  40. package/dist/universes.mjs +4 -4
  41. package/dist/{validation-Cg2lBhpQ.mjs → validation-BwjwOJPD.mjs} +2 -2
  42. package/dist/{validation-Cg2lBhpQ.mjs.map → validation-BwjwOJPD.mjs.map} +1 -1
  43. package/package.json +1 -1
  44. package/dist/polling-Bs0GDvEa.d.mts.map +0 -1
  45. package/dist/polling-helpers-BjFXyaOm.mjs.map +0 -1
  46. package/dist/rate-limit-Df55K34f.mjs.map +0 -1
  47. package/dist/resource-client-DtfDWglY.mjs +0 -1177
  48. package/dist/resource-client-DtfDWglY.mjs.map +0 -1
  49. package/dist/retry-DM2-tlR8.mjs +0 -458
  50. package/dist/retry-DM2-tlR8.mjs.map +0 -1
  51. package/dist/types-mhEalVsR.d.mts.map +0 -1
@@ -1,1177 +0,0 @@
1
- import { i as requestContextOf, n as NetworkError, r as ApiError, t as RateLimitError } from "./rate-limit-Df55K34f.mjs";
2
- import { c as defaultRetryDelay, f as PermissionError, l as mergeConfig, r as IDEMPOTENT_METHOD_DEFAULTS, s as computeRetryWaitMs, u as shouldRetry } from "./retry-DM2-tlR8.mjs";
3
- import { setTimeout } from "node:timers/promises";
4
- //#region src/internal/utils/is-date-time-string.ts
5
- /**
6
- * Narrows `value` to a string that parses to a real {@link Date} via the
7
- * `Date(string)` constructor. Used by resource parsers to gate
8
- * `format: date-time` wire fields before handing them to `new Date(...)`,
9
- * which silently produces an `Invalid Date` for invalid input.
10
- *
11
- * @param value - The unknown wire value to validate.
12
- * @returns `true` when `value` is a string and `new Date(value).getTime()`
13
- * is not `NaN`.
14
- */
15
- function isDateTimeString(value) {
16
- if (typeof value !== "string") return false;
17
- const parsed = new Date(value);
18
- return !Number.isNaN(parsed.getTime());
19
- }
20
- //#endregion
21
- //#region src/internal/utils/is-record.ts
22
- /**
23
- * Narrows `value` to a plain JSON-style record. Excludes arrays, class
24
- * instances, primitives, and `null`/`undefined`. Used by resource
25
- * parsers to gate property access on wire bodies whose shape isn't
26
- * known at compile time.
27
- *
28
- * @param value - The unknown value to narrow.
29
- * @returns `true` when `value` is a plain `[object Object]`.
30
- */
31
- function isRecord(value) {
32
- return Object.prototype.toString.call(value) === "[object Object]";
33
- }
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
81
- //#region src/internal/http/budget-tracker.ts
82
- const MS_PER_SECOND = 1e3;
83
- /**
84
- * Tracks the live rate-limit budget for a single scope. Primed by `observe`
85
- * from response headers and drawn down by `reserve` as requests leave, so
86
- * `waitMs` can pace requests across the window.
87
- *
88
- * Pacing has two regimes. While budget remains, requests are spread evenly over
89
- * the time left in the window (`timeLeft / remaining`), so a burst does not
90
- * spend the whole window's budget up front and then stall. Once the budget is
91
- * spent, requests hold until the window resets. Budget and reset time move
92
- * together as one window, so the tracker is either unprimed or fully primed,
93
- * never half-known.
94
- */
95
- var BudgetTracker = class {
96
- /** Time (ms) the most recent request was allowed out, for spacing. */
97
- #lastAllowedAt = void 0;
98
- #window = void 0;
99
- /**
100
- * Folds a fresh server reading in, replacing any prior window. The latest
101
- * reading wins: observe time is monotonic, so the most recently resolved
102
- * response is the best current estimate. The spacing reference is left
103
- * untouched so a window refresh does not reset pacing mid-stream.
104
- *
105
- * @param sample - Parsed `remaining`/`resetSeconds` from a response.
106
- * @param now - The current time in ms.
107
- */
108
- observe(sample, now) {
109
- this.#window = {
110
- predictedRemaining: sample.remaining,
111
- resetAt: now + sample.resetSeconds * MS_PER_SECOND
112
- };
113
- }
114
- /**
115
- * Accounts for one request leaving at `now`: records the spacing reference
116
- * and decrements the prediction. A no-op on the prediction while unprimed.
117
- *
118
- * @param now - The time the request was allowed out, in ms.
119
- */
120
- reserve(now) {
121
- this.#lastAllowedAt = now;
122
- if (this.#window !== void 0) this.#window = {
123
- ...this.#window,
124
- predictedRemaining: this.#window.predictedRemaining - 1
125
- };
126
- }
127
- /**
128
- * Milliseconds to wait before the next request is allowed.
129
- *
130
- * @param now - The current time in ms.
131
- * @returns `0` when a request may go now (unprimed, or the first paced send);
132
- * the time until reset when the budget is spent; otherwise the time until
133
- * this request's evenly-spaced slot.
134
- */
135
- waitMs(now) {
136
- if (this.#window === void 0) return 0;
137
- const { predictedRemaining, resetAt } = this.#window;
138
- if (predictedRemaining <= 0) return Math.max(0, resetAt - now);
139
- if (this.#lastAllowedAt === void 0) return 0;
140
- const interval = (resetAt - now) / predictedRemaining;
141
- return Math.max(0, this.#lastAllowedAt + interval - now);
142
- }
143
- };
144
- //#endregion
145
- //#region src/internal/http/budget-gate.ts
146
- /**
147
- * Header-primed rate-limit gate shared across a client. Holds one
148
- * {@link BudgetTracker} per {@link BudgetScope}. Before each request the caller
149
- * gates on the request's scope (sleeping if that budget is spent), and after
150
- * each response folds the parsed sample back in, so a later call on the same
151
- * scope can head off a 429 the static per-operation token bucket cannot
152
- * foresee.
153
- *
154
- * Gating is serialized per scope through a promise chain so concurrent
155
- * requests on one scope cannot read the same budget and reserve the same slot;
156
- * each waits for the prior gate's reserve before computing its own.
157
- */
158
- var BudgetGate = class {
159
- #chains = /* @__PURE__ */ new Map();
160
- #sleep;
161
- #trackers = /* @__PURE__ */ new Map();
162
- /**
163
- * Creates a gate bound to an injectable sleep.
164
- *
165
- * @param sleep - Injectable sleep (tests pass a fake clock).
166
- */
167
- constructor(sleep) {
168
- this.#sleep = sleep;
169
- }
170
- /**
171
- * Holds until the scope's budget permits a send, then reserves one slot.
172
- * Runs after the prior gate on the same scope settles, whether it resolved
173
- * or rejected, so one failed attempt cannot poison later gates on the
174
- * scope.
175
- *
176
- * @param scope - The API key and operation to gate on.
177
- */
178
- async gateAsync(scope) {
179
- const key = scopeKey(scope);
180
- const previous = this.#chains.get(key) ?? Promise.resolve();
181
- const runGateAsync = async () => this.#gateOnce(key);
182
- const mine = previous.then(runGateAsync, runGateAsync);
183
- this.#chains.set(key, mine);
184
- await mine;
185
- }
186
- /**
187
- * Folds a response's parsed budget back onto the scope. A `undefined`
188
- * sample (headers absent or non-numeric) is ignored, leaving the scope on
189
- * static pacing.
190
- *
191
- * @param scope - The same scope passed to {@link gateAsync}.
192
- * @param sample - Parsed sample, or `undefined` when none was reported.
193
- */
194
- observe(scope, sample) {
195
- if (sample === void 0) return;
196
- this.#tracker(scopeKey(scope)).observe(sample, Date.now());
197
- }
198
- async #gateOnce(key) {
199
- const tracker = this.#tracker(key);
200
- const waitMs = tracker.waitMs(Date.now());
201
- if (waitMs > 0) await this.#sleep(waitMs);
202
- tracker.reserve(Date.now());
203
- }
204
- #tracker(key) {
205
- const existing = this.#trackers.get(key);
206
- if (existing !== void 0) return existing;
207
- const tracker = new BudgetTracker();
208
- this.#trackers.set(key, tracker);
209
- return tracker;
210
- }
211
- };
212
- /**
213
- * Composes the map key one budget window is tracked under.
214
- *
215
- * @param scope - The API key and operation naming the window.
216
- * @returns The key for the tracker and chain maps.
217
- */
218
- function scopeKey({ apiKey, operationKey }) {
219
- return `${apiKey}::${operationKey}`;
220
- }
221
- //#endregion
222
- //#region src/internal/http/execute.ts
223
- /**
224
- * Retry-aware orchestration loop. Coordinates a single logical request,
225
- * looping over `options.send` until it succeeds, the error is non-retryable,
226
- * or `options.config.maxRetries` is exhausted. Fires observability hooks
227
- * at each transition. Domain- and queue-agnostic: `send` may be any
228
- * callback, including one wrapped by a rate-limit queue.
229
- *
230
- * @param request - The immutable request to send.
231
- * @param options - The transport callback, resolved config, hooks, and sleep.
232
- * @returns The first success, or the final error after retries are exhausted.
233
- */
234
- async function executeWithRetryAsync(request, { config, hooks, send, sleep }) {
235
- async function attemptAsync() {
236
- hooks.onRequest?.(request);
237
- return send(request);
238
- }
239
- let result = await attemptAsync();
240
- for (let retry = 0; retry < config.maxRetries; retry++) {
241
- if (result.success || !shouldRetry(result.err, config)) return result;
242
- const { err } = result;
243
- hooks.onRetry?.(retry + 1, err);
244
- const waitMs = computeRetryWaitMs(err, {
245
- attempt: retry,
246
- retryDelay: config.retryDelay
247
- });
248
- hooks.onRateLimit?.(waitMs);
249
- await sleep(waitMs);
250
- result = await attemptAsync();
251
- }
252
- return result;
253
- }
254
- //#endregion
255
- //#region src/internal/http/rate-limit-sample.ts
256
- /**
257
- * Reduces a comma-separated rate-limit header value (e.g. `"0, 70000"`) to a
258
- * single non-negative integer via `combine`. Tokens are trimmed; blank and
259
- * non-finite tokens (`""`, `"Infinity"`, `"abc"`) are dropped so a stray value
260
- * cannot corrupt the result. Returns `undefined` when the header is absent or
261
- * has no finite tokens.
262
- *
263
- * @param headerValue - The raw header value, or `undefined` if missing.
264
- * @param combine - Pairwise reducer, `Math.min` for remaining, `Math.max` for reset.
265
- * @returns The reduced, floored, clamped value, or `undefined`.
266
- */
267
- function reduceRateLimitTokens(headerValue, combine) {
268
- if (headerValue === void 0) return;
269
- const tokens = headerValue.split(",").map((part) => part.trim()).filter((part) => part !== "").map((part) => Number(part)).filter((value) => Number.isFinite(value));
270
- if (tokens.length === 0) return;
271
- return Math.max(0, Math.floor(tokens.reduce(combine)));
272
- }
273
- /**
274
- * Parses the `x-ratelimit-remaining` and `x-ratelimit-reset` response headers
275
- * into a {@link RateLimitSample}. Each header may carry a comma-separated list
276
- * of per-window values; `remaining` takes the smallest (most constrained) and
277
- * `resetSeconds` takes the largest (longest wait), symmetric to how a 429's
278
- * retry delay is reduced. Returns `undefined` when either header is missing or
279
- * has no finite numeric tokens, so a caller can fall back to static pacing.
280
- *
281
- * @param headers - Response headers with lowercased keys.
282
- * @returns The parsed sample, or `undefined` when the budget cannot be read.
283
- */
284
- function parseRateLimitHeaders(headers) {
285
- const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
286
- return Math.min(a, b);
287
- });
288
- const resetSeconds = reduceRateLimitTokens(headers["x-ratelimit-reset"], (a, b) => {
289
- return Math.max(a, b);
290
- });
291
- if (remaining === void 0 || resetSeconds === void 0) return;
292
- return {
293
- remaining,
294
- resetSeconds
295
- };
296
- }
297
- //#endregion
298
- //#region src/internal/http/rate-limit-observation.ts
299
- /**
300
- * Extracts a {@link RateLimitSample} from a transport result so the budget gate
301
- * can be fed from every attempt. A 2xx carries the budget in its headers; a 429
302
- * carries it on the {@link RateLimitError} (the raw headers are dropped before
303
- * this point). Any other error, or a response that reported no budget, yields
304
- * `undefined` and leaves the gate on static pacing.
305
- *
306
- * @param result - The classified transport result for one attempt.
307
- * @returns The parsed sample, or `undefined` when none was reported.
308
- */
309
- function rateLimitSampleFromResult(result) {
310
- if (result.success) return parseRateLimitHeaders(result.data.headers);
311
- const { err } = result;
312
- if (err instanceof RateLimitError && err.remaining !== void 0) return {
313
- remaining: err.remaining,
314
- resetSeconds: err.retryAfterSeconds
315
- };
316
- }
317
- //#endregion
318
- //#region src/internal/http/rate-limit-queue.ts
319
- /**
320
- * Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every
321
- * call to `acquire` consumes one token; when the bucket is empty the call
322
- * waits until a token regenerates before invoking the task. Tokens refill at
323
- * `maxPerSecond` per second, up to the operation's `burstCapacity`.
324
- *
325
- * Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`
326
- * advances by `waitMs` after every sleep so the algorithm stays correct
327
- * whether or not the injected sleep moves `Date.now()` forward. `#bucketLevel`
328
- * and `#maxBucketLevel` are both ms of drain debt, so the ceiling is the burst
329
- * expressed in that unit: `burstCapacity` refill intervals. Deriving it any
330
- * other way (notably `maxPerSecond * intervalMs`, whose units cancel to a
331
- * constant 1000) starves every operation slower than one request per second.
332
- */
333
- var RateLimitQueue = class {
334
- #hooks;
335
- #intervalMs;
336
- #maxBucketLevel;
337
- #sleep;
338
- #bucketLevel = 0;
339
- #chain = Promise.resolve();
340
- #lastCheck = Date.now();
341
- /**
342
- * Creates a rate-limit queue bound to a single operation.
343
- *
344
- * @param limit - The operation key and its per-second request ceiling.
345
- * @param hooks - Observability callbacks; `onRateLimit` fires when the
346
- * bucket is empty and a sleep is about to start.
347
- * @param sleep - Injectable sleep (tests pass a fake).
348
- */
349
- constructor(limit, hooks, sleep) {
350
- this.#intervalMs = 1e3 / limit.maxPerSecond;
351
- const burstCapacity = limit.burstCapacity ?? Math.max(1, limit.maxPerSecond);
352
- this.#maxBucketLevel = burstCapacity * this.#intervalMs;
353
- this.#hooks = hooks;
354
- this.#sleep = sleep;
355
- }
356
- /**
357
- * Waits for a token — sleeping and firing `hooks.onRateLimit` if the
358
- * bucket is empty — then executes `task`. Concurrent callers are
359
- * serialized at token acquisition; tasks themselves run independently
360
- * once their token is secured.
361
- *
362
- * @param task - The request to run once a token is available.
363
- * @returns The value produced by `task`.
364
- */
365
- async acquireAsync(task) {
366
- const myTurn = this.#chain.then(async () => this.#waitForToken());
367
- this.#chain = myTurn;
368
- await myTurn;
369
- return task();
370
- }
371
- async #waitForToken() {
372
- const now = Math.max(Date.now(), this.#lastCheck);
373
- const drained = Math.max(0, this.#bucketLevel - (now - this.#lastCheck));
374
- this.#lastCheck = now;
375
- if (drained + this.#intervalMs <= this.#maxBucketLevel) {
376
- this.#bucketLevel = drained + this.#intervalMs;
377
- return;
378
- }
379
- const waitMs = drained + this.#intervalMs - this.#maxBucketLevel;
380
- this.#hooks.onRateLimit?.(waitMs);
381
- await this.#sleep(waitMs);
382
- this.#bucketLevel = this.#maxBucketLevel;
383
- this.#lastCheck = now + waitMs;
384
- }
385
- };
386
- //#endregion
387
- //#region src/internal/utils/try-catch.ts
388
- /**
389
- * Wraps a promise into a {@link Result}, catching rejections.
390
- *
391
- * @template T - The resolved value type.
392
- * @param promise - The promise to wrap.
393
- * @returns A Result containing the resolved value or the rejection error.
394
- */
395
- async function tryCatchAsync(promise) {
396
- try {
397
- return {
398
- data: await promise,
399
- success: true
400
- };
401
- } catch (err) {
402
- return {
403
- err: err instanceof Error ? err : new Error(String(err)),
404
- success: false
405
- };
406
- }
407
- }
408
- //#endregion
409
- //#region src/internal/http/diagnostics.ts
410
- const MAX_DETAIL_LENGTH = 500;
411
- const CONTENT_TYPE_HEADER$1 = "content-type";
412
- const DIAGNOSTIC_HEADER_ALLOWLIST = new Set([
413
- "cf-ray",
414
- "server",
415
- "via",
416
- "x-request-id"
417
- ]);
418
- const DIAGNOSTIC_HEADER_PREFIX = "x-roblox-";
419
- const TITLE_OPEN_PATTERN = /<title[^>]*>/i;
420
- const H1_OPEN_PATTERN = /<h1[^>]*>/i;
421
- const TAG_PATTERN = /<[^<>]*>/g;
422
- const WHITESPACE_PATTERN = /\s+/g;
423
- /**
424
- * Extracts a one-line human summary from an HTML gateway error page, or returns
425
- * `undefined` when the body is not such a page. A load balancer (HAProxy-style)
426
- * rejects a request before it reaches Open Cloud and answers with an HTML page,
427
- * not a JSON Open Cloud error; dumping that HTML whole is noise. The body is
428
- * treated as HTML when the content-type is `text/html` or the trimmed body is
429
- * tag-led (`<html`/`<!doctype html`), and the summary is taken from the
430
- * `<title>` (falling back to the first `<h1>`), tags stripped and whitespace
431
- * collapsed.
432
- *
433
- * @param contentType - The response `content-type` header, if present.
434
- * @param rawText - The raw response body text.
435
- * @returns The extracted summary, or `undefined` when the body is not an HTML
436
- * gateway page (or carries no title/h1 text).
437
- */
438
- function extractGatewaySummary(contentType, rawText) {
439
- if (!isHtmlBody(contentType, rawText)) return;
440
- return firstTagText(rawText, {
441
- close: "</title>",
442
- open: TITLE_OPEN_PATTERN
443
- }) ?? firstTagText(rawText, {
444
- close: "</h1>",
445
- open: H1_OPEN_PATTERN
446
- });
447
- }
448
- /**
449
- * Filters a lowercased header record down to the diagnostic allowlist: a few
450
- * named escalation headers plus any `x-roblox-*` header. Keeps errors light and
451
- * avoids retaining anything sensitive from the full response header set.
452
- *
453
- * @param headers - The full header record (lowercased keys).
454
- * @returns A record containing only the allowlisted headers that were present.
455
- */
456
- function pickDiagnosticHeaders(headers) {
457
- const picked = {};
458
- for (const [name, value] of Object.entries(headers)) if (DIAGNOSTIC_HEADER_ALLOWLIST.has(name) || name.startsWith(DIAGNOSTIC_HEADER_PREFIX)) picked[name] = value;
459
- return picked;
460
- }
461
- /**
462
- * Converts a `Headers` object to a plain record with lowercased keys.
463
- *
464
- * @param headers - The `Headers` instance to convert.
465
- * @returns A record mapping lowercased header names to their values.
466
- */
467
- function headersToRecord(headers) {
468
- return Object.fromEntries(headers);
469
- }
470
- /**
471
- * Projects a read body to the detail carried on an error: the parsed JSON when
472
- * it parsed, otherwise the raw text truncated to {@link MAX_DETAIL_LENGTH}.
473
- *
474
- * @param text - The raw response body text.
475
- * @param parsed - The best-effort parse result from the transport's body read.
476
- * @returns The parsed body, or the truncated raw text on a parse failure.
477
- */
478
- function bodyDetail(text, parsed) {
479
- return parsed.success ? parsed.data : text.slice(0, MAX_DETAIL_LENGTH);
480
- }
481
- /**
482
- * Builds the error for a 2xx response whose body could not be parsed as JSON,
483
- * preserving the parse `cause`, the (truncated) raw body, the declared
484
- * content-type, and the request that produced it so the failure can be
485
- * diagnosed after the fact.
486
- *
487
- * The received length is on the message rather than only on the error, because
488
- * `details` retains just the first {@link MAX_DETAIL_LENGTH} characters: for a
489
- * body that stopped mid-token the head says nothing and the length says
490
- * everything. A `SyntaxError` position equal to this number is a body the edge
491
- * cut short, not one the API mis-serialized.
492
- *
493
- * @param args - The Response, raw body text, request context, and underlying
494
- * parse error.
495
- * @returns An ApiError carrying the diagnostic context.
496
- */
497
- function parseFailureError({ cause, context, response, text }) {
498
- return new ApiError(`Failed to parse response body (content-type: ${response.headers.get(CONTENT_TYPE_HEADER$1) ?? "unknown"}, ${String(text.length)} chars read)`, {
499
- cause,
500
- details: text.slice(0, MAX_DETAIL_LENGTH),
501
- elapsedMs: context.elapsedMs,
502
- method: context.method,
503
- responseHeaders: pickDiagnosticHeaders(headersToRecord(response.headers)),
504
- statusCode: response.status,
505
- unparsedBodyLength: text.length,
506
- url: context.url
507
- });
508
- }
509
- function firstTagText(html, tag) {
510
- const open = tag.open.exec(html);
511
- if (open === null) return;
512
- const start = open.index + open[0].length;
513
- const end = html.toLowerCase().indexOf(tag.close, start);
514
- if (end === -1) return;
515
- const text = html.slice(start, end).replace(TAG_PATTERN, " ").replace(WHITESPACE_PATTERN, " ").trim();
516
- return text === "" ? void 0 : text;
517
- }
518
- function isHtmlBody(contentType, rawText) {
519
- if (contentType?.toLowerCase().includes("text/html") === true) return true;
520
- const head = rawText.trimStart().toLowerCase();
521
- return head.startsWith("<html") || head.startsWith("<!doctype html");
522
- }
523
- //#endregion
524
- //#region src/internal/http/http1-dispatcher.ts
525
- /**
526
- * Well-known globals under which undici publishes its global dispatcher,
527
- * newest first. The suffix is undici's own contract version: it moved from
528
- * `.1` to `.2` in undici 8, so a future major may move it again. Both are
529
- * probed, and {@link createHttp1Dispatcher} degrades to `undefined` when
530
- * neither is present — which is also the Bun path, since Bun's `fetch` is not
531
- * undici-backed and never publishes these.
532
- */
533
- const GLOBAL_DISPATCHER_KEYS = Object.freeze(["undici.globalDispatcher.2", "undici.globalDispatcher.1"]);
534
- /**
535
- * Narrow a value read off the global dispatcher to something
536
- * `Reflect.construct` accepts. Exported so the narrowing is unit-testable: at
537
- * the call site every rejected shape funnels into the same `undefined`, which
538
- * makes the branch unobservable from `createHttp1Dispatcher` alone.
539
- *
540
- * @param value - The candidate `constructor` read off the global dispatcher.
541
- * @returns Whether the value can be constructed.
542
- */
543
- function isAgentConstructor(value) {
544
- return typeof value === "function";
545
- }
546
- /**
547
- * Builds a request dispatcher that negotiates HTTP/1.1 only, by reusing the
548
- * class of the runtime's own global dispatcher.
549
- *
550
- * From Node 26 (undici 8) `fetch` offers h2 in ALPN, which defeats the
551
- * `connection: close` an upload sets: `connection` is a connection-specific
552
- * header, so an h2 transport drops it before the wire and pools every upload
553
- * onto one multiplexed session. One session death then fails every upload in
554
- * flight. Constructing the same agent with `allowH2: false` restores the
555
- * per-upload connection the directive was written for.
556
- *
557
- * There is no standard `fetch` option for this, so the agent is reached
558
- * through undici's versioned global symbol and its class rather than through
559
- * an import — which keeps the package dependency-free. The contract is
560
- * internal, so every step is guarded: an absent symbol, a non-constructible
561
- * value, or a constructor that throws all yield `undefined`, and the caller
562
- * sends the request unmodified.
563
- *
564
- * @param scope - The object to read the global dispatcher from. Defaults to
565
- * `globalThis`; injectable so tests need not mutate the real global.
566
- * @returns A dispatcher restricted to HTTP/1.1, or `undefined` when this
567
- * runtime offers no reachable one.
568
- */
569
- function createHttp1Dispatcher(scope = globalThis) {
570
- for (const key of GLOBAL_DISPATCHER_KEYS) {
571
- const dispatcher = constructHttp1(Reflect.get(scope, Symbol.for(key)));
572
- if (dispatcher !== void 0) return dispatcher;
573
- }
574
- }
575
- /**
576
- * Reconstructs `agent`'s class with h2 disabled.
577
- *
578
- * Most ways `agent` can be wrong already throw: `Reflect.get` rejects a
579
- * primitive, `null`, and an absent key, and `Reflect.construct` rejects a
580
- * `constructor` that is not one, or that refuses the options. One shape gets
581
- * through — a plain object, whose `constructor` is `Object`, so constructing
582
- * it hands back the options bag. The result is therefore checked against the
583
- * one part of undici's surface that is public and stable: a `Dispatcher`
584
- * exposes `dispatch`.
585
- *
586
- * @param agent - The candidate global dispatcher; any value, since it comes
587
- * from an undocumented global.
588
- * @returns The new dispatcher, or `undefined` when `agent` is not an object
589
- * whose constructor accepts undici's agent options.
590
- */
591
- function constructHttp1(agent) {
592
- try {
593
- const agentClass = Reflect.get(agent, "constructor");
594
- if (!isAgentConstructor(agentClass)) return;
595
- const dispatcher = Reflect.construct(agentClass, [{ allowH2: false }]);
596
- return typeof Reflect.get(dispatcher, "dispatch") === "function" ? dispatcher : void 0;
597
- } catch {
598
- return;
599
- }
600
- }
601
- //#endregion
602
- //#region src/internal/http/upload-request.ts
603
- /**
604
- * Reports whether a request is an upload: its body is `FormData`
605
- * (multipart) or `Uint8Array` (raw binary). Upload latency is
606
- * bandwidth-bound rather than compute-bound, so the SDK applies no default
607
- * request timeout to these requests; a sensible wall-clock budget depends on
608
- * payload size and link quality the SDK cannot know.
609
- *
610
- * @param request - The built request to classify.
611
- * @returns `true` when the body is `FormData` or `Uint8Array`.
612
- */
613
- function isUploadRequest(request) {
614
- return request.body instanceof FormData || request.body instanceof Uint8Array;
615
- }
616
- //#endregion
617
- //#region src/internal/http/fetch-client.ts
618
- const CONTENT_TYPE_HEADER = "content-type";
619
- const CONNECTION_HEADER = "connection";
620
- /**
621
- * Permissively extracts a machine-readable error code from a response body.
622
- *
623
- * Three shapes are checked, in precedence order. Modern Open Cloud responses
624
- * use `{ errorCode: string, message: string }`; Open Cloud v2 endpoints carry
625
- * the canonical status in `error` (`{ error: "NOT_FOUND", message: string }`);
626
- * the legacy game-internationalization endpoints use
627
- * `{ errors: [{ code: number, message: string }, ...] }`. Numeric legacy codes
628
- * are returned as strings so callers see one consistent type.
629
- *
630
- * `error` is read only when it holds a string. A Google-style nested envelope
631
- * (`{ error: { code, message, status } }`) puts an object there, and coercing
632
- * that to a string would hand callers `"[object Object]"` as a status.
633
- *
634
- * @param body - The parsed response body (unknown shape).
635
- * @returns The error code if present, otherwise `undefined`.
636
- */
637
- function extractErrorCode(body) {
638
- if (body === null || typeof body !== "object") return;
639
- const errorCode = Reflect.get(body, "errorCode");
640
- if (typeof errorCode === "string") return errorCode;
641
- const v2Error = Reflect.get(body, "error");
642
- if (typeof v2Error === "string") return v2Error;
643
- return extractLegacyCode(body);
644
- }
645
- /**
646
- * Permissively extracts a human-readable error message from a response body.
647
- *
648
- * Modern Open Cloud responses expose `message` at the top level; the legacy
649
- * game-internationalization endpoints nest it under `errors[0].message`.
650
- *
651
- * @param body - The parsed response body (unknown shape).
652
- * @returns The message if present, otherwise `undefined`.
653
- */
654
- function extractErrorMessage(body) {
655
- if (body === null || typeof body !== "object") return;
656
- const message = Reflect.get(body, "message");
657
- if (typeof message === "string") return message;
658
- return extractLegacyMessage(body);
659
- }
660
- /**
661
- * Parses the `x-ratelimit-reset` header value into seconds. On a 429 the
662
- * header is a comma-separated list of per-window reset times (e.g. `"22, 0"`,
663
- * one entry per rate-limit window); the largest value is the longest-resetting
664
- * window and the only safe wait that won't retry into a still-exhausted
665
- * window. A single value is treated as a one-element list.
666
- *
667
- * @param headerValue - The raw header value, or `undefined` if missing.
668
- * @returns The number of seconds to wait, or 0 if missing/invalid.
669
- */
670
- function parseRetryAfterSeconds(headerValue) {
671
- return reduceRateLimitTokens(headerValue, (a, b) => Math.max(a, b)) ?? 0;
672
- }
673
- /**
674
- * Joins the base URL from config with the relative path from the request.
675
- *
676
- * @param request - The HTTP request containing the relative URL.
677
- * @param config - The request config containing the base URL.
678
- * @returns The fully-qualified URL string.
679
- */
680
- function buildUrl(request, config) {
681
- return `${config.baseUrl.endsWith("/") ? config.baseUrl.slice(0, -1) : config.baseUrl}${request.url}`;
682
- }
683
- /**
684
- * Constructs the `RequestInit` options for a `fetch` call.
685
- *
686
- * @param request - The HTTP request to build options for.
687
- * @param config - The request config containing API key and timeout.
688
- * @returns A `RequestInit` object ready for `fetch`.
689
- */
690
- function buildFetchOptions(request, config) {
691
- const headers = new Headers({ "x-api-key": config.apiKey });
692
- const options = {
693
- headers,
694
- method: request.method
695
- };
696
- if (request.body instanceof FormData) options.body = request.body;
697
- else if (request.body instanceof Uint8Array) {
698
- headers.set(CONTENT_TYPE_HEADER, "application/octet-stream");
699
- options.body = request.body;
700
- } else if (request.body !== void 0) {
701
- headers.set(CONTENT_TYPE_HEADER, "application/json");
702
- options.body = JSON.stringify(request.body);
703
- }
704
- applyRequestHeaders(headers, request);
705
- if (config.timeout !== void 0) options.signal = AbortSignal.timeout(config.timeout);
706
- return options;
707
- }
708
- /**
709
- * Creates an {@link HttpClient} backed by the Fetch API.
710
- *
711
- * @param fetchFunc - The fetch implementation to use. Defaults to `globalThis.fetch`.
712
- * @param seams - Injectable clock and dispatcher factory, so tests need not
713
- * depend on wall-clock time or on the runtime's global dispatcher.
714
- * @returns An HttpClient that classifies responses into typed Results.
715
- */
716
- function createFetchHttpClient(fetchFunc = fetch, { createDispatcher = createHttp1Dispatcher, now = Date.now } = {}) {
717
- const dispatcherFor = createUploadDispatcherCache(createDispatcher);
718
- return { async request(httpRequest, config) {
719
- const url = buildUrl(httpRequest, config);
720
- const options = buildFetchOptions(httpRequest, config);
721
- options.dispatcher = dispatcherFor(httpRequest);
722
- const target = {
723
- method: httpRequest.method,
724
- url
725
- };
726
- const { elapsedMs, fetchResult } = await timedFetchAsync(now, async () => {
727
- return fetchFunc(url, options);
728
- });
729
- if (!fetchResult.success) return {
730
- err: networkError(fetchResult.err, target),
731
- success: false
732
- };
733
- const context = {
734
- elapsedMs,
735
- method: target.method,
736
- url: target.url
737
- };
738
- const classified = await tryCatchAsync(classifyResponseAsync(fetchResult.data, context));
739
- if (!classified.success) return {
740
- err: networkError(classified.err, target),
741
- success: false
742
- };
743
- return classified.data;
744
- } };
745
- }
746
- function readLegacyErrorEntry(body) {
747
- const errors = Reflect.get(body, "errors");
748
- if (!Array.isArray(errors)) return;
749
- const [first] = errors;
750
- if (typeof first !== "object" || first === null) return;
751
- return first;
752
- }
753
- function extractLegacyCode(body) {
754
- const first = readLegacyErrorEntry(body);
755
- if (first === void 0) return;
756
- const code = Reflect.get(first, "code");
757
- if (typeof code === "string") return code;
758
- return typeof code === "number" ? String(code) : void 0;
759
- }
760
- function extractLegacyMessage(body) {
761
- const first = readLegacyErrorEntry(body);
762
- if (first === void 0) return;
763
- const message = Reflect.get(first, "message");
764
- return typeof message === "string" ? message : void 0;
765
- }
766
- /**
767
- * Merges the request's own headers onto the transport's, then applies the
768
- * transport-owned connection directive. `x-api-key` is skipped so a request
769
- * cannot override the configured credential, and the upload directive is set
770
- * last so a request header cannot silently re-enable pooling for an upload.
771
- *
772
- * @param headers - The headers being built for the fetch call. Mutated.
773
- * @param request - The request whose headers and body shape drive the merge.
774
- */
775
- function applyRequestHeaders(headers, request) {
776
- const requestHeaders = request.headers ?? {};
777
- for (const [name, value] of Object.entries(requestHeaders)) {
778
- if (name.toLowerCase() === "x-api-key") continue;
779
- headers.set(name, value);
780
- }
781
- if (isUploadRequest(request)) headers.set(CONNECTION_HEADER, "close");
782
- }
783
- /**
784
- * Wraps a dispatcher factory in the caching policy uploads need.
785
- *
786
- * Resolution happens on the first upload rather than at construction: undici
787
- * publishes its global dispatcher lazily, so before a process's first `fetch`
788
- * there is nothing to read. A resolved dispatcher is kept, and an unresolved
789
- * one is retried on the next upload — so a runtime that publishes late is
790
- * still picked up, and the first request of a process, which has no pooled
791
- * connection to lose, is safe either way.
792
- *
793
- * @param createDispatcher - Builds the HTTP/1.1-only transport.
794
- * @returns A function yielding the dispatcher for a request, or `undefined`
795
- * when the request is not an upload or no dispatcher is available.
796
- */
797
- function createUploadDispatcherCache(createDispatcher) {
798
- let cached;
799
- return (request) => {
800
- if (!isUploadRequest(request)) return;
801
- cached ??= createDispatcher();
802
- return cached;
803
- };
804
- }
805
- /**
806
- * Runs `send` and reports both its Result and how long it was in flight,
807
- * measured with `now`. Isolated so the timing start need not sit in the request
808
- * body ahead of the transport-failure early return.
809
- *
810
- * @param now - The clock used to bound the call.
811
- * @param send - A thunk that issues the fetch.
812
- * @returns The fetch Result and the elapsed milliseconds.
813
- */
814
- async function timedFetchAsync(now, send) {
815
- const start = now();
816
- const fetchResult = await tryCatchAsync(send());
817
- return {
818
- elapsedMs: Math.max(0, now() - start),
819
- fetchResult
820
- };
821
- }
822
- function networkError(cause, target) {
823
- return new NetworkError("Network request failed", {
824
- cause,
825
- method: target.method,
826
- url: target.url
827
- });
828
- }
829
- function formatApiErrorMessage({ code, message, status }) {
830
- const base = `HTTP ${status}`;
831
- if (message === void 0 && code === void 0) return base;
832
- if (message === void 0) return `${base} (code ${code})`;
833
- if (code === void 0) return `${base}: ${message}`;
834
- return `${base}: ${message} (code ${code})`;
835
- }
836
- function createApiError(args) {
837
- const { context, rawText, response } = args;
838
- const { status } = response;
839
- const headers = headersToRecord(response.headers);
840
- const requestContext = {
841
- elapsedMs: context.elapsedMs,
842
- method: context.method,
843
- responseHeaders: pickDiagnosticHeaders(headers),
844
- statusCode: status,
845
- url: context.url
846
- };
847
- const gatewaySummary = extractGatewaySummary(headers[CONTENT_TYPE_HEADER], rawText);
848
- if (gatewaySummary !== void 0) return new ApiError(`HTTP ${status}`, {
849
- ...requestContext,
850
- gatewaySummary
851
- });
852
- const body = bodyDetail(rawText, args.parsed);
853
- const code = extractErrorCode(body);
854
- return new ApiError(formatApiErrorMessage({
855
- code,
856
- message: extractErrorMessage(body),
857
- status
858
- }), {
859
- ...requestContext,
860
- code,
861
- details: body
862
- });
863
- }
864
- /**
865
- * Parses response text as JSON, returning the underlying `SyntaxError` on
866
- * failure rather than throwing. The synchronous sibling of {@link
867
- * tryCatchAsync}.
868
- *
869
- * @param text - The raw response body text.
870
- * @returns A Result wrapping the parsed value, or the parse error.
871
- */
872
- function parseJson(text) {
873
- try {
874
- return {
875
- data: JSON.parse(text),
876
- success: true
877
- };
878
- } catch (err) {
879
- return {
880
- err: err instanceof Error ? err : new Error(String(err)),
881
- success: false
882
- };
883
- }
884
- }
885
- /**
886
- * Reads a response body once and parses it best-effort: an empty body is a
887
- * successful `undefined`, otherwise the JSON parse result (which carries the
888
- * `SyntaxError` on failure). Returns the raw `text` alongside so callers that
889
- * need the original bytes (parse-failure diagnostics) do not re-read the
890
- * consumed stream.
891
- *
892
- * @param response - The Response whose body to read.
893
- * @returns The parse result and the raw text.
894
- */
895
- async function readResponseBodyAsync(response) {
896
- const text = await response.text();
897
- return {
898
- parsed: text === "" ? {
899
- data: void 0,
900
- success: true
901
- } : parseJson(text),
902
- text
903
- };
904
- }
905
- async function createRateLimitErrorAsync(response) {
906
- const headers = headersToRecord(response.headers);
907
- const { parsed, text } = await readResponseBodyAsync(response);
908
- return new RateLimitError("Rate limited", {
909
- details: bodyDetail(text, parsed),
910
- remaining: reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
911
- return Math.min(a, b);
912
- }),
913
- retryAfterSeconds: parseRetryAfterSeconds(headers["x-ratelimit-reset"]),
914
- statusCode: response.status
915
- });
916
- }
917
- /**
918
- * Classifies a fetch `Response` into a typed `Result`.
919
- *
920
- * The body is read once and parsed best-effort. Error responses (status >= 300)
921
- * never require valid JSON: an error body that is not valid JSON degrades to a
922
- * status-based {@link ApiError} carrying the raw text, and an HTML gateway page
923
- * is summarized rather than dumped. A parse failure is only fatal on a 2xx,
924
- * where a parseable body is part of the contract.
925
- *
926
- * @param response - The raw fetch Response to classify.
927
- * @param context - The request context (method, url, elapsed time) threaded
928
- * onto every {@link ApiError} built here, whether for an error response or
929
- * for a 2xx whose body would not parse.
930
- * @returns A Result containing an HttpResponse on success or an OpenCloudError on failure.
931
- */
932
- async function classifyResponseAsync(response, context) {
933
- if (response.status === 429) return {
934
- err: await createRateLimitErrorAsync(response),
935
- success: false
936
- };
937
- const { parsed, text } = await readResponseBodyAsync(response);
938
- if (response.status >= 300) return {
939
- err: createApiError({
940
- context,
941
- parsed,
942
- rawText: text,
943
- response
944
- }),
945
- success: false
946
- };
947
- if (!parsed.success) return {
948
- err: parseFailureError({
949
- cause: parsed.err,
950
- context,
951
- response,
952
- text
953
- }),
954
- success: false
955
- };
956
- return {
957
- data: {
958
- body: parsed.data,
959
- headers: headersToRecord(response.headers),
960
- status: response.status
961
- },
962
- success: true
963
- };
964
- }
965
- //#endregion
966
- //#region src/internal/http/resolve-dependencies.ts
967
- /**
968
- * Resolves the concrete HTTP client and sleep implementation a resource
969
- * client should use. Falls back to the fetch-backed HTTP client and the
970
- * default `setTimeout`-based sleep when the caller omits the test seams.
971
- *
972
- * Extracted so resource client constructors can keep their dependency
973
- * resolution logic in a single, unit-testable place; this makes the
974
- * default branches easy to cover without stubbing globals like `fetch`.
975
- *
976
- * @param options - Optional {@link HttpClient} and {@link SleepFunc} test seams.
977
- * @returns A {@link ResolvedDependencies} with defaults applied.
978
- */
979
- function resolveDependencies(options) {
980
- return {
981
- httpClient: options.httpClient ?? createFetchHttpClient(),
982
- sleep: options.sleep ?? setTimeout
983
- };
984
- }
985
- //#endregion
986
- //#region src/internal/resource-client.ts
987
- /**
988
- * Wraps an infallible request build as a {@link Result}-returning
989
- * `buildRequest` callback compatible with {@link ResourceMethodSpec}.
990
- * Use from a resource client whose builder cannot fail; resource clients
991
- * with local validation should construct the {@link Result} directly.
992
- *
993
- * @param request - The pre-built {@link HttpRequest}.
994
- * @returns A success Result wrapping the request.
995
- */
996
- function okRequest(request) {
997
- return {
998
- data: request,
999
- success: true
1000
- };
1001
- }
1002
- /**
1003
- * A {@link ResourceMethodSpec.parse} implementation for endpoints that return
1004
- * no business payload on success (such as `DELETE` and reorder operations).
1005
- * Surfaces `undefined` data and never inspects the response body.
1006
- *
1007
- * @returns A success Result with `undefined` data.
1008
- */
1009
- function parseEmptyResponse() {
1010
- return {
1011
- data: void 0,
1012
- success: true
1013
- };
1014
- }
1015
- const CLIENT_DEFAULTS = Object.freeze({
1016
- baseUrl: "https://apis.roblox.com",
1017
- maxRetries: 3,
1018
- retryableStatuses: IDEMPOTENT_METHOD_DEFAULTS.retryableStatuses,
1019
- retryableTransportCodes: IDEMPOTENT_METHOD_DEFAULTS.retryableTransportCodes,
1020
- retryDelay: defaultRetryDelay,
1021
- timeout: 3e4
1022
- });
1023
- /**
1024
- * Internal orchestrator shared by every Open Cloud resource client. Holds
1025
- * the frozen client config, observability hooks, injected HTTP client and
1026
- * sleep, and the per-effective-key rate-limit queue registry. Resource
1027
- * classes compose one instance and dispatch every public method through
1028
- * {@link ResourceClient.executeAsync} with a per-method {@link ResourceMethodSpec}.
1029
- * Not exported from any package subpath; reachable only via sibling
1030
- * `src/resources/**` modules in this package.
1031
- */
1032
- var ResourceClient = class {
1033
- #budgets;
1034
- #config;
1035
- #hooks;
1036
- #httpClient;
1037
- #queues = /* @__PURE__ */ new Map();
1038
- #sleep;
1039
- /**
1040
- * Creates a new {@link ResourceClient}. Resolves the injected HTTP
1041
- * client and sleep (defaulting to fetch + `setTimeout`) and freezes the
1042
- * merged client config so subsequent calls cannot mutate it.
1043
- *
1044
- * @param options - Client-level configuration including the API key
1045
- * and optional construction-time test seams.
1046
- */
1047
- constructor({ apiKey, hooks, httpClient, sleep, ...overrides }) {
1048
- const resolved = resolveDependencies({
1049
- httpClient,
1050
- sleep
1051
- });
1052
- this.#httpClient = resolved.httpClient;
1053
- this.#sleep = resolved.sleep;
1054
- this.#budgets = new BudgetGate(this.#sleep);
1055
- this.#hooks = hooks ?? {};
1056
- this.#config = Object.freeze({
1057
- ...CLIENT_DEFAULTS,
1058
- apiKey,
1059
- ...overrides
1060
- });
1061
- }
1062
- /**
1063
- * Dispatches a single resource-method call. Merges the frozen client
1064
- * config with the method's `methodDefaults` and the caller's optional
1065
- * per-request `options`, routes through the effective-apiKey rate-limit
1066
- * queue, runs the retry loop, and finally parses the response with the
1067
- * spec's parser.
1068
- *
1069
- * @param call - The per-method spec, resource-specific parameters, and
1070
- * optional per-request overrides.
1071
- * @returns The parsed success payload or the {@link OpenCloudError} that
1072
- * caused the request to fail. Never throws.
1073
- */
1074
- async executeAsync({ options, parameters, spec }) {
1075
- const merged = mergeConfig(this.#config, {
1076
- methodDefaults: spec.methodDefaults,
1077
- methodKind: spec.methodKind,
1078
- requestOptions: options ?? {}
1079
- });
1080
- const requestResult = spec.buildRequest(parameters);
1081
- if (!requestResult.success) return requestResult;
1082
- const requestConfig = buildRequestConfig({
1083
- merged,
1084
- options,
1085
- request: requestResult.data
1086
- });
1087
- const httpResult = await this.#getQueue(merged.apiKey, spec.operationLimit).acquireAsync(async () => {
1088
- return executeWithRetryAsync(requestResult.data, {
1089
- config: merged,
1090
- hooks: this.#hooks,
1091
- send: this.#gatedSend({
1092
- apiKey: merged.apiKey,
1093
- operationKey: spec.operationLimit.operationKey
1094
- }, requestConfig),
1095
- sleep: this.#sleep
1096
- });
1097
- });
1098
- if (!httpResult.success) return {
1099
- err: enrichPermissionError(httpResult.err, spec),
1100
- success: false
1101
- };
1102
- return spec.parse(httpResult.data);
1103
- }
1104
- /**
1105
- * Returns the sleep function used by this client instance.
1106
- *
1107
- * @returns The sleep function injected at construction time.
1108
- */
1109
- get sleep() {
1110
- return this.#sleep;
1111
- }
1112
- /**
1113
- * Builds the transport callback for one logical call, wrapping the HTTP
1114
- * client with the budget gate: each attempt waits on the scope's budget
1115
- * before sending, then folds the response's reported budget back in so the
1116
- * next attempt (or a later call on the same scope) can head off a 429.
1117
- *
1118
- * @param scope - The API key and operation whose bucket to gate on.
1119
- * @param requestConfig - The resolved per-request transport config.
1120
- * @returns A send callback for {@link executeWithRetryAsync}.
1121
- */
1122
- #gatedSend(scope, requestConfig) {
1123
- return async (toSend) => {
1124
- await this.#budgets.gateAsync(scope);
1125
- const sendResult = await this.#httpClient.request(toSend, requestConfig);
1126
- this.#budgets.observe(scope, rateLimitSampleFromResult(sendResult));
1127
- return sendResult;
1128
- };
1129
- }
1130
- #getQueue(apiKey, limit) {
1131
- const key = `${apiKey}::${limit.operationKey}`;
1132
- const existing = this.#queues.get(key);
1133
- if (existing !== void 0) return existing;
1134
- const queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);
1135
- this.#queues.set(key, queue);
1136
- return queue;
1137
- }
1138
- };
1139
- /**
1140
- * Resolves the per-request {@link RequestConfig}. Upload requests
1141
- * ({@link isUploadRequest}) carry no default timeout: a multi-megabyte place
1142
- * file over a slow link is bandwidth-bound, so a client-side deadline only
1143
- * fires spuriously. An explicit `options.timeout` still applies to any
1144
- * request; every non-upload request keeps the merged default.
1145
- *
1146
- * @param inputs - The merged config, the built request, and per-request overrides.
1147
- * @returns The config to hand to the transport, with `timeout` omitted when
1148
- * no client-side deadline should apply.
1149
- */
1150
- function buildRequestConfig({ merged, options, request }) {
1151
- const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
1152
- return {
1153
- apiKey: merged.apiKey,
1154
- baseUrl: merged.baseUrl,
1155
- ...shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }
1156
- };
1157
- }
1158
- function enrichPermissionError(err, spec) {
1159
- if (spec.requiredScopes === void 0) return err;
1160
- if (err instanceof PermissionError) return err;
1161
- if (!(err instanceof ApiError)) return err;
1162
- if (err.statusCode !== 401 && err.statusCode !== 403) return err;
1163
- if (err.gatewaySummary !== void 0) return err;
1164
- return new PermissionError(err.message, {
1165
- ...requestContextOf(err),
1166
- cause: err.cause,
1167
- code: err.code,
1168
- details: err.details,
1169
- operationKey: spec.operationLimit.operationKey,
1170
- requiredScopes: spec.requiredScopes,
1171
- statusCode: err.statusCode
1172
- });
1173
- }
1174
- //#endregion
1175
- export { isRecord as a, toJsonDetails as i, okRequest as n, isDateTimeString as o, parseEmptyResponse as r, ResourceClient as t };
1176
-
1177
- //# sourceMappingURL=resource-client-DtfDWglY.mjs.map