@bedrock-rbx/ocale 0.3.4 → 0.5.0

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 (95) hide show
  1. package/README.md +10 -5
  2. package/dist/assets.d.mts +64 -0
  3. package/dist/assets.d.mts.map +1 -0
  4. package/dist/assets.mjs +301 -0
  5. package/dist/assets.mjs.map +1 -0
  6. package/dist/badge-insufficient-funds-BLFvQZt1.mjs +91 -0
  7. package/dist/badge-insufficient-funds-BLFvQZt1.mjs.map +1 -0
  8. package/dist/badges.d.mts +359 -196
  9. package/dist/badges.d.mts.map +1 -1
  10. package/dist/badges.mjs +493 -59
  11. package/dist/badges.mjs.map +1 -1
  12. package/dist/capacity-admission-Ce2V9QNb.d.mts +347 -0
  13. package/dist/capacity-admission-Ce2V9QNb.d.mts.map +1 -0
  14. package/dist/{data.generated-B2ceLfSn.d.mts → data.generated-B4Fztv_7.d.mts} +23 -25
  15. package/dist/data.generated-B4Fztv_7.d.mts.map +1 -0
  16. package/dist/developer-products.d.mts +207 -194
  17. package/dist/developer-products.d.mts.map +1 -1
  18. package/dist/developer-products.mjs +125 -39
  19. package/dist/developer-products.mjs.map +1 -1
  20. package/dist/game-passes.d.mts +206 -211
  21. package/dist/game-passes.d.mts.map +1 -1
  22. package/dist/game-passes.mjs +35 -36
  23. package/dist/game-passes.mjs.map +1 -1
  24. package/dist/index.d.mts +947 -366
  25. package/dist/index.d.mts.map +1 -1
  26. package/dist/index.mjs +324 -12
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/is-date-time-string-C91G44SI.mjs +19 -0
  29. package/dist/is-date-time-string-C91G44SI.mjs.map +1 -0
  30. package/dist/locales.d.mts +28 -2
  31. package/dist/locales.d.mts.map +1 -0
  32. package/dist/locales.mjs +24 -3
  33. package/dist/locales.mjs.map +1 -1
  34. package/dist/luau-execution.d.mts +154 -157
  35. package/dist/luau-execution.d.mts.map +1 -1
  36. package/dist/luau-execution.mjs +15 -16
  37. package/dist/luau-execution.mjs.map +1 -1
  38. package/dist/{network-error-DR9FX5hb.mjs → network-error-P4An7nUB.mjs} +48 -14
  39. package/dist/network-error-P4An7nUB.mjs.map +1 -0
  40. package/dist/places.d.mts +258 -186
  41. package/dist/places.d.mts.map +1 -1
  42. package/dist/places.mjs +187 -35
  43. package/dist/places.mjs.map +1 -1
  44. package/dist/{poll-timeout-3PXLsabj.mjs → poll-timeout-BCxgN97O.mjs} +4 -6
  45. package/dist/{poll-timeout-3PXLsabj.mjs.map → poll-timeout-BCxgN97O.mjs.map} +1 -1
  46. package/dist/{polling-helpers-CoVhsC33.mjs → polling-helpers-BtEYR5dN.mjs} +260 -105
  47. package/dist/polling-helpers-BtEYR5dN.mjs.map +1 -0
  48. package/dist/{price-information-B0tkOoAX.mjs → price-information--d6GZAcp.mjs} +3 -4
  49. package/dist/{price-information-B0tkOoAX.mjs.map → price-information--d6GZAcp.mjs.map} +1 -1
  50. package/dist/resource-client-CF8SPsV8.d.mts +162 -0
  51. package/dist/resource-client-CF8SPsV8.d.mts.map +1 -0
  52. package/dist/{resource-client-rqTMkBeR.mjs → resource-client-Cm_bPcCs.mjs} +589 -197
  53. package/dist/resource-client-Cm_bPcCs.mjs.map +1 -0
  54. package/dist/retry-DYxm_eBU.d.mts +225 -0
  55. package/dist/retry-DYxm_eBU.d.mts.map +1 -0
  56. package/dist/{retry-BlX4tUnT.mjs → retry-Dv5TsY9O.mjs} +312 -54
  57. package/dist/retry-Dv5TsY9O.mjs.map +1 -0
  58. package/dist/{signatures-JF-7Psce.mjs → signatures-CtJ7jfVN.mjs} +2 -3
  59. package/dist/{signatures-JF-7Psce.mjs.map → signatures-CtJ7jfVN.mjs.map} +1 -1
  60. package/dist/storage.d.mts +333 -344
  61. package/dist/storage.d.mts.map +1 -1
  62. package/dist/storage.mjs +39 -40
  63. package/dist/storage.mjs.map +1 -1
  64. package/dist/testing.d.mts +369 -434
  65. package/dist/testing.d.mts.map +1 -1
  66. package/dist/testing.mjs +18 -33
  67. package/dist/testing.mjs.map +1 -1
  68. package/dist/{to-blob-RPqMBuft.mjs → to-blob-Bqu7bmlE.mjs} +2 -3
  69. package/dist/{to-blob-RPqMBuft.mjs.map → to-blob-Bqu7bmlE.mjs.map} +1 -1
  70. package/dist/types-Z4abDJfK.d.mts +501 -0
  71. package/dist/types-Z4abDJfK.d.mts.map +1 -0
  72. package/dist/universes.d.mts +619 -436
  73. package/dist/universes.d.mts.map +1 -1
  74. package/dist/universes.mjs +432 -79
  75. package/dist/universes.mjs.map +1 -1
  76. package/dist/{validation-B_Zs1So2.mjs → validation-kaTLLAD1.mjs} +3 -4
  77. package/dist/{validation-B_Zs1So2.mjs.map → validation-kaTLLAD1.mjs.map} +1 -1
  78. package/dist/wire-DDG87I-d.d.mts +39 -0
  79. package/dist/wire-DDG87I-d.d.mts.map +1 -0
  80. package/package.json +15 -14
  81. package/dist/capacity-admission-IDO3fcUC.d.mts +0 -369
  82. package/dist/capacity-admission-IDO3fcUC.d.mts.map +0 -1
  83. package/dist/data.generated-B2ceLfSn.d.mts.map +0 -1
  84. package/dist/network-error-DR9FX5hb.mjs.map +0 -1
  85. package/dist/polling-helpers-CoVhsC33.mjs.map +0 -1
  86. package/dist/resource-client-B6NeFXUv.d.mts +0 -164
  87. package/dist/resource-client-B6NeFXUv.d.mts.map +0 -1
  88. package/dist/resource-client-rqTMkBeR.mjs.map +0 -1
  89. package/dist/retry-BlX4tUnT.mjs.map +0 -1
  90. package/dist/retry-war_-9tb.d.mts +0 -373
  91. package/dist/retry-war_-9tb.d.mts.map +0 -1
  92. package/dist/types-CvYh4SPC.d.mts +0 -386
  93. package/dist/types-CvYh4SPC.d.mts.map +0 -1
  94. package/dist/wire-D3K-a-UP.d.mts +0 -37
  95. package/dist/wire-D3K-a-UP.d.mts.map +0 -1
