brumate 0.7.1 → 0.8.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 (93) hide show
  1. package/dist/{boot-CMy0f_iC.d.ts → boot-BkUdiYOF.d.ts} +2 -2
  2. package/dist/cli.js +3 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{client-Bm0XbjHr.js → client-B0FXW5Kw.js} +50 -15
  5. package/dist/client-B0FXW5Kw.js.map +1 -0
  6. package/dist/{client-DnFF9_lv.d.ts → client-Cq6aTiDs.d.ts} +15 -7
  7. package/dist/{defer-BWwxv7Qf.js → defer-BMIMP4Hq.js} +3 -3
  8. package/dist/{defer-BWwxv7Qf.js.map → defer-BMIMP4Hq.js.map} +1 -1
  9. package/dist/{devtools-Cl6AhENB.js → devtools-B4prrxht.js} +258 -118
  10. package/dist/devtools-B4prrxht.js.map +1 -0
  11. package/dist/devtools-calls-DGW6nLZ2.js +249 -0
  12. package/dist/devtools-calls-DGW6nLZ2.js.map +1 -0
  13. package/dist/devtools-panel-B1nF1KB7.js +3978 -0
  14. package/dist/devtools-panel-B1nF1KB7.js.map +1 -0
  15. package/dist/error-catalog-DakxjSgj.js +308 -0
  16. package/dist/error-catalog-DakxjSgj.js.map +1 -0
  17. package/dist/error-catalog-VxLbz-6p.js +1 -0
  18. package/dist/{files-BuQvpBwF.js → files-D5GtxwEQ.js} +2 -2
  19. package/dist/{files-BuQvpBwF.js.map → files-D5GtxwEQ.js.map} +1 -1
  20. package/dist/index.d.ts +73 -18
  21. package/dist/index.js +11 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/{inspect-BSHv1_25.js → inspect-CGl5Y8q6.js} +581 -399
  24. package/dist/inspect-CGl5Y8q6.js.map +1 -0
  25. package/dist/{loader-BPNSRA2A.js → loader-BsaSuIoG.js} +4 -4
  26. package/dist/{loader-BPNSRA2A.js.map → loader-BsaSuIoG.js.map} +1 -1
  27. package/dist/{navigate-r23FFR6e.js → navigate-BlowKvhB.js} +18 -10
  28. package/dist/navigate-BlowKvhB.js.map +1 -0
  29. package/dist/{rpc-DqfCaYgF.js → rpc-C1jYVNAe.js} +5 -4
  30. package/dist/rpc-C1jYVNAe.js.map +1 -0
  31. package/dist/runtime/bundles.d.ts +1 -1
  32. package/dist/runtime/client.d.ts +2 -2
  33. package/dist/runtime/client.js +4 -3
  34. package/dist/runtime/devtools.d.ts +59 -1
  35. package/dist/runtime/devtools.js +1 -1
  36. package/dist/runtime/hot.d.ts +1 -1
  37. package/dist/runtime/hot.js +6 -2
  38. package/dist/runtime/hot.js.map +1 -1
  39. package/dist/runtime/loader.d.ts +2 -2
  40. package/dist/runtime/loader.js +2 -2
  41. package/dist/runtime/server.d.ts +1 -1
  42. package/dist/runtime/server.js +3 -2
  43. package/dist/runtime/signals.d.ts +1 -1
  44. package/dist/runtime/static-loader.d.ts +2 -2
  45. package/dist/runtime/static-loader.js +1 -1
  46. package/dist/runtime/store.d.ts +2 -2
  47. package/dist/runtime/store.js +1 -1
  48. package/dist/runtime/testing.d.ts +2 -2
  49. package/dist/runtime/testing.js +2 -2
  50. package/dist/search-params-Wg-0FsMj.js +148 -0
  51. package/dist/search-params-Wg-0FsMj.js.map +1 -0
  52. package/dist/{stream-RXLadXx1.js → serial-ioa17MuY.js} +67 -168
  53. package/dist/serial-ioa17MuY.js.map +1 -0
  54. package/dist/serial-ribg9NAj.js +1 -0
  55. package/dist/{server-BVObWh-w.js → server-BUuf7XPZ.js} +61 -16
  56. package/dist/server-BUuf7XPZ.js.map +1 -0
  57. package/dist/{server-0rS5vUW1.d.ts → server-DesBZv5g.d.ts} +8 -3
  58. package/dist/{search-params-C64liRBj.js → shared-CX_YacDm.js} +3 -148
  59. package/dist/shared-CX_YacDm.js.map +1 -0
  60. package/dist/{signals-DBnq9QRW.d.ts → signals-7VVD9C_H.d.ts} +2 -2
  61. package/dist/skew-CwmX_GFI.js +21 -0
  62. package/dist/skew-CwmX_GFI.js.map +1 -0
  63. package/dist/{static-loader-V4V1Oy6G.js → static-loader-C_en-4v8.js} +2 -2
  64. package/dist/{static-loader-V4V1Oy6G.js.map → static-loader-C_en-4v8.js.map} +1 -1
  65. package/dist/{static-loader-BYbXVJDY.d.ts → static-loader-UKnK11Em.d.ts} +2 -2
  66. package/dist/{store-xlTzAM_r.d.ts → store-9_oa0HG1.d.ts} +15 -2
  67. package/dist/{store-BIBAYZo-.js → store-Cy4EEyZ7.js} +148 -2
  68. package/dist/store-Cy4EEyZ7.js.map +1 -0
  69. package/dist/stream-read-BTsYstJY.js +22 -0
  70. package/dist/stream-read-BTsYstJY.js.map +1 -0
  71. package/dist/stream-read-Dek3HnqO.js +1 -0
  72. package/dist/{skew-FRmAy9iy.js → trusted-g_zUJbh2.js} +11 -22
  73. package/dist/trusted-g_zUJbh2.js.map +1 -0
  74. package/dist/vite.d.ts +1 -1
  75. package/dist/vite.js +37 -5
  76. package/dist/vite.js.map +1 -1
  77. package/package.json +7 -4
  78. package/skills/brumate/SKILL.md +6 -2
  79. package/skills/brumate/references/errors.md +21 -2
  80. package/skills/brumate/references/state.md +31 -0
  81. package/skills/brumate/references/syntax.md +45 -1
  82. package/dist/client-Bm0XbjHr.js.map +0 -1
  83. package/dist/devtools-Cl6AhENB.js.map +0 -1
  84. package/dist/devtools-panel-DLIeWcAj.js +0 -2017
  85. package/dist/devtools-panel-DLIeWcAj.js.map +0 -1
  86. package/dist/inspect-BSHv1_25.js.map +0 -1
  87. package/dist/navigate-r23FFR6e.js.map +0 -1
  88. package/dist/rpc-DqfCaYgF.js.map +0 -1
  89. package/dist/search-params-C64liRBj.js.map +0 -1
  90. package/dist/server-BVObWh-w.js.map +0 -1
  91. package/dist/skew-FRmAy9iy.js.map +0 -1
  92. package/dist/store-BIBAYZo-.js.map +0 -1
  93. package/dist/stream-RXLadXx1.js.map +0 -1
