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.
- package/README.md +93 -79
- package/dist/dev/api.js +275 -0
- package/dist/dev/forms.js +330 -0
- package/dist/dev/index.js +26 -326
- package/dist/dev/router.js +24 -5
- package/dist/dev/shared/computed-DrF8O8b4.js +40 -0
- package/dist/dev/shared/{element-C4DfKtZW.js → element-DXwmUAnz.js} +32 -111
- package/dist/dev/shared/{graph-D6-x_CWC.js → graph-SIvYLXSv.js} +62 -3
- package/dist/dev/shared/hydrate-C8cOsDDH.js +588 -0
- package/dist/dev/shared/mount-CDB2HgN5.js +23 -0
- package/dist/dev/shared/namespaces-Cz82B0Pr.js +84 -0
- package/dist/dev/shared/owner-BuwIoI4j.js +72 -0
- package/dist/dev/shared/render-context-k2uu_dM_.js +34 -0
- package/dist/dev/shared/render-effect-Uk9dDmuU.js +32 -0
- package/dist/dev/shared/resource-DlgzdtcG.js +145 -0
- package/dist/dev/shared/signal-B3xOKbVm.js +24 -0
- package/dist/dev/shared/store-0vEg2bQV.js +152 -0
- package/dist/dev/shared/unsafe-keys-CB1P22No.js +8 -0
- package/dist/dev/static.js +76 -0
- package/dist/dev/svg.js +2 -1
- package/dist/dev/testing.js +216 -0
- package/dist/dev/vite.js +141 -0
- package/dist/prod/api.js +215 -0
- package/dist/prod/forms.js +240 -0
- package/dist/prod/index.js +110 -327
- package/dist/prod/router.js +83 -68
- package/dist/prod/shared/computed-BjqJ6Pps.js +33 -0
- package/dist/prod/shared/element-DCit4-3e.js +129 -0
- package/dist/prod/shared/{graph-C_aA46c6.js → graph-CR2WKbwr.js} +107 -63
- package/dist/prod/shared/hydrate-kKnJbkV7.js +480 -0
- package/dist/prod/shared/mount-DbeKIoyD.js +18 -0
- package/dist/prod/shared/namespaces-BSRrBJIU.js +71 -0
- package/dist/prod/shared/owner-DBi3odT4.js +67 -0
- package/dist/prod/shared/render-context-DF8lr1uu.js +30 -0
- package/dist/prod/shared/render-effect-UFDi2Pfh.js +25 -0
- package/dist/prod/shared/resource-Ch5tVseZ.js +91 -0
- package/dist/prod/shared/signal-BDMlfa0Z.js +16 -0
- package/dist/prod/shared/store-CvW0DbmK.js +110 -0
- package/dist/prod/shared/unsafe-keys-C5PMlerl.js +7 -0
- package/dist/prod/static.js +48 -0
- package/dist/prod/svg.js +3 -2
- package/dist/prod/testing.js +144 -0
- package/dist/prod/vite.js +106 -0
- package/dist/types/api/cache.d.ts +16 -0
- package/dist/types/api/client.d.ts +42 -0
- package/dist/types/api/error.d.ts +16 -0
- package/dist/types/api/index.d.ts +3 -0
- package/dist/types/api/url.d.ts +5 -0
- package/dist/types/async/render-context.d.ts +10 -0
- package/dist/types/core/effect.d.ts +1 -0
- package/dist/types/core/graph.d.ts +11 -0
- package/dist/types/core/owner.d.ts +1 -0
- package/dist/types/core/unsafe-keys.d.ts +2 -0
- package/dist/types/dom/hooks.d.ts +4 -0
- package/dist/types/dom/types.d.ts +5 -0
- package/dist/types/forms/form.d.ts +55 -0
- package/dist/types/forms/index.d.ts +2 -0
- package/dist/types/forms/paths.d.ts +6 -0
- package/dist/types/forms/types.d.ts +38 -0
- package/dist/types/router/index.d.ts +1 -0
- package/dist/types/router/match.d.ts +1 -0
- package/dist/types/router/types.d.ts +1 -0
- package/dist/types/static/head.d.ts +36 -0
- package/dist/types/static/hydrate.d.ts +3 -0
- package/dist/types/static/index.d.ts +4 -0
- package/dist/types/static/island.d.ts +14 -0
- package/dist/types/static/json.d.ts +1 -0
- package/dist/types/static/render.d.ts +11 -0
- package/dist/types/static/server-dom.d.ts +100 -0
- package/dist/types/testing/index.d.ts +62 -0
- package/dist/types/vite/index.d.ts +24 -0
- package/package.json +46 -5
- package/dist/dev/shared/owner-DlUsXKXE.js +0 -122
- package/dist/prod/shared/element-DUtXb3px.js +0 -187
- 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
|
|
14
|
-
|
|
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
|
-
##
|
|
15
|
+
## A component
|
|
17
16
|
|
|
18
17
|
```ts
|
|
19
|
-
import {
|
|
18
|
+
import { $button, $p, mount, signal } from "keits";
|
|
20
19
|
|
|
21
|
-
|
|
22
|
-
const
|
|
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
|
-
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
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
|
-
|
|
42
|
-
created inside it, so nothing leaks.
|
|
48
|
+
## Data
|
|
43
49
|
|
|
44
50
|
```ts
|
|
45
|
-
import {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
##
|
|
66
|
+
## Routing
|
|
64
67
|
|
|
65
68
|
```ts
|
|
66
|
-
import {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
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
|
-
|
|
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
|
-
|
|
90
|
+
Pages render to HTML at build time. Only islands load JavaScript in the browser:
|
|
84
91
|
|
|
85
92
|
```ts
|
|
86
|
-
|
|
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
|
-
|
|
96
|
+
// In the browser:
|
|
97
|
+
hydrateIslands({ "contact-form": () => import("./contact-form").then((m) => m.ContactForm) });
|
|
98
|
+
```
|
|
89
99
|
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
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
|
-
|
|
113
|
+
## Testing
|
|
98
114
|
|
|
99
115
|
```ts
|
|
100
|
-
import {
|
|
116
|
+
import { cleanup, render, user } from "keits/testing";
|
|
101
117
|
|
|
102
|
-
|
|
118
|
+
afterEach(cleanup);
|
|
103
119
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
|
|
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
|
-
|
|
133
|
+
```ts
|
|
134
|
+
const comments = api.query("/comments", { parse: Comments.parse }); // a zod or valibot schema
|
|
135
|
+
```
|
|
120
136
|
|
|
121
|
-
|
|
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
|
|
package/dist/dev/api.js
ADDED
|
@@ -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 };
|