@bedrock-rbx/ocale 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +13 -1
  2. package/dist/badges.d.mts +1 -1
  3. package/dist/badges.mjs +3 -3
  4. package/dist/{polling-Bs0GDvEa.d.mts → capacity-admission-BvnJjY0S.d.mts} +53 -14
  5. package/dist/capacity-admission-BvnJjY0S.d.mts.map +1 -0
  6. package/dist/developer-products.d.mts +1 -1
  7. package/dist/developer-products.mjs +4 -4
  8. package/dist/game-passes.d.mts +1 -1
  9. package/dist/game-passes.mjs +4 -4
  10. package/dist/index.d.mts +217 -3
  11. package/dist/index.d.mts.map +1 -1
  12. package/dist/index.mjs +70 -5
  13. package/dist/index.mjs.map +1 -0
  14. package/dist/luau-execution.d.mts +39 -5
  15. package/dist/luau-execution.d.mts.map +1 -1
  16. package/dist/luau-execution.mjs +8 -13
  17. package/dist/luau-execution.mjs.map +1 -1
  18. package/dist/{rate-limit-Df55K34f.mjs → network-error-DR9FX5hb.mjs} +81 -36
  19. package/dist/network-error-DR9FX5hb.mjs.map +1 -0
  20. package/dist/places.d.mts +4 -4
  21. package/dist/places.d.mts.map +1 -1
  22. package/dist/places.mjs +8 -13
  23. package/dist/places.mjs.map +1 -1
  24. package/dist/{poll-timeout-DpEY-gAc.mjs → poll-timeout-3PXLsabj.mjs} +2 -2
  25. package/dist/{poll-timeout-DpEY-gAc.mjs.map → poll-timeout-3PXLsabj.mjs.map} +1 -1
  26. package/dist/{polling-helpers-BjFXyaOm.mjs → polling-helpers-CFuSt2O5.mjs} +349 -67
  27. package/dist/polling-helpers-CFuSt2O5.mjs.map +1 -0
  28. package/dist/{price-information-Brs8ebsh.mjs → price-information-D8BxwgTS.mjs} +2 -2
  29. package/dist/{price-information-Brs8ebsh.mjs.map → price-information-D8BxwgTS.mjs.map} +1 -1
  30. package/dist/resource-client--yYybltk.mjs +899 -0
  31. package/dist/resource-client--yYybltk.mjs.map +1 -0
  32. package/dist/resource-client-BivRq3JZ.d.mts +164 -0
  33. package/dist/resource-client-BivRq3JZ.d.mts.map +1 -0
  34. package/dist/retry-Cc4LcXYZ.mjs +1456 -0
  35. package/dist/retry-Cc4LcXYZ.mjs.map +1 -0
  36. package/dist/{retry-CdpA3z4A.d.mts → retry-DXEklFrt.d.mts} +51 -16
  37. package/dist/{retry-CdpA3z4A.d.mts.map → retry-DXEklFrt.d.mts.map} +1 -1
  38. package/dist/storage.d.mts +2 -157
  39. package/dist/storage.d.mts.map +1 -1
  40. package/dist/storage.mjs +3 -3
  41. package/dist/testing.d.mts +9 -17
  42. package/dist/testing.d.mts.map +1 -1
  43. package/dist/testing.mjs +1 -1
  44. package/dist/{types-mhEalVsR.d.mts → types-C3Egi37J.d.mts} +86 -10
  45. package/dist/types-C3Egi37J.d.mts.map +1 -0
  46. package/dist/universes.d.mts +1 -1
  47. package/dist/universes.mjs +4 -4
  48. package/dist/{validation-Cg2lBhpQ.mjs → validation-B_Zs1So2.mjs} +2 -2
  49. package/dist/{validation-Cg2lBhpQ.mjs.map → validation-B_Zs1So2.mjs.map} +1 -1
  50. package/package.json +1 -1
  51. package/dist/polling-Bs0GDvEa.d.mts.map +0 -1
  52. package/dist/polling-helpers-BjFXyaOm.mjs.map +0 -1
  53. package/dist/rate-limit-Df55K34f.mjs.map +0 -1
  54. package/dist/resource-client-DtfDWglY.mjs +0 -1177
  55. package/dist/resource-client-DtfDWglY.mjs.map +0 -1
  56. package/dist/retry-DM2-tlR8.mjs +0 -458
  57. package/dist/retry-DM2-tlR8.mjs.map +0 -1
  58. package/dist/types-mhEalVsR.d.mts.map +0 -1
