clarusjs 0.9.0 → 0.11.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.js +15 -8
- package/dist/cli/check.d.ts +7 -0
- package/dist/cli/check.js +14 -6
- package/dist/cli/explain.js +1 -1
- package/dist/cli/index.js +6 -3
- package/dist/cli/project.d.ts +7 -2
- package/dist/cli/project.js +4 -3
- package/dist/compiler/emit-client.d.ts +2 -1
- package/dist/compiler/emit-client.js +19 -7
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +4 -1
- package/dist/compiler/errors.d.ts +14 -1
- package/dist/compiler/html-expr.d.ts +21 -0
- package/dist/compiler/html-expr.js +24 -1
- package/dist/compiler/index.d.ts +23 -2
- package/dist/compiler/index.js +5 -3
- package/dist/compiler/ir.d.ts +6 -1
- package/dist/compiler/ir.js +104 -4
- package/dist/compiler/lint.d.ts +82 -0
- package/dist/compiler/lint.js +177 -0
- package/dist/compiler/parse.d.ts +34 -0
- package/dist/compiler/parse.js +11 -0
- package/dist/compiler/script.js +27 -0
- package/dist/fetch/index.d.ts +149 -0
- package/dist/fetch/index.js +312 -0
- package/dist/forms/index.d.ts +21 -2
- package/dist/forms/types.d.ts +20 -3
- package/dist/runtime/attrs.js +10 -2
- package/dist/runtime/dom.d.ts +15 -7
- package/dist/runtime/dom.js +33 -13
- package/dist/runtime/env.d.ts +8 -1
- package/dist/runtime/env.js +8 -1
- package/dist/runtime/hot.d.ts +2 -0
- package/dist/runtime/hot.js +51 -0
- package/dist/runtime/html.d.ts +9 -7
- package/dist/runtime/html.js +12 -7
- package/dist/runtime/navigate.d.ts +5 -0
- package/dist/runtime/navigation.d.ts +85 -13
- package/dist/runtime/navigation.js +77 -11
- package/dist/runtime/serialize.d.ts +1 -1
- package/dist/runtime/serialize.js +1 -1
- package/dist/runtime/server.d.ts +18 -1
- package/dist/runtime/server.js +42 -4
- package/dist/runtime/signals.d.ts +97 -4
- package/dist/runtime/signals.js +88 -4
- package/dist/server/handler.d.ts +115 -5
- package/dist/server/handler.js +233 -10
- package/dist/server/head.d.ts +4 -1
- package/dist/server/manifest.d.ts +14 -1
- package/dist/server/views.d.ts +64 -6
- package/dist/server/views.js +46 -0
- package/dist/vite/aliases.js +3 -3
- package/dist/vite/build.d.ts +2 -1
- package/dist/vite/build.js +1 -1
- package/dist/vite/manifest.d.ts +15 -0
- package/dist/vite/manifest.js +2 -2
- package/dist/vite/node.js +4 -1
- package/dist/vite/plugin.d.ts +47 -3
- package/dist/vite/plugin.js +197 -106
- package/dist/vite/sitemap.d.ts +1 -0
- package/package.json +5 -1
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An island's fetched data. Its getters read signals, so a template that shows them updates on its own.
|
|
3
|
+
* @see https://clarusjs.com/reference/fetch#resource
|
|
4
|
+
*/
|
|
5
|
+
export type Resource<T> = {
|
|
6
|
+
/** The last successful answer (kept during a refetch and after an error), or `initial`. */
|
|
7
|
+
readonly value: T | undefined;
|
|
8
|
+
/** A run is in flight. */
|
|
9
|
+
readonly loading: boolean;
|
|
10
|
+
/** The last run's error, cleared when a run starts. */
|
|
11
|
+
readonly error: unknown;
|
|
12
|
+
/** Run now, aborting a run in flight. */
|
|
13
|
+
refetch(): Promise<void>;
|
|
14
|
+
/** Set the shown value (e.g. optimistically, before a POST); the next run overwrites it. Keyed: its cache entry. */
|
|
15
|
+
mutate(value: T): void;
|
|
16
|
+
/** The first answer (`value`), or the first run's error. On the server, `initial`. In handlers, not top level. */
|
|
17
|
+
ready(): Promise<T | undefined>;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* `resource()`'s options: a starting value, retry, refetch, and (with `key`) caching.
|
|
21
|
+
* @see https://clarusjs.com/reference/fetch#resource
|
|
22
|
+
*/
|
|
23
|
+
export type ResourceOptions<T> = {
|
|
24
|
+
/** The starting value (from the page's load()): shown in server HTML and while the browser revalidates. */
|
|
25
|
+
initial?: T;
|
|
26
|
+
/** Attempts after a failed one: a count, or a count and the delay before each (default 500 ms, doubling, ≤ 8 s). */
|
|
27
|
+
retry?: number | {
|
|
28
|
+
count: number;
|
|
29
|
+
delay?(attempt: number): number;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* When to run again: every `interval` ms while the page is visible; on `focus` (the page shown again). `onStart`
|
|
33
|
+
* (default true): run on attach. With `onStart: false` the resource doesn't follow its signals until a first run.
|
|
34
|
+
*/
|
|
35
|
+
refetch?: {
|
|
36
|
+
interval?: number;
|
|
37
|
+
focus?: boolean;
|
|
38
|
+
onStart?: boolean;
|
|
39
|
+
};
|
|
40
|
+
/** Cache answers by this key (`['items', { page }]`), page-wide: seen keys need no request until invalidated. */
|
|
41
|
+
key?: () => unknown[] | undefined | null | false;
|
|
42
|
+
/** With `key`: refetch cached answers older than this (ms). Unset: fresh until invalidated. */
|
|
43
|
+
stale?: number;
|
|
44
|
+
/** With `key`: keep an unshown answer this long (ms, default 5 min). */
|
|
45
|
+
keep?: number;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* A fetcher's answer: a value, a promise of one, or undefined/null/false for "not ready" (a chain still waiting). An
|
|
49
|
+
* async fetcher resolving to undefined is "not ready" too. Signals it reads before its first `await` are tracked.
|
|
50
|
+
*/
|
|
51
|
+
type Fetcher<T> = (ctx: {
|
|
52
|
+
signal: AbortSignal;
|
|
53
|
+
}) => T | Promise<T> | undefined | null | false;
|
|
54
|
+
/**
|
|
55
|
+
* Runs `fetcher` in the browser and gives its answer as `value`, `loading` and `error`, which update an island's
|
|
56
|
+
* template on their own. It runs again when a signal the fetcher reads changes (another resource's `value`, a
|
|
57
|
+
* `state`), so requests chain; a falsy return means "not ready" (no request). The latest run wins; an island that
|
|
58
|
+
* goes away aborts its run. On the server the fetcher never runs.
|
|
59
|
+
*
|
|
60
|
+
* @param fetcher Returns the value or a promise of it (it can be `async`); pass `signal` on to `fetch`. Signals it
|
|
61
|
+
* reads before its first `await` are the ones it follows.
|
|
62
|
+
* @param options `initial` (a starting value), `retry`, `refetch: { interval, focus, onStart }`.
|
|
63
|
+
* @returns A {@link Resource}: `value`, `loading`, `error`, `refetch()`, `mutate()`.
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* const team = resource(({ signal }) => json('/api/team', { signal }))
|
|
67
|
+
* // A chain: waits for the team, and runs again when it changes.
|
|
68
|
+
* const members = resource(({ signal }) => team.value && json(`/api/teams/${team.value.id}/members`, { signal }), {
|
|
69
|
+
* retry: 2,
|
|
70
|
+
* refetch: { interval: 30_000 },
|
|
71
|
+
* })
|
|
72
|
+
* ```
|
|
73
|
+
* @see https://clarusjs.com/reference/fetch#resource
|
|
74
|
+
*/
|
|
75
|
+
export declare function resource<T>(fetcher: Fetcher<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
76
|
+
/**
|
|
77
|
+
* Mark every cached answer whose key starts with `prefix` (element by element) as stale: the resources showing one
|
|
78
|
+
* fetch it again now, the others when next used. With no prefix: everything.
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* await fetch(`/api/items/${id}`, { method: 'PATCH', body })
|
|
82
|
+
* invalidate(['items']) // every cached page of items
|
|
83
|
+
* ```
|
|
84
|
+
* @see https://clarusjs.com/reference/fetch#invalidate
|
|
85
|
+
*/
|
|
86
|
+
export declare function invalidate(prefix?: unknown[]): void;
|
|
87
|
+
/**
|
|
88
|
+
* Set a cached answer (an optimistic edit) and show it in every resource using that key; creates it if missing.
|
|
89
|
+
* @example
|
|
90
|
+
* ```ts
|
|
91
|
+
* setData(['items', { page }], (rows) => rows.map((r) => (r.id === id ? { ...r, name } : r)))
|
|
92
|
+
* ```
|
|
93
|
+
* @see https://clarusjs.com/reference/fetch#setdata
|
|
94
|
+
*/
|
|
95
|
+
export declare function setData<T>(key: unknown[], value: T | ((prev: T | undefined) => T)): void;
|
|
96
|
+
/**
|
|
97
|
+
* Fetch an answer into the cache ahead of time (the next page), unless it's there and fresh. Errors are ignored.
|
|
98
|
+
* @example
|
|
99
|
+
* ```ts
|
|
100
|
+
* prefetch(['items', { page: page + 1 }], ({ signal }) => json(`/api/items?page=${page + 1}`, { signal }))
|
|
101
|
+
* ```
|
|
102
|
+
* @see https://clarusjs.com/reference/fetch#prefetch
|
|
103
|
+
*/
|
|
104
|
+
export declare function prefetch<T>(key: unknown[], fetcher: (ctx: {
|
|
105
|
+
signal: AbortSignal;
|
|
106
|
+
}) => T | Promise<T>): Promise<void>;
|
|
107
|
+
/**
|
|
108
|
+
* Keys asked of one endpoint at the same moment, answered by one request: what `batch()` gives.
|
|
109
|
+
* @see https://clarusjs.com/reference/fetch#batch
|
|
110
|
+
*/
|
|
111
|
+
export type Batch<T> = {
|
|
112
|
+
get(key: string): Promise<T>;
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* One request for the keys asked at the same moment (the same task, or within `wait` ms), from the islands asking
|
|
116
|
+
* then (islands attaching later, such as on idle or when visible, join with a longer `wait`):
|
|
117
|
+
* `load(keys)` answers each key. Concurrent asks for a key share its request; nothing is kept after it settles.
|
|
118
|
+
* `max` splits a large batch. Share it from a module (`export const stats = batch(…)`).
|
|
119
|
+
*
|
|
120
|
+
* @param load Fetches the answers for `keys`: an object with one entry per key.
|
|
121
|
+
* @param options `wait` (ms to collect keys), `max` (keys per request).
|
|
122
|
+
* @returns `{ get(key) }`: a promise of that key's answer.
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* // stores/stats.ts: every card on the page joins the same request
|
|
126
|
+
* export const stats = batch((keys, { signal }) => json(`/api/stats?keys=${keys.join(',')}`, { signal }))
|
|
127
|
+
* // in a card's script
|
|
128
|
+
* const visits = resource(() => stats.get('visits'))
|
|
129
|
+
* ```
|
|
130
|
+
* @see https://clarusjs.com/reference/fetch#batch
|
|
131
|
+
*/
|
|
132
|
+
export declare function batch<T>(load: (keys: string[], ctx: {
|
|
133
|
+
signal: AbortSignal;
|
|
134
|
+
}) => Record<string, T> | Promise<Record<string, T>>, options?: {
|
|
135
|
+
wait?: number;
|
|
136
|
+
max?: number;
|
|
137
|
+
}): Batch<T>;
|
|
138
|
+
/**
|
|
139
|
+
* `fetch(url, init)`, then the response's JSON. A response that isn't 2xx throws an Error naming the URL and status
|
|
140
|
+
* (its `status` property holds the code), so a resource's `retry` and `error` see it.
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* ```ts
|
|
144
|
+
* const me = resource(({ signal }) => json<User>('/api/me', { signal }))
|
|
145
|
+
* ```
|
|
146
|
+
* @see https://clarusjs.com/reference/fetch#json
|
|
147
|
+
*/
|
|
148
|
+
export declare function json<T = any>(url: string | URL, init?: RequestInit): Promise<T>;
|
|
149
|
+
export {};
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { batch as group, effect, onDispose, state, untrack } from '../runtime/index.js';
|
|
2
|
+
import { browser } from '../runtime/env.js';
|
|
3
|
+
export function resource(fetcher, options = {}) {
|
|
4
|
+
const value = state(options.initial);
|
|
5
|
+
const loading = state(!browser && options.initial === undefined);
|
|
6
|
+
const error = state(undefined);
|
|
7
|
+
const tick = state(0);
|
|
8
|
+
let controller;
|
|
9
|
+
let runs = 0;
|
|
10
|
+
let pending = Promise.resolve();
|
|
11
|
+
let stop;
|
|
12
|
+
let disposed = false;
|
|
13
|
+
let quiet = options.initial !== undefined;
|
|
14
|
+
let busy = false;
|
|
15
|
+
let inFetcher = false;
|
|
16
|
+
const retry = typeof options.retry === 'number' ? { count: options.retry } : options.retry ?? { count: 0 };
|
|
17
|
+
const delay = retry.delay ?? ((attempt) => Math.min(500 * 2 ** (attempt - 1), 8000));
|
|
18
|
+
const keyed = browser && !!options.key;
|
|
19
|
+
let entry;
|
|
20
|
+
let force = false;
|
|
21
|
+
const user = {
|
|
22
|
+
keep: options.keep ?? KEEP,
|
|
23
|
+
push: (v) => { if (!disposed)
|
|
24
|
+
value.set(v); },
|
|
25
|
+
rerun: () => { if (stop)
|
|
26
|
+
tick.set(untrack(tick.get) + 1); },
|
|
27
|
+
};
|
|
28
|
+
const join = (e) => {
|
|
29
|
+
if (e === entry)
|
|
30
|
+
return;
|
|
31
|
+
if (entry) {
|
|
32
|
+
entry.users.delete(user);
|
|
33
|
+
release(entry, user);
|
|
34
|
+
}
|
|
35
|
+
entry = e;
|
|
36
|
+
if (e) {
|
|
37
|
+
e.users.add(user);
|
|
38
|
+
clearTimeout(e.drop);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
if (keyed && options.initial !== undefined) {
|
|
42
|
+
try {
|
|
43
|
+
const k = untrack(options.key);
|
|
44
|
+
if (k) {
|
|
45
|
+
const e = entryOf(k);
|
|
46
|
+
if (!e.has)
|
|
47
|
+
store(e, options.initial, e.seq);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch { }
|
|
51
|
+
}
|
|
52
|
+
const run = () => {
|
|
53
|
+
tick.get();
|
|
54
|
+
const forced = force;
|
|
55
|
+
force = false;
|
|
56
|
+
controller?.abort();
|
|
57
|
+
const id = ++runs;
|
|
58
|
+
const c = (controller = new AbortController());
|
|
59
|
+
let state = 'fetch';
|
|
60
|
+
let out;
|
|
61
|
+
inFetcher = true;
|
|
62
|
+
try {
|
|
63
|
+
if (keyed) {
|
|
64
|
+
const k = options.key();
|
|
65
|
+
if (!k)
|
|
66
|
+
state = 'not ready';
|
|
67
|
+
else {
|
|
68
|
+
const e = entryOf(k);
|
|
69
|
+
join(e);
|
|
70
|
+
if (!forced && e.has && !e.invalid && (options.stale === undefined || Date.now() - e.at < options.stale)) {
|
|
71
|
+
state = 'hit';
|
|
72
|
+
out = e.value;
|
|
73
|
+
}
|
|
74
|
+
else if (!forced && e.pending)
|
|
75
|
+
out = e.pending;
|
|
76
|
+
else {
|
|
77
|
+
const rc = new AbortController();
|
|
78
|
+
const first = fetcher({ signal: rc.signal });
|
|
79
|
+
if (first === undefined || first === null || first === false)
|
|
80
|
+
state = 'not ready';
|
|
81
|
+
else
|
|
82
|
+
out = request(e, retrying(first, () => fetcher({ signal: rc.signal }), rc.signal));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (state === 'not ready')
|
|
86
|
+
join(undefined);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
out = fetcher({ signal: c.signal });
|
|
90
|
+
if (out === undefined || out === null || out === false)
|
|
91
|
+
state = 'not ready';
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
out = Promise.reject(err);
|
|
96
|
+
state = 'fetch';
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
inFetcher = false;
|
|
100
|
+
}
|
|
101
|
+
pending = untrack(() => {
|
|
102
|
+
const wasQuiet = quiet;
|
|
103
|
+
quiet = false;
|
|
104
|
+
if (state !== 'fetch') {
|
|
105
|
+
controller = undefined;
|
|
106
|
+
busy = false;
|
|
107
|
+
if (state === 'hit') {
|
|
108
|
+
value.set(out);
|
|
109
|
+
error.set(undefined);
|
|
110
|
+
}
|
|
111
|
+
loading.set(false);
|
|
112
|
+
return Promise.resolve();
|
|
113
|
+
}
|
|
114
|
+
error.set(undefined);
|
|
115
|
+
if (!wasQuiet)
|
|
116
|
+
loading.set(true);
|
|
117
|
+
busy = true;
|
|
118
|
+
const latest = () => id === runs && !disposed;
|
|
119
|
+
return (keyed ? out : retrying(out, () => fetcher({ signal: c.signal }), c.signal)).then((v) => { if (latest()) {
|
|
120
|
+
if (!keyed && v !== undefined)
|
|
121
|
+
value.set(v);
|
|
122
|
+
loading.set(false);
|
|
123
|
+
busy = false;
|
|
124
|
+
} }, (err) => { if (latest()) {
|
|
125
|
+
error.set(err);
|
|
126
|
+
loading.set(false);
|
|
127
|
+
busy = false;
|
|
128
|
+
} });
|
|
129
|
+
});
|
|
130
|
+
};
|
|
131
|
+
function retrying(first, again, signal) {
|
|
132
|
+
const attempt = async (n) => {
|
|
133
|
+
try {
|
|
134
|
+
return await (n === 0 ? first : again());
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
if (n >= retry.count || signal.aborted)
|
|
138
|
+
throw err;
|
|
139
|
+
await sleep(delay(n + 1), signal);
|
|
140
|
+
return attempt(n + 1);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
return attempt(0);
|
|
144
|
+
}
|
|
145
|
+
const timers = [];
|
|
146
|
+
const dispose = () => { disposed = true; stop?.(); controller?.abort(); for (const t of timers)
|
|
147
|
+
t(); join(undefined); };
|
|
148
|
+
const again = () => { if (!busy && document.visibilityState !== 'hidden')
|
|
149
|
+
void self.refetch(); };
|
|
150
|
+
if (browser) {
|
|
151
|
+
onDispose(dispose);
|
|
152
|
+
if (options.refetch?.onStart !== false)
|
|
153
|
+
stop = effect(run);
|
|
154
|
+
const { interval, focus } = options.refetch ?? {};
|
|
155
|
+
if (interval) {
|
|
156
|
+
const t = setInterval(again, interval);
|
|
157
|
+
timers.push(() => clearInterval(t));
|
|
158
|
+
}
|
|
159
|
+
if (focus) {
|
|
160
|
+
document.addEventListener('visibilitychange', again);
|
|
161
|
+
timers.push(() => document.removeEventListener('visibilitychange', again));
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const read = (s) => (inFetcher ? untrack(s.get) : s.get());
|
|
165
|
+
const self = {
|
|
166
|
+
get value() { return read(value); },
|
|
167
|
+
get loading() { return read(loading); },
|
|
168
|
+
get error() { return read(error); },
|
|
169
|
+
refetch() {
|
|
170
|
+
if (!browser || disposed)
|
|
171
|
+
return Promise.resolve();
|
|
172
|
+
force = true;
|
|
173
|
+
if (stop)
|
|
174
|
+
tick.set(untrack(tick.get) + 1);
|
|
175
|
+
else
|
|
176
|
+
stop = effect(run);
|
|
177
|
+
return Promise.resolve().then(() => pending);
|
|
178
|
+
},
|
|
179
|
+
mutate(v) { if (browser) {
|
|
180
|
+
if (entry)
|
|
181
|
+
store(entry, v, ++entry.seq);
|
|
182
|
+
else
|
|
183
|
+
value.set(v);
|
|
184
|
+
} },
|
|
185
|
+
async ready() {
|
|
186
|
+
for (let p; p !== pending;) {
|
|
187
|
+
p = pending;
|
|
188
|
+
await p;
|
|
189
|
+
}
|
|
190
|
+
const v = untrack(value.get);
|
|
191
|
+
if (v === undefined && untrack(error.get) !== undefined)
|
|
192
|
+
throw untrack(error.get);
|
|
193
|
+
return v;
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
return self;
|
|
197
|
+
}
|
|
198
|
+
const KEEP = 5 * 60_000;
|
|
199
|
+
const cache = new Map();
|
|
200
|
+
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));
|
|
201
|
+
const entryOf = (key) => {
|
|
202
|
+
const h = hash(key);
|
|
203
|
+
let e = cache.get(h);
|
|
204
|
+
if (!e)
|
|
205
|
+
cache.set(h, (e = { key, has: false, at: 0, invalid: false, seq: 0, users: new Set() }));
|
|
206
|
+
return e;
|
|
207
|
+
};
|
|
208
|
+
const release = (e, leaving) => {
|
|
209
|
+
e.keep = e.users.size ? Math.max(...[...e.users].map((u) => u.keep)) : leaving?.keep ?? e.keep;
|
|
210
|
+
if (e.users.size)
|
|
211
|
+
return;
|
|
212
|
+
clearTimeout(e.drop);
|
|
213
|
+
e.drop = setTimeout(() => { if (!e.users.size)
|
|
214
|
+
cache.delete(hash(e.key)); }, e.keep ?? KEEP);
|
|
215
|
+
};
|
|
216
|
+
const store = (e, v, seq) => {
|
|
217
|
+
if (seq !== e.seq)
|
|
218
|
+
return;
|
|
219
|
+
Object.assign(e, { value: v, has: true, at: Date.now(), invalid: false });
|
|
220
|
+
for (const u of e.users)
|
|
221
|
+
u.push(v);
|
|
222
|
+
};
|
|
223
|
+
const request = (e, answer) => {
|
|
224
|
+
const seq = ++e.seq;
|
|
225
|
+
const p = answer.then((v) => { if (v !== undefined)
|
|
226
|
+
store(e, v, seq); return v; });
|
|
227
|
+
e.pending = p;
|
|
228
|
+
const clear = () => { if (e.pending === p)
|
|
229
|
+
e.pending = undefined; };
|
|
230
|
+
p.then(clear, clear);
|
|
231
|
+
return p;
|
|
232
|
+
};
|
|
233
|
+
export function invalidate(prefix = []) {
|
|
234
|
+
if (!browser)
|
|
235
|
+
return;
|
|
236
|
+
const parts = prefix.map(hash);
|
|
237
|
+
group(() => {
|
|
238
|
+
for (const e of cache.values()) {
|
|
239
|
+
if (!parts.every((p, i) => i < e.key.length && hash(e.key[i]) === p))
|
|
240
|
+
continue;
|
|
241
|
+
e.seq++;
|
|
242
|
+
e.pending = undefined;
|
|
243
|
+
e.invalid = true;
|
|
244
|
+
for (const u of e.users)
|
|
245
|
+
u.rerun();
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
export function setData(key, value) {
|
|
250
|
+
if (!browser)
|
|
251
|
+
return;
|
|
252
|
+
const e = entryOf(key);
|
|
253
|
+
store(e, typeof value === 'function' ? value(e.value) : value, ++e.seq);
|
|
254
|
+
release(e);
|
|
255
|
+
}
|
|
256
|
+
export function prefetch(key, fetcher) {
|
|
257
|
+
if (!browser)
|
|
258
|
+
return Promise.resolve();
|
|
259
|
+
const e = entryOf(key);
|
|
260
|
+
const p = e.has && !e.invalid ? Promise.resolve() : e.pending ?? request(e, (async () => fetcher({ signal: new AbortController().signal }))());
|
|
261
|
+
release(e);
|
|
262
|
+
return p.then(() => { }, () => { });
|
|
263
|
+
}
|
|
264
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
265
|
+
const abort = () => { clearTimeout(t); reject(signal.reason); };
|
|
266
|
+
const t = setTimeout(() => { signal.removeEventListener('abort', abort); resolve(); }, ms);
|
|
267
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
268
|
+
});
|
|
269
|
+
export function batch(load, options = {}) {
|
|
270
|
+
let queued;
|
|
271
|
+
const inFlight = new Map();
|
|
272
|
+
const send = (keys) => {
|
|
273
|
+
const settle = (fn) => { for (const [key, w] of keys) {
|
|
274
|
+
inFlight.delete(key);
|
|
275
|
+
fn(key, w);
|
|
276
|
+
} };
|
|
277
|
+
Promise.resolve()
|
|
278
|
+
.then(() => load([...keys.keys()], { signal: new AbortController().signal }))
|
|
279
|
+
.then((answers) => settle((key, w) => (answers !== null && typeof answers === 'object' && Object.hasOwn(answers, key) ? w.resolve(answers[key]) : w.reject(new Error(`batch: no answer for "${key}"`)))), (err) => settle((_, w) => w.reject(err)));
|
|
280
|
+
};
|
|
281
|
+
const flush = () => {
|
|
282
|
+
const all = [...queued];
|
|
283
|
+
queued = undefined;
|
|
284
|
+
const max = Math.max(1, options.max ?? all.length);
|
|
285
|
+
for (let i = 0; i < all.length; i += max)
|
|
286
|
+
send(new Map(all.slice(i, i + max)));
|
|
287
|
+
};
|
|
288
|
+
return {
|
|
289
|
+
get(key) {
|
|
290
|
+
const pending = inFlight.get(key);
|
|
291
|
+
if (pending)
|
|
292
|
+
return pending;
|
|
293
|
+
if (!queued) {
|
|
294
|
+
queued = new Map();
|
|
295
|
+
setTimeout(flush, options.wait ?? 0);
|
|
296
|
+
}
|
|
297
|
+
let w;
|
|
298
|
+
const promise = new Promise((resolve, reject) => { w = { resolve, reject }; });
|
|
299
|
+
queued.set(key, w);
|
|
300
|
+
inFlight.set(key, promise);
|
|
301
|
+
return promise;
|
|
302
|
+
},
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
export async function json(url, init) {
|
|
306
|
+
const res = await fetch(url, init);
|
|
307
|
+
if (!res.ok) {
|
|
308
|
+
await res.text().catch(() => { });
|
|
309
|
+
throw Object.assign(new Error(`${url}: ${res.status} ${res.statusText}`.trim()), { status: res.status });
|
|
310
|
+
}
|
|
311
|
+
return res.json();
|
|
312
|
+
}
|
package/dist/forms/index.d.ts
CHANGED
|
@@ -1,7 +1,26 @@
|
|
|
1
1
|
import { type Ctx, type Signal } from '../runtime/index.ts';
|
|
2
2
|
import type { Form, FormOptions } from './types.ts';
|
|
3
3
|
export type { Form, FormError, FormOptions, Path, StandardSchema } from './types.ts';
|
|
4
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* A form's engine: connect it to a `<form>` with `[engine]`, and it validates the fields bound to `values` (native
|
|
6
|
+
* constraints, a Standard Schema, server errors), shows each error on its field, and runs `submit` once all is valid.
|
|
7
|
+
* `values`: the form's state, a component's or a store's (on the server it only renders).
|
|
8
|
+
* @example
|
|
9
|
+
* ```tscl
|
|
10
|
+
* <script>
|
|
11
|
+
* import { form } from 'clarusjs/forms'
|
|
12
|
+
* let signup = state({ name: '', email: '' })
|
|
13
|
+
* const f = form(signup, {
|
|
14
|
+
* submit: async (v) => { const res = await post('/api/signup', v); if (!res.ok) return { errors: await res.json() } },
|
|
15
|
+
* })
|
|
16
|
+
* </script>
|
|
17
|
+
* <form [engine]="f" novalidate>
|
|
18
|
+
* <label>Email <input type="email" required [(value)]="signup.email"> <small data-cl-message></small></label>
|
|
19
|
+
* <button [disabled]="f.submitting">Sign up</button>
|
|
20
|
+
* </form>
|
|
21
|
+
* ```
|
|
22
|
+
* @see https://clarusjs.com/reference/forms#form
|
|
23
|
+
*/
|
|
5
24
|
export declare function form<T extends object>(values: Signal<T> | T, options?: FormOptions<T>): Form<T>;
|
|
6
|
-
/** [engine]="f" (compiled): connect the element marked data-cl-form="index" to its form until the island goes. */
|
|
25
|
+
/** [engine]="f" (compiled): connect the element marked data-cl-form="index" to its form until the island goes. @internal */
|
|
7
26
|
export declare function connect(ctx: Ctx, index: number, get: () => Form<any>): void;
|
package/dist/forms/types.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* A Standard Schema (https://standardschema.dev): Zod, Valibot, ArkType… Declared here, so there's no dependency.
|
|
3
|
+
* @see https://clarusjs.com/reference/forms#standardschema
|
|
4
|
+
*/
|
|
2
5
|
export type StandardSchema<T = unknown> = {
|
|
3
6
|
readonly '~standard': {
|
|
4
7
|
readonly version: 1;
|
|
@@ -18,12 +21,19 @@ export type StandardResult<T> = {
|
|
|
18
21
|
} | {
|
|
19
22
|
readonly issues: ReadonlyArray<StandardIssue>;
|
|
20
23
|
};
|
|
21
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* The dotted paths of a form's values: `customer.email`, `lines.0.item` (any string for values typed `any`).
|
|
26
|
+
* @see https://clarusjs.com/reference/forms#path
|
|
27
|
+
*/
|
|
22
28
|
export type Path<T> = 0 extends 1 & T ? string : PathOf<T, 6>;
|
|
23
29
|
type Prev = [never, 0, 1, 2, 3, 4, 5];
|
|
24
30
|
type PathOf<T, D extends number> = [D] extends [never] ? never : T extends readonly (infer U)[] ? `${number}` | `${number}.${PathOf<U, Prev[D]>}` : T extends object ? {
|
|
25
31
|
[K in keyof T & string]: K | `${K}.${PathOf<T[K], Prev[D]>}`;
|
|
26
32
|
}[keyof T & string] : never;
|
|
33
|
+
/**
|
|
34
|
+
* `form()`'s options: a schema, when errors show, messages, and the submit callback.
|
|
35
|
+
* @see https://clarusjs.com/reference/forms#form
|
|
36
|
+
*/
|
|
27
37
|
export type FormOptions<T> = {
|
|
28
38
|
/** Validates the whole object; its issues land on their fields by path. Sync or async. */
|
|
29
39
|
schema?: StandardSchema<T>;
|
|
@@ -38,13 +48,20 @@ export type FormOptions<T> = {
|
|
|
38
48
|
errors?: Record<string, string>;
|
|
39
49
|
}>;
|
|
40
50
|
};
|
|
41
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* An error being shown, for a summary: its path, message, its message element's id, and its step.
|
|
53
|
+
* @see https://clarusjs.com/reference/forms#formerror
|
|
54
|
+
*/
|
|
42
55
|
export type FormError<T = any> = {
|
|
43
56
|
path: Path<T>;
|
|
44
57
|
message: string;
|
|
45
58
|
id: string;
|
|
46
59
|
step: string | null;
|
|
47
60
|
};
|
|
61
|
+
/**
|
|
62
|
+
* A form's engine, as `form()` returns it: errors, touched and changed fields, steps, and submit.
|
|
63
|
+
* @see https://clarusjs.com/reference/forms#form
|
|
64
|
+
*/
|
|
48
65
|
export type Form<T> = {
|
|
49
66
|
/** The message shown for a field now: '' when there is none, or it isn't shown yet. */
|
|
50
67
|
error(path: Path<T>): string;
|
package/dist/runtime/attrs.js
CHANGED
|
@@ -25,16 +25,24 @@ function safeUrl(url, image) {
|
|
|
25
25
|
return true;
|
|
26
26
|
return image && RASTER_DATA.test(compact);
|
|
27
27
|
}
|
|
28
|
+
// false is a value here, not a missing attribute: enumerated attributes (removing one means its default), and the
|
|
29
|
+
// ARIA states whose absence means "doesn't apply" (no aria-expanded: nothing expands). Other aria-* (aria-current:
|
|
30
|
+
// `active ? 'page' : false`) keep false = removed.
|
|
31
|
+
const ENUMERATED = new Set(['contenteditable', 'draggable', 'spellcheck', 'translate', 'aria-expanded', 'aria-pressed', 'aria-checked', 'aria-selected']);
|
|
28
32
|
/**
|
|
29
33
|
* What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
|
|
30
34
|
*/
|
|
31
35
|
export function attrValue(name, value, tag) {
|
|
32
|
-
if (value
|
|
36
|
+
if (value == null)
|
|
37
|
+
return null;
|
|
38
|
+
const n = name.toLowerCase();
|
|
39
|
+
if (typeof value === 'boolean' && ENUMERATED.has(n))
|
|
40
|
+
return n === 'translate' ? (value ? 'yes' : 'no') : String(value); // translate: yes/no
|
|
41
|
+
if (value === false)
|
|
33
42
|
return null;
|
|
34
43
|
if (value === true)
|
|
35
44
|
return true;
|
|
36
45
|
const s = String(value);
|
|
37
|
-
const n = name.toLowerCase();
|
|
38
46
|
// List-valued URL attributes: every entry must be safe, not just the first.
|
|
39
47
|
if (n === 'srcset') {
|
|
40
48
|
// "url 1x, url 2x"
|
package/dist/runtime/dom.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { type Signal } from './signals.ts';
|
|
2
|
+
/** @internal Compiled components call this; apps don't. */
|
|
2
3
|
export type Hole = {
|
|
3
4
|
start: Comment;
|
|
4
5
|
end: Comment;
|
|
5
6
|
};
|
|
7
|
+
/** @internal Compiled components call this; apps don't. */
|
|
6
8
|
export type Block = {
|
|
7
9
|
start: Comment;
|
|
8
10
|
end: Comment;
|
|
@@ -19,59 +21,65 @@ export type For = Range & {
|
|
|
19
21
|
/**
|
|
20
22
|
* Where wiring looks for its markers: a whole island, or one @for row inside it. A row template repeats its marker
|
|
21
23
|
* numbers once per row, so code wiring a row only looks between that row's markers.
|
|
24
|
+
* @internal Compiled components call this; apps don't.
|
|
22
25
|
*/
|
|
23
26
|
export type Ctx = Element | {
|
|
24
27
|
root: Element;
|
|
25
28
|
start: Comment;
|
|
26
29
|
end: Comment;
|
|
27
30
|
};
|
|
28
|
-
/** Hole markers in `ctx`, by index. */
|
|
31
|
+
/** Hole markers in `ctx`, by index. @internal */
|
|
29
32
|
export declare function holes(ctx: Ctx): Hole[];
|
|
30
|
-
/** @if block markers in `ctx`, by index. */
|
|
33
|
+
/** @if block markers in `ctx`, by index. @internal */
|
|
31
34
|
export declare function blocks(ctx: Ctx): Block[];
|
|
32
35
|
/**
|
|
33
36
|
* An @if block. `which()` picks the branch (-1 for none). The server-rendered branch is wired in place; a change
|
|
34
37
|
* removes the old branch (disposing its effects and handlers), inserts the new branch's HTML and wires it.
|
|
38
|
+
* @internal Compiled components call this; apps don't.
|
|
35
39
|
*/
|
|
36
40
|
export declare function block(ctx: Ctx, index: number, which: () => number, branches: {
|
|
37
41
|
html: () => string;
|
|
38
42
|
wire: () => void;
|
|
39
43
|
}[]): void;
|
|
44
|
+
/** @internal Compiled components call this; apps don't. */
|
|
40
45
|
export declare function region(ctx: Ctx, index: number, html: () => string, wire: () => void): void;
|
|
41
46
|
/**
|
|
42
47
|
* A @for list. Rows the server rendered are adopted in place. When the list changes, rows are matched by key:
|
|
43
48
|
* kept rows keep their DOM nodes (moved only when out of order) and get the new item and index through their
|
|
44
49
|
* signals; new rows are rendered and wired; removed rows are disposed and removed. `@empty` content is shown while
|
|
45
50
|
* the list is empty.
|
|
51
|
+
* @internal Compiled components call this; apps don't.
|
|
46
52
|
*/
|
|
47
53
|
export declare function forBlock(ctx: Ctx, index: number, list: () => unknown, keyOf: (item: any, i: number) => unknown, row: {
|
|
48
|
-
html: (item: any, i: number) => string;
|
|
49
|
-
wire: (ctx: Ctx, item: Signal<any>, index: Signal<number>) => void;
|
|
54
|
+
html: (item: any, i: number, list: unknown[]) => string;
|
|
55
|
+
wire: (ctx: Ctx, item: Signal<any>, index: Signal<number>, count: Signal<number>) => void;
|
|
50
56
|
}, empty: {
|
|
51
57
|
html: () => string;
|
|
52
58
|
wire: (ctx: Ctx) => void;
|
|
53
59
|
} | null): void;
|
|
54
|
-
/** Keep exactly one text node between the hole's markers, set to `fn()`. */
|
|
60
|
+
/** Keep exactly one text node between the hole's markers, set to `fn()`. @internal */
|
|
55
61
|
export declare function text(hole: Hole, fn: () => unknown): void;
|
|
56
62
|
/**
|
|
57
63
|
* Register a handler for elements marked `data-cl-e="index"` inside `ctx`.
|
|
58
64
|
* One listener per island per event type; it walks from the target up to the island root, running handlers
|
|
59
65
|
* innermost first and stopping when one calls `stopPropagation()`. A handler registered for a @for row only fires
|
|
60
66
|
* for elements in that row.
|
|
67
|
+
* @internal Compiled components call this; apps don't.
|
|
61
68
|
*/
|
|
62
69
|
export declare function on(ctx: Ctx, index: number, type: string, fn: (e: Event) => void): void;
|
|
63
70
|
/** The element matching `selector` in `ctx`: this island's (not a nested island's), and in a row, that row's. */
|
|
64
71
|
export declare function marked(ctx: Ctx, selector: string): Element | undefined;
|
|
65
|
-
/** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. */
|
|
72
|
+
/** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. @internal */
|
|
66
73
|
export declare function attr(ctx: Ctx, index: number, name: string, fn: () => unknown, tag?: string): void;
|
|
67
74
|
/**
|
|
68
75
|
* A @model input: writing it asks the parent island to update its state (a bubbling, cancelable cl:model event from
|
|
69
76
|
* the island); when no parent takes it (a top-level island), the input keeps the value itself. New props from the
|
|
70
77
|
* parent set it with own().
|
|
78
|
+
* @internal Compiled components call this; apps don't.
|
|
71
79
|
*/
|
|
72
80
|
export declare function modelInput<T>(root: Element, name: string, initial: T): Signal<T> & {
|
|
73
81
|
own(value: T): void;
|
|
74
82
|
};
|
|
75
|
-
/** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. */
|
|
83
|
+
/** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
|
|
76
84
|
export declare function model(ctx: Ctx, index: number, name: string, set: (value: unknown) => void): void;
|
|
77
85
|
export {};
|