@@ -1,38 +1,7 @@
1
- import { a as ApiError, n as RateLimitError, o as requestContextOf, r as hasServerRetryGuidance } from "./network-error-DR9FX5hb.mjs";
2
- import { C as parseRateLimitHeaders, S as RequestAbortedError, _ as createFetchHttpClient, b as raceWithAbortAsync, c as defaultRetryDelay, d as shouldRetry, g as PermissionError, h as RateLimitWaitRefusedError, l as hasGuidedWait, m as RequestDeadlineExceededError, p as RetryDelayExceededError, r as IDEMPOTENT_METHOD_DEFAULTS, s as computeRetryWaitMs, u as mergeConfig, v as isUploadRequest, w as withReportedWindow, x as requestAbortedError, y as ABORTED } from "./retry-BlX4tUnT.mjs";
1
+ import { a as ApiError, c as recordPreviousAttempts, n as RateLimitError, o as requestContextOf, r as hasServerRetryGuidance } from "./network-error-P4An7nUB.mjs";
2
+ import { C as isUploadRequest, D as requestAbortedError, E as raceWithAbortAsync, F as pickDiagnosticHeaders, M as withReportedWindow, N as isRecord, O as RequestAbortedError, P as extractErrorMessage, S as createFetchHttpClient, T as ABORTED, _ as RateLimitWaitRefusedError, b as CredentialNotSupportedError, c as defaultRetryDelay, d as mergeConfig, f as shouldRetry, g as RequestDeadlineExceededError, h as RetryDelayExceededError, j as parseRateLimitHeaders, l as hasGuidedWait, m as UnexpectedResponseError, r as IDEMPOTENT_METHOD_DEFAULTS, s as computeRetryWaitMs, u as isRefusedGuidedWait, v as PermissionError, x as CredentialError, y as CredentialRejectedError } from "./retry-Dv5TsY9O.mjs";
3
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
4
+ // src/internal/utils/to-json-details.ts
36
5
  /**
37
6
  * Narrows an untyped response body to the `JSONValue` accepted by
38
7
  * `ApiError.details`. `HttpResponse.body` is `unknown` because a transport may
@@ -77,8 +46,56 @@ function asJsonObject(value, seen) {
77
46
  seen.delete(value);
78
47
  return Object.fromEntries(entries);
79
48
  }
80
- //#endregion
81
- //#region src/internal/http/admission-wait.ts
49
+ // src/internal/api-key-only.ts
50
+ /**
51
+ * Fails an OAuth call to an Operation that Roblox accepts only with an API
52
+ * key. Runs before the provider is asked for a token and before any request.
53
+ *
54
+ * @param spec - The method spec's flag and operation limit.
55
+ * @param credential - The effective credential for the call.
56
+ * @returns A {@link CredentialNotSupportedError} failure, or `undefined` when
57
+ * the call may proceed.
58
+ */
59
+ function credentialNotSupportedFailure(spec, credential) {
60
+ if (spec.apiKeyOnly !== true || credential.kind !== "oauth") return;
61
+ const { operationKey } = spec.operationLimit;
62
+ return {
63
+ err: new CredentialNotSupportedError(`Operation ${operationKey} accepts only an API key credential`, { operationKey }),
64
+ success: false
65
+ };
66
+ }
67
+ // src/internal/credential-snapshot.ts
68
+ /**
69
+ * Copies a caller's credential, so a later change to the caller's object
70
+ * cannot change the key or the OAuth identity a client or a queued request
71
+ * uses. An OAuth provider stays a call on the caller's object, so a class
72
+ * method keeps its `this`.
73
+ *
74
+ * @param credential - The caller's credential.
75
+ * @returns A copy the caller does not hold.
76
+ */
77
+ function snapshotCredential(credential) {
78
+ if (credential.kind !== "oauth") return { ...credential };
79
+ return {
80
+ getAccessToken: async (context) => credential.getAccessToken(context),
81
+ identity: credential.identity,
82
+ kind: "oauth"
83
+ };
84
+ }
85
+ /**
86
+ * Copies the credential of a per-request override, if it has one.
87
+ *
88
+ * @template T - The override shape.
89
+ * @param options - The caller's per-request overrides.
90
+ * @returns The overrides, with a credential the caller does not hold.
91
+ */
92
+ function withCredentialSnapshot(options) {
93
+ return options.credential === void 0 ? options : {
94
+ ...options,
95
+ credential: snapshotCredential(options.credential)
96
+ };
97
+ }
98
+ // src/internal/http/admission-wait.ts
82
99
  /**
83
100
  * Performs one SDK-managed wait and emits a balanced request-scoped lifecycle.
84
101
  * Observer failures are deliberately ignored: observation cannot become part
@@ -112,9 +129,8 @@ function notify(observer, event) {
112
129
  if (notification !== void 0) Promise.resolve(notification).catch(Boolean);
113
130
  } catch {}
114
131
  }
115
- //#endregion
116
- //#region src/internal/http/budget-tracker.ts
117
- const MS_PER_SECOND = 1e3;
132
+ // src/internal/http/budget-tracker.ts
133
+ const MS_PER_SECOND$1 = 1e3;
118
134
  /**
119
135
  * Tracks the live rate-limit budget for a single scope. Primed by `observe`
120
136
  * from response headers and drawn down by `reserve` as requests leave, so
@@ -136,10 +152,17 @@ const MS_PER_SECOND = 1e3;
136
152
  var BudgetTracker = class {
137
153
  /** Time (ms) the most recent request was allowed out, for spacing. */
138
154
  #lastAllowedAt = void 0;
155
+ /** Token of the latest reservation, compared by identity. */
156
+ #latestReservation = void 0;
139
157
  /** Requests the server grants per window, used when a window rolls over. */
140
158
  #rolloverWindow;
141
159
  #window = void 0;
142
160
  /**
161
+ * Token of the window in force, compared by identity. A new window gets a
162
+ * new token, so a release can tell its window is gone.
163
+ */
164
+ #windowToken = {};
165
+ /**
143
166
  * Creates a tracker for one scope.
144
167
  *
145
168
  * @param documentedWindow - The operation's documented capacity, used
@@ -159,9 +182,10 @@ var BudgetTracker = class {
159
182
  */
160
183
  observe(sample, now) {
161
184
  this.#rolloverWindow = sample.window ?? this.#rolloverWindow;
185
+ this.#windowToken = {};
162
186
  this.#window = {
163
187
  predictedRemaining: sample.remaining,
164
- resetAt: now + sample.resetSeconds * MS_PER_SECOND
188
+ resetAt: now + sample.resetSeconds * MS_PER_SECOND$1
165
189
  };
166
190
  }
167
191
  /**
@@ -169,14 +193,29 @@ var BudgetTracker = class {
169
193
  * and decrements the prediction. A no-op on the prediction while unprimed.
170
194
  *
171
195
  * @param now - The time the request was allowed out, in ms.
196
+ * @returns The reservation, to release if the request is not sent.
172
197
  */
173
198
  reserve(now) {
199
+ const previousAllowedAt = this.#lastAllowedAt;
174
200
  this.#lastAllowedAt = now;
201
+ const reservation = {};
202
+ this.#latestReservation = reservation;
175
203
  const window = this.#windowAt(now);
176
204
  if (window !== void 0) this.#window = {
177
205
  ...window,
178
206
  predictedRemaining: window.predictedRemaining - 1
179
207
  };
208
+ const windowToken = this.#windowToken;
209
+ let isReleased = false;
210
+ return { release: () => {
211
+ if (isReleased) return;
212
+ isReleased = true;
213
+ this.#release({
214
+ previousAllowedAt,
215
+ reservation,
216
+ windowToken
217
+ });
218
+ } };
180
219
  }
