brumate 0.6.2 → 0.7.1

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 (96) hide show
  1. package/check.d.ts +3 -3
  2. package/dist/{boot-DkbcqdUz.d.ts → boot-CMy0f_iC.d.ts} +2 -2
  3. package/dist/cli.js +77 -6
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{client-C3vRNuLi.js → client-Bm0XbjHr.js} +274 -113
  6. package/dist/client-Bm0XbjHr.js.map +1 -0
  7. package/dist/{client-CqGDbWd_.d.ts → client-DnFF9_lv.d.ts} +40 -14
  8. package/dist/{client-routes-BtGpYCef.js → client-routes-BmPvNr4s.js} +10 -1
  9. package/dist/client-routes-BmPvNr4s.js.map +1 -0
  10. package/dist/{context-btHuB01Z.d.ts → context-BNgBXVUQ.d.ts} +7 -5
  11. package/dist/{context-CTiSzQRc.js → context-CU4Fpn5a.js} +10 -13
  12. package/dist/context-CU4Fpn5a.js.map +1 -0
  13. package/dist/{defer-M18UKyfG.js → defer-BWwxv7Qf.js} +2 -2
  14. package/dist/{defer-M18UKyfG.js.map → defer-BWwxv7Qf.js.map} +1 -1
  15. package/dist/{devtools-D9Q7a41M.js → devtools-Cl6AhENB.js} +4 -4
  16. package/dist/{devtools-D9Q7a41M.js.map → devtools-Cl6AhENB.js.map} +1 -1
  17. package/dist/{devtools-panel-DTQtljeA.js → devtools-panel-DLIeWcAj.js} +32 -9
  18. package/dist/devtools-panel-DLIeWcAj.js.map +1 -0
  19. package/dist/events-LgLdp1R7.js.map +1 -1
  20. package/dist/{features-CbgII-o7.js → features-DwMYKBIC.js} +6 -2
  21. package/dist/features-DwMYKBIC.js.map +1 -0
  22. package/dist/{files-DtDH5AR4.js → files-BuQvpBwF.js} +94 -3
  23. package/dist/files-BuQvpBwF.js.map +1 -0
  24. package/dist/{html-t1JpkODI.js → html-Cf5uKhLs.js} +3 -3
  25. package/dist/html-Cf5uKhLs.js.map +1 -0
  26. package/dist/index.d.ts +44 -0
  27. package/dist/index.js +3 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/{inspect-Bonq6EJO.js → inspect-BSHv1_25.js} +2739 -2080
  30. package/dist/inspect-BSHv1_25.js.map +1 -0
  31. package/dist/{loader-C-S3yzep.js → loader-BPNSRA2A.js} +5 -5
  32. package/dist/{loader-C-S3yzep.js.map → loader-BPNSRA2A.js.map} +1 -1
  33. package/dist/{rpc-C_znDZ_w.js → rpc-DqfCaYgF.js} +3 -3
  34. package/dist/{rpc-C_znDZ_w.js.map → rpc-DqfCaYgF.js.map} +1 -1
  35. package/dist/runtime/bundles.d.ts +1 -1
  36. package/dist/runtime/bundles.js +2 -0
  37. package/dist/runtime/bundles.js.map +1 -1
  38. package/dist/runtime/client.d.ts +4 -4
  39. package/dist/runtime/client.js +5 -5
  40. package/dist/runtime/context.d.ts +2 -2
  41. package/dist/runtime/context.js +1 -1
  42. package/dist/runtime/devtools.d.ts +2 -2
  43. package/dist/runtime/devtools.js +1 -1
  44. package/dist/runtime/events.d.ts +1 -1
  45. package/dist/runtime/hot.d.ts +1 -1
  46. package/dist/runtime/html.d.ts +1 -1
  47. package/dist/runtime/html.js +1 -1
  48. package/dist/runtime/loader.d.ts +2 -2
  49. package/dist/runtime/loader.js +2 -2
  50. package/dist/runtime/server.d.ts +4 -4
  51. package/dist/runtime/server.js +5 -5
  52. package/dist/runtime/signals.d.ts +2 -2
  53. package/dist/runtime/signals.js +43 -5
  54. package/dist/runtime/signals.js.map +1 -1
  55. package/dist/runtime/static-loader.d.ts +2 -2
  56. package/dist/runtime/static-loader.js +1 -1
  57. package/dist/runtime/store.d.ts +2 -0
  58. package/dist/runtime/store.js +1 -0
  59. package/dist/runtime/testing.d.ts +2 -2
  60. package/dist/runtime/testing.js +2 -2
  61. package/dist/{search-params-CM1RWR2P.js → search-params-C64liRBj.js} +34 -9
  62. package/dist/search-params-C64liRBj.js.map +1 -0
  63. package/dist/{server-dP_ucRiJ.d.ts → server-0rS5vUW1.d.ts} +37 -10
  64. package/dist/{server-BcT9icQ4.js → server-BVObWh-w.js} +132 -16
  65. package/dist/server-BVObWh-w.js.map +1 -0
  66. package/dist/{shared-CzbnWkVA.d.ts → shared-CuJdWifz.d.ts} +16 -3
  67. package/dist/{signals-BwD4u22K.d.ts → signals-DBnq9QRW.d.ts} +46 -6
  68. package/dist/{static-loader-DysAET-w.d.ts → static-loader-BYbXVJDY.d.ts} +2 -2
  69. package/dist/{static-loader-Bt2WDkY1.js → static-loader-V4V1Oy6G.js} +13 -5
  70. package/dist/static-loader-V4V1Oy6G.js.map +1 -0
  71. package/dist/store-BIBAYZo-.js +293 -0
  72. package/dist/store-BIBAYZo-.js.map +1 -0
  73. package/dist/store-xlTzAM_r.d.ts +171 -0
  74. package/dist/{stream-DRjx0keF.js → stream-RXLadXx1.js} +90 -4
  75. package/dist/stream-RXLadXx1.js.map +1 -0
  76. package/dist/vite.d.ts +1 -1
  77. package/dist/vite.js +128 -13
  78. package/dist/vite.js.map +1 -1
  79. package/elements.d.ts +349 -79
  80. package/package.json +5 -1
  81. package/skills/brumate/SKILL.md +1 -1
  82. package/skills/brumate/references/errors.md +127 -9
  83. package/skills/brumate/references/signals.md +37 -30
  84. package/skills/brumate/references/state.md +3 -2
  85. package/dist/client-C3vRNuLi.js.map +0 -1
  86. package/dist/client-routes-BtGpYCef.js.map +0 -1
  87. package/dist/context-CTiSzQRc.js.map +0 -1
  88. package/dist/devtools-panel-DTQtljeA.js.map +0 -1
  89. package/dist/features-CbgII-o7.js.map +0 -1
  90. package/dist/files-DtDH5AR4.js.map +0 -1
  91. package/dist/html-t1JpkODI.js.map +0 -1
  92. package/dist/inspect-Bonq6EJO.js.map +0 -1
  93. package/dist/search-params-CM1RWR2P.js.map +0 -1
  94. package/dist/server-BcT9icQ4.js.map +0 -1
  95. package/dist/static-loader-Bt2WDkY1.js.map +0 -1
  96. package/dist/stream-DRjx0keF.js.map +0 -1
