keits 0.0.3 → 0.1.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.
Files changed (75) hide show
  1. package/README.md +93 -79
  2. package/dist/dev/api.js +275 -0
  3. package/dist/dev/forms.js +330 -0
  4. package/dist/dev/index.js +26 -326
  5. package/dist/dev/router.js +24 -5
  6. package/dist/dev/shared/computed-DrF8O8b4.js +40 -0
  7. package/dist/dev/shared/{element-C4DfKtZW.js → element-DXwmUAnz.js} +32 -111
  8. package/dist/dev/shared/{graph-D6-x_CWC.js → graph-SIvYLXSv.js} +62 -3
  9. package/dist/dev/shared/hydrate-C8cOsDDH.js +588 -0
  10. package/dist/dev/shared/mount-CDB2HgN5.js +23 -0
  11. package/dist/dev/shared/namespaces-Cz82B0Pr.js +84 -0
  12. package/dist/dev/shared/owner-BuwIoI4j.js +72 -0
  13. package/dist/dev/shared/render-context-k2uu_dM_.js +34 -0
  14. package/dist/dev/shared/render-effect-Uk9dDmuU.js +32 -0
  15. package/dist/dev/shared/resource-DlgzdtcG.js +145 -0
  16. package/dist/dev/shared/signal-B3xOKbVm.js +24 -0
  17. package/dist/dev/shared/store-0vEg2bQV.js +152 -0
  18. package/dist/dev/shared/unsafe-keys-CB1P22No.js +8 -0
  19. package/dist/dev/static.js +76 -0
  20. package/dist/dev/svg.js +2 -1
  21. package/dist/dev/testing.js +216 -0
  22. package/dist/dev/vite.js +141 -0
  23. package/dist/prod/api.js +215 -0
  24. package/dist/prod/forms.js +240 -0
  25. package/dist/prod/index.js +110 -327
  26. package/dist/prod/router.js +83 -68
  27. package/dist/prod/shared/computed-BjqJ6Pps.js +33 -0
  28. package/dist/prod/shared/element-DCit4-3e.js +129 -0
  29. package/dist/prod/shared/{graph-C_aA46c6.js → graph-CR2WKbwr.js} +107 -63
  30. package/dist/prod/shared/hydrate-kKnJbkV7.js +480 -0
  31. package/dist/prod/shared/mount-DbeKIoyD.js +18 -0
  32. package/dist/prod/shared/namespaces-BSRrBJIU.js +71 -0
  33. package/dist/prod/shared/owner-DBi3odT4.js +67 -0
  34. package/dist/prod/shared/render-context-DF8lr1uu.js +30 -0
  35. package/dist/prod/shared/render-effect-UFDi2Pfh.js +25 -0
  36. package/dist/prod/shared/resource-Ch5tVseZ.js +91 -0
  37. package/dist/prod/shared/signal-BDMlfa0Z.js +16 -0
  38. package/dist/prod/shared/store-CvW0DbmK.js +110 -0
  39. package/dist/prod/shared/unsafe-keys-C5PMlerl.js +7 -0
  40. package/dist/prod/static.js +48 -0
  41. package/dist/prod/svg.js +3 -2
  42. package/dist/prod/testing.js +144 -0
  43. package/dist/prod/vite.js +106 -0
  44. package/dist/types/api/cache.d.ts +16 -0
  45. package/dist/types/api/client.d.ts +42 -0
  46. package/dist/types/api/error.d.ts +16 -0
  47. package/dist/types/api/index.d.ts +3 -0
  48. package/dist/types/api/url.d.ts +5 -0
  49. package/dist/types/async/render-context.d.ts +10 -0
  50. package/dist/types/core/effect.d.ts +1 -0
  51. package/dist/types/core/graph.d.ts +11 -0
  52. package/dist/types/core/owner.d.ts +1 -0
  53. package/dist/types/core/unsafe-keys.d.ts +2 -0
  54. package/dist/types/dom/hooks.d.ts +4 -0
  55. package/dist/types/dom/types.d.ts +5 -0
  56. package/dist/types/forms/form.d.ts +55 -0
  57. package/dist/types/forms/index.d.ts +2 -0
  58. package/dist/types/forms/paths.d.ts +6 -0
  59. package/dist/types/forms/types.d.ts +38 -0
  60. package/dist/types/router/index.d.ts +1 -0
  61. package/dist/types/router/match.d.ts +1 -0
  62. package/dist/types/router/types.d.ts +1 -0
  63. package/dist/types/static/head.d.ts +36 -0
  64. package/dist/types/static/hydrate.d.ts +3 -0
  65. package/dist/types/static/index.d.ts +4 -0
  66. package/dist/types/static/island.d.ts +14 -0
  67. package/dist/types/static/json.d.ts +1 -0
  68. package/dist/types/static/render.d.ts +11 -0
  69. package/dist/types/static/server-dom.d.ts +100 -0
  70. package/dist/types/testing/index.d.ts +62 -0
  71. package/dist/types/vite/index.d.ts +24 -0
  72. package/package.json +46 -5
  73. package/dist/dev/shared/owner-DlUsXKXE.js +0 -122
  74. package/dist/prod/shared/element-DUtXb3px.js +0 -187
  75. package/dist/prod/shared/owner-DgJNPM0P.js +0 -104