181
220
  /**
182
221
  * Milliseconds to wait before the next request is allowed.
@@ -195,6 +234,13 @@ var BudgetTracker = class {
195
234
  const interval = window.spacingMs ?? (resetAt - now) / predictedRemaining;
196
235
  return Math.max(0, this.#lastAllowedAt + interval - now);
197
236
  }
237
+ #release({ previousAllowedAt, reservation, windowToken }) {
238
+ if (reservation === this.#latestReservation) this.#lastAllowedAt = previousAllowedAt;
239
+ if (this.#window !== void 0 && windowToken === this.#windowToken) this.#window = {
240
+ ...this.#window,
241
+ predictedRemaining: this.#window.predictedRemaining + 1
242
+ };
243
+ }
198
244
  /**
199
245
  * The window in force at `now`, opening the next one at full capacity once
200
246
  * the current window's reset has passed.
@@ -205,7 +251,8 @@ var BudgetTracker = class {
205
251
  #windowAt(now) {
206
252
  if (this.#window !== void 0 && now >= this.#window.resetAt) {
207
253
  const { capacity, windowSeconds } = this.#rolloverWindow;
208
- const windowMs = windowSeconds * MS_PER_SECOND;
254
+ const windowMs = windowSeconds * MS_PER_SECOND$1;
255
+ this.#windowToken = {};
209
256
  this.#window = {
210
257
  predictedRemaining: capacity,
211
258
  resetAt: now + windowMs,
@@ -215,9 +262,9 @@ var BudgetTracker = class {
215
262
  return this.#window;
216
263
  }
217
264
  };
218
- //#endregion
219
- //#region src/internal/http/request-deadline.ts
265
+ // src/internal/http/request-deadline.ts
220
266
  const DEADLINE_ELAPSED = Symbol("request deadline elapsed");
267
+ /** The longest delay a timer accepts; `AbortSignal.timeout` throws above it. */
221
268
  const MAX_ABORT_TIMEOUT_MS = 2147483647;
222
269
  /**
223
270
  * Resolves one signal that spans the whole logical request.
@@ -243,24 +290,27 @@ function requestLifecycle(deadlineMs, callerSignal) {
243
290
  * Returns a typed failure when the deadline signal ended the request.
244
291
  *
245
292
  * @param lifecycle - Signals and timestamp for the logical request.
293
+ * @param cause - The failure the deadline failure replaces, if any.
246
294
  * @returns A deadline failure, or `undefined` when another signal won.
247
295
  */
248
- function elapsedDeadlineFailure({ deadlineMs, deadlineSignal, signal }) {
296
+ function elapsedDeadlineFailure({ deadlineMs, deadlineSignal, signal }, cause) {
249
297
  if (deadlineMs === void 0 || deadlineSignal?.aborted !== true || !Object.is(signal?.reason, deadlineSignal.reason)) return;
250
298
  return new RequestDeadlineExceededError("Request deadline elapsed", {
299
+ cause,
251
300
  deadlineMs,
252
301
  remainingMs: 0
253
302
  });
254
303
  }
255
304
  /**
256
305
  * Reclassifies an internal abort when the request deadline supplied its signal.
306
+ * The abort becomes the deadline failure's `cause`.
257
307
  *
258
308
  * @param error - Error returned by the request pipeline.
259
309
  * @param lifecycle - Signals and timestamp for the logical request.
260
310
  * @returns A deadline failure, or `undefined` for other failures.
261
311
  */
262
312
  function deadlineFailureFromError(error, lifecycle) {
263
- return error instanceof RequestAbortedError ? elapsedDeadlineFailure(lifecycle) : void 0;
313
+ return error instanceof RequestAbortedError ? elapsedDeadlineFailure(lifecycle, error) : void 0;
264
314
  }
265
315
  /**
266
316
  * Refuses a known admission wait that cannot fit before the deadline.
@@ -301,9 +351,9 @@ function deadlineTimeout(deadlineMs) {
301
351
  function waitMessage(waitMs, remainingMs) {
302
352
  return `Admission wait would take ${waitMs / 1e3}s; ${remainingMs / 1e3}s remain before the request deadline`;
303
353
  }
304
- //#endregion
305
- //#region src/internal/http/budget-gate.ts
354
+ // src/internal/http/budget-gate.ts
306
355
  const REPORTED_BUDGET_REASON = "reported-budget";
356
+ const MS_PER_SECOND = 1e3;
307
357
  /**
308
358
  * Header-primed rate-limit gate shared across a client. Holds one
309
359
  * {@link BudgetTracker} per {@link BudgetScope}. Before each request the caller
@@ -318,6 +368,7 @@ const REPORTED_BUDGET_REASON = "reported-budget";
318
368
  */
319
369
  var BudgetGate = class {
320
370
  #chains = /* @__PURE__ */ new Map();
371
+ #lockouts = /* @__PURE__ */ new Map();
321
372
  #pendingGates = /* @__PURE__ */ new Map();
322
373
  #sleep;
323
374
  #trackers = /* @__PURE__ */ new Map();
@@ -335,18 +386,19 @@ var BudgetGate = class {
335
386
  * or rejected, so one failed attempt cannot poison later gates on the
336
387
  * scope.
337
388
  *
338
- * @param scope - The API key and operation to gate on.
389
+ * @param scope - The credential and operation to gate on.
339
390
  * @param context - Request-local observer and cancellation signal.
391
+ * @returns The reserved slot. Release it when the request is not sent.
340
392
  * @rejects {@link RequestAbortedError} when the caller cancels while waiting.
393
+ * @rejects {@link RateLimitWaitRefusedError} while the scope is locked out.
341
394
  */
342
395
  async gateAsync(scope, { deadlineMs, observer, signal } = {}) {
343
396
  const key = scopeKey(scope);
344
- const tracker = this.#tracker(key, scope.documentedWindow);
345
397
  const pendingGates = this.#pendingGates.get(key) ?? 0;
346
398
  const waitsForEarlierGate = pendingGates > 0;
347
399
  this.#pendingGates.set(key, pendingGates + 1);
348
400
  const completed = (this.#chains.get(key) ?? Promise.resolve()).catch(ignoreRejection$1).then(async () => {
349
- return this.#gateOnce(tracker, {
401
+ return this.#gateOnce(scope, {
350
402
  deadlineMs,
351
403
  observer: waitsForEarlierGate ? void 0 : observer,
352
404
  signal
@@ -355,13 +407,27 @@ var BudgetGate = class {
355
407
  const remainingGates = (this.#pendingGates.get(key) ?? 1) - 1;
356
408
  this.#pendingGates.set(key, remainingGates);
357
409
  });
358
- this.#chains.set(key, completed.catch(ignoreRejection$1));
359
- if (waitsForEarlierGate) await observeAdmissionWaitAsync({
410
+ this.#chains.set(key, completed.then(ignoreRejection$1).catch(ignoreRejection$1));
411
+ if (waitsForEarlierGate) return observeAdmissionWaitAsync({
360
412
  observer,
361
413
  reason: REPORTED_BUDGET_REASON,
362
414
  waitAsync: async () => waitForGateAsync(completed, signal)
363
415
  });
364
- else await waitForGateAsync(completed, signal);
416
+ return waitForGateAsync(completed, signal);
417
+ }
418
+ /**
419
+ * Locks the scope out until the refused 429's guided wait ends. Until then
420
+ * every gate on the scope is refused at once, without sleeping or
421
+ * reserving budget. The latest lockout replaces any earlier one.
422
+ *
423
+ * @param scope - The same scope passed to {@link gateAsync}.
424
+ * @param cause - The 429 whose guided wait was too long to take.
425
+ */
426
+ lockOut(scope, cause) {
427
+ this.#lockouts.set(scopeKey(scope), {
428
+ cause,
429
+ resetAt: Date.now() + cause.retryAfterSeconds * MS_PER_SECOND
430
+ });
365
431
  }
366
432
  /**
367
433
  * Folds a response's parsed budget back onto the scope. A `undefined`
@@ -375,15 +441,55 @@ var BudgetGate = class {
375
441
  if (sample === void 0) return;
376
442
  this.#tracker(scopeKey(scope), scope.documentedWindow).observe(sample, Date.now());
377
443
  }
378
- async #gateOnce(tracker, { deadlineMs, observer, signal }) {
444
+ /**
445
+ * Refuses a request at once while its scope is locked out, so it fails
446
+ * before taking a static queue slot or waiting on anything.
447
+ *
448
+ * @param scope - The same scope passed to {@link gateAsync}.
449
+ * @throws {@link RateLimitWaitRefusedError} While the scope is locked out.
450
+ */
451
+ refuseDuringLockout(scope) {
452
+ this.#refuseDuringLockout(scopeKey(scope));
453
+ }
454
+ /**
455
+ * Swaps a request's result for the lockout refusal while its scope is
456
+ * locked out, for a lockout that began after the request passed its gate.
457
+ *
458
+ * @param scope - The same scope passed to {@link gateAsync}.
459
+ * @param result - The request's result so far.
460
+ * @returns The refusal while the scope is locked out, else `result`.
461
+ */
462
+ refuseIfLockedOut(scope, result) {
463
+ const refusal = this.#lockoutRefusal(scopeKey(scope));
464
+ return refusal === void 0 ? result : {
465
+ err: refusal,
466
+ success: false
467
+ };
468
+ }
469
+ async #gateOnce(scope, { deadlineMs, observer, signal }) {
379
470
  if (signal?.aborted === true) throw requestAbortedError(signal);
471
+ const key = scopeKey(scope);
472
+ const tracker = this.#tracker(key, scope.documentedWindow);
473
+ this.#refuseDuringLockout(key);
380
474
  const waitMs = tracker.waitMs(Date.now());
381
- if (waitMs > 0) await this.#waitAsync(waitMs, {
382
- deadlineMs,
383
- observer,
384
- signal
385
- });
386
- tracker.reserve(Date.now());
475
+ if (waitMs > 0) {
476
+ await this.#waitAsync(waitMs, {
477
+ deadlineMs,
478
+ observer,
479
+ signal
480
+ });
481
+ this.#refuseDuringLockout(key);
482
+ }
483
+ return tracker.reserve(Date.now());
484
+ }
485
+ #lockoutRefusal(key) {
486
+ const lockout = this.#lockouts.get(key);
487
+ const now = Date.now();
488
+ return lockout !== void 0 && now < lockout.resetAt ? lockoutRefusal(lockout, now) : void 0;
489
+ }
490
+ #refuseDuringLockout(key) {
491
+ const refusal = this.#lockoutRefusal(key);
492
+ if (refusal !== void 0) throw refusal;
387
493
  }