@@ -48,7 +48,7 @@ declare function affix(prefix: string, value: unknown, suffix: string): unknown;
48
48
  /** Returns a style with custom properties before an element's own style. */
49
49
  declare function vars(variables: Record<string, unknown>, own: unknown): string;
50
50
  /** Returns a `<style>` element for a component's stylesheet. */
51
- declare function styleElement(id: string, css: string): string;
51
+ declare function styleElement(id: string, css: string, nonce?: string): string;
52
52
  /**
53
53
  * Merges the attributes of an element that has spreads, in their order: a
54
54
  * later value wins, except `class`, whose values all apply.
@@ -169,6 +169,14 @@ declare function unbind(props: Record<string, unknown>, names?: readonly string[
169
169
  interface PropSink {
170
170
  props?: Promise<unknown>[] | undefined;
171
171
  }
172
+ /** The value of a `$gate`, which cannot be a promise or a stream. A throw is held like a memo error. */
173
+ declare function gateValue<T>(value: T): T;
174
+ /**
175
+ * A read of `$store`: the key of the context, or the index of the source in the exports `z` of
176
+ * the component; the slot; the key of the store in the value of the context; and 1 when `let`
177
+ * writes the store.
178
+ */
179
+ type StoreRead = [from: string | number, slot: number, path?: string, write?: 1];
172
180
  /** The state of one scope in the page. */