package/README.md CHANGED
@@ -1,126 +1,140 @@
1
1
  # keits
2
2
 
3
3
  A fine-grained reactive TypeScript framework. Real DOM, no virtual DOM, zero dependencies.
4
-
5
- > **Status: 0.0.x, early.** This release is the **reactive core** only. The DOM layer
6
- > (`$div`, `mount`, `$if`, `$for`, …), router, forms and static builds are in progress.
7
- > Expect breaking changes before 1.0.
4
+ Build SPAs, static websites with islands, and server-rendered apps from the same components.
8
5
 
9
6
  ```sh
10
7
  npm install keits
11
8
  ```
12
9
 
13
- About 2.6 KB min+gzip for the whole core, and about 1.6 KB if you only use the basics
14
- (everything is tree-shakable).
10
+ About 7.4 KB min+gzip for the whole core. Everything is tree-shakable: a small app ships about 3 KB,
11
+ a static page with one interactive island about 4 KB.
12
+
13
+ > **Status: 0.1.** The API is complete and tested; expect small breaking changes before 1.0.
15
14
 
16
- ## Signals
15
+ ## A component
17
16
 
18
17
  ```ts
19
- import { signal, computed, effect } from "keits";
18
+ import { $button, $p, mount, signal } from "keits";
20
19
 
21
- const count = signal(0);
22
- const double = computed(() => count() * 2); // lazy and cached
20
+ function Counter() {
21
+ const count = signal(0);
22
+ return [
23
+ $p(() => `Clicked ${count()} times`), // a function child updates by itself
24
+ $button({ onclick: () => count.set((n) => n + 1) }, "+1"),
25
+ ];
26
+ }
23
27
 
24
- effect(() => {
25
- console.log(`${count()} × 2 = ${double()}`); // re-runs when count changes
26
- });
27
-
28
- count.set(1); // logs "1 × 2 = 2" before set() returns
29
- count.set((prev) => prev + 1);
28
+ mount(Counter, document.getElementById("app")!);
30
29
  ```
31
30
 
32
- - Read by calling: `count()`. Write with `.set(value)` or `.set(prev => next)`.
33
- - Updates are **synchronous** and **glitch-free**: an effect never sees a half-updated state,
34
- and runs once per change even when several computeds it reads changed.
35
- - Equal values don't notify (`Object.is` by default; pass `{ equals }` to customise,
36
- or `equals: false` to always notify).
37
- - `batch(fn)` groups writes; `untrack(fn)` reads without subscribing.
31
+ Components run once. Only the parts that read a signal update, without re-rendering anything else.
32
+ Every HTML tag has a factory (`$div`, `$input`, ...); SVG ones come from `keits/svg`.
33
+ Text is always escaped: `unsafeHTML()` is the only way to insert HTML, and `javascript:` URLs are blocked.
34
+
35
+ ## What's included
38
36
 
