clarusjs 0.13.0 → 0.15.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/dist/check/generate.d.ts +2 -5
- package/dist/check/generate.js +148 -13
- package/dist/cli/check.d.ts +4 -0
- package/dist/cli/check.js +3 -1
- package/dist/cli/mapper.js +19 -1
- package/dist/cli/project.d.ts +4 -0
- package/dist/cli/project.js +1 -1
- package/dist/compiler/class-style.d.ts +1 -1
- package/dist/compiler/class-style.js +6 -2
- package/dist/compiler/components.d.ts +32 -0
- package/dist/compiler/components.js +63 -0
- package/dist/compiler/emit-client.js +33 -4
- package/dist/compiler/emit-server.js +21 -11
- package/dist/compiler/html-expr.d.ts +11 -2
- package/dist/compiler/html-expr.js +38 -20
- package/dist/compiler/icon.d.ts +1 -1
- package/dist/compiler/icon.js +4 -0
- package/dist/compiler/index.d.ts +13 -1
- package/dist/compiler/index.js +64 -2
- package/dist/compiler/ir.d.ts +39 -0
- package/dist/compiler/ir.js +104 -11
- package/dist/compiler/lint.js +12 -1
- package/dist/compiler/parse.d.ts +44 -0
- package/dist/compiler/parse.js +93 -10
- package/dist/compiler/script.d.ts +21 -1
- package/dist/compiler/script.js +58 -3
- package/dist/compiler/shared.d.ts +6 -0
- package/dist/compiler/shared.js +14 -0
- package/dist/fetch/index.d.ts +157 -3
- package/dist/fetch/index.js +135 -14
- package/dist/forms/index.js +15 -3
- package/dist/runtime/attrs.d.ts +6 -0
- package/dist/runtime/attrs.js +16 -0
- package/dist/runtime/dom.d.ts +42 -1
- package/dist/runtime/dom.js +152 -23
- package/dist/runtime/html.d.ts +6 -0
- package/dist/runtime/html.js +12 -0
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/loader.js +32 -6
- package/dist/runtime/router.d.ts +6 -1
- package/dist/runtime/router.js +1 -1
- package/dist/runtime/server.d.ts +20 -2
- package/dist/runtime/server.js +48 -8
- package/dist/server/handler.d.ts +28 -1
- package/dist/server/handler.js +48 -2
- package/dist/server/modes.d.ts +2 -0
- package/dist/server/modes.js +5 -1
- package/dist/server/views.d.ts +1 -1
- package/dist/server/views.js +1 -1
- package/dist/vite/plugin.d.ts +19 -0
- package/dist/vite/plugin.js +61 -14
- package/package.json +1 -1
package/dist/compiler/script.js
CHANGED
|
@@ -184,14 +184,14 @@ function signalCall(init) {
|
|
|
184
184
|
const name = init.callee.name;
|
|
185
185
|
return name === 'state' || name === 'derived' || name === 'shared' ? name : undefined;
|
|
186
186
|
}
|
|
187
|
-
export function splitImports(code, file, source, offset) {
|
|
187
|
+
export function splitImports(code, file, source, offset, server = false) {
|
|
188
188
|
const imports = [];
|
|
189
189
|
let body = code;
|
|
190
190
|
for (const stmt of parseScript(code, file, source, offset).body) {
|
|
191
191
|
if (stmt.type !== 'ImportDeclaration')
|
|
192
192
|
continue;
|
|
193
193
|
const from = String(stmt.source.value);
|
|
194
|
-
if (from.startsWith('node:')) {
|
|
194
|
+
if (!server && from.startsWith('node:')) {
|
|
195
195
|
throw new ClarusError(`\`${from}\` can't be imported in an island script: the script is bundled for the browser`, file, source, offset + stmt.start);
|
|
196
196
|
}
|
|
197
197
|
imports.push({ text: code.slice(stmt.start, stmt.end), start: stmt.start });
|
|
@@ -199,6 +199,20 @@ export function splitImports(code, file, source, offset) {
|
|
|
199
199
|
}
|
|
200
200
|
return { imports, body };
|
|
201
201
|
}
|
|
202
|
+
export function serverScriptParts(code, file, source, offset) {
|
|
203
|
+
const ast = parseScript(code, file, source, offset);
|
|
204
|
+
const imports = [];
|
|
205
|
+
let body = code;
|
|
206
|
+
for (const stmt of ast.body) {
|
|
207
|
+
if (stmt.type.startsWith('Export'))
|
|
208
|
+
throw new ClarusError('a <script server> cannot export anything: its names are for the template', file, source, offset + stmt.start);
|
|
209
|
+
if (stmt.type !== 'ImportDeclaration')
|
|
210
|
+
continue;
|
|
211
|
+
imports.push(code.slice(stmt.start, stmt.end));
|
|
212
|
+
body = body.slice(0, stmt.start) + code.slice(stmt.start, stmt.end).replace(/[^\n]/g, ' ') + body.slice(stmt.end);
|
|
213
|
+
}
|
|
214
|
+
return { imports, body, awaits: !!topLevelAwait(ast) };
|
|
215
|
+
}
|
|
202
216
|
export function untypedParams(code) {
|
|
203
217
|
const ast = parseScript(code);
|
|
204
218
|
const isFn = (n) => !!n && (n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression');
|
|
@@ -254,7 +268,7 @@ export function analyzeScript(code, file, source, offset) {
|
|
|
254
268
|
}
|
|
255
269
|
const tla = topLevelAwait(ast);
|
|
256
270
|
if (tla)
|
|
257
|
-
throw new ClarusError("top
|
|
271
|
+
throw new ClarusError("an island's <script> can't await at the top level (the browser attaches it without waiting): await data on the server in a <script server>, or in the browser inside a function, such as a resource()'s fetcher or an event handler", file, source, offset + tla.start);
|
|
258
272
|
for (const stmt of ast.body) {
|
|
259
273
|
if (stmt.type.startsWith('Export')) {
|
|
260
274
|
throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
|
|
@@ -299,6 +313,9 @@ function clientHook(code, signals, entered = new WeakSet(), forms) {
|
|
|
299
313
|
const [first, ...rest] = node.arguments;
|
|
300
314
|
return `${forms}(${first.name}${rest.map((a) => `, ${rec(a)}`).join('')})`;
|
|
301
315
|
}
|
|
316
|
+
const provided = provideCall(node, rec);
|
|
317
|
+
if (provided)
|
|
318
|
+
return provided;
|
|
302
319
|
if (node.type === 'UpdateExpression' && isSignal(node.argument)) {
|
|
303
320
|
const name = node.argument.name;
|
|
304
321
|
const op = node.operator[0];
|
|
@@ -347,11 +364,49 @@ export function rewriteClientExpr(expr, signals) {
|
|
|
347
364
|
const ast = parseExpr(expr);
|
|
348
365
|
return expr.slice(0, ast.start) + print(ast, expr, clientHook(expr, signals)) + expr.slice(ast.end);
|
|
349
366
|
}
|
|
367
|
+
export function providesIn(split, file, source, offset) {
|
|
368
|
+
for (const imp of split.imports) {
|
|
369
|
+
if (parseScript(imp.text).body[0].specifiers.some((x) => x.local.name === 'provide'))
|
|
370
|
+
throw new ClarusError('provide is reserved for context: rename this import (import { provide as other } …)', file, source, offset + imp.start);
|
|
371
|
+
}
|
|
372
|
+
const code = split.body;
|
|
373
|
+
let found = false;
|
|
374
|
+
const usage = "provide is called with a string key and a value: provide('tabs', { value })";
|
|
375
|
+
const hook = (node, parent, key) => {
|
|
376
|
+
if (node.type === 'Identifier' && node.name === 'provide' && !(parent?.type === 'CallExpression' && key === 'callee') && (!isBinding(parent, key) || parent?.shorthand)) {
|
|
377
|
+
throw new ClarusError(usage, file, source, offset + node.start);
|
|
378
|
+
}
|
|
379
|
+
const declared = (node.type === 'FunctionDeclaration' || node.type === 'VariableDeclarator' || node.type === 'ClassDeclaration') && node.id?.type === 'Identifier' && node.id.name === 'provide';
|
|
380
|
+
if (declared)
|
|
381
|
+
throw new ClarusError('provide is reserved for context: give this function another name', file, source, offset + node.start);
|
|
382
|
+
if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'provide') {
|
|
383
|
+
found = true;
|
|
384
|
+
const key = node.arguments[0];
|
|
385
|
+
if (!key || key.type !== 'Literal' || typeof key.value !== 'string' || node.arguments.length !== 2) {
|
|
386
|
+
throw new ClarusError(usage, file, source, offset + node.start);
|
|
387
|
+
}
|
|
388
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(key.value))
|
|
389
|
+
throw new ClarusError(`provide's key "${key.value}" isn't a name @context can read: use letters, digits, _ or $, like 'tabs'`, file, source, offset + node.start);
|
|
390
|
+
}
|
|
391
|
+
return undefined;
|
|
392
|
+
};
|
|
393
|
+
print(parseScript(code, file, source, offset), code, hook);
|
|
394
|
+
return found;
|
|
395
|
+
}
|
|
396
|
+
function provideCall(node, rec) {
|
|
397
|
+
if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier' || node.callee.name !== 'provide' || node.arguments.length !== 2)
|
|
398
|
+
return undefined;
|
|
399
|
+
const [key, value] = node.arguments;
|
|
400
|
+
return `provide(${rec(key)}, () => (${rec(value)}))`;
|
|
401
|
+
}
|
|
350
402
|
export function rewriteServer(code) {
|
|
351
403
|
const ast = parseScript(code);
|
|
352
404
|
const hook = (node) => {
|
|
353
405
|
if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier')
|
|
354
406
|
return undefined;
|
|
407
|
+
const provided = provideCall(node, (n) => print(n, code, hook));
|
|
408
|
+
if (provided)
|
|
409
|
+
return provided;
|
|
355
410
|
const arg = node.arguments[0];
|
|
356
411
|
const inner = arg ? print(arg, code, hook) : 'undefined';
|
|
357
412
|
if (node.callee.name === 'state')
|
|
@@ -4,3 +4,9 @@ export declare function inputsLine(ir: ComponentIR): string;
|
|
|
4
4
|
/** Dedent a script block and indent it by two spaces, one statement line per line. */
|
|
5
5
|
export declare function indentScript(code: string): string;
|
|
6
6
|
export declare const renderName: (name: string) => string;
|
|
7
|
+
/**
|
|
8
|
+
* The context a component renders its children with (#465): what it was given (render option cx), plus what its
|
|
9
|
+
* script provides. provide(key, get) adds a getter, so a child reads the value current when it renders. Only when
|
|
10
|
+
* the component calls components, places slots, reads context or provides.
|
|
11
|
+
*/
|
|
12
|
+
export declare function contextLines(ir: ComponentIR, incoming: string): string;
|
package/dist/compiler/shared.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { templateRanges } from './script.js';
|
|
2
|
+
import { walk } from './html-expr.js';
|
|
2
3
|
export function inputsLine(ir) {
|
|
3
4
|
if (!ir.inputs.length)
|
|
4
5
|
return '';
|
|
@@ -19,3 +20,16 @@ export function indentScript(code) {
|
|
|
19
20
|
return lines.map((l) => (l.literal ? l.text : ' ' + l.text.slice(indent))).join('\n') + '\n';
|
|
20
21
|
}
|
|
21
22
|
export const renderName = (name) => '__cl_render_' + name.replace(/-/g, '$');
|
|
23
|
+
export function contextLines(ir, incoming) {
|
|
24
|
+
const all = walk(ir.nodes);
|
|
25
|
+
if (!ir.provides && !ir.contexts.length && !all.some((n) => n.kind === 'component' || n.kind === 'slot'))
|
|
26
|
+
return '';
|
|
27
|
+
let out = ir.provides
|
|
28
|
+
? ` const __cl_cx = { ...${incoming} }\n const provide = (k, get) => { Object.defineProperty(__cl_cx, k, { get, enumerable: true, configurable: true }) }\n`
|
|
29
|
+
: ` const __cl_cx = ${incoming}\n`;
|
|
30
|
+
for (const c of ir.contexts) {
|
|
31
|
+
const missing = `throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> reads context "${c.name}", which no component around it provides`)})`;
|
|
32
|
+
out += ` const ${c.name} = __cl_cx && {}.hasOwnProperty.call(__cl_cx, ${JSON.stringify(c.name)}) ? __cl_cx.${c.name} : ${c.default !== undefined ? `(${c.default})` : `(() => { ${missing} })()`}\n`;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
package/dist/fetch/index.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export type Resource<T> = {
|
|
|
11
11
|
readonly error: unknown;
|
|
12
12
|
/** Run now, aborting a run in flight. */
|
|
13
13
|
refetch(): Promise<void>;
|
|
14
|
+
/** Cancel the run in flight: back to idle, the value kept, no error and no callbacks (a cancel isn't a failure). */
|
|
15
|
+
abort(): void;
|
|
14
16
|
/** Set the shown value (e.g. optimistically, before a POST); the next run overwrites it. Keyed: its cache entry. */
|
|
15
17
|
mutate(value: T): void;
|
|
16
18
|
/** The first answer (`value`), or the first run's error. On the server, `initial`. In handlers, not top level. */
|
|
@@ -43,7 +45,49 @@ export type ResourceOptions<T> = {
|
|
|
43
45
|
stale?: number;
|
|
44
46
|
/** With `key`: keep an unshown answer this long (ms, default 5 min). */
|
|
45
47
|
keep?: number;
|
|
48
|
+
/** Fail a run (retries included) after this many ms, with a `TimeoutError`: an error, unlike `abort()`. */
|
|
49
|
+
timeout?: number;
|
|
50
|
+
} & Callbacks<T>;
|
|
51
|
+
/**
|
|
52
|
+
* What happens after a request settles, once per request (an event, so the same error twice is two calls; an effect
|
|
53
|
+
* on `error` is for state). A cancel calls none of them; with `retry`, after the last attempt. Browser only.
|
|
54
|
+
* @see https://clarusjs.com/guide/fetching#errors
|
|
55
|
+
*/
|
|
56
|
+
export type Callbacks<T, I = void> = {
|
|
57
|
+
/** It succeeded (an action's input second). Return `false` to skip `configure()`'s `onSuccess`. */
|
|
58
|
+
onSuccess?(value: T, input: I): unknown;
|
|
59
|
+
/** It failed (a timeout too). Return `false` to skip `configure()`'s `onError` (handled here). */
|
|
60
|
+
onError?(error: unknown, input: I): unknown;
|
|
61
|
+
/** After either, last: `(value, undefined)` or `(undefined, error)`. */
|
|
62
|
+
onSettled?(value: T | undefined, error: unknown, input: I): unknown;
|
|
63
|
+
/** Anything for `configure()`'s handlers: `{ success: 'Saved' }`, `{ silent: true }`. */
|
|
64
|
+
meta?: Record<string, unknown>;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Handlers for every resource and action on the page, after their own callbacks: toasts in one place.
|
|
68
|
+
* @see https://clarusjs.com/reference/fetch#configure
|
|
69
|
+
*/
|
|
70
|
+
export type Handlers = {
|
|
71
|
+
onSuccess?(value: unknown, ctx: {
|
|
72
|
+
meta: Record<string, unknown> | undefined;
|
|
73
|
+
}): void;
|
|
74
|
+
onError?(error: unknown, ctx: {
|
|
75
|
+
meta: Record<string, unknown> | undefined;
|
|
76
|
+
}): void;
|
|
46
77
|
};
|
|
78
|
+
/**
|
|
79
|
+
* Set the handlers every resource and action calls after its own callbacks (one place for toasts); replaces the
|
|
80
|
+
* previous ones. An instance's `meta` reaches them; its own callback returning `false` skips them.
|
|
81
|
+
* @example
|
|
82
|
+
* ```ts
|
|
83
|
+
* configure({
|
|
84
|
+
* onError: (e, { meta }) => { if (!meta?.silent) toast.error(String(e)) },
|
|
85
|
+
* onSuccess: (_, { meta }) => { if (meta?.success) toast(String(meta.success)) },
|
|
86
|
+
* })
|
|
87
|
+
* ```
|
|
88
|
+
* @see https://clarusjs.com/reference/fetch#configure
|
|
89
|
+
*/
|
|
90
|
+
export declare function configure(next: Handlers): void;
|
|
47
91
|
/**
|
|
48
92
|
* A fetcher's answer: a value, a promise of one, or undefined/null/false for "not ready" (a chain still waiting). An
|
|
49
93
|
* async fetcher resolving to undefined is "not ready" too. Signals it reads before its first `await` are tracked.
|
|
@@ -73,6 +117,55 @@ type Fetcher<T> = (ctx: {
|
|
|
73
117
|
* @see https://clarusjs.com/reference/fetch#resource
|
|
74
118
|
*/
|
|
75
119
|
export declare function resource<T>(fetcher: Fetcher<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
120
|
+
/**
|
|
121
|
+
* A one-off async call (delete, save, like): what `action()` gives. Its getters read signals.
|
|
122
|
+
* @see https://clarusjs.com/reference/fetch#action
|
|
123
|
+
*/
|
|
124
|
+
export type Action<I, R> = {
|
|
125
|
+
/** A call is in flight. */
|
|
126
|
+
readonly pending: boolean;
|
|
127
|
+
/** The last call's error (a timeout too, not a cancel), cleared when a call starts. */
|
|
128
|
+
readonly error: unknown;
|
|
129
|
+
/** The last successful call's answer, kept until the next success. */
|
|
130
|
+
readonly result: R | undefined;
|
|
131
|
+
/** Call it: resolves to the answer, or `undefined` if it failed or was cancelled. Never rejects. */
|
|
132
|
+
run(input: I): Promise<R | undefined>;
|
|
133
|
+
/** Call it, and reject if it fails or is cancelled (for try/catch and chains). */
|
|
134
|
+
runAsync(input: I): Promise<R>;
|
|
135
|
+
/** Cancel the call in flight: back to idle, no error, no callbacks. */
|
|
136
|
+
abort(): void;
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* `action()`'s options: `timeout`, `concurrency`, and the callbacks and `meta` a resource takes.
|
|
140
|
+
* @see https://clarusjs.com/reference/fetch#action
|
|
141
|
+
*/
|
|
142
|
+
export type ActionOptions<I, R> = {
|
|
143
|
+
/** Fail a call after this many ms, with a `TimeoutError`. */
|
|
144
|
+
timeout?: number;
|
|
145
|
+
/** A call while one runs: `'join'` (default) shares the one in flight (no double submit); `'latest'` cancels it. */
|
|
146
|
+
concurrency?: 'join' | 'latest';
|
|
147
|
+
} & Callbacks<R, I>;
|
|
148
|
+
/**
|
|
149
|
+
* A one-off async call from the browser (delete, save, like), with `pending`, `error` and `result` for the template.
|
|
150
|
+
* `run()` never rejects (the error lands in `error`, `onError` and `configure()`'s handler); `runAsync()` does. A
|
|
151
|
+
* call while one runs joins it; created in an island, the call is cancelled when the island goes away. On the server
|
|
152
|
+
* nothing runs.
|
|
153
|
+
*
|
|
154
|
+
* @param fn Gets the input and `{ signal }` (pass it on to `request()`); returns the answer or a promise of it.
|
|
155
|
+
* @param options `timeout`, `concurrency` (`'join'` or `'latest'`), `onSuccess` / `onError` / `onSettled`, `meta`.
|
|
156
|
+
* @example
|
|
157
|
+
* ```ts
|
|
158
|
+
* const remove = action((id: number, { signal }) => request(`/api/posts/${id}`, { method: 'DELETE', signal }), {
|
|
159
|
+
* meta: { success: 'Deleted' },
|
|
160
|
+
* onSuccess: () => invalidate(['posts']),
|
|
161
|
+
* })
|
|
162
|
+
* // <button (click)="remove.run(post.id)" [disabled]="remove.pending">Delete</button>
|
|
163
|
+
* ```
|
|
164
|
+
* @see https://clarusjs.com/reference/fetch#action
|
|
165
|
+
*/
|
|
166
|
+
export declare function action<I = void, R = unknown>(fn: (input: I, ctx: {
|
|
167
|
+
signal: AbortSignal;
|
|
168
|
+
}) => R | Promise<R>, options?: ActionOptions<I, R>): Action<I, R>;
|
|
76
169
|
/**
|
|
77
170
|
* Mark every cached answer whose key starts with `prefix` (element by element) as stale: the resources showing one
|
|
78
171
|
* fetch it again now, the others when next used. With no prefix: everything.
|
|
@@ -136,14 +229,75 @@ export declare function batch<T>(load: (keys: string[], ctx: {
|
|
|
136
229
|
max?: number;
|
|
137
230
|
}): Batch<T>;
|
|
138
231
|
/**
|
|
139
|
-
* `
|
|
140
|
-
*
|
|
232
|
+
* What `request()` reads from a response: by default from its `Content-Type` (JSON for `application/json` and
|
|
233
|
+
* `+json` types, text for `text/*` and XML, else a Blob; nothing for a 204), or as `as` says.
|
|
234
|
+
* @see https://clarusjs.com/reference/fetch#request
|
|
235
|
+
*/
|
|
236
|
+
export type ReadAs = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData' | 'response' | 'stream';
|
|
237
|
+
/**
|
|
238
|
+
* `request()`'s options: `fetch`'s, plus `body` (a plain object or array is sent as JSON), `as`, `parse` and `timeout`.
|
|
239
|
+
* @see https://clarusjs.com/reference/fetch#request
|
|
240
|
+
*/
|
|
241
|
+
export type RequestOptions = Omit<RequestInit, 'body'> & {
|
|
242
|
+
/** What `fetch` takes, or a plain object or array: sent as JSON, with `Content-Type: application/json` unless set. */
|
|
243
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null;
|
|
244
|
+
/** What to read from the response; by default its `Content-Type` decides. */
|
|
245
|
+
as?: ReadAs;
|
|
246
|
+
/** Your own reader per content type (`'application/x-ndjson'`, without parameters), ahead of the built-in ones. */
|
|
247
|
+
parse?: Record<string, (res: Response) => unknown>;
|
|
248
|
+
/** Abort after this many ms, with a `TimeoutError` (on top of `signal`). */
|
|
249
|
+
timeout?: number;
|
|
250
|
+
};
|
|
251
|
+
/**
|
|
252
|
+
* The error a non-2xx response throws: its `status`, and its body read like a success's (`data`).
|
|
253
|
+
* @see https://clarusjs.com/reference/fetch#request
|
|
254
|
+
*/
|
|
255
|
+
export type ResponseError = Error & {
|
|
256
|
+
status: number;
|
|
257
|
+
data: unknown;
|
|
258
|
+
};
|
|
259
|
+
/** What `request()` resolves to for each built-in `as` (without `parse`, which can read anything). */
|
|
260
|
+
type ReadResult = {
|
|
261
|
+
text: string;
|
|
262
|
+
blob: Blob;
|
|
263
|
+
arrayBuffer: ArrayBuffer;
|
|
264
|
+
formData: FormData;
|
|
265
|
+
response: Response;
|
|
266
|
+
stream: ReadableStream<Uint8Array> | null;
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* `fetch`, then the response read by its `Content-Type` (or as `as` says). A response that isn't 2xx throws an Error
|
|
270
|
+
* naming the URL and status, with `status` and the error body (`data`), so a resource's `retry` and `error` see it.
|
|
141
271
|
*
|
|
272
|
+
* @param options `fetch`'s options, plus `body` (a plain object or array goes as JSON), `as`, `parse`, `timeout`.
|
|
273
|
+
* @example
|
|
274
|
+
* ```ts
|
|
275
|
+
* const csv = await request<string>('/api/export', { as: 'text', timeout: 10_000 })
|
|
276
|
+
* await request(`/api/posts/${id}`, { method: 'PATCH', body: { title } })
|
|
277
|
+
* ```
|
|
278
|
+
* @see https://clarusjs.com/reference/fetch#request
|
|
279
|
+
*/
|
|
280
|
+
export declare function request<A extends keyof ReadResult>(url: string | URL, options: RequestOptions & {
|
|
281
|
+
as: A;
|
|
282
|
+
parse?: undefined;
|
|
283
|
+
}): Promise<ReadResult[A]>;
|
|
284
|
+
export declare function request<T = any>(url: string | URL, options?: RequestOptions): Promise<T>;
|
|
285
|
+
/**
|
|
286
|
+
* `request()` reading JSON whatever the `Content-Type`. A non-2xx response throws (with `status` and `data`).
|
|
142
287
|
* @example
|
|
143
288
|
* ```ts
|
|
144
289
|
* const me = resource(({ signal }) => json<User>('/api/me', { signal }))
|
|
145
290
|
* ```
|
|
146
291
|
* @see https://clarusjs.com/reference/fetch#json
|
|
147
292
|
*/
|
|
148
|
-
export declare
|
|
293
|
+
export declare const json: <T = any>(url: string | URL, options?: RequestOptions) => Promise<T>;
|
|
294
|
+
/**
|
|
295
|
+
* `request()` reading text whatever the `Content-Type`. A non-2xx response throws (with `status` and `data`).
|
|
296
|
+
* @example
|
|
297
|
+
* ```ts
|
|
298
|
+
* const readme = resource(({ signal }) => text('/README.md', { signal }))
|
|
299
|
+
* ```
|
|
300
|
+
* @see https://clarusjs.com/reference/fetch#text
|
|
301
|
+
*/
|
|
302
|
+
export declare const text: (url: string | URL, options?: RequestOptions) => Promise<string>;
|
|
149
303
|
export {};
|
package/dist/fetch/index.js
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
import { batch as group, effect, onDispose, state, untrack } from '../runtime/index.js';
|
|
2
2
|
import { browser } from '../runtime/env.js';
|
|
3
|
+
let handlers = {};
|
|
4
|
+
export function configure(next) {
|
|
5
|
+
handlers = next;
|
|
6
|
+
}
|
|
7
|
+
const call = (fn, ...args) => {
|
|
8
|
+
try {
|
|
9
|
+
return fn?.(...args);
|
|
10
|
+
}
|
|
11
|
+
catch (err) {
|
|
12
|
+
(globalThis.reportError ?? console.error)(err);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const settled = (o, ok, value, err, input) => {
|
|
16
|
+
const ctx = { meta: o.meta };
|
|
17
|
+
if (ok) {
|
|
18
|
+
if (call(o.onSuccess, value, input) !== false)
|
|
19
|
+
call(handlers.onSuccess, value, ctx);
|
|
20
|
+
}
|
|
21
|
+
else if (call(o.onError, err, input) !== false)
|
|
22
|
+
call(handlers.onError, err, ctx);
|
|
23
|
+
call(o.onSettled, ok ? value : undefined, ok ? undefined : err, input);
|
|
24
|
+
};
|
|
25
|
+
const within = (signal, ms) => (ms === undefined ? signal : AbortSignal.any([signal, AbortSignal.timeout(ms)]));
|
|
3
26
|
export function resource(fetcher, options = {}) {
|
|
4
27
|
const value = state(options.initial);
|
|
5
28
|
const loading = state(!browser && options.initial === undefined);
|
|
@@ -18,9 +41,10 @@ export function resource(fetcher, options = {}) {
|
|
|
18
41
|
const keyed = browser && !!options.key;
|
|
19
42
|
let entry;
|
|
20
43
|
let force = false;
|
|
44
|
+
let cancelled = -1;
|
|
21
45
|
const user = {
|
|
22
46
|
keep: options.keep ?? KEEP,
|
|
23
|
-
push: (v) => { if (!disposed)
|
|
47
|
+
push: (v, seq) => { if (!disposed && seq !== cancelled)
|
|
24
48
|
value.set(v); },
|
|
25
49
|
rerun: () => { if (stop)
|
|
26
50
|
tick.set(untrack(tick.get) + 1); },
|
|
@@ -51,11 +75,13 @@ export function resource(fetcher, options = {}) {
|
|
|
51
75
|
}
|
|
52
76
|
const run = () => {
|
|
53
77
|
tick.get();
|
|
78
|
+
cancelled = -1;
|
|
54
79
|
const forced = force;
|
|
55
80
|
force = false;
|
|
56
81
|
controller?.abort();
|
|
57
82
|
const id = ++runs;
|
|
58
83
|
const c = (controller = new AbortController());
|
|
84
|
+
const signal = within(c.signal, options.timeout);
|
|
59
85
|
let state = 'fetch';
|
|
60
86
|
let out;
|
|
61
87
|
inFetcher = true;
|
|
@@ -74,19 +100,19 @@ export function resource(fetcher, options = {}) {
|
|
|
74
100
|
else if (!forced && e.pending)
|
|
75
101
|
out = e.pending;
|
|
76
102
|
else {
|
|
77
|
-
const
|
|
78
|
-
const first = fetcher({ signal:
|
|
103
|
+
const rs = within(new AbortController().signal, options.timeout);
|
|
104
|
+
const first = fetcher({ signal: rs });
|
|
79
105
|
if (first === undefined || first === null || first === false)
|
|
80
106
|
state = 'not ready';
|
|
81
107
|
else
|
|
82
|
-
out =
|
|
108
|
+
out = track(e, retrying(first, () => fetcher({ signal: rs }), rs));
|
|
83
109
|
}
|
|
84
110
|
}
|
|
85
111
|
if (state === 'not ready')
|
|
86
112
|
join(undefined);
|
|
87
113
|
}
|
|
88
114
|
else {
|
|
89
|
-
out = fetcher({ signal
|
|
115
|
+
out = fetcher({ signal });
|
|
90
116
|
if (out === undefined || out === null || out === false)
|
|
91
117
|
state = 'not ready';
|
|
92
118
|
}
|
|
@@ -116,15 +142,19 @@ export function resource(fetcher, options = {}) {
|
|
|
116
142
|
loading.set(true);
|
|
117
143
|
busy = true;
|
|
118
144
|
const latest = () => id === runs && !disposed;
|
|
119
|
-
return (keyed ? out : retrying(out, () => fetcher({ signal
|
|
145
|
+
return (keyed ? Promise.race([out, aborted(signal)]) : retrying(out, () => fetcher({ signal }), signal)).then((v) => { if (latest()) {
|
|
120
146
|
if (!keyed && v !== undefined)
|
|
121
147
|
value.set(v);
|
|
122
148
|
loading.set(false);
|
|
123
149
|
busy = false;
|
|
124
|
-
|
|
150
|
+
if (v !== undefined)
|
|
151
|
+
settled(options, true, v, undefined);
|
|
152
|
+
} }, (e) => { if (latest()) {
|
|
153
|
+
const err = signal.aborted ? signal.reason : e;
|
|
125
154
|
error.set(err);
|
|
126
155
|
loading.set(false);
|
|
127
156
|
busy = false;
|
|
157
|
+
settled(options, false, undefined, err);
|
|
128
158
|
} });
|
|
129
159
|
});
|
|
130
160
|
};
|
|
@@ -176,6 +206,17 @@ export function resource(fetcher, options = {}) {
|
|
|
176
206
|
stop = effect(run);
|
|
177
207
|
return Promise.resolve().then(() => pending);
|
|
178
208
|
},
|
|
209
|
+
abort() {
|
|
210
|
+
if (!controller)
|
|
211
|
+
return;
|
|
212
|
+
runs++;
|
|
213
|
+
if (entry?.pending)
|
|
214
|
+
cancelled = entry.seq;
|
|
215
|
+
controller.abort();
|
|
216
|
+
controller = undefined;
|
|
217
|
+
busy = false;
|
|
218
|
+
loading.set(false);
|
|
219
|
+
},
|
|
179
220
|
mutate(v) { if (browser) {
|
|
180
221
|
if (entry)
|
|
181
222
|
store(entry, v, ++entry.seq);
|
|
@@ -195,6 +236,53 @@ export function resource(fetcher, options = {}) {
|
|
|
195
236
|
};
|
|
196
237
|
return self;
|
|
197
238
|
}
|
|
239
|
+
const aborted = (signal) => new Promise((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true }));
|
|
240
|
+
export function action(fn, options = {}) {
|
|
241
|
+
const pending = state(false);
|
|
242
|
+
const error = state(undefined);
|
|
243
|
+
const result = state(undefined);
|
|
244
|
+
let controller;
|
|
245
|
+
let current;
|
|
246
|
+
const abort = () => { controller?.abort(); controller = current = undefined; pending.set(false); };
|
|
247
|
+
if (browser)
|
|
248
|
+
onDispose(abort);
|
|
249
|
+
const runAsync = (input) => {
|
|
250
|
+
if (!browser)
|
|
251
|
+
return Promise.resolve(undefined);
|
|
252
|
+
if (current && options.concurrency !== 'latest')
|
|
253
|
+
return current;
|
|
254
|
+
abort();
|
|
255
|
+
const c = (controller = new AbortController());
|
|
256
|
+
const signal = within(c.signal, options.timeout);
|
|
257
|
+
const mine = () => controller === c;
|
|
258
|
+
const end = () => { controller = current = undefined; };
|
|
259
|
+
error.set(undefined);
|
|
260
|
+
const p = Promise.race([(async () => fn(input, { signal }))(), aborted(signal)]).then((v) => { if (mine()) {
|
|
261
|
+
end();
|
|
262
|
+
group(() => { result.set(v); pending.set(false); });
|
|
263
|
+
settled(options, true, v, undefined, input);
|
|
264
|
+
} return v; }, (e) => {
|
|
265
|
+
const err = signal.aborted ? signal.reason : e;
|
|
266
|
+
if (mine()) {
|
|
267
|
+
end();
|
|
268
|
+
group(() => { error.set(err); pending.set(false); });
|
|
269
|
+
settled(options, false, undefined, err, input);
|
|
270
|
+
}
|
|
271
|
+
throw err;
|
|
272
|
+
});
|
|
273
|
+
current = p;
|
|
274
|
+
pending.set(true);
|
|
275
|
+
return p;
|
|
276
|
+
};
|
|
277
|
+
return {
|
|
278
|
+
get pending() { return pending.get(); },
|
|
279
|
+
get error() { return error.get(); },
|
|
280
|
+
get result() { return result.get(); },
|
|
281
|
+
run: (input) => runAsync(input).catch(() => undefined),
|
|
282
|
+
runAsync,
|
|
283
|
+
abort,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
198
286
|
const KEEP = 5 * 60_000;
|
|
199
287
|
const cache = new Map();
|
|
200
288
|
const hash = (v) => JSON.stringify(v, (_, x) => (x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : x));
|
|
@@ -218,9 +306,9 @@ const store = (e, v, seq) => {
|
|
|
218
306
|
return;
|
|
219
307
|
Object.assign(e, { value: v, has: true, at: Date.now(), invalid: false });
|
|
220
308
|
for (const u of e.users)
|
|
221
|
-
u.push(v);
|
|
309
|
+
u.push(v, seq);
|
|
222
310
|
};
|
|
223
|
-
const
|
|
311
|
+
const track = (e, answer) => {
|
|
224
312
|
const seq = ++e.seq;
|
|
225
313
|
const p = answer.then((v) => { if (v !== undefined)
|
|
226
314
|
store(e, v, seq); return v; });
|
|
@@ -257,7 +345,7 @@ export function prefetch(key, fetcher) {
|
|
|
257
345
|
if (!browser)
|
|
258
346
|
return Promise.resolve();
|
|
259
347
|
const e = entryOf(key);
|
|
260
|
-
const p = e.has && !e.invalid ? Promise.resolve() : e.pending ??
|
|
348
|
+
const p = e.has && !e.invalid ? Promise.resolve() : e.pending ?? track(e, (async () => fetcher({ signal: new AbortController().signal }))());
|
|
261
349
|
release(e);
|
|
262
350
|
return p.then(() => { }, () => { });
|
|
263
351
|
}
|
|
@@ -302,11 +390,44 @@ export function batch(load, options = {}) {
|
|
|
302
390
|
},
|
|
303
391
|
};
|
|
304
392
|
}
|
|
305
|
-
|
|
393
|
+
const read = (res, as, parse) => {
|
|
394
|
+
const type = res.headers.get('content-type')?.split(';')[0].trim().toLowerCase() ?? '';
|
|
395
|
+
const own = parse?.[type];
|
|
396
|
+
if (own)
|
|
397
|
+
return own(res);
|
|
398
|
+
if (as === 'response')
|
|
399
|
+
return res;
|
|
400
|
+
if (as === 'stream')
|
|
401
|
+
return res.body;
|
|
402
|
+
if (as)
|
|
403
|
+
return res[as]();
|
|
404
|
+
if (res.status === 204)
|
|
405
|
+
return undefined;
|
|
406
|
+
if (type === 'application/json' || type.endsWith('+json'))
|
|
407
|
+
return res.json();
|
|
408
|
+
return type.startsWith('text/') || type.endsWith('xml') ? res.text() : res.blob();
|
|
409
|
+
};
|
|
410
|
+
export async function request(url, options = {}) {
|
|
411
|
+
const { as, parse, timeout, body, ...init } = options;
|
|
412
|
+
if (body !== undefined) {
|
|
413
|
+
const plain = body !== null && typeof body === 'object' && (Array.isArray(body) || [Object.prototype, null].includes(Object.getPrototypeOf(body)));
|
|
414
|
+
if (plain) {
|
|
415
|
+
const headers = new Headers(init.headers);
|
|
416
|
+
if (!headers.has('content-type'))
|
|
417
|
+
headers.set('content-type', 'application/json');
|
|
418
|
+
Object.assign(init, { body: JSON.stringify(body), headers });
|
|
419
|
+
}
|
|
420
|
+
else
|
|
421
|
+
init.body = body;
|
|
422
|
+
}
|
|
423
|
+
if (timeout !== undefined)
|
|
424
|
+
init.signal = AbortSignal.any([AbortSignal.timeout(timeout), ...(init.signal ? [init.signal] : [])]);
|
|
306
425
|
const res = await fetch(url, init);
|
|
307
426
|
if (!res.ok) {
|
|
308
|
-
await
|
|
309
|
-
throw Object.assign(new Error(`${url}: ${res.status} ${res.statusText}`.trim()), { status: res.status });
|
|
427
|
+
const data = await Promise.resolve().then(() => read(res, as === 'response' || as === 'stream' ? 'text' : undefined, parse)).catch(() => undefined);
|
|
428
|
+
throw Object.assign(new Error(`${url}: ${res.status} ${res.statusText}`.trim()), { status: res.status, data });
|
|
310
429
|
}
|
|
311
|
-
return res
|
|
430
|
+
return read(res, as, parse);
|
|
312
431
|
}
|
|
432
|
+
export const json = (url, options) => request(url, { ...options, as: 'json' });
|
|
433
|
+
export const text = (url, options) => request(url, { ...options, as: 'text' });
|
package/dist/forms/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { effect, onDispose, state, untrack } from '../runtime/index.js';
|
|
2
|
-
import { marked } from '../runtime/dom.js';
|
|
2
|
+
import { marked, openSlots, owner } from '../runtime/dom.js';
|
|
3
3
|
import { browser } from '../runtime/env.js';
|
|
4
4
|
const CONTAINERS = 'label, [data-cl-field], fieldset, cl-island';
|
|
5
5
|
const FIELDS = 'input[data-cl-path],select[data-cl-path],textarea[data-cl-path]';
|
|
@@ -9,16 +9,28 @@ const read = (value, path) => path.split('.').reduce((v, k) => (v == null ? v :
|
|
|
9
9
|
const dotted = (path = []) => path.map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
|
|
10
10
|
function pathOf(field, root) {
|
|
11
11
|
const parts = [];
|
|
12
|
+
let through = 0;
|
|
12
13
|
for (let el = field; el && el !== root.parentElement; el = el.parentElement) {
|
|
13
14
|
const here = el;
|
|
15
|
+
if (through && here.localName === 'cl-island') {
|
|
16
|
+
through--;
|
|
17
|
+
through += openSlots(here);
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (through) {
|
|
21
|
+
through += openSlots(here);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
through += openSlots(here);
|
|
14
25
|
let part = here.getAttribute('data-cl-path');
|
|
15
26
|
if (part?.startsWith('@')) {
|
|
16
27
|
const [model, ...rest] = part.slice(1).split('.');
|
|
17
|
-
const island = here
|
|
18
|
-
if (!island)
|
|
28
|
+
const island = owner(here);
|
|
29
|
+
if (!island?.hasAttribute(`data-cl-path-${model}`))
|
|
19
30
|
return '';
|
|
20
31
|
part = [island.getAttribute(`data-cl-path-${model}`), ...rest].filter(Boolean).join('.');
|
|
21
32
|
el = island;
|
|
33
|
+
through = openSlots(island);
|
|
22
34
|
}
|
|
23
35
|
if (part)
|
|
24
36
|
parts.unshift(part);
|
package/dist/runtime/attrs.d.ts
CHANGED
|
@@ -30,3 +30,9 @@ export declare function spreadAttrs(obj: unknown, skip: readonly string[], tag?:
|
|
|
30
30
|
set: [string, string | true | null][];
|
|
31
31
|
dropped: [string, string][];
|
|
32
32
|
};
|
|
33
|
+
/**
|
|
34
|
+
* The attributes a parent passed to a component (#463): its props with an attribute-like name that it doesn't declare
|
|
35
|
+
* as an input. They land on its root element (a spread, so the root's own attributes win; style merges).
|
|
36
|
+
* @internal Compiled components call this.
|
|
37
|
+
*/
|
|
38
|
+
export declare function passed(props: Record<string, unknown>, inputs: readonly string[]): Record<string, unknown>;
|
package/dist/runtime/attrs.js
CHANGED
|
@@ -128,3 +128,19 @@ export function spreadAttrs(obj, skip, tag) {
|
|
|
128
128
|
}
|
|
129
129
|
return { set, dropped };
|
|
130
130
|
}
|
|
131
|
+
// What a parent's attributes may set on a component's root (#463): attribute-like names only, so a page's load() data or
|
|
132
|
+
// a layout's path never become attributes.
|
|
133
|
+
const PASSED = /^(id|role|tabindex|hidden|lang|dir|style|(data|aria)-[\w:.-]+)$/;
|
|
134
|
+
/**
|
|
135
|
+
* The attributes a parent passed to a component (#463): its props with an attribute-like name that it doesn't declare
|
|
136
|
+
* as an input. They land on its root element (a spread, so the root's own attributes win; style merges).
|
|
137
|
+
* @internal Compiled components call this.
|
|
138
|
+
*/
|
|
139
|
+
export function passed(props, inputs) {
|
|
140
|
+
const out = {};
|
|
141
|
+
// Never clarusjs's own markers (data-cl-e, data-cl-u, data-cl-path…): passed data must not spoof the runtime's wiring.
|
|
142
|
+
for (const k in props)
|
|
143
|
+
if (PASSED.test(k) && !/^data-cl-/i.test(k) && !inputs.includes(k))
|
|
144
|
+
out[k] = props[k];
|
|
145
|
+
return out;
|
|
146
|
+
}
|