@tschk/moonshine-svelte 0.4.4 → 0.4.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,18 +10,24 @@ exports `crepusRenderer` with the framework's `Renderer` contract. The framework
10
10
  remains optional for runtime imports and bridge-only browser/Bun/Node bundles.
11
11
  This requirement does not apply to the signal-only `@tschk/moonshine` core entry.
12
12
 
13
- | Subpath | Provides |
14
- | ---------- | ------------------------------------------------------------------- |
15
- | `.` | signal bridges and lazy native SSR compatibility renderer |
16
- | `./svelte` | lifecycle, context, typed `createContext`, component event dispatch |
17
- | `./class` | opt-in `classValue` normalization for source class expressions |
18
- | `./store` | independent `writable`, `readable`, `derived`, and `get` |
13
+ | Subpath | Provides |
14
+ | ---------- | -------------------------------------------------------------------------------------------- |
15
+ | `.` | signal bridges and lazy native SSR compatibility renderer |
16
+ | `./svelte` | lifecycle, context, typed `createContext`, component event dispatch |
17
+ | `./class` | opt-in `classValue` and `classDirectives` for source classes |
18
+ | `./store` | independent `writable`, `readable`, `readonly`, `derived`, `get`, `toStore`, and `fromStore` |
19
19
 
20
20
  `classValue` flattens nested class arrays and includes truthy object keys. Empty
21
21
  results return `undefined`, omitting the DOM/SSR attribute. Top-level primitive
22
22
  values retain Svelte 5.57 stringification; nested falsy values are omitted. This
23
- helper does not change ordinary native `h()` attributes or implement class/style
24
- directives.
23
+ helper does not change ordinary native `h()` attributes.
24
+
25
+ `classDirectives(base, hash, flags)` normalizes the base, appends an optional scope
26
+ hash, then applies own class flags in order. Truthy flags append tokens; false
27
+ flags remove matching tokens, including a matching hash. The local Crepus compiler
28
+ uses it for authored intrinsic `class:` directives, including dynamic elements.
29
+ Source parsing and independent input memoization belong to Crepus; this helper
30
+ does not execute Svelte's compiled component instructions or implement style directives.
25
31
 
26
32
  The optional `/runes` entry exports compiler-facing `createState`, `createDerived`
27
33
  and `createRuneEffect`.
@@ -39,8 +45,79 @@ descriptors once per render pass. Getters remain lazy and read from the merged
39
45
  object; symbols and inherited properties are omitted. DOM and SSR spread helpers
40
46
  intentionally have different contracts. The native SFC gate verifies bounded component spread lowering, including
41
47
  call-expression caching, live rest props, explicit children and component
42
- references. Implicit body/legacy slots, element spreads and hydration remain
43
- unverified.
48
+ references. Intrinsic forwarding has the separate bounded contract below.
49
+ Implicit body/legacy slots and hydration remain unverified.
50
+
51
+ ### Native intrinsic attribute forwarding
52
+
53
+ The local unpublished Crepuscularity compiler now lowers spreads on ordinary
54
+ static HTML elements through independent Moonshine helpers. This includes a
55
+ wrapper's live `$props()` rest object, multiple interspersed layers, removed keys,
56
+ and named attributes that override or fall back when spread keys disappear.
57
+ `installElementSpread` on `/runes` owns DOM updates and direct event listeners;
58
+ `installBoundElementSpread` installs compiler-owned binding callbacks once between
59
+ capture and ordinary input/change listeners, without filtering spread-provided
60
+ live values. Details toggle handlers precede their binding write;
61
+ `spreadServerEntries` on `/ssr` supplies explicit server attribute entries.
62
+ The local form-spread work adds `spreadServerElement` for input defaults and
63
+ typed select/option identity; these form helpers require Moonshine 0.4.40 or newer.
64
+ Component prop spreads keep their existing contract.
65
+
66
+ Each layer expression and enumerable getter runs once per update/render in
67
+ source order, including overridden values. Function data is not invoked.
68
+ Class values use the source class normalizer; spread style values use string
69
+ coercion, not the native DOM factory's object-style API. Event handler replacement
70
+ retains a stable listener; removal and owner disposal release it. Listeners are
71
+ direct rather than Svelte's delegated events. Mixed-case event-like attribute
72
+ strings are filtered consistently with native SSR, which is stricter than Svelte.
73
+ DOM content-replacement keys reject before mutation. String-valued `ref` and
74
+ `children` remain attributes and do not replace template children.
75
+
76
+ The locally verified compiler also admits unbound input/select/option/textarea
77
+ spreads. DOM values remain separate from reset defaults; option and input values
78
+ use Moonshine's typed stores. Selects reconcile live/default selection after
79
+ children mount and observe inserted options. An authored fixture matches Svelte
80
+ in five Chromium phases and repeated SSR; an isolated Bun/Node source regression
81
+ checks typed option identity. This does not establish full form compatibility.
82
+
83
+ The local compiler also combines spreads with input/textarea `bind:value`,
84
+ checkbox `bind:checked`, select `bind:value`, static file-input `bind:files`,
85
+ and static checkbox/radio `bind:group`.
86
+ Authored input/checkbox/select/file/group
87
+ fixtures match Svelte in Chromium and repeated SSR, including handler order and
88
+ typed selections. File SSR preserves authored attributes without reading the
89
+ bound model. The local compiler additionally admits spread `bind:open` on details. This
90
+ requires Moonshine 0.4.41 or newer: existing toggle
91
+ handlers run before the binding write; handlers removed and re-added follow
92
+ ordinary listener registration order. Authored Chromium and six SSR renders
93
+ cover this bounded path. Spread `bind:group` requires a static `type="checkbox"`
94
+ or `type="radio"` attribute; spread-only `value` changes update the input value
95
+ without re-evaluating `checked` until the group model or an authored dynamic
96
+ `value={expr}` updates, and SSR derives `checked` at the `bind:group` position
97
+ only when an authored `value` attribute is present.
98
+
99
+ Source admission still rejects spreads on title, dynamic or namespaced/custom
100
+ elements, and combinations with actions,
101
+ attachments, class/style directives or scoped CSS. Attachment symbols and
102
+ autofocus behavior are not implemented by this helper. Hydration and arbitrary
103
+ precompiled Svelte instructions remain unsupported.
104
+
105
+ The authored wrapper matches Svelte 5.57.1 through five Chromium update phases,
106
+ including two independent instances, attribute fallback, clicks, node/focus
107
+ retention and disposal. Repeated SSR and isolated Bun/Node source tests verify
108
+ getter order and attribute output without installing a host runtime. These checks do
109
+ not establish complete source compatibility.
110
+
111
+ Reproduce the form SSR comparison with
112
+ `bun scripts/benchmark-svelte-form-ssr.ts --compiler /path/to/crepus`
113
+ from the repository root. Use `--svelte /path/to/installed/svelte` when the
114
+ reference package is installed outside the root resolver. It runs seven
115
+ alternating fresh Bun processes, 1,000 warmups and 5,000 timed renders per
116
+ process, and reports minified bundle bytes, first-render and process wall time.
117
+ Process wall time includes warmup/workload and is not startup-only. The measured
118
+ native form bundle is smaller, while its repeated SSR is slower than Svelte
119
+ 5.57.1 in this workload. Machine contention is uncontrolled; this does not
120
+ establish a general speed or size ranking.
44
121
 