39
- ## Ownership and cleanup
37
+ | Import | What it does |
38
+ | --- | --- |
39
+ | `keits` | `signal`, `computed`, `effect`, `batch`, `store`, context, error boundaries, the `$tag` factories, control flow (`$if`, `$for`, `$show`, `$switch`, `$dynamic`, `$portal`), `$catch`, `$suspense`, `resource`, `lazy` |
40
+ | `keits/router` | Typed routes, params and query (`navigate("/jobs/:id", { params: { id } })` is checked), layouts that stay mounted, guards, `onLeave`, link clicks, scroll restoration |
41
+ | `keits/api` | `createApi()`: JSON requests, `ApiError`, timeouts, one shared token refresh on 401, cached queries with `invalidate("/jobs")` |
42
+ | `keits/forms` | `form()`: `bind()` for inputs, Standard Schema (zod, valibot...) or plain checks, typed paths, lists, submit, server errors on their fields |
43
+ | `keits/static` | `renderToString()`, `head()`, `hydrate()`, `island()` and `hydrateIslands()` |
44
+ | `keits/vite` | Vite plugin: builds every page to HTML, with `sitemap.xml`, `robots.txt` and incremental builds |
45
+ | `keits/testing` | `render()`, queries by role, label and text, `user.click/type/submit`, `renderOnServer()` |
46
+ | `keits/svg` | SVG element factories |
40
47
 
41
- Every effect and computed belongs to an **owner**. Disposing the owner disposes everything
42
- created inside it, so nothing leaks.
48
+ ## Data
43
49
 
44
50
  ```ts
45
- import { createRoot, effect, onCleanup, onMount } from "keits";
46
-
47
- const dispose = createRoot((dispose) => {
48
- effect(() => {
49
- const id = setInterval(tick, 1000);
50
- onCleanup(() => clearInterval(id)); // runs before each re-run, and on dispose
51
- });
52
- onMount(() => console.log("ready")); // once, after the current update settles
53
- return dispose;
54
- });
51
+ import { $for, $li, $suspense, $ul } from "keits";
52
+ import { createApi } from "keits/api";
53
+
54
+ const api = createApi({ baseUrl: "/api", headers: () => ({ Authorization: `Bearer ${token()}` }) });
55
55
 
56
- dispose();
56
+ function Jobs() {
57
+ const jobs = api.query<Job[]>("/jobs", { query: () => ({ page: page() }) }); // reloads when page changes
58
+ return $suspense(() => $ul($for(() => jobs() ?? [], (job) => $li(job.title))), () => "Loading…");
59
+ }
60
+
61
+ await api.post("/jobs", { body: draft, invalidate: "/jobs" }); // lists under /jobs refresh
57
62
  ```
58
63
 
59
- - An effect created inside another effect is disposed when the outer one re-runs.
60
- - Parent effects always run before their children.
61
- - `getOwner()` / `runWithOwner(owner, fn)` resume an owner later, e.g. after an `await`.
64
+ Create resources and queries in the component body, and read them inside `() =>`.
62
65
 
63
- ## Errors
66
+ ## Routing
64
67
 
65
68
  ```ts
66
- import { catchError, effect } from "keits";
67
-
68
- catchError(
69
- () => {
70
- effect(() => {
71
- if (input() < 0) throw new Error("negative");
72
- });
73
- },
74
- (error) => showError(error), // error: unknown
75
- );
69
+ import { createRouter } from "keits/router";
70
+
71
+ export const router = createRouter({
72
+ routes: [
73
+ {
74
+ path: "/",
75
+ layout: Shell, // stays mounted while its pages change
76
+ children: [
77
+ { path: "", component: Home },
78
+ { path: "jobs/:id", component: Job, guard: () => loggedIn() || "/login" },
79
+ ],
80
+ },
81
+ { path: "*", component: NotFound },
82
+ ],
83
+ });
84
+
85
+ mount(() => router.view(), document.getElementById("app")!);
76
86
  ```
