acrylblends 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +2 -2
  2. package/dist/index.js +41 -1
  3. package/dist/index.js.map +1 -1
  4. package/docs/framework/README.md +2 -1
  5. package/docs/framework/UPSTREAM.md +1 -1
  6. package/docs/framework/api/summary.md +6 -3
  7. package/docs/framework/cordis/node-server.md +3 -0
  8. package/docs/framework/getting-started/deploy.md +133 -0
  9. package/docs/framework/getting-started/nodejs.md +37 -16
  10. package/docs/framework/guides/client-modules.md +175 -0
  11. package/docs/framework/guides/forms-and-sessions.md +1 -1
  12. package/docs/framework/guides/jsx-dom.md +6 -1
  13. package/docs/framework/guides/validation.md +87 -0
  14. package/docs/framework/helpers/testing.md +17 -0
  15. package/docs/framework/upstream.json +3 -3
  16. package/lib/browser/client.js +307 -0
  17. package/lib/browser/jsx-dom.js +1432 -0
  18. package/lib/index.js +1 -25
  19. package/lib/node-server/register.js +7 -49
  20. package/lib/node-server.d.ts +74 -7
  21. package/lib/node-server.js +264 -7
  22. package/lib/schema-validator.d.ts +40 -14
  23. package/lib/schema-validator.js +2 -2
  24. package/lib/src-0hI7M7cN.js +27 -0
  25. package/lib/transpile-CTnWof4z.js +90 -0
  26. package/package.json +1 -1
  27. package/plugins/acryl-inspect/upstream.json +1 -1
  28. package/plugins/acryl-node-server/src/adapter/server.ts +28 -5
  29. package/plugins/acryl-node-server/src/adapter/types.ts +14 -2
  30. package/plugins/acryl-node-server/src/client-modules.ts +293 -0
  31. package/plugins/acryl-node-server/src/register.ts +5 -62
  32. package/plugins/acryl-node-server/src/transpile.ts +120 -0
  33. package/plugins/acryl-node-server/upstream.json +4 -3
  34. package/plugins/acryl-router/src/browser/client.ts +3 -0
  35. package/plugins/acryl-router/src/browser/jsx-dom.ts +9 -0
  36. package/plugins/acryl-router/src/helpers/index.ts +1 -1
  37. package/plugins/acryl-router/src/helpers/schema-validator.ts +39 -12
  38. package/plugins/acryl-router/upstream.json +2 -2
  39. package/plugins/acryl-router-http/upstream.json +1 -1
  40. package/plugins/acryl-state/upstream.json +1 -1
  41. package/plugins/desktop/upstream.json +1 -1
  42. package/plugins/desktop-web/upstream.json +1 -1
  43. package/templates/agent/package.json +4 -3
  44. package/templates/blank/package.json +4 -3
  45. package/templates/todo/package.json +4 -3
  46. package/templates/todo/upstream.json +1 -1