45
122
  Lifecycle helpers require a live native owner. `onMount` runs untracked in a
46
123
  microtask after synchronous DOM insertion; a synchronous returned function is
@@ -472,3 +549,47 @@ behavior/type tests and bounded private-class source acceptance in the shared
472
549
  shared source gate.
473
550
 
474
551
  The optional `/mount` entry freshly mounts compiler-marked native SFC factories and returns their synchronous typed exports. It supports owned teardown, target-local anchors and copied root contexts; `/server-mount` rejects client mounting on the server. Hydration, transitions/outros, legacy event options and error transforms remain unsupported and reject explicitly. Both boolean `intro` values are accepted for sources without transitions. The erased `ComponentView<View, Exports, Props>` return metadata and `ComponentFactory<Implementation>` callable type preserve required/optional props and export types. Generated public functions must also preserve ESM hoisting. Public mounting checks metadata props rather than an implementation parameter typed `any`. The standalone `scripts/check-native-svelte-mount.ts --compiler <path>` source check verifies 28 generated modules with frozen compiler `703ceb65`: unchanged authored launchers, typed synchronous exports, two independent instances, anchor/context/cleanup behavior, DOM-free server imports and real Bun/Node ESM cycles. The combined await/source gate currently uses a separate compiler snapshot; merging those compiler lineages remains open. Declaration emission for setup-local interfaces is also unfinished.
552
+
553
+ `readonly(store)` exposes only a bound `subscribe`, preserving custom store
554
+ receivers, invalidators and cleanup. Writes through the original store still
555
+ notify its subscribers. This facade does not freeze stored values. `toStore(get,
556
+ set?)` bridges reactive state into a `Readable` or `Writable` store with eager
557
+ initial evaluation, post-order Rune effect scheduling on the client, independent
558
+ root survival across component disposal while subscribers remain active, and
559
+ one-shot `writable(get())` behavior on SSR. `fromStore(store)` bridges a
560
+ `Readable` or `Writable` store (or `{ subscribe }` observable) into a `{ current }`
561
+ reactive wrapper, sharing one store subscription across tracked readers and
562
+ derived chains on the client, releasing after a microtask when demand drops to
563
+ zero, and reading via `get(store)` outside tracking or on SSR. Authored
564
+ `svelte/store` named imports, aliases and re-exports of `readonly`, `toStore`
565
+ and `fromStore` are admitted by the locally verified Crepus compiler for DOM and
566
+ SSR. That compiler change is not published yet; the direct Moonshine `/store`
567
+ API is available independently.
568
+
569
+ The optional `/binding` entry re-exports native `bindFiles` for independent
570
+ file-input factories. Nullish models preserve selected files; clearing requires
571
+ an empty `FileList`. Change and connected-form reset write the current list.
572
+ Disposal removes listeners, including on retained detached inputs; Svelte's
573
+ reference can still update its model from those saved elements. The locally
574
+ verified Crepus compiler lowers authored `bind:files` on static file inputs with
575
+ identifier/member targets, including keyed rows. SSR omits the value without
576
+ reading it and retains unreachable checks for typed assignments/change handlers.
577
+ Function bindings, dynamic input types, spreads and hydration remain unsupported.
578
+ This compiler change is unpublished and requires the `bindFiles` runtime from
579
+ Moonshine 0.4.13 or newer.
580
+
581
+ The locally verified Crepus compiler also lowers `bind:open` on static HTML
582
+ `<details>` elements through the existing independent `bindOpen` helper. Shorthand,
583
+ state/prop identifiers, member targets, writable stores, keyed rows and imported
584
+ child bindings have DOM/SSR source coverage. User `ontoggle` handlers run before
585
+ the binding write, and member-based handlers are read at dispatch. SSR snapshots
586
+ the boolean `open` attribute without installing listeners or running handlers.
587
+ Nullish state closes the element without adopting its DOM state.
588
+
589
+ This compiler work remains unpublished. Function-pair targets, dynamic elements,
590
+ other element types, duplicate bindings and conflicting `open` attributes reject.
591
+ Native owner cleanup removes listeners even from saved detached nodes; the
592
+ Svelte 5.57.1 reference retains them. This is bounded authored-source support,
593
+ without hydration or Svelte's compiled component ABI. Set
594
+ `MOONSHINE_CREPUS_COMPILER` to the local compiler to enable the isolated source
595
+ regression in `test/standalone.test.ts`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-svelte",
3
- "version": "0.4.4",
3
+ "version": "0.4.49",
4
4
  "description": "Independent Svelte store and native lifecycle APIs with Moonshine signal bridges",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -27,14 +27,14 @@
27
27
  "./const": "./src/const-derived.ts"
28
28
  },
29
29
  "dependencies": {
30
- "@tschk/moonshine": "^0.4.4",
31
- "@tschk/moonshine-dom": "^0.4.4"
30
+ "@tschk/moonshine": "^0.4.48",
31
+ "@tschk/moonshine-dom": "^0.4.48"
32
32
  },
33
33
  "devDependencies": {
34
34
  "typescript": "7.0.2"
35
35
  },
36
36
  "peerDependencies": {
37
- "@tschk/moonshine-framework": "^0.4.4"
37
+ "@tschk/moonshine-framework": "^0.4.48"
38
38
  },