77
87
 
78
- Errors from effects, cleanups and `onMount` go to the nearest `catchError`. With none,
79
- the rest of the update still finishes and the error is rethrown afterwards (several
80
- become one `AggregateError`). A failed effect keeps its subscriptions and retries when
81
- its inputs change.
88
+ ## Static sites and server rendering
82
89
 
83
- ## Context
90
+ Pages render to HTML at build time. Only islands load JavaScript in the browser:
84
91
 
85
92
  ```ts
86
- import { createContext, provide, useContext } from "keits";
93
+ // The interactive part. Everything else on the page stays plain HTML.
94
+ export const ContactForm = island("contact-form", (props: { to: string }) => ...);
87
95
 
88
- const Theme = createContext("light");
96
+ // In the browser:
97
+ hydrateIslands({ "contact-form": () => import("./contact-form").then((m) => m.ContactForm) });
98
+ ```
89
99
 
90
- provide(Theme, "dark", () => {
91
- useContext(Theme); // "dark", here and in anything created in here, even later
92
- });
100
+ ```ts
101
+ // vite.config.ts
102
+ import { keits } from "keits/vite";
103
+ export default { plugins: [keits({ entry: "src/server.ts", site: "https://example.com" })] };
104
+
105
+ // src/server.ts: the pages to build, and how to render one
106
+ export const pages = () => staticPaths(routes); // param routes list theirs with `paths: () => [...]`
107
+ export const render = (url: string) => renderToString(() => App(url));
93
108
  ```
94
109
 
95
- ## Stores
110
+ `index.html` needs `<!--app-head-->` in `<head>` and `<!--app-html-->` where the page goes.
111
+ For a whole app, use `renderToString(App, { hydrate: true })` on the server and `hydrate(App, el)` in the browser.
96
112
 
97
- Fine-grained reactivity for nested objects and arrays.
113
+ ## Testing
98
114
 
99
115
  ```ts
100
- import { store, reconcile, unwrap } from "keits";
116
+ import { cleanup, render, user } from "keits/testing";
101
117
 
102
- const [state, setState] = store({ filter: "all", jobs: [] as Job[] });
118
+ afterEach(cleanup);
103
119
 
104
- effect(() => console.log(state.jobs[0]?.amount)); // tracks exactly that field
105
-
106
- setState((draft) => {
107
- draft.jobs.push({ id: 1, amount: 100 }); // only readers of what changed re-run
108
- draft.filter = "paid";
120
+ it("signs up", () => {
121
+ const page = render(() => SignupForm());
122
+ user.type(page.getByLabelText("Email"), "kei@example.com");
123
+ user.click(page.getByRole("button", { name: "Sign up" }));
109
124
  });
110
-
111
- // Fresh data from an API: keep existing objects, update only what changed
112
- setState((draft) => reconcile(draft.jobs, freshJobs, { key: "id" }));
113
-
114
- localStorage.setItem("state", JSON.stringify(unwrap(state)));
115
125
  ```
116
126
 
117
- Stores are read-only outside `setState`, enforced both by the types and at runtime in dev.
127
+ ## Security
128
+
129
+ - Text is always escaped, in the browser and on the server. `unsafeHTML()` is the only way to insert markup.
130
+ - URL props (`href`, `src`, `action`...) block `javascript:` URLs, `innerHTML` and `srcdoc` aren't allowed as props, and event props must be functions.
131
+ - Validate data you don't control with `parse`, so its types are true at runtime as well:
118
132
 
119
- ## Static rendering
133
+ ```ts
134
+ const comments = api.query("/comments", { parse: Comments.parse }); // a zod or valibot schema
135
+ ```
120
136
 