388
494
  #tracker(key, documentedWindow) {
389
495
  const existing = this.#trackers.get(key);
@@ -409,21 +515,94 @@ var BudgetGate = class {
409
515
  });
410
516
  }
411
517
  };
518
+ /**
519
+ * Composes the map key one credential and operation are tracked under. The
520
+ * budget gate and the rate-limit queues share it.
521
+ *
522
+ * @param scope - The credential key and operation naming the window.
523
+ * @returns The key for the tracker, chain and queue maps.
524
+ */
525
+ function scopeKey({ credentialKey, operationKey }) {
526
+ return `${credentialKey}::${operationKey}`;
527
+ }
528
+ function lockoutRefusal({ cause, resetAt }, now) {
529
+ const secondsLeft = Math.ceil((resetAt - now) / MS_PER_SECOND);
530
+ const remainingLockout = new RateLimitError(cause.message, {
531
+ cause,
532
+ code: cause.code,
533
+ details: cause.details,
534
+ remaining: cause.remaining,
535
+ responseHeaders: cause.responseHeaders,
536
+ retryAfterSeconds: secondsLeft,
537
+ source: cause.source,
538
+ statusCode: cause.statusCode
539
+ });
540
+ return new RateLimitWaitRefusedError(`Rate limit lockout on this operation lasts another ${secondsLeft}s; request not sent`, { cause: remainingLockout });
541
+ }
412
542
  function ignoreRejection$1() {}
413
543
  async function waitForGateAsync(gate, signal) {
414
- if (await raceWithAbortAsync(async () => gate, signal) === ABORTED) throw requestAbortedError(signal);
544
+ const gateResult = await raceWithAbortAsync(async () => gate, signal);
545
+ if (gateResult === ABORTED) throw requestAbortedError(signal);
546
+ return gateResult;
415
547
  }
548
+ // src/internal/http/credential-rejection.ts
549
+ /** The v1 body message Roblox sends on a 502 after an app removal. */
550
+ const SCOPE_AUTHORIZATION_FAILED = "Scope authorization failed.";
551
+ const OAUTH_PERMISSION_HINT = "The OAuth grant may not include the required scope or this universe.";
416
552
  /**
417
- * Composes the map key one budget window is tracked under.
553
+ * Turns Roblox's refusal of an OAuth token into a
554
+ * {@link CredentialRejectedError}: a non-gateway 401, or a non-gateway 502
555
+ * whose body message is "Scope authorization failed.". The result is not an
556
+ * `ApiError`, so the retry loop never retries it. Every other error, and
557
+ * every error on an API-key credential, passes through unchanged.
418
558
  *
419
- * @param scope - The API key and operation naming the window.
420
- * @returns The key for the tracker and chain maps.
559
+ * @param err - The transport error for one attempt.
560
+ * @param credential - The effective credential of the call.
561
+ * @returns The classified error.
421
562
  */