173
181
  interface ScopeState {
174
182
  /** The scope's ID in the compiled component. */
@@ -194,6 +202,11 @@ interface ScopeState {
194
202
  v?: Record<string, unknown>;
195
203
  /** The slots that hold the contexts that the scope reads, by context key. */
196
204
  x?: Record<string, number>;
205
+ /**
206
+ * The slots that hold the values of stores that `$store` reads: the key of the context, the
207
+ * slot, and the key of the context value that holds the store, when it is not the value.
208
+ */
209
+ z?: StoreRead[];
197
210
  /** Slot values, in the order of the scope's layout. */
198
211
  s?: unknown[];
199
212
  /** The scope IDs of child components, by anchor index. */
@@ -251,5 +264,5 @@ declare const SCOPE_IDS: {
251
264
  holders: readonly (abstract new (...args: never[]) => object)[];
252
265
  };
253
266
  //#endregion
254
- export { onAttribute as A, escapeAttribute as C, isInternal as D, internal as E, spread as F, styleElement as I, textValue as L, ownValue as M, raw as N, isRaw as O, rawHTML as P, vars as R, escape as S, insertValue as T, attribute as _, PageState as a, classAttribute as b, ScopeId as c, useSerialEntry as d, Internal as f, affix as g, actionAttributes as h, PackedState as i, onValue as j, mergeAttributes as k, ScopeState as l, VOID_ELEMENTS as m, ElementReference as n, PropSink as o, Raw as p, FunctionReference as r, SCOPE_IDS as s, Binding as t, unbind as u, attributeText as v, handlerEntry as w, classValue as x, bindEntry as y };
255
- //# sourceMappingURL=shared-CzbnWkVA.d.ts.map
267
+ export { mergeAttributes as A, escape as C, internal as D, insertValue as E, rawHTML as F, spread as I, styleElement as L, onValue as M, ownValue as N, isInternal as O, raw as P, textValue as R, classValue as S, handlerEntry as T, affix as _, PageState as a, bindEntry as b, ScopeId as c, unbind as d, useSerialEntry as f, actionAttributes as g, VOID_ELEMENTS as h, PackedState as i, onAttribute as j, isRaw as k, ScopeState as l, Raw as m, ElementReference as n, PropSink as o, Internal as p, FunctionReference as r, SCOPE_IDS as s, Binding as t, gateValue as u, attribute as v, escapeAttribute as w, classAttribute as x, attributeText as y, vars as z };
268
+ //# sourceMappingURL=shared-CuJdWifz.d.ts.map
@@ -1,4 +1,5 @@
1
- import { a as Route, r as NavigationState, t as Context } from "./context-btHuB01Z.js";
1
+ import { a as Route, r as NavigationState, t as Context } from "./context-BNgBXVUQ.js";
2
+ import { a as Store, o as StoreLike } from "./store-xlTzAM_r.js";
2
3
  import { n as RouteParams, r as RoutePath } from "./routes-BZNt7DSZ.js";
3
4
  //#region src/runtime/signals.d.ts
4
5
  declare const BINDABLE: unique symbol;
@@ -40,6 +41,15 @@ type MemoValue<T> = Awaited<T> extends AsyncIterable<infer U> ? U : Awaited<T>;
40
41
  * is read. An async iterable gives each of its values in turn.
41
42
  */
42
43
  declare function $memo<T>(_value: T): MemoValue<T>;
44
+ /**
45
+ * Declares a memo that takes a new value only when the guard returns true.
46
+ * Otherwise it keeps its value and its readers do not run. The first value
47
+ * passes without the guard, and the server has no history, so it renders the
48
+ * value. The guard runs in the browser, on changes only, with the value the
49
+ * memo holds and the new one. A throw in the guard is held like a throw in
50
+ * a memo. The value cannot be a promise.
51
+ */
52
+ declare function $gate<T>(_value: T, _guard: (prev: T, next: T) => boolean): T;
43
53
  /**
44
54
  * Declares a memo that takes the value once it stops changing for `ms`
45
55
  * milliseconds, such as a search query while the user types. On the server,
@@ -65,8 +75,8 @@ declare function $effect(_callback: () => void | (() => void)): void;
65
75
  declare function $client(_callback: () => void | (() => void), _trigger?: "visible" | "idle" | "load"): void;
66
76
  /** Reads a value without depending on it. */
67
77
  declare function $untrack<T>(_value: T): T;
68
- /** True while a new value of a memo, or of a memo it reads, loads on the client. Always false on the server. */
69
- declare function $isPending(_memo: unknown): boolean;
78
+ /** True while a new value of one of the memos, or of a memo one reads, loads on the client. Always false on the server. */
79
+ declare function $isPending(..._memos: unknown[]): boolean;
70
80
  /**
71
81
  * Waits for a memo to have its value, and gives it. It resolves at once when the memo is settled,
72
82
  * and after the load when the memo loads its first value or loads again. When the inputs of the
@@ -92,8 +102,38 @@ declare function $isPassed(_prop: unknown): boolean;
92
102
  declare function $id(): string;
93
103
  /** Provides a value of a context to the components inside this one. */
94
104
  declare function $setContext<T>(_context: Context<T>, _value: T): void;
95
- /** Reads a context from the nearest component above that provides it, or its default value. */
105
+ /**
106
+ * Reads a context from the nearest component above that provides it. Without a provider it throws,
107
+ * or, with a second argument, gives `fallback`: `$getContext(Field, undefined)` is a read that may
108
+ * have no provider. A fallback that is not a literal runs only when no provider is above, once per
109
+ * read.
110
+ */
96
111
  declare function $getContext<T>(_context: Context<T>): T;
112
+ declare function $getContext<T, F>(_context: Context<T>, _fallback: F): T | F;
113
+ /**
114
+ * Binds a store to a variable. The store is any value with the functions `get`, `subscribe`
115
+ * (which returns a function that stops it) and, optionally, `set`. The source gives a store:
116
+ * `$store(field.state)` for `const field = $getContext(FieldContext)`,
117
+ * `$store($getContext(FieldContext))` for a context that holds a store, an import, a prop, a local
118
+ * `store(0)` or a call. A source that gives no store throws a `TypeError`. For a context that may
119
+ * have no provider, guard on its value, `const s = field ? $store(field.state) : undefined` with
120
+ * `const field = $getContext(FieldContext, undefined)`, or give a store as the fallback,
121
+ * `$store($getContext(LocaleContext, store('en-US')))`. It runs once and is not tracked, and the
122
+ * subscription ends with the scope. On resume the browser keeps the value that the server
123
+ * rendered, runs the source again when it is not a context, and writes the variable once if the
124
+ * store's value differs.
125
+ *
126
+ * `const x = $store(source)` is one-way: the store writes the variable. `let x = $store(source)`
127
+ * is two-way: a write to the variable, such as `x = next` or `x++`, calls `set` of the store, and
128
+ * a store without `set` throws a `TypeError` when the variable registers.
129
+ */
130
+ declare function $store<T>(_source: StoreLike<T>): T;
131
+ /**
132
+ * The store of a memo, a signal or a prop, for a value of `$setContext`. It adds no reactive
133
+ * value: the provider's update writes it. A store of a signal has a `set` that writes the
134
+ * signal; a store of a memo or a prop is read-only.
135
+ */
136
+ declare function $toStore<T>(_value: T): Store<T>;
97
137
  /**
98
138
  * The route of the page: its URL, its query string and its params, typed
99
139
  * from the route files as `href` is. The server reads the request, and the
@@ -161,5 +201,5 @@ declare function $handler<A extends unknown[]>(fn: (...args: A) => unknown, ...a
161
201
  */
162
202
  declare function flush(): void;
163
203
  //#endregion
164
- export { Unbound as A, $title as C, BoundSignal as D, BindableMark as E, flush as M, MemoValue as O, $throttled as S, Bindable as T, $resolve as _, $effect as a, $setContext as b, $id as c, $isPending as d, $memo as f, $props as g, $produce as h, $debounced as i, WritableMark as j, SearchParamOptions as k, $isBound as l, $optimistic as m, $bind as n, $getContext as o, $navigation as p, $client as r, $handler as s, $action as t, $isPassed as u, $route as v, $untrack as w, $signal as x, $searchParam as y };
165
- //# sourceMappingURL=signals-BwD4u22K.d.ts.map
204
+ export { BoundSignal as A, $store as C, $untrack as D, $toStore as E, flush as F, SearchParamOptions as M, Unbound as N, Bindable as O, WritableMark as P, $signal as S, $title as T, $props as _, $effect as a, $searchParam as b, $handler as c, $isPassed as d, $isPending as f, $produce as g, $optimistic as h, $debounced as i, MemoValue as j, BindableMark as k, $id as l, $navigation as m, $bind as n, $gate as o, $memo as p, $client as r, $getContext as s, $action as t, $isBound as u, $resolve as v, $throttled as w, $setContext as x, $route as y };
205
+ //# sourceMappingURL=signals-DBnq9QRW.d.ts.map
@@ -1,4 +1,4 @@
1
- import { t as LoaderOptions } from "./boot-DkbcqdUz.js";
1
+ import { t as LoaderOptions } from "./boot-CMy0f_iC.js";
2
2
  //#region src/runtime/static-loader.d.ts
3
3
  /**
4
4
  * `start` for a site that loads every page with a full page load, as with
@@ -8,4 +8,4 @@ import { t as LoaderOptions } from "./boot-DkbcqdUz.js";
8
8
  declare function startWithoutNavigation(options: LoaderOptions): () => void;
9
9
  //#endregion
10
10
  export { startWithoutNavigation as t };
11
- //# sourceMappingURL=static-loader-DysAET-w.d.ts.map
11
+ //# sourceMappingURL=static-loader-BYbXVJDY.d.ts.map
@@ -1,4 +1,4 @@
1
- import { c as HAS_LATE_MARKUP, l as HAS_LISTENERS, r as HAS_BLOCKS, t as HAS_ACTIONS } from "./features-CbgII-o7.js";
1
+ import { l as HAS_LATE_MARKUP, r as HAS_BLOCKS, t as HAS_ACTIONS, u as HAS_LISTENERS } from "./features-DwMYKBIC.js";
2
2
  //#region src/runtime/boot.ts
3
3
  /** True on the dev server. A Vite build replaces it with `false`, so the devtools calls go. */
4
4
  const DEV = import.meta.env?.DEV;
@@ -80,12 +80,20 @@ function boot(options, navigate) {
80
80
  /**
81
81
  * A key of `prevent` matches its `event.key` while only the modifier that it names is held. A
82
82
  * key alone matches while Ctrl, Meta and Alt are up, so the shortcuts of the browser, such as
83
- * Cmd+Left or Alt+Left, keep their default. `Mod+` is Ctrl or Meta. Shift does not count.
83
+ * Cmd+Left or Alt+Left, keep their default. `Mod+` is Ctrl or Meta. Shift does not count. A
84
+ * single letter after a modifier matches in either case, as the browser sends `k` for Cmd+K and
85
+ * `K` for Cmd+Shift+K. A letter alone keeps its case, as `a` and `A` type different text.
84
86
  */
85
87
  const keyMatches = (key, event) => {
86
88
  const plus = key.indexOf("+", 1);
87
89
  const modifier = plus > 0 ? key.slice(0, plus) : "";
88
- if ((event.key === " " ? "Space" : event.key) !== (plus > 0 ? key.slice(plus + 1) : key)) return false;
90
+ let name = plus > 0 ? key.slice(plus + 1) : key;
91
+ let pressed = event.key === " " ? "Space" : event.key;
92
+ if (plus > 0 && name.length === 1) {
93
+ name = name.toLowerCase();
94
+ pressed = pressed.toLowerCase();
95
+ }
96
+ if (pressed !== name) return false;
89
97
  switch (modifier) {
90
98
  case "Mod": return (event.ctrlKey || event.metaKey) && !event.altKey;
91
99
  case "Ctrl": return event.ctrlKey && !event.metaKey && !event.altKey;
@@ -201,7 +209,7 @@ function boot(options, navigate) {
201
209
  run(template, ref);
202
210
  return;
203
211
  }
204
- const done = import("./defer-M18UKyfG.js").then((module) => module.loadDeferred(template));
212
+ const done = import("./defer-BWwxv7Qf.js").then((module) => module.loadDeferred(template));
205
213
  if (DEV) devtools()?.defer?.(template, done);
206
214
  };
207
215
  const near = template.getAttribute("b-near");
@@ -287,4 +295,4 @@ function startWithoutNavigation(options) {
287
295
  //#endregion
288
296
  export { boot as n, importCore as r, startWithoutNavigation as t };
289
297
 
290
- //# sourceMappingURL=static-loader-Bt2WDkY1.js.map
298
+ //# sourceMappingURL=static-loader-V4V1Oy6G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"static-loader-V4V1Oy6G.js","names":[],"sources":["../src/runtime/boot.ts","../src/runtime/static-loader.ts"],"sourcesContent":["// The loader's code that every page runs. `loader.ts` adds client navigation,\n// and `static-loader.ts` starts it without, so a site that turns navigation\n// off does not have its code, or the parts of the core that only it uses, in\n// its bundle.\n//\n// This file keeps its arrow functions and its Array methods, for size: the loader ships to every\n// page, and the function declarations and loops measured 20 to 50 bytes of gzip larger.\n\nimport { HAS_ACTIONS, HAS_BLOCKS, HAS_LATE_MARKUP, HAS_LISTENERS } from './features.ts';\nimport type * as Client from './client.ts';\nimport type { ClientModule, DevtoolsHooks } from './client.ts';\nimport type { SerialEntry } from './values.ts';\n\n/** True on the dev server. A Vite build replaces it with `false`, so the devtools calls go. */\nconst DEV = (import.meta as { env?: { DEV?: boolean } }).env?.DEV;\n\n/** The hooks of the devtools overlay, under the same key as the core's. */\nfunction devtools(): DevtoolsHooks | undefined {\n return (globalThis as Record<symbol, DevtoolsHooks | undefined>)[Symbol.for('brumate.devtools')];\n}\n\nexport interface LoaderOptions {\n /**\n * Imports the client module of a component, by component ID. Undefined for\n * a component that has no client code.\n */\n load: (id: string) => Promise<ClientModule> | undefined;\n /** The URL prefix of server function calls. */\n rpc?: string;\n /** Imports the serial entry, which the core takes before it reads the page state. */\n serial?: () => Promise<SerialEntry>;\n /**\n * Loads pages without a full page load: links to the same origin, the back\n * and forward buttons, forms that post to a server function, and redirects\n * from server functions to the same origin. Defaults to true.\n */\n navigate?: boolean | NavigateOptions;\n /**\n * The ID of the build of the page, for skew protection. The Vite plugin\n * sets it. Calls send it, and a page of another build, or a call that\n * answers 409 after a deploy, makes the next navigation a full page load.\n */\n build?: string;\n /**\n * Receives every error of client code first: of a handler, an effect, a\n * `$client` callback or a memo that loads, such as for a reporting\n * service. `scope` is the ID of the scope that the code belongs to. The\n * error then renders the `#catch` body of the nearest `#try`, or the page\n * gets a `brumate:error` event on `window` and the error is logged.\n */\n onError?: (error: unknown, info: { scope?: number | string }) => void;\n}\n\nexport interface NavigateOptions {\n /**\n * Swaps the page inside a view transition, where the browser has them.\n * CSS can tell links, the back and forward buttons and forms apart with\n * the types `push`, `traverse` and `form`. A redirect from a server\n * function has the type `form`.\n */\n transition?: boolean;\n /**\n * After a navigation, moves the focus to the first `<h1>` of the routes\n * that changed, or to `<main>`, as a full page load starts it at the top.\n * Defaults to true.\n */\n focus?: boolean;\n}\n\ninterface Entry {\n raw: string;\n type: string;\n modifiers: string[];\n ref: string;\n}\n\n// Parsed `b-on` values, so repeated events do not parse them again.\nconst parsed = new Map<string, Entry[]>();\n\nexport function entries(element: Element): Entry[] {\n const value = element.getAttribute('b-on') ?? '';\n return (parsed.get(value) ??\n parsed\n .set(\n value,\n value\n .split(' ')\n .filter(Boolean)\n .map((entry) => {\n const [name, ref] = entry.split('=') as [string, string];\n const [type, ...modifiers] = name.split(':') as [string, ...string[]];\n return { raw: entry, type, modifiers, ref };\n }),\n )\n .get(value))!;\n}\n\n/** The functions of the core that the loader calls. */\nexport type Core = (typeof Client)['loader'];\n\n/**\n * Imports the core. It reads one export by name, so a build keeps only it and\n * the helpers that compiled components call.\n */\nlet corePromise: Promise<Core> | undefined;\nexport const importCore = (): Promise<Core> =>\n (corePromise ??= import('./client.ts').then(\n (client) => client.loader,\n (error: unknown) => {\n // A load that fails can start again, such as after the network comes back.\n corePromise = undefined;\n throw error;\n },\n ));\n\n/** Runs a function when the browser is idle. */\nconst idle = (fn: () => void): unknown => (window.requestIdleCallback ?? setTimeout)(fn);\n\n/** What the loader gives the code that loads pages without a full page load. */\nexport interface Navigation {\n options: LoaderOptions;\n listen: (\n target: EventTarget,\n type: string,\n listener: (event: Event) => void,\n flags?: AddEventListenerOptions | boolean,\n ) => void;\n core: () => Promise<Core> | undefined;\n /** Starts the core, or returns the one that runs. */\n start: () => Promise<Core>;\n scan: (root: ParentNode) => void;\n}\n\n/**\n * Starts resuming the page. Listens to the events in `b-on` attributes\n * and loads `brumate/client` and the component's module on the first one.\n * `navigate` adds client navigation, and returns how to import the core.\n * Returns a function that removes the listeners and stops the core.\n */\nexport function boot(\n options: LoaderOptions,\n navigate?: (navigation: Navigation) => () => Promise<Core>,\n): () => void {\n let core: Promise<Core> | undefined;\n // Once stopped, the loader starts nothing, also from markup that the core inserts later with the\n // hooks that this loader gave it. A new loader can reuse the IDs of client scopes, so a stale\n // start would run in a scope of the new page.\n let stopped = false;\n /** The event types that the document listens to, and whether each listener is passive. */\n const types = new Map<string, boolean>();\n const removers: (() => void)[] = [];\n const listen = (\n target: EventTarget,\n type: string,\n listener: (event: Event) => void,\n flags?: AddEventListenerOptions | boolean,\n ): void => {\n target.addEventListener(type, listener, flags);\n removers.push(() => target.removeEventListener(type, listener, flags));\n };\n\n // Client navigation imports the core with the code that reads the pages it adds.\n let load = importCore;\n // The modules that the loader asked for, which the core takes, so a handler whose\n // code loaded runs without another `import()`. In Chrome, an `import()` of a module that is\n // loaded already still resolves in a task of its own, which can wait for the next frame.\n const modules = new Map<string, Promise<ClientModule> | undefined>();\n const loadModule = (id: string): Promise<ClientModule> | undefined => {\n if (modules.has(id)) {\n return modules.get(id);\n }\n const promise = options.load(id);\n modules.set(id, promise);\n // A load that fails can start again, such as after the network comes back.\n promise?.catch(() => modules.delete(id));\n return promise;\n };\n // The serial entry loads with the core, so the core can make the values of the app.\n let serialLoad: Promise<SerialEntry> | undefined;\n const loadSerial = (): Promise<SerialEntry> | undefined => {\n serialLoad ??= options.serial?.();\n serialLoad?.catch(() => (serialLoad = undefined));\n return serialLoad;\n };\n const loadCore = (): Promise<Core> =>\n (core ??= Promise.all([load(), loadSerial()]).then(([client, serial]) => {\n client.init({ ...options, load: loadModule, listen: scanInsert, inserted, serial });\n return client;\n }));\n\n // The devtools panel asks for the core when it opens, so it can show the page before any event.\n listen(document, 'brumate:core', () => void loadCore());\n\n const run = (element: Element, ref: string, event?: Event): void => {\n if (stopped) {\n return;\n }\n void loadCore().then((client) => client.handle(element, ref, event));\n };\n\n /**\n * A key of `prevent` matches its `event.key` while only the modifier that it names is held. A\n * key alone matches while Ctrl, Meta and Alt are up, so the shortcuts of the browser, such as\n * Cmd+Left or Alt+Left, keep their default. `Mod+` is Ctrl or Meta. Shift does not count. A\n * single letter after a modifier matches in either case, as the browser sends `k` for Cmd+K and\n * `K` for Cmd+Shift+K. A letter alone keeps its case, as `a` and `A` type different text.\n */\n const keyMatches = (key: string, event: KeyboardEvent): boolean => {\n const plus = key.indexOf('+', 1);\n const modifier = plus > 0 ? key.slice(0, plus) : '';\n let name = plus > 0 ? key.slice(plus + 1) : key;\n let pressed = event.key === ' ' ? 'Space' : event.key;\n if (plus > 0 && name.length === 1) {\n name = name.toLowerCase();\n pressed = pressed.toLowerCase();\n }\n if (pressed !== name) {\n return false;\n }\n switch (modifier) {\n case 'Mod':\n return (event.ctrlKey || event.metaKey) && !event.altKey;\n case 'Ctrl':\n return event.ctrlKey && !event.metaKey && !event.altKey;\n case 'Meta':\n return event.metaKey && !event.ctrlKey && !event.altKey;\n case 'Alt':\n return event.altKey && !event.ctrlKey && !event.metaKey;\n default:\n return !event.ctrlKey && !event.metaKey && !event.altKey;\n }\n };\n\n const apply = (event: Event, element: Element, entry: Entry): boolean => {\n for (const modifier of entry.modifiers) {\n // `prevent(ArrowDown,Enter)` prevents only these keys, by `event.key`. A key that commits\n // or moves within the text of an input method, such as Enter while it composes, is the\n // input method's, so it keeps its default.\n if (\n modifier === 'prevent' ||\n (modifier.startsWith('prevent(') &&\n !(event as KeyboardEvent).isComposing &&\n modifier\n .slice(8, -1)\n .split(',')\n .some((key) => keyMatches(key, event as KeyboardEvent)))\n ) {\n event.preventDefault();\n }\n }\n if (entry.modifiers.includes('once')) {\n element.setAttribute(\n 'b-on',\n entries(element)\n .map((item) => item.raw)\n .filter((raw) => raw !== entry.raw)\n .join(' '),\n );\n }\n run(element, entry.ref, event);\n return entry.modifiers.includes('stop');\n };\n\n /**\n * Handlers run as if each element had its own listener: those with\n * `capture` from the outside in, then the others from the target outwards.\n * An event that does not bubble, such as `focus`, reaches only the others\n * of its target. `stop` ends the event where it is.\n */\n const onEvent = (event: Event): void => {\n // The checks of `cancelWhen`, from the target up, run before any handler.\n for (let node = event.target as Node | null; node; node = node.parentNode) {\n for (const [type, check] of cancels.get(node as Element) ?? []) {\n if (type !== event.type) {\n continue;\n }\n let cancel = false;\n try {\n cancel = check(event);\n } catch (error) {\n // A check that throws cancels nothing, and the other checks and the handlers still run.\n console.error(error);\n }\n if (cancel) {\n event.preventDefault();\n return;\n }\n }\n }\n const path: Element[] = [];\n for (\n let node = event.target as Node | null;\n node && node !== document;\n node = node.parentNode\n ) {\n if (node.nodeType === 1 && (node as Element).hasAttribute('b-on')) {\n path.push(node as Element);\n }\n }\n const phase = (elements: Element[], capture: boolean): boolean => {\n for (const element of elements) {\n let stop = false;\n for (const entry of entries(element)) {\n if (\n entry.type === event.type &&\n entry.modifiers.includes('capture') === capture &&\n apply(event, element, entry)\n ) {\n stop = true;\n }\n }\n if (stop) {\n event.stopPropagation();\n return true;\n }\n }\n return false;\n };\n if (!phase([...path].reverse(), true)) {\n phase(event.bubbles ? path : path.filter((element) => element === event.target), false);\n }\n };\n\n // The checks of `cancelWhen`, by element. `events.ts` reaches them through a symbol of the registry.\n const cancels = new WeakMap<Node, Set<[string, (event: Event) => boolean]>>();\n (globalThis as { [key: symbol]: unknown })[Symbol.for('brumate.cancel')] = (\n element: Element,\n type: string,\n check: (event: Event) => boolean,\n ): (() => void) => {\n const entry: [string, typeof check] = [type, check];\n let set = cancels.get(element);\n if (!set) {\n cancels.set(element, (set = new Set()));\n }\n set.add(entry);\n delegate(type, false);\n return () => void set.delete(entry);\n };\n\n /** True for an entry that prevents the default action, which a passive listener cannot do. */\n const prevents = (entry: Entry): boolean =>\n entry.modifiers.some((modifier) => modifier.startsWith('prevent'));\n\n /**\n * Listens to an event type on the document. The listener is passive, so\n * scrolling does not wait for it, until an entry of the type prevents. `click` and `submit` never\n * scroll, so they are never passive: a `prevent` that is written after load cancels them.\n */\n const delegate = (type: string, cancel: boolean): void => {\n const prevent = cancel || type === 'click' || type === 'submit';\n const passive = types.get(type);\n if (passive === false || (passive === true && !prevent)) {\n return;\n }\n if (passive) {\n document.removeEventListener(type, onEvent, true);\n }\n types.set(type, !prevent);\n listen(document, type, onEvent, { capture: true, passive: !prevent });\n };\n\n // Templates are started once, even when markup is scanned again.\n const started = new WeakSet<Element>();\n const select = (root: ParentNode, selector: string): Element[] => {\n const found: Element[] = [];\n const add = (element: Element): void => {\n if (element.tagName === 'TEMPLATE') {\n if (started.has(element)) {\n return;\n }\n started.add(element);\n }\n found.push(element);\n };\n if ((root as Element).matches?.(selector)) {\n add(root as Element);\n }\n for (const element of root.querySelectorAll(selector)) {\n add(element);\n }\n return found;\n };\n\n // The values of `b-on` whose event types the document listens to already. The rows of a\n // list repeat the same few values.\n const delegated = new Set<string>();\n const onElement = (element: Element): void => {\n const value = element.getAttribute('b-on')!;\n if (!delegated.has(value)) {\n delegated.add(value);\n for (const entry of entries(element)) {\n delegate(entry.type, prevents(entry));\n }\n }\n };\n const onListener = (template: Element): void => {\n const target = template.getAttribute('b-listen') === 'window' ? window : document;\n for (const entry of entries(template)) {\n // Markup that is gone, such as a page that navigation replaced, no longer listens.\n listen(\n target,\n entry.type,\n (event) => {\n if (template.isConnected) {\n apply(event, template, entry);\n }\n },\n { capture: entry.modifiers.includes('capture'), passive: !prevents(entry) },\n );\n }\n };\n // A `#defer` block whose body the server sends in the same response, with `b-hole`, waits for it.\n const onBlock = (root: ParentNode, template: Element): void => {\n const client = template.getAttribute('b-client');\n const [trigger, ref] = (client ?? template.getAttribute('b-defer')!).split(\n client ? '=' : ':',\n ) as [string, string];\n // A `#defer` block asks the server for its body, with a module that only it needs.\n const go = (): void => {\n if (client) {\n run(template, ref);\n return;\n }\n const done = import('./defer.ts').then((module) => module.loadDeferred(template));\n if (DEV) {\n devtools()?.defer?.(template, done);\n }\n };\n // The element that a `$client` callback reads through `ref` (`b-b`), or that a component\n // forwards to its signal (`b-r`), or the one after the marker.\n // Other markers can follow it, and a template has no box, so it is never in view.\n const near = template.getAttribute('b-near');\n let after = template.nextElementSibling;\n while (after?.tagName === 'TEMPLATE') {\n after = after.nextElementSibling;\n }\n const selector = `[b-b=\"${near}\"],[b-r=\"${near}\"]`;\n const next =\n (near && (root.querySelector(selector) ?? document.querySelector(selector))) || after;\n if (trigger === 'idle') {\n idle(go);\n } else if (trigger === 'visible' && next && typeof IntersectionObserver !== 'undefined') {\n const observer = new IntersectionObserver((records) => {\n if (records.some((record) => record.isIntersecting)) {\n observer.disconnect();\n go();\n }\n });\n observer.observe(next);\n } else {\n go();\n }\n };\n const SCANNED = '[b-on],template[b-listen],template[b-client],template[b-defer]';\n // One query of the markup for everything that the loader starts. The blocks start after the\n // rest, as they did when each kind had its own query.\n const scan = (root: ParentNode): void => {\n if (stopped) {\n return;\n }\n const blocks: Element[] = [];\n for (const element of select(root, SCANNED)) {\n if (element.tagName === 'TEMPLATE') {\n if (HAS_LISTENERS && element.hasAttribute('b-listen')) {\n onListener(element);\n } else if (\n HAS_BLOCKS &&\n (element.hasAttribute('b-client') ||\n (element.hasAttribute('b-defer') && !element.hasAttribute('b-hole')))\n ) {\n blocks.push(element);\n }\n continue;\n }\n if (element.hasAttribute('b-on')) {\n onElement(element);\n }\n }\n for (const template of blocks) {\n onBlock(root, template);\n }\n };\n\n // A form of an `$action` sends its data with `fetch`, and the core writes the result into the page.\n listen(document, 'submit', (event) => {\n const form = event.target as HTMLFormElement;\n if (!HAS_ACTIONS || event.defaultPrevented || !form.hasAttribute?.('b-result')) {\n return;\n }\n event.preventDefault();\n const submitter = (event as SubmitEvent).submitter;\n void loadCore().then((client) => client.submitAction(form, submitter));\n });\n\n if (navigate) {\n load = navigate({ options, listen, core: () => core, start: loadCore, scan });\n } else {\n // A hot update whose markup changed loads the page again.\n listen(document, 'brumate:reload', () => location.reload());\n }\n\n scan(document);\n // Markup that streams in later, such as a `#loading` body, has handlers too.\n const scanAdded = (records: MutationRecord[]): void => {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeType === 1) {\n scan(node as Element);\n }\n }\n }\n };\n // Without markup that others insert, the core scans all that comes into the page. The rest of\n // the page that the browser reads after an `async` script starts is scanned when it ends.\n const observer = HAS_LATE_MARKUP ? new MutationObserver(scanAdded) : undefined;\n observer?.observe(document, { childList: true, subtree: true });\n if (!HAS_LATE_MARKUP && document.readyState === 'loading') {\n listen(document, 'DOMContentLoaded', () => scan(document));\n }\n // The core scans the markup that it inserts before the insert, so the records of the insert\n // are dropped instead of scanned again. The markup that others inserted first is scanned\n // first.\n const scanInsert = (root: ParentNode): void => {\n if (observer) {\n scanAdded(observer.takeRecords());\n }\n scan(root);\n };\n const inserted = (): void => {\n observer?.takeRecords();\n };\n\n // The core starts at once and loads the code of the components on the page, so a call of a\n // function of another component, such as a function prop, runs at once and in order.\n void loadCore().catch(() => {});\n return () => {\n stopped = true;\n observer?.disconnect();\n for (const remove of removers.splice(0)) {\n remove();\n }\n void core?.then((client) => client.dispose());\n };\n}\n","// The loader without client navigation, for `navigate: false`. It is a module\n// of its own, so a bundle that starts it has no import of the navigation code,\n// and keeps none of the core's exports that only navigation reads.\n\nimport { boot } from './boot.ts';\nimport type { LoaderOptions } from './boot.ts';\n\nexport type { LoaderOptions } from './boot.ts';\n\n/**\n * `start` for a site that loads every page with a full page load, as with\n * `navigate: false`. A bundle that only calls it leaves out the code of\n * client navigation.\n */\nexport function startWithoutNavigation(options: LoaderOptions): () => void {\n return boot(options);\n}\n"],"mappings":";;;AAcA,MAAM,MAAO,YAA4C,KAAK;;AAG9D,SAAS,WAAsC;CAC7C,OAAQ,WAAyD,OAAO,IAAI,kBAAkB;AAChG;AA0DA,MAAM,yBAAS,IAAI,IAAqB;AAExC,SAAgB,QAAQ,SAA2B;CACjD,MAAM,QAAQ,QAAQ,aAAa,MAAM,KAAK;CAC9C,OAAQ,OAAO,IAAI,KAAK,KACtB,OACG,IACC,OACA,MACG,MAAM,GAAG,CAAC,CACV,OAAO,OAAO,CAAC,CACf,KAAK,UAAU;EACd,MAAM,CAAC,MAAM,OAAO,MAAM,MAAM,GAAG;EACnC,MAAM,CAAC,MAAM,GAAG,aAAa,KAAK,MAAM,GAAG;EAC3C,OAAO;GAAE,KAAK;GAAO;GAAM;GAAW;EAAI;CAC5C,CAAC,CACL,CAAC,CACA,IAAI,KAAK;AAChB;;;;;AASA,IAAI;AACJ,MAAa,mBACV,gBAAgB,OAAO,sBAAc,CAAC,MACpC,WAAW,OAAO,SAClB,UAAmB;CAElB,cAAc,KAAA;CACd,MAAM;AACR,CACF;;AAGF,MAAM,QAAQ,QAA6B,OAAO,uBAAuB,WAAA,CAAY,EAAE;;;;;;;AAuBvF,SAAgB,KACd,SACA,UACY;CACZ,IAAI;CAIJ,IAAI,UAAU;;CAEd,MA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ets, 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
+ const BRIDGES = Symbol.for("brumate.bridges");
110
+ const BRIDGE_LOAD = Symbol.for("brumate.bridge-load");
111
+ /** The bridges by name, which any copy of the runtime shares. */
112
+ function bridges() {
113
+ return globalThis[BRIDGES] ??= /* @__PURE__ */ new Map();
114
+ }
115
+ /**
116
+ * Sets how the browser loads the module of a bridge, and where a failed load is reported. The
117
+ * core calls it when it starts.
118
+ */
119
+ function setBridgeLoader(...loader) {
120
+ globalThis[BRIDGE_LOAD] = loader;
121
+ }
122
+ /** The module of a bridge, from its name. */
123
+ function bridgeModule(id) {
124
+ return id.slice(0, id.lastIndexOf("#"));
125
+ }
126
+ /**
127
+ * Makes a bridge. Keep its value in a module-level export, so the page state can name it:
128
+ * `export const bears = bridge({ … })`. The compiler gives it its name.
129
+ */
130
+ function bridge(options) {
131
+ const made = Object.assign((snapshot) => new Bridged(made, options.create(snapshot)), { b: options });
132
+ return made;
133
+ }
134
+ /** Gives a bridge its name, which the compiler writes at the end of its module. */
135
+ function nameBridge(made, id) {
136
+ made.i = id;
137
+ bridges().set(id, made);
138
+ }
139
+ /** True for a store of `bridge()`, of any copy of the runtime. */
140
+ function isBridged(value) {
141
+ return typeof value === "object" && value !== null && value.k === "brumate.bridge";
142
+ }
143
+ /**
144
+ * Whether two values hold the same data: the same value, or arrays and plain objects whose items
145
+ * hold the same data. A store that the browser makes again holds a new object with the content
146
+ * the server sent, which needs no repair.
147
+ */
148
+ function sameData(a, b, open) {
149
+ if (Object.is(a, b)) return true;
150
+ const array = Array.isArray(a);
151
+ if (array ? !Array.isArray(b) || a.length !== b.length : !isPlain(a) || !isPlain(b)) return false;
152
+ const left = a;
153
+ const right = b;
154
+ open ??= /* @__PURE__ */ new Map();
155
+ let pairs = open.get(left);
156
+ if (pairs?.has(right)) return true;
157
+ if (!pairs) {
158
+ pairs = /* @__PURE__ */ new Set();
159
+ open.set(left, pairs);
160
+ }
161
+ pairs.add(right);
162
+ const keys = Object.keys(left);
163
+ if (!array && keys.length !== Object.keys(right).length) return false;
164
+ for (const key of keys) if (!(key in right) || !sameData(left[key], right[key], open)) return false;
165
+ return true;
166
+ }
167
+ /** Whether a value is an object of `Object` or of no prototype, as page state holds. */
168
+ function isPlain(value) {
169
+ if (typeof value !== "object" || value === null) return false;
170
+ const proto = Object.getPrototypeOf(value);
171
+ return proto === Object.prototype || proto === null;
172
+ }
173
+ /**
174
+ * The store that a bridge makes. On the server it holds the library's store from the start. In
175
+ * the browser the page state makes it with the name of the bridge and the data of the server, and
176
+ * it makes the library's store at its first subscriber.
177
+ */
178
+ var Bridged = class {
179
+ /** The mark of a bridged store, which `isBridged` reads in every copy of the runtime. */
180
+ k = "brumate.bridge";
181
+ /** The bridge. Undefined for a store of the page state until the module of the bridge loads. */
182
+ f;
183
+ /** The name of the bridge, for a store of the page state. */
184
+ i;
185
+ /** The library's store. */
186
+ s;
187
+ /** True once the library's store exists. */
188
+ m = false;
189
+ /** The data that the server sent, until the library's store exists. */
190
+ v;
191
+ /** Whether the bridge has `set`, as the server sent it, until the module loads. */
192
+ w;
193
+ constructor(made, source, id, snapshot, writable) {
194
+ this.f = made;
195
+ this.i = id;
196
+ this.v = snapshot;
197
+ this.w = writable;
198
+ if (made) {
199
+ this.s = source;
200
+ this.m = true;
201
+ }
202
+ }
203
+ /**
204
+ * The library's store. In the browser it is undefined until the store has a subscriber and the
205
+ * module of the bridge has loaded.
206
+ */
207
+ get source() {
208
+ return this.s;
209
+ }
210
+ /** The name of the bridge. */
211
+ get id() {
212
+ return this.f?.i ?? this.i;
213
+ }
214
+ /** The data of the store: what `get` reads, or what the server sent before the first subscriber. */
215
+ get() {
216
+ return this.m ? this.f.b.get(this.s) : this.v;
217
+ }
218
+ /**
219
+ * Calls `listener` with the data when it changes. The first subscriber makes the library's
220
+ * store in the browser. When the module of the bridge has not loaded, the subscription starts
221
+ * when it has.
222
+ */
223
+ subscribe(listener, ...seen) {
224
+ let stopped = false;
225
+ let stop;
226
+ let last = seen.length > 0 ? seen[0] : this.get();
227
+ const start = () => {
228
+ if (stopped) return;
229
+ const options = this.f.b;
230
+ const source = this.make();
231
+ stop = options.subscribe(source, () => {
232
+ const next = options.get(source);
233
+ if (!sameData(next, last)) {
234
+ last = next;
235
+ listener(next);
236
+ }
237
+ });
238
+ const first = options.get(source);
239
+ if (!sameData(first, last)) {
240
+ last = first;
241
+ listener(first);
242
+ }
243
+ };
244
+ if (this.find()) start();
245
+ else this.load().then((loaded) => loaded && start());
246
+ return () => {
247
+ stopped = true;
248
+ stop?.();
249
+ };
250
+ }
251
+ /** Writes the library's store, when the bridge has `set`. */
252
+ get set() {
253
+ return (this.find() ? !!this.f.b.set : this.w !== false) ? (value) => this.write(value) : void 0;
254
+ }
255
+ /** Writes the library's store, after the module of the bridge has loaded. */
256
+ write(value) {
257
+ if (this.find()) this.f.b.set(this.make(), value);
258
+ else this.load().then((loaded) => loaded && this.write(value));
259
+ }
260
+ /** The bridge, once its module has loaded. */
261
+ find() {
262
+ if (!this.f && this.i !== void 0) this.f = bridges().get(this.i);
263
+ return this.f;
264
+ }
265
+ /** Loads the module of the bridge. A failure goes to the core's error path; it gives false. */
266
+ load() {
267
+ const [load, report] = globalThis[BRIDGE_LOAD] ?? [];
268
+ return Promise.resolve(load?.(bridgeModule(this.i))).then(() => {
269
+ if (this.find()) return true;
270
+ 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({ … })"`));
271
+ return false;
272
+ }, (error) => {
273
+ this.fail(report, error);
274
+ return false;
275
+ });
276
+ }
277
+ fail(report, error) {
278
+ if (report) report(error);
279
+ else console.error(error);
280
+ }
281
+ /** Makes the library's store once, with the data of the server. */
282
+ make() {
283
+ if (!this.m) {
284
+ this.s = this.f.b.create(this.v);
285
+ this.m = true;
286
+ }
287
+ return this.s;
288
+ }
289
+ };
290
+ //#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 };
292
+
293
+ //# sourceMappingURL=store-BIBAYZo-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-BIBAYZo-.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// 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,IA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