@@ -106,6 +106,152 @@ function sendStore(target, value, force) {
106
106
  if (pass) pass(listeners);
107
107
  else listeners();
108
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
+ function derived(sources, fn, initial) {
135
+ const single = !Array.isArray(sources);
136
+ const list = single ? [sources] : sources;
137
+ for (const source of list) if (!source) throw new Error("derived() expects stores as input, got a falsy value");
138
+ const auto = fn.length < 2;
139
+ const out = new Store(initial);
140
+ const subscribers = /* @__PURE__ */ new Set();
141
+ let level = 1;
142
+ for (const source of list) level = Math.max(level, (source.d ?? 0) + 1);
143
+ let cleanup;
144
+ let started = false;
145
+ let starting = false;
146
+ let stops = [];
147
+ /** Runs `fn` over the current values of the sources. */
148
+ const compute = (write) => {
149
+ const values = [];
150
+ for (const source of list) values.push(source.get());
151
+ const set = write;
152
+ const update = (change) => write(change(out.v));
153
+ cleanup?.();
154
+ cleanup = void 0;
155
+ const result = fn(single ? values[0] : values, set, update);
156
+ if (auto) write(result);
157
+ else if (typeof result === "function") cleanup = result;
158
+ };
159
+ const send = (value) => {
160
+ if (starting) out.v = value;
161
+ else if (started) sendStore(out, value);
162
+ else out.v = value;
163
+ };
164
+ const state = {
165
+ level,
166
+ waits: false,
167
+ run() {
168
+ if (started) compute(send);
169
+ }
170
+ };
171
+ /**
172
+ * Called by a source. The store waits until the source has called all its listeners, so a store
173
+ * that reads this one and the source computes once, after this one.
174
+ */
175
+ const heard = (source) => {
176
+ if (!started || state.waits) return;
177
+ state.waits = true;
178
+ waiting.push(state);
179
+ if (flushing) return;
180
+ const listeners = source.l;
181
+ if (!listeners || armed.has(listeners)) {
182
+ if (!listeners) flushComputed();
183
+ return;
184
+ }
185
+ const trail = () => {
186
+ listeners.delete(trail);
187
+ armed.delete(listeners);
188
+ flushComputed();
189
+ };
190
+ armed.add(listeners);
191
+ listeners.add(trail);
192
+ };
193
+ const start = () => {
194
+ starting = true;
195
+ started = true;
196
+ try {
197
+ compute(send);
198
+ for (const source of list) stops.push(source.subscribe(() => heard(source)));
199
+ } catch (error) {
200
+ started = false;
201
+ for (const end of stops) end();
202
+ stops = [];
203
+ cleanup?.();
204
+ cleanup = void 0;
205
+ throw error;
206
+ } finally {
207
+ starting = false;
208
+ }
209
+ };
210
+ const stop = () => {
211
+ started = false;
212
+ for (const end of stops) end();
213
+ stops = [];
214
+ cleanup?.();
215
+ cleanup = void 0;
216
+ if (state.waits) {
217
+ state.waits = false;
218
+ waiting.splice(waiting.indexOf(state), 1);
219
+ }
220
+ };
221
+ return Object.assign({
222
+ get() {
223
+ if (started) return out.v;
224
+ let value = out.v;
225
+ started = true;
226
+ try {
227
+ compute((next) => {
228
+ value = next;
229
+ });
230
+ } finally {
231
+ started = false;
232
+ cleanup?.();
233
+ cleanup = void 0;
234
+ }
235
+ return value;
236
+ },
237
+ subscribe(listener) {
238
+ const stopListening = out.subscribe(listener);
239
+ if (!started) try {
240
+ start();
241
+ } catch (error) {
242
+ stopListening();
243
+ throw error;
244
+ }
245
+ subscribers.add(stopListening);
246
+ return () => {
247
+ if (subscribers.delete(stopListening)) {
248
+ stopListening();
249
+ if (subscribers.size === 0) stop();
250
+ }
251
+ };
252
+ }
253
+ }, { d: level });
254
+ }
109
255
  const BRIDGES = Symbol.for("brumate.bridges");
110
256
  const BRIDGE_LOAD = Symbol.for("brumate.bridge-load");
111
257
  /** The bridges by name, which any copy of the runtime shares. */
@@ -288,6 +434,6 @@ var Bridged = class {
288
434
  }
289
435
  };
290
436
  //#endregion
291
- export { findStored as a, isContract as c, nameBridge as d, sameData as f, store as g, setBridgeLoader as h, canSet as i, isForeignStore as l, sentForeignStore as m, Store as n, isBridged as o, sendStore as p, bridge as r, isContext as s, Bridged as t, isStore as u };
437
+ export { store as _, derived as a, isContext as c, isStore as d, nameBridge as f, setBridgeLoader as g, sentForeignStore as h, canSet as i, isContract as l, sendStore as m, Store as n, findStored as o, sameData as p, bridge as r, isBridged as s, Bridged as t, isForeignStore as u };
292
438
 
