@krate/runtime 0.5.0-alpha.2 → 0.5.0-alpha.4

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 (105) hide show
  1. package/dist/action-context.d.ts +56 -0
  2. package/dist/action-context.js +73 -0
  3. package/dist/action-context.test.d.ts +1 -0
  4. package/dist/action-context.test.js +47 -0
  5. package/dist/actions.d.ts +120 -0
  6. package/dist/actions.js +550 -0
  7. package/dist/actions.test.d.ts +1 -0
  8. package/dist/actions.test.js +417 -0
  9. package/dist/boundary.d.ts +121 -0
  10. package/dist/boundary.js +429 -0
  11. package/dist/cache-scope.d.ts +118 -0
  12. package/dist/cache-scope.js +311 -0
  13. package/dist/cache.d.ts +55 -0
  14. package/dist/cache.js +155 -0
  15. package/dist/cache.test.d.ts +1 -0
  16. package/dist/cache.test.js +217 -0
  17. package/dist/class-component.d.ts +66 -0
  18. package/dist/class-component.js +633 -0
  19. package/dist/class-component.test.d.ts +1 -0
  20. package/dist/class-component.test.js +411 -0
  21. package/dist/context.d.ts +13 -0
  22. package/dist/context.js +58 -32
  23. package/dist/context.test.d.ts +1 -0
  24. package/dist/context.test.js +57 -0
  25. package/dist/derived.test.d.ts +1 -0
  26. package/dist/derived.test.js +140 -0
  27. package/dist/discrete.test.d.ts +1 -0
  28. package/dist/discrete.test.js +100 -0
  29. package/dist/dom.d.ts +55 -0
  30. package/dist/dom.js +414 -63
  31. package/dist/effects.d.ts +88 -0
  32. package/dist/effects.js +790 -0
  33. package/dist/effects.test.d.ts +1 -0
  34. package/dist/effects.test.js +485 -0
  35. package/dist/events.d.ts +58 -0
  36. package/dist/events.js +503 -0
  37. package/dist/events.test.d.ts +1 -0
  38. package/dist/events.test.js +447 -0
  39. package/dist/index.d.ts +14 -4
  40. package/dist/index.js +9 -3
  41. package/dist/jsx-types.d.ts +2 -0
  42. package/dist/krate-hydrate-lite.js +7 -1
  43. package/dist/krate-hydrate.js +7 -1
  44. package/dist/krate-runtime.js +7 -1
  45. package/dist/krate-suspense.js +2 -0
  46. package/dist/lanes.test.d.ts +1 -0
  47. package/dist/lanes.test.js +59 -0
  48. package/dist/list.d.ts +20 -0
  49. package/dist/list.js +466 -0
  50. package/dist/list.test.d.ts +1 -0
  51. package/dist/list.test.js +344 -0
  52. package/dist/optimistic-lanes.test.d.ts +1 -0
  53. package/dist/optimistic-lanes.test.js +45 -0
  54. package/dist/portal.d.ts +47 -0
  55. package/dist/portal.js +189 -0
  56. package/dist/portal.test.d.ts +1 -0
  57. package/dist/portal.test.js +99 -0
  58. package/dist/react-effects.test.d.ts +1 -0
  59. package/dist/react-effects.test.js +96 -0
  60. package/dist/react-suspense.test.d.ts +1 -0
  61. package/dist/react-suspense.test.js +194 -0
  62. package/dist/react.d.ts +132 -32
  63. package/dist/react.js +335 -81
  64. package/dist/react.test.js +12 -2
  65. package/dist/reconcile.js +13 -0
  66. package/dist/refs.d.ts +33 -0
  67. package/dist/refs.js +142 -0
  68. package/dist/refs.test.d.ts +1 -0
  69. package/dist/refs.test.js +257 -0
  70. package/dist/request-context.d.ts +62 -0
  71. package/dist/request-context.js +107 -0
  72. package/dist/resource.js +20 -1
  73. package/dist/router-layout.test.d.ts +1 -0
  74. package/dist/router-layout.test.js +179 -0
  75. package/dist/router-lite.d.ts +25 -0
  76. package/dist/router-lite.js +73 -0
  77. package/dist/router-nav.test.d.ts +1 -0
  78. package/dist/router-nav.test.js +399 -0
  79. package/dist/router-slots.test.d.ts +1 -0
  80. package/dist/router-slots.test.js +144 -0
  81. package/dist/router.d.ts +66 -2
  82. package/dist/router.js +1535 -650
  83. package/dist/server-async.test.d.ts +1 -0
  84. package/dist/server-async.test.js +174 -0
  85. package/dist/server-renderer.js +494 -119
  86. package/dist/server.d.ts +27 -1
  87. package/dist/server.js +187 -1
  88. package/dist/server.test.js +20 -0
  89. package/dist/signal-lanes.test.d.ts +1 -0
  90. package/dist/signal-lanes.test.js +32 -0
  91. package/dist/signal.d.ts +186 -1
  92. package/dist/signal.js +896 -66
  93. package/dist/slots.d.ts +22 -0
  94. package/dist/slots.js +134 -0
  95. package/dist/slots.test.d.ts +1 -0
  96. package/dist/slots.test.js +169 -0
  97. package/dist/snapshots.test.d.ts +1 -0
  98. package/dist/snapshots.test.js +208 -0
  99. package/dist/suspense-actions.test.d.ts +1 -0
  100. package/dist/suspense-actions.test.js +72 -0
  101. package/dist/suspense.d.ts +220 -0
  102. package/dist/suspense.js +901 -0
  103. package/dist/suspense.test.d.ts +1 -0
  104. package/dist/suspense.test.js +518 -0
  105. package/package.json +5 -1
