brumate 0.8.0 → 0.9.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.
Files changed (122) hide show
  1. package/dist/{boot-BkUdiYOF.d.ts → boot-ej-9NRT3.d.ts} +20 -2
  2. package/dist/cli.js +88 -82
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{client-B0FXW5Kw.js → client-B-ww-PQ7.js} +402 -63
  5. package/dist/client-B-ww-PQ7.js.map +1 -0
  6. package/dist/{client-Cq6aTiDs.d.ts → client-Do6IBIhI.d.ts} +58 -14
  7. package/dist/{defer-BMIMP4Hq.js → defer-JD2FK9mV.js} +5 -3
  8. package/dist/defer-JD2FK9mV.js.map +1 -0
  9. package/dist/{devtools-calls-DGW6nLZ2.js → devtools-calls-DCjuSkim.js} +3 -3
  10. package/dist/{devtools-calls-DGW6nLZ2.js.map → devtools-calls-DCjuSkim.js.map} +1 -1
  11. package/dist/{devtools-panel-B1nF1KB7.js → devtools-panel-DLeWTPhU.js} +4 -4
  12. package/dist/{devtools-panel-B1nF1KB7.js.map → devtools-panel-DLeWTPhU.js.map} +1 -1
  13. package/dist/{devtools-B4prrxht.js → devtools-tuq7ATGN.js} +10 -7
  14. package/dist/devtools-tuq7ATGN.js.map +1 -0
  15. package/dist/{error-catalog-DakxjSgj.js → error-catalog-BBWB7w-E.js} +11 -4
  16. package/dist/error-catalog-BBWB7w-E.js.map +1 -0
  17. package/dist/{error-catalog-VxLbz-6p.js → error-catalog-CbmQqfat.js} +1 -1
  18. package/dist/{events-LgLdp1R7.js → events-BDVITj3P.js} +3 -5
  19. package/dist/events-BDVITj3P.js.map +1 -0
  20. package/dist/{features-DwMYKBIC.js → features-Cte5aj20.js} +8 -2
  21. package/dist/features-Cte5aj20.js.map +1 -0
  22. package/dist/{files-D5GtxwEQ.js → files-Bz0lAQzD.js} +2 -2
  23. package/dist/{files-D5GtxwEQ.js.map → files-Bz0lAQzD.js.map} +1 -1
  24. package/dist/{html-Cf5uKhLs.js → html-BYuHDvxy.js} +10 -3
  25. package/dist/html-BYuHDvxy.js.map +1 -0
  26. package/dist/index.d.ts +71 -19
  27. package/dist/index.js +3 -3
  28. package/dist/{inspect-CGl5Y8q6.js → inspect-fpaBJ5pm.js} +1305 -75
  29. package/dist/inspect-fpaBJ5pm.js.map +1 -0
  30. package/dist/{loader-BsaSuIoG.js → loader-DMxuZ6He.js} +14 -6
  31. package/dist/loader-DMxuZ6He.js.map +1 -0
  32. package/dist/{navigate-BlowKvhB.js → navigate-C5PjwYMh.js} +108 -20
  33. package/dist/navigate-C5PjwYMh.js.map +1 -0
  34. package/dist/{produce-CLABZ8k2.d.ts → produce-BDkCsGH7.d.ts} +3 -3
  35. package/dist/{rpc-C1jYVNAe.js → rpc-DOdrekhP.js} +23 -13
  36. package/dist/rpc-DOdrekhP.js.map +1 -0
  37. package/dist/runtime/bundles.d.ts +3 -2
  38. package/dist/runtime/bundles.js +20 -5
  39. package/dist/runtime/bundles.js.map +1 -1
  40. package/dist/runtime/client.d.ts +4 -3
  41. package/dist/runtime/client.js +5 -5
  42. package/dist/runtime/devtools.d.ts +3 -1
  43. package/dist/runtime/devtools.js +1 -1
  44. package/dist/runtime/events.js +1 -1
  45. package/dist/runtime/hot.d.ts +1 -1
  46. package/dist/runtime/html.js +1 -1
  47. package/dist/runtime/loader.d.ts +2 -2
  48. package/dist/runtime/loader.js +2 -2
  49. package/dist/runtime/otel.d.ts +18 -0
  50. package/dist/runtime/otel.js +127 -0
  51. package/dist/runtime/otel.js.map +1 -0
  52. package/dist/runtime/server.d.ts +4 -3
  53. package/dist/runtime/server.js +5 -5
  54. package/dist/runtime/signals.d.ts +2 -2
  55. package/dist/runtime/signals.js +4 -1
  56. package/dist/runtime/signals.js.map +1 -1
  57. package/dist/runtime/static-loader.d.ts +2 -2
  58. package/dist/runtime/static-loader.js +1 -1
  59. package/dist/runtime/store.d.ts +2 -2
  60. package/dist/runtime/store.js +1 -1
  61. package/dist/runtime/testing.d.ts +2 -2
  62. package/dist/runtime/testing.js +2 -2
  63. package/dist/search-params-qGERTLi3.js +382 -0
  64. package/dist/search-params-qGERTLi3.js.map +1 -0
  65. package/dist/{serial-ribg9NAj.js → serial-B2AJ9VGx.js} +1 -1
  66. package/dist/{serial-ioa17MuY.js → serial-Cj6pDGOq.js} +6 -6
  67. package/dist/{serial-ioa17MuY.js.map → serial-Cj6pDGOq.js.map} +1 -1
  68. package/dist/{server-DesBZv5g.d.ts → server-2-LS_KFo.d.ts} +125 -9
  69. package/dist/{server-BUuf7XPZ.js → server-CRGZMWnK.js} +545 -236
  70. package/dist/server-CRGZMWnK.js.map +1 -0
  71. package/dist/{shared-CX_YacDm.js → shared-CUBWrbiM.js} +4 -4
  72. package/dist/{shared-CX_YacDm.js.map → shared-CUBWrbiM.js.map} +1 -1
  73. package/dist/sheets-B9Zr50mf.js +105 -0
  74. package/dist/sheets-B9Zr50mf.js.map +1 -0
  75. package/dist/{signals-7VVD9C_H.d.ts → signals-BgsJK-uT.d.ts} +16 -6
  76. package/dist/{static-loader-C_en-4v8.js → static-loader-BDBtWsdg.js} +107 -19
  77. package/dist/static-loader-BDBtWsdg.js.map +1 -0
  78. package/dist/{static-loader-UKnK11Em.d.ts → static-loader-CAFn6p0l.d.ts} +2 -2
  79. package/dist/{store-9_oa0HG1.d.ts → store-BwWg-Iei.d.ts} +79 -2
  80. package/dist/store-DNr24Z8L.js +950 -0
  81. package/dist/store-DNr24Z8L.js.map +1 -0
  82. package/dist/{stream-read-BTsYstJY.js → stream-read-CiLDH60b.js} +2 -2
  83. package/dist/{stream-read-BTsYstJY.js.map → stream-read-CiLDH60b.js.map} +1 -1
  84. package/dist/{stream-read-Dek3HnqO.js → stream-read-DVoregpA.js} +1 -1
  85. package/dist/trace-DT7RGRAV.d.ts +52 -0
  86. package/dist/trace-browser-C7MFMove.js +170 -0
  87. package/dist/trace-browser-C7MFMove.js.map +1 -0
  88. package/dist/trace-flag-Dy267snx.js +7 -0
  89. package/dist/trace-flag-Dy267snx.js.map +1 -0
  90. package/dist/{trusted-g_zUJbh2.js → trusted-Bmwg4_hf.js} +12 -5
  91. package/dist/trusted-Bmwg4_hf.js.map +1 -0
  92. package/dist/view-transitions-BpnVwtS4.js +141 -0
  93. package/dist/view-transitions-BpnVwtS4.js.map +1 -0
  94. package/dist/vite.d.ts +8 -1
  95. package/dist/vite.js +356 -46
  96. package/dist/vite.js.map +1 -1
  97. package/elements.d.ts +8 -0
  98. package/package.json +13 -1
  99. package/skills/brumate/SKILL.md +9 -5
  100. package/skills/brumate/references/errors.md +95 -14
  101. package/skills/brumate/references/events.md +27 -1
  102. package/skills/brumate/references/signals.md +4 -4
  103. package/skills/brumate/references/state.md +79 -4
  104. package/skills/brumate/references/syntax.md +58 -9
  105. package/dist/client-B0FXW5Kw.js.map +0 -1
  106. package/dist/defer-BMIMP4Hq.js.map +0 -1
  107. package/dist/devtools-B4prrxht.js.map +0 -1
  108. package/dist/error-catalog-DakxjSgj.js.map +0 -1
  109. package/dist/events-LgLdp1R7.js.map +0 -1
  110. package/dist/features-DwMYKBIC.js.map +0 -1
  111. package/dist/html-Cf5uKhLs.js.map +0 -1
  112. package/dist/inspect-CGl5Y8q6.js.map +0 -1
  113. package/dist/loader-BsaSuIoG.js.map +0 -1
  114. package/dist/navigate-BlowKvhB.js.map +0 -1
  115. package/dist/rpc-C1jYVNAe.js.map +0 -1
  116. package/dist/search-params-Wg-0FsMj.js +0 -148
  117. package/dist/search-params-Wg-0FsMj.js.map +0 -1
  118. package/dist/server-BUuf7XPZ.js.map +0 -1
  119. package/dist/static-loader-C_en-4v8.js.map +0 -1
  120. package/dist/store-Cy4EEyZ7.js +0 -439
  121. package/dist/store-Cy4EEyZ7.js.map +0 -1
  122. package/dist/trusted-g_zUJbh2.js.map +0 -1