293
- //# sourceMappingURL=store-BIBAYZo-.js.map
439
+ //# sourceMappingURL=store-Cy4EEyZ7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-Cy4EEyZ7.js","names":[],"sources":["../src/runtime/store.ts"],"sourcesContent":["// Stores: values that change, which a context can hold while the context itself stays the same.\n// `$toStore` makes the store of a provider, and `$store` reads one in a component. The page state\n// sends only the value of a store; the browser makes a new store for it.\n\nimport type { Context } from './context.ts';\nimport { HAS_BRIDGES } from './features.ts';\n\n/** The pass of the core, which the browser sets, so a store's readers update in one pass. */\nconst PASS = Symbol.for('brumate.pass');\n\n/** True for a context, which `createContext` made. */\nexport function isContext(value: unknown): value is Context<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { key?: unknown }).key === 'string' &&\n Object.keys(value).length === 1 &&\n !isContract(value)\n );\n}\n\n/**\n * The store that `$store` reads: `value` is the store, or for `path` an object that holds it there.\n * `key` names the context that gave `value`, for the message. Throws a `TypeError` for a value that\n * is no store, such as `undefined` or a context, and for `write` on a store that has no `set`.\n */\nexport function findStored(\n value: unknown,\n path: string | undefined,\n write: boolean | undefined,\n key?: string,\n): StoreLike<unknown> {\n const found = path === undefined ? value : (value as Record<string, unknown> | undefined)?.[path];\n if (!isContract(found)) {\n // A context is the most likely mistake, so its message names the read that gives its store.\n if (isContext(found)) {\n throw new TypeError(\n `$store reads the context \"${found.key}\", which is no store. Read the store in it with $store($getContext(Context))`,\n );\n }\n throw new TypeError(\n `$store reads ${key === undefined ? 'a value' : `the context \"${key}\"`}${path === undefined ? '' : ` at \"${path}\"`}, which gives no store: a store has the functions get and subscribe`,\n );\n }\n if (write && !canSet(found)) {\n throw new TypeError(\n `let $store(${key ?? '…'}) writes the store, but the store has no set. Read it with const`,\n );\n }\n return found;\n}\n\n/**\n * The error of `$store` for a store of another library in a value that the page sends, such as a\n * prop: only the value of a store of `brumate/store` crosses. The fix is said here only.\n */\nexport function sentForeignStore(component: string, value: string): Error {\n return new Error(\n `$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`,\n );\n}\n\n/** Where `$toStore` made a store: its scope, the ID of its site, and the slot of its signal. */\nexport type StoreOrigin = [scope: number | string, site: number, slot?: number];\n\n/**\n * The contract of a store, which `$store` reads: `get`, `subscribe` (which returns the function\n * that stops it, and does not call the listener at once) and, for a two-way binding, `set`.\n */\nexport interface StoreLike<T> {\n get(): T;\n subscribe(listener: (value: T) => void): () => void;\n set?(value: T): void;\n}\n\n/** A value that changes, with the functions that read it and write it. */\nexport class Store<T> implements StoreLike<T> {\n /** The value. */\n v: T;\n /** The functions that `subscribe` added. */\n l: Set<(value: T) => void> = new Set();\n /** For a store of `$toStore(signal)`, the write of the signal, which the browser sets. */\n w?: (value: T) => void;\n /** True for a store of `$toStore(memo)`, which only its provider writes. */\n r?: boolean;\n /** Where `$toStore` made it, for the page state. */\n o?: StoreOrigin;\n /** True for a store of `$toStore` in the browser until its first update. */\n f?: boolean;\n /**\n * The mark of a store, which `isStore` reads in every copy of the runtime. A field, so a build\n * without stores drops the class.\n */\n k = 'brumate.store' as const;\n\n constructor(value: T) {\n this.v = value;\n }\n\n /** The current value. */\n get(): T {\n return this.v;\n }\n\n /** Calls `listener` with each new value. Returns the function that stops it. */\n subscribe(listener: (value: T) => void): () => void {\n this.l.add(listener);\n return () => {\n this.l.delete(listener);\n };\n }\n\n /**\n * Writes the value, and calls the listeners when it changed. A store of `$toStore(signal)`\n * writes the signal, and a store of a memo throws.\n */\n set(value: T): void {\n if (this.r) {\n throw new Error('This store follows a memo, so only its provider writes it');\n }\n if (Object.is(this.v, value)) {\n return;\n }\n if (this.w) {\n this.v = value;\n this.w(value);\n return;\n }\n sendStore(this, value);\n }\n}\n\n/** True for a store of `brumate/store`, of any copy of the runtime. */\nexport function isStore(value: unknown): value is Store<unknown> {\n return (\n typeof value === 'object' && value !== null && (value as { k?: unknown }).k === 'brumate.store'\n );\n}\n\n/** True for a value with the functions `get` and `subscribe` of the store contract. */\nexport function isContract(value: unknown): value is StoreLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { get?: unknown }).get === 'function' &&\n typeof (value as { subscribe?: unknown }).subscribe === 'function'\n );\n}\n\n/** True for a value of the store contract that is not a store of brumate. */\nexport function isForeignStore(value: unknown): boolean {\n return isContract(value) && !isStore(value) && !(HAS_BRIDGES && isBridged(value));\n}\n\n/** True when `$store` can write the store: it has `set`, and is not the store of a memo. */\nexport function canSet(value: StoreLike<unknown>): boolean {\n return typeof value.set === 'function' && !(value as Store<unknown>).r;\n}\n\n/** Makes a store, such as one that a module holds for the whole app. */\nexport function store<T>(value: T): Store<T> {\n return new Store(value);\n}\n\n/** Writes the value of a store and calls its listeners, in one pass of the page. */\nexport function sendStore<T>(target: Store<T>, value: T, force?: boolean): void {\n // The listeners hear of a change only. A provider's update forces it, since a `set` of\n // `$toStore(signal)` wrote the value before the signal's update came.\n if (!force && Object.is(target.v, value)) {\n return;\n }\n target.v = value;\n const listeners = () => {\n for (const listener of target.l) {\n listener(value);\n }\n };\n const pass = (globalThis as { [key: symbol]: (<R>(run: () => R) => R) | undefined })[PASS];\n if (pass) {\n pass(listeners);\n } else {\n listeners();\n }\n}\n\n// Derived stores: a read-only store that computes its value from other stores, with the API of\n// Svelte 4's `derived`.\n\n/** The stores that `derived` reads: one store, or an array of them. */\nexport type Stores = StoreLike<any> | [StoreLike<any>, ...StoreLike<any>[]] | StoreLike<any>[];\n\n/** The values of `Stores`: a value for one store, an array of values for an array. */\nexport type StoresValues<S> =\n S extends StoreLike<infer U>\n ? U\n : { [K in keyof S]: S[K] extends StoreLike<infer U> ? U : never };\n\n/** The derived stores that heard of a change and wait to compute. */\nconst waiting: Computed[] = [];\n/** The listener sets that have a trailing listener, which computes the waiting stores. */\nconst armed = new Set<Set<unknown>>();\n/** True while the waiting stores compute. */\nlet flushing = false;\n\n/** Computes the waiting derived stores, the ones that read the fewest derived stores first. */\nfunction flushComputed(): void {\n flushing = true;\n try {\n while (waiting.length > 0) {\n let next = 0;\n for (let i = 1; i < waiting.length; i++) {\n if (waiting[i]!.level < waiting[next]!.level) {\n next = i;\n }\n }\n const [computed] = waiting.splice(next, 1);\n computed!.waits = false;\n computed!.run();\n }\n } catch (error) {\n // The stores that still wait would never hear a source again, so they leave the queue.\n for (const computed of waiting) {\n computed.waits = false;\n }\n waiting.length = 0;\n throw error;\n } finally {\n flushing = false;\n }\n}\n\n/** The state of a derived store while it has subscribers. */\ninterface Computed {\n /** The number of derived stores below it, so a store computes after the ones it reads. */\n level: number;\n /** True while it waits in the queue. */\n waits: boolean;\n run(): void;\n}\n\n/**\n * A store computed from `sources`. With a function of one parameter, the result is the value. With\n * two or three, the function calls `set` or `update`, and a function it returns runs before the\n * next call and when the last subscriber leaves. It follows its sources only while it has\n * subscribers; `get` computes from the sources otherwise. A source change that reaches it in one\n * pass computes it once, after the stores it reads.\n */\nexport function derived<S extends Stores, T>(\n sources: S,\n fn: (\n values: StoresValues<S>,\n set: (value: T) => void,\n update: (change: (value: T) => T) => void,\n ) => (() => void) | void,\n initial?: T,\n): StoreLike<T>;\nexport function derived<S extends Stores, T>(\n sources: S,\n fn: (values: StoresValues<S>) => T,\n initial?: T,\n): StoreLike<T>;\nexport function derived<T>(\n sources: Stores,\n fn: (\n values: unknown,\n set: (value: T) => void,\n update: (change: (value: T) => T) => void,\n ) => unknown,\n initial?: T,\n): StoreLike<T> {\n const single = !Array.isArray(sources);\n const list: StoreLike<unknown>[] = single ? [sources] : sources;\n for (const source of list) {\n if (!source) {\n throw new Error('derived() expects stores as input, got a falsy value');\n }\n }\n const auto = fn.length < 2;\n const out = new Store<T>(initial as T);\n const subscribers = new Set<() => void>();\n let level = 1;\n for (const source of list) {\n level = Math.max(level, ((source as { d?: number }).d ?? 0) + 1);\n }\n\n // The state of one run: `cleanup` is what `fn` returned, and `write` is where `set` goes.\n let cleanup: (() => void) | undefined;\n let started = false;\n let starting = false;\n let stops: (() => void)[] = [];\n\n /** Runs `fn` over the current values of the sources. */\n const compute = (write: (value: T) => void): void => {\n const values: unknown[] = [];\n for (const source of list) {\n values.push(source.get());\n }\n const set = write;\n const update = (change: (value: T) => T): void => write(change(out.v));\n cleanup?.();\n cleanup = undefined;\n const result = fn(single ? values[0] : values, set, update);\n if (auto) {\n write(result as T);\n } else if (typeof result === 'function') {\n cleanup = result as () => void;\n }\n };\n\n // The value is written without a notice while the first subscriber starts it, since nobody\n // listens yet and `subscribe` does not call the listener.\n const send = (value: T): void => {\n if (starting) {\n out.v = value;\n } else if (started) {\n sendStore(out, value);\n } else {\n // A late `set` after the last subscriber left keeps its value, as Svelte's store does.\n out.v = value;\n }\n };\n\n const state: Computed = {\n level,\n waits: false,\n run() {\n if (started) {\n compute(send);\n }\n },\n };\n\n /**\n * Called by a source. The store waits until the source has called all its listeners, so a store\n * that reads this one and the source computes once, after this one.\n */\n const heard = (source: StoreLike<unknown>): void => {\n if (!started || state.waits) {\n return;\n }\n state.waits = true;\n waiting.push(state);\n if (flushing) {\n return;\n }\n const listeners = (source as Partial<Store<unknown>>).l;\n if (!listeners || armed.has(listeners)) {\n if (!listeners) {\n // A store of another library has no listeners to wait behind.\n flushComputed();\n }\n return;\n }\n // A listener added now runs after the ones of the source, in the same send.\n const trail = (): void => {\n listeners.delete(trail);\n armed.delete(listeners);\n flushComputed();\n };\n armed.add(listeners);\n listeners.add(trail as never);\n };\n\n const start = (): void => {\n starting = true;\n started = true;\n try {\n compute(send);\n for (const source of list) {\n stops.push(source.subscribe(() => heard(source)));\n }\n } catch (error) {\n // A store that failed to start has no subscriptions, so it can start again.\n started = false;\n for (const end of stops) {\n end();\n }\n stops = [];\n cleanup?.();\n cleanup = undefined;\n throw error;\n } finally {\n starting = false;\n }\n };\n\n const stop = (): void => {\n started = false;\n for (const end of stops) {\n end();\n }\n stops = [];\n cleanup?.();\n cleanup = undefined;\n if (state.waits) {\n state.waits = false;\n waiting.splice(waiting.indexOf(state), 1);\n }\n };\n\n return Object.assign(\n {\n get(): T {\n if (started) {\n return out.v;\n }\n // No subscriber: compute once from the sources and stop. The async form keeps the\n // initial value until `set` runs.\n let value = out.v;\n started = true;\n try {\n compute((next) => {\n value = next;\n });\n } finally {\n started = false;\n cleanup?.();\n cleanup = undefined;\n }\n return value;\n },\n subscribe(listener: (value: T) => void): () => void {\n const stopListening = out.subscribe(listener);\n if (!started) {\n try {\n start();\n } catch (error) {\n stopListening();\n throw error;\n }\n }\n subscribers.add(stopListening);\n return () => {\n if (subscribers.delete(stopListening)) {\n stopListening();\n if (subscribers.size === 0) {\n stop();\n }\n }\n };\n },\n },\n { d: level },\n );\n}\n\n// Bridges: a store of another library that can cross the page state. `bridge()` names how to make\n// the library's store, read it and listen to it, and the page state sends the data that `get`\n// reads, with the name of the bridge. The browser makes the library's store again, once, from\n// that data.\n\n/** What `bridge` takes. */\nexport interface BridgeOptions<S, T> {\n /**\n * Makes the library's store. On the server it runs once for each call of the bridge. In the\n * browser it runs once, when the store gets its first subscriber, with the data that the server\n * sent. It must be in a module that the browser can load.\n */\n create: (snapshot: T | undefined) => S;\n /** The data of the store: plain data that the page state can send. */\n get: (source: S) => T;\n /** Calls `listener` when the store changes. Returns the function that stops it. */\n subscribe: (source: S, listener: () => void) => () => void;\n /** Writes the store. The browser never calls it when the page resumes. */\n set?: (source: S, value: T) => void;\n}\n\n/** A store of `bridge()`: the contract of a store, and the store of the library. */\nexport interface BridgedStore<S, T> extends StoreLike<T> {\n /**\n * The store of the library. In the browser it is undefined until the store has a subscriber,\n * since the browser makes it at the first subscriber.\n */\n readonly source: S | undefined;\n}\n\n/** What `bridge` returns: makes a store, from the data of the server in the browser. */\nexport interface Bridge<S, T> {\n (snapshot?: T): BridgedStore<S, T>;\n /** The options. */\n b: BridgeOptions<S, T>;\n /** The name that the compiler gave, `bridge:<file>#<export>`. */\n i?: string;\n}\n\nconst BRIDGES = Symbol.for('brumate.bridges');\nconst BRIDGE_LOAD = Symbol.for('brumate.bridge-load');\n\ntype Global = { [BRIDGES]?: Map<string, Bridge<never, never>>; [BRIDGE_LOAD]?: Loader };\ntype Loader = [load: (module: string) => Promise<unknown>, report: (error: unknown) => void];\n\n/** The bridges by name, which any copy of the runtime shares. */\nfunction bridges(): Map<string, Bridge<never, never>> {\n return ((globalThis as Global)[BRIDGES] ??= new Map());\n}\n\n/**\n * Sets how the browser loads the module of a bridge, and where a failed load is reported. The\n * core calls it when it starts.\n */\nexport function setBridgeLoader(...loader: Loader): void {\n (globalThis as Global)[BRIDGE_LOAD] = loader;\n}\n\n/** The module of a bridge, from its name. */\nfunction bridgeModule(id: string): string {\n return id.slice(0, id.lastIndexOf('#'));\n}\n\n/**\n * Makes a bridge. Keep its value in a module-level export, so the page state can name it:\n * `export const bears = bridge({ … })`. The compiler gives it its name.\n */\nexport function bridge<S, T>(options: BridgeOptions<S, T>): Bridge<S, T> {\n const made = Object.assign(\n (snapshot?: T): BridgedStore<S, T> => new Bridged(made, options.create(snapshot)),\n { b: options },\n ) as Bridge<S, T>;\n return made;\n}\n\n/** Gives a bridge its name, which the compiler writes at the end of its module. */\nexport function nameBridge(made: Bridge<never, never>, id: string): void {\n made.i = id;\n bridges().set(id, made);\n}\n\n/** True for a store of `bridge()`, of any copy of the runtime. */\nexport function isBridged(value: unknown): value is Bridged<unknown, unknown> {\n return (\n typeof value === 'object' && value !== null && (value as { k?: unknown }).k === 'brumate.bridge'\n );\n}\n\n/**\n * Whether two values hold the same data: the same value, or arrays and plain objects whose items\n * hold the same data. A store that the browser makes again holds a new object with the content\n * the server sent, which needs no repair.\n */\nexport function sameData(a: unknown, b: unknown, open?: Map<object, Set<unknown>>): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n const array = Array.isArray(a);\n if (array ? !Array.isArray(b) || a.length !== b.length : !isPlain(a) || !isPlain(b)) {\n return false;\n }\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n // A pair already under compare is a cycle: it counts as the same, so each pair is compared once.\n open ??= new Map();\n let pairs = open.get(left);\n if (pairs?.has(right)) {\n return true;\n }\n if (!pairs) {\n pairs = new Set();\n open.set(left, pairs);\n }\n pairs.add(right);\n const keys = Object.keys(left);\n if (!array && keys.length !== Object.keys(right).length) {\n return false;\n }\n for (const key of keys) {\n if (!(key in right) || !sameData(left[key], right[key], open)) {\n return false;\n }\n }\n return true;\n}\n\n/** Whether a value is an object of `Object` or of no prototype, as page state holds. */\nfunction isPlain(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * The store that a bridge makes. On the server it holds the library's store from the start. In\n * the browser the page state makes it with the name of the bridge and the data of the server, and\n * it makes the library's store at its first subscriber.\n */\nexport class Bridged<S, T> implements BridgedStore<S, T> {\n /** The mark of a bridged store, which `isBridged` reads in every copy of the runtime. */\n k = 'brumate.bridge' as const;\n /** The bridge. Undefined for a store of the page state until the module of the bridge loads. */\n f?: Bridge<S, T>;\n /** The name of the bridge, for a store of the page state. */\n i?: string;\n /** The library's store. */\n s?: S;\n /** True once the library's store exists. */\n m = false;\n /** The data that the server sent, until the library's store exists. */\n v?: T;\n /** Whether the bridge has `set`, as the server sent it, until the module loads. */\n w?: boolean;\n\n constructor(\n made: Bridge<S, T> | undefined,\n source: S | undefined,\n id?: string,\n snapshot?: T,\n writable?: boolean,\n ) {\n this.f = made;\n this.i = id;\n this.v = snapshot;\n this.w = writable;\n if (made) {\n this.s = source;\n this.m = true;\n }\n }\n\n /**\n * The library's store. In the browser it is undefined until the store has a subscriber and the\n * module of the bridge has loaded.\n */\n get source(): S | undefined {\n return this.s;\n }\n\n /** The name of the bridge. */\n get id(): string | undefined {\n return this.f?.i ?? this.i;\n }\n\n /** The data of the store: what `get` reads, or what the server sent before the first subscriber. */\n get(): T {\n return this.m ? this.f!.b.get(this.s as S) : (this.v as T);\n }\n\n /**\n * Calls `listener` with the data when it changes. The first subscriber makes the library's\n * store in the browser. When the module of the bridge has not loaded, the subscription starts\n * when it has.\n */\n subscribe(listener: (value: T) => void, ...seen: [value?: T]): () => void {\n let stopped = false;\n let stop: (() => void) | undefined;\n // What this subscriber has seen, which `seen` can name: a source that starts later compares\n // with it.\n let last = seen.length > 0 ? (seen[0] as T) : this.get();\n const start = (): void => {\n if (stopped) {\n return;\n }\n const options = this.f!.b;\n const source = this.make();\n stop = options.subscribe(source, () => {\n const next = options.get(source);\n if (!sameData(next, last)) {\n last = next;\n listener(next);\n }\n });\n // A source that starts from other data than this subscriber saw, such as one that keeps its\n // own state, is written once.\n const first = options.get(source);\n if (!sameData(first, last)) {\n last = first;\n listener(first);\n }\n };\n if (this.find()) {\n start();\n } else {\n void this.load().then((loaded) => loaded && start());\n }\n return () => {\n stopped = true;\n stop?.();\n };\n }\n\n /** Writes the library's store, when the bridge has `set`. */\n get set(): ((value: T) => void) | undefined {\n // Before the module loads, the server's word is all there is, so `let` checks the same.\n const writable = this.find() ? !!this.f!.b.set : this.w !== false;\n return writable ? (value) => this.write(value) : undefined;\n }\n\n /** Writes the library's store, after the module of the bridge has loaded. */\n private write(value: T): void {\n if (this.find()) {\n this.f!.b.set!(this.make(), value);\n } else {\n void this.load().then((loaded) => loaded && this.write(value));\n }\n }\n\n /** The bridge, once its module has loaded. */\n private find(): Bridge<S, T> | undefined {\n if (!this.f && this.i !== undefined) {\n this.f = bridges().get(this.i) as Bridge<S, T> | undefined;\n }\n return this.f;\n }\n\n /** Loads the module of the bridge. A failure goes to the core's error path; it gives false. */\n private load(): Promise<boolean> {\n const [load, report] = (globalThis as Global)[BRIDGE_LOAD] ?? [];\n return Promise.resolve(load?.(bridgeModule(this.i!))).then(\n () => {\n if (this.find()) {\n return true;\n }\n this.fail(\n report,\n new Error(\n `The bridge \"${this.i}\" is not in its module. Keep bridge() in a module-level export, as \"export const name = bridge({ … })\"`,\n ),\n );\n return false;\n },\n (error: unknown) => {\n this.fail(report, error);\n return false;\n },\n );\n }\n\n private fail(report: ((error: unknown) => void) | undefined, error: unknown): void {\n if (report) {\n report(error);\n } else {\n console.error(error);\n }\n }\n\n /** Makes the library's store once, with the data of the server. */\n private make(): S {\n if (!this.m) {\n this.s = this.f!.b.create(this.v);\n this.m = true;\n }\n return this.s as S;\n }\n}\n"],"mappings":";;;AAQA,MAAM,OAAO,OAAO,IAAI,cAAc;;AAGtC,SAAgB,UAAU,OAA2C;CACnE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA4B,QAAQ,YAC5C,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,KAC9B,CAAC,WAAW,KAAK;AAErB;;;;;;AAOA,SAAgB,WACd,OACA,MACA,OACA,KACoB;CACpB,MAAM,QAAQ,SAAS,KAAA,IAAY,QAAS,QAAgD;CAC5F,IAAI,CAAC,WAAW,KAAK,GAAG;EAEtB,IAAI,UAAU,KAAK,GACjB,MAAM,IAAI,UACR,6BAA6B,MAAM,IAAI,6EACzC;EAEF,MAAM,IAAI,UACR,gBAAgB,QAAQ,KAAA,IAAY,YAAY,gBAAgB,IAAI,KAAK,SAAS,KAAA,IAAY,KAAK,QAAQ,KAAK,GAAG,oEACrH;CACF;CACA,IAAI,SAAS,CAAC,OAAO,KAAK,GACxB,MAAM,IAAI,UACR,cAAc,OAAO,IAAI,iEAC3B;CAEF,OAAO;AACT;;;;;AAMA,SAAgB,iBAAiB,WAAmB,OAAsB;CACxE,uBAAO,IAAI,MACT,a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OAAO,KAAK;CACd;;CAGA,OAAiC;EAC/B,MAAM,CAAC,MAAM,UAAW,WAAsB,gBAAgB,CAAC;EAC/D,OAAO,QAAQ,QAAQ,OAAO,aAAa,KAAK,CAAE,CAAC,CAAC,CAAC,CAAC,WAC9C;GACJ,IAAI,KAAK,KAAK,GACZ,OAAO;GAET,KAAK,KACH,wBACA,IAAI,MACF,eAAe,KAAK,EAAE,uGACxB,CACF;GACA,OAAO;EACT,IACC,UAAmB;GAClB,KAAK,KAAK,QAAQ,KAAK;GACvB,OAAO;EACT,CACF;CACF;CAEA,KAAa,QAAgD,OAAsB;EACjF,IAAI,QACF,OAAO,KAAK;OAEZ,QAAQ,MAAM,KAAK;CAEvB;;CAGA,OAAkB;EAChB,IAAI,CAAC,KAAK,GAAG;GACX,KAAK,IAAI,KAAK,EAAG,EAAE,OAAO,KAAK,CAAC;GAChC,KAAK,IAAI;EACX;EACA,OAAO,KAAK;CACd;AACF"}
@@ -0,0 +1,22 @@
1
+ import { a as serialOptions, i as plugins } from "./serial-ioa17MuY.js";
2
+ import { fromWebStream } from "@seroval/transport/web";
3
+ import { createJSONReader } from "@seroval/transport/read";
4
+ //#region src/runtime/stream-read.ts
5
+ /** The key of the answer among the values of the stream. */
6
+ const ANSWER = "answer";
7
+ /**
8
+ * Reads the first value of a byte stream, and the rest in the background, so
9
+ * the promises and async iterables in it settle as their messages arrive.
10
+ */
11
+ async function fromChunkStream(stream) {
12
+ const reader = createJSONReader({
13
+ plugins,
14
+ ...serialOptions()
15
+ });
16
+ fromWebStream(stream, reader);
17
+ return reader.get(ANSWER);
18
+ }
19
+ //#endregion
20
+ export { fromChunkStream as n, ANSWER as t };
21
+
22
+ //# sourceMappingURL=stream-read-BTsYstJY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-read-BTsYstJY.js","names":[],"sources":["../src/runtime/stream-read.ts"],"sourcesContent":["// The read side of the answer of a server function. The browser loads only this\n// module, not the writer that the server uses (see `stream.ts`).\n\nimport { createJSONReader } from '@seroval/transport/read';\nimport { fromWebStream } from '@seroval/transport/web';\nimport { serialOptions, plugins } from './serial.ts';\n\n/** The key of the answer among the values of the stream. */\nexport const ANSWER = 'answer';\n\n/**\n * Reads the first value of a byte stream, and the rest in the background, so\n * the promises and async iterables in it settle as their messages arrive.\n */\nexport async function fromChunkStream(stream: ReadableStream<Uint8Array>): Promise<unknown> {\n const reader = createJSONReader({ plugins, ...serialOptions() });\n void fromWebStream(stream, reader);\n return reader.get(ANSWER);\n}\n"],"mappings":";;;;;AAQA,MAAa,SAAS;;;;;AAMtB,eAAsB,gBAAgB,QAAsD;CAC1F,MAAM,SAAS,iBAAiB;EAAE;EAAS,GAAG,cAAc;CAAE,CAAC;CAC/D,cAAmB,QAAQ,MAAM;CACjC,OAAO,OAAO,IAAI,MAAM;AAC1B"}
@@ -0,0 +1 @@
1
+ export { t as ANSWER, n as fromChunkStream } from "./stream-read-BTsYstJY.js";
@@ -1,17 +1,24 @@
1
1
  //#region src/runtime/trusted.ts
