mobx-mantle 0.6.1 → 0.7.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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/services.tsx","../src/config.ts","../src/model-scope.tsx","../src/mantle.tsx","../src/observer.ts","../src/decorators.ts","../src/behavior.ts","../src/internals.ts","../src/useBehavior.ts","../src/shared.ts"],"sourcesContent":["import React from 'react';\nimport { globalConfig } from './config';\n\ndeclare const serviceType: unique symbol;\n/** Class tokens and typed symbols are also valid tsyringe injection tokens. */\nexport type ServiceToken<T extends object> = (new (...args: any[]) => T) | (symbol & { readonly [serviceType]: T });\nexport type ServiceResolver = <T extends object>(token: ServiceToken<T>) => T;\nexport function createServiceToken<T extends object>(description: string): ServiceToken<T> {\n return Symbol(description) as ServiceToken<T>;\n}\n\nexport const ServiceContext = React.createContext<ServiceResolver | undefined>(undefined);\nexport function ServiceProvider({ resolve, children }: { resolve: ServiceResolver; children?: React.ReactNode }) {\n return <ServiceContext.Provider value={resolve}>{children}</ServiceContext.Provider>;\n}\n\ninterface ServiceScope {\n resolve: ServiceResolver | undefined;\n values: WeakSet<object>;\n}\nlet constructingScope: ServiceScope | undefined;\nconst scopes = new WeakMap<object, ServiceScope>();\n\nfunction runWithScope<T>(scope: ServiceScope, construct: () => T): T {\n const previous = constructingScope;\n constructingScope = scope;\n try { return construct(); } finally { constructingScope = previous; }\n}\n\n/** Synchronous construction scope, also useful outside React. Does not own services. */\nexport function withInjectionScope<T>(resolve: ServiceResolver | undefined, construct: () => T): T {\n return runWithScope({ resolve: resolve ?? globalConfig.resolveService, values: new WeakSet() }, construct);\n}\nexport function captureServiceScope(owner: object): void {\n scopes.set(owner, constructingScope ?? { resolve: globalConfig.resolveService, values: new WeakSet() });\n}\nexport function resolveService<T extends object>(owner: object, token: ServiceToken<T>): T {\n return resolveInScope(scopes.get(owner), token);\n}\n\n/** Resolve during synchronous construction/onCreate, or inside withInjectionScope(). */\nexport function inject<T extends object>(token: ServiceToken<T>): T {\n if (!constructingScope) {\n throw new Error('[mobx-mantle] inject() requires an active construction scope. Use this.inject() in later methods, or withInjectionScope() outside React.');\n }\n return resolveInScope(constructingScope, token);\n}\n\nfunction resolveInScope<T extends object>(scope: ServiceScope | undefined, token: ServiceToken<T>): T {\n if (!scope?.resolve) throw new Error('[mobx-mantle] Service injection requires configure({ resolveService }), a ServiceProvider, or withInjectionScope() during construction.');\n const value = scope.resolve(token);\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') {\n throw new Error('[mobx-mantle] Services must be objects or functions; wrap primitive configuration in an object.');\n }\n scope.values.add(value);\n return value;\n}\nexport function isServiceValue(owner: object, value: unknown): boolean {\n return scopes.get(owner)?.values.has(value as object) ?? false;\n}\nexport function withOwnerServiceScope<T>(owner: object, construct: () => T): T {\n const scope = scopes.get(owner);\n if (!scope) throw new Error('[mobx-mantle] Missing owner service scope.');\n return runWithScope(scope, construct);\n}\n","import { configure as mobxConfigure } from 'mobx';\nimport type { ServiceResolver } from './services';\n\n/** Options for the watch method */\nexport interface WatchOptions {\n /** Debounce the callback by N milliseconds */\n delay?: number;\n /** Run callback immediately with current value */\n fireImmediately?: boolean;\n}\n\n/** Options for the effect method */\nexport interface EffectOptions {\n /** Debounce the effect by N milliseconds */\n delay?: number;\n}\n\n/**\n * Error context passed to the onError handler\n */\nexport interface MantleErrorContext {\n /** The lifecycle phase where the error occurred */\n phase: 'onLayoutMount' | 'onMount' | 'onUpdate' | 'onUnmount' | 'watch' | 'effect' | 'sync';\n /** The Component or Behavior class name */\n name: string;\n /** Whether the error came from a Behavior (true) or a Component (false) */\n isBehavior: boolean;\n}\n\n/**\n * Global configuration options for mobx-mantle\n */\nexport interface MantleConfig {\n /** Application service resolver, captured at construction. Explicit service scopes override it. */\n resolveService?: ServiceResolver;\n /** Whether to automatically make Component/Behavior instances observable (default: true) */\n autoObservable?: boolean;\n /**\n * Cache per-class prototype annotation data (getters, methods) so repeated\n * instantiations of the same class skip the prototype walk (default: true).\n * Turn off only if a class's prototype is mutated between instantiations.\n */\n cacheAnnotations?: boolean;\n /** Global error handler for lifecycle errors. Defaults to console.error. */\n onError?: (error: unknown, context: MantleErrorContext) => void;\n /**\n * Set true to opt into process-wide permissive MobX actions (default: false).\n * By default Mantle preserves the host's MobX policy. Synchronous methods\n * and lifecycle callbacks are actions; async continuations should use\n * runInAction. Configure before the first component or behavior is created.\n */\n manageMobxActions?: boolean;\n}\n\nexport const globalConfig: MantleConfig = {\n autoObservable: true,\n cacheAnnotations: true,\n manageMobxActions: false,\n};\n\nlet actionPolicyApplied = false;\n\n/**\n * @internal Apply the MobX action policy once, lazily at the first\n * component/behavior instantiation. Lazy (rather than at import) so an app\n * can opt in with configure({ manageMobxActions: true }) during startup,\n * regardless of module import order.\n */\nexport function applyMobxActionPolicy(): void {\n if (actionPolicyApplied) return;\n actionPolicyApplied = true;\n if (globalConfig.manageMobxActions === true) {\n mobxConfigure({ enforceActions: 'never' });\n }\n}\n\n/** @internal Report a lifecycle error through the configured handler or console.error */\nexport function reportError(error: unknown, context: MantleErrorContext): void {\n if (globalConfig.onError) {\n globalConfig.onError(error, context);\n } else {\n console.error(\n `[mobx-mantle] Error in ${context.isBehavior ? 'behavior' : 'component'} ${context.name}.${context.phase}():`,\n error,\n );\n }\n}\n\n/**\n * Configure global defaults for mobx-mantle.\n * Settings can still be overridden per-component in createComponent options.\n */\nexport function configure(config: MantleConfig): void {\n Object.assign(globalConfig, config);\n}\n","import React from 'react';\nimport type { Component } from './mantle';\n\nexport type ModelClass<C extends Component<any> = Component<any>> = new (...args: any[]) => C;\nexport interface ModelSubstitution<C extends Component<any> = Component<any>> {\n /** Runs for each instance instead of its original constructor. Supply data/callbacks only. */\n state: () => object;\n /** Required for integrated render() classes; optional for separate templates. */\n template?: (model: C) => React.JSX.Element;\n}\nexport const ModelContext = React.createContext<ReadonlyMap<ModelClass, ModelSubstitution> | undefined>(undefined);\n/** Construction policy. The mounted tree takes a snapshot; remount to change it. */\nexport function ModelProvider({ models, children }: { models: ReadonlyMap<ModelClass, ModelSubstitution>; children?: React.ReactNode }) {\n const [snapshot] = React.useState(() => new Map(Array.from(models, ([type, replacement]) => [type, { ...replacement }])));\n return <ModelContext.Provider value={snapshot}>{children}</ModelContext.Provider>;\n}\nconst identities = new WeakMap<object, ModelClass>();\nexport function setModelIdentity(model: object, type: ModelClass): void { identities.set(model, type); }\n/** Logical identity works for real and substituted models. It does not fake instanceof. */\nexport function isModel<C extends Component<any>>(model: object, type: abstract new (...args: any[]) => C): model is C {\n const logical = identities.get(model);\n return model instanceof type || logical === (type as Function) || !!logical && logical.prototype instanceof type;\n}\r\n","import { ServiceContext, captureServiceScope, resolveService, isServiceValue, withInjectionScope, withOwnerServiceScope, type ServiceToken } from './services';\nimport { ModelContext, isModel, setModelIdentity } from './model-scope';\nimport React, { useRef, useEffect, forwardRef as reactForwardRef, memo, type Ref, type JSX } from 'react';\nimport { makeObservable, observable, computed, runInAction, reaction, autorun, type AnnotationsMap, createAtom, isObservableProp, type IAtom, _getGlobalState } from 'mobx';\nimport { useMantleObserver, useIsomorphicLayoutEffect, type RenderReactionHolder } from './observer';\nimport {\n type BehaviorEntry,\n isBehavior,\n layoutMountBehavior,\n mountBehavior,\n unmountBehavior,\n warnUncollectedBehaviors,\n} from './behavior';\nimport { globalConfig, reportError, applyMobxActionPolicy, type WatchOptions, type EffectOptions } from './config';\nimport { getAnnotations } from './decorators';\nimport {\n type ReactiveSpec,\n type ProtoInfo,\n registerReactive,\n activateSpecs,\n collectProtoInfo,\n smartBind,\n toWatchExpression,\n} from './internals';\nimport type { MaybeGetter } from './reactive-args';\n\n// Re-export config utilities\nexport { configure, type MantleConfig, type MantleErrorContext, type WatchOptions, type EffectOptions } from './config';\n\n// Re-export decorators for single-import convenience\nexport { observable, action, computed } from './decorators';\n\n/** Tracks refs created by Component.ref() — no footprint on the object itself */\nconst componentRefs = new WeakSet();\n\n/**\n * A stable, wrapper-owned reference to the currently mounted Mantle instance.\n * The object identity survives an HMR instance replacement so descendants do\n * not retain the discarded model.\n */\ninterface ComponentHandle {\n current: Component<any> | undefined;\n}\n\n/** Carries the nearest logical Mantle ancestor without adding a DOM wrapper. */\nconst ComponentParentContext = React.createContext<ComponentHandle | undefined>(undefined);\n\n/** Runtime-only ancestry — deliberately absent from observable/serialized state. */\nconst componentParents = new WeakMap<Component<any>, ComponentHandle | undefined>();\n\ninterface ComponentConstructionScope {\n expectedClass: Function;\n parentHandle: ComponentHandle | undefined;\n consumed: boolean;\n}\n\n/**\n * React supplies context before the model exists, while derived field\n * initializers run immediately after super(). This short-lived scope bridges\n * those two moments without changing public constructor signatures.\n */\nlet activeComponentConstruction: ComponentConstructionScope | undefined;\n\nfunction constructComponent<C extends Component<any>>(\n ComponentClass: new (...args: any[]) => C,\n props: unknown,\n parentHandle: ComponentHandle | undefined\n): C {\n const previousScope = activeComponentConstruction;\n const scope: ComponentConstructionScope = {\n expectedClass: ComponentClass,\n parentHandle,\n consumed: false,\n };\n\n activeComponentConstruction = scope;\n try {\n return new ComponentClass(props);\n } finally {\n activeComponentConstruction = previousScope;\n }\n}\n\nfunction captureConstructingComponentParent(instance: Component<any>): void {\n const scope = activeComponentConstruction;\n if (\n !scope ||\n scope.consumed ||\n instance.constructor !== scope.expectedClass\n ) {\n return;\n }\n\n scope.consumed = true;\n componentParents.set(instance, scope.parentHandle);\n}\n\n/** Shallow-compare two objects by own enumerable keys */\nfunction shallowEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n for (const key of keysA) {\n if (a[key] !== b[key]) return false;\n }\n return true;\n}\n\n/**\n * Props holder built on MobX's public atom API. Reads are tracked like any\n * observable. Writes come in two flavors:\n * - setSilently: update the value without notifying observers — safe during\n * React's render phase (see Component._syncProps)\n * - set: update and notify observers — called from useLayoutEffect after\n * React finishes the render pass\n */\nclass PropsBox<P> {\n private _atom: IAtom;\n private _value: P;\n\n /**\n * @internal The owning component's render reaction. Reads coming from it\n * are not tracked: React already re-renders the component on prop change\n * (via memo), so letting the render reaction observe the props atom would\n * only schedule a redundant second render after every prop change.\n * Computeds, watchers, and other components track normally.\n */\n _renderReaction: RenderReactionHolder | null = null;\n\n constructor(value: P, name: string) {\n this._value = value;\n this._atom = createAtom(name);\n }\n\n get(): P {\n const own = this._renderReaction?.current;\n if (!own || _getGlobalState().trackingDerivation !== own) {\n this._atom.reportObserved();\n }\n return this._value;\n }\n\n setSilently(value: P): void {\n this._value = value;\n }\n\n set(value: P): void {\n this._value = value;\n this._atom.reportChanged();\n }\n}\n\nexport type ComponentConstructor<C extends Component<any> = Component<any>> =\n abstract new (...args: any[]) => C;\n\nexport class Component<P = {}> {\n /** @internal */\n _propsBox!: PropsBox<P>;\n\n constructor(props?: P) {\n this._propsBox = new PropsBox(props as P, `${this.constructor.name}.props`);\n captureConstructingComponentParent(this);\n captureServiceScope(this);\n }\n\n get props(): P {\n return this._propsBox.get();\n }\n\n /** Resolve through the scope captured during construction; preserve service identity. */\n inject<T extends object>(token: ServiceToken<T>): T { return resolveService(this, token); }\n\n /** Return the immediate ancestor in the live Mantle view tree. */\n getParent(): Component<any> | undefined {\n return componentParents.get(this)?.current;\n }\n\n /** Find the nearest parent with the supplied logical model identity. */\n findParent<C extends Component<any>>(\n type: ComponentConstructor<C>\n ): C | undefined {\n for (const parent of this.getParents()) {\n if (isModel(parent, type)) return parent;\n }\n return undefined;\n }\n\n /** Return all Mantle parents, ordered from the immediate parent to the root. */\n getParents(): readonly Component<any>[] {\n const parents: Component<any>[] = [];\n let current = this.getParent();\n while (current) {\n parents.push(current);\n current = current.getParent();\n }\n return parents;\n }\n\n /** Return the highest Mantle ancestor, or this instance when already root. */\n getRoot(): Component<any> {\n const parents = this.getParents();\n return parents[parents.length - 1] ?? this;\n }\n\n /** @internal — called by createComponent to silently update props during render */\n _syncProps(value: P) {\n // Update the value without triggering MobX notifications. React renders\n // the component tree synchronously — if we notified here, MobX would\n // flush reactions and try to update other observer components while\n // React is still rendering, causing:\n // \"Cannot update component A while rendering component B\"\n //\n // The value is updated so this._propsBox.get() returns the correct value\n // during render. Observers are notified separately in useLayoutEffect.\n this._propsBox.setSilently(value);\n }\n\n forwardRef?: Ref<any>;\n\n /** @internal */\n _behaviors: BehaviorEntry[] = [];\n\n /** @internal */\n _watchDisposers: (() => void)[] = [];\n\n /** @internal — pre-mount watch/effect registrations, materialized at mount */\n _reactiveSpecs: ReactiveSpec[] = [];\n\n /** @internal — true after the first (layout) mount */\n _mounted = false;\n\n /** @internal — set when effects clean up so StrictMode replay can resurrect watchers */\n _wasUnmounted = false;\n\n onCreate?(props: P): void;\n onLayoutMount?(): void | (() => void);\n onMount?(): void | (() => void);\n onUpdate?(): void;\n onUnmount?(): void;\n\n ref<T extends HTMLElement = HTMLElement>(): { current: T | null } {\n const r = { current: null } as { current: T | null };\n componentRefs.add(r);\n return r;\n }\n\n /**\n * Register a cleanup function to run automatically on unmount.\n * Returns a function that can be called for early cleanup.\n *\n * Cleanups are one-shot: they are not re-created during React StrictMode's\n * same-instance effect replay. Call this from onMount (which is replayed),\n * or use effect() for a replay-safe setup/teardown pair.\n */\n addCleanup(cleanup: () => void): () => void {\n if (process.env.NODE_ENV !== 'production' && !this._mounted) {\n console.warn(\n `[mobx-mantle] ${this.constructor.name}.addCleanup() called before mount. ` +\n `Cleanups are one-shot: they run when mount effects clean up and are not ` +\n `re-created during React StrictMode's same-instance effect replay. Acquire ` +\n `resources in onMount(), or use effect() for a replay-safe setup/teardown pair.`\n );\n }\n return this._addCleanup(cleanup);\n }\n\n /** @internal — addCleanup without the pre-mount dev warning (used by watch/effect) */\n _addCleanup(cleanup: () => void): () => void {\n let active = true;\n\n const dispose = () => {\n if (!active) return;\n active = false;\n try {\n runInAction(cleanup);\n } finally {\n const idx = this._watchDisposers.indexOf(dispose);\n if (idx !== -1) this._watchDisposers.splice(idx, 1);\n }\n };\n\n this._watchDisposers.push(dispose);\n return dispose;\n }\n\n /**\n * Watch a reactive expression and run a callback when it changes.\n * Automatically disposed on unmount. Watchers declared before mount\n * (field initializers, onCreate) are re-created during React StrictMode's\n * same-instance effect replay.\n *\n * @param source - Reactive expression (getter) to watch, or a MaybeGetter\n * argument passed through as-is. To watch a value that is itself a\n * function, wrap it: `watch(() => this.callback, …)`\n * @param callback - Called when the expression result changes\n * @param options - Optional configuration (delay, fireImmediately)\n * @returns Dispose function for early teardown\n * \n * @example\n * ```tsx\n * onMount() {\n * this.watch(\n * () => this.query,\n * async (query) => {\n * if (query.length > 2) {\n * this.results = await searchApi(query);\n * }\n * },\n * { delay: 300 }\n * );\n * }\n * ```\n */\n watch<T>(\n source: MaybeGetter<T>,\n callback: (value: T, prevValue: T | undefined) => void,\n options?: WatchOptions\n ): () => void {\n // A function is the tracked expression; a plain value is a constant\n // (dev-warns unless fireImmediately — a constant watch can never fire).\n // To watch a value that IS a function, wrap it: watch(() => this.callback, …)\n const expr = toWatchExpression(source, options?.fireImmediately, this.constructor.name);\n return registerReactive(this, () => {\n const dispose = reaction(\n expr,\n (value, prevValue) => {\n try {\n callback(value, prevValue);\n } catch (e) {\n reportError(e, { phase: 'watch', name: this.constructor.name, isBehavior: false });\n }\n },\n {\n delay: options?.delay,\n fireImmediately: options?.fireImmediately,\n }\n );\n\n return this._addCleanup(dispose);\n });\n }\n\n /**\n * Run a side effect that auto-tracks reactive dependencies.\n * Re-runs whenever any accessed observable changes.\n * Automatically disposed on unmount. Effects declared before mount\n * (field initializers, onCreate) are re-created during React StrictMode's\n * same-instance effect replay.\n *\n * Best for simple synchronization (DOM updates, logging). For complex\n * side effects with explicit triggers, prefer `watch()`.\n *\n * @param fn - Effect function. May return a cleanup function.\n * @param options - Optional configuration (delay)\n * @returns Dispose function for early teardown\n * \n * @example\n * ```tsx\n * onMount() {\n * this.effect(() => {\n * document.title = `${this.items.length} items`;\n * });\n * }\n * ```\n *\n * @example With cleanup\n * ```tsx\n * onMount() {\n * this.effect(() => {\n * const handler = () => console.log(this.count);\n * window.addEventListener('click', handler);\n * return () => window.removeEventListener('click', handler);\n * });\n * }\n * ```\n */\n effect(\n fn: () => void | (() => void),\n options?: EffectOptions\n ): () => void {\n return registerReactive(this, () => {\n let cleanup: (() => void) | undefined;\n\n const dispose = autorun(\n () => {\n // Run previous cleanup before re-running effect\n runInAction(() => cleanup?.());\n cleanup = undefined;\n\n try {\n const result = fn();\n if (typeof result === 'function') {\n cleanup = result;\n }\n } catch (e) {\n reportError(e, { phase: 'effect', name: this.constructor.name, isBehavior: false });\n }\n },\n { delay: options?.delay }\n );\n\n return this._addCleanup(() => {\n runInAction(() => cleanup?.());\n dispose();\n });\n });\n }\n\n /** @internal */\n _disposeWatchers(): void {\n const disposers = this._watchDisposers.slice();\n this._watchDisposers.length = 0;\n\n for (const dispose of disposers) {\n dispose();\n }\n }\n\n /** @internal - Scan own properties for behavior instances and register them */\n _collectBehaviors(): void {\n for (const key of Object.keys(this)) {\n if (key.startsWith('_')) continue;\n const value = (this as any)[key];\n if (isBehavior(value) && !isServiceValue(this, value)) {\n this._behaviors.push({ instance: value });\n }\n }\n }\n\n /** @internal */\n _layoutMountBehaviors(): void {\n for (const behavior of this._behaviors) {\n layoutMountBehavior(behavior);\n }\n }\n\n /** @internal */\n _mountBehaviors(): void {\n for (const behavior of this._behaviors) {\n mountBehavior(behavior);\n }\n }\n\n /** @internal */\n _unmountBehaviors(): void {\n for (const behavior of this._behaviors) {\n unmountBehavior(behavior);\n }\n }\n\n render?(): JSX.Element | null;\n}\n\n/** Alias for Component - use when separating ViewModel from template */\nexport { Component as ViewModel };\n\n// Re-export from behavior module\nexport { createBehavior, Behavior } from './behavior';\n\n// Base class members that should not be made observable\nconst BASE_EXCLUDES = new Set([\n 'props',\n 'getParent',\n 'findParent',\n 'getParents',\n 'getRoot',\n '_propsBox',\n 'forwardRef', \n 'onCreate',\n 'onLayoutMount',\n 'onMount', \n 'onUpdate',\n 'onUnmount',\n 'render', \n 'ref',\n 'addCleanup',\n '_addCleanup',\n 'watch',\n 'effect',\n 'constructor',\n 'inject',\n '_behaviors',\n '_collectBehaviors',\n '_layoutMountBehaviors',\n '_mountBehaviors',\n '_unmountBehaviors',\n '_syncProps',\n '_watchDisposers',\n '_disposeWatchers',\n '_reactiveSpecs',\n '_mounted',\n '_wasUnmounted',\n]);\n\n/**\n * Detects if a value is a ref created by Component.ref()\n * These should use observable.ref to preserve object identity for React\n */\nfunction isComponentRef(value: unknown): boolean {\n return value !== null && typeof value === 'object' && componentRefs.has(value as object);\n}\n\n/** Per-class cache of prototype-derived info (getters, methods) */\nconst componentProtoInfo = new WeakMap<Function, ProtoInfo>();\n\n/**\n * Creates observable annotations for a Component subclass instance.\n * This is needed because makeAutoObservable doesn't work with inheritance.\n */\nfunction makeComponentObservable<T extends Component>(instance: T, autoBind: boolean) {\n const annotations: AnnotationsMap<T, never> = {} as AnnotationsMap<T, never>;\n\n // Collect own properties (instance state) → observable\n // Also check prototype for class field declarations (handles uninitialized fields)\n const ownKeys = new Set([\n ...Object.keys(instance),\n ...Object.keys(Object.getPrototypeOf(instance)),\n ]);\n\n for (const key of ownKeys) {\n if (BASE_EXCLUDES.has(key)) continue;\n if (key in annotations) continue;\n\n const value = (instance as any)[key];\n\n // Skip functions (these are handled via the prototype info)\n if (typeof value === 'function' || isServiceValue(instance, value)) continue;\n\n // Skip behavior instances (they're already observable)\n if (isBehavior(value)) {\n (annotations as any)[key] = observable.ref;\n continue;\n }\n\n // Use observable.ref for Component.ref() objects to preserve identity\n if (isComponentRef(value)) {\n (annotations as any)[key] = observable.ref;\n } else {\n (annotations as any)[key] = observable;\n }\n }\n\n // Prototype facts (getters → computed, methods to bind) are identical for\n // every instance of a class, so they're collected once and cached per class.\n const protoInfo = collectProtoInfo(instance, Component.prototype, BASE_EXCLUDES, componentProtoInfo);\n\n for (const key of protoInfo.computedKeys) {\n if (key in annotations) continue;\n (annotations as any)[key] = computed;\n }\n\n makeObservable(instance, annotations);\n\n // Methods: don't wrap in action (breaks observable tracking in render helpers).\n // Use smartBind: allows tracking in render context, batches mutations elsewhere.\n if (autoBind) {\n for (const key of protoInfo.methodKeys) {\n if (key in annotations) continue;\n const method = (instance as any)[key];\n if (typeof method === 'function') {\n (instance as any)[key] = smartBind(method, instance);\n }\n }\n }\n}\n\n/** The substitute owns normal Component infrastructure, never the real prototype. */\nclass SubstituteComponent extends Component<any> {}\nfunction installSubstituteState(instance: Component<any>, state: object): void {\n const annotations: Record<string, any> = {};\n for (const key of Reflect.ownKeys(state)) {\n if (typeof key !== 'string' || key.startsWith('_') || key in instance || BASE_EXCLUDES.has(key)) throw new Error('[mobx-mantle] Substitute state cannot replace framework member ' + String(key));\n const descriptor = Object.getOwnPropertyDescriptor(state, key)!;\n if (!('value' in descriptor)) throw new Error('[mobx-mantle] Substitute state must contain data/callbacks, not getters.');\n Object.defineProperty(instance, key, { value: descriptor.value, enumerable: true, writable: true, configurable: true });\n annotations[key] = observable.ref;\n }\n makeObservable(instance, annotations);\n}\n\ntype PropsOf<C> = C extends Component<infer P> ? P : object;\n\n/**\n * Return type for createComponent.\n * \n * Simple callable signature that works with libraries expecting ComponentType<P>\n * or strict function components (react-window, react-virtualized, etc.).\n * \n * Uses ReactElement | null rather than React.FC's looser ReactNode return type.\n */\nexport type MantleComponent<P> = (props: P) => React.ReactElement | null;\n\n/**\n * Return type for createForwardRef when you need typed ref forwarding.\n * \n * Use this when you need to forward refs to DOM elements or child components\n * and want TypeScript to know the ref type.\n */\nexport type ForwardRefMantleComponent<P, RefType> = \n ((props: P) => React.ReactElement | null) &\n React.ForwardRefExoticComponent<\n React.PropsWithoutRef<P> & React.RefAttributes<RefType>\n >;\n\nexport function createComponent<C extends Component<any>>(\n ComponentClass: new (...args: any[]) => C,\n templateOrOptions?: ((vm: C) => JSX.Element) | { autoObservable?: boolean }\n) {\n type P = PropsOf<C>;\n\n const template = typeof templateOrOptions === 'function' ? templateOrOptions : undefined;\n const options = typeof templateOrOptions === 'object' ? templateOrOptions : {};\n const { autoObservable = globalConfig.autoObservable } = options;\n\n const ReactComponent = reactForwardRef<unknown, P>((props, ref) => {\n const parentHandle = React.useContext(ComponentParentContext);\n const resolver = React.useContext(ServiceContext);\n const substitutions = React.useContext(ModelContext);\n const substitutedTemplate = useRef<typeof template>(undefined);\n const vmRef = useRef<C | null>(null);\n const componentHandleRef = useRef<ComponentHandle | null>(null);\n const classRef = useRef(ComponentClass);\n const prevPropsRef = useRef<P | null>(null);\n const propsNotifyingRef = useRef(false);\n // Identity of this component's render reaction, wired into PropsBox so\n // it can skip tracking self-reads. Stable across HMR instance swaps.\n const renderReactionRef = useRef<RenderReactionHolder>({ current: null });\n\n if (!componentHandleRef.current) {\n componentHandleRef.current = { current: undefined };\n }\n const componentHandle = componentHandleRef.current;\n\n // HMR: class identity changes when the module re-executes, but useRef\n // values survive (React Fast Refresh preserves hooks). On detection,\n // we simply discard the old instance and create fresh — clean slate.\n // In production this check is always false (class identity is stable).\n if (vmRef.current && classRef.current !== ComponentClass) {\n classRef.current = ComponentClass;\n vmRef.current = null;\n }\n\n if (!vmRef.current) {\n applyMobxActionPolicy();\n\n const substitution = substitutions?.get(ComponentClass);\n if (substitution && !substitution.template && !template) throw new Error('[mobx-mantle] A substituted integrated model requires an explicit test template.');\n const instance = withInjectionScope(resolver, () => substitution\n ? constructComponent(SubstituteComponent, props, parentHandle) as C\n : constructComponent(ComponentClass, props as P, parentHandle));\n substitutedTemplate.current = substitution?.template;\n setModelIdentity(instance, ComponentClass);\n if (substitution) installSubstituteState(instance, substitution.state());\n instance.forwardRef = ref;\n instance._propsBox._renderReaction = renderReactionRef.current;\n\n // Collect behavior instances from properties (must happen before makeObservable)\n if (!substitution) instance._collectBehaviors();\n\n // Check for Mantle decorator annotations first\n const decoratorAnnotations = getAnnotations(instance);\n \n if (substitution) {\n // State is annotated by reference once; never scan the original class.\n } else if (decoratorAnnotations) {\n // Mantle decorators: use collected annotations\n const annotations = { ...decoratorAnnotations };\n\n makeObservable(instance, annotations as AnnotationsMap<C, never>);\n\n // Bind methods not explicitly decorated, to preserve `this` without\n // an action wrapper (actions break observable tracking in render\n // helpers). smartBind allows tracking in render context and batches\n // mutations elsewhere.\n const protoInfo = collectProtoInfo(instance, Component.prototype, BASE_EXCLUDES, componentProtoInfo);\n for (const key of protoInfo.methodKeys) {\n if (key in annotations) continue;\n const method = (instance as any)[key];\n if (typeof method === 'function') {\n (instance as any)[key] = smartBind(method, instance);\n }\n }\n } else if (autoObservable) {\n makeComponentObservable(instance, true);\n } else {\n // For legacy decorator users: applies decorator metadata\n makeObservable(instance);\n }\n\n // Note: watch/effect registrations from field initializers and\n // onCreate stay dormant here. They come alive in the mount layout\n // effect (activateSpecs) — the commit phase — so renders React never\n // commits (Suspense, aborted transitions, SSR) leak no reactions.\n\n // Proxy forwards property access to instance.props, so reads are tracked\n // by MobX when used in reactions/computeds (same behavior as this.props)\n const reactiveProps = new Proxy({} as P, {\n get: (_, key) => (instance.props as any)[key],\n has: (_, key) => key in (instance.props as any),\n ownKeys: () => Reflect.ownKeys(instance.props as object),\n getOwnPropertyDescriptor: (_, key) =>\n Reflect.getOwnPropertyDescriptor(instance.props as object, key),\n });\n withOwnerServiceScope(instance, () => runInAction(() => instance.onCreate?.(reactiveProps)));\n\n // Dev check: fields first assigned in onCreate() (not declared as class\n // fields) were invisible to the annotation scan and are silently\n // non-reactive. Only meaningful in auto-observable mode — with\n // decorators, undecorated fields are inert by design.\n if (process.env.NODE_ENV !== 'production' && autoObservable && !decoratorAnnotations && !substitution) {\n for (const key of Object.keys(instance)) {\n if (BASE_EXCLUDES.has(key) || key.startsWith('_')) continue;\n const value = (instance as any)[key];\n if (typeof value === 'function' || isServiceValue(instance, value)) continue;\n if (!isObservableProp(instance, key)) {\n console.warn(\n `[mobx-mantle] ${ComponentClass.name}.${key} was first assigned in onCreate() ` +\n `and is not reactive. Declare it as a class field so it can be made observable.`\n );\n }\n }\n }\n\n vmRef.current = instance;\n prevPropsRef.current = props as P;\n }\n\n const vm = vmRef.current;\r\n const renderTemplate = substitutedTemplate.current ?? template;\n\n // Context can change when a component is genuinely reparented. Refresh\n // the WeakMap every render; descendants resolve through our stable handle.\n componentParents.set(vm, parentHandle);\n componentHandle.current = vm;\n\n // Dev warning: detect when a prop-triggered reaction causes a re-render.\n // This means a reaction is being used for derived state — a computed getter\n // would avoid the double render.\n if (process.env.NODE_ENV !== 'production' && propsNotifyingRef.current) {\n console.warn(\n `[mobx-mantle] ${ComponentClass.name}: A reaction to a prop change modified ` +\n `observable state, which caused an extra re-render. Consider using a ` +\n `computed getter instead.`\n );\n propsNotifyingRef.current = false;\n }\n\n // Silently update _propsBox.value_ so this.props returns the correct value\n // during render, without triggering MobX reactions (which would cause\n // \"Cannot update component A while rendering component B\").\n vm._syncProps(props as P);\n vm.forwardRef = ref;\n\n // After render completes, properly notify MobX observers of prop changes.\n // This enables reaction(() => this.props.x, ...) in lifecycle methods.\n // useLayoutEffect runs after React finishes the render pass, so it's safe\n // to flush reactions here.\n useIsomorphicLayoutEffect(() => {\n if (!shallowEqual(prevPropsRef.current, props)) {\n prevPropsRef.current = props as P;\n propsNotifyingRef.current = true;\n runInAction(() => {\n vm._propsBox.set(props);\n });\n // If a reaction triggered a synchronous re-render, the warning\n // already fired above. Clear the flag for the normal case.\n propsNotifyingRef.current = false;\n }\n });\n\n // [vm] dep ensures effects re-run when instance changes (HMR).\n // On normal renders vm is stable, so effects run once — same as [].\n useIsomorphicLayoutEffect(() => {\n // Commit reached: bring pre-mount watch/effect registrations alive\n // (first mount), or re-create the ones disposed when React StrictMode\n // replays mount effects with the same instance in development.\n // onMount/onLayoutMount registrations re-run on their own.\n activateSpecs(vm);\n\n vm._layoutMountBehaviors();\n let cleanup: (() => void) | undefined;\n try {\n const result = runInAction(() => vm.onLayoutMount?.());\n if (process.env.NODE_ENV !== 'production' && result instanceof Promise) {\n console.error(\n `[mobx-mantle] ${ComponentClass.name}.onLayoutMount() returned a Promise. ` +\n `Lifecycle methods must be synchronous. Use a sync onLayoutMount that ` +\n `calls an async method instead.`\n );\n }\n // Only a returned function is a cleanup; anything else (notably a\n // Promise from an async method) must not be called at unmount.\n cleanup = typeof result === 'function' ? (result as () => void) : undefined;\n } catch (e) {\n reportError(e, { phase: 'onLayoutMount', name: ComponentClass.name, isBehavior: false });\n }\n return () => {\n runInAction(() => cleanup?.());\n };\n }, [vm]);\n\n useEffect(() => {\n vm._mountBehaviors();\n let cleanup: (() => void) | undefined;\n try {\n const result = runInAction(() => vm.onMount?.());\n if (process.env.NODE_ENV !== 'production' && result instanceof Promise) {\n console.error(\n `[mobx-mantle] ${ComponentClass.name}.onMount() returned a Promise. ` +\n `Lifecycle methods must be synchronous. Use a sync onMount that ` +\n `calls an async method instead.`\n );\n }\n // Only a returned function is a cleanup; anything else (notably a\n // Promise from an async method) must not be called at unmount.\n cleanup = typeof result === 'function' ? (result as () => void) : undefined;\n } catch (e) {\n reportError(e, { phase: 'onMount', name: ComponentClass.name, isBehavior: false });\n }\n\n // Dev check: behaviors assigned after construction (in onCreate,\n // conditionally, or lazily) were invisible to _collectBehaviors, so\n // their lifecycle would silently never run.\n if (process.env.NODE_ENV !== 'production') {\n warnUncollectedBehaviors(vm, ComponentClass.name, vm._behaviors);\n }\n\n return () => {\n runInAction(() => cleanup?.());\n try {\n runInAction(() => vm.onUnmount?.());\n } catch (e) {\n reportError(e, { phase: 'onUnmount', name: ComponentClass.name, isBehavior: false });\n }\n vm._disposeWatchers();\n vm._unmountBehaviors();\n vm._wasUnmounted = true;\n };\n }, [vm]);\n\n // Called after every render (via useEffect)\n useEffect(() => {\n try {\n runInAction(() => vm.onUpdate?.());\n } catch (e) {\n reportError(e, { phase: 'onUpdate', name: ComponentClass.name, isBehavior: false });\n }\n });\n\n if (!renderTemplate && !vm.render) {\n throw new Error(\n `[mobx-mantle] ${ComponentClass.name}: Missing render() method. Either define render() in your Component class or pass a template function to createComponent().`\n );\n }\n\n // Only the render call is tracked by MobX. The reaction is owned by\n // Mantle (src/observer.ts) so PropsBox can recognize self-reads.\n const rendered = useMantleObserver(\n () => (renderTemplate ? renderTemplate(vm) : vm.render!()),\n ComponentClass.name,\n renderReactionRef.current\n );\n\n return (\n <ComponentParentContext.Provider value={componentHandle}>\n {rendered}\n </ComponentParentContext.Provider>\n );\n });\n\n // Wrap in React.memo to match observer()'s behavior — skip re-renders\n // when parent re-renders but props haven't changed (shallow comparison).\n return memo(ReactComponent) as MantleComponent<P>;\n}\n\n/**\n * Creates a React component with typed ref forwarding.\n * \n * Use this instead of createComponent when you need to forward refs to DOM elements\n * or child components and want proper TypeScript support for the ref type.\n * \n * @example\n * ```tsx\n * class FancyInput extends Component<Props> {\n * render() {\n * return <input ref={this.forwardRef} className=\"fancy\" />;\n * }\n * }\n * \n * const FancyInputComponent = createForwardRef<HTMLInputElement>(FancyInput);\n * \n * // Parent gets typed ref:\n * const inputRef = useRef<HTMLInputElement>(null);\n * <FancyInputComponent ref={inputRef} />\n * ```\n */\nexport function createForwardRef<RefType, C extends Component<any> = Component<any>>(\n ComponentClass: new (...args: any[]) => C,\n templateOrOptions?: ((vm: C) => JSX.Element) | { autoObservable?: boolean }\n): ForwardRefMantleComponent<PropsOf<C>, RefType> {\n // Same implementation as createComponent - the runtime behavior is identical.\n // Only the return type differs to provide proper ref typing.\n return createComponent(ComponentClass, templateOrOptions) as ForwardRefMantleComponent<PropsOf<C>, RefType>;\n}\r\n","import React, { memo, useRef, useSyncExternalStore, useEffect, useLayoutEffect } from 'react';\nimport { Reaction } from 'mobx';\n\n/**\n * useLayoutEffect that falls back to useEffect on the server, where layout\n * effects never run and React warns during renderToString. Neither runs\n * server-side; the fallback only silences the noise.\n */\nexport const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n\n/**\n * Holder linking a component instance to its render reaction, so PropsBox\n * can recognize \"my own render is reading me\" and skip tracking (React\n * already delivers prop changes through memo — tracking would only schedule\n * a redundant second render). Stable per React component instance; survives\n * HMR instance swaps.\n */\nexport interface RenderReactionHolder {\n current: Reaction | null;\n}\n\ninterface ObserverAdmin {\n reaction: Reaction | null;\n onStoreChange: (() => void) | null;\n stateVersion: symbol;\n name: string;\n holder: RenderReactionHolder | undefined;\n subscribe: (onStoreChange: () => void) => () => void;\n getSnapshot: () => symbol;\n}\n\n/**\n * Reactions are created during render, but React may never commit that\n * render (Suspense throws, aborted transitions, StrictMode's discarded\n * pass) — then no cleanup effect ever runs. The registry disposes reactions\n * whose owning component was garbage-collected without committing.\n * Committed components unregister in subscribe() and dispose through the\n * normal unsubscribe path.\n */\nconst uncommittedReactionRegistry =\n typeof FinalizationRegistry !== 'undefined'\n ? new FinalizationRegistry<ObserverAdmin>((adm) => {\n adm.reaction?.dispose();\n adm.reaction = null;\n })\n : undefined;\n\nif (process.env.NODE_ENV !== 'production' && !uncommittedReactionRegistry) {\n console.warn(\n '[mobx-mantle] FinalizationRegistry is not available in this environment. ' +\n 'Reactions created for renders that React discards cannot be cleaned up, ' +\n 'which can leak under Suspense and concurrent rendering.'\n );\n}\n\nconst isServer = typeof window === 'undefined';\n\nfunction createReaction(adm: ObserverAdmin): void {\n adm.reaction = new Reaction(`mantle-observer(${adm.name})`, () => {\n adm.stateVersion = Symbol();\n adm.onStoreChange?.();\n });\n if (adm.holder) {\n adm.holder.current = adm.reaction;\n }\n}\n\n/**\n * Track a render function with a MobX Reaction owned by Mantle (rather than\n * mobx-react-lite's useObserver). Owning the reaction exposes its identity —\n * that is what lets PropsBox skip self-notification (see RenderReactionHolder).\n *\n * On the server this renders untracked: no reaction is ever created, so\n * renderToString leaks nothing by construction.\n */\nexport function useMantleObserver<T>(render: () => T, name: string, holder?: RenderReactionHolder): T {\n if (isServer) {\n return render();\n }\n\n const admRef = useRef<ObserverAdmin | null>(null);\n\n if (!admRef.current) {\n const adm: ObserverAdmin = {\n reaction: null,\n onStoreChange: null,\n stateVersion: Symbol(),\n name,\n holder,\n subscribe(onStoreChange: () => void) {\n // Committed: normal effect lifecycle owns disposal from here on.\n uncommittedReactionRegistry?.unregister(adm);\n adm.onStoreChange = onStoreChange;\n\n if (!adm.reaction) {\n // The reaction was disposed before this commit (registry cleanup,\n // or a StrictMode unmount pass). Re-create it and force one\n // re-render so it tracks current dependencies.\n createReaction(adm);\n adm.stateVersion = Symbol();\n onStoreChange();\n }\n\n return () => {\n adm.onStoreChange = null;\n adm.reaction?.dispose();\n adm.reaction = null;\n if (adm.holder) {\n adm.holder.current = null;\n }\n };\n },\n getSnapshot() {\n return adm.stateVersion;\n },\n };\n admRef.current = adm;\n }\n\n const adm = admRef.current;\n adm.holder = holder;\n\n if (!adm.reaction) {\n // First render, or first render after disposal. Guard against the\n // never-committed case until subscribe() takes ownership.\n createReaction(adm);\n uncommittedReactionRegistry?.register(admRef, adm, adm);\n }\n\n useSyncExternalStore(adm.subscribe, adm.getSnapshot, adm.getSnapshot);\n\n let result!: T;\n let didThrow = false;\n let thrown: unknown;\n adm.reaction!.track(() => {\n try {\n result = render();\n } catch (e) {\n didThrow = true;\n thrown = e;\n }\n });\n if (didThrow) {\n throw thrown;\n }\n return result;\n}\n\n/**\n * Minimal observer() for plain function components — re-renders when any\n * observable read during render changes. Useful together with useBehavior()\n * in codebases that don't (or don't yet) use Mantle components.\n *\n * @example\n * ```tsx\n * const Toolbar = observer((props: Props) => {\n * const size = useBehavior(() => withWindowSize());\n * return <div>{size.width}px</div>;\n * });\n * ```\n */\nexport function observer<P extends object>(\n fc: ((props: P) => React.ReactElement | null) & { displayName?: string }\n): (props: P) => React.ReactElement | null {\n const name = fc.displayName || fc.name || 'observed';\n const Observed = (props: P) => useMantleObserver(() => fc(props), name);\n Observed.displayName = `observer(${name})`;\n return memo(Observed) as unknown as (props: P) => React.ReactElement | null;\n}\n","import * as mobx from 'mobx';\nimport { isServiceValue } from './services';\n\nexport const ANNOTATIONS = Symbol('mantle:annotations');\ntype Annotations = Record<string | symbol, any>;\ntype Context = { kind: string; name: string | symbol; metadata?: Record<symbol, unknown>; static?: boolean; private?: boolean };\nconst legacy = new WeakMap<object, Annotations>();\n\nfunction annotation(value: any, kind: 'field' | 'method' | 'getter') {\n return function (_target: any, key: string | symbol | Context, descriptor?: PropertyDescriptor): void {\n let map: Annotations;\n let name: string | symbol;\n if (typeof key === 'object') {\n if (key.static || key.private || key.kind !== kind) {\n throw new Error(`[mobx-mantle] This decorator requires a public instance ${kind}. Use an ordinary field, not an auto-accessor, for @observable.`);\n }\n if (!key.metadata) throw new Error('[mobx-mantle] TC39 decorators require Symbol.metadata. Load its polyfill before decorated classes.');\n // Metadata inherits from base metadata. Never mutate its annotation map.\n if (!Object.prototype.hasOwnProperty.call(key.metadata, ANNOTATIONS)) key.metadata[ANNOTATIONS] = Object.create(null);\n map = key.metadata[ANNOTATIONS] as Annotations;\n name = key.name;\n } else {\n if (typeof _target === 'function' || (kind === 'method' && typeof descriptor?.value !== 'function') || (kind === 'getter' && !descriptor?.get) || (kind === 'field' && descriptor)) {\n throw new Error(`[mobx-mantle] This decorator requires a public instance ${kind}.`);\n }\n map = legacy.get(_target) ?? Object.create(null);\n legacy.set(_target, map);\n name = key;\n }\n map[name] = value;\n };\n}\n\n/** Plain fields in either TypeScript decorator mode; no accessor keyword needed. */\nexport const observable = Object.assign(annotation(mobx.observable, 'field'), {\n ref: annotation(mobx.observable.ref, 'field'),\n shallow: annotation(mobx.observable.shallow, 'field'),\n deep: annotation(mobx.observable.deep, 'field'),\n struct: annotation(mobx.observable.struct, 'field'),\n});\nconst actionMethod = annotation(mobx.action.bound, 'method');\nconst actionField = annotation(mobx.action, 'field');\n/** Bound prototype method, or an arrow-function field (already bound); synchronous writes are batched. */\nexport const action = function (target: any, key: string | symbol | Context, descriptor?: PropertyDescriptor): void {\n const isField = typeof key === 'object' ? key.kind === 'field' : !descriptor;\n return (isField ? actionField : actionMethod)(target, key, descriptor);\n};\nexport const computed = annotation(mobx.computed, 'getter');\n\n/** Both Components and Behaviors apply this map once after construction. */\nexport function getAnnotations(instance: object): Annotations | undefined {\n const chain: object[] = [];\n for (let proto = Object.getPrototypeOf(instance); proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) chain.unshift(proto);\n const result: Annotations = Object.create(null);\n for (const proto of chain) {\n const constructor = (proto as any).constructor;\n const symbol = (Symbol as any).metadata;\n const metadata = symbol && Object.prototype.hasOwnProperty.call(constructor, symbol) ? constructor[symbol] : undefined;\n const modern = metadata && Object.prototype.hasOwnProperty.call(metadata, ANNOTATIONS) ? metadata[ANNOTATIONS] : undefined;\n for (const own of [legacy.get(proto), modern]) {\n if (!own) continue;\n for (const key of Reflect.ownKeys(own)) {\n if (key in result && result[key] !== own[key]) throw new Error(`[mobx-mantle] Cannot change the inherited annotation of ${String(key)}.`);\n result[key] = own[key];\n }\n }\n }\n for (const key of Reflect.ownKeys(result)) {\n // Avoid invoking computed getters while checking service field identity.\n const own = Object.getOwnPropertyDescriptor(instance, key);\n if (own && 'value' in own && isServiceValue(instance, own.value)) throw new Error(`[mobx-mantle] Leave service field ${String(key)} undecorated; its resolver owns observability.`);\n }\n return Reflect.ownKeys(result).length ? result : undefined;\n}\n","import { captureServiceScope, resolveService, isServiceValue, withOwnerServiceScope, type ServiceToken } from './services';\nimport { getAnnotations } from './decorators';\nimport { makeObservable, observable, computed, reaction, autorun, intercept, runInAction, type AnnotationsMap } from 'mobx';\nimport { globalConfig, reportError, applyMobxActionPolicy, type WatchOptions, type EffectOptions } from './config';\nimport {\n type ReactiveSpec,\n type ProtoInfo,\n registerReactive,\n activateSpecs,\n collectProtoInfo,\n smartBind,\n toWatchExpression,\n} from './internals';\nimport { toValue, type MaybeGetter } from './reactive-args';\n\n/**\n * Symbol marker to identify behavior instances. Registered globally\n * (Symbol.for) so detection works even when the module is duplicated across\n * bundles or entry points (e.g. the main entry and ./behaviors in a CJS\n * build each carrying their own copy).\n */\nexport const BEHAVIOR_MARKER = Symbol.for('mobx-mantle.behavior');\n\n// Behavior base class members that should not be made observable\nconst BEHAVIOR_EXCLUDES = new Set([\n 'onCreate',\n 'onLayoutMount',\n 'onMount',\n 'onUnmount',\n 'addCleanup',\n '_addCleanup',\n 'watch',\n 'effect',\n 'sync',\n 'constructor',\n 'inject',\n '_watchDisposers',\n '_disposeWatchers',\n '_reactiveSpecs',\n '_behaviors',\n '_pendingSyncs',\n '_syncWriting',\n '_mounted',\n '_wasUnmounted',\n]);\n\n/**\n * Placeholder returned by sync() during construction. The wrapper constructor\n * scans own fields right after onCreate, finds which key holds each marker,\n * swaps in the initial value, and registers the hidden sync effect for that\n * key. (Same post-onCreate scan window that behavior collection uses.)\n */\nclass SyncMarker {\n constructor(readonly source: () => unknown) {}\n}\n\n/**\n * Detects if a value looks like a React ref ({ current: ... })\n * These should use observable.ref to preserve object identity\n */\nfunction isRefLike(value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false;\n if (Array.isArray(value)) return false;\n return 'current' in value && Object.keys(value).length === 1;\n}\n\n/**\n * Base class for behaviors. Provides lifecycle method signatures for IDE autocomplete.\n * Extend this class and wrap with createBehavior() to create a factory.\n * \n * @example\n * ```tsx\n * class WindowSizeBehavior extends Behavior {\n * width = window.innerWidth;\n * onCreate(breakpoint = 768) { ... }\n * onMount() { ... }\n * }\n * export const withWindowSize = createBehavior(WindowSizeBehavior);\n * ```\n */\nexport class Behavior {\n constructor() { captureServiceScope(this); }\n inject<T extends object>(token: ServiceToken<T>): T { return resolveService(this, token); }\n /** @internal */\n _watchDisposers: (() => void)[] = [];\n\n /** @internal — pre-mount watch/effect registrations, materialized at mount */\n _reactiveSpecs: ReactiveSpec[] = [];\n\n /** @internal — child behaviors declared as fields, collected at construction */\n _behaviors: BehaviorEntry[] = [];\n\n /** @internal — true after the parent Component first mounts */\n _mounted = false;\n\n /** @internal — set when effects clean up so StrictMode replay can resurrect pre-mount watchers */\n _wasUnmounted = false;\n\n /** @internal — sync() markers awaiting the post-onCreate field scan; null once construction completes */\n _pendingSyncs: SyncMarker[] | null = [];\n\n /** @internal — true while the hidden sync effect writes a mirrored field (dev write-guard) */\n _syncWriting = false;\n\n onCreate?(...args: any[]): void;\n onLayoutMount?(): void | (() => void);\n onMount?(): void | (() => void);\n onUnmount?(): void;\n\n /**\n * Register a cleanup function to run automatically on unmount.\n * Returns a function that can be called for early cleanup.\n *\n * Cleanups are one-shot: they are not re-created during React StrictMode's\n * same-instance effect replay. Call this from onMount (which is replayed),\n * or use effect() for a replay-safe setup/teardown pair.\n */\n addCleanup(cleanup: () => void): () => void {\n if (process.env.NODE_ENV !== 'production' && !this._mounted) {\n console.warn(\n `[mobx-mantle] ${this.constructor.name}.addCleanup() called before mount. ` +\n `Cleanups are one-shot: they run when mount effects clean up and are not ` +\n `re-created during React StrictMode's same-instance effect replay. ` +\n `Acquire resources in onMount(), or use effect() for a replay-safe ` +\n `setup/teardown pair.`\n );\n }\n return this._addCleanup(cleanup);\n }\n\n /** @internal — addCleanup without the pre-mount dev warning (used by watch/effect) */\n _addCleanup(cleanup: () => void): () => void {\n let active = true;\n\n const dispose = () => {\n if (!active) return;\n active = false;\n try {\n runInAction(cleanup);\n } finally {\n const idx = this._watchDisposers.indexOf(dispose);\n if (idx !== -1) this._watchDisposers.splice(idx, 1);\n }\n };\n\n this._watchDisposers.push(dispose);\n return dispose;\n }\n\n /**\n * Watch a reactive expression and run a callback when it changes.\n * Automatically disposed on unmount and re-created during React StrictMode's\n * same-instance effect replay.\n *\n * Safe to call from onCreate: registration is recorded and comes alive\n * when the parent commits (just before first paint), so the watcher\n * tracks observable fields correctly and renders that React discards\n * never leak reactions.\n *\n * @param source - Reactive expression (getter) to watch, or a MaybeGetter\n * argument passed through as-is. To watch a value that is itself a\n * function, wrap it: `watch(() => this.callback, …)`\n * @param callback - Called when the expression result changes\n * @param options - Optional configuration (delay, fireImmediately)\n * @returns Dispose function for early teardown\n *\n * @example\n * ```tsx\n * onCreate(url: string) {\n * this.url = url;\n * this.watch(() => this.url, () => this.fetchData());\n * }\n * ```\n */\n watch<T>(\n source: MaybeGetter<T>,\n callback: (value: T, prevValue: T | undefined) => void,\n options?: WatchOptions\n ): () => void {\n const expr = toWatchExpression(source, options?.fireImmediately, this.constructor.name);\n return registerReactive(this, () => {\n const dispose = reaction(\n expr,\n (value, prevValue) => {\n try {\n callback(value, prevValue);\n } catch (e) {\n reportError(e, { phase: 'watch', name: this.constructor.name, isBehavior: true });\n }\n },\n {\n delay: options?.delay,\n fireImmediately: options?.fireImmediately,\n }\n );\n\n return this._addCleanup(dispose);\n });\n }\n\n /**\n * Run a side effect that auto-tracks reactive dependencies.\n * Re-runs whenever any accessed observable changes.\n * Automatically disposed on unmount.\n * \n * Best for simple synchronization (DOM updates, logging). For complex\n * side effects with explicit triggers, prefer `watch()`.\n * \n * @param fn - Effect function. May return a cleanup function.\n * @param options - Optional configuration (delay)\n * @returns Dispose function for early teardown\n * \n * @example\n * ```tsx\n * onCreate() {\n * this.effect(() => {\n * console.log('Current value:', this.value);\n * });\n * }\n * ```\n */\n effect(\n fn: () => void | (() => void),\n options?: EffectOptions\n ): () => void {\n return registerReactive(this, () => {\n let cleanup: (() => void) | undefined;\n\n const dispose = autorun(\n () => {\n // Run previous cleanup before re-running effect\n runInAction(() => cleanup?.());\n cleanup = undefined;\n\n try {\n const result = fn();\n if (typeof result === 'function') {\n cleanup = result;\n }\n } catch (e) {\n reportError(e, { phase: 'effect', name: this.constructor.name, isBehavior: true });\n }\n },\n { delay: options?.delay }\n );\n\n return this._addCleanup(() => {\n runInAction(() => cleanup?.());\n dispose();\n });\n });\n }\n\n /**\n * Normalize a MaybeGetter argument into an ordinary field that stays\n * current. Call once in onCreate (or a field initializer) and assign the\n * result to a field; everywhere else, read the field like normal state:\n *\n * ```tsx\n * url!: string;\n *\n * onCreate(url: MaybeGetter<string>) {\n * this.url = this.sync(url); // the one convention line\n * this.watch(() => this.url, (u) => this.load(u));\n * }\n * refresh() { this.load(this.url); } // plain read, always current\n * ```\n *\n * - Plain value → the field just holds it (no effect registered).\n * - Getter → a hidden effect keeps the field updated whenever the getter's\n * observable sources change (alive from mount, like watch/effect).\n *\n * The sync is one-way (argument → field). Don't write to the field from\n * outside: the next source change overwrites it (dev mode warns).\n */\n sync<T>(source: MaybeGetter<T>): T {\n // A plain value IS its own snapshot forever — no machinery needed.\n if (typeof source !== 'function') {\n return source;\n }\n\n if (this._pendingSyncs === null) {\n // Construction is over; the field scan already ran, so a marker could\n // never be bound. Degrade to a one-time read.\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[mobx-mantle] ${this.constructor.name}.sync() called after construction. ` +\n `sync() only works in field initializers or onCreate; returning a ` +\n `one-time snapshot instead. Use watch()/effect() for post-mount reactions.`\n );\n }\n return toValue(source);\n }\n\n const marker = new SyncMarker(source as () => unknown);\n this._pendingSyncs.push(marker);\n // The marker briefly occupies the field; the post-onCreate scan replaces\n // it with the real initial value before anything else can read it.\n return marker as unknown as T;\n }\n\n /** @internal */\n _disposeWatchers(): void {\n const disposers = this._watchDisposers.slice();\n this._watchDisposers.length = 0;\n\n for (const dispose of disposers) {\n dispose();\n }\n }\n}\n\n/** Per-class cache of prototype-derived info (getters, methods) */\nconst behaviorProtoInfo = new WeakMap<Function, ProtoInfo>();\n\n/**\n * Makes a behavior instance observable, handling inheritance properly.\n * Works with classes that extend Behavior or plain classes.\n */\nfunction makeBehaviorObservable<T extends object>(instance: T): void {\n const annotations: AnnotationsMap<T, never> = {} as AnnotationsMap<T, never>;\n\n // Collect own properties → observable\n const ownKeys = new Set([\n ...Object.keys(instance),\n ...Object.keys(Object.getPrototypeOf(instance)),\n ]);\n\n for (const key of ownKeys) {\n if (BEHAVIOR_EXCLUDES.has(key)) continue;\n if (key in annotations) continue;\n\n const value = (instance as any)[key];\n if (typeof value === 'function' || isServiceValue(instance, value)) continue;\n\n // Child behaviors are already observable; keep their identity\n if (isBehavior(value)) {\n (annotations as any)[key] = observable.ref;\n continue;\n }\n\n // Use observable.ref for ref-like objects to preserve identity\n if (isRefLike(value)) {\n (annotations as any)[key] = observable.ref;\n } else {\n (annotations as any)[key] = observable;\n }\n }\n\n // Prototype facts (getters → computed, methods to bind) are\n // identical for every instance of a class; collected once, cached per class.\n const protoInfo = collectProtoInfo(instance, Behavior.prototype, BEHAVIOR_EXCLUDES, behaviorProtoInfo);\n\n for (const key of protoInfo.computedKeys) {\n if (key in annotations) continue;\n (annotations as any)[key] = computed;\n }\n makeObservable(instance, annotations);\n\n // Match Component method semantics. action.bound would make observable\n // reads inside behavior helpers untracked when a render/computed calls them.\n // smartBind preserves those dependencies and still batches handler writes.\n for (const key of protoInfo.methodKeys) {\n if (key in annotations) continue;\n const method = (instance as any)[key];\n if (typeof method === 'function') {\n (instance as any)[key] = smartBind(method, instance);\n }\n }\n}\n\n/** @internal */\nexport interface BehaviorEntry {\n instance: any;\n cleanup?: () => void;\n layoutCleanup?: () => void;\n}\n\n/**\n * Extracts parameter types from onCreate method\n */\ntype OnCreateParams<T> = T extends { onCreate(...args: infer A): any } ? A : [];\n\n/**\n * Extracts constructor parameter types\n */\ntype ConstructorParams<T> = T extends new (...args: infer A) => any ? A : [];\n\n/**\n * Determines the args for createBehavior:\n * - If constructor has args, use those\n * - Otherwise, if onCreate has args, use those\n */\ntype BehaviorArgs<T extends new (...args: any[]) => any> = \n ConstructorParams<T> extends [] \n ? OnCreateParams<InstanceType<T>> \n : ConstructorParams<T>;\n\n/**\n * Creates a behavior factory with automatic observable wrapping and lifecycle management.\n * \n * Returns a factory function (not a class) — use without `new`:\n * \n * @example Defining a behavior\n * ```tsx\n * class DragTrait extends Behavior {\n * ref!: RefObject<HTMLElement>;\n * \n * onCreate(ref: RefObject<HTMLElement>) {\n * this.ref = ref;\n * }\n * \n * onMount() {\n * this.ref.current?.addEventListener('pointerdown', this.onPointerDown);\n * return () => this.ref.current?.removeEventListener('pointerdown', this.onPointerDown);\n * }\n * }\n * \n * export const withDrag = createBehavior(DragTrait);\n * ```\n * \n * @example Using in a Component\n * ```tsx\n * class Editor extends Component<Props> {\n * canvas = this.ref<HTMLCanvasElement>();\n * \n * // No `new` keyword — factory function\n * drag = withDrag(this.canvas);\n * autosave = withAutosave('/api/save', 5000);\n * }\n * export default createComponent(Editor);\n * ```\n * \n * The `with` prefix convention signals that the component manages this behavior's lifecycle.\n */\n/**\n * Type that supports both `new` and direct call syntax\n */\ntype BehaviorFactory<Args extends any[], Instance> = {\n new (...args: Args): Instance;\n (...args: Args): Instance;\n};\n\nexport function createBehavior<T extends new (...args: any[]) => any>(\n Def: T,\n options?: { autoObservable?: boolean }\n): BehaviorFactory<BehaviorArgs<T>, InstanceType<T>> {\n // Internal class that wraps the user's behavior definition\n const BehaviorClass = class extends (Def as any) {\n static [BEHAVIOR_MARKER] = true;\n\n constructor(...args: any[]) {\n applyMobxActionPolicy();\n super(...args);\n\n // Call onCreate with args (if it exists). This runs BEFORE\n // makeObservable so the field scan sees the values onCreate assigns\n // (e.g. ref-like objects get observable.ref, preserving identity).\n // watch/effect calls made here are recorded as dormant specs and come\n // alive when the parent commits (activateSpecs in the mount relay) —\n // renders React never commits therefore leak no reactions.\n if (typeof this.onCreate === 'function') {\n withOwnerServiceScope(this, () => runInAction(() => this.onCreate!(...args)));\n }\n\n // Collect child behaviors declared as fields or assigned in onCreate,\n // mirroring Component behavior collection. The lifecycle relay\n // recurses into these. Underscore-prefixed keys are skipped,\n // consistent with the Component scan.\n const children: BehaviorEntry[] = [];\n for (const key of Object.keys(this)) {\n if (key.startsWith('_')) continue;\n const value = (this as any)[key];\n if (isBehavior(value) && !isServiceValue(this, value)) {\n children.push({ instance: value });\n }\n }\n (this as any)._behaviors = children;\n\n // Bind sync() markers: find which field holds each marker, swap in the\n // initial value (so makeObservable annotates a real value), and record\n // the key→source pairs. Must run before makeObservable.\n const syncedFields: Array<{ key: string; source: () => unknown }> = [];\n const pending: SyncMarker[] | null = (this as any)._pendingSyncs ?? null;\n if (Array.isArray(pending) && pending.length > 0) {\n for (const key of Object.keys(this)) {\n const value = (this as any)[key];\n if (value instanceof SyncMarker) {\n syncedFields.push({ key, source: value.source });\n (this as any)[key] = value.source();\n }\n }\n if (process.env.NODE_ENV !== 'production' && syncedFields.length !== pending.length) {\n console.warn(\n `[mobx-mantle] ${Def.name}: ${pending.length - syncedFields.length} sync() ` +\n `result(s) were not assigned to a field. Assign sync() directly to a ` +\n `field (this.url = this.sync(url)) so Mantle can keep it updated.`\n );\n }\n }\n (this as any)._pendingSyncs = null;\n\n // Make the instance observable (respects global config and per-behavior options)\n const autoObservable = options?.autoObservable ?? globalConfig.autoObservable;\n const annotations = getAnnotations(this);\n if (annotations) {\n makeObservable(this, annotations);\n const info = collectProtoInfo(this, Behavior.prototype, BEHAVIOR_EXCLUDES, behaviorProtoInfo);\n for (const key of info.methodKeys) if (!(key in annotations)) (this as any)[key] = smartBind((this as any)[key], this);\n } else if (autoObservable) {\n makeBehaviorObservable(this);\n } else {\n // For decorator users: applies decorator metadata\n makeObservable(this);\n }\n\n // Register the hidden sync effects — at the FRONT of the spec list, so\n // at mount activation every mirrored field refreshes before any\n // author-registered watcher fires (authors see current values).\n if (syncedFields.length > 0) {\n const self = this as any;\n const specs: ReactiveSpec[] = syncedFields.map(({ key, source }) => ({\n create: () => {\n const dispose = autorun(() => {\n try {\n const next = source(); // tracked read — this is the live link\n self._syncWriting = true;\n try {\n runInAction(() => {\n self[key] = next;\n });\n } finally {\n self._syncWriting = false;\n }\n } catch (e) {\n reportError(e, { phase: 'sync', name: self.constructor.name, isBehavior: true });\n }\n });\n return self._addCleanup(dispose);\n },\n stopped: false,\n dispose: null,\n }));\n self._reactiveSpecs.unshift(...specs);\n\n // Dev write-guard: the sync is one-way; an outside write works until\n // the next source change silently overwrites it. Warn at the write.\n if (process.env.NODE_ENV !== 'production') {\n for (const { key } of syncedFields) {\n try {\n intercept(self, key, (change: any) => {\n if (!self._syncWriting) {\n console.warn(\n `[mobx-mantle] ${Def.name}.${key} is a one-way synced field ` +\n `(this.sync()). Writing to it from outside will be overwritten ` +\n `by the next source change. Derive with a computed getter, or ` +\n `own the state in a plain field instead.`\n );\n }\n return change;\n });\n } catch {\n // Field not observable (custom annotations) — skip the guard.\n }\n }\n }\n }\n }\n };\n\n // Preserve the original class name for debugging\n Object.defineProperty(BehaviorClass, 'name', { value: Def.name });\n\n // Use Proxy to make the class callable without `new`\n // This allows both: withWindowSize(768) and new withWindowSize(768)\n return new Proxy(BehaviorClass, {\n apply(_target, _thisArg, args) {\n return new BehaviorClass(...args);\n },\n }) as unknown as BehaviorFactory<BehaviorArgs<T>, InstanceType<T>>;\n}\n\n\n/**\n * Checks if a value is a behavior instance created by createBehavior()\n */\nexport function isBehavior(value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false;\n return (value.constructor as any)?.[BEHAVIOR_MARKER] === true;\n}\n\n/**\n * @internal Child behaviors of a behavior instance, or an empty list for\n * plain (non-Behavior-derived) classes that never ran the collection scan.\n */\nfunction childBehaviors(inst: any): BehaviorEntry[] {\n return Array.isArray(inst._behaviors) ? inst._behaviors : [];\n}\n\n/**\n * @internal Relay functions recurse into nested behaviors. The visited set\n * guards against cycles (a parent assigned into a child's field); a cycle is\n * simply not relayed twice.\n */\nexport function layoutMountBehavior(behavior: BehaviorEntry, visited: WeakSet<object> = new WeakSet()): void {\n const inst = behavior.instance;\n if (visited.has(inst)) return;\n visited.add(inst);\n\n // Children mount before their parent, so the parent's lifecycle can rely\n // on live children.\n for (const child of childBehaviors(inst)) {\n layoutMountBehavior(child, visited);\n }\n\n // Bring pre-mount watch/effect registrations alive (first mount), or\n // re-create the ones disposed during StrictMode's same-instance effect replay.\n if (Array.isArray(inst._reactiveSpecs)) {\n activateSpecs(inst);\n } else {\n inst._mounted = true;\n }\n\n if ('onLayoutMount' in inst && typeof inst.onLayoutMount === 'function') {\n try {\n const result = runInAction(() => inst.onLayoutMount!());\n // Only a returned function is a cleanup; ignore a Promise from an async\n // method so unmount doesn't try to call it.\n behavior.layoutCleanup = typeof result === 'function' ? result : undefined;\n } catch (e) {\n reportError(e, { phase: 'onLayoutMount', name: inst.constructor.name, isBehavior: true });\n }\n }\n}\n\n/** @internal */\nexport function mountBehavior(behavior: BehaviorEntry, visited: WeakSet<object> = new WeakSet()): void {\n const inst = behavior.instance;\n if (visited.has(inst)) return;\n visited.add(inst);\n\n // Children before parent — mirror of layoutMountBehavior\n for (const child of childBehaviors(inst)) {\n mountBehavior(child, visited);\n }\n\n if ('onMount' in inst && typeof inst.onMount === 'function') {\n try {\n const result = runInAction(() => inst.onMount!());\n // Only a returned function is a cleanup; ignore a Promise from an async\n // method so unmount doesn't try to call it.\n behavior.cleanup = typeof result === 'function' ? result : undefined;\n } catch (e) {\n reportError(e, { phase: 'onMount', name: inst.constructor.name, isBehavior: true });\n }\n }\n}\n\n/** @internal */\nexport function unmountBehavior(behavior: BehaviorEntry, visited: WeakSet<object> = new WeakSet()): void {\n const inst = behavior.instance;\n if (visited.has(inst)) return;\n visited.add(inst);\n\n // Call layout cleanup if exists\n runInAction(() => behavior.layoutCleanup?.());\n\n // Call cleanup if exists\n runInAction(() => behavior.cleanup?.());\n\n // Call onUnmount if exists\n if ('onUnmount' in inst && typeof inst.onUnmount === 'function') {\n try {\n runInAction(() => inst.onUnmount!());\n } catch (e) {\n reportError(e, { phase: 'onUnmount', name: inst.constructor.name, isBehavior: true });\n }\n }\n\n // Dispose all watchers\n if (typeof inst._disposeWatchers === 'function') {\n inst._disposeWatchers();\n }\n\n // Allow StrictMode's same-instance effect replay to resurrect pre-mount watchers\n inst._wasUnmounted = true;\n\n // Children tear down after their parent's onUnmount, in reverse of mount order\n const children = childBehaviors(inst);\n for (let i = children.length - 1; i >= 0; i--) {\n unmountBehavior(children[i], visited);\n }\n}\n\n/**\n * @internal Dev-only: warn about behavior instances sitting in fields that\n * were never collected into the lifecycle relay (assigned after\n * construction — conditionally, lazily, or in a Component's onCreate).\n * Their onMount/watchers/cleanup would otherwise silently never run.\n * Recurses into collected behaviors to catch late-assigned grandchildren.\n */\nexport function warnUncollectedBehaviors(\n host: object,\n hostName: string,\n entries: BehaviorEntry[],\n visited: WeakSet<object> = new WeakSet()\n): void {\n if (visited.has(host)) return;\n visited.add(host);\n\n const collected = new Set(entries.map((e) => e.instance));\n for (const key of Object.keys(host)) {\n if (key.startsWith('_')) continue;\n const value = (host as any)[key];\n if (isBehavior(value) && !isServiceValue(host, value) && !collected.has(value)) {\n console.warn(\n `[mobx-mantle] ${hostName}.${key} holds a behavior that was assigned after ` +\n `construction, so its lifecycle (onMount, watchers, cleanup) will never run. ` +\n `Create behaviors as class fields so they are collected when the host is constructed.`\n );\n }\n }\n\n for (const entry of entries) {\n warnUncollectedBehaviors(\n entry.instance,\n entry.instance.constructor.name,\n childBehaviors(entry.instance),\n visited\n );\n }\n}\r\n","import { _getGlobalState, runInAction } from 'mobx';\nimport { globalConfig } from './config';\nimport type { MaybeGetter } from './reactive-args';\n\n/**\n * Bind a model method without hiding observable reads from an enclosing\n * render/computed/reaction. Outside a tracking context the same method runs in\n * an action so event-handler mutations are still batched.\n *\n * Component and Behavior methods deliberately share this policy. A plain\n * `action.bound` would make a read helper such as `size.below(640)` untracked,\n * so the consumer would never subscribe to `size.width`.\n */\nexport function smartBind<T extends (...args: any[]) => any>(fn: T, context: any): T {\n return function (this: any, ...args: any[]) {\n const globalState = _getGlobalState();\n const isInTrackingContext = globalState.trackingDerivation !== null;\n\n if (isInTrackingContext) {\n return fn.apply(context, args);\n }\n return runInAction(() => fn.apply(context, args));\n } as T;\n}\n\n// smartBind and PropsBox.get rely on MobX's internal global state shape\n// (trackingDerivation). Fail loudly if a MobX upgrade changes it instead of\n// silently breaking method tracking or mutation batching.\nif (process.env.NODE_ENV !== 'production') {\n const globalState = _getGlobalState() as Record<string, unknown> | undefined;\n if (!globalState || !('trackingDerivation' in globalState)) {\n console.warn(\n '[mobx-mantle] MobX internal state no longer exposes trackingDerivation. ' +\n 'smartBind cannot detect tracking contexts and props reads cannot skip ' +\n 'self-notification, so method calls may not batch correctly and prop ' +\n 'changes may double-render. Check mobx version compatibility.'\n );\n }\n}\n\n/**\n * Normalize a watch source: a function is the tracked expression; a plain\n * value becomes a constant expression. A constant with no fireImmediately is\n * an unreachable watch — the callback can never fire — which is the signature\n * of a missing-arrow mistake, so dev mode warns.\n */\nexport function toWatchExpression<T>(\n source: MaybeGetter<T>,\n fireImmediately: boolean | undefined,\n ownerName: string\n): () => T {\n if (typeof source === 'function') {\n return source as () => T;\n }\n if (process.env.NODE_ENV !== 'production' && !fireImmediately) {\n console.warn(\n `[mobx-mantle] ${ownerName}.watch() received a plain value, which can never ` +\n `change — the callback will never fire. Pass a getter (() => expr) to watch ` +\n `a live source, or add { fireImmediately: true } if a single immediate call ` +\n `is intended.`\n );\n }\n return () => source;\n}\n\n/**\n * A watch/effect registration. `create` builds the underlying MobX reaction\n * and returns its disposer. Specs registered before mount are kept so the\n * reaction can be re-created if the host unmounts and remounts with the same\n * instance — React StrictMode does exactly this in development.\n */\nexport interface ReactiveSpec {\n create: () => () => void;\n stopped: boolean;\n dispose: (() => void) | null;\n}\n\n/** Common reactive bookkeeping shape shared by Component and Behavior */\nexport interface ReactiveHost {\n _reactiveSpecs: ReactiveSpec[];\n _mounted: boolean;\n _wasUnmounted: boolean;\n}\n\n/**\n * Register a watch/effect on a host.\n *\n * - Before mount (field initializers, onCreate): recorded as a dormant spec.\n * activateSpecs() brings it alive in the commit phase (useLayoutEffect),\n * so renders React never commits (Suspense throws, aborted transitions,\n * server rendering) create no live MobX reactions.\n * - At or after mount (onLayoutMount, onMount, event handlers): created\n * immediately with no spec — those callsites re-run on remount, so they\n * re-register naturally.\n *\n * Returns an early-disposal function that also cancels any future\n * materialization or resurrection.\n */\nexport function registerReactive(host: ReactiveHost, create: () => () => void): () => void {\n if (host._mounted) {\n return create();\n }\n\n const spec: ReactiveSpec = { create, stopped: false, dispose: null };\n host._reactiveSpecs.push(spec);\n\n return () => {\n spec.stopped = true;\n spec.dispose?.();\n };\n}\n\n/**\n * Bring a host's pre-mount registrations alive at commit time and mark it\n * mounted. First mount materializes dormant specs; a remount with a\n * surviving instance (React StrictMode simulates this in development)\n * re-creates the reactions that were disposed at unmount.\n */\nexport function activateSpecs(host: ReactiveHost): void {\n if (host._wasUnmounted) {\n host._wasUnmounted = false;\n for (const spec of host._reactiveSpecs) {\n if (!spec.stopped) {\n spec.dispose = spec.create();\n }\n }\n } else if (!host._mounted) {\n for (const spec of host._reactiveSpecs) {\n if (!spec.stopped && spec.dispose === null) {\n spec.dispose = spec.create();\n }\n }\n }\n host._mounted = true;\n}\n\n/** Per-class prototype facts: getter keys and plain method keys */\nexport interface ProtoInfo {\n computedKeys: string[];\n methodKeys: string[];\n}\n\n/**\n * Walk a class's prototype chain (stopping before the framework base class\n * and Object.prototype), collecting getter keys and method keys. The result\n * depends only on the prototype, so it is identical for every instance of a\n * class and cached per class. Disable with configure({ cacheAnnotations: false }).\n */\nexport function collectProtoInfo(\n instance: object,\n stopProto: object,\n excludes: Set<string>,\n cache: WeakMap<Function, ProtoInfo>\n): ProtoInfo {\n const ctor = instance.constructor as Function;\n const useCache = globalConfig.cacheAnnotations !== false;\n\n if (useCache) {\n const cached = cache.get(ctor);\n if (cached) return cached;\n }\n\n const info: ProtoInfo = { computedKeys: [], methodKeys: [] };\n const seen = new Set<string>();\n\n let proto = Object.getPrototypeOf(instance);\n while (proto && proto !== stopProto && proto !== Object.prototype) {\n const descriptors = Object.getOwnPropertyDescriptors(proto);\n\n for (const [key, descriptor] of Object.entries(descriptors)) {\n if (excludes.has(key) || seen.has(key)) continue;\n seen.add(key);\n\n if (descriptor.get) {\n info.computedKeys.push(key);\n } else if (typeof descriptor.value === 'function') {\n info.methodKeys.push(key);\n }\n }\n\n proto = Object.getPrototypeOf(proto);\n }\n\n if (useCache) cache.set(ctor, info);\n return info;\n}\n","import { useContext } from 'react';\nimport { ServiceContext, withInjectionScope } from './services';\nimport { useEffect, useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './observer';\nimport {\n type BehaviorEntry,\n isBehavior,\n layoutMountBehavior,\n mountBehavior,\n unmountBehavior,\n} from './behavior';\n\n/**\n * Host a behavior inside a plain React function component. The behavior gets\n * the same lifecycle relay a Mantle Component would give it: onLayoutMount in\n * the layout phase, onMount after paint, watchers alive from commit, full\n * teardown at unmount, and StrictMode remount resurrection.\n *\n * The instance is created once per mount lifetime, from a factory so nothing\n * is constructed on re-renders. It is returned as-is — wrap the component in\n * observer() (from mobx-mantle) so renders track the behavior's observables:\n *\n * @example\n * ```tsx\n * const Toolbar = observer(() => {\n * const size = useBehavior(() => withWindowSize());\n * return <div>{size.width} × {size.height}</div>;\n * });\n * ```\n *\n * Note: the factory runs once, so getter arguments close over the first\n * render's scope. Getters reading observables (a store, another behavior)\n * stay live; getters reading a function component's props capture the first\n * render's props object and go stale — pass observable sources instead.\n */\nexport function useBehavior<T extends object>(create: () => T): T {\n const resolver = useContext(ServiceContext);\n const [entry] = useState<BehaviorEntry>(() => {\n const instance = withInjectionScope(resolver, create);\n if (process.env.NODE_ENV !== 'production' && !isBehavior(instance)) {\n console.warn(\n '[mobx-mantle] useBehavior() expected the factory to return a behavior ' +\n 'instance (created with a factory from createBehavior). Lifecycle relay ' +\n 'will be skipped for this value.'\n );\n }\n return { instance };\n });\n\n useIsomorphicLayoutEffect(() => {\n if (!isBehavior(entry.instance)) return;\n layoutMountBehavior(entry);\n }, [entry]);\n\n useEffect(() => {\n if (!isBehavior(entry.instance)) return;\n mountBehavior(entry);\n return () => unmountBehavior(entry);\n }, [entry]);\n\n return entry.instance as T;\n}\n","import { isObservableProp, reaction, runInAction, toJS } from 'mobx';\n\nexport interface SharedOptions {\n /**\n * Persist the shared fields to localStorage under the key and restore\n * them at startup, so a fresh window starts where the last one left off.\n * Default true.\n */\n persist?: boolean;\n /**\n * The fields to share. Defaults to the store's own observable data\n * fields: not getters, not methods, not names starting with `_`.\n */\n fields?: readonly string[];\n}\n\nexport interface ShareStoresOptions extends SharedOptions {\n /** Key prefix for each store; the key is `${prefix}:${name}`. Default `shared`. */\n prefix?: string;\n}\n\ninterface SharedEntry {\n dispose(): void;\n}\n\nconst registry = new WeakMap<object, SharedEntry>();\n\nfunction ownDataFields(store: object): string[] {\n return Object.keys(store).filter((key) => {\n if (key.startsWith('_')) return false;\n if (typeof (store as Record<string, unknown>)[key] === 'function') return false;\n return isObservableProp(store, key);\n });\n}\n\nfunction serialize(store: Record<string, unknown>, fields: readonly string[]): string {\n const values: Record<string, unknown> = {};\n for (const field of fields) values[field] = toJS(store[field]);\n return JSON.stringify(values);\n}\n\n/** Apply a serialized state inside one action; false when it is not usable. */\nfunction apply(store: Record<string, unknown>, fields: readonly string[], json: string): boolean {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch {\n return false;\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;\n const values = parsed as Record<string, unknown>;\n runInAction(() => {\n for (const field of fields) {\n if (field in values) store[field] = values[field];\n }\n });\n return true;\n}\n\nfunction safeStorage(): Storage | null {\n try {\n return typeof localStorage === 'undefined' ? null : localStorage;\n } catch {\n // Blocked storage (sandboxed or privacy settings): share without persisting.\n return null;\n }\n}\n\n/**\n * Share a MobX store's state across every window of one application:\n * other tabs, the frames a design tool hosts, anything on the same origin\n * that imports the same module. Each window keeps its own store instance;\n * values are mirrored, identity is not shared, and nothing goes through a\n * server or a parent document.\n *\n * Mechanics, the web's own answer for two windows, packaged so it is never\n * written by hand:\n * - restore the store's fields from localStorage at startup (`persist`);\n * - publish changes through a reaction to localStorage and a\n * BroadcastChannel;\n * - apply incoming changes from the channel or the `storage` event inside\n * an action.\n * Echo loops are bounded because a window only publishes when its\n * serialized state changed, and only applies what differs from it.\n *\n * The one authoring rule: effects must derive from state — a `reaction`,\n * `autorun`, or a component's `watch`/`effect` — never run inside setters,\n * because a change that arrives from another window sets fields directly.\n *\n * @example\n * export const themeStore = shared(new ThemeStore(), 'theme');\n */\nexport function shared<T extends object>(store: T, key: string, options: SharedOptions = {}): T {\n if (registry.has(store) || typeof window === 'undefined') return store;\n const target = store as Record<string, unknown>;\n const fields = options.fields ? [...options.fields] : ownDataFields(store);\n const storage = options.persist === false ? null : safeStorage();\n const channel =\n typeof BroadcastChannel === 'function' ? new BroadcastChannel(`mantle-shared:${key}`) : null;\n // Node's BroadcastChannel would keep a process alive; browsers have no unref.\n (channel as { unref?: () => void } | null)?.unref?.();\n\n let stored: string | null = null;\n try {\n stored = storage?.getItem(key) ?? null;\n } catch {\n stored = null;\n }\n if (stored !== null) apply(target, fields, stored);\n\n // The last state this window published or applied; the echo bound.\n let current = serialize(target, fields);\n\n const stopPublish = reaction(\n () => serialize(target, fields),\n (json) => {\n if (json === current) return;\n current = json;\n try {\n storage?.setItem(key, json);\n } catch {\n // quota exceeded or blocked storage — the value still travels the channel\n }\n channel?.postMessage(json);\n },\n );\n\n const receive = (json: string) => {\n if (json === current) return;\n current = json;\n apply(target, fields, json);\n };\n const onMessage = (event: MessageEvent) => {\n if (typeof event.data === 'string') receive(event.data);\n };\n const onStorage = (event: StorageEvent) => {\n if (event.key === key && event.newValue !== null) receive(event.newValue);\n };\n channel?.addEventListener('message', onMessage);\n window.addEventListener('storage', onStorage);\n\n registry.set(store, {\n dispose() {\n stopPublish();\n channel?.removeEventListener('message', onMessage);\n channel?.close();\n window.removeEventListener('storage', onStorage);\n registry.delete(store);\n },\n });\n return store;\n}\n\n/** Stop sharing a store (tests, teardown). The store keeps its current state. */\nexport function unshare(store: object): void {\n registry.get(store)?.dispose();\n}\n\n/**\n * Share several stores at once, keyed by name: the one line an application\n * writes at its entry point (a design tool's manifest, an app's main\n * module) so every window that imports it wires the same stores.\n *\n * @example\n * shareStores({ themeStore, navPreferences });\n */\nexport function shareStores<T extends Record<string, object>>(\n stores: T,\n options: ShareStoresOptions = {},\n): T {\n const { prefix = 'shared', ...rest } = options;\n for (const [name, store] of Object.entries(stores)) {\n shared(store, `${prefix}:${name}`, rest);\n }\n return stores;\n}\n"],"mappings":";;;;;AAAA,OAAO,WAAW;;;ACAlB,SAAS,aAAa,qBAAqB;AAsDpC,IAAM,eAA6B;AAAA,EACxC,gBAAgB;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AW,SAAS;AAC9C,SAAO,iBAAiB,WAAW,SAAS;AAE5C,WAAS,IAAI,OAAO;AAAA,IAClB,UAAU;AACR,kBAAY;AACZ,eAAS,oBAAoB,WAAW,SAAS;AACjD,eAAS,MAAM;AACf,aAAO,oBAAoB,WAAW,SAAS;AAC/C,eAAS,OAAO,KAAK;AAAA,IACvB;AAAA,EACF,CAAC;AACD,SAAO;AACT;AAGO,SAAS,QAAQ,OAAqB;AAC3C,WAAS,IAAI,KAAK,GAAG,QAAQ;AAC/B;AAUO,SAAS,YACd,QACA,UAA8B,CAAC,GAC5B;AACH,QAAM,EAAE,SAAS,UAAU,GAAG,KAAK,IAAI;AACvC,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AAClD,WAAO,OAAO,GAAG,MAAM,IAAI,IAAI,IAAI,IAAI;AAAA,EACzC;AACA,SAAO;AACT;","names":["React","jsx","React","useRef","useEffect","memo","makeObservable","observable","computed","runInAction","reaction","autorun","_getGlobalState","adm","observable","action","computed","observable","computed","runInAction","runInAction","observable","computed","jsx","React","_getGlobalState","runInAction","reaction","autorun","observable","computed","makeObservable","React","useRef","runInAction","useEffect","jsx","memo","useEffect","useEffect","isObservableProp","reaction","runInAction"]}
1
+ {"version":3,"sources":["../src/services.tsx","../src/config.ts","../src/model-scope.tsx","../src/mantle.tsx","../src/observer.ts","../src/decorators.ts","../src/behavior.ts","../src/internals.ts","../src/useBehavior.ts","../src/shared.ts"],"sourcesContent":["import React from 'react';\r\nimport { globalConfig } from './config';\r\n\r\ndeclare const serviceType: unique symbol;\r\n/** Class tokens and typed symbols are also valid tsyringe injection tokens. */\r\nexport type ServiceToken<T extends object> = (new (...args: any[]) => T) | (symbol & { readonly [serviceType]: T });\r\nexport type ServiceResolver = <T extends object>(token: ServiceToken<T>) => T;\r\nexport function createServiceToken<T extends object>(description: string): ServiceToken<T> {\r\n return Symbol(description) as ServiceToken<T>;\r\n}\r\n\r\nexport const ServiceContext = React.createContext<ServiceResolver | undefined>(undefined);\r\nexport function ServiceProvider({ resolve, children }: { resolve: ServiceResolver; children?: React.ReactNode }) {\r\n return <ServiceContext.Provider value={resolve}>{children}</ServiceContext.Provider>;\r\n}\r\n\r\ninterface ServiceScope {\r\n resolve: ServiceResolver | undefined;\r\n values: WeakSet<object>;\r\n}\r\nlet constructingScope: ServiceScope | undefined;\r\nconst scopes = new WeakMap<object, ServiceScope>();\r\n\r\nfunction runWithScope<T>(scope: ServiceScope, construct: () => T): T {\r\n const previous = constructingScope;\r\n constructingScope = scope;\r\n try { return construct(); } finally { constructingScope = previous; }\r\n}\r\n\r\n/** Synchronous construction scope, also useful outside React. Does not own services. */\r\nexport function withInjectionScope<T>(resolve: ServiceResolver | undefined, construct: () => T): T {\r\n return runWithScope({ resolve: resolve ?? globalConfig.resolveService, values: new WeakSet() }, construct);\r\n}\r\nexport function captureServiceScope(owner: object): void {\r\n scopes.set(owner, constructingScope ?? { resolve: globalConfig.resolveService, values: new WeakSet() });\r\n}\r\n/** The resolver captured at construction, for re-providing it in another React tree. */\r\nexport function getServiceResolver(owner: object): ServiceResolver | undefined {\r\n return scopes.get(owner)?.resolve;\r\n}\r\nexport function resolveService<T extends object>(owner: object, token: ServiceToken<T>): T {\r\n return resolveInScope(scopes.get(owner), token);\r\n}\r\n\r\n/** Resolve during synchronous construction/onCreate, or inside withInjectionScope(). */\r\nexport function inject<T extends object>(token: ServiceToken<T>): T {\r\n if (!constructingScope) {\r\n throw new Error('[mobx-mantle] inject() requires an active construction scope. Use this.inject() in later methods, or withInjectionScope() outside React.');\r\n }\r\n return resolveInScope(constructingScope, token);\r\n}\r\n\r\nfunction resolveInScope<T extends object>(scope: ServiceScope | undefined, token: ServiceToken<T>): T {\r\n if (!scope?.resolve) throw new Error('[mobx-mantle] Service injection requires configure({ resolveService }), a ServiceProvider, or withInjectionScope() during construction.');\r\n const value = scope.resolve(token);\r\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') {\r\n throw new Error('[mobx-mantle] Services must be objects or functions; wrap primitive configuration in an object.');\r\n }\r\n scope.values.add(value);\r\n return value;\r\n}\r\nexport function isServiceValue(owner: object, value: unknown): boolean {\r\n return scopes.get(owner)?.values.has(value as object) ?? false;\r\n}\r\nexport function withOwnerServiceScope<T>(owner: object, construct: () => T): T {\r\n const scope = scopes.get(owner);\r\n if (!scope) throw new Error('[mobx-mantle] Missing owner service scope.');\r\n return runWithScope(scope, construct);\r\n}\r\n","import { configure as mobxConfigure } from 'mobx';\nimport type { ServiceResolver } from './services';\n\n/** Options for the watch method */\nexport interface WatchOptions {\n /** Debounce the callback by N milliseconds */\n delay?: number;\n /** Run callback immediately with current value */\n fireImmediately?: boolean;\n}\n\n/** Options for the effect method */\nexport interface EffectOptions {\n /** Debounce the effect by N milliseconds */\n delay?: number;\n}\n\n/**\n * Error context passed to the onError handler\n */\nexport interface MantleErrorContext {\n /** The lifecycle phase where the error occurred */\n phase: 'onLayoutMount' | 'onMount' | 'onUpdate' | 'onUnmount' | 'watch' | 'effect' | 'sync';\n /** The Component or Behavior class name */\n name: string;\n /** Whether the error came from a Behavior (true) or a Component (false) */\n isBehavior: boolean;\n}\n\n/**\n * Global configuration options for mobx-mantle\n */\nexport interface MantleConfig {\n /** Application service resolver, captured at construction. Explicit service scopes override it. */\n resolveService?: ServiceResolver;\n /** Whether to automatically make Component/Behavior instances observable (default: true) */\n autoObservable?: boolean;\n /**\n * Cache per-class prototype annotation data (getters, methods) so repeated\n * instantiations of the same class skip the prototype walk (default: true).\n * Turn off only if a class's prototype is mutated between instantiations.\n */\n cacheAnnotations?: boolean;\n /** Global error handler for lifecycle errors. Defaults to console.error. */\n onError?: (error: unknown, context: MantleErrorContext) => void;\n /**\n * Set true to opt into process-wide permissive MobX actions (default: false).\n * By default Mantle preserves the host's MobX policy. Synchronous methods\n * and lifecycle callbacks are actions; async continuations should use\n * runInAction. Configure before the first component or behavior is created.\n */\n manageMobxActions?: boolean;\n}\n\nexport const globalConfig: MantleConfig = {\n autoObservable: true,\n cacheAnnotations: true,\n manageMobxActions: false,\n};\n\nlet actionPolicyApplied = false;\n\n/**\n * @internal Apply the MobX action policy once, lazily at the first\n * component/behavior instantiation. Lazy (rather than at import) so an app\n * can opt in with configure({ manageMobxActions: true }) during startup,\n * regardless of module import order.\n */\nexport function applyMobxActionPolicy(): void {\n if (actionPolicyApplied) return;\n actionPolicyApplied = true;\n if (globalConfig.manageMobxActions === true) {\n mobxConfigure({ enforceActions: 'never' });\n }\n}\n\n/** @internal Report a lifecycle error through the configured handler or console.error */\nexport function reportError(error: unknown, context: MantleErrorContext): void {\n if (globalConfig.onError) {\n globalConfig.onError(error, context);\n } else {\n console.error(\n `[mobx-mantle] Error in ${context.isBehavior ? 'behavior' : 'component'} ${context.name}.${context.phase}():`,\n error,\n );\n }\n}\n\n/**\n * Configure global defaults for mobx-mantle.\n * Settings can still be overridden per-component in createComponent options.\n */\nexport function configure(config: MantleConfig): void {\n Object.assign(globalConfig, config);\n}\n","import React from 'react';\nimport type { Component } from './mantle';\n\nexport type ModelClass<C extends Component<any> = Component<any>> = new (...args: any[]) => C;\nexport interface ModelSubstitution<C extends Component<any> = Component<any>> {\n /** Runs for each instance instead of its original constructor. Supply data/callbacks only. */\n state: () => object;\n /** Required for integrated render() classes; optional for separate templates. */\n template?: (model: C) => React.JSX.Element;\n}\nexport const ModelContext = React.createContext<ReadonlyMap<ModelClass, ModelSubstitution> | undefined>(undefined);\n/** Construction policy. The mounted tree takes a snapshot; remount to change it. */\nexport function ModelProvider({ models, children }: { models: ReadonlyMap<ModelClass, ModelSubstitution>; children?: React.ReactNode }) {\n const [snapshot] = React.useState(() => new Map(Array.from(models, ([type, replacement]) => [type, { ...replacement }])));\n return <ModelContext.Provider value={snapshot}>{children}</ModelContext.Provider>;\n}\nconst identities = new WeakMap<object, ModelClass>();\nexport function setModelIdentity(model: object, type: ModelClass): void { identities.set(model, type); }\n/** Logical identity works for real and substituted models. It does not fake instanceof. */\nexport function isModel<C extends Component<any>>(model: object, type: abstract new (...args: any[]) => C): model is C {\n const logical = identities.get(model);\n return model instanceof type || logical === (type as Function) || !!logical && logical.prototype instanceof type;\n}\r\n","import { ServiceContext, captureServiceScope, resolveService, isServiceValue, withInjectionScope, withOwnerServiceScope, getServiceResolver, type ServiceToken, type ServiceResolver } from './services';\r\nimport { ModelContext, isModel, setModelIdentity, type ModelClass, type ModelSubstitution } from './model-scope';\r\nimport React, { useRef, useEffect, useContext, forwardRef as reactForwardRef, memo, type Ref, type JSX, type ReactElement } from 'react';\r\nimport { makeObservable, observable, computed, runInAction, reaction, autorun, type AnnotationsMap, createAtom, isObservableProp, type IAtom, _getGlobalState } from 'mobx';\r\nimport { useMantleObserver, useIsomorphicLayoutEffect, trackedComponents, type RenderReactionHolder } from './observer';\r\nimport {\r\n type BehaviorEntry,\r\n isBehavior,\r\n layoutMountBehavior,\r\n mountBehavior,\r\n unmountBehavior,\r\n warnUncollectedBehaviors,\r\n} from './behavior';\r\nimport { globalConfig, reportError, applyMobxActionPolicy, type WatchOptions, type EffectOptions } from './config';\r\nimport { getAnnotations } from './decorators';\r\nimport {\r\n type ReactiveSpec,\r\n type ProtoInfo,\r\n registerReactive,\r\n activateSpecs,\r\n collectProtoInfo,\r\n smartBind,\r\n toWatchExpression,\r\n} from './internals';\r\nimport type { MaybeGetter } from './reactive-args';\r\n\r\n// Re-export config utilities\r\nexport { configure, type MantleConfig, type MantleErrorContext, type WatchOptions, type EffectOptions } from './config';\r\n\r\n// Re-export decorators for single-import convenience\r\nexport { observable, action, computed } from './decorators';\r\n\r\n/** Tracks refs created by Component.ref() — no footprint on the object itself */\r\nconst componentRefs = new WeakSet();\r\n\r\n/**\r\n * A stable, wrapper-owned reference to the currently mounted Mantle instance.\r\n * The object identity survives an HMR instance replacement so descendants do\r\n * not retain the discarded model.\r\n */\r\ninterface ComponentHandle {\r\n current: Component<any> | undefined;\r\n}\r\n\r\n/** Carries the nearest logical Mantle ancestor without adding a DOM wrapper. */\r\nconst ComponentParentContext = React.createContext<ComponentHandle | undefined>(undefined);\r\n\r\n/** Runtime-only ancestry — deliberately absent from observable/serialized state. */\r\nconst componentParents = new WeakMap<Component<any>, ComponentHandle | undefined>();\r\n\r\n/**\r\n * What a view handed out by a model (this.view) carries with it: the model's\r\n * own handle for ancestry, and the service/substitution scopes it was built\r\n * under. Lets the view work in a React root Mantle does not control.\r\n */\r\ninterface OwnerScope {\r\n handle: ComponentHandle;\r\n resolver: ServiceResolver | undefined;\r\n substitutions: ReadonlyMap<ModelClass, ModelSubstitution> | undefined;\r\n}\r\nconst ownerScopes = new WeakMap<Component<any>, OwnerScope>();\r\n\r\nfunction ownerScope(owner: Component<any>): OwnerScope {\r\n let scope = ownerScopes.get(owner);\r\n if (!scope) {\r\n // Constructed with `new` outside createComponent: the owner is its own root.\r\n scope = { handle: { current: owner }, resolver: getServiceResolver(owner), substitutions: undefined };\r\n ownerScopes.set(owner, scope);\r\n }\r\n return scope;\r\n}\r\n\r\n/** forwardRef delivers the ref beside props; templates read it as a prop. */\r\nfunction withRef<P extends object>(props: P, ref: Ref<unknown>): P {\r\n return ref == null ? props : { ...props, ref };\r\n}\r\n\r\ninterface ComponentConstructionScope {\r\n expectedClass: Function;\r\n parentHandle: ComponentHandle | undefined;\r\n consumed: boolean;\r\n}\r\n\r\n/**\r\n * React supplies context before the model exists, while derived field\r\n * initializers run immediately after super(). This short-lived scope bridges\r\n * those two moments without changing public constructor signatures.\r\n */\r\nlet activeComponentConstruction: ComponentConstructionScope | undefined;\r\n\r\nfunction constructComponent<C extends Component<any>>(\r\n ComponentClass: new (...args: any[]) => C,\r\n props: unknown,\r\n parentHandle: ComponentHandle | undefined\r\n): C {\r\n const previousScope = activeComponentConstruction;\r\n const scope: ComponentConstructionScope = {\r\n expectedClass: ComponentClass,\r\n parentHandle,\r\n consumed: false,\r\n };\r\n\r\n activeComponentConstruction = scope;\r\n try {\r\n return new ComponentClass(props);\r\n } finally {\r\n activeComponentConstruction = previousScope;\r\n }\r\n}\r\n\r\nfunction captureConstructingComponentParent(instance: Component<any>): void {\r\n const scope = activeComponentConstruction;\r\n if (\r\n !scope ||\r\n scope.consumed ||\r\n instance.constructor !== scope.expectedClass\r\n ) {\r\n return;\r\n }\r\n\r\n scope.consumed = true;\r\n componentParents.set(instance, scope.parentHandle);\r\n}\r\n\r\n/** Shallow-compare two objects by own enumerable keys */\r\nfunction shallowEqual(a: any, b: any): boolean {\r\n if (a === b) return true;\r\n if (!a || !b) return false;\r\n const keysA = Object.keys(a);\r\n const keysB = Object.keys(b);\r\n if (keysA.length !== keysB.length) return false;\r\n for (const key of keysA) {\r\n if (a[key] !== b[key]) return false;\r\n }\r\n return true;\r\n}\r\n\r\n/**\r\n * Props holder built on MobX's public atom API. Reads are tracked like any\r\n * observable. Writes come in two flavors:\r\n * - setSilently: update the value without notifying observers — safe during\r\n * React's render phase (see Component._syncProps)\r\n * - set: update and notify observers — called from useLayoutEffect after\r\n * React finishes the render pass\r\n */\r\nclass PropsBox<P> {\r\n private _atom: IAtom;\r\n private _value: P;\r\n\r\n /**\r\n * @internal The owning component's render reaction. Reads coming from it\r\n * are not tracked: React already re-renders the component on prop change\r\n * (via memo), so letting the render reaction observe the props atom would\r\n * only schedule a redundant second render after every prop change.\r\n * Computeds, watchers, and other components track normally.\r\n */\r\n _renderReaction: RenderReactionHolder | null = null;\r\n\r\n constructor(value: P, name: string) {\r\n this._value = value;\r\n this._atom = createAtom(name);\r\n }\r\n\r\n get(): P {\r\n const own = this._renderReaction?.current;\r\n if (!own || _getGlobalState().trackingDerivation !== own) {\r\n this._atom.reportObserved();\r\n }\r\n return this._value;\r\n }\r\n\r\n setSilently(value: P): void {\r\n this._value = value;\r\n }\r\n\r\n set(value: P): void {\r\n this._value = value;\r\n this._atom.reportChanged();\r\n }\r\n}\r\n\r\nexport type ComponentConstructor<C extends Component<any> = Component<any>> =\r\n abstract new (...args: any[]) => C;\r\n\r\nexport class Component<P = {}> {\r\n /** @internal */\r\n _propsBox!: PropsBox<P>;\r\n\r\n constructor(props?: P) {\r\n this._propsBox = new PropsBox(props as P, `${this.constructor.name}.props`);\r\n captureConstructingComponentParent(this);\r\n captureServiceScope(this);\r\n }\r\n\r\n get props(): P {\r\n return this._propsBox.get();\r\n }\r\n\r\n /** Resolve through the scope captured during construction; preserve service identity. */\r\n inject<T extends object>(token: ServiceToken<T>): T { return resolveService(this, token); }\r\n\r\n /** Return the immediate ancestor in the live Mantle view tree. */\r\n getParent(): Component<any> | undefined {\r\n return componentParents.get(this)?.current;\r\n }\r\n\r\n /** Find the nearest parent with the supplied logical model identity. */\r\n findParent<C extends Component<any>>(\r\n type: ComponentConstructor<C>\r\n ): C | undefined {\r\n for (const parent of this.getParents()) {\r\n if (isModel(parent, type)) return parent;\r\n }\r\n return undefined;\r\n }\r\n\r\n /** Return all Mantle parents, ordered from the immediate parent to the root. */\r\n getParents(): readonly Component<any>[] {\r\n const parents: Component<any>[] = [];\r\n let current = this.getParent();\r\n while (current) {\r\n parents.push(current);\r\n current = current.getParent();\r\n }\r\n return parents;\r\n }\r\n\r\n /** Return the highest Mantle ancestor, or this instance when already root. */\r\n getRoot(): Component<any> {\r\n const parents = this.getParents();\r\n return parents[parents.length - 1] ?? this;\r\n }\r\n\r\n /** @internal — called by createComponent to silently update props during render */\r\n _syncProps(value: P) {\r\n // Update the value without triggering MobX notifications. React renders\r\n // the component tree synchronously — if we notified here, MobX would\r\n // flush reactions and try to update other observer components while\r\n // React is still rendering, causing:\r\n // \"Cannot update component A while rendering component B\"\r\n //\r\n // The value is updated so this._propsBox.get() returns the correct value\r\n // during render. Observers are notified separately in useLayoutEffect.\r\n this._propsBox.setSilently(value);\r\n }\r\n\r\n forwardRef?: Ref<any>;\r\n\r\n /** @internal */\r\n _behaviors: BehaviorEntry[] = [];\r\n\r\n /** @internal */\r\n _watchDisposers: (() => void)[] = [];\r\n\r\n /** @internal — pre-mount watch/effect registrations, materialized at mount */\r\n _reactiveSpecs: ReactiveSpec[] = [];\r\n\r\n /** @internal — true after the first (layout) mount */\r\n _mounted = false;\r\n\r\n /** @internal — set when effects clean up so StrictMode replay can resurrect watchers */\r\n _wasUnmounted = false;\r\n\r\n onCreate?(props: P): void;\r\n onLayoutMount?(): void | (() => void);\r\n onMount?(): void | (() => void);\r\n onUpdate?(): void;\r\n onUnmount?(): void;\r\n\r\n ref<T extends HTMLElement = HTMLElement>(): { current: T | null } {\r\n const r = { current: null } as { current: T | null };\r\n componentRefs.add(r);\r\n return r;\r\n }\r\n\r\n /**\r\n * A tracked view of this instance, for handing to code you don't control\r\n * (a table's row renderer, an error boundary's fallback, a map popup).\r\n * Created once, so its identity is stable. Re-renders on its own when the\r\n * state it reads changes. Forwards refs. Carries this model's context, so\r\n * `findParent()` and services resolve inside it even when a library renders\r\n * it in its own React root.\r\n *\r\n * @example\r\n * ```tsx\r\n * row = this.view((props: RowProps) => (\r\n * <tr {...props} className={props.id === this.activeId ? 'active' : ''} />\r\n * ));\r\n * ```\r\n */\r\n view<P extends object = {}>(render: (props: P) => ReactElement | null): MantleComponent<P> {\r\n const owner = this;\r\n const name = `${owner.constructor.name}.${render.name || 'view'}`;\r\n const View = reactForwardRef<unknown, P>((props, ref) => {\r\n const scope = ownerScope(owner);\r\n const rendered = useMantleObserver(() => render(withRef(props as unknown as P, ref)), name);\r\n return (\r\n <ComponentParentContext.Provider value={scope.handle}>\r\n <ServiceContext.Provider value={scope.resolver}>\r\n <ModelContext.Provider value={scope.substitutions}>{rendered}</ModelContext.Provider>\r\n </ServiceContext.Provider>\r\n </ComponentParentContext.Provider>\r\n );\r\n });\r\n View.displayName = name;\r\n const Memoized = memo(View);\r\n trackedComponents.add(Memoized);\r\n return Memoized as unknown as MantleComponent<P>;\r\n }\r\n\r\n /**\r\n * Register a cleanup function to run automatically on unmount.\r\n * Returns a function that can be called for early cleanup.\r\n *\r\n * Cleanups are one-shot: they are not re-created during React StrictMode's\r\n * same-instance effect replay. Call this from onMount (which is replayed),\r\n * or use effect() for a replay-safe setup/teardown pair.\r\n */\r\n addCleanup(cleanup: () => void): () => void {\r\n if (process.env.NODE_ENV !== 'production' && !this._mounted) {\r\n console.warn(\r\n `[mobx-mantle] ${this.constructor.name}.addCleanup() called before mount. ` +\r\n `Cleanups are one-shot: they run when mount effects clean up and are not ` +\r\n `re-created during React StrictMode's same-instance effect replay. Acquire ` +\r\n `resources in onMount(), or use effect() for a replay-safe setup/teardown pair.`\r\n );\r\n }\r\n return this._addCleanup(cleanup);\r\n }\r\n\r\n /** @internal — addCleanup without the pre-mount dev warning (used by watch/effect) */\r\n _addCleanup(cleanup: () => void): () => void {\r\n let active = true;\r\n\r\n const dispose = () => {\r\n if (!active) return;\r\n active = false;\r\n try {\r\n runInAction(cleanup);\r\n } finally {\r\n const idx = this._watchDisposers.indexOf(dispose);\r\n if (idx !== -1) this._watchDisposers.splice(idx, 1);\r\n }\r\n };\r\n\r\n this._watchDisposers.push(dispose);\r\n return dispose;\r\n }\r\n\r\n /**\r\n * Watch a reactive expression and run a callback when it changes.\r\n * Automatically disposed on unmount. Watchers declared before mount\r\n * (field initializers, onCreate) are re-created during React StrictMode's\r\n * same-instance effect replay.\r\n *\r\n * @param source - Reactive expression (getter) to watch, or a MaybeGetter\r\n * argument passed through as-is. To watch a value that is itself a\r\n * function, wrap it: `watch(() => this.callback, …)`\r\n * @param callback - Called when the expression result changes\r\n * @param options - Optional configuration (delay, fireImmediately)\r\n * @returns Dispose function for early teardown\r\n * \r\n * @example\r\n * ```tsx\r\n * onMount() {\r\n * this.watch(\r\n * () => this.query,\r\n * async (query) => {\r\n * if (query.length > 2) {\r\n * this.results = await searchApi(query);\r\n * }\r\n * },\r\n * { delay: 300 }\r\n * );\r\n * }\r\n * ```\r\n */\r\n watch<T>(\r\n source: MaybeGetter<T>,\r\n callback: (value: T, prevValue: T | undefined) => void,\r\n options?: WatchOptions\r\n ): () => void {\r\n // A function is the tracked expression; a plain value is a constant\r\n // (dev-warns unless fireImmediately — a constant watch can never fire).\r\n // To watch a value that IS a function, wrap it: watch(() => this.callback, …)\r\n const expr = toWatchExpression(source, options?.fireImmediately, this.constructor.name);\r\n return registerReactive(this, () => {\r\n const dispose = reaction(\r\n expr,\r\n (value, prevValue) => {\r\n try {\r\n callback(value, prevValue);\r\n } catch (e) {\r\n reportError(e, { phase: 'watch', name: this.constructor.name, isBehavior: false });\r\n }\r\n },\r\n {\r\n delay: options?.delay,\r\n fireImmediately: options?.fireImmediately,\r\n }\r\n );\r\n\r\n return this._addCleanup(dispose);\r\n });\r\n }\r\n\r\n /**\r\n * Run a side effect that auto-tracks reactive dependencies.\r\n * Re-runs whenever any accessed observable changes.\r\n * Automatically disposed on unmount. Effects declared before mount\r\n * (field initializers, onCreate) are re-created during React StrictMode's\r\n * same-instance effect replay.\r\n *\r\n * Best for simple synchronization (DOM updates, logging). For complex\r\n * side effects with explicit triggers, prefer `watch()`.\r\n *\r\n * @param fn - Effect function. May return a cleanup function.\r\n * @param options - Optional configuration (delay)\r\n * @returns Dispose function for early teardown\r\n * \r\n * @example\r\n * ```tsx\r\n * onMount() {\r\n * this.effect(() => {\r\n * document.title = `${this.items.length} items`;\r\n * });\r\n * }\r\n * ```\r\n *\r\n * @example With cleanup\r\n * ```tsx\r\n * onMount() {\r\n * this.effect(() => {\r\n * const handler = () => console.log(this.count);\r\n * window.addEventListener('click', handler);\r\n * return () => window.removeEventListener('click', handler);\r\n * });\r\n * }\r\n * ```\r\n */\r\n effect(\r\n fn: () => void | (() => void),\r\n options?: EffectOptions\r\n ): () => void {\r\n return registerReactive(this, () => {\r\n let cleanup: (() => void) | undefined;\r\n\r\n const dispose = autorun(\r\n () => {\r\n // Run previous cleanup before re-running effect\r\n runInAction(() => cleanup?.());\r\n cleanup = undefined;\r\n\r\n try {\r\n const result = fn();\r\n if (typeof result === 'function') {\r\n cleanup = result;\r\n }\r\n } catch (e) {\r\n reportError(e, { phase: 'effect', name: this.constructor.name, isBehavior: false });\r\n }\r\n },\r\n { delay: options?.delay }\r\n );\r\n\r\n return this._addCleanup(() => {\r\n runInAction(() => cleanup?.());\r\n dispose();\r\n });\r\n });\r\n }\r\n\r\n /** @internal */\r\n _disposeWatchers(): void {\r\n const disposers = this._watchDisposers.slice();\r\n this._watchDisposers.length = 0;\r\n\r\n for (const dispose of disposers) {\r\n dispose();\r\n }\r\n }\r\n\r\n /** @internal - Scan own properties for behavior instances and register them */\r\n _collectBehaviors(): void {\r\n for (const key of Object.keys(this)) {\r\n if (key.startsWith('_')) continue;\r\n const value = (this as any)[key];\r\n if (isBehavior(value) && !isServiceValue(this, value)) {\r\n this._behaviors.push({ instance: value });\r\n }\r\n }\r\n }\r\n\r\n /** @internal */\r\n _layoutMountBehaviors(): void {\r\n for (const behavior of this._behaviors) {\r\n layoutMountBehavior(behavior);\r\n }\r\n }\r\n\r\n /** @internal */\r\n _mountBehaviors(): void {\r\n for (const behavior of this._behaviors) {\r\n mountBehavior(behavior);\r\n }\r\n }\r\n\r\n /** @internal */\r\n _unmountBehaviors(): void {\r\n for (const behavior of this._behaviors) {\r\n unmountBehavior(behavior);\r\n }\r\n }\r\n\r\n render?(): JSX.Element | null;\r\n}\r\n\r\n/** Alias for Component - use when separating ViewModel from template */\r\nexport { Component as ViewModel };\r\n\r\n// Re-export from behavior module\r\nexport { createBehavior, Behavior } from './behavior';\r\n\r\n// Base class members that should not be made observable\r\nconst BASE_EXCLUDES = new Set([\r\n 'props',\r\n 'getParent',\r\n 'findParent',\r\n 'getParents',\r\n 'getRoot',\r\n '_propsBox',\r\n 'forwardRef', \r\n 'onCreate',\r\n 'onLayoutMount',\r\n 'onMount', \r\n 'onUpdate',\r\n 'onUnmount',\r\n 'render', \r\n 'ref',\r\n 'view',\r\n 'addCleanup',\r\n '_addCleanup',\r\n 'watch',\r\n 'effect',\r\n 'constructor',\r\n 'inject',\r\n '_behaviors',\r\n '_collectBehaviors',\r\n '_layoutMountBehaviors',\r\n '_mountBehaviors',\r\n '_unmountBehaviors',\r\n '_syncProps',\r\n '_watchDisposers',\r\n '_disposeWatchers',\r\n '_reactiveSpecs',\r\n '_mounted',\r\n '_wasUnmounted',\r\n]);\r\n\r\n/**\r\n * Detects if a value is a ref created by Component.ref()\r\n * These should use observable.ref to preserve object identity for React\r\n */\r\nfunction isComponentRef(value: unknown): boolean {\r\n return value !== null && typeof value === 'object' && componentRefs.has(value as object);\r\n}\r\n\r\n/** Per-class cache of prototype-derived info (getters, methods) */\r\nconst componentProtoInfo = new WeakMap<Function, ProtoInfo>();\r\n\r\n/**\r\n * Creates observable annotations for a Component subclass instance.\r\n * This is needed because makeAutoObservable doesn't work with inheritance.\r\n */\r\nfunction makeComponentObservable<T extends Component>(instance: T, autoBind: boolean) {\r\n const annotations: AnnotationsMap<T, never> = {} as AnnotationsMap<T, never>;\r\n\r\n // Collect own properties (instance state) → observable\r\n // Also check prototype for class field declarations (handles uninitialized fields)\r\n const ownKeys = new Set([\r\n ...Object.keys(instance),\r\n ...Object.keys(Object.getPrototypeOf(instance)),\r\n ]);\r\n\r\n for (const key of ownKeys) {\r\n if (BASE_EXCLUDES.has(key)) continue;\r\n if (key in annotations) continue;\r\n\r\n const value = (instance as any)[key];\r\n\r\n // Skip functions (these are handled via the prototype info), services,\r\n // and React components Mantle made (this.view / observer) — never convert those.\r\n if (typeof value === 'function' || isServiceValue(instance, value) || trackedComponents.has(value)) continue;\r\n\r\n // Skip behavior instances (they're already observable)\r\n if (isBehavior(value)) {\r\n (annotations as any)[key] = observable.ref;\r\n continue;\r\n }\r\n\r\n // Use observable.ref for Component.ref() objects to preserve identity\r\n if (isComponentRef(value)) {\r\n (annotations as any)[key] = observable.ref;\r\n } else {\r\n (annotations as any)[key] = observable;\r\n }\r\n }\r\n\r\n // Prototype facts (getters → computed, methods to bind) are identical for\r\n // every instance of a class, so they're collected once and cached per class.\r\n const protoInfo = collectProtoInfo(instance, Component.prototype, BASE_EXCLUDES, componentProtoInfo);\r\n\r\n for (const key of protoInfo.computedKeys) {\r\n if (key in annotations) continue;\r\n (annotations as any)[key] = computed;\r\n }\r\n\r\n makeObservable(instance, annotations);\r\n\r\n // Methods: don't wrap in action (breaks observable tracking in render helpers).\r\n // Use smartBind: allows tracking in render context, batches mutations elsewhere.\r\n if (autoBind) {\r\n for (const key of protoInfo.methodKeys) {\r\n if (key in annotations) continue;\r\n const method = (instance as any)[key];\r\n if (typeof method === 'function') {\r\n (instance as any)[key] = smartBind(method, instance);\r\n }\r\n }\r\n }\r\n}\r\n\r\n/** The substitute owns normal Component infrastructure, never the real prototype. */\r\nclass SubstituteComponent extends Component<any> {}\r\nfunction installSubstituteState(instance: Component<any>, state: object): void {\r\n const annotations: Record<string, any> = {};\r\n for (const key of Reflect.ownKeys(state)) {\r\n if (typeof key !== 'string' || key.startsWith('_') || key in instance || BASE_EXCLUDES.has(key)) throw new Error('[mobx-mantle] Substitute state cannot replace framework member ' + String(key));\r\n const descriptor = Object.getOwnPropertyDescriptor(state, key)!;\r\n if (!('value' in descriptor)) throw new Error('[mobx-mantle] Substitute state must contain data/callbacks, not getters.');\r\n Object.defineProperty(instance, key, { value: descriptor.value, enumerable: true, writable: true, configurable: true });\r\n annotations[key] = observable.ref;\r\n }\r\n makeObservable(instance, annotations);\r\n}\r\n\r\ntype PropsOf<C> = C extends Component<infer P> ? P : object;\r\n\r\n/**\r\n * Return type for createComponent.\r\n * \r\n * Simple callable signature that works with libraries expecting ComponentType<P>\r\n * or strict function components (react-window, react-virtualized, etc.).\r\n * \r\n * Uses ReactElement | null rather than React.FC's looser ReactNode return type.\r\n */\r\nexport type MantleComponent<P> = (props: P) => React.ReactElement | null;\r\n\r\n/**\r\n * Return type for createForwardRef when you need typed ref forwarding.\r\n * \r\n * Use this when you need to forward refs to DOM elements or child components\r\n * and want TypeScript to know the ref type.\r\n */\r\nexport type ForwardRefMantleComponent<P, RefType> = \r\n ((props: P) => React.ReactElement | null) &\r\n React.ForwardRefExoticComponent<\r\n React.PropsWithoutRef<P> & React.RefAttributes<RefType>\r\n >;\r\n\r\nexport function createComponent<C extends Component<any>>(\r\n ComponentClass: new (...args: any[]) => C,\r\n templateOrOptions?: ((vm: C) => JSX.Element) | { autoObservable?: boolean }\r\n) {\r\n type P = PropsOf<C>;\r\n\r\n const template = typeof templateOrOptions === 'function' ? templateOrOptions : undefined;\r\n const options = typeof templateOrOptions === 'object' ? templateOrOptions : {};\r\n const { autoObservable = globalConfig.autoObservable } = options;\r\n\r\n const ReactComponent = reactForwardRef<unknown, P>((props, ref) => {\r\n const parentHandle = React.useContext(ComponentParentContext);\r\n const resolver = React.useContext(ServiceContext);\r\n const substitutions = React.useContext(ModelContext);\r\n const substitutedTemplate = useRef<typeof template>(undefined);\r\n const vmRef = useRef<C | null>(null);\r\n const componentHandleRef = useRef<ComponentHandle | null>(null);\r\n const classRef = useRef(ComponentClass);\r\n const prevPropsRef = useRef<P | null>(null);\r\n const propsNotifyingRef = useRef(false);\r\n // Identity of this component's render reaction, wired into PropsBox so\r\n // it can skip tracking self-reads. Stable across HMR instance swaps.\r\n const renderReactionRef = useRef<RenderReactionHolder>({ current: null });\r\n\r\n if (!componentHandleRef.current) {\r\n componentHandleRef.current = { current: undefined };\r\n }\r\n const componentHandle = componentHandleRef.current;\r\n\r\n // HMR: class identity changes when the module re-executes, but useRef\r\n // values survive (React Fast Refresh preserves hooks). On detection,\r\n // we simply discard the old instance and create fresh — clean slate.\r\n // In production this check is always false (class identity is stable).\r\n if (vmRef.current && classRef.current !== ComponentClass) {\r\n classRef.current = ComponentClass;\r\n vmRef.current = null;\r\n }\r\n\r\n if (!vmRef.current) {\r\n applyMobxActionPolicy();\r\n\r\n const substitution = substitutions?.get(ComponentClass);\r\n if (substitution && !substitution.template && !template) throw new Error('[mobx-mantle] A substituted integrated model requires an explicit test template.');\r\n const instance = withInjectionScope(resolver, () => substitution\r\n ? constructComponent(SubstituteComponent, props, parentHandle) as C\r\n : constructComponent(ComponentClass, props as P, parentHandle));\r\n substitutedTemplate.current = substitution?.template;\r\n setModelIdentity(instance, ComponentClass);\r\n if (substitution) installSubstituteState(instance, substitution.state());\r\n instance.forwardRef = ref;\r\n instance._propsBox._renderReaction = renderReactionRef.current;\r\n ownerScopes.set(instance, { handle: componentHandle, resolver: getServiceResolver(instance), substitutions });\r\n\r\n // Collect behavior instances from properties (must happen before makeObservable)\r\n if (!substitution) instance._collectBehaviors();\r\n\r\n // Check for Mantle decorator annotations first\r\n const decoratorAnnotations = getAnnotations(instance);\r\n \r\n if (substitution) {\r\n // State is annotated by reference once; never scan the original class.\r\n } else if (decoratorAnnotations) {\r\n // Mantle decorators: use collected annotations\r\n const annotations = { ...decoratorAnnotations };\r\n\r\n makeObservable(instance, annotations as AnnotationsMap<C, never>);\r\n\r\n // Bind methods not explicitly decorated, to preserve `this` without\r\n // an action wrapper (actions break observable tracking in render\r\n // helpers). smartBind allows tracking in render context and batches\r\n // mutations elsewhere.\r\n const protoInfo = collectProtoInfo(instance, Component.prototype, BASE_EXCLUDES, componentProtoInfo);\r\n for (const key of protoInfo.methodKeys) {\r\n if (key in annotations) continue;\r\n const method = (instance as any)[key];\r\n if (typeof method === 'function') {\r\n (instance as any)[key] = smartBind(method, instance);\r\n }\r\n }\r\n } else if (autoObservable) {\r\n makeComponentObservable(instance, true);\r\n } else {\r\n // For legacy decorator users: applies decorator metadata\r\n makeObservable(instance);\r\n }\r\n\r\n // Note: watch/effect registrations from field initializers and\r\n // onCreate stay dormant here. They come alive in the mount layout\r\n // effect (activateSpecs) — the commit phase — so renders React never\r\n // commits (Suspense, aborted transitions, SSR) leak no reactions.\r\n\r\n // Proxy forwards property access to instance.props, so reads are tracked\r\n // by MobX when used in reactions/computeds (same behavior as this.props)\r\n const reactiveProps = new Proxy({} as P, {\r\n get: (_, key) => (instance.props as any)[key],\r\n has: (_, key) => key in (instance.props as any),\r\n ownKeys: () => Reflect.ownKeys(instance.props as object),\r\n getOwnPropertyDescriptor: (_, key) =>\r\n Reflect.getOwnPropertyDescriptor(instance.props as object, key),\r\n });\r\n withOwnerServiceScope(instance, () => runInAction(() => instance.onCreate?.(reactiveProps)));\r\n\r\n // Dev check: fields first assigned in onCreate() (not declared as class\r\n // fields) were invisible to the annotation scan and are silently\r\n // non-reactive. Only meaningful in auto-observable mode — with\r\n // decorators, undecorated fields are inert by design.\r\n if (process.env.NODE_ENV !== 'production' && autoObservable && !decoratorAnnotations && !substitution) {\r\n for (const key of Object.keys(instance)) {\r\n if (BASE_EXCLUDES.has(key) || key.startsWith('_')) continue;\r\n const value = (instance as any)[key];\r\n if (typeof value === 'function' || isServiceValue(instance, value) || trackedComponents.has(value)) continue;\r\n if (!isObservableProp(instance, key)) {\r\n console.warn(\r\n `[mobx-mantle] ${ComponentClass.name}.${key} was first assigned in onCreate() ` +\r\n `and is not reactive. Declare it as a class field so it can be made observable.`\r\n );\r\n }\r\n }\r\n }\r\n\r\n vmRef.current = instance;\r\n prevPropsRef.current = props as P;\r\n }\r\n\r\n const vm = vmRef.current;\r\n const renderTemplate = substitutedTemplate.current ?? template;\r\n\r\n // Context can change when a component is genuinely reparented. Refresh\r\n // the WeakMap every render; descendants resolve through our stable handle.\r\n componentParents.set(vm, parentHandle);\r\n componentHandle.current = vm;\r\n\r\n // Dev warning: detect when a prop-triggered reaction causes a re-render.\r\n // This means a reaction is being used for derived state — a computed getter\r\n // would avoid the double render.\r\n if (process.env.NODE_ENV !== 'production' && propsNotifyingRef.current) {\r\n console.warn(\r\n `[mobx-mantle] ${ComponentClass.name}: A reaction to a prop change modified ` +\r\n `observable state, which caused an extra re-render. Consider using a ` +\r\n `computed getter instead.`\r\n );\r\n propsNotifyingRef.current = false;\r\n }\r\n\r\n // Silently update _propsBox.value_ so this.props returns the correct value\r\n // during render, without triggering MobX reactions (which would cause\r\n // \"Cannot update component A while rendering component B\").\r\n vm._syncProps(props as P);\r\n vm.forwardRef = ref;\r\n\r\n // After render completes, properly notify MobX observers of prop changes.\r\n // This enables reaction(() => this.props.x, ...) in lifecycle methods.\r\n // useLayoutEffect runs after React finishes the render pass, so it's safe\r\n // to flush reactions here.\r\n useIsomorphicLayoutEffect(() => {\r\n if (!shallowEqual(prevPropsRef.current, props)) {\r\n prevPropsRef.current = props as P;\r\n propsNotifyingRef.current = true;\r\n runInAction(() => {\r\n vm._propsBox.set(props);\r\n });\r\n // If a reaction triggered a synchronous re-render, the warning\r\n // already fired above. Clear the flag for the normal case.\r\n propsNotifyingRef.current = false;\r\n }\r\n });\r\n\r\n // [vm] dep ensures effects re-run when instance changes (HMR).\r\n // On normal renders vm is stable, so effects run once — same as [].\r\n useIsomorphicLayoutEffect(() => {\r\n // Commit reached: bring pre-mount watch/effect registrations alive\r\n // (first mount), or re-create the ones disposed when React StrictMode\r\n // replays mount effects with the same instance in development.\r\n // onMount/onLayoutMount registrations re-run on their own.\r\n activateSpecs(vm);\r\n\r\n vm._layoutMountBehaviors();\r\n let cleanup: (() => void) | undefined;\r\n try {\r\n const result = runInAction(() => vm.onLayoutMount?.());\r\n if (process.env.NODE_ENV !== 'production' && result instanceof Promise) {\r\n console.error(\r\n `[mobx-mantle] ${ComponentClass.name}.onLayoutMount() returned a Promise. ` +\r\n `Lifecycle methods must be synchronous. Use a sync onLayoutMount that ` +\r\n `calls an async method instead.`\r\n );\r\n }\r\n // Only a returned function is a cleanup; anything else (notably a\r\n // Promise from an async method) must not be called at unmount.\r\n cleanup = typeof result === 'function' ? (result as () => void) : undefined;\r\n } catch (e) {\r\n reportError(e, { phase: 'onLayoutMount', name: ComponentClass.name, isBehavior: false });\r\n }\r\n return () => {\r\n runInAction(() => cleanup?.());\r\n };\r\n }, [vm]);\r\n\r\n useEffect(() => {\r\n vm._mountBehaviors();\r\n let cleanup: (() => void) | undefined;\r\n try {\r\n const result = runInAction(() => vm.onMount?.());\r\n if (process.env.NODE_ENV !== 'production' && result instanceof Promise) {\r\n console.error(\r\n `[mobx-mantle] ${ComponentClass.name}.onMount() returned a Promise. ` +\r\n `Lifecycle methods must be synchronous. Use a sync onMount that ` +\r\n `calls an async method instead.`\r\n );\r\n }\r\n // Only a returned function is a cleanup; anything else (notably a\r\n // Promise from an async method) must not be called at unmount.\r\n cleanup = typeof result === 'function' ? (result as () => void) : undefined;\r\n } catch (e) {\r\n reportError(e, { phase: 'onMount', name: ComponentClass.name, isBehavior: false });\r\n }\r\n\r\n // Dev check: behaviors assigned after construction (in onCreate,\r\n // conditionally, or lazily) were invisible to _collectBehaviors, so\r\n // their lifecycle would silently never run.\r\n if (process.env.NODE_ENV !== 'production') {\r\n warnUncollectedBehaviors(vm, ComponentClass.name, vm._behaviors);\r\n }\r\n\r\n return () => {\r\n runInAction(() => cleanup?.());\r\n try {\r\n runInAction(() => vm.onUnmount?.());\r\n } catch (e) {\r\n reportError(e, { phase: 'onUnmount', name: ComponentClass.name, isBehavior: false });\r\n }\r\n vm._disposeWatchers();\r\n vm._unmountBehaviors();\r\n vm._wasUnmounted = true;\r\n };\r\n }, [vm]);\r\n\r\n // Called after every render (via useEffect)\r\n useEffect(() => {\r\n try {\r\n runInAction(() => vm.onUpdate?.());\r\n } catch (e) {\r\n reportError(e, { phase: 'onUpdate', name: ComponentClass.name, isBehavior: false });\r\n }\r\n });\r\n\r\n if (!renderTemplate && !vm.render) {\r\n throw new Error(\r\n `[mobx-mantle] ${ComponentClass.name}: Missing render() method. Either define render() in your Component class or pass a template function to createComponent().`\r\n );\r\n }\r\n\r\n // Only the render call is tracked by MobX. The reaction is owned by\r\n // Mantle (src/observer.ts) so PropsBox can recognize self-reads.\r\n const rendered = useMantleObserver(\r\n () => (renderTemplate ? renderTemplate(vm) : vm.render!()),\r\n ComponentClass.name,\r\n renderReactionRef.current\r\n );\r\n\r\n return (\r\n <ComponentParentContext.Provider value={componentHandle}>\r\n {rendered}\r\n </ComponentParentContext.Provider>\r\n );\r\n });\r\n\r\n // Wrap in React.memo to match observer()'s behavior — skip re-renders\r\n // when parent re-renders but props haven't changed (shallow comparison).\r\n return memo(ReactComponent) as MantleComponent<P>;\r\n}\r\n\r\n/**\r\n * Creates a React component with typed ref forwarding.\r\n * \r\n * Use this instead of createComponent when you need to forward refs to DOM elements\r\n * or child components and want proper TypeScript support for the ref type.\r\n * \r\n * @example\r\n * ```tsx\r\n * class FancyInput extends Component<Props> {\r\n * render() {\r\n * return <input ref={this.forwardRef} className=\"fancy\" />;\r\n * }\r\n * }\r\n * \r\n * const FancyInputComponent = createForwardRef<HTMLInputElement>(FancyInput);\r\n * \r\n * // Parent gets typed ref:\r\n * const inputRef = useRef<HTMLInputElement>(null);\r\n * <FancyInputComponent ref={inputRef} />\r\n * ```\r\n */\r\nexport function createForwardRef<RefType, C extends Component<any> = Component<any>>(\r\n ComponentClass: new (...args: any[]) => C,\r\n templateOrOptions?: ((vm: C) => JSX.Element) | { autoObservable?: boolean }\r\n): ForwardRefMantleComponent<PropsOf<C>, RefType> {\r\n // Same implementation as createComponent - the runtime behavior is identical.\r\n // Only the return type differs to provide proper ref typing.\r\n return createComponent(ComponentClass, templateOrOptions) as ForwardRefMantleComponent<PropsOf<C>, RefType>;\r\n}\r\n\r\n/**\r\n * A tracked view of a model that already exists above it in the tree. Where\r\n * createComponent creates and owns a model, createView borrows the nearest\r\n * instance of `ModelClass` and renders the template with it as `vm`. Use it\r\n * to split a large template across files, or to hand a library a component\r\n * that reads your model's state.\r\n *\r\n * @example\r\n * ```tsx\r\n * const Summary = createView(TodoList, ({ vm }) => <p>{vm.remaining} left</p>);\r\n *\r\n * const TodoListView = createComponent(TodoList, (vm) => (\r\n * <div><Summary /><ul>…</ul></div>\r\n * ));\r\n * ```\r\n */\r\nexport function createView<C extends Component<any>, P extends { vm: C } = { vm: C }>(\r\n ModelClass: ComponentConstructor<C>,\r\n template: (props: P) => ReactElement | null\r\n): MantleComponent<Omit<P, 'vm'>> {\r\n const name = `${ModelClass.name}.${template.name || 'view'}`;\r\n const View = reactForwardRef<unknown, Omit<P, 'vm'>>((props, ref) => {\r\n let vm = useContext(ComponentParentContext)?.current;\r\n while (vm && !isModel(vm, ModelClass)) vm = vm.getParent();\r\n if (!vm) {\r\n throw new Error(\r\n `[mobx-mantle] createView(${ModelClass.name}): no ${ModelClass.name} is mounted above this view.`\r\n );\r\n }\r\n const model = vm;\r\n return useMantleObserver(() => template(withRef({ ...props, vm: model } as unknown as P, ref)), name);\r\n });\r\n View.displayName = name;\r\n const Memoized = memo(View);\r\n trackedComponents.add(Memoized);\r\n return Memoized as unknown as MantleComponent<Omit<P, 'vm'>>;\r\n}\r\n","import React, { memo, useRef, useSyncExternalStore, useEffect, useLayoutEffect } from 'react';\r\nimport { Reaction } from 'mobx';\r\n\r\n/**\r\n * useLayoutEffect that falls back to useEffect on the server, where layout\r\n * effects never run and React warns during renderToString. Neither runs\r\n * server-side; the fallback only silences the noise.\r\n */\r\nexport const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\r\n\r\n/**\r\n * Holder linking a component instance to its render reaction, so PropsBox\r\n * can recognize \"my own render is reading me\" and skip tracking (React\r\n * already delivers prop changes through memo — tracking would only schedule\r\n * a redundant second render). Stable per React component instance; survives\r\n * HMR instance swaps.\r\n */\r\nexport interface RenderReactionHolder {\r\n current: Reaction | null;\r\n}\r\n\r\ninterface ObserverAdmin {\r\n reaction: Reaction | null;\r\n onStoreChange: (() => void) | null;\r\n stateVersion: symbol;\r\n name: string;\r\n holder: RenderReactionHolder | undefined;\r\n subscribe: (onStoreChange: () => void) => () => void;\r\n getSnapshot: () => symbol;\r\n}\r\n\r\n/**\r\n * Reactions are created during render, but React may never commit that\r\n * render (Suspense throws, aborted transitions, StrictMode's discarded\r\n * pass) — then no cleanup effect ever runs. The registry disposes reactions\r\n * whose owning component was garbage-collected without committing.\r\n * Committed components unregister in subscribe() and dispose through the\r\n * normal unsubscribe path.\r\n */\r\nconst uncommittedReactionRegistry =\r\n typeof FinalizationRegistry !== 'undefined'\r\n ? new FinalizationRegistry<ObserverAdmin>((adm) => {\r\n adm.reaction?.dispose();\r\n adm.reaction = null;\r\n })\r\n : undefined;\r\n\r\nif (process.env.NODE_ENV !== 'production' && !uncommittedReactionRegistry) {\r\n console.warn(\r\n '[mobx-mantle] FinalizationRegistry is not available in this environment. ' +\r\n 'Reactions created for renders that React discards cannot be cleaned up, ' +\r\n 'which can leak under Suspense and concurrent rendering.'\r\n );\r\n}\r\n\r\nconst isServer = typeof window === 'undefined';\r\n\r\n/**\r\n * React components Mantle produced (observer(), this.view(), createView()).\r\n * Auto-observable mode must store these by reference, never convert them.\r\n */\r\nexport const trackedComponents = new WeakSet<object>();\r\n\r\nfunction createReaction(adm: ObserverAdmin): void {\r\n adm.reaction = new Reaction(`mantle-observer(${adm.name})`, () => {\r\n adm.stateVersion = Symbol();\r\n adm.onStoreChange?.();\r\n });\r\n if (adm.holder) {\r\n adm.holder.current = adm.reaction;\r\n }\r\n}\r\n\r\n/**\r\n * Track a render function with a MobX Reaction owned by Mantle (rather than\r\n * mobx-react-lite's useObserver). Owning the reaction exposes its identity —\r\n * that is what lets PropsBox skip self-notification (see RenderReactionHolder).\r\n *\r\n * On the server this renders untracked: no reaction is ever created, so\r\n * renderToString leaks nothing by construction.\r\n */\r\nexport function useMantleObserver<T>(render: () => T, name: string, holder?: RenderReactionHolder): T {\r\n if (isServer) {\r\n return render();\r\n }\r\n\r\n const admRef = useRef<ObserverAdmin | null>(null);\r\n\r\n if (!admRef.current) {\r\n const adm: ObserverAdmin = {\r\n reaction: null,\r\n onStoreChange: null,\r\n stateVersion: Symbol(),\r\n name,\r\n holder,\r\n subscribe(onStoreChange: () => void) {\r\n // Committed: normal effect lifecycle owns disposal from here on.\r\n uncommittedReactionRegistry?.unregister(adm);\r\n adm.onStoreChange = onStoreChange;\r\n\r\n if (!adm.reaction) {\r\n // The reaction was disposed before this commit (registry cleanup,\r\n // or a StrictMode unmount pass). Re-create it and force one\r\n // re-render so it tracks current dependencies.\r\n createReaction(adm);\r\n adm.stateVersion = Symbol();\r\n onStoreChange();\r\n }\r\n\r\n return () => {\r\n adm.onStoreChange = null;\r\n adm.reaction?.dispose();\r\n adm.reaction = null;\r\n if (adm.holder) {\r\n adm.holder.current = null;\r\n }\r\n };\r\n },\r\n getSnapshot() {\r\n return adm.stateVersion;\r\n },\r\n };\r\n admRef.current = adm;\r\n }\r\n\r\n const adm = admRef.current;\r\n adm.holder = holder;\r\n\r\n if (!adm.reaction) {\r\n // First render, or first render after disposal. Guard against the\r\n // never-committed case until subscribe() takes ownership.\r\n createReaction(adm);\r\n uncommittedReactionRegistry?.register(admRef, adm, adm);\r\n }\r\n\r\n useSyncExternalStore(adm.subscribe, adm.getSnapshot, adm.getSnapshot);\r\n\r\n let result!: T;\r\n let didThrow = false;\r\n let thrown: unknown;\r\n adm.reaction!.track(() => {\r\n try {\r\n result = render();\r\n } catch (e) {\r\n didThrow = true;\r\n thrown = e;\r\n }\r\n });\r\n if (didThrow) {\r\n throw thrown;\r\n }\r\n return result;\r\n}\r\n\r\n/**\r\n * Minimal observer() for plain function components — re-renders when any\r\n * observable read during render changes. Useful together with useBehavior()\r\n * in codebases that don't (or don't yet) use Mantle components.\r\n *\r\n * @example\r\n * ```tsx\r\n * const Toolbar = observer((props: Props) => {\r\n * const size = useBehavior(() => withWindowSize());\r\n * return <div>{size.width}px</div>;\r\n * });\r\n * ```\r\n */\r\nexport function observer<P extends object>(\r\n fc: ((props: P) => React.ReactElement | null) & { displayName?: string }\r\n): (props: P) => React.ReactElement | null {\r\n const name = fc.displayName || fc.name || 'observed';\r\n const Observed = (props: P) => useMantleObserver(() => fc(props), name);\r\n Observed.displayName = `observer(${name})`;\r\n const Memoized = memo(Observed);\r\n trackedComponents.add(Memoized);\r\n return Memoized as unknown as (props: P) => React.ReactElement | null;\r\n}\r\n","import * as mobx from 'mobx';\nimport { isServiceValue } from './services';\n\nexport const ANNOTATIONS = Symbol('mantle:annotations');\ntype Annotations = Record<string | symbol, any>;\ntype Context = { kind: string; name: string | symbol; metadata?: Record<symbol, unknown>; static?: boolean; private?: boolean };\nconst legacy = new WeakMap<object, Annotations>();\n\nfunction annotation(value: any, kind: 'field' | 'method' | 'getter') {\n return function (_target: any, key: string | symbol | Context, descriptor?: PropertyDescriptor): void {\n let map: Annotations;\n let name: string | symbol;\n if (typeof key === 'object') {\n if (key.static || key.private || key.kind !== kind) {\n throw new Error(`[mobx-mantle] This decorator requires a public instance ${kind}. Use an ordinary field, not an auto-accessor, for @observable.`);\n }\n if (!key.metadata) throw new Error('[mobx-mantle] TC39 decorators require Symbol.metadata. Load its polyfill before decorated classes.');\n // Metadata inherits from base metadata. Never mutate its annotation map.\n if (!Object.prototype.hasOwnProperty.call(key.metadata, ANNOTATIONS)) key.metadata[ANNOTATIONS] = Object.create(null);\n map = key.metadata[ANNOTATIONS] as Annotations;\n name = key.name;\n } else {\n if (typeof _target === 'function' || (kind === 'method' && typeof descriptor?.value !== 'function') || (kind === 'getter' && !descriptor?.get) || (kind === 'field' && descriptor)) {\n throw new Error(`[mobx-mantle] This decorator requires a public instance ${kind}.`);\n }\n map = legacy.get(_target) ?? Object.create(null);\n legacy.set(_target, map);\n name = key;\n }\n map[name] = value;\n };\n}\n\n/** Plain fields in either TypeScript decorator mode; no accessor keyword needed. */\nexport const observable = Object.assign(annotation(mobx.observable, 'field'), {\n ref: annotation(mobx.observable.ref, 'field'),\n shallow: annotation(mobx.observable.shallow, 'field'),\n deep: annotation(mobx.observable.deep, 'field'),\n struct: annotation(mobx.observable.struct, 'field'),\n});\nconst actionMethod = annotation(mobx.action.bound, 'method');\nconst actionField = annotation(mobx.action, 'field');\n/** Bound prototype method, or an arrow-function field (already bound); synchronous writes are batched. */\nexport const action = function (target: any, key: string | symbol | Context, descriptor?: PropertyDescriptor): void {\n const isField = typeof key === 'object' ? key.kind === 'field' : !descriptor;\n return (isField ? actionField : actionMethod)(target, key, descriptor);\n};\nexport const computed = annotation(mobx.computed, 'getter');\n\n/** Both Components and Behaviors apply this map once after construction. */\nexport function getAnnotations(instance: object): Annotations | undefined {\n const chain: object[] = [];\n for (let proto = Object.getPrototypeOf(instance); proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) chain.unshift(proto);\n const result: Annotations = Object.create(null);\n for (const proto of chain) {\n const constructor = (proto as any).constructor;\n const symbol = (Symbol as any).metadata;\n const metadata = symbol && Object.prototype.hasOwnProperty.call(constructor, symbol) ? constructor[symbol] : undefined;\n const modern = metadata && Object.prototype.hasOwnProperty.call(metadata, ANNOTATIONS) ? metadata[ANNOTATIONS] : undefined;\n for (const own of [legacy.get(proto), modern]) {\n if (!own) continue;\n for (const key of Reflect.ownKeys(own)) {\n if (key in result && result[key] !== own[key]) throw new Error(`[mobx-mantle] Cannot change the inherited annotation of ${String(key)}.`);\n result[key] = own[key];\n }\n }\n }\n for (const key of Reflect.ownKeys(result)) {\n // Avoid invoking computed getters while checking service field identity.\n const own = Object.getOwnPropertyDescriptor(instance, key);\n if (own && 'value' in own && isServiceValue(instance, own.value)) throw new Error(`[mobx-mantle] Leave service field ${String(key)} undecorated; its resolver owns observability.`);\n }\n return Reflect.ownKeys(result).length ? result : undefined;\n}\n","import { captureServiceScope, resolveService, isServiceValue, withOwnerServiceScope, type ServiceToken } from './services';\nimport { getAnnotations } from './decorators';\nimport { makeObservable, observable, computed, reaction, autorun, intercept, runInAction, type AnnotationsMap } from 'mobx';\nimport { globalConfig, reportError, applyMobxActionPolicy, type WatchOptions, type EffectOptions } from './config';\nimport {\n type ReactiveSpec,\n type ProtoInfo,\n registerReactive,\n activateSpecs,\n collectProtoInfo,\n smartBind,\n toWatchExpression,\n} from './internals';\nimport { toValue, type MaybeGetter } from './reactive-args';\n\n/**\n * Symbol marker to identify behavior instances. Registered globally\n * (Symbol.for) so detection works even when the module is duplicated across\n * bundles or entry points (e.g. the main entry and ./behaviors in a CJS\n * build each carrying their own copy).\n */\nexport const BEHAVIOR_MARKER = Symbol.for('mobx-mantle.behavior');\n\n// Behavior base class members that should not be made observable\nconst BEHAVIOR_EXCLUDES = new Set([\n 'onCreate',\n 'onLayoutMount',\n 'onMount',\n 'onUnmount',\n 'addCleanup',\n '_addCleanup',\n 'watch',\n 'effect',\n 'sync',\n 'constructor',\n 'inject',\n '_watchDisposers',\n '_disposeWatchers',\n '_reactiveSpecs',\n '_behaviors',\n '_pendingSyncs',\n '_syncWriting',\n '_mounted',\n '_wasUnmounted',\n]);\n\n/**\n * Placeholder returned by sync() during construction. The wrapper constructor\n * scans own fields right after onCreate, finds which key holds each marker,\n * swaps in the initial value, and registers the hidden sync effect for that\n * key. (Same post-onCreate scan window that behavior collection uses.)\n */\nclass SyncMarker {\n constructor(readonly source: () => unknown) {}\n}\n\n/**\n * Detects if a value looks like a React ref ({ current: ... })\n * These should use observable.ref to preserve object identity\n */\nfunction isRefLike(value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false;\n if (Array.isArray(value)) return false;\n return 'current' in value && Object.keys(value).length === 1;\n}\n\n/**\n * Base class for behaviors. Provides lifecycle method signatures for IDE autocomplete.\n * Extend this class and wrap with createBehavior() to create a factory.\n * \n * @example\n * ```tsx\n * class WindowSizeBehavior extends Behavior {\n * width = window.innerWidth;\n * onCreate(breakpoint = 768) { ... }\n * onMount() { ... }\n * }\n * export const withWindowSize = createBehavior(WindowSizeBehavior);\n * ```\n */\nexport class Behavior {\n constructor() { captureServiceScope(this); }\n inject<T extends object>(token: ServiceToken<T>): T { return resolveService(this, token); }\n /** @internal */\n _watchDisposers: (() => void)[] = [];\n\n /** @internal — pre-mount watch/effect registrations, materialized at mount */\n _reactiveSpecs: ReactiveSpec[] = [];\n\n /** @internal — child behaviors declared as fields, collected at construction */\n _behaviors: BehaviorEntry[] = [];\n\n /** @internal — true after the parent Component first mounts */\n _mounted = false;\n\n /** @internal — set when effects clean up so StrictMode replay can resurrect pre-mount watchers */\n _wasUnmounted = false;\n\n /** @internal — sync() markers awaiting the post-onCreate field scan; null once construction completes */\n _pendingSyncs: SyncMarker[] | null = [];\n\n /** @internal — true while the hidden sync effect writes a mirrored field (dev write-guard) */\n _syncWriting = false;\n\n onCreate?(...args: any[]): void;\n onLayoutMount?(): void | (() => void);\n onMount?(): void | (() => void);\n onUnmount?(): void;\n\n /**\n * Register a cleanup function to run automatically on unmount.\n * Returns a function that can be called for early cleanup.\n *\n * Cleanups are one-shot: they are not re-created during React StrictMode's\n * same-instance effect replay. Call this from onMount (which is replayed),\n * or use effect() for a replay-safe setup/teardown pair.\n */\n addCleanup(cleanup: () => void): () => void {\n if (process.env.NODE_ENV !== 'production' && !this._mounted) {\n console.warn(\n `[mobx-mantle] ${this.constructor.name}.addCleanup() called before mount. ` +\n `Cleanups are one-shot: they run when mount effects clean up and are not ` +\n `re-created during React StrictMode's same-instance effect replay. ` +\n `Acquire resources in onMount(), or use effect() for a replay-safe ` +\n `setup/teardown pair.`\n );\n }\n return this._addCleanup(cleanup);\n }\n\n /** @internal — addCleanup without the pre-mount dev warning (used by watch/effect) */\n _addCleanup(cleanup: () => void): () => void {\n let active = true;\n\n const dispose = () => {\n if (!active) return;\n active = false;\n try {\n runInAction(cleanup);\n } finally {\n const idx = this._watchDisposers.indexOf(dispose);\n if (idx !== -1) this._watchDisposers.splice(idx, 1);\n }\n };\n\n this._watchDisposers.push(dispose);\n return dispose;\n }\n\n /**\n * Watch a reactive expression and run a callback when it changes.\n * Automatically disposed on unmount and re-created during React StrictMode's\n * same-instance effect replay.\n *\n * Safe to call from onCreate: registration is recorded and comes alive\n * when the parent commits (just before first paint), so the watcher\n * tracks observable fields correctly and renders that React discards\n * never leak reactions.\n *\n * @param source - Reactive expression (getter) to watch, or a MaybeGetter\n * argument passed through as-is. To watch a value that is itself a\n * function, wrap it: `watch(() => this.callback, …)`\n * @param callback - Called when the expression result changes\n * @param options - Optional configuration (delay, fireImmediately)\n * @returns Dispose function for early teardown\n *\n * @example\n * ```tsx\n * onCreate(url: string) {\n * this.url = url;\n * this.watch(() => this.url, () => this.fetchData());\n * }\n * ```\n */\n watch<T>(\n source: MaybeGetter<T>,\n callback: (value: T, prevValue: T | undefined) => void,\n options?: WatchOptions\n ): () => void {\n const expr = toWatchExpression(source, options?.fireImmediately, this.constructor.name);\n return registerReactive(this, () => {\n const dispose = reaction(\n expr,\n (value, prevValue) => {\n try {\n callback(value, prevValue);\n } catch (e) {\n reportError(e, { phase: 'watch', name: this.constructor.name, isBehavior: true });\n }\n },\n {\n delay: options?.delay,\n fireImmediately: options?.fireImmediately,\n }\n );\n\n return this._addCleanup(dispose);\n });\n }\n\n /**\n * Run a side effect that auto-tracks reactive dependencies.\n * Re-runs whenever any accessed observable changes.\n * Automatically disposed on unmount.\n * \n * Best for simple synchronization (DOM updates, logging). For complex\n * side effects with explicit triggers, prefer `watch()`.\n * \n * @param fn - Effect function. May return a cleanup function.\n * @param options - Optional configuration (delay)\n * @returns Dispose function for early teardown\n * \n * @example\n * ```tsx\n * onCreate() {\n * this.effect(() => {\n * console.log('Current value:', this.value);\n * });\n * }\n * ```\n */\n effect(\n fn: () => void | (() => void),\n options?: EffectOptions\n ): () => void {\n return registerReactive(this, () => {\n let cleanup: (() => void) | undefined;\n\n const dispose = autorun(\n () => {\n // Run previous cleanup before re-running effect\n runInAction(() => cleanup?.());\n cleanup = undefined;\n\n try {\n const result = fn();\n if (typeof result === 'function') {\n cleanup = result;\n }\n } catch (e) {\n reportError(e, { phase: 'effect', name: this.constructor.name, isBehavior: true });\n }\n },\n { delay: options?.delay }\n );\n\n return this._addCleanup(() => {\n runInAction(() => cleanup?.());\n dispose();\n });\n });\n }\n\n /**\n * Normalize a MaybeGetter argument into an ordinary field that stays\n * current. Call once in onCreate (or a field initializer) and assign the\n * result to a field; everywhere else, read the field like normal state:\n *\n * ```tsx\n * url!: string;\n *\n * onCreate(url: MaybeGetter<string>) {\n * this.url = this.sync(url); // the one convention line\n * this.watch(() => this.url, (u) => this.load(u));\n * }\n * refresh() { this.load(this.url); } // plain read, always current\n * ```\n *\n * - Plain value → the field just holds it (no effect registered).\n * - Getter → a hidden effect keeps the field updated whenever the getter's\n * observable sources change (alive from mount, like watch/effect).\n *\n * The sync is one-way (argument → field). Don't write to the field from\n * outside: the next source change overwrites it (dev mode warns).\n */\n sync<T>(source: MaybeGetter<T>): T {\n // A plain value IS its own snapshot forever — no machinery needed.\n if (typeof source !== 'function') {\n return source;\n }\n\n if (this._pendingSyncs === null) {\n // Construction is over; the field scan already ran, so a marker could\n // never be bound. Degrade to a one-time read.\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[mobx-mantle] ${this.constructor.name}.sync() called after construction. ` +\n `sync() only works in field initializers or onCreate; returning a ` +\n `one-time snapshot instead. Use watch()/effect() for post-mount reactions.`\n );\n }\n return toValue(source);\n }\n\n const marker = new SyncMarker(source as () => unknown);\n this._pendingSyncs.push(marker);\n // The marker briefly occupies the field; the post-onCreate scan replaces\n // it with the real initial value before anything else can read it.\n return marker as unknown as T;\n }\n\n /** @internal */\n _disposeWatchers(): void {\n const disposers = this._watchDisposers.slice();\n this._watchDisposers.length = 0;\n\n for (const dispose of disposers) {\n dispose();\n }\n }\n}\n\n/** Per-class cache of prototype-derived info (getters, methods) */\nconst behaviorProtoInfo = new WeakMap<Function, ProtoInfo>();\n\n/**\n * Makes a behavior instance observable, handling inheritance properly.\n * Works with classes that extend Behavior or plain classes.\n */\nfunction makeBehaviorObservable<T extends object>(instance: T): void {\n const annotations: AnnotationsMap<T, never> = {} as AnnotationsMap<T, never>;\n\n // Collect own properties → observable\n const ownKeys = new Set([\n ...Object.keys(instance),\n ...Object.keys(Object.getPrototypeOf(instance)),\n ]);\n\n for (const key of ownKeys) {\n if (BEHAVIOR_EXCLUDES.has(key)) continue;\n if (key in annotations) continue;\n\n const value = (instance as any)[key];\n if (typeof value === 'function' || isServiceValue(instance, value)) continue;\n\n // Child behaviors are already observable; keep their identity\n if (isBehavior(value)) {\n (annotations as any)[key] = observable.ref;\n continue;\n }\n\n // Use observable.ref for ref-like objects to preserve identity\n if (isRefLike(value)) {\n (annotations as any)[key] = observable.ref;\n } else {\n (annotations as any)[key] = observable;\n }\n }\n\n // Prototype facts (getters → computed, methods to bind) are\n // identical for every instance of a class; collected once, cached per class.\n const protoInfo = collectProtoInfo(instance, Behavior.prototype, BEHAVIOR_EXCLUDES, behaviorProtoInfo);\n\n for (const key of protoInfo.computedKeys) {\n if (key in annotations) continue;\n (annotations as any)[key] = computed;\n }\n makeObservable(instance, annotations);\n\n // Match Component method semantics. action.bound would make observable\n // reads inside behavior helpers untracked when a render/computed calls them.\n // smartBind preserves those dependencies and still batches handler writes.\n for (const key of protoInfo.methodKeys) {\n if (key in annotations) continue;\n const method = (instance as any)[key];\n if (typeof method === 'function') {\n (instance as any)[key] = smartBind(method, instance);\n }\n }\n}\n\n/** @internal */\nexport interface BehaviorEntry {\n instance: any;\n cleanup?: () => void;\n layoutCleanup?: () => void;\n}\n\n/**\n * Extracts parameter types from onCreate method\n */\ntype OnCreateParams<T> = T extends { onCreate(...args: infer A): any } ? A : [];\n\n/**\n * Extracts constructor parameter types\n */\ntype ConstructorParams<T> = T extends new (...args: infer A) => any ? A : [];\n\n/**\n * Determines the args for createBehavior:\n * - If constructor has args, use those\n * - Otherwise, if onCreate has args, use those\n */\ntype BehaviorArgs<T extends new (...args: any[]) => any> = \n ConstructorParams<T> extends [] \n ? OnCreateParams<InstanceType<T>> \n : ConstructorParams<T>;\n\n/**\n * Creates a behavior factory with automatic observable wrapping and lifecycle management.\n * \n * Returns a factory function (not a class) — use without `new`:\n * \n * @example Defining a behavior\n * ```tsx\n * class DragTrait extends Behavior {\n * ref!: RefObject<HTMLElement>;\n * \n * onCreate(ref: RefObject<HTMLElement>) {\n * this.ref = ref;\n * }\n * \n * onMount() {\n * this.ref.current?.addEventListener('pointerdown', this.onPointerDown);\n * return () => this.ref.current?.removeEventListener('pointerdown', this.onPointerDown);\n * }\n * }\n * \n * export const withDrag = createBehavior(DragTrait);\n * ```\n * \n * @example Using in a Component\n * ```tsx\n * class Editor extends Component<Props> {\n * canvas = this.ref<HTMLCanvasElement>();\n * \n * // No `new` keyword — factory function\n * drag = withDrag(this.canvas);\n * autosave = withAutosave('/api/save', 5000);\n * }\n * export default createComponent(Editor);\n * ```\n * \n * The `with` prefix convention signals that the component manages this behavior's lifecycle.\n */\n/**\n * Type that supports both `new` and direct call syntax\n */\ntype BehaviorFactory<Args extends any[], Instance> = {\n new (...args: Args): Instance;\n (...args: Args): Instance;\n};\n\nexport function createBehavior<T extends new (...args: any[]) => any>(\n Def: T,\n options?: { autoObservable?: boolean }\n): BehaviorFactory<BehaviorArgs<T>, InstanceType<T>> {\n // Internal class that wraps the user's behavior definition\n const BehaviorClass = class extends (Def as any) {\n static [BEHAVIOR_MARKER] = true;\n\n constructor(...args: any[]) {\n applyMobxActionPolicy();\n super(...args);\n\n // Call onCreate with args (if it exists). This runs BEFORE\n // makeObservable so the field scan sees the values onCreate assigns\n // (e.g. ref-like objects get observable.ref, preserving identity).\n // watch/effect calls made here are recorded as dormant specs and come\n // alive when the parent commits (activateSpecs in the mount relay) —\n // renders React never commits therefore leak no reactions.\n if (typeof this.onCreate === 'function') {\n withOwnerServiceScope(this, () => runInAction(() => this.onCreate!(...args)));\n }\n\n // Collect child behaviors declared as fields or assigned in onCreate,\n // mirroring Component behavior collection. The lifecycle relay\n // recurses into these. Underscore-prefixed keys are skipped,\n // consistent with the Component scan.\n const children: BehaviorEntry[] = [];\n for (const key of Object.keys(this)) {\n if (key.startsWith('_')) continue;\n const value = (this as any)[key];\n if (isBehavior(value) && !isServiceValue(this, value)) {\n children.push({ instance: value });\n }\n }\n (this as any)._behaviors = children;\n\n // Bind sync() markers: find which field holds each marker, swap in the\n // initial value (so makeObservable annotates a real value), and record\n // the key→source pairs. Must run before makeObservable.\n const syncedFields: Array<{ key: string; source: () => unknown }> = [];\n const pending: SyncMarker[] | null = (this as any)._pendingSyncs ?? null;\n if (Array.isArray(pending) && pending.length > 0) {\n for (const key of Object.keys(this)) {\n const value = (this as any)[key];\n if (value instanceof SyncMarker) {\n syncedFields.push({ key, source: value.source });\n (this as any)[key] = value.source();\n }\n }\n if (process.env.NODE_ENV !== 'production' && syncedFields.length !== pending.length) {\n console.warn(\n `[mobx-mantle] ${Def.name}: ${pending.length - syncedFields.length} sync() ` +\n `result(s) were not assigned to a field. Assign sync() directly to a ` +\n `field (this.url = this.sync(url)) so Mantle can keep it updated.`\n );\n }\n }\n (this as any)._pendingSyncs = null;\n\n // Make the instance observable (respects global config and per-behavior options)\n const autoObservable = options?.autoObservable ?? globalConfig.autoObservable;\n const annotations = getAnnotations(this);\n if (annotations) {\n makeObservable(this, annotations);\n const info = collectProtoInfo(this, Behavior.prototype, BEHAVIOR_EXCLUDES, behaviorProtoInfo);\n for (const key of info.methodKeys) if (!(key in annotations)) (this as any)[key] = smartBind((this as any)[key], this);\n } else if (autoObservable) {\n makeBehaviorObservable(this);\n } else {\n // For decorator users: applies decorator metadata\n makeObservable(this);\n }\n\n // Register the hidden sync effects — at the FRONT of the spec list, so\n // at mount activation every mirrored field refreshes before any\n // author-registered watcher fires (authors see current values).\n if (syncedFields.length > 0) {\n const self = this as any;\n const specs: ReactiveSpec[] = syncedFields.map(({ key, source }) => ({\n create: () => {\n const dispose = autorun(() => {\n try {\n const next = source(); // tracked read — this is the live link\n self._syncWriting = true;\n try {\n runInAction(() => {\n self[key] = next;\n });\n } finally {\n self._syncWriting = false;\n }\n } catch (e) {\n reportError(e, { phase: 'sync', name: self.constructor.name, isBehavior: true });\n }\n });\n return self._addCleanup(dispose);\n },\n stopped: false,\n dispose: null,\n }));\n self._reactiveSpecs.unshift(...specs);\n\n // Dev write-guard: the sync is one-way; an outside write works until\n // the next source change silently overwrites it. Warn at the write.\n if (process.env.NODE_ENV !== 'production') {\n for (const { key } of syncedFields) {\n try {\n intercept(self, key, (change: any) => {\n if (!self._syncWriting) {\n console.warn(\n `[mobx-mantle] ${Def.name}.${key} is a one-way synced field ` +\n `(this.sync()). Writing to it from outside will be overwritten ` +\n `by the next source change. Derive with a computed getter, or ` +\n `own the state in a plain field instead.`\n );\n }\n return change;\n });\n } catch {\n // Field not observable (custom annotations) — skip the guard.\n }\n }\n }\n }\n }\n };\n\n // Preserve the original class name for debugging\n Object.defineProperty(BehaviorClass, 'name', { value: Def.name });\n\n // Use Proxy to make the class callable without `new`\n // This allows both: withWindowSize(768) and new withWindowSize(768)\n return new Proxy(BehaviorClass, {\n apply(_target, _thisArg, args) {\n return new BehaviorClass(...args);\n },\n }) as unknown as BehaviorFactory<BehaviorArgs<T>, InstanceType<T>>;\n}\n\n\n/**\n * Checks if a value is a behavior instance created by createBehavior()\n */\nexport function isBehavior(value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false;\n return (value.constructor as any)?.[BEHAVIOR_MARKER] === true;\n}\n\n/**\n * @internal Child behaviors of a behavior instance, or an empty list for\n * plain (non-Behavior-derived) classes that never ran the collection scan.\n */\nfunction childBehaviors(inst: any): BehaviorEntry[] {\n return Array.isArray(inst._behaviors) ? inst._behaviors : [];\n}\n\n/**\n * @internal Relay functions recurse into nested behaviors. The visited set\n * guards against cycles (a parent assigned into a child's field); a cycle is\n * simply not relayed twice.\n */\nexport function layoutMountBehavior(behavior: BehaviorEntry, visited: WeakSet<object> = new WeakSet()): void {\n const inst = behavior.instance;\n if (visited.has(inst)) return;\n visited.add(inst);\n\n // Children mount before their parent, so the parent's lifecycle can rely\n // on live children.\n for (const child of childBehaviors(inst)) {\n layoutMountBehavior(child, visited);\n }\n\n // Bring pre-mount watch/effect registrations alive (first mount), or\n // re-create the ones disposed during StrictMode's same-instance effect replay.\n if (Array.isArray(inst._reactiveSpecs)) {\n activateSpecs(inst);\n } else {\n inst._mounted = true;\n }\n\n if ('onLayoutMount' in inst && typeof inst.onLayoutMount === 'function') {\n try {\n const result = runInAction(() => inst.onLayoutMount!());\n // Only a returned function is a cleanup; ignore a Promise from an async\n // method so unmount doesn't try to call it.\n behavior.layoutCleanup = typeof result === 'function' ? result : undefined;\n } catch (e) {\n reportError(e, { phase: 'onLayoutMount', name: inst.constructor.name, isBehavior: true });\n }\n }\n}\n\n/** @internal */\nexport function mountBehavior(behavior: BehaviorEntry, visited: WeakSet<object> = new WeakSet()): void {\n const inst = behavior.instance;\n if (visited.has(inst)) return;\n visited.add(inst);\n\n // Children before parent — mirror of layoutMountBehavior\n for (const child of childBehaviors(inst)) {\n mountBehavior(child, visited);\n }\n\n if ('onMount' in inst && typeof inst.onMount === 'function') {\n try {\n const result = runInAction(() => inst.onMount!());\n // Only a returned function is a cleanup; ignore a Promise from an async\n // method so unmount doesn't try to call it.\n behavior.cleanup = typeof result === 'function' ? result : undefined;\n } catch (e) {\n reportError(e, { phase: 'onMount', name: inst.constructor.name, isBehavior: true });\n }\n }\n}\n\n/** @internal */\nexport function unmountBehavior(behavior: BehaviorEntry, visited: WeakSet<object> = new WeakSet()): void {\n const inst = behavior.instance;\n if (visited.has(inst)) return;\n visited.add(inst);\n\n // Call layout cleanup if exists\n runInAction(() => behavior.layoutCleanup?.());\n\n // Call cleanup if exists\n runInAction(() => behavior.cleanup?.());\n\n // Call onUnmount if exists\n if ('onUnmount' in inst && typeof inst.onUnmount === 'function') {\n try {\n runInAction(() => inst.onUnmount!());\n } catch (e) {\n reportError(e, { phase: 'onUnmount', name: inst.constructor.name, isBehavior: true });\n }\n }\n\n // Dispose all watchers\n if (typeof inst._disposeWatchers === 'function') {\n inst._disposeWatchers();\n }\n\n // Allow StrictMode's same-instance effect replay to resurrect pre-mount watchers\n inst._wasUnmounted = true;\n\n // Children tear down after their parent's onUnmount, in reverse of mount order\n const children = childBehaviors(inst);\n for (let i = children.length - 1; i >= 0; i--) {\n unmountBehavior(children[i], visited);\n }\n}\n\n/**\n * @internal Dev-only: warn about behavior instances sitting in fields that\n * were never collected into the lifecycle relay (assigned after\n * construction — conditionally, lazily, or in a Component's onCreate).\n * Their onMount/watchers/cleanup would otherwise silently never run.\n * Recurses into collected behaviors to catch late-assigned grandchildren.\n */\nexport function warnUncollectedBehaviors(\n host: object,\n hostName: string,\n entries: BehaviorEntry[],\n visited: WeakSet<object> = new WeakSet()\n): void {\n if (visited.has(host)) return;\n visited.add(host);\n\n const collected = new Set(entries.map((e) => e.instance));\n for (const key of Object.keys(host)) {\n if (key.startsWith('_')) continue;\n const value = (host as any)[key];\n if (isBehavior(value) && !isServiceValue(host, value) && !collected.has(value)) {\n console.warn(\n `[mobx-mantle] ${hostName}.${key} holds a behavior that was assigned after ` +\n `construction, so its lifecycle (onMount, watchers, cleanup) will never run. ` +\n `Create behaviors as class fields so they are collected when the host is constructed.`\n );\n }\n }\n\n for (const entry of entries) {\n warnUncollectedBehaviors(\n entry.instance,\n entry.instance.constructor.name,\n childBehaviors(entry.instance),\n visited\n );\n }\n}\r\n","import { _getGlobalState, runInAction } from 'mobx';\nimport { globalConfig } from './config';\nimport type { MaybeGetter } from './reactive-args';\n\n/**\n * Bind a model method without hiding observable reads from an enclosing\n * render/computed/reaction. Outside a tracking context the same method runs in\n * an action so event-handler mutations are still batched.\n *\n * Component and Behavior methods deliberately share this policy. A plain\n * `action.bound` would make a read helper such as `size.below(640)` untracked,\n * so the consumer would never subscribe to `size.width`.\n */\nexport function smartBind<T extends (...args: any[]) => any>(fn: T, context: any): T {\n return function (this: any, ...args: any[]) {\n const globalState = _getGlobalState();\n const isInTrackingContext = globalState.trackingDerivation !== null;\n\n if (isInTrackingContext) {\n return fn.apply(context, args);\n }\n return runInAction(() => fn.apply(context, args));\n } as T;\n}\n\n// smartBind and PropsBox.get rely on MobX's internal global state shape\n// (trackingDerivation). Fail loudly if a MobX upgrade changes it instead of\n// silently breaking method tracking or mutation batching.\nif (process.env.NODE_ENV !== 'production') {\n const globalState = _getGlobalState() as Record<string, unknown> | undefined;\n if (!globalState || !('trackingDerivation' in globalState)) {\n console.warn(\n '[mobx-mantle] MobX internal state no longer exposes trackingDerivation. ' +\n 'smartBind cannot detect tracking contexts and props reads cannot skip ' +\n 'self-notification, so method calls may not batch correctly and prop ' +\n 'changes may double-render. Check mobx version compatibility.'\n );\n }\n}\n\n/**\n * Normalize a watch source: a function is the tracked expression; a plain\n * value becomes a constant expression. A constant with no fireImmediately is\n * an unreachable watch — the callback can never fire — which is the signature\n * of a missing-arrow mistake, so dev mode warns.\n */\nexport function toWatchExpression<T>(\n source: MaybeGetter<T>,\n fireImmediately: boolean | undefined,\n ownerName: string\n): () => T {\n if (typeof source === 'function') {\n return source as () => T;\n }\n if (process.env.NODE_ENV !== 'production' && !fireImmediately) {\n console.warn(\n `[mobx-mantle] ${ownerName}.watch() received a plain value, which can never ` +\n `change — the callback will never fire. Pass a getter (() => expr) to watch ` +\n `a live source, or add { fireImmediately: true } if a single immediate call ` +\n `is intended.`\n );\n }\n return () => source;\n}\n\n/**\n * A watch/effect registration. `create` builds the underlying MobX reaction\n * and returns its disposer. Specs registered before mount are kept so the\n * reaction can be re-created if the host unmounts and remounts with the same\n * instance — React StrictMode does exactly this in development.\n */\nexport interface ReactiveSpec {\n create: () => () => void;\n stopped: boolean;\n dispose: (() => void) | null;\n}\n\n/** Common reactive bookkeeping shape shared by Component and Behavior */\nexport interface ReactiveHost {\n _reactiveSpecs: ReactiveSpec[];\n _mounted: boolean;\n _wasUnmounted: boolean;\n}\n\n/**\n * Register a watch/effect on a host.\n *\n * - Before mount (field initializers, onCreate): recorded as a dormant spec.\n * activateSpecs() brings it alive in the commit phase (useLayoutEffect),\n * so renders React never commits (Suspense throws, aborted transitions,\n * server rendering) create no live MobX reactions.\n * - At or after mount (onLayoutMount, onMount, event handlers): created\n * immediately with no spec — those callsites re-run on remount, so they\n * re-register naturally.\n *\n * Returns an early-disposal function that also cancels any future\n * materialization or resurrection.\n */\nexport function registerReactive(host: ReactiveHost, create: () => () => void): () => void {\n if (host._mounted) {\n return create();\n }\n\n const spec: ReactiveSpec = { create, stopped: false, dispose: null };\n host._reactiveSpecs.push(spec);\n\n return () => {\n spec.stopped = true;\n spec.dispose?.();\n };\n}\n\n/**\n * Bring a host's pre-mount registrations alive at commit time and mark it\n * mounted. First mount materializes dormant specs; a remount with a\n * surviving instance (React StrictMode simulates this in development)\n * re-creates the reactions that were disposed at unmount.\n */\nexport function activateSpecs(host: ReactiveHost): void {\n if (host._wasUnmounted) {\n host._wasUnmounted = false;\n for (const spec of host._reactiveSpecs) {\n if (!spec.stopped) {\n spec.dispose = spec.create();\n }\n }\n } else if (!host._mounted) {\n for (const spec of host._reactiveSpecs) {\n if (!spec.stopped && spec.dispose === null) {\n spec.dispose = spec.create();\n }\n }\n }\n host._mounted = true;\n}\n\n/** Per-class prototype facts: getter keys and plain method keys */\nexport interface ProtoInfo {\n computedKeys: string[];\n methodKeys: string[];\n}\n\n/**\n * Walk a class's prototype chain (stopping before the framework base class\n * and Object.prototype), collecting getter keys and method keys. The result\n * depends only on the prototype, so it is identical for every instance of a\n * class and cached per class. Disable with configure({ cacheAnnotations: false }).\n */\nexport function collectProtoInfo(\n instance: object,\n stopProto: object,\n excludes: Set<string>,\n cache: WeakMap<Function, ProtoInfo>\n): ProtoInfo {\n const ctor = instance.constructor as Function;\n const useCache = globalConfig.cacheAnnotations !== false;\n\n if (useCache) {\n const cached = cache.get(ctor);\n if (cached) return cached;\n }\n\n const info: ProtoInfo = { computedKeys: [], methodKeys: [] };\n const seen = new Set<string>();\n\n let proto = Object.getPrototypeOf(instance);\n while (proto && proto !== stopProto && proto !== Object.prototype) {\n const descriptors = Object.getOwnPropertyDescriptors(proto);\n\n for (const [key, descriptor] of Object.entries(descriptors)) {\n if (excludes.has(key) || seen.has(key)) continue;\n seen.add(key);\n\n if (descriptor.get) {\n info.computedKeys.push(key);\n } else if (typeof descriptor.value === 'function') {\n info.methodKeys.push(key);\n }\n }\n\n proto = Object.getPrototypeOf(proto);\n }\n\n if (useCache) cache.set(ctor, info);\n return info;\n}\n","import { useContext } from 'react';\nimport { ServiceContext, withInjectionScope } from './services';\nimport { useEffect, useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './observer';\nimport {\n type BehaviorEntry,\n isBehavior,\n layoutMountBehavior,\n mountBehavior,\n unmountBehavior,\n} from './behavior';\n\n/**\n * Host a behavior inside a plain React function component. The behavior gets\n * the same lifecycle relay a Mantle Component would give it: onLayoutMount in\n * the layout phase, onMount after paint, watchers alive from commit, full\n * teardown at unmount, and StrictMode remount resurrection.\n *\n * The instance is created once per mount lifetime, from a factory so nothing\n * is constructed on re-renders. It is returned as-is — wrap the component in\n * observer() (from mobx-mantle) so renders track the behavior's observables:\n *\n * @example\n * ```tsx\n * const Toolbar = observer(() => {\n * const size = useBehavior(() => withWindowSize());\n * return <div>{size.width} × {size.height}</div>;\n * });\n * ```\n *\n * Note: the factory runs once, so getter arguments close over the first\n * render's scope. Getters reading observables (a store, another behavior)\n * stay live; getters reading a function component's props capture the first\n * render's props object and go stale — pass observable sources instead.\n */\nexport function useBehavior<T extends object>(create: () => T): T {\n const resolver = useContext(ServiceContext);\n const [entry] = useState<BehaviorEntry>(() => {\n const instance = withInjectionScope(resolver, create);\n if (process.env.NODE_ENV !== 'production' && !isBehavior(instance)) {\n console.warn(\n '[mobx-mantle] useBehavior() expected the factory to return a behavior ' +\n 'instance (created with a factory from createBehavior). Lifecycle relay ' +\n 'will be skipped for this value.'\n );\n }\n return { instance };\n });\n\n useIsomorphicLayoutEffect(() => {\n if (!isBehavior(entry.instance)) return;\n layoutMountBehavior(entry);\n }, [entry]);\n\n useEffect(() => {\n if (!isBehavior(entry.instance)) return;\n mountBehavior(entry);\n return () => unmountBehavior(entry);\n }, [entry]);\n\n return entry.instance as T;\n}\n","import { isObservableProp, reaction, runInAction, toJS } from 'mobx';\n\nexport interface SharedOptions {\n /**\n * Persist the shared fields to localStorage under the key and restore\n * them at startup, so a fresh window starts where the last one left off.\n * Default true.\n */\n persist?: boolean;\n /**\n * The fields to share. Defaults to the store's own observable data\n * fields: not getters, not methods, not names starting with `_`.\n */\n fields?: readonly string[];\n}\n\nexport interface ShareStoresOptions extends SharedOptions {\n /** Key prefix for each store; the key is `${prefix}:${name}`. Default `shared`. */\n prefix?: string;\n}\n\ninterface SharedEntry {\n dispose(): void;\n}\n\nconst registry = new WeakMap<object, SharedEntry>();\n\nfunction ownDataFields(store: object): string[] {\n return Object.keys(store).filter((key) => {\n if (key.startsWith('_')) return false;\n if (typeof (store as Record<string, unknown>)[key] === 'function') return false;\n return isObservableProp(store, key);\n });\n}\n\nfunction serialize(store: Record<string, unknown>, fields: readonly string[]): string {\n const values: Record<string, unknown> = {};\n for (const field of fields) values[field] = toJS(store[field]);\n return JSON.stringify(values);\n}\n\n/** Apply a serialized state inside one action; false when it is not usable. */\nfunction apply(store: Record<string, unknown>, fields: readonly string[], json: string): boolean {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch {\n return false;\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;\n const values = parsed as Record<string, unknown>;\n runInAction(() => {\n for (const field of fields) {\n if (field in values) store[field] = values[field];\n }\n });\n return true;\n}\n\nfunction safeStorage(): Storage | null {\n try {\n return typeof localStorage === 'undefined' ? null : localStorage;\n } catch {\n // Blocked storage (sandboxed or privacy settings): share without persisting.\n return null;\n }\n}\n\n/**\n * Share a MobX store's state across every window of one application:\n * other tabs, the frames a design tool hosts, anything on the same origin\n * that imports the same module. Each window keeps its own store instance;\n * values are mirrored, identity is not shared, and nothing goes through a\n * server or a parent document.\n *\n * Mechanics, the web's own answer for two windows, packaged so it is never\n * written by hand:\n * - restore the store's fields from localStorage at startup (`persist`);\n * - publish changes through a reaction to localStorage and a\n * BroadcastChannel;\n * - apply incoming changes from the channel or the `storage` event inside\n * an action.\n * Echo loops are bounded because a window only publishes when its\n * serialized state changed, and only applies what differs from it.\n *\n * The one authoring rule: effects must derive from state — a `reaction`,\n * `autorun`, or a component's `watch`/`effect` — never run inside setters,\n * because a change that arrives from another window sets fields directly.\n *\n * @example\n * export const themeStore = shared(new ThemeStore(), 'theme');\n */\nexport function shared<T extends object>(store: T, key: string, options: SharedOptions = {}): T {\n if (registry.has(store) || typeof window === 'undefined') return store;\n const target = store as Record<string, unknown>;\n const fields = options.fields ? [...options.fields] : ownDataFields(store);\n const storage = options.persist === false ? null : safeStorage();\n const channel =\n typeof BroadcastChannel === 'function' ? new BroadcastChannel(`mantle-shared:${key}`) : null;\n // Node's BroadcastChannel would keep a process alive; browsers have no unref.\n (channel as { unref?: () => void } | null)?.unref?.();\n\n let stored: string | null = null;\n try {\n stored = storage?.getItem(key) ?? null;\n } catch {\n stored = null;\n }\n if (stored !== null) apply(target, fields, stored);\n\n // The last state this window published or applied; the echo bound.\n let current = serialize(target, fields);\n\n const stopPublish = reaction(\n () => serialize(target, fields),\n (json) => {\n if (json === current) return;\n current = json;\n try {\n storage?.setItem(key, json);\n } catch {\n // quota exceeded or blocked storage — the value still travels the channel\n }\n channel?.postMessage(json);\n },\n );\n\n const receive = (json: string) => {\n if (json === current) return;\n current = json;\n apply(target, fields, json);\n };\n const onMessage = (event: MessageEvent) => {\n if (typeof event.data === 'string') receive(event.data);\n };\n const onStorage = (event: StorageEvent) => {\n if (event.key === key && event.newValue !== null) receive(event.newValue);\n };\n channel?.addEventListener('message', onMessage);\n window.addEventListener('storage', onStorage);\n\n registry.set(store, {\n dispose() {\n stopPublish();\n channel?.removeEventListener('message', onMessage);\n channel?.close();\n window.removeEventListener('storage', onStorage);\n registry.delete(store);\n },\n });\n return store;\n}\n\n/** Stop sharing a store (tests, teardown). The store keeps its current state. */\nexport function unshare(store: object): void {\n registry.get(store)?.dispose();\n}\n\n/**\n * Share several stores at once, keyed by name: the one line an application\n * writes at its entry point (a design tool's manifest, an app's main\n * module) so every window that imports it wires the same stores.\n *\n * @example\n * shareStores({ themeStore, navPreferences });\n */\nexport function shareStores<T extends Record<string, object>>(\n stores: T,\n options: ShareStoresOptions = {},\n): T {\n const { prefix = 'shared', ...rest } = options;\n for (const [name, store] of Object.entries(stores)) {\n shared(store, `${prefix}:${name}`, rest);\n }\n return stores;\n}\n"],"mappings":";;;;;AAAA,OAAO,WAAW;;;ACAlB,SAAS,aAAa,qBAAqB;AAsDpC,IAAM,eAA6B;AAAA,EACxC,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,mBAAmB;AACrB;AAEA,IAAI,sBAAsB;AAQnB,SAAS,wBAA8B;AAC5C,MAAI,oBAAqB;AACzB,wBAAsB;AACtB,MA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,QAAM,cAAcD;AAAA,IAClB,MAAM,UAAU,QAAQ,MAAM;AAAA,IAC9B,CAAC,SAAS;AACR,UAAI,SAAS,QAAS;AACtB,gBAAU;AACV,UAAI;AACF,iBAAS,QAAQ,KAAK,IAAI;AAAA,MAC5B,QAAQ;AAAA,MAER;AACA,eAAS,YAAY,IAAI;AAAA,IAC3B;AAAA,EACF;AAEA,QAAM,UAAU,CAAC,SAAiB;AAChC,QAAI,SAAS,QAAS;AACtB,cAAU;AACV,UAAM,QAAQ,QAAQ,IAAI;AAAA,EAC5B;AACA,QAAM,YAAY,CAAC,UAAwB;AACzC,QAAI,OAAO,MAAM,SAAS,SAAU,SAAQ,MAAM,IAAI;AAAA,EACxD;AACA,QAAM,YAAY,CAAC,UAAwB;AACzC,QAAI,MAAM,QAAQ,OAAO,MAAM,aAAa,KAAM,SAAQ,MAAM,QAAQ;AAAA,EAC1E;AACA,WAAS,iBAAiB,WAAW,SAAS;AAC9C,SAAO,iBAAiB,WAAW,SAAS;AAE5C,WAAS,IAAI,OAAO;AAAA,IAClB,UAAU;AACR,kBAAY;AACZ,eAAS,oBAAoB,WAAW,SAAS;AACjD,eAAS,MAAM;AACf,aAAO,oBAAoB,WAAW,SAAS;AAC/C,eAAS,OAAO,KAAK;AAAA,IACvB;AAAA,EACF,CAAC;AACD,SAAO;AACT;AAGO,SAAS,QAAQ,OAAqB;AAC3C,WAAS,IAAI,KAAK,GAAG,QAAQ;AAC/B;AAUO,SAAS,YACd,QACA,UAA8B,CAAC,GAC5B;AACH,QAAM,EAAE,SAAS,UAAU,GAAG,KAAK,IAAI;AACvC,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AAClD,WAAO,OAAO,GAAG,MAAM,IAAI,IAAI,IAAI,IAAI;AAAA,EACzC;AACA,SAAO;AACT;","names":["React","jsx","React","useRef","useEffect","memo","makeObservable","observable","computed","runInAction","reaction","autorun","_getGlobalState","adm","observable","action","computed","observable","computed","runInAction","runInAction","observable","computed","jsx","React","_getGlobalState","memo","runInAction","reaction","autorun","observable","computed","makeObservable","React","useRef","runInAction","useEffect","jsx","memo","useContext","useEffect","useContext","useEffect","isObservableProp","reaction","runInAction"]}