@coherent.js/state 1.1.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/reactive-state.js"],
4
- "sourcesContent": ["/**\n * Reactive State Management System for Coherent.js\n * Provides computed properties, watchers, and reactive updates\n */\n\n// Simple error handling for this module\nexport class StateError extends Error {\n constructor(message, options = {}) {\n super(message);\n this.name = 'StateError';\n this.type = options.type || 'state';\n this.component = options.component;\n this.context = options.context;\n this.timestamp = Date.now();\n }\n}\n\nexport const globalErrorHandler = {\n handle(error, context = {}) {\n console.error('State Error:', error.message, context);\n }\n};\n\n/**\n * Observable wrapper for tracking state changes\n */\nexport class Observable {\n constructor(value, options = {}) {\n this._value = value;\n this._observers = new Set();\n this._computedDependents = new Set();\n this._options = {\n deep: options.deep !== false,\n immediate: options.immediate !== false,\n ...options\n };\n }\n\n get value() {\n // Track dependency for computed properties\n if (Observable._currentComputed) {\n this._computedDependents.add(Observable._currentComputed);\n }\n return this._value;\n }\n\n set value(newValue) {\n if (this._value === newValue && !this._options.deep) {\n return;\n }\n\n const oldValue = this._value;\n this._value = newValue;\n\n // Notify observers\n this._observers.forEach(observer => {\n try {\n observer(newValue, oldValue);\n } catch (_error) {\n globalErrorHandler.handle(_error, {\n type: 'watcher-_error',\n context: { newValue, oldValue }\n });\n }\n });\n\n // Update computed dependents\n this._computedDependents.forEach(computed => {\n computed._invalidate();\n });\n }\n\n watch(callback, options = {}) {\n if (typeof callback !== 'function') {\n throw new StateError('Watch callback must be a function');\n }\n\n const observer = (newValue, oldValue) => {\n callback(newValue, oldValue, () => this.unwatch(observer));\n };\n\n this._observers.add(observer);\n\n // Call immediately if requested\n if (options.immediate !== false) {\n observer(this._value, undefined);\n }\n\n // Return unwatch function\n return () => this.unwatch(observer);\n }\n\n unwatch(observer) {\n this._observers.delete(observer);\n }\n\n unwatchAll() {\n this._observers.clear();\n this._computedDependents.clear();\n }\n}\n\n/**\n * Computed property implementation\n */\nclass Computed extends Observable {\n constructor(getter, options = {}) {\n super(undefined, options);\n this._getter = getter;\n this._cached = false;\n this._dirty = true;\n\n if (typeof getter !== 'function') {\n throw new StateError('Computed getter must be a function');\n }\n }\n\n get value() {\n if (this._dirty || !this._cached) {\n this._compute();\n }\n return this._value;\n }\n\n set value(newValue) {\n throw new StateError('Cannot set value on computed property');\n }\n\n _compute() {\n const prevComputed = Observable._currentComputed;\n Observable._currentComputed = this;\n\n try {\n const newValue = this._getter();\n\n if (newValue !== this._value) {\n const oldValue = this._value;\n this._value = newValue;\n\n // Notify observers\n this._observers.forEach(observer => {\n observer(newValue, oldValue);\n });\n }\n\n this._cached = true;\n this._dirty = false;\n } catch (_error) {\n globalErrorHandler.handle(_error, {\n type: 'computed-_error',\n context: { getter: this._getter.toString() }\n });\n } finally {\n Observable._currentComputed = prevComputed;\n }\n }\n\n _invalidate() {\n this._dirty = true;\n this._computedDependents.forEach(computed => {\n computed._invalidate();\n });\n }\n}\n\n// Static property for tracking current computed\nObservable._currentComputed = null;\n\n/**\n * Reactive state container with advanced features\n */\nexport class ReactiveState {\n constructor(initialState = {}, options = {}) {\n this._state = new Map();\n this._computed = new Map();\n this._watchers = new Map();\n this._middleware = [];\n this._history = [];\n this._options = {\n enableHistory: options.enableHistory !== false,\n maxHistorySize: options.maxHistorySize || 50,\n enableMiddleware: options.enableMiddleware !== false,\n deep: options.deep !== false,\n ...options\n };\n\n // Initialize state\n Object.entries(initialState).forEach(([key, value]) => {\n this.set(key, value);\n });\n }\n\n /**\n * Get reactive state value\n */\n get(key) {\n const observable = this._state.get(key);\n return observable ? observable.value : undefined;\n }\n\n /**\n * Set reactive state value\n */\n set(key, value, options = {}) {\n const config = { ...this._options, ...options };\n\n // Run middleware\n if (config.enableMiddleware) {\n const middlewareResult = this._runMiddleware('set', { key, value, oldValue: this.get(key) });\n if (middlewareResult.cancelled) {\n return false;\n }\n value = middlewareResult.value !== undefined ? middlewareResult.value : value;\n }\n\n // Get or create observable\n let observable = this._state.get(key);\n if (!observable) {\n observable = new Observable(value, config);\n this._state.set(key, observable);\n } else {\n // Record history\n if (config.enableHistory) {\n this._addToHistory('set', key, observable.value, value);\n }\n\n observable.value = value;\n }\n\n return true;\n }\n\n /**\n * Check if state has a key\n */\n has(key) {\n return this._state.has(key);\n }\n\n /**\n * Delete state key\n */\n delete(key) {\n const observable = this._state.get(key);\n if (observable) {\n // Record history\n if (this._options.enableHistory) {\n this._addToHistory('delete', key, observable.value, undefined);\n }\n\n observable.unwatchAll();\n this._state.delete(key);\n return true;\n }\n return false;\n }\n\n /**\n * Clear all state\n */\n clear() {\n // Record history\n if (this._options.enableHistory) {\n this._addToHistory('clear', null, this.toObject(), {});\n }\n\n // Cleanup observables\n for (const observable of this._state.values()) {\n observable.unwatchAll();\n }\n\n this._state.clear();\n this._computed.clear();\n this._watchers.clear();\n }\n\n /**\n * Create computed property\n */\n computed(key, getter, options = {}) {\n if (typeof getter !== 'function') {\n throw new StateError(`Computed property '${key}' getter must be a function`);\n }\n\n const computed = new Computed(getter, { ...this._options, ...options });\n this._computed.set(key, computed);\n\n return computed;\n }\n\n /**\n * Get computed property value\n */\n getComputed(key) {\n const computed = this._computed.get(key);\n return computed ? computed.value : undefined;\n }\n\n /**\n * Watch state changes\n */\n watch(key, callback, options = {}) {\n if (typeof key === 'function') {\n // Watch computed expression\n return this._watchComputed(key, callback, options);\n }\n\n const observable = this._state.get(key);\n if (!observable) {\n throw new StateError(`Cannot watch undefined state key: ${key}`);\n }\n\n const unwatch = observable.watch(callback, options);\n\n // Store watcher for cleanup\n if (!this._watchers.has(key)) {\n this._watchers.set(key, new Set());\n }\n this._watchers.get(key).add(unwatch);\n\n return unwatch;\n }\n\n /**\n * Watch computed expression\n */\n _watchComputed(expression, callback, options = {}) {\n const computed = new Computed(expression, options);\n const unwatch = computed.watch(callback, options);\n\n return unwatch;\n }\n\n /**\n * Batch state updates\n */\n batch(updates) {\n if (typeof updates === 'function') {\n // Batch function updates\n const oldEnableHistory = this._options.enableHistory;\n this._options.enableHistory = false;\n\n try {\n const result = updates(this);\n\n // Record batch in history\n if (oldEnableHistory) {\n this._addToHistory('batch', null, null, this.toObject());\n }\n\n return result;\n } finally {\n this._options.enableHistory = oldEnableHistory;\n }\n } else if (typeof updates === 'object') {\n // Batch object updates\n return this.batch(() => {\n Object.entries(updates).forEach(([key, value]) => {\n this.set(key, value);\n });\n });\n }\n }\n\n /**\n * Subscribe to multiple state changes\n */\n subscribe(keys, callback, options = {}) {\n if (!Array.isArray(keys)) {\n keys = [keys];\n }\n\n const unwatchers = keys.map(key => {\n return this.watch(key, (newValue, oldValue) => {\n callback({\n key,\n newValue,\n oldValue,\n state: this.toObject()\n });\n }, options);\n });\n\n // Return unsubscribe function\n return () => {\n unwatchers.forEach(unwatch => unwatch());\n };\n }\n\n /**\n * Add middleware for state changes\n */\n use(middleware) {\n if (typeof middleware !== 'function') {\n throw new StateError('Middleware must be a function');\n }\n this._middleware.push(middleware);\n }\n\n /**\n * Run middleware chain\n */\n _runMiddleware(action, context) {\n let result = { ...context, cancelled: false };\n\n for (const middleware of this._middleware) {\n try {\n const middlewareResult = middleware(action, result);\n if (middlewareResult) {\n result = { ...result, ...middlewareResult };\n if (result.cancelled) {\n break;\n }\n }\n } catch (_error) {\n globalErrorHandler.handle(_error, {\n type: 'middleware-_error',\n context: { action, middleware: middleware.toString() }\n });\n }\n }\n\n return result;\n }\n\n /**\n * Add action to history\n */\n _addToHistory(action, key, oldValue, newValue) {\n if (!this._options.enableHistory) return;\n\n this._history.unshift({\n action,\n key,\n oldValue,\n newValue,\n timestamp: Date.now()\n });\n\n // Limit history size\n if (this._history.length > this._options.maxHistorySize) {\n this._history = this._history.slice(0, this._options.maxHistorySize);\n }\n }\n\n /**\n * Get state history\n */\n getHistory(limit = 10) {\n return this._history.slice(0, limit);\n }\n\n /**\n * Undo last action\n */\n undo() {\n const lastAction = this._history.shift();\n if (!lastAction) return false;\n\n const { action, key, oldValue } = lastAction;\n\n // Temporarily disable history\n const oldEnableHistory = this._options.enableHistory;\n this._options.enableHistory = false;\n\n try {\n switch (action) {\n case 'set':\n if (oldValue === undefined) {\n this.delete(key);\n } else {\n this.set(key, oldValue);\n }\n break;\n case 'delete':\n this.set(key, oldValue);\n break;\n case 'clear':\n this.clear();\n Object.entries(oldValue || {}).forEach(([k, v]) => {\n this.set(k, v);\n });\n break;\n }\n return true;\n } finally {\n this._options.enableHistory = oldEnableHistory;\n }\n }\n\n /**\n * Convert state to plain object\n */\n toObject() {\n const result = {};\n for (const [key, observable] of this._state.entries()) {\n result[key] = observable.value;\n }\n return result;\n }\n\n /**\n * Convert computed properties to object\n */\n getComputedValues() {\n const result = {};\n for (const [key, computed] of this._computed.entries()) {\n result[key] = computed.value;\n }\n return result;\n }\n\n /**\n * Get state statistics\n */\n getStats() {\n return {\n stateKeys: this._state.size,\n computedKeys: this._computed.size,\n watcherKeys: this._watchers.size,\n historyLength: this._history.length,\n middlewareCount: this._middleware.length\n };\n }\n\n /**\n * Cleanup and destroy\n */\n destroy() {\n // Clear all watchers\n for (const observable of this._state.values()) {\n observable.unwatchAll();\n }\n for (const computed of this._computed.values()) {\n computed.unwatchAll();\n }\n\n // Clear collections\n this._state.clear();\n this._computed.clear();\n this._watchers.clear();\n this._middleware.length = 0;\n this._history.length = 0;\n }\n}\n\n/**\n * Create reactive state store\n */\nexport function createReactiveState(initialState, options = {}) {\n return new ReactiveState(initialState, options);\n}\n\n/**\n * Create observable value\n */\nexport function observable(value, options = {}) {\n return new Observable(value, options);\n}\n\n/**\n * Create computed property\n */\nexport function computed(getter, options = {}) {\n return new Computed(getter, options);\n}\n\n/**\n * Utility functions for common state patterns\n */\nexport const stateUtils = {\n /**\n * Create a toggle state\n */\n toggle(initialValue = false) {\n const obs = observable(initialValue);\n obs.toggle = () => {\n obs.value = !obs.value;\n };\n return obs;\n },\n\n /**\n * Create a counter state\n */\n counter(initialValue = 0) {\n const obs = observable(initialValue);\n obs.increment = (by = 1) => {\n obs.value += by;\n };\n obs.decrement = (by = 1) => {\n obs.value -= by;\n };\n obs.reset = () => {\n obs.value = initialValue;\n };\n return obs;\n },\n\n /**\n * Create an array state with utilities\n */\n array(initialArray = []) {\n const obs = observable([...initialArray]);\n obs.push = (...items) => {\n obs.value = [...obs.value, ...items];\n };\n obs.pop = () => {\n const newArray = [...obs.value];\n const result = newArray.pop();\n obs.value = newArray;\n return result;\n };\n obs.filter = (predicate) => {\n obs.value = obs.value.filter(predicate);\n };\n obs.clear = () => {\n obs.value = [];\n };\n return obs;\n },\n\n /**\n * Create object state with deep reactivity\n */\n object(initialObject = {}) {\n const state = createReactiveState(initialObject, { deep: true });\n return state;\n }\n};\n\nexport default ReactiveState;\n"],
5
- "mappings": ";AAMO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAClC,YAAY,SAAS,UAAU,CAAC,GAAG;AAC/B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,YAAY,QAAQ;AACzB,SAAK,UAAU,QAAQ;AACvB,SAAK,YAAY,KAAK,IAAI;AAAA,EAC9B;AACJ;AAEO,IAAM,qBAAqB;AAAA,EAC9B,OAAO,OAAO,UAAU,CAAC,GAAG;AACxB,YAAQ,MAAM,gBAAgB,MAAM,SAAS,OAAO;AAAA,EACxD;AACJ;AAKO,IAAM,aAAN,MAAM,YAAW;AAAA,EACpB,YAAY,OAAO,UAAU,CAAC,GAAG;AAC7B,SAAK,SAAS;AACd,SAAK,aAAa,oBAAI,IAAI;AAC1B,SAAK,sBAAsB,oBAAI,IAAI;AACnC,SAAK,WAAW;AAAA,MACZ,MAAM,QAAQ,SAAS;AAAA,MACvB,WAAW,QAAQ,cAAc;AAAA,MACjC,GAAG;AAAA,IACP;AAAA,EACJ;AAAA,EAEA,IAAI,QAAQ;AAER,QAAI,YAAW,kBAAkB;AAC7B,WAAK,oBAAoB,IAAI,Y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CAAC,GAAG,YAAY,CAAC;AACxC,QAAI,OAAO,IAAI,UAAU;AACrB,UAAI,QAAQ,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK;AAAA,IACvC;AACA,QAAI,MAAM,MAAM;AACZ,YAAM,WAAW,CAAC,GAAG,IAAI,KAAK;AAC9B,YAAM,SAAS,SAAS,IAAI;AAC5B,UAAI,QAAQ;AACZ,aAAO;AAAA,IACX;AACA,QAAI,SAAS,CAAC,cAAc;AACxB,UAAI,QAAQ,IAAI,MAAM,OAAO,SAAS;AAAA,IAC1C;AACA,QAAI,QAAQ,MAAM;AACd,UAAI,QAAQ,CAAC;AAAA,IACjB;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,gBAAgB,CAAC,GAAG;AACvB,UAAM,QAAQ,oBAAoB,eAAe,EAAE,MAAM,KAAK,CAAC;AAC/D,WAAO;AAAA,EACX;AACJ;AAEA,IAAO,yBAAQ;",
4
+ "sourcesContent": ["/**\n * Reactive State Management System for Coherent.js\n * Provides computed properties, watchers, and reactive updates\n *\n * Design:\n *\n * - Reading an Observable or Computed inside a computed getter records it as a\n * dependency. A Computed recomputes lazily, on read, and only when a\n * dependency actually changed (version check).\n * - A Computed that is watched, or that a watched Computed depends on, is\n * \"live\": it subscribes to its dependencies so a change marks it dirty and\n * schedules its watchers. When it stops being watched it unsubscribes, so\n * nothing keeps a discarded computed reachable.\n * - Watchers do not run inside the setter: changes are queued and flushed in\n * a loop once the outermost batch() ends (every write outside a batch is its\n * own batch). A watcher that writes queues further work instead of\n * recursing; a loop that never settles is stopped and reported.\n * - Each watcher runs in isolation: an error is reported through the\n * `onError` option, or `globalErrorHandler`, and the other watchers still run.\n * - Reading a computed that (indirectly) reads itself throws a StateError.\n */\n\n// Simple error handling for this module\nexport class StateError extends Error {\n constructor(message, options = {}) {\n super(message);\n this.name = 'StateError';\n this.type = options.type || 'state';\n this.component = options.component;\n this.context = options.context;\n this.timestamp = Date.now();\n }\n}\n\nexport const globalErrorHandler = {\n handle(error, context = {}) {\n console.error('State Error:', error.message, context);\n }\n};\n\n/** Flush iterations after which a watcher loop is considered runaway. */\nconst MAX_FLUSH_ITERATIONS = 100;\n\n/** The computed currently collecting dependencies. */\nlet activeComputed = null;\n/** Nesting depth of batch(). */\nlet batchDepth = 0;\n/** Whether the notification queue is being flushed. */\nlet flushing = false;\n/** Observables with watchers that changed: observable -> value before the change. */\nconst pendingObservables = new Map();\n/** Watched computeds whose dependencies changed. */\nconst pendingComputeds = new Set();\n/** Bumped on every write, so an unobserved computed can skip validation. */\nlet globalVersion = 0;\n\nfunction reportError(source, error, type, context = {}) {\n const onError = source?._options?.onError;\n if (typeof onError === 'function') {\n try {\n onError(error, { type, ...context });\n return;\n } catch (handlerError) {\n error = handlerError;\n }\n }\n globalErrorHandler.handle(error, { type, context });\n}\n\nfunction runObserver(source, observer, newValue, oldValue) {\n try {\n observer.callback(newValue, oldValue, observer.unwatch);\n } catch (error) {\n reportError(source, error, 'watcher-error', { newValue, oldValue });\n }\n}\n\nfunction flush() {\n flushing = true;\n let iterations = 0;\n\n try {\n while (pendingObservables.size > 0 || pendingComputeds.size > 0) {\n if (++iterations > MAX_FLUSH_ITERATIONS) {\n const culprits = [...pendingObservables.keys(), ...pendingComputeds];\n pendingObservables.clear();\n pendingComputeds.clear();\n reportError(\n culprits[0],\n new StateError(\n `Watchers kept changing state after ${MAX_FLUSH_ITERATIONS} rounds; ` +\n 'a watcher probably writes a new value to a state it (indirectly) watches.',\n { type: 'update-depth' }\n ),\n 'update-depth'\n );\n return;\n }\n\n const observables = [...pendingObservables];\n pendingObservables.clear();\n for (const [source, oldValue] of observables) {\n const newValue = source._value;\n // Changed and changed back within one batch\n if (!source._changed(oldValue, newValue)) continue;\n for (const observer of [...source._observers]) {\n if (source._observers.has(observer)) {\n runObserver(source, observer, newValue, oldValue);\n }\n }\n }\n\n const computeds = [...pendingComputeds];\n pendingComputeds.clear();\n for (const source of computeds) {\n if (source._observers.size === 0) continue;\n try {\n source._refresh();\n } catch (error) {\n reportError(source, error, 'computed-error');\n continue;\n }\n const newValue = source._value;\n const oldValue = source._lastNotified;\n if (Object.is(newValue, oldValue)) continue;\n source._lastNotified = newValue;\n for (const observer of [...source._observers]) {\n if (source._observers.has(observer)) {\n runObserver(source, observer, newValue, oldValue);\n }\n }\n }\n }\n } finally {\n flushing = false;\n }\n}\n\nfunction scheduleFlush() {\n if (batchDepth === 0 && !flushing) {\n flush();\n }\n}\n\n/**\n * Run `fn` with watcher notifications deferred until it returns; every\n * watcher then runs once, with the final value. Nested batches flush when the\n * outermost one ends. `fn` must be synchronous.\n *\n * @template T\n * @param {() => T} fn\n * @returns {T}\n */\nexport function batch(fn) {\n batchDepth++;\n try {\n return fn();\n } finally {\n batchDepth--;\n scheduleFlush();\n }\n}\n\n/**\n * Observable wrapper for tracking state changes\n */\nexport class Observable {\n constructor(value, options = {}) {\n this._value = value;\n this._version = 0;\n /** @type {Set<{callback: Function, unwatch: Function}>} */\n this._observers = new Set();\n /** Live computeds depending on this value */\n this._subscribers = new Set();\n this._options = {\n deep: options.deep !== false,\n immediate: options.immediate !== false,\n ...options\n };\n }\n\n get value() {\n activeComputed?._track(this);\n return this._value;\n }\n\n set value(newValue) {\n this._write(newValue);\n }\n\n /** Read without registering a dependency. */\n peek() {\n return this._value;\n }\n\n /**\n * Whether a write from `oldValue` to `newValue` is a change. Identical\n * primitives never are; with `deep` (the default) re-assigning the same\n * object is, since it may have been mutated in place.\n * @private\n */\n _changed(oldValue, newValue) {\n if (!Object.is(oldValue, newValue)) return true;\n return this._options.deep && newValue !== null && typeof newValue === 'object';\n }\n\n /** @private */\n _write(newValue) {\n const oldValue = this._value;\n if (!this._changed(oldValue, newValue)) {\n return;\n }\n\n this._value = newValue;\n this._version++;\n globalVersion++;\n\n for (const subscriber of [...this._subscribers]) {\n subscriber._markDirty();\n }\n if (this._observers.size > 0 && !pendingObservables.has(this)) {\n pendingObservables.set(this, oldValue);\n }\n scheduleFlush();\n }\n\n /** @private */\n _addSubscriber(computed) {\n this._subscribers.add(computed);\n }\n\n /** @private */\n _removeSubscriber(computed) {\n this._subscribers.delete(computed);\n }\n\n /** @private */\n _addObserver(observer) {\n this._observers.add(observer);\n }\n\n /** @private */\n _removeObserver(observer) {\n this._observers.delete(observer);\n }\n\n watch(callback, options = {}) {\n if (typeof callback !== 'function') {\n throw new StateError('Watch callback must be a function');\n }\n\n const observer = { callback, unwatch: null };\n observer.unwatch = () => this._removeObserver(observer);\n this._addObserver(observer);\n\n // Call immediately if requested\n if (options.immediate !== false) {\n runObserver(this, observer, this._value, undefined);\n }\n\n // Return unwatch function\n return observer.unwatch;\n }\n\n /**\n * Remove a watcher, by the callback passed to watch()\n * @param {Function} callback\n */\n unwatch(callback) {\n for (const observer of [...this._observers]) {\n if (observer.callback === callback || observer.unwatch === callback) {\n this._removeObserver(observer);\n }\n }\n }\n\n /** Remove every watcher. */\n unwatchAll() {\n for (const observer of [...this._observers]) {\n this._removeObserver(observer);\n }\n }\n}\n\n/**\n * Computed property implementation\n */\nclass Computed extends Observable {\n constructor(getter, options = {}) {\n if (typeof getter !== 'function') {\n throw new StateError('Computed getter must be a function');\n }\n super(undefined, options);\n this._getter = getter;\n /** Dependencies read by the last computation: source -> its version then */\n this._deps = new Map();\n this._dirty = true;\n this._computing = false;\n this._globalVersionSeen = -1;\n this._lastNotified = undefined;\n }\n\n get value() {\n this._refresh();\n activeComputed?._track(this);\n return this._value;\n }\n\n set value(_newValue) {\n throw new StateError('Cannot set value on computed property');\n }\n\n peek() {\n this._refresh();\n return this._value;\n }\n\n /** Watched, or a dependency of a live computed. @private */\n get _live() {\n return this._observers.size > 0 || this._subscribers.size > 0;\n }\n\n /** @private */\n _track(source) {\n if (!this._deps.has(source)) {\n this._deps.set(source, source._version);\n }\n }\n\n /** Bring the cached value up to date. @private */\n _refresh() {\n if (this._computing) {\n throw new StateError('Circular dependency between computed properties', {\n type: 'computed-cycle',\n context: { getter: this._getter.name || 'anonymous' }\n });\n }\n if (!this._dirty) {\n // A live computed is marked dirty by its dependencies\n if (this._live || this._globalVersionSeen === globalVersion) return;\n if (!this._dependenciesChanged()) {\n this._globalVersionSeen = globalVersion;\n return;\n }\n }\n this._recompute();\n }\n\n /** @private */\n _dependenciesChanged() {\n for (const [source, version] of this._deps) {\n if (source instanceof Computed) {\n source._refresh();\n }\n if (source._version !== version) return true;\n }\n return false;\n }\n\n /** @private */\n _recompute() {\n const previousDeps = this._deps;\n const previousActive = activeComputed;\n this._deps = new Map();\n this._computing = true;\n activeComputed = this;\n\n let newValue;\n try {\n newValue = this._getter();\n } catch (error) {\n // Stay dirty so the next read retries\n this._deps = previousDeps;\n this._dirty = true;\n throw error;\n } finally {\n this._computing = false;\n activeComputed = previousActive;\n }\n\n if (this._live) {\n for (const source of previousDeps.keys()) {\n if (!this._deps.has(source)) source._removeSubscriber(this);\n }\n for (const source of this._deps.keys()) {\n if (!previousDeps.has(source)) source._addSubscriber(this);\n }\n }\n\n this._dirty = false;\n this._globalVersionSeen = globalVersion;\n if (!Object.is(newValue, this._value)) {\n this._value = newValue;\n this._version++;\n }\n }\n\n /** A dependency changed. @private */\n _markDirty() {\n if (this._dirty) return;\n this._dirty = true;\n if (this._observers.size > 0) {\n pendingComputeds.add(this);\n }\n for (const subscriber of [...this._subscribers]) {\n subscriber._markDirty();\n }\n }\n\n /** Subscribe to dependencies. @private */\n _goLive() {\n this._refresh();\n for (const source of this._deps.keys()) {\n source._addSubscriber(this);\n }\n }\n\n /** Unsubscribe from dependencies. @private */\n _goLazy() {\n for (const source of this._deps.keys()) {\n source._removeSubscriber(this);\n }\n }\n\n /** @private */\n _addSubscriber(computed) {\n const wasLive = this._live;\n this._subscribers.add(computed);\n if (!wasLive) this._goLive();\n }\n\n /** @private */\n _removeSubscriber(computed) {\n this._subscribers.delete(computed);\n if (!this._live) this._goLazy();\n }\n\n /** @private */\n _addObserver(observer) {\n const hadObservers = this._observers.size > 0;\n const wasLive = this._live;\n this._observers.add(observer);\n try {\n if (wasLive) {\n this._refresh();\n } else {\n this._goLive();\n }\n } catch (error) {\n this._observers.delete(observer);\n throw error;\n }\n if (!hadObservers) {\n // Baseline for the next notification's oldValue\n this._lastNotified = this._value;\n }\n }\n\n /** @private */\n _removeObserver(observer) {\n if (!this._observers.delete(observer)) return;\n if (!this._live) this._goLazy();\n }\n}\n\n/** Placeholder observables for keys read before they exist or after delete(). */\nconst ABSENT = Symbol('absent');\n\nfunction isPath(key) {\n return typeof key === 'string' && key.includes('.');\n}\n\nfunction readPath(value, segments) {\n let current = value;\n for (const segment of segments) {\n if (current === null || current === undefined) return undefined;\n current = current[segment];\n }\n return current;\n}\n\n/** A copy of `target` with `segments` set to `value`, creating objects as needed. */\nfunction writePath(target, segments, value) {\n const [head, ...rest] = segments;\n const base = target !== null && typeof target === 'object'\n ? (Array.isArray(target) ? [...target] : { ...target })\n : {};\n const next = rest.length === 0 ? value : writePath(base[head], rest, value);\n Object.defineProperty(base, head, { value: next, enumerable: true, writable: true, configurable: true });\n return base;\n}\n\n/** A copy of `target` without the property at `segments`. */\nfunction deletePath(target, segments) {\n if (target === null || typeof target !== 'object') return target;\n const [head, ...rest] = segments;\n if (!Object.prototype.hasOwnProperty.call(target, head)) return target;\n const base = Array.isArray(target) ? [...target] : { ...target };\n if (rest.length === 0) {\n delete base[head];\n } else {\n base[head] = deletePath(base[head], rest);\n }\n return base;\n}\n\n/**\n * Reactive state container with advanced features\n *\n * Keys may be dot paths into object values: `set('user.name', 'Ada')` writes\n * a copy of `user` with the new name (notifying watchers of `user` and of\n * `user.name`), and `get`/`has`/`watch`/`delete` accept paths too.\n */\nexport class ReactiveState {\n constructor(initialState = {}, options = {}) {\n /** @type {Map<string, Observable>} */\n this._state = new Map();\n this._computed = new Map();\n this._watchers = new Map();\n this._expressionWatchers = new Set();\n this._middleware = [];\n this._history = [];\n this._options = {\n enableHistory: options.enableHistory !== false,\n maxHistorySize: options.maxHistorySize || 50,\n enableMiddleware: options.enableMiddleware !== false,\n deep: options.deep !== false,\n ...options\n };\n\n // Initialize state\n Object.entries(initialState).forEach(([key, value]) => {\n this.set(key, value);\n });\n }\n\n /** Observable for a key, created as an absent placeholder if needed. @private */\n _observable(key) {\n let observable = this._state.get(key);\n if (!observable) {\n observable = new Observable(ABSENT, this._options);\n this._state.set(key, observable);\n }\n return observable;\n }\n\n /** Whether a key is stored under its full name. @private */\n _hasOwnKey(key) {\n const observable = this._state.get(key);\n return Boolean(observable) && observable._value !== ABSENT;\n }\n\n /** [rootKey, pathSegments] for a dot path, or null for a plain key. @private */\n _splitPath(key) {\n if (!isPath(key)) return null;\n const [root, ...segments] = key.split('.');\n return [root, segments];\n }\n\n /**\n * Get reactive state value\n */\n get(key) {\n const path = this._splitPath(key);\n if (path) {\n return readPath(this.get(path[0]), path[1]);\n }\n // Reading a missing key inside a computed still records the\n // dependency, so the computed updates once the key is set.\n const observable = activeComputed ? this._observable(key) : this._state.get(key);\n if (!observable) return undefined;\n const value = observable.value;\n return value === ABSENT ? undefined : value;\n }\n\n /**\n * Set reactive state value\n */\n set(key, value, options = {}) {\n const config = { ...this._options, ...options };\n const oldValue = this.get(key);\n\n // Run middleware\n if (config.enableMiddleware) {\n const middlewareResult = this._runMiddleware('set', { key, value, oldValue });\n if (middlewareResult.cancelled) {\n return false;\n }\n value = middlewareResult.value !== undefined ? middlewareResult.value : value;\n }\n\n const path = this._splitPath(key);\n if (path) {\n const [root, segments] = path;\n if (config.enableHistory) {\n this._addToHistory('set', key, oldValue, value);\n }\n this._writeKey(root, writePath(this.get(root), segments, value));\n return true;\n }\n\n // Record history\n if (config.enableHistory && this._hasOwnKey(key)) {\n this._addToHistory('set', key, oldValue, value);\n }\n\n this._writeKey(key, value);\n return true;\n }\n\n /** @private */\n _writeKey(key, value) {\n this._observable(key)._write(value);\n }\n\n /**\n * Check if state has a key\n */\n has(key) {\n const path = this._splitPath(key);\n if (path) {\n const parent = readPath(this.get(path[0]), path[1].slice(0, -1));\n return parent !== null && typeof parent === 'object' &&\n Object.prototype.hasOwnProperty.call(parent, path[1][path[1].length - 1]);\n }\n return this._hasOwnKey(key);\n }\n\n /**\n * Delete state key. Its watchers are removed; computed properties that\n * read it update.\n */\n delete(key) {\n const path = this._splitPath(key);\n if (path) {\n if (!this.has(key)) return false;\n if (this._options.enableHistory) {\n this._addToHistory('delete', key, this.get(key), undefined);\n }\n this._writeKey(path[0], deletePath(this.get(path[0]), path[1]));\n return true;\n }\n\n if (!this._hasOwnKey(key)) {\n return false;\n }\n\n const observable = this._state.get(key);\n\n // Record history\n if (this._options.enableHistory) {\n this._addToHistory('delete', key, observable._value, undefined);\n }\n\n observable.unwatchAll();\n this._releaseKeyWatchers(key);\n observable._write(ABSENT);\n return true;\n }\n\n /** @private */\n _releaseKeyWatchers(key) {\n const unwatchers = this._watchers.get(key);\n if (unwatchers) {\n for (const unwatch of unwatchers) unwatch();\n this._watchers.delete(key);\n }\n }\n\n /**\n * Clear all state\n */\n clear() {\n // Record history\n if (this._options.enableHistory) {\n this._addToHistory('clear', null, this.toObject(), {});\n }\n\n batch(() => {\n for (const [key, observable] of this._state) {\n observable.unwatchAll();\n this._releaseKeyWatchers(key);\n observable._write(ABSENT);\n }\n });\n\n this._computed.clear();\n this._watchers.clear();\n }\n\n /**\n * Create computed property\n */\n computed(key, getter, options = {}) {\n if (typeof getter !== 'function') {\n throw new StateError(`Computed property '${key}' getter must be a function`);\n }\n\n const computed = new Computed(getter, { ...this._options, ...options });\n this._computed.set(key, computed);\n\n return computed;\n }\n\n /**\n * Get computed property value\n */\n getComputed(key) {\n const computed = this._computed.get(key);\n return computed ? computed.value : undefined;\n }\n\n /**\n * Watch state changes: a key, a dot path into a key, or a getter\n * expression (re-evaluated whenever what it reads changes).\n */\n watch(key, callback, options = {}) {\n if (typeof key === 'function') {\n // Watch computed expression\n return this._watchComputed(key, callback, options);\n }\n\n const path = this._splitPath(key);\n if (path) {\n if (!this._hasOwnKey(path[0])) {\n throw new StateError(`Cannot watch undefined state key: ${path[0]}`);\n }\n const computed = new Computed(() => this.get(key), { ...this._options, ...options });\n return this._track(key, computed.watch(callback, options));\n }\n\n if (!this._hasOwnKey(key)) {\n throw new StateError(`Cannot watch undefined state key: ${key}`);\n }\n\n return this._track(key, this._state.get(key).watch(callback, options));\n }\n\n /** Remember an unwatch function for cleanup. @private */\n _track(key, unwatch) {\n if (!this._watchers.has(key)) {\n this._watchers.set(key, new Set());\n }\n const unwatchers = this._watchers.get(key);\n const release = () => {\n unwatch();\n unwatchers.delete(release);\n };\n unwatchers.add(release);\n return release;\n }\n\n /**\n * Watch computed expression\n */\n _watchComputed(expression, callback, options = {}) {\n const computed = new Computed(expression, { ...this._options, ...options });\n const unwatch = computed.watch(callback, options);\n const release = () => {\n unwatch();\n this._expressionWatchers.delete(release);\n };\n this._expressionWatchers.add(release);\n return release;\n }\n\n /**\n * Batch state updates: watchers run once, after every update, with the\n * final values.\n */\n batch(updates) {\n if (typeof updates === 'function') {\n // Batch function updates\n const oldEnableHistory = this._options.enableHistory;\n this._options.enableHistory = false;\n\n try {\n const result = batch(() => updates(this));\n\n // Record batch in history\n if (oldEnableHistory) {\n this._addToHistory('batch', null, null, this.toObject());\n }\n\n return result;\n } finally {\n this._options.enableHistory = oldEnableHistory;\n }\n } else if (typeof updates === 'object') {\n // Batch object updates\n return this.batch(() => {\n Object.entries(updates).forEach(([key, value]) => {\n this.set(key, value);\n });\n });\n }\n }\n\n /**\n * Subscribe to multiple state changes\n */\n subscribe(keys, callback, options = {}) {\n if (!Array.isArray(keys)) {\n keys = [keys];\n }\n\n const unwatchers = keys.map(key => {\n return this.watch(key, (newValue, oldValue) => {\n callback({\n key,\n newValue,\n oldValue,\n state: this.toObject()\n });\n }, options);\n });\n\n // Return unsubscribe function\n return () => {\n unwatchers.forEach(unwatch => unwatch());\n };\n }\n\n /**\n * Add middleware for state changes\n */\n use(middleware) {\n if (typeof middleware !== 'function') {\n throw new StateError('Middleware must be a function');\n }\n this._middleware.push(middleware);\n }\n\n /**\n * Run middleware chain\n */\n _runMiddleware(action, context) {\n let result = { ...context, cancelled: false };\n\n for (const middleware of this._middleware) {\n try {\n const middlewareResult = middleware(action, result);\n if (middlewareResult) {\n result = { ...result, ...middlewareResult };\n if (result.cancelled) {\n break;\n }\n }\n } catch (error) {\n reportError(this, error, 'middleware-error', { action });\n }\n }\n\n return result;\n }\n\n /**\n * Add action to history\n */\n _addToHistory(action, key, oldValue, newValue) {\n if (!this._options.enableHistory) return;\n\n this._history.unshift({\n action,\n key,\n oldValue,\n newValue,\n timestamp: Date.now()\n });\n\n // Limit history size\n if (this._history.length > this._options.maxHistorySize) {\n this._history = this._history.slice(0, this._options.maxHistorySize);\n }\n }\n\n /**\n * Get state history\n */\n getHistory(limit = 10) {\n return this._history.slice(0, limit);\n }\n\n /**\n * Undo last action\n */\n undo() {\n const lastAction = this._history.shift();\n if (!lastAction) return false;\n\n const { action, key, oldValue } = lastAction;\n\n // Temporarily disable history\n const oldEnableHistory = this._options.enableHistory;\n this._options.enableHistory = false;\n\n try {\n switch (action) {\n case 'set':\n if (oldValue === undefined) {\n this.delete(key);\n } else {\n this.set(key, oldValue);\n }\n break;\n case 'delete':\n this.set(key, oldValue);\n break;\n case 'clear':\n this.clear();\n Object.entries(oldValue || {}).forEach(([k, v]) => {\n this.set(k, v);\n });\n break;\n }\n return true;\n } finally {\n this._options.enableHistory = oldEnableHistory;\n }\n }\n\n /**\n * Convert state to plain object\n */\n toObject() {\n // Object.fromEntries defines own properties, so a \"__proto__\" key\n // stays a key instead of replacing the result's prototype.\n return Object.fromEntries(\n [...this._state]\n .filter(([, observable]) => observable._value !== ABSENT)\n .map(([key, observable]) => [key, observable._value])\n );\n }\n\n /**\n * Convert computed properties to object\n */\n getComputedValues() {\n return Object.fromEntries(\n [...this._computed].map(([key, computed]) => [key, computed.value])\n );\n }\n\n /**\n * Get state statistics\n */\n getStats() {\n let stateKeys = 0;\n for (const observable of this._state.values()) {\n if (observable._value !== ABSENT) stateKeys++;\n }\n return {\n stateKeys,\n computedKeys: this._computed.size,\n watcherKeys: this._watchers.size,\n historyLength: this._history.length,\n middlewareCount: this._middleware.length\n };\n }\n\n /**\n * Cleanup and destroy\n */\n destroy() {\n // Clear all watchers\n for (const key of [...this._watchers.keys()]) {\n this._releaseKeyWatchers(key);\n }\n for (const release of [...this._expressionWatchers]) {\n release();\n }\n for (const observable of this._state.values()) {\n observable.unwatchAll();\n }\n for (const computed of this._computed.values()) {\n computed.unwatchAll();\n }\n\n // Clear collections\n this._state.clear();\n this._computed.clear();\n this._watchers.clear();\n this._middleware.length = 0;\n this._history.length = 0;\n }\n}\n\n/**\n * Create reactive state store\n */\nexport function createReactiveState(initialState, options = {}) {\n return new ReactiveState(initialState, options);\n}\n\n/**\n * Create observable value\n */\nexport function observable(value, options = {}) {\n return new Observable(value, options);\n}\n\n/**\n * Create computed property\n */\nexport function computed(getter, options = {}) {\n return new Computed(getter, options);\n}\n\n/**\n * Utility functions for common state patterns\n */\nexport const stateUtils = {\n /**\n * Create a toggle state\n */\n toggle(initialValue = false) {\n const obs = observable(initialValue);\n obs.toggle = () => {\n obs.value = !obs.value;\n };\n return obs;\n },\n\n /**\n * Create a counter state\n */\n counter(initialValue = 0) {\n const obs = observable(initialValue);\n obs.increment = (by = 1) => {\n obs.value += by;\n };\n obs.decrement = (by = 1) => {\n obs.value -= by;\n };\n obs.reset = () => {\n obs.value = initialValue;\n };\n return obs;\n },\n\n /**\n * Create an array state with utilities\n */\n array(initialArray = []) {\n const obs = observable([...initialArray]);\n obs.push = (...items) => {\n obs.value = [...obs.value, ...items];\n };\n obs.pop = () => {\n const newArray = [...obs.value];\n const result = newArray.pop();\n obs.value = newArray;\n return result;\n };\n obs.filter = (predicate) => {\n obs.value = obs.value.filter(predicate);\n };\n obs.clear = () => {\n obs.value = [];\n };\n return obs;\n },\n\n /**\n * Create object state with deep reactivity\n */\n object(initialObject = {}) {\n const state = createReactiveState(initialObject, { deep: true });\n return state;\n }\n};\n\nexport default ReactiveState;\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AAG,YAAY,CAAC;AACxC,QAAI,OAAO,IAAI,UAAU;AACrB,UAAI,QAAQ,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK;AAAA,IACvC;AACA,QAAI,MAAM,MAAM;AACZ,YAAM,WAAW,CAAC,GAAG,IAAI,KAAK;AAC9B,YAAM,SAAS,SAAS,IAAI;AAC5B,UAAI,QAAQ;AACZ,aAAO;AAAA,IACX;AACA,QAAI,SAAS,CAAC,cAAc;AACxB,UAAI,QAAQ,IAAI,MAAM,OAAO,SAAS;AAAA,IAC1C;AACA,QAAI,QAAQ,MAAM;AACd,UAAI,QAAQ,CAAC;AAAA,IACjB;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,gBAAgB,CAAC,GAAG;AACvB,UAAM,QAAQ,oBAAoB,eAAe,EAAE,MAAM,KAAK,CAAC;AAC/D,WAAO;AAAA,EACX;AACJ;AAEA,IAAO,yBAAQ;",
6
6
  "names": ["computed", "observable"]
7
7
  }