39
39
  "peerDependenciesMeta": {
40
40
  "@tschk/moonshine-framework": {
package/src/binding.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  import { captureRuneReferenceCleanup } from "./pre";
20
20
  export {
21
21
  bindChecked,
22
+ bindFiles,
22
23
  bindOpen,
23
24
  setOptionValue,
24
25
  setInputValue,
@@ -34,10 +35,10 @@ export function bindSelectValue(
34
35
  }
35
36
 
36
37
  export function createInputGroup(
37
- kind: "radio" | "checkbox",
38
+ kind: "radio" | "checkbox" | "mixed",
38
39
  read: () => unknown,
39
40
  write: (value: unknown) => void,
40
- ): { bind(input: HTMLInputElement): void } {
41
+ ): { bind(input: HTMLInputElement, watch?: () => unknown): void } {
41
42
  return nativeCreateInputGroup(kind, read, write, stateEquals);
42
43
  }
43
44
 
package/src/class.ts CHANGED
@@ -19,3 +19,60 @@ export function classValue(value: unknown): string | undefined {
19
19
  append(value);
20
20
  return tokens.join(" ") || undefined;
21
21
  }
22
+
23
+ function isClassWhitespace(code: number): boolean {
24
+ return (
25
+ code === 0x20 ||
26
+ (code >= 0x09 && code <= 0x0d) ||
27
+ code === 0xa0 ||
28
+ code === 0xfeff
29
+ );
30
+ }
31
+
32
+ /** Host-free class directive application over a classValue-normalized base. */
33
+ export function classDirectives(
34
+ value: unknown,
35
+ hash: string | null | undefined,
36
+ directives: Readonly<Record<string, unknown>>,
37
+ ): string | undefined {
38
+ const names = Object.keys(directives);
39
+ for (const name of names) {
40
+ let blank = true;
41
+ for (let index = 0; index < name.length; index++) {
42
+ if (!isClassWhitespace(name.charCodeAt(index))) {
43
+ blank = false;
44
+ break;
45
+ }
46
+ }
47
+ if (blank) {
48
+ throw new TypeError(
49
+ `Class directive name must contain a non-whitespace character: ${JSON.stringify(name)}`,
50
+ );
51
+ }
52
+ }
53
+ let result = classValue(value) ?? "";
54
+ if (hash) result = result ? `${result} ${hash}` : hash;
55
+ for (const name of names) {
56
+ if (directives[name]) {
57
+ result = result ? `${result} ${name}` : name;
58
+ continue;
59
+ }
60
+ const width = name.length;
61
+ let from = 0;
62
+ while (result.length > 0) {
63
+ const start = result.indexOf(name, from);
64
+ if (start < 0) break;
65
+ const end = start + width;
66
+ if (
67
+ (start === 0 || isClassWhitespace(result.charCodeAt(start - 1))) &&
68
+ (end === result.length || isClassWhitespace(result.charCodeAt(end)))
69
+ ) {
70
+ // The delimiter after the removed token is consumed with it.
71
+ result = result.slice(0, start) + result.slice(end + 1);
72
+ } else {
73
+ from = end;
74
+ }
75
+ }
76
+ }
77
+ return result || undefined;
78
+ }
package/src/effect.ts CHANGED
@@ -17,6 +17,7 @@ import { peekComponentContext } from "@tschk/moonshine-dom/component";
17
17
  import { flushComponentReferences } from "@tschk/moonshine-dom/component-instance";
18
18
 
19
19
  import { holdHistory, releaseHistory, withHistoryCleanup } from "./history";
20
+ import { notifyTrackableUnsubscribe } from "./store-demand";
20
21
  import { queueTickWork, removeTickWork } from "./tick-queue";
21
22
 
22
23
  const pending = new Set<() => void>();
@@ -168,6 +169,7 @@ export function createRuneEffect(fn: () => void | (() => void)): void {
168
169
  const cleanup = stopRun as (() => void) | undefined;
169
170
  stopRun = undefined;
170
171
  untrack(() => cleanup?.());
172
+ notifyTrackableUnsubscribe();
171
173
  if (failed) throw failure;
172
174
  return;
173
175
  }
@@ -184,12 +186,16 @@ export function createRuneEffect(fn: () => void | (() => void)): void {
184
186
  }),
185
187
  );
186
188
  for (const [dependency, unsubscribe] of subscriptions)
187
- if (!next.has(dependency)) unsubscribe();
189
+ if (!next.has(dependency)) {
190
+ unsubscribe();
191
+ notifyTrackableUnsubscribe();
192
+ }
188
193
  });
189
194
  subscriptions = next;
190
195
  } catch (error) {
191
196
  for (const [dependency, unsubscribe] of next)
192
197
  if (!subscriptions.has(dependency)) unsubscribe();
198
+ notifyTrackableUnsubscribe();
193
199
  if (!failed) failure = error;
194
200
  failed = true;
195
201
  }
@@ -234,6 +240,7 @@ export function createRuneEffect(fn: () => void | (() => void)): void {
234
240
  }
235
241
  subscriptions.clear();
236
242
  stopRun = undefined;
243
+ notifyTrackableUnsubscribe();
237
244
  if (failed) throw failure;
238
245
  });
239
246
  enqueue();
package/src/pre.ts CHANGED
@@ -29,11 +29,14 @@ import {
29
29
  import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
30
30
  import { flushComponentReferences } from "@tschk/moonshine-dom/component-instance";
31
31
  import { holdHistory, releaseHistory, withHistoryCleanup } from "./history";
32
+ import { notifyTrackableUnsubscribe } from "./store-demand";
32
33
  import { queueTickWork, removeTickWork } from "./tick-queue";
33
34
  const runeConsumerKey = /* @__PURE__ */ Symbol("moonshine.svelte.consumer");
34
35
  const runeNodeKey = /* @__PURE__ */ Symbol("moonshine.svelte.node");
35
36
  type Node = {
36
37
  source?: true;
38
+ independentRoot?: true;
39
+ hasRenderChild?: true;
37
40
  componentCap?: Node;
38
41
  referenceTail?: { owner: Owner; callbacks: Array<() => void> };
39
42
  consumer?: ComponentContext;
@@ -48,6 +51,8 @@ type Node = {
48
51
  };
49
52
  type Job = Node & { run: () => void };
50
53
  function node(owner: Owner, parent?: Node, phase?: Node["phase"]): Node {
54
+ if (parent && (phase === "render" || phase === "structural"))
55
+ parent.hasRenderChild = true;
51
56
  return {
52
57
  owner,
53
58
  parent,
@@ -129,8 +134,10 @@ export function flushRuneWork(): void {
129
134
  flush();
130
135
  }
131
136
  function alive(job: Job): boolean {
132
- for (let next: Node | undefined = job; next; next = next.parent)
137
+ for (let next: Node | undefined = job; next; next = next.parent) {
133
138
  if (next.disposed || next.owner.disposed) return false;
139
+ if (next.independentRoot) return true;
140
+ }
134
141
  return true;
135
142
  }
136
143
  function compare(a: Node, b: Node): number {
@@ -175,6 +182,7 @@ let preDepth = 0;
175
182
  let inPost = false;
176
183
  let inPublication = false;
177
184
  let currentStructural: Job | undefined;
185
+ let initializingJob: Job | undefined;
178
186
  function flush() {
179
187
  removeTickWork(flushRuneWork);
180
188
  flushing = true;
@@ -510,6 +518,8 @@ function ownedJob(
510
518
  } catch (error) {
511
519
  if (!unsubscribeFailed) unsubscribeFailure = error;
512
520
  unsubscribeFailed = true;
521
+ } finally {
522
+ notifyTrackableUnsubscribe();
513
523
  }
514
524
  }
515
525
  if (unsubscribeFailed) {
@@ -545,10 +555,17 @@ function ownedJob(
545
555
  failed = true;
546
556
  }
547
557
  }
558
+ notifyTrackableUnsubscribe();
548
559
  if (failed) throw failure;
549
560
  }
550
561
  onCleanup(shutdown);
551
- runWithPhase();
562
+ const previousInitializingJob = initializingJob;
563
+ initializingJob = job;
564
+ try {
565
+ runWithPhase();
566
+ } finally {
567
+ initializingJob = previousInitializingJob;
568
+ }
552
569
  }
553
570
  /** Internal const evaluation provenance; synthetic scheduler groups inherit it. */
554
571
  export function getRuneConsumer(): ComponentContext | undefined {
@@ -669,3 +686,64 @@ export function createRunePreEffect(fn: () => void | (() => void)): void {
669
686
  if (!scheduler) throw Error("Pre effects require withRuneScheduler");
670
687
  scheduler.pre(fn);
671
688
  }
689
+ export type RuneToStoreScope = {
690
+ readonly owner: Owner | null;
691
+ readonly node: Node | undefined;
692
+ };
693
+ export function captureRuneToStoreScope(): RuneToStoreScope {
694
+ return { owner: getOwner(), node: runeNode() };
695
+ }
696
+ export function createRuneToStoreEffect(
697
+ captured: RuneToStoreScope,
698
+ fn: () => void,
699
+ ): () => void {
700
+ if (isSSRRendering() || peekComponentContext()?.mode === "ssr")
701
+ return () => {};
702
+ return runWithOwner(
703
+ captured.owner && !captured.owner.disposed ? captured.owner : null,
704
+ () =>
705
+ createRoot((stop) => {
706
+ const owner = getOwner()!;
707
+ const parent =
708
+ captured.node &&
709
+ !captured.node.disposed &&
710
+ !captured.node.owner.disposed
711
+ ? captured.node
712
+ : undefined;
713
+ const group = node(
714
+ owner,
715
+ parent,
716
+ parent?.hasRenderChild ? "render" : "pre",
717
+ );
718
+ group.independentRoot = true;
719
+ if (parent) {
720
+ if (initializingJob?.parent === parent) {
721
+ initializingJob.order = parent.next++;
722
+ }
723
+ runWithOwner(parent.owner, () =>
724
+ onCleanup(() => {
725
+ if (group.parent === parent) {
726
+ group.parent = undefined;
727
+ queueRoot(group);
728
+ jobsDirty = true;
729
+ }
730
+ }),
731
+ );
732
+ }
733
+ onCleanup(() => {
734
+ group.disposed = true;
735
+ });
736
+ owner.context = new Map(owner.context);
737
+ owner.context.delete(cleanupOrderKey);
738
+ owner.context.set(renderSchedulerKey, carrier(group));
739
+ const previous = current;
740
+ current = group;
741
+ try {
742
+ ownedJob(fn, group.phase === "pre" ? "pre" : "render", group);
743
+ } finally {
744
+ current = previous;
745
+ }
746
+ return () => runWithOwner(owner, () => withHistoryCleanup(stop));
747
+ }),
748
+ );
749
+ }
package/src/runes.ts CHANGED
@@ -5,6 +5,10 @@ export { createDerived } from "./derived";
5
5
  export { createProp } from "./prop";
6
6
  export { createRawState } from "./raw-state";
7
7
  export { spreadProps } from "./spread-props";
8
+ export {
9
+ installElementSpread,
10
+ installBoundElementSpread,
11
+ } from "./spread-element-dom";
8
12
  export {
9
13
  createPrivateState,
10
14
  createPrivateRawState,
@@ -0,0 +1,343 @@
1
+ import { sourceAttributeValue } from "@tschk/moonshine-dom/attributes";
2
+ import { setInputValue, setOptionValue } from "@tschk/moonshine-dom/binding";
3
+ import {
4
+ createComponentScope,
5
+ createRenderEffect,
6
+ getOwner,
7
+ getRenderScheduler,
8
+ onAfterDispose,
9
+ onCleanup,
10
+ runWithOwner,
11
+ templateRetentionKey,
12
+ untrack,
13
+ } from "@tschk/moonshine-dom/reactive";
14
+ import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
15
+ import { peekComponentContext } from "@tschk/moonshine-dom/component";
16
+ import { classValue } from "./class";
17
+ import { withHistoryCleanup } from "./history";
18
+ import { createSpreadSelect } from "./spread-select";
19
+
20
+ const ATTRIBUTE_NAME = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
21
+ const CONTENT = /* @__PURE__ */ new Set([
22
+ "innerhtml",
23
+ "outerhtml",
24
+ "textcontent",
25
+ "innertext",
26
+ ]);
27
+ const ALIASES: Record<string, string> = {
28
+ formnovalidate: "formNoValidate",
29
+ ismap: "isMap",
30
+ nomodule: "noModule",
31
+ playsinline: "playsInline",
32
+ readonly: "readOnly",
33
+ defaultvalue: "defaultValue",
34
+ defaultchecked: "defaultChecked",
35
+ srcobject: "srcObject",
36
+ novalidate: "noValidate",
37
+ allowfullscreen: "allowFullscreen",
38
+ disablepictureinpicture: "disablePictureInPicture",
39
+ disableremoteplayback: "disableRemotePlayback",
40
+ };
41
+
42
+ type Handler = (this: unknown, event: Event) => unknown;
43
+ interface Listener {
44
+ type: string;
45
+ capture: boolean;
46
+ handler: Handler;
47
+ wrapper: (this: unknown, event: Event) => unknown;
48
+ }
49
+
50
+ function install(fn: () => void): void {
51
+ if (isSSRRendering() || peekComponentContext()?.mode === "ssr") return;
52
+ const owner = getOwner(),
53
+ scheduler = getRenderScheduler();
54
+ if (!owner || owner.disposed || !scheduler)
55
+ throw Error("Native directives require a live owner and withRuneScheduler");
56
+ createComponentScope(() => scheduler.branch(fn));
57
+ }
58
+
59
+ function cleanup(fn: () => void): void {
60
+ const finish = () => withHistoryCleanup(() => untrack(fn));
61
+ const owner = getOwner();
62
+ if (owner?.disposed) finish();
63
+ else if (owner?.context?.has(templateRetentionKey))
64
+ onCleanup(() => runWithOwner(owner, finish));
65
+ else onAfterDispose(finish);
66
+ }
67
+
68
+ function setters(element: Element): Set<string> {
69
+ const found = new Set<string>();
70
+ const stop = Element.prototype;
71
+ for (
72
+ let proto: object | null = element;
73
+ proto && proto !== stop;
74
+ proto = Object.getPrototypeOf(proto)
75
+ ) {
76
+ const descriptors = Object.getOwnPropertyDescriptors(proto);
77
+ for (const key of Object.keys(descriptors))
78
+ if (descriptors[key]!.set && !CONTENT.has(key.toLowerCase()))
79
+ found.add(key);
80
+ }
81
+ return found;
82
+ }
83
+
84
+ /** Eager null-prototype merge: every thunk and getter is read exactly once, later layers win. */
85
+ function snapshot(layers: readonly unknown[]): Record<string, unknown> {
86
+ const merged: Record<string, unknown> = Object.create(null);
87
+ for (let index = 0; index < layers.length; index++) {
88
+ const layer = layers[index];
89
+ const source = typeof layer === "function" ? layer() : layer;
90
+ if (source != null) Object.assign(merged, source);
91
+ }
92
+ return merged;
93
+ }
94
+
95
+ /**
96
+ * Ordinary HTML intrinsic spread for compiler-owned DOM output.
97
+ * Events attach directly (no delegation) with Svelte's case-preserving names and `capture` suffix.
98
+ * Namespaces, custom elements, autofocus and scoped directives remain unsupported.
99
+ */
100
+ export function installElementSpread(
101
+ element: Element,
102
+ ...layers: unknown[]
103
+ ): void {
104
+ installSpread(element, [], layers);
105
+ }
106
+
107
+ /** Compiler-owned bindings install once; details toggle handlers precede binding writes. */
108
+ export function installBoundElementSpread<T extends Element>(
109
+ element: T,
110
+ bindings: readonly ((element: T) => void)[],
111
+ ...layers: unknown[]
112
+ ): void {
113
+ installSpread(
114
+ element,
115
+ bindings.map((bind) => () => bind(element)),
116
+ layers,
117
+ );
118
+ }
119
+
120
+ function installSpread(
121
+ element: Element,
122
+ bindings: readonly (() => void)[],
123
+ layers: readonly unknown[],
124
+ ): void {
125
+ install(() => {
126
+ const scope = getOwner()!;
127
+ const bindAfterEvents = element.tagName === "DETAILS";
128
+ const bindAll = () =>
129
+ runWithOwner(scope, () =>
130
+ untrack(() => {
131
+ for (const bind of bindings) bind();
132
+ }),
133
+ );
134
+ const applied = new Map<string, unknown>();
135
+ const listeners = new Map<string, Listener>();
136
+ let known: Set<string> | undefined;
137
+ const input =
138
+ element.tagName === "INPUT" ? (element as HTMLInputElement) : undefined;
139
+ const valueElement =
140
+ input ??
141
+ (element.tagName === "TEXTAREA"
142
+ ? (element as HTMLTextAreaElement)
143
+ : undefined);
144
+ let initial = true;
145
+ const select =
146
+ element.tagName === "SELECT"
147
+ ? createSpreadSelect(element as HTMLSelectElement, (run) => {
148
+ if (bindings.length) run();
149
+ else getRenderScheduler()!.post(run);
150
+ })
151
+ : undefined;
152
+ if (select) cleanup(select.dispose);
153
+
154
+ const release = (key: string): void => {
155
+ const listener = listeners.get(key);
156
+ if (!listener) return;
157
+ listeners.delete(key);
158
+ element.removeEventListener(listener.type, listener.wrapper, {
159
+ capture: listener.capture,
160
+ });
161
+ };
162
+
163
+ cleanup(() => {
164
+ for (const key of listeners.keys()) release(key);
165
+ applied.clear();
166
+ });
167
+
168
+ createRenderEffect(() => {
169
+ const merged = snapshot(layers);
170
+ const attributes = new Map<string, unknown>();
171
+ const events = new Map<string, unknown>();
172
+ const keys = Object.keys(merged);
173
+ for (let index = 0; index < keys.length; index++) {
174
+ const key = keys[index]!;
175
+ const value = merged[key];
176
+ if (key.startsWith("$$")) continue;
177
+ if (key.length > 2 && key.startsWith("on")) {
178
+ events.set(key, value);
179
+ continue;
180
+ }
181
+ // Keep the native SSR event filter: never install inline handler strings.
182
+ if (/^on/i.test(key)) continue;
183
+ const name = key.toLowerCase();
184
+ if (CONTENT.has(name))
185
+ throw new TypeError(
186
+ `Spread attribute ${JSON.stringify(key)} would overwrite element content`,
187
+ );
188
+ if (typeof value === "function" || !ATTRIBUTE_NAME.test(key)) continue;
189
+ attributes.set(
190
+ key,
191
+ key === "class"
192
+ ? classValue(value)
193
+ : name === "style" && value != null
194
+ ? String(value)
195
+ : value,
196
+ );
197
+ }
198
+
199
+ // Missing raw keys follow current keys, including case variants of one HTML name.
200
+ for (const key of applied.keys()) {
201
+ if (!attributes.has(key)) attributes.set(key, null);
202
+ }
203
+ if (
204
+ input &&
205
+ attributes.has("type") &&
206
+ (attributes.has("value") || attributes.has("__value"))
207
+ ) {
208
+ const type = attributes.get("type");
209
+ if (
210
+ applied.get("type") !== type ||
211
+ (type === undefined && input.hasAttribute("type"))
212
+ ) {
213
+ if (type == null) input.removeAttribute("type");
214
+ else input.setAttribute("type", String(type));
215
+ applied.set("type", type);
216
+ }
217
+ }
218
+ for (const [key, value] of attributes) {
219
+ const name = key.toLowerCase();
220
+ if (select && (key === "value" || key === "defaultValue")) {
221
+ if (
222
+ key === "value" &&
223
+ (!applied.has(key) || applied.get(key) !== value)
224
+ )
225
+ (element as HTMLSelectElement).value =
226
+ value == null ? "" : String(value);
227
+ applied.set(key, value);
228
+ continue;
229
+ }
230
+ if (element.tagName === "OPTION" && key === "value") {
231
+ // Spread option null/removal means the empty typed value, not label fallback.
232
+ if (value == null || !applied.has(key) || applied.get(key) !== value)
233
+ setOptionValue(element as HTMLOptionElement, value ?? "");
234
+ applied.set(key, value);
235
+ continue;
236
+ }
237
+ if (
238
+ applied.has(key) &&
239
+ applied.get(key) === value &&
240
+ !(value === undefined && element.hasAttribute(name))
241
+ )
242
+ continue;
243
+ if (element.tagName === "OPTION" && key === "selected") {
244
+ if (value) element.setAttribute("selected", "");
245
+ else element.removeAttribute("selected");
246
+ applied.set(key, value);
247
+ continue;
248
+ }
249
+ if (
250
+ valueElement &&
251
+ (key === "__value" || (key === "value" && value != null))
252
+ ) {
253
+ if (input) setInputValue(input, value, !bindings.length);
254
+ else valueElement.value = value as string;
255
+ } else if (input && name === "defaultchecked") {
256
+ input.defaultChecked = value as boolean;
257
+ } else if (input && name === "checked" && value == null) {
258
+ const reset = input.defaultChecked;
259
+ input.removeAttribute(name);
260
+ input.defaultChecked = reset;
261
+ input.checked = initial ? reset : false;
262
+ } else if (valueElement && name === "defaultvalue") {
263
+ valueElement.defaultValue = value as string;
264
+ } else if (valueElement && name === "value" && value == null) {
265
+ const reset = valueElement.defaultValue;
266
+ valueElement.removeAttribute(name);
267
+ valueElement.defaultValue = reset;
268
+ const next = initial ? reset : null;
269
+ if (input) setInputValue(input, next, !bindings.length);
270
+ else valueElement.value = next ?? "";
271
+ } else if (input && name === "checked" && typeof value !== "string") {
272
+ input.checked = value as boolean;
273
+ } else if (
274
+ input &&
275
+ typeof value === "boolean" &&
276
+ (known ??= setters(element)).has(ALIASES[name] ?? name)
277
+ ) {
278
+ (input as unknown as Record<string, unknown>)[ALIASES[name] ?? name] =
279
+ value;
280
+ } else if (value == null) {
281
+ element.removeAttribute(name);
282
+ } else if (name === "style") {
283
+ (element as HTMLElement).style.cssText = value as string;
284
+ } else {
285
+ const property = ALIASES[name] ?? name;
286
+ if (
287
+ typeof value !== "string" &&
288
+ typeof value !== "boolean" &&
289
+ (known ??= setters(element)).has(property)
290
+ ) {
291
+ (element as unknown as Record<string, unknown>)[property] = value;
292
+ } else {
293
+ const text =
294
+ name === "class"
295
+ ? (value as string)
296
+ : sourceAttributeValue(name, value, true);
297
+ if (text === undefined) element.removeAttribute(name);
298
+ else element.setAttribute(name, text);
299
+ }
300
+ }
301
+ applied.set(key, value);
302
+ }
303
+ select?.update(attributes);
304
+
305
+ for (const key of listeners.keys())
306
+ if (typeof events.get(key) !== "function") release(key);
307
+ for (const capturePhase of [true, false]) {
308
+ if (!capturePhase && initial && bindings.length && !bindAfterEvents)
309
+ bindAll();
310
+ for (const [key, value] of events) {
311
+ if (typeof value !== "function") continue;
312
+ const eventType = key.slice(2);
313
+ const eventCapture =
314
+ eventType.endsWith("capture") &&
315
+ eventType !== "gotpointercapture" &&
316
+ eventType !== "lostpointercapture";
317
+ if (eventCapture !== capturePhase) continue;
318
+ const existing = listeners.get(key);
319
+ if (existing) {
320
+ existing.handler = value as Handler;
321
+ continue;
322
+ }
323
+ let type = eventType;
324
+ const capture = eventCapture;
325
+ if (capture) type = type.slice(0, -7);
326
+ if (!type) continue;
327
+ const listener: Listener = {
328
+ type,
329
+ capture,
330
+ handler: value as Handler,
331
+ wrapper(this: unknown, event: Event) {
332
+ return listener.handler.call(this, event);
333
+ },
334
+ };
335
+ listeners.set(key, listener);
336
+ element.addEventListener(type, listener.wrapper, { capture });
337
+ }
338
+ }
339
+ if (initial && bindings.length && bindAfterEvents) bindAll();
340
+ initial = false;
341
+ });
342
+ });
343
+ }
@@ -0,0 +1,106 @@
1
+ import { sourceAttributeValue } from "@tschk/moonshine-dom/attributes";
2
+ import { classValue } from "./class";
3
+ import {
4
+ hAttributeEntries,
5
+ hSelectionEntries,
6
+ type SSRChild,
7
+ } from "@tschk/moonshine-dom/ssr";
8
+
9
+ const ATTRIBUTE_NAME = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
10
+ const EVENT_NAME = /^on/i;
11
+
12
+ /** Compiler-owned form spread; selection retains source identity through lazy SSR children. */
13
+ export function spreadServerElement(
14
+ tag: "input" | "textarea" | "select" | "option",
15
+ layers: readonly unknown[],
16
+ ...children: SSRChild[]
17
+ ): SSRChild {
18
+ const merged = merge(layers);
19
+ if (tag === "select") {
20
+ return hSelectionEntries(
21
+ "select",
22
+ entriesFromMerged(merged, "select"),
23
+ {
24
+ value: merged.value === undefined ? merged.defaultValue : merged.value,
25
+ preserveSelected: true,
26
+ },
27
+ ...children,
28
+ );
29
+ }
30
+ if (tag === "option" && Object.hasOwn(merged, "value"))
31
+ return hSelectionEntries(
32
+ "option",
33
+ entriesFromMerged(merged),
34
+ { value: merged.value },
35
+ ...children,
36
+ );
37
+ return hAttributeEntries(
38
+ tag,
39
+ entriesFromMerged(merged, tag === "input" ? "input" : undefined),
40
+ ...children,
41
+ );
42
+ }
43
+
44
+ /**
45
+ * Ordinary HTML intrinsic spread for compiler-owned `hAttributeEntries` output.
46
+ * Layers merge eagerly like JS object spread, so each getter runs exactly once.
47
+ * Pass `"input"` for input defaults; other form elements need their own lowering.
48
+ */
49
+ export function spreadServerEntries(
50
+ layers: readonly unknown[],
51
+ element?: "input",
52
+ ): readonly (readonly [string, string | undefined])[] {
53
+ return entriesFromMerged(merge(layers), element);
54
+ }
55
+
56
+ function merge(layers: readonly unknown[]): Record<string, unknown> {
57
+ // A null prototype keeps `__proto__` and inherited names ordinary data.
58
+ const merged: Record<string | symbol, unknown> = Object.create(null);
59
+ for (let index = 0; index < layers.length; index++) {
60
+ const layer = layers[index];
61
+ if (layer != null) Object.assign(merged, layer);
62
+ }
63
+ return merged;
64
+ }
65
+
66
+ function entriesFromMerged(
67
+ merged: Record<string, unknown>,
68
+ element?: "input" | "select",
69
+ ): readonly (readonly [string, string | undefined])[] {
70
+ const entries: Array<readonly [string, string | undefined]> = [];
71
+ const keys = Object.keys(merged);
72
+ let loweredKeys: string[] | undefined;
73
+ for (let index = 0; index < keys.length; index++) {
74
+ const key = keys[index]!;
75
+ if (element === "select" && (key === "value" || key === "defaultValue"))
76
+ continue;
77
+ const value = merged[key];
78
+ // Functions, event handlers and internal or invalid names are never attributes.
79
+ if (typeof value === "function" || !ATTRIBUTE_NAME.test(key)) continue;
80
+ if (EVENT_NAME.test(key)) continue;
81
+ let name = key.toLowerCase();
82
+ if (
83
+ element === "input" &&
84
+ (name === "defaultvalue" || name === "defaultchecked")
85
+ ) {
86
+ name = name === "defaultvalue" ? "value" : "checked";
87
+ // Presence wins even for nullish values, functions and differently cased keys.
88
+ if (
89
+ Object.hasOwn(merged, name) ||
90
+ (loweredKeys ??= keys.map((candidate) =>
91
+ candidate.toLowerCase(),
92
+ )).includes(name)
93
+ )
94
+ continue;
95
+ }
96
+ entries.push([
97
+ name,
98
+ sourceAttributeValue(
99
+ name,
100
+ key === "class" ? classValue(value) : value,
101
+ true,
102
+ ),
103
+ ]);
104
+ }
105
+ return entries;
106
+ }
@@ -0,0 +1,86 @@
1
+ import { optionValue } from "@tschk/moonshine-dom/binding";
2
+ import { stateEquals } from "./state";
3
+
4
+ /** Compiler-owned select reconciliation, using the native typed-option store. */
5
+ export function createSpreadSelect(
6
+ select: HTMLSelectElement,
7
+ enqueue: (run: () => void) => void,
8
+ ): {
9
+ update: (attributes: ReadonlyMap<string, unknown>) => void;
10
+ dispose: () => void;
11
+ } {
12
+ let attributes: ReadonlyMap<string, unknown> = new Map();
13
+ let initialized = false,
14
+ active = true,
15
+ defaultApplied = false;
16
+ let previousDefault: unknown;
17
+ function reconcile(mounting = false, optionsChanged = false): void {
18
+ if (!active) return;
19
+ const options = Array.from(select.options);
20
+ const defaultValue = attributes.get("defaultValue");
21
+ if (
22
+ attributes.has("defaultValue") &&
23
+ (!defaultApplied || previousDefault !== defaultValue || optionsChanged)
24
+ ) {
25
+ const preserve =
26
+ !optionsChanged && (defaultApplied || attributes.has("value"));
27
+ const index = select.selectedIndex;
28
+ const selected = new Set(options.filter((option) => option.selected));
29
+ for (const option of options) {
30
+ const matches = select.multiple
31
+ ? Array.isArray(defaultValue) &&
32
+ defaultValue.includes(optionValue(option))
33
+ : stateEquals(optionValue(option), defaultValue);
34
+ if (matches) {
35
+ if (!option.hasAttribute("selected"))
36
+ option.setAttribute("selected", "");
37
+ } else option.removeAttribute("selected");
38
+ }
39
+ if (preserve) {
40
+ if (select.multiple)
41
+ for (const option of options) option.selected = selected.has(option);
42
+ else select.selectedIndex = index;
43
+ }
44
+ previousDefault = defaultValue;
45
+ defaultApplied = true;
46
+ }
47
+ if (!mounting && !attributes.has("value")) return;
48
+ const value = attributes.get("value");
49
+ if (select.multiple) {
50
+ if (value == null || !Array.isArray(value)) return;
51
+ for (const option of options)
52
+ option.selected = value.includes(optionValue(option));
53
+ } else {
54
+ const found = options.find((option) =>
55
+ stateEquals(optionValue(option), value),
56
+ );
57
+ if (found) found.selected = true;
58
+ else if (!mounting || value !== undefined) select.selectedIndex = -1;
59
+ }
60
+ }
61
+ const observer = new MutationObserver(() => {
62
+ if (initialized) reconcile(false, true);
63
+ });
64
+ observer.observe(select, {
65
+ childList: true,
66
+ subtree: true,
67
+ attributes: true,
68
+ attributeFilter: ["value"],
69
+ });
70
+ return {
71
+ update(next) {
72
+ attributes = next;
73
+ if (initialized) reconcile();
74
+ else
75
+ enqueue(() => {
76
+ if (!active || initialized) return;
77
+ reconcile(true);
78
+ initialized = true;
79
+ });
80
+ },
81
+ dispose() {
82
+ active = false;
83
+ observer.disconnect();
84
+ },
85
+ };
86
+ }
package/src/ssr.ts CHANGED
@@ -2,6 +2,10 @@
2
2
  export { createServerProp } from "./server-prop";
3
3
  export { afterRender, settle } from "@tschk/moonshine-dom/ssr";
4
4
  export { spreadServerProps } from "./spread-props";
5
+ export {
6
+ spreadServerEntries,
7
+ spreadServerElement,
8
+ } from "./spread-element-server";
5
9
  export {
6
10
  setStoreValue,
7
11
  mutateServerStore,
@@ -0,0 +1,18 @@
1
+ const demandChecks = new Set<() => void>();
2
+ let demandCheckScheduled = false;
3
+
4
+ export function registerDemandCheck(check: () => void): () => void {
5
+ demandChecks.add(check);
6
+ return () => {
7
+ demandChecks.delete(check);
8
+ };
9
+ }
10
+
11
+ export function notifyTrackableUnsubscribe(): void {
12
+ if (!demandChecks.size || demandCheckScheduled) return;
13
+ demandCheckScheduled = true;
14
+ queueMicrotask(() => {
15
+ demandCheckScheduled = false;
16
+ for (const check of Array.from(demandChecks)) check();
17
+ });
18
+ }
@@ -0,0 +1,145 @@
1
+ import { createSignal, untrack } from "@tschk/moonshine";
2
+ import {
3
+ collectDeps,
4
+ hasValueDemand,
5
+ isTracking,
6
+ } from "@tschk/moonshine/tracking";
7
+ import { peekComponentContext } from "@tschk/moonshine-dom/component";
8
+ import { getOwner, onCleanup, type Owner } from "@tschk/moonshine-dom/reactive";
9
+ import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
10
+ import {
11
+ recordHistory,
12
+ trackHistoryRead,
13
+ withHistoryMutation,
14
+ } from "./history";
15
+ import { captureRuneToStoreScope, createRuneToStoreEffect } from "./pre";
16
+ import {
17
+ get as getStoreValue,
18
+ writable,
19
+ type Readable,
20
+ type Unsubscriber,
21
+ type Writable,
22
+ } from "./store";
23
+ import {
24
+ notifyTrackableUnsubscribe,
25
+ registerDemandCheck,
26
+ } from "./store-demand";
27
+ import { subscribeTo } from "./store-internal";
28
+
29
+ const trackedOwners = /* @__PURE__ */ new WeakSet<Owner>();
30
+
31
+ export function toStore<V>(get: () => V, set: (v: V) => void): Writable<V>;
32
+ export function toStore<V>(get: () => V): Readable<V>;
33
+ export function toStore<V>(
34
+ get: () => V,
35
+ set?: (v: V) => void,
36
+ ): Writable<V> | Readable<V> {
37
+ const captured = captureRuneToStoreScope();
38
+ const server = isSSRRendering() || peekComponentContext()?.mode === "ssr";
39
+ const initValue = get();
40
+ const store = server
41
+ ? writable(initValue)
42
+ : writable(initValue, (setStore) => {
43
+ if (isSSRRendering() || peekComponentContext()?.mode === "ssr") return;
44
+ let ran = initValue !== get();
45
+ const teardown = createRuneToStoreEffect(captured, () => {
46
+ const value = get();
47
+ if (ran) setStore(value);
48
+ });
49
+ ran = true;
50
+ return teardown;
51
+ });
52
+ if (set) {
53
+ return {
54
+ set,
55
+ update: (fn) => set(fn(get())),
56
+ subscribe: store.subscribe,
57
+ };
58
+ }
59
+ return {
60
+ subscribe: store.subscribe,
61
+ };
62
+ }
63
+
64
+ export function fromStore<V>(store: Writable<V>): { current: V };
65
+ export function fromStore<V>(store: Readable<V>): { readonly current: V };
66
+ export function fromStore<V>(
67
+ store: Writable<V> | Readable<V>,
68
+ ): { current: V } | { readonly current: V } {
69
+ let value = undefined as V;
70
+ let stop: Unsubscriber | undefined;
71
+ let unregisterDemand: (() => void) | undefined;
72
+ const version = createSignal(0);
73
+ const versionNode = collectDeps(() => version())[0]!;
74
+ const originalSubscribe = versionNode.subscribe;
75
+ versionNode.subscribe = (...args) => {
76
+ const unsubscribe = originalSubscribe(...args);
77
+ return () => {
78
+ unsubscribe();
79
+ notifyTrackableUnsubscribe();
80
+ };
81
+ };
82
+
83
+ function current(): V {
84
+ if (
85
+ !isSSRRendering() &&
86
+ peekComponentContext()?.mode !== "ssr" &&
87
+ isTracking() &&
88
+ !getOwner()?.disposed
89
+ ) {
90
+ const owner = getOwner();
91
+ if (owner && !trackedOwners.has(owner)) {
92
+ trackedOwners.add(owner);
93
+ onCleanup(notifyTrackableUnsubscribe);
94
+ }
95
+ version();
96
+ trackHistoryRead(version, "value");
97
+ if (!stop) {
98
+ let ran = false;
99
+ stop = untrack(() =>
100
+ subscribeTo(store, (next) => {
101
+ if (ran) {
102
+ withHistoryMutation(() => {
103
+ recordHistory(version, "value", value, next);
104
+ value = next;
105
+ version.set((n) => n + 1);
106
+ });
107
+ } else {
108
+ value = next;
109
+ }
110
+ }),
111
+ );
112
+ ran = true;
113
+ unregisterDemand = registerDemandCheck(() => {
114
+ if (stop && !hasValueDemand(versionNode)) {
115
+ const cleanup = stop;
116
+ stop = undefined;
117
+ unregisterDemand?.();
118
+ unregisterDemand = undefined;
119
+ version.set((n) => n + 1);
120
+ untrack(() => cleanup());
121
+ }
122
+ });
123
+ }
124
+ return value;
125
+ }
126
+ return getStoreValue(store);
127
+ }
128
+
129
+ if ("set" in store) {
130
+ return {
131
+ get current() {
132
+ return current();
133
+ },
134
+ set current(v: V) {
135
+ store.set(v);
136
+ },
137
+ };
138
+ }
139
+
140
+ return {
141
+ get current() {
142
+ return current();
143
+ },
144
+ };
145
+ }
package/src/store.ts CHANGED
@@ -101,6 +101,11 @@ export function readable<T>(
101
101
  return { subscribe: writable(initial, start).subscribe };
102
102
  }
103
103
 
104
+ /** Expose subscriptions without forwarding a store's mutation methods. */
105
+ export function readonly<T>(store: Readable<T>): Readable<T> {
106
+ return { subscribe: store.subscribe.bind(store) };
107
+ }
108
+
104
109
  type Stores = Readable<any> | readonly Readable<any>[];
105
110
  type Values<S> =
106
111
  S extends Readable<infer T>
@@ -206,3 +211,5 @@ export function get<T>(store: Readable<T>): T {
206
211
  })();
207
212
  return value;
208
213
  }
214
+
215
+ export { fromStore, toStore } from "./store-interop";