@@ -0,0 +1,550 @@
1
+ /**
2
+ * React 19 actions on Krate's server-action transport.
3
+ *
4
+ * This module owns the client half of server actions and the action hooks the
5
+ * compiler lowers React source to:
6
+ *
7
+ * - `__krateAction(id)` builds the client proxy for a `"use server"` export.
8
+ * - A document `submit` listener runs `<form action={fn}>` and
9
+ * `<button formAction={fn}>` actions (server proxies or client functions)
10
+ * inside an async action scope, drives `useFormStatus`, and resets the form
11
+ * after success. Without JavaScript, forms bound to server actions still POST
12
+ * to the action URL.
13
+ * - `__krateActionState` backs `useActionState`, `__krateOptimistic` backs
14
+ * `useOptimistic`, and `__krateFormStatusMount` backs `useFormStatus`.
15
+ *
16
+ * Wire format (see guides/server-actions.md):
17
+ * request JSON {"args":[...]} every argument JSON
18
+ * multipart form fields + "__krate_args" last argument a FormData;
19
+ * (JSON array of leading args)
20
+ * response {"ok":true,"result":R,"redirect":"/path"?,
21
+ * "revalidated":true?,"revalidation":{"paths":[...],"tags":[...]}?}
22
+ * {"ok":false,"error":{"message":M,"digest":D}}
23
+ */
24
+ import { createEffect, onCleanup, krateRunEvent, krateTransitionWrites } from './signal.js';
25
+ /** Field and query parameter carrying the JSON leading arguments of a form call. */
26
+ export const ACTION_ARGS_FIELD = '__krate_args';
27
+ /** Error raised on the client when a server action fails. */
28
+ export class ServerActionError extends Error {
29
+ constructor(message, status, digest) {
30
+ super(message);
31
+ this.name = 'ServerActionError';
32
+ this.status = status;
33
+ if (digest)
34
+ this.digest = digest;
35
+ }
36
+ }
37
+ function basePath() {
38
+ const cfg = globalThis.__KRATE_CFG__;
39
+ return cfg && cfg.basePath ? cfg.basePath : '';
40
+ }
41
+ /** True for a server action proxy created by `__krateAction`. */
42
+ export function isServerAction(value) {
43
+ return typeof value === 'function' && typeof value.$$krateAction === 'string';
44
+ }
45
+ function navigateTo(url) {
46
+ const nav = globalThis.navigate;
47
+ if (typeof nav === 'function')
48
+ nav(url);
49
+ else if (typeof location !== 'undefined')
50
+ location.assign(url);
51
+ }
52
+ /**
53
+ * Tells the page that the action revalidated server caches. The router
54
+ * listens for `krate:revalidate` and refreshes the current route; detail is
55
+ * `{ paths: [{ path, type }], tags: [...] }`.
56
+ */
57
+ function dispatchRevalidate(info) {
58
+ if (typeof window === 'undefined' || typeof CustomEvent === 'undefined')
59
+ return;
60
+ const detail = {
61
+ paths: info && Array.isArray(info.paths) ? info.paths : [],
62
+ tags: info && Array.isArray(info.tags) ? info.tags : [],
63
+ };
64
+ window.dispatchEvent(new CustomEvent('krate:revalidate', { detail }));
65
+ }
66
+ function errorFrom(p, status, statusText) {
67
+ const e = p ? p.error : undefined;
68
+ if (e && typeof e === 'object') {
69
+ return new ServerActionError(e.message || 'Server action failed', status, e.digest);
70
+ }
71
+ const message = (p && (p.details || (typeof e === 'string' ? e : ''))) || statusText || 'Server action failed';
72
+ return new ServerActionError(message, status);
73
+ }
74
+ /**
75
+ * POSTs one action call. A trailing FormData argument is sent as multipart
76
+ * with the leading arguments JSON-encoded in `__krate_args`; anything else is
77
+ * sent as a JSON `{args}` body. Resolves with the action's return value and
78
+ * follows a `redirect` from the response.
79
+ */
80
+ export async function callServerAction(url, args) {
81
+ const headers = {
82
+ accept: 'application/json',
83
+ 'x-krate-action': 'fetch',
84
+ };
85
+ if (typeof location !== 'undefined')
86
+ headers['x-krate-return'] = location.pathname + location.search;
87
+ let body;
88
+ const last = args[args.length - 1];
89
+ if (typeof FormData !== 'undefined' && last instanceof FormData) {
90
+ const fd = new FormData();
91
+ last.forEach((value, key) => {
92
+ if (key !== ACTION_ARGS_FIELD)
93
+ fd.append(key, value);
94
+ });
95
+ const leading = args.slice(0, -1);
96
+ if (leading.length > 0)
97
+ fd.set(ACTION_ARGS_FIELD, JSON.stringify(leading));
98
+ body = fd;
99
+ }
100
+ else {
101
+ headers['content-type'] = 'application/json';
102
+ body = JSON.stringify({ args });
103
+ }
104
+ const res = await fetch(url, { method: 'POST', credentials: 'same-origin', headers, body });
105
+ let payload = null;
106
+ try {
107
+ payload = (await res.json());
108
+ }
109
+ catch {
110
+ payload = null;
111
+ }
112
+ if (!res.ok || !payload || payload.ok === false) {
113
+ throw errorFrom(payload, res.status, res.statusText);
114
+ }
115
+ if (payload.revalidated)
116
+ dispatchRevalidate(payload.revalidation);
117
+ if (typeof payload.redirect === 'string' && payload.redirect)
118
+ navigateTo(payload.redirect);
119
+ return payload.result;
120
+ }
121
+ function makeProxy(id, bound) {
122
+ const url = basePath() + '/__krate/action/' + id;
123
+ const action = function (...args) {
124
+ return callServerAction(url, bound.concat(args));
125
+ };
126
+ Object.defineProperty(action, 'actionUrl', { value: url });
127
+ Object.defineProperty(action, '$$krateAction', { value: id });
128
+ Object.defineProperty(action, '$$krateBound', { value: bound });
129
+ // React server references support `.bind(null, ...args)` to pre-fill
130
+ // arguments; the result is still a server action.
131
+ Object.defineProperty(action, 'bind', {
132
+ value: (_this, ...more) => makeProxy(id, bound.concat(more)),
133
+ });
134
+ action.toString = () => url;
135
+ return action;
136
+ }
137
+ /** Client proxy for the server action with the given id. */
138
+ export function __krateAction(id) {
139
+ return makeProxy(id, []);
140
+ }
141
+ // Action scope (async transitions)
142
+ let pendingActions = 0;
143
+ const settleListeners = new Set();
144
+ /**
145
+ * Marks the start of an action or async transition and returns its end
146
+ * callback. Optimistic updates stay applied while any scope is open. Exposed so
147
+ * `startTransition` implementations can join the same scope.
148
+ */
149
+ export function __krateBeginAction() {
150
+ pendingActions++;
151
+ let ended = false;
152
+ return () => {
153
+ if (ended)
154
+ return;
155
+ ended = true;
156
+ pendingActions--;
157
+ if (pendingActions === 0) {
158
+ // Optimistic reverts land with the action's other settle updates, in
159
+ // the transition lane.
160
+ krateTransitionWrites(() => {
161
+ for (const listener of Array.from(settleListeners))
162
+ listener();
163
+ });
164
+ }
165
+ };
166
+ }
167
+ /** True while an action or async transition is pending. */
168
+ export function isActionPending() {
169
+ return pendingActions > 0;
170
+ }
171
+ const defaultRunner = (fn) => {
172
+ const end = __krateBeginAction();
173
+ let result;
174
+ try {
175
+ result = fn();
176
+ }
177
+ catch (err) {
178
+ end();
179
+ return Promise.reject(err);
180
+ }
181
+ return Promise.resolve(result).finally(end);
182
+ };
183
+ let runner = defaultRunner;
184
+ /**
185
+ * Replaces the transition runner used for form actions and `useActionState`
186
+ * dispatches, so a framework-wide async `startTransition` can own them. Passing
187
+ * null restores the built-in runner.
188
+ */
189
+ export function setActionTransitionRunner(next) {
190
+ runner = next || defaultRunner;
191
+ }
192
+ /** Runs fn inside the current action transition runner. */
193
+ export function runActionTransition(fn) {
194
+ return runner(fn);
195
+ }
196
+ // Errors
197
+ /**
198
+ * Reports an action error. An error boundary integration can install
199
+ * `globalThis.__krateActionError(error, element)` and return true to claim the
200
+ * error; otherwise a bubbling `krate:action-error` event is dispatched on the
201
+ * element (or document) and the error is logged.
202
+ */
203
+ export function reportActionError(error, el) {
204
+ const g = globalThis;
205
+ if (typeof g.__krateActionError === 'function') {
206
+ try {
207
+ if (g.__krateActionError(error, el) === true)
208
+ return;
209
+ }
210
+ catch {
211
+ // A failing boundary hook must not hide the original error.
212
+ }
213
+ }
214
+ const target = el || (typeof document !== 'undefined' ? document : null);
215
+ let handled = false;
216
+ if (target && typeof CustomEvent !== 'undefined') {
217
+ const ev = new CustomEvent('krate:action-error', { bubbles: true, cancelable: true, detail: { error } });
218
+ handled = !target.dispatchEvent(ev);
219
+ }
220
+ if (!handled)
221
+ console.error('krate server action:', error);
222
+ }
223
+ const IDLE = Object.freeze({ pending: false, data: null, method: null, action: null });
224
+ const formStates = new WeakMap();
225
+ function formState(form) {
226
+ let st = formStates.get(form);
227
+ if (!st) {
228
+ st = { status: IDLE, subs: new Set(), running: 0, resetRequested: false };
229
+ formStates.set(form, st);
230
+ }
231
+ return st;
232
+ }
233
+ function publish(st, status) {
234
+ st.status = status;
235
+ for (const sub of Array.from(st.subs))
236
+ sub(status);
237
+ }
238
+ /**
239
+ * Subscribes a component's `useFormStatus()` to the nearest form that contains
240
+ * its root element `el` (not `el` itself, matching React: a component reads the
241
+ * status of a parent form). Returns the unsubscribe function, used as the
242
+ * callback-ref cleanup when the element detaches.
243
+ */
244
+ export function __krateFormStatusMount(el, setters) {
245
+ let form = null;
246
+ for (let n = el ? el.parentElement : null; n; n = n.parentElement) {
247
+ if (n.tagName === 'FORM') {
248
+ form = n;
249
+ break;
250
+ }
251
+ }
252
+ if (!form)
253
+ return () => { };
254
+ const st = formState(form);
255
+ const sub = (s) => {
256
+ if (setters.status)
257
+ setters.status(s);
258
+ if (setters.pending)
259
+ setters.pending(s.pending);
260
+ if (setters.data)
261
+ setters.data(s.data);
262
+ if (setters.method)
263
+ setters.method(s.method);
264
+ if (setters.action)
265
+ setters.action(s.action);
266
+ };
267
+ st.subs.add(sub);
268
+ sub(st.status);
269
+ // The returned function is the callback-ref cleanup: the ref system calls
270
+ // it when the element detaches. Registering it with onCleanup instead would
271
+ // tie it to the ref binding's effect, which may re-run.
272
+ return () => {
273
+ st.subs.delete(sub);
274
+ };
275
+ }
276
+ /**
277
+ * Assigns an element to a ref value (callback or `{ current }` object). Used
278
+ * when the compiler composes a component's own ref with the useFormStatus
279
+ * mount ref.
280
+ */
281
+ export function __krateAssignRef(ref, el) {
282
+ if (typeof ref === 'function')
283
+ ref(el);
284
+ else if (ref && typeof ref === 'object')
285
+ ref.current = el;
286
+ }
287
+ /** Current status of a form (idle unless an action submitted from it is pending). */
288
+ export function getFormStatus(form) {
289
+ return formStates.get(form)?.status || IDLE;
290
+ }
291
+ // Form reset
292
+ function resetForm(form) {
293
+ // Controlled fields keep their signal value: snapshot and restore them
294
+ // around the native reset, which only affects uncontrolled fields.
295
+ const controlled = Array.from(form.querySelectorAll('[data-kattr-value],[data-kattr-checked]')).map((el) => ({ el, value: el.value, checked: el.checked }));
296
+ form.reset();
297
+ for (const c of controlled) {
298
+ if (c.el.hasAttribute('data-kattr-value'))
299
+ c.el.value = c.value;
300
+ if (c.el.hasAttribute('data-kattr-checked'))
301
+ c.el.checked = c.checked;
302
+ }
303
+ }
304
+ /**
305
+ * React DOM's `requestFormReset(form)`: resets the form's uncontrolled fields
306
+ * once the action currently pending on it settles, or immediately when none is.
307
+ */
308
+ export function requestFormReset(form) {
309
+ const st = formStates.get(form);
310
+ if (st && st.running > 0) {
311
+ st.resetRequested = true;
312
+ return;
313
+ }
314
+ resetForm(form);
315
+ }
316
+ /** Binds a function action to a form or submit button (`action={fn}` / `formAction={fn}`). */
317
+ export function __krateBindFormAction(el, get) {
318
+ el.__krateFormAction = get;
319
+ // The native POST target only serves the no-JS fallback; once the function
320
+ // is bound the element matches React's client DOM (no action attribute).
321
+ if (el.tagName === 'FORM') {
322
+ el.removeAttribute('action');
323
+ el.removeAttribute('method');
324
+ }
325
+ else {
326
+ el.removeAttribute('formaction');
327
+ el.removeAttribute('formmethod');
328
+ }
329
+ el.removeAttribute('data-krate-action');
330
+ }
331
+ function boundAction(el) {
332
+ if (!el)
333
+ return null;
334
+ const get = el.__krateFormAction;
335
+ if (typeof get !== 'function')
336
+ return null;
337
+ try {
338
+ return get();
339
+ }
340
+ catch {
341
+ return null;
342
+ }
343
+ }
344
+ function resolveSubmission(form, submitter) {
345
+ if (submitter && submitter !== form) {
346
+ const fn = boundAction(submitter);
347
+ if (typeof fn === 'function')
348
+ return { fn };
349
+ if (submitter.hasAttribute('data-krate-action')) {
350
+ return { url: submitter.formAction || form.action };
351
+ }
352
+ // A plain native formaction wins over the form's action.
353
+ if (submitter.hasAttribute('formaction'))
354
+ return null;
355
+ }
356
+ const fn = boundAction(form);
357
+ if (typeof fn === 'function')
358
+ return { fn };
359
+ if (form.hasAttribute('data-krate-action'))
360
+ return { url: form.action };
361
+ return null;
362
+ }
363
+ function formDataFor(form, submitter) {
364
+ let fd;
365
+ try {
366
+ fd = submitter ? new FormData(form, submitter) : new FormData(form);
367
+ }
368
+ catch {
369
+ fd = new FormData(form);
370
+ const s = submitter;
371
+ if (s && s.name)
372
+ fd.append(s.name, s.value);
373
+ }
374
+ return fd;
375
+ }
376
+ function stripActionURL(url) {
377
+ // The no-JS leading-args query is only for native posts.
378
+ const i = url.indexOf('?');
379
+ return i < 0 ? url : url.slice(0, i);
380
+ }
381
+ /**
382
+ * Runs a form action: sets the form status, invokes the action with the form
383
+ * data in an async transition, resets the form on success and reports errors.
384
+ * Resolves true when the action succeeded.
385
+ */
386
+ export async function submitFormAction(form, action, data, submitter = null, url) {
387
+ const st = formState(form);
388
+ const method = ((submitter && submitter.getAttribute('formmethod')) ||
389
+ form.getAttribute('method') ||
390
+ 'get').toLowerCase();
391
+ st.running++;
392
+ publish(st, { pending: true, data, method, action: action || url || null });
393
+ form.setAttribute('data-krate-action-pending', '1');
394
+ let ok = false;
395
+ try {
396
+ await runActionTransition(async () => {
397
+ const run = action;
398
+ if (run && typeof run.__krateRun === 'function') {
399
+ // useActionState dispatch: it queues and reports its own errors.
400
+ ok = await run.__krateRun(data);
401
+ return;
402
+ }
403
+ if (typeof run === 'function')
404
+ await run(data);
405
+ else if (url)
406
+ await callServerAction(stripActionURL(url), [data]);
407
+ ok = true;
408
+ });
409
+ }
410
+ catch (err) {
411
+ reportActionError(err, form);
412
+ }
413
+ finally {
414
+ st.running--;
415
+ if (st.running === 0) {
416
+ form.removeAttribute('data-krate-action-pending');
417
+ // The settled status commits in a later task (React's transition
418
+ // lane), so the pending render is painted, as in React.
419
+ krateTransitionWrites(() => publish(st, IDLE));
420
+ if (ok || st.resetRequested) {
421
+ st.resetRequested = false;
422
+ if (ok && form.hasAttribute('data-krate-reload'))
423
+ location.reload();
424
+ else
425
+ resetForm(form);
426
+ }
427
+ }
428
+ }
429
+ return ok;
430
+ }
431
+ function onSubmit(e) {
432
+ const form = e.target;
433
+ if (!form || form.tagName !== 'FORM' || e.defaultPrevented)
434
+ return;
435
+ const submitter = e.submitter || null;
436
+ const target = resolveSubmission(form, submitter);
437
+ if (!target)
438
+ return;
439
+ e.preventDefault();
440
+ const data = formDataFor(form, submitter);
441
+ // submit is a discrete event: the pending status (useFormStatus,
442
+ // useActionState) commits before the event returns, as in React, even when
443
+ // the action itself settles a few microtasks later. A focused submit button
444
+ // disabled by that pending render loses focus like React's does.
445
+ krateRunEvent('submit', true, () => {
446
+ void submitFormAction(form, target.fn, data, submitter, target.url);
447
+ });
448
+ }
449
+ /** Installs the document submit listener once per window. */
450
+ export function installActionForms(doc = typeof document !== 'undefined' ? document : undefined) {
451
+ if (!doc)
452
+ return;
453
+ const w = doc.defaultView;
454
+ if (!w || w.__krateActionBound)
455
+ return;
456
+ w.__krateActionBound = true;
457
+ doc.addEventListener('submit', onSubmit, false);
458
+ }
459
+ /**
460
+ * Backs `const [state, formAction, isPending] = useActionState(fn, initial)`.
461
+ * The returned dispatch can be a form action, a button formAction, or called
462
+ * directly. Calls run one at a time in dispatch order; each receives the state
463
+ * the previous call produced. An error cancels the queued calls and is
464
+ * reported to the nearest error boundary hook.
465
+ */
466
+ export function __krateActionState(action, getState, setState, setPending) {
467
+ const queue = [];
468
+ let running = false;
469
+ const drain = async () => {
470
+ running = true;
471
+ while (queue.length > 0) {
472
+ const item = queue.shift();
473
+ let ok = false;
474
+ try {
475
+ const next = await runActionTransition(() => action(getState(), item.payload));
476
+ krateTransitionWrites(() => setState(next));
477
+ ok = true;
478
+ }
479
+ catch (err) {
480
+ const cancelled = queue.splice(0);
481
+ for (const c of cancelled) {
482
+ c.end();
483
+ c.done(false);
484
+ }
485
+ reportActionError(err);
486
+ }
487
+ finally {
488
+ krateTransitionWrites(() => {
489
+ item.end();
490
+ item.done(ok);
491
+ });
492
+ }
493
+ }
494
+ running = false;
495
+ krateTransitionWrites(() => setPending(false));
496
+ };
497
+ const run = (payload) => new Promise((done) => {
498
+ queue.push({ payload, end: __krateBeginAction(), done });
499
+ setPending(true);
500
+ if (!running)
501
+ void drain();
502
+ });
503
+ const dispatch = ((payload) => {
504
+ void run(payload);
505
+ });
506
+ dispatch.__krateRun = run;
507
+ return dispatch;
508
+ }
509
+ // useOptimistic
510
+ /**
511
+ * Backs `const [value, addOptimistic] = useOptimistic(state, update?)`.
512
+ * Optimistic updates are applied on top of the latest base state while an
513
+ * action or async transition is pending and dropped when every pending action
514
+ * has settled. Updates made outside any action are dropped on the next
515
+ * microtask unless an action starts first.
516
+ */
517
+ export function __krateOptimistic(base, set, update) {
518
+ let updates = [];
519
+ const apply = (b) => {
520
+ let v = b;
521
+ for (const a of updates)
522
+ v = update ? update(v, a) : a;
523
+ return v;
524
+ };
525
+ createEffect(() => {
526
+ set(apply(base()));
527
+ });
528
+ const revert = () => {
529
+ if (updates.length === 0)
530
+ return;
531
+ updates = [];
532
+ set(base());
533
+ };
534
+ settleListeners.add(revert);
535
+ onCleanup(() => {
536
+ settleListeners.delete(revert);
537
+ });
538
+ return (a) => {
539
+ updates.push(a);
540
+ set(apply(base()));
541
+ if (pendingActions === 0) {
542
+ queueMicrotask(() => {
543
+ if (pendingActions === 0)
544
+ revert();
545
+ });
546
+ }
547
+ };
548
+ }
549
+ if (typeof document !== 'undefined')
550
+ installActionForms(document);
@@ -0,0 +1 @@
1
+ export {};