@c9up/aurora 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/browser.d.ts +136 -4
- package/dist/browser.js +324 -15
- package/dist/http.d.ts +79 -0
- package/dist/http.js +199 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +2 -7
- package/package.json +1 -1
- package/src/browser.ts +425 -16
- package/src/http.ts +278 -0
- package/src/index.ts +32 -1
package/src/http.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `HttpClient` — a small typed wrapper over `fetch` so call sites read
|
|
3
|
+
* `await http.get<User>("/auth/me")` instead of hand-rolling headers,
|
|
4
|
+
* `res.json()`, and status checks.
|
|
5
|
+
*
|
|
6
|
+
* - Auto JSON: a plain-object/array body is `JSON.stringify`-d with a
|
|
7
|
+
* `Content-Type: application/json` header; a JSON response is parsed.
|
|
8
|
+
* `FormData`/`Blob`/`URLSearchParams`/`string`/binary bodies pass through
|
|
9
|
+
* untouched.
|
|
10
|
+
* - Bearer auth: a `token` (string or getter, read fresh per request) is sent
|
|
11
|
+
* as `Authorization: Bearer …` unless the caller set the header themselves.
|
|
12
|
+
* - Errors: a non-2xx response rejects with an {@link HttpError} carrying the
|
|
13
|
+
* status, the `Response`, and the parsed body.
|
|
14
|
+
*
|
|
15
|
+
* Node-free and isomorphic — uses the global `fetch` (browsers, Node 18+,
|
|
16
|
+
* Workers, Bun, Deno). Part of the client barrel.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export interface HttpClientOptions {
|
|
20
|
+
/** Prepended to every request URL, unless the URL is already absolute. */
|
|
21
|
+
baseURL?: string;
|
|
22
|
+
/** Headers merged into every request. */
|
|
23
|
+
headers?: Record<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* Bearer token sent as `Authorization: Bearer <token>`. A getter is read
|
|
26
|
+
* fresh on each request (so a rotated/late-set token is always current);
|
|
27
|
+
* a `null`/`undefined` result omits the header.
|
|
28
|
+
*/
|
|
29
|
+
token?: string | null | (() => string | null | undefined);
|
|
30
|
+
/** Default `credentials` mode (e.g. `"include"` to send cookies). */
|
|
31
|
+
credentials?: RequestCredentials;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface HttpRequestOptions<T = unknown> {
|
|
35
|
+
/** Query params appended to the URL. `null`/`undefined` values are skipped. */
|
|
36
|
+
query?: Record<string, string | number | boolean | null | undefined>;
|
|
37
|
+
/** Extra headers for this request (override the client defaults). */
|
|
38
|
+
headers?: Record<string, string>;
|
|
39
|
+
/** Per-request bearer token override (`null` to force-omit). */
|
|
40
|
+
token?: string | null;
|
|
41
|
+
/** Abort signal. */
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
/** `credentials` mode for this request. */
|
|
44
|
+
credentials?: RequestCredentials;
|
|
45
|
+
/**
|
|
46
|
+
* Runtime validator/mapper for the parsed body. When provided, the return
|
|
47
|
+
* type is whatever it returns — no unchecked cast. When omitted, the parsed
|
|
48
|
+
* body is returned as `T` (an UNCHECKED assertion of the response shape).
|
|
49
|
+
*/
|
|
50
|
+
parse?: (raw: unknown) => T;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Thrown on a non-2xx response. Carries the status, the `Response`, and the parsed body. */
|
|
54
|
+
export class HttpError extends Error {
|
|
55
|
+
readonly status: number;
|
|
56
|
+
readonly response: Response;
|
|
57
|
+
readonly data: unknown;
|
|
58
|
+
|
|
59
|
+
constructor(response: Response, data: unknown) {
|
|
60
|
+
super(`HTTP ${response.status} ${response.statusText} for ${response.url}`);
|
|
61
|
+
this.name = "HttpError";
|
|
62
|
+
this.status = response.status;
|
|
63
|
+
this.response = response;
|
|
64
|
+
this.data = data;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Whether `body` should be JSON-encoded (vs. passed to `fetch` untouched). */
|
|
69
|
+
function shouldJsonEncode(body: unknown): boolean {
|
|
70
|
+
if (body === null || typeof body !== "object") {
|
|
71
|
+
return typeof body !== "string";
|
|
72
|
+
}
|
|
73
|
+
if (
|
|
74
|
+
body instanceof FormData ||
|
|
75
|
+
body instanceof Blob ||
|
|
76
|
+
body instanceof URLSearchParams ||
|
|
77
|
+
body instanceof ArrayBuffer ||
|
|
78
|
+
ArrayBuffer.isView(body)
|
|
79
|
+
) {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Case-insensitive header presence check. */
|
|
89
|
+
function hasHeader(headers: Record<string, string>, name: string): boolean {
|
|
90
|
+
const lower = name.toLowerCase();
|
|
91
|
+
for (const key of Object.keys(headers)) {
|
|
92
|
+
if (key.toLowerCase() === lower) return true;
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Parse a response by content-type; `null` for empty / no-content bodies. */
|
|
98
|
+
async function parseBody(response: Response): Promise<unknown> {
|
|
99
|
+
if (response.status === 204 || response.status === 205) return null;
|
|
100
|
+
const type = response.headers.get("content-type") ?? "";
|
|
101
|
+
const text = await response.text();
|
|
102
|
+
if (text === "") return null;
|
|
103
|
+
if (type.includes("application/json")) return JSON.parse(text);
|
|
104
|
+
return text;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export class HttpClient {
|
|
108
|
+
readonly #baseURL: string;
|
|
109
|
+
readonly #headers: Record<string, string>;
|
|
110
|
+
readonly #token?: string | null | (() => string | null | undefined);
|
|
111
|
+
readonly #credentials?: RequestCredentials;
|
|
112
|
+
|
|
113
|
+
constructor(options: HttpClientOptions = {}) {
|
|
114
|
+
this.#baseURL = options.baseURL ?? "";
|
|
115
|
+
this.#headers = { ...options.headers };
|
|
116
|
+
this.#token = options.token;
|
|
117
|
+
this.#credentials = options.credentials;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Set a default header for every subsequent request (case-insensitive replace). Chainable. */
|
|
121
|
+
setHeader(name: string, value: string): this {
|
|
122
|
+
this.#deleteHeader(name);
|
|
123
|
+
this.#headers[name] = value;
|
|
124
|
+
return this;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Merge several default headers at once. Chainable. */
|
|
128
|
+
setHeaders(headers: Record<string, string>): this {
|
|
129
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
130
|
+
this.setHeader(name, value);
|
|
131
|
+
}
|
|
132
|
+
return this;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Remove a default header (case-insensitive). Chainable. */
|
|
136
|
+
removeHeader(name: string): this {
|
|
137
|
+
this.#deleteHeader(name);
|
|
138
|
+
return this;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** A copy of the current default headers. */
|
|
142
|
+
getHeaders(): Record<string, string> {
|
|
143
|
+
return { ...this.#headers };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#deleteHeader(name: string): void {
|
|
147
|
+
const lower = name.toLowerCase();
|
|
148
|
+
for (const key of Object.keys(this.#headers)) {
|
|
149
|
+
if (key.toLowerCase() === lower) delete this.#headers[key];
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
get<T>(url: string, options?: HttpRequestOptions<T>): Promise<T> {
|
|
154
|
+
return this.#request("GET", url, undefined, options);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
delete<T>(url: string, options?: HttpRequestOptions<T>): Promise<T> {
|
|
158
|
+
return this.#request("DELETE", url, undefined, options);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
post<T>(
|
|
162
|
+
url: string,
|
|
163
|
+
body?: unknown,
|
|
164
|
+
options?: HttpRequestOptions<T>,
|
|
165
|
+
): Promise<T> {
|
|
166
|
+
return this.#request("POST", url, body, options);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
put<T>(
|
|
170
|
+
url: string,
|
|
171
|
+
body?: unknown,
|
|
172
|
+
options?: HttpRequestOptions<T>,
|
|
173
|
+
): Promise<T> {
|
|
174
|
+
return this.#request("PUT", url, body, options);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
patch<T>(
|
|
178
|
+
url: string,
|
|
179
|
+
body?: unknown,
|
|
180
|
+
options?: HttpRequestOptions<T>,
|
|
181
|
+
): Promise<T> {
|
|
182
|
+
return this.#request("PATCH", url, body, options);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Send a request and return the raw `Response` (no parsing, no throw on non-2xx). */
|
|
186
|
+
raw(
|
|
187
|
+
method: string,
|
|
188
|
+
url: string,
|
|
189
|
+
body?: unknown,
|
|
190
|
+
options: HttpRequestOptions = {},
|
|
191
|
+
): Promise<Response> {
|
|
192
|
+
return this.#send(method, url, body, options);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Derive a new client with merged defaults (e.g. a scope that adds a token). */
|
|
196
|
+
extend(options: HttpClientOptions): HttpClient {
|
|
197
|
+
return new HttpClient({
|
|
198
|
+
baseURL: options.baseURL ?? this.#baseURL,
|
|
199
|
+
headers: { ...this.#headers, ...options.headers },
|
|
200
|
+
token: options.token ?? this.#token,
|
|
201
|
+
credentials: options.credentials ?? this.#credentials,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
#resolveToken(override?: string | null): string | null | undefined {
|
|
206
|
+
if (override !== undefined) return override;
|
|
207
|
+
return typeof this.#token === "function" ? this.#token() : this.#token;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
#buildUrl(url: string, query?: HttpRequestOptions["query"]): string {
|
|
211
|
+
const base = /^[a-z][a-z\d+\-.]*:\/\//i.test(url)
|
|
212
|
+
? url
|
|
213
|
+
: this.#baseURL + url;
|
|
214
|
+
if (!query) return base;
|
|
215
|
+
const params = new URLSearchParams();
|
|
216
|
+
for (const [key, value] of Object.entries(query)) {
|
|
217
|
+
if (value !== null && value !== undefined)
|
|
218
|
+
params.append(key, String(value));
|
|
219
|
+
}
|
|
220
|
+
const qs = params.toString();
|
|
221
|
+
if (qs === "") return base;
|
|
222
|
+
return `${base}${base.includes("?") ? "&" : "?"}${qs}`;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
#send(
|
|
226
|
+
method: string,
|
|
227
|
+
url: string,
|
|
228
|
+
body: unknown,
|
|
229
|
+
options: HttpRequestOptions,
|
|
230
|
+
): Promise<Response> {
|
|
231
|
+
const headers: Record<string, string> = {
|
|
232
|
+
...this.#headers,
|
|
233
|
+
...options.headers,
|
|
234
|
+
};
|
|
235
|
+
const token = this.#resolveToken(options.token);
|
|
236
|
+
if (token != null && !hasHeader(headers, "authorization")) {
|
|
237
|
+
headers.Authorization = `Bearer ${token}`;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
let payload: BodyInit | undefined;
|
|
241
|
+
if (body !== undefined && body !== null) {
|
|
242
|
+
if (shouldJsonEncode(body)) {
|
|
243
|
+
payload = JSON.stringify(body);
|
|
244
|
+
if (!hasHeader(headers, "content-type")) {
|
|
245
|
+
headers["Content-Type"] = "application/json";
|
|
246
|
+
}
|
|
247
|
+
} else {
|
|
248
|
+
// Already a valid BodyInit (string / FormData / Blob / …).
|
|
249
|
+
payload = body as BodyInit;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return fetch(this.#buildUrl(url, options.query), {
|
|
254
|
+
method,
|
|
255
|
+
headers,
|
|
256
|
+
body: payload,
|
|
257
|
+
signal: options.signal,
|
|
258
|
+
credentials: options.credentials ?? this.#credentials,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async #request<T>(
|
|
263
|
+
method: string,
|
|
264
|
+
url: string,
|
|
265
|
+
body: unknown,
|
|
266
|
+
options: HttpRequestOptions<T> = {},
|
|
267
|
+
): Promise<T> {
|
|
268
|
+
const response = await this.#send(method, url, body, options);
|
|
269
|
+
const data = await parseBody(response);
|
|
270
|
+
if (!response.ok) throw new HttpError(response, data);
|
|
271
|
+
// `parse` validates at runtime; without it, `T` is the caller's
|
|
272
|
+
// unchecked assertion of the response shape (the usual HTTP boundary).
|
|
273
|
+
return options.parse ? options.parse(data) : (data as T);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Default same-origin client. Configure your own via `new HttpClient({ … })`. */
|
|
278
|
+
export const http = new HttpClient();
|
package/src/index.ts
CHANGED
|
@@ -4,9 +4,40 @@
|
|
|
4
4
|
// node:fs / node:path / node:url live in `@c9up/aurora/server`. Keeping them off
|
|
5
5
|
// this barrel is what lets a browser bundle import the client primitives without
|
|
6
6
|
// the bundler dragging Node built-ins through the import graph.
|
|
7
|
-
export {
|
|
7
|
+
export type {
|
|
8
|
+
CookieOptions,
|
|
9
|
+
PersistedSignalOptions,
|
|
10
|
+
ShareData,
|
|
11
|
+
StorageArea,
|
|
12
|
+
WebStorageOptions,
|
|
13
|
+
WindowSize,
|
|
14
|
+
} from "./browser.js";
|
|
15
|
+
export {
|
|
16
|
+
back,
|
|
17
|
+
clipboard,
|
|
18
|
+
cookie,
|
|
19
|
+
forward,
|
|
20
|
+
hash,
|
|
21
|
+
mediaQuery,
|
|
22
|
+
navigate,
|
|
23
|
+
online,
|
|
24
|
+
persistedSignal,
|
|
25
|
+
prefersDark,
|
|
26
|
+
queryParam,
|
|
27
|
+
redirect,
|
|
28
|
+
reload,
|
|
29
|
+
replace,
|
|
30
|
+
session,
|
|
31
|
+
share,
|
|
32
|
+
storage,
|
|
33
|
+
visibility,
|
|
34
|
+
WebStorage,
|
|
35
|
+
windowSize,
|
|
36
|
+
} from "./browser.js";
|
|
8
37
|
export { component, onMount, onUnmount } from "./component.js";
|
|
9
38
|
export { html, isTemplateResult } from "./html.js";
|
|
39
|
+
export type { HttpClientOptions, HttpRequestOptions } from "./http.js";
|
|
40
|
+
export { HttpClient, HttpError, http } from "./http.js";
|
|
10
41
|
export { hydrate } from "./hydrate.js";
|
|
11
42
|
export {
|
|
12
43
|
batch,
|