@@ -0,0 +1,175 @@
1
+ # Client components without a bundler
2
+
3
+ A page can run [client components](jsx-dom.md) written in TypeScript and JSX with no bundler and no build configuration. `clientModules` from
4
+ `acrylblends/node-server` serves a folder of client modules to the browser: each `.tsx`, `.ts` or `.jsx` file is compiled when the browser asks
5
+ for it, with your app's own `typescript`, and the framework's browser imports are pointed at the browser builds the package ships. The page
6
+ needs one script tag.
7
+
8
+ It runs on Node, the runtime the framework targets. For a large client app with many npm packages, a bundler (Vite, esbuild) remains the
9
+ better tool; see [The `acrylblends/jsx/dom` runtime](jsx-dom.md#the-acrylblendsjsxdom-runtime).
10
+
11
+ ## Set up
12
+
13
+ The routes, with the type the browser's typed client uses, in a file of their own (`app.ts`):
14
+
15
+ ```ts
16
+ import { Acryl } from 'acrylblends'
17
+
18
+ export const app = new Acryl()
19
+ .get('/', (c) =>
20
+ c.html(
21
+ '<!doctype html><div id="counter"></div><p id="greeting"></p>' +
22
+ '<script type="module" src="/client/counter.tsx"></script>'
23
+ )
24
+ )
25
+ .get('/api/hello', (c) => c.json({ hello: 'browser' }))
26
+
27
+ export type AppType = typeof app
28
+ ```
29
+
30
+ The Node entry routes the client modules next to them (`site.ts`):
31
+
32
+ ```ts
33
+ import { Acryl } from 'acrylblends'
34
+ import { clientModules, serve } from 'acrylblends/node-server'
35
+ import { app } from './app.ts'
36
+
37
+ const site = new Acryl()
38
+ .route('/', app)
39
+ .route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
40
+
41
+ serve({ fetch: site.fetch, port: 3000 })
42
+ ```
43
+
44
+ A client component (`src/client/counter.tsx`), with a helper module beside it (`src/client/parts/label.ts`):
45
+
46
+ ```tsx
47
+ import { render, useState } from 'acrylblends/jsx/dom'
48
+ import { hc } from 'acrylblends/client'
49
+ import type { AppType } from '../../app.ts'
50
+ import { label } from './parts/label.ts'
51
+
52
+ const Counter = () => {
53
+ const [count, setCount] = useState(0)
54
+ return <button onClick={() => setCount(count + 1)}>{label(count)}</button>
55
+ }
56
+
57
+ render(<Counter />, document.getElementById('counter')!)
58
+
59
+ const client = hc<AppType>(location.origin)
60
+ const { hello } = await (await client.api.hello.$get()).json()
61
+ document.getElementById('greeting')!.textContent = `hello ${hello}`
62
+ ```
63
+
64
+ ```ts
65
+ export const label = (count: number): string => `Count ${count}`
66
+ ```
67
+
68
+ Start the site with `node site.ts` and open `http://localhost:3000`. Edit `counter.tsx` and reload: the module is compiled again.
69
+
70
+ Your editor checks the client folder as browser code with its own `src/client/tsconfig.json`: the DOM library, the DOM renderer, no Node
71
+ types. This is why `AppType` comes from `app.ts`, which does not import the Node adapter.
72
+
73
+ ```json
74
+ {
75
+ "compilerOptions": {
76
+ "target": "ES2024",
77
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
78
+ "module": "NodeNext",
79
+ "moduleResolution": "NodeNext",
80
+ "strict": true,
81
+ "noEmit": true,
82
+ "allowImportingTsExtensions": true,
83
+ "jsx": "react-jsx",
84
+ "jsxImportSource": "acrylblends/jsx/dom",
85
+ "types": []
86
+ },
87
+ "include": ["**/*.ts", "**/*.tsx"]
88
+ }
89
+ ```
90
+
91
+ ## Server markup and `hydrateRoot`
92
+
93
+ A page can carry server-rendered markup for an island and take it over in the browser with `hydrateRoot` from `acrylblends/jsx/dom/client`:
94
+
95
+ ```tsx
96
+ import { useState } from 'acrylblends/jsx/dom'
97
+ import { hydrateRoot } from 'acrylblends/jsx/dom/client'
98
+
99
+ const Counter = () => {
100
+ const [count, setCount] = useState(0)
101
+ return <button onClick={() => setCount(count + 1)}>Count {count}</button>
102
+ }
103
+
104
+ hydrateRoot(document.getElementById('island')!, <Counter />)
105
+ ```
106
+
107
+ The DOM renderer does not reuse server markup: `hydrateRoot` renders the component and replaces the element's children with its output
108
+ in one step, so the page shows the server markup until the module runs and the component from then on, with no empty frame between. The
109
+ server's nodes are gone afterwards, together with anything the visitor did to them before the module ran: focus, a selection, text typed
110
+ into an input. Keep the server markup the same as the component's first render, so the swap does not show, and keep inputs out of the
111
+ server markup of an island, or render them only in the browser.
112
+
113
+ ## How the imports reach the browser
114
+
115
+ - JSX in a client module always compiles for the DOM renderer (`acrylblends/jsx/dom`), whatever the server's `tsconfig.json` says. A file's
116
+ own `/** @jsxImportSource ... */` comment still wins.
117
+ - `acrylblends/jsx/dom`, its `jsx-runtime`, `jsx-dev-runtime` and `client` are one browser module (`@acrylblends/jsx-dom.js`), and
118
+ `acrylblends/client` is another (`@acrylblends/client.js`). Neither imports anything. The same app serves them, and each import is
119
+ rewritten to a URL relative to the module, so the setup works under whatever path you route `clientModules` at.
120
+ - Import your own modules with their file names, as the browser fetches them: `import { label } from './parts/label.ts'`.
121
+ - Another package (`import confetti from 'canvas-confetti'`) is left as it is: add an
122
+ [import map](https://developer.mozilla.org/docs/Web/HTML/Element/script/type/importmap) to the page for it, or use a bundler.
123
+ - `.js` and `.mjs` files are served unchanged.
124
+
125
+ A module is compiled once and kept in memory until its file changes, up to 16 MiB of compiled code (the least recently served goes first;
126
+ set `cacheBytes` to change the bound). Responses carry an `ETag` and `Cache-Control: no-cache`, so the browser revalidates and an edit shows
127
+ on the next reload. Only files inside the folder are served: a path with `..` or a dot segment, a `.d.ts` file, a symbolic link out of the
128
+ folder and other file types answer 404.
129
+
130
+ ## In production
131
+
132
+ Templates install `typescript` as a development dependency, and a deploy that leaves those out (`npm ci --omit=dev`) has no compiler.
133
+ Compile the client folder once when you build, as the `build` script of your `package.json`:
134
+
135
+ ```json
136
+ {
137
+ "scripts": {
138
+ "build": "acrylblends build-client"
139
+ }
140
+ }
141
+ ```
142
+
143
+ `acrylblends build-client [root] [outDir]` (from acrylblends 0.7.2; `src/client` and `dist/client` when not given) calls
144
+ `buildClientModules`. With an earlier version, or without the command line tool, call the function itself:
145
+
146
+ ```json
147
+ {
148
+ "scripts": {
149
+ "build": "node --input-type=module -e \"import { buildClientModules } from 'acrylblends/node-server'; buildClientModules({ root: 'src/client', outDir: 'dist/client' })\""
150
+ }
151
+ }
152
+ ```
153
+
154
+ It writes each module compiled to `dist/client` at the same path and file name, so the page's URLs stay the same, and copies the two
155
+ browser modules to `dist/client/@acrylblends/`. Run it where `typescript` is installed, before the development dependencies are removed.
156
+
157
+ With `NODE_ENV=production` and the `compiled` option set, `clientModules` serves only that folder and compiles nothing. A module that is in
158
+ `src/client` but missing from `dist/client` answers 500 with a message to build again, and a `compiled` folder that does not exist stops the
159
+ server at startup. Outside production, modules are always compiled on request, so a stale `dist/client` never hides an edit.
160
+
161
+ When `typescript` is missing where a module has to be compiled, the module answers 500 with the message
162
+ `... is a client module, and compiling it needs the typescript package in this app: npm install --save-dev typescript`.
163
+
164
+ ## Reference
165
+
166
+ `clientModules(options)` returns an app; route it where the page's script tags point.
167
+
168
+ | Option | Meaning |
169
+ | --- | --- |
170
+ | `root` | The folder of client modules, absolute or relative to the working directory. |
171
+ | `compiled` | The folder `buildClientModules` wrote. Served instead of compiling when `NODE_ENV` is `production`. |
172
+ | `cacheBytes` | The bound of the in-memory cache of compiled modules, in bytes. 16 MiB when not given. |
173
+
174
+ `buildClientModules({ root, outDir })` compiles every module below `root` (dot files, `node_modules` and `.d.ts` files skipped) into `outDir`,
175
+ which must not lie inside `root`, and returns the paths it wrote. Files already in `outDir` that no source produces are left there.
@@ -228,4 +228,4 @@ export const Field = () => (
228
228
  )
229
229
  ```
230
230
 
231
- [Client Components](jsx-dom.md) (`acrylblends/jsx/dom`) are for pages that need components and state in the browser; they have to be bundled for the browser first (with Vite or esbuild).
231
+ [Client Components](jsx-dom.md) (`acrylblends/jsx/dom`) are for pages that need components and state in the browser; on Node, [Client components without a bundler](client-modules.md) serves them to the browser with one script tag, or bundle them with Vite or esbuild.
@@ -2,7 +2,9 @@
2
2
 
3
3
  `acrylblends/jsx` supports not only server side but also client side. This means that it is possible to create an interactive UI that runs in the browser. We call it Client Components or `acrylblends/jsx/dom`.
4
4
 
5
- It is fast and very small. The counter program in `acrylblends/jsx/dom` is only 2.8KB with Brotli compression, but 47.8KB for React.
5
+ It is small and imports nothing. Measured with Node's `zlib.brotliCompressSync` at the highest quality: the whole runtime as
6
+ [`clientModules`](client-modules.md) serves it (`jsx-dom.js`, not minified) is 11,209 bytes with Brotli compression, and the counter
7
+ below, bundled and minified with tsdown so only the parts it uses are kept, is 5,804 bytes.
6
8
 
7
9
  This section introduces Client Components-specific features.
8
10
 
@@ -272,6 +274,9 @@ export default function App() {
272
274
 
273
275
  ## The `acrylblends/jsx/dom` runtime
274
276
 
277
+ On Node you can skip the bundler: [Client components without a bundler](client-modules.md) serves `.tsx` client modules to the browser with
278
+ this runtime and one script tag, in development and in production.
279
+
275
280
  There is a small JSX Runtime for Client Components. Using this will result in smaller bundled results than using `acrylblends/jsx`. Specify `acrylblends/jsx/dom` in `tsconfig.json`. For Deno, modify the deno.json.
276
281
 
277
282
  ```json
@@ -144,6 +144,93 @@ app.post(
144
144
  )
145
145
  ```
146
146
 
147
+ ## Validating an HTML form
148
+
149
+ A browser posts a `<form>` as `application/x-www-form-urlencoded`, or as `multipart/form-data` when it has `enctype="multipart/form-data"` (needed
150
+ for file inputs). `validator('form', ...)` parses both. Each field arrives as a `string`, a file input as a `File`, and a name that appears more
151
+ than once (several checkboxes, or a name ending in `[]`) as an array, so the value has the type `Record<string, string | File | (string | File)[]>`.
152
+
153
+ This page shows a form and re-renders it with a message when a field is wrong:
154
+
155
+ ```ts
156
+ import { Acryl } from 'acrylblends'
157
+ import { html } from 'acrylblends/html'
158
+ import { validator } from 'acrylblends/validator'
159
+
160
+ const page = (error?: string) => html`<!doctype html>
161
+ <form method="post" action="/notes" enctype="multipart/form-data">
162
+ <input name="title" required>
163
+ <textarea name="body"></textarea>
164
+ <input type="file" name="attachment">
165
+ <button>Save</button>
166
+ ${error === undefined ? '' : html`<p role="alert">${error}</p>`}
167
+ </form>`
168
+
169
+ const app = new Acryl()
170
+ .get('/notes/new', (c) => c.html(page()))
171
+ .post(
172
+ '/notes',
173
+ validator('form', (form, c) => {
174
+ const { title, body, attachment } = form
175
+ if (typeof title !== 'string' || title.trim() === '') return c.html(page('Title is required'), 400)
176
+ if (body !== undefined && typeof body !== 'string') return c.html(page('Body must be text'), 400)
177
+ if (attachment !== undefined && !(attachment instanceof File)) return c.html(page('Attachment must be one file'), 400)
178
+ return {
179
+ title: title.trim(),
180
+ body: body ?? '',
181
+ // A file input left empty still sends a part: a File with no name and no bytes.
182
+ attachment: attachment !== undefined && attachment.size > 0 ? attachment : undefined,
183
+ }
184
+ }),
185
+ (c) => {
186
+ const { title, attachment } = c.req.valid('form') // { title: string, body: string, attachment: File | undefined }
187
+ return c.text(`Saved ${title}${attachment === undefined ? '' : ` with ${attachment.name}`}`, 201)
188
+ }
189
+ )
190
+ ```
191
+
192
+ The messages are escaped by `html`, so a field value shown back in the page cannot inject markup.
193
+
194
+ ### With a schema
195
+
196
+ `schemaValidator('form', schema)` takes the same value. It answers a failure with 400 and JSON issues, which suits a form your own script submits
197
+ with `fetch()`:
198
+
199
+ ```ts
200
+ import * as z from 'zod'
201
+ import { schemaValidator } from 'acrylblends/schema-validator'
202
+
203
+ const NoteForm = z.object({
204
+ title: z.string().trim().min(1, 'Title is required'),
205
+ body: z.string().default(''),
206
+ attachment: z.instanceof(File).optional(),
207
+ })
208
+
209
+ app.post('/api/notes', schemaValidator('form', NoteForm), (c) => {
210
+ const { title } = c.req.valid('form') // typed by the schema's output
211
+ return c.json({ title }, 201)
212
+ })
213
+ ```
214
+
215
+ For a plain HTML form, call the schema inside `validator('form', ...)` to re-render the page with the first message instead:
216
+
217
+ ```ts
218
+ validator('form', (form, c) => {
219
+ const result = NoteForm.safeParse(form)
220
+ return result.success ? result.data : c.html(page(result.error.issues[0]?.message), 400)
221
+ })
222
+ ```
223
+
224
+ To test a form route, send a `FormData`: `app.request` sets the `multipart/form-data` content type with its boundary itself.
225
+
226
+ ```ts
227
+ const form = new FormData()
228
+ form.set('title', 'Groceries')
229
+ form.set('attachment', new File(['milk'], 'list.txt', { type: 'text/plain' }))
230
+ const res = await app.request('/notes', { method: 'POST', body: form })
231
+ // res.status === 201, await res.text() === 'Saved Groceries with list.txt'
232
+ ```
233
+
147
234
  ## Multiple validators
148
235
 
149
236
  You can also include multiple validators to validate different parts of request:
@@ -99,3 +99,20 @@ describe('Search Endpoint', () => {
99
99
  })
100
100
  })
101
101
  ```
102
+
103
+ ### Default request options
104
+
105
+ `testClient(app, env?, executionCtx?, options?)` takes the client's request options as its fourth argument, so headers every request of a test
106
+ needs, such as a session cookie, are set once. Headers given to a single call are merged over them.
107
+
108
+ ```ts
109
+ import { Acryl } from 'acrylblends'
110
+ import { getCookie } from 'acrylblends/cookie'
111
+ import { testClient } from 'acrylblends/testing'
112
+
113
+ const app = new Acryl().get('/me', (c) => c.json({ session: getCookie(c, 'session') ?? null }))
114
+
115
+ const client = testClient(app, undefined, undefined, { headers: { cookie: 'session=abc' } })
116
+ await (await client.me.$get()).json() // { session: 'abc' }
117
+ await (await client.me.$get(undefined, { headers: { cookie: 'session=xyz' } })).json() // { session: 'xyz' }
118
+ ```
@@ -2,8 +2,8 @@
2
2
  "source": {
3
3
  "repo": "acryldev/acryl",
4
4
  "path": "docs/framework",
5
- "commit": "524406d2033cdc5ca5e01207f9ce29543bbf221b"
5
+ "commit": "cdc083e1bbaedaeafa7494fe646bdb202ce86d09"
6
6
  },
7
- "files": 89,
8
- "digest": "sha256:fe2da945c3286e316a0412b2d3cfccc4dbf8d1c082e283b77606b45e27b778aa"
7
+ "files": 91,
8
+ "digest": "sha256:964e5ff58d487ce53394469d359a251265a3ef093354f55b6b4c47c55051774b"
9
9
  }
@@ -0,0 +1,307 @@
1
+ //#region ../../plugins/acryl-router/src/core/utils/cookie.ts
2
+ const validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
3
+ const _serialize = (name, value, opt = {}) => {
4
+ if (!validCookieNameRegEx.test(name)) throw new Error("Invalid cookie name");
5
+ let cookie = `${name}=${value}`;
6
+ if (name.startsWith("__Secure-") && !opt.secure) throw new Error("__Secure- Cookie must have Secure attributes");
7
+ if (name.startsWith("__Host-")) {
8
+ if (!opt.secure) throw new Error("__Host- Cookie must have Secure attributes");
9
+ if (opt.path !== "/") throw new Error("__Host- Cookie must have Path attributes with \"/\"");
10
+ if (opt.domain) throw new Error("__Host- Cookie must not have Domain attributes");
11
+ }
12
+ for (const key of [
13
+ "domain",
14
+ "path",
15
+ "sameSite",
16
+ "priority"
17
+ ]) if (opt[key] && /[;\r\n]/.test(opt[key])) throw new Error(`${key} must not contain ";", "\\r", or "\\n"`);
18
+ if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) {
19
+ if (opt.maxAge > 3456e4) throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");
20
+ cookie += `; Max-Age=${opt.maxAge | 0}`;
21
+ }
22
+ if (opt.domain && opt.prefix !== "host") cookie += `; Domain=${opt.domain}`;
23
+ if (opt.path) cookie += `; Path=${opt.path}`;
24
+ if (opt.expires) {
25
+ if (opt.expires.getTime() - Date.now() > 3456e7) throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");
26
+ cookie += `; Expires=${opt.expires.toUTCString()}`;
27
+ }
28
+ if (opt.httpOnly) cookie += "; HttpOnly";
29
+ if (opt.secure) cookie += "; Secure";
30
+ if (opt.sameSite) cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;
31
+ if (opt.priority) cookie += `; Priority=${opt.priority.charAt(0).toUpperCase() + opt.priority.slice(1)}`;
32
+ if (opt.partitioned) {
33
+ if (!opt.secure) throw new Error("Partitioned Cookie must have Secure attributes");
34
+ cookie += "; Partitioned";
35
+ }
36
+ return cookie;
37
+ };
38
+ const serialize = (name, value, opt) => {
39
+ value = encodeURIComponent(value);
40
+ return _serialize(name, value, opt);
41
+ };
42
+ //#endregion
43
+ //#region ../../plugins/acryl-router/src/core/client/fetch-result-please.ts
44
+ /**
45
+ * @description This file is a modified version of `fetch-result-please` (`ofetch`), minimalized and adapted to Acryl's custom needs.
46
+ *
47
+ * @link https://www.npmjs.com/package/fetch-result-please
48
+ */
49
+ const nullBodyResponses = /* @__PURE__ */ new Set([
50
+ 101,
51
+ 204,
52
+ 205,
53
+ 304
54
+ ]);
55
+ /**
56
+ * Smartly parses and return the consumable result from a fetch `Response`.
57
+ *
58
+ * Throwing a structured error if the response is not `ok`. ({@link DetailedError})
59
+ */
60
+ async function fetchRP(fetchRes) {
61
+ const _fetchRes = await fetchRes;
62
+ if ((_fetchRes.body || _fetchRes._bodyInit) && !nullBodyResponses.has(_fetchRes.status)) _fetchRes._data = await _fetchRes[detectResponseType(_fetchRes)]();
63
+ if (!_fetchRes.ok) throw new DetailedError(`${_fetchRes.status} ${_fetchRes.statusText}`, {
64
+ statusCode: _fetchRes?.status,
65
+ detail: {
66
+ data: _fetchRes?._data,
67
+ statusText: _fetchRes?.statusText
68
+ }
69
+ });
70
+ return _fetchRes._data;
71
+ }
72
+ var DetailedError = class extends Error {
73
+ /**
74
+ * Additional `message` that will be logged AND returned to client
75
+ */
76
+ detail;
77
+ /**
78
+ * Additional `code` that will be logged AND returned to client
79
+ */
80
+ code;
81
+ /**
82
+ * Additional value that will be logged AND NOT returned to client
83
+ */
84
+ log;
85
+ /**
86
+ * Optionally set the status code to return, in a web server context
87
+ */
88
+ statusCode;
89
+ constructor(message, options = {}) {
90
+ super(message);
91
+ this.name = "DetailedError";
92
+ this.log = options.log;
93
+ this.detail = options.detail;
94
+ this.code = options.code;
95
+ this.statusCode = options.statusCode;
96
+ }
97
+ };
98
+ const jsonRegex = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(?:;.+)?$/i;
99
+ function detectResponseType(response) {
100
+ const _contentType = response.headers.get("content-type");
101
+ if (!_contentType) return "text";
102
+ const contentType = _contentType.split(";").shift();
103
+ if (jsonRegex.test(contentType)) return "json";
104
+ return "text";
105
+ }
106
+ //#endregion
107
+ //#region ../../plugins/acryl-router/src/core/client/utils.ts
108
+ const mergePath = (base, path) => {
109
+ base = base.replace(/\/+$/, "");
110
+ base = base + "/";
111
+ path = path.replace(/^\/+/, "");
112
+ return base + path;
113
+ };
114
+ const replaceUrlParam = (urlString, params) => {
115
+ for (const [k, v] of Object.entries(params)) {
116
+ const reg = new RegExp("/:" + k + "(?:{[^/]+})?\\??(?=/|$)");
117
+ urlString = urlString.replace(reg, () => v ? `/${v}` : "");
118
+ }
119
+ return urlString;
120
+ };
121
+ const buildSearchParams = (query) => {
122
+ const searchParams = new URLSearchParams();
123
+ for (const [k, v] of Object.entries(query)) {
124
+ if (v === void 0) continue;
125
+ if (Array.isArray(v)) for (const v2 of v) {
126
+ if (v2 === void 0) continue;
127
+ searchParams.append(k, v2);
128
+ }
129
+ else searchParams.set(k, v);
130
+ }
131
+ return searchParams;
132
+ };
133
+ const replaceUrlProtocol = (urlString, protocol) => {
134
+ switch (protocol) {
135
+ case "ws": return urlString.replace(/^http/, "ws");
136
+ case "http": return urlString.replace(/^ws/, "http");
137
+ }
138
+ };
139
+ const removeIndexString = (urlString) => {
140
+ if (/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(urlString)) return urlString.replace(/\/index(?=\?|$)/, "/");
141
+ return urlString.replace(/\/index(?=\?|$)/, "");
142
+ };
143
+ function isObject(item) {
144
+ return typeof item === "object" && item !== null && !Array.isArray(item);
145
+ }
146
+ function deepMerge(target, source) {
147
+ if (!isObject(target) && !isObject(source)) return source;
148
+ const merged = { ...target };
149
+ for (const key in source) {
150
+ const value = source[key];
151
+ if (isObject(merged[key]) && isObject(value)) merged[key] = deepMerge(merged[key], value);
152
+ else merged[key] = value;
153
+ }
154
+ return merged;
155
+ }
156
+ /**
157
+ * Shortcut to get a consumable response from `hc`'s fetch calls (Response), with types inference.
158
+ *
159
+ * Smartly parse the response data, throwing a structured error if the response is not `ok`. ({@link DetailedError})
160
+ *
161
+ * @example const result = await parseResponse(client.posts.$get())
162
+ */
163
+ async function parseResponse(fetchRes) {
164
+ return fetchRP(fetchRes);
165
+ }
166
+ //#endregion
167
+ //#region ../../plugins/acryl-router/src/core/client/client.ts
168
+ const createProxy = (callback, path) => {
169
+ return new Proxy(() => {}, {
170
+ get(_obj, key) {
171
+ if (typeof key !== "string" || key === "then") return;
172
+ return createProxy(callback, [...path, key]);
173
+ },
174
+ apply(_1, _2, args) {
175
+ return callback({
176
+ path,
177
+ args
178
+ });
179
+ }
180
+ });
181
+ };
182
+ const appendQueryParams = (url, searchParams) => {
183
+ const queryString = searchParams.toString();
184
+ return queryString ? `${url}?${queryString}` : url;
185
+ };
186
+ var ClientRequestImpl = class {
187
+ url;
188
+ method;
189
+ buildSearchParams;
190
+ queryParams = void 0;
191
+ pathParams = {};
192
+ rBody;
193
+ cType = void 0;
194
+ constructor(url, method, options) {
195
+ this.url = url;
196
+ this.method = method;
197
+ this.buildSearchParams = options.buildSearchParams;
198
+ }
199
+ fetch = async (args, opt) => {
200
+ if (args) {
201
+ if (args.query) this.queryParams = this.buildSearchParams(args.query);
202
+ if (args.form) {
203
+ const form = new FormData();
204
+ for (const [k, v] of Object.entries(args.form)) {
205
+ if (v === void 0) continue;
206
+ if (Array.isArray(v)) for (const v2 of v) {
207
+ if (v2 === void 0) continue;
208
+ form.append(k, v2);
209
+ }
210
+ else form.append(k, v);
211
+ }
212
+ this.rBody = form;
213
+ }
214
+ if (args.json !== void 0) {
215
+ this.rBody = JSON.stringify(args.json);
216
+ this.cType = "application/json";
217
+ }
218
+ if (args.param) this.pathParams = args.param;
219
+ }
220
+ let methodUpperCase = this.method.toUpperCase();
221
+ const headerValues = {
222
+ ...args?.header,
223
+ ...typeof opt?.headers === "function" ? await opt.headers() : opt?.headers
224
+ };
225
+ if (args?.cookie) {
226
+ const cookies = [];
227
+ for (const [key, value] of Object.entries(args.cookie)) {
228
+ if (value === void 0) continue;
229
+ cookies.push(serialize(key, value));
230
+ }
231
+ if (cookies.length > 0) headerValues["Cookie"] = cookies.join("; ");
232
+ }
233
+ if (this.cType) headerValues["Content-Type"] = this.cType;
234
+ const headers = new Headers();
235
+ for (const [key, value] of Object.entries(headerValues)) if (value !== void 0) headers.set(key, value);
236
+ let url = this.url;
237
+ url = removeIndexString(url);
238
+ url = replaceUrlParam(url, this.pathParams);
239
+ if (this.queryParams) url = appendQueryParams(url, this.queryParams);
240
+ methodUpperCase = this.method.toUpperCase();
241
+ const setBody = !(methodUpperCase === "GET" || methodUpperCase === "HEAD");
242
+ return (opt?.fetch || fetch)(url, {
243
+ body: setBody ? this.rBody : void 0,
244
+ method: methodUpperCase,
245
+ headers,
246
+ ...opt?.init
247
+ });
248
+ };
249
+ };
250
+ const hc = (baseUrl, options) => createProxy(function proxyCallback(opts) {
251
+ const buildSearchParamsOption = options?.buildSearchParams ?? buildSearchParams;
252
+ const parts = [...opts.path];
253
+ const lastParts = parts.slice(-3).reverse();
254
+ if (lastParts[0] === "toString") {
255
+ if (lastParts[1] === "name") return lastParts[2] || "";
256
+ return proxyCallback.toString();
257
+ }
258
+ if (lastParts[0] === "valueOf") {
259
+ if (lastParts[1] === "name") return lastParts[2] || "";
260
+ return proxyCallback;
261
+ }
262
+ let method = "";
263
+ if (/^\$/.test(lastParts[0])) {
264
+ const last = parts.pop();
265
+ if (last) method = last.replace(/^\$/, "");
266
+ }
267
+ const url = mergePath(baseUrl, parts.join("/"));
268
+ if (method === "url" || method === "path") {
269
+ let result = removeIndexString(url);
270
+ if (opts.args[0]) {
271
+ if (opts.args[0].param) result = replaceUrlParam(result, opts.args[0].param);
272
+ if (opts.args[0].query) result = appendQueryParams(result, buildSearchParamsOption(opts.args[0].query));
273
+ }
274
+ if (method === "url") return new URL(result);
275
+ return result.slice(baseUrl.replace(/\/+$/, "").length).replace(/^\/?/, "/");
276
+ }
277
+ if (method === "ws") {
278
+ const normalizedUrl = removeIndexString(url);
279
+ const webSocketUrl = replaceUrlProtocol(opts.args[0]?.param ? replaceUrlParam(normalizedUrl, opts.args[0].param) : normalizedUrl, "ws");
280
+ const targetUrl = new URL(webSocketUrl);
281
+ const queryParams = opts.args[0]?.query;
282
+ if (queryParams) buildSearchParamsOption(queryParams).forEach((value, key) => {
283
+ targetUrl.searchParams.append(key, value);
284
+ });
285
+ const establishWebSocket = (...args) => {
286
+ if (options?.webSocket !== void 0 && typeof options.webSocket === "function") return options.webSocket(...args);
287
+ return new WebSocket(...args);
288
+ };
289
+ return establishWebSocket(targetUrl.toString());
290
+ }
291
+ const req = new ClientRequestImpl(url, method, { buildSearchParams: buildSearchParamsOption });
292
+ if (method) {
293
+ options ??= {};
294
+ const reqOptions = { ...opts.args[1] };
295
+ const baseHeaders = options.headers;
296
+ const reqHeaders = reqOptions.headers;
297
+ if (baseHeaders && reqHeaders) reqOptions.headers = async () => ({
298
+ ...typeof baseHeaders === "function" ? await baseHeaders() : baseHeaders,
299
+ ...typeof reqHeaders === "function" ? await reqHeaders() : reqHeaders
300
+ });
301
+ const args = deepMerge(options, reqOptions);
302
+ return req.fetch(opts.args[0], args);
303
+ }
304
+ return req;
305
+ }, []);
306
+ //#endregion
307
+ export { DetailedError, hc, parseResponse };