@formless63/provider-http 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 formless63
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @formless63/provider-http
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Plumbing for API clients: safe requests, safe errors, rate budgets. No dependencies.
4
+
5
+ ```ts
6
+ import { createHttpClient, createRateBudget, kindFromStatus } from "@formless63/provider-http";
7
+
8
+ const http = createHttpClient({
9
+ provider: "Acme",
10
+ baseUrl: "https://api.acme.example/v1",
11
+ headers: { authorization: `Bearer ${token}` },
12
+ secrets: [token],
13
+ rateBudget: createRateBudget({ provider: "Acme", capacity: 5, refillPerSecond: 1 })
14
+ });
15
+
16
+ const result = await http.request({ operation: "things.list", path: "/things", query: { page: 1 } });
17
+ if (result.status !== 200) {
18
+ throw http.error({
19
+ kind: kindFromStatus(result.status),
20
+ message: `Acme refused: ${http.safeText(result.text)}`,
21
+ status: result.status,
22
+ retryAfterMs: result.retryAfterMs
23
+ });
24
+ }
25
+ const body = result.json();
26
+ ```
27
+
28
+ `request` resolves for any HTTP status and rejects only without a usable response: `timeout`, `aborted`,
29
+ `unavailable`, `rate_limited` (local budget) or `invalid_response` (a success answer that is too large). An
30
+ error answer that is too large resolves with its status and an empty `text`. Redirects are refused.
31
+
32
+ Also exported: `normalizeBaseUrl`, `isPrivateHost` (address literals outside public unicast, and local names; it does not resolve DNS),
33
+ `isLoopbackHost`,
34
+ `parseRetryAfter`, `safeProviderText`, `readBounded`, `sleep`.
35
+
36
+ `retryable` means the request might succeed later. It does not mean repeating a write is safe.
@@ -0,0 +1 @@
1
+ {"version":"7.0.2","root":[[64,68]],"packageJsons":["../package.json"],"fileNames":["lib.es5.d.ts","lib.es2015.d.ts","lib.es2016.d.ts","lib.es2017.d.ts","lib.es2018.d.ts","lib.es2019.d.ts","lib.es2020.d.ts","lib.es2021.d.ts","lib.es2022.d.ts","lib.es2023.d.ts","lib.dom.d.ts","lib.dom.iterable.d.ts","lib.es2015.core.d.ts","lib.es2015.collection.d.ts","lib.es2015.generator.d.ts","lib.es2015.iterable.d.ts","lib.es2015.promise.d.ts","lib.es2015.proxy.d.ts","lib.es2015.reflect.d.ts","lib.es2015.symbol.d.ts","lib.es2015.symbol.wellknown.d.ts","lib.es2016.array.include.d.ts","lib.es2016.intl.d.ts","lib.es2017.arraybuffer.d.ts","lib.es2017.date.d.ts","lib.es2017.object.d.ts","lib.es2017.sharedmemory.d.ts","lib.es2017.string.d.ts","lib.es2017.intl.d.ts","lib.es2017.typedarrays.d.ts","lib.es2018.asyncgenerator.d.ts","lib.es2018.asynciterable.d.ts","lib.es2018.intl.d.ts","lib.es2018.promise.d.ts","lib.es2018.regexp.d.ts","lib.es2019.array.d.ts","lib.es2019.object.d.ts","lib.es2019.string.d.ts","lib.es2019.symbol.d.ts","lib.es2019.intl.d.ts","lib.es2020.bigint.d.ts","lib.es2020.date.d.ts","lib.es2020.promise.d.ts","lib.es2020.sharedmemory.d.ts","lib.es2020.string.d.ts","lib.es2020.symbol.wellknown.d.ts","lib.es2020.intl.d.ts","lib.es2020.number.d.ts","lib.es2021.promise.d.ts","lib.es2021.string.d.ts","lib.es2021.weakref.d.ts","lib.es2021.intl.d.ts","lib.es2022.array.d.ts","lib.es2022.error.d.ts","lib.es2022.intl.d.ts","lib.es2022.object.d.ts","lib.es2022.string.d.ts","lib.es2022.regexp.d.ts","lib.es2023.array.d.ts","lib.es2023.collection.d.ts","lib.es2023.intl.d.ts","lib.decorators.d.ts","lib.decorators.legacy.d.ts","../src/errors.ts","../src/rate-budget.ts","../src/url.ts","../src/client.ts","../src/index.ts"],"fileInfos":[{"version":"16934abaab7026ac114da441aabea1a0","affectsGlobalScope":true,"impliedNodeFormat":1},"d4306fb2e47f74835e8674ffac07d76f","e437c5c1302869326c3bb93da85bbbcf","e4324975a566567b21d350615f1fc6ac","333b1b9a2a9ac3b8497dba5c63b5ba50","6cffacd662b6eb5fa7a36aa2ea366bfa","b4c34f9c23304dbef2d23698637ed638","e5cb86a5fc491796ecd1d2dd348d208f","feb6c6fb19cdb246a5d8acb36a6901c7","9443a7f109277ffaa79d893ed2549995",{"version":"aae8996e8b5684814785a42cbbefcd79","affectsGlobalScope":true,"impliedNodeFormat":1},"abad6dd56cc8caf095c165df8124d237",{"version":"926204c28cd3d073865348473ae28d2e","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"f25e42c801b2cb3cf2b39792006a9beb","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6344b55f26a4e81d9608777dbfb877dd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3c0ed28e53d3695b363e256ec1c023fd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4c2761daba7f17141c25baa0821ac5da","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b87656acabd63e69379ff6ffcfe52fc7","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"597469522da047a5af5222cc6989f405","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1708ea4d34dc37fadadc63ca01127e80","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"55d97a8c6fbf34a30450a7b1e5f7a298","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"0ee05eb59426d33e374226d8dcfa708b","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"e347c14030993906efcfbb88915b6a05","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b0231263857c9b6a03641acdc9280ceb","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3b15c4a83b598cacb4067676e6f0abed","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b417d97b7934cef63b1889abec0bbfbf","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"09a6cf4032ebba60ce22a501e663f881","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2b056277dd138e8f5650fc04e20eaa8d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"e22cc07e3f3cc242ba52fa3f8ea1fc58","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2c45da767a1bfbb220848df1bc4029e4","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b44c3e0fbaf2130cdcf6ac38b120ffa1","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b612fb5cf8e5d964b92063a75207632a","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"02705151a5e1551b9162a9ed8ab763f7","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"41025e398be9215d32e4337335da8f0b","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"52684c2b1f353a5538e4f275182a54cd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6dedb6a4f90d1df3a6fbe5693e44886c","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"ca3f36fe3562c07e0f0d71c2bebd3f6d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"409974d6129befbb8226ddd1c6558568","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4d9cfde2a1ae1b4925f1f9bc10848e5d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"7e1daecc66dd564144e3bb1a0266b5fd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a8e1d9bb35fd0637f2f9fd2b2a54f2ec","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4f168501772a6543182765bfd5f2fbfe","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a19c80aad1b2162103496f5ba293a732","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b69afa63cd5d059851c78adb2856ee09","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"ae2fc5d954e9b0f5feee3d481b953c27","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1cfd3091a071d8b6feec15277643bafe","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1da2c1f258970fd3cc91184f69e91a9d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a0d87491913d843139e0c993650a3235","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4ef72aa378127e7b7abba915b0110b1e","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3ec74c6a7d4463f0254db3a74cf75646","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"84c2bdfa470d075526cce6322d81b0b6","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"0b3844c2b8c73e4e1ab91431411cad11","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4fc71cf4a15b8d99675a31df77f26e07","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d1b49564ddaeca3df5b6dbae925d2242","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6a25be566d60ccfc2d6e8b7bfdeefa83","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8a20e27646985dfd58c57ca6566553dd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"9969f02ad3cdcbf4f709405cda44167f","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"9c9be4792a7a4f42c15ae7360bf28779","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8cf777fe00349b71ee9c4b6f3fe7fd19","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"74f96bc192530c9723f572bfff3d3078","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1df91c56b25955c56387426f378173c5","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"f64453cbf9671f28158677fa5c43967a","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"33f317af5428801f944a478d2c1e38e5","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"5349a06a02cd85c15f5996b6f019218a","signature":"beb330e63ebb8f469a1fa417cdf076f4","impliedNodeFormat":99},{"version":"458b3fab84997c53c900f8195a341dc2","signature":"916d5c1edcce2ae32520b3c6eb62d519","impliedNodeFormat":99},{"version":"dcc17f224ed1df9f39671142087467a0","signature":"7e2e5bc5318a6f096a815443ae15bc25","impliedNodeFormat":99},{"version":"f7cbdbaab3043e5f1efa7ec3014cd77d","signature":"c058e7bed755873e4703ed39e543764b","impliedNodeFormat":99},{"version":"cb426bf5a12c14db800be65b77a87c94","impliedNodeFormat":99}],"fileIdsList":[[64,65,66],[64,65,66,67],[64]],"options":{"allowImportingTsExtensions":true,"composite":true,"declaration":true,"declarationMap":true,"erasableSyntaxOnly":true,"exactOptionalPropertyTypes":true,"module":199,"noUncheckedIndexedAccess":true,"outDir":"./","rewriteRelativeImportExtensions":true,"rootDir":"../src","skipLibCheck":true,"strict":true,"sourceMap":true,"target":10,"tsBuildInfoFile":"./.tsbuildinfo","verbatimModuleSyntax":true},"referencedMap":[[67,1],[68,2],[65,3],[66,3]],"latestChangedDtsFile":"./index.d.ts"}
@@ -0,0 +1,82 @@
1
+ import { ProviderError, type ProviderErrorOptions } from './errors.ts';
2
+ import type { RateBudget } from './rate-budget.ts';
3
+ import { type BaseUrlOptions } from './url.ts';
4
+ /** The part of `fetch` this package uses. `globalThis.fetch` satisfies it. */
5
+ export type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponse>;
6
+ export interface FetchInit {
7
+ method: string;
8
+ headers: Record<string, string>;
9
+ signal: AbortSignal;
10
+ redirect: 'error' | 'manual';
11
+ body?: string;
12
+ }
13
+ export interface FetchResponse {
14
+ readonly status: number;
15
+ readonly headers?: {
16
+ get(name: string): string | null;
17
+ };
18
+ readonly body?: ReadableStream<Uint8Array> | null;
19
+ text(): Promise<string>;
20
+ }
21
+ export type QueryValue = string | number | boolean | null | undefined;
22
+ export interface HttpRequest {
23
+ /** Label for errors, e.g. `zones.list`. */
24
+ operation: string;
25
+ method?: string;
26
+ /** Appended to the base URL. Build segments with `encodeURIComponent`. */
27
+ path?: string;
28
+ query?: Record<string, QueryValue>;
29
+ headers?: Record<string, string>;
30
+ /** Sent as JSON. */
31
+ json?: unknown;
32
+ signal?: AbortSignal;
33
+ }
34
+ export interface HttpResult {
35
+ status: number;
36
+ text: string;
37
+ retryAfterMs: number | null;
38
+ header(name: string): string | null;
39
+ /** Parses the body, throwing `invalid_response` when it is not JSON. */
40
+ json(): unknown;
41
+ }
42
+ export interface HttpClientOptions extends Omit<BaseUrlOptions, 'provider'> {
43
+ provider: string;
44
+ baseUrl: string;
45
+ /** Sent on every request. Values are never placed in errors. */
46
+ headers?: Record<string, string>;
47
+ /** Credential values to strip from any provider text that reaches an error. */
48
+ secrets?: readonly string[];
49
+ fetch?: FetchLike;
50
+ timeoutMs?: number;
51
+ maxResponseBytes?: number;
52
+ rateBudget?: RateBudget;
53
+ /** Lets a package throw its own subclass. */
54
+ createError?: (options: ProviderErrorOptions) => ProviderError;
55
+ }
56
+ export interface HttpClient {
57
+ readonly provider: string;
58
+ readonly baseUrl: string;
59
+ /**
60
+ * Performs one request. Resolves for any HTTP status; throws only without a usable response. An
61
+ * oversized error answer resolves with its status and an empty `text`.
62
+ */
63
+ request(request: HttpRequest): Promise<HttpResult>;
64
+ /** Builds an error with provider text already made safe. */
65
+ error(options: Omit<ProviderErrorOptions, 'provider'>): ProviderError;
66
+ /** Strips credentials and control characters from provider text. */
67
+ safeText(text: string, maxLength?: number): string;
68
+ }
69
+ export declare const DEFAULT_TIMEOUT_MS = 20000;
70
+ export declare const DEFAULT_MAX_RESPONSE_BYTES = 5000000;
71
+ /** Rejects values that would break out of a header. */
72
+ export declare function assertHeaderSafe(provider: string, label: string, value: unknown): string;
73
+ /** Reads at most `limit` bytes, so a hostile or broken server cannot exhaust memory. */
74
+ export declare function readBounded(response: FetchResponse, limit: number): Promise<string>;
75
+ /**
76
+ * A small request function with the safety rules every provider client needs:
77
+ * redirects are refused (so credentials cannot be replayed to another origin),
78
+ * responses are size-bounded, requests time out, and nothing from the request
79
+ * or the transport error can reach a thrown message.
80
+ */
81
+ export declare function createHttpClient(options: HttpClientOptions): HttpClient;
82
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,aAAa,EAAoB,KAAK,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAC1G,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAoB,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAEjE,8EAA8E;AAC9E,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,KAAK,OAAO,CAAC,aAAa,CAAC,CAAC;AAEjF,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,MAAM,EAAE,WAAW,CAAC;IACpB,QAAQ,EAAE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191 @@
1
+ import { parseRetryAfter, ProviderError, safeProviderText } from './errors.js';
2
+ import { normalizeBaseUrl } from './url.js';
3
+ export const DEFAULT_TIMEOUT_MS = 20_000;
4
+ export const DEFAULT_MAX_RESPONSE_BYTES = 5_000_000;
5
+ /** Rejects values that would break out of a header. */
6
+ export function assertHeaderSafe(provider, label, value) {
7
+ // oxlint-disable-next-line no-control-regex
8
+ if (typeof value !== 'string' || value.trim() === '' || /[\u0000-\u001f\u007f]/.test(value)) {
9
+ throw new ProviderError({
10
+ provider,
11
+ kind: 'invalid_input',
12
+ message: `the ${provider} ${label} is missing or malformed`
13
+ });
14
+ }
15
+ return value.trim();
16
+ }
17
+ class TooLarge extends Error {
18
+ status;
19
+ }
20
+ /** Reads at most `limit` bytes, so a hostile or broken server cannot exhaust memory. */
21
+ export async function readBounded(response, limit) {
22
+ const declared = Number(response.headers?.get('content-length') ?? Number.NaN);
23
+ if (declared > limit) {
24
+ await response.body?.cancel().catch(() => undefined);
25
+ throw new TooLarge();
26
+ }
27
+ if (!response.body) {
28
+ const text = await response.text();
29
+ if (new TextEncoder().encode(text).byteLength > limit)
30
+ throw new TooLarge();
31
+ return text;
32
+ }
33
+ const reader = response.body.getReader();
34
+ const decoder = new TextDecoder();
35
+ let size = 0;
36
+ let text = '';
37
+ for (;;) {
38
+ const { done, value } = await reader.read();
39
+ if (done)
40
+ return text + decoder.decode();
41
+ size += value.byteLength;
42
+ if (size > limit) {
43
+ await reader.cancel().catch(() => undefined);
44
+ throw new TooLarge();
45
+ }
46
+ text += decoder.decode(value, { stream: true });
47
+ }
48
+ }
49
+ /** A network error code such as ECONNREFUSED. Anything else could echo a URL. */
50
+ function networkCode(error) {
51
+ for (const candidate of [error, error?.cause]) {
52
+ const code = candidate?.code;
53
+ if (typeof code === 'string' && /^[A-Z][A-Z0-9_]{2,40}$/.test(code))
54
+ return code;
55
+ }
56
+ return null;
57
+ }
58
+ function buildQuery(query) {
59
+ const params = new URLSearchParams();
60
+ for (const [key, value] of Object.entries(query ?? {})) {
61
+ if (value !== undefined && value !== null)
62
+ params.append(key, String(value));
63
+ }
64
+ const text = params.toString();
65
+ return text === '' ? '' : `?${text}`;
66
+ }
67
+ /**
68
+ * A small request function with the safety rules every provider client needs:
69
+ * redirects are refused (so credentials cannot be replayed to another origin),
70
+ * responses are size-bounded, requests time out, and nothing from the request
71
+ * or the transport error can reach a thrown message.
72
+ */
73
+ export function createHttpClient(options) {
74
+ const { provider } = options;
75
+ const baseUrl = normalizeBaseUrl(options.baseUrl, { ...options, provider });
76
+ const doFetch = options.fetch ?? ((url, init) => globalThis.fetch(url, init));
77
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
78
+ const limit = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
79
+ const secrets = options.secrets ?? [];
80
+ const makeError = options.createError ?? ((input) => new ProviderError(input));
81
+ const error = (input) => makeError({ ...input, provider });
82
+ const safeText = (text, maxLength) => safeProviderText(text, secrets, maxLength);
83
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
84
+ throw error({ kind: 'invalid_input', message: `the ${provider} timeout must be positive` });
85
+ }
86
+ return {
87
+ provider,
88
+ baseUrl,
89
+ error,
90
+ safeText,
91
+ async request(input) {
92
+ const { operation } = input;
93
+ try {
94
+ await options.rateBudget?.acquire(1, input.signal ? { signal: input.signal } : {});
95
+ }
96
+ catch (cause) {
97
+ if (cause instanceof ProviderError) {
98
+ throw error({
99
+ kind: cause.kind,
100
+ message: cause.message,
101
+ operation,
102
+ retryAfterMs: cause.retryAfterMs,
103
+ detail: cause.detail
104
+ });
105
+ }
106
+ throw cause;
107
+ }
108
+ const timeout = AbortSignal.timeout(timeoutMs);
109
+ const signal = input.signal ? AbortSignal.any([timeout, input.signal]) : timeout;
110
+ const failure = (cause) => {
111
+ if (cause instanceof TooLarge) {
112
+ return error({
113
+ kind: 'invalid_response',
114
+ message: `the ${provider} answer is too large (over ${limit} bytes)`,
115
+ status: cause.status ?? null,
116
+ operation
117
+ });
118
+ }
119
+ if (input.signal?.aborted) {
120
+ return error({ kind: 'aborted', message: `the ${provider} request was aborted`, operation });
121
+ }
122
+ if (timeout.aborted || cause?.name === 'TimeoutError') {
123
+ return error({
124
+ kind: 'timeout',
125
+ message: `${provider} did not answer within ${timeoutMs} ms`,
126
+ operation
127
+ });
128
+ }
129
+ const code = networkCode(cause);
130
+ return error({
131
+ kind: 'unavailable',
132
+ message: `${provider} could not be reached${code ? ` (${code})` : ''}`,
133
+ operation,
134
+ detail: code ? { networkCode: code } : {}
135
+ });
136
+ };
137
+ try {
138
+ signal.throwIfAborted();
139
+ const response = await doFetch(`${baseUrl}${input.path ?? ''}${buildQuery(input.query)}`, {
140
+ method: input.method ?? 'GET',
141
+ headers: {
142
+ ...(input.json === undefined ? {} : { 'content-type': 'application/json' }),
143
+ ...options.headers,
144
+ ...input.headers
145
+ },
146
+ signal,
147
+ redirect: 'error',
148
+ ...(input.json === undefined ? {} : { body: JSON.stringify(input.json) })
149
+ });
150
+ let text;
151
+ try {
152
+ text = await readBounded(response, limit);
153
+ }
154
+ catch (cause) {
155
+ // An oversized refusal still says what happened: keep its status, drop its body.
156
+ if (!(cause instanceof TooLarge))
157
+ throw cause;
158
+ if (response.status >= 200 && response.status < 300) {
159
+ cause.status = response.status;
160
+ throw cause;
161
+ }
162
+ text = '';
163
+ }
164
+ const header = (name) => response.headers?.get(name) ?? null;
165
+ return {
166
+ status: response.status,
167
+ text,
168
+ retryAfterMs: parseRetryAfter(header('retry-after')),
169
+ header,
170
+ json() {
171
+ try {
172
+ return JSON.parse(text);
173
+ }
174
+ catch {
175
+ throw error({
176
+ kind: 'invalid_response',
177
+ message: `the ${provider} answer is not JSON`,
178
+ status: response.status,
179
+ operation
180
+ });
181
+ }
182
+ }
183
+ };
184
+ }
185
+ catch (cause) {
186
+ throw failure(cause);
187
+ }
188
+ }
189
+ };
190
+ }
191
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {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gBACpF,OAAO;oBACL,MAAM,EAAE,QAAQ,CAAC,MAAM;oBACvB,IAAI;oBACJ,YAAY,EAAE,eAAe,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;oBACpD,MAAM;oBACN,IAAI;wBACF,IAAI,CAAC;4BACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAC;wBACrC,CAAC;wBAAC,MAAM,CAAC;4BACP,MAAM,KAAK,CAAC;gCACV,IAAI,EAAE,kBAAkB;gCACxB,OAAO,EAAE,OAAO,QAAQ,qBAAqB;gCAC7C,MAAM,EAAE,QAAQ,CAAC,MAAM;gCACvB,SAAS;6BACV,CAAC,CAAC;wBACL,CAAC;oBACH,CAAC;iBACF,CAAC;YACJ,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;YACvB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * One error vocabulary for every provider client, so callers can branch on
3
+ * `kind` without knowing the provider.
4
+ */
5
+ export declare const PROVIDER_ERROR_KINDS: readonly [
6
+ /** The caller passed something unusable; no request was made. */
7
+ 'invalid_input',
8
+ /** The provider understood the request and refused it. */
9
+ 'invalid_request',
10
+ /** The credential is missing, wrong or expired. */
11
+ 'unauthorized',
12
+ /** The credential is valid but not allowed to do this. */
13
+ 'forbidden', 'not_found',
14
+ /** The provider, or the local rate budget, is limiting requests. */
15
+ 'rate_limited', 'timeout',
16
+ /** The caller's AbortSignal fired. */
17
+ 'aborted',
18
+ /** Network failure or a provider 5xx. */
19
+ 'unavailable',
20
+ /** The provider answered with something that could not be understood. */
21
+ 'invalid_response'];
22
+ export type ProviderErrorKind = (typeof PROVIDER_ERROR_KINDS)[number];
23
+ export interface ProviderErrorOptions {
24
+ provider: string;
25
+ kind: ProviderErrorKind;
26
+ message: string;
27
+ /** HTTP status, when a response was received. */
28
+ status?: number | null;
29
+ /** Client operation label such as `zones.list`. Never a URL. */
30
+ operation?: string | null;
31
+ /** The provider's own error code, verbatim. */
32
+ providerCode?: string | null;
33
+ retryAfterMs?: number | null;
34
+ /** Extra sanitized evidence. Must not contain credentials, headers, URLs or bodies. */
35
+ detail?: Readonly<Record<string, unknown>>;
36
+ }
37
+ /**
38
+ * Thrown by every client. Everything on it is safe to log: no headers, URLs,
39
+ * query strings, bodies, credentials, or underlying `cause`.
40
+ */
41
+ export declare class ProviderError extends Error {
42
+ readonly provider: string;
43
+ readonly kind: ProviderErrorKind;
44
+ readonly status: number | null;
45
+ readonly operation: string | null;
46
+ readonly providerCode: string | null;
47
+ readonly retryAfterMs: number | null;
48
+ readonly detail: Readonly<Record<string, unknown>>;
49
+ constructor(options: ProviderErrorOptions);
50
+ /**
51
+ * Whether the same request might succeed later. This says nothing about
52
+ * whether repeating it is safe: a timed-out create may have happened.
53
+ */
54
+ get retryable(): boolean;
55
+ toJSON(): Record<string, unknown>;
56
+ }
57
+ export declare function kindFromStatus(status: number): ProviderErrorKind;
58
+ /** Parses `Retry-After` (delta seconds or HTTP date) to milliseconds, or null. */
59
+ export declare function parseRetryAfter(value: string | null, now?: number): number | null;
60
+ /**
61
+ * Makes provider-supplied text safe to put in an error: secrets (and their
62
+ * URL-encoded forms) are replaced, control characters removed, length bounded.
63
+ */
64
+ export declare function safeProviderText(text: string, secrets?: readonly string[], maxLength?: number): string;
65
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,oBAAoB;AAC/B,iEAAiE;AACjE,eAAe;AACf,0DAA0D;AAC1D,iBAAiB;AACjB,mDAAmD;AACnD,cAAc;AACd,0DAA0D;AAC1D,WAAW,EACX,WAAW;AACX,oEAAoE;AACpE,cAAc,EACd,SAAS;AACT,sCAAsC;AACtC,SAAS;AACT,yCAAyC;AACzC,aAAa;AACb,y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M,GAAG,iBAAiB,CAShE;AAED,kFAAkF;AAClF,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,GAAE,MAAmB,GAAG,MAAM,GAAG,IAAI,CAM7F;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,SAAS,MAAM,EAAO,EAC/B,SAAS,SAAM,GACd,MAAM,CAeR"}
package/dist/errors.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * One error vocabulary for every provider client, so callers can branch on
3
+ * `kind` without knowing the provider.
4
+ */
5
+ export const PROVIDER_ERROR_KINDS = [
6
+ /** The caller passed something unusable; no request was made. */
7
+ 'invalid_input',
8
+ /** The provider understood the request and refused it. */
9
+ 'invalid_request',
10
+ /** The credential is missing, wrong or expired. */
11
+ 'unauthorized',
12
+ /** The credential is valid but not allowed to do this. */
13
+ 'forbidden',
14
+ 'not_found',
15
+ /** The provider, or the local rate budget, is limiting requests. */
16
+ 'rate_limited',
17
+ 'timeout',
18
+ /** The caller's AbortSignal fired. */
19
+ 'aborted',
20
+ /** Network failure or a provider 5xx. */
21
+ 'unavailable',
22
+ /** The provider answered with something that could not be understood. */
23
+ 'invalid_response'
24
+ ];
25
+ /**
26
+ * Thrown by every client. Everything on it is safe to log: no headers, URLs,
27
+ * query strings, bodies, credentials, or underlying `cause`.
28
+ */
29
+ export class ProviderError extends Error {
30
+ provider;
31
+ kind;
32
+ status;
33
+ operation;
34
+ providerCode;
35
+ retryAfterMs;
36
+ detail;
37
+ constructor(options) {
38
+ super(options.message);
39
+ this.name = new.target.name;
40
+ this.provider = options.provider;
41
+ this.kind = options.kind;
42
+ this.status = options.status ?? null;
43
+ this.operation = options.operation ?? null;
44
+ this.providerCode = options.providerCode ?? null;
45
+ this.retryAfterMs = options.retryAfterMs ?? null;
46
+ this.detail = options.detail ?? {};
47
+ }
48
+ /**
49
+ * Whether the same request might succeed later. This says nothing about
50
+ * whether repeating it is safe: a timed-out create may have happened.
51
+ */
52
+ get retryable() {
53
+ return this.kind === 'rate_limited' || this.kind === 'timeout' || this.kind === 'unavailable';
54
+ }
55
+ toJSON() {
56
+ return {
57
+ name: this.name,
58
+ message: this.message,
59
+ provider: this.provider,
60
+ kind: this.kind,
61
+ status: this.status,
62
+ operation: this.operation,
63
+ providerCode: this.providerCode,
64
+ retryAfterMs: this.retryAfterMs,
65
+ detail: this.detail
66
+ };
67
+ }
68
+ }
69
+ export function kindFromStatus(status) {
70
+ if (status === 401)
71
+ return 'unauthorized';
72
+ if (status === 403)
73
+ return 'forbidden';
74
+ if (status === 404)
75
+ return 'not_found';
76
+ if (status === 408 || status === 504)
77
+ return 'timeout';
78
+ if (status === 429)
79
+ return 'rate_limited';
80
+ if (status >= 400 && status < 500)
81
+ return 'invalid_request';
82
+ if (status >= 500)
83
+ return 'unavailable';
84
+ return 'invalid_response';
85
+ }
86
+ /** Parses `Retry-After` (delta seconds or HTTP date) to milliseconds, or null. */
87
+ export function parseRetryAfter(value, now = Date.now()) {
88
+ if (value === null)
89
+ return null;
90
+ const text = value.trim();
91
+ if (/^\d{1,9}$/.test(text))
92
+ return Number(text) * 1000;
93
+ const at = Date.parse(text);
94
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
95
+ }
96
+ /**
97
+ * Makes provider-supplied text safe to put in an error: secrets (and their
98
+ * URL-encoded forms) are replaced, control characters removed, length bounded.
99
+ */
100
+ export function safeProviderText(text, secrets = [], maxLength = 200) {
101
+ let clean = text;
102
+ for (const secret of secrets) {
103
+ if (secret === '')
104
+ continue;
105
+ for (const form of new Set([
106
+ secret,
107
+ encodeURIComponent(secret),
108
+ new URLSearchParams([['', secret]]).toString().slice(1)
109
+ ])) {
110
+ clean = clean.split(form).join('[redacted]');
111
+ }
112
+ }
113
+ // oxlint-disable-next-line no-control-regex
114
+ clean = clean.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim();
115
+ return clean.length > maxLength ? `${clean.slice(0, maxLength)}…` : clean;
116
+ }
117
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,iEAAiE;IACjE,eAAe;IACf,0DAA0D;IAC1D,iBAAiB;IACjB,mDAAmD;IACnD,cAAc;IACd,0DAA0D;IAC1D,WAAW;IACX,WAAW;IACX,oEAAoE;IACpE,cAAc;IACd,SAAS;IACT,sCAAsC;IACtC,SAAS;IACT,yCAAyC;IACzC,aAAa;IACb,yEAAyE;IACzE,kBAAkB;CACV,CAAC;AAmBX;;;GAGG;AACH,MAAM,OAAO,aAAc,SAAQ,KAAK;IAC7B,QAAQ,CAAS;IACjB,IAAI,CAAoB;IACxB,MAAM,CAAgB;IACtB,SAAS,CAAgB;IACzB,YAAY,CAAgB;IAC5B,YAAY,CAAgB;IAC5B,MAAM,CAAoC;IAEnD,YAAY,OAA6B;QACvC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC;QAC5B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC;QAC3C,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,IAAI,CAAC;QACjD,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,IAAI,CAAC;QACjD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;IACrC,CAAC;IAED;;;OAGG;IACH,IAAI,SAAS;Q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ts';
3
+ export * from './rate-budget.ts';
4
+ export * from './client.ts';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './errors.js';
2
+ export * from './url.js';
3
+ export * from './rate-budget.js';
4
+ export * from './client.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC"}
@@ -0,0 +1,40 @@
1
+ export interface RateBudgetStats {
2
+ capacity: number;
3
+ refillPerSecond: number;
4
+ /** Tokens available now; 0 while waiters have reserved ahead. */
5
+ available: number;
6
+ /** Acquisitions waiting on refill. */
7
+ pending: number;
8
+ acquired: number;
9
+ rejected: number;
10
+ }
11
+ export interface RateBudget {
12
+ /** Takes `cost` tokens, waiting for refill when needed. */
13
+ acquire(cost?: number, options?: {
14
+ maxWaitMs?: number;
15
+ signal?: AbortSignal;
16
+ }): Promise<void>;
17
+ /** Takes `cost` tokens only if that needs no wait. */
18
+ tryAcquire(cost?: number): boolean;
19
+ stats(): RateBudgetStats;
20
+ }
21
+ export interface RateBudgetOptions {
22
+ /** Names the budget in errors. */
23
+ provider?: string;
24
+ capacity: number;
25
+ refillPerSecond: number;
26
+ /** Longest wait `acquire` accepts before failing. Default 30 000. */
27
+ maxWaitMs?: number;
28
+ /** Test seams. */
29
+ now?: () => number;
30
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
31
+ }
32
+ /** A promise-based delay that rejects with the signal's reason when aborted. */
33
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
34
+ /**
35
+ * A token bucket: starts full, refills continuously, and makes waiters reserve
36
+ * ahead so they are served roughly in order. In-memory and per-process; divide
37
+ * the rate when several processes share one account.
38
+ */
39
+ export declare function createRateBudget(options: RateBudgetOptions): RateBudget;
40
+ //# sourceMappingURL=rate-budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-budget.d.ts","sourceRoot":"","sources":["../src/rate-budget.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,iEAAiE;IACjE,SAAS,EAAE,MAAM,CAAC;IAClB,sCAAsC;IACtC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,UAAU;IACzB,2DAA2D;IAC3D,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9F,sDAAsD;IACtD,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IACnC,KAAK,IAAI,eAAe,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,kCAAkC;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,qEAAqE;IACrE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kBAAkB;IAClB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7D;AAED,gFAAgF;AAChF,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBrE;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,GAAG,UAAU,CAqFvE"}
@@ -0,0 +1,110 @@
1
+ import { ProviderError } from './errors.js';
2
+ /** A promise-based delay that rejects with the signal's reason when aborted. */
3
+ export function sleep(ms, signal) {
4
+ return new Promise((resolve, reject) => {
5
+ if (signal?.aborted) {
6
+ reject(signal.reason);
7
+ return;
8
+ }
9
+ const onAbort = () => {
10
+ clearTimeout(timer);
11
+ reject(signal.reason);
12
+ };
13
+ const timer = setTimeout(() => {
14
+ signal?.removeEventListener('abort', onAbort);
15
+ resolve();
16
+ }, ms);
17
+ signal?.addEventListener('abort', onAbort, { once: true });
18
+ });
19
+ }
20
+ /**
21
+ * A token bucket: starts full, refills continuously, and makes waiters reserve
22
+ * ahead so they are served roughly in order. In-memory and per-process; divide
23
+ * the rate when several processes share one account.
24
+ */
25
+ export function createRateBudget(options) {
26
+ const { capacity, refillPerSecond } = options;
27
+ const provider = options.provider ?? 'provider';
28
+ const defaultMaxWaitMs = options.maxWaitMs ?? 30_000;
29
+ const now = options.now ?? Date.now;
30
+ const wait = options.sleep ?? sleep;
31
+ const invalid = (message) => {
32
+ throw new ProviderError({ provider, kind: 'invalid_input', message });
33
+ };
34
+ if (!Number.isFinite(capacity) || capacity <= 0)
35
+ invalid('rate budget capacity must be positive');
36
+ if (!Number.isFinite(refillPerSecond) || refillPerSecond <= 0) {
37
+ invalid('rate budget refillPerSecond must be positive');
38
+ }
39
+ let tokens = capacity;
40
+ let refilledAt = now();
41
+ let pending = 0;
42
+ let acquired = 0;
43
+ let rejected = 0;
44
+ const refill = () => {
45
+ const at = now();
46
+ if (at > refilledAt)
47
+ tokens = Math.min(capacity, tokens + ((at - refilledAt) / 1000) * refillPerSecond);
48
+ refilledAt = at;
49
+ };
50
+ const check = (cost) => {
51
+ if (!Number.isFinite(cost) || cost <= 0 || cost > capacity) {
52
+ invalid('rate budget cost must be positive and no greater than capacity');
53
+ }
54
+ };
55
+ return {
56
+ async acquire(cost = 1, { maxWaitMs = defaultMaxWaitMs, signal } = {}) {
57
+ check(cost);
58
+ refill();
59
+ if (tokens >= cost) {
60
+ tokens -= cost;
61
+ acquired += 1;
62
+ return;
63
+ }
64
+ const waitMs = Math.ceil(((cost - tokens) / refillPerSecond) * 1000);
65
+ if (waitMs > maxWaitMs) {
66
+ rejected += 1;
67
+ throw new ProviderError({
68
+ provider,
69
+ kind: 'rate_limited',
70
+ message: `the local ${provider} rate budget is exhausted`,
71
+ retryAfterMs: waitMs,
72
+ detail: { source: 'local_rate_budget', maxWaitMs }
73
+ });
74
+ }
75
+ tokens -= cost;
76
+ pending += 1;
77
+ try {
78
+ await wait(waitMs, signal);
79
+ }
80
+ catch {
81
+ // Abandoned: give the reservation back so later callers are not charged for it.
82
+ refill();
83
+ tokens = Math.min(capacity, tokens + cost);
84
+ throw new ProviderError({
85
+ provider,
86
+ kind: 'aborted',
87
+ message: `the ${provider} request was aborted while waiting for the rate budget`
88
+ });
89
+ }
90
+ finally {
91
+ pending -= 1;
92
+ }
93
+ acquired += 1;
94
+ },
95
+ tryAcquire(cost = 1) {
96
+ check(cost);
97
+ refill();
98
+ if (tokens < cost)
99
+ return false;
100
+ tokens -= cost;
101
+ acquired += 1;
102
+ return true;
103
+ },
104
+ stats() {
105
+ refill();
106
+ return { capacity, refillPerSecond, available: Math.max(0, tokens), pending, acquired, rejected };
107
+ }
108
+ };
109
+ }
110
+ //# sourceMappingURL=rate-budget.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-budget.js","sourceRoot":"","sources":["../src/rate-budget.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAiC5C,gFAAgF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,CAAC;QAED,KAAK;YACH,MAAM,EAAE,CAAC;YACT,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC;QACpG,CAAC;KACF,CAAC;AACJ,CAAC"}
package/dist/url.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Whether a host is an address or name that only means something locally, or
3
+ * is not a public unicast address: loopback, private, shared (CGNAT),
4
+ * link-local, unique-local, multicast, documentation and reserved ranges (in
5
+ * IPv6, anything outside global unicast `2000::/3`, with mapped, NAT64 and
6
+ * 6to4 addresses judged by their IPv4 part), plus `localhost`, `.local`,
7
+ * `.internal`, `.home.arpa` and bare names. Pass a `URL.hostname`, which
8
+ * already turns odd IPv4 spellings (`127.1`, `0x7f000001`) into dotted form.
9
+ *
10
+ * Names are not resolved. A public name that resolves to a private address
11
+ * passes; block that with an egress policy or a checking resolver.
12
+ */
13
+ export declare function isPrivateHost(hostname: string): boolean;
14
+ export declare function isLoopbackHost(hostname: string): boolean;
15
+ export interface BaseUrlOptions {
16
+ provider: string;
17
+ /** Permit `http:` to a loopback host, for tests and local mocks. */
18
+ allowLoopbackHttp?: boolean;
19
+ /** Permit `http:` to other hosts whose transport is already encrypted. */
20
+ allowHttpHost?: (hostname: string) => boolean;
21
+ }
22
+ /**
23
+ * Validates and normalizes an API base URL: https only (see options), no
24
+ * embedded credentials, no query or fragment, no trailing slash.
25
+ */
26
+ export declare function normalizeBaseUrl(input: string, options: BaseUrlOptions): string;
27
+ //# sourceMappingURL=url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../src/url.ts"],"names":[],"mappings":"AA6EA;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAWvD;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAKxD;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,oEAAoE;IACpE,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,0EAA0E;IAC1E,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;CAC/C;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,MAAM,CAsB/E"}
package/dist/url.js ADDED
@@ -0,0 +1,144 @@
1
+ import { ProviderError } from './errors.js';
2
+ function ipv4Value(address) {
3
+ const parts = address.split('.');
4
+ if (parts.length !== 4)
5
+ return null;
6
+ let value = 0;
7
+ for (const part of parts) {
8
+ if (!/^\d{1,3}$/.test(part) || Number(part) > 255)
9
+ return null;
10
+ value = value * 256 + Number(part);
11
+ }
12
+ return value;
13
+ }
14
+ /** Loopback, private, shared, link-local, multicast, documentation and reserved ranges. */
15
+ const PRIVATE_V4 = [
16
+ ['0.0.0.0', 8],
17
+ ['10.0.0.0', 8],
18
+ ['100.64.0.0', 10],
19
+ ['127.0.0.0', 8],
20
+ ['169.254.0.0', 16],
21
+ ['172.16.0.0', 12],
22
+ ['192.0.0.0', 24],
23
+ ['192.0.2.0', 24],
24
+ ['192.88.99.0', 24],
25
+ ['192.168.0.0', 16],
26
+ ['198.18.0.0', 15],
27
+ ['198.51.100.0', 24],
28
+ ['203.0.113.0', 24],
29
+ ['224.0.0.0', 4],
30
+ ['240.0.0.0', 4]
31
+ ];
32
+ function isPrivateV4(value) {
33
+ return PRIVATE_V4.some(([base, prefix]) => {
34
+ const size = 2 ** (32 - prefix);
35
+ return Math.floor(value / size) === Math.floor(ipv4Value(base) / size);
36
+ });
37
+ }
38
+ function ipv6Value(address) {
39
+ let text = address.toLowerCase();
40
+ const tail = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(text);
41
+ if (tail) {
42
+ const v4 = ipv4Value(tail[2]);
43
+ if (v4 === null)
44
+ return null;
45
+ text = `${tail[1]}${Math.floor(v4 / 65536).toString(16)}:${(v4 % 65536).toString(16)}`;
46
+ }
47
+ const halves = text.split('::');
48
+ if (halves.length > 2)
49
+ return null;
50
+ const groups = (part) => (part === '' ? [] : part.split(':'));
51
+ const head = groups(halves[0]);
52
+ const end = halves.length === 2 ? groups(halves[1]) : [];
53
+ const missing = 8 - head.length - end.length;
54
+ if (halves.length === 2 ? missing < 1 : missing !== 0)
55
+ return null;
56
+ let value = 0n;
57
+ for (const group of [...head, ...Array(missing).fill('0'), ...end]) {
58
+ if (!/^[0-9a-f]{1,4}$/.test(group))
59
+ return null;
60
+ value = (value << 16n) | BigInt(`0x${group}`);
61
+ }
62
+ return value;
63
+ }
64
+ function isPrivateV6(value) {
65
+ const top = (bits) => value >> (128n - bits);
66
+ const v4At = (shift) => Number((value >> shift) & 0xffffffffn);
67
+ // Forms that carry an IPv4 address are judged by that address.
68
+ if (top(96n) === 0xffffn)
69
+ return isPrivateV4(v4At(0n)); // ::ffff:0:0/96 mapped
70
+ if (top(96n) === 0x64ff9bn << 64n)
71
+ return isPrivateV4(v4At(0n)); // 64:ff9b::/96 NAT64
72
+ if (top(16n) === 0x2002n)
73
+ return isPrivateV4(v4At(80n)); // 2002::/16 6to4
74
+ // Only 2000::/3 is global unicast. This refuses ::, ::1, IPv4-compatible,
75
+ // unique-local, link-local, site-local, multicast and local-use NAT64.
76
+ if (top(3n) !== 1n)
77
+ return true;
78
+ if (top(23n) === 0x20010000n >> 9n)
79
+ return true; // 2001::/23: Teredo and other special use
80
+ if (top(32n) === 0x20010db8n)
81
+ return true; // 2001:db8::/32 documentation
82
+ return top(20n) === 0x3fff0n; // 3fff::/20 documentation
83
+ }
84
+ /**
85
+ * Whether a host is an address or name that only means something locally, or
86
+ * is not a public unicast address: loopback, private, shared (CGNAT),
87
+ * link-local, unique-local, multicast, documentation and reserved ranges (in
88
+ * IPv6, anything outside global unicast `2000::/3`, with mapped, NAT64 and
89
+ * 6to4 addresses judged by their IPv4 part), plus `localhost`, `.local`,
90
+ * `.internal`, `.home.arpa` and bare names. Pass a `URL.hostname`, which
91
+ * already turns odd IPv4 spellings (`127.1`, `0x7f000001`) into dotted form.
92
+ *
93
+ * Names are not resolved. A public name that resolves to a private address
94
+ * passes; block that with an egress policy or a checking resolver.
95
+ */
96
+ export function isPrivateHost(hostname) {
97
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
98
+ if (host.includes(':')) {
99
+ const value = ipv6Value(host);
100
+ return value === null || isPrivateV6(value);
101
+ }
102
+ const v4 = ipv4Value(host);
103
+ if (v4 !== null)
104
+ return isPrivateV4(v4);
105
+ return (!host.includes('.') || /(^|\.)(localhost|local|internal|home\.arpa)$/.test(host));
106
+ }
107
+ export function isLoopbackHost(hostname) {
108
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
109
+ if (host === 'localhost' || host === '::1')
110
+ return true;
111
+ const v4 = ipv4Value(host);
112
+ return v4 !== null && Math.floor(v4 / 2 ** 24) === 127;
113
+ }
114
+ /**
115
+ * Validates and normalizes an API base URL: https only (see options), no
116
+ * embedded credentials, no query or fragment, no trailing slash.
117
+ */
118
+ export function normalizeBaseUrl(input, options) {
119
+ const fail = (message) => {
120
+ throw new ProviderError({
121
+ provider: options.provider,
122
+ kind: 'invalid_input',
123
+ message: `the ${options.provider} base URL ${message}`
124
+ });
125
+ };
126
+ let url;
127
+ try {
128
+ url = new URL(input);
129
+ }
130
+ catch {
131
+ return fail('is not an absolute URL');
132
+ }
133
+ if (url.username !== '' || url.password !== '')
134
+ fail('must not carry credentials');
135
+ if (url.search !== '' || url.hash !== '')
136
+ fail('must not carry a query string or fragment');
137
+ const httpAllowed = url.protocol === 'http:' &&
138
+ ((options.allowLoopbackHttp === true && isLoopbackHost(url.hostname)) ||
139
+ options.allowHttpHost?.(url.hostname) === true);
140
+ if (url.protocol !== 'https:' && !httpAllowed)
141
+ fail(`must use https, not ${url.protocol}`);
142
+ return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
143
+ }
144
+ //# sourceMappingURL=url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url.js","sourceRoot":"","sources":["../src/url.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,SAAS,SAAS,CAAC,OAAe;IAChC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACjC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACpC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG;YAAE,OAAO,IAAI,CAAC;QAC/D,KAAK,GAAG,KAAK,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,2FAA2F;AAC3F,MAAM,UAAU,GAA2D;IACzE,CAAC,SAAS,EAAE,CAAC,CAAC;IACd,CAAC,UAAU,EAAE,CAAC,CAAC;IACf,CAAC,YAAY,EAAE,EAAE,CAAC;IAClB,CAAC,WAAW,EAAE,CAAC,CAAC;IAChB,CAAC,aAAa,EAAE,EAAE,CAAC;IACnB,CAAC,YAAY,EAAE,EAAE,CAAC;IAClB,CAAC,WAAW,EAAE,EAAE,CAAC;IACjB,CAAC,WAAW,EAAE,EAAE,CAAC;IACjB,CAAC,aAAa,EAAE,EAAE,CAAC;IACnB,CAAC,aAAa,EAAE,EAAE,CAAC;IACnB,CAAC,YAAY,EAAE,EAAE,CAAC;IAClB,CAAC,cAAc,EAAE,EAAE,CAAC;IACpB,CAAC,aAAa,EAAE,EAAE,CAAC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AAM,WAAW,GACf,GAAG,CAAC,QAAQ,KAAK,OAAO;QACxB,CAAC,CAAC,OAAO,CAAC,iBAAiB,KAAK,IAAI,IAAI,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACnE,OAAO,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAC;IACpD,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,WAAW;QAAE,IAAI,CAAC,uBAAuB,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC3F,OAAO,GAAG,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;AAC5D,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@formless63/provider-http",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Safe HTTP plumbing for API clients: URL guards, bounded reads, sanitized errors, rate budgets.",
5
+ "keywords": [
6
+ "http",
7
+ "fetch",
8
+ "rate-limit",
9
+ "api-client"
10
+ ],
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/formless63/netlibs.git",
15
+ "directory": "packages/provider-http"
16
+ },
17
+ "homepage": "https://github.com/formless63/netlibs/tree/main/packages/provider-http#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/formless63/netlibs/issues"
20
+ },
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "engines": {
24
+ "node": ">=22"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "LICENSE",
29
+ "README.md"
30
+ ],
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ }
41
+ }