121
- `renderStatic(fn)` runs components the way a static build does: `effect` and `onMount`
122
- are skipped, everything else works, and it all gets disposed afterwards. `isServer` is
123
- `true` outside the browser.
137
+ - A plain object as the first argument is read as props. When a value from outside might not be a string, write `$p(String(value))` or put it after a props object: `$p({}, value)`. A plain object there is refused with an error.
124
138
 
125
139
  ## License
126
140
 
@@ -0,0 +1,275 @@
1
+ import { t as resource } from "./shared/resource-DlgzdtcG.js";
2
+ import { f as isStaticRender } from "./shared/graph-SIvYLXSv.js";
3
+ import { a as onCleanup } from "./shared/owner-BuwIoI4j.js";
4
+ // src/api/url.ts
5
+ function buildPath(path, params, query) {
6
+ const filled = path.replace(/:([A-Za-z0-9_]+)/g, (_, name) => {
7
+ const value = params?.[name];
8
+ if (value === void 0) throw new Error(`[keits/api] Missing param "${name}" for "${path}".`);
9
+ const text = String(value);
10
+ if (text === "." || text === "..") throw new Error(`[keits/api] Param "${name}" can't be "${text}" (in "${path}").`);
11
+ return encodeURIComponent(text);
12
+ });
13
+ if (query === void 0) return filled;
14
+ const search = new URLSearchParams();
15
+ for (const [key, value] of Object.entries(query)) {
16
+ if (value === null || value === void 0) continue;
17
+ if (Array.isArray(value)) for (const item of value) search.append(key, String(item));
18
+ else search.append(key, String(value));
19
+ }
20
+ const text = search.toString();
21
+ return text === "" ? filled : `${filled}${filled.includes("?") ? "&" : "?"}${text}`;
22
+ }
23
+ function underPrefix(url, prefix) {
24
+ if (!url.startsWith(prefix)) return false;
25
+ const next = url.charAt(prefix.length);
26
+ return next === "" || next === "/" || next === "?" || prefix.endsWith("/");
27
+ }
28
+ // src/api/cache.ts
29
+ function createQueryCache(load, staleTime, maxEntries = 100) {
30
+ const entries = /* @__PURE__ */ new Map();
31
+ const watchers = /* @__PURE__ */ new Set();
32
+ const entryFor = (url) => {
33
+ let entry = entries.get(url);
34
+ if (entry === void 0) {
35
+ entry = {
36
+ data: void 0,
37
+ hasData: false,
38
+ fetchedAt: 0,
39
+ promise: null,
40
+ generation: 0
41
+ };
42
+ entries.set(url, entry);
43
+ evict();
44
+ }
45
+ return entry;
46
+ };
47
+ const evict = () => {
48
+ if (entries.size <= maxEntries) return;
49
+ const shown = new Set([...watchers].map((watcher) => watcher.url));
50
+ for (const [url, entry] of entries) {
51
+ if (entries.size <= maxEntries) return;
52
+ if (!shown.has(url) && entry.promise === null) entries.delete(url);
53
+ }
54
+ };
55
+ return {
56
+ peek(url) {
57
+ const entry = entries.get(url);
58
+ if (entry === void 0 || !entry.hasData) return null;
59
+ return {
60
+ data: entry.data,
61
+ stale: Date.now() - entry.fetchedAt >= staleTime
62
+ };
63
+ },
64
+ fetch(url) {
65
+ const entry = entryFor(url);
66
+ if (entry.promise !== null) return entry.promise;
67
+ const generation = entry.generation;
68
+ const promise = load(url).then((data) => {
69
+ if (entry.promise === promise) entry.promise = null;
70
+ if (entry.generation !== generation) return data;
71
+ entry.data = data;
72
+ entry.hasData = true;
73
+ entry.fetchedAt = Date.now();
74
+ for (const watcher of watchers) if (watcher.url === url) watcher.push(data);
75
+ return data;
76
+ }, (error) => {
77
+ if (entry.promise === promise) entry.promise = null;
78
+ throw error;
79
+ });
80
+ entry.promise = promise;
81
+ return promise;
82
+ },
83
+ watch(watcher) {
84
+ watchers.add(watcher);
85
+ return () => watchers.delete(watcher);
86
+ },
87
+ async invalidate(prefix) {
88
+ for (const [url, entry] of entries) {
89
+ if (!underPrefix(url, prefix)) continue;
90
+ entry.fetchedAt = 0;
91
+ entry.generation++;
92
+ entry.promise = null;
93
+ }
94
+ const shown = [...watchers].filter((watcher) => watcher.url !== null && underPrefix(watcher.url, prefix));
95
+ await Promise.all(shown.map((watcher) => watcher.refetch()));
96
+ },
97
+ clear() {
98
+ entries.clear();
99
+ }
100
+ };
101
+ }
102
+ // src/api/error.ts
103
+ var ApiError = class extends Error {
104
+ name = "ApiError";
105
+ status;
106
+ body;
107
+ method;
108
+ url;
109
+ constructor(init) {
110
+ super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
111
+ this.status = init.status;
112
+ this.body = init.body;
113
+ this.method = init.method;
114
+ this.url = init.url;
115
+ }
116
+ get timedOut() {
117
+ return this.status === 0 && this.cause?.name === "TimeoutError";
118
+ }
119
+ };
120
+ // src/api/client.ts
121
+ function createApi(config = {}) {
122
+ const base = (config.baseUrl ?? "").replace(/\/+$/, "");
123
+ let refreshing = null;
124
+ const refreshOnce = () => refreshing ??= Promise.resolve().then(() => config.refresh()).then(Boolean, () => false).finally(() => {
125
+ refreshing = null;
126
+ });
127
+ async function send(method, path, options, retried = false) {
128
+ if (!/^\/(?![/\\])/.test(path)) throw new Error(`[keits/api] "${path}" must start with a single "/".`);
129
+ const url = base + path;
130
+ const headers = new Headers({ Accept: "application/json" });
131
+ const shared = typeof config.headers === "function" ? await config.headers() : config.headers;
132
+ for (const extra of [shared, options.headers]) if (extra !== void 0) new Headers(extra).forEach((value, key) => headers.set(key, value));
133
+ let body = null;
134
+ if (options.body !== void 0) {
135
+ if (isRawBody(options.body)) body = options.body;
136
+ else {
137
+ body = JSON.stringify(options.body);
138
+ if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
139
+ }
140
+ }
141
+ const timeout = options.timeout ?? config.timeout;
142
+ const { signal, done } = withTimeout(options.signal, timeout);
143
+ const init = {
144
+ method,
145
+ headers,
146
+ body,
147
+ signal
148
+ };
149
+ if (config.credentials !== void 0) init.credentials = config.credentials;
150
+ let response;
151
+ let data;
152
+ try {
153
+ response = await (config.fetch ?? fetch)(url, init);
154
+ if (response.status === 401 && config.refresh !== void 0 && !retried) {
155
+ done();
156
+ if (await refreshOnce()) return send(method, path, options, true);
157
+ }
158
+ data = await readBody(response, method);
159
+ } catch (error) {
160
+ done();
161
+ if (options.signal?.aborted) throw error;
162
+ const cause = signal?.aborted ? signal.reason : error;
163
+ throw new ApiError({
164
+ status: 0,
165
+ body: void 0,
166
+ method,
167
+ url,
168
+ message: `${method} ${url} ${cause?.name === "TimeoutError" ? `timed out after ${timeout} ms` : "got no response"}`,
169
+ cause
170
+ });
171
+ }
172
+ done();
173
+ if (!response.ok) throw new ApiError({
174
+ status: response.status,
175
+ body: data,
176
+ method,
177
+ url,
178
+ message: `${method} ${url} failed with ${response.status}`
179
+ });
180
+ return options.parse ? options.parse(data) : data;
181
+ }
182
+ const request = async (method, path, options = {}) => {
183
+ const data = await send(method.toUpperCase(), buildPath(path, options.params, options.query), options);
184
+ if (options.invalidate !== void 0) {
185
+ const prefixes = typeof options.invalidate === "string" ? [options.invalidate] : options.invalidate;
186
+ await Promise.all(prefixes.map((prefix) => cache.invalidate(prefix)));
187
+ }
188
+ return data;
189
+ };
190
+ const cache = createQueryCache((path) => send("GET", path, {}), config.staleTime ?? 0);
191
+ return {
192
+ get: (path, options) => request("GET", path, options),
193
+ post: (path, options) => request("POST", path, options),
194
+ put: (path, options) => request("PUT", path, options),
195
+ patch: (path, options) => request("PATCH", path, options),
196
+ delete: (path, options) => request("DELETE", path, options),
197
+ request,
198
+ query(path, options = {}) {
199
+ const parse = options.parse ?? ((data) => data);
200
+ let shownUrl = null;
201
+ const key = () => {
202
+ const params = typeof options.params === "function" ? options.params() : options.params;
203
+ const query = typeof options.query === "function" ? options.query() : options.query;
204
+ shownUrl = params === null || params === false || query === null || query === false ? null : buildPath(path, params, query);
205
+ return shownUrl;
206
+ };
207
+ const result = resource(key, (url, { refetching }) => {
208
+ if (isStaticRender()) return send("GET", url, {}).then(parse);
209
+ const cached = refetching ? null : cache.peek(url);
210
+ if (cached === null) return cache.fetch(url).then(parse);
211
+ if (cached.stale) cache.fetch(url).catch(() => {});
212
+ return parse(cached.data);
213
+ });
214
+ const stop = cache.watch({
215
+ get url() {
216
+ return shownUrl;
217
+ },
218
+ push: (data) => result.mutate(parse(data)),
219
+ refetch: () => result.refetch()
220
+ });
221
+ onCleanup(stop);
222
+ return result;
223
+ },
224
+ async prefetch(path, options = {}) {
225
+ const url = buildPath(path, options.params, options.query);
226
+ const cached = cache.peek(url);
227
+ if (cached === null || cached.stale) await cache.fetch(url).catch(() => {});
228
+ },
229
+ invalidate: (prefix = "") => cache.invalidate(prefix),
230
+ clear: () => cache.clear()
231
+ };
232
+ }
233
+ function isRawBody(body) {
234
+ if (typeof body === "string" || body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return true;
235
+ for (const name of [
236
+ "Blob",
237
+ "FormData",
238
+ "URLSearchParams",
239
+ "ReadableStream"
240
+ ]) {
241
+ const type = globalThis[name];
242
+ if (typeof type === "function" && body instanceof type) return true;
243
+ }
244
+ return false;
245
+ }
246
+ async function readBody(response, method) {
247
+ if (method === "HEAD" || response.status === 204 || response.status === 205 || response.status === 304) return void 0;
248
+ const text = await response.text();
249
+ if (text === "") return void 0;
250
+ if (!(response.headers.get("Content-Type") ?? "").includes("json")) return text;
251
+ try {
252
+ return JSON.parse(text);
253
+ } catch {
254
+ return text;
255
+ }
256
+ }
257
+ function withTimeout(outer, timeout) {
258
+ if (timeout === void 0) return {
259
+ signal: outer ?? null,
260
+ done: () => {}
261
+ };
262
+ const controller = new AbortController();
263
+ const timer = setTimeout(() => controller.abort(new DOMException(`Timed out after ${timeout} ms`, "TimeoutError")), timeout);
264
+ const forward = () => controller.abort(outer.reason);
265
+ if (outer?.aborted) forward();
266
+ else outer?.addEventListener("abort", forward, { once: true });
267
+ return {
268
+ signal: controller.signal,
269
+ done: () => {
270
+ clearTimeout(timer);
271
+ outer?.removeEventListener("abort", forward);
272
+ }
273
+ };
274
+ }
275
+ export { ApiError, createApi };