422
- function scopeKey({ apiKey, operationKey }) {
423
- return `${apiKey}::${operationKey}`;
563
+ function classifyCredentialRejection(err, credential) {
564
+ if (credential.kind !== "oauth" || !isTokenRefusal(err)) return err;
565
+ return new CredentialRejectedError(err.message, {
566
+ cause: err,
567
+ code: err.code,
568
+ identity: credential.identity,
569
+ statusCode: err.statusCode
570
+ });
424
571
  }
425
- //#endregion
426
- //#region src/internal/http/execute.ts
572
+ /**
573
+ * Upgrades a non-gateway 401 or 403 `ApiError` to a {@link PermissionError}
574
+ * when the method declares its scopes. On an OAuth credential the message
575
+ * adds a hint that the grant may not include the scope or this universe.
576
+ *
577
+ * @param err - The final error of the call.
578
+ * @param context - The credential, operation key and declared scopes.
579
+ * @returns The upgraded error, or `err` unchanged.
580
+ */
581
+ function enrichPermissionError(err, { credential, operationKey, requiredScopes }) {
582
+ if (requiredScopes === void 0) return err;
583
+ if (err instanceof PermissionError) return err;
584
+ if (!(err instanceof ApiError)) return err;
585
+ if (err.statusCode !== 401 && err.statusCode !== 403) return err;
586
+ if (err.gatewaySummary !== void 0) return err;
587
+ return new PermissionError(permissionMessage(err.message, credential), {
588
+ ...requestContextOf(err),
589
+ cause: err.cause,
590
+ code: err.code,
591
+ details: err.details,
592
+ operationKey,
593
+ requiredScopes,
594
+ statusCode: err.statusCode
595
+ });
596
+ }
597
+ function isTokenRefusal(err) {
598
+ if (!(err instanceof ApiError) || err.gatewaySummary !== void 0) return false;
599
+ return err.statusCode === 401 || err.statusCode === 502 && extractErrorMessage(err.details) === SCOPE_AUTHORIZATION_FAILED;
600
+ }
601
+ function permissionMessage(message, credential) {
602
+ if (credential.kind !== "oauth") return message;
603
+ return `${message}${message.endsWith(".") ? " " : ". "}${OAUTH_PERMISSION_HINT}`;
604
+ }
605
+ // src/internal/http/execute.ts
427
606
  /**
428
607
  * Retry-aware orchestration loop. Coordinates a single logical request,
429
608
  * looping over `options.send` until it succeeds, the error is non-retryable,
@@ -441,31 +620,35 @@ async function executeWithRetryAsync(request, options) {
441
620
  if (signal?.aborted === true) return abortedResult(signal);
442
621
  let result = await attemptAsync(request, options);
443
622
  let retries = 0;
444
- let waits = 0;
623
+ let earlier = [];
445
624
  while (!result.success) {
446
- const plan = planRetry(result.err, {
625
+ const failure = result.err;
626
+ const plan = planRetry(failure, {
447
627
  config,
448
628
  deadlineMs,
449
629
  retries
450
630
  });
451
- if (plan === void 0) return result;
452
- if ("refusal" in plan) return {
453
- err: plan.refusal,
454
- success: false
455
- };
631
+ if (plan === void 0) return failed(failure, earlier);
632
+ if ("refusal" in plan) return failed(plan.refusal, earlier);
456
633
  retries += plan.spendsAttempt ? 1 : 0;
457
- waits += 1;
634
+ earlier = [...earlier, failure];
458
635
  announceRetry({
459
- attempt: waits,
460
- error: result.err,
636
+ attempt: earlier.length,
637
+ error: failure,
461
638
  hooks,
462
639
  waitMs: plan.waitMs
463
640
  });
464
- if (await waitForRetryAsync(plan.waitMs, options) === ABORTED) return abortedResult(signal);
641
+ if (await waitForRetryAsync(plan.waitMs, options) === ABORTED) return failed(requestAbortedError(signal), earlier);
465
642
  result = await attemptAsync(request, options);
466
643
  }
467
644
  return result;
468
645
  }
646
+ function failed(err, earlier) {
647
+ return {
648
+ err: recordPreviousAttempts(err, earlier),
649
+ success: false
650
+ };
651
+ }
469
652
  function retryRefusal({ cause, deadlineMs, retryAfterMs }) {
470
653
  if (deadlineMs === void 0) return;
471
654
  const refusal = waitDeadlineFailure({
@@ -501,7 +684,7 @@ function planRetry(err, { config, deadlineMs, retries }) {
501
684
  if (!shouldRetry(err, config)) return;
502
685
  const guided = hasGuidedWait(err);
503
686
  if (!guided && retries >= config.maxRetries) return;
504
- if (guided && err.retryAfterSeconds > 60) return { refusal: guidedWaitRefusal(err) };
687
+ if (isRefusedGuidedWait(err)) return { refusal: guidedWaitRefusal(err) };
505
688
  const waitMs = computeRetryWaitMs(err, {
506
689
  attempt: retries,
507
690
  retryDelay: config.retryDelay
@@ -539,15 +722,14 @@ async function attemptAsync(request, { hooks, send, signal }) {
539
722
  const attempt = await raceWithAbortAsync(async () => send(request), signal);
540
723
  return attempt === ABORTED ? abortedResult(signal) : attempt;
541
724
  }
542
- //#endregion
543
- //#region src/internal/http/rate-limit-observation.ts
725
+ // src/internal/http/rate-limit-observation.ts
544
726
  /**
545
727
  * Extracts a {@link RateLimitSample} from a transport result so the budget
546
728
  * gate can be fed from every attempt. A 2xx carries the budget in its headers.
547
- * A 429 only primes the gate when it reports zero remaining and valid
548
- * guidance. This is a conservative scheduling condition, not a semantic
549
- * classification of the 429. A 429 asking for a longer wait than the SDK takes
550
- * is refused, so it does not hold later requests either. A 429 also carries
729
+ * A 429 with valid server guidance primes the gate as spent for its guided
730
+ * wait, whatever `x-ratelimit-remaining` reports: the remaining count is only
731
+ * a pacing hint on 2xx responses. A 429 asking for a longer wait than the SDK
732
+ * takes is refused, so it does not prime the gate either. A 429 also carries
551
733
  * the window capacity its `x-ratelimit-limit` header reports. Any other error
552
734
  * yields `undefined`.
553
735
  *
@@ -557,19 +739,45 @@ async function attemptAsync(request, { hooks, send, signal }) {
557
739
  function rateLimitSampleFromResult(result) {
558
740
  if (result.success) return parseRateLimitHeaders(result.data.headers);
559
741
  const { err } = result;
560
- if (err instanceof RateLimitError && err.remaining === 0 && hasServerRetryGuidance(err) && err.retryAfterSeconds <= 60) return withReportedWindow({
561
- remaining: err.remaining,
562
- resetSeconds: err.retryAfterSeconds
563
- }, err.responseHeaders?.["x-ratelimit-limit"]);
742
+ if (err instanceof RateLimitError && hasServerRetryGuidance(err) && err.retryAfterSeconds <= 60) {
743
+ const sample = {
744
+ remaining: 0,
745
+ resetSeconds: err.retryAfterSeconds
746
+ };
747
+ return withReportedWindow(sample, err.responseHeaders?.["x-ratelimit-limit"]);
748
+ }
564
749
  }
565
- //#endregion
566
- //#region src/internal/http/rate-limit-queue.ts
750
+ /**
751
+ * Picks out a 429 whose guided wait is longer than the SDK waits out on its
752
+ * own. Such a lockout is refused, and later requests on the same scope fail
753
+ * locally until it ends instead of reaching the server.
754
+ *
755
+ * @param result - The classified transport result for one attempt.
756
+ * @returns The locking 429, or `undefined` for any other result.
757
+ */
758
+ function rateLimitLockoutFromResult(result) {
759
+ return !result.success && isRefusedGuidedWait(result.err) ? result.err : void 0;
760
+ }
761
+ /**
762
+ * Feeds one attempt back into the budget gate: its reported budget always,
763
+ * and a long 429 as a lockout unless the caller exempts it (such as a 429
764
+ * naming tasks that occupy a Luau place).
765
+ *
766
+ * @param budgets - The gate shared across the client.
767
+ * @param attempt - The scope, transport result, and lockout exemption.
768
+ */
769
+ function observeAttempt(budgets, { exemptsLockout, scope, transportResult }) {
770
+ budgets.observe(scope, rateLimitSampleFromResult(transportResult));
771
+ const lockout = rateLimitLockoutFromResult(transportResult);
772
+ if (lockout !== void 0 && exemptsLockout?.(lockout) !== true) budgets.lockOut(scope, lockout);
773
+ }
774
+ // src/internal/http/rate-limit-queue.ts
567
775
  const OPERATION_QUEUE_REASON = "operation-queue";
568
776
  /**
569
- * Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every
570
- * call to `acquire` consumes one token; when the bucket is empty the call
571
- * waits until a token regenerates before invoking the task. Tokens refill at
572
- * `maxPerSecond` per second, up to the operation's `burstCapacity`.
777
+ * Token-bucket rate limiter for a single `(credential identity, operation)`
778
+ * pair. Every call to `acquire` consumes one token; when the bucket is empty
779
+ * the call waits until a token regenerates before invoking the task. Tokens
780
+ * refill at `maxPerSecond` per second, up to the operation's `burstCapacity`.
573
781
  *
574
782
  * Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`
575
783
  * advances by `waitMs` after every sleep so the algorithm stays correct
@@ -691,8 +899,29 @@ function ignoreRejection() {}
691
899
  async function waitForTurnAsync(turn, signal) {
692
900
  if (await raceWithAbortAsync(async () => turn, signal) === ABORTED) throw requestAbortedError(signal);
693
901
  }
694
- //#endregion
695
- //#region src/internal/utils/sleep.ts
902
+ // src/internal/http/request-config.ts
903
+ /**
904
+ * Resolves the per-request {@link RequestConfig}, less the credential, which
905
+ * is resolved per transport attempt. Upload requests ({@link isUploadRequest})
906
+ * carry no default timeout: a multi-megabyte place file over a slow link is
907
+ * bandwidth-bound, so a transport-attempt timeout only fires spuriously. An
908
+ * explicit `options.timeout` still applies to any request; every non-upload
909
+ * request keeps the merged default.
910
+ *
911
+ * @param inputs - The merged config, the built request, and per-request
912
+ * overrides.
913
+ * @returns The config to hand to the transport, with `timeout` omitted when
914
+ * no transport-attempt timeout should apply.
915
+ */
916
+ function buildRequestConfig({ merged, options, request, signal }) {
917
+ const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
918
+ return {
919
+ baseUrl: merged.baseUrl,
920
+ ...signal === void 0 ? {} : { signal },
921
+ ...shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }
922
+ };
923
+ }
924
+ // src/internal/utils/sleep.ts
696
925
  /**
697
926
  * Timer-backed production sleep that releases its timer on cancellation.
698
927
  *
@@ -702,8 +931,7 @@ async function waitForTurnAsync(turn, signal) {
702
931
  async function defaultSleepAsync(ms, signal) {
703
932
  await setTimeout(ms, void 0, { signal });
704
933
  }
705
- //#endregion
706
- //#region src/internal/http/resolve-dependencies.ts
934
+ // src/internal/http/resolve-dependencies.ts
707
935
  /**
708
936
  * Resolves the concrete HTTP client and sleep implementation a resource
709
937
  * client should use. Falls back to the fetch-backed HTTP client and the
@@ -722,8 +950,180 @@ function resolveDependencies(options) {
722
950
  sleep: options.sleep ?? defaultSleepAsync
723
951
  };
724
952
  }
725
- //#endregion
726
- //#region src/internal/resource-client.ts
953
+ // src/internal/http/start-request.ts
954
+ /**
955
+ * Resolve the request-only controls of one call before its request is
956
+ * built: fail at once on an already-aborted caller signal or an elapsed
957
+ * deadline, otherwise start the request lifecycle and split the per-call
958
+ * options from the admission controls.
959
+ *
960
+ * @param options - The caller's per-request options, if any.
961
+ * @returns The resolved controls, or the abort or deadline failure.
962
+ */
963
+ function startRequest(options) {
964
+ const callerSignal = options?.signal;
965
+ if (callerSignal?.aborted === true) return {
966
+ err: requestAbortedError(callerSignal),
967
+ success: false
968
+ };
969
+ const lifecycle = requestLifecycle(options?.deadlineMs, callerSignal);
970
+ const deadlineFailure = elapsedDeadlineFailure(lifecycle);
971
+ if (deadlineFailure !== void 0) return {
972
+ err: deadlineFailure,
973
+ success: false
974
+ };
975
+ const { deadlineMs, onAdmissionWait, signal: _signal, ...requestOptions } = options ?? {};
976
+ return {
977
+ data: {
978
+ admission: {
979
+ deadlineMs,
980
+ observer: onAdmissionWait,
981
+ signal: lifecycle.signal
982
+ },
983
+ lifecycle,
984
+ requestOptions: withCredentialSnapshot(requestOptions)
985
+ },
986
+ success: true
987
+ };
988
+ }
989
+ // src/internal/http/credential.ts
990
+ /**
991
+ * Names the rate-limit bucket a credential draws on. The key is namespaced by
992
+ * kind, so an OAuth identity never shares a bucket with an equal API key. An
993
+ * OAuth credential keys on its identity, so a token rotation keeps the bucket.
994
+ *
995
+ * @param credential - The effective credential.
996
+ * @returns The bucket key. It holds the API key, so keep it in private maps.
997
+ */
998
+ function credentialQueueKey(credential) {
999
+ return credential.kind === "apiKey" ? `apiKey:${credential.apiKey}` : `oauth:${credential.identity}`;
1000
+ }
1001
+ /**
1002
+ * Turns the effective credential into the header-ready form for one transport
1003
+ * attempt. Calls an OAuth provider once; a throw or a rejection becomes a
1004
+ * {@link CredentialError} whose `cause` is the provider's error.
1005
+ *
1006
+ * @param credential - The effective credential.
1007
+ * @param signal - The request's signal, handed to an OAuth provider. A
1008
+ * request with no signal hands the provider one that never aborts.
1009
+ * @returns The resolved credential, or the provider failure.
1010
+ */
1011
+ async function resolveAttemptCredentialAsync(credential, signal) {
1012
+ if (credential.kind === "apiKey") return {
1013
+ data: {
1014
+ apiKey: credential.apiKey,
1015
+ kind: "apiKey"
1016
+ },
1017
+ success: true
1018
+ };
1019
+ try {
1020
+ return {
1021
+ data: {
1022
+ accessToken: await credential.getAccessToken({ signal: signal ?? neverAbortingSignal() }),
1023
+ kind: "oauth"
1024
+ },
1025
+ success: true
1026
+ };
1027
+ } catch (err) {
1028
+ return {
1029
+ err: new CredentialError("OAuth credential provider failed", { cause: err }),
1030
+ success: false
1031
+ };
1032
+ }
1033
+ }
1034
+ function neverAbortingSignal() {
1035
+ return new AbortController().signal;
1036
+ }
1037
+ // src/internal/http/unauthenticated.ts
1038
+ const UNAUTHENTICATED_QUEUE_KEY = "none";
1039
+ const UNAUTHENTICATED = Object.freeze({
1040
+ data: Object.freeze({ kind: "none" }),
1041
+ success: true
1042
+ });
1043
+ /**
1044
+ * Applies a method's authentication to the merged config. An unauthenticated
1045
+ * method is served from its own origin and carries no credential. A
1046
+ * `{ kind: "none" }` credential carries none either.
1047
+ *
1048
+ * @param merged - The merged config of the call.
1049
+ * @param spec - The method's authentication declaration.
1050
+ * @returns The config to send with and the credential, if any.
1051
+ */
1052
+ function authenticateCall(merged, { unauthenticatedBaseUrl }) {
1053
+ if (unauthenticatedBaseUrl !== void 0) return {
1054
+ credential: void 0,
1055
+ merged: {
1056
+ ...merged,
1057
+ baseUrl: unauthenticatedBaseUrl
1058
+ }
1059
+ };
1060
+ return {
1061
+ credential: merged.credential.kind === "none" ? void 0 : merged.credential,
1062
+ merged
1063
+ };
1064
+ }
1065
+ /**
1066
+ * Keys the rate-limit queue of a call. Every unauthenticated call shares one
1067
+ * key, since Roblox counts those per caller.
1068
+ *
1069
+ * @param credential - The call's credential, or `undefined` when it sends
1070
+ * none.
1071
+ * @returns The credential's queue key, or the shared unauthenticated key.
1072
+ */
1073
+ function callQueueKey(credential) {
1074
+ return credential === void 0 ? UNAUTHENTICATED_QUEUE_KEY : credentialQueueKey(credential);
1075
+ }
1076
+ /**
1077
+ * Resolves the credential one attempt sends. An unauthenticated call sends
1078
+ * none and runs no OAuth provider.
1079
+ *
1080
+ * @param credential - The call's credential, if any.
1081
+ * @param signal - The caller's cancellation signal.
1082
+ * @returns The resolved credential, or the provider failure.
1083
+ */
1084
+ async function resolveCallCredentialAsync(credential, signal) {
1085
+ return credential === void 0 ? UNAUTHENTICATED : resolveAttemptCredentialAsync(credential, signal);
1086
+ }
1087
+ /**
1088
+ * Refines one attempt's transport error, then classifies a refused OAuth
1089
+ * token. An unauthenticated call sent no token, so none was refused.
1090
+ *
1091
+ * @param err - The transport error of the attempt.
1092
+ * @param context - The call's credential and optional refinement.
1093
+ * @returns The classified error.
1094
+ */
1095
+ function classifySendError(err, { credential, refineError }) {
1096
+ const refined = refineError === void 0 ? err : refineError(err);
1097
+ return credential === void 0 ? refined : classifyCredentialRejection(refined, credential);
1098
+ }
1099
+ // src/internal/with-request-context.ts
1100
+ const TRAILING_SLASH = /\/$/;
1101
+ /**
1102
+ * Rebuilds a parser's {@link UnexpectedResponseError} with the request it
1103
+ * answered. A parser sees only the response, so the call site adds the method,
1104
+ * the full URL, and the allowlisted response headers, and ends the message with
1105
+ * the bug report link when `reportHint` is set. Any other error is returned
1106
+ * unchanged.
1107
+ *
1108
+ * @param err - The parser's error.
1109
+ * @param exchange - The base URL, the request sent, and the response parsed.
1110
+ * @returns `err`, carrying the request context when it is an unexpected
1111
+ * response.
1112
+ */
1113
+ function withRequestContext(err, { baseUrl, reportHint, request, response }) {
1114
+ if (!(err instanceof UnexpectedResponseError)) return err;
1115
+ return new UnexpectedResponseError(err.message, {
1116
+ cause: err.cause,
1117
+ code: err.code,
1118
+ details: err.details,
1119
+ method: request.method,
1120
+ reportHint,
1121
+ responseHeaders: pickDiagnosticHeaders({ ...response.headers }),
1122
+ statusCode: err.statusCode,
1123
+ url: `${baseUrl.replace(TRAILING_SLASH, "")}${request.url}`
1124
+ });
1125
+ }
1126
+ // src/internal/resource-client.ts
727
1127
  /**
728
1128
  * Wraps an infallible request build as a {@link Result}-returning
729
1129
  * `buildRequest` callback compatible with {@link ResourceMethodSpec}.
@@ -775,16 +1175,17 @@ var ResourceClient = class {
775
1175
  #hooks;
776
1176
  #httpClient;
777
1177
  #queues = /* @__PURE__ */ new Map();