@@ -45,58 +45,160 @@ var globalStateManager = {
45
45
  return createState();
46
46
  }
47
47
  };
48
- var contextStacks = /* @__PURE__ */ new Map();
49
- function provideContext(key, value) {
50
- if (!contextStacks.has(key)) {
51
- contextStacks.set(key, []);
48
+ var EMPTY_SCOPE = /* @__PURE__ */ new Map();
49
+ function createAsyncStorage() {
50
+ try {
51
+ const asyncHooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
52
+ const AsyncLocalStorage = asyncHooks?.AsyncLocalStorage;
53
+ return typeof AsyncLocalStorage === "function" ? new AsyncLocalStorage() : null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+ var asyncStorage = createAsyncStorage();
59
+ var syncHolder = { scope: EMPTY_SCOPE, owned: true };
60
+ function currentHolder() {
61
+ return asyncStorage ? asyncStorage.getStore() : syncHolder;
62
+ }
63
+ function currentScope() {
64
+ return currentHolder()?.scope ?? EMPTY_SCOPE;
65
+ }
66
+ function setScope(scope, holder = currentHolder()) {
67
+ if (!holder?.owned) {
68
+ throw new Error(
69
+ "Context can only be provided inside runWithContext() on the server: outside it the value would leak into other requests. Wrap each request or render: runWithContext(() => ...)."
70
+ );
71
+ }
72
+ holder.scope = scope;
73
+ }
74
+ function runInScope(scope, fn, args) {
75
+ if (asyncStorage) {
76
+ return asyncStorage.run({ scope, owned: true }, fn, ...args);
77
+ }
78
+ const previous = syncHolder.scope;
79
+ syncHolder.scope = scope;
80
+ try {
81
+ return fn(...args);
82
+ } finally {
83
+ syncHolder.scope = previous;
52
84
  }
53
- const stack = contextStacks.get(key);
54
- const previousValue = globalState.get(key);
55
- stack.push(previousValue);
56
- globalState.set(key, value);
85
+ }
86
+ function withValue(scope, key, value) {
87
+ const next = new Map(scope);
88
+ next.set(key, { value, previous: scope.get(key) });
89
+ return next;
90
+ }
91
+ function runWithContext(fn, values) {
92
+ if (typeof fn !== "function") {
93
+ throw new TypeError(`runWithContext() requires a function, received: ${typeof fn}`);
94
+ }
95
+ let scope = EMPTY_SCOPE;
96
+ if (values && typeof values === "object") {
97
+ for (const [key, value] of Object.entries(values)) {
98
+ scope = withValue(scope, key, value);
99
+ }
100
+ }
101
+ return runInScope(scope, fn, []);
102
+ }
103
+ function provideContext(key, value) {
104
+ setScope(withValue(currentScope(), key, value));
57
105
  }
58
106
  function createContextProvider(key, value, children) {
59
- return (renderFunction) => {
60
- try {
61
- provideContext(key, value);
62
- if (renderFunction && typeof renderFunction === "function") {
63
- return renderFunction(children);
64
- } else {
65
- return children;
66
- }
67
- } finally {
68
- restoreContext(key);
107
+ function contextProvider(...args) {
108
+ const renderFunction = args[0];
109
+ const scope = withValue(currentScope(), key, value);
110
+ if (typeof renderFunction === "function") {
111
+ return runInScope(scope, renderFunction, [children]);
69
112
  }
113
+ return runInScope(scope, resolveComponents, [children]);
114
+ }
115
+ return contextProvider;
116
+ }
117
+ var TAG_NAME = /^[a-zA-Z][a-zA-Z0-9-]*$/;
118
+ function resolveComponents(node, depth = 0) {
119
+ if (depth > 1e3) return node;
120
+ if (typeof node === "function") {
121
+ return resolveComponents(node(), depth + 1);
122
+ }
123
+ if (Array.isArray(node)) {
124
+ let changed2 = false;
125
+ const resolved2 = node.map((child) => {
126
+ const next = resolveComponents(child, depth + 1);
127
+ if (next !== child) changed2 = true;
128
+ return next;
129
+ });
130
+ return changed2 ? resolved2 : node;
131
+ }
132
+ if (!node || typeof node !== "object") return node;
133
+ if (node.__isLazy === true && typeof node.evaluate === "function") {
134
+ return resolveComponents(node.evaluate(), depth + 1);
135
+ }
136
+ const tags = Object.keys(node);
137
+ if (tags.length === 0 || !tags.every((tag) => TAG_NAME.test(tag))) return node;
138
+ let changed = false;
139
+ const resolved = {};
140
+ for (const tag of tags) {
141
+ let content = node[tag];
142
+ if (typeof content === "function") {
143
+ content = resolveComponents(content(), depth + 1);
144
+ }
145
+ if (content && typeof content === "object" && !Array.isArray(content) && !isTrusted(content)) {
146
+ content = resolveProps(content, depth);
147
+ }
148
+ if (content !== node[tag]) changed = true;
149
+ resolved[tag] = content;
150
+ }
151
+ return changed ? resolved : node;
152
+ }
153
+ function isTrusted(value) {
154
+ return value[/* @__PURE__ */ Symbol.for("coherent.js.trustedContent")] === true;
155
+ }
156
+ function resolveProps(props, depth) {
157
+ let next = props;
158
+ const set = (key, value) => {
159
+ if (next === props) next = { ...props };
160
+ next[key] = value;
70
161
  };
162
+ for (const key of Object.keys(props)) {
163
+ const value = props[key];
164
+ if (key === "children") {
165
+ if (value !== void 0 && value !== null) {
166
+ const children = resolveComponents(value, depth + 1);
167
+ if (children !== value) set(key, children);
168
+ }
169
+ } else if (typeof value === "function" && key !== "key") {
170
+ if (key === "text" || key === "html") {
171
+ set(key, value());
172
+ } else if (!key.startsWith("on")) {
173
+ try {
174
+ set(key, value());
175
+ } catch {
176
+ }
177
+ }
178
+ }
179
+ }
180
+ return next;
71
181
  }
72
182
  function restoreContext(key) {
73
- if (!contextStacks.has(key)) return;
74
- const stack = contextStacks.get(key);
75
- const previousValue = stack.pop();
76
- if (stack.length === 0) {
77
- if (previousValue === void 0) {
78
- globalState.delete(key);
79
- } else {
80
- globalState.set(key, previousValue);
81
- }
82
- contextStacks.delete(key);
183
+ const scope = currentScope();
184
+ const entry = scope.get(key);
185
+ if (!entry) return;
186
+ const next = new Map(scope);
187
+ if (entry.previous) {
188
+ next.set(key, entry.previous);
83
189
  } else {
84
- globalState.set(key, previousValue);
190
+ next.delete(key);
85
191
  }
192
+ setScope(next);
86
193
  }
87
194
  function clearAllContexts() {
88
- for (const [key, stack] of contextStacks) {
89
- const beforeFirstProvide = stack[0];
90
- if (beforeFirstProvide === void 0) {
91
- globalState.delete(key);
92
- } else {
93
- globalState.set(key, beforeFirstProvide);
94
- }
195
+ if (currentScope().size > 0) {
196
+ setScope(EMPTY_SCOPE);
95
197
  }
96
- contextStacks.clear();
97
198
  }
98
199
  function useContext(key) {
99
- return globalState.get(key);
200
+ const entry = currentScope().get(key);
201
+ return entry ? entry.value : globalState.get(key);
100
202
  }
101
203
  export {
102
204
  clearAllContexts,
@@ -105,6 +207,7 @@ export {
105
207
  globalStateManager,
106
208
  provideContext,
107
209
  restoreContext,
210
+ runWithContext,
108
211
  useContext
109
212
  };
110
213
  //# sourceMappingURL=state-manager.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/state-manager.js"],
4
- "sourcesContent": ["/**\n * Simple state management for server-side rendering\n * This is mainly for component state during rendering\n */\n\nconst globalState = new Map();\n\n/**\n * Creates a state container for a request/render cycle\n * @param {Object} initialState - Initial state object\n * @returns {Object} State container\n */\nexport function createState(initialState = {}) {\n const state = new Map(Object.entries(initialState));\n\n return {\n get(key) {\n return state.get(key);\n },\n\n set(key, value) {\n state.set(key, value);\n return this;\n },\n\n has(key) {\n return state.has(key);\n },\n\n delete(key) {\n return state.delete(key);\n },\n\n clear() {\n state.clear();\n return this;\n },\n\n toObject() {\n return Object.fromEntries(state);\n },\n\n // For debugging\n _internal: state\n };\n}\n\n/**\n * Global state for sharing data across components during SSR\n */\nexport const globalStateManager = {\n set(key, value) {\n globalState.set(key, value);\n },\n\n get(key) {\n return globalState.get(key);\n },\n\n has(key) {\n return globalState.has(key);\n },\n\n clear() {\n globalState.clear();\n },\n\n // Create isolated state for each request\n createRequestState() {\n return createState();\n }\n};\n\n/**\n * Context stack for managing nested context providers\n */\nconst contextStacks = new Map();\n\n/**\n * Context provider for passing data down the component tree\n * @param {string} key - Context key\n * @param {*} value - Context value\n * @param {Object} children - Children to render with context\n * @returns {Object} Children with context available\n */\nexport function provideContext(key, value) {\n // Initialize context stack if it doesn't exist\n if (!contextStacks.has(key)) {\n contextStacks.set(key, []);\n }\n \n const stack = contextStacks.get(key);\n \n // Store previous value\n const previousValue = globalState.get(key);\n \n // Push previous value to stack and set new value\n stack.push(previousValue);\n globalState.set(key, value);\n}\n\n/**\n * Create a context provider component that works with the rendering system\n * @param {string} key - Context key\n * @param {*} value - Context value\n * @param {Object} children - Children to render with context\n * @returns {Function} Component function that provides context\n */\nexport function createContextProvider(key, value, children) {\n // Return a function that will render the children within the context\n return (renderFunction) => {\n try {\n // Provide context\n provideContext(key, value);\n \n // If a render function is provided, use it to render children\n // Otherwise return children to be rendered by the caller\n if (renderFunction && typeof renderFunction === 'function') {\n return renderFunction(children);\n } else {\n return children;\n }\n } finally {\n // Always restore context when done\n restoreContext(key);\n }\n };\n}\n\n/**\n * Restore context to previous value\n * @param {string} key - Context key\n */\nexport function restoreContext(key) {\n if (!contextStacks.has(key)) return;\n \n const stack = contextStacks.get(key);\n \n // Restore previous value from stack\n const previousValue = stack.pop();\n \n if (stack.length === 0) {\n // No more providers, delete the key if it was undefined before\n if (previousValue === undefined) {\n globalState.delete(key);\n } else {\n globalState.set(key, previousValue);\n }\n \n // Clean up empty stack\n contextStacks.delete(key);\n } else {\n // Restore previous value\n globalState.set(key, previousValue);\n }\n}\n\n/**\n * Clear all context stacks (useful for cleanup after rendering)\n *\n * useContext() reads from globalState, which is module-level and therefore\n * shared by every render in the process. Clearing only contextStacks left the\n * values themselves in place, so a context provided while rendering one\n * request stayed readable while rendering the next \u2014 and became unrecoverable,\n * since restoreContext() bails out once a key's stack is gone.\n *\n * Unwind each tracked key to the value it held before its first\n * provideContext() \u2014 the bottom of that key's stack. Only keys that were\n * actually provided as contexts are touched, so unrelated global state\n * survives, which is what the previous implementation was trying to protect.\n */\nexport function clearAllContexts() {\n for (const [key, stack] of contextStacks) {\n const beforeFirstProvide = stack[0];\n\n if (beforeFirstProvide === undefined) {\n globalState.delete(key);\n } else {\n globalState.set(key, beforeFirstProvide);\n }\n }\n\n contextStacks.clear();\n}\n\n/**\n * Context consumer to access provided context\n * @param {string} key - Context key\n * @returns {*} Context value\n */\nexport function useContext(key) {\n return globalState.get(key);\n}\n"],
5
- "mappings": ";AAKA,IAAM,cAAc,oBAAI,IAAI;AAOrB,SAAS,YAAY,eAAe,CAAC,GAAG;AAC3C,QAAM,QAAQ,IAAI,IAAI,OAAO,QAAQ,YAAY,CAAC;AAElD,SAAO;AAAA,IACH,IAAI,KAAK;AACL,aAAO,MAAM,IAAI,GAAG;AAAA,IACxB;AAAA,IAEA,IAAI,KAAK,OAAO;AACZ,YAAM,IAAI,KAAK,KAAK;AACpB,aAAO;AAAA,IACX;AAAA,IAEA,IAAI,KAAK;AACL,aAAO,MAAM,IAAI,GAAG;AAAA,IACxB;AAAA,IAEA,OAAO,KAAK;AACR,aAAO,MAAM,OAAO,GAAG;AAAA,IAC3B;AAAA,IAEA,QAAQ;AACJ,YAAM,MAAM;AACZ,aAAO;AAAA,IACX;AAAA,IAEA,WAAW;AACP,aAAO,OAAO,YAAY,KAAK;AAAA,IACnC;AAAA;AAAA,IAGA,WAAW;AAAA,EACf;AACJ;AAKO,IAAM,qBAAqB;AAAA,EAC9B,IAAI,KAAK,OAAO;AACZ,gBAAY,IAAI,KAAK,KAAK;AAAA,EAC9B;AAAA,EAEA,IAAI,KAAK;AACL,WAAO,YAAY,IAAI,GAAG;AAAA,EAC9B;AAAA,EAEA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AAuB,QAAW;AAClC,kBAAY,OAAO,GAAG;AAAA,IAC1B,OAAO;AACH,kBAAY,IAAI,KAAK,kBAAkB;AAAA,IAC3C;AAAA,EACJ;AAEA,gBAAc,MAAM;AACxB;AAOO,SAAS,WAAW,KAAK;AAC5B,SAAO,YAAY,IAAI,GAAG;AAC9B;",
6
- "names": []
4
+ "sourcesContent": ["/**\n * Simple state management for server-side rendering\n * This is mainly for component state during rendering\n */\n\nconst globalState = new Map();\n\n/**\n * Creates a state container for a request/render cycle\n * @param {Object} initialState - Initial state object\n * @returns {Object} State container\n */\nexport function createState(initialState = {}) {\n const state = new Map(Object.entries(initialState));\n\n return {\n get(key) {\n return state.get(key);\n },\n\n set(key, value) {\n state.set(key, value);\n return this;\n },\n\n has(key) {\n return state.has(key);\n },\n\n delete(key) {\n return state.delete(key);\n },\n\n clear() {\n state.clear();\n return this;\n },\n\n toObject() {\n return Object.fromEntries(state);\n },\n\n // For debugging\n _internal: state\n };\n}\n\n/**\n * Global state for sharing data across components during SSR.\n *\n * This store is process-wide: every request sees it. It is also the fallback\n * useContext() reads when no context has been provided for a key, so it suits\n * application-wide defaults, never request data.\n */\nexport const globalStateManager = {\n set(key, value) {\n globalState.set(key, value);\n },\n\n get(key) {\n return globalState.get(key);\n },\n\n has(key) {\n return globalState.has(key);\n },\n\n clear() {\n globalState.clear();\n },\n\n // Create isolated state for each request\n createRequestState() {\n return createState();\n }\n};\n\n// ============================================================================\n// Context API\n// ============================================================================\n//\n// A scope is an immutable Map from context key to a linked stack entry\n// `{ value, previous }`. A holder `{ scope, owned }` points at the current\n// scope.\n//\n// On Node the holder lives in an AsyncLocalStorage, so it follows each\n// request's async execution:\n//\n// - runWithContext() (and a provider) runs its callback with a fresh holder\n// that it owns. Inside it every change updates that holder in place, so\n// the value stays put across the awaits and yields of an async or\n// streaming render, and nothing leaks out of it.\n// - Outside any owned holder there is nothing request-scoped to write to, so\n// providing a value throws (see setScope()).\n//\n// Browsers have no AsyncLocalStorage. There a single module holder is updated\n// in place, which is exact for synchronous rendering; a value read after an\n// `await` sees whatever is current at that point.\n\nconst EMPTY_SCOPE = new Map();\n\nfunction createAsyncStorage() {\n try {\n // Never a static import: this module also runs in browsers.\n const asyncHooks = globalThis.process?.getBuiltinModule?.('node:async_hooks');\n const AsyncLocalStorage = asyncHooks?.AsyncLocalStorage;\n return typeof AsyncLocalStorage === 'function' ? new AsyncLocalStorage() : null;\n } catch {\n return null;\n }\n}\n\nconst asyncStorage = createAsyncStorage();\n\n/** The holder used when AsyncLocalStorage is unavailable. */\nconst syncHolder = { scope: EMPTY_SCOPE, owned: true };\n\nfunction currentHolder() {\n return asyncStorage ? asyncStorage.getStore() : syncHolder;\n}\n\nfunction currentScope() {\n return currentHolder()?.scope ?? EMPTY_SCOPE;\n}\n\n/**\n * Make `scope` current in `holder` (the scope of the enclosing\n * runWithContext() call, or the browser's single holder).\n *\n * There is deliberately no fallback outside runWithContext() on the server.\n * AsyncLocalStorage#enterWith() attached the value to the caller's async\n * context, and a request's async context is shared with the next request\n * on the same keep-alive connection: the value leaked to other users (and\n * a module-level store would leak to every request).\n */\nfunction setScope(scope, holder = currentHolder()) {\n if (!holder?.owned) {\n throw new Error(\n 'Context can only be provided inside runWithContext() on the server: outside it the value ' +\n 'would leak into other requests. Wrap each request or render: runWithContext(() => ...).'\n );\n }\n holder.scope = scope;\n}\n\n/**\n * Run `fn(...args)` with `scope` current in a holder of its own, restoring the\n * previous scope afterwards.\n */\nfunction runInScope(scope, fn, args) {\n if (asyncStorage) {\n return asyncStorage.run({ scope, owned: true }, fn, ...args);\n }\n\n const previous = syncHolder.scope;\n syncHolder.scope = scope;\n try {\n return fn(...args);\n } finally {\n syncHolder.scope = previous;\n }\n}\n\nfunction withValue(scope, key, value) {\n const next = new Map(scope);\n next.set(key, { value, previous: scope.get(key) });\n return next;\n}\n\n/**\n * Run `fn` in a fresh, isolated context scope \u2014 one per request or render.\n *\n * Nothing provided inside `fn` is visible outside it and nothing provided\n * outside is visible inside. On Node this holds across `await`s, so wrap each\n * request (or each `renderToStream()` consumer) in it.\n *\n * @template T\n * @param {() => T} fn - Work to run, typically a request handler or a render\n * @param {Object} [values] - Initial context values, keyed by context key\n * @returns {T} Whatever `fn` returns (a promise for an async `fn`)\n */\nexport function runWithContext(fn, values) {\n if (typeof fn !== 'function') {\n throw new TypeError(`runWithContext() requires a function, received: ${typeof fn}`);\n }\n\n let scope = EMPTY_SCOPE;\n if (values && typeof values === 'object') {\n for (const [key, value] of Object.entries(values)) {\n scope = withValue(scope, key, value);\n }\n }\n\n return runInScope(scope, fn, []);\n}\n\n/**\n * Provide a context value for the rest of the current runWithContext() scope,\n * remembering the previous one so {@link restoreContext} can unwind it.\n *\n * On Node it must be called inside {@link runWithContext} (it throws\n * otherwise); a concurrent request does not see the value, even across\n * `await`s. In browsers it may be called anywhere.\n *\n * @throws {Error} On Node, when called outside runWithContext()\n *\n * @param {string} key - Context key\n * @param {*} value - Context value\n */\nexport function provideContext(key, value) {\n setScope(withValue(currentScope(), key, value));\n}\n\n/**\n * Create a context provider component.\n *\n * The provider is a zero-argument function component. When the renderer calls\n * it, it evaluates the function components and function-valued props below\n * it with the value provided, and returns the resulting plain tree; its\n * siblings do not see the value. Nothing is pre-rendered, so the renderer\n * escapes the children exactly once. Values read later, such as in an event\n * handler, do not see it.\n *\n * Called with a render function instead, the provider runs\n * `renderFunction(children)` with the context provided and returns its result.\n * On Node an async render function keeps the context across its `await`s.\n *\n * @param {string} key - Context key\n * @param {*} value - Context value\n * @param {*} children - Children to render with context\n * @returns {Function} Context provider component\n */\nexport function createContextProvider(key, value, children) {\n // Rest parameters keep `length` at 0, so a renderer calls this as an\n // ordinary function component.\n function contextProvider(...args) {\n const renderFunction = args[0];\n const scope = withValue(currentScope(), key, value);\n\n if (typeof renderFunction === 'function') {\n return runInScope(scope, renderFunction, [children]);\n }\n\n // Evaluate the function components below the provider inside its\n // scope, and hand the renderer the resulting plain tree. The scope\n // is restored even when a child throws; enter/leave marker\n // components used to leave the value set for the next request when\n // a child threw before the \"leave\" marker ran.\n return runInScope(scope, resolveComponents, [children]);\n }\n\n return contextProvider;\n}\n\nconst TAG_NAME = /^[a-zA-Z][a-zA-Z0-9-]*$/;\n\n/**\n * Call the function components in a tree the way the renderer does (no\n * arguments, following returned functions), so context reads happen now.\n * Unchanged nodes are returned as they are (trusted-content markers keep\n * their brand); event handlers are props and are never called.\n */\nfunction resolveComponents(node, depth = 0) {\n if (depth > 1000) return node;\n\n if (typeof node === 'function') {\n return resolveComponents(node(), depth + 1);\n }\n if (Array.isArray(node)) {\n let changed = false;\n const resolved = node.map((child) => {\n const next = resolveComponents(child, depth + 1);\n if (next !== child) changed = true;\n return next;\n });\n return changed ? resolved : node;\n }\n if (!node || typeof node !== 'object') return node;\n\n if (node.__isLazy === true && typeof node.evaluate === 'function') {\n return resolveComponents(node.evaluate(), depth + 1);\n }\n\n const tags = Object.keys(node);\n if (tags.length === 0 || !tags.every((tag) => TAG_NAME.test(tag))) return node;\n\n let changed = false;\n const resolved = {};\n for (const tag of tags) {\n let content = node[tag];\n if (typeof content === 'function') {\n content = resolveComponents(content(), depth + 1);\n }\n if (content && typeof content === 'object' && !Array.isArray(content) && !isTrusted(content)) {\n content = resolveProps(content, depth);\n }\n if (content !== node[tag]) changed = true;\n resolved[tag] = content;\n }\n return changed ? resolved : node;\n}\n\nfunction isTrusted(value) {\n return value[Symbol.for('coherent.js.trustedContent')] === true;\n}\n\n/**\n * Evaluate the function-valued props the renderer would call (`text`,\n * `html` and attributes other than `on*` event handlers) and the children.\n * An attribute function that throws is left for the renderer, which\n * reports it and renders an empty value.\n */\nfunction resolveProps(props, depth) {\n let next = props;\n const set = (key, value) => {\n if (next === props) next = { ...props };\n next[key] = value;\n };\n\n for (const key of Object.keys(props)) {\n const value = props[key];\n if (key === 'children') {\n if (value !== undefined && value !== null) {\n const children = resolveComponents(value, depth + 1);\n if (children !== value) set(key, children);\n }\n } else if (typeof value === 'function' && key !== 'key') {\n if (key === 'text' || key === 'html') {\n set(key, value());\n } else if (!key.startsWith('on')) {\n try {\n set(key, value());\n } catch {\n // left in place for the renderer\n }\n }\n }\n }\n return next;\n}\n\n/**\n * Restore context to its previous value\n * @param {string} key - Context key\n */\nexport function restoreContext(key) {\n const scope = currentScope();\n const entry = scope.get(key);\n if (!entry) return;\n\n const next = new Map(scope);\n if (entry.previous) {\n next.set(key, entry.previous);\n } else {\n next.delete(key);\n }\n setScope(next);\n}\n\n/**\n * Drop every context provided in the current execution.\n *\n * Values set through {@link globalStateManager} are not contexts and are left\n * alone; useContext() falls back to them again.\n */\nexport function clearAllContexts() {\n if (currentScope().size > 0) {\n setScope(EMPTY_SCOPE);\n }\n}\n\n/**\n * Context consumer to access provided context\n *\n * Falls back to {@link globalStateManager} when no context has been provided\n * for `key`.\n *\n * @param {string} key - Context key\n * @returns {*} Context value\n */\nexport function useContext(key) {\n const entry = currentScope().get(key);\n return entry ? entry.value : globalState.get(key);\n}\n"],
5
+ "mappings": ";AAKA,IAAM,cAAc,oBAAI,IAAI;AAOrB,SAAS,YAAY,eAAe,CAAC,GAAG;AAC3C,QAAM,QAAQ,IAAI,IAAI,OAAO,QAAQ,YAAY,CAAC;AAElD,SAAO;AAAA,IACH,IAAI,KAAK;AACL,aAAO,MAAM,IAAI,GAAG;AAAA,IACxB;AAAA,IAEA,IAAI,KAAK,OAAO;AACZ,YAAM,IAAI,KAAK,KAAK;AACpB,aAAO;AAAA,IACX;AAAA,IAEA,IAAI,KAAK;AACL,aAAO,MAAM,IAAI,GAAG;AAAA,IACxB;AAAA,IAEA,OAAO,KAAK;AACR,aAAO,MAAM,OAAO,GAAG;AAAA,IAC3B;AAAA,IAEA,QAAQ;AACJ,YAAM,MAAM;AACZ,aAAO;AAAA,IACX;AAAA,IAEA,WAAW;AACP,aAAO,OAAO,YAAY,KAAK;AAAA,IACnC;AAAA;AAAA,IAGA,WAAW;AAAA,EACf;AACJ;AASO,IAAM,qBAAqB;AAAA,EAC9B,IAAI,KAAK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