@@ -0,0 +1,1456 @@
1
+ import { a as ApiError, i as markServerRetryGuidance, n as RateLimitError, r as hasServerRetryGuidance, s as OpenCloudError, t as NetworkError } from "./network-error-DR9FX5hb.mjs";
2
+ //#region src/internal/utils/try-catch.ts
3
+ /**
4
+ * Wraps a promise into a {@link Result}, catching rejections.
5
+ *
6
+ * @template T - The resolved value type.
7
+ * @param promise - The promise to wrap.
8
+ * @returns A Result containing the resolved value or the rejection error.
9
+ */
10
+ async function tryCatchAsync(promise) {
11
+ try {
12
+ return {
13
+ data: await promise,
14
+ success: true
15
+ };
16
+ } catch (err) {
17
+ return {
18
+ err: err instanceof Error ? err : new Error(String(err)),
19
+ success: false
20
+ };
21
+ }
22
+ }
23
+ //#endregion
24
+ //#region src/internal/http/diagnostics.ts
25
+ const MAX_DETAIL_LENGTH = 500;
26
+ const CONTENT_TYPE_HEADER$1 = "content-type";
27
+ const DIAGNOSTIC_HEADER_ALLOWLIST = new Set([
28
+ "cf-ray",
29
+ "server",
30
+ "via",
31
+ "x-request-id"
32
+ ]);
33
+ const DIAGNOSTIC_HEADER_PREFIX = "x-roblox-";
34
+ const RATE_LIMIT_HEADER_ALLOWLIST = new Set([
35
+ "date",
36
+ "retry-after",
37
+ "x-envoy-ratelimited",
38
+ "x-ratelimit-limit",
39
+ "x-ratelimit-remaining",
40
+ "x-ratelimit-reset",
41
+ "x-retry-after-coverage"
42
+ ]);
43
+ const TITLE_OPEN_PATTERN = /<title[^>]*>/i;
44
+ const H1_OPEN_PATTERN = /<h1[^>]*>/i;
45
+ const TAG_PATTERN = /<[^<>]*>/g;
46
+ const WHITESPACE_PATTERN = /\s+/g;
47
+ /**
48
+ * Extracts a one-line human summary from an HTML gateway error page, or returns
49
+ * `undefined` when the body is not such a page. A load balancer (HAProxy-style)
50
+ * rejects a request before it reaches Open Cloud and answers with an HTML page,
51
+ * not a JSON Open Cloud error; dumping that HTML whole is noise. The body is
52
+ * treated as HTML when the content-type is `text/html` or the trimmed body is
53
+ * tag-led (`<html`/`<!doctype html`), and the summary is taken from the
54
+ * `<title>` (falling back to the first `<h1>`), tags stripped and whitespace
55
+ * collapsed.
56
+ *
57
+ * @param contentType - The response `content-type` header, if present.
58
+ * @param rawText - The raw response body text.
59
+ * @returns The extracted summary, or `undefined` when the body is not an HTML
60
+ * gateway page (or carries no title/h1 text).
61
+ */
62
+ function extractGatewaySummary(contentType, rawText) {
63
+ if (!isHtmlBody(contentType, rawText)) return;
64
+ return firstTagText(rawText, {
65
+ close: "</title>",
66
+ open: TITLE_OPEN_PATTERN
67
+ }) ?? firstTagText(rawText, {
68
+ close: "</h1>",
69
+ open: H1_OPEN_PATTERN
70
+ });
71
+ }
72
+ /**
73
+ * Filters a lowercased header record down to the diagnostic allowlist: a few
74
+ * named escalation headers plus any `x-roblox-*` header. Keeps errors light and
75
+ * avoids retaining anything sensitive from the full response header set.
76
+ *
77
+ * @param headers - The full header record (lowercased keys).
78
+ * @returns A record containing only the allowlisted headers that were present.
79
+ */
80
+ function pickDiagnosticHeaders(headers) {
81
+ return pickHeaders(headers);
82
+ }
83
+ /**
84
+ * Filters a lowercased header record to the raw evidence useful for diagnosing
85
+ * a 429: the general diagnostic headers plus rate-limit guidance and counters.
86
+ * Values are copied without parsing so comma-joined windows remain available.
87
+ *
88
+ * @param headers - The full header record (lowercased keys).
89
+ * @returns Only allowlisted diagnostic and rate-limit headers.
90
+ */
91
+ function pickRateLimitHeaders(headers) {
92
+ return pickHeaders(headers, RATE_LIMIT_HEADER_ALLOWLIST);
93
+ }
94
+ /**
95
+ * Converts a `Headers` object to a plain record with lowercased keys.
96
+ *
97
+ * @param headers - The `Headers` instance to convert.
98
+ * @returns A record mapping lowercased header names to their values.
99
+ */
100
+ function headersToRecord(headers) {
101
+ return Object.fromEntries(headers);
102
+ }
103
+ /**
104
+ * Projects a read body to the detail carried on an error: the parsed JSON when
105
+ * it parsed, otherwise the raw text truncated to {@link MAX_DETAIL_LENGTH}.
106
+ *
107
+ * @param text - The raw response body text.
108
+ * @param parsed - The best-effort parse result from the transport's body read.
109
+ * @returns The parsed body, or the truncated raw text on a parse failure.
110
+ */
111
+ function bodyDetail(text, parsed) {
112
+ return parsed.success ? parsed.data : text.slice(0, MAX_DETAIL_LENGTH);
113
+ }
114
+ /**
115
+ * Builds the error for a 2xx response whose body could not be parsed as JSON,
116
+ * preserving the parse `cause`, the (truncated) raw body, the declared
117
+ * content-type, and the request that produced it so the failure can be
118
+ * diagnosed after the fact.
119
+ *
120
+ * The received length is on the message rather than only on the error, because
121
+ * `details` retains just the first {@link MAX_DETAIL_LENGTH} characters: for a
122
+ * body that stopped mid-token the head says nothing and the length says
123
+ * everything. A `SyntaxError` position equal to this number is a body the edge
124
+ * cut short, not one the API mis-serialized.
125
+ *
126
+ * @param args - The Response, raw body text, request context, and underlying
127
+ * parse error.
128
+ * @returns An ApiError carrying the diagnostic context.
129
+ */
130
+ function parseFailureError({ cause, context, response, text }) {
131
+ return new ApiError(`Failed to parse response body (content-type: ${response.headers.get(CONTENT_TYPE_HEADER$1) ?? "unknown"}, ${String(text.length)} chars read)`, {
132
+ cause,
133
+ details: text.slice(0, MAX_DETAIL_LENGTH),
134
+ elapsedMs: context.elapsedMs,
135
+ method: context.method,
136
+ responseHeaders: pickDiagnosticHeaders(headersToRecord(response.headers)),
137
+ statusCode: response.status,
138
+ unparsedBodyLength: text.length,
139
+ url: context.url
140
+ });
141
+ }
142
+ function firstTagText(html, tag) {
143
+ const open = tag.open.exec(html);
144
+ if (open === null) return;
145
+ const start = open.index + open[0].length;
146
+ const end = html.toLowerCase().indexOf(tag.close, start);
147
+ if (end === -1) return;
148
+ const text = html.slice(start, end).replace(TAG_PATTERN, " ").replace(WHITESPACE_PATTERN, " ").trim();
149
+ return text === "" ? void 0 : text;
150
+ }
151
+ function isHtmlBody(contentType, rawText) {
152
+ if (contentType?.toLowerCase().includes("text/html") === true) return true;
153
+ const head = rawText.trimStart().toLowerCase();
154
+ return head.startsWith("<html") || head.startsWith("<!doctype html");
155
+ }
156
+ function pickHeaders(headers, additionalAllowlist) {
157
+ const picked = {};
158
+ for (const [name, value] of Object.entries(headers)) if (DIAGNOSTIC_HEADER_ALLOWLIST.has(name) || name.startsWith(DIAGNOSTIC_HEADER_PREFIX) || additionalAllowlist?.has(name) === true) picked[name] = value;
159
+ return picked;
160
+ }
161
+ //#endregion
162
+ //#region src/internal/http/http1-dispatcher.ts
163
+ /**
164
+ * Well-known globals under which undici publishes its global dispatcher,
165
+ * newest first. The suffix is undici's own contract version: it moved from
166
+ * `.1` to `.2` in undici 8, so a future major may move it again. Both are
167
+ * probed, and {@link createHttp1Dispatcher} degrades to `undefined` when
168
+ * neither is present — which is also the Bun path, since Bun's `fetch` is not
169
+ * undici-backed and never publishes these.
170
+ */
171
+ const GLOBAL_DISPATCHER_KEYS = Object.freeze(["undici.globalDispatcher.2", "undici.globalDispatcher.1"]);
172
+ /**
173
+ * Narrow a value read off the global dispatcher to something
174
+ * `Reflect.construct` accepts. Exported so the narrowing is unit-testable: at
175
+ * the call site every rejected shape funnels into the same `undefined`, which
176
+ * makes the branch unobservable from `createHttp1Dispatcher` alone.
177
+ *
178
+ * @param value - The candidate `constructor` read off the global dispatcher.
179
+ * @returns Whether the value can be constructed.
180
+ */
181
+ function isAgentConstructor(value) {
182
+ return typeof value === "function";
183
+ }
184
+ /**
185
+ * Builds a request dispatcher that negotiates HTTP/1.1 only, by reusing the
186
+ * class of the runtime's own global dispatcher.
187
+ *
188
+ * From Node 26 (undici 8) `fetch` offers h2 in ALPN, which defeats the
189
+ * `connection: close` an upload sets: `connection` is a connection-specific
190
+ * header, so an h2 transport drops it before the wire and pools every upload
191
+ * onto one multiplexed session. One session death then fails every upload in
192
+ * flight. Constructing the same agent with `allowH2: false` restores the
193
+ * per-upload connection the directive was written for.
194
+ *
195
+ * There is no standard `fetch` option for this, so the agent is reached
196
+ * through undici's versioned global symbol and its class rather than through
197
+ * an import — which keeps the package dependency-free. The contract is
198
+ * internal, so every step is guarded: an absent symbol, a non-constructible
199
+ * value, or a constructor that throws all yield `undefined`, and the caller
200
+ * sends the request unmodified.
201
+ *
202
+ * @param scope - The object to read the global dispatcher from. Defaults to
203
+ * `globalThis`; injectable so tests need not mutate the real global.
204
+ * @returns A dispatcher restricted to HTTP/1.1, or `undefined` when this
205
+ * runtime offers no reachable one.
206
+ */
207
+ function createHttp1Dispatcher(scope = globalThis) {
208
+ for (const key of GLOBAL_DISPATCHER_KEYS) {
209
+ const dispatcher = constructHttp1(Reflect.get(scope, Symbol.for(key)));
210
+ if (dispatcher !== void 0) return dispatcher;
211
+ }
212
+ }
213
+ /**
214
+ * Reconstructs `agent`'s class with h2 disabled.
215
+ *
216
+ * Most ways `agent` can be wrong already throw: `Reflect.get` rejects a
217
+ * primitive, `null`, and an absent key, and `Reflect.construct` rejects a
218
+ * `constructor` that is not one, or that refuses the options. One shape gets
219
+ * through — a plain object, whose `constructor` is `Object`, so constructing
220
+ * it hands back the options bag. The result is therefore checked against the
221
+ * one part of undici's surface that is public and stable: a `Dispatcher`
222
+ * exposes `dispatch`.
223
+ *
224
+ * @param agent - The candidate global dispatcher; any value, since it comes
225
+ * from an undocumented global.
226
+ * @returns The new dispatcher, or `undefined` when `agent` is not an object
227
+ * whose constructor accepts undici's agent options.
228
+ */
229
+ function constructHttp1(agent) {
230
+ try {
231
+ const agentClass = Reflect.get(agent, "constructor");
232
+ if (!isAgentConstructor(agentClass)) return;
233
+ const dispatcher = Reflect.construct(agentClass, [{ allowH2: false }]);
234
+ return typeof Reflect.get(dispatcher, "dispatch") === "function" ? dispatcher : void 0;
235
+ } catch {
236
+ return;
237
+ }
238
+ }
239
+ //#endregion
240
+ //#region src/internal/http/rate-limit-sample.ts
241
+ const NON_NEGATIVE_INTEGER_PATTERN = /^\d+$/;
242
+ /**
243
+ * Reduces a comma-separated rate-limit header value (e.g. `"0, 70000"`) to a
244
+ * single non-negative integer via `combine`. Tokens are trimmed; blank,
245
+ * fractional, negative, and non-finite tokens are dropped so a stray value
246
+ * cannot corrupt the result. Returns `undefined` when the header is absent or
247
+ * has no valid tokens.
248
+ *
249
+ * @param headerValue - The raw header value, or `undefined` if missing.
250
+ * @param combine - Pairwise reducer, `Math.min` for remaining, `Math.max` for reset.
251
+ * @returns The reduced value, or `undefined`.
252
+ */
253
+ function reduceRateLimitTokens(headerValue, combine) {
254
+ if (headerValue === void 0) return;
255
+ const tokens = headerValue.split(",").map((part) => part.trim()).filter((part) => NON_NEGATIVE_INTEGER_PATTERN.test(part)).map((part) => Number(part)).filter((value) => Number.isInteger(value));
256
+ if (tokens.length === 0) return;
257
+ return tokens.reduce(combine);
258
+ }
259
+ /**
260
+ * Parses the `x-ratelimit-remaining` and `x-ratelimit-reset` response headers
261
+ * into a {@link RateLimitSample}. Each header may carry a comma-separated list
262
+ * of per-window values; `remaining` takes the smallest (most constrained) and
263
+ * `resetSeconds` takes the largest (longest wait). Returns `undefined` when
264
+ * either header is missing or has no valid non-negative integer tokens, so a
265
+ * caller can fall back to static pacing.
266
+ *
267
+ * @param headers - Response headers with lowercased keys.
268
+ * @returns The parsed sample, or `undefined` when the budget cannot be read.
269
+ */
270
+ function parseRateLimitHeaders(headers) {
271
+ const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
272
+ return Math.min(a, b);
273
+ });
274
+ const resetSeconds = reduceRateLimitTokens(headers["x-ratelimit-reset"], (a, b) => {
275
+ return Math.max(a, b);
276
+ });
277
+ if (remaining === void 0 || resetSeconds === void 0) return;
278
+ return {
279
+ remaining,
280
+ resetSeconds
281
+ };
282
+ }
283
+ //#endregion
284
+ //#region src/internal/http/retry-guidance.ts
285
+ const ABBREVIATED_WEEKDAYS = [
286
+ "Sun",
287
+ "Mon",
288
+ "Tue",
289
+ "Wed",
290
+ "Thu",
291
+ "Fri",
292
+ "Sat"
293
+ ];
294
+ const ANSI_DATE_PATTERN = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d{2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/;
295
+ const DELAY_SECONDS_PATTERN = /^\d+$/;
296
+ const FIXED_DATE_PATTERN = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
297
+ const FULL_WEEKDAY_TO_ABBREVIATED = {
298
+ Friday: "Fri",
299
+ Monday: "Mon",
300
+ Saturday: "Sat",
301
+ Sunday: "Sun",
302
+ Thursday: "Thu",
303
+ Tuesday: "Tue",
304
+ Wednesday: "Wed"
305
+ };
306
+ const MONTHS = [
307
+ "Jan",
308
+ "Feb",
309
+ "Mar",
310
+ "Apr",
311
+ "May",
312
+ "Jun",
313
+ "Jul",
314
+ "Aug",
315
+ "Sep",
316
+ "Oct",
317
+ "Nov",
318
+ "Dec"
319
+ ];
320
+ const OBSOLETE_DATE_PATTERN = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
321
+ /**
322
+ * Parses `x-ratelimit-reset` as seconds until quota replenishment. Roblox can
323
+ * report multiple comma-separated windows; the longest valid window is the
324
+ * earliest safe quota retry.
325
+ *
326
+ * @param headerValue - The raw reset value, or `undefined` if missing.
327
+ * @returns The longest reset delay, or `undefined` when absent or invalid.
328
+ */
329
+ function parseQuotaResetSeconds(headerValue) {
330
+ return reduceRateLimitTokens(headerValue, (a, b) => Math.max(a, b));
331
+ }
332
+ /**
333
+ * Parses the standard `Retry-After` header. RFC 9110 permits either a
334
+ * non-negative integer number of seconds or any HTTP-date form. A date is
335
+ * rounded up so a retry never starts before the server's stated instant.
336
+ *
337
+ * @param headerValue - The raw `Retry-After` value, or `undefined` if missing.
338
+ * @param nowMs - Current Unix time in milliseconds, injectable for tests.
339
+ * @returns The delay in seconds, or `undefined` when absent or invalid.
340
+ */
341
+ function parseRetryAfterSeconds(headerValue, nowMs = Date.now()) {
342
+ if (headerValue === void 0) return;
343
+ const value = headerValue.trim();
344
+ if (DELAY_SECONDS_PATTERN.test(value)) {
345
+ const seconds = Number(value);
346
+ return Number.isFinite(seconds) ? seconds : void 0;
347
+ }
348
+ const retryAt = parseHttpDate(value, nowMs);
349
+ return retryAt === void 0 ? void 0 : Math.max(0, Math.ceil((retryAt - nowMs) / 1e3));
350
+ }
351
+ /**
352
+ * Chooses the applicable server-directed delay for one 429 response.
353
+ *
354
+ * @param options - Response headers, remaining quota, and optional clock.
355
+ * @returns The delay in seconds, or `undefined` when caller backoff applies.
356
+ */
357
+ function resolveRetryGuidance({ headers, nowMs, remaining }) {
358
+ const retryAfter = parseRetryAfterSeconds(headers["retry-after"], nowMs);
359
+ if (remaining !== 0) return retryAfter;
360
+ const quotaReset = parseQuotaResetSeconds(headers["x-ratelimit-reset"]);
361
+ return quotaReset === void 0 ? retryAfter : Math.max(retryAfter ?? 0, quotaReset);
362
+ }
363
+ function httpDateTimestamp(parts) {
364
+ if (parts.minute > 59 || parts.second > 59) return;
365
+ const date = /* @__PURE__ */ new Date(0);
366
+ date.setUTCFullYear(parts.year, parts.month, parts.day);
367
+ date.setUTCHours(parts.hour, parts.minute, parts.second, 0);
368
+ return date.getUTCDate() === parts.day && ABBREVIATED_WEEKDAYS[date.getUTCDay()] === parts.weekday ? date.getTime() : void 0;
369
+ }
370
+ function parseAnsiDate(value) {
371
+ const match = ANSI_DATE_PATTERN.exec(value);
372
+ return match === null ? void 0 : httpDateTimestamp({
373
+ day: Number(match[3]),
374
+ hour: Number(match[4]),
375
+ minute: Number(match[5]),
376
+ month: MONTHS.indexOf(String(match[2])),
377
+ second: Number(match[6]),
378
+ weekday: String(match[1]),
379
+ year: Number(match[7])
380
+ });
381
+ }
382
+ function parseFixedDate(value) {
383
+ const match = FIXED_DATE_PATTERN.exec(value);
384
+ return match === null ? void 0 : httpDateTimestamp({
385
+ day: Number(match[2]),
386
+ hour: Number(match[5]),
387
+ minute: Number(match[6]),
388
+ month: MONTHS.indexOf(String(match[3])),
389
+ second: Number(match[7]),
390
+ weekday: String(match[1]),
391
+ year: Number(match[4])
392
+ });
393
+ }
394
+ function parseObsoleteDate(value, nowMs) {
395
+ const match = OBSOLETE_DATE_PATTERN.exec(value);
396
+ if (match === null) return;
397
+ const currentYear = new Date(nowMs).getUTCFullYear();
398
+ let year = Math.floor(currentYear / 100) * 100 + Number(match[4]);
399
+ if (year > currentYear + 50) year -= 100;
400
+ return httpDateTimestamp({
401
+ day: Number(match[2]),
402
+ hour: Number(match[5]),
403
+ minute: Number(match[6]),
404
+ month: MONTHS.indexOf(String(match[3])),
405
+ second: Number(match[7]),
406
+ weekday: String(FULL_WEEKDAY_TO_ABBREVIATED[String(match[1])]),
407
+ year
408
+ });
409
+ }
410
+ function parseHttpDate(value, nowMs) {
411
+ return parseFixedDate(value) ?? parseObsoleteDate(value, nowMs) ?? parseAnsiDate(value);
412
+ }
413
+ //#endregion
414
+ //#region src/internal/http/rate-limit-response.ts
415
+ /**
416
+ * Builds a public rate-limit error from a 429 response and its already-read
417
+ * body, retaining safe raw evidence alongside the existing parsed guidance.
418
+ *
419
+ * @param response - The 429 response to classify.
420
+ * @param details - The parsed or safely truncated response body.
421
+ * @returns A rate-limit error carrying the response evidence.
422
+ */
423
+ function createRateLimitError(response, details) {
424
+ const headers = headersToRecord(response.headers);
425
+ const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
426
+ return Math.min(a, b);
427
+ });
428
+ const guidedRetrySeconds = resolveRetryGuidance({
429
+ headers,
430
+ remaining
431
+ });
432
+ const error = new RateLimitError("Rate limited", {
433
+ code: extractRateLimitErrorCode(details),
434
+ details,
435
+ remaining,
436
+ responseHeaders: pickRateLimitHeaders(headers),
437
+ retryAfterSeconds: guidedRetrySeconds ?? 0,
438
+ statusCode: response.status
439
+ });
440
+ return guidedRetrySeconds === void 0 ? error : markServerRetryGuidance(error);
441
+ }
442
+ function extractRateLimitErrorCode(body) {
443
+ if (body === null || typeof body !== "object") return;
444
+ const code = Reflect.get(body, "code");
445
+ return typeof code === "string" && code.trim() ? code : void 0;
446
+ }
447
+ //#endregion
448
+ //#region src/errors/request-aborted.ts
449
+ /**
450
+ * Returned when a caller's `AbortSignal` cancels an Open Cloud request.
451
+ * The reason is preserved so intentional cancellation can be distinguished
452
+ * from transport failures and SDK-owned request timeouts.
453
+ *
454
+ * @since 0.3.1
455
+ *
456
+ * @example
457
+ *
458
+ * ```ts
459
+ * import { RequestAbortedError } from "@bedrock-rbx/ocale";
460
+ *
461
+ * const error = new RequestAbortedError("Request was aborted", {
462
+ * reason: "superseded",
463
+ * });
464
+ *
465
+ * expect(error).toBeInstanceOf(RequestAbortedError);
466
+ * expect(error.reason).toBe("superseded");
467
+ * ```
468
+ */
469
+ var RequestAbortedError = class extends OpenCloudError {
470
+ name = "RequestAbortedError";
471
+ reason;
472
+ /**
473
+ * Creates a new RequestAbortedError.
474
+ *
475
+ * @param message - Human-readable description of the cancellation.
476
+ * @param options - Error options including the caller's abort reason.
477
+ */
478
+ constructor(message, options = {}) {
479
+ super(message, options);
480
+ this.reason = options.reason;
481
+ }
482
+ };
483
+ //#endregion
484
+ //#region src/internal/utils/abort.ts
485
+ /**
486
+ * Sentinel returned when an asynchronous operation loses a race with a signal.
487
+ */
488
+ const ABORTED = Symbol("aborted");
489
+ /**
490
+ * Runs an asynchronous operation and resolves with {@link ABORTED} when the
491
+ * supplied signal fires first. The underlying operation still receives the
492
+ * signal separately so cancellable implementations can release their work.
493
+ *
494
+ * @template T - Value produced by the operation.
495
+ * @param operation - Operation to start after the abort observer is installed.
496
+ * @param signal - Optional caller cancellation signal.
497
+ * @returns The operation's value, or {@link ABORTED} when cancellation wins.
498
+ * @rejects The operation's error when it fails before cancellation.
499
+ */
500
+ async function raceWithAbortAsync(operation, signal) {
501
+ if (signal === void 0) return operation();
502
+ if (signal.aborted) return ABORTED;
503
+ const { promise, resolve } = Promise.withResolvers();
504
+ function onAbort() {
505
+ resolve(ABORTED);
506
+ }
507
+ signal.addEventListener("abort", onAbort);
508
+ try {
509
+ return await Promise.race([operation(), promise]);
510
+ } finally {
511
+ signal.removeEventListener("abort", onAbort);
512
+ }
513
+ }
514
+ /**
515
+ * Creates the canonical typed failure for caller-request cancellation.
516
+ *
517
+ * @param signal - The caller signal whose reason should be preserved.
518
+ * @returns A cancellation error carrying the signal's reason.
519
+ */
520
+ function requestAbortedError(signal) {
521
+ return new RequestAbortedError("Request was aborted", { reason: signal?.reason });
522
+ }
523
+ //#endregion
524
+ //#region src/internal/http/request-signal.ts
525
+ /**
526
+ * Composes caller cancellation with Ocale's transport-attempt timeout. The
527
+ * winning signal's reason is retained by `AbortSignal.any`, allowing failure
528
+ * classification to distinguish cancellation from timeout.
529
+ *
530
+ * @param config - Transport configuration for one request.
531
+ * @returns A caller signal, timeout signal, their composition, or `undefined`.
532
+ */
533
+ function requestSignal(config) {
534
+ if (config.timeout === void 0) return config.signal;
535
+ const timeout = AbortSignal.timeout(config.timeout);
536
+ return config.signal === void 0 ? timeout : AbortSignal.any([config.signal, timeout]);
537
+ }
538
+ /**
539
+ * Classifies a fetch rejection without confusing a caller abort with the
540
+ * transport's own timeout.
541
+ *
542
+ * @param args - Failure, target, request config, and effective fetch signal.
543
+ * @returns A typed caller cancellation or network failure.
544
+ */
545
+ function requestFailure({ cause, config, effectiveSignal, target }) {
546
+ if (config.signal?.aborted === true && effectiveSignal?.aborted === true && Object.is(effectiveSignal.reason, config.signal.reason)) return requestAbortedError(config.signal);
547
+ return new NetworkError("Network request failed", {
548
+ cause,
549
+ method: target.method,
550
+ url: target.url
551
+ });
552
+ }
553
+ //#endregion
554
+ //#region src/internal/http/upload-request.ts
555
+ /**
556
+ * Reports whether a request is an upload: its body is `FormData`
557
+ * (multipart) or `Uint8Array` (raw binary). Upload latency is
558
+ * bandwidth-bound rather than compute-bound, so the SDK applies no default
559
+ * request timeout to these requests; a sensible wall-clock budget depends on
560
+ * payload size and link quality the SDK cannot know.
561
+ *
562
+ * @param request - The built request to classify.
563
+ * @returns `true` when the body is `FormData` or `Uint8Array`.
564
+ */
565
+ function isUploadRequest(request) {
566
+ return request.body instanceof FormData || request.body instanceof Uint8Array;
567
+ }
568
+ //#endregion
569
+ //#region src/internal/http/fetch-client.ts
570
+ const CONTENT_TYPE_HEADER = "content-type";
571
+ const CONNECTION_HEADER = "connection";
572
+ /**
573
+ * Permissively extracts a machine-readable error code from a response body.
574
+ *
575
+ * Three shapes are checked, in precedence order. Modern Open Cloud responses
576
+ * use `{ errorCode: string, message: string }`; Open Cloud v2 endpoints carry
577
+ * the canonical status in `error` (`{ error: "NOT_FOUND", message: string }`);
578
+ * the legacy game-internationalization endpoints use
579
+ * `{ errors: [{ code: number, message: string }, ...] }`. Numeric legacy codes
580
+ * are returned as strings so callers see one consistent type.
581
+ *
582
+ * `error` is read only when it holds a string. A Google-style nested envelope
583
+ * (`{ error: { code, message, status } }`) puts an object there, and coercing
584
+ * that to a string would hand callers `"[object Object]"` as a status.
585
+ *
586
+ * @param body - The parsed response body (unknown shape).
587
+ * @returns The error code if present, otherwise `undefined`.
588
+ */
589
+ function extractErrorCode(body) {
590
+ if (body === null || typeof body !== "object") return;
591
+ const errorCode = Reflect.get(body, "errorCode");
592
+ if (typeof errorCode === "string") return errorCode;
593
+ const v2Error = Reflect.get(body, "error");
594
+ if (typeof v2Error === "string") return v2Error;
595
+ return extractLegacyCode(body);
596
+ }
597
+ /**
598
+ * Permissively extracts a human-readable error message from a response body.
599
+ *
600
+ * Modern Open Cloud responses expose `message` at the top level; the legacy
601
+ * game-internationalization endpoints nest it under `errors[0].message`.
602
+ *
603
+ * @param body - The parsed response body (unknown shape).
604
+ * @returns The message if present, otherwise `undefined`.
605
+ */
606
+ function extractErrorMessage(body) {
607
+ if (body === null || typeof body !== "object") return;
608
+ const message = Reflect.get(body, "message");
609
+ if (typeof message === "string") return message;
610
+ return extractLegacyMessage(body);
611
+ }
612
+ /**
613
+ * Joins the base URL from config with the relative path from the request.
614
+ *
615
+ * @param request - The HTTP request containing the relative URL.
616
+ * @param config - The request config containing the base URL.
617
+ * @returns The fully-qualified URL string.
618
+ */
619
+ function buildUrl(request, config) {
620
+ return `${config.baseUrl.endsWith("/") ? config.baseUrl.slice(0, -1) : config.baseUrl}${request.url}`;
621
+ }
622
+ /**
623
+ * Constructs the `RequestInit` options for a `fetch` call.
624
+ *
625
+ * @param request - The HTTP request to build options for.
626
+ * @param config - The request config containing API key and timeout.
627
+ * @returns A `RequestInit` object ready for `fetch`.
628
+ */
629
+ function buildFetchOptions(request, config) {
630
+ const headers = new Headers({ "x-api-key": config.apiKey });
631
+ const options = {
632
+ headers,
633
+ method: request.method
634
+ };
635
+ if (request.body instanceof FormData) options.body = request.body;
636
+ else if (request.body instanceof Uint8Array) {
637
+ headers.set(CONTENT_TYPE_HEADER, "application/octet-stream");
638
+ options.body = request.body;
639
+ } else if (request.body !== void 0) {
640
+ headers.set(CONTENT_TYPE_HEADER, "application/json");
641
+ options.body = JSON.stringify(request.body);
642
+ }
643
+ applyRequestHeaders(headers, request);
644
+ const signal = requestSignal(config);
645
+ if (signal !== void 0) options.signal = signal;
646
+ return options;
647
+ }
648
+ /**
649
+ * Creates an {@link HttpClient} backed by the Fetch API.
650
+ *
651
+ * @param fetchFunc - The fetch implementation to use. Defaults to `globalThis.fetch`.
652
+ * @param seams - Injectable clock and dispatcher factory, so tests need not
653
+ * depend on wall-clock time or on the runtime's global dispatcher.
654
+ * @returns An HttpClient that classifies responses into typed Results.
655
+ */
656
+ function createFetchHttpClient(fetchFunc = fetch, { createDispatcher = createHttp1Dispatcher, now = Date.now } = {}) {
657
+ const dispatcherFor = createUploadDispatcherCache(createDispatcher);
658
+ return { async request(httpRequest, config) {
659
+ return sendRequestAsync({
660
+ config,
661
+ dispatcherFor,
662
+ fetchFunc,
663
+ httpRequest,
664
+ now
665
+ });
666
+ } };
667
+ }
668
+ function readLegacyErrorEntry(body) {
669
+ const errors = Reflect.get(body, "errors");
670
+ if (!Array.isArray(errors)) return;
671
+ const [first] = errors;
672
+ if (typeof first !== "object" || first === null) return;
673
+ return first;
674
+ }
675
+ function extractLegacyCode(body) {
676
+ const first = readLegacyErrorEntry(body);
677
+ if (first === void 0) return;
678
+ const code = Reflect.get(first, "code");
679
+ if (typeof code === "string") return code;
680
+ return typeof code === "number" ? String(code) : void 0;
681
+ }
682
+ function extractLegacyMessage(body) {
683
+ const first = readLegacyErrorEntry(body);
684
+ if (first === void 0) return;
685
+ const message = Reflect.get(first, "message");
686
+ return typeof message === "string" ? message : void 0;
687
+ }
688
+ /**
689
+ * Merges the request's own headers onto the transport's, then applies the
690
+ * transport-owned connection directive. `x-api-key` is skipped so a request
691
+ * cannot override the configured credential, and the upload directive is set
692
+ * last so a request header cannot silently re-enable pooling for an upload.
693
+ *
694
+ * @param headers - The headers being built for the fetch call. Mutated.
695
+ * @param request - The request whose headers and body shape drive the merge.
696
+ */
697
+ function applyRequestHeaders(headers, request) {
698
+ const requestHeaders = request.headers ?? {};
699
+ for (const [name, value] of Object.entries(requestHeaders)) {
700
+ if (name.toLowerCase() === "x-api-key") continue;
701
+ headers.set(name, value);
702
+ }
703
+ if (isUploadRequest(request)) headers.set(CONNECTION_HEADER, "close");
704
+ }
705
+ function failureResult(args) {
706
+ return {
707
+ err: requestFailure(args),
708
+ success: false
709
+ };
710
+ }
711
+ /**
712
+ * Runs `send` and reports both its Result and how long it was in flight,
713
+ * measured with `now`. Isolated so the timing start need not sit in the request
714
+ * body ahead of the transport-failure early return.
715
+ *
716
+ * @param now - The clock used to bound the call.
717
+ * @param send - A thunk that issues the fetch.
718
+ * @returns The fetch Result and the elapsed milliseconds.
719
+ */
720
+ async function timedFetchAsync(now, send) {
721
+ const start = now();
722
+ const fetchResult = await tryCatchAsync(send());
723
+ return {
724
+ elapsedMs: Math.max(0, now() - start),
725
+ fetchResult
726
+ };
727
+ }
728
+ function formatApiErrorMessage({ code, message, status }) {
729
+ const base = `HTTP ${status}`;
730
+ if (message === void 0 && code === void 0) return base;
731
+ if (message === void 0) return `${base} (code ${code})`;
732
+ if (code === void 0) return `${base}: ${message}`;
733
+ return `${base}: ${message} (code ${code})`;
734
+ }
735
+ function createApiError(args) {
736
+ const { context, rawText, response } = args;
737
+ const { status } = response;
738
+ const headers = headersToRecord(response.headers);
739
+ const requestContext = {
740
+ elapsedMs: context.elapsedMs,
741
+ method: context.method,
742
+ responseHeaders: pickDiagnosticHeaders(headers),
743
+ statusCode: status,
744
+ url: context.url
745
+ };
746
+ const gatewaySummary = extractGatewaySummary(headers[CONTENT_TYPE_HEADER], rawText);
747
+ if (gatewaySummary !== void 0) return new ApiError(`HTTP ${status}`, {
748
+ ...requestContext,
749
+ gatewaySummary
750
+ });
751
+ const body = bodyDetail(rawText, args.parsed);
752
+ const code = extractErrorCode(body);
753
+ return new ApiError(formatApiErrorMessage({
754
+ code,
755
+ message: extractErrorMessage(body),
756
+ status
757
+ }), {
758
+ ...requestContext,
759
+ code,
760
+ details: body
761
+ });
762
+ }
763
+ /**
764
+ * Parses response text as JSON, returning the underlying `SyntaxError` on
765
+ * failure rather than throwing. The synchronous sibling of {@link
766
+ * tryCatchAsync}.
767
+ *
768
+ * @param text - The raw response body text.
769
+ * @returns A Result wrapping the parsed value, or the parse error.
770
+ */
771
+ function parseJson(text) {
772
+ try {
773
+ return {
774
+ data: JSON.parse(text),
775
+ success: true
776
+ };
777
+ } catch (err) {
778
+ return {
779
+ err: err instanceof Error ? err : new Error(String(err)),
780
+ success: false
781
+ };
782
+ }
783
+ }
784
+ /**
785
+ * Reads a response body once and parses it best-effort: an empty body is a
786
+ * successful `undefined`, otherwise the JSON parse result (which carries the
787
+ * `SyntaxError` on failure). Returns the raw `text` alongside so callers that
788
+ * need the original bytes (parse-failure diagnostics) do not re-read the
789
+ * consumed stream.
790
+ *
791
+ * @param response - The Response whose body to read.
792
+ * @returns The parse result and the raw text.
793
+ */
794
+ async function readResponseBodyAsync(response) {
795
+ const text = await response.text();
796
+ return {
797
+ parsed: text === "" ? {
798
+ data: void 0,
799
+ success: true
800
+ } : parseJson(text),
801
+ text
802
+ };
803
+ }
804
+ /**
805
+ * Classifies a fetch `Response` into a typed `Result`.
806
+ *
807
+ * The body is read once and parsed best-effort. Error responses (status >= 300)
808
+ * never require valid JSON: an error body that is not valid JSON degrades to a
809
+ * status-based {@link ApiError} carrying the raw text, and an HTML gateway page
810
+ * is summarized rather than dumped. A parse failure is only fatal on a 2xx,
811
+ * where a parseable body is part of the contract.
812
+ *
813
+ * @param response - The raw fetch Response to classify.
814
+ * @param context - The request context (method, url, elapsed time) threaded
815
+ * onto every {@link ApiError} built here, whether for an error response or
816
+ * for a 2xx whose body would not parse.
817
+ * @returns A Result containing an HttpResponse on success or an OpenCloudError on failure.
818
+ */
819
+ async function classifyResponseAsync(response, context) {
820
+ const { parsed, text } = await readResponseBodyAsync(response);
821
+ if (response.status === 429) return {
822
+ err: createRateLimitError(response, bodyDetail(text, parsed)),
823
+ success: false
824
+ };
825
+ if (response.status >= 300) return {
826
+ err: createApiError({
827
+ context,
828
+ parsed,
829
+ rawText: text,
830
+ response
831
+ }),
832
+ success: false
833
+ };
834
+ if (!parsed.success) return {
835
+ err: parseFailureError({
836
+ cause: parsed.err,
837
+ context,
838
+ response,
839
+ text
840
+ }),
841
+ success: false
842
+ };
843
+ return {
844
+ data: {
845
+ body: parsed.data,
846
+ headers: headersToRecord(response.headers),
847
+ status: response.status
848
+ },
849
+ success: true
850
+ };
851
+ }
852
+ async function sendRequestAsync({ config, dispatcherFor, fetchFunc, httpRequest, now }) {
853
+ const url = buildUrl(httpRequest, config);
854
+ const options = buildFetchOptions(httpRequest, config);
855
+ options.dispatcher = dispatcherFor(httpRequest);
856
+ const target = {
857
+ method: httpRequest.method,
858
+ url
859
+ };
860
+ const { elapsedMs, fetchResult } = await timedFetchAsync(now, async () => {
861
+ return fetchFunc(url, options);
862
+ });
863
+ if (!fetchResult.success) return failureResult({
864
+ cause: fetchResult.err,
865
+ config,
866
+ effectiveSignal: options.signal,
867
+ target
868
+ });
869
+ const context = {
870
+ elapsedMs,
871
+ method: target.method,
872
+ url: target.url
873
+ };
874
+ const classified = await tryCatchAsync(classifyResponseAsync(fetchResult.data, context));
875
+ return classified.success ? classified.data : failureResult({
876
+ cause: classified.err,
877
+ config,
878
+ effectiveSignal: options.signal,
879
+ target
880
+ });
881
+ }
882
+ /**
883
+ * Wraps a dispatcher factory in the caching policy uploads need.
884
+ *
885
+ * Resolution happens on the first upload rather than at construction: undici
886
+ * publishes its global dispatcher lazily, so before a process's first `fetch`
887
+ * there is nothing to read. A resolved dispatcher is kept, and an unresolved
888
+ * one is retried on the next upload — so a runtime that publishes late is
889
+ * still picked up, and the first request of a process, which has no pooled
890
+ * connection to lose, is safe either way.
891
+ *
892
+ * @param createDispatcher - Builds the HTTP/1.1-only transport.
893
+ * @returns A function yielding the dispatcher for a request, or `undefined`
894
+ * when the request is not an upload or no dispatcher is available.
895
+ */
896
+ function createUploadDispatcherCache(createDispatcher) {
897
+ let cached;
898
+ return (request) => {
899
+ if (!isUploadRequest(request)) return;
900
+ cached ??= createDispatcher();
901
+ return cached;
902
+ };
903
+ }
904
+ //#endregion
905
+ //#region src/errors/permission-error.ts
906
+ /**
907
+ * Thrown when the Roblox Open Cloud API returns a 401 or 403 for an operation
908
+ * whose required scopes are known. Subclass of {@link ApiError} carrying the
909
+ * scope strings the operation requires plus the operation key, so a consumer
910
+ * can name them when guiding the user to their API key settings.
911
+ *
912
+ * The scopes are what the operation needs, not a diagnosis of what the
913
+ * credential lacks: a 403 does mean the scopes fall short, but Roblox also
914
+ * answers 401 for a key that is invalid, disabled, or expired. Check
915
+ * {@link ApiError.statusCode} before wording the failure as a missing scope.
916
+ *
917
+ * @since 0.1.0
918
+ *
919
+ * @example
920
+ *
921
+ * ```ts
922
+ * import { PermissionError } from "@bedrock-rbx/ocale";
923
+ *
924
+ * const error = new PermissionError("HTTP 403", {
925
+ * operationKey: "developer-products.create",
926
+ * requiredScopes: ["creator-store-product:write"],
927
+ * statusCode: 403,
928
+ * });
929
+ *
930
+ * expect(error).toBeInstanceOf(PermissionError);
931
+ * expect(error.requiredScopes).toStrictEqual(["creator-store-product:write"]);
932
+ * expect(error.operationKey).toBe("developer-products.create");
933
+ * ```
934
+ */
935
+ var PermissionError = class extends ApiError {
936
+ name = "PermissionError";
937
+ operationKey;
938
+ requiredScopes;
939
+ /**
940
+ * Creates a new PermissionError.
941
+ *
942
+ * @param message - Human-readable error description.
943
+ * @param options - Error options including status code, the operation key,
944
+ * and the scopes the caller's credential must carry.
945
+ */
946
+ constructor(message, options) {
947
+ super(message, options);
948
+ this.operationKey = options.operationKey;
949
+ this.requiredScopes = options.requiredScopes;
950
+ }
951
+ };
952
+ //#endregion
953
+ //#region src/errors/request-deadline-exceeded.ts
954
+ /**
955
+ * Returned when a logical request cannot complete by its absolute deadline.
956
+ * Optional wait details identify an SDK-managed admission wait that was
957
+ * refused. This is distinct from caller cancellation so consumers can report
958
+ * exhausted wall-clock budget accurately.
959
+ *
960
+ * @since 0.3.2
961
+ *
962
+ * @example
963
+ *
964
+ * ```ts
965
+ * import { RequestDeadlineExceededError } from "@bedrock-rbx/ocale";
966
+ *
967
+ * const error = new RequestDeadlineExceededError("Request deadline elapsed", {
968
+ * deadlineMs: 1_000_000,
969
+ * remainingMs: 0,
970
+ * waitReason: "operation-queue",
971
+ * });
972
+ *
973
+ * expect(error.remainingMs).toBe(0);
974
+ * expect(error.waitReason).toBe("operation-queue");
975
+ * ```
976
+ */
977
+ var RequestDeadlineExceededError = class extends OpenCloudError {
978
+ /** Absolute caller-supplied deadline, as Unix epoch milliseconds. */
979
+ deadlineMs;
980
+ name = "RequestDeadlineExceededError";
981
+ /** Time left when the SDK refused or ended the wait. */
982
+ remainingMs;
983
+ /** Intended wait duration, when known. */
984
+ waitMs;
985
+ /** SDK admission mechanism whose wait could not meet the deadline. */
986
+ waitReason;
987
+ /**
988
+ * Creates a new RequestDeadlineExceededError.
989
+ *
990
+ * @param message - Human-readable description of the exhausted deadline.
991
+ * @param options - Deadline, remaining budget, and optional wait details.
992
+ */
993
+ constructor(message, options) {
994
+ super(message, options);
995
+ this.deadlineMs = options.deadlineMs;
996
+ this.remainingMs = options.remainingMs;
997
+ this.waitMs = options.waitMs;
998
+ this.waitReason = options.waitReason;
999
+ }
1000
+ };
1001
+ //#endregion
1002
+ //#region src/errors/retry-delay-exceeded.ts
1003
+ /**
1004
+ * Returned when the SDK refuses a retry delay that cannot complete before the
1005
+ * request deadline. This is distinct from cancellation so consumers can
1006
+ * report the server's stated retry time without waiting for it.
1007
+ *
1008
+ * @since 0.3.2
1009
+ *
1010
+ * @example
1011
+ *
1012
+ * ```ts
1013
+ * import { RetryDelayExceededError } from "@bedrock-rbx/ocale";
1014
+ *
1015
+ * const error = new RetryDelayExceededError("Retry delay exceeds the request deadline", {
1016
+ * deadlineMs: 1_000_000,
1017
+ * remainingMs: 495_000,
1018
+ * retryAfterMs: 1_856_000,
1019
+ * });
1020
+ *
1021
+ * expect(error.retryAfterMs).toBe(1_856_000);
1022
+ * expect(error.remainingMs).toBe(495_000);
1023
+ * ```
1024
+ */
1025
+ var RetryDelayExceededError = class extends RequestDeadlineExceededError {
1026
+ name = "RetryDelayExceededError";
1027
+ /** Computed retry delay refused by the SDK, in milliseconds. */
1028
+ retryAfterMs;
1029
+ /** Computed retry delay refused by the SDK, in seconds. */
1030
+ retryAfterSeconds;
1031
+ /**
1032
+ * Creates a new RetryDelayExceededError.
1033
+ *
1034
+ * @param message - Human-readable description of the refused retry delay.
1035
+ * @param options - Refused delay, deadline budget, and original failure.
1036
+ */
1037
+ constructor(message, options) {
1038
+ super(message, {
1039
+ ...options,
1040
+ waitMs: options.retryAfterMs,
1041
+ waitReason: "retry-delay"
1042
+ });
1043
+ this.retryAfterMs = options.retryAfterMs;
1044
+ this.retryAfterSeconds = options.retryAfterMs / 1e3;
1045
+ }
1046
+ };
1047
+ //#endregion
1048
+ //#region src/internal/utils/find-error-code.ts
1049
+ /**
1050
+ * Maximum cause-chain depth walked by {@link findErrorCode}. Caps pathological
1051
+ * self-referential or deeply nested chains; transport failures surface as
1052
+ * `NetworkError → TypeError("fetch failed") → OS Error{code}`, so three
1053
+ * levels is the expected shape and five leaves headroom.
1054
+ */
1055
+ const MAX_DEPTH = 5;
1056
+ /**
1057
+ * Walks an error's `cause` chain and returns the first node-style string
1058
+ * `code` it finds (for example `"ECONNRESET"`, `"ETIMEDOUT"`). Native `fetch`
1059
+ * surfaces a transport reset as a `NetworkError` wrapping a
1060
+ * `TypeError("fetch failed")` whose own cause carries the OS-level `code`, so
1061
+ * the code lives several links down the chain.
1062
+ *
1063
+ * @example
1064
+ *
1065
+ * ```ts
1066
+ * import { findErrorCode } from "./find-error-code";
1067
+ *
1068
+ * const root = Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" });
1069
+ * const outer = new Error("Network request failed", {
1070
+ * cause: new TypeError("fetch failed", { cause: root }),
1071
+ * });
1072
+ *
1073
+ * expect(findErrorCode(outer)).toBe("ECONNRESET");
1074
+ * ```
1075
+ *
1076
+ * @param error - The error to inspect; typically a `NetworkError`.
1077
+ * @returns The first string `code` in the chain, or `undefined` if none.
1078
+ */
1079
+ function findErrorCode(error) {
1080
+ let current = error;
1081
+ for (let depth = 0; depth < MAX_DEPTH && current instanceof Error; depth += 1) {
1082
+ const code = readCode(current);
1083
+ if (code !== void 0) return code;
1084
+ current = current.cause;
1085
+ }
1086
+ }
1087
+ function readCode(error) {
1088
+ const code = Reflect.get(error, "code");
1089
+ return typeof code === "string" ? code : void 0;
1090
+ }
1091
+ /**
1092
+ * `DOMException.name` produced when an `AbortSignal.timeout` fires. This is the
1093
+ * web-standard discriminator (stable across Node and Bun, unlike the
1094
+ * runtime-specific message) and distinguishes the SDK's own request timeout
1095
+ * from a caller-supplied cancellation, which surfaces as `"AbortError"`.
1096
+ */
1097
+ const TIMEOUT_ABORT_NAME = "TimeoutError";
1098
+ /**
1099
+ * Reports whether an error chain was produced by the SDK's own
1100
+ * `AbortSignal.timeout` self-abort. Such a `DOMException` carries a numeric
1101
+ * `code` (23), so {@link findErrorCode} (which only reads string codes)
1102
+ * cannot classify it; this walk keys on `name` instead. A caller-supplied
1103
+ * abort (`"AbortError"`) is deliberately not matched.
1104
+ *
1105
+ * @example
1106
+ *
1107
+ * ```ts
1108
+ * import { isTimeoutAbort } from "./find-error-code";
1109
+ *
1110
+ * const error = new Error("Network request failed", {
1111
+ * cause: new DOMException("timed out", "TimeoutError"),
1112
+ * });
1113
+ *
1114
+ * expect(isTimeoutAbort(error)).toBe(true);
1115
+ * expect(isTimeoutAbort(new DOMException("cancelled", "AbortError"))).toBe(false);
1116
+ * ```
1117
+ *
1118
+ * @param error - The error to inspect; typically a `NetworkError`.
1119
+ * @returns `true` when a `TimeoutError` abort sits within the cause chain.
1120
+ */
1121
+ function isTimeoutAbort(error) {
1122
+ let current = error;
1123
+ for (let depth = 0; depth < MAX_DEPTH && current instanceof Error; depth += 1) {
1124
+ if (Reflect.get(current, "name") === TIMEOUT_ABORT_NAME) return true;
1125
+ current = current.cause;
1126
+ }
1127
+ return false;
1128
+ }
1129
+ //#endregion
1130
+ //#region src/internal/http/retry.ts
1131
+ /**
1132
+ * Transient transport error codes that are safe to retry for idempotent
1133
+ * operations. Connection resets, timeouts, and DNS hiccups are recoverable on
1134
+ * a retry. A self-aborted request timeout carries no OS-level `code`, so
1135
+ * {@link shouldRetry} folds it into this set as `ETIMEDOUT` (via
1136
+ * {@link isTimeoutAbort}) for idempotent methods; create methods retry no
1137
+ * transport codes and so still never re-issue a timed-out write.
1138
+ *
1139
+ * `ERR_HTTP2_STREAM_ERROR`, `ERR_HTTP2_SESSION_ERROR`, and `UND_ERR_INFO` are
1140
+ * the same deaths as spelled by a runtime whose `fetch` negotiates HTTP/2
1141
+ * (Node 26 and later). They differ from the socket codes in one way that
1142
+ * matters: they do not prove the request went unprocessed. `UND_ERR_INFO`
1143
+ * covers both a `GOAWAY` declaring a stream was never started and a stream
1144
+ * that was fully sent, and `UND_ERR_SOCKET` can fire once a response is
1145
+ * already streaming. Retrying them is therefore justified by the operation
1146
+ * being safe to repeat, never by the request having gone unseen — which is
1147
+ * why {@link UPLOAD_METHOD_DEFAULTS}, the one write policy that includes
1148
+ * them, documents its own grounds.
1149
+ *
1150
+ * @since 0.1.0
1151
+ */
1152
+ const TRANSIENT_TRANSPORT_CODES = Object.freeze([
1153
+ "ECONNRESET",
1154
+ "ECONNREFUSED",
1155
+ "ETIMEDOUT",
1156
+ "EPIPE",
1157
+ "ENETUNREACH",
1158
+ "EHOSTDOWN",
1159
+ "EAI_AGAIN",
1160
+ "UND_ERR_SOCKET",
1161
+ "ERR_HTTP2_STREAM_ERROR",
1162
+ "ERR_HTTP2_SESSION_ERROR",
1163
+ "UND_ERR_INFO"
1164
+ ]);
1165
+ /**
1166
+ * Synthetic transport code for a response that came from an edge gateway
1167
+ * rather than Open Cloud ({@link ApiError.gatewaySummary}). Such a response
1168
+ * proves the request was rejected before any Open Cloud handler saw it, so it
1169
+ * is classified alongside {@link TRANSIENT_TRANSPORT_CODES} rather than by its
1170
+ * HTTP status: the status belongs to the gateway, not to the API, and a
1171
+ * gateway `400` says nothing about the validity of the request.
1172
+ *
1173
+ * Name it in a per-request `retryableTransportCodes` override to opt an
1174
+ * operation into (or out of) gateway-rejection retry.
1175
+ *
1176
+ * @since 0.1.2
1177
+ */
1178
+ const GATEWAY_REJECTED = "GATEWAY_REJECTED";
1179
+ /**
1180
+ * Synthetic transport code for a 2xx whose body could not be parsed as JSON
1181
+ * ({@link ApiError.unparsedBodyLength}). Open Cloud does not answer a success
1182
+ * status with a malformed document; what this failure describes in practice is
1183
+ * a body the edge delivered short, ending mid-token at exactly the length that
1184
+ * arrived. The next read is a fresh body and usually a whole one.
1185
+ *
1186
+ * Classifying it by transport code rather than by HTTP status is what makes it
1187
+ * recoverable at all: the status is a 200, which no `retryableStatuses` list
1188
+ * contains, so a status-keyed decision could only ever say "do not retry".
1189
+ *
1190
+ * Retrying is justified by the operation being safe to repeat, never by the
1191
+ * request having gone unprocessed — a 200 proves it was processed. So this code
1192
+ * is in {@link IDEMPOTENT_METHOD_DEFAULTS} only. Creates and uploads leave it
1193
+ * out: their write landed, and re-issuing it to re-read the answer would risk a
1194
+ * second resource for a response body, which is the wrong trade. A consumer who
1195
+ * can tolerate that duplicate names this code in a per-request
1196
+ * `retryableTransportCodes` override.
1197
+ *
1198
+ * @since 0.1.5
1199
+ */
1200
+ const RESPONSE_UNPARSEABLE = "RESPONSE_UNPARSEABLE";
1201
+ /**
1202
+ * Default retry policy for idempotent operations (read, list, update,
1203
+ * delete). Safe to retry on rate limits, transient server errors, and
1204
+ * transient transport failures.
1205
+ */
1206
+ const IDEMPOTENT_METHOD_DEFAULTS = Object.freeze({
1207
+ retryableStatuses: Object.freeze([
1208
+ 429,
1209
+ 500,
1210
+ 502,
1211
+ 503,
1212
+ 504
1213
+ ]),
1214
+ retryableTransportCodes: Object.freeze([...TRANSIENT_TRANSPORT_CODES, RESPONSE_UNPARSEABLE])
1215
+ });
1216
+ /**
1217
+ * Default retry policy for create operations. Retries rate limits only (no
1218
+ * 5xx and no transport-error retries) to prevent duplicate resources, since
1219
+ * Roblox Open Cloud has no idempotency-key support. Consumers who can tolerate
1220
+ * a duplicate opt in per request.
1221
+ */
1222
+ const CREATE_METHOD_DEFAULTS = Object.freeze({
1223
+ retryableStatuses: Object.freeze([429]),
1224
+ retryableTransportCodes: Object.freeze([])
1225
+ });
1226
+ /**
1227
+ * Default retry policy for upload operations (place publish and save). Keeps
1228
+ * {@link CREATE_METHOD_DEFAULTS}'s 5xx guard (a 5xx comes from Open Cloud and
1229
+ * may describe a write that partly landed), but retries transport failures:
1230
+ * {@link TRANSIENT_TRANSPORT_CODES} and {@link GATEWAY_REJECTED}.
1231
+ *
1232
+ * This is the one write policy that retries codes which do not prove the
1233
+ * request went unprocessed, and the grounds are specific to a place version:
1234
+ * Roblox dedupes identical place content, so a retry that races a publish
1235
+ * which did land returns that same version rather than creating a second one.
1236
+ * That is load-bearing, not incidental — an upload operation without content
1237
+ * dedupe would need its own allowlist.
1238
+ */
1239
+ const UPLOAD_METHOD_DEFAULTS = Object.freeze({
1240
+ ...CREATE_METHOD_DEFAULTS,
1241
+ retryableTransportCodes: Object.freeze([...TRANSIENT_TRANSPORT_CODES, GATEWAY_REJECTED])
1242
+ });
1243
+ /**
1244
+ * Default exponential backoff: 1s → 2s → 4s → 8s → 16s → 30s (capped).
1245
+ *
1246
+ * @example
1247
+ *
1248
+ * ```ts
1249
+ * import { defaultRetryDelay } from "./retry";
1250
+ *
1251
+ * expect(defaultRetryDelay(0)).toBe(1000);
1252
+ * expect(defaultRetryDelay(4)).toBe(16_000);
1253
+ * expect(defaultRetryDelay(10)).toBe(30_000);
1254
+ * ```
1255
+ *
1256
+ * @param attempt - Zero-indexed retry attempt number.
1257
+ * @returns Wait duration in milliseconds.
1258
+ */
1259
+ function defaultRetryDelay(attempt) {
1260
+ return Math.min(1e3 * 2 ** attempt, 3e4);
1261
+ }
1262
+ /**
1263
+ * Computes how long to wait before the next retry. Prefers valid server
1264
+ * guidance on a {@link RateLimitError}, including an explicit zero-second
1265
+ * delay; otherwise falls through to `retryDelay(attempt)`.
1266
+ *
1267
+ * @example
1268
+ *
1269
+ * ```ts
1270
+ * import { RateLimitError } from "../../errors/rate-limit.ts";
1271
+ * import { computeRetryWaitMs, defaultRetryDelay } from "./retry";
1272
+ *
1273
+ * const error = new RateLimitError("slow down", { retryAfterSeconds: 3 });
1274
+ *
1275
+ * expect(computeRetryWaitMs(error, { attempt: 0, retryDelay: defaultRetryDelay })).toBe(
1276
+ * 3000,
1277
+ * );
1278
+ * ```
1279
+ *
1280
+ * @example
1281
+ *
1282
+ * ```ts
1283
+ * import { ApiError } from "../../errors/api-error.ts";
1284
+ * import { computeRetryWaitMs, defaultRetryDelay } from "./retry";
1285
+ *
1286
+ * const error = new ApiError("server error", { statusCode: 503 });
1287
+ *
1288
+ * expect(computeRetryWaitMs(error, { attempt: 2, retryDelay: defaultRetryDelay })).toBe(
1289
+ * 4000,
1290
+ * );
1291
+ * ```
1292
+ *
1293
+ * @param error - The error returned by the failing request.
1294
+ * @param options - Retry attempt index and fallback delay function.
1295
+ * @returns Wait duration in milliseconds before the next attempt.
1296
+ */
1297
+ function computeRetryWaitMs(error, options) {
1298
+ if (error instanceof RateLimitError && hasServerRetryGuidance(error)) return error.retryAfterSeconds * 1e3;
1299
+ return options.retryDelay(options.attempt);
1300
+ }
1301
+ /**
1302
+ * Decides whether a failed request is eligible for retry. {@link
1303
+ * RateLimitError} (checked against 429) and {@link ApiError} (checked against
1304
+ * its `statusCode`) are retryable when their status is in `retryableStatuses`.
1305
+ * Two {@link ApiError} shapes are the exception, both checked against
1306
+ * `retryableTransportCodes` with their status never consulted: one carrying a
1307
+ * `gatewaySummary` is checked against {@link GATEWAY_REJECTED}, and one
1308
+ * carrying an `unparsedBodyLength` — a 2xx whose body would not parse —
1309
+ * against {@link RESPONSE_UNPARSEABLE}. A {@link NetworkError} is
1310
+ * retryable when its transport code ({@link findErrorCode}) is in
1311
+ * `retryableTransportCodes`. This is how transient connection resets recover.
1312
+ * A self-aborted request timeout ({@link isTimeoutAbort}) carries no transport
1313
+ * code, so it is classified as `ETIMEDOUT`: recovered for idempotent methods,
1314
+ * never for creates (whose list is empty). All other failures return `false`.
1315
+ *
1316
+ * @example
1317
+ *
1318
+ * ```ts
1319
+ * import { RateLimitError } from "../../errors/rate-limit.ts";
1320
+ * import { shouldRetry } from "./retry";
1321
+ *
1322
+ * const error = new RateLimitError("", { retryAfterSeconds: 1 });
1323
+ *
1324
+ * expect(shouldRetry(error, { retryableStatuses: [429], retryableTransportCodes: [] })).toBe(
1325
+ * true,
1326
+ * );
1327
+ * ```
1328
+ *
1329
+ * @example
1330
+ *
1331
+ * ```ts
1332
+ * import { NetworkError } from "../../errors/network-error.ts";
1333
+ * import { shouldRetry } from "./retry";
1334
+ *
1335
+ * const reset = Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" });
1336
+ * const error = new NetworkError("Network request failed", { cause: reset });
1337
+ *
1338
+ * expect(
1339
+ * shouldRetry(error, { retryableStatuses: [], retryableTransportCodes: ["ECONNRESET"] }),
1340
+ * ).toBe(true);
1341
+ * ```
1342
+ *
1343
+ * @param error - The error returned by the failing request.
1344
+ * @param config - Object carrying the retry-eligible status and transport-code lists.
1345
+ * @returns `true` if the error should be retried, `false` otherwise.
1346
+ */
1347
+ function shouldRetry(error, config) {
1348
+ if (error instanceof RateLimitError) return config.retryableStatuses.includes(429);
1349
+ if (error instanceof ApiError) {
1350
+ if (error.gatewaySummary !== void 0) return config.retryableTransportCodes.includes(GATEWAY_REJECTED);
1351
+ if (error.unparsedBodyLength !== void 0) return config.retryableTransportCodes.includes(RESPONSE_UNPARSEABLE);
1352
+ return config.retryableStatuses.includes(error.statusCode);
1353
+ }
1354
+ if (error instanceof NetworkError) {
1355
+ const code = findErrorCode(error) ?? (isTimeoutAbort(error) ? "ETIMEDOUT" : void 0);
1356
+ return code !== void 0 && config.retryableTransportCodes.includes(code);
1357
+ }
1358
+ return false;
1359
+ }
1360
+ /**
1361
+ * Resolves the effective config for a single request by shallow-merging the
1362
+ * client config, method defaults, and per-request options. Precedence depends
1363
+ * on `methodKind`:
1364
+ *
1365
+ * - `"create"`: method defaults override client config, so client-level
1366
+ * settings cannot silently relax create-method safety. Only explicit
1367
+ * per-request `requestOptions` can.
1368
+ * - `"idempotent"`: client config overrides method defaults, so consumers
1369
+ * can loosen or tighten retry policy globally. `requestOptions` still wins
1370
+ * when provided.
1371
+ *
1372
+ * Array-valued fields like `retryableStatuses` are *replaced*, not extended.
1373
+ *
1374
+ * @template T - Concrete `RetryResolvable` subtype being merged.
1375
+ *
1376
+ * @example
1377
+ *
1378
+ * ```ts
1379
+ * import {
1380
+ * CREATE_METHOD_DEFAULTS,
1381
+ * defaultRetryDelay,
1382
+ * mergeConfig,
1383
+ * type RetryResolvable,
1384
+ * } from "./retry";
1385
+ *
1386
+ * const clientConfig: RetryResolvable = {
1387
+ * apiKey: "k",
1388
+ * baseUrl: "https://apis.roblox.com",
1389
+ * maxRetries: 3,
1390
+ * retryableStatuses: [429, 500],
1391
+ * retryableTransportCodes: [],
1392
+ * retryDelay: defaultRetryDelay,
1393
+ * timeout: 30_000,
1394
+ * };
1395
+ *
1396
+ * const merged = mergeConfig(clientConfig, {
1397
+ * methodDefaults: CREATE_METHOD_DEFAULTS,
1398
+ * methodKind: "create",
1399
+ * });
1400
+ *
1401
+ * expect(merged.retryableStatuses).toStrictEqual([429]);
1402
+ * ```
1403
+ *
1404
+ * @example
1405
+ *
1406
+ * ```ts
1407
+ * import {
1408
+ * defaultRetryDelay,
1409
+ * IDEMPOTENT_METHOD_DEFAULTS,
1410
+ * mergeConfig,
1411
+ * type RetryResolvable,
1412
+ * } from "./retry";
1413
+ *
1414
+ * const clientConfig: RetryResolvable = {
1415
+ * apiKey: "k",
1416
+ * baseUrl: "https://apis.roblox.com",
1417
+ * maxRetries: 3,
1418
+ * retryableStatuses: [429],
1419
+ * retryableTransportCodes: [],
1420
+ * retryDelay: defaultRetryDelay,
1421
+ * timeout: 30_000,
1422
+ * };
1423
+ *
1424
+ * const merged = mergeConfig(clientConfig, {
1425
+ * methodDefaults: IDEMPOTENT_METHOD_DEFAULTS,
1426
+ * methodKind: "idempotent",
1427
+ * requestOptions: { timeout: 10_000 },
1428
+ * });
1429
+ *
1430
+ * expect(merged.retryableStatuses).toStrictEqual([429]);
1431
+ * expect(merged.timeout).toBe(10_000);
1432
+ * ```
1433
+ *
1434
+ * @param clientConfig - Config frozen at client construction.
1435
+ * @param options - Method defaults, method kind, and optional per-request overrides.
1436
+ * @returns A new merged config object. Inputs are not mutated.
1437
+ */
1438
+ function mergeConfig(clientConfig, { methodDefaults, methodKind, requestOptions }) {
1439
+ switch (methodKind) {
1440
+ case "create": return {
1441
+ ...clientConfig,
1442
+ ...methodDefaults,
1443
+ ...requestOptions
1444
+ };
1445
+ case "idempotent": return {
1446
+ ...methodDefaults,
1447
+ ...clientConfig,
1448
+ ...requestOptions
1449
+ };
1450
+ default: throw new Error(`Unexpected methodKind: ${String(methodKind)}`);
1451
+ }
1452
+ }
1453
+ //#endregion
1454
+ export { ABORTED as _, TRANSIENT_TRANSPORT_CODES as a, RequestAbortedError as b, defaultRetryDelay as c, findErrorCode as d, RetryDelayExceededError as f, isUploadRequest as g, createFetchHttpClient as h, RESPONSE_UNPARSEABLE as i, mergeConfig as l, PermissionError as m, GATEWAY_REJECTED as n, UPLOAD_METHOD_DEFAULTS as o, RequestDeadlineExceededError as p, IDEMPOTENT_METHOD_DEFAULTS as r, computeRetryWaitMs as s, CREATE_METHOD_DEFAULTS as t, shouldRetry as u, raceWithAbortAsync as v, parseRateLimitHeaders as x, requestAbortedError as y };
1455
+
1456
+ //# sourceMappingURL=retry-Cc4LcXYZ.mjs.map