1178
+ #reportHint;
778
1179
  #sleep;
779
1180
  /**
780
1181
  * Creates a new {@link ResourceClient}. Resolves the injected HTTP
781
1182
  * client and sleep (defaulting to fetch + `setTimeout`) and freezes the
782
1183
  * merged client config so subsequent calls cannot mutate it.
783
1184
  *
784
- * @param options - Client-level configuration including the API key
1185
+ * @param options - Client-level configuration including the credential
785
1186
  * and optional construction-time test seams.
786
1187
  */
787
- constructor({ apiKey, hooks, httpClient, sleep, ...overrides }) {
1188
+ constructor({ hooks, httpClient, reportHint, sleep, ...overrides }) {
788
1189
  const resolved = resolveDependencies({
789
1190
  httpClient,
790
1191
  sleep
@@ -793,16 +1194,17 @@ var ResourceClient = class {
793
1194
  this.#sleep = resolved.sleep;
794
1195
  this.#budgets = new BudgetGate(this.#sleep);
795
1196
  this.#hooks = hooks ?? {};
1197
+ this.#reportHint = reportHint ?? true;
796
1198
  this.#config = Object.freeze({
797
1199
  ...CLIENT_DEFAULTS,
798
- apiKey,
799
- ...overrides
1200
+ ...overrides,
1201
+ credential: snapshotCredential(overrides.credential)
800
1202
  });
801
1203
  }
802
1204
  /**
803
1205
  * Dispatches a single resource-method call. Merges the frozen client
804
1206
  * config with the method's `methodDefaults` and the caller's optional
805
- * per-request `options`, routes through the effective-apiKey rate-limit
1207
+ * per-request `options`, routes through the effective-credential rate-limit
806
1208
  * queue, runs the retry loop, and finally parses the response with the
807
1209
  * spec's parser.
808
1210
  *
@@ -812,16 +1214,12 @@ var ResourceClient = class {
812
1214
  * caused the request to fail. Never throws.
813
1215
  * @rejects An unexpected collaborator failure unrelated to caller cancellation.
814
1216
  */
815
- async executeAsync({ options, parameters, refineError, spec }) {
1217
+ async executeAsync({ exemptsLockout, options, parameters, refineError, spec }) {
816
1218
  const start = startRequest(options);
817
1219
  if (!start.success) return start;
818
1220
  const { admission, lifecycle, requestOptions } = start.data;
819
- const merged = mergeConfig(this.#config, {
820
- methodDefaults: spec.methodDefaults,
821
- methodKind: spec.methodKind,
822
- requestOptions
823
- });
824
- const requestResult = spec.buildRequest(parameters);
1221
+ const { credential, merged } = authenticateCall(this.#merge(spec, requestOptions), spec);
1222
+ const requestResult = credentialNotSupportedFailure(spec, merged.credential) ?? spec.buildRequest(parameters);
825
1223
  if (!requestResult.success) return requestResult;
826
1224
  const request = requestResult.data;
827
1225
  const { signal } = admission;
@@ -834,6 +1232,8 @@ var ResourceClient = class {
834
1232
  return finishRequest({
835
1233
  httpResult: await this.#dispatchAsync({
836
1234
  admission,
1235
+ credential,
1236
+ exemptsLockout,
837
1237
  merged,
838
1238
  operationLimit: spec.operationLimit,
839
1239
  refineError,
@@ -841,8 +1241,10 @@ var ResourceClient = class {
841
1241
  requestConfig
842
1242
  }),
843
1243
  lifecycle,
1244
+ merged,
1245
+ request,
844
1246
  spec
845
- });
1247
+ }, this.#reportHint);
846
1248
  }
847
1249
  /**
848
1250
  * Returns the sleep function used by this client instance.
@@ -852,9 +1254,12 @@ var ResourceClient = class {
852
1254
  get sleep() {
853
1255
  return this.#sleep;
854
1256
  }
855
- async #dispatchAsync({ admission, merged, operationLimit, refineError, request, requestConfig }) {
856
- const queue = this.#getQueue(merged.apiKey, operationLimit);
1257
+ async #dispatchAsync({ admission, credential, exemptsLockout, merged, operationLimit, refineError, request, requestConfig }) {
1258
+ const credentialKey = callQueueKey(credential);
1259
+ const queue = this.#getQueue(credentialKey, operationLimit);
1260
+ const scope = budgetScopeFor(credentialKey, operationLimit);
857
1261
  try {
1262
+ this.#budgets.refuseDuringLockout(scope);
858
1263
  return await queue.acquireAsync(async () => {
859
1264
  return executeWithRetryAsync(request, {
860
1265
  admissionWaitObserver: admission.observer,
@@ -863,13 +1268,11 @@ var ResourceClient = class {
863
1268
  hooks: this.#hooks,
864
1269
  send: this.#gatedSend({
865
1270
  admission,
1271
+ credential,
1272
+ exemptsLockout,
866
1273
  refineError,
867
1274
  requestConfig,
868
- scope: {
869
- apiKey: merged.apiKey,
870
- documentedWindow: documentedWindow(operationLimit),
871
- operationKey: operationLimit.operationKey
872
- }
1275
+ scope
873
1276
  }),
874
1277
  signal: admission.signal,
875
1278
  sleep: this.#sleep
@@ -881,111 +1284,100 @@ var ResourceClient = class {
881
1284
  }
882
1285
  /**
883
1286
  * Builds the transport callback for one logical call, wrapping the HTTP
884
- * client with the budget gate: each attempt waits on the scope's budget
885
- * before sending, then folds the response's reported budget back in so the
886
- * next attempt (or a later call on the same scope) can head off a 429.
1287
+ * client with the budget gate: each attempt waits on the scope's budget,
1288
+ * then resolves the credential (an OAuth provider runs here, after every
1289
+ * admission wait) before sending, then folds the response's reported
1290
+ * budget back in so the next attempt (or a later call on the same scope)
1291
+ * can head off a 429. A provider failure, or a lockout that began while the
1292
+ * provider ran, ends the attempt unsent and gives its budget slot back.
887
1293
  *
888
1294
  * @param inputs - Budget scope, transport config, observer, and caller signal.
889
1295
  * @returns A send callback for {@link executeWithRetryAsync}.
890
1296
  */
891
- #gatedSend({ admission, refineError, requestConfig, scope }) {
1297
+ #gatedSend({ admission, credential, exemptsLockout, refineError, requestConfig, scope }) {
892
1298
  return async (toSend) => {
893
- await this.#budgets.gateAsync(scope, admission);
894
- const transportResult = await this.#httpClient.request(toSend, requestConfig);
895
- const sendResult = refineError === void 0 || transportResult.success ? transportResult : {
896
- err: refineError(transportResult.err),
1299
+ const reservation = await this.#budgets.gateAsync(scope, admission);
1300
+ const attempted = await resolveCallCredentialAsync(credential, admission.signal);
1301
+ const resolved = this.#budgets.refuseIfLockedOut(scope, attempted);
1302
+ if (!resolved.success) {
1303
+ reservation.release();
1304
+ return resolved;
1305
+ }
1306
+ const transportResult = await this.#httpClient.request(toSend, {
1307
+ ...requestConfig,
1308
+ credential: resolved.data
1309
+ });
1310
+ const sendResult = transportResult.success ? transportResult : {
1311
+ err: classifySendError(transportResult.err, {
1312
+ credential,
1313
+ refineError
1314
+ }),
897
1315
  success: false
898
1316
  };
899
- this.#budgets.observe(scope, rateLimitSampleFromResult(transportResult));
1317
+ observeAttempt(this.#budgets, {
1318
+ exemptsLockout,
1319
+ scope,
1320
+ transportResult
1321
+ });
900
1322
  return sendResult;
901
1323
  };
