@bedrock-rbx/ocale 0.1.0-beta.19 → 0.1.0-beta.20

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.
@@ -1 +1 @@
1
- {"version":3,"file":"resource-client-lE7Tg3BK.mjs","names":["#window","#lastAllowedAt","#chains","#sleep","#trackers","#gateOnce","#tracker","#hooks","#intervalMs","#maxBucketLevel","#sleep","#chain","#waitForToken","#lastCheck","#bucketLevel","#budgets","#config","#hooks","#httpClient","#queues","#sleep","#getQueue","#gatedSend"],"sources":["../src/internal/utils/is-date-time-string.ts","../src/internal/utils/is-record.ts","../src/internal/http/budget-tracker.ts","../src/internal/http/budget-gate.ts","../src/internal/http/execute.ts","../src/internal/http/rate-limit-sample.ts","../src/internal/http/rate-limit-observation.ts","../src/internal/http/rate-limit-queue.ts","../src/internal/utils/try-catch.ts","../src/internal/http/fetch-client.ts","../src/internal/http/resolve-dependencies.ts","../src/internal/http/upload-request.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\treturn !Number.isNaN(new Date(value).getTime());\n}\n","/**\n * Narrows `value` to a plain JSON-style record. Excludes arrays, class\n * instances, primitives, and `null`/`undefined`. Used by resource\n * parsers to gate property access on wire bodies whose shape isn't\n * known at compile time.\n *\n * @param value - The unknown value to narrow.\n * @returns `true` when `value` is a plain `[object Object]`.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn Object.prototype.toString.call(value) === \"[object Object]\";\n}\n","import type { RateLimitSample } from \"./rate-limit-sample.ts\";\n\nconst MS_PER_SECOND = 1000;\n\n/** Live window state for one scope: budget left and when it resets. */\ninterface WindowState {\n\t/** Best estimate of requests still allowed before the window resets. */\n\treadonly predictedRemaining: number;\n\t/** Absolute time (ms) the window resets to full. */\n\treadonly resetAt: number;\n}\n\n/**\n * Tracks the live rate-limit budget for a single scope. Primed by `observe`\n * from response headers and drawn down by `reserve` as requests leave, so\n * `waitMs` can pace requests across the window.\n *\n * Pacing has two regimes. While budget remains, requests are spread evenly over\n * the time left in the window (`timeLeft / remaining`), so a burst does not\n * spend the whole window's budget up front and then stall. Once the budget is\n * spent, requests hold until the window resets. Budget and reset time move\n * together as one window, so the tracker is either unprimed or fully primed,\n * never half-known.\n */\nexport class BudgetTracker {\n\t/** Time (ms) the most recent request was allowed out, for spacing. */\n\t#lastAllowedAt: number | undefined = undefined;\n\t#window: undefined | WindowState = undefined;\n\n\t/**\n\t * Folds a fresh server reading in, replacing any prior window. The latest\n\t * reading wins: observe time is monotonic, so the most recently resolved\n\t * response is the best current estimate. The spacing reference is left\n\t * untouched so a window refresh does not reset pacing mid-stream.\n\t *\n\t * @param sample - Parsed `remaining`/`resetSeconds` from a response.\n\t * @param now - The current time in ms.\n\t */\n\tpublic observe(sample: RateLimitSample, now: number): void {\n\t\tthis.#window = {\n\t\t\tpredictedRemaining: sample.remaining,\n\t\t\tresetAt: now + sample.resetSeconds * MS_PER_SECOND,\n\t\t};\n\t}\n\n\t/**\n\t * Accounts for one request leaving at `now`: records the spacing reference\n\t * and decrements the prediction. A no-op on the prediction while unprimed.\n\t *\n\t * @param now - The time the request was allowed out, in ms.\n\t */\n\tpublic reserve(now: number): void {\n\t\tthis.#lastAllowedAt = now;\n\t\tif (this.#window !== undefined) {\n\t\t\tthis.#window = {\n\t\t\t\t...this.#window,\n\t\t\t\tpredictedRemaining: this.#window.predictedRemaining - 1,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Milliseconds to wait before the next request is allowed.\n\t *\n\t * @param now - The current time in ms.\n\t * @returns `0` when a request may go now (unprimed, or the first paced send);\n\t * the time until reset when the budget is spent; otherwise the time until\n\t * this request's evenly-spaced slot.\n\t */\n\tpublic waitMs(now: number): number {\n\t\tif (this.#window === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst { predictedRemaining, resetAt } = this.#window;\n\t\tif (predictedRemaining <= 0) {\n\t\t\treturn Math.max(0, resetAt - now);\n\t\t}\n\n\t\tif (this.#lastAllowedAt === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst interval = (resetAt - now) / predictedRemaining;\n\t\treturn Math.max(0, this.#lastAllowedAt + interval - now);\n\t}\n}\n","import type { SleepFunc } from \"../utils/sleep.ts\";\nimport { BudgetTracker } from \"./budget-tracker.ts\";\nimport type { RateLimitSample } from \"./rate-limit-sample.ts\";\n\n/**\n * Header-primed rate-limit gate shared across a client. Holds one\n * {@link BudgetTracker} per API key, since the tightest Roblox window is the\n * per-key one shared across every operation. Before each request the caller\n * gates on the request's key (sleeping if its budget is spent), and after each\n * response folds the parsed sample back in, so a sibling operation on the same\n * key can head off a 429 the static per-operation token bucket cannot foresee.\n * A per-operation tracker is deliberately not kept: every operation reports the\n * same most-constrained `remaining`, so a per-key tracker (drawn down by all\n * operations) is always the binding constraint.\n *\n * Gating is serialized per scope through a promise chain so concurrent\n * requests on one key cannot read the same budget and reserve the same slot;\n * each waits for the prior gate's reserve before computing its own.\n */\nexport class BudgetGate {\n\treadonly #chains = new Map<string, Promise<void>>();\n\treadonly #sleep: SleepFunc;\n\treadonly #trackers = new Map<string, BudgetTracker>();\n\n\t/**\n\t * Creates a gate bound to an injectable sleep.\n\t *\n\t * @param sleep - Injectable sleep (tests pass a fake clock).\n\t */\n\tconstructor(sleep: SleepFunc) {\n\t\tthis.#sleep = sleep;\n\t}\n\n\t/**\n\t * Holds until the scope's budget permits a send, then reserves one slot.\n\t * Runs after the prior gate on the same scope settles, whether it resolved\n\t * or rejected, so one failed attempt cannot poison later gates on the key.\n\t *\n\t * @param scope - The scope key to gate on (the effective API key).\n\t */\n\tpublic async gate(scope: string): Promise<void> {\n\t\tconst previous = this.#chains.get(scope) ?? Promise.resolve();\n\t\tconst runGate = async (): Promise<void> => this.#gateOnce(scope);\n\t\tconst mine = previous.then(runGate, runGate);\n\t\tthis.#chains.set(scope, mine);\n\t\tawait mine;\n\t}\n\n\t/**\n\t * Folds a response's parsed budget back onto the scope. A `undefined`\n\t * sample (headers absent or non-numeric) is ignored, leaving the scope on\n\t * static pacing.\n\t *\n\t * @param scope - The same scope key passed to {@link gate}.\n\t * @param sample - Parsed sample, or `undefined` when none was reported.\n\t */\n\tpublic observe(scope: string, sample: RateLimitSample | undefined): void {\n\t\tif (sample === undefined) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#tracker(scope).observe(sample, Date.now());\n\t}\n\n\tasync #gateOnce(scope: string): Promise<void> {\n\t\tconst tracker = this.#tracker(scope);\n\t\tconst waitMs = tracker.waitMs(Date.now());\n\t\tif (waitMs > 0) {\n\t\t\tawait this.#sleep(waitMs);\n\t\t}\n\n\t\ttracker.reserve(Date.now());\n\t}\n\n\t#tracker(scope: string): BudgetTracker {\n\t\tconst existing = this.#trackers.get(scope);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst tracker = new BudgetTracker();\n\t\tthis.#trackers.set(scope, tracker);\n\t\treturn tracker;\n\t}\n}\n","import type { OpenCloudError } from \"../../errors/base.ts\";\nimport type { Result } from \"../../types.ts\";\nimport type { SleepFunc } from \"../utils/sleep.ts\";\nimport { computeRetryWaitMs, type RetryResolvable, shouldRetry } from \"./retry.ts\";\nimport type { HttpRequest, HttpResponse, OpenCloudHooks } from \"./types.ts\";\n\n/** A transport callback: takes a request, returns a classified Result. */\ntype SendFunc = (request: HttpRequest) => Promise<Result<HttpResponse, OpenCloudError>>;\n\n/**\n * Inputs to {@link executeWithRetry} bundled as an options object to keep the\n * function signature narrow.\n */\ninterface ExecuteOptions {\n\t/** Fully-resolved retry config (post-merge). */\n\treadonly config: RetryResolvable;\n\t/** Client-level observability hooks. */\n\treadonly hooks: OpenCloudHooks;\n\t/** Transport callback. May be pre-wrapped by a rate-limit queue. */\n\treadonly send: SendFunc;\n\t/** Injectable sleep (tests pass a fake). */\n\treadonly sleep: SleepFunc;\n}\n\n/**\n * Retry-aware orchestration loop. Coordinates a single logical request,\n * looping over `options.send` until it succeeds, the error is non-retryable,\n * or `options.config.maxRetries` is exhausted. Fires observability hooks\n * at each transition. Domain- and queue-agnostic: `send` may be any\n * callback, including one wrapped by a rate-limit queue.\n *\n * @param request - The immutable request to send.\n * @param options - The transport callback, resolved config, hooks, and sleep.\n * @returns The first success, or the final error after retries are exhausted.\n */\nexport async function executeWithRetry(\n\trequest: HttpRequest,\n\toptions: ExecuteOptions,\n): Promise<Result<HttpResponse, OpenCloudError>> {\n\tconst { config, hooks, send, sleep } = options;\n\n\tasync function attempt(): Promise<Result<HttpResponse, OpenCloudError>> {\n\t\thooks.onRequest?.(request);\n\t\treturn send(request);\n\t}\n\n\tlet result = await attempt();\n\n\tfor (let retry = 0; retry < config.maxRetries; retry++) {\n\t\tif (result.success || !shouldRetry(result.err, config)) {\n\t\t\treturn result;\n\t\t}\n\n\t\tconst { err } = result;\n\t\thooks.onRetry?.(retry + 1, err);\n\t\tconst waitMs = computeRetryWaitMs(err, { attempt: retry, retryDelay: config.retryDelay });\n\t\thooks.onRateLimit?.(waitMs);\n\t\tawait sleep(waitMs);\n\n\t\tresult = await attempt();\n\t}\n\n\treturn result;\n}\n","/**\n * A point-in-time rate-limit budget reading parsed from Roblox Open Cloud\n * response headers. Both fields are non-negative integers.\n */\nexport interface RateLimitSample {\n\t/** Requests still allowed in the current window (the most-constrained one). */\n\treadonly remaining: number;\n\t/** Seconds until the most-constrained window resets to full. */\n\treadonly resetSeconds: number;\n}\n\n/**\n * Reduces a comma-separated rate-limit header value (e.g. `\"0, 70000\"`) to a\n * single non-negative integer via `combine`. Tokens are trimmed; blank and\n * non-finite tokens (`\"\"`, `\"Infinity\"`, `\"abc\"`) are dropped so a stray value\n * cannot corrupt the result. Returns `undefined` when the header is absent or\n * has no finite tokens.\n *\n * @param headerValue - The raw header value, or `undefined` if missing.\n * @param combine - Pairwise reducer, `Math.min` for remaining, `Math.max` for reset.\n * @returns The reduced, floored, clamped value, or `undefined`.\n */\nexport function reduceRateLimitTokens(\n\theaderValue: string | undefined,\n\tcombine: (a: number, b: number) => number,\n): number | undefined {\n\tif (headerValue === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst tokens = headerValue\n\t\t.split(\",\")\n\t\t.map((part) => part.trim())\n\t\t.filter((part) => part !== \"\")\n\t\t.map((part) => Number(part))\n\t\t.filter((value) => Number.isFinite(value));\n\tif (tokens.length === 0) {\n\t\treturn undefined;\n\t}\n\n\treturn Math.max(0, Math.floor(tokens.reduce(combine)));\n}\n\n/**\n * Parses the `x-ratelimit-remaining` and `x-ratelimit-reset` response headers\n * into a {@link RateLimitSample}. Each header may carry a comma-separated list\n * of per-window values; `remaining` takes the smallest (most constrained) and\n * `resetSeconds` takes the largest (longest wait), symmetric to how a 429's\n * retry delay is reduced. Returns `undefined` when either header is missing or\n * has no finite numeric tokens, so a caller can fall back to static pacing.\n *\n * @param headers - Response headers with lowercased keys.\n * @returns The parsed sample, or `undefined` when the budget cannot be read.\n */\nexport function parseRateLimitHeaders(\n\theaders: Readonly<Record<string, string>>,\n): RateLimitSample | undefined {\n\tconst remaining = reduceRateLimitTokens(headers[\"x-ratelimit-remaining\"], (a, b) =>\n\t\tMath.min(a, b),\n\t);\n\tconst resetSeconds = reduceRateLimitTokens(headers[\"x-ratelimit-reset\"], (a, b) =>\n\t\tMath.max(a, b),\n\t);\n\tif (remaining === undefined || resetSeconds === undefined) {\n\t\treturn undefined;\n\t}\n\n\treturn { remaining, resetSeconds };\n}\n","import type { OpenCloudError } from \"../../errors/base.ts\";\nimport { RateLimitError } from \"../../errors/rate-limit.ts\";\nimport type { Result } from \"../../types.ts\";\nimport type { RateLimitSample } from \"./rate-limit-sample.ts\";\nimport { parseRateLimitHeaders } from \"./rate-limit-sample.ts\";\nimport type { HttpResponse } from \"./types.ts\";\n\n/**\n * Extracts a {@link RateLimitSample} from a transport result so the budget gate\n * can be fed from every attempt. A 2xx carries the budget in its headers; a 429\n * carries it on the {@link RateLimitError} (the raw headers are dropped before\n * this point). Any other error, or a response that reported no budget, yields\n * `undefined` and leaves the gate on static pacing.\n *\n * @param result - The classified transport result for one attempt.\n * @returns The parsed sample, or `undefined` when none was reported.\n */\nexport function rateLimitSampleFromResult(\n\tresult: Result<HttpResponse, OpenCloudError>,\n): RateLimitSample | undefined {\n\tif (result.success) {\n\t\treturn parseRateLimitHeaders(result.data.headers);\n\t}\n\n\tconst { err } = result;\n\tif (err instanceof RateLimitError && err.remaining !== undefined) {\n\t\treturn { remaining: err.remaining, resetSeconds: err.retryAfterSeconds };\n\t}\n\n\treturn undefined;\n}\n","import type { SleepFunc } from \"../utils/sleep.ts\";\nimport type { OpenCloudHooks } from \"./types.ts\";\n\n/**\n * Identifies and bounds a single Roblox Open Cloud operation for rate\n * limiting, e.g. `{ operationKey: \"game-passes.create\", maxPerSecond: 5 }`.\n */\nexport interface OperationLimit {\n\t/** Maximum sustained request rate in requests per second. */\n\treadonly maxPerSecond: number;\n\t/**\n\t * Stable identifier for the operation (e.g. \"game-passes.create\"). Not\n\t * consumed by the queue itself; callers use it to key per-operation\n\t * queues in a registry (see GamePassesClient).\n\t */\n\treadonly operationKey: string;\n}\n\n/**\n * Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every\n * call to `acquire` consumes one token; when the bucket is empty the call\n * waits until a token regenerates before invoking the task. Burst capacity\n * equals `maxPerSecond`, refilling at `maxPerSecond` tokens per second.\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.\n */\nexport class RateLimitQueue {\n\treadonly #hooks: OpenCloudHooks;\n\treadonly #intervalMs: number;\n\treadonly #maxBucketLevel: number;\n\treadonly #sleep: SleepFunc;\n\n\t#bucketLevel = 0;\n\t#chain: Promise<void> = Promise.resolve();\n\t#lastCheck: number = Date.now();\n\n\t/**\n\t * Creates a rate-limit queue bound to a single operation.\n\t *\n\t * @param limit - The operation key and its per-second request ceiling.\n\t * @param hooks - Observability callbacks; `onRateLimit` fires when the\n\t * bucket is empty and a sleep is about to start.\n\t * @param sleep - Injectable sleep (tests pass a fake).\n\t */\n\tconstructor(limit: OperationLimit, hooks: OpenCloudHooks, sleep: SleepFunc) {\n\t\tthis.#intervalMs = 1000 / limit.maxPerSecond;\n\t\tthis.#maxBucketLevel = limit.maxPerSecond * this.#intervalMs;\n\t\tthis.#hooks = hooks;\n\t\tthis.#sleep = sleep;\n\t}\n\n\t/**\n\t * Waits for a token — sleeping and firing `hooks.onRateLimit` if the\n\t * bucket is empty — then executes `task`. Concurrent callers are\n\t * serialized at token acquisition; tasks themselves run independently\n\t * once their token is secured.\n\t *\n\t * @param task - The request to run once a token is available.\n\t * @returns The value produced by `task`.\n\t */\n\tpublic async acquire<T>(task: () => Promise<T>): Promise<T> {\n\t\tconst myTurn = this.#chain.then(async () => this.#waitForToken());\n\t\tthis.#chain = myTurn;\n\t\tawait myTurn;\n\t\treturn task();\n\t}\n\n\tasync #waitForToken(): Promise<void> {\n\t\tconst now = Math.max(Date.now(), this.#lastCheck);\n\t\tconst drained = Math.max(0, this.#bucketLevel - (now - this.#lastCheck));\n\t\tthis.#lastCheck = now;\n\n\t\tif (drained + this.#intervalMs <= this.#maxBucketLevel) {\n\t\t\tthis.#bucketLevel = drained + this.#intervalMs;\n\t\t\treturn;\n\t\t}\n\n\t\tconst waitMs = drained + this.#intervalMs - this.#maxBucketLevel;\n\t\tthis.#hooks.onRateLimit?.(waitMs);\n\t\tawait this.#sleep(waitMs);\n\t\tthis.#bucketLevel = this.#maxBucketLevel;\n\t\tthis.#lastCheck = now + waitMs;\n\t}\n}\n","import type { Result } from \"../../types.ts\";\n\n/**\n * Wraps a promise into a {@link Result}, catching rejections.\n *\n * @template T - The resolved value type.\n * @param promise - The promise to wrap.\n * @returns A Result containing the resolved value or the rejection error.\n */\nexport async function tryCatch<T>(promise: Promise<T>): Promise<Result<T>> {\n\ttry {\n\t\tconst data = await promise;\n\t\treturn { data, success: true };\n\t} catch (err) {\n\t\treturn { err: err instanceof Error ? err : new Error(String(err)), success: false };\n\t}\n}\n","import { ApiError } from \"../../errors/api-error.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { NetworkError } from \"../../errors/network-error.ts\";\nimport { RateLimitError } from \"../../errors/rate-limit.ts\";\nimport type { Result } from \"../../types.ts\";\nimport { tryCatch } from \"../utils/try-catch.ts\";\nimport { reduceRateLimitTokens } from \"./rate-limit-sample.ts\";\nimport type { HttpClient, HttpRequest, HttpResponse, RequestConfig } from \"./types.ts\";\n\n// Caps the raw body retained when a response cannot be parsed, so a multi-KB\n// HTML error page is not surfaced or logged whole.\nconst MAX_DETAIL_LENGTH = 500;\n\nconst CONTENT_TYPE_HEADER = \"content-type\";\n\ninterface ParseFailureArgs {\n\treadonly cause: Error;\n\treadonly response: Response;\n\treadonly text: string;\n}\n\ninterface ApiErrorMessageParts {\n\treadonly code: string | undefined;\n\treadonly message: string | undefined;\n\treadonly status: number;\n}\n\n/**\n * Converts a `Headers` object to a plain record with lowercased keys.\n *\n * @param headers - The `Headers` instance to convert.\n * @returns A record mapping lowercased header names to their values.\n */\nexport function headersToRecord(headers: Headers): Record<string, string> {\n\treturn Object.fromEntries(headers);\n}\n\n/**\n * Permissively extracts a machine-readable error code from a response body.\n *\n * Modern Open Cloud responses use `{ errorCode: string, message: string }`;\n * the legacy game-internationalization endpoints use\n * `{ errors: [{ code: number, message: string }, ...] }`. Both shapes are\n * checked; numeric legacy codes are returned as strings so callers see one\n * consistent type.\n *\n * @param body - The parsed response body (unknown shape).\n * @returns The error code if present, otherwise `undefined`.\n */\nexport function extractErrorCode(body: unknown): string | undefined {\n\tif (body === null || typeof body !== \"object\") {\n\t\treturn undefined;\n\t}\n\n\tconst errorCode = Reflect.get(body, \"errorCode\");\n\tif (typeof errorCode === \"string\") {\n\t\treturn errorCode;\n\t}\n\n\treturn extractLegacyCode(body);\n}\n\n/**\n * Permissively extracts a human-readable error message from a response body.\n *\n * Modern Open Cloud responses expose `message` at the top level; the legacy\n * game-internationalization endpoints nest it under `errors[0].message`.\n *\n * @param body - The parsed response body (unknown shape).\n * @returns The message if present, otherwise `undefined`.\n */\nexport function extractErrorMessage(body: unknown): string | undefined {\n\tif (body === null || typeof body !== \"object\") {\n\t\treturn undefined;\n\t}\n\n\tconst message = Reflect.get(body, \"message\");\n\tif (typeof message === \"string\") {\n\t\treturn message;\n\t}\n\n\treturn extractLegacyMessage(body);\n}\n\n/**\n * Parses the `x-ratelimit-reset` header value into seconds. On a 429 the header\n * is a comma-separated list of per-window reset times (e.g. `\"22, 0\"`, one entry\n * per rate-limit window); the largest value is the longest-resetting window and\n * the only safe wait that won't retry into a still-exhausted window. A single\n * value is treated as a one-element list.\n *\n * @param headerValue - The raw header value, or `undefined` if missing.\n * @returns The number of seconds to wait, or 0 if missing/invalid.\n */\nexport function parseRetryAfterSeconds(headerValue: string | undefined): number {\n\treturn reduceRateLimitTokens(headerValue, (a, b) => Math.max(a, b)) ?? 0;\n}\n\n/**\n * Joins the base URL from config with the relative path from the request.\n *\n * @param request - The HTTP request containing the relative URL.\n * @param config - The request config containing the base URL.\n * @returns The fully-qualified URL string.\n */\nexport function buildUrl(request: HttpRequest, config: RequestConfig): string {\n\tconst base = config.baseUrl.endsWith(\"/\") ? config.baseUrl.slice(0, -1) : config.baseUrl;\n\treturn `${base}${request.url}`;\n}\n\n/**\n * Constructs the `RequestInit` options for a `fetch` call.\n *\n * @param request - The HTTP request to build options for.\n * @param config - The request config containing API key and timeout.\n * @returns A `RequestInit` object ready for `fetch`.\n */\nexport function buildFetchOptions(request: HttpRequest, config: RequestConfig): RequestInit {\n\tconst headers = new Headers({\n\t\t\"x-api-key\": config.apiKey,\n\t});\n\n\tconst options: RequestInit = {\n\t\theaders,\n\t\tmethod: request.method,\n\t};\n\n\tif (request.body instanceof FormData) {\n\t\toptions.body = request.body;\n\t} else if (request.body instanceof Uint8Array) {\n\t\theaders.set(CONTENT_TYPE_HEADER, \"application/octet-stream\");\n\t\toptions.body = request.body;\n\t} else if (request.body !== undefined) {\n\t\theaders.set(CONTENT_TYPE_HEADER, \"application/json\");\n\t\toptions.body = JSON.stringify(request.body);\n\t}\n\n\tif (request.headers !== undefined) {\n\t\tfor (const [name, value] of Object.entries(request.headers)) {\n\t\t\tif (name.toLowerCase() === \"x-api-key\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\theaders.set(name, value);\n\t\t}\n\t}\n\n\tif (config.timeout !== undefined) {\n\t\toptions.signal = AbortSignal.timeout(config.timeout);\n\t}\n\n\treturn options;\n}\n\n/**\n * Creates an {@link HttpClient} backed by the Fetch API.\n *\n * @param fetchFunc - The fetch implementation to use. Defaults to `globalThis.fetch`.\n * @returns An HttpClient that classifies responses into typed Results.\n */\nexport function createFetchHttpClient(\n\tfetchFunc: (url: string, init: RequestInit) => Promise<Response> = globalThis.fetch,\n): HttpClient {\n\treturn {\n\t\tasync request(\n\t\t\thttpRequest: HttpRequest,\n\t\t\tconfig: RequestConfig,\n\t\t): Promise<Result<HttpResponse, OpenCloudError>> {\n\t\t\tconst url = buildUrl(httpRequest, config);\n\t\t\tconst options = buildFetchOptions(httpRequest, config);\n\n\t\t\tconst fetchResult = await tryCatch(fetchFunc(url, options));\n\t\t\tif (!fetchResult.success) {\n\t\t\t\treturn {\n\t\t\t\t\terr: new NetworkError(\"Network request failed\", {\n\t\t\t\t\t\tcause: fetchResult.err,\n\t\t\t\t\t\tmethod: httpRequest.method,\n\t\t\t\t\t\turl,\n\t\t\t\t\t}),\n\t\t\t\t\tsuccess: false,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn classifyResponse(fetchResult.data);\n\t\t},\n\t};\n}\n\nfunction readLegacyErrorEntry(body: object): object | undefined {\n\tconst errors = Reflect.get(body, \"errors\");\n\tif (!Array.isArray(errors)) {\n\t\treturn undefined;\n\t}\n\n\tconst [first] = errors;\n\tif (typeof first !== \"object\" || first === null) {\n\t\treturn undefined;\n\t}\n\n\treturn first;\n}\n\nfunction extractLegacyCode(body: object): string | undefined {\n\tconst first = readLegacyErrorEntry(body);\n\tif (first === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst code = Reflect.get(first, \"code\");\n\tif (typeof code === \"string\") {\n\t\treturn code;\n\t}\n\n\treturn typeof code === \"number\" ? String(code) : undefined;\n}\n\nfunction extractLegacyMessage(body: object): string | undefined {\n\tconst first = readLegacyErrorEntry(body);\n\tif (first === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst message = Reflect.get(first, \"message\");\n\treturn typeof message === \"string\" ? message : undefined;\n}\n\nfunction formatApiErrorMessage(parts: ApiErrorMessageParts): string {\n\tconst { code, message, status } = parts;\n\tconst base = `HTTP ${status}`;\n\tif (message === undefined && code === undefined) {\n\t\treturn base;\n\t}\n\n\tif (message === undefined) {\n\t\treturn `${base} (code ${code})`;\n\t}\n\n\tif (code === undefined) {\n\t\treturn `${base}: ${message}`;\n\t}\n\n\treturn `${base}: ${message} (code ${code})`;\n}\n\nfunction createApiError(status: number, body: JSONValue | undefined): ApiError {\n\tconst code = extractErrorCode(body);\n\tconst message = extractErrorMessage(body);\n\treturn new ApiError(formatApiErrorMessage({ code, message, status }), {\n\t\tcode,\n\t\tdetails: body,\n\t\tstatusCode: status,\n\t});\n}\n\nfunction createRateLimitError(response: Response): RateLimitError {\n\tconst headers = headersToRecord(response.headers);\n\treturn new RateLimitError(\"Rate limited\", {\n\t\tremaining: reduceRateLimitTokens(headers[\"x-ratelimit-remaining\"], (a, b) =>\n\t\t\tMath.min(a, b),\n\t\t),\n\t\tretryAfterSeconds: parseRetryAfterSeconds(headers[\"x-ratelimit-reset\"]),\n\t});\n}\n\n/**\n * Parses response text as JSON, returning the underlying `SyntaxError` on\n * failure rather than throwing. The synchronous sibling of {@link tryCatch}.\n *\n * @param text - The raw response body text.\n * @returns A Result wrapping the parsed value, or the parse error.\n */\nfunction parseJson(text: string): Result<JSONValue> {\n\ttry {\n\t\treturn { data: JSON.parse(text), success: true };\n\t} catch (err) {\n\t\treturn { err: err instanceof Error ? err : new Error(String(err)), success: false };\n\t}\n}\n\n/**\n * Builds the error for a 2xx response whose body could not be parsed as JSON,\n * preserving the parse `cause`, the (truncated) raw body, and the declared\n * content-type so the failure can be diagnosed after the fact.\n *\n * @param args - The Response, raw body text, and underlying parse error.\n * @returns An ApiError carrying the diagnostic context.\n */\nfunction parseFailureError({ cause, response, text }: ParseFailureArgs): ApiError {\n\tconst contentType = response.headers.get(CONTENT_TYPE_HEADER) ?? \"unknown\";\n\treturn new ApiError(`Failed to parse response body (content-type: ${contentType})`, {\n\t\tcause,\n\t\tdetails: text.slice(0, MAX_DETAIL_LENGTH),\n\t\tstatusCode: response.status,\n\t});\n}\n\n/**\n * Classifies a fetch `Response` into a typed `Result`.\n *\n * The body is read once and parsed best-effort. Error responses (status >= 300)\n * never require valid JSON: an error body that is not valid JSON (for example\n * an HTML gateway page) degrades to a status-based {@link ApiError} carrying\n * the raw text. A parse failure is only fatal on a 2xx, where a parseable body is part\n * of the contract.\n *\n * @param response - The raw fetch Response to classify.\n * @returns A Result containing an HttpResponse on success or an OpenCloudError on failure.\n */\nasync function classifyResponse(response: Response): Promise<Result<HttpResponse, OpenCloudError>> {\n\tif (response.status === 429) {\n\t\treturn { err: createRateLimitError(response), success: false };\n\t}\n\n\tconst text = await response.text();\n\tconst parsed: Result<JSONValue | undefined> =\n\t\ttext === \"\" ? { data: undefined, success: true } : parseJson(text);\n\n\tif (response.status >= 300) {\n\t\tconst body = parsed.success ? parsed.data : text.slice(0, MAX_DETAIL_LENGTH);\n\t\treturn { err: createApiError(response.status, body), success: false };\n\t}\n\n\tif (!parsed.success) {\n\t\treturn { err: parseFailureError({ cause: parsed.err, response, text }), success: false };\n\t}\n\n\treturn {\n\t\tdata: {\n\t\t\tbody: parsed.data,\n\t\t\theaders: headersToRecord(response.headers),\n\t\t\tstatus: response.status,\n\t\t},\n\t\tsuccess: true,\n\t};\n}\n","import { setTimeout } from \"node:timers/promises\";\n\nimport type { HttpClient, SleepFunc } from \"../../client/types.ts\";\nimport { createFetchHttpClient } from \"./fetch-client.ts\";\n\n/**\n * Options accepted by {@link resolveDependencies}. Mirrors the test-seam\n * subset of the public client options.\n */\ninterface ResolveDependenciesOptions {\n\t/** Test seam: custom {@link HttpClient}. Defaults to a fetch-backed client. */\n\treadonly httpClient?: HttpClient | undefined;\n\t/** Test seam: custom {@link SleepFunc}. Defaults to a `setTimeout`-backed sleep. */\n\treadonly sleep?: SleepFunc | undefined;\n}\n\n/**\n * Fully-populated dependency set consumed by resource client constructors.\n */\ninterface ResolvedDependencies {\n\t/** Concrete {@link HttpClient} implementation. */\n\treadonly httpClient: HttpClient;\n\t/** Concrete {@link SleepFunc} implementation. */\n\treadonly sleep: SleepFunc;\n}\n\n/**\n * Resolves the concrete HTTP client and sleep implementation a resource\n * client should use. Falls back to the fetch-backed HTTP client and the\n * default `setTimeout`-based sleep when the caller omits the test seams.\n *\n * Extracted so resource client constructors can keep their dependency\n * resolution logic in a single, unit-testable place; this makes the\n * default branches easy to cover without stubbing globals like `fetch`.\n *\n * @param options - Optional {@link HttpClient} and {@link SleepFunc} test seams.\n * @returns A {@link ResolvedDependencies} with defaults applied.\n */\nexport function resolveDependencies(options: ResolveDependenciesOptions): ResolvedDependencies {\n\treturn {\n\t\thttpClient: options.httpClient ?? createFetchHttpClient(),\n\t\tsleep: options.sleep ?? setTimeout,\n\t};\n}\n","import type { HttpRequest } from \"../../client/types.ts\";\n\n/**\n * Reports whether a request is an upload: its body is `FormData`\n * (multipart) or `Uint8Array` (raw binary). Upload latency is\n * bandwidth-bound rather than compute-bound, so the SDK applies no default\n * request timeout to these requests; a sensible wall-clock budget depends on\n * payload size and link quality the SDK cannot know.\n *\n * @param request - The built request to classify.\n * @returns `true` when the body is `FormData` or `Uint8Array`.\n */\nexport function isUploadRequest(request: HttpRequest): boolean {\n\treturn request.body instanceof FormData || request.body instanceof Uint8Array;\n}\n","import type { Except } from \"type-fest\";\n\nimport type {\n\tHttpClient,\n\tHttpRequest,\n\tHttpResponse,\n\tOpenCloudClientOptions,\n\tOpenCloudHooks,\n\tRequestConfig,\n\tRequestOptions,\n\tSleepFunc,\n} from \"../client/types.ts\";\nimport { ApiError } from \"../errors/api-error.ts\";\nimport type { OpenCloudError } from \"../errors/base.ts\";\nimport { PermissionError } from \"../errors/permission-error.ts\";\nimport type { Result } from \"../types.ts\";\nimport { BudgetGate } from \"./http/budget-gate.ts\";\nimport { executeWithRetry } from \"./http/execute.ts\";\nimport { rateLimitSampleFromResult } from \"./http/rate-limit-observation.ts\";\nimport { type OperationLimit, RateLimitQueue } from \"./http/rate-limit-queue.ts\";\nimport { resolveDependencies } from \"./http/resolve-dependencies.ts\";\nimport {\n\tdefaultRetryDelay,\n\tIDEMPOTENT_METHOD_DEFAULTS,\n\tmergeConfig,\n\ttype MethodKind,\n\ttype RetryResolvable,\n} from \"./http/retry.ts\";\nimport { isUploadRequest } from \"./http/upload-request.ts\";\n\n/**\n * Describes a single resource method's shape for dispatch through\n * `ResourceClient.execute`. Each resource client declares one module-level\n * constant per public method; that constant binds the four resource-specific\n * values (request builder, response parser, retry-policy method kind,\n * operation-level rate limit) and flows through `execute` uniformly.\n *\n * @template P - The resource-specific parameter shape the builder\n * accepts.\n * @template T - The resource-specific parsed success type the parser\n * produces.\n */\nexport interface ResourceMethodSpec<P, T> {\n\t/**\n\t * Builds the pure {@link HttpRequest} for a single call. Returns a\n\t * {@link Result} so a builder can short-circuit with a local error\n\t * (typically a {@link OpenCloudError} subclass such as `ValidationError`)\n\t * before any HTTP, queue, or retry work happens. Builders that cannot\n\t * fail wrap their return as `{ data: request, success: true }`.\n\t */\n\treadonly buildRequest: (parameters: P) => Result<HttpRequest, OpenCloudError>;\n\t/** Method-level retry defaults merged into the resolved config. */\n\treadonly methodDefaults: Partial<RetryResolvable>;\n\t/**\n\t * Method kind, controlling merge precedence: `\"create\"` lets method\n\t * defaults win over client config so create safety cannot be relaxed\n\t * silently; `\"idempotent\"` lets client config win over method defaults\n\t * so consumers can loosen retry globally.\n\t */\n\treadonly methodKind: MethodKind;\n\t/** Operation-level rate limit, keyed into the client's per-key queue map. */\n\treadonly operationLimit: OperationLimit;\n\t/**\n\t * Converts the full {@link HttpResponse} into the resource-specific\n\t * parsed shape. Takes the whole response (body, status, headers) so\n\t * future parsers can read headers without widening the signature.\n\t */\n\treadonly parse: (response: HttpResponse) => Result<T, OpenCloudError>;\n\t/**\n\t * Open Cloud scopes the API key or OAuth token must carry for this\n\t * method, sourced from the vendored OpenAPI schema's `x-roblox-scopes`.\n\t * When set, a 401 or 403 ApiError from the upstream call is upgraded to\n\t * a {@link PermissionError} carrying these scopes alongside\n\t * {@link OperationLimit.operationKey}, so callers can name the missing\n\t * scope instead of just the HTTP status. Optional so test specs and\n\t * not-yet-wired resources can opt out.\n\t */\n\treadonly requiredScopes?: ReadonlyArray<string>;\n}\n\n/**\n * Single-argument bundle consumed by `ResourceClient.execute`: the per-method\n * spec, the resource-specific parameters, and optional per-request config\n * overrides.\n *\n * @template P - The resource-specific parameter shape the builder accepts.\n * @template T - The resource-specific parsed success type the parser produces.\n */\ninterface ExecuteCall<P, T> {\n\t/** Optional per-request config overrides. */\n\treadonly options?: RequestOptions | undefined;\n\t/** Resource-specific request parameters. */\n\treadonly parameters: P;\n\t/** Per-method binding of builder, parser, method kind, and operation limit. */\n\treadonly spec: ResourceMethodSpec<P, T>;\n}\n\n/**\n * Wraps an infallible request build as a {@link Result}-returning\n * `buildRequest` callback compatible with {@link ResourceMethodSpec}.\n * Use from a resource client whose builder cannot fail; resource clients\n * with local validation should construct the {@link Result} directly.\n *\n * @param request - The pre-built {@link HttpRequest}.\n * @returns A success Result wrapping the request.\n */\nexport function okRequest(request: HttpRequest): Result<HttpRequest, OpenCloudError> {\n\treturn { data: request, success: true };\n}\n\n/**\n * A {@link ResourceMethodSpec.parse} implementation for endpoints that return\n * no business payload on success (such as `DELETE` and reorder operations).\n * Surfaces `undefined` data and never inspects the response body.\n *\n * @returns A success Result with `undefined` data.\n */\nexport function parseEmptyResponse(): Result<undefined, OpenCloudError> {\n\treturn { data: undefined, success: true };\n}\n\nconst CLIENT_DEFAULTS = Object.freeze({\n\tbaseUrl: \"https://apis.roblox.com\",\n\tmaxRetries: 3,\n\tretryableStatuses: IDEMPOTENT_METHOD_DEFAULTS.retryableStatuses,\n\tretryableTransportCodes: IDEMPOTENT_METHOD_DEFAULTS.retryableTransportCodes,\n\tretryDelay: defaultRetryDelay,\n\ttimeout: 30_000,\n} satisfies Except<RetryResolvable, \"apiKey\">);\n\n/**\n * Inputs to {@link buildRequestConfig}, bundled to keep the signature narrow.\n */\ninterface RequestConfigInputs {\n\t/** The resolved config for this call. */\n\treadonly merged: RetryResolvable;\n\t/** The caller's per-request overrides, if any. */\n\treadonly options: RequestOptions | undefined;\n\t/** The built request, inspected for an upload body. */\n\treadonly request: HttpRequest;\n}\n\n/**\n * Internal orchestrator shared by every Open Cloud resource client. Holds\n * the frozen client config, observability hooks, injected HTTP client and\n * sleep, and the per-effective-key rate-limit queue registry. Resource\n * classes compose one instance and dispatch every public method through\n * {@link ResourceClient.execute} with a per-method {@link ResourceMethodSpec}.\n * Not exported from any package subpath; reachable only via sibling\n * `src/resources/**` modules in this package.\n */\nexport class ResourceClient {\n\treadonly #budgets: BudgetGate;\n\treadonly #config: Readonly<RetryResolvable>;\n\treadonly #hooks: OpenCloudHooks;\n\treadonly #httpClient: HttpClient;\n\treadonly #queues = new Map<string, RateLimitQueue>();\n\treadonly #sleep: SleepFunc;\n\n\t/**\n\t * Creates a new {@link ResourceClient}. Resolves the injected HTTP\n\t * client and sleep (defaulting to fetch + `setTimeout`) and freezes the\n\t * merged client config so subsequent calls cannot mutate it.\n\t *\n\t * @param options - Client-level configuration including the API key\n\t * and optional construction-time test seams.\n\t */\n\tconstructor(options: OpenCloudClientOptions) {\n\t\tconst { apiKey, hooks, httpClient, sleep, ...overrides } = options;\n\t\tconst resolved = resolveDependencies({ httpClient, sleep });\n\t\tthis.#httpClient = resolved.httpClient;\n\t\tthis.#sleep = resolved.sleep;\n\t\tthis.#budgets = new BudgetGate(this.#sleep);\n\t\tthis.#hooks = hooks ?? {};\n\t\tthis.#config = Object.freeze({\n\t\t\t...CLIENT_DEFAULTS,\n\t\t\tapiKey,\n\t\t\t...overrides,\n\t\t});\n\t}\n\n\t/**\n\t * Dispatches a single resource-method call. Merges the frozen client\n\t * config with the method's `methodDefaults` and the caller's optional\n\t * per-request `options`, routes through the effective-apiKey rate-limit\n\t * queue, runs the retry loop, and finally parses the response with the\n\t * spec's parser.\n\t *\n\t * @param call - The per-method spec, resource-specific parameters, and\n\t * optional per-request overrides.\n\t * @returns The parsed success payload or the {@link OpenCloudError} that\n\t * caused the request to fail. Never throws.\n\t */\n\tpublic async execute<P, T>(call: ExecuteCall<P, T>): Promise<Result<T, OpenCloudError>> {\n\t\tconst { options, parameters, spec } = call;\n\t\tconst merged = mergeConfig(this.#config, {\n\t\t\tmethodDefaults: spec.methodDefaults,\n\t\t\tmethodKind: spec.methodKind,\n\t\t\trequestOptions: options ?? {},\n\t\t});\n\t\tconst requestResult = spec.buildRequest(parameters);\n\t\tif (!requestResult.success) {\n\t\t\treturn requestResult;\n\t\t}\n\n\t\tconst requestConfig = buildRequestConfig({ merged, options, request: requestResult.data });\n\t\tconst queue = this.#getQueue(merged.apiKey, spec.operationLimit);\n\t\tconst httpResult = await queue.acquire(async () => {\n\t\t\treturn executeWithRetry(requestResult.data, {\n\t\t\t\tconfig: merged,\n\t\t\t\thooks: this.#hooks,\n\t\t\t\tsend: this.#gatedSend(merged.apiKey, requestConfig),\n\t\t\t\tsleep: this.#sleep,\n\t\t\t});\n\t\t});\n\t\tif (!httpResult.success) {\n\t\t\treturn { err: enrichPermissionError(httpResult.err, spec), success: false };\n\t\t}\n\n\t\treturn spec.parse(httpResult.data);\n\t}\n\n\t/**\n\t * Returns the sleep function used by this client instance.\n\t *\n\t * @returns The sleep function injected at construction time.\n\t */\n\tpublic get sleep(): SleepFunc {\n\t\treturn this.#sleep;\n\t}\n\n\t/**\n\t * Builds the transport callback for one logical call, wrapping the HTTP\n\t * client with the budget gate: each attempt waits on the API key's budget\n\t * before sending, then folds the response's reported budget back in so the\n\t * next attempt (or a sibling operation on the same key) can head off a 429.\n\t *\n\t * @param apiKey - The effective API key to gate on.\n\t * @param requestConfig - The resolved per-request transport config.\n\t * @returns A send callback for {@link executeWithRetry}.\n\t */\n\t#gatedSend(\n\t\tapiKey: string,\n\t\trequestConfig: RequestConfig,\n\t): (request: HttpRequest) => Promise<Result<HttpResponse, OpenCloudError>> {\n\t\treturn async (toSend) => {\n\t\t\tawait this.#budgets.gate(apiKey);\n\t\t\tconst sendResult = await this.#httpClient.request(toSend, requestConfig);\n\t\t\tthis.#budgets.observe(apiKey, rateLimitSampleFromResult(sendResult));\n\t\t\treturn sendResult;\n\t\t};\n\t}\n\n\t#getQueue(apiKey: string, limit: OperationLimit): RateLimitQueue {\n\t\tconst key = `${apiKey}::${limit.operationKey}`;\n\t\tconst existing = this.#queues.get(key);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);\n\t\tthis.#queues.set(key, queue);\n\t\treturn queue;\n\t}\n}\n\n/**\n * Resolves the per-request {@link RequestConfig}. Upload requests\n * ({@link isUploadRequest}) carry no default timeout: a multi-megabyte place\n * file over a slow link is bandwidth-bound, so a client-side deadline only\n * fires spuriously. An explicit `options.timeout` still applies to any\n * request; every non-upload request keeps the merged default.\n *\n * @param inputs - The merged config, the built request, and per-request overrides.\n * @returns The config to hand to the transport, with `timeout` omitted when\n * no client-side deadline should apply.\n */\nfunction buildRequestConfig(inputs: RequestConfigInputs): RequestConfig {\n\tconst { merged, options, request } = inputs;\n\tconst shouldOmitDefaultTimeout = options?.timeout === undefined && isUploadRequest(request);\n\treturn {\n\t\tapiKey: merged.apiKey,\n\t\tbaseUrl: merged.baseUrl,\n\t\t...(shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }),\n\t};\n}\n\nfunction enrichPermissionError<P, T>(\n\terr: OpenCloudError,\n\tspec: ResourceMethodSpec<P, T>,\n): OpenCloudError {\n\tif (spec.requiredScopes === undefined) {\n\t\treturn err;\n\t}\n\n\tif (err instanceof PermissionError) {\n\t\treturn err;\n\t}\n\n\tif (!(err instanceof ApiError)) {\n\t\treturn err;\n\t}\n\n\tif (err.statusCode !== 401 && err.statusCode !== 403) {\n\t\treturn err;\n\t}\n\n\treturn new PermissionError(err.message, {\n\t\tcause: err.cause,\n\t\tcode: err.code,\n\t\toperationKey: spec.operationLimit.operationKey,\n\t\trequiredScopes: spec.requiredScopes,\n\t\tstatusCode: err.statusCode,\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,iBAAiB,OAAiC;CACjE,IAAI,OAAO,UAAU,UACpB,OAAO;CAGR,OAAO,CAAC,OAAO,MAAM,IAAI,KAAK,KAAK,EAAE,QAAQ,CAAC;AAC/C;;;;;;;;;;;;ACPA,SAAgB,SAAS,OAAkD;CAC1E,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AAClD;;;ACTA,MAAM,gBAAgB;;;;;;;;;;;;;AAsBtB,IAAa,gBAAb,MAA2B;;CAE1B,iBAAqC,KAAA;CACrC,UAAmC,KAAA;;;;;;;;;;CAWnC,QAAe,QAAyB,KAAmB;EAC1D,KAAKA,UAAU;GACd,oBAAoB,OAAO;GAC3B,SAAS,MAAM,OAAO,eAAe;EACtC;CACD;;;;;;;CAQA,QAAe,KAAmB;EACjC,KAAKC,iBAAiB;EACtB,IAAI,KAAKD,YAAY,K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ource-client-lE7Tg3BK.mjs","names":["#window","#lastAllowedAt","#chains","#sleep","#trackers","#gateOnce","#tracker","#hooks","#intervalMs","#maxBucketLevel","#sleep","#chain","#waitForToken","#lastCheck","#bucketLevel","#budgets","#config","#hooks","#httpClient","#queues","#sleep","#getQueue","#gatedSend"],"sources":["../src/internal/utils/is-date-time-string.ts","../src/internal/utils/is-record.ts","../src/internal/http/budget-tracker.ts","../src/internal/http/budget-gate.ts","../src/internal/http/execute.ts","../src/internal/http/rate-limit-sample.ts","../src/internal/http/rate-limit-observation.ts","../src/internal/http/rate-limit-queue.ts","../src/internal/utils/try-catch.ts","../src/internal/http/fetch-client.ts","../src/internal/http/resolve-dependencies.ts","../src/internal/http/upload-request.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\treturn !Number.isNaN(new Date(value).getTime());\n}\n","/**\n * Narrows `value` to a plain JSON-style record. Excludes arrays, class\n * instances, primitives, and `null`/`undefined`. Used by resource\n * parsers to gate property access on wire bodies whose shape isn't\n * known at compile time.\n *\n * @param value - The unknown value to narrow.\n * @returns `true` when `value` is a plain `[object Object]`.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn Object.prototype.toString.call(value) === \"[object Object]\";\n}\n","import type { RateLimitSample } from \"./rate-limit-sample.ts\";\n\nconst MS_PER_SECOND = 1000;\n\n/** Live window state for one scope: budget left and when it resets. */\ninterface WindowState {\n\t/** Best estimate of requests still allowed before the window resets. */\n\treadonly predictedRemaining: number;\n\t/** Absolute time (ms) the window resets to full. */\n\treadonly resetAt: number;\n}\n\n/**\n * Tracks the live rate-limit budget for a single scope. Primed by `observe`\n * from response headers and drawn down by `reserve` as requests leave, so\n * `waitMs` can pace requests across the window.\n *\n * Pacing has two regimes. While budget remains, requests are spread evenly over\n * the time left in the window (`timeLeft / remaining`), so a burst does not\n * spend the whole window's budget up front and then stall. Once the budget is\n * spent, requests hold until the window resets. Budget and reset time move\n * together as one window, so the tracker is either unprimed or fully primed,\n * never half-known.\n */\nexport class BudgetTracker {\n\t/** Time (ms) the most recent request was allowed out, for spacing. */\n\t#lastAllowedAt: number | undefined = undefined;\n\t#window: undefined | WindowState = undefined;\n\n\t/**\n\t * Folds a fresh server reading in, replacing any prior window. The latest\n\t * reading wins: observe time is monotonic, so the most recently resolved\n\t * response is the best current estimate. The spacing reference is left\n\t * untouched so a window refresh does not reset pacing mid-stream.\n\t *\n\t * @param sample - Parsed `remaining`/`resetSeconds` from a response.\n\t * @param now - The current time in ms.\n\t */\n\tpublic observe(sample: RateLimitSample, now: number): void {\n\t\tthis.#window = {\n\t\t\tpredictedRemaining: sample.remaining,\n\t\t\tresetAt: now + sample.resetSeconds * MS_PER_SECOND,\n\t\t};\n\t}\n\n\t/**\n\t * Accounts for one request leaving at `now`: records the spacing reference\n\t * and decrements the prediction. A no-op on the prediction while unprimed.\n\t *\n\t * @param now - The time the request was allowed out, in ms.\n\t */\n\tpublic reserve(now: number): void {\n\t\tthis.#lastAllowedAt = now;\n\t\tif (this.#window !== undefined) {\n\t\t\tthis.#window = {\n\t\t\t\t...this.#window,\n\t\t\t\tpredictedRemaining: this.#window.predictedRemaining - 1,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Milliseconds to wait before the next request is allowed.\n\t *\n\t * @param now - The current time in ms.\n\t * @returns `0` when a request may go now (unprimed, or the first paced send);\n\t * the time until reset when the budget is spent; otherwise the time until\n\t * this request's evenly-spaced slot.\n\t */\n\tpublic waitMs(now: number): number {\n\t\tif (this.#window === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst { predictedRemaining, resetAt } = this.#window;\n\t\tif (predictedRemaining <= 0) {\n\t\t\treturn Math.max(0, resetAt - now);\n\t\t}\n\n\t\tif (this.#lastAllowedAt === undefined) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst interval = (resetAt - now) / predictedRemaining;\n\t\treturn Math.max(0, this.#lastAllowedAt + interval - now);\n\t}\n}\n","import type { SleepFunc } from \"../utils/sleep.ts\";\nimport { BudgetTracker } from \"./budget-tracker.ts\";\nimport type { RateLimitSample } from \"./rate-limit-sample.ts\";\n\n/**\n * Header-primed rate-limit gate shared across a client. Holds one\n * {@link BudgetTracker} per API key, since the tightest Roblox window is the\n * per-key one shared across every operation. Before each request the caller\n * gates on the request's key (sleeping if its budget is spent), and after each\n * response folds the parsed sample back in, so a sibling operation on the same\n * key can head off a 429 the static per-operation token bucket cannot foresee.\n * A per-operation tracker is deliberately not kept: every operation reports the\n * same most-constrained `remaining`, so a per-key tracker (drawn down by all\n * operations) is always the binding constraint.\n *\n * Gating is serialized per scope through a promise chain so concurrent\n * requests on one key cannot read the same budget and reserve the same slot;\n * each waits for the prior gate's reserve before computing its own.\n */\nexport class BudgetGate {\n\treadonly #chains = new Map<string, Promise<void>>();\n\treadonly #sleep: SleepFunc;\n\treadonly #trackers = new Map<string, BudgetTracker>();\n\n\t/**\n\t * Creates a gate bound to an injectable sleep.\n\t *\n\t * @param sleep - Injectable sleep (tests pass a fake clock).\n\t */\n\tconstructor(sleep: SleepFunc) {\n\t\tthis.#sleep = sleep;\n\t}\n\n\t/**\n\t * Holds until the scope's budget permits a send, then reserves one slot.\n\t * Runs after the prior gate on the same scope settles, whether it resolved\n\t * or rejected, so one failed attempt cannot poison later gates on the key.\n\t *\n\t * @param scope - The scope key to gate on (the effective API key).\n\t */\n\tpublic async gate(scope: string): Promise<void> {\n\t\tconst previous = this.#chains.get(scope) ?? Promise.resolve();\n\t\tconst runGate = async (): Promise<void> => this.#gateOnce(scope);\n\t\tconst mine = previous.then(runGate, runGate);\n\t\tthis.#chains.set(scope, mine);\n\t\tawait mine;\n\t}\n\n\t/**\n\t * Folds a response's parsed budget back onto the scope. A `undefined`\n\t * sample (headers absent or non-numeric) is ignored, leaving the scope on\n\t * static pacing.\n\t *\n\t * @param scope - The same scope key passed to {@link gate}.\n\t * @param sample - Parsed sample, or `undefined` when none was reported.\n\t */\n\tpublic observe(scope: string, sample: RateLimitSample | undefined): void {\n\t\tif (sample === undefined) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#tracker(scope).observe(sample, Date.now());\n\t}\n\n\tasync #gateOnce(scope: string): Promise<void> {\n\t\tconst tracker = this.#tracker(scope);\n\t\tconst waitMs = tracker.waitMs(Date.now());\n\t\tif (waitMs > 0) {\n\t\t\tawait this.#sleep(waitMs);\n\t\t}\n\n\t\ttracker.reserve(Date.now());\n\t}\n\n\t#tracker(scope: string): BudgetTracker {\n\t\tconst existing = this.#trackers.get(scope);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst tracker = new BudgetTracker();\n\t\tthis.#trackers.set(scope, tracker);\n\t\treturn tracker;\n\t}\n}\n","import type { OpenCloudError } from \"../../errors/base.ts\";\nimport type { Result } from \"../../types.ts\";\nimport type { SleepFunc } from \"../utils/sleep.ts\";\nimport { computeRetryWaitMs, type RetryResolvable, shouldRetry } from \"./retry.ts\";\nimport type { HttpRequest, HttpResponse, OpenCloudHooks } from \"./types.ts\";\n\n/** A transport callback: takes a request, returns a classified Result. */\ntype SendFunc = (request: HttpRequest) => Promise<Result<HttpResponse, OpenCloudError>>;\n\n/**\n * Inputs to {@link executeWithRetry} bundled as an options object to keep the\n * function signature narrow.\n */\ninterface ExecuteOptions {\n\t/** Fully-resolved retry config (post-merge). */\n\treadonly config: RetryResolvable;\n\t/** Client-level observability hooks. */\n\treadonly hooks: OpenCloudHooks;\n\t/** Transport callback. May be pre-wrapped by a rate-limit queue. */\n\treadonly send: SendFunc;\n\t/** Injectable sleep (tests pass a fake). */\n\treadonly sleep: SleepFunc;\n}\n\n/**\n * Retry-aware orchestration loop. Coordinates a single logical request,\n * looping over `options.send` until it succeeds, the error is non-retryable,\n * or `options.config.maxRetries` is exhausted. Fires observability hooks\n * at each transition. Domain- and queue-agnostic: `send` may be any\n * callback, including one wrapped by a rate-limit queue.\n *\n * @param request - The immutable request to send.\n * @param options - The transport callback, resolved config, hooks, and sleep.\n * @returns The first success, or the final error after retries are exhausted.\n */\nexport async function executeWithRetry(\n\trequest: HttpRequest,\n\toptions: ExecuteOptions,\n): Promise<Result<HttpResponse, OpenCloudError>> {\n\tconst { config, hooks, send, sleep } = options;\n\n\tasync function attempt(): Promise<Result<HttpResponse, OpenCloudError>> {\n\t\thooks.onRequest?.(request);\n\t\treturn send(request);\n\t}\n\n\tlet result = await attempt();\n\n\tfor (let retry = 0; retry < config.maxRetries; retry++) {\n\t\tif (result.success || !shouldRetry(result.err, config)) {\n\t\t\treturn result;\n\t\t}\n\n\t\tconst { err } = result;\n\t\thooks.onRetry?.(retry + 1, err);\n\t\tconst waitMs = computeRetryWaitMs(err, { attempt: retry, retryDelay: config.retryDelay });\n\t\thooks.onRateLimit?.(waitMs);\n\t\tawait sleep(waitMs);\n\n\t\tresult = await attempt();\n\t}\n\n\treturn result;\n}\n","/**\n * A point-in-time rate-limit budget reading parsed from Roblox Open Cloud\n * response headers. Both fields are non-negative integers.\n */\nexport interface RateLimitSample {\n\t/** Requests still allowed in the current window (the most-constrained one). */\n\treadonly remaining: number;\n\t/** Seconds until the most-constrained window resets to full. */\n\treadonly resetSeconds: number;\n}\n\n/**\n * Reduces a comma-separated rate-limit header value (e.g. `\"0, 70000\"`) to a\n * single non-negative integer via `combine`. Tokens are trimmed; blank and\n * non-finite tokens (`\"\"`, `\"Infinity\"`, `\"abc\"`) are dropped so a stray value\n * cannot corrupt the result. Returns `undefined` when the header is absent or\n * has no finite tokens.\n *\n * @param headerValue - The raw header value, or `undefined` if missing.\n * @param combine - Pairwise reducer, `Math.min` for remaining, `Math.max` for reset.\n * @returns The reduced, floored, clamped value, or `undefined`.\n */\nexport function reduceRateLimitTokens(\n\theaderValue: string | undefined,\n\tcombine: (a: number, b: number) => number,\n): number | undefined {\n\tif (headerValue === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst tokens = headerValue\n\t\t.split(\",\")\n\t\t.map((part) => part.trim())\n\t\t.filter((part) => part !== \"\")\n\t\t.map((part) => Number(part))\n\t\t.filter((value) => Number.isFinite(value));\n\tif (tokens.length === 0) {\n\t\treturn undefined;\n\t}\n\n\treturn Math.max(0, Math.floor(tokens.reduce(combine)));\n}\n\n/**\n * Parses the `x-ratelimit-remaining` and `x-ratelimit-reset` response headers\n * into a {@link RateLimitSample}. Each header may carry a comma-separated list\n * of per-window values; `remaining` takes the smallest (most constrained) and\n * `resetSeconds` takes the largest (longest wait), symmetric to how a 429's\n * retry delay is reduced. Returns `undefined` when either header is missing or\n * has no finite numeric tokens, so a caller can fall back to static pacing.\n *\n * @param headers - Response headers with lowercased keys.\n * @returns The parsed sample, or `undefined` when the budget cannot be read.\n */\nexport function parseRateLimitHeaders(\n\theaders: Readonly<Record<string, string>>,\n): RateLimitSample | undefined {\n\tconst remaining = reduceRateLimitTokens(headers[\"x-ratelimit-remaining\"], (a, b) =>\n\t\tMath.min(a, b),\n\t);\n\tconst resetSeconds = reduceRateLimitTokens(headers[\"x-ratelimit-reset\"], (a, b) =>\n\t\tMath.max(a, b),\n\t);\n\tif (remaining === undefined || resetSeconds === undefined) {\n\t\treturn undefined;\n\t}\n\n\treturn { remaining, resetSeconds };\n}\n","import type { OpenCloudError } from \"../../errors/base.ts\";\nimport { RateLimitError } from \"../../errors/rate-limit.ts\";\nimport type { Result } from \"../../types.ts\";\nimport type { RateLimitSample } from \"./rate-limit-sample.ts\";\nimport { parseRateLimitHeaders } from \"./rate-limit-sample.ts\";\nimport type { HttpResponse } from \"./types.ts\";\n\n/**\n * Extracts a {@link RateLimitSample} from a transport result so the budget gate\n * can be fed from every attempt. A 2xx carries the budget in its headers; a 429\n * carries it on the {@link RateLimitError} (the raw headers are dropped before\n * this point). Any other error, or a response that reported no budget, yields\n * `undefined` and leaves the gate on static pacing.\n *\n * @param result - The classified transport result for one attempt.\n * @returns The parsed sample, or `undefined` when none was reported.\n */\nexport function rateLimitSampleFromResult(\n\tresult: Result<HttpResponse, OpenCloudError>,\n): RateLimitSample | undefined {\n\tif (result.success) {\n\t\treturn parseRateLimitHeaders(result.data.headers);\n\t}\n\n\tconst { err } = result;\n\tif (err instanceof RateLimitError && err.remaining !== undefined) {\n\t\treturn { remaining: err.remaining, resetSeconds: err.retryAfterSeconds };\n\t}\n\n\treturn undefined;\n}\n","import type { SleepFunc } from \"../utils/sleep.ts\";\nimport type { OpenCloudHooks } from \"./types.ts\";\n\n/**\n * Identifies and bounds a single Roblox Open Cloud operation for rate\n * limiting, e.g. `{ operationKey: \"game-passes.create\", maxPerSecond: 5 }`.\n */\nexport interface OperationLimit {\n\t/** Maximum sustained request rate in requests per second. */\n\treadonly maxPerSecond: number;\n\t/**\n\t * Stable identifier for the operation (e.g. \"game-passes.create\"). Not\n\t * consumed by the queue itself; callers use it to key per-operation\n\t * queues in a registry (see GamePassesClient).\n\t */\n\treadonly operationKey: string;\n}\n\n/**\n * Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every\n * call to `acquire` consumes one token; when the bucket is empty the call\n * waits until a token regenerates before invoking the task. Burst capacity\n * equals `maxPerSecond`, refilling at `maxPerSecond` tokens per second.\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.\n */\nexport class RateLimitQueue {\n\treadonly #hooks: OpenCloudHooks;\n\treadonly #intervalMs: number;\n\treadonly #maxBucketLevel: number;\n\treadonly #sleep: SleepFunc;\n\n\t#bucketLevel = 0;\n\t#chain: Promise<void> = Promise.resolve();\n\t#lastCheck: number = Date.now();\n\n\t/**\n\t * Creates a rate-limit queue bound to a single operation.\n\t *\n\t * @param limit - The operation key and its per-second request ceiling.\n\t * @param hooks - Observability callbacks; `onRateLimit` fires when the\n\t * bucket is empty and a sleep is about to start.\n\t * @param sleep - Injectable sleep (tests pass a fake).\n\t */\n\tconstructor(limit: OperationLimit, hooks: OpenCloudHooks, sleep: SleepFunc) {\n\t\tthis.#intervalMs = 1000 / limit.maxPerSecond;\n\t\tthis.#maxBucketLevel = limit.maxPerSecond * this.#intervalMs;\n\t\tthis.#hooks = hooks;\n\t\tthis.#sleep = sleep;\n\t}\n\n\t/**\n\t * Waits for a token — sleeping and firing `hooks.onRateLimit` if the\n\t * bucket is empty — then executes `task`. Concurrent callers are\n\t * serialized at token acquisition; tasks themselves run independently\n\t * once their token is secured.\n\t *\n\t * @param task - The request to run once a token is available.\n\t * @returns The value produced by `task`.\n\t */\n\tpublic async acquire<T>(task: () => Promise<T>): Promise<T> {\n\t\tconst myTurn = this.#chain.then(async () => this.#waitForToken());\n\t\tthis.#chain = myTurn;\n\t\tawait myTurn;\n\t\treturn task();\n\t}\n\n\tasync #waitForToken(): Promise<void> {\n\t\tconst now = Math.max(Date.now(), this.#lastCheck);\n\t\tconst drained = Math.max(0, this.#bucketLevel - (now - this.#lastCheck));\n\t\tthis.#lastCheck = now;\n\n\t\tif (drained + this.#intervalMs <= this.#maxBucketLevel) {\n\t\t\tthis.#bucketLevel = drained + this.#intervalMs;\n\t\t\treturn;\n\t\t}\n\n\t\tconst waitMs = drained + this.#intervalMs - this.#maxBucketLevel;\n\t\tthis.#hooks.onRateLimit?.(waitMs);\n\t\tawait this.#sleep(waitMs);\n\t\tthis.#bucketLevel = this.#maxBucketLevel;\n\t\tthis.#lastCheck = now + waitMs;\n\t}\n}\n","import type { Result } from \"../../types.ts\";\n\n/**\n * Wraps a promise into a {@link Result}, catching rejections.\n *\n * @template T - The resolved value type.\n * @param promise - The promise to wrap.\n * @returns A Result containing the resolved value or the rejection error.\n */\nexport async function tryCatch<T>(promise: Promise<T>): Promise<Result<T>> {\n\ttry {\n\t\tconst data = await promise;\n\t\treturn { data, success: true };\n\t} catch (err) {\n\t\treturn { err: err instanceof Error ? err : new Error(String(err)), success: false };\n\t}\n}\n","import { ApiError } from \"../../errors/api-error.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { NetworkError } from \"../../errors/network-error.ts\";\nimport { RateLimitError } from \"../../errors/rate-limit.ts\";\nimport type { Result } from \"../../types.ts\";\nimport { tryCatch } from \"../utils/try-catch.ts\";\nimport { reduceRateLimitTokens } from \"./rate-limit-sample.ts\";\nimport type { HttpClient, HttpRequest, HttpResponse, RequestConfig } from \"./types.ts\";\n\n// Caps the raw body retained when a response cannot be parsed, so a multi-KB\n// HTML error page is not surfaced or logged whole.\nconst MAX_DETAIL_LENGTH = 500;\n\nconst CONTENT_TYPE_HEADER = \"content-type\";\n\ninterface ParseFailureArgs {\n\treadonly cause: Error;\n\treadonly response: Response;\n\treadonly text: string;\n}\n\ninterface ApiErrorMessageParts {\n\treadonly code: string | undefined;\n\treadonly message: string | undefined;\n\treadonly status: number;\n}\n\n/**\n * Converts a `Headers` object to a plain record with lowercased keys.\n *\n * @param headers - The `Headers` instance to convert.\n * @returns A record mapping lowercased header names to their values.\n */\nexport function headersToRecord(headers: Headers): Record<string, string> {\n\treturn Object.fromEntries(headers);\n}\n\n/**\n * Permissively extracts a machine-readable error code from a response body.\n *\n * Modern Open Cloud responses use `{ errorCode: string, message: string }`;\n * the legacy game-internationalization endpoints use\n * `{ errors: [{ code: number, message: string }, ...] }`. Both shapes are\n * checked; numeric legacy codes are returned as strings so callers see one\n * consistent type.\n *\n * @param body - The parsed response body (unknown shape).\n * @returns The error code if present, otherwise `undefined`.\n */\nexport function extractErrorCode(body: unknown): string | undefined {\n\tif (body === null || typeof body !== \"object\") {\n\t\treturn undefined;\n\t}\n\n\tconst errorCode = Reflect.get(body, \"errorCode\");\n\tif (typeof errorCode === \"string\") {\n\t\treturn errorCode;\n\t}\n\n\treturn extractLegacyCode(body);\n}\n\n/**\n * Permissively extracts a human-readable error message from a response body.\n *\n * Modern Open Cloud responses expose `message` at the top level; the legacy\n * game-internationalization endpoints nest it under `errors[0].message`.\n *\n * @param body - The parsed response body (unknown shape).\n * @returns The message if present, otherwise `undefined`.\n */\nexport function extractErrorMessage(body: unknown): string | undefined {\n\tif (body === null || typeof body !== \"object\") {\n\t\treturn undefined;\n\t}\n\n\tconst message = Reflect.get(body, \"message\");\n\tif (typeof message === \"string\") {\n\t\treturn message;\n\t}\n\n\treturn extractLegacyMessage(body);\n}\n\n/**\n * Parses the `x-ratelimit-reset` header value into seconds. On a 429 the header\n * is a comma-separated list of per-window reset times (e.g. `\"22, 0\"`, one entry\n * per rate-limit window); the largest value is the longest-resetting window and\n * the only safe wait that won't retry into a still-exhausted window. A single\n * value is treated as a one-element list.\n *\n * @param headerValue - The raw header value, or `undefined` if missing.\n * @returns The number of seconds to wait, or 0 if missing/invalid.\n */\nexport function parseRetryAfterSeconds(headerValue: string | undefined): number {\n\treturn reduceRateLimitTokens(headerValue, (a, b) => Math.max(a, b)) ?? 0;\n}\n\n/**\n * Joins the base URL from config with the relative path from the request.\n *\n * @param request - The HTTP request containing the relative URL.\n * @param config - The request config containing the base URL.\n * @returns The fully-qualified URL string.\n */\nexport function buildUrl(request: HttpRequest, config: RequestConfig): string {\n\tconst base = config.baseUrl.endsWith(\"/\") ? config.baseUrl.slice(0, -1) : config.baseUrl;\n\treturn `${base}${request.url}`;\n}\n\n/**\n * Constructs the `RequestInit` options for a `fetch` call.\n *\n * @param request - The HTTP request to build options for.\n * @param config - The request config containing API key and timeout.\n * @returns A `RequestInit` object ready for `fetch`.\n */\nexport function buildFetchOptions(request: HttpRequest, config: RequestConfig): RequestInit {\n\tconst headers = new Headers({\n\t\t\"x-api-key\": config.apiKey,\n\t});\n\n\tconst options: RequestInit = {\n\t\theaders,\n\t\tmethod: request.method,\n\t};\n\n\tif (request.body instanceof FormData) {\n\t\toptions.body = request.body;\n\t} else if (request.body instanceof Uint8Array) {\n\t\theaders.set(CONTENT_TYPE_HEADER, \"application/octet-stream\");\n\t\toptions.body = request.body;\n\t} else if (request.body !== undefined) {\n\t\theaders.set(CONTENT_TYPE_HEADER, \"application/json\");\n\t\toptions.body = JSON.stringify(request.body);\n\t}\n\n\tif (request.headers !== undefined) {\n\t\tfor (const [name, value] of Object.entries(request.headers)) {\n\t\t\tif (name.toLowerCase() === \"x-api-key\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\theaders.set(name, value);\n\t\t}\n\t}\n\n\tif (config.timeout !== undefined) {\n\t\toptions.signal = AbortSignal.timeout(config.timeout);\n\t}\n\n\treturn options;\n}\n\n/**\n * Creates an {@link HttpClient} backed by the Fetch API.\n *\n * @param fetchFunc - The fetch implementation to use. Defaults to `globalThis.fetch`.\n * @returns An HttpClient that classifies responses into typed Results.\n */\nexport function createFetchHttpClient(\n\tfetchFunc: (url: string, init: RequestInit) => Promise<Response> = globalThis.fetch,\n): HttpClient {\n\treturn {\n\t\tasync request(\n\t\t\thttpRequest: HttpRequest,\n\t\t\tconfig: RequestConfig,\n\t\t): Promise<Result<HttpResponse, OpenCloudError>> {\n\t\t\tconst url = buildUrl(httpRequest, config);\n\t\t\tconst options = buildFetchOptions(httpRequest, config);\n\n\t\t\tconst fetchResult = await tryCatch(fetchFunc(url, options));\n\t\t\tif (!fetchResult.success) {\n\t\t\t\treturn {\n\t\t\t\t\terr: new NetworkError(\"Network request failed\", {\n\t\t\t\t\t\tcause: fetchResult.err,\n\t\t\t\t\t\tmethod: httpRequest.method,\n\t\t\t\t\t\turl,\n\t\t\t\t\t}),\n\t\t\t\t\tsuccess: false,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn classifyResponse(fetchResult.data);\n\t\t},\n\t};\n}\n\nfunction readLegacyErrorEntry(body: object): object | undefined {\n\tconst errors = Reflect.get(body, \"errors\");\n\tif (!Array.isArray(errors)) {\n\t\treturn undefined;\n\t}\n\n\tconst [first] = errors;\n\tif (typeof first !== \"object\" || first === null) {\n\t\treturn undefined;\n\t}\n\n\treturn first;\n}\n\nfunction extractLegacyCode(body: object): string | undefined {\n\tconst first = readLegacyErrorEntry(body);\n\tif (first === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst code = Reflect.get(first, \"code\");\n\tif (typeof code === \"string\") {\n\t\treturn code;\n\t}\n\n\treturn typeof code === \"number\" ? String(code) : undefined;\n}\n\nfunction extractLegacyMessage(body: object): string | undefined {\n\tconst first = readLegacyErrorEntry(body);\n\tif (first === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst message = Reflect.get(first, \"message\");\n\treturn typeof message === \"string\" ? message : undefined;\n}\n\nfunction formatApiErrorMessage(parts: ApiErrorMessageParts): string {\n\tconst { code, message, status } = parts;\n\tconst base = `HTTP ${status}`;\n\tif (message === undefined && code === undefined) {\n\t\treturn base;\n\t}\n\n\tif (message === undefined) {\n\t\treturn `${base} (code ${code})`;\n\t}\n\n\tif (code === undefined) {\n\t\treturn `${base}: ${message}`;\n\t}\n\n\treturn `${base}: ${message} (code ${code})`;\n}\n\nfunction createApiError(status: number, body: JSONValue | undefined): ApiError {\n\tconst code = extractErrorCode(body);\n\tconst message = extractErrorMessage(body);\n\treturn new ApiError(formatApiErrorMessage({ code, message, status }), {\n\t\tcode,\n\t\tdetails: body,\n\t\tstatusCode: status,\n\t});\n}\n\nfunction createRateLimitError(response: Response): RateLimitError {\n\tconst headers = headersToRecord(response.headers);\n\treturn new RateLimitError(\"Rate limited\", {\n\t\tremaining: reduceRateLimitTokens(headers[\"x-ratelimit-remaining\"], (a, b) =>\n\t\t\tMath.min(a, b),\n\t\t),\n\t\tretryAfterSeconds: parseRetryAfterSeconds(headers[\"x-ratelimit-reset\"]),\n\t});\n}\n\n/**\n * Parses response text as JSON, returning the underlying `SyntaxError` on\n * failure rather than throwing. The synchronous sibling of {@link tryCatch}.\n *\n * @param text - The raw response body text.\n * @returns A Result wrapping the parsed value, or the parse error.\n */\nfunction parseJson(text: string): Result<JSONValue> {\n\ttry {\n\t\treturn { data: JSON.parse(text), success: true };\n\t} catch (err) {\n\t\treturn { err: err instanceof Error ? err : new Error(String(err)), success: false };\n\t}\n}\n\n/**\n * Builds the error for a 2xx response whose body could not be parsed as JSON,\n * preserving the parse `cause`, the (truncated) raw body, and the declared\n * content-type so the failure can be diagnosed after the fact.\n *\n * @param args - The Response, raw body text, and underlying parse error.\n * @returns An ApiError carrying the diagnostic context.\n */\nfunction parseFailureError({ cause, response, text }: ParseFailureArgs): ApiError {\n\tconst contentType = response.headers.get(CONTENT_TYPE_HEADER) ?? \"unknown\";\n\treturn new ApiError(`Failed to parse response body (content-type: ${contentType})`, {\n\t\tcause,\n\t\tdetails: text.slice(0, MAX_DETAIL_LENGTH),\n\t\tstatusCode: response.status,\n\t});\n}\n\n/**\n * Classifies a fetch `Response` into a typed `Result`.\n *\n * The body is read once and parsed best-effort. Error responses (status >= 300)\n * never require valid JSON: an error body that is not valid JSON (for example\n * an HTML gateway page) degrades to a status-based {@link ApiError} carrying\n * the raw text. A parse failure is only fatal on a 2xx, where a parseable body is part\n * of the contract.\n *\n * @param response - The raw fetch Response to classify.\n * @returns A Result containing an HttpResponse on success or an OpenCloudError on failure.\n */\nasync function classifyResponse(response: Response): Promise<Result<HttpResponse, OpenCloudError>> {\n\tif (response.status === 429) {\n\t\treturn { err: createRateLimitError(response), success: false };\n\t}\n\n\tconst text = await response.text();\n\tconst parsed: Result<JSONValue | undefined> =\n\t\ttext === \"\" ? { data: undefined, success: true } : parseJson(text);\n\n\tif (response.status >= 300) {\n\t\tconst body = parsed.success ? parsed.data : text.slice(0, MAX_DETAIL_LENGTH);\n\t\treturn { err: createApiError(response.status, body), success: false };\n\t}\n\n\tif (!parsed.success) {\n\t\treturn { err: parseFailureError({ cause: parsed.err, response, text }), success: false };\n\t}\n\n\treturn {\n\t\tdata: {\n\t\t\tbody: parsed.data,\n\t\t\theaders: headersToRecord(response.headers),\n\t\t\tstatus: response.status,\n\t\t},\n\t\tsuccess: true,\n\t};\n}\n","import { setTimeout } from \"node:timers/promises\";\n\nimport type { HttpClient, SleepFunc } from \"../../client/types.ts\";\nimport { createFetchHttpClient } from \"./fetch-client.ts\";\n\n/**\n * Options accepted by {@link resolveDependencies}. Mirrors the test-seam\n * subset of the public client options.\n */\ninterface ResolveDependenciesOptions {\n\t/** Test seam: custom {@link HttpClient}. Defaults to a fetch-backed client. */\n\treadonly httpClient?: HttpClient | undefined;\n\t/** Test seam: custom {@link SleepFunc}. Defaults to a `setTimeout`-backed sleep. */\n\treadonly sleep?: SleepFunc | undefined;\n}\n\n/**\n * Fully-populated dependency set consumed by resource client constructors.\n */\ninterface ResolvedDependencies {\n\t/** Concrete {@link HttpClient} implementation. */\n\treadonly httpClient: HttpClient;\n\t/** Concrete {@link SleepFunc} implementation. */\n\treadonly sleep: SleepFunc;\n}\n\n/**\n * Resolves the concrete HTTP client and sleep implementation a resource\n * client should use. Falls back to the fetch-backed HTTP client and the\n * default `setTimeout`-based sleep when the caller omits the test seams.\n *\n * Extracted so resource client constructors can keep their dependency\n * resolution logic in a single, unit-testable place; this makes the\n * default branches easy to cover without stubbing globals like `fetch`.\n *\n * @param options - Optional {@link HttpClient} and {@link SleepFunc} test seams.\n * @returns A {@link ResolvedDependencies} with defaults applied.\n */\nexport function resolveDependencies(options: ResolveDependenciesOptions): ResolvedDependencies {\n\treturn {\n\t\thttpClient: options.httpClient ?? createFetchHttpClient(),\n\t\tsleep: options.sleep ?? setTimeout,\n\t};\n}\n","import type { HttpRequest } from \"../../client/types.ts\";\n\n/**\n * Reports whether a request is an upload: its body is `FormData`\n * (multipart) or `Uint8Array` (raw binary). Upload latency is\n * bandwidth-bound rather than compute-bound, so the SDK applies no default\n * request timeout to these requests; a sensible wall-clock budget depends on\n * payload size and link quality the SDK cannot know.\n *\n * @param request - The built request to classify.\n * @returns `true` when the body is `FormData` or `Uint8Array`.\n */\nexport function isUploadRequest(request: HttpRequest): boolean {\n\treturn request.body instanceof FormData || request.body instanceof Uint8Array;\n}\n","import type { Except } from \"type-fest\";\n\nimport type {\n\tHttpClient,\n\tHttpRequest,\n\tHttpResponse,\n\tOpenCloudClientOptions,\n\tOpenCloudHooks,\n\tRequestConfig,\n\tRequestOptions,\n\tSleepFunc,\n} from \"../client/types.ts\";\nimport { ApiError } from \"../errors/api-error.ts\";\nimport type { OpenCloudError } from \"../errors/base.ts\";\nimport { PermissionError } from \"../errors/permission-error.ts\";\nimport type { Result } from \"../types.ts\";\nimport { BudgetGate } from \"./http/budget-gate.ts\";\nimport { executeWithRetry } from \"./http/execute.ts\";\nimport { rateLimitSampleFromResult } from \"./http/rate-limit-observation.ts\";\nimport { type OperationLimit, RateLimitQueue } from \"./http/rate-limit-queue.ts\";\nimport { resolveDependencies } from \"./http/resolve-dependencies.ts\";\nimport {\n\tdefaultRetryDelay,\n\tIDEMPOTENT_METHOD_DEFAULTS,\n\tmergeConfig,\n\ttype MethodKind,\n\ttype RetryResolvable,\n} from \"./http/retry.ts\";\nimport { isUploadRequest } from \"./http/upload-request.ts\";\n\n/**\n * Describes a single resource method's shape for dispatch through\n * `ResourceClient.execute`. Each resource client declares one module-level\n * constant per public method; that constant binds the four resource-specific\n * values (request builder, response parser, retry-policy method kind,\n * operation-level rate limit) and flows through `execute` uniformly.\n *\n * @template P - The resource-specific parameter shape the builder\n * accepts.\n * @template T - The resource-specific parsed success type the parser\n * produces.\n */\nexport interface ResourceMethodSpec<P, T> {\n\t/**\n\t * Builds the pure {@link HttpRequest} for a single call. Returns a\n\t * {@link Result} so a builder can short-circuit with a local error\n\t * (typically a {@link OpenCloudError} subclass such as `ValidationError`)\n\t * before any HTTP, queue, or retry work happens. Builders that cannot\n\t * fail wrap their return as `{ data: request, success: true }`.\n\t */\n\treadonly buildRequest: (parameters: P) => Result<HttpRequest, OpenCloudError>;\n\t/** Method-level retry defaults merged into the resolved config. */\n\treadonly methodDefaults: Partial<RetryResolvable>;\n\t/**\n\t * Method kind, controlling merge precedence: `\"create\"` lets method\n\t * defaults win over client config so create safety cannot be relaxed\n\t * silently; `\"idempotent\"` lets client config win over method defaults\n\t * so consumers can loosen retry globally.\n\t */\n\treadonly methodKind: MethodKind;\n\t/** Operation-level rate limit, keyed into the client's per-key queue map. */\n\treadonly operationLimit: OperationLimit;\n\t/**\n\t * Converts the full {@link HttpResponse} into the resource-specific\n\t * parsed shape. Takes the whole response (body, status, headers) so\n\t * future parsers can read headers without widening the signature.\n\t */\n\treadonly parse: (response: HttpResponse) => Result<T, OpenCloudError>;\n\t/**\n\t * Open Cloud scopes the API key or OAuth token must carry for this\n\t * method, sourced from the vendored OpenAPI schema's `x-roblox-scopes`.\n\t * When set, a 401 or 403 ApiError from the upstream call is upgraded to\n\t * a {@link PermissionError} carrying these scopes alongside\n\t * {@link OperationLimit.operationKey}, so callers can name the missing\n\t * scope instead of just the HTTP status. Optional so test specs and\n\t * not-yet-wired resources can opt out.\n\t */\n\treadonly requiredScopes?: ReadonlyArray<string>;\n}\n\n/**\n * Single-argument bundle consumed by `ResourceClient.execute`: the per-method\n * spec, the resource-specific parameters, and optional per-request config\n * overrides.\n *\n * @template P - The resource-specific parameter shape the builder accepts.\n * @template T - The resource-specific parsed success type the parser produces.\n */\ninterface ExecuteCall<P, T> {\n\t/** Optional per-request config overrides. */\n\treadonly options?: RequestOptions | undefined;\n\t/** Resource-specific request parameters. */\n\treadonly parameters: P;\n\t/** Per-method binding of builder, parser, method kind, and operation limit. */\n\treadonly spec: ResourceMethodSpec<P, T>;\n}\n\n/**\n * Wraps an infallible request build as a {@link Result}-returning\n * `buildRequest` callback compatible with {@link ResourceMethodSpec}.\n * Use from a resource client whose builder cannot fail; resource clients\n * with local validation should construct the {@link Result} directly.\n *\n * @param request - The pre-built {@link HttpRequest}.\n * @returns A success Result wrapping the request.\n */\nexport function okRequest(request: HttpRequest): Result<HttpRequest, OpenCloudError> {\n\treturn { data: request, success: true };\n}\n\n/**\n * A {@link ResourceMethodSpec.parse} implementation for endpoints that return\n * no business payload on success (such as `DELETE` and reorder operations).\n * Surfaces `undefined` data and never inspects the response body.\n *\n * @returns A success Result with `undefined` data.\n */\nexport function parseEmptyResponse(): Result<undefined, OpenCloudError> {\n\treturn { data: undefined, success: true };\n}\n\nconst CLIENT_DEFAULTS = Object.freeze({\n\tbaseUrl: \"https://apis.roblox.com\",\n\tmaxRetries: 3,\n\tretryableStatuses: IDEMPOTENT_METHOD_DEFAULTS.retryableStatuses,\n\tretryableTransportCodes: IDEMPOTENT_METHOD_DEFAULTS.retryableTransportCodes,\n\tretryDelay: defaultRetryDelay,\n\ttimeout: 30_000,\n} satisfies Except<RetryResolvable, \"apiKey\">);\n\n/**\n * Inputs to {@link buildRequestConfig}, bundled to keep the signature narrow.\n */\ninterface RequestConfigInputs {\n\t/** The resolved config for this call. */\n\treadonly merged: RetryResolvable;\n\t/** The caller's per-request overrides, if any. */\n\treadonly options: RequestOptions | undefined;\n\t/** The built request, inspected for an upload body. */\n\treadonly request: HttpRequest;\n}\n\n/**\n * Internal orchestrator shared by every Open Cloud resource client. Holds\n * the frozen client config, observability hooks, injected HTTP client and\n * sleep, and the per-effective-key rate-limit queue registry. Resource\n * classes compose one instance and dispatch every public method through\n * {@link ResourceClient.execute} with a per-method {@link ResourceMethodSpec}.\n * Not exported from any package subpath; reachable only via sibling\n * `src/resources/**` modules in this package.\n */\nexport class ResourceClient {\n\treadonly #budgets: BudgetGate;\n\treadonly #config: Readonly<RetryResolvable>;\n\treadonly #hooks: OpenCloudHooks;\n\treadonly #httpClient: HttpClient;\n\treadonly #queues = new Map<string, RateLimitQueue>();\n\treadonly #sleep: SleepFunc;\n\n\t/**\n\t * Creates a new {@link ResourceClient}. Resolves the injected HTTP\n\t * client and sleep (defaulting to fetch + `setTimeout`) and freezes the\n\t * merged client config so subsequent calls cannot mutate it.\n\t *\n\t * @param options - Client-level configuration including the API key\n\t * and optional construction-time test seams.\n\t */\n\tconstructor(options: OpenCloudClientOptions) {\n\t\tconst { apiKey, hooks, httpClient, sleep, ...overrides } = options;\n\t\tconst resolved = resolveDependencies({ httpClient, sleep });\n\t\tthis.#httpClient = resolved.httpClient;\n\t\tthis.#sleep = resolved.sleep;\n\t\tthis.#budgets = new BudgetGate(this.#sleep);\n\t\tthis.#hooks = hooks ?? {};\n\t\tthis.#config = Object.freeze({\n\t\t\t...CLIENT_DEFAULTS,\n\t\t\tapiKey,\n\t\t\t...overrides,\n\t\t});\n\t}\n\n\t/**\n\t * Dispatches a single resource-method call. Merges the frozen client\n\t * config with the method's `methodDefaults` and the caller's optional\n\t * per-request `options`, routes through the effective-apiKey rate-limit\n\t * queue, runs the retry loop, and finally parses the response with the\n\t * spec's parser.\n\t *\n\t * @param call - The per-method spec, resource-specific parameters, and\n\t * optional per-request overrides.\n\t * @returns The parsed success payload or the {@link OpenCloudError} that\n\t * caused the request to fail. Never throws.\n\t */\n\tpublic async execute<P, T>(call: ExecuteCall<P, T>): Promise<Result<T, OpenCloudError>> {\n\t\tconst { options, parameters, spec } = call;\n\t\tconst merged = mergeConfig(this.#config, {\n\t\t\tmethodDefaults: spec.methodDefaults,\n\t\t\tmethodKind: spec.methodKind,\n\t\t\trequestOptions: options ?? {},\n\t\t});\n\t\tconst requestResult = spec.buildRequest(parameters);\n\t\tif (!requestResult.success) {\n\t\t\treturn requestResult;\n\t\t}\n\n\t\tconst requestConfig = buildRequestConfig({ merged, options, request: requestResult.data });\n\t\tconst queue = this.#getQueue(merged.apiKey, spec.operationLimit);\n\t\tconst httpResult = await queue.acquire(async () => {\n\t\t\treturn executeWithRetry(requestResult.data, {\n\t\t\t\tconfig: merged,\n\t\t\t\thooks: this.#hooks,\n\t\t\t\tsend: this.#gatedSend(merged.apiKey, requestConfig),\n\t\t\t\tsleep: this.#sleep,\n\t\t\t});\n\t\t});\n\t\tif (!httpResult.success) {\n\t\t\treturn { err: enrichPermissionError(httpResult.err, spec), success: false };\n\t\t}\n\n\t\treturn spec.parse(httpResult.data);\n\t}\n\n\t/**\n\t * Returns the sleep function used by this client instance.\n\t *\n\t * @returns The sleep function injected at construction time.\n\t */\n\tpublic get sleep(): SleepFunc {\n\t\treturn this.#sleep;\n\t}\n\n\t/**\n\t * Builds the transport callback for one logical call, wrapping the HTTP\n\t * client with the budget gate: each attempt waits on the API key's budget\n\t * before sending, then folds the response's reported budget back in so the\n\t * next attempt (or a sibling operation on the same key) can head off a 429.\n\t *\n\t * @param apiKey - The effective API key to gate on.\n\t * @param requestConfig - The resolved per-request transport config.\n\t * @returns A send callback for {@link executeWithRetry}.\n\t */\n\t#gatedSend(\n\t\tapiKey: string,\n\t\trequestConfig: RequestConfig,\n\t): (request: HttpRequest) => Promise<Result<HttpResponse, OpenCloudError>> {\n\t\treturn async (toSend) => {\n\t\t\tawait this.#budgets.gate(apiKey);\n\t\t\tconst sendResult = await this.#httpClient.request(toSend, requestConfig);\n\t\t\tthis.#budgets.observe(apiKey, rateLimitSampleFromResult(sendResult));\n\t\t\treturn sendResult;\n\t\t};\n\t}\n\n\t#getQueue(apiKey: string, limit: OperationLimit): RateLimitQueue {\n\t\tconst key = `${apiKey}::${limit.operationKey}`;\n\t\tconst existing = this.#queues.get(key);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);\n\t\tthis.#queues.set(key, queue);\n\t\treturn queue;\n\t}\n}\n\n/**\n * Resolves the per-request {@link RequestConfig}. Upload requests\n * ({@link isUploadRequest}) carry no default timeout: a multi-megabyte place\n * file over a slow link is bandwidth-bound, so a client-side deadline only\n * fires spuriously. An explicit `options.timeout` still applies to any\n * request; every non-upload request keeps the merged default.\n *\n * @param inputs - The merged config, the built request, and per-request overrides.\n * @returns The config to hand to the transport, with `timeout` omitted when\n * no client-side deadline should apply.\n */\nfunction buildRequestConfig(inputs: RequestConfigInputs): RequestConfig {\n\tconst { merged, options, request } = inputs;\n\tconst shouldOmitDefaultTimeout = options?.timeout === undefined && isUploadRequest(request);\n\treturn {\n\t\tapiKey: merged.apiKey,\n\t\tbaseUrl: merged.baseUrl,\n\t\t...(shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }),\n\t};\n}\n\nfunction enrichPermissionError<P, T>(\n\terr: OpenCloudError,\n\tspec: ResourceMethodSpec<P, T>,\n): OpenCloudError {\n\tif (spec.requiredScopes === undefined) {\n\t\treturn err;\n\t}\n\n\tif (err instanceof PermissionError) {\n\t\treturn err;\n\t}\n\n\tif (!(err instanceof ApiError)) {\n\t\treturn err;\n\t}\n\n\tif (err.statusCode !== 401 && err.statusCode !== 403) {\n\t\treturn err;\n\t}\n\n\treturn new PermissionError(err.message, {\n\t\tcause: err.cause,\n\t\tcode: err.code,\n\t\toperationKey: spec.operationLimit.operationKey,\n\t\trequiredScopes: spec.requiredScopes,\n\t\tstatusCode: err.statusCode,\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,iBAAiB,OAAiC;CACjE,IAAI,OAAO,UAAU,UACpB,OAAO;CAGR,OAAO,CAAC,OAAO,MAAM,IAAI,KAAK,KAAK,CAAC,CAAC,QAAQ,CAAC;AAC/C;;;;;;;;;;;;ACPA,SAAgB,SAAS,OAAkD;CAC1E,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AAClD;;;ACTA,MAAM,gBAAgB;;;;;;;;;;;;;AAsBtB,IAAa,gBAAb,MAA2B;;CAE1B,iBAAqC,KAAA;CACrC,UAAmC,KAAA;;;;;;;;;;CAWnC,QAAe,QAAyB,KAAmB;EAC1D,KAAKA,UAAU;GACd,oBAAoB,OAAO;GAC3B,SAAS,MAAM,OAAO,eAAe;EACtC;CACD;;;;;;;CAQA,QAAe,KAAmB;EACjC,KAAKC,iBAAiB;EACtB,IAAI,KAAKD,YAAY,KAAA,GACpB,KAAKA,UAAU;GACd,GAAG,KAAKA;GACR,oBAAoB,KAAKA,QAAQ,qBAAqB;EACvD;CAEF;;;;;;;;;CAUA,OAAc,KAAqB;EAClC,IAAI,KAAKA,YAAY,KAAA,GACp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A,WACC,QACA,eAC0E;EAC1E,OAAO,OAAO,WAAW;GACxB,MAAM,KAAKL,SAAS,KAAK,MAAM;GAC/B,MAAM,aAAa,MAAM,KAAKG,YAAY,QAAQ,QAAQ,aAAa;GACvE,KAAKH,SAAS,QAAQ,QAAQ,0BAA0B,UAAU,CAAC;GACnE,OAAO;EACR;CACD;CAEA,UAAU,QAAgB,OAAuC;EAChE,MAAM,MAAM,GAAG,OAAO,IAAI,MAAM;EAChC,MAAM,WAAW,KAAKI,QAAQ,IAAI,GAAG;EACrC,IAAI,aAAa,KAAA,GAChB,OAAO;EAGR,MAAM,QAAQ,IAAI,eAAe,OAAO,KAAKF,QAAQ,KAAKG,MAAM;EAChE,KAAKD,QAAQ,IAAI,KAAK,KAAK;EAC3B,OAAO;CACR;AACD;;;;;;;;;;;;AAaA,SAAS,mBAAmB,QAA4C;CACvE,MAAM,EAAE,QAAQ,SAAS,YAAY;CACrC,MAAM,2BAA2B,SAAS,YAAY,KAAA,KAAa,gBAAgB,OAAO;CAC1F,OAAO;EACN,QAAQ,OAAO;EACf,SAAS,OAAO;EAChB,GAAI,2BAA2B,CAAC,IAAI,EAAE,SAAS,OAAO,QAAQ;CAC/D;AACD;AAEA,SAAS,sBACR,KACA,MACiB;CACjB,IAAI,KAAK,mBAAmB,KAAA,GAC3B,OAAO;CAGR,IAAI,eAAe,iBAClB,OAAO;CAGR,IAAI,EAAE,eAAe,WACpB,OAAO;CAGR,IAAI,IAAI,eAAe,OAAO,IAAI,eAAe,KAChD,OAAO;CAGR,OAAO,IAAI,gBAAgB,IAAI,SAAS;EACvC,OAAO,IAAI;EACX,MAAM,IAAI;EACV,cAAc,KAAK,eAAe;EAClC,gBAAgB,KAAK;EACrB,YAAY,IAAI;CACjB,CAAC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"storage.mjs","names":["SECONDS_PER_MINUTE","PATH_PATTERN","makeSpec","#inner","#inner"],"sources":["../src/domains/cloud-v2/memory-store-queues/builders.ts","../src/domains/cloud-v2/memory-store-queues/operations.ts","../src/domains/cloud-v2/memory-store-queues/parsers.ts","../src/resources/storage/queues-group.ts","../src/domains/cloud-v2/memory-store-sorted-maps/builders.ts","../src/domains/cloud-v2/memory-store-sorted-maps/operations.ts","../src/domains/cloud-v2/memory-store-sorted-maps/parsers.ts","../src/resources/storage/sorted-maps-group.ts","../src/resources/storage/client.ts"],"sourcesContent":["import type { HttpRequest } from \"../../../client/types.ts\";\nimport type {\n\tDequeueQueueItemsParameters,\n\tDiscardQueueItemsParameters,\n\tEnqueueQueueItemParameters,\n} from \"./types.ts\";\n\n/**\n * Builds a `POST` request for the Open Cloud\n * `Cloud_CreateMemoryStoreQueueItem` endpoint. Serializes the optional\n * `ttl` field as a Google protobuf `Duration` string in seconds (`\"30s\"`)\n * to match the wire contract.\n *\n * @param parameters - Universe and queue identifiers, the opaque payload,\n * and optional priority and TTL.\n * @returns A pure {@link HttpRequest} describing the enqueue call.\n */\nexport function buildEnqueueRequest(parameters: EnqueueQueueItemParameters): HttpRequest {\n\tconst { data, priority, queueId, ttl, universeId } = parameters;\n\tconst body: Record<string, unknown> = { data };\n\tif (priority !== undefined) {\n\t\tbody[\"priority\"] = priority;\n\t}\n\n\tif (ttl !== undefined) {\n\t\tbody[\"ttl\"] = `${ttl}s`;\n\t}\n\n\treturn {\n\t\tbody,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"POST\",\n\t\turl: `/cloud/v2/universes/${universeId}/memory-store/queues/${queueId}/items`,\n\t};\n}\n\n/**\n * Builds a `GET` request for the Open Cloud\n * `Cloud_ReadMemoryStoreQueueItems` endpoint. The `:read` suffix is a\n * custom-method marker; the call is HTTP `GET` despite the AIP-136\n * convention that custom methods use `POST`. Parameters travel as query\n * string only; there is no request body.\n *\n * `invisibilityWindow` is serialized as a Google protobuf `Duration`\n * string in seconds (`\"30s\"`), matching the wire contract.\n *\n * @param parameters - Universe and queue identifiers, plus optional\n * `count`, `allOrNothing`, and `invisibilityWindow`.\n * @returns A pure {@link HttpRequest} describing the dequeue call.\n */\nexport function buildDequeueRequest(parameters: DequeueQueueItemsParameters): HttpRequest {\n\tconst query = new URLSearchParams();\n\tif (parameters.count !== undefined) {\n\t\tquery.append(\"count\", String(parameters.count));\n\t}\n\n\tif (parameters.allOrNothing !== undefined) {\n\t\tquery.append(\"allOrNothing\", String(parameters.allOrNothing));\n\t}\n\n\tif (parameters.invisibilityWindow !== undefined) {\n\t\tquery.append(\"invisibilityWindow\", `${parameters.invisibilityWindow}s`);\n\t}\n\n\tconst queryString = query.toString();\n\tconst { queueId, universeId } = parameters;\n\tconst base = `/cloud/v2/universes/${universeId}/memory-store/queues/${queueId}/items:read`;\n\treturn {\n\t\tmethod: \"GET\",\n\t\turl: queryString === \"\" ? base : `${base}?${queryString}`,\n\t};\n}\n\n/**\n * Builds a `POST` request for the Open Cloud\n * `Cloud_DiscardMemoryStoreQueueItems` endpoint. The request body uses\n * `{ readId }`, matching the schema (the dequeue *response* uses `id`,\n * but the discard *request* matches the schema and is not patched).\n *\n * @param parameters - Universe and queue identifiers, plus the\n * `readId` returned from a prior dequeue.\n * @returns A pure {@link HttpRequest} describing the discard call.\n */\nexport function buildDiscardRequest(parameters: DiscardQueueItemsParameters): HttpRequest {\n\tconst { queueId, readId, universeId } = parameters;\n\treturn {\n\t\tbody: { readId },\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"POST\",\n\t\turl: `/cloud/v2/universes/${universeId}/memory-store/queues/${queueId}/items:discard`,\n\t};\n}\n","import type { OperationLimit } from \"../../../internal/http/rate-limit-queue.ts\";\n\nconst ENQUEUE_PER_MINUTE = 1_000_000;\nconst SECONDS_PER_MINUTE = 60;\n\n/**\n * Per-second request ceiling for enqueueing a memory-store queue item,\n * from the Open Cloud OpenAPI schema (1,000,000 requests per minute per\n * API key owner). Keyed independently from the dequeue and discard\n * operations so the three do not share a queue; upstream quota\n * accounting is documented per-operation, and the conservative default\n * is fewer cross-method contention surprises.\n */\nexport const ENQUEUE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: ENQUEUE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-queues.enqueue\",\n});\n\n/**\n * Scopes required to enqueue a memory-store queue item, sourced from\n * `x-roblox-scopes` on the `Cloud_CreateMemoryStoreQueueItem` operation\n * in the vendored OpenAPI schema.\n */\nexport const ENQUEUE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.queue:add\",\n]);\n\nconst DEQUEUE_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for dequeueing memory-store queue items,\n * from the Open Cloud OpenAPI schema (1,000,000 requests per minute\n * per API key owner). Keyed independently from enqueue and discard.\n */\nexport const DEQUEUE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: DEQUEUE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-queues.dequeue\",\n});\n\n/**\n * Scopes required to dequeue memory-store queue items, sourced from\n * `x-roblox-scopes` on the `Cloud_ReadMemoryStoreQueueItems` operation\n * in the vendored OpenAPI schema.\n */\nexport const DEQUEUE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.queue:dequeue\",\n]);\n\nconst DISCARD_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for discarding (acknowledging) memory-store\n * queue items, from the Open Cloud OpenAPI schema (1,000,000 requests\n * per minute per API key owner). Keyed independently from enqueue and\n * dequeue.\n */\nexport const DISCARD_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: DISCARD_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-queues.discard\",\n});\n\n/**\n * Scopes required to discard memory-store queue items, sourced from\n * `x-roblox-scopes` on the `Cloud_DiscardMemoryStoreQueueItems`\n * operation in the vendored OpenAPI schema.\n */\nexport const DISCARD_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.queue:discard\",\n]);\n","import type { HttpResponse } from \"../../../client/types.ts\";\nimport { ApiError } from \"../../../errors/api-error.ts\";\nimport { isDateTimeString } from \"../../../internal/utils/is-date-time-string.ts\";\nimport { isRecord } from \"../../../internal/utils/is-record.ts\";\nimport type { Result } from \"../../../types.ts\";\nimport type { DequeueResult, QueueItem } from \"./types.ts\";\nimport type { MemoryStoreQueueItemWire } from \"./wire.ts\";\n\nconst PATH_PATTERN = /^cloud\\/v2\\/universes\\/(\\d+)\\/memory-store\\/queues\\/([^/]+)\\/items\\/([^/]+)$/;\nconst MALFORMED_QUEUE_ITEM_MESSAGE = \"Malformed memory-store queue item response\";\nconst MALFORMED_DEQUEUE_MESSAGE = \"Malformed memory-store dequeue response\";\n\n/**\n * Parses a successful memory-store queue-item response body (the\n * `Cloud_CreateMemoryStoreQueueItem` happy path) into the public\n * {@link QueueItem} shape.\n *\n * @param response - The full {@link HttpResponse} from the Open Cloud API.\n * @returns A success result wrapping the parsed {@link QueueItem}, or an\n * {@link ApiError} when the body does not match the wire schema.\n */\nexport function parseQueueItemResponse(response: HttpResponse): Result<QueueItem, ApiError> {\n\tconst item = wireBodyToQueueItem(response.body);\n\tif (item === undefined) {\n\t\treturn malformedQueueItem(response.status);\n\t}\n\n\treturn { data: item, success: true };\n}\n\n/**\n * Parses a successful `Cloud_ReadMemoryStoreQueueItems` response body\n * into the public {@link DequeueResult} shape. Each item in the\n * `queueItems` array is validated through the same path-and-shape\n * checks as {@link parseQueueItemResponse}; a malformed entry rejects\n * the whole response.\n *\n * @param response - The full {@link HttpResponse} from the Open Cloud API.\n * @returns A success result wrapping the parsed {@link DequeueResult},\n * or an {@link ApiError} when the response shape is wrong.\n */\nexport function parseDequeueResponse(response: HttpResponse): Result<DequeueResult, ApiError> {\n\tconst { body, status: statusCode } = response;\n\tif (!isRecord(body)) {\n\t\treturn malformedDequeue(statusCode);\n\t}\n\n\tconst { id, queueItems } = body;\n\tif (typeof id !== \"string\") {\n\t\treturn malformedDequeue(statusCode);\n\t}\n\n\tif (queueItems !== undefined && queueItems !== null && !Array.isArray(queueItems)) {\n\t\treturn malformedDequeue(statusCode);\n\t}\n\n\tconst rawItems = queueItems ?? [];\n\tconst items = rawItems.map(wireBodyToQueueItem);\n\tif (!items.every(isQueueItem)) {\n\t\treturn malformedDequeue(statusCode);\n\t}\n\n\treturn { data: { items, readId: id }, success: true };\n}\n\nfunction isQueueItemWire(body: unknown): body is MemoryStoreQueueItemWire {\n\tif (!isRecord(body)) {\n\t\treturn false;\n\t}\n\n\tconst { data, expireTime, path, priority } = body;\n\treturn (\n\t\ttypeof path === \"string\" &&\n\t\tisDateTimeString(expireTime) &&\n\t\tdata !== undefined &&\n\t\tdata !== null &&\n\t\t(priority === undefined || priority === null || typeof priority === \"number\")\n\t);\n}\n\nfunction wireBodyToQueueItem(body: unknown): QueueItem | undefined {\n\tif (!isQueueItemWire(body)) {\n\t\treturn undefined;\n\t}\n\n\tconst match = PATH_PATTERN.exec(body.path);\n\tconst universeId = match?.[1];\n\tconst queueId = match?.[2];\n\tconst id = match?.[3];\n\tif (universeId === undefined || queueId === undefined || id === undefined) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tid,\n\t\tdata: body.data,\n\t\texpiresAt: new Date(body.expireTime),\n\t\tpriority: body.priority ?? undefined,\n\t\tqueueId,\n\t\tuniverseId,\n\t};\n}\n\nfunction malformedQueueItem(statusCode: number): Result<QueueItem, ApiError> {\n\treturn {\n\t\terr: new ApiError(MALFORMED_QUEUE_ITEM_MESSAGE, { statusCode }),\n\t\tsuccess: false,\n\t};\n}\n\nfunction isQueueItem(item: QueueItem | undefined): item is QueueItem {\n\treturn item !== undefined;\n}\n\nfunction malformedDequeue(statusCode: number): Result<DequeueResult, ApiError> {\n\treturn {\n\t\terr: new ApiError(MALFORMED_DEQUEUE_MESSAGE, { statusCode }),\n\t\tsuccess: false,\n\t};\n}\n","import type { OpenCloudClientOptions, RequestOptions } from \"../../client/types.ts\";\nimport {\n\tbuildDequeueRequest,\n\tbuildDiscardRequest,\n\tbuildEnqueueRequest,\n} from \"../../domains/cloud-v2/memory-store-queues/builders.ts\";\nimport {\n\tDEQUEUE_OPERATION_LIMIT,\n\tDEQUEUE_REQUIRED_SCOPES,\n\tDISCARD_OPERATION_LIMIT,\n\tDISCARD_REQUIRED_SCOPES,\n\tENQUEUE_OPERATION_LIMIT,\n\tENQUEUE_REQUIRED_SCOPES,\n} from \"../../domains/cloud-v2/memory-store-queues/operations.ts\";\nimport {\n\tparseDequeueResponse,\n\tparseQueueItemResponse,\n} from \"../../domains/cloud-v2/memory-store-queues/parsers.ts\";\nimport type {\n\tDequeueQueueItemsParameters,\n\tDequeueResult,\n\tDiscardQueueItemsParameters,\n\tEnqueueQueueItemParameters,\n\tQueueItem,\n} from \"../../domains/cloud-v2/memory-store-queues/types.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { CREATE_METHOD_DEFAULTS, IDEMPOTENT_METHOD_DEFAULTS } from \"../../internal/http/retry.ts\";\nimport {\n\tokRequest,\n\tparseEmptyResponse,\n\ttype ResourceClient,\n\ttype ResourceMethodSpec,\n} from \"../../internal/resource-client.ts\";\nimport type { Result } from \"../../types.ts\";\n\nfunction makeSpec<P, R>(spec: ResourceMethodSpec<P, R>): ResourceMethodSpec<P, R> {\n\treturn Object.freeze(spec);\n}\n\nconst ENQUEUE_SPEC = makeSpec<EnqueueQueueItemParameters, QueueItem>({\n\tbuildRequest: (parameters) => okRequest(buildEnqueueRequest(parameters)),\n\tmethodDefaults: CREATE_METHOD_DEFAULTS,\n\tmethodKind: \"create\",\n\toperationLimit: ENQUEUE_OPERATION_LIMIT,\n\tparse: parseQueueItemResponse,\n\trequiredScopes: ENQUEUE_REQUIRED_SCOPES,\n});\n\n// Dequeue uses HTTP GET but mutates server state via the invisibility\n// window. Retrying a 5xx where the server set invisibility before\n// failing the response would lose the original batch (it stays\n// invisible until the window elapses) and return a different one. So\n// the retry policy mirrors `create`: only 429, never 5xx.\nconst DEQUEUE_SPEC = makeSpec<DequeueQueueItemsParameters, DequeueResult>({\n\tbuildRequest: (parameters) => okRequest(buildDequeueRequest(parameters)),\n\tmethodDefaults: CREATE_METHOD_DEFAULTS,\n\tmethodKind: \"create\",\n\toperationLimit: DEQUEUE_OPERATION_LIMIT,\n\tparse: parseDequeueResponse,\n\trequiredScopes: DEQUEUE_REQUIRED_SCOPES,\n});\n\nconst DISCARD_SPEC = makeSpec<DiscardQueueItemsParameters, undefined>({\n\tbuildRequest: (parameters) => okRequest(buildDiscardRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: DISCARD_OPERATION_LIMIT,\n\tparse: parseEmptyResponse,\n\trequiredScopes: DISCARD_REQUIRED_SCOPES,\n});\n\n/**\n * Operation Group on `StorageClient` that exposes the memory-store\n * queue endpoints. Queues are FIFO collections of opaque JSON values\n * with optional priority and TTL; consumers enqueue items, dequeue\n * them in batches, and acknowledge processed batches with a read\n * identifier.\n */\nexport class MemoryStoreQueuesGroup {\n\treadonly #inner: ResourceClient;\n\n\t/**\n\t * Wraps the shared {@link ResourceClient} so the Operation Group\n\t * routes calls through the same retry, hooks, and rate-limit queues\n\t * as the rest of the parent client.\n\t *\n\t * @param inner - The shared {@link ResourceClient} owned by the\n\t * parent client.\n\t */\n\tconstructor(inner: ResourceClient) {\n\t\tthis.#inner = inner;\n\t}\n\n\t/**\n\t * Dequeues up to `count` items from the front of the queue. Items\n\t * returned become invisible to subsequent reads for\n\t * `invisibilityWindow` seconds (default 30 server-side); they\n\t * reappear once the window elapses unless acknowledged via\n\t * `discard` with the returned `readId`.\n\t *\n\t * On 5xx, dequeue does not retry: the server may have set\n\t * invisibility on a batch before the response failed, so a retry\n\t * would return a *different* batch and the first one is lost until\n\t * the window expires. Callers that can detect duplicates externally\n\t * may opt back into 5xx retry per call by passing `retryableStatuses`\n\t * on `options`.\n\t *\n\t * @param parameters - Universe and queue identifiers, plus optional\n\t * `count`, `allOrNothing`, and `invisibilityWindow`.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping the parsed {@link DequeueResult}\n\t * or the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async dequeue(\n\t\tparameters: DequeueQueueItemsParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<DequeueResult, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: DEQUEUE_SPEC });\n\t}\n\n\t/**\n\t * Acknowledges a dequeued batch of items, removing them from the\n\t * queue permanently. Pass the `readId` returned from the prior\n\t * `dequeue` call. Without `discard`, the items reappear once the\n\t * invisibility window elapses.\n\t *\n\t * The call is idempotent: a second `discard` with the same `readId`\n\t * is a no-op once the batch has been acknowledged. The retry policy\n\t * therefore retries both 429 and 5xx.\n\t *\n\t * @param parameters - Universe and queue identifiers, plus the\n\t * `readId` returned from a prior dequeue.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping `undefined` on success (the\n\t * server returns an empty body) or the {@link OpenCloudError}\n\t * that caused the request to fail.\n\t */\n\tpublic async discard(\n\t\tparameters: DiscardQueueItemsParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<undefined, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: DISCARD_SPEC });\n\t}\n\n\t/**\n\t * Enqueues a single item onto a memory-store queue. The queue is\n\t * auto-created on first use; the queue identifier is any string the\n\t * caller picks. Items with higher `priority` values are dequeued\n\t * first; equal priorities preserve insertion order. Items expire\n\t * and are removed automatically after `ttl` seconds, or after a\n\t * server-default lifetime when omitted.\n\t *\n\t * @param parameters - Universe and queue identifiers, the opaque\n\t * payload, and optional `priority` and `ttl`.\n\t * @param options - Optional per-request overrides (e.g. A different\n\t * {@link OpenCloudClientOptions.apiKey} for this call only).\n\t * @returns A {@link Result} wrapping the parsed {@link QueueItem} or\n\t * the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async enqueue(\n\t\tparameters: EnqueueQueueItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<QueueItem, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: ENQUEUE_SPEC });\n\t}\n}\n","import type { HttpRequest } from \"../../../client/types.ts\";\nimport type {\n\tCreateSortedMapItemParameters,\n\tDeleteSortedMapItemParameters,\n\tGetSortedMapItemParameters,\n\tListSortedMapItemsParameters,\n\tSortKey,\n\tUpdateSortedMapItemParameters,\n} from \"./types.ts\";\n\n/**\n * Builds a `POST` request for the Open Cloud\n * `Cloud_CreateMemoryStoreSortedMapItem` endpoint. The caller-supplied\n * `itemId` travels as the `id` query parameter (URL-encoded by\n * `URLSearchParams`); the body carries `value`, the optional `ttl`\n * (serialized as a Google protobuf `Duration` string in seconds), and\n * one of `stringSortKey`/`numericSortKey` projected from the\n * {@link SortKey} discriminated union.\n *\n * @param parameters - Universe, sorted-map, item identifiers, the\n * value to store, and optional `sortKey` and `ttl`.\n * @returns A pure {@link HttpRequest} describing the create call.\n */\nexport function buildCreateRequest(parameters: CreateSortedMapItemParameters): HttpRequest {\n\tconst { itemId, mapId, sortKey, ttl, universeId, value } = parameters;\n\tconst body: Record<string, unknown> = { value };\n\tif (ttl !== undefined) {\n\t\tbody[\"ttl\"] = `${ttl}s`;\n\t}\n\n\tapplySortKeyToBody(body, sortKey);\n\n\tconst query = new URLSearchParams({ id: itemId });\n\treturn {\n\t\tbody,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"POST\",\n\t\turl: `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items?${query.toString()}`,\n\t};\n}\n\n/**\n * Builds a `DELETE` request for the Open Cloud\n * `Cloud_DeleteMemoryStoreSortedMapItem` endpoint. Every path segment\n * (universe, sorted-map, item identifiers) is URL-encoded so callers\n * can pass values containing reserved characters without manual\n * escaping.\n *\n * @param parameters - Universe, sorted-map, and item identifiers.\n * @returns A pure {@link HttpRequest} describing the delete call.\n */\nexport function buildDeleteRequest(parameters: DeleteSortedMapItemParameters): HttpRequest {\n\tconst { itemId, mapId, universeId } = parameters;\n\treturn {\n\t\tmethod: \"DELETE\",\n\t\turl: `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items/${encodeURIComponent(itemId)}`,\n\t};\n}\n\n/**\n * Builds a `GET` request for the Open Cloud\n * `Cloud_GetMemoryStoreSortedMapItem` endpoint. Every path segment\n * (universe, sorted-map, item identifiers) is URL-encoded so callers\n * can pass values containing reserved characters without manual\n * escaping.\n *\n * @param parameters - Universe, sorted-map, and item identifiers.\n * @returns A pure {@link HttpRequest} describing the get call.\n */\nexport function buildGetRequest(parameters: GetSortedMapItemParameters): HttpRequest {\n\tconst { itemId, mapId, universeId } = parameters;\n\treturn {\n\t\tmethod: \"GET\",\n\t\turl: `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items/${encodeURIComponent(itemId)}`,\n\t};\n}\n\n/**\n * Builds a `GET` request for the Open Cloud\n * `Cloud_ListMemoryStoreSortedMapItems` endpoint. Optional `filter`,\n * `maxPageSize`, `orderBy`, and `pageToken` parameters travel as query\n * string parameters and are omitted when unset.\n *\n * @param parameters - Universe and sorted-map identifiers, plus\n * optional pagination and filter parameters.\n * @returns A pure {@link HttpRequest} describing the list call.\n */\nexport function buildListRequest(parameters: ListSortedMapItemsParameters): HttpRequest {\n\tconst { filter, mapId, maxPageSize, orderBy, pageToken, universeId } = parameters;\n\tconst query = new URLSearchParams();\n\tif (maxPageSize !== undefined) {\n\t\tquery.append(\"maxPageSize\", String(maxPageSize));\n\t}\n\n\tif (pageToken !== undefined) {\n\t\tquery.append(\"pageToken\", pageToken);\n\t}\n\n\tif (orderBy !== undefined) {\n\t\tquery.append(\"orderBy\", orderBy);\n\t}\n\n\tif (filter !== undefined) {\n\t\tquery.append(\"filter\", filter);\n\t}\n\n\tconst base = `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items`;\n\tconst queryString = query.toString();\n\treturn { method: \"GET\", url: queryString === \"\" ? base : `${base}?${queryString}` };\n}\n\n/**\n * Builds a `PATCH` request for the Open Cloud\n * `Cloud_UpdateMemoryStoreSortedMapItem` endpoint. Body fields are\n * conditionally included so a partial update sends only the changed\n * fields; the optional `allowMissing` query string drives\n * upsert-on-missing behaviour server-side.\n *\n * @param parameters - Universe, sorted-map, and item identifiers,\n * plus any subset of `value`, `ttl`, `sortKey`, and `allowMissing`.\n * @returns A pure {@link HttpRequest} describing the update call.\n */\nexport function buildUpdateRequest(parameters: UpdateSortedMapItemParameters): HttpRequest {\n\tconst { allowMissing: shouldAllowMissing, itemId, mapId, universeId } = parameters;\n\tconst base = `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items/${encodeURIComponent(itemId)}`;\n\tconst query = new URLSearchParams();\n\tif (shouldAllowMissing !== undefined) {\n\t\tquery.append(\"allowMissing\", String(shouldAllowMissing));\n\t}\n\n\tconst queryString = query.toString();\n\treturn {\n\t\tbody: buildUpdateBody(parameters),\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"PATCH\",\n\t\turl: queryString === \"\" ? base : `${base}?${queryString}`,\n\t};\n}\n\nfunction applySortKeyToBody(body: Record<string, unknown>, sortKey: SortKey | undefined): void {\n\tif (sortKey === undefined) {\n\t\treturn;\n\t}\n\n\tif (sortKey.kind === \"string\") {\n\t\tbody[\"stringSortKey\"] = sortKey.value;\n\t\treturn;\n\t}\n\n\tbody[\"numericSortKey\"] = sortKey.value;\n}\n\nfunction buildUpdateBody(parameters: UpdateSortedMapItemParameters): Record<string, unknown> {\n\tconst { sortKey, ttl, value } = parameters;\n\tconst body: Record<string, unknown> = {};\n\tif (value !== undefined) {\n\t\tbody[\"value\"] = value;\n\t}\n\n\tif (ttl !== undefined) {\n\t\tbody[\"ttl\"] = `${ttl}s`;\n\t}\n\n\tapplySortKeyToBody(body, sortKey);\n\treturn body;\n}\n","import type { OperationLimit } from \"../../../internal/http/rate-limit-queue.ts\";\n\nconst CREATE_PER_MINUTE = 1_000_000;\nconst SECONDS_PER_MINUTE = 60;\n\nconst WRITE_SCOPE = \"memory-store.sorted-map:write\";\n\n/**\n * Per-second request ceiling for creating a memory-store sorted-map\n * item, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner). Keyed independently from the get, update,\n * delete, and list operations so the five do not share a queue.\n */\nexport const CREATE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: CREATE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.create\",\n});\n\n/**\n * Scopes required to create a memory-store sorted-map item, sourced\n * from `x-roblox-scopes` on the `Cloud_CreateMemoryStoreSortedMapItem`\n * operation in the vendored OpenAPI schema.\n */\nexport const CREATE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([WRITE_SCOPE]);\n\nconst DELETE_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for deleting a memory-store sorted-map\n * item, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner).\n */\nexport const DELETE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: DELETE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.delete\",\n});\n\n/**\n * Scopes required to delete a memory-store sorted-map item, sourced\n * from `x-roblox-scopes` on the `Cloud_DeleteMemoryStoreSortedMapItem`\n * operation in the vendored OpenAPI schema.\n */\nexport const DELETE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([WRITE_SCOPE]);\n\nconst GET_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for reading a memory-store sorted-map\n * item, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner).\n */\nexport const GET_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: GET_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.get\",\n});\n\n/**\n * Scopes required to read a memory-store sorted-map item, sourced from\n * `x-roblox-scopes` on the `Cloud_GetMemoryStoreSortedMapItem`\n * operation in the vendored OpenAPI schema.\n */\nexport const GET_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.sorted-map:read\",\n]);\n\nconst LIST_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for listing memory-store sorted-map\n * items, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner).\n */\nexport const LIST_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: LIST_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.list\",\n});\n\n/**\n * Scopes required to list memory-store sorted-map items, sourced from\n * `x-roblox-scopes` on the `Cloud_ListMemoryStoreSortedMapItems`\n * operation in the vendored OpenAPI schema.\n */\nexport const LIST_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.sorted-map:read\",\n]);\n\nconst UPDATE_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for updating a memory-store sorted-map\n * item, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner).\n */\nexport const UPDATE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: UPDATE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.update\",\n});\n\n/**\n * Scopes required to update a memory-store sorted-map item, sourced\n * from `x-roblox-scopes` on the `Cloud_UpdateMemoryStoreSortedMapItem`\n * operation in the vendored OpenAPI schema.\n */\nexport const UPDATE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([WRITE_SCOPE]);\n","import type { HttpResponse } from \"../../../client/types.ts\";\nimport { ApiError } from \"../../../errors/api-error.ts\";\nimport { isDateTimeString } from \"../../../internal/utils/is-date-time-string.ts\";\nimport { isRecord } from \"../../../internal/utils/is-record.ts\";\nimport type { Result } from \"../../../types.ts\";\nimport type { ListSortedMapItemsResult, SortedMapItem, SortKey } from \"./types.ts\";\nimport type { MemoryStoreSortedMapItemWire } from \"./wire.ts\";\n\nconst PATH_PATTERN =\n\t/^cloud\\/v2\\/universes\\/(\\d+)\\/memory-stores?\\/sorted-maps\\/([^/]+)\\/items\\/([^/]+)$/;\nconst MALFORMED_MESSAGE = \"Malformed memory-store sorted-map item response\";\nconst MALFORMED_LIST_MESSAGE = \"Malformed memory-store sorted-map list response\";\n\n/**\n * Parses a successful memory-store sorted-map item response body (the\n * happy path for create, get, and update) into the public\n * {@link SortedMapItem} shape.\n *\n * @param response - The full {@link HttpResponse} from the Open Cloud API.\n * @returns A success result wrapping the parsed {@link SortedMapItem},\n * or an {@link ApiError} when the body does not match the wire schema.\n */\nexport function parseSortedMapItemResponse(\n\tresponse: HttpResponse,\n): Result<SortedMapItem, ApiError> {\n\tconst item = wireBodyToSortedMapItem(response.body);\n\tif (item === undefined) {\n\t\treturn malformedSortedMapItem(response.status);\n\t}\n\n\treturn { data: item, success: true };\n}\n\n/**\n * Parses a successful `Cloud_ListMemoryStoreSortedMapItems` response\n * body into the public {@link ListSortedMapItemsResult} shape. Each\n * item in the `items` array is validated through the same\n * path-and-shape checks as {@link parseSortedMapItemResponse}; a\n * malformed entry rejects the whole response.\n *\n * @param response - The full {@link HttpResponse} from the Open Cloud API.\n * @returns A success result wrapping the parsed\n * {@link ListSortedMapItemsResult}, or an {@link ApiError} when the\n * response shape is wrong.\n */\nexport function parseListResponse(\n\tresponse: HttpResponse,\n): Result<ListSortedMapItemsResult, ApiError> {\n\tconst { body, status: statusCode } = response;\n\tif (!isRecord(body)) {\n\t\treturn malformedList(statusCode);\n\t}\n\n\tconst { items: rawItemsField, nextPageToken } = body;\n\tif (rawItemsField !== undefined && rawItemsField !== null && !Array.isArray(rawItemsField)) {\n\t\treturn malformedList(statusCode);\n\t}\n\n\tconst normalizedToken = nextPageToken ?? undefined;\n\tif (normalizedToken !== undefined && typeof normalizedToken !== \"string\") {\n\t\treturn malformedList(statusCode);\n\t}\n\n\tconst rawItems = rawItemsField ?? [];\n\tconst items = rawItems.map(wireBodyToSortedMapItem);\n\tif (!items.every(isSortedMapItem)) {\n\t\treturn malformedList(statusCode);\n\t}\n\n\treturn { data: { items, nextPageToken: normalizedToken }, success: true };\n}\n\nfunction isSortedMapItemWire(body: unknown): body is MemoryStoreSortedMapItemWire {\n\tif (!isRecord(body)) {\n\t\treturn false;\n\t}\n\n\tconst { id, etag, expireTime, numericSortKey, path, stringSortKey, value } = body;\n\treturn (\n\t\ttypeof path === \"string\" &&\n\t\ttypeof etag === \"string\" &&\n\t\ttypeof id === \"string\" &&\n\t\tisDateTimeString(expireTime) &&\n\t\tvalue !== undefined &&\n\t\t(stringSortKey === undefined ||\n\t\t\tstringSortKey === null ||\n\t\t\ttypeof stringSortKey === \"string\") &&\n\t\t(numericSortKey === undefined ||\n\t\t\tnumericSortKey === null ||\n\t\t\ttypeof numericSortKey === \"number\")\n\t);\n}\n\nfunction extractSortKey(body: MemoryStoreSortedMapItemWire): \"conflict\" | SortKey | undefined {\n\tconst hasStringKey = typeof body.stringSortKey === \"string\";\n\tconst hasNumericKey = typeof body.numericSortKey === \"number\";\n\tif (hasStringKey && hasNumericKey) {\n\t\treturn \"conflict\";\n\t}\n\n\tif (hasStringKey) {\n\t\treturn { kind: \"string\", value: body.stringSortKey };\n\t}\n\n\tif (hasNumericKey) {\n\t\treturn { kind: \"numeric\", value: body.numericSortKey };\n\t}\n\n\treturn undefined;\n}\n\nfunction wireBodyToSortedMapItem(body: unknown): SortedMapItem | undefined {\n\tif (!isSortedMapItemWire(body)) {\n\t\treturn undefined;\n\t}\n\n\t// Item ids round-trip URL-encoded in `path` (e.g. `name::id` arrives\n\t// as `name%3A%3Aid`), so the decoded id is read from `body.id` rather\n\t// than the regex group.\n\tconst match = PATH_PATTERN.exec(body.path);\n\tconst universeId = match?.[1];\n\tconst mapId = match?.[2];\n\tif (universeId === undefined || mapId === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst sortKey = extractSortKey(body);\n\tif (sortKey === \"conflict\") {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tid: body.id,\n\t\tetag: body.etag,\n\t\texpiresAt: new Date(body.expireTime),\n\t\tmapId,\n\t\tsortKey,\n\t\tuniverseId,\n\t\tvalue: body.value,\n\t};\n}\n\nfunction malformedSortedMapItem(statusCode: number): Result<SortedMapItem, ApiError> {\n\treturn {\n\t\terr: new ApiError(MALFORMED_MESSAGE, { statusCode }),\n\t\tsuccess: false,\n\t};\n}\n\nfunction isSortedMapItem(item: SortedMapItem | undefined): item is SortedMapItem {\n\treturn item !== undefined;\n}\n\nfunction malformedList(statusCode: number): Result<ListSortedMapItemsResult, ApiError> {\n\treturn {\n\t\terr: new ApiError(MALFORMED_LIST_MESSAGE, { statusCode }),\n\t\tsuccess: false,\n\t};\n}\n","import type { OpenCloudClientOptions, RequestOptions } from \"../../client/types.ts\";\nimport {\n\tbuildCreateRequest,\n\tbuildDeleteRequest,\n\tbuildGetRequest,\n\tbuildListRequest,\n\tbuildUpdateRequest,\n} from \"../../domains/cloud-v2/memory-store-sorted-maps/builders.ts\";\nimport {\n\tCREATE_OPERATION_LIMIT,\n\tCREATE_REQUIRED_SCOPES,\n\tDELETE_OPERATION_LIMIT,\n\tDELETE_REQUIRED_SCOPES,\n\tGET_OPERATION_LIMIT,\n\tGET_REQUIRED_SCOPES,\n\tLIST_OPERATION_LIMIT,\n\tLIST_REQUIRED_SCOPES,\n\tUPDATE_OPERATION_LIMIT,\n\tUPDATE_REQUIRED_SCOPES,\n} from \"../../domains/cloud-v2/memory-store-sorted-maps/operations.ts\";\nimport {\n\tparseListResponse,\n\tparseSortedMapItemResponse,\n} from \"../../domains/cloud-v2/memory-store-sorted-maps/parsers.ts\";\nimport type {\n\tCreateSortedMapItemParameters,\n\tDeleteSortedMapItemParameters,\n\tGetSortedMapItemParameters,\n\tListSortedMapItemsParameters,\n\tListSortedMapItemsResult,\n\tSortedMapItem,\n\tUpdateSortedMapItemParameters,\n} from \"../../domains/cloud-v2/memory-store-sorted-maps/types.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { CREATE_METHOD_DEFAULTS, IDEMPOTENT_METHOD_DEFAULTS } from \"../../internal/http/retry.ts\";\nimport {\n\tokRequest,\n\tparseEmptyResponse,\n\ttype ResourceClient,\n\ttype ResourceMethodSpec,\n} from \"../../internal/resource-client.ts\";\nimport type { Result } from \"../../types.ts\";\n\nfunction makeSpec<P, R>(spec: ResourceMethodSpec<P, R>): ResourceMethodSpec<P, R> {\n\treturn Object.freeze(spec);\n}\n\nconst CREATE_SPEC = makeSpec<CreateSortedMapItemParameters, SortedMapItem>({\n\tbuildRequest: (parameters) => okRequest(buildCreateRequest(parameters)),\n\tmethodDefaults: CREATE_METHOD_DEFAULTS,\n\tmethodKind: \"create\",\n\toperationLimit: CREATE_OPERATION_LIMIT,\n\tparse: parseSortedMapItemResponse,\n\trequiredScopes: CREATE_REQUIRED_SCOPES,\n});\n\nconst DELETE_SPEC = makeSpec<DeleteSortedMapItemParameters, undefined>({\n\tbuildRequest: (parameters) => okRequest(buildDeleteRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: DELETE_OPERATION_LIMIT,\n\tparse: parseEmptyResponse,\n\trequiredScopes: DELETE_REQUIRED_SCOPES,\n});\n\nconst GET_SPEC = makeSpec<GetSortedMapItemParameters, SortedMapItem>({\n\tbuildRequest: (parameters) => okRequest(buildGetRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: GET_OPERATION_LIMIT,\n\tparse: parseSortedMapItemResponse,\n\trequiredScopes: GET_REQUIRED_SCOPES,\n});\n\nconst LIST_SPEC = makeSpec<ListSortedMapItemsParameters, ListSortedMapItemsResult>({\n\tbuildRequest: (parameters) => okRequest(buildListRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: LIST_OPERATION_LIMIT,\n\tparse: parseListResponse,\n\trequiredScopes: LIST_REQUIRED_SCOPES,\n});\n\nconst UPDATE_SPEC = makeSpec<UpdateSortedMapItemParameters, SortedMapItem>({\n\tbuildRequest: (parameters) => okRequest(buildUpdateRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: UPDATE_OPERATION_LIMIT,\n\tparse: parseSortedMapItemResponse,\n\trequiredScopes: UPDATE_REQUIRED_SCOPES,\n});\n\n/**\n * Operation Group on `StorageClient` that exposes the memory-store\n * sorted-map endpoints. Sorted maps are ordered collections of\n * (id, value, sortKey) triples; consumers create, read, update, list,\n * and delete items keyed by a caller-supplied identifier and ordered\n * by an optional string or numeric sort key.\n */\nexport class MemoryStoreSortedMapsGroup {\n\treadonly #inner: ResourceClient;\n\n\t/**\n\t * Wraps the shared {@link ResourceClient} so the Operation Group\n\t * routes calls through the same retry, hooks, and rate-limit queues\n\t * as the rest of the parent client.\n\t *\n\t * @param inner - The shared {@link ResourceClient} owned by the\n\t * parent client.\n\t */\n\tconstructor(inner: ResourceClient) {\n\t\tthis.#inner = inner;\n\t}\n\n\t/**\n\t * Creates a single item in a sorted map. The sorted map is\n\t * auto-created on first use; the map identifier is any string the\n\t * caller picks. Items are keyed by `itemId` (case-sensitive) and\n\t * ordered by an optional `sortKey`. Items expire and are removed\n\t * automatically after `ttl` seconds, or after a server-default\n\t * lifetime when omitted.\n\t *\n\t * On 5xx, create does not retry: Roblox Open Cloud has no\n\t * idempotency-key support, so a retry of a transient failure risks\n\t * producing a duplicate item.\n\t *\n\t * @param parameters - Universe, sorted-map, item identifiers, the\n\t * value to store, and optional `sortKey` and `ttl`.\n\t * @param options - Optional per-request overrides (e.g. A different\n\t * {@link OpenCloudClientOptions.apiKey} for this call only).\n\t * @returns A {@link Result} wrapping the parsed {@link SortedMapItem}\n\t * or the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async create(\n\t\tparameters: CreateSortedMapItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<SortedMapItem, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: CREATE_SPEC });\n\t}\n\n\t/**\n\t * Removes a single item from a sorted map. The call is idempotent:\n\t * a second `delete` against the same item is a no-op once the\n\t * server has dropped the row. The retry policy retries both 429\n\t * and 5xx.\n\t *\n\t * @param parameters - Universe, sorted-map, and item identifiers.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping `undefined` on success or the\n\t * {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async delete(\n\t\tparameters: DeleteSortedMapItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<undefined, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: DELETE_SPEC });\n\t}\n\n\t/**\n\t * Reads a single item from a sorted map. Returns the parsed\n\t * {@link SortedMapItem} with the server-recorded `etag` for use in\n\t * subsequent conditional updates (once the SDK begins emitting\n\t * `If-Match`; see the package README).\n\t *\n\t * @param parameters - Universe, sorted-map, and item identifiers.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping the parsed {@link SortedMapItem}\n\t * or the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async get(\n\t\tparameters: GetSortedMapItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<SortedMapItem, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: GET_SPEC });\n\t}\n\n\t/**\n\t * Lists items in a sorted map. The server caps `maxPageSize` at\n\t * `100` and defaults it to `1` when omitted, so callers explicitly\n\t * pass `maxPageSize` to retrieve more than a single item per page.\n\t * The `filter` parameter accepts a CEL expression on `id` and\n\t * `sortKey` (operators `<`, `>`, `&&` only).\n\t *\n\t * @param parameters - Universe and sorted-map identifiers, plus\n\t * optional pagination and filter parameters.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping the parsed\n\t * {@link ListSortedMapItemsResult} or the {@link OpenCloudError}\n\t * that caused the request to fail.\n\t */\n\tpublic async list(\n\t\tparameters: ListSortedMapItemsParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<ListSortedMapItemsResult, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: LIST_SPEC });\n\t}\n\n\t/**\n\t * Updates a sorted-map item under PATCH semantics: omitted body\n\t * fields are left unchanged on the server, supplied fields replace\n\t * their existing values. Passing `allowMissing: true` creates the\n\t * item when no row exists instead of returning 404.\n\t *\n\t * Retries 5xx because PATCH with the same body produces the same\n\t * server state.\n\t *\n\t * @param parameters - Universe, sorted-map, and item identifiers,\n\t * plus any subset of `value`, `ttl`, `sortKey`, and\n\t * `allowMissing`.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping the parsed {@link SortedMapItem}\n\t * or the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async update(\n\t\tparameters: UpdateSortedMapItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<SortedMapItem, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: UPDATE_SPEC });\n\t}\n}\n","import type { OpenCloudClientOptions } from \"../../client/types.ts\";\nimport { ResourceClient } from \"../../internal/resource-client.ts\";\nimport { MemoryStoreQueuesGroup } from \"./queues-group.ts\";\nimport { MemoryStoreSortedMapsGroup } from \"./sorted-maps-group.ts\";\n\n/**\n * Public client for the Roblox Open Cloud `Data and memory stores`\n * Feature. Today it covers memory-store queues via the\n * {@link StorageClient.queues} Operation Group and memory-store sorted\n * maps via the {@link StorageClient.sortedMaps} Operation Group; a\n * future data-stores Operation Group slots in as a sibling on the same\n * client.\n *\n * Every method returns a `Result` so callers handle failure\n * explicitly; no thrown error ever escapes the client.\n *\n * @since 0.1.0\n *\n * @example\n *\n * ```ts\n * import { StorageClient } from \"@bedrock-rbx/ocale/storage\";\n *\n * const client = new StorageClient({ apiKey: \"your-key\" });\n * expect(client).toBeInstanceOf(StorageClient);\n * ```\n */\nexport class StorageClient {\n\t/** Memory-store queue Operation Group. */\n\tpublic readonly queues: MemoryStoreQueuesGroup;\n\t/** Memory-store sorted-map Operation Group. */\n\tpublic readonly sortedMaps: MemoryStoreSortedMapsGroup;\n\n\t/**\n\t * Creates a new {@link StorageClient}. Configuration is frozen on\n\t * construction; per-request overrides are accepted on each method.\n\t *\n\t * @param options - Client-level configuration including the API key.\n\t */\n\tconstructor(options: OpenCloudClientOptions) {\n\t\tconst inner = new ResourceClient(options);\n\t\tthis.queues = new MemoryStoreQueuesGroup(inner);\n\t\tthis.sortedMaps = new MemoryStoreSortedMapsGroup(inner);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,SAAgB,oBAAoB,YAAqD;CACxF,MAAM,EAAE,MAAM,UAAU,SAAS,KAAK,eAAe;CACrD,MAAM,OAAgC,EAAE,KAAK;CAC7C,IAAI,aAAa,KAAA,GAChB,KAAK,cAAc;CAGpB,IAAI,QAAQ,KAAA,GACX,KAAK,SAAS,GAAG,IAAI;CAGtB,OAAO;EACN;EACA,SAAS,EAAE,gBAAgB,mBAAmB;EAC9C,QAAQ;EACR,KAAK,uBAAuB,WAAW,uBAAuB,QAAQ;CACvE;AACD;;;;;;;;;;;;;;;AAgBA,SAAgB,oBAAoB,YAAsD;CACzF,MAAM,QAAQ,IAAI,gBAAgB;CAClC,IAAI,WAAW,UAAU,KAAA,GACxB,MAAM,OAAO,SAAS,OAAO,WAAW,KAAK,CAAC;CAG/C,IAAI,WAAW,iBAAiB,KAAA,GAC/B,MAAM,OAAO,gBAAgB,OAAO,WAAW,YAAY,CAAC;CAG7D,IAAI,WAAW,uBAAuB,K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tE;;;;;;;;;;;;CAaA,MAAa,IACZ,YACA,SACiD;EACjD,OAAO,KAAKA,OAAO,QAAQ;GAAE;GAAS;GAAY,MAAM;EAAS,CAAC;CACnE;;;;;;;;;;;;;;;CAgBA,MAAa,KACZ,YACA,SAC4D;EAC5D,OAAO,KAAKA,OAAO,QAAQ;GAAE;GAAS;GAAY,MAAM;EAAU,CAAC;CACpE;;;;;;;;;;;;;;;;;CAkBA,MAAa,OACZ,YACA,SACiD;EACjD,OAAO,KAAKA,OAAO,QAAQ;GAAE;GAAS;GAAY,MAAM;EAAY,CAAC;CACtE;AACD;;;;;;;;;;;;;;;;;;;;;;;;;AChMA,IAAa,gBAAb,MAA2B;;CAE1B;;CAEA;;;;;;;CAQA,YAAY,SAAiC;EAC5C,MAAM,QAAQ,IAAI,eAAe,OAAO;EACxC,KAAK,SAAS,IAAI,uBAAuB,KAAK;EAC9C,KAAK,aAAa,IAAI,2BAA2B,KAAK;CACvD;AACD"}
1
+ {"version":3,"file":"storage.mjs","names":["SECONDS_PER_MINUTE","PATH_PATTERN","makeSpec","#inner","#inner"],"sources":["../src/domains/cloud-v2/memory-store-queues/builders.ts","../src/domains/cloud-v2/memory-store-queues/operations.ts","../src/domains/cloud-v2/memory-store-queues/parsers.ts","../src/resources/storage/queues-group.ts","../src/domains/cloud-v2/memory-store-sorted-maps/builders.ts","../src/domains/cloud-v2/memory-store-sorted-maps/operations.ts","../src/domains/cloud-v2/memory-store-sorted-maps/parsers.ts","../src/resources/storage/sorted-maps-group.ts","../src/resources/storage/client.ts"],"sourcesContent":["import type { HttpRequest } from \"../../../client/types.ts\";\nimport type {\n\tDequeueQueueItemsParameters,\n\tDiscardQueueItemsParameters,\n\tEnqueueQueueItemParameters,\n} from \"./types.ts\";\n\n/**\n * Builds a `POST` request for the Open Cloud\n * `Cloud_CreateMemoryStoreQueueItem` endpoint. Serializes the optional\n * `ttl` field as a Google protobuf `Duration` string in seconds (`\"30s\"`)\n * to match the wire contract.\n *\n * @param parameters - Universe and queue identifiers, the opaque payload,\n * and optional priority and TTL.\n * @returns A pure {@link HttpRequest} describing the enqueue call.\n */\nexport function buildEnqueueRequest(parameters: EnqueueQueueItemParameters): HttpRequest {\n\tconst { data, priority, queueId, ttl, universeId } = parameters;\n\tconst body: Record<string, unknown> = { data };\n\tif (priority !== undefined) {\n\t\tbody[\"priority\"] = priority;\n\t}\n\n\tif (ttl !== undefined) {\n\t\tbody[\"ttl\"] = `${ttl}s`;\n\t}\n\n\treturn {\n\t\tbody,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"POST\",\n\t\turl: `/cloud/v2/universes/${universeId}/memory-store/queues/${queueId}/items`,\n\t};\n}\n\n/**\n * Builds a `GET` request for the Open Cloud\n * `Cloud_ReadMemoryStoreQueueItems` endpoint. The `:read` suffix is a\n * custom-method marker; the call is HTTP `GET` despite the AIP-136\n * convention that custom methods use `POST`. Parameters travel as query\n * string only; there is no request body.\n *\n * `invisibilityWindow` is serialized as a Google protobuf `Duration`\n * string in seconds (`\"30s\"`), matching the wire contract.\n *\n * @param parameters - Universe and queue identifiers, plus optional\n * `count`, `allOrNothing`, and `invisibilityWindow`.\n * @returns A pure {@link HttpRequest} describing the dequeue call.\n */\nexport function buildDequeueRequest(parameters: DequeueQueueItemsParameters): HttpRequest {\n\tconst query = new URLSearchParams();\n\tif (parameters.count !== undefined) {\n\t\tquery.append(\"count\", String(parameters.count));\n\t}\n\n\tif (parameters.allOrNothing !== undefined) {\n\t\tquery.append(\"allOrNothing\", String(parameters.allOrNothing));\n\t}\n\n\tif (parameters.invisibilityWindow !== undefined) {\n\t\tquery.append(\"invisibilityWindow\", `${parameters.invisibilityWindow}s`);\n\t}\n\n\tconst queryString = query.toString();\n\tconst { queueId, universeId } = parameters;\n\tconst base = `/cloud/v2/universes/${universeId}/memory-store/queues/${queueId}/items:read`;\n\treturn {\n\t\tmethod: \"GET\",\n\t\turl: queryString === \"\" ? base : `${base}?${queryString}`,\n\t};\n}\n\n/**\n * Builds a `POST` request for the Open Cloud\n * `Cloud_DiscardMemoryStoreQueueItems` endpoint. The request body uses\n * `{ readId }`, matching the schema (the dequeue *response* uses `id`,\n * but the discard *request* matches the schema and is not patched).\n *\n * @param parameters - Universe and queue identifiers, plus the\n * `readId` returned from a prior dequeue.\n * @returns A pure {@link HttpRequest} describing the discard call.\n */\nexport function buildDiscardRequest(parameters: DiscardQueueItemsParameters): HttpRequest {\n\tconst { queueId, readId, universeId } = parameters;\n\treturn {\n\t\tbody: { readId },\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"POST\",\n\t\turl: `/cloud/v2/universes/${universeId}/memory-store/queues/${queueId}/items:discard`,\n\t};\n}\n","import type { OperationLimit } from \"../../../internal/http/rate-limit-queue.ts\";\n\nconst ENQUEUE_PER_MINUTE = 1_000_000;\nconst SECONDS_PER_MINUTE = 60;\n\n/**\n * Per-second request ceiling for enqueueing a memory-store queue item,\n * from the Open Cloud OpenAPI schema (1,000,000 requests per minute per\n * API key owner). Keyed independently from the dequeue and discard\n * operations so the three do not share a queue; upstream quota\n * accounting is documented per-operation, and the conservative default\n * is fewer cross-method contention surprises.\n */\nexport const ENQUEUE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: ENQUEUE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-queues.enqueue\",\n});\n\n/**\n * Scopes required to enqueue a memory-store queue item, sourced from\n * `x-roblox-scopes` on the `Cloud_CreateMemoryStoreQueueItem` operation\n * in the vendored OpenAPI schema.\n */\nexport const ENQUEUE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.queue:add\",\n]);\n\nconst DEQUEUE_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for dequeueing memory-store queue items,\n * from the Open Cloud OpenAPI schema (1,000,000 requests per minute\n * per API key owner). Keyed independently from enqueue and discard.\n */\nexport const DEQUEUE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: DEQUEUE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-queues.dequeue\",\n});\n\n/**\n * Scopes required to dequeue memory-store queue items, sourced from\n * `x-roblox-scopes` on the `Cloud_ReadMemoryStoreQueueItems` operation\n * in the vendored OpenAPI schema.\n */\nexport const DEQUEUE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.queue:dequeue\",\n]);\n\nconst DISCARD_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for discarding (acknowledging) memory-store\n * queue items, from the Open Cloud OpenAPI schema (1,000,000 requests\n * per minute per API key owner). Keyed independently from enqueue and\n * dequeue.\n */\nexport const DISCARD_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: DISCARD_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-queues.discard\",\n});\n\n/**\n * Scopes required to discard memory-store queue items, sourced from\n * `x-roblox-scopes` on the `Cloud_DiscardMemoryStoreQueueItems`\n * operation in the vendored OpenAPI schema.\n */\nexport const DISCARD_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.queue:discard\",\n]);\n","import type { HttpResponse } from \"../../../client/types.ts\";\nimport { ApiError } from \"../../../errors/api-error.ts\";\nimport { isDateTimeString } from \"../../../internal/utils/is-date-time-string.ts\";\nimport { isRecord } from \"../../../internal/utils/is-record.ts\";\nimport type { Result } from \"../../../types.ts\";\nimport type { DequeueResult, QueueItem } from \"./types.ts\";\nimport type { MemoryStoreQueueItemWire } from \"./wire.ts\";\n\nconst PATH_PATTERN = /^cloud\\/v2\\/universes\\/(\\d+)\\/memory-store\\/queues\\/([^/]+)\\/items\\/([^/]+)$/;\nconst MALFORMED_QUEUE_ITEM_MESSAGE = \"Malformed memory-store queue item response\";\nconst MALFORMED_DEQUEUE_MESSAGE = \"Malformed memory-store dequeue response\";\n\n/**\n * Parses a successful memory-store queue-item response body (the\n * `Cloud_CreateMemoryStoreQueueItem` happy path) into the public\n * {@link QueueItem} shape.\n *\n * @param response - The full {@link HttpResponse} from the Open Cloud API.\n * @returns A success result wrapping the parsed {@link QueueItem}, or an\n * {@link ApiError} when the body does not match the wire schema.\n */\nexport function parseQueueItemResponse(response: HttpResponse): Result<QueueItem, ApiError> {\n\tconst item = wireBodyToQueueItem(response.body);\n\tif (item === undefined) {\n\t\treturn malformedQueueItem(response.status);\n\t}\n\n\treturn { data: item, success: true };\n}\n\n/**\n * Parses a successful `Cloud_ReadMemoryStoreQueueItems` response body\n * into the public {@link DequeueResult} shape. Each item in the\n * `queueItems` array is validated through the same path-and-shape\n * checks as {@link parseQueueItemResponse}; a malformed entry rejects\n * the whole response.\n *\n * @param response - The full {@link HttpResponse} from the Open Cloud API.\n * @returns A success result wrapping the parsed {@link DequeueResult},\n * or an {@link ApiError} when the response shape is wrong.\n */\nexport function parseDequeueResponse(response: HttpResponse): Result<DequeueResult, ApiError> {\n\tconst { body, status: statusCode } = response;\n\tif (!isRecord(body)) {\n\t\treturn malformedDequeue(statusCode);\n\t}\n\n\tconst { id, queueItems } = body;\n\tif (typeof id !== \"string\") {\n\t\treturn malformedDequeue(statusCode);\n\t}\n\n\tif (queueItems !== undefined && queueItems !== null && !Array.isArray(queueItems)) {\n\t\treturn malformedDequeue(statusCode);\n\t}\n\n\tconst rawItems = queueItems ?? [];\n\tconst items = rawItems.map(wireBodyToQueueItem);\n\tif (!items.every(isQueueItem)) {\n\t\treturn malformedDequeue(statusCode);\n\t}\n\n\treturn { data: { items, readId: id }, success: true };\n}\n\nfunction isQueueItemWire(body: unknown): body is MemoryStoreQueueItemWire {\n\tif (!isRecord(body)) {\n\t\treturn false;\n\t}\n\n\tconst { data, expireTime, path, priority } = body;\n\treturn (\n\t\ttypeof path === \"string\" &&\n\t\tisDateTimeString(expireTime) &&\n\t\tdata !== undefined &&\n\t\tdata !== null &&\n\t\t(priority === undefined || priority === null || typeof priority === \"number\")\n\t);\n}\n\nfunction wireBodyToQueueItem(body: unknown): QueueItem | undefined {\n\tif (!isQueueItemWire(body)) {\n\t\treturn undefined;\n\t}\n\n\tconst match = PATH_PATTERN.exec(body.path);\n\tconst universeId = match?.[1];\n\tconst queueId = match?.[2];\n\tconst id = match?.[3];\n\tif (universeId === undefined || queueId === undefined || id === undefined) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tid,\n\t\tdata: body.data,\n\t\texpiresAt: new Date(body.expireTime),\n\t\tpriority: body.priority ?? undefined,\n\t\tqueueId,\n\t\tuniverseId,\n\t};\n}\n\nfunction malformedQueueItem(statusCode: number): Result<QueueItem, ApiError> {\n\treturn {\n\t\terr: new ApiError(MALFORMED_QUEUE_ITEM_MESSAGE, { statusCode }),\n\t\tsuccess: false,\n\t};\n}\n\nfunction isQueueItem(item: QueueItem | undefined): item is QueueItem {\n\treturn item !== undefined;\n}\n\nfunction malformedDequeue(statusCode: number): Result<DequeueResult, ApiError> {\n\treturn {\n\t\terr: new ApiError(MALFORMED_DEQUEUE_MESSAGE, { statusCode }),\n\t\tsuccess: false,\n\t};\n}\n","import type { OpenCloudClientOptions, RequestOptions } from \"../../client/types.ts\";\nimport {\n\tbuildDequeueRequest,\n\tbuildDiscardRequest,\n\tbuildEnqueueRequest,\n} from \"../../domains/cloud-v2/memory-store-queues/builders.ts\";\nimport {\n\tDEQUEUE_OPERATION_LIMIT,\n\tDEQUEUE_REQUIRED_SCOPES,\n\tDISCARD_OPERATION_LIMIT,\n\tDISCARD_REQUIRED_SCOPES,\n\tENQUEUE_OPERATION_LIMIT,\n\tENQUEUE_REQUIRED_SCOPES,\n} from \"../../domains/cloud-v2/memory-store-queues/operations.ts\";\nimport {\n\tparseDequeueResponse,\n\tparseQueueItemResponse,\n} from \"../../domains/cloud-v2/memory-store-queues/parsers.ts\";\nimport type {\n\tDequeueQueueItemsParameters,\n\tDequeueResult,\n\tDiscardQueueItemsParameters,\n\tEnqueueQueueItemParameters,\n\tQueueItem,\n} from \"../../domains/cloud-v2/memory-store-queues/types.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { CREATE_METHOD_DEFAULTS, IDEMPOTENT_METHOD_DEFAULTS } from \"../../internal/http/retry.ts\";\nimport {\n\tokRequest,\n\tparseEmptyResponse,\n\ttype ResourceClient,\n\ttype ResourceMethodSpec,\n} from \"../../internal/resource-client.ts\";\nimport type { Result } from \"../../types.ts\";\n\nfunction makeSpec<P, R>(spec: ResourceMethodSpec<P, R>): ResourceMethodSpec<P, R> {\n\treturn Object.freeze(spec);\n}\n\nconst ENQUEUE_SPEC = makeSpec<EnqueueQueueItemParameters, QueueItem>({\n\tbuildRequest: (parameters) => okRequest(buildEnqueueRequest(parameters)),\n\tmethodDefaults: CREATE_METHOD_DEFAULTS,\n\tmethodKind: \"create\",\n\toperationLimit: ENQUEUE_OPERATION_LIMIT,\n\tparse: parseQueueItemResponse,\n\trequiredScopes: ENQUEUE_REQUIRED_SCOPES,\n});\n\n// Dequeue uses HTTP GET but mutates server state via the invisibility\n// window. Retrying a 5xx where the server set invisibility before\n// failing the response would lose the original batch (it stays\n// invisible until the window elapses) and return a different one. So\n// the retry policy mirrors `create`: only 429, never 5xx.\nconst DEQUEUE_SPEC = makeSpec<DequeueQueueItemsParameters, DequeueResult>({\n\tbuildRequest: (parameters) => okRequest(buildDequeueRequest(parameters)),\n\tmethodDefaults: CREATE_METHOD_DEFAULTS,\n\tmethodKind: \"create\",\n\toperationLimit: DEQUEUE_OPERATION_LIMIT,\n\tparse: parseDequeueResponse,\n\trequiredScopes: DEQUEUE_REQUIRED_SCOPES,\n});\n\nconst DISCARD_SPEC = makeSpec<DiscardQueueItemsParameters, undefined>({\n\tbuildRequest: (parameters) => okRequest(buildDiscardRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: DISCARD_OPERATION_LIMIT,\n\tparse: parseEmptyResponse,\n\trequiredScopes: DISCARD_REQUIRED_SCOPES,\n});\n\n/**\n * Operation Group on `StorageClient` that exposes the memory-store\n * queue endpoints. Queues are FIFO collections of opaque JSON values\n * with optional priority and TTL; consumers enqueue items, dequeue\n * them in batches, and acknowledge processed batches with a read\n * identifier.\n */\nexport class MemoryStoreQueuesGroup {\n\treadonly #inner: ResourceClient;\n\n\t/**\n\t * Wraps the shared {@link ResourceClient} so the Operation Group\n\t * routes calls through the same retry, hooks, and rate-limit queues\n\t * as the rest of the parent client.\n\t *\n\t * @param inner - The shared {@link ResourceClient} owned by the\n\t * parent client.\n\t */\n\tconstructor(inner: ResourceClient) {\n\t\tthis.#inner = inner;\n\t}\n\n\t/**\n\t * Dequeues up to `count` items from the front of the queue. Items\n\t * returned become invisible to subsequent reads for\n\t * `invisibilityWindow` seconds (default 30 server-side); they\n\t * reappear once the window elapses unless acknowledged via\n\t * `discard` with the returned `readId`.\n\t *\n\t * On 5xx, dequeue does not retry: the server may have set\n\t * invisibility on a batch before the response failed, so a retry\n\t * would return a *different* batch and the first one is lost until\n\t * the window expires. Callers that can detect duplicates externally\n\t * may opt back into 5xx retry per call by passing `retryableStatuses`\n\t * on `options`.\n\t *\n\t * @param parameters - Universe and queue identifiers, plus optional\n\t * `count`, `allOrNothing`, and `invisibilityWindow`.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping the parsed {@link DequeueResult}\n\t * or the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async dequeue(\n\t\tparameters: DequeueQueueItemsParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<DequeueResult, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: DEQUEUE_SPEC });\n\t}\n\n\t/**\n\t * Acknowledges a dequeued batch of items, removing them from the\n\t * queue permanently. Pass the `readId` returned from the prior\n\t * `dequeue` call. Without `discard`, the items reappear once the\n\t * invisibility window elapses.\n\t *\n\t * The call is idempotent: a second `discard` with the same `readId`\n\t * is a no-op once the batch has been acknowledged. The retry policy\n\t * therefore retries both 429 and 5xx.\n\t *\n\t * @param parameters - Universe and queue identifiers, plus the\n\t * `readId` returned from a prior dequeue.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping `undefined` on success (the\n\t * server returns an empty body) or the {@link OpenCloudError}\n\t * that caused the request to fail.\n\t */\n\tpublic async discard(\n\t\tparameters: DiscardQueueItemsParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<undefined, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: DISCARD_SPEC });\n\t}\n\n\t/**\n\t * Enqueues a single item onto a memory-store queue. The queue is\n\t * auto-created on first use; the queue identifier is any string the\n\t * caller picks. Items with higher `priority` values are dequeued\n\t * first; equal priorities preserve insertion order. Items expire\n\t * and are removed automatically after `ttl` seconds, or after a\n\t * server-default lifetime when omitted.\n\t *\n\t * @param parameters - Universe and queue identifiers, the opaque\n\t * payload, and optional `priority` and `ttl`.\n\t * @param options - Optional per-request overrides (e.g. A different\n\t * {@link OpenCloudClientOptions.apiKey} for this call only).\n\t * @returns A {@link Result} wrapping the parsed {@link QueueItem} or\n\t * the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async enqueue(\n\t\tparameters: EnqueueQueueItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<QueueItem, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: ENQUEUE_SPEC });\n\t}\n}\n","import type { HttpRequest } from \"../../../client/types.ts\";\nimport type {\n\tCreateSortedMapItemParameters,\n\tDeleteSortedMapItemParameters,\n\tGetSortedMapItemParameters,\n\tListSortedMapItemsParameters,\n\tSortKey,\n\tUpdateSortedMapItemParameters,\n} from \"./types.ts\";\n\n/**\n * Builds a `POST` request for the Open Cloud\n * `Cloud_CreateMemoryStoreSortedMapItem` endpoint. The caller-supplied\n * `itemId` travels as the `id` query parameter (URL-encoded by\n * `URLSearchParams`); the body carries `value`, the optional `ttl`\n * (serialized as a Google protobuf `Duration` string in seconds), and\n * one of `stringSortKey`/`numericSortKey` projected from the\n * {@link SortKey} discriminated union.\n *\n * @param parameters - Universe, sorted-map, item identifiers, the\n * value to store, and optional `sortKey` and `ttl`.\n * @returns A pure {@link HttpRequest} describing the create call.\n */\nexport function buildCreateRequest(parameters: CreateSortedMapItemParameters): HttpRequest {\n\tconst { itemId, mapId, sortKey, ttl, universeId, value } = parameters;\n\tconst body: Record<string, unknown> = { value };\n\tif (ttl !== undefined) {\n\t\tbody[\"ttl\"] = `${ttl}s`;\n\t}\n\n\tapplySortKeyToBody(body, sortKey);\n\n\tconst query = new URLSearchParams({ id: itemId });\n\treturn {\n\t\tbody,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"POST\",\n\t\turl: `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items?${query.toString()}`,\n\t};\n}\n\n/**\n * Builds a `DELETE` request for the Open Cloud\n * `Cloud_DeleteMemoryStoreSortedMapItem` endpoint. Every path segment\n * (universe, sorted-map, item identifiers) is URL-encoded so callers\n * can pass values containing reserved characters without manual\n * escaping.\n *\n * @param parameters - Universe, sorted-map, and item identifiers.\n * @returns A pure {@link HttpRequest} describing the delete call.\n */\nexport function buildDeleteRequest(parameters: DeleteSortedMapItemParameters): HttpRequest {\n\tconst { itemId, mapId, universeId } = parameters;\n\treturn {\n\t\tmethod: \"DELETE\",\n\t\turl: `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items/${encodeURIComponent(itemId)}`,\n\t};\n}\n\n/**\n * Builds a `GET` request for the Open Cloud\n * `Cloud_GetMemoryStoreSortedMapItem` endpoint. Every path segment\n * (universe, sorted-map, item identifiers) is URL-encoded so callers\n * can pass values containing reserved characters without manual\n * escaping.\n *\n * @param parameters - Universe, sorted-map, and item identifiers.\n * @returns A pure {@link HttpRequest} describing the get call.\n */\nexport function buildGetRequest(parameters: GetSortedMapItemParameters): HttpRequest {\n\tconst { itemId, mapId, universeId } = parameters;\n\treturn {\n\t\tmethod: \"GET\",\n\t\turl: `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items/${encodeURIComponent(itemId)}`,\n\t};\n}\n\n/**\n * Builds a `GET` request for the Open Cloud\n * `Cloud_ListMemoryStoreSortedMapItems` endpoint. Optional `filter`,\n * `maxPageSize`, `orderBy`, and `pageToken` parameters travel as query\n * string parameters and are omitted when unset.\n *\n * @param parameters - Universe and sorted-map identifiers, plus\n * optional pagination and filter parameters.\n * @returns A pure {@link HttpRequest} describing the list call.\n */\nexport function buildListRequest(parameters: ListSortedMapItemsParameters): HttpRequest {\n\tconst { filter, mapId, maxPageSize, orderBy, pageToken, universeId } = parameters;\n\tconst query = new URLSearchParams();\n\tif (maxPageSize !== undefined) {\n\t\tquery.append(\"maxPageSize\", String(maxPageSize));\n\t}\n\n\tif (pageToken !== undefined) {\n\t\tquery.append(\"pageToken\", pageToken);\n\t}\n\n\tif (orderBy !== undefined) {\n\t\tquery.append(\"orderBy\", orderBy);\n\t}\n\n\tif (filter !== undefined) {\n\t\tquery.append(\"filter\", filter);\n\t}\n\n\tconst base = `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items`;\n\tconst queryString = query.toString();\n\treturn { method: \"GET\", url: queryString === \"\" ? base : `${base}?${queryString}` };\n}\n\n/**\n * Builds a `PATCH` request for the Open Cloud\n * `Cloud_UpdateMemoryStoreSortedMapItem` endpoint. Body fields are\n * conditionally included so a partial update sends only the changed\n * fields; the optional `allowMissing` query string drives\n * upsert-on-missing behaviour server-side.\n *\n * @param parameters - Universe, sorted-map, and item identifiers,\n * plus any subset of `value`, `ttl`, `sortKey`, and `allowMissing`.\n * @returns A pure {@link HttpRequest} describing the update call.\n */\nexport function buildUpdateRequest(parameters: UpdateSortedMapItemParameters): HttpRequest {\n\tconst { allowMissing: shouldAllowMissing, itemId, mapId, universeId } = parameters;\n\tconst base = `/cloud/v2/universes/${encodeURIComponent(universeId)}/memory-store/sorted-maps/${encodeURIComponent(mapId)}/items/${encodeURIComponent(itemId)}`;\n\tconst query = new URLSearchParams();\n\tif (shouldAllowMissing !== undefined) {\n\t\tquery.append(\"allowMissing\", String(shouldAllowMissing));\n\t}\n\n\tconst queryString = query.toString();\n\treturn {\n\t\tbody: buildUpdateBody(parameters),\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"PATCH\",\n\t\turl: queryString === \"\" ? base : `${base}?${queryString}`,\n\t};\n}\n\nfunction applySortKeyToBody(body: Record<string, unknown>, sortKey: SortKey | undefined): void {\n\tif (sortKey === undefined) {\n\t\treturn;\n\t}\n\n\tif (sortKey.kind === \"string\") {\n\t\tbody[\"stringSortKey\"] = sortKey.value;\n\t\treturn;\n\t}\n\n\tbody[\"numericSortKey\"] = sortKey.value;\n}\n\nfunction buildUpdateBody(parameters: UpdateSortedMapItemParameters): Record<string, unknown> {\n\tconst { sortKey, ttl, value } = parameters;\n\tconst body: Record<string, unknown> = {};\n\tif (value !== undefined) {\n\t\tbody[\"value\"] = value;\n\t}\n\n\tif (ttl !== undefined) {\n\t\tbody[\"ttl\"] = `${ttl}s`;\n\t}\n\n\tapplySortKeyToBody(body, sortKey);\n\treturn body;\n}\n","import type { OperationLimit } from \"../../../internal/http/rate-limit-queue.ts\";\n\nconst CREATE_PER_MINUTE = 1_000_000;\nconst SECONDS_PER_MINUTE = 60;\n\nconst WRITE_SCOPE = \"memory-store.sorted-map:write\";\n\n/**\n * Per-second request ceiling for creating a memory-store sorted-map\n * item, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner). Keyed independently from the get, update,\n * delete, and list operations so the five do not share a queue.\n */\nexport const CREATE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: CREATE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.create\",\n});\n\n/**\n * Scopes required to create a memory-store sorted-map item, sourced\n * from `x-roblox-scopes` on the `Cloud_CreateMemoryStoreSortedMapItem`\n * operation in the vendored OpenAPI schema.\n */\nexport const CREATE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([WRITE_SCOPE]);\n\nconst DELETE_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for deleting a memory-store sorted-map\n * item, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner).\n */\nexport const DELETE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: DELETE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.delete\",\n});\n\n/**\n * Scopes required to delete a memory-store sorted-map item, sourced\n * from `x-roblox-scopes` on the `Cloud_DeleteMemoryStoreSortedMapItem`\n * operation in the vendored OpenAPI schema.\n */\nexport const DELETE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([WRITE_SCOPE]);\n\nconst GET_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for reading a memory-store sorted-map\n * item, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner).\n */\nexport const GET_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: GET_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.get\",\n});\n\n/**\n * Scopes required to read a memory-store sorted-map item, sourced from\n * `x-roblox-scopes` on the `Cloud_GetMemoryStoreSortedMapItem`\n * operation in the vendored OpenAPI schema.\n */\nexport const GET_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.sorted-map:read\",\n]);\n\nconst LIST_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for listing memory-store sorted-map\n * items, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner).\n */\nexport const LIST_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: LIST_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.list\",\n});\n\n/**\n * Scopes required to list memory-store sorted-map items, sourced from\n * `x-roblox-scopes` on the `Cloud_ListMemoryStoreSortedMapItems`\n * operation in the vendored OpenAPI schema.\n */\nexport const LIST_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([\n\t\"memory-store.sorted-map:read\",\n]);\n\nconst UPDATE_PER_MINUTE = 1_000_000;\n\n/**\n * Per-second request ceiling for updating a memory-store sorted-map\n * item, from the Open Cloud OpenAPI schema (1,000,000 requests per\n * minute per API key owner).\n */\nexport const UPDATE_OPERATION_LIMIT: OperationLimit = Object.freeze({\n\tmaxPerSecond: UPDATE_PER_MINUTE / SECONDS_PER_MINUTE,\n\toperationKey: \"memory-store-sorted-maps.update\",\n});\n\n/**\n * Scopes required to update a memory-store sorted-map item, sourced\n * from `x-roblox-scopes` on the `Cloud_UpdateMemoryStoreSortedMapItem`\n * operation in the vendored OpenAPI schema.\n */\nexport const UPDATE_REQUIRED_SCOPES: ReadonlyArray<string> = Object.freeze([WRITE_SCOPE]);\n","import type { HttpResponse } from \"../../../client/types.ts\";\nimport { ApiError } from \"../../../errors/api-error.ts\";\nimport { isDateTimeString } from \"../../../internal/utils/is-date-time-string.ts\";\nimport { isRecord } from \"../../../internal/utils/is-record.ts\";\nimport type { Result } from \"../../../types.ts\";\nimport type { ListSortedMapItemsResult, SortedMapItem, SortKey } from \"./types.ts\";\nimport type { MemoryStoreSortedMapItemWire } from \"./wire.ts\";\n\nconst PATH_PATTERN =\n\t/^cloud\\/v2\\/universes\\/(\\d+)\\/memory-stores?\\/sorted-maps\\/([^/]+)\\/items\\/([^/]+)$/;\nconst MALFORMED_MESSAGE = \"Malformed memory-store sorted-map item response\";\nconst MALFORMED_LIST_MESSAGE = \"Malformed memory-store sorted-map list response\";\n\n/**\n * Parses a successful memory-store sorted-map item response body (the\n * happy path for create, get, and update) into the public\n * {@link SortedMapItem} shape.\n *\n * @param response - The full {@link HttpResponse} from the Open Cloud API.\n * @returns A success result wrapping the parsed {@link SortedMapItem},\n * or an {@link ApiError} when the body does not match the wire schema.\n */\nexport function parseSortedMapItemResponse(\n\tresponse: HttpResponse,\n): Result<SortedMapItem, ApiError> {\n\tconst item = wireBodyToSortedMapItem(response.body);\n\tif (item === undefined) {\n\t\treturn malformedSortedMapItem(response.status);\n\t}\n\n\treturn { data: item, success: true };\n}\n\n/**\n * Parses a successful `Cloud_ListMemoryStoreSortedMapItems` response\n * body into the public {@link ListSortedMapItemsResult} shape. Each\n * item in the `items` array is validated through the same\n * path-and-shape checks as {@link parseSortedMapItemResponse}; a\n * malformed entry rejects the whole response.\n *\n * @param response - The full {@link HttpResponse} from the Open Cloud API.\n * @returns A success result wrapping the parsed\n * {@link ListSortedMapItemsResult}, or an {@link ApiError} when the\n * response shape is wrong.\n */\nexport function parseListResponse(\n\tresponse: HttpResponse,\n): Result<ListSortedMapItemsResult, ApiError> {\n\tconst { body, status: statusCode } = response;\n\tif (!isRecord(body)) {\n\t\treturn malformedList(statusCode);\n\t}\n\n\tconst { items: rawItemsField, nextPageToken } = body;\n\tif (rawItemsField !== undefined && rawItemsField !== null && !Array.isArray(rawItemsField)) {\n\t\treturn malformedList(statusCode);\n\t}\n\n\tconst normalizedToken = nextPageToken ?? undefined;\n\tif (normalizedToken !== undefined && typeof normalizedToken !== \"string\") {\n\t\treturn malformedList(statusCode);\n\t}\n\n\tconst rawItems = rawItemsField ?? [];\n\tconst items = rawItems.map(wireBodyToSortedMapItem);\n\tif (!items.every(isSortedMapItem)) {\n\t\treturn malformedList(statusCode);\n\t}\n\n\treturn { data: { items, nextPageToken: normalizedToken }, success: true };\n}\n\nfunction isSortedMapItemWire(body: unknown): body is MemoryStoreSortedMapItemWire {\n\tif (!isRecord(body)) {\n\t\treturn false;\n\t}\n\n\tconst { id, etag, expireTime, numericSortKey, path, stringSortKey, value } = body;\n\treturn (\n\t\ttypeof path === \"string\" &&\n\t\ttypeof etag === \"string\" &&\n\t\ttypeof id === \"string\" &&\n\t\tisDateTimeString(expireTime) &&\n\t\tvalue !== undefined &&\n\t\t(stringSortKey === undefined ||\n\t\t\tstringSortKey === null ||\n\t\t\ttypeof stringSortKey === \"string\") &&\n\t\t(numericSortKey === undefined ||\n\t\t\tnumericSortKey === null ||\n\t\t\ttypeof numericSortKey === \"number\")\n\t);\n}\n\nfunction extractSortKey(body: MemoryStoreSortedMapItemWire): \"conflict\" | SortKey | undefined {\n\tconst hasStringKey = typeof body.stringSortKey === \"string\";\n\tconst hasNumericKey = typeof body.numericSortKey === \"number\";\n\tif (hasStringKey && hasNumericKey) {\n\t\treturn \"conflict\";\n\t}\n\n\tif (hasStringKey) {\n\t\treturn { kind: \"string\", value: body.stringSortKey };\n\t}\n\n\tif (hasNumericKey) {\n\t\treturn { kind: \"numeric\", value: body.numericSortKey };\n\t}\n\n\treturn undefined;\n}\n\nfunction wireBodyToSortedMapItem(body: unknown): SortedMapItem | undefined {\n\tif (!isSortedMapItemWire(body)) {\n\t\treturn undefined;\n\t}\n\n\t// Item ids round-trip URL-encoded in `path` (e.g. `name::id` arrives\n\t// as `name%3A%3Aid`), so the decoded id is read from `body.id` rather\n\t// than the regex group.\n\tconst match = PATH_PATTERN.exec(body.path);\n\tconst universeId = match?.[1];\n\tconst mapId = match?.[2];\n\tif (universeId === undefined || mapId === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst sortKey = extractSortKey(body);\n\tif (sortKey === \"conflict\") {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tid: body.id,\n\t\tetag: body.etag,\n\t\texpiresAt: new Date(body.expireTime),\n\t\tmapId,\n\t\tsortKey,\n\t\tuniverseId,\n\t\tvalue: body.value,\n\t};\n}\n\nfunction malformedSortedMapItem(statusCode: number): Result<SortedMapItem, ApiError> {\n\treturn {\n\t\terr: new ApiError(MALFORMED_MESSAGE, { statusCode }),\n\t\tsuccess: false,\n\t};\n}\n\nfunction isSortedMapItem(item: SortedMapItem | undefined): item is SortedMapItem {\n\treturn item !== undefined;\n}\n\nfunction malformedList(statusCode: number): Result<ListSortedMapItemsResult, ApiError> {\n\treturn {\n\t\terr: new ApiError(MALFORMED_LIST_MESSAGE, { statusCode }),\n\t\tsuccess: false,\n\t};\n}\n","import type { OpenCloudClientOptions, RequestOptions } from \"../../client/types.ts\";\nimport {\n\tbuildCreateRequest,\n\tbuildDeleteRequest,\n\tbuildGetRequest,\n\tbuildListRequest,\n\tbuildUpdateRequest,\n} from \"../../domains/cloud-v2/memory-store-sorted-maps/builders.ts\";\nimport {\n\tCREATE_OPERATION_LIMIT,\n\tCREATE_REQUIRED_SCOPES,\n\tDELETE_OPERATION_LIMIT,\n\tDELETE_REQUIRED_SCOPES,\n\tGET_OPERATION_LIMIT,\n\tGET_REQUIRED_SCOPES,\n\tLIST_OPERATION_LIMIT,\n\tLIST_REQUIRED_SCOPES,\n\tUPDATE_OPERATION_LIMIT,\n\tUPDATE_REQUIRED_SCOPES,\n} from \"../../domains/cloud-v2/memory-store-sorted-maps/operations.ts\";\nimport {\n\tparseListResponse,\n\tparseSortedMapItemResponse,\n} from \"../../domains/cloud-v2/memory-store-sorted-maps/parsers.ts\";\nimport type {\n\tCreateSortedMapItemParameters,\n\tDeleteSortedMapItemParameters,\n\tGetSortedMapItemParameters,\n\tListSortedMapItemsParameters,\n\tListSortedMapItemsResult,\n\tSortedMapItem,\n\tUpdateSortedMapItemParameters,\n} from \"../../domains/cloud-v2/memory-store-sorted-maps/types.ts\";\nimport type { OpenCloudError } from \"../../errors/base.ts\";\nimport { CREATE_METHOD_DEFAULTS, IDEMPOTENT_METHOD_DEFAULTS } from \"../../internal/http/retry.ts\";\nimport {\n\tokRequest,\n\tparseEmptyResponse,\n\ttype ResourceClient,\n\ttype ResourceMethodSpec,\n} from \"../../internal/resource-client.ts\";\nimport type { Result } from \"../../types.ts\";\n\nfunction makeSpec<P, R>(spec: ResourceMethodSpec<P, R>): ResourceMethodSpec<P, R> {\n\treturn Object.freeze(spec);\n}\n\nconst CREATE_SPEC = makeSpec<CreateSortedMapItemParameters, SortedMapItem>({\n\tbuildRequest: (parameters) => okRequest(buildCreateRequest(parameters)),\n\tmethodDefaults: CREATE_METHOD_DEFAULTS,\n\tmethodKind: \"create\",\n\toperationLimit: CREATE_OPERATION_LIMIT,\n\tparse: parseSortedMapItemResponse,\n\trequiredScopes: CREATE_REQUIRED_SCOPES,\n});\n\nconst DELETE_SPEC = makeSpec<DeleteSortedMapItemParameters, undefined>({\n\tbuildRequest: (parameters) => okRequest(buildDeleteRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: DELETE_OPERATION_LIMIT,\n\tparse: parseEmptyResponse,\n\trequiredScopes: DELETE_REQUIRED_SCOPES,\n});\n\nconst GET_SPEC = makeSpec<GetSortedMapItemParameters, SortedMapItem>({\n\tbuildRequest: (parameters) => okRequest(buildGetRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: GET_OPERATION_LIMIT,\n\tparse: parseSortedMapItemResponse,\n\trequiredScopes: GET_REQUIRED_SCOPES,\n});\n\nconst LIST_SPEC = makeSpec<ListSortedMapItemsParameters, ListSortedMapItemsResult>({\n\tbuildRequest: (parameters) => okRequest(buildListRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: LIST_OPERATION_LIMIT,\n\tparse: parseListResponse,\n\trequiredScopes: LIST_REQUIRED_SCOPES,\n});\n\nconst UPDATE_SPEC = makeSpec<UpdateSortedMapItemParameters, SortedMapItem>({\n\tbuildRequest: (parameters) => okRequest(buildUpdateRequest(parameters)),\n\tmethodDefaults: IDEMPOTENT_METHOD_DEFAULTS,\n\tmethodKind: \"idempotent\",\n\toperationLimit: UPDATE_OPERATION_LIMIT,\n\tparse: parseSortedMapItemResponse,\n\trequiredScopes: UPDATE_REQUIRED_SCOPES,\n});\n\n/**\n * Operation Group on `StorageClient` that exposes the memory-store\n * sorted-map endpoints. Sorted maps are ordered collections of\n * (id, value, sortKey) triples; consumers create, read, update, list,\n * and delete items keyed by a caller-supplied identifier and ordered\n * by an optional string or numeric sort key.\n */\nexport class MemoryStoreSortedMapsGroup {\n\treadonly #inner: ResourceClient;\n\n\t/**\n\t * Wraps the shared {@link ResourceClient} so the Operation Group\n\t * routes calls through the same retry, hooks, and rate-limit queues\n\t * as the rest of the parent client.\n\t *\n\t * @param inner - The shared {@link ResourceClient} owned by the\n\t * parent client.\n\t */\n\tconstructor(inner: ResourceClient) {\n\t\tthis.#inner = inner;\n\t}\n\n\t/**\n\t * Creates a single item in a sorted map. The sorted map is\n\t * auto-created on first use; the map identifier is any string the\n\t * caller picks. Items are keyed by `itemId` (case-sensitive) and\n\t * ordered by an optional `sortKey`. Items expire and are removed\n\t * automatically after `ttl` seconds, or after a server-default\n\t * lifetime when omitted.\n\t *\n\t * On 5xx, create does not retry: Roblox Open Cloud has no\n\t * idempotency-key support, so a retry of a transient failure risks\n\t * producing a duplicate item.\n\t *\n\t * @param parameters - Universe, sorted-map, item identifiers, the\n\t * value to store, and optional `sortKey` and `ttl`.\n\t * @param options - Optional per-request overrides (e.g. A different\n\t * {@link OpenCloudClientOptions.apiKey} for this call only).\n\t * @returns A {@link Result} wrapping the parsed {@link SortedMapItem}\n\t * or the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async create(\n\t\tparameters: CreateSortedMapItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<SortedMapItem, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: CREATE_SPEC });\n\t}\n\n\t/**\n\t * Removes a single item from a sorted map. The call is idempotent:\n\t * a second `delete` against the same item is a no-op once the\n\t * server has dropped the row. The retry policy retries both 429\n\t * and 5xx.\n\t *\n\t * @param parameters - Universe, sorted-map, and item identifiers.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping `undefined` on success or the\n\t * {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async delete(\n\t\tparameters: DeleteSortedMapItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<undefined, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: DELETE_SPEC });\n\t}\n\n\t/**\n\t * Reads a single item from a sorted map. Returns the parsed\n\t * {@link SortedMapItem} with the server-recorded `etag` for use in\n\t * subsequent conditional updates (once the SDK begins emitting\n\t * `If-Match`; see the package README).\n\t *\n\t * @param parameters - Universe, sorted-map, and item identifiers.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping the parsed {@link SortedMapItem}\n\t * or the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async get(\n\t\tparameters: GetSortedMapItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<SortedMapItem, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: GET_SPEC });\n\t}\n\n\t/**\n\t * Lists items in a sorted map. The server caps `maxPageSize` at\n\t * `100` and defaults it to `1` when omitted, so callers explicitly\n\t * pass `maxPageSize` to retrieve more than a single item per page.\n\t * The `filter` parameter accepts a CEL expression on `id` and\n\t * `sortKey` (operators `<`, `>`, `&&` only).\n\t *\n\t * @param parameters - Universe and sorted-map identifiers, plus\n\t * optional pagination and filter parameters.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping the parsed\n\t * {@link ListSortedMapItemsResult} or the {@link OpenCloudError}\n\t * that caused the request to fail.\n\t */\n\tpublic async list(\n\t\tparameters: ListSortedMapItemsParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<ListSortedMapItemsResult, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: LIST_SPEC });\n\t}\n\n\t/**\n\t * Updates a sorted-map item under PATCH semantics: omitted body\n\t * fields are left unchanged on the server, supplied fields replace\n\t * their existing values. Passing `allowMissing: true` creates the\n\t * item when no row exists instead of returning 404.\n\t *\n\t * Retries 5xx because PATCH with the same body produces the same\n\t * server state.\n\t *\n\t * @param parameters - Universe, sorted-map, and item identifiers,\n\t * plus any subset of `value`, `ttl`, `sortKey`, and\n\t * `allowMissing`.\n\t * @param options - Optional per-request overrides.\n\t * @returns A {@link Result} wrapping the parsed {@link SortedMapItem}\n\t * or the {@link OpenCloudError} that caused the request to fail.\n\t */\n\tpublic async update(\n\t\tparameters: UpdateSortedMapItemParameters,\n\t\toptions?: RequestOptions,\n\t): Promise<Result<SortedMapItem, OpenCloudError>> {\n\t\treturn this.#inner.execute({ options, parameters, spec: UPDATE_SPEC });\n\t}\n}\n","import type { OpenCloudClientOptions } from \"../../client/types.ts\";\nimport { ResourceClient } from \"../../internal/resource-client.ts\";\nimport { MemoryStoreQueuesGroup } from \"./queues-group.ts\";\nimport { MemoryStoreSortedMapsGroup } from \"./sorted-maps-group.ts\";\n\n/**\n * Public client for the Roblox Open Cloud `Data and memory stores`\n * Feature. Today it covers memory-store queues via the\n * {@link StorageClient.queues} Operation Group and memory-store sorted\n * maps via the {@link StorageClient.sortedMaps} Operation Group; a\n * future data-stores Operation Group slots in as a sibling on the same\n * client.\n *\n * Every method returns a `Result` so callers handle failure\n * explicitly; no thrown error ever escapes the client.\n *\n * @since 0.1.0\n *\n * @example\n *\n * ```ts\n * import { StorageClient } from \"@bedrock-rbx/ocale/storage\";\n *\n * const client = new StorageClient({ apiKey: \"your-key\" });\n * expect(client).toBeInstanceOf(StorageClient);\n * ```\n */\nexport class StorageClient {\n\t/** Memory-store queue Operation Group. */\n\tpublic readonly queues: MemoryStoreQueuesGroup;\n\t/** Memory-store sorted-map Operation Group. */\n\tpublic readonly sortedMaps: MemoryStoreSortedMapsGroup;\n\n\t/**\n\t * Creates a new {@link StorageClient}. Configuration is frozen on\n\t * construction; per-request overrides are accepted on each method.\n\t *\n\t * @param options - Client-level configuration including the API key.\n\t */\n\tconstructor(options: OpenCloudClientOptions) {\n\t\tconst inner = new ResourceClient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