2
2
  /** The name of the policy, for `trusted-types brumate` in the policy of the site. */
3
3
  const POLICY = "brumate";
4
+ /**
5
+ * The key of the policy on the browser's `trustedTypes`. A second copy of the core on the page, or
6
+ * the core after a hot update, reuses it, since the browser refuses a second policy of the same
7
+ * name unless the policy of the site says `'allow-duplicates'`.
8
+ */
9
+ const KEY = Symbol.for("brumate.trusted-types");
4
10
  /** The policy, made on the first insert. Null where the browser has no Trusted Types. */
5
11
  let policy;
6
12
  function ensure() {
7
13
  if (policy !== void 0) return policy;
8
14
  const factory = globalThis.trustedTypes;
9
- policy = null;
10
- if (factory) try {
15
+ policy = factory?.[KEY] ?? null;
16
+ if (factory && !policy) try {
11
17
  policy = factory.createPolicy(POLICY, {
12
18
  createHTML: (html) => html,
13
19
  createScript: (code) => code
14
20
  });
21
+ factory[KEY] = policy;
15
22
  } catch (error) {
16
23
  console.error(`brumate: the Content Security Policy does not allow the Trusted Types policy "${POLICY}". Add "trusted-types ${POLICY}" to it`, error);
17
24
  }
@@ -26,24 +33,6 @@ function trustedScript(code) {
26
33
  return ensure()?.createScript(code) ?? code;
27
34
  }
28
35
  //#endregion
29
- //#region src/runtime/skew.ts
30
- const KEY = "brumate:builds";
31
- /**
32
- * True the first time in this tab that a page loads in full for `build`,
33
- * the build that it loads. The build is kept, so the next time is false.
34
- * Without session storage it is false, since the page cannot tell a loop.
35
- */
36
- function loadOnce(build) {
37
- try {
38
- const builds = JSON.parse(sessionStorage.getItem(KEY) ?? "[]");
39
- if (builds.includes(build)) return false;
40
- sessionStorage.setItem(KEY, JSON.stringify([...builds, build].slice(-8)));
41
- return true;
42
- } catch {
43
- return false;
44
- }
45
- }
46
- //#endregion
47
- export { trustedHTML as n, trustedScript as r, loadOnce as t };
36
+ export { trustedScript as n, trustedHTML as t };
48
37
 
49
- //# sourceMappingURL=skew-FRmAy9iy.js.map
38
+ //# sourceMappingURL=trusted-g_zUJbh2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trusted-g_zUJbh2.js","names":[],"sources":["../src/runtime/trusted.ts"],"sourcesContent":["// Trusted Types. A site whose Content Security Policy has\n// `require-trusted-types-for 'script'` refuses a string in `innerHTML` and\n// in the text of a script. The core passes the markup that it inserts, and\n// the scripts that it copies to run them, through a policy named `brumate`:\n// the markup of renders, deferred blocks, client navigation and the devtools.\n// The markup is what brumate's own render code made, with every value\n// escaped, and the scripts come from the server with the page, so the\n// policy passes them as they are.\n\n/** The name of the policy, for `trusted-types brumate` in the policy of the site. */\nexport const POLICY = 'brumate';\n\ninterface Policy {\n createHTML(html: string): string;\n createScript(code: string): string;\n}\n\n/**\n * The key of the policy on the browser's `trustedTypes`. A second copy of the core on the page, or\n * the core after a hot update, reuses it, since the browser refuses a second policy of the same\n * name unless the policy of the site says `'allow-duplicates'`.\n */\nconst KEY = Symbol.for('brumate.trusted-types');\n\ninterface Factory {\n createPolicy(name: string, rules: Policy): Policy;\n [KEY]?: Policy;\n}\n\n/** The policy, made on the first insert. Null where the browser has no Trusted Types. */\nlet policy: Policy | null | undefined;\n\nfunction ensure(): Policy | null {\n if (policy !== undefined) {\n return policy;\n }\n const factory = (globalThis as { trustedTypes?: Factory }).trustedTypes;\n policy = factory?.[KEY] ?? null;\n if (factory && !policy) {\n try {\n policy = factory.createPolicy(POLICY, {\n createHTML: (html) => html,\n createScript: (code) => code,\n });\n factory[KEY] = policy;\n } catch (error) {\n // The policy of the site names other policies, so the inserts below fail too.\n console.error(\n `brumate: the Content Security Policy does not allow the Trusted Types policy \"${POLICY}\". Add \"trusted-types ${POLICY}\" to it`,\n error,\n );\n }\n }\n return policy;\n}\n\n/** Markup that the core made, as the browser accepts it in `innerHTML`. */\nexport function trustedHTML(html: string): string {\n return ensure()?.createHTML(html) ?? html;\n}\n\n/** The code of a script that came with the page, as the browser accepts it in a script's text. */\nexport function trustedScript(code: string): string {\n return ensure()?.createScript(code) ?? code;\n}\n"],"mappings":";;AAUA,MAAa,SAAS;;;;;;AAYtB,MAAM,MAAM,OAAO,IAAI,uBAAuB;;AAQ9C,IAAI;AAEJ,SAAS,SAAwB;CAC/B,IAAI,WAAW,KAAA,GACb,OAAO;CAET,MAAM,UAAW,WAA0C;CAC3D,SAAS,UAAU,QAAQ;CAC3B,IAAI,WAAW,CAAC,QACd,IAAI;EACF,SAAS,QAAQ,aAAa,QAAQ;GACpC,aAAa,SAAS;GACtB,eAAe,SAAS;EAC1B,CAAC;EACD,QAAQ,OAAO;CACjB,SAAS,OAAO;EAEd,QAAQ,MACN,iFAAiF,OAAO,wBAAwB,OAAO,UACvH,KACF;CACF;CAEF,OAAO;AACT;;AAGA,SAAgB,YAAY,MAAsB;CAChD,OAAO,OAAO,CAAC,EAAE,WAAW,IAAI,KAAK;AACvC;;AAGA,SAAgB,cAAc,MAAsB;CAClD,OAAO,OAAO,CAAC,EAAE,aAAa,IAAI,KAAK;AACzC"}
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as NavigateOptions } from "./boot-CMy0f_iC.js";
1
+ import { n as NavigateOptions } from "./boot-BkUdiYOF.js";
2
2
  import { Plugin, ViteDevServer } from "vite";
3
3
  //#region src/report.d.ts
4
4
  /** Sizes in bytes, after gzip. */
package/dist/vite.js CHANGED
@@ -1,7 +1,7 @@
1
- import { A as analyzeProject, C as isReactiveModule, E as originalPosition, G as bridgeModuleId, H as resolveMacros, I as parse, J as nameBridges, K as hasBridge, M as importSource, N as importedComponents, O as entryClasses, P as resolveRelative, Q as getLocation, R as forEachNode, T as builtin, U as walk, _ as functionId, a as scopeLabel, b as SHARED_QUERY, f as instanceScope, i as report, k as refreshedNames, n as formatReport, p as slotIndex, q as mayHaveBridge, s as compile, t as anchorLabel, v as getComponentName, w as resolveFromDisk, x as generateShared, y as hash, z as analyze } from "./inspect-BSHv1_25.js";
1
+ import { C as resolveFromDisk, D as entryClasses, F as parse, G as bridgeModuleId, H as resolveMacros, J as nameBridges, K as hasBridge, M as importedComponents, N as resolveRelative, O as refreshedNames, Q as getLocation, R as forEachNode, S as isReactiveModule, T as originalPosition, U as walk, _ as getComponentName, a as scopeLabel, b as generateShared, f as instanceScope, g as functionId, i as report, j as importSource, k as analyzeProject, n as formatReport, p as slotIndex, q as mayHaveBridge, s as compile, t as anchorLabel, v as hash, w as builtin, y as SHARED_QUERY, z as analyze } from "./inspect-CGl5Y8q6.js";
2
2
  import { s as toNodeHeaders } from "./cookies-Cnbf4w-S.js";
3
3
  import { t as LOGO } from "./logo-DQ_OYhBi.js";
4
- import { _ as findPackages, a as findScripts, b as resolveComponentPackage, d as isScriptFile, f as serverExports, g as findPackage, h as findBridgePackages, i as findFiles, l as hasServerMiddleware, m as serverStubs, n as defaultExclude, o as findServerFiles, p as serverModule, r as findBridgeFiles, s as findPackageServerFile, u as hasUseServer, v as packageFileName, y as reachableFiles } from "./files-BuQvpBwF.js";
4
+ import { _ as findPackages, a as findScripts, b as resolveComponentPackage, d as isScriptFile, f as serverExports, g as findPackage, h as findBridgePackages, i as findFiles, l as hasServerMiddleware, m as serverStubs, n as defaultExclude, o as findServerFiles, p as serverModule, r as findBridgeFiles, s as findPackageServerFile, u as hasUseServer, v as packageFileName, y as reachableFiles } from "./files-D5GtxwEQ.js";
5
5
  import { parseSync } from "oxc-parser";
6
6
  import { createHash } from "node:crypto";
7
7
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
@@ -1755,6 +1755,11 @@ async function inBatches(list, run) {
1755
1755
  return results;
1756
1756
  }
1757
1757
  const START = "virtual:brumate/start";
1758
+ /**
1759
+ * On the dev server, a client entry that imports `start` from `brumate/loader` gets this module
1760
+ * in its place. It sets up the hot updates and the devtools around `start`.
1761
+ */
1762
+ const DEV_START = "virtual:brumate/dev-start";
1758
1763
  /** Exports `load(id)`, which imports the client module of a component. */
1759
1764
  const MANIFEST = "virtual:brumate/manifest";
1760
1765
  /** `virtual:brumate/bundle/<id>` imports the client modules of a root component and those it renders. */
@@ -1858,7 +1863,8 @@ function getMarkup(result) {
1858
1863
  const ranges = [
1859
1864
  ...file.instanceScript ? [file.instanceScript] : [],
1860
1865
  ...file.moduleScript ? [file.moduleScript] : [],
1861
- ...file.styles
1866
+ ...file.styles,
1867
+ ...file.blockStyles
1862
1868
  ];
1863
1869
  forEachNode(file.children, (node) => {
1864
1870
  if ("body" in node && node.body && "script" in node.body && node.body.script) ranges.push(node.body.script);
@@ -2799,6 +2805,18 @@ function brumate(options = {}) {
2799
2805
  response.end(errorPage(error, server));
2800
2806
  }
2801
2807
  }
2808
+ let recording;
2809
+ async function recorder() {
2810
+ if (!recording) {
2811
+ const [{ AsyncLocalStorage }, { format }, { createRecorder }] = await Promise.all([
2812
+ import("node:async_hooks"),
2813
+ import("node:util"),
2814
+ import("./devtools-calls-DGW6nLZ2.js")
2815
+ ]);
2816
+ recording = createRecorder(new AsyncLocalStorage(), format);
2817
+ }
2818
+ return recording;
2819
+ }
2802
2820
  async function handleDevRPC(server, request, response) {
2803
2821
  const id = decodeURIComponent((request.url ?? "").slice(rpc.length + 1).split("?")[0]);
2804
2822
  const owner = id.split("#")[0];
@@ -2823,7 +2841,7 @@ function brumate(options = {}) {
2823
2841
  body: new Uint8Array(await readBody(request))
2824
2842
  });
2825
2843
  const began = performance.now();
2826
- const answer = await handle(webRequest, { address: request.socket.remoteAddress });
2844
+ const answer = await (await recorder())(() => handle(webRequest, { address: request.socket.remoteAddress }));
2827
2845
  answer.headers.append("server-timing", `brumate;dur=${(performance.now() - began).toFixed(1)};desc="server function"`);
2828
2846
  response.statusCode = answer.status;
2829
2847
  for (const [name, value] of Object.entries(toNodeHeaders(answer.headers))) response.setHeader(name, value);
@@ -3178,7 +3196,8 @@ function brumate(options = {}) {
3178
3196
  writeRouteTypes();
3179
3197
  },
3180
3198
  async resolveId(id, importer, resolveOptions) {
3181
- if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING || id === BUNDLES || id === CLIENT_BUNDLES || id.startsWith(BUNDLE)) return `\0${id}`;
3199
+ if (isServe && id === "brumate/loader" && !resolveOptions?.ssr && importer !== `\0${START}` && importer !== `\0${DEV_START}`) return `\0${DEV_START}`;
3200
+ if (id === START || id === DEV_START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING || id === BUNDLES || id === CLIENT_BUNDLES || id.startsWith(BUNDLE)) return `\0${id}`;
3182
3201
  const env = resolveOptions?.ssr ? void 0 : envFile();
3183
3202
  const from = importer?.split("?")[0];
3184
3203
  if (env && importer && from && from !== env && isScriptFile(from) && !importer.startsWith("\0") && !importer.includes(SERVER_QUERY) && !importer.includes("/node_modules/")) {
@@ -3228,6 +3247,19 @@ function brumate(options = {}) {
3228
3247
  vite: version
3229
3248
  })}, import.meta.hot));`] : []
3230
3249
  ].join("\n");
3250
+ if (id === `\0${DEV_START}`) return [
3251
+ "import { start as startLoader } from 'brumate/loader';",
3252
+ "import { hotLoad } from 'brumate/hot';",
3253
+ "export { startWithoutNavigation } from 'brumate/loader';",
3254
+ "export function start(options) {",
3255
+ " const stop = startLoader({ ...options, load: hotLoad(import.meta.hot, options.load) });",
3256
+ ...options.devtools !== false ? [` import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}, ${JSON.stringify({
3257
+ version: BRUMATE_VERSION,
3258
+ vite: version
3259
+ })}, import.meta.hot));`] : [],
3260
+ " return stop;",
3261
+ "}"
3262
+ ].join("\n");
3231
3263
  if (id === `\0${MANIFEST}`) return await manifest();
3232
3264
  if (id === `\0${BUNDLES}`) {
3233
3265
  const lines = [];