902
1324
  }
903
- #getQueue(apiKey, limit) {
904
- const key = `${apiKey}::${limit.operationKey}`;
1325
+ #getQueue(credentialKey, limit) {
1326
+ const key = scopeKey({
1327
+ credentialKey,
1328
+ operationKey: limit.operationKey
1329
+ });
905
1330
  const existing = this.#queues.get(key);
906
1331
  if (existing !== void 0) return existing;
907
1332
  const queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);
908
1333
  this.#queues.set(key, queue);
909
1334
  return queue;
910
1335
  }
1336
+ #merge(spec, requestOptions) {
1337
+ return mergeConfig(this.#config, {
1338
+ methodDefaults: spec.methodDefaults,
1339
+ methodKind: spec.methodKind,
1340
+ requestOptions
1341
+ });
1342
+ }
911
1343
  };
912
- function startRequest(options) {
913
- const callerSignal = options?.signal;
914
- if (callerSignal?.aborted === true) return {
915
- err: requestAbortedError(callerSignal),
916
- success: false
917
- };
918
- const lifecycle = requestLifecycle(options?.deadlineMs, callerSignal);
919
- const deadlineFailure = elapsedDeadlineFailure(lifecycle);
920
- if (deadlineFailure !== void 0) return {
921
- err: deadlineFailure,
922
- success: false
923
- };
924
- const { deadlineMs, onAdmissionWait, signal: _signal, ...requestOptions } = options ?? {};
1344
+ function budgetScopeFor(credentialKey, operationLimit) {
925
1345
  return {
926
- data: {
927
- admission: {
928
- deadlineMs,
929
- observer: onAdmissionWait,
930
- signal: lifecycle.signal
931
- },
932
- lifecycle,
933
- requestOptions
934
- },
935
- success: true
1346
+ credentialKey,
1347
+ documentedWindow: documentedWindow(operationLimit),
1348
+ operationKey: operationLimit.operationKey
936
1349
  };
937
1350
  }
938
1351
  function dispatchFailure(err) {
939
- if (err instanceof RequestAbortedError || err instanceof RequestDeadlineExceededError) return {
1352
+ if (err instanceof RequestAbortedError || err instanceof RequestDeadlineExceededError || err instanceof RateLimitWaitRefusedError) return {
940
1353
  err,
941
1354
  success: false
942
1355
  };
943
1356
  throw err;
944
1357
  }
945
- /**
946
- * Resolves the per-request {@link RequestConfig}. Upload requests
947
- * ({@link isUploadRequest}) carry no default timeout: a multi-megabyte place
948
- * file over a slow link is bandwidth-bound, so a transport-attempt timeout only
949
- * fires spuriously. An explicit `options.timeout` still applies to any
950
- * request; every non-upload request keeps the merged default.
951
- *
952
- * @param inputs - The merged config, the built request, and per-request overrides.
953
- * @returns The config to hand to the transport, with `timeout` omitted when
954
- * no transport-attempt timeout should apply.
955
- */
956
- function buildRequestConfig({ merged, options, request, signal }) {
957
- const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
958
- return {
959
- apiKey: merged.apiKey,
960
- baseUrl: merged.baseUrl,
961
- ...signal === void 0 ? {} : { signal },
962
- ...shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }
963
- };
964
- }
965
- function enrichPermissionError(err, spec) {
966
- if (spec.requiredScopes === void 0) return err;
967
- if (err instanceof PermissionError) return err;
968
- if (!(err instanceof ApiError)) return err;
969
- if (err.statusCode !== 401 && err.statusCode !== 403) return err;
970
- if (err.gatewaySummary !== void 0) return err;
971
- return new PermissionError(err.message, {
972
- ...requestContextOf(err),
973
- cause: err.cause,
974
- code: err.code,
975
- details: err.details,
1358
+ function finishRequest({ httpResult, lifecycle, merged, request, spec }, reportHint) {
1359
+ if (httpResult.success) {
1360
+ const parsed = spec.parse(httpResult.data);
1361
+ return parsed.success ? parsed : {
1362
+ err: withRequestContext(parsed.err, {
1363
+ baseUrl: merged.baseUrl,
1364
+ reportHint,
1365
+ request,
1366
+ response: httpResult.data
1367
+ }),
1368
+ success: false
1369
+ };
1370
+ }
1371
+ const err = deadlineFailureFromError(httpResult.err, lifecycle) ?? enrichPermissionError(httpResult.err, {
1372
+ credential: merged.credential,
976
1373
  operationKey: spec.operationLimit.operationKey,
977
- requiredScopes: spec.requiredScopes,
978
- statusCode: err.statusCode
1374
+ requiredScopes: spec.requiredScopes
979
1375
  });
980
- }
981
- function finishRequest({ httpResult, lifecycle, spec }) {
982
- if (httpResult.success) return spec.parse(httpResult.data);
983
1376
  return {
984
- err: deadlineFailureFromError(httpResult.err, lifecycle) ?? enrichPermissionError(httpResult.err, spec),
1377
+ err: recordPreviousAttempts(err, httpResult.err.previousAttempts),
985
1378
  success: false
986
1379
  };
987
1380
  }
988
- //#endregion
989
- export { observeAdmissionWaitAsync as a, isDateTimeString as c, waitDeadlineFailure as i, okRequest as n, toJsonDetails as o, parseEmptyResponse as r, isRecord as s, ResourceClient as t };
1381
+ export { waitDeadlineFailure as a, MAX_ABORT_TIMEOUT_MS as i, okRequest as n, observeAdmissionWaitAsync as o, parseEmptyResponse as r, toJsonDetails as s, ResourceClient as t };
990
1382
 
991
- //# sourceMappingURL=resource-client-rqTMkBeR.mjs.map
1383
+ //# sourceMappingURL=resource-client-Cm_bPcCs.mjs.map