@@ -0,0 +1,950 @@
1
+ import { i as HAS_BRIDGES } from "./features-Cte5aj20.js";
2
+ //#region src/runtime/store.ts
3
+ /** The pass of the core, which the browser sets, so a store's readers update in one pass. */
4
+ const PASS = Symbol.for("brumate.pass");
5
+ /** True for a context, which `createContext` made. */
6
+ function isContext(value) {
7
+ return typeof value === "object" && value !== null && typeof value.key === "string" && Object.keys(value).length === 1 && !isContract(value);
8
+ }
9
+ /**
10
+ * The store that `$store` reads: `value` is the store, or for `path` an object that holds it there.
11
+ * `key` names the context that gave `value`, for the message. Throws a `TypeError` for a value that
12
+ * is no store, such as `undefined` or a context, and for `write` on a store that has no `set`.
13
+ */
14
+ function findStored(value, path, write, key) {
15
+ const found = path === void 0 ? value : value?.[path];
16
+ if (!isContract(found)) {
17
+ if (isContext(found)) throw new TypeError(`$store reads the context "${found.key}", which is no store. Read the store in it with $store($getContext(Context))`);
18
+ throw new TypeError(`$store reads ${key === void 0 ? "a value" : `the context "${key}"`}${path === void 0 ? "" : ` at "${path}"`}, which gives no store: a store has the functions get and subscribe`);
19
+ }
20
+ if (write && !canSet(found)) throw new TypeError(`let $store(${key ?? "…"}) writes the store, but the store has no set. Read it with const`);
21
+ return found;
22
+ }
23
+ /**
24
+ * The error of `$store` for a store of another library in a value that the page sends, such as a
25
+ * prop: only the value of a store of `brumate/store` crosses. The fix is said here only.
26
+ */
27
+ function sentForeignStore(component, value) {
28
+ return /* @__PURE__ */ new Error(`$store in ${component} reads a store of another library from ${value}, which the page sends, and only a store of brumate/store crosses. Wrap the library's store with bridge() in a module, or read it from an import, <script module> or a call in this component`);
29
+ }
30
+ /** A value that changes, with the functions that read it and write it. */
31
+ var Store = class {
32
+ /** The value. */
33
+ v;
34
+ /** The functions that `subscribe` added. */
35
+ l = /* @__PURE__ */ new Set();
36
+ /** For a store of `$toStore(signal)`, the write of the signal, which the browser sets. */
37
+ w;
38
+ /** True for a store of `$toStore(memo)`, which only its provider writes. */
39
+ r;
40
+ /** Where `$toStore` made it, for the page state. */
41
+ o;
42
+ /** True for a store of `$toStore` in the browser until its first update. */
43
+ f;
44
+ /**
45
+ * The mark of a store, which `isStore` reads in every copy of the runtime. A field, so a build
46
+ * without stores drops the class.
47
+ */
48
+ k = "brumate.store";
49
+ constructor(value) {
50
+ this.v = value;
51
+ }
52
+ /** The current value. */
53
+ get() {
54
+ return this.v;
55
+ }
56
+ /** Calls `listener` with each new value. Returns the function that stops it. */
57
+ subscribe(listener) {
58
+ this.l.add(listener);
59
+ return () => {
60
+ this.l.delete(listener);
61
+ };
62
+ }
63
+ /**
64
+ * Writes the value, and calls the listeners when it changed. A store of `$toStore(signal)`
65
+ * writes the signal, and a store of a memo throws.
66
+ */
67
+ set(value) {
68
+ if (this.r) throw new Error("This store follows a memo, so only its provider writes it");
69
+ if (Object.is(this.v, value)) return;
70
+ if (this.w) {
71
+ this.v = value;
72
+ this.w(value);
73
+ return;
74
+ }
75
+ sendStore(this, value);
76
+ }
77
+ };
78
+ /** True for a store of `brumate/store`, of any copy of the runtime. */
79
+ function isStore(value) {
80
+ return typeof value === "object" && value !== null && value.k === "brumate.store";
81
+ }
82
+ /** True for a value with the functions `get` and `subscribe` of the store contract. */
83
+ function isContract(value) {
84
+ return typeof value === "object" && value !== null && typeof value.get === "function" && typeof value.subscribe === "function";
85
+ }
86
+ /** True for a value of the store contract that is not a store of brumate. */
87
+ function isForeignStore(value) {
88
+ return isContract(value) && !isStore(value) && !(HAS_BRIDGES && isBridged(value));
89
+ }
90
+ /** True when `$store` can write the store: it has `set`, and is not the store of a memo. */
91
+ function canSet(value) {
92
+ return typeof value.set === "function" && !value.r;
93
+ }
94
+ /** Makes a store, such as one that a module holds for the whole app. */
95
+ function store(value) {
96
+ return new Store(value);
97
+ }
98
+ /** Writes the value of a store and calls its listeners, in one pass of the page. */
99
+ function sendStore(target, value, force) {
100
+ if (!force && Object.is(target.v, value)) return;
101
+ target.v = value;
102
+ const listeners = () => {
103
+ for (const listener of target.l) listener(value);
104
+ };
105
+ const pass = globalThis[PASS];
106
+ if (pass) pass(listeners);
107
+ else listeners();
108
+ }
109
+ /** The derived stores that heard of a change and wait to compute. */
110
+ const waiting = [];
111
+ /** The listener sets that have a trailing listener, which computes the waiting stores. */
112
+ const armed = /* @__PURE__ */ new Set();
113
+ /** True while the waiting stores compute. */
114
+ let flushing = false;
115
+ /** Computes the waiting derived stores, the ones that read the fewest derived stores first. */
116
+ function flushComputed() {
117
+ flushing = true;
118
+ try {
119
+ while (waiting.length > 0) {
120
+ let next = 0;
121
+ for (let i = 1; i < waiting.length; i++) if (waiting[i].level < waiting[next].level) next = i;
122
+ const [computed] = waiting.splice(next, 1);
123
+ computed.waits = false;
124
+ computed.run();
125
+ }
126
+ } catch (error) {
127
+ for (const computed of waiting) computed.waits = false;
128
+ waiting.length = 0;
129
+ throw error;
130
+ } finally {
131
+ flushing = false;
132
+ }
133
+ }
134
+ /**
135
+ * Queues a derived store that a source told of a change. The store waits until the source has
136
+ * called all its listeners, so a store that reads this one and the source computes once, after
137
+ * this one.
138
+ */
139
+ function enqueue(state, source) {
140
+ if (state.waits) return;
141
+ state.waits = true;
142
+ waiting.push(state);
143
+ if (flushing) return;
144
+ const listeners = source.l;
145
+ if (!listeners || armed.has(listeners)) {
146
+ if (!listeners) flushComputed();
147
+ return;
148
+ }
149
+ const trail = () => {
150
+ listeners.delete(trail);
151
+ armed.delete(listeners);
152
+ flushComputed();
153
+ };
154
+ armed.add(listeners);
155
+ listeners.add(trail);
156
+ }
157
+ function derived(sources, fn, initial) {
158
+ const single = !Array.isArray(sources);
159
+ const list = single ? [sources] : sources;
160
+ for (const source of list) if (!source) throw new Error("derived() expects stores as input, got a falsy value");
161
+ const auto = fn.length < 2;
162
+ const out = new Store(initial);
163
+ const subscribers = /* @__PURE__ */ new Set();
164
+ let level = 1;
165
+ const pend = {};
166
+ for (const source of list) {
167
+ level = Math.max(level, (source.d ?? 0) + 1);
168
+ if (pendingOf(source)) pend.q = /* @__PURE__ */ new Set();
169
+ }
170
+ let cleanup;
171
+ let started = false;
172
+ let starting = false;
173
+ let stops = [];
174
+ /** Runs `fn` over the current values of the sources. */
175
+ const compute = (write) => {
176
+ const values = [];
177
+ for (const source of list) values.push(source.get());
178
+ const set = write;
179
+ const update = (change) => write(change(out.v));
180
+ cleanup?.();
181
+ cleanup = void 0;
182
+ const result = fn(single ? values[0] : values, set, update);
183
+ if (auto) write(result);
184
+ else if (typeof result === "function") cleanup = result;
185
+ };
186
+ const send = (value) => {
187
+ if (starting) out.v = value;
188
+ else if (started) sendStore(out, value);
189
+ else out.v = value;
190
+ };
191
+ const state = {
192
+ level,
193
+ waits: false,
194
+ run() {
195
+ if (started) compute(send);
196
+ }
197
+ };
198
+ /** Called by a source. */
199
+ const heard = (source) => {
200
+ if (started) enqueue(state, source);
201
+ };
202
+ const start = () => {
203
+ starting = true;
204
+ started = true;
205
+ try {
206
+ compute(send);
207
+ for (const source of list) stops.push(source.subscribe(() => heard(source)));
208
+ if (pend.q) {
209
+ const check = () => {
210
+ let pending = false;
211
+ for (const source of list) pending ||= !!pendingOf(source)?.n;
212
+ setPending(pend, pending);
213
+ };
214
+ for (const source of list) {
215
+ const q = pendingOf(source)?.q;
216
+ if (q) {
217
+ q.add(check);
218
+ stops.push(() => q.delete(check));
219
+ }
220
+ }
221
+ check();
222
+ }
223
+ } catch (error) {
224
+ started = false;
225
+ for (const end of stops) end();
226
+ stops = [];
227
+ cleanup?.();
228
+ cleanup = void 0;
229
+ throw error;
230
+ } finally {
231
+ starting = false;
232
+ }
233
+ };
234
+ const stop = () => {
235
+ started = false;
236
+ for (const end of stops) end();
237
+ stops = [];
238
+ cleanup?.();
239
+ cleanup = void 0;
240
+ if (state.waits) {
241
+ state.waits = false;
242
+ waiting.splice(waiting.indexOf(state), 1);
243
+ }
244
+ };
245
+ const result = Object.assign({
246
+ get() {
247
+ if (started) return out.v;
248
+ let value = out.v;
249
+ started = true;
250
+ try {
251
+ compute((next) => {
252
+ value = next;
253
+ });
254
+ } finally {
255
+ started = false;
256
+ cleanup?.();
257
+ cleanup = void 0;
258
+ }
259
+ return value;
260
+ },
261
+ subscribe(listener) {
262
+ const stopListening = out.subscribe(listener);
263
+ if (!started) try {
264
+ start();
265
+ } catch (error) {
266
+ stopListening();
267
+ throw error;
268
+ }
269
+ subscribers.add(stopListening);
270
+ return () => {
271
+ if (subscribers.delete(stopListening)) {
272
+ stopListening();
273
+ if (subscribers.size === 0) stop();
274
+ }
275
+ };
276
+ }
277
+ }, { d: level });
278
+ if (pend.q) Object.defineProperty(result, PENDING, { value: pend });
279
+ return result;
280
+ }
281
+ /** The key of a store that holds the error of a run, which `$store` reads again on each notice. */
282
+ const HOLDS = Symbol.for("brumate.holds");
283
+ /**
284
+ * The key of the pending state of a store, which a store of a module can hold, as a memo that
285
+ * loads is pending. `$isPending` and `$resolve` read it in a component.
286
+ */
287
+ const PENDING = Symbol.for("brumate.pending");
288
+ /** The pending state of a store, when it has one. */
289
+ function pendingOf(store) {
290
+ const state = store?.[PENDING];
291
+ return state?.q instanceof Set ? state : void 0;
292
+ }
293
+ /** Sets the pending flag of a store, and tells its listeners when it changed. */
294
+ function setPending(target, pending) {
295
+ if (!!target.n !== pending) {
296
+ target.n = pending;
297
+ for (const listener of target.q) listener(pending);
298
+ }
299
+ }
300
+ /** True on the server, or in a test while server code runs. */
301
+ function onServer() {
302
+ const inRequest = globalThis[Symbol.for("brumate.inRequest")];
303
+ return typeof document === "undefined" || inRequest?.() === true;
304
+ }
305
+ /** Thrown by a read of a memo of a module whose first value still loads. It carries the load. */
306
+ var Waiting = class extends Error {
307
+ /** The load, which settles when the memo has its value or its error. */
308
+ load;
309
+ constructor(load) {
310
+ super("This value is still loading. Wait for it with await $resolve(memo), or check $isPending(memo) first");
311
+ this.load = load;
312
+ }
313
+ };
314
+ /** True for a store that `memoStore` made. */
315
+ function isMemoStore(value) {
316
+ return typeof value.p === "function" && isContract(value.i);
317
+ }
318
+ /** True for a promise or an async iterable, which a memo loads. */
319
+ function loads(value) {
320
+ return value !== null && typeof value === "object" && (typeof value.then === "function" || typeof value[Symbol.asyncIterator] === "function");
321
+ }
322
+ /** The value of a store, or the error that its `get` throws. */
323
+ function peekStore(source) {
324
+ try {
325
+ return source.get();
326
+ } catch (error) {
327
+ return error;
328
+ }
329
+ }
330
+ /**
331
+ * The key of what the server sends in the slot of `.i` in place of a value: `0` for a value that
332
+ * the importer's memo sends, or the promise of a value that loaded, with its sources in `s`. A
333
+ * value of a memo never has the key, and a promise in an object stays a promise in the browser.
334
+ */
335
+ const FACE = "$$ms";
336
+ /** True for what the server sends for a value that loaded: its promise and its sources. */
337
+ function isLoadedFace(value) {
338
+ return typeof value === "object" && value !== null && value[FACE] instanceof Promise;
339
+ }
340
+ /**
341
+ * True when two values of sources hold the same data, as the page state sends them: plain objects
342
+ * and arrays item by item, a date by its time, a map and a set by their entries, a regular
343
+ * expression by its source and flags, a typed array by its items, anything else by `Object.is`.
344
+ */
345
+ function sameSource(a, b, open = /* @__PURE__ */ new Set()) {
346
+ if (Object.is(a, b)) return true;
347
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
348
+ if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
349
+ if (open.has(a)) return true;
350
+ open.add(a);
351
+ if (a instanceof Date) return Object.is(a.getTime(), b.getTime());
352
+ if (a instanceof RegExp) return a.source === b.source && a.flags === b.flags;
353
+ if (a instanceof Map || a instanceof Set || ArrayBuffer.isView(a) && !(a instanceof DataView)) return sameSource([...a], [...b], open);
354
+ const left = Object.keys(a);
355
+ if (left.length !== Object.keys(b).length) return false;
356
+ for (const key of left) if (!(key in b) || !sameSource(a[key], b[key], open)) return false;
357
+ return true;
358
+ }
359
+ /** The render of the server that runs now, so a failed load is shared within it only. */
360
+ function currentRender() {
361
+ return globalThis[Symbol.for("brumate.render")];
362
+ }
363
+ /**
364
+ * The store of `$memo(expr)` at the top level of a module, and of `$gate`, `$debounced` and
365
+ * `$throttled` with `options`. It computes when it is read, and again when a source changes: while
366
+ * it has subscribers, at once, and otherwise at the next read, which compares the sources. A
367
+ * promise or an async iterable loads: a read gives the last value, and `p` the load, and only the
368
+ * latest run is written. A throw or a rejection is held until the memo computes again; on the
369
+ * server only for the renders that read that run. A memo that reads one with no value yet waits for
370
+ * it.
371
+ */
372
+ function memoStore(sources, fn, options) {
373
+ const single = !Array.isArray(sources);
374
+ const list = single ? [sources] : sources;
375
+ let level = 1;
376
+ for (const source of list) level = Math.max(level, (source.d ?? 0) + 1);
377
+ /** The value, which the listeners of the module hear. */
378
+ const out = new Store(void 0);
379
+ /** What the memos of importers follow: the value, or an object that is new for each change. */
380
+ const face = new Store(void 0);
381
+ const pend = { q: /* @__PURE__ */ new Set() };
382
+ /** True when the latest run loaded, or waited for a memo that loads. */
383
+ let loaded = false;
384
+ /** On the server: the renders that read the latest run, which share its error. */
385
+ let readers;
386
+ /** On the server: the error of a run that failed, for each render that read it. */
387
+ const failed = /* @__PURE__ */ new WeakMap();
388
+ /** On the server: the promise of a value that loaded, which the page state sends. */
389
+ let sent;
390
+ let timer;
391
+ /** When the last throttled value was taken. */
392
+ let last = -Infinity;
393
+ let has = false;
394
+ let held;
395
+ /** Changes with each value or error. */
396
+ let token = {};
397
+ /** What the sources were at the last run: their values, or the tokens of memos. */
398
+ let seen;
399
+ /** The number of the latest run, so a load that a newer run replaced is dropped. */
400
+ let run = 0;
401
+ /** The run whose own load is out, or 0. */
402
+ let loading = 0;
403
+ /** While the memo loads: the promise that its readers wait for. */
404
+ let wait;
405
+ let stopStream;
406
+ /** The subscribers of the value and of the sources. */
407
+ let count = 0;
408
+ let stops = [];
409
+ /** What the sources are now: a memo gives its token, brought up to date unless `raw`. */
410
+ const marks = (raw) => {
411
+ const values = [];
412
+ for (const source of list) values.push(isMemoStore(source) ? source.t(raw) : peekStore(source));
413
+ return values;
414
+ };
415
+ const changed = (raw) => {
416
+ if (!seen) return true;
417
+ const now = marks(raw);
418
+ for (const [index, value] of now.entries()) if (!Object.is(value, seen[index])) return true;
419
+ return false;
420
+ };
421
+ /** True while a source loads, such as a debounced value that waits. */
422
+ const sourcesPending = () => {
423
+ for (const source of list) if (pendingOf(source)?.n) return true;
424
+ return false;
425
+ };
426
+ /** What a component that imports the memo reads now. In the browser it is new for a load. */
427
+ const show = () => {
428
+ if (held) throw held.error;
429
+ return wait ? face.v : out.v;
430
+ };
431
+ /** The values of the sources by name, through the memos that it reads, without computing. */
432
+ const record = () => {
433
+ const values = {};
434
+ for (const [index, source] of list.entries()) values[options?.n?.[index] ?? String(index)] = isMemoStore(source) ? source.r() : peekStore(source);
435
+ return values;
436
+ };
437
+ /**
438
+ * The memos of importers compute again. The reader of the slot reads `show` again, as for any
439
+ * store that holds an error, so what goes out is a notice only.
440
+ */
441
+ const bump = () => {
442
+ if (wait) face.v = {};
443
+ if (face.l.size > 0) sendStore(face, face.v, true);
444
+ };
445
+ /** The memo loads: its readers get a promise, and it is pending. */
446
+ const enter = () => {
447
+ if (wait) return;
448
+ let resolve;
449
+ let reject;
450
+ const promise = new Promise((done, fail) => {
451
+ resolve = done;
452
+ reject = fail;
453
+ });
454
+ promise.catch(() => {});
455
+ wait = {
456
+ promise,
457
+ resolve,
458
+ reject
459
+ };
460
+ setPending(pend, true);
461
+ bump();
462
+ };
463
+ /** The load ends: the readers that wait get the value or the error. */
464
+ const release = () => {
465
+ if (!wait || loading !== 0 || sourcesPending()) return;
466
+ if (!has && !held) {
467
+ compute();
468
+ return;
469
+ }
470
+ const done = wait;
471
+ wait = void 0;
472
+ setPending(pend, false);
473
+ if (held) done.reject(held.error);
474
+ else done.resolve(out.v);
475
+ };
476
+ /** Writes the value or the error of a run, unless a newer run replaced it. */
477
+ const finish = (id, value, failure) => {
478
+ if (id !== run) return;
479
+ loading = 0;
480
+ const had = held;
481
+ const before = out.v;
482
+ const first = !has;
483
+ held = failure;
484
+ sent = void 0;
485
+ if (failure) for (const render of readers ?? []) failed.set(render, failure);
486
+ readers = void 0;
487
+ if (!failure) {
488
+ has = true;
489
+ out.v = value;
490
+ }
491
+ const news = !!failure || !!had || first || !Object.is(before, out.v);
492
+ if (news) token = {};
493
+ if (wait) release();
494
+ else if (news) bump();
495
+ if (news) sendStore(out, out.v, true);
496
+ };
497
+ /** Reads a stream: each value is the value, and the first one ends the load. */
498
+ const read = (id, stream, server) => {
499
+ const iterator = stream[Symbol.asyncIterator]();
500
+ stopStream = () => {
501
+ iterator.return?.();
502
+ };
503
+ const step = () => {
504
+ iterator.next().then((result) => {
505
+ if (id !== run) return;
506
+ if (result.done) {
507
+ stopStream = void 0;
508
+ if (loading === id) finish(id, void 0);
509
+ return;
510
+ }
511
+ finish(id, result.value);
512
+ if (server) {
513
+ stopStream?.();
514
+ stopStream = void 0;
515
+ return;
516
+ }
517
+ step();
518
+ }, (error) => finish(id, void 0, { error }));
519
+ };
520
+ step();
521
+ };
522
+ /** Runs the function over the values of the sources, for the run `id`. */
523
+ const evaluate = (id) => {
524
+ let result;
525
+ loaded = false;
526
+ try {
527
+ seen = marks();
528
+ const values = [];
529
+ for (const source of list) values.push(source.get());
530
+ result = fn(single ? values[0] : values);
531
+ } catch (error) {
532
+ if (error instanceof Waiting) {
533
+ loaded = true;
534
+ loading = id;
535
+ enter();
536
+ const again = () => {
537
+ if (id === run) {
538
+ loading = 0;
539
+ evaluate(id);
540
+ }
541
+ };
542
+ error.load.then(again, again);
543
+ return;
544
+ }
545
+ finish(id, void 0, { error });
546
+ return;
547
+ }
548
+ const guard = options?.g;
549
+ if (guard) {
550
+ if (loads(result)) {
551
+ finish(id, void 0, { error: /* @__PURE__ */ new TypeError("The value of $gate is a promise or a stream. Use $memo for a value that loads") });
552
+ return;
553
+ }
554
+ if (count > 0 && has && !held) try {
555
+ if (!guard(out.v, result)) result = out.v;
556
+ } catch (error) {
557
+ finish(id, void 0, { error });
558
+ return;
559
+ }
560
+ }
561
+ if (!loads(result)) {
562
+ finish(id, result);
563
+ return;
564
+ }
565
+ loaded = true;
566
+ loading = id;
567
+ enter();
568
+ const server = onServer();
569
+ Promise.resolve(result).then((value) => {
570
+ if (id !== run) return;
571
+ if (loads(value)) read(id, value, server);
572
+ else finish(id, value);
573
+ }, (error) => finish(id, void 0, { error }));
574
+ };
575
+ /** Fires the wait of a debounced or throttled value: the latest run takes the value. */
576
+ const fire = () => {
577
+ timer = void 0;
578
+ last = Date.now();
579
+ loading = 0;
580
+ evaluate(run);
581
+ };
582
+ /**
583
+ * Starts a run. A debounced or throttled value that a subscriber holds in the browser waits:
584
+ * it takes the value after `m` once the sources stop changing, or at most once every `m`.
585
+ */
586
+ const compute = () => {
587
+ const id = ++run;
588
+ stopStream?.();
589
+ stopStream = void 0;
590
+ loading = 0;
591
+ readers = void 0;
592
+ const ms = options?.m;
593
+ if (ms === void 0 || count === 0 || onServer()) {
594
+ evaluate(id);
595
+ return;
596
+ }
597
+ const since = Date.now() - last;
598
+ if (options.t && timer === void 0 && since >= ms) {
599
+ last = Date.now();
600
+ evaluate(id);
601
+ return;
602
+ }
603
+ if (!options.t) {
604
+ clearTimeout(timer);
605
+ timer = void 0;
606
+ }
607
+ loading = id;
608
+ enter();
609
+ timer ??= setTimeout(fire, options.t ? ms - since : ms);
610
+ };
611
+ /**
612
+ * Computes when the memo has no value, or, with no subscriber, when a source changed. With
613
+ * `retry`, on the server, a held error is read again only by the renders that read its run: a
614
+ * later render loads again.
615
+ */
616
+ const ensure = (retry) => {
617
+ if (!has && !held && !wait) compute();
618
+ else if (count === 0 && changed()) compute();
619
+ else if (retry && held && !wait) {
620
+ const render = currentRender();
621
+ if (render && !failed.has(render)) compute();
622
+ }
623
+ };
624
+ /**
625
+ * Notes the render of the server that reads the latest run: while it loads, so its error goes to
626
+ * the render, and once it failed, as the render's own error. Returns the error that the render
627
+ * read before, which it keeps, though a later render loaded again. A render that reads a value
628
+ * is not kept.
629
+ */
630
+ const note = () => {
631
+ const render = currentRender();
632
+ if (!render) return;
633
+ const kept = failed.get(render);
634
+ if (kept) return kept;
635
+ if (wait) (readers ??= /* @__PURE__ */ new Set()).add(render);
636
+ else if (held) failed.set(render, held);
637
+ };
638
+ const state = {
639
+ level,
640
+ waits: false,
641
+ run() {
642
+ if (count > 0 && changed()) compute();
643
+ }
644
+ };
645
+ /** A subscriber starts to follow the sources; the last one to leave stops it. */
646
+ const follow = () => {
647
+ if (count++ === 0) {
648
+ for (const source of list) {
649
+ const heard = () => enqueue(state, source);
650
+ stops.push(isMemoStore(source) ? source.f(heard) : source.subscribe(heard));
651
+ const q = pendingOf(source)?.q;
652
+ if (q) {
653
+ const check = () => {
654
+ if (sourcesPending()) enter();
655
+ else release();
656
+ };
657
+ q.add(check);
658
+ stops.push(() => q.delete(check));
659
+ }
660
+ }
661
+ if (sourcesPending()) enter();
662
+ if (seen && changed(true)) compute();
663
+ }
664
+ let done = false;
665
+ return () => {
666
+ if (!done) {
667
+ done = true;
668
+ if (--count === 0) {
669
+ for (const end of stops) end();
670
+ stops = [];
671
+ if (timer !== void 0) {
672
+ clearTimeout(timer);
673
+ fire();
674
+ }
675
+ }
676
+ }
677
+ };
678
+ };
679
+ /** A subscription of `target`, which also follows the sources. */
680
+ const listen = (target, listener) => {
681
+ const off = target.subscribe(listener);
682
+ const unfollow = follow();
683
+ return () => {
684
+ off();
685
+ unfollow();
686
+ };
687
+ };
688
+ const memo = {
689
+ get() {
690
+ ensure();
691
+ if (held) throw held.error;
692
+ if (has) return out.v;
693
+ throw new Waiting(wait.promise);
694
+ },
695
+ subscribe(listener) {
696
+ ensure();
697
+ return listen(out, listener);
698
+ },
699
+ p() {
700
+ ensure(true);
701
+ const kept = note();
702
+ if (kept) throw kept.error;
703
+ if (wait) return wait.promise;
704
+ if (held) throw held.error;
705
+ return out.v;
706
+ },
707
+ f(listener) {
708
+ return listen(out, listener);
709
+ },
710
+ t(raw) {
711
+ if (!raw) ensure();
712
+ return token;
713
+ },
714
+ a() {
715
+ if (loaded) return true;
716
+ for (const source of list) if (isMemoStore(source) && source.a()) return true;
717
+ return false;
718
+ },
719
+ r: record,
720
+ h: () => readers?.size ?? 0,
721
+ i: {
722
+ get() {
723
+ if (count > 0) return show();
724
+ ensure(true);
725
+ if (note() || held && !wait) return;
726
+ if (!wait && !memo.a()) return typeof out.v === "object" && out.v !== null ? out.v : { [FACE]: 0 };
727
+ const promise = (wait ? wait.promise : sent ??= Promise.resolve(out.v)).catch(() => {
728
+ throw new Error("The page could not compute a value");
729
+ });
730
+ return {
731
+ [FACE]: promise,
732
+ s: record()
733
+ };
734
+ },
735
+ subscribe(listener) {
736
+ return listen(face, listener);
737
+ },
738
+ s(value) {
739
+ if (has || held || wait || seen || value === void 0) return;
740
+ if (!isLoadedFace(value)) {
741
+ compute();
742
+ return;
743
+ }
744
+ const promise = value[FACE];
745
+ if (!sameSource(value.s, record())) {
746
+ compute();
747
+ return;
748
+ }
749
+ const id = ++run;
750
+ loaded = true;
751
+ loading = id;
752
+ enter();
753
+ face.v = value;
754
+ seen = marks(true);
755
+ promise.then((settled) => finish(id, settled), (error) => finish(id, void 0, { error }));
756
+ },
757
+ [HOLDS]: true
758
+ },
759
+ l: out.l,
760
+ d: level,
761
+ [PENDING]: pend,
762
+ [HOLDS]: true
763
+ };
764
+ return memo;
765
+ }
766
+ const BRIDGES = Symbol.for("brumate.bridges");
767
+ const BRIDGE_LOAD = Symbol.for("brumate.bridge-load");
768
+ /** The bridges by name, which any copy of the runtime shares. */
769
+ function bridges() {
770
+ return globalThis[BRIDGES] ??= /* @__PURE__ */ new Map();
771
+ }
772
+ /**
773
+ * Sets how the browser loads the module of a bridge, and where a failed load is reported. The
774
+ * core calls it when it starts.
775
+ */
776
+ function setBridgeLoader(...loader) {
777
+ globalThis[BRIDGE_LOAD] = loader;
778
+ }
779
+ /** The module of a bridge, from its name. */
780
+ function bridgeModule(id) {
781
+ return id.slice(0, id.lastIndexOf("#"));
782
+ }
783
+ /**
784
+ * Makes a bridge. Keep its value in a module-level export, so the page state can name it:
785
+ * `export const bears = bridge({ … })`. The compiler gives it its name.
786
+ */
787
+ function bridge(options) {
788
+ const made = Object.assign((snapshot) => new Bridged(made, options.create(snapshot)), { b: options });
789
+ return made;
790
+ }
791
+ /** Gives a bridge its name, which the compiler writes at the end of its module. */
792
+ function nameBridge(made, id) {
793
+ made.i = id;
794
+ bridges().set(id, made);
795
+ }
796
+ /** True for a store of `bridge()`, of any copy of the runtime. */
797
+ function isBridged(value) {
798
+ return typeof value === "object" && value !== null && value.k === "brumate.bridge";
799
+ }
800
+ /**
801
+ * Whether two values hold the same data: the same value, or arrays and plain objects whose items
802
+ * hold the same data. A store that the browser makes again holds a new object with the content
803
+ * the server sent, which needs no repair.
804
+ */
805
+ function sameData(a, b, open) {
806
+ if (Object.is(a, b)) return true;
807
+ const array = Array.isArray(a);
808
+ if (array ? !Array.isArray(b) || a.length !== b.length : !isPlain(a) || !isPlain(b)) return false;
809
+ const left = a;
810
+ const right = b;
811
+ open ??= /* @__PURE__ */ new Map();
812
+ let pairs = open.get(left);
813
+ if (pairs?.has(right)) return true;
814
+ if (!pairs) {
815
+ pairs = /* @__PURE__ */ new Set();
816
+ open.set(left, pairs);
817
+ }
818
+ pairs.add(right);
819
+ const keys = Object.keys(left);
820
+ if (!array && keys.length !== Object.keys(right).length) return false;
821
+ for (const key of keys) if (!(key in right) || !sameData(left[key], right[key], open)) return false;
822
+ return true;
823
+ }
824
+ /** Whether a value is an object of `Object` or of no prototype, as page state holds. */
825
+ function isPlain(value) {
826
+ if (typeof value !== "object" || value === null) return false;
827
+ const proto = Object.getPrototypeOf(value);
828
+ return proto === Object.prototype || proto === null;
829
+ }
830
+ /**
831
+ * The store that a bridge makes. On the server it holds the library's store from the start. In
832
+ * the browser the page state makes it with the name of the bridge and the data of the server, and
833
+ * it makes the library's store at its first subscriber.
834
+ */
835
+ var Bridged = class {
836
+ /** The mark of a bridged store, which `isBridged` reads in every copy of the runtime. */
837
+ k = "brumate.bridge";
838
+ /** The bridge. Undefined for a store of the page state until the module of the bridge loads. */
839
+ f;
840
+ /** The name of the bridge, for a store of the page state. */
841
+ i;
842
+ /** The library's store. */
843
+ s;
844
+ /** True once the library's store exists. */
845
+ m = false;
846
+ /** The data that the server sent, until the library's store exists. */
847
+ v;
848
+ /** Whether the bridge has `set`, as the server sent it, until the module loads. */
849
+ w;
850
+ constructor(made, source, id, snapshot, writable) {
851
+ this.f = made;
852
+ this.i = id;
853
+ this.v = snapshot;
854
+ this.w = writable;
855
+ if (made) {
856
+ this.s = source;
857
+ this.m = true;
858
+ }
859
+ }
860
+ /**
861
+ * The library's store. In the browser it is undefined until the store has a subscriber and the
862
+ * module of the bridge has loaded.
863
+ */
864
+ get source() {
865
+ return this.s;
866
+ }
867
+ /** The name of the bridge. */
868
+ get id() {
869
+ return this.f?.i ?? this.i;
870
+ }
871
+ /** The data of the store: what `get` reads, or what the server sent before the first subscriber. */
872
+ get() {
873
+ return this.m ? this.f.b.get(this.s) : this.v;
874
+ }
875
+ /**
876
+ * Calls `listener` with the data when it changes. The first subscriber makes the library's
877
+ * store in the browser. When the module of the bridge has not loaded, the subscription starts
878
+ * when it has.
879
+ */
880
+ subscribe(listener, ...seen) {
881
+ let stopped = false;
882
+ let stop;
883
+ let last = seen.length > 0 ? seen[0] : this.get();
884
+ const start = () => {
885
+ if (stopped) return;
886
+ const options = this.f.b;
887
+ const source = this.make();
888
+ stop = options.subscribe(source, () => {
889
+ const next = options.get(source);
890
+ if (!sameData(next, last)) {
891
+ last = next;
892
+ listener(next);
893
+ }
894
+ });
895
+ const first = options.get(source);
896
+ if (!sameData(first, last)) {
897
+ last = first;
898
+ listener(first);
899
+ }
900
+ };
901
+ if (this.find()) start();
902
+ else this.load().then((loaded) => loaded && start());
903
+ return () => {
904
+ stopped = true;
905
+ stop?.();
906
+ };
907
+ }
908
+ /** Writes the library's store, when the bridge has `set`. */
909
+ get set() {
910
+ return (this.find() ? !!this.f.b.set : this.w !== false) ? (value) => this.write(value) : void 0;
911
+ }
912
+ /** Writes the library's store, after the module of the bridge has loaded. */
913
+ write(value) {
914
+ if (this.find()) this.f.b.set(this.make(), value);
915
+ else this.load().then((loaded) => loaded && this.write(value));
916
+ }
917
+ /** The bridge, once its module has loaded. */
918
+ find() {
919
+ if (!this.f && this.i !== void 0) this.f = bridges().get(this.i);
920
+ return this.f;
921
+ }
922
+ /** Loads the module of the bridge. A failure goes to the core's error path; it gives false. */
923
+ load() {
924
+ const [load, report] = globalThis[BRIDGE_LOAD] ?? [];
925
+ return Promise.resolve(load?.(bridgeModule(this.i))).then(() => {
926
+ if (this.find()) return true;
927
+ this.fail(report, /* @__PURE__ */ new Error(`The bridge "${this.i}" is not in its module. Keep bridge() in a module-level export, as "export const name = bridge({ … })"`));
928
+ return false;
929
+ }, (error) => {
930
+ this.fail(report, error);
931
+ return false;
932
+ });
933
+ }
934
+ fail(report, error) {
935
+ if (report) report(error);
936
+ else console.error(error);
937
+ }
938
+ /** Makes the library's store once, with the data of the server. */
939
+ make() {
940
+ if (!this.m) {
941
+ this.s = this.f.b.create(this.v);
942
+ this.m = true;
943
+ }
944
+ return this.s;
945
+ }
946
+ };
947
+ //#endregion
948
+ export { store as C, setBridgeLoader as S, onServer as _, Waiting as a, sendStore as b, derived as c, isContext as d, isContract as f, nameBridge as g, memoStore as h, Store as i, findStored as l, isStore as m, HOLDS as n, bridge as o, isForeignStore as p, PENDING as r, canSet as s, Bridged as t, isBridged as u, pendingOf as v, sentForeignStore as x, sameData as y };
949
+
950
+ //# sourceMappingURL=store-DNr24Z8L.js.map