@bedrock-rbx/ocale 0.3.4 → 0.4.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.
- package/README.md +9 -5
- package/dist/badge-cost-mismatch-DrlvhlQc.mjs +47 -0
- package/dist/badge-cost-mismatch-DrlvhlQc.mjs.map +1 -0
- package/dist/badges.d.mts +228 -184
- package/dist/badges.d.mts.map +1 -1
- package/dist/badges.mjs +176 -18
- package/dist/badges.mjs.map +1 -1
- package/dist/capacity-admission-hycCFkTo.d.mts +355 -0
- package/dist/capacity-admission-hycCFkTo.d.mts.map +1 -0
- package/dist/{data.generated-B2ceLfSn.d.mts → data.generated-D_vpa5-g.d.mts} +23 -23
- package/dist/data.generated-D_vpa5-g.d.mts.map +1 -0
- package/dist/developer-products.d.mts +181 -186
- package/dist/developer-products.d.mts.map +1 -1
- package/dist/developer-products.mjs +24 -24
- package/dist/developer-products.mjs.map +1 -1
- package/dist/game-passes.d.mts +206 -203
- package/dist/game-passes.d.mts.map +1 -1
- package/dist/game-passes.mjs +26 -21
- package/dist/game-passes.mjs.map +1 -1
- package/dist/index.d.mts +905 -343
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +325 -10
- package/dist/index.mjs.map +1 -1
- package/dist/locales.d.mts +30 -2
- package/dist/locales.d.mts.map +1 -0
- package/dist/locales.mjs +24 -1
- package/dist/locales.mjs.map +1 -1
- package/dist/luau-execution.d.mts +154 -151
- package/dist/luau-execution.d.mts.map +1 -1
- package/dist/luau-execution.mjs +11 -8
- package/dist/luau-execution.mjs.map +1 -1
- package/dist/{network-error-DR9FX5hb.mjs → network-error-iVSng5MT.mjs} +44 -6
- package/dist/network-error-iVSng5MT.mjs.map +1 -0
- package/dist/places.d.mts +204 -180
- package/dist/places.d.mts.map +1 -1
- package/dist/places.mjs +66 -20
- package/dist/places.mjs.map +1 -1
- package/dist/{poll-timeout-3PXLsabj.mjs → poll-timeout-DzztDymd.mjs} +2 -2
- package/dist/{poll-timeout-3PXLsabj.mjs.map → poll-timeout-DzztDymd.mjs.map} +1 -1
- package/dist/{polling-helpers-CoVhsC33.mjs → polling-helpers-DfF5dspc.mjs} +249 -83
- package/dist/polling-helpers-DfF5dspc.mjs.map +1 -0
- package/dist/{price-information-B0tkOoAX.mjs → price-information-DEkEQ8Pq.mjs} +2 -2
- package/dist/{price-information-B0tkOoAX.mjs.map → price-information-DEkEQ8Pq.mjs.map} +1 -1
- package/dist/resource-client-BCKukheG.d.mts +168 -0
- package/dist/resource-client-BCKukheG.d.mts.map +1 -0
- package/dist/{resource-client-rqTMkBeR.mjs → resource-client-CaIVr-go.mjs} +586 -158
- package/dist/resource-client-CaIVr-go.mjs.map +1 -0
- package/dist/retry-C2oHesDx.d.mts +229 -0
- package/dist/retry-C2oHesDx.d.mts.map +1 -0
- package/dist/{retry-BlX4tUnT.mjs → retry-CMRDvAR4.mjs} +278 -18
- package/dist/retry-CMRDvAR4.mjs.map +1 -0
- package/dist/storage.d.mts +333 -334
- package/dist/storage.d.mts.map +1 -1
- package/dist/storage.mjs +29 -22
- package/dist/storage.mjs.map +1 -1
- package/dist/testing.d.mts +347 -360
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +3 -4
- package/dist/testing.mjs.map +1 -1
- package/dist/types-CdMr_J1M.d.mts +509 -0
- package/dist/types-CdMr_J1M.d.mts.map +1 -0
- package/dist/universes.d.mts +619 -422
- package/dist/universes.d.mts.map +1 -1
- package/dist/universes.mjs +421 -48
- package/dist/universes.mjs.map +1 -1
- package/dist/{validation-B_Zs1So2.mjs → validation-964VNlbp.mjs} +2 -2
- package/dist/{validation-B_Zs1So2.mjs.map → validation-964VNlbp.mjs.map} +1 -1
- package/dist/wire-DJqupefn.d.mts +41 -0
- package/dist/wire-DJqupefn.d.mts.map +1 -0
- package/package.json +14 -14
- package/dist/capacity-admission-IDO3fcUC.d.mts +0 -369
- package/dist/capacity-admission-IDO3fcUC.d.mts.map +0 -1
- package/dist/data.generated-B2ceLfSn.d.mts.map +0 -1
- package/dist/network-error-DR9FX5hb.mjs.map +0 -1
- package/dist/polling-helpers-CoVhsC33.mjs.map +0 -1
- package/dist/resource-client-B6NeFXUv.d.mts +0 -164
- package/dist/resource-client-B6NeFXUv.d.mts.map +0 -1
- package/dist/resource-client-rqTMkBeR.mjs.map +0 -1
- package/dist/retry-BlX4tUnT.mjs.map +0 -1
- package/dist/retry-war_-9tb.d.mts +0 -373
- package/dist/retry-war_-9tb.d.mts.map +0 -1
- package/dist/types-CvYh4SPC.d.mts +0 -386
- package/dist/types-CvYh4SPC.d.mts.map +0 -1
- package/dist/wire-D3K-a-UP.d.mts +0 -37
- package/dist/wire-D3K-a-UP.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-client-CaIVr-go.mjs","names":["MS_PER_SECOND","ignoreRejection"],"sources":["../src/internal/utils/is-date-time-string.ts","../src/internal/utils/to-json-details.ts","../src/internal/api-key-only.ts","../src/internal/credential-snapshot.ts","../src/internal/http/admission-wait.ts","../src/internal/http/budget-tracker.ts","../src/internal/http/request-deadline.ts","../src/internal/http/budget-gate.ts","../src/internal/http/credential-rejection.ts","../src/internal/http/execute.ts","../src/internal/http/rate-limit-observation.ts","../src/internal/http/rate-limit-queue.ts","../src/internal/http/request-config.ts","../src/internal/utils/sleep.ts","../src/internal/http/resolve-dependencies.ts","../src/internal/http/start-request.ts","../src/internal/http/credential.ts","../src/internal/http/unauthenticated.ts","../src/internal/with-request-context.ts","../src/internal/resource-client.ts"],"sourcesContent":["/**\n * Narrows `value` to a string that parses to a real {@link Date} via the\n * `Date(string)` constructor. Used by resource parsers to gate\n * `format: date-time` wire fields before handing them to `new Date(...)`,\n * which silently produces an `Invalid Date` for invalid input.\n *\n * @param value - The unknown wire value to validate.\n * @returns `true` when `value` is a string and `new Date(value).getTime()`\n * is not `NaN`.\n */\nexport function isDateTimeString(value: unknown): value is string {\n\tif (typeof value !== \"string\") {\n\t\treturn false;\n\t}\n\n\tconst parsed = new Date(value);\n\treturn !Number.isNaN(parsed.getTime());\n}\n","import { isRecord } from \"./is-record.ts\";\n\n/**\n * Narrows an untyped response body to the `JSONValue` accepted by\n * `ApiError.details`. `HttpResponse.body` is `unknown` because a transport may\n * hand back anything, but only a JSON graph is safe to retain on an error for\n * diagnostics. Anything else — functions, symbols, bigints, class instances,\n * or a cyclic graph — is dropped rather than asserted through.\n *\n * @param value - The parsed response body, or `undefined` for an empty body.\n * @returns The value as a `JSONValue`, or `undefined` when it is absent or not\n * JSON-representable.\n */\nexport function toJsonDetails(value: unknown): JSONValue | undefined {\n\treturn asJsonValue(value, new Set());\n}\n\nfunction asJsonValue(value: unknown, seen: Set<object>): JSONValue | undefined {\n\tif (value === null) {\n\t\t// eslint-disable-next-line unicorn/no-null -- JSON null is a JSONValue; the repo's undefined-only rule stops at this wire boundary\n\t\treturn null;\n\t}\n\n\tif (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n\t\treturn value;\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn asJsonArray(value, seen);\n\t}\n\n\tif (isRecord(value)) {\n\t\treturn asJsonObject(value, seen);\n\t}\n\n\treturn undefined;\n}\n\nfunction asJsonArray(value: ReadonlyArray<unknown>, seen: Set<object>): JSONValue | undefined {\n\tif (seen.has(value)) {\n\t\treturn undefined;\n\t}\n\n\tseen.add(value);\n\tconst items: Array<JSONValue> = [];\n\tfor (const item of value) {\n\t\tconst converted = asJsonValue(item, seen);\n\t\tif (converted === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\titems.push(converted);\n\t}\n\n\tseen.delete(value);\n\treturn items;\n}\n\nfunction asJsonObject(value: Record<string, unknown>, seen: Set<object>): JSONValue | undefined {\n\tif (seen.has(value)) {\n\t\treturn undefined;\n\t}\n\n\tseen.add(value);\n\tconst entries: Array<[string, JSONValue]> = [];\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tconst converted = asJsonValue(item, seen);\n\t\tif (converted === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tentries.push([key, converted]);\n\t}\n\n\tseen.delete(value);\n\treturn Object.fromEntries(entries);\n}\n","import type { Credential } from \"../client/types.ts\";\nimport { CredentialNotSupportedError } from \"../errors/credential-not-supported.ts\";\nimport type { Result } from \"../types.ts\";\nimport type { OperationLimit } from \"./http/rate-limit-queue.ts\";\n\n/** The parts of a method spec the API-key-only check reads. */\ninterface ApiKeyOnlySpec {\n\treadonly apiKeyOnly?: boolean;\n\treadonly operationLimit: OperationLimit;\n}\n\n/**\n * Fails an OAuth call to an Operation that Roblox accepts only with an API\n * key. Runs before the provider is asked for a token and before any request.\n *\n * @param spec - The method spec's flag and operation limit.\n * @param credential - The effective credential for the call.\n * @returns A {@link CredentialNotSupportedError} failure, or `undefined` when\n * the call may proceed.\n */\nexport function credentialNotSupportedFailure(\n\tspec: ApiKeyOnlySpec,\n\tcredential: Credential,\n): Result<never, CredentialNotSupportedError> | undefined {\n\tif (spec.apiKeyOnly !== true || credential.kind !== \"oauth\") {\n\t\treturn undefined;\n\t}\n\n\tconst { operationKey } = spec.operationLimit;\n\treturn {\n\t\terr: new CredentialNotSupportedError(\n\t\t\t`Operation ${operationKey} accepts only an API key credential`,\n\t\t\t{ operationKey },\n\t\t),\n\t\tsuccess: false,\n\t};\n}\n","import type { Credential } from \"../client/types.ts\";\n\n/**\n * Copies a caller's credential, so a later change to the caller's object\n * cannot change the key or the OAuth identity a client or a queued request\n * uses. An OAuth provider stays a call on the caller's object, so a class\n * method keeps its `this`.\n *\n * @param credential - The caller's credential.\n * @returns A copy the caller does not hold.\n */\nexport function snapshotCredential(credential: Credential): Credential {\n\tif (credential.kind !== \"oauth\") {\n\t\treturn { ...credential };\n\t}\n\n\treturn {\n\t\tgetAccessToken: async (context) => credential.getAccessToken(context),\n\t\tidentity: credential.identity,\n\t\tkind: \"oauth\",\n\t};\n}\n\n/**\n * Copies the credential of a per-request override, if it has one.\n *\n * @template T - The override shape.\n * @param options - The caller's per-request overrides.\n * @returns The overrides, with a credential the caller does not hold.\n */\nexport function withCredentialSnapshot<T extends { readonly credential?: Credential }>(\n\toptions: T,\n): T {\n\treturn options.credential === undefined\n\t\t? options\n\t\t: { ...options, credential: snapshotCredential(options.credential) };\n}\n","import type {\n\tAdmissionWaitEvent,\n\tAdmissionWaitObserver,\n\tAdmissionWaitReason,\n} from \"../../client/types.ts\";\n\n/** Request-local controls shared by SDK admission mechanisms. */\nexport interface AdmissionWaitContext {\n\t/**\n\t * Absolute deadline for the logical request, as Unix epoch milliseconds.\n\t */\n\treadonly deadlineMs?: number | undefined;\n\t/** Observer for this request's admission waits. */\n\treadonly observer?: AdmissionWaitObserver | undefined;\n\t/** Optional caller cancellation signal. */\n\treadonly signal?: AbortSignal | undefined;\n}\n\ninterface ObserveAdmissionWaitOptions<T> {\n\t/** Intended wait duration, when the scheduler can determine one. */\n\treadonly durationMs?: number;\n\t/** Request-scoped notification callback. */\n\treadonly observer?: AdmissionWaitObserver | undefined;\n\t/** SDK admission mechanism responsible for the wait. */\n\treadonly reason: AdmissionWaitReason;\n\t/** The actual wait to perform. */\n\treadonly waitAsync: () => Promise<T>;\n}\n\n/**\n * Performs one SDK-managed wait and emits a balanced request-scoped lifecycle.\n * Observer failures are deliberately ignored: observation cannot become part\n * of admission control.\n *\n * @template T - Value produced by the observed wait.\n * @param options - Wait metadata, observer, and the wait operation itself.\n * @returns The value produced by the wait.\n */\nexport async function observeAdmissionWaitAsync<T>({\n\tdurationMs,\n\tobserver,\n\treason,\n\twaitAsync,\n}: ObserveAdmissionWaitOptions<T>): Promise<T> {\n\tconst details = {\n\t\t...(durationMs === undefined ? {} : { durationMs }),\n\t\treason,\n\t};\n\tnotify(observer, { ...details, phase: \"started\" });\n\ttry {\n\t\treturn await waitAsync();\n\t} finally {\n\t\tnotify(observer, { ...details, phase: \"ended\" });\n\t}\n}\n\nfunction notify(observer: AdmissionWaitObserver | undefined, event: AdmissionWaitEvent): void {\n\ttry {\n\t\tconst notification = observer?.(event);\n\t\tif (notification !== undefined) {\n\t\t\t// `Boolean` consumes every rejection without throwing; the returned\n\t\t\t// promise and its boolean fulfillment are deliberately ignored.\n\t\t\tvoid Promise.resolve(notification).catch(Boolean);\n\t\t}\n\t} catch {\n\t\t// Admission observers are notification-only and cannot alter control\n\t\t// flow.\n\t}\n}\n","import type { RateLimitSample, RateLimitWindow } from \"./rate-limit-sample.ts\";\n\nconst MS_PER_SECOND = 1000;\n\n/**\n * One budget slot taken by {@link BudgetTracker.reserve}. Release it when the\n * request it paced is not sent.\n */\nexport interface BudgetReservation {\n\t/**\n\t * Gives the slot back: restores the budget when the window it came from is\n\t * still in force, and restores the pacing clock when no later reservation\n\t * has moved it. A second call does nothing.\n\t */\n\treadonly release: () => void;\n}\n\n/** Live window state for one scope: budget left and when it resets. */\ninterface WindowState {\n\t/** Best estimate of requests still allowed before the window resets. */\n\treadonly predictedRemaining: number;\n\t/** Absolute time (ms) the window resets to full. */\n\treadonly resetAt: number;\n\t/**\n\t * Fixed spacing (ms) between sends in a window opened by rollover, or\n\t * `undefined` for a window a server reading primed.\n\t */\n\treadonly spacingMs?: number;\n}\n\n/**\n * Tracks the live rate-limit budget for a single scope. Primed by `observe`\n * from response headers and drawn down by `reserve` as requests leave, so\n * `waitMs` can pace requests across the window.\n *\n * Pacing has two regimes. While budget remains, requests are spread evenly over\n * the time left in the window (`timeLeft / remaining`), so a burst does not\n * spend the whole window's budget up front and then stall. Once the budget is\n * spent, requests hold until the window resets. Budget and reset time move\n * together as one window, so the tracker is either unprimed or fully primed,\n * never half-known.\n *\n * Once a primed window's reset passes with no fresh reading, the next window\n * opens holding the scope's capacity: the last capacity a response reported,\n * or the operation's documented one. Requests queued behind a reset are\n * admitted at that capacity per window, spaced one window-length divided by\n * capacity apart.\n */\nexport class BudgetTracker {\n\t/** Time (ms) the most recent request was allowed out, for spacing. */\n\t#lastAllowedAt: number | undefined = undefined;\n\t/** Token of the latest reservation, compared by identity. */\n\t#latestReservation: object | undefined = undefined;\n\t/** Requests the server grants per window, used when a window rolls over. */\n\t#rolloverWindow: RateLimitWindow;\n\t#window: undefined | WindowState = undefined;\n\t/**\n\t * Token of the window in force, compared by identity. A new window gets a\n\t * new token, so a release can tell its window is gone.\n\t */\n\t#windowToken: object = {};\n\n\t/**\n\t * Creates a tracker for one scope.\n\t *\n\t * @param documentedWindow - The operation's documented capacity, used\n\t * until a response reports one.\n\t */\n\tconstructor(documentedWindow: RateLimitWindow) {\n\t\tthis.#rolloverWindow = documentedWindow;\n\t}\n\n\t/**\n\t * Folds a fresh server reading in, replacing any prior window. The latest\n\t * reading wins: observe time is monotonic, so the most recently resolved\n\t * response is the best current estimate. The spacing reference is left\n\t * untouched so a window refresh does not reset pacing mid-stream.\n\t *\n\t * @param sample - Parsed `remaining`/`resetSeconds` from a response.\n\t * @param now - The current time in ms.\n\t */\n\tpublic observe(sample: RateLimitSample, now: number): void {\n\t\tthis.#rolloverWindow = sample.window ?? this.#rolloverWindow;\n\t\tthis.#windowToken = {};\n\t\tthis.#window = {\n\t\t\tpredictedRemaining: sample.remaining,\n\t\t\tresetAt: now + sample.resetSeconds * MS_PER_SECOND,\n\t\t};\n\t}\n\n\t/**\n\t * Accounts for one request leaving at `now`: records the spacing reference\n\t * and decrements the prediction. A no-op on the prediction while unprimed.\n\t *\n\t * @param now - The time the request was allowed out, in ms.\n\t * @returns The reservation, to release if the request is not sent.\n\t */\n\tpublic reserve(now: number): BudgetReservation {\n\t\tconst previousAllowedAt = this.#lastAllowedAt;\n\t\tthis.#lastAllowedAt = now;\n\t\tconst reservation = {};\n\t\tthis.#latestReservation = reservation;\n\t\tconst window = this.#windowAt(now);\n\t\tif (window !== undefined) {\n\t\t\tthis.#window = { ...window, predictedRemaining: window.predictedRemaining - 1 };\n\t\t}\n\n\t\tconst windowToken = this.#windowToken;\n\t\tlet isReleased = false;\n\t\treturn {\n\t\t\trelease: () => {\n\t\t\t\tif (isReleased) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tisReleased = true;\n\t\t\t\tthis.#release({ previousAllowedAt, reservation, windowToken });\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Milliseconds to wait before the next request is allowed.\n\t *\n\t * @param now - The current time in ms.\n\t * @returns `0` when a request may go now (unprimed, or the first paced send);\n\t * the time until reset when the budget is spent; otherwise the time until\n\t * this request's evenly-spaced slot.\n\t */\n\tpublic waitMs(now: number): number {\n\t\tconst window = this.#windowAt(now);\n\t\tif (window === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst { predictedRemaining, resetAt } = window;\n\t\tif (predictedRemaining <= 0) {\n\t\t\treturn Math.max(0, resetAt - now);\n\t\t}\n\n\t\tif (this.#lastAllowedAt === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst interval = window.spacingMs ?? (resetAt - now) / predictedRemaining;\n\t\treturn Math.max(0, this.#lastAllowedAt + interval - now);\n\t}\n\n\t#release({\n\t\tpreviousAllowedAt,\n\t\treservation,\n\t\twindowToken,\n\t}: {\n\t\treadonly previousAllowedAt: number | undefined;\n\t\treadonly reservation: object;\n\t\treadonly windowToken: object;\n\t}): void {\n\t\tif (reservation === this.#latestReservation) {\n\t\t\tthis.#lastAllowedAt = previousAllowedAt;\n\t\t}\n\n\t\tif (this.#window !== undefined && windowToken === this.#windowToken) {\n\t\t\tthis.#window = {\n\t\t\t\t...this.#window,\n\t\t\t\tpredictedRemaining: this.#window.predictedRemaining + 1,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * The window in force at `now`, opening the next one at full capacity once\n\t * the current window's reset has passed.\n\t *\n\t * @param now - The current time in ms.\n\t * @returns The live window, or `undefined` while unprimed.\n\t */\n\t#windowAt(now: number): undefined | WindowState {\n\t\tif (this.#window !== undefined && now >= this.#window.resetAt) {\n\t\t\tconst { capacity, windowSeconds } = this.#rolloverWindow;\n\t\t\tconst windowMs = windowSeconds * MS_PER_SECOND;\n\t\t\tthis.#windowToken = {};\n\t\t\tthis.#window = {\n\t\t\t\tpredictedRemaining: capacity,\n\t\t\t\tresetAt: now + windowMs,\n\t\t\t\tspacingMs: windowMs / capacity,\n\t\t\t};\n\t\t}\n\n\t\treturn this.#window;\n\t}\n}\n","import type { AdmissionWaitReason } from \"../../client/types.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { RequestAbortedError } from \"../../errors/request-aborted.ts\";\nimport {\n\tRequestDeadlineExceededError,\n\ttype RequestDeadlineExceededErrorOptions,\n} from \"../../errors/request-deadline-exceeded.ts\";\n\nconst DEADLINE_ELAPSED = Symbol(\"request deadline elapsed\");\n/** The longest delay a timer accepts; `AbortSignal.timeout` throws above it. */\nexport const MAX_ABORT_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * Request-lifecycle signals derived from caller cancellation and a deadline.\n */\nexport interface RequestLifecycle {\n\t/** Caller-supplied absolute deadline, as Unix epoch milliseconds. */\n\treadonly deadlineMs: number | undefined;\n\t/** Signal owned by the deadline, used to classify its expiry. */\n\treadonly deadlineSignal: AbortSignal | undefined;\n\t/** Caller and deadline signals composed for every stage of the request. */\n\treadonly signal: AbortSignal | undefined;\n}\n\ninterface WaitDeadlineInputs {\n\treadonly cause?: Error | undefined;\n\treadonly deadlineMs: number | undefined;\n\treadonly waitMs: number;\n\treadonly waitReason: AdmissionWaitReason;\n}\n\n/**\n * Resolves one signal that spans the whole logical request.\n *\n * @param deadlineMs - Absolute deadline, as Unix epoch milliseconds.\n * @param callerSignal - Optional caller cancellation signal.\n * @returns Signals that span and classify the logical request.\n */\nexport function requestLifecycle(\n\tdeadlineMs: number | undefined,\n\tcallerSignal: AbortSignal | undefined,\n): RequestLifecycle {\n\tif (deadlineMs === undefined) {\n\t\treturn { deadlineMs, deadlineSignal: undefined, signal: callerSignal };\n\t}\n\n\tconst deadlineSignal = deadlineTimeout(deadlineMs);\n\tconst signal =\n\t\tcallerSignal === undefined\n\t\t\t? deadlineSignal\n\t\t\t: AbortSignal.any([callerSignal, deadlineSignal]);\n\treturn { deadlineMs, deadlineSignal, signal };\n}\n\n/**\n * Returns a typed failure when the deadline signal ended the request.\n *\n * @param lifecycle - Signals and timestamp for the logical request.\n * @param cause - The failure the deadline failure replaces, if any.\n * @returns A deadline failure, or `undefined` when another signal won.\n */\nexport function elapsedDeadlineFailure(\n\t{ deadlineMs, deadlineSignal, signal }: RequestLifecycle,\n\tcause?: OpenCloudError,\n): RequestDeadlineExceededError | undefined {\n\tif (\n\t\tdeadlineMs === undefined ||\n\t\tdeadlineSignal?.aborted !== true ||\n\t\t!Object.is(signal?.reason, deadlineSignal.reason)\n\t) {\n\t\treturn undefined;\n\t}\n\n\treturn new RequestDeadlineExceededError(\"Request deadline elapsed\", {\n\t\tcause,\n\t\tdeadlineMs,\n\t\tremainingMs: 0,\n\t});\n}\n\n/**\n * Reclassifies an internal abort when the request deadline supplied its signal.\n * The abort becomes the deadline failure's `cause`.\n *\n * @param error - Error returned by the request pipeline.\n * @param lifecycle - Signals and timestamp for the logical request.\n * @returns A deadline failure, or `undefined` for other failures.\n */\nexport function deadlineFailureFromError(\n\terror: OpenCloudError,\n\tlifecycle: RequestLifecycle,\n): RequestDeadlineExceededError | undefined {\n\treturn error instanceof RequestAbortedError\n\t\t? elapsedDeadlineFailure(lifecycle, error)\n\t\t: undefined;\n}\n\n/**\n * Refuses a known admission wait that cannot fit before the deadline.\n *\n * @param inputs - Deadline, wait duration, reason, and optional cause.\n * @returns A typed refusal, or `undefined` when the wait fits.\n */\nexport function waitDeadlineFailure({\n\tcause,\n\tdeadlineMs,\n\twaitMs,\n\twaitReason,\n}: WaitDeadlineInputs): RequestDeadlineExceededError | undefined {\n\tif (deadlineMs === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst now = Date.now();\n\tconst remainingMs = Math.max(0, deadlineMs - now);\n\tif (now < deadlineMs && waitMs <= remainingMs) {\n\t\treturn undefined;\n\t}\n\n\tconst options: RequestDeadlineExceededErrorOptions = {\n\t\tcause,\n\t\tdeadlineMs,\n\t\tremainingMs,\n\t\twaitMs,\n\t\twaitReason,\n\t};\n\treturn new RequestDeadlineExceededError(waitMessage(waitMs, remainingMs), options);\n}\n\nfunction armDeadlineTimeout(controller: AbortController, deadlineMs: number): void {\n\tconst remainingMs = deadlineMs - Date.now();\n\tif (remainingMs <= 0) {\n\t\tcontroller.abort(DEADLINE_ELAPSED);\n\t\treturn;\n\t}\n\n\tconst timeout = AbortSignal.timeout(Math.min(Math.ceil(remainingMs), MAX_ABORT_TIMEOUT_MS));\n\ttimeout.addEventListener(\"abort\", () => {\n\t\tarmDeadlineTimeout(controller, deadlineMs);\n\t});\n}\n\nfunction deadlineTimeout(deadlineMs: number): AbortSignal {\n\tconst controller = new AbortController();\n\tif (Number.isFinite(deadlineMs)) {\n\t\tarmDeadlineTimeout(controller, deadlineMs);\n\t} else {\n\t\tcontroller.abort(DEADLINE_ELAPSED);\n\t}\n\n\treturn controller.signal;\n}\n\nfunction waitMessage(waitMs: number, remainingMs: number): string {\n\treturn `Admission wait would take ${waitMs / 1000}s; ${remainingMs / 1000}s remain before the request deadline`;\n}\n","import type { OpenCloudError } from \"../../errors/base.ts\";\nimport { RateLimitWaitRefusedError } from \"../../errors/rate-limit-wait-refused.ts\";\nimport { RateLimitError } from \"../../errors/rate-limit.ts\";\nimport type { Result } from \"../../types.ts\";\nimport { ABORTED, raceWithAbortAsync, requestAbortedError } from \"../utils/abort.ts\";\nimport type { SleepFunc } from \"../utils/sleep.ts\";\nimport { type AdmissionWaitContext, observeAdmissionWaitAsync } from \"./admission-wait.ts\";\nimport { type BudgetReservation, BudgetTracker } from \"./budget-tracker.ts\";\nimport type { RateLimitSample, RateLimitWindow } from \"./rate-limit-sample.ts\";\nimport { waitDeadlineFailure } from \"./request-deadline.ts\";\n\nconst REPORTED_BUDGET_REASON = \"reported-budget\";\nconst MS_PER_SECOND = 1000;\n\n/**\n * Identifies the rate-limit bucket one request draws on: Roblox meters each\n * operation in its own per-credential bucket.\n */\nexport interface BudgetScope {\n\t/** The effective credential's queue key, namespaced by kind. */\n\treadonly credentialKey: string;\n\t/**\n\t * The operation's documented capacity, admitted per window once a reset\n\t * passes before any response has reported the real one.\n\t */\n\treadonly documentedWindow: RateLimitWindow;\n\t/** The operation the request belongs to. */\n\treadonly operationKey: string;\n}\n\n/** A refused long 429 and the instant its scope may send again. */\ninterface Lockout {\n\treadonly cause: RateLimitError;\n\treadonly resetAt: number;\n}\n\n/**\n * Header-primed rate-limit gate shared across a client. Holds one\n * {@link BudgetTracker} per {@link BudgetScope}. Before each request the caller\n * gates on the request's scope (sleeping if that budget is spent), and after\n * each response folds the parsed sample back in, so a later call on the same\n * scope can head off a 429 the static per-operation token bucket cannot\n * foresee.\n *\n * Gating is serialized per scope through a promise chain so concurrent\n * requests on one scope cannot read the same budget and reserve the same slot;\n * each waits for the prior gate's reserve before computing its own.\n */\nexport class BudgetGate {\n\treadonly #chains = new Map<string, Promise<void>>();\n\treadonly #lockouts = new Map<string, Lockout>();\n\treadonly #pendingGates = new Map<string, number>();\n\treadonly #sleep: SleepFunc;\n\treadonly #trackers = new Map<string, BudgetTracker>();\n\n\t/**\n\t * Creates a gate bound to an injectable sleep.\n\t *\n\t * @param sleep - Injectable sleep (tests pass a fake clock).\n\t */\n\tconstructor(sleep: SleepFunc) {\n\t\tthis.#sleep = sleep;\n\t}\n\n\t/**\n\t * Holds until the scope's budget permits a send, then reserves one slot.\n\t * Runs after the prior gate on the same scope settles, whether it resolved\n\t * or rejected, so one failed attempt cannot poison later gates on the\n\t * scope.\n\t *\n\t * @param scope - The credential and operation to gate on.\n\t * @param context - Request-local observer and cancellation signal.\n\t * @returns The reserved slot. Release it when the request is not sent.\n\t * @rejects {@link RequestAbortedError} when the caller cancels while waiting.\n\t * @rejects {@link RateLimitWaitRefusedError} while the scope is locked out.\n\t */\n\tpublic async gateAsync(\n\t\tscope: BudgetScope,\n\t\t{ deadlineMs, observer, signal }: AdmissionWaitContext = {},\n\t): Promise<BudgetReservation> {\n\t\tconst key = scopeKey(scope);\n\t\tconst pendingGates = this.#pendingGates.get(key) ?? 0;\n\t\tconst waitsForEarlierGate = pendingGates > 0;\n\t\tthis.#pendingGates.set(key, pendingGates + 1);\n\t\tconst previous = this.#chains.get(key) ?? Promise.resolve();\n\t\tconst recovered = previous.catch(ignoreRejection);\n\t\tconst mine = recovered.then(async () => {\n\t\t\treturn this.#gateOnce(scope, {\n\t\t\t\tdeadlineMs,\n\t\t\t\tobserver: waitsForEarlierGate ? undefined : observer,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t});\n\t\tconst completed = mine.finally(() => {\n\t\t\tconst remainingGates = (this.#pendingGates.get(key) ?? 1) - 1;\n\t\t\tthis.#pendingGates.set(key, remainingGates);\n\t\t});\n\t\tthis.#chains.set(key, completed.then(ignoreRejection).catch(ignoreRejection));\n\t\tif (waitsForEarlierGate) {\n\t\t\treturn observeAdmissionWaitAsync({\n\t\t\t\tobserver,\n\t\t\t\treason: REPORTED_BUDGET_REASON,\n\t\t\t\twaitAsync: async () => waitForGateAsync(completed, signal),\n\t\t\t});\n\t\t}\n\n\t\treturn waitForGateAsync(completed, signal);\n\t}\n\n\t/**\n\t * Locks the scope out until the refused 429's guided wait ends. Until then\n\t * every gate on the scope is refused at once, without sleeping or\n\t * reserving budget. The latest lockout replaces any earlier one.\n\t *\n\t * @param scope - The same scope passed to {@link gateAsync}.\n\t * @param cause - The 429 whose guided wait was too long to take.\n\t */\n\tpublic lockOut(scope: BudgetScope, cause: RateLimitError): void {\n\t\tthis.#lockouts.set(scopeKey(scope), {\n\t\t\tcause,\n\t\t\tresetAt: Date.now() + cause.retryAfterSeconds * MS_PER_SECOND,\n\t\t});\n\t}\n\n\t/**\n\t * Folds a response's parsed budget back onto the scope. A `undefined`\n\t * sample (headers absent or non-numeric) is ignored, leaving the scope on\n\t * static pacing.\n\t *\n\t * @param scope - The same scope passed to {@link gateAsync}.\n\t * @param sample - Parsed sample, or `undefined` when none was reported.\n\t */\n\tpublic observe(scope: BudgetScope, sample: RateLimitSample | undefined): void {\n\t\tif (sample === undefined) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#tracker(scopeKey(scope), scope.documentedWindow).observe(sample, Date.now());\n\t}\n\n\t/**\n\t * Refuses a request at once while its scope is locked out, so it fails\n\t * before taking a static queue slot or waiting on anything.\n\t *\n\t * @param scope - The same scope passed to {@link gateAsync}.\n\t * @throws {@link RateLimitWaitRefusedError} While the scope is locked out.\n\t */\n\tpublic refuseDuringLockout(scope: BudgetScope): void {\n\t\tthis.#refuseDuringLockout(scopeKey(scope));\n\t}\n\n\t/**\n\t * Swaps a request's result for the lockout refusal while its scope is\n\t * locked out, for a lockout that began after the request passed its gate.\n\t *\n\t * @param scope - The same scope passed to {@link gateAsync}.\n\t * @param result - The request's result so far.\n\t * @returns The refusal while the scope is locked out, else `result`.\n\t */\n\tpublic refuseIfLockedOut<T>(\n\t\tscope: BudgetScope,\n\t\tresult: Result<T, OpenCloudError>,\n\t): Result<T, OpenCloudError> {\n\t\tconst refusal = this.#lockoutRefusal(scopeKey(scope));\n\t\treturn refusal === undefined ? result : { err: refusal, success: false };\n\t}\n\n\tasync #gateOnce(\n\t\tscope: BudgetScope,\n\t\t{ deadlineMs, observer, signal }: AdmissionWaitContext,\n\t): Promise<BudgetReservation> {\n\t\tif (signal?.aborted === true) {\n\t\t\tthrow requestAbortedError(signal);\n\t\t}\n\n\t\tconst key = scopeKey(scope);\n\t\tconst tracker = this.#tracker(key, scope.documentedWindow);\n\n\t\tthis.#refuseDuringLockout(key);\n\t\tconst waitMs = tracker.waitMs(Date.now());\n\t\tif (waitMs > 0) {\n\t\t\tawait this.#waitAsync(waitMs, { deadlineMs, observer, signal });\n\t\t\tthis.#refuseDuringLockout(key);\n\t\t}\n\n\t\treturn tracker.reserve(Date.now());\n\t}\n\n\t#lockoutRefusal(key: string): RateLimitWaitRefusedError | undefined {\n\t\tconst lockout = this.#lockouts.get(key);\n\t\tconst now = Date.now();\n\t\treturn lockout !== undefined && now < lockout.resetAt\n\t\t\t? lockoutRefusal(lockout, now)\n\t\t\t: undefined;\n\t}\n\n\t#refuseDuringLockout(key: string): void {\n\t\tconst refusal = this.#lockoutRefusal(key);\n\t\tif (refusal !== undefined) {\n\t\t\tthrow refusal;\n\t\t}\n\t}\n\n\t#tracker(key: string, documentedWindow: RateLimitWindow): BudgetTracker {\n\t\tconst existing = this.#trackers.get(key);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst tracker = new BudgetTracker(documentedWindow);\n\t\tthis.#trackers.set(key, tracker);\n\t\treturn tracker;\n\t}\n\n\tasync #waitAsync(\n\t\twaitMs: number,\n\t\t{ deadlineMs, observer, signal }: AdmissionWaitContext,\n\t): Promise<void> {\n\t\tconst refusal = waitDeadlineFailure({\n\t\t\tdeadlineMs,\n\t\t\twaitMs,\n\t\t\twaitReason: REPORTED_BUDGET_REASON,\n\t\t});\n\t\tif (refusal !== undefined) {\n\t\t\tthrow refusal;\n\t\t}\n\n\t\tawait observeAdmissionWaitAsync({\n\t\t\tdurationMs: waitMs,\n\t\t\tobserver,\n\t\t\treason: REPORTED_BUDGET_REASON,\n\t\t\twaitAsync: async () => {\n\t\t\t\tconst sleepResult = await raceWithAbortAsync(\n\t\t\t\t\tasync () => this.#sleep(waitMs, signal),\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t\tif (sleepResult === ABORTED) {\n\t\t\t\t\tthrow requestAbortedError(signal);\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t}\n}\n\n/**\n * Composes the map key one credential and operation are tracked under. The\n * budget gate and the rate-limit queues share it.\n *\n * @param scope - The credential key and operation naming the window.\n * @returns The key for the tracker, chain and queue maps.\n */\nexport function scopeKey({\n\tcredentialKey,\n\toperationKey,\n}: Pick<BudgetScope, \"credentialKey\" | \"operationKey\">): string {\n\treturn `${credentialKey}::${operationKey}`;\n}\n\nfunction lockoutRefusal({ cause, resetAt }: Lockout, now: number): RateLimitWaitRefusedError {\n\tconst secondsLeft = Math.ceil((resetAt - now) / MS_PER_SECOND);\n\tconst remainingLockout = new RateLimitError(cause.message, {\n\t\tcause,\n\t\tcode: cause.code,\n\t\tdetails: cause.details,\n\t\tremaining: cause.remaining,\n\t\tresponseHeaders: cause.responseHeaders,\n\t\tretryAfterSeconds: secondsLeft,\n\t\tsource: cause.source,\n\t\tstatusCode: cause.statusCode,\n\t});\n\treturn new RateLimitWaitRefusedError(\n\t\t`Rate limit lockout on this operation lasts another ${secondsLeft}s; request not sent`,\n\t\t{ cause: remainingLockout },\n\t);\n}\n\nfunction ignoreRejection(): void {\n\t// A failed or cancelled gate must not poison the next caller's chain.\n}\n\nasync function waitForGateAsync(\n\tgate: Promise<BudgetReservation>,\n\tsignal: AbortSignal | undefined,\n): Promise<BudgetReservation> {\n\tconst gateResult = await raceWithAbortAsync(async () => gate, signal);\n\tif (gateResult === ABORTED) {\n\t\tthrow requestAbortedError(signal);\n\t}\n\n\treturn gateResult;\n}\n","import type { Credential } from \"../../client/types.ts\";\nimport { ApiError, requestContextOf } from \"../../errors/api-error.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { CredentialRejectedError } from \"../../errors/credential-rejected.ts\";\nimport { PermissionError } from \"../../errors/permission-error.ts\";\nimport { extractErrorMessage } from \"./error-body.ts\";\n\n/** The v1 body message Roblox sends on a 502 after an app removal. */\nconst SCOPE_AUTHORIZATION_FAILED = \"Scope authorization failed.\";\n\nconst OAUTH_PERMISSION_HINT =\n\t\"The OAuth grant may not include the required scope or this universe.\";\n\n/** What the permission upgrade needs to know about the call. */\nexport interface PermissionContext {\n\t/** The effective credential of the call. */\n\treadonly credential: Credential;\n\t/** The operation key named on the upgraded error. */\n\treadonly operationKey: string;\n\t/**\n\t * The scopes the method declares, if any. Without them there is no\n\t * upgrade.\n\t */\n\treadonly requiredScopes: ReadonlyArray<string> | undefined;\n}\n\n/**\n * Turns Roblox's refusal of an OAuth token into a\n * {@link CredentialRejectedError}: a non-gateway 401, or a non-gateway 502\n * whose body message is \"Scope authorization failed.\". The result is not an\n * `ApiError`, so the retry loop never retries it. Every other error, and\n * every error on an API-key credential, passes through unchanged.\n *\n * @param err - The transport error for one attempt.\n * @param credential - The effective credential of the call.\n * @returns The classified error.\n */\nexport function classifyCredentialRejection(\n\terr: OpenCloudError,\n\tcredential: Credential,\n): OpenCloudError {\n\tif (credential.kind !== \"oauth\" || !isTokenRefusal(err)) {\n\t\treturn err;\n\t}\n\n\treturn new CredentialRejectedError(err.message, {\n\t\tcause: err,\n\t\tcode: err.code,\n\t\tidentity: credential.identity,\n\t\tstatusCode: err.statusCode,\n\t});\n}\n\n/**\n * Upgrades a non-gateway 401 or 403 `ApiError` to a {@link PermissionError}\n * when the method declares its scopes. On an OAuth credential the message\n * adds a hint that the grant may not include the scope or this universe.\n *\n * @param err - The final error of the call.\n * @param context - The credential, operation key and declared scopes.\n * @returns The upgraded error, or `err` unchanged.\n */\nexport function enrichPermissionError(\n\terr: OpenCloudError,\n\t{ credential, operationKey, requiredScopes }: PermissionContext,\n): OpenCloudError {\n\tif (requiredScopes === undefined) {\n\t\treturn err;\n\t}\n\n\tif (err instanceof PermissionError) {\n\t\treturn err;\n\t}\n\n\tif (!(err instanceof ApiError)) {\n\t\treturn err;\n\t}\n\n\tif (err.statusCode !== 401 && err.statusCode !== 403) {\n\t\treturn err;\n\t}\n\n\t// An edge gateway answers 401 and 403 for its own reasons, and the request\n\t// never reached the operation whose scopes these are.\n\tif (err.gatewaySummary !== undefined) {\n\t\treturn err;\n\t}\n\n\treturn new PermissionError(permissionMessage(err.message, credential), {\n\t\t...requestContextOf(err),\n\t\tcause: err.cause,\n\t\tcode: err.code,\n\t\tdetails: err.details,\n\t\toperationKey,\n\t\trequiredScopes,\n\t\tstatusCode: err.statusCode,\n\t});\n}\n\nfunction isTokenRefusal(err: OpenCloudError): err is ApiError {\n\tif (!(err instanceof ApiError) || err.gatewaySummary !== undefined) {\n\t\treturn false;\n\t}\n\n\treturn (\n\t\terr.statusCode === 401 ||\n\t\t(err.statusCode === 502 && extractErrorMessage(err.details) === SCOPE_AUTHORIZATION_FAILED)\n\t);\n}\n\nfunction permissionMessage(message: string, credential: Credential): string {\n\tif (credential.kind !== \"oauth\") {\n\t\treturn message;\n\t}\n\n\tconst separator = message.endsWith(\".\") ? \" \" : \". \";\n\treturn `${message}${separator}${OAUTH_PERMISSION_HINT}`;\n}\n","import { type OpenCloudError, recordPreviousAttempts } from \"../../errors/base.ts\";\nimport { RateLimitWaitRefusedError } from \"../../errors/rate-limit-wait-refused.ts\";\nimport type { RateLimitError } from \"../../errors/rate-limit.ts\";\nimport { RetryDelayExceededError } from \"../../errors/retry-delay-exceeded.ts\";\nimport type { Result } from \"../../types.ts\";\nimport { ABORTED, raceWithAbortAsync, requestAbortedError } from \"../utils/abort.ts\";\nimport type { SleepFunc } from \"../utils/sleep.ts\";\nimport { observeAdmissionWaitAsync } from \"./admission-wait.ts\";\nimport { waitDeadlineFailure } from \"./request-deadline.ts\";\nimport { MAX_GUIDED_WAIT_SECONDS } from \"./retry-guidance.ts\";\nimport {\n\tcomputeRetryWaitMs,\n\thasGuidedWait,\n\tisRefusedGuidedWait,\n\ttype RetryResolvable,\n\tshouldRetry,\n} from \"./retry.ts\";\nimport type { AdmissionWaitObserver, HttpRequest, HttpResponse, OpenCloudHooks } from \"./types.ts\";\n\n/** A transport callback: takes a request, returns a classified Result. */\ntype SendFunc = (request: HttpRequest) => Promise<Result<HttpResponse, OpenCloudError>>;\n\ninterface RetryLimit {\n\treadonly cause: OpenCloudError;\n\treadonly deadlineMs: number | undefined;\n\treadonly retryAfterMs: number;\n}\n\n/** What follows a failed attempt: a wait to take, or a refusal to return. */\ntype RetryPlan =\n\t| { readonly refusal: OpenCloudError }\n\t| { readonly spendsAttempt: boolean; readonly waitMs: number };\n\ninterface RetryState {\n\treadonly config: RetryResolvable;\n\treadonly deadlineMs: number | undefined;\n\treadonly retries: number;\n}\n\ninterface RetryNotification {\n\treadonly attempt: number;\n\treadonly error: OpenCloudError;\n\treadonly hooks: OpenCloudHooks;\n\treadonly waitMs: number;\n}\n\n/**\n * Inputs to {@link executeWithRetryAsync} bundled as an options object to keep\n * the function signature narrow.\n */\ninterface ExecuteOptions {\n\t/** Request-scoped admission-wait observer. */\n\treadonly admissionWaitObserver?: AdmissionWaitObserver | undefined;\n\t/** Fully-resolved retry config (post-merge). */\n\treadonly config: RetryResolvable;\n\t/**\n\t * Absolute deadline for the logical request, as Unix epoch milliseconds.\n\t */\n\treadonly deadlineMs?: number | undefined;\n\t/** Client-level observability hooks. */\n\treadonly hooks: OpenCloudHooks;\n\t/** Transport callback. May be pre-wrapped by a rate-limit queue. */\n\treadonly send: SendFunc;\n\t/** Optional caller cancellation signal. */\n\treadonly signal?: AbortSignal | undefined;\n\t/** Injectable sleep (tests pass a fake). */\n\treadonly sleep: SleepFunc;\n}\n\n/**\n * Retry-aware orchestration loop. Coordinates a single logical request,\n * looping over `options.send` until it succeeds, the error is non-retryable,\n * or `options.config.maxRetries` is exhausted. Server-guided rate-limit waits\n * do not count against `maxRetries`; the request deadline and `signal` bound\n * them. Fires observability hooks at each transition. Queue-agnostic: `send`\n * may be any callback, including one wrapped by a rate-limit queue.\n *\n * @param request - The immutable request to send.\n * @param options - The transport callback, resolved config, hooks, and sleep.\n * @returns The first success, or the final error after retries are exhausted.\n */\nexport async function executeWithRetryAsync(\n\trequest: HttpRequest,\n\toptions: ExecuteOptions,\n): Promise<Result<HttpResponse, OpenCloudError>> {\n\tconst { config, deadlineMs, hooks, signal } = options;\n\tif (signal?.aborted === true) {\n\t\treturn abortedResult(signal);\n\t}\n\n\tlet result = await attemptAsync(request, options);\n\tlet retries = 0;\n\tlet earlier: ReadonlyArray<OpenCloudError> = [];\n\n\twhile (!result.success) {\n\t\tconst failure = result.err;\n\t\tconst plan = planRetry(failure, { config, deadlineMs, retries });\n\t\tif (plan === undefined) {\n\t\t\treturn failed(failure, earlier);\n\t\t}\n\n\t\tif (\"refusal\" in plan) {\n\t\t\treturn failed(plan.refusal, earlier);\n\t\t}\n\n\t\tretries += plan.spendsAttempt ? 1 : 0;\n\t\tearlier = [...earlier, failure];\n\t\tannounceRetry({ attempt: earlier.length, error: failure, hooks, waitMs: plan.waitMs });\n\t\tif ((await waitForRetryAsync(plan.waitMs, options)) === ABORTED) {\n\t\t\treturn failed(requestAbortedError(signal), earlier);\n\t\t}\n\n\t\tresult = await attemptAsync(request, options);\n\t}\n\n\treturn result;\n}\n\nfunction failed(\n\terr: OpenCloudError,\n\tearlier: ReadonlyArray<OpenCloudError>,\n): Result<never, OpenCloudError> {\n\treturn { err: recordPreviousAttempts(err, earlier), success: false };\n}\n\nfunction retryRefusal({\n\tcause,\n\tdeadlineMs,\n\tretryAfterMs,\n}: RetryLimit): RetryDelayExceededError | undefined {\n\tif (deadlineMs === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst refusal = waitDeadlineFailure({\n\t\tcause,\n\t\tdeadlineMs,\n\t\twaitMs: retryAfterMs,\n\t\twaitReason: \"retry-delay\",\n\t});\n\tif (refusal === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst { remainingMs } = refusal;\n\treturn new RetryDelayExceededError(\n\t\t`Retry delay would wait ${retryAfterMs / 1000}s; ${remainingMs / 1000}s remain before the request deadline`,\n\t\t{ cause, deadlineMs, remainingMs, retryAfterMs },\n\t);\n}\n\nfunction guidedWaitRefusal(cause: RateLimitError): RateLimitWaitRefusedError {\n\treturn new RateLimitWaitRefusedError(\n\t\t`Rate limit asks for a ${cause.retryAfterSeconds}s wait, longer than the ${MAX_GUIDED_WAIT_SECONDS}s the SDK waits out`,\n\t\t{ cause },\n\t);\n}\n\n/**\n * Decides what follows a failed attempt. A rate limit carrying a server-guided\n * wait is waited out without spending one of `maxRetries`, unless the wait is\n * longer than {@link MAX_GUIDED_WAIT_SECONDS}, which is refused outright; every\n * other retryable failure spends one.\n *\n * @param err - The failure the attempt returned.\n * @param state - Resolved config, request deadline, and attempts spent so far.\n * @returns The wait to take, a refusal to return instead, or `undefined` to\n * return the failure as is.\n */\nfunction planRetry(\n\terr: OpenCloudError,\n\t{ config, deadlineMs, retries }: RetryState,\n): RetryPlan | undefined {\n\tif (!shouldRetry(err, config)) {\n\t\treturn undefined;\n\t}\n\n\tconst guided = hasGuidedWait(err);\n\tif (!guided && retries >= config.maxRetries) {\n\t\treturn undefined;\n\t}\n\n\tif (isRefusedGuidedWait(err)) {\n\t\treturn { refusal: guidedWaitRefusal(err) };\n\t}\n\n\tconst waitMs = computeRetryWaitMs(err, { attempt: retries, retryDelay: config.retryDelay });\n\tconst refusal = retryRefusal({ cause: err, deadlineMs, retryAfterMs: waitMs });\n\treturn refusal === undefined ? { spendsAttempt: !guided, waitMs } : { refusal };\n}\n\nasync function waitForRetryAsync(\n\twaitMs: number,\n\t{ admissionWaitObserver, signal, sleep }: ExecuteOptions,\n): Promise<typeof ABORTED | void> {\n\treturn observeAdmissionWaitAsync({\n\t\tdurationMs: waitMs,\n\t\tobserver: admissionWaitObserver,\n\t\treason: \"retry-delay\",\n\t\twaitAsync: async () => raceWithAbortAsync(async () => sleep(waitMs, signal), signal),\n\t});\n}\n\nfunction announceRetry({ attempt, error, hooks, waitMs }: RetryNotification): void {\n\thooks.onRetry?.(attempt, error);\n\thooks.onRateLimit?.(waitMs);\n}\n\nfunction abortedResult(signal: AbortSignal | undefined): Result<never, OpenCloudError> {\n\treturn { err: requestAbortedError(signal), success: false };\n}\n\nasync function attemptAsync(\n\trequest: HttpRequest,\n\t{ hooks, send, signal }: ExecuteOptions,\n): Promise<Result<HttpResponse, OpenCloudError>> {\n\thooks.onRequest?.(request);\n\tconst attempt = await raceWithAbortAsync(async () => send(request), signal);\n\treturn attempt === ABORTED ? abortedResult(signal) : attempt;\n}\n","import type { OpenCloudError } from \"../../errors/base.ts\";\nimport { hasServerRetryGuidance, RateLimitError } from \"../../errors/rate-limit.ts\";\nimport type { Result } from \"../../types.ts\";\nimport type { BudgetGate, BudgetScope } from \"./budget-gate.ts\";\nimport type { RateLimitSample } from \"./rate-limit-sample.ts\";\nimport { parseRateLimitHeaders, withReportedWindow } from \"./rate-limit-sample.ts\";\nimport { MAX_GUIDED_WAIT_SECONDS } from \"./retry-guidance.ts\";\nimport { isRefusedGuidedWait } from \"./retry.ts\";\nimport type { HttpResponse } from \"./types.ts\";\n\n/**\n * Returns `true` when a long 429's evidence shows it clears on some other\n * event than its guided wait, so it must not lock its scope out.\n */\nexport type LockoutExemption = (error: RateLimitError) => boolean;\n\n/** One sent attempt, as the budget gate learns from it. */\nexport interface ObservedAttempt {\n\t/** Returns `true` to keep a long 429 from locking the scope out. */\n\treadonly exemptsLockout: LockoutExemption | undefined;\n\t/** The scope the attempt was gated on. */\n\treadonly scope: BudgetScope;\n\t/** The classified, unrefined transport result of the attempt. */\n\treadonly transportResult: Result<HttpResponse, OpenCloudError>;\n}\n\n/**\n * Extracts a {@link RateLimitSample} from a transport result so the budget\n * gate can be fed from every attempt. A 2xx carries the budget in its headers.\n * A 429 with valid server guidance primes the gate as spent for its guided\n * wait, whatever `x-ratelimit-remaining` reports: the remaining count is only\n * a pacing hint on 2xx responses. A 429 asking for a longer wait than the SDK\n * takes is refused, so it does not prime the gate either. A 429 also carries\n * the window capacity its `x-ratelimit-limit` header reports. Any other error\n * yields `undefined`.\n *\n * @param result - The classified transport result for one attempt.\n * @returns The parsed sample, or `undefined` when none was reported.\n */\nexport function rateLimitSampleFromResult(\n\tresult: Result<HttpResponse, OpenCloudError>,\n): RateLimitSample | undefined {\n\tif (result.success) {\n\t\treturn parseRateLimitHeaders(result.data.headers);\n\t}\n\n\tconst { err } = result;\n\tif (\n\t\terr instanceof RateLimitError &&\n\t\thasServerRetryGuidance(err) &&\n\t\terr.retryAfterSeconds <= MAX_GUIDED_WAIT_SECONDS\n\t) {\n\t\tconst sample = { remaining: 0, resetSeconds: err.retryAfterSeconds };\n\t\treturn withReportedWindow(sample, err.responseHeaders?.[\"x-ratelimit-limit\"]);\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Picks out a 429 whose guided wait is longer than the SDK waits out on its\n * own. Such a lockout is refused, and later requests on the same scope fail\n * locally until it ends instead of reaching the server.\n *\n * @param result - The classified transport result for one attempt.\n * @returns The locking 429, or `undefined` for any other result.\n */\nexport function rateLimitLockoutFromResult(\n\tresult: Result<HttpResponse, OpenCloudError>,\n): RateLimitError | undefined {\n\treturn !result.success && isRefusedGuidedWait(result.err) ? result.err : undefined;\n}\n\n/**\n * Feeds one attempt back into the budget gate: its reported budget always,\n * and a long 429 as a lockout unless the caller exempts it (such as a 429\n * naming tasks that occupy a Luau place).\n *\n * @param budgets - The gate shared across the client.\n * @param attempt - The scope, transport result, and lockout exemption.\n */\nexport function observeAttempt(\n\tbudgets: BudgetGate,\n\t{ exemptsLockout, scope, transportResult }: ObservedAttempt,\n): void {\n\tbudgets.observe(scope, rateLimitSampleFromResult(transportResult));\n\tconst lockout = rateLimitLockoutFromResult(transportResult);\n\tif (lockout !== undefined && exemptsLockout?.(lockout) !== true) {\n\t\tbudgets.lockOut(scope, lockout);\n\t}\n}\n","import { ABORTED, raceWithAbortAsync, requestAbortedError } from \"../utils/abort.ts\";\nimport type { SleepFunc } from \"../utils/sleep.ts\";\nimport { type AdmissionWaitContext, observeAdmissionWaitAsync } from \"./admission-wait.ts\";\nimport type { RateLimitWindow } from \"./rate-limit-sample.ts\";\nimport { waitDeadlineFailure } from \"./request-deadline.ts\";\nimport type { OpenCloudHooks } from \"./types.ts\";\n\nconst OPERATION_QUEUE_REASON = \"operation-queue\";\n\n/**\n * Identifies and bounds a single Roblox Open Cloud operation for rate\n * limiting, e.g. `{ operationKey: \"game-passes.create\", maxPerSecond: 5 }`.\n */\nexport interface OperationLimit {\n\t/**\n\t * How many requests may be issued back to back before pacing begins,\n\t * as a whole number of requests. Defaults to `max(1, maxPerSecond)`,\n\t * which leaves operations at or above 1/s paced exactly as their\n\t * sustained rate allows while still granting a slower operation one\n\t * request after it has idled. Set this to the allowance the schema\n\t * documents (e.g. 5 per minute) to grant the burst the server permits.\n\t */\n\treadonly burstCapacity?: number;\n\t/** Maximum sustained request rate in requests per second. */\n\treadonly maxPerSecond: number;\n\t/**\n\t * Stable identifier for the operation (e.g. \"game-passes.create\"). Not\n\t * consumed by the queue itself; callers use it to key per-operation\n\t * queues in a registry (see GamePassesClient).\n\t */\n\treadonly operationKey: string;\n}\n\ninterface QueueWait extends AdmissionWaitContext {\n\treadonly now: number;\n\treadonly waitMs: number;\n}\n\n/**\n * Token-bucket rate limiter for a single `(credential identity, operation)`\n * pair. Every call to `acquire` consumes one token; when the bucket is empty\n * the call waits until a token regenerates before invoking the task. Tokens\n * refill at `maxPerSecond` per second, up to the operation's `burstCapacity`.\n *\n * Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`\n * advances by `waitMs` after every sleep so the algorithm stays correct\n * whether or not the injected sleep moves `Date.now()` forward. `#bucketLevel`\n * and `#maxBucketLevel` are both ms of drain debt, so the ceiling is the burst\n * expressed in that unit: `burstCapacity` refill intervals. Deriving it any\n * other way (notably `maxPerSecond * intervalMs`, whose units cancel to a\n * constant 1000) starves every operation slower than one request per second.\n */\nexport class RateLimitQueue {\n\treadonly #hooks: OpenCloudHooks;\n\treadonly #intervalMs: number;\n\treadonly #maxBucketLevel: number;\n\treadonly #sleep: SleepFunc;\n\n\t#bucketLevel = 0;\n\t#chain: Promise<void> = Promise.resolve();\n\t#lastCheck: number = Date.now();\n\t#pendingAcquisitions = 0;\n\n\t/**\n\t * Creates a rate-limit queue bound to a single operation.\n\t *\n\t * @param limit - The operation key and its per-second request ceiling.\n\t * @param hooks - Observability callbacks; `onRateLimit` fires when the\n\t * bucket is empty and a sleep is about to start.\n\t * @param sleep - Injectable sleep (tests pass a fake).\n\t */\n\tconstructor(limit: OperationLimit, hooks: OpenCloudHooks, sleep: SleepFunc) {\n\t\tthis.#intervalMs = 1000 / limit.maxPerSecond;\n\t\tthis.#maxBucketLevel = documentedWindow(limit).capacity * this.#intervalMs;\n\t\tthis.#hooks = hooks;\n\t\tthis.#sleep = sleep;\n\t}\n\n\t/**\n\t * Waits for a token — sleeping and firing `hooks.onRateLimit` if the\n\t * bucket is empty — then executes `task`. Concurrent callers are\n\t * serialized at token acquisition; tasks themselves run independently\n\t * once their token is secured.\n\t *\n\t * @param task - The request to run once a token is available.\n\t * @param context - Request-local observer and cancellation signal.\n\t * @returns The value produced by `task`.\n\t * @rejects {@link RequestAbortedError} when the caller cancels while queued.\n\t */\n\tpublic async acquireAsync<T>(\n\t\ttask: () => Promise<T>,\n\t\t{ deadlineMs, observer, signal }: AdmissionWaitContext = {},\n\t): Promise<T> {\n\t\tconst waitsForEarlierAcquisition = this.#pendingAcquisitions > 0;\n\t\tthis.#pendingAcquisitions++;\n\t\tconst waitForTokenAsync = async (): Promise<void> => {\n\t\t\treturn this.#waitForToken({\n\t\t\t\tdeadlineMs,\n\t\t\t\tobserver: waitsForEarlierAcquisition ? undefined : observer,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t};\n\n\t\tconst myTurn = this.#chain.catch(ignoreRejection).then(waitForTokenAsync);\n\t\tconst completed = myTurn.finally(() => {\n\t\t\tthis.#pendingAcquisitions--;\n\t\t});\n\t\tthis.#chain = completed.catch(ignoreRejection);\n\t\tif (waitsForEarlierAcquisition) {\n\t\t\tawait observeAdmissionWaitAsync({\n\t\t\t\tobserver,\n\t\t\t\treason: OPERATION_QUEUE_REASON,\n\t\t\t\twaitAsync: async () => waitForTurnAsync(completed, signal),\n\t\t\t});\n\t\t} else {\n\t\t\tawait waitForTurnAsync(completed, signal);\n\t\t}\n\n\t\treturn task();\n\t}\n\n\tasync #waitAsync({ deadlineMs, now, observer, signal, waitMs }: QueueWait): Promise<void> {\n\t\tconst refusal = waitDeadlineFailure({\n\t\t\tdeadlineMs,\n\t\t\twaitMs,\n\t\t\twaitReason: OPERATION_QUEUE_REASON,\n\t\t});\n\t\tif (refusal !== undefined) {\n\t\t\tthrow refusal;\n\t\t}\n\n\t\tthis.#hooks.onRateLimit?.(waitMs);\n\t\tawait observeAdmissionWaitAsync({\n\t\t\tdurationMs: waitMs,\n\t\t\tobserver,\n\t\t\treason: OPERATION_QUEUE_REASON,\n\t\t\twaitAsync: async () => {\n\t\t\t\tconst sleepResult = await raceWithAbortAsync(\n\t\t\t\t\tasync () => this.#sleep(waitMs, signal),\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t\tif (sleepResult === ABORTED) {\n\t\t\t\t\tthrow requestAbortedError(signal);\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t\tthis.#bucketLevel = this.#maxBucketLevel;\n\t\tthis.#lastCheck = now + waitMs;\n\t}\n\n\tasync #waitForToken({ deadlineMs, observer, signal }: AdmissionWaitContext): Promise<void> {\n\t\tif (signal?.aborted === true) {\n\t\t\tthrow requestAbortedError(signal);\n\t\t}\n\n\t\tconst now = Math.max(Date.now(), this.#lastCheck);\n\t\tconst drained = Math.max(0, this.#bucketLevel - (now - this.#lastCheck));\n\t\tthis.#lastCheck = now;\n\n\t\tif (drained + this.#intervalMs <= this.#maxBucketLevel) {\n\t\t\tthis.#bucketLevel = drained + this.#intervalMs;\n\t\t\treturn;\n\t\t}\n\n\t\tconst waitMs = drained + this.#intervalMs - this.#maxBucketLevel;\n\t\tawait this.#waitAsync({ deadlineMs, now, observer, signal, waitMs });\n\t}\n}\n\n/**\n * Expresses an operation's documented limit as a fixed window: its burst\n * capacity, granted once per the time the sustained rate takes to refill it.\n *\n * @param limit - The operation's documented rate limit.\n * @returns The capacity granted per window and the window's length.\n */\nexport function documentedWindow(limit: OperationLimit): RateLimitWindow {\n\tconst capacity = limit.burstCapacity ?? Math.max(1, limit.maxPerSecond);\n\treturn { capacity, windowSeconds: capacity / limit.maxPerSecond };\n}\n\nfunction ignoreRejection(): void {\n\t// A failed or cancelled acquire must not poison the next caller's chain.\n}\n\nasync function waitForTurnAsync(\n\tturn: Promise<void>,\n\tsignal: AbortSignal | undefined,\n): Promise<void> {\n\tconst turnResult = await raceWithAbortAsync(async () => turn, signal);\n\tif (turnResult === ABORTED) {\n\t\tthrow requestAbortedError(signal);\n\t}\n}\n","import type { Except } from \"type-fest\";\n\nimport type { HttpRequest, RequestConfig, RequestOptions } from \"../../client/types.ts\";\nimport type { RetryResolvable } from \"./retry.ts\";\nimport { isUploadRequest } from \"./upload-request.ts\";\n\n/**\n * Inputs to {@link buildRequestConfig}, bundled to keep the signature narrow.\n */\nexport interface RequestConfigInputs {\n\t/** The resolved config for this call. */\n\treadonly merged: RetryResolvable;\n\t/** The caller's per-request overrides, if any. */\n\treadonly options: RequestOptions | undefined;\n\t/** The built request, inspected for an upload body. */\n\treadonly request: HttpRequest;\n\t/** Caller and deadline signal composed for the whole logical request. */\n\treadonly signal: AbortSignal | undefined;\n}\n\n/**\n * Resolves the per-request {@link RequestConfig}, less the credential, which\n * is resolved per transport attempt. Upload requests ({@link isUploadRequest})\n * carry no default timeout: a multi-megabyte place file over a slow link is\n * bandwidth-bound, so a transport-attempt timeout only fires spuriously. An\n * explicit `options.timeout` still applies to any request; every non-upload\n * request keeps the merged default.\n *\n * @param inputs - The merged config, the built request, and per-request\n * overrides.\n * @returns The config to hand to the transport, with `timeout` omitted when\n * no transport-attempt timeout should apply.\n */\nexport function buildRequestConfig({\n\tmerged,\n\toptions,\n\trequest,\n\tsignal,\n}: RequestConfigInputs): Except<RequestConfig, \"credential\"> {\n\tconst shouldOmitDefaultTimeout = options?.timeout === undefined && isUploadRequest(request);\n\treturn {\n\t\tbaseUrl: merged.baseUrl,\n\t\t...(signal === undefined ? {} : { signal }),\n\t\t...(shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }),\n\t};\n}\n","import { setTimeout } from \"node:timers/promises\";\n\n/**\n * Injectable sleep function signature for testing.\n *\n * @since 0.1.0\n */\nexport type SleepFunc = (ms: number, signal?: AbortSignal) => Promise<void>;\n\n/**\n * Timer-backed production sleep that releases its timer on cancellation.\n *\n * @param ms - Duration to wait in milliseconds.\n * @param signal - Optional caller cancellation signal.\n */\nexport async function defaultSleepAsync(ms: number, signal?: AbortSignal): Promise<void> {\n\tawait setTimeout(ms, undefined, { signal });\n}\n","import type { HttpClient, SleepFunc } from \"../../client/types.ts\";\nimport { defaultSleepAsync } from \"../utils/sleep.ts\";\nimport { createFetchHttpClient } from \"./fetch-client.ts\";\n\n/**\n * Options accepted by {@link resolveDependencies}. Mirrors the test-seam\n * subset of the public client options.\n */\ninterface ResolveDependenciesOptions {\n\t/**\n\t * Test seam: custom {@link HttpClient}. Defaults to a fetch-backed client.\n\t */\n\treadonly httpClient?: HttpClient | undefined;\n\t/**\n\t * Test seam: custom {@link SleepFunc}. Defaults to a `setTimeout`-backed\n\t * sleep.\n\t */\n\treadonly sleep?: SleepFunc | undefined;\n}\n\n/**\n * Fully-populated dependency set consumed by resource client constructors.\n */\ninterface ResolvedDependencies {\n\t/** Concrete {@link HttpClient} implementation. */\n\treadonly httpClient: HttpClient;\n\t/** Concrete {@link SleepFunc} implementation. */\n\treadonly sleep: SleepFunc;\n}\n\n/**\n * Resolves the concrete HTTP client and sleep implementation a resource\n * client should use. Falls back to the fetch-backed HTTP client and the\n * default `setTimeout`-based sleep when the caller omits the test seams.\n *\n * Extracted so resource client constructors can keep their dependency\n * resolution logic in a single, unit-testable place; this makes the\n * default branches easy to cover without stubbing globals like `fetch`.\n *\n * @param options - Optional {@link HttpClient} and {@link SleepFunc} test seams.\n * @returns A {@link ResolvedDependencies} with defaults applied.\n */\nexport function resolveDependencies(options: ResolveDependenciesOptions): ResolvedDependencies {\n\treturn {\n\t\thttpClient: options.httpClient ?? createFetchHttpClient(),\n\t\tsleep: options.sleep ?? defaultSleepAsync,\n\t};\n}\n","import type { RequestOptions } from \"../../client/types.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport type { Result } from \"../../types.ts\";\nimport { withCredentialSnapshot } from \"../credential-snapshot.ts\";\nimport { requestAbortedError } from \"../utils/abort.ts\";\nimport type { AdmissionWaitContext } from \"./admission-wait.ts\";\nimport {\n\telapsedDeadlineFailure,\n\trequestLifecycle,\n\ttype RequestLifecycle,\n} from \"./request-deadline.ts\";\nimport type { RetryResolvable } from \"./retry.ts\";\n\n/** Request-only controls resolved before request construction. */\nexport interface RequestStart {\n\t/** Admission controls the rate-limit queue and budget gate honour. */\n\treadonly admission: AdmissionWaitContext;\n\t/** Abort and deadline signals for the whole request. */\n\treadonly lifecycle: RequestLifecycle;\n\t/** Per-call options to merge over the client config. */\n\treadonly requestOptions: Partial<RetryResolvable>;\n}\n\n/**\n * Resolve the request-only controls of one call before its request is\n * built: fail at once on an already-aborted caller signal or an elapsed\n * deadline, otherwise start the request lifecycle and split the per-call\n * options from the admission controls.\n *\n * @param options - The caller's per-request options, if any.\n * @returns The resolved controls, or the abort or deadline failure.\n */\nexport function startRequest(\n\toptions: RequestOptions | undefined,\n): Result<RequestStart, OpenCloudError> {\n\tconst callerSignal = options?.signal;\n\tif (callerSignal?.aborted === true) {\n\t\treturn { err: requestAbortedError(callerSignal), success: false };\n\t}\n\n\tconst lifecycle = requestLifecycle(options?.deadlineMs, callerSignal);\n\tconst deadlineFailure = elapsedDeadlineFailure(lifecycle);\n\tif (deadlineFailure !== undefined) {\n\t\treturn { err: deadlineFailure, success: false };\n\t}\n\n\tconst { deadlineMs, onAdmissionWait, signal: _signal, ...requestOptions } = options ?? {};\n\treturn {\n\t\tdata: {\n\t\t\tadmission: { deadlineMs, observer: onAdmissionWait, signal: lifecycle.signal },\n\t\t\tlifecycle,\n\t\t\trequestOptions: withCredentialSnapshot(requestOptions),\n\t\t},\n\t\tsuccess: true,\n\t};\n}\n","import type { Credential, ResolvedCredential } from \"../../client/types.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { CredentialError } from \"../../errors/credential-error.ts\";\nimport type { Result } from \"../../types.ts\";\n\n/** A credential that sends a header. */\nexport type SendingCredential = Extract<Credential, Readonly<Record<\"kind\", \"apiKey\" | \"oauth\">>>;\n\n/**\n * Names the rate-limit bucket a credential draws on. The key is namespaced by\n * kind, so an OAuth identity never shares a bucket with an equal API key. An\n * OAuth credential keys on its identity, so a token rotation keeps the bucket.\n *\n * @param credential - The effective credential.\n * @returns The bucket key. It holds the API key, so keep it in private maps.\n */\nexport function credentialQueueKey(credential: SendingCredential): string {\n\treturn credential.kind === \"apiKey\"\n\t\t? `apiKey:${credential.apiKey}`\n\t\t: `oauth:${credential.identity}`;\n}\n\n/**\n * Turns the effective credential into the header-ready form for one transport\n * attempt. Calls an OAuth provider once; a throw or a rejection becomes a\n * {@link CredentialError} whose `cause` is the provider's error.\n *\n * @param credential - The effective credential.\n * @param signal - The request's signal, handed to an OAuth provider. A\n * request with no signal hands the provider one that never aborts.\n * @returns The resolved credential, or the provider failure.\n */\nexport async function resolveAttemptCredentialAsync(\n\tcredential: SendingCredential,\n\tsignal: AbortSignal | undefined,\n): Promise<Result<ResolvedCredential, OpenCloudError>> {\n\tif (credential.kind === \"apiKey\") {\n\t\treturn { data: { apiKey: credential.apiKey, kind: \"apiKey\" }, success: true };\n\t}\n\n\ttry {\n\t\tconst accessToken = await credential.getAccessToken({\n\t\t\tsignal: signal ?? neverAbortingSignal(),\n\t\t});\n\t\treturn { data: { accessToken, kind: \"oauth\" }, success: true };\n\t} catch (err) {\n\t\treturn {\n\t\t\terr: new CredentialError(\"OAuth credential provider failed\", { cause: err }),\n\t\t\tsuccess: false,\n\t\t};\n\t}\n}\n\nfunction neverAbortingSignal(): AbortSignal {\n\tconst controller = new AbortController();\n\treturn controller.signal;\n}\n","import type { ResolvedCredential } from \"../../client/types.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport type { Result } from \"../../types.ts\";\nimport { classifyCredentialRejection } from \"./credential-rejection.ts\";\nimport {\n\tcredentialQueueKey,\n\tresolveAttemptCredentialAsync,\n\ttype SendingCredential,\n} from \"./credential.ts\";\nimport type { RetryResolvable } from \"./retry.ts\";\n\n/** What a method declares about its authentication. */\ninterface AuthenticationSpec {\n\treadonly unauthenticatedBaseUrl?: string;\n}\n\n/** The call's config and credential once its authentication is applied. */\ninterface CallAuthentication {\n\t/** The credential to send, or `undefined` for an unauthenticated call. */\n\treadonly credential: SendingCredential | undefined;\n\t/**\n\t * The merged config, pointed at the method's own origin when it has one.\n\t */\n\treadonly merged: RetryResolvable;\n}\n\nconst UNAUTHENTICATED_QUEUE_KEY = \"none\";\n\nconst UNAUTHENTICATED = Object.freeze({\n\tdata: Object.freeze({ kind: \"none\" }),\n\tsuccess: true,\n} satisfies Result<ResolvedCredential, OpenCloudError>);\n\n/**\n * Applies a method's authentication to the merged config. An unauthenticated\n * method is served from its own origin and carries no credential. A\n * `{ kind: \"none\" }` credential carries none either.\n *\n * @param merged - The merged config of the call.\n * @param spec - The method's authentication declaration.\n * @returns The config to send with and the credential, if any.\n */\nexport function authenticateCall(\n\tmerged: RetryResolvable,\n\t{ unauthenticatedBaseUrl }: AuthenticationSpec,\n): CallAuthentication {\n\tif (unauthenticatedBaseUrl !== undefined) {\n\t\treturn { credential: undefined, merged: { ...merged, baseUrl: unauthenticatedBaseUrl } };\n\t}\n\n\treturn {\n\t\tcredential: merged.credential.kind === \"none\" ? undefined : merged.credential,\n\t\tmerged,\n\t};\n}\n\n/**\n * Keys the rate-limit queue of a call. Every unauthenticated call shares one\n * key, since Roblox counts those per caller.\n *\n * @param credential - The call's credential, or `undefined` when it sends\n * none.\n * @returns The credential's queue key, or the shared unauthenticated key.\n */\nexport function callQueueKey(credential: SendingCredential | undefined): string {\n\treturn credential === undefined ? UNAUTHENTICATED_QUEUE_KEY : credentialQueueKey(credential);\n}\n\n/**\n * Resolves the credential one attempt sends. An unauthenticated call sends\n * none and runs no OAuth provider.\n *\n * @param credential - The call's credential, if any.\n * @param signal - The caller's cancellation signal.\n * @returns The resolved credential, or the provider failure.\n */\nexport async function resolveCallCredentialAsync(\n\tcredential: SendingCredential | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<Result<ResolvedCredential, OpenCloudError>> {\n\treturn credential === undefined\n\t\t? UNAUTHENTICATED\n\t\t: resolveAttemptCredentialAsync(credential, signal);\n}\n\n/**\n * Refines one attempt's transport error, then classifies a refused OAuth\n * token. An unauthenticated call sent no token, so none was refused.\n *\n * @param err - The transport error of the attempt.\n * @param context - The call's credential and optional refinement.\n * @returns The classified error.\n */\nexport function classifySendError(\n\terr: OpenCloudError,\n\t{\n\t\tcredential,\n\t\trefineError,\n\t}: {\n\t\treadonly credential: SendingCredential | undefined;\n\t\treadonly refineError: ((error: OpenCloudError) => OpenCloudError) | undefined;\n\t},\n): OpenCloudError {\n\tconst refined = refineError === undefined ? err : refineError(err);\n\treturn credential === undefined ? refined : classifyCredentialRejection(refined, credential);\n}\n","import type { HttpRequest, HttpResponse } from \"../client/types.ts\";\nimport type { OpenCloudError } from \"../errors/base.ts\";\nimport { UnexpectedResponseError } from \"../errors/unexpected-response.ts\";\nimport { pickDiagnosticHeaders } from \"./http/diagnostics.ts\";\n\nconst TRAILING_SLASH = /\\/$/;\n\n/** The request a parser's input answered, and the response it parsed. */\nexport interface ParsedExchange {\n\t/** Base URL the request path was sent against. */\n\treadonly baseUrl: string;\n\t/** End the message with the bug report link. */\n\treadonly reportHint: boolean;\n\t/** The request that was sent. */\n\treadonly request: HttpRequest;\n\t/** The successful response the parser rejected. */\n\treadonly response: HttpResponse;\n}\n\n/**\n * Rebuilds a parser's {@link UnexpectedResponseError} with the request it\n * answered. A parser sees only the response, so the call site adds the method,\n * the full URL, and the allowlisted response headers, and ends the message with\n * the bug report link when `reportHint` is set. Any other error is returned\n * unchanged.\n *\n * @param err - The parser's error.\n * @param exchange - The base URL, the request sent, and the response parsed.\n * @returns `err`, carrying the request context when it is an unexpected\n * response.\n */\nexport function withRequestContext(\n\terr: OpenCloudError,\n\t{ baseUrl, reportHint, request, response }: ParsedExchange,\n): OpenCloudError {\n\tif (!(err instanceof UnexpectedResponseError)) {\n\t\treturn err;\n\t}\n\n\treturn new UnexpectedResponseError(err.message, {\n\t\tcause: err.cause,\n\t\tcode: err.code,\n\t\tdetails: err.details,\n\t\tmethod: request.method,\n\t\treportHint,\n\t\tresponseHeaders: pickDiagnosticHeaders({ ...response.headers }),\n\t\tstatusCode: err.statusCode,\n\t\turl: `${baseUrl.replace(TRAILING_SLASH, \"\")}${request.url}`,\n\t});\n}\n","import type { Except } from \"type-fest\";\n\nimport type {\n\tHttpClient,\n\tHttpRequest,\n\tHttpResponse,\n\tOpenCloudClientOptions,\n\tOpenCloudHooks,\n\tRequestConfig,\n\tRequestOptions,\n\tSleepFunc,\n} from \"../client/types.ts\";\nimport { type OpenCloudError, recordPreviousAttempts } from \"../errors/base.ts\";\nimport type { PermissionError } from \"../errors/permission-error.ts\";\nimport { RateLimitWaitRefusedError } from \"../errors/rate-limit-wait-refused.ts\";\nimport { RequestAbortedError } from \"../errors/request-aborted.ts\";\nimport { RequestDeadlineExceededError } from \"../errors/request-deadline-exceeded.ts\";\nimport type { Result } from \"../types.ts\";\nimport { credentialNotSupportedFailure } from \"./api-key-only.ts\";\nimport { snapshotCredential } from \"./credential-snapshot.ts\";\nimport type { AdmissionWaitContext } from \"./http/admission-wait.ts\";\nimport { BudgetGate, type BudgetScope, scopeKey } from \"./http/budget-gate.ts\";\nimport { enrichPermissionError } from \"./http/credential-rejection.ts\";\nimport type { SendingCredential } from \"./http/credential.ts\";\nimport { executeWithRetryAsync } from \"./http/execute.ts\";\nimport { type LockoutExemption, observeAttempt } from \"./http/rate-limit-observation.ts\";\nimport { documentedWindow, type OperationLimit, RateLimitQueue } from \"./http/rate-limit-queue.ts\";\nimport { buildRequestConfig } from \"./http/request-config.ts\";\nimport { deadlineFailureFromError, type RequestLifecycle } from \"./http/request-deadline.ts\";\nimport { resolveDependencies } from \"./http/resolve-dependencies.ts\";\nimport {\n\tdefaultRetryDelay,\n\tIDEMPOTENT_METHOD_DEFAULTS,\n\tmergeConfig,\n\ttype MethodKind,\n\ttype RetryResolvable,\n} from \"./http/retry.ts\";\nimport { startRequest } from \"./http/start-request.ts\";\nimport {\n\tauthenticateCall,\n\tcallQueueKey,\n\tclassifySendError,\n\tresolveCallCredentialAsync,\n} from \"./http/unauthenticated.ts\";\nimport { withRequestContext } from \"./with-request-context.ts\";\n\n/**\n * Describes a single resource method's shape for dispatch through\n * `ResourceClient.execute`. Each resource client declares one module-level\n * constant per public method; that constant binds the four resource-specific\n * values (request builder, response parser, retry-policy method kind,\n * operation-level rate limit) and flows through `execute` uniformly.\n *\n * @template P - The resource-specific parameter shape the builder\n * accepts.\n * @template T - The resource-specific parsed success type the parser\n * produces.\n */\nexport interface ResourceMethodSpec<P, T> {\n\t/**\n\t * Marks an Operation that Roblox accepts only with an API key. An OAuth\n\t * call returns `CredentialNotSupportedError` with no token and no request.\n\t */\n\treadonly apiKeyOnly?: boolean;\n\t/**\n\t * Builds the pure {@link HttpRequest} for a single call. Returns a\n\t * {@link Result} so a builder can short-circuit with a local error\n\t * (typically a {@link OpenCloudError} subclass such as `ValidationError`)\n\t * before any HTTP, queue, or retry work happens. Builders that cannot\n\t * fail wrap their return as `{ data: request, success: true }`.\n\t */\n\treadonly buildRequest: (parameters: P) => Result<HttpRequest, OpenCloudError>;\n\t/** Method-level retry defaults merged into the resolved config. */\n\treadonly methodDefaults: Partial<RetryResolvable>;\n\t/**\n\t * Method kind, controlling merge precedence: `\"create\"` lets method\n\t * defaults win over client config so create safety cannot be relaxed\n\t * silently; `\"idempotent\"` lets client config win over method defaults\n\t * so consumers can loosen retry globally.\n\t */\n\treadonly methodKind: MethodKind;\n\t/**\n\t * Operation-level rate limit, keyed into the client's per-key queue map.\n\t */\n\treadonly operationLimit: OperationLimit;\n\t/**\n\t * Converts the full {@link HttpResponse} into the resource-specific\n\t * parsed shape. Takes the whole response (body, status, headers) so\n\t * future parsers can read headers without widening the signature.\n\t */\n\treadonly parse: (response: HttpResponse) => Result<T, OpenCloudError>;\n\t/**\n\t * Open Cloud scopes the API key or OAuth token must carry for this\n\t * method, sourced from the vendored OpenAPI schema's `x-roblox-scopes`.\n\t * When set, a 401 or 403 ApiError from the upstream call is upgraded to\n\t * a {@link PermissionError} carrying these scopes alongside\n\t * {@link OperationLimit.operationKey}, so callers can name the missing\n\t * scope instead of just the HTTP status. On an OAuth credential a\n\t * non-gateway 401 is a `CredentialRejectedError` instead, and the 403\n\t * message adds a grant hint. Optional so test specs and\n\t * not-yet-wired resources can opt out.\n\t */\n\treadonly requiredScopes?: ReadonlyArray<string>;\n\t/**\n\t * Marks an Operation that Roblox documents as unauthenticated, served from\n\t * this origin. The call sends no credential, never asks an OAuth provider\n\t * for a token, and shares one rate-limit queue across credentials.\n\t */\n\treadonly unauthenticatedBaseUrl?: string;\n}\n\n/**\n * Single-argument bundle consumed by `ResourceClient.execute`: the per-method\n * spec, the resource-specific parameters, and optional per-request config\n * overrides.\n *\n * @template P - The resource-specific parameter shape the builder accepts.\n * @template T - The resource-specific parsed success type the parser produces.\n */\ninterface ExecuteCall<P, T> {\n\t/**\n\t * Optionally exempts a long 429 from locking the operation out, when its\n\t * evidence shows it clears on some other event than its guided wait.\n\t */\n\treadonly exemptsLockout?: LockoutExemption | undefined;\n\t/** Optional per-request config overrides. */\n\treadonly options?: RequestOptions | undefined;\n\t/** Resource-specific request parameters. */\n\treadonly parameters: P;\n\t/** Optionally refines a transport error with resource-specific evidence. */\n\treadonly refineError?: ((error: OpenCloudError) => OpenCloudError) | undefined;\n\t/**\n\t * Per-method binding of builder, parser, method kind, and operation limit.\n\t */\n\treadonly spec: ResourceMethodSpec<P, T>;\n}\n\n/**\n * Wraps an infallible request build as a {@link Result}-returning\n * `buildRequest` callback compatible with {@link ResourceMethodSpec}.\n * Use from a resource client whose builder cannot fail; resource clients\n * with local validation should construct the {@link Result} directly.\n *\n * @param request - The pre-built {@link HttpRequest}.\n * @returns A success Result wrapping the request.\n */\nexport function okRequest(request: HttpRequest): Result<HttpRequest, OpenCloudError> {\n\treturn { data: request, success: true };\n}\n\n/**\n * A {@link ResourceMethodSpec.parse} implementation for endpoints that return\n * no business payload on success (such as `DELETE` and reorder operations).\n * Surfaces `undefined` data and never inspects the response body.\n *\n * @returns A success Result with `undefined` data.\n */\nexport function parseEmptyResponse(): Result<undefined, OpenCloudError> {\n\treturn { data: undefined, success: true };\n}\n\nconst CLIENT_DEFAULTS = Object.freeze({\n\tbaseUrl: \"https://apis.roblox.com\",\n\tmaxRetries: 3,\n\tretryableStatuses: IDEMPOTENT_METHOD_DEFAULTS.retryableStatuses,\n\tretryableTransportCodes: IDEMPOTENT_METHOD_DEFAULTS.retryableTransportCodes,\n\tretryDelay: defaultRetryDelay,\n\ttimeout: 30_000,\n} satisfies Except<RetryResolvable, \"credential\">);\n\ninterface DispatchInputs {\n\treadonly admission: AdmissionWaitContext;\n\treadonly credential: SendingCredential | undefined;\n\treadonly exemptsLockout: LockoutExemption | undefined;\n\treadonly merged: RetryResolvable;\n\treadonly operationLimit: OperationLimit;\n\treadonly refineError: ((error: OpenCloudError) => OpenCloudError) | undefined;\n\treadonly request: HttpRequest;\n\treadonly requestConfig: Except<RequestConfig, \"credential\">;\n}\n\n/** Inputs to the request-scoped budget-gated transport callback. */\ninterface GatedSendInputs {\n\treadonly admission: AdmissionWaitContext;\n\treadonly credential: SendingCredential | undefined;\n\treadonly exemptsLockout: LockoutExemption | undefined;\n\treadonly refineError: ((error: OpenCloudError) => OpenCloudError) | undefined;\n\treadonly requestConfig: Except<RequestConfig, \"credential\">;\n\treadonly scope: BudgetScope;\n}\n\ninterface FinishRequestInputs<P, T> {\n\treadonly httpResult: Result<HttpResponse, OpenCloudError>;\n\treadonly lifecycle: RequestLifecycle;\n\treadonly merged: RetryResolvable;\n\treadonly request: HttpRequest;\n\treadonly spec: ResourceMethodSpec<P, T>;\n}\n\n/**\n * Internal orchestrator shared by every Open Cloud resource client. Holds\n * the frozen client config, observability hooks, injected HTTP client and\n * sleep, and the per-effective-key rate-limit queue registry. Resource\n * classes compose one instance and dispatch every public method through\n * {@link ResourceClient.executeAsync} with a per-method {@link ResourceMethodSpec}.\n * Not exported from any package subpath; reachable only via sibling\n * `src/resources/**` modules in this package.\n */\nexport class ResourceClient {\n\treadonly #budgets: BudgetGate;\n\treadonly #config: Readonly<RetryResolvable>;\n\treadonly #hooks: OpenCloudHooks;\n\treadonly #httpClient: HttpClient;\n\treadonly #queues = new Map<string, RateLimitQueue>();\n\treadonly #reportHint: boolean;\n\treadonly #sleep: SleepFunc;\n\n\t/**\n\t * Creates a new {@link ResourceClient}. Resolves the injected HTTP\n\t * client and sleep (defaulting to fetch + `setTimeout`) and freezes the\n\t * merged client config so subsequent calls cannot mutate it.\n\t *\n\t * @param options - Client-level configuration including the credential\n\t * and optional construction-time test seams.\n\t */\n\tconstructor({ hooks, httpClient, reportHint, sleep, ...overrides }: OpenCloudClientOptions) {\n\t\tconst resolved = resolveDependencies({ httpClient, sleep });\n\t\tthis.#httpClient = resolved.httpClient;\n\t\tthis.#sleep = resolved.sleep;\n\t\tthis.#budgets = new BudgetGate(this.#sleep);\n\t\tthis.#hooks = hooks ?? {};\n\t\tthis.#reportHint = reportHint ?? true;\n\t\tthis.#config = Object.freeze({\n\t\t\t...CLIENT_DEFAULTS,\n\t\t\t...overrides,\n\t\t\tcredential: snapshotCredential(overrides.credential),\n\t\t});\n\t}\n\n\t/**\n\t * Dispatches a single resource-method call. Merges the frozen client\n\t * config with the method's `methodDefaults` and the caller's optional\n\t * per-request `options`, routes through the effective-credential rate-limit\n\t * queue, runs the retry loop, and finally parses the response with the\n\t * spec's parser.\n\t *\n\t * @param call - The per-method spec, resource-specific parameters, and\n\t * optional per-request overrides.\n\t * @returns The parsed success payload or the {@link OpenCloudError} that\n\t * caused the request to fail. Never throws.\n\t * @rejects An unexpected collaborator failure unrelated to caller cancellation.\n\t */\n\tpublic async executeAsync<P, T>({\n\t\texemptsLockout,\n\t\toptions,\n\t\tparameters,\n\t\trefineError,\n\t\tspec,\n\t}: ExecuteCall<P, T>): Promise<Result<T, OpenCloudError>> {\n\t\tconst start = startRequest(options);\n\t\tif (!start.success) {\n\t\t\treturn start;\n\t\t}\n\n\t\tconst { admission, lifecycle, requestOptions } = start.data;\n\t\tconst { credential, merged } = authenticateCall(this.#merge(spec, requestOptions), spec);\n\t\tconst requestResult =\n\t\t\tcredentialNotSupportedFailure(spec, merged.credential) ?? spec.buildRequest(parameters);\n\t\tif (!requestResult.success) {\n\t\t\treturn requestResult;\n\t\t}\n\n\t\tconst request = requestResult.data;\n\t\tconst { signal } = admission;\n\t\tconst requestConfig = buildRequestConfig({ merged, options, request, signal });\n\t\tconst httpResult = await this.#dispatchAsync({\n\t\t\tadmission,\n\t\t\tcredential,\n\t\t\texemptsLockout,\n\t\t\tmerged,\n\t\t\toperationLimit: spec.operationLimit,\n\t\t\trefineError,\n\t\t\trequest,\n\t\t\trequestConfig,\n\t\t});\n\t\treturn finishRequest({ httpResult, lifecycle, merged, request, spec }, this.#reportHint);\n\t}\n\n\t/**\n\t * Returns the sleep function used by this client instance.\n\t *\n\t * @returns The sleep function injected at construction time.\n\t */\n\tpublic get sleep(): SleepFunc {\n\t\treturn this.#sleep;\n\t}\n\n\tasync #dispatchAsync({\n\t\tadmission,\n\t\tcredential,\n\t\texemptsLockout,\n\t\tmerged,\n\t\toperationLimit,\n\t\trefineError,\n\t\trequest,\n\t\trequestConfig,\n\t}: DispatchInputs): Promise<Result<HttpResponse, OpenCloudError>> {\n\t\tconst credentialKey = callQueueKey(credential);\n\t\tconst queue = this.#getQueue(credentialKey, operationLimit);\n\t\tconst scope = budgetScopeFor(credentialKey, operationLimit);\n\t\ttry {\n\t\t\tthis.#budgets.refuseDuringLockout(scope);\n\t\t\treturn await queue.acquireAsync(async () => {\n\t\t\t\treturn executeWithRetryAsync(request, {\n\t\t\t\t\tadmissionWaitObserver: admission.observer,\n\t\t\t\t\tconfig: merged,\n\t\t\t\t\tdeadlineMs: admission.deadlineMs,\n\t\t\t\t\thooks: this.#hooks,\n\t\t\t\t\tsend: this.#gatedSend({\n\t\t\t\t\t\tadmission,\n\t\t\t\t\t\tcredential,\n\t\t\t\t\t\texemptsLockout,\n\t\t\t\t\t\trefineError,\n\t\t\t\t\t\trequestConfig,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t}),\n\t\t\t\t\tsignal: admission.signal,\n\t\t\t\t\tsleep: this.#sleep,\n\t\t\t\t});\n\t\t\t}, admission);\n\t\t} catch (err) {\n\t\t\treturn dispatchFailure(err);\n\t\t}\n\t}\n\n\t/**\n\t * Builds the transport callback for one logical call, wrapping the HTTP\n\t * client with the budget gate: each attempt waits on the scope's budget,\n\t * then resolves the credential (an OAuth provider runs here, after every\n\t * admission wait) before sending, then folds the response's reported\n\t * budget back in so the next attempt (or a later call on the same scope)\n\t * can head off a 429. A provider failure, or a lockout that began while the\n\t * provider ran, ends the attempt unsent and gives its budget slot back.\n\t *\n\t * @param inputs - Budget scope, transport config, observer, and caller signal.\n\t * @returns A send callback for {@link executeWithRetryAsync}.\n\t */\n\t#gatedSend({\n\t\tadmission,\n\t\tcredential,\n\t\texemptsLockout,\n\t\trefineError,\n\t\trequestConfig,\n\t\tscope,\n\t}: GatedSendInputs): (request: HttpRequest) => Promise<Result<HttpResponse, OpenCloudError>> {\n\t\treturn async (toSend) => {\n\t\t\tconst reservation = await this.#budgets.gateAsync(scope, admission);\n\t\t\tconst attempted = await resolveCallCredentialAsync(credential, admission.signal);\n\t\t\tconst resolved = this.#budgets.refuseIfLockedOut(scope, attempted);\n\t\t\tif (!resolved.success) {\n\t\t\t\treservation.release();\n\t\t\t\treturn resolved;\n\t\t\t}\n\n\t\t\tconst transportResult = await this.#httpClient.request(toSend, {\n\t\t\t\t...requestConfig,\n\t\t\t\tcredential: resolved.data,\n\t\t\t});\n\t\t\tconst sendResult = transportResult.success\n\t\t\t\t? transportResult\n\t\t\t\t: {\n\t\t\t\t\t\terr: classifySendError(transportResult.err, { credential, refineError }),\n\t\t\t\t\t\tsuccess: false as const,\n\t\t\t\t\t};\n\t\t\tobserveAttempt(this.#budgets, { exemptsLockout, scope, transportResult });\n\t\t\treturn sendResult;\n\t\t};\n\t}\n\n\t#getQueue(credentialKey: string, limit: OperationLimit): RateLimitQueue {\n\t\tconst key = scopeKey({ credentialKey, operationKey: limit.operationKey });\n\t\tconst existing = this.#queues.get(key);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);\n\t\tthis.#queues.set(key, queue);\n\t\treturn queue;\n\t}\n\n\t#merge<P, T>(\n\t\tspec: ResourceMethodSpec<P, T>,\n\t\trequestOptions: Partial<RetryResolvable>,\n\t): RetryResolvable {\n\t\treturn mergeConfig(this.#config, {\n\t\t\tmethodDefaults: spec.methodDefaults,\n\t\t\tmethodKind: spec.methodKind,\n\t\t\trequestOptions,\n\t\t});\n\t}\n}\n\nfunction budgetScopeFor(credentialKey: string, operationLimit: OperationLimit): BudgetScope {\n\treturn {\n\t\tcredentialKey,\n\t\tdocumentedWindow: documentedWindow(operationLimit),\n\t\toperationKey: operationLimit.operationKey,\n\t};\n}\n\nfunction dispatchFailure(err: unknown): Result<never, OpenCloudError> {\n\tif (\n\t\terr instanceof RequestAbortedError ||\n\t\terr instanceof RequestDeadlineExceededError ||\n\t\terr instanceof RateLimitWaitRefusedError\n\t) {\n\t\treturn { err, success: false };\n\t}\n\n\tthrow err;\n}\n\nfunction finishRequest<P, T>(\n\t{ httpResult, lifecycle, merged, request, spec }: FinishRequestInputs<P, T>,\n\treportHint: boolean,\n): Result<T, OpenCloudError> {\n\tif (httpResult.success) {\n\t\tconst parsed = spec.parse(httpResult.data);\n\t\treturn parsed.success\n\t\t\t? parsed\n\t\t\t: {\n\t\t\t\t\terr: withRequestContext(parsed.err, {\n\t\t\t\t\t\tbaseUrl: merged.baseUrl,\n\t\t\t\t\t\treportHint,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tresponse: httpResult.data,\n\t\t\t\t\t}),\n\t\t\t\t\tsuccess: false,\n\t\t\t\t};\n\t}\n\n\tconst deadlineFailure = deadlineFailureFromError(httpResult.err, lifecycle);\n\tconst err =\n\t\tdeadlineFailure ??\n\t\tenrichPermissionError(httpResult.err, {\n\t\t\tcredential: merged.credential,\n\t\t\toperationKey: spec.operationLimit.operationKey,\n\t\t\trequiredScopes: spec.requiredScopes,\n\t\t});\n\treturn {\n\t\terr: recordPreviousAttempts(err, httpResult.err.previousAttempts),\n\t\tsuccess: false,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,iBAAiB,OAAiC;CACjE,IAAI,OAAO,UAAU,UACpB,OAAO;CAGR,MAAM,SAAS,IAAI,KAAK,KAAK;CAC7B,OAAO,CAAC,OAAO,MAAM,OAAO,QAAQ,CAAC;AACtC;;;;;;;;;;;;;;ACJA,SAAgB,cAAc,OAAuC;CACpE,OAAO,YAAY,uBAAO,IAAI,IAAI,CAAC;AACpC;AAEA,SAAS,YAAY,OAAgB,MAA0C;CAC9E,IAAI,UAAU,MAEb,OAAO;CAGR,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAC9E,OAAO;CAGR,IAAI,MAAM,QAAQ,KAAK,GACtB,OAAO,YAAY,OAAO,IAAI;CAG/B,IAAI,SAAS,KAAK,GACjB,OAAO,aAAa,OAAO,IAAI;AAIjC;AAEA,SAAS,YAAY,OAA+B,MAA0C;CAC7F,IAAI,KAAK,IAAI,KAAK,GACjB;CAGD,KAAK,IAAI,KAAK;CACd,MAAM,QAA0B,CAAC;CACjC,KAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,YAAY,YAAY,MAAM,IAAI;EACxC,IAAI,cAAc,KAAA,GACjB;EAGD,MAAM,KAAK,SAAS;CACrB;CAEA,KAAK,OAAO,KAAK;CACjB,OAAO;AACR;AAEA,SAAS,aAAa,OAAgC,MAA0C;CAC/F,IAAI,KAAK,IAAI,KAAK,GACjB;CAGD,KAAK,IAAI,KAAK;CACd,MAAM,UAAsC,CAAC;CAC7C,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,KAAK,GAAG;EAChD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,cAAc;EACjD,cAAc,eAAe;CAC9B;AACD;AAEA,SAAS,gBAAgB,KAA6C;CACrE,IACC,eAAe,uBACf,eAAe,gCACf,eAAe,2BAEf,OAAO;EAAE;EAAK,SAAS;CAAM;CAG9B,MAAM;AACP;AAEA,SAAS,cACR,EAAE,YAAY,WAAW,QAAQ,SAAS,QAC1C,YAC4B;CAC5B,IAAI,WAAW,SAAS;EACvB,MAAM,SAAS,KAAK,MAAM,WAAW,IAAI;EACzC,OAAO,OAAO,UACX,SACA;GACA,KAAK,mBAAmB,OAAO,KAAK;IACnC,SAAS,OAAO;IAChB;IACA;IACA,UAAU,WAAW;GACtB,CAAC;GACD,SAAS;EACV;CACH;CAGA,MAAM,MADkB,yBAAyB,WAAW,KAAK,SAElD,KACd,sBAAsB,WAAW,KAAK;EACrC,YAAY,OAAO;EACnB,cAAc,KAAK,eAAe;EAClC,gBAAgB,KAAK;CACtB,CAAC;CACF,OAAO;EACN,KAAK,uBAAuB,KAAK,WAAW,IAAI,gBAAgB;EAChE,SAAS;CACV;AACD"}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { _ as OpenCloudErrorOptions, g as OpenCloudError, i as Credential } from "./types-CdMr_J1M.mjs";
|
|
2
|
+
//#region src/errors/rate-limit.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Which layer refused a 429, as best the SDK can tell from one response.
|
|
5
|
+
* It names the refusing layer only, not the cause of the refusal.
|
|
6
|
+
*
|
|
7
|
+
* - `"edge"`: the gateway refused before the request reached the service.
|
|
8
|
+
* - `"service"`: the service behind the gateway refused (the response names it
|
|
9
|
+
* in `x-roblox-system-reason`).
|
|
10
|
+
* - `"unknown"`: the response has no positive evidence for either layer.
|
|
11
|
+
*
|
|
12
|
+
* @since 0.4.0
|
|
13
|
+
*/
|
|
14
|
+
type RateLimitSource = "edge" | "service" | "unknown";
|
|
15
|
+
/**
|
|
16
|
+
* Options for constructing a {@link RateLimitError}.
|
|
17
|
+
*
|
|
18
|
+
* @since 0.1.0
|
|
19
|
+
*/
|
|
20
|
+
interface RateLimitErrorOptions extends OpenCloudErrorOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Parsed 429 response body, when present. Holds the server's 429
|
|
23
|
+
* explanation (JSON when the body parses, otherwise the truncated raw
|
|
24
|
+
* text) so a rate limit stays diagnosable from the error alone. A literal
|
|
25
|
+
* JSON `null` remains `null`; an absent body is `undefined`.
|
|
26
|
+
*/
|
|
27
|
+
details?: JSONValue | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Requests left in the reported rate-limit window. Read from
|
|
30
|
+
* `x-ratelimit-remaining` using the smallest valid token.
|
|
31
|
+
*
|
|
32
|
+
* `undefined` when the header has no valid non-negative integer token.
|
|
33
|
+
*
|
|
34
|
+
* Parsed separately from `x-ratelimit-reset`; a valid value survives an
|
|
35
|
+
* invalid reset.
|
|
36
|
+
*
|
|
37
|
+
* This is one budget reading, not a classifier for the cause of the 429.
|
|
38
|
+
*/
|
|
39
|
+
remaining?: number | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Allowlisted response headers useful for diagnosing the 429. Values are
|
|
42
|
+
* preserved exactly as the Fetch API presents them, including comma-joined
|
|
43
|
+
* multi-window values. The full header set is never retained.
|
|
44
|
+
*/
|
|
45
|
+
responseHeaders?: Readonly<Record<string, string>> | undefined;
|
|
46
|
+
/** Seconds to wait before retrying the request. */
|
|
47
|
+
retryAfterSeconds: number;
|
|
48
|
+
/**
|
|
49
|
+
* Which layer refused the request. Defaults to `"unknown"`.
|
|
50
|
+
*
|
|
51
|
+
* @since 0.4.0
|
|
52
|
+
*/
|
|
53
|
+
source?: RateLimitSource | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* HTTP status code that produced the error. Always `429` when minted by the
|
|
56
|
+
* SDK transport; `undefined` when constructed without one.
|
|
57
|
+
*/
|
|
58
|
+
statusCode?: number | undefined;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Thrown when the Roblox Open Cloud API returns a 429 Too Many Requests
|
|
62
|
+
* response. Contains the server-suggested retry delay and safe,
|
|
63
|
+
* machine-readable response evidence. The body code, remaining budget, and
|
|
64
|
+
* headers do not identify the upstream cause (for example quota vs place
|
|
65
|
+
* capacity). `source` names only the layer that refused the request;
|
|
66
|
+
* `"unknown"` means the response carried no positive evidence for either
|
|
67
|
+
* layer.
|
|
68
|
+
*
|
|
69
|
+
* @since 0.1.0
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
*
|
|
73
|
+
* ```ts
|
|
74
|
+
* import { RateLimitError } from "@bedrock-rbx/ocale";
|
|
75
|
+
*
|
|
76
|
+
* const error = new RateLimitError("Too many requests", {
|
|
77
|
+
* code: "RESOURCE_EXHAUSTED",
|
|
78
|
+
* remaining: 3,
|
|
79
|
+
* responseHeaders: {
|
|
80
|
+
* "retry-after": "1856",
|
|
81
|
+
* "x-ratelimit-limit": "5, 5;w=60, 5;w=60",
|
|
82
|
+
* },
|
|
83
|
+
* retryAfterSeconds: 1856,
|
|
84
|
+
* source: "service",
|
|
85
|
+
* });
|
|
86
|
+
*
|
|
87
|
+
* // `source` is a classification; the raw evidence stays available.
|
|
88
|
+
* const evidence = {
|
|
89
|
+
* code: error.code,
|
|
90
|
+
* limit: error.responseHeaders?.["x-ratelimit-limit"],
|
|
91
|
+
* retryAfter: error.responseHeaders?.["retry-after"],
|
|
92
|
+
* source: error.source,
|
|
93
|
+
* };
|
|
94
|
+
*
|
|
95
|
+
* expect(evidence).toEqual({
|
|
96
|
+
* code: "RESOURCE_EXHAUSTED",
|
|
97
|
+
* limit: "5, 5;w=60, 5;w=60",
|
|
98
|
+
* retryAfter: "1856",
|
|
99
|
+
* source: "service",
|
|
100
|
+
* });
|
|
101
|
+
* ```
|
|
102
|
+
*/
|
|
103
|
+
declare class RateLimitError extends OpenCloudError {
|
|
104
|
+
/**
|
|
105
|
+
* Parsed 429 response body. A literal JSON `null` remains `null`; an absent
|
|
106
|
+
* body is `undefined`.
|
|
107
|
+
*/
|
|
108
|
+
readonly details: JSONValue | undefined;
|
|
109
|
+
override readonly name = "RateLimitError";
|
|
110
|
+
/**
|
|
111
|
+
* Requests left in the reported window, or `undefined` if not reported.
|
|
112
|
+
*/
|
|
113
|
+
readonly remaining: number | undefined;
|
|
114
|
+
/** Allowlisted raw response headers, or `undefined` if not set. */
|
|
115
|
+
readonly responseHeaders: Readonly<Record<string, string>> | undefined;
|
|
116
|
+
readonly retryAfterSeconds: number;
|
|
117
|
+
/**
|
|
118
|
+
* Which layer refused the request, or `"unknown"` without evidence.
|
|
119
|
+
*
|
|
120
|
+
* @since 0.4.0
|
|
121
|
+
*/
|
|
122
|
+
readonly source: RateLimitSource;
|
|
123
|
+
/** HTTP status code that produced the error, or `undefined` if not set. */
|
|
124
|
+
readonly statusCode: number | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* Creates a new RateLimitError.
|
|
127
|
+
*
|
|
128
|
+
* @param message - Human-readable error description.
|
|
129
|
+
* @param options - Error options including the retry delay.
|
|
130
|
+
*/
|
|
131
|
+
constructor(message: string, options: RateLimitErrorOptions);
|
|
132
|
+
}
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/internal/http/retry.d.ts
|
|
135
|
+
/**
|
|
136
|
+
* Fully-resolved retry config shape that {@link mergeConfig} and
|
|
137
|
+
* {@link shouldRetry} operate on. Fields are required because this represents
|
|
138
|
+
* the post-defaulting, internal view; callers should supply every field (or
|
|
139
|
+
* resolve them via a test factory / client constructor). The partial,
|
|
140
|
+
* user-facing type lives on client construction options; method defaults and
|
|
141
|
+
* per-request overrides use `Partial<RetryResolvable>`.
|
|
142
|
+
*/
|
|
143
|
+
interface RetryResolvable {
|
|
144
|
+
/** Base URL for the Open Cloud API. */
|
|
145
|
+
readonly baseUrl: string;
|
|
146
|
+
/** Effective credential, resolved per transport attempt. */
|
|
147
|
+
readonly credential: Credential;
|
|
148
|
+
/** Maximum retry attempts before giving up. */
|
|
149
|
+
readonly maxRetries: number;
|
|
150
|
+
/** Status codes that are eligible for retry. */
|
|
151
|
+
readonly retryableStatuses: ReadonlyArray<number>;
|
|
152
|
+
/**
|
|
153
|
+
* Codes for transport-level failures eligible for retry: node-style
|
|
154
|
+
* transport codes ({@link findErrorCode}) surfaced as a
|
|
155
|
+
* {@link NetworkError}, plus the synthetic {@link GATEWAY_REJECTED} for a
|
|
156
|
+
* response served by an edge gateway. Not all of them prove the request
|
|
157
|
+
* went unprocessed — see {@link TRANSIENT_TRANSPORT_CODES}. Empty for
|
|
158
|
+
* create operations by default; consumers opt a create in via a per-request
|
|
159
|
+
* override.
|
|
160
|
+
*/
|
|
161
|
+
readonly retryableTransportCodes: ReadonlyArray<string>;
|
|
162
|
+
/** Fallback delay function when no server hint is available. */
|
|
163
|
+
readonly retryDelay: (attempt: number) => number;
|
|
164
|
+
/** Per-request timeout in milliseconds. */
|
|
165
|
+
readonly timeout: number;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Transient transport error codes that are safe to retry for idempotent
|
|
169
|
+
* operations. Connection resets, timeouts, and DNS hiccups are recoverable on
|
|
170
|
+
* a retry. A self-aborted request timeout carries no OS-level `code`, so
|
|
171
|
+
* {@link shouldRetry} folds it into this set as `ETIMEDOUT` (via
|
|
172
|
+
* {@link isTimeoutAbort}) for idempotent methods; create methods retry no
|
|
173
|
+
* transport codes and so still never re-issue a timed-out write.
|
|
174
|
+
*
|
|
175
|
+
* `ERR_HTTP2_STREAM_ERROR`, `ERR_HTTP2_SESSION_ERROR`, and `UND_ERR_INFO` are
|
|
176
|
+
* the same deaths as spelled by a runtime whose `fetch` negotiates HTTP/2
|
|
177
|
+
* (Node 26 and later). They differ from the socket codes in one way that
|
|
178
|
+
* matters: they do not prove the request went unprocessed. `UND_ERR_INFO`
|
|
179
|
+
* covers both a `GOAWAY` declaring a stream was never started and a stream
|
|
180
|
+
* that was fully sent, and `UND_ERR_SOCKET` can fire once a response is
|
|
181
|
+
* already streaming. Retrying them is therefore justified by the operation
|
|
182
|
+
* being safe to repeat, never by the request having gone unseen — which is
|
|
183
|
+
* why {@link UPLOAD_METHOD_DEFAULTS}, the one write policy that includes
|
|
184
|
+
* them, documents its own grounds.
|
|
185
|
+
*
|
|
186
|
+
* @since 0.1.0
|
|
187
|
+
*/
|
|
188
|
+
declare const TRANSIENT_TRANSPORT_CODES: ReadonlyArray<string>;
|
|
189
|
+
/**
|
|
190
|
+
* Synthetic transport code for a response that came from an edge gateway
|
|
191
|
+
* rather than Open Cloud ({@link ApiError.gatewaySummary}). Such a response
|
|
192
|
+
* proves the request was rejected before any Open Cloud handler saw it, so it
|
|
193
|
+
* is classified alongside {@link TRANSIENT_TRANSPORT_CODES} rather than by its
|
|
194
|
+
* HTTP status: the status belongs to the gateway, not to the API, and a
|
|
195
|
+
* gateway `400` says nothing about the validity of the request.
|
|
196
|
+
*
|
|
197
|
+
* Name it in a per-request `retryableTransportCodes` override to opt an
|
|
198
|
+
* operation into (or out of) gateway-rejection retry.
|
|
199
|
+
*
|
|
200
|
+
* @since 0.1.2
|
|
201
|
+
*/
|
|
202
|
+
declare const GATEWAY_REJECTED = "GATEWAY_REJECTED";
|
|
203
|
+
/**
|
|
204
|
+
* Synthetic transport code for a 2xx whose body could not be parsed as JSON
|
|
205
|
+
* ({@link ApiError.unparsedBodyLength}). Open Cloud does not answer a success
|
|
206
|
+
* status with a malformed document; what this failure describes in practice is
|
|
207
|
+
* a body the edge delivered short, ending mid-token at exactly the length that
|
|
208
|
+
* arrived. The next read is a fresh body and usually a whole one.
|
|
209
|
+
*
|
|
210
|
+
* Classifying it by transport code rather than by HTTP status is what makes it
|
|
211
|
+
* recoverable at all: the status is a 200, which no `retryableStatuses` list
|
|
212
|
+
* contains, so a status-keyed decision could only ever say "do not retry".
|
|
213
|
+
*
|
|
214
|
+
* Retrying is justified by the operation being safe to repeat, never by the
|
|
215
|
+
* request having gone unprocessed — a 200 proves it was processed. So this code
|
|
216
|
+
* is in {@link IDEMPOTENT_METHOD_DEFAULTS} only. Creates and uploads leave it
|
|
217
|
+
* out: their write landed, and re-issuing it to re-read the answer would risk a
|
|
218
|
+
* second resource for a response body, which is the wrong trade. A consumer who
|
|
219
|
+
* can tolerate that duplicate names this code in a per-request
|
|
220
|
+
* `retryableTransportCodes` override.
|
|
221
|
+
*
|
|
222
|
+
* @since 0.1.5
|
|
223
|
+
*/
|
|
224
|
+
declare const RESPONSE_UNPARSEABLE = "RESPONSE_UNPARSEABLE";
|
|
225
|
+
/** Kind of HTTP method the merge is being performed for. */
|
|
226
|
+
type MethodKind = "create" | "idempotent";
|
|
227
|
+
//#endregion
|
|
228
|
+
export { TRANSIENT_TRANSPORT_CODES as a, RateLimitSource as c, RetryResolvable as i, MethodKind as n, RateLimitError as o, RESPONSE_UNPARSEABLE as r, RateLimitErrorOptions as s, GATEWAY_REJECTED as t };
|
|
229
|
+
//# sourceMappingURL=retry-C2oHesDx.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry-C2oHesDx.d.mts","names":[],"sources":["../src/errors/rate-limit.ts","../src/internal/http/retry.ts"],"mappings":";;;;;;;;;;;;;KAaY;;;;;;UAOK,8BAA8B;;;;;;;EAO9C,UAAU;;;;;;;;;;;;EAYV;;;;;;EAMA,kBAAkB,SAAS;;EAE3B;;;;;;EAMA,SAAS;;;;;EAKT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8CY,uBAAuB;;;;;WAKnB,SAAS;oBACA;;;;WAIT;;WAEA,iBAAiB,SAAS;WAC1B;;;;;;WAMA,QAAQ;;WAER;;;;;;;EAQhB,YAAY,iBAAiB,SAAS;;;;;;;;;;;;UCtHtB;;WAEP;;WAEA,YAAY;;WAEZ;;WAEA,mBAAmB;;;;;;;;;;WAUnB,yBAAyB;;WAEzB,aAAa;;WAEb;;;;;;;;;;;;;;;;;;;;;;;cAwBG,2BAA2B;;;;;;;;;;;;;;cA2B3B;;;;;;;;;;;;;;;;;;;;;;cAuBA;;KA+CD"}
|