@mmstack/primitives 21.8.4 → 21.9.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.
@@ -4622,8 +4622,11 @@ function toStore(source, { injector, vivify = false, noUnionLeaves = false, ...r
4622
4622
  return idx >= 0 && idx < v.length;
4623
4623
  }
4624
4624
  }
4625
- // nullish node values are routinely descended with vivify on `in` must not throw
4626
- return v == null ? false : Reflect.has(v, prop);
4625
+ // nullish/primitive node values are routinely descended with vivify on or probed
4626
+ // with `in` (e.g. isMutable) `in` must not throw
4627
+ return v == null || (typeof v !== 'object' && typeof v !== 'function')
4628
+ ? false
4629
+ : Reflect.has(v, prop);
4627
4630
  },
4628
4631
  ownKeys() {
4629
4632
  const v = untracked(source);
@@ -6824,6 +6827,9 @@ function stored(fallback, { key, store: providedStore, serialize = JSON.stringif
6824
6827
  writable.key = keySig;
6825
6828
  return writable;
6826
6829
  }
6830
+ function isStored(value) {
6831
+ return 'clear' in value && typeof value.clear === 'function' && 'key' in value;
6832
+ }
6827
6833
 
6828
6834
  /** Op-mode sync for a writable store: hello exchange, then live envelopes. */
6829
6835
  function storeTabSync(sig, opt, bus, injector) {
@@ -7061,6 +7067,125 @@ function tabSync(sig, opt) {
7061
7067
  return sig;
7062
7068
  }
7063
7069
 
7070
+ /**
7071
+ * Wraps any member of the writable-signal family so that every synchronous write
7072
+ * first records an ambient "cause" (via the caller-provided `capture` function)
7073
+ * and then delegates to the original write, preserving the wrapped signal's exact
7074
+ * write semantics. The recorded cause is exposed through a plain {@link Traced.causedBy}
7075
+ * read, letting a downstream consumer attribute a change to whatever caused it —
7076
+ * without any dependency on a particular telemetry system.
7077
+ *
7078
+ * Capture is **synchronous-only** and last-writer-wins: the cause is whatever
7079
+ * `capture()` returns during the `set`/`update`/`mutate`/`inline` call. A write
7080
+ * performed after an `await` (once the ambient cause has been cleared) records
7081
+ * `undefined`; a write while `capture()` returns `undefined` clears the cause.
7082
+ * `causedBy()` is a plain read, not a signal — reading it never subscribes, and
7083
+ * a cause-only change (a write with a different cause but no dependent-visible
7084
+ * value change) never invalidates a consumer.
7085
+ *
7086
+ * The traced twin behaves like the original except for `causedBy`: it carries the
7087
+ * wrapped signal's surface — `asReadonly`, the `mutate`/`inline` methods of a
7088
+ * mutable, and the `from` of a derived — and the underlying write semantics survive
7089
+ * (a traced `derived` still writes through to its source; a traced `toWritable` still
7090
+ * runs its custom `set`). Reads through the twin stay tracked — consumers subscribe
7091
+ * exactly as they would to the source.
7092
+ *
7093
+ * @typeParam S - The wrapped writable-signal type.
7094
+ * @typeParam C - The type of the captured cause.
7095
+ *
7096
+ * @param sig - The writable signal to trace. Any family member is accepted
7097
+ * (`signal`, `mutable`, `derived`, `toWritable`, `stored`, ...).
7098
+ * @param capture - A function invoked synchronously at the start of every write.
7099
+ * Its return value becomes the current cause; returning `undefined`
7100
+ * clears it.
7101
+ * @param opt - Optional configuration.
7102
+ * @param opt.pure - If `true` (the default), the returned twin is a **new** signal
7103
+ * that reads through to `sig`; `sig` itself is left untouched, so
7104
+ * tracing a shared signal never makes the original writable or
7105
+ * alters its behaviour.
7106
+ *
7107
+ * CAUTION: with `pure: false` the write methods are patched
7108
+ * directly onto the `sig` object you passed in — every other
7109
+ * holder of that signal now records causes on write. Only use it
7110
+ * with a signal you created and own exclusively.
7111
+ *
7112
+ * @returns A {@link Traced} twin of `sig` exposing `causedBy()`.
7113
+ *
7114
+ * @example
7115
+ * // A refetch attributing itself to whatever wrote the query.
7116
+ * let activeCause: string | undefined;
7117
+ * const query = traced(signal(''), () => activeCause);
7118
+ *
7119
+ * activeCause = 'user-typed';
7120
+ * query.set('hello');
7121
+ * query.causedBy(); // 'user-typed'
7122
+ *
7123
+ * @example
7124
+ * // Tracing a shared, read-only-exposed signal without making it writable.
7125
+ * const shared = signal(0);
7126
+ * const twin = traced(shared, () => currentInteraction());
7127
+ * twin === shared; // false — the original is untouched
7128
+ */
7129
+ function traced(sig, capture, opt) {
7130
+ const twin = (opt?.pure === false ? sig : facadeOf(sig));
7131
+ let cause;
7132
+ const setOriginal = sig.set.bind(sig);
7133
+ twin.set = (value) => {
7134
+ cause = capture();
7135
+ setOriginal(value);
7136
+ };
7137
+ const updateOriginal = sig.update.bind(sig);
7138
+ twin.update = (updater) => {
7139
+ cause = capture();
7140
+ updateOriginal(updater);
7141
+ };
7142
+ if (isMutable(sig)) {
7143
+ const source = sig;
7144
+ const mutableTwin = twin;
7145
+ const mutateOriginal = source.mutate.bind(source);
7146
+ mutableTwin.mutate = (updater) => {
7147
+ cause = capture();
7148
+ mutateOriginal(updater);
7149
+ };
7150
+ const inlineOriginal = source.inline.bind(source);
7151
+ mutableTwin.inline = (updater) => {
7152
+ cause = capture();
7153
+ inlineOriginal(updater);
7154
+ };
7155
+ }
7156
+ if (isStored(sig)) {
7157
+ const source = sig;
7158
+ const storedTwin = twin;
7159
+ const clearOriginal = source.clear.bind(source);
7160
+ storedTwin.clear = () => {
7161
+ cause = capture();
7162
+ clearOriginal();
7163
+ };
7164
+ }
7165
+ twin.causedBy = () => cause;
7166
+ return twin;
7167
+ }
7168
+ /**
7169
+ * Builds a read-through facade over `sig`: a fresh signal whose reads track `sig`,
7170
+ * carrying `sig`'s non-write surface (`asReadonly`, and `from` on a derived signal)
7171
+ * by explicit delegation. The write methods are attached by {@link traced}. The
7172
+ * facade's `equal` always reports "changed", so it forwards every notification `sig`
7173
+ * emits — including the same-reference `mutate`/`inline` force-notifies that a default
7174
+ * `computed` would swallow (see `mutable`'s docs). The change decision is thereby
7175
+ * delegated entirely to `sig`.
7176
+ */
7177
+ function facadeOf(sig) {
7178
+ const facade = computed(sig, { equal: () => false });
7179
+ facade.asReadonly = sig.asReadonly.bind(sig);
7180
+ if (isDerivation(sig)) {
7181
+ facade.from = sig.from;
7182
+ }
7183
+ if (isStored(sig)) {
7184
+ facade.key = sig.key;
7185
+ }
7186
+ return facade;
7187
+ }
7188
+
7064
7189
  function until(sourceSignal, predicate, options = {}) {
7065
7190
  return new Promise((resolve, reject) => {
7066
7191
  let effectRef;
@@ -7258,5 +7383,5 @@ function withHistory(sourceOrValue, opt) {
7258
7383
  * Generated bundle index. Do not edit.
7259
7384
  */
7260
7385
 
7261
- export { CONCURRENCY_INSTRUMENTATION, MmActivity, MmTransition, MmViewTransitionName, OP_PROTO_VERSION, PAUSABLE_OPTIONS, PERSISTED_STORE_OPTIONS, POS_SEGMENT, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, applyOps, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, compareHlc, compareSiblings, compareTotal, createAttributedPending, createConvergingApply, createForwardingScope, createHlcClock, createStoreContext, createTransaction, createTransitionScope, debounce, debounced, defaultFold, deferredValue, derived, diffOps, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, insertElement, invertBatch, isConflicted, isDerivation, isLeaf, isMutable, isOpaque, isStore, keepPrevious, keyArray, keyedArray, latest, lww, map, mapArray, mapObject, mediaQuery, merge3, mergeThree, mousePosition, moveElement, mutable, mutableStore, nestedEffect, networkStatus, opLog, opSync, opaque, orderedEntries, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, perfCustomTracks, persist, persistedStore, pipeable, piped, pointerDrag, policyStrategy, pooled, pooledArray, pooledMap, pooledSet, posBetween, prefersDarkMode, prefersReducedMotion, preserve, projection, provideConcurrencyInstrumentation, provideForwardingTransitionScope, providePausableOptions, providePaused, providePersistedStoreOptions, provideTransitionScope, rebalanceContainer, rebaseOps, reconcile, registerResource, removeElement, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, storeHistory, stored, syncedFork, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, use, validateEnvelope, windowSize, withHistory };
7386
+ export { CONCURRENCY_INSTRUMENTATION, MmActivity, MmTransition, MmViewTransitionName, OP_PROTO_VERSION, PAUSABLE_OPTIONS, PERSISTED_STORE_OPTIONS, POS_SEGMENT, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, applyOps, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, compareHlc, compareSiblings, compareTotal, createAttributedPending, createConvergingApply, createForwardingScope, createHlcClock, createStoreContext, createTransaction, createTransitionScope, debounce, debounced, defaultFold, deferredValue, derived, diffOps, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, insertElement, invertBatch, isConflicted, isDerivation, isLeaf, isMutable, isOpaque, isStore, isStored, keepPrevious, keyArray, keyedArray, latest, lww, map, mapArray, mapObject, mediaQuery, merge3, mergeThree, mousePosition, moveElement, mutable, mutableStore, nestedEffect, networkStatus, opLog, opSync, opaque, orderedEntries, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, perfCustomTracks, persist, persistedStore, pipeable, piped, pointerDrag, policyStrategy, pooled, pooledArray, pooledMap, pooledSet, posBetween, prefersDarkMode, prefersReducedMotion, preserve, projection, provideConcurrencyInstrumentation, provideForwardingTransitionScope, providePausableOptions, providePaused, providePersistedStoreOptions, provideTransitionScope, rebalanceContainer, rebaseOps, reconcile, registerResource, removeElement, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, storeHistory, stored, syncedFork, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, traced, until, use, validateEnvelope, windowSize, withHistory };
7262
7387
  //# sourceMappingURL=mmstack-primitives.mjs.map