@vielzeug/ore 1.1.0 → 1.2.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.
Files changed (63) hide show
  1. package/dist/base-element.cjs +1 -1
  2. package/dist/base-element.cjs.map +1 -1
  3. package/dist/base-element.d.ts +6 -0
  4. package/dist/base-element.d.ts.map +1 -1
  5. package/dist/base-element.js +1 -1
  6. package/dist/base-element.js.map +1 -1
  7. package/dist/errors.cjs.map +1 -1
  8. package/dist/errors.d.ts +2 -1
  9. package/dist/errors.d.ts.map +1 -1
  10. package/dist/errors.js.map +1 -1
  11. package/dist/forms/field.cjs +1 -1
  12. package/dist/forms/field.cjs.map +1 -1
  13. package/dist/forms/field.d.ts +17 -0
  14. package/dist/forms/field.d.ts.map +1 -1
  15. package/dist/forms/field.js +1 -1
  16. package/dist/forms/field.js.map +1 -1
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/ore.cjs +1 -1
  22. package/dist/ore.cjs.map +1 -1
  23. package/dist/ore.iife.js +1 -1
  24. package/dist/ore.iife.js.map +1 -1
  25. package/dist/ore.js +1 -1
  26. package/dist/ore.js.map +1 -1
  27. package/dist/runtime.cjs +1 -1
  28. package/dist/runtime.cjs.map +1 -1
  29. package/dist/runtime.d.ts +9 -0
  30. package/dist/runtime.d.ts.map +1 -1
  31. package/dist/runtime.js +1 -1
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/testing/dom.cjs +2 -0
  34. package/dist/testing/dom.cjs.map +1 -0
  35. package/dist/testing/dom.d.ts +22 -0
  36. package/dist/testing/dom.d.ts.map +1 -0
  37. package/dist/testing/dom.js +2 -0
  38. package/dist/testing/dom.js.map +1 -0
  39. package/dist/testing/form-internals-polyfill.cjs +2 -0
  40. package/dist/testing/form-internals-polyfill.cjs.map +1 -0
  41. package/dist/testing/form-internals-polyfill.d.ts +17 -0
  42. package/dist/testing/form-internals-polyfill.d.ts.map +1 -0
  43. package/dist/testing/form-internals-polyfill.js +2 -0
  44. package/dist/testing/form-internals-polyfill.js.map +1 -0
  45. package/dist/testing/render-hook.cjs +1 -1
  46. package/dist/testing/render-hook.cjs.map +1 -1
  47. package/dist/testing/render-hook.js +1 -1
  48. package/dist/testing/render-hook.js.map +1 -1
  49. package/dist/testing/testing.cjs +1 -1
  50. package/dist/testing/testing.cjs.map +1 -1
  51. package/dist/testing/testing.d.ts +7 -1
  52. package/dist/testing/testing.d.ts.map +1 -1
  53. package/dist/testing/testing.js +1 -1
  54. package/dist/testing/testing.js.map +1 -1
  55. package/dist/testing.cjs +1 -1
  56. package/dist/testing.js +1 -1
  57. package/dist/utils/emit.cjs +1 -1
  58. package/dist/utils/emit.cjs.map +1 -1
  59. package/dist/utils/emit.d.ts +11 -4
  60. package/dist/utils/emit.d.ts.map +1 -1
  61. package/dist/utils/emit.js +1 -1
  62. package/dist/utils/emit.js.map +1 -1
  63. package/package.json +2 -2
@@ -1,2 +1,2 @@
1
- const e=require("./_dev.cjs"),t=require("./errors.cjs");require("./types/bindings.cjs");const n=require("./runtime.cjs"),r=require("./props.cjs"),i=require("./types.cjs"),a=require("./utils/css.cjs");let o=require("@vielzeug/ripple");var s=()=>({generation:0,mountCallbacks:[],phase:i.ComponentPhase.UNINITIALIZED,scope:(0,o.scope)(),templateResult:null}),c=class extends HTMLElement{static _definition;static _normalizedPropDefs;static formAssociated=!1;static observedAttributes=[];_component;constructor(){super();let e=this.constructor._definition;e?.shadow!==!1&&this.attachShadow({mode:`open`,...e?.shadow}),this._component=s()}connectedCallback(){(0,o.untrack)(()=>{this._component.phase===i.ComponentPhase.UNINITIALIZED&&this._runSetup(),this._init()}),this.dispatchEvent(new CustomEvent(i.LIFECYCLE_EVENTS.CONNECT,{bubbles:!1,composed:!1}))}attributeChangedCallback(e,t,n){if(t===n)return;let i=r.getPropMeta(this,e);if(!i)return;let a=i.parse(n);Object.is((0,o.untrack)(()=>i.signal.value),a)||(i.signal.value=a)}disconnectedCallback(){this._component.generation++,this._component.phase=i.ComponentPhase.UNMOUNTED,this.dispatchEvent(new CustomEvent(i.LIFECYCLE_EVENTS.DISCONNECT,{bubbles:!1,composed:!1})),this._component.scope.dispose(),this._component.mountCallbacks=[],this._component.phase=i.ComponentPhase.UNINITIALIZED,this._component.scope=(0,o.scope)(),this._component.templateResult=null}_handleSetupError(e,n=`setup`){let r=e instanceof Error?e:Error(String(e)),i=new t.OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${n})`,{cause:r,component:this.localName,phase:n}),a=this.constructor._definition;if(a?.onError)try{return a.onError(i,this)}catch{}t.reportRuntimeError(i,this)}_runSetup(){this._component.phase=i.ComponentPhase.SETUP_RUNNING;let e=this.constructor._definition,t=this.constructor._normalizedPropDefs,a={element:this,mountCallbacks:[]};try{let o;if(this._component.scope.run(()=>{o=n.runWithContext(a,()=>{let n=t?r.createProps(this,t):{};return e.setup(n)})}),this._component.mountCallbacks.push(...a.mountCallbacks),o!=null&&typeof o.then==`function`){let t=this._component.mountCallbacks.splice(0);this._component.phase=i.ComponentPhase.LOADING,e.loading&&(this._component.templateResult=e.loading()),this._runSetupAsync(o,t,this._component.generation)}else this._component.templateResult=o??null,this._component.phase=i.ComponentPhase.SETUP_DONE}catch(e){let t=this._handleSetupError(e);if(t)this._component.templateResult=t,this._component.phase=i.ComponentPhase.SETUP_DONE;else throw this._component.phase=i.ComponentPhase.UNINITIALIZED,e}}_isStale(e){return this._component.generation!==e||!this.isConnected}async _runSetupAsync(t,n,r){try{let a=await t;if(this._isStale(r)){e.warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);return}this._component.templateResult=a??null,this._component.phase=i.ComponentPhase.SETUP_DONE,this._component.mountCallbacks.push(...n),a&&this._applyResult(a),this._scheduleMountCallbacks()}catch(t){if(this._isStale(r)){e.warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);return}let n=this._handleSetupError(t,`async-setup`);n?(this._component.templateResult=n,this._component.phase=i.ComponentPhase.SETUP_DONE,this._applyResult(n)):this._component.phase=i.ComponentPhase.UNINITIALIZED}}_applyResult(e){e&&((this.shadowRoot??this).replaceChildren(e.fragment),this._component.scope.run(()=>{e.apply(n.onCleanup)}))}_init(){this._applyStyles(),this._mountTemplate(),this._component.phase===i.ComponentPhase.SETUP_DONE&&this._scheduleMountCallbacks()}_applyStyles(){let e=this.constructor._definition;this.shadowRoot&&e?.styles?.length&&(this.shadowRoot.adoptedStyleSheets=e.styles.map(a.loadStylesheet))}_mountTemplate(){let e=this._component.templateResult;e&&this._applyResult(e)}_scheduleMountCallbacks(){if(this._component.mountCallbacks.length===0)return;let e=this._component.generation;queueMicrotask(()=>{if(this._isStale(e))return;let t=this._component.mountCallbacks.splice(0);for(let e of t)try{let t={element:this,mountCallbacks:[]};this._component.scope.run(()=>{n.runWithContext(t,()=>{let t=e();typeof t==`function`&&n.onCleanup(t)})}),t.mountCallbacks.length>0&&this._component.mountCallbacks.push(...t.mountCallbacks)}catch(e){this._handleSetupError(e,`mounted`)}this._component.mountCallbacks.length>0&&this._scheduleMountCallbacks()})}};exports.BaseElement=c;
1
+ const e=require("./_dev.cjs"),t=require("./errors.cjs");require("./types/bindings.cjs");const n=require("./runtime.cjs"),r=require("./props.cjs"),i=require("./types.cjs"),a=require("./utils/css.cjs");let o=require("@vielzeug/ripple");var s=()=>({formResetCallbacks:[],generation:0,mountCallbacks:[],phase:i.ComponentPhase.UNINITIALIZED,scope:(0,o.scope)(),templateResult:null}),c=class extends HTMLElement{static _definition;static _normalizedPropDefs;static formAssociated=!1;static observedAttributes=[];_component;constructor(){super();let e=this.constructor._definition;e?.shadow!==!1&&this.attachShadow({mode:`open`,...e?.shadow}),this._component=s()}connectedCallback(){(0,o.untrack)(()=>{this._component.phase===i.ComponentPhase.UNINITIALIZED&&this._runSetup(),this._init()}),this.dispatchEvent(new CustomEvent(i.LIFECYCLE_EVENTS.CONNECT,{bubbles:!1,composed:!1}))}attributeChangedCallback(e,t,n){if(t===n)return;let i=r.getPropMeta(this,e);if(!i)return;let a=i.parse(n);Object.is((0,o.untrack)(()=>i.signal.value),a)||(i.signal.value=a)}disconnectedCallback(){this._component.generation++,this._component.phase=i.ComponentPhase.UNMOUNTED,this.dispatchEvent(new CustomEvent(i.LIFECYCLE_EVENTS.DISCONNECT,{bubbles:!1,composed:!1})),this._component.scope.dispose(),this._component.formResetCallbacks=[],this._component.mountCallbacks=[],this._component.phase=i.ComponentPhase.UNINITIALIZED,this._component.scope=(0,o.scope)(),this._component.templateResult=null}formResetCallback(){for(let e of this._component.formResetCallbacks)try{e()}catch(e){this._handleSetupError(e,`form-reset`)}}_handleSetupError(e,n=`setup`){let r=e instanceof Error?e:Error(String(e)),i=new t.OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${n})`,{cause:r,component:this.localName,phase:n}),a=this.constructor._definition;if(a?.onError)try{return a.onError(i,this)}catch{}t.reportRuntimeError(i,this)}_runSetup(){this._component.phase=i.ComponentPhase.SETUP_RUNNING;let e=this.constructor._definition,t=this.constructor._normalizedPropDefs,a={element:this,formResetCallbacks:[],mountCallbacks:[]};try{let o;if(this._component.scope.run(()=>{o=n.runWithContext(a,()=>{let n=t?r.createProps(this,t):{};return e.setup(n)})}),this._component.mountCallbacks.push(...a.mountCallbacks),this._component.formResetCallbacks.push(...a.formResetCallbacks),o!=null&&typeof o.then==`function`){let t=this._component.mountCallbacks.splice(0);this._component.phase=i.ComponentPhase.LOADING,e.loading&&(this._component.templateResult=e.loading()),this._runSetupAsync(o,t,this._component.generation)}else this._component.templateResult=o??null,this._component.phase=i.ComponentPhase.SETUP_DONE}catch(e){let t=this._handleSetupError(e);if(t)this._component.templateResult=t,this._component.phase=i.ComponentPhase.SETUP_DONE;else throw this._component.phase=i.ComponentPhase.UNINITIALIZED,e}}_isStale(e){return this._component.generation!==e||!this.isConnected}async _runSetupAsync(t,n,r){try{let a=await t;if(this._isStale(r)){e.warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);return}this._component.templateResult=a??null,this._component.phase=i.ComponentPhase.SETUP_DONE,this._component.mountCallbacks.push(...n),a&&this._applyResult(a),this._scheduleMountCallbacks()}catch(t){if(this._isStale(r)){e.warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);return}let n=this._handleSetupError(t,`async-setup`);n?(this._component.templateResult=n,this._component.phase=i.ComponentPhase.SETUP_DONE,this._applyResult(n)):this._component.phase=i.ComponentPhase.UNINITIALIZED}}_applyResult(e){e&&((this.shadowRoot??this).replaceChildren(e.fragment),this._component.scope.run(()=>{e.apply(n.onCleanup)}))}_init(){this._applyStyles(),this._mountTemplate(),this._component.phase===i.ComponentPhase.SETUP_DONE&&this._scheduleMountCallbacks()}_applyStyles(){let e=this.constructor._definition;this.shadowRoot&&e?.styles?.length&&(this.shadowRoot.adoptedStyleSheets=e.styles.map(a.loadStylesheet))}_mountTemplate(){let e=this._component.templateResult;e&&this._applyResult(e)}_scheduleMountCallbacks(){if(this._component.mountCallbacks.length===0)return;let e=this._component.generation;queueMicrotask(()=>{if(this._isStale(e))return;let t=this._component.mountCallbacks.splice(0);for(let e of t)try{let t={element:this,formResetCallbacks:[],mountCallbacks:[]};this._component.scope.run(()=>{n.runWithContext(t,()=>{let t=e();typeof t==`function`&&n.onCleanup(t)})}),t.mountCallbacks.length>0&&this._component.mountCallbacks.push(...t.mountCallbacks),t.formResetCallbacks.length>0&&this._component.formResetCallbacks.push(...t.formResetCallbacks)}catch(e){this._handleSetupError(e,`mounted`)}this._component.mountCallbacks.length>0&&this._scheduleMountCallbacks()})}};exports.BaseElement=c;
2
2
  //# sourceMappingURL=base-element.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"base-element.cjs","names":[],"sources":["../src/base-element.ts"],"sourcesContent":["import { scope as _scope, type Scope, untrack } from '@vielzeug/ripple';\n\nimport type { ComponentDefinition } from './component-types';\n\nimport { warn } from './_dev';\nimport { type OreErrorPhase, OreLifecycleError, reportRuntimeError } from './errors';\nimport { createProps, getPropMeta, type InferProps, type PropInputDefs, type PropsDef } from './props';\nimport { type OnMountedCallback, onCleanup, type RuntimeContext, runWithContext } from './runtime';\nimport { ComponentPhase, LIFECYCLE_EVENTS } from './types';\nimport { type HTMLResult } from './types/bindings';\nimport { loadStylesheet } from './utils/css';\n\n// ─── Internal component state ─────────────────────────────────────────────────\n\ntype ComponentState = {\n /** Incremented on every disconnect — guards both mount callbacks and async setup results. */\n generation: number;\n mountCallbacks: OnMountedCallback[];\n phase: ComponentPhase;\n scope: Scope;\n templateResult: HTMLResult | null;\n};\n\nconst createComponentState = (): ComponentState => ({\n generation: 0,\n mountCallbacks: [],\n phase: ComponentPhase.UNINITIALIZED,\n scope: _scope(),\n templateResult: null,\n});\n\n// ─── BaseElement ──────────────────────────────────────────────────────────────\n\n/**\n * Phase transitions:\n *\n * ```\n * UNINITIALIZED ──_runSetup()──┬─(sync result)──► SETUP_DONE\n * └─(promise)──────► LOADING ──(resolves)──► SETUP_DONE\n * SETUP_DONE / LOADING ──disconnectedCallback()──► UNMOUNTED ──(reset)──► UNINITIALIZED\n * ```\n *\n * `generation` increments on every disconnect and is captured before an async\n * `setup()` is awaited; if it no longer matches when the promise settles, the\n * element was disconnected (and possibly reconnected) in the meantime and the\n * result is discarded (see `_isStale`).\n *\n * Why this lives on the class instead of a standalone pure reducer: every\n * transition here is triggered by running actual user code (`def.setup()`,\n * `onMounted` callbacks) inside a reactive `scope.run()` + `runWithContext()`\n * — there is no meaningful \"decide the next phase\" step that can be separated\n * from \"run the side-effecting thing that produces the phase change\" without\n * introducing a data-only effect-description layer that this package has no\n * other use for. That's why the methods below stay as direct, readable\n * procedural steps instead of a reducer + effect interpreter.\n */\nexport class BaseElement extends HTMLElement {\n static _definition: ComponentDefinition<any>;\n static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;\n static formAssociated = false;\n static observedAttributes: string[] = [];\n\n private _component: ComponentState;\n\n constructor() {\n super();\n\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.shadow !== false) {\n this.attachShadow({ mode: 'open', ...(def?.shadow as Partial<ShadowRootInit> | undefined) });\n }\n\n this._component = createComponentState();\n }\n\n connectedCallback(): void {\n untrack(() => {\n if (this._component.phase === ComponentPhase.UNINITIALIZED) this._runSetup();\n\n this._init();\n });\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.CONNECT, { bubbles: false, composed: false }));\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue) return;\n\n const propMeta = getPropMeta(this, name);\n\n if (!propMeta) return;\n\n const parsed = propMeta.parse(newValue);\n\n if (\n !Object.is(\n untrack(() => propMeta.signal.value),\n parsed,\n )\n )\n propMeta.signal.value = parsed as never;\n }\n\n disconnectedCallback(): void {\n this._component.generation++;\n this._component.phase = ComponentPhase.UNMOUNTED;\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.DISCONNECT, { bubbles: false, composed: false }));\n this._component.scope.dispose();\n // Reset mutable fields for next connect, keeping the same object for stable references\n this._component.mountCallbacks = [];\n this._component.phase = ComponentPhase.UNINITIALIZED;\n this._component.scope = _scope();\n this._component.templateResult = null;\n }\n\n private _handleSetupError(error: unknown, phase: OreErrorPhase = 'setup'): HTMLResult | void {\n const err = error instanceof Error ? error : new Error(String(error));\n const oreError = new OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${phase})`, {\n cause: err,\n component: this.localName,\n phase,\n });\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.onError) {\n try {\n return def.onError(oreError, this);\n } catch {\n /* fall through */\n }\n }\n\n reportRuntimeError(oreError, this);\n }\n\n private _runSetup(): void {\n this._component.phase = ComponentPhase.SETUP_RUNNING;\n\n const def = (this.constructor as typeof BaseElement)._definition;\n const normalizedPropDefs = (this.constructor as typeof BaseElement)._normalizedPropDefs;\n const ctx: RuntimeContext = { element: this, mountCallbacks: [] };\n\n try {\n let setupResult: HTMLResult | null | Promise<HTMLResult | null> | undefined;\n\n this._component.scope.run(() => {\n setupResult = runWithContext(ctx, () => {\n const setupProps = normalizedPropDefs\n ? createProps(this, normalizedPropDefs)\n : ({} as InferProps<PropInputDefs>);\n\n return def.setup(setupProps as InferProps<PropInputDefs>);\n });\n });\n this._component.mountCallbacks.push(...ctx.mountCallbacks);\n\n if (setupResult != null && typeof (setupResult as Promise<HTMLResult | null>).then === 'function') {\n // Async setup: show loading template immediately, swap when resolved.\n // Store captured mount callbacks; they will be scheduled after the real template mounts.\n const pendingCallbacks = this._component.mountCallbacks.splice(0);\n\n this._component.phase = ComponentPhase.LOADING;\n\n if (def.loading) {\n this._component.templateResult = def.loading();\n }\n\n // Capture the current generation so the async handler can detect staleness:\n // if the element disconnects+reconnects before the promise resolves, generation is\n // incremented and the old promise result must be discarded.\n void this._runSetupAsync(\n setupResult as Promise<HTMLResult | null>,\n pendingCallbacks,\n this._component.generation,\n );\n } else {\n this._component.templateResult = (setupResult as HTMLResult | null) ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n }\n } catch (error) {\n const recoveryTemplate = this._handleSetupError(error);\n\n if (recoveryTemplate) {\n this._component.templateResult = recoveryTemplate;\n this._component.phase = ComponentPhase.SETUP_DONE;\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n throw error;\n }\n }\n }\n\n /**\n * True once the element has disconnected (and possibly reconnected) since\n * `capturedGeneration` was recorded — an in-flight async `setup()` result\n * arriving after that point is for an instance state that no longer exists.\n */\n private _isStale(capturedGeneration: number): boolean {\n return this._component.generation !== capturedGeneration || !this.isConnected;\n }\n\n private async _runSetupAsync(\n promise: Promise<HTMLResult | null>,\n pendingCallbacks: OnMountedCallback[],\n capturedGeneration: number,\n ): Promise<void> {\n try {\n const result = await promise;\n\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n this._component.templateResult = result ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._component.mountCallbacks.push(...pendingCallbacks);\n\n if (result) this._applyResult(result);\n\n this._scheduleMountCallbacks();\n } catch (error) {\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n const recovery = this._handleSetupError(error, 'async-setup');\n\n if (recovery) {\n this._component.templateResult = recovery;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._applyResult(recovery);\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n }\n }\n }\n\n private _applyResult(result: HTMLResult | null): void {\n if (!result) return;\n\n const host: Element | ShadowRoot = this.shadowRoot ?? this;\n\n host.replaceChildren(result.fragment);\n this._component.scope.run(() => {\n result.apply(onCleanup);\n });\n }\n\n private _init(): void {\n this._applyStyles();\n this._mountTemplate();\n\n // Only schedule mount callbacks once setup is fully complete (not in LOADING state)\n if (this._component.phase === ComponentPhase.SETUP_DONE) this._scheduleMountCallbacks();\n }\n\n private _applyStyles(): void {\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (this.shadowRoot && def?.styles?.length) {\n this.shadowRoot.adoptedStyleSheets = def.styles.map(loadStylesheet);\n }\n }\n\n private _mountTemplate(): void {\n const result = this._component.templateResult;\n\n if (!result) return;\n\n this._applyResult(result);\n }\n\n private _scheduleMountCallbacks(): void {\n if (this._component.mountCallbacks.length === 0) return;\n\n const capturedGeneration = this._component.generation;\n\n queueMicrotask(() => {\n if (this._isStale(capturedGeneration)) return;\n\n // Snapshot callbacks so in-loop registrations don't extend this iteration.\n const batch = this._component.mountCallbacks.splice(0);\n\n for (const callback of batch) {\n try {\n const nestedCtx = { element: this, mountCallbacks: [] as typeof this._component.mountCallbacks };\n\n this._component.scope.run(() => {\n runWithContext(nestedCtx, () => {\n const cleanup = callback();\n\n if (typeof cleanup === 'function') onCleanup(cleanup);\n });\n });\n\n if (nestedCtx.mountCallbacks.length > 0) {\n this._component.mountCallbacks.push(...nestedCtx.mountCallbacks);\n }\n } catch (error) {\n this._handleSetupError(error, 'mounted');\n }\n }\n\n // If nested onMounted calls registered new callbacks, schedule them with\n // a fresh token check in the next microtask.\n if (this._component.mountCallbacks.length > 0) {\n this._scheduleMountCallbacks();\n }\n });\n }\n}\n"],"mappings":"0OAuBA,IAAM,OAA8C,CAClD,WAAY,EACZ,eAAgB,CAAC,EACjB,MAAO,EAAA,eAAe,cACtB,OAAA,EAAA,EAAA,MAAA,CAAc,EACd,eAAgB,IAClB,GA2Ba,EAAb,cAAiC,WAAY,CAC3C,OAAO,YACP,OAAO,oBACP,OAAO,eAAiB,GACxB,OAAO,mBAA+B,CAAC,EAEvC,WAEA,aAAc,CACZ,MAAM,EAEN,IAAM,EAAO,KAAK,YAAmC,YAEjD,GAAK,SAAW,IAClB,KAAK,aAAa,CAAE,KAAM,OAAQ,GAAI,GAAK,MAA+C,CAAC,EAG7F,KAAK,WAAa,EAAqB,CACzC,CAEA,mBAA0B,EACxB,EAAA,EAAA,QAAA,KAAc,CACR,KAAK,WAAW,QAAU,EAAA,eAAe,eAAe,KAAK,UAAU,EAE3E,KAAK,MAAM,CACb,CAAC,EACD,KAAK,cAAc,IAAI,YAAY,EAAA,iBAAiB,QAAS,CAAE,QAAS,GAAO,SAAU,EAAM,CAAC,CAAC,CACnG,CAEA,yBAAyB,EAAc,EAAyB,EAA+B,CAC7F,GAAI,IAAa,EAAU,OAE3B,IAAM,EAAW,EAAA,YAAY,KAAM,CAAI,EAEvC,GAAI,CAAC,EAAU,OAEf,IAAM,EAAS,EAAS,MAAM,CAAQ,EAGnC,OAAO,IAAA,EAAA,EAAA,QAAA,KACQ,EAAS,OAAO,KAAK,EACnC,CACF,IAEA,EAAS,OAAO,MAAQ,EAC5B,CAEA,sBAA6B,CAC3B,KAAK,WAAW,aAChB,KAAK,WAAW,MAAQ,EAAA,eAAe,UACvC,KAAK,cAAc,IAAI,YAAY,EAAA,iBAAiB,WAAY,CAAE,QAAS,GAAO,SAAU,EAAM,CAAC,CAAC,EACpG,KAAK,WAAW,MAAM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EAAO,KAAK,YAAmC,YAEjD,KAAK,YAAc,GAAK,QAAQ,SAClC,KAAK,WAAW,mBAAqB,EAAI,OAAO,IAAI,EAAA,cAAc,EAEtE,CAEA,gBAA+B,CAC7B,IAAM,EAAS,KAAK,WAAW,eAE1B,GAEL,KAAK,aAAa,CAAM,CAC1B,CAEA,yBAAwC,CACtC,GAAI,KAAK,WAAW,eAAe,SAAW,EAAG,OAEjD,IAAM,EAAqB,KAAK,WAAW,WAE3C,mBAAqB,CACnB,GAAI,KAAK,SAAS,CAAkB,EAAG,OAGvC,IAAM,EAAQ,KAAK,WAAW,eAAe,OAAO,CAAC,EAErD,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,IAAM,EAAY,CAAE,QAAS,KAAM,eAAgB,CAAC,CAA2C,EAE/F,KAAK,WAAW,MAAM,QAAU,CAC9B,EAAA,eAAe,MAAiB,CAC9B,IAAM,EAAU,EAAS,EAErB,OAAO,GAAY,YAAY,EAAA,UAAU,CAAO,CACtD,CAAC,CACH,CAAC,EAEG,EAAU,eAAe,OAAS,GACpC,KAAK,WAAW,eAAe,KAAK,GAAG,EAAU,cAAc,CAEnE,OAAS,EAAO,CACd,KAAK,kBAAkB,EAAO,SAAS,CACzC,CAKE,KAAK,WAAW,eAAe,OAAS,GAC1C,KAAK,wBAAwB,CAEjC,CAAC,CACH,CACF"}
1
+ {"version":3,"file":"base-element.cjs","names":[],"sources":["../src/base-element.ts"],"sourcesContent":["import { scope as _scope, type Scope, untrack } from '@vielzeug/ripple';\n\nimport type { ComponentDefinition } from './component-types';\n\nimport { warn } from './_dev';\nimport { type OreErrorPhase, OreLifecycleError, reportRuntimeError } from './errors';\nimport { createProps, getPropMeta, type InferProps, type PropInputDefs, type PropsDef } from './props';\nimport {\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n type RuntimeContext,\n runWithContext,\n} from './runtime';\nimport { ComponentPhase, LIFECYCLE_EVENTS } from './types';\nimport { type HTMLResult } from './types/bindings';\nimport { loadStylesheet } from './utils/css';\n\n// ─── Internal component state ─────────────────────────────────────────────────\n\ntype ComponentState = {\n /** Registered via `onFormReset()` — persists across mount callbacks, unlike `mountCallbacks`. */\n formResetCallbacks: OnFormResetCallback[];\n /** Incremented on every disconnect — guards both mount callbacks and async setup results. */\n generation: number;\n mountCallbacks: OnMountedCallback[];\n phase: ComponentPhase;\n scope: Scope;\n templateResult: HTMLResult | null;\n};\n\nconst createComponentState = (): ComponentState => ({\n formResetCallbacks: [],\n generation: 0,\n mountCallbacks: [],\n phase: ComponentPhase.UNINITIALIZED,\n scope: _scope(),\n templateResult: null,\n});\n\n// ─── BaseElement ──────────────────────────────────────────────────────────────\n\n/**\n * Phase transitions:\n *\n * ```\n * UNINITIALIZED ──_runSetup()──┬─(sync result)──► SETUP_DONE\n * └─(promise)──────► LOADING ──(resolves)──► SETUP_DONE\n * SETUP_DONE / LOADING ──disconnectedCallback()──► UNMOUNTED ──(reset)──► UNINITIALIZED\n * ```\n *\n * `generation` increments on every disconnect and is captured before an async\n * `setup()` is awaited; if it no longer matches when the promise settles, the\n * element was disconnected (and possibly reconnected) in the meantime and the\n * result is discarded (see `_isStale`).\n *\n * Why this lives on the class instead of a standalone pure reducer: every\n * transition here is triggered by running actual user code (`def.setup()`,\n * `onMounted` callbacks) inside a reactive `scope.run()` + `runWithContext()`\n * — there is no meaningful \"decide the next phase\" step that can be separated\n * from \"run the side-effecting thing that produces the phase change\" without\n * introducing a data-only effect-description layer that this package has no\n * other use for. That's why the methods below stay as direct, readable\n * procedural steps instead of a reducer + effect interpreter.\n */\nexport class BaseElement extends HTMLElement {\n static _definition: ComponentDefinition<any>;\n static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;\n static formAssociated = false;\n static observedAttributes: string[] = [];\n\n private _component: ComponentState;\n\n constructor() {\n super();\n\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.shadow !== false) {\n this.attachShadow({ mode: 'open', ...(def?.shadow as Partial<ShadowRootInit> | undefined) });\n }\n\n this._component = createComponentState();\n }\n\n connectedCallback(): void {\n untrack(() => {\n if (this._component.phase === ComponentPhase.UNINITIALIZED) this._runSetup();\n\n this._init();\n });\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.CONNECT, { bubbles: false, composed: false }));\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue) return;\n\n const propMeta = getPropMeta(this, name);\n\n if (!propMeta) return;\n\n const parsed = propMeta.parse(newValue);\n\n if (\n !Object.is(\n untrack(() => propMeta.signal.value),\n parsed,\n )\n )\n propMeta.signal.value = parsed as never;\n }\n\n disconnectedCallback(): void {\n this._component.generation++;\n this._component.phase = ComponentPhase.UNMOUNTED;\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.DISCONNECT, { bubbles: false, composed: false }));\n this._component.scope.dispose();\n // Reset mutable fields for next connect, keeping the same object for stable references\n this._component.formResetCallbacks = [];\n this._component.mountCallbacks = [];\n this._component.phase = ComponentPhase.UNINITIALIZED;\n this._component.scope = _scope();\n this._component.templateResult = null;\n }\n\n /**\n * Native form-association lifecycle callback — the browser calls this on every\n * `formAssociated: true` element inside a `<form>` when that form is reset.\n * Runs every `onFormReset()` callback registered during `setup()`.\n */\n formResetCallback(): void {\n for (const callback of this._component.formResetCallbacks) {\n try {\n callback();\n } catch (error) {\n this._handleSetupError(error, 'form-reset');\n }\n }\n }\n\n private _handleSetupError(error: unknown, phase: OreErrorPhase = 'setup'): HTMLResult | void {\n const err = error instanceof Error ? error : new Error(String(error));\n const oreError = new OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${phase})`, {\n cause: err,\n component: this.localName,\n phase,\n });\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.onError) {\n try {\n return def.onError(oreError, this);\n } catch {\n /* fall through */\n }\n }\n\n reportRuntimeError(oreError, this);\n }\n\n private _runSetup(): void {\n this._component.phase = ComponentPhase.SETUP_RUNNING;\n\n const def = (this.constructor as typeof BaseElement)._definition;\n const normalizedPropDefs = (this.constructor as typeof BaseElement)._normalizedPropDefs;\n const ctx: RuntimeContext = { element: this, formResetCallbacks: [], mountCallbacks: [] };\n\n try {\n let setupResult: HTMLResult | null | Promise<HTMLResult | null> | undefined;\n\n this._component.scope.run(() => {\n setupResult = runWithContext(ctx, () => {\n const setupProps = normalizedPropDefs\n ? createProps(this, normalizedPropDefs)\n : ({} as InferProps<PropInputDefs>);\n\n return def.setup(setupProps as InferProps<PropInputDefs>);\n });\n });\n this._component.mountCallbacks.push(...ctx.mountCallbacks);\n this._component.formResetCallbacks.push(...ctx.formResetCallbacks);\n\n if (setupResult != null && typeof (setupResult as Promise<HTMLResult | null>).then === 'function') {\n // Async setup: show loading template immediately, swap when resolved.\n // Store captured mount callbacks; they will be scheduled after the real template mounts.\n const pendingCallbacks = this._component.mountCallbacks.splice(0);\n\n this._component.phase = ComponentPhase.LOADING;\n\n if (def.loading) {\n this._component.templateResult = def.loading();\n }\n\n // Capture the current generation so the async handler can detect staleness:\n // if the element disconnects+reconnects before the promise resolves, generation is\n // incremented and the old promise result must be discarded.\n void this._runSetupAsync(\n setupResult as Promise<HTMLResult | null>,\n pendingCallbacks,\n this._component.generation,\n );\n } else {\n this._component.templateResult = (setupResult as HTMLResult | null) ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n }\n } catch (error) {\n const recoveryTemplate = this._handleSetupError(error);\n\n if (recoveryTemplate) {\n this._component.templateResult = recoveryTemplate;\n this._component.phase = ComponentPhase.SETUP_DONE;\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n throw error;\n }\n }\n }\n\n /**\n * True once the element has disconnected (and possibly reconnected) since\n * `capturedGeneration` was recorded — an in-flight async `setup()` result\n * arriving after that point is for an instance state that no longer exists.\n */\n private _isStale(capturedGeneration: number): boolean {\n return this._component.generation !== capturedGeneration || !this.isConnected;\n }\n\n private async _runSetupAsync(\n promise: Promise<HTMLResult | null>,\n pendingCallbacks: OnMountedCallback[],\n capturedGeneration: number,\n ): Promise<void> {\n try {\n const result = await promise;\n\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n this._component.templateResult = result ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._component.mountCallbacks.push(...pendingCallbacks);\n\n if (result) this._applyResult(result);\n\n this._scheduleMountCallbacks();\n } catch (error) {\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n const recovery = this._handleSetupError(error, 'async-setup');\n\n if (recovery) {\n this._component.templateResult = recovery;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._applyResult(recovery);\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n }\n }\n }\n\n private _applyResult(result: HTMLResult | null): void {\n if (!result) return;\n\n const host: Element | ShadowRoot = this.shadowRoot ?? this;\n\n host.replaceChildren(result.fragment);\n this._component.scope.run(() => {\n result.apply(onCleanup);\n });\n }\n\n private _init(): void {\n this._applyStyles();\n this._mountTemplate();\n\n // Only schedule mount callbacks once setup is fully complete (not in LOADING state)\n if (this._component.phase === ComponentPhase.SETUP_DONE) this._scheduleMountCallbacks();\n }\n\n private _applyStyles(): void {\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (this.shadowRoot && def?.styles?.length) {\n this.shadowRoot.adoptedStyleSheets = def.styles.map(loadStylesheet);\n }\n }\n\n private _mountTemplate(): void {\n const result = this._component.templateResult;\n\n if (!result) return;\n\n this._applyResult(result);\n }\n\n private _scheduleMountCallbacks(): void {\n if (this._component.mountCallbacks.length === 0) return;\n\n const capturedGeneration = this._component.generation;\n\n queueMicrotask(() => {\n if (this._isStale(capturedGeneration)) return;\n\n // Snapshot callbacks so in-loop registrations don't extend this iteration.\n const batch = this._component.mountCallbacks.splice(0);\n\n for (const callback of batch) {\n try {\n const nestedCtx = {\n element: this,\n formResetCallbacks: [] as typeof this._component.formResetCallbacks,\n mountCallbacks: [] as typeof this._component.mountCallbacks,\n };\n\n this._component.scope.run(() => {\n runWithContext(nestedCtx, () => {\n const cleanup = callback();\n\n if (typeof cleanup === 'function') onCleanup(cleanup);\n });\n });\n\n if (nestedCtx.mountCallbacks.length > 0) {\n this._component.mountCallbacks.push(...nestedCtx.mountCallbacks);\n }\n\n if (nestedCtx.formResetCallbacks.length > 0) {\n this._component.formResetCallbacks.push(...nestedCtx.formResetCallbacks);\n }\n } catch (error) {\n this._handleSetupError(error, 'mounted');\n }\n }\n\n // If nested onMounted calls registered new callbacks, schedule them with\n // a fresh token check in the next microtask.\n if (this._component.mountCallbacks.length > 0) {\n this._scheduleMountCallbacks();\n }\n });\n }\n}\n"],"mappings":"0OA+BA,IAAM,OAA8C,CAClD,mBAAoB,CAAC,EACrB,WAAY,EACZ,eAAgB,CAAC,EACjB,MAAO,EAAA,eAAe,cACtB,OAAA,EAAA,EAAA,MAAA,CAAc,EACd,eAAgB,IAClB,GA2Ba,EAAb,cAAiC,WAAY,CAC3C,OAAO,YACP,OAAO,oBACP,OAAO,eAAiB,GACxB,OAAO,mBAA+B,CAAC,EAEvC,WAEA,aAAc,CACZ,MAAM,EAEN,IAAM,EAAO,KAAK,YAAmC,YAEjD,GAAK,SAAW,IAClB,KAAK,aAAa,CAAE,KAAM,OAAQ,GAAI,GAAK,MAA+C,CAAC,EAG7F,KAAK,WAAa,EAAqB,CACzC,CAEA,mBAA0B,EACxB,EAAA,EAAA,QAAA,KAAc,CACR,KAAK,WAAW,QAAU,EAAA,eAAe,eAAe,KAAK,UAAU,EAE3E,KAAK,MAAM,CACb,CAAC,EACD,KAAK,cAAc,IAAI,YAAY,EAAA,iBAAiB,QAAS,CAAE,QAAS,GAAO,SAAU,EAAM,CAAC,CAAC,CACnG,CAEA,yBAAyB,EAAc,EAAyB,EAA+B,CAC7F,GAAI,IAAa,EAAU,OAE3B,IAAM,EAAW,EAAA,YAAY,KAAM,CAAI,EAEvC,GAAI,CAAC,EAAU,OAEf,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OAAS,GACpC,KAAK,WAAW,eAAe,KAAK,GAAG,EAAU,cAAc,EAG7D,EAAU,mBAAmB,OAAS,GACxC,KAAK,WAAW,mBAAmB,KAAK,GAAG,EAAU,kBAAkB,CAE3E,OAAS,EAAO,CACd,KAAK,kBAAkB,EAAO,SAAS,CACzC,CAKE,KAAK,WAAW,eAAe,OAAS,GAC1C,KAAK,wBAAwB,CAEjC,CAAC,CACH,CACF"}
@@ -33,6 +33,12 @@ export declare class BaseElement extends HTMLElement {
33
33
  connectedCallback(): void;
34
34
  attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void;
35
35
  disconnectedCallback(): void;
36
+ /**
37
+ * Native form-association lifecycle callback — the browser calls this on every
38
+ * `formAssociated: true` element inside a `<form>` when that form is reset.
39
+ * Runs every `onFormReset()` callback registered during `setup()`.
40
+ */
41
+ formResetCallback(): void;
36
42
  private _handleSetupError;
37
43
  private _runSetup;
38
44
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"base-element.d.ts","sourceRoot":"","sources":["../src/base-element.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAI7D,OAAO,EAAiE,KAAK,QAAQ,EAAE,MAAM,SAAS,CAAC;AA2BvG;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,WAAY,SAAQ,WAAW;IAC1C,MAAM,CAAC,WAAW,EAAE,mBAAmB,CAAC,GAAG,CAAC,CAAC;IAC7C,MAAM,CAAC,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,GAAG,SAAS,CAAC;IACvE,MAAM,CAAC,cAAc,UAAS;IAC9B,MAAM,CAAC,kBAAkB,EAAE,MAAM,EAAE,CAAM;IAEzC,OAAO,CAAC,UAAU,CAAiB;;IAcnC,iBAAiB,IAAI,IAAI;IASzB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GA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YAAY;IAWpB,OAAO,CAAC,KAAK;IAQb,OAAO,CAAC,YAAY;IAQpB,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,uBAAuB;CA8ChC"}
@@ -1,2 +1,2 @@
1
- import{warn as e}from"./_dev.js";import{OreLifecycleError as t,reportRuntimeError as n}from"./errors.js";import"./types/bindings.js";import{onCleanup as r,runWithContext as i}from"./runtime.js";import{createProps as a,getPropMeta as o}from"./props.js";import{ComponentPhase as s,LIFECYCLE_EVENTS as c}from"./types.js";import{loadStylesheet as l}from"./utils/css.js";import{scope as u,untrack as d}from"@vielzeug/ripple";var f=()=>({generation:0,mountCallbacks:[],phase:s.UNINITIALIZED,scope:u(),templateResult:null}),p=class extends HTMLElement{static _definition;static _normalizedPropDefs;static formAssociated=!1;static observedAttributes=[];_component;constructor(){super();let e=this.constructor._definition;e?.shadow!==!1&&this.attachShadow({mode:`open`,...e?.shadow}),this._component=f()}connectedCallback(){d(()=>{this._component.phase===s.UNINITIALIZED&&this._runSetup(),this._init()}),this.dispatchEvent(new CustomEvent(c.CONNECT,{bubbles:!1,composed:!1}))}attributeChangedCallback(e,t,n){if(t===n)return;let r=o(this,e);if(!r)return;let i=r.parse(n);Object.is(d(()=>r.signal.value),i)||(r.signal.value=i)}disconnectedCallback(){this._component.generation++,this._component.phase=s.UNMOUNTED,this.dispatchEvent(new CustomEvent(c.DISCONNECT,{bubbles:!1,composed:!1})),this._component.scope.dispose(),this._component.mountCallbacks=[],this._component.phase=s.UNINITIALIZED,this._component.scope=u(),this._component.templateResult=null}_handleSetupError(e,r=`setup`){let i=e instanceof Error?e:Error(String(e)),a=new t(`<${this.localName}> failed during ${this._component.phase} (${r})`,{cause:i,component:this.localName,phase:r}),o=this.constructor._definition;if(o?.onError)try{return o.onError(a,this)}catch{}n(a,this)}_runSetup(){this._component.phase=s.SETUP_RUNNING;let e=this.constructor._definition,t=this.constructor._normalizedPropDefs,n={element:this,mountCallbacks:[]};try{let r;if(this._component.scope.run(()=>{r=i(n,()=>{let n=t?a(this,t):{};return e.setup(n)})}),this._component.mountCallbacks.push(...n.mountCallbacks),r!=null&&typeof r.then==`function`){let t=this._component.mountCallbacks.splice(0);this._component.phase=s.LOADING,e.loading&&(this._component.templateResult=e.loading()),this._runSetupAsync(r,t,this._component.generation)}else this._component.templateResult=r??null,this._component.phase=s.SETUP_DONE}catch(e){let t=this._handleSetupError(e);if(t)this._component.templateResult=t,this._component.phase=s.SETUP_DONE;else throw this._component.phase=s.UNINITIALIZED,e}}_isStale(e){return this._component.generation!==e||!this.isConnected}async _runSetupAsync(t,n,r){try{let i=await t;if(this._isStale(r)){e(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);return}this._component.templateResult=i??null,this._component.phase=s.SETUP_DONE,this._component.mountCallbacks.push(...n),i&&this._applyResult(i),this._scheduleMountCallbacks()}catch(t){if(this._isStale(r)){e(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);return}let n=this._handleSetupError(t,`async-setup`);n?(this._component.templateResult=n,this._component.phase=s.SETUP_DONE,this._applyResult(n)):this._component.phase=s.UNINITIALIZED}}_applyResult(e){e&&((this.shadowRoot??this).replaceChildren(e.fragment),this._component.scope.run(()=>{e.apply(r)}))}_init(){this._applyStyles(),this._mountTemplate(),this._component.phase===s.SETUP_DONE&&this._scheduleMountCallbacks()}_applyStyles(){let e=this.constructor._definition;this.shadowRoot&&e?.styles?.length&&(this.shadowRoot.adoptedStyleSheets=e.styles.map(l))}_mountTemplate(){let e=this._component.templateResult;e&&this._applyResult(e)}_scheduleMountCallbacks(){if(this._component.mountCallbacks.length===0)return;let e=this._component.generation;queueMicrotask(()=>{if(this._isStale(e))return;let t=this._component.mountCallbacks.splice(0);for(let e of t)try{let t={element:this,mountCallbacks:[]};this._component.scope.run(()=>{i(t,()=>{let t=e();typeof t==`function`&&r(t)})}),t.mountCallbacks.length>0&&this._component.mountCallbacks.push(...t.mountCallbacks)}catch(e){this._handleSetupError(e,`mounted`)}this._component.mountCallbacks.length>0&&this._scheduleMountCallbacks()})}};export{p as BaseElement};
1
+ import{warn as e}from"./_dev.js";import{OreLifecycleError as t,reportRuntimeError as n}from"./errors.js";import"./types/bindings.js";import{onCleanup as r,runWithContext as i}from"./runtime.js";import{createProps as a,getPropMeta as o}from"./props.js";import{ComponentPhase as s,LIFECYCLE_EVENTS as c}from"./types.js";import{loadStylesheet as l}from"./utils/css.js";import{scope as u,untrack as d}from"@vielzeug/ripple";var f=()=>({formResetCallbacks:[],generation:0,mountCallbacks:[],phase:s.UNINITIALIZED,scope:u(),templateResult:null}),p=class extends HTMLElement{static _definition;static _normalizedPropDefs;static formAssociated=!1;static observedAttributes=[];_component;constructor(){super();let e=this.constructor._definition;e?.shadow!==!1&&this.attachShadow({mode:`open`,...e?.shadow}),this._component=f()}connectedCallback(){d(()=>{this._component.phase===s.UNINITIALIZED&&this._runSetup(),this._init()}),this.dispatchEvent(new CustomEvent(c.CONNECT,{bubbles:!1,composed:!1}))}attributeChangedCallback(e,t,n){if(t===n)return;let r=o(this,e);if(!r)return;let i=r.parse(n);Object.is(d(()=>r.signal.value),i)||(r.signal.value=i)}disconnectedCallback(){this._component.generation++,this._component.phase=s.UNMOUNTED,this.dispatchEvent(new CustomEvent(c.DISCONNECT,{bubbles:!1,composed:!1})),this._component.scope.dispose(),this._component.formResetCallbacks=[],this._component.mountCallbacks=[],this._component.phase=s.UNINITIALIZED,this._component.scope=u(),this._component.templateResult=null}formResetCallback(){for(let e of this._component.formResetCallbacks)try{e()}catch(e){this._handleSetupError(e,`form-reset`)}}_handleSetupError(e,r=`setup`){let i=e instanceof Error?e:Error(String(e)),a=new t(`<${this.localName}> failed during ${this._component.phase} (${r})`,{cause:i,component:this.localName,phase:r}),o=this.constructor._definition;if(o?.onError)try{return o.onError(a,this)}catch{}n(a,this)}_runSetup(){this._component.phase=s.SETUP_RUNNING;let e=this.constructor._definition,t=this.constructor._normalizedPropDefs,n={element:this,formResetCallbacks:[],mountCallbacks:[]};try{let r;if(this._component.scope.run(()=>{r=i(n,()=>{let n=t?a(this,t):{};return e.setup(n)})}),this._component.mountCallbacks.push(...n.mountCallbacks),this._component.formResetCallbacks.push(...n.formResetCallbacks),r!=null&&typeof r.then==`function`){let t=this._component.mountCallbacks.splice(0);this._component.phase=s.LOADING,e.loading&&(this._component.templateResult=e.loading()),this._runSetupAsync(r,t,this._component.generation)}else this._component.templateResult=r??null,this._component.phase=s.SETUP_DONE}catch(e){let t=this._handleSetupError(e);if(t)this._component.templateResult=t,this._component.phase=s.SETUP_DONE;else throw this._component.phase=s.UNINITIALIZED,e}}_isStale(e){return this._component.generation!==e||!this.isConnected}async _runSetupAsync(t,n,r){try{let i=await t;if(this._isStale(r)){e(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);return}this._component.templateResult=i??null,this._component.phase=s.SETUP_DONE,this._component.mountCallbacks.push(...n),i&&this._applyResult(i),this._scheduleMountCallbacks()}catch(t){if(this._isStale(r)){e(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);return}let n=this._handleSetupError(t,`async-setup`);n?(this._component.templateResult=n,this._component.phase=s.SETUP_DONE,this._applyResult(n)):this._component.phase=s.UNINITIALIZED}}_applyResult(e){e&&((this.shadowRoot??this).replaceChildren(e.fragment),this._component.scope.run(()=>{e.apply(r)}))}_init(){this._applyStyles(),this._mountTemplate(),this._component.phase===s.SETUP_DONE&&this._scheduleMountCallbacks()}_applyStyles(){let e=this.constructor._definition;this.shadowRoot&&e?.styles?.length&&(this.shadowRoot.adoptedStyleSheets=e.styles.map(l))}_mountTemplate(){let e=this._component.templateResult;e&&this._applyResult(e)}_scheduleMountCallbacks(){if(this._component.mountCallbacks.length===0)return;let e=this._component.generation;queueMicrotask(()=>{if(this._isStale(e))return;let t=this._component.mountCallbacks.splice(0);for(let e of t)try{let t={element:this,formResetCallbacks:[],mountCallbacks:[]};this._component.scope.run(()=>{i(t,()=>{let t=e();typeof t==`function`&&r(t)})}),t.mountCallbacks.length>0&&this._component.mountCallbacks.push(...t.mountCallbacks),t.formResetCallbacks.length>0&&this._component.formResetCallbacks.push(...t.formResetCallbacks)}catch(e){this._handleSetupError(e,`mounted`)}this._component.mountCallbacks.length>0&&this._scheduleMountCallbacks()})}};export{p as BaseElement};
2
2
  //# sourceMappingURL=base-element.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"base-element.js","names":[],"sources":["../src/base-element.ts"],"sourcesContent":["import { scope as _scope, type Scope, untrack } from '@vielzeug/ripple';\n\nimport type { ComponentDefinition } from './component-types';\n\nimport { warn } from './_dev';\nimport { type OreErrorPhase, OreLifecycleError, reportRuntimeError } from './errors';\nimport { createProps, getPropMeta, type InferProps, type PropInputDefs, type PropsDef } from './props';\nimport { type OnMountedCallback, onCleanup, type RuntimeContext, runWithContext } from './runtime';\nimport { ComponentPhase, LIFECYCLE_EVENTS } from './types';\nimport { type HTMLResult } from './types/bindings';\nimport { loadStylesheet } from './utils/css';\n\n// ─── Internal component state ─────────────────────────────────────────────────\n\ntype ComponentState = {\n /** Incremented on every disconnect — guards both mount callbacks and async setup results. */\n generation: number;\n mountCallbacks: OnMountedCallback[];\n phase: ComponentPhase;\n scope: Scope;\n templateResult: HTMLResult | null;\n};\n\nconst createComponentState = (): ComponentState => ({\n generation: 0,\n mountCallbacks: [],\n phase: ComponentPhase.UNINITIALIZED,\n scope: _scope(),\n templateResult: null,\n});\n\n// ─── BaseElement ──────────────────────────────────────────────────────────────\n\n/**\n * Phase transitions:\n *\n * ```\n * UNINITIALIZED ──_runSetup()──┬─(sync result)──► SETUP_DONE\n * └─(promise)──────► LOADING ──(resolves)──► SETUP_DONE\n * SETUP_DONE / LOADING ──disconnectedCallback()──► UNMOUNTED ──(reset)──► UNINITIALIZED\n * ```\n *\n * `generation` increments on every disconnect and is captured before an async\n * `setup()` is awaited; if it no longer matches when the promise settles, the\n * element was disconnected (and possibly reconnected) in the meantime and the\n * result is discarded (see `_isStale`).\n *\n * Why this lives on the class instead of a standalone pure reducer: every\n * transition here is triggered by running actual user code (`def.setup()`,\n * `onMounted` callbacks) inside a reactive `scope.run()` + `runWithContext()`\n * — there is no meaningful \"decide the next phase\" step that can be separated\n * from \"run the side-effecting thing that produces the phase change\" without\n * introducing a data-only effect-description layer that this package has no\n * other use for. That's why the methods below stay as direct, readable\n * procedural steps instead of a reducer + effect interpreter.\n */\nexport class BaseElement extends HTMLElement {\n static _definition: ComponentDefinition<any>;\n static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;\n static formAssociated = false;\n static observedAttributes: string[] = [];\n\n private _component: ComponentState;\n\n constructor() {\n super();\n\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.shadow !== false) {\n this.attachShadow({ mode: 'open', ...(def?.shadow as Partial<ShadowRootInit> | undefined) });\n }\n\n this._component = createComponentState();\n }\n\n connectedCallback(): void {\n untrack(() => {\n if (this._component.phase === ComponentPhase.UNINITIALIZED) this._runSetup();\n\n this._init();\n });\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.CONNECT, { bubbles: false, composed: false }));\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue) return;\n\n const propMeta = getPropMeta(this, name);\n\n if (!propMeta) return;\n\n const parsed = propMeta.parse(newValue);\n\n if (\n !Object.is(\n untrack(() => propMeta.signal.value),\n parsed,\n )\n )\n propMeta.signal.value = parsed as never;\n }\n\n disconnectedCallback(): void {\n this._component.generation++;\n this._component.phase = ComponentPhase.UNMOUNTED;\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.DISCONNECT, { bubbles: false, composed: false }));\n this._component.scope.dispose();\n // Reset mutable fields for next connect, keeping the same object for stable references\n this._component.mountCallbacks = [];\n this._component.phase = ComponentPhase.UNINITIALIZED;\n this._component.scope = _scope();\n this._component.templateResult = null;\n }\n\n private _handleSetupError(error: unknown, phase: OreErrorPhase = 'setup'): HTMLResult | void {\n const err = error instanceof Error ? error : new Error(String(error));\n const oreError = new OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${phase})`, {\n cause: err,\n component: this.localName,\n phase,\n });\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.onError) {\n try {\n return def.onError(oreError, this);\n } catch {\n /* fall through */\n }\n }\n\n reportRuntimeError(oreError, this);\n }\n\n private _runSetup(): void {\n this._component.phase = ComponentPhase.SETUP_RUNNING;\n\n const def = (this.constructor as typeof BaseElement)._definition;\n const normalizedPropDefs = (this.constructor as typeof BaseElement)._normalizedPropDefs;\n const ctx: RuntimeContext = { element: this, mountCallbacks: [] };\n\n try {\n let setupResult: HTMLResult | null | Promise<HTMLResult | null> | undefined;\n\n this._component.scope.run(() => {\n setupResult = runWithContext(ctx, () => {\n const setupProps = normalizedPropDefs\n ? createProps(this, normalizedPropDefs)\n : ({} as InferProps<PropInputDefs>);\n\n return def.setup(setupProps as InferProps<PropInputDefs>);\n });\n });\n this._component.mountCallbacks.push(...ctx.mountCallbacks);\n\n if (setupResult != null && typeof (setupResult as Promise<HTMLResult | null>).then === 'function') {\n // Async setup: show loading template immediately, swap when resolved.\n // Store captured mount callbacks; they will be scheduled after the real template mounts.\n const pendingCallbacks = this._component.mountCallbacks.splice(0);\n\n this._component.phase = ComponentPhase.LOADING;\n\n if (def.loading) {\n this._component.templateResult = def.loading();\n }\n\n // Capture the current generation so the async handler can detect staleness:\n // if the element disconnects+reconnects before the promise resolves, generation is\n // incremented and the old promise result must be discarded.\n void this._runSetupAsync(\n setupResult as Promise<HTMLResult | null>,\n pendingCallbacks,\n this._component.generation,\n );\n } else {\n this._component.templateResult = (setupResult as HTMLResult | null) ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n }\n } catch (error) {\n const recoveryTemplate = this._handleSetupError(error);\n\n if (recoveryTemplate) {\n this._component.templateResult = recoveryTemplate;\n this._component.phase = ComponentPhase.SETUP_DONE;\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n throw error;\n }\n }\n }\n\n /**\n * True once the element has disconnected (and possibly reconnected) since\n * `capturedGeneration` was recorded — an in-flight async `setup()` result\n * arriving after that point is for an instance state that no longer exists.\n */\n private _isStale(capturedGeneration: number): boolean {\n return this._component.generation !== capturedGeneration || !this.isConnected;\n }\n\n private async _runSetupAsync(\n promise: Promise<HTMLResult | null>,\n pendingCallbacks: OnMountedCallback[],\n capturedGeneration: number,\n ): Promise<void> {\n try {\n const result = await promise;\n\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n this._component.templateResult = result ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._component.mountCallbacks.push(...pendingCallbacks);\n\n if (result) this._applyResult(result);\n\n this._scheduleMountCallbacks();\n } catch (error) {\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n const recovery = this._handleSetupError(error, 'async-setup');\n\n if (recovery) {\n this._component.templateResult = recovery;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._applyResult(recovery);\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n }\n }\n }\n\n private _applyResult(result: HTMLResult | null): void {\n if (!result) return;\n\n const host: Element | ShadowRoot = this.shadowRoot ?? this;\n\n host.replaceChildren(result.fragment);\n this._component.scope.run(() => {\n result.apply(onCleanup);\n });\n }\n\n private _init(): void {\n this._applyStyles();\n this._mountTemplate();\n\n // Only schedule mount callbacks once setup is fully complete (not in LOADING state)\n if (this._component.phase === ComponentPhase.SETUP_DONE) this._scheduleMountCallbacks();\n }\n\n private _applyStyles(): void {\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (this.shadowRoot && def?.styles?.length) {\n this.shadowRoot.adoptedStyleSheets = def.styles.map(loadStylesheet);\n }\n }\n\n private _mountTemplate(): void {\n const result = this._component.templateResult;\n\n if (!result) return;\n\n this._applyResult(result);\n }\n\n private _scheduleMountCallbacks(): void {\n if (this._component.mountCallbacks.length === 0) return;\n\n const capturedGeneration = this._component.generation;\n\n queueMicrotask(() => {\n if (this._isStale(capturedGeneration)) return;\n\n // Snapshot callbacks so in-loop registrations don't extend this iteration.\n const batch = this._component.mountCallbacks.splice(0);\n\n for (const callback of batch) {\n try {\n const nestedCtx = { element: this, mountCallbacks: [] as typeof this._component.mountCallbacks };\n\n this._component.scope.run(() => {\n runWithContext(nestedCtx, () => {\n const cleanup = callback();\n\n if (typeof cleanup === 'function') onCleanup(cleanup);\n });\n });\n\n if (nestedCtx.mountCallbacks.length > 0) {\n this._component.mountCallbacks.push(...nestedCtx.mountCallbacks);\n }\n } catch (error) {\n this._handleSetupError(error, 'mounted');\n }\n }\n\n // If nested onMounted calls registered new callbacks, schedule them with\n // a fresh token check in the next microtask.\n if (this._component.mountCallbacks.length > 0) {\n this._scheduleMountCallbacks();\n }\n });\n }\n}\n"],"mappings":"oaAuBA,IAAM,OAA8C,CAClD,WAAY,EACZ,eAAgB,CAAC,EACjB,MAAO,EAAe,cACtB,MAAO,EAAO,EACd,eAAgB,IAClB,GA2Ba,EAAb,cAAiC,WAAY,CAC3C,OAAO,YACP,OAAO,oBACP,OAAO,eAAiB,GACxB,OAAO,mBAA+B,CAAC,EAEvC,WAEA,aAAc,CACZ,MAAM,EAEN,IAAM,EAAO,KAAK,YAAmC,YAEjD,GAAK,SAAW,IAClB,KAAK,aAAa,CAAE,KAAM,OAAQ,GAAI,GAAK,MAA+C,CAAC,EAG7F,KAAK,WAAa,EAAqB,CACzC,CAEA,mBAA0B,CACxB,MAAc,CACR,KAAK,WAAW,QAAU,EAAe,eAAe,KAAK,UAAU,EAE3E,KAAK,MAAM,CACb,CAAC,EACD,KAAK,cAAc,IAAI,YAAY,EAAiB,QAAS,CAAE,QAAS,GAAO,SAAU,EAAM,CAAC,CAAC,CACnG,CAEA,yBAAyB,EAAc,EAAyB,EAA+B,CAC7F,GAAI,IAAa,EAAU,OAE3B,IAAM,EAAW,EAAY,KAAM,CAAI,EAEvC,GAAI,CAAC,EAAU,OAEf,IAAM,EAAS,EAAS,MAA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B,CAAC,EACH,CAEA,OAAsB,CACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EAGhB,KAAK,WAAW,QAAU,EAAe,YAAY,KAAK,wBAAwB,CACxF,CAEA,cAA6B,CAC3B,IAAM,EAAO,KAAK,YAAmC,YAEjD,KAAK,YAAc,GAAK,QAAQ,SAClC,KAAK,WAAW,mBAAqB,EAAI,OAAO,IAAI,CAAc,EAEtE,CAEA,gBAA+B,CAC7B,IAAM,EAAS,KAAK,WAAW,eAE1B,GAEL,KAAK,aAAa,CAAM,CAC1B,CAEA,yBAAwC,CACtC,GAAI,KAAK,WAAW,eAAe,SAAW,EAAG,OAEjD,IAAM,EAAqB,KAAK,WAAW,WAE3C,mBAAqB,CACnB,GAAI,KAAK,SAAS,CAAkB,EAAG,OAGvC,IAAM,EAAQ,KAAK,WAAW,eAAe,OAAO,CAAC,EAErD,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,IAAM,EAAY,CAAE,QAAS,KAAM,eAAgB,CAAC,CAA2C,EAE/F,KAAK,WAAW,MAAM,QAAU,CAC9B,EAAe,MAAiB,CAC9B,IAAM,EAAU,EAAS,EAErB,OAAO,GAAY,YAAY,EAAU,CAAO,CACtD,CAAC,CACH,CAAC,EAEG,EAAU,eAAe,OAAS,GACpC,KAAK,WAAW,eAAe,KAAK,GAAG,EAAU,cAAc,CAEnE,OAAS,EAAO,CACd,KAAK,kBAAkB,EAAO,SAAS,CACzC,CAKE,KAAK,WAAW,eAAe,OAAS,GAC1C,KAAK,wBAAwB,CAEjC,CAAC,CACH,CACF"}
1
+ {"version":3,"file":"base-element.js","names":[],"sources":["../src/base-element.ts"],"sourcesContent":["import { scope as _scope, type Scope, untrack } from '@vielzeug/ripple';\n\nimport type { ComponentDefinition } from './component-types';\n\nimport { warn } from './_dev';\nimport { type OreErrorPhase, OreLifecycleError, reportRuntimeError } from './errors';\nimport { createProps, getPropMeta, type InferProps, type PropInputDefs, type PropsDef } from './props';\nimport {\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n type RuntimeContext,\n runWithContext,\n} from './runtime';\nimport { ComponentPhase, LIFECYCLE_EVENTS } from './types';\nimport { type HTMLResult } from './types/bindings';\nimport { loadStylesheet } from './utils/css';\n\n// ─── Internal component state ─────────────────────────────────────────────────\n\ntype ComponentState = {\n /** Registered via `onFormReset()` — persists across mount callbacks, unlike `mountCallbacks`. */\n formResetCallbacks: OnFormResetCallback[];\n /** Incremented on every disconnect — guards both mount callbacks and async setup results. */\n generation: number;\n mountCallbacks: OnMountedCallback[];\n phase: ComponentPhase;\n scope: Scope;\n templateResult: HTMLResult | null;\n};\n\nconst createComponentState = (): ComponentState => ({\n formResetCallbacks: [],\n generation: 0,\n mountCallbacks: [],\n phase: ComponentPhase.UNINITIALIZED,\n scope: _scope(),\n templateResult: null,\n});\n\n// ─── BaseElement ──────────────────────────────────────────────────────────────\n\n/**\n * Phase transitions:\n *\n * ```\n * UNINITIALIZED ──_runSetup()──┬─(sync result)──► SETUP_DONE\n * └─(promise)──────► LOADING ──(resolves)──► SETUP_DONE\n * SETUP_DONE / LOADING ──disconnectedCallback()──► UNMOUNTED ──(reset)──► UNINITIALIZED\n * ```\n *\n * `generation` increments on every disconnect and is captured before an async\n * `setup()` is awaited; if it no longer matches when the promise settles, the\n * element was disconnected (and possibly reconnected) in the meantime and the\n * result is discarded (see `_isStale`).\n *\n * Why this lives on the class instead of a standalone pure reducer: every\n * transition here is triggered by running actual user code (`def.setup()`,\n * `onMounted` callbacks) inside a reactive `scope.run()` + `runWithContext()`\n * — there is no meaningful \"decide the next phase\" step that can be separated\n * from \"run the side-effecting thing that produces the phase change\" without\n * introducing a data-only effect-description layer that this package has no\n * other use for. That's why the methods below stay as direct, readable\n * procedural steps instead of a reducer + effect interpreter.\n */\nexport class BaseElement extends HTMLElement {\n static _definition: ComponentDefinition<any>;\n static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;\n static formAssociated = false;\n static observedAttributes: string[] = [];\n\n private _component: ComponentState;\n\n constructor() {\n super();\n\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.shadow !== false) {\n this.attachShadow({ mode: 'open', ...(def?.shadow as Partial<ShadowRootInit> | undefined) });\n }\n\n this._component = createComponentState();\n }\n\n connectedCallback(): void {\n untrack(() => {\n if (this._component.phase === ComponentPhase.UNINITIALIZED) this._runSetup();\n\n this._init();\n });\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.CONNECT, { bubbles: false, composed: false }));\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue) return;\n\n const propMeta = getPropMeta(this, name);\n\n if (!propMeta) return;\n\n const parsed = propMeta.parse(newValue);\n\n if (\n !Object.is(\n untrack(() => propMeta.signal.value),\n parsed,\n )\n )\n propMeta.signal.value = parsed as never;\n }\n\n disconnectedCallback(): void {\n this._component.generation++;\n this._component.phase = ComponentPhase.UNMOUNTED;\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.DISCONNECT, { bubbles: false, composed: false }));\n this._component.scope.dispose();\n // Reset mutable fields for next connect, keeping the same object for stable references\n this._component.formResetCallbacks = [];\n this._component.mountCallbacks = [];\n this._component.phase = ComponentPhase.UNINITIALIZED;\n this._component.scope = _scope();\n this._component.templateResult = null;\n }\n\n /**\n * Native form-association lifecycle callback — the browser calls this on every\n * `formAssociated: true` element inside a `<form>` when that form is reset.\n * Runs every `onFormReset()` callback registered during `setup()`.\n */\n formResetCallback(): void {\n for (const callback of this._component.formResetCallbacks) {\n try {\n callback();\n } catch (error) {\n this._handleSetupError(error, 'form-reset');\n }\n }\n }\n\n private _handleSetupError(error: unknown, phase: OreErrorPhase = 'setup'): HTMLResult | void {\n const err = error instanceof Error ? error : new Error(String(error));\n const oreError = new OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${phase})`, {\n cause: err,\n component: this.localName,\n phase,\n });\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.onError) {\n try {\n return def.onError(oreError, this);\n } catch {\n /* fall through */\n }\n }\n\n reportRuntimeError(oreError, this);\n }\n\n private _runSetup(): void {\n this._component.phase = ComponentPhase.SETUP_RUNNING;\n\n const def = (this.constructor as typeof BaseElement)._definition;\n const normalizedPropDefs = (this.constructor as typeof BaseElement)._normalizedPropDefs;\n const ctx: RuntimeContext = { element: this, formResetCallbacks: [], mountCallbacks: [] };\n\n try {\n let setupResult: HTMLResult | null | Promise<HTMLResult | null> | undefined;\n\n this._component.scope.run(() => {\n setupResult = runWithContext(ctx, () => {\n const setupProps = normalizedPropDefs\n ? createProps(this, normalizedPropDefs)\n : ({} as InferProps<PropInputDefs>);\n\n return def.setup(setupProps as InferProps<PropInputDefs>);\n });\n });\n this._component.mountCallbacks.push(...ctx.mountCallbacks);\n this._component.formResetCallbacks.push(...ctx.formResetCallbacks);\n\n if (setupResult != null && typeof (setupResult as Promise<HTMLResult | null>).then === 'function') {\n // Async setup: show loading template immediately, swap when resolved.\n // Store captured mount callbacks; they will be scheduled after the real template mounts.\n const pendingCallbacks = this._component.mountCallbacks.splice(0);\n\n this._component.phase = ComponentPhase.LOADING;\n\n if (def.loading) {\n this._component.templateResult = def.loading();\n }\n\n // Capture the current generation so the async handler can detect staleness:\n // if the element disconnects+reconnects before the promise resolves, generation is\n // incremented and the old promise result must be discarded.\n void this._runSetupAsync(\n setupResult as Promise<HTMLResult | null>,\n pendingCallbacks,\n this._component.generation,\n );\n } else {\n this._component.templateResult = (setupResult as HTMLResult | null) ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n }\n } catch (error) {\n const recoveryTemplate = this._handleSetupError(error);\n\n if (recoveryTemplate) {\n this._component.templateResult = recoveryTemplate;\n this._component.phase = ComponentPhase.SETUP_DONE;\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n throw error;\n }\n }\n }\n\n /**\n * True once the element has disconnected (and possibly reconnected) since\n * `capturedGeneration` was recorded — an in-flight async `setup()` result\n * arriving after that point is for an instance state that no longer exists.\n */\n private _isStale(capturedGeneration: number): boolean {\n return this._component.generation !== capturedGeneration || !this.isConnected;\n }\n\n private async _runSetupAsync(\n promise: Promise<HTMLResult | null>,\n pendingCallbacks: OnMountedCallback[],\n capturedGeneration: number,\n ): Promise<void> {\n try {\n const result = await promise;\n\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n this._component.templateResult = result ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._component.mountCallbacks.push(...pendingCallbacks);\n\n if (result) this._applyResult(result);\n\n this._scheduleMountCallbacks();\n } catch (error) {\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n const recovery = this._handleSetupError(error, 'async-setup');\n\n if (recovery) {\n this._component.templateResult = recovery;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._applyResult(recovery);\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n }\n }\n }\n\n private _applyResult(result: HTMLResult | null): void {\n if (!result) return;\n\n const host: Element | ShadowRoot = this.shadowRoot ?? this;\n\n host.replaceChildren(result.fragment);\n this._component.scope.run(() => {\n result.apply(onCleanup);\n });\n }\n\n private _init(): void {\n this._applyStyles();\n this._mountTemplate();\n\n // Only schedule mount callbacks once setup is fully complete (not in LOADING state)\n if (this._component.phase === ComponentPhase.SETUP_DONE) this._scheduleMountCallbacks();\n }\n\n private _applyStyles(): void {\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (this.shadowRoot && def?.styles?.length) {\n this.shadowRoot.adoptedStyleSheets = def.styles.map(loadStylesheet);\n }\n }\n\n private _mountTemplate(): void {\n const result = this._component.templateResult;\n\n if (!result) return;\n\n this._applyResult(result);\n }\n\n private _scheduleMountCallbacks(): void {\n if (this._component.mountCallbacks.length === 0) return;\n\n const capturedGeneration = this._component.generation;\n\n queueMicrotask(() => {\n if (this._isStale(capturedGeneration)) return;\n\n // Snapshot callbacks so in-loop registrations don't extend this iteration.\n const batch = this._component.mountCallbacks.splice(0);\n\n for (const callback of batch) {\n try {\n const nestedCtx = {\n element: this,\n formResetCallbacks: [] as typeof this._component.formResetCallbacks,\n mountCallbacks: [] as typeof this._component.mountCallbacks,\n };\n\n this._component.scope.run(() => {\n runWithContext(nestedCtx, () => {\n const cleanup = callback();\n\n if (typeof cleanup === 'function') onCleanup(cleanup);\n });\n });\n\n if (nestedCtx.mountCallbacks.length > 0) {\n this._component.mountCallbacks.push(...nestedCtx.mountCallbacks);\n }\n\n if (nestedCtx.formResetCallbacks.length > 0) {\n this._component.formResetCallbacks.push(...nestedCtx.formResetCallbacks);\n }\n } catch (error) {\n this._handleSetupError(error, 'mounted');\n }\n }\n\n // If nested onMounted calls registered new callbacks, schedule them with\n // a fresh token check in the next microtask.\n if (this._component.mountCallbacks.length > 0) {\n this._scheduleMountCallbacks();\n }\n });\n }\n}\n"],"mappings":"oaA+BA,IAAM,OAA8C,CAClD,mBAAoB,CAAC,EACrB,WAAY,EACZ,eAAgB,CAAC,EACjB,MAAO,EAAe,cACtB,MAAO,EAAO,EACd,eAAgB,IAClB,GA2Ba,EAAb,cAAiC,WAAY,CAC3C,OAAO,YACP,OAAO,oBACP,OAAO,eAAiB,GACxB,OAAO,mBAA+B,CAAC,EAEvC,WAEA,aAAc,CACZ,MAAM,EAEN,IAAM,EAAO,KAAK,YAAmC,YAEjD,GAAK,SAAW,IAClB,KAAK,aAAa,CAAE,KAAM,OAAQ,GAAI,GAAK,MAA+C,CAAC,EAG7F,KAAK,WAAa,EAAqB,CACzC,CAEA,mBAA0B,CACxB,MAAc,CACR,KAAK,WAAW,QAAU,EAAe,eAAe,KAAK,UAAU,EAE3E,KAAK,MAAM,CACb,CAAC,EACD,KAAK,cAAc,IAAI,YAAY,EAAiB,QAAS,CAAE,QAAS,GAAO,SAAU,EAAM,CAAC,CAAC,CACnG,CAEA,yBAAyB,EAAc,EAAyB,EAA+B,CAC7F,GAAI,IAAa,EAAU,OAE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,KAAK,GAAG,EAAU,kBAAkB,CAE3E,OAAS,EAAO,CACd,KAAK,kBAAkB,EAAO,SAAS,CACzC,CAKE,KAAK,WAAW,eAAe,OAAS,GAC1C,KAAK,wBAAwB,CAEjC,CAAC,CACH,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { error as logError } from './_dev';\n\n// ─── Structured error types ───────────────────────────────────────────────────\n\n/** Base class for all Ore errors. Use `instanceof OreError` to catch any Ore-originated error. */\nexport class OreError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is OreError {\n return err instanceof OreError;\n }\n}\n\n/** Thrown when Ore API is called incorrectly (e.g. outside setup, duplicate define, invalid prop). */\nexport class OreApiError extends OreError {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * Thrown when an internal invariant fails — e.g. compiled template metadata no\n * longer matching the DOM it was cloned from. Distinct from `OreApiError`: this\n * is never the caller's fault, it signals a bug in ore itself. See `invariant()`.\n */\nexport class OreInternalError extends OreError {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * The phase in which a component error occurred.\n * - `'setup'` — synchronous setup() threw\n * - `'async-setup'` — async setup() promise rejected\n * - `'mounted'` — an onMounted callback threw\n */\nexport type OreErrorPhase = 'async-setup' | 'mounted' | 'setup';\n\n/**\n * Structured error thrown by the Ore runtime when component setup fails.\n * Provides component name and original cause for debugging.\n */\nexport class OreLifecycleError extends OreError {\n readonly component: string;\n readonly phase: OreErrorPhase;\n\n constructor(message: string, options: { cause: Error; component: string; phase: OreErrorPhase }) {\n super(message, { cause: options.cause });\n this.component = options.component;\n this.phase = options.phase;\n }\n}\n\n/**\n * Report a runtime error via the ore:error event and console.\n */\nexport function reportRuntimeError(error: OreLifecycleError, element: HTMLElement): void {\n logError(`<${error.component}> setup error (phase: ${error.phase}):`, error.cause);\n\n element.dispatchEvent(\n new CustomEvent('ore:error', {\n bubbles: true,\n composed: true,\n detail: error,\n }),\n );\n}\n\n// ─── Error message constants ─────────────────────────────────────────────────\n\n/** Thrown by `waitFor` and `waitForEvent` in the testing sub-path when a condition is not met within the timeout. */\nexport class OreTimeoutError extends OreError {}\n\nexport const ORE_ERRORS = {\n defineDuplicate: (tag: string): string => `define('${tag}') called twice — custom element already registered`,\n defineFieldRequiresFormAssociated: (tag: string): string =>\n `useField() requires define('${tag}', { formAssociated: true })`,\n defineRequiresTag: 'define() requires a tag name',\n eachDuplicateKey: (key: string, index: number): string => `each() received duplicate key \"${key}\" at index ${index}`,\n injectStrictFailed: (key: string, tag: string): string => `injectStrict() could not resolve key \"${key}\" in <${tag}>`,\n invalidDynamicTagName: (tagName: string): string =>\n `html\\`...\\`: dynamic tag name \"${tagName}\" is not a valid HTML element name`,\n invariantViolated: (message: string): string => `invariant violated: ${message}`,\n lifecycleOutsideSetup: 'Lifecycle hooks must be called during component setup',\n propInvalidReflect: 'Structured props cannot use reflect:true — use prop.json() with reflect:false',\n validationFailed: (tag: string, errors: string[]): string => `Validation failed for <${tag}>:\\n${errors.join('\\n')}`,\n} as const;\n\n/**\n * Assert an internal invariant that must always hold — e.g. compiled template\n * metadata staying in sync with the DOM it was cloned from. A failed invariant\n * means a bug in ore itself, never user input, so it throws `OreInternalError`\n * unconditionally (every build, never gated like `_dev.ts`'s `warn()`).\n *\n * Narrowing caveat: `asserts condition` only narrows the exact expression\n * passed in. Assign to a local `const` first — `invariant(el.parentNode, msg)`\n * does not narrow later reads of `el.parentNode`.\n */\nexport function invariant(condition: unknown, message: string): asserts condition {\n if (!condition) throw new OreInternalError(ORE_ERRORS.invariantViolated(message));\n}\n"],"mappings":"8BAKA,IAAa,EAAb,MAAa,UAAiB,KAAM,CAClC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAA+B,CACvC,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAAiC,CAAS,CACxC,YAAY,EAAiB,CAC3B,MAAM,CAAO,CACf,CACF,EAOa,EAAb,cAAsC,CAAS,CAC7C,YAAY,EAAiB,CAC3B,MAAM,CAAO,CACf,CACF,EAca,EAAb,cAAuC,CAAS,CAC9C,UACA,MAEA,YAAY,EAAiB,EAAoE,CAC/F,MAAM,EAAS,CAAE,MAAO,EAAQ,KAAM,CAAC,EACvC,KAAK,UAAY,EAAQ,UACzB,KAAK,MAAQ,EAAQ,KACvB,CACF,EAKA,SAAgB,EAAmB,EAA0B,EAA4B,CACvF,EAAA,MAAS,IAAI,EAAM,UAAU,wBAAwB,EAAM,MAAM,IAAK,EAAM,KAAK,EAEjF,EAAQ,cACN,IAAI,YAAY,YAAa,CAC3B,QAAS,GACT,SAAU,GACV,OAAQ,CACV,CAAC,CACH,CACF,CAKA,IAAa,EAAb,cAAqC,CAAS,CAAC,EAElC,EAAa,CACxB,gBAAkB,GAAwB,WAAW,EAAI,qDACzD,kCAAoC,GAClC,+BAA+B,EAAI,8BACrC,kBAAmB,+BACnB,kBAAmB,EAAa,IAA0B,kCAAkC,EAAI,aAAa,IAC7G,oBAAqB,EAAa,IAAwB,yCAAyC,EAAI,QAAQ,EAAI,GACnH,sBAAwB,GACtB,kCAAkC,EAAQ,oCAC5C,kBAAoB,GAA4B,uBAAuB,IACvE,sBAAuB,wDACvB,mBAAoB,gFACpB,kBAAmB,EAAa,IAA6B,0BAA0B,EAAI,MAAM,EAAO,KAAK;CAAI,GACnH,EAYA,SAAgB,EAAU,EAAoB,EAAoC,CAChF,GAAI,CAAC,EAAW,MAAM,IAAI,EAAiB,EAAW,kBAAkB,CAAO,CAAC,CAClF"}
1
+ {"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { error as logError } from './_dev';\n\n// ─── Structured error types ───────────────────────────────────────────────────\n\n/** Base class for all Ore errors. Use `instanceof OreError` to catch any Ore-originated error. */\nexport class OreError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is OreError {\n return err instanceof OreError;\n }\n}\n\n/** Thrown when Ore API is called incorrectly (e.g. outside setup, duplicate define, invalid prop). */\nexport class OreApiError extends OreError {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * Thrown when an internal invariant fails — e.g. compiled template metadata no\n * longer matching the DOM it was cloned from. Distinct from `OreApiError`: this\n * is never the caller's fault, it signals a bug in ore itself. See `invariant()`.\n */\nexport class OreInternalError extends OreError {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * The phase in which a component error occurred.\n * - `'setup'` — synchronous setup() threw\n * - `'async-setup'` — async setup() promise rejected\n * - `'mounted'` — an onMounted callback threw\n * - `'form-reset'` — an onFormReset callback threw\n */\nexport type OreErrorPhase = 'async-setup' | 'form-reset' | 'mounted' | 'setup';\n\n/**\n * Structured error thrown by the Ore runtime when component setup fails.\n * Provides component name and original cause for debugging.\n */\nexport class OreLifecycleError extends OreError {\n readonly component: string;\n readonly phase: OreErrorPhase;\n\n constructor(message: string, options: { cause: Error; component: string; phase: OreErrorPhase }) {\n super(message, { cause: options.cause });\n this.component = options.component;\n this.phase = options.phase;\n }\n}\n\n/**\n * Report a runtime error via the ore:error event and console.\n */\nexport function reportRuntimeError(error: OreLifecycleError, element: HTMLElement): void {\n logError(`<${error.component}> setup error (phase: ${error.phase}):`, error.cause);\n\n element.dispatchEvent(\n new CustomEvent('ore:error', {\n bubbles: true,\n composed: true,\n detail: error,\n }),\n );\n}\n\n// ─── Error message constants ─────────────────────────────────────────────────\n\n/** Thrown by `waitFor` and `waitForEvent` in the testing sub-path when a condition is not met within the timeout. */\nexport class OreTimeoutError extends OreError {}\n\nexport const ORE_ERRORS = {\n defineDuplicate: (tag: string): string => `define('${tag}') called twice — custom element already registered`,\n defineFieldRequiresFormAssociated: (tag: string): string =>\n `useField() requires define('${tag}', { formAssociated: true })`,\n defineRequiresTag: 'define() requires a tag name',\n eachDuplicateKey: (key: string, index: number): string => `each() received duplicate key \"${key}\" at index ${index}`,\n injectStrictFailed: (key: string, tag: string): string => `injectStrict() could not resolve key \"${key}\" in <${tag}>`,\n invalidDynamicTagName: (tagName: string): string =>\n `html\\`...\\`: dynamic tag name \"${tagName}\" is not a valid HTML element name`,\n invariantViolated: (message: string): string => `invariant violated: ${message}`,\n lifecycleOutsideSetup: 'Lifecycle hooks must be called during component setup',\n propInvalidReflect: 'Structured props cannot use reflect:true — use prop.json() with reflect:false',\n validationFailed: (tag: string, errors: string[]): string => `Validation failed for <${tag}>:\\n${errors.join('\\n')}`,\n} as const;\n\n/**\n * Assert an internal invariant that must always hold — e.g. compiled template\n * metadata staying in sync with the DOM it was cloned from. A failed invariant\n * means a bug in ore itself, never user input, so it throws `OreInternalError`\n * unconditionally (every build, never gated like `_dev.ts`'s `warn()`).\n *\n * Narrowing caveat: `asserts condition` only narrows the exact expression\n * passed in. Assign to a local `const` first — `invariant(el.parentNode, msg)`\n * does not narrow later reads of `el.parentNode`.\n */\nexport function invariant(condition: unknown, message: string): asserts condition {\n if (!condition) throw new OreInternalError(ORE_ERRORS.invariantViolated(message));\n}\n"],"mappings":"8BAKA,IAAa,EAAb,MAAa,UAAiB,KAAM,CAClC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAA+B,CACvC,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAAiC,CAAS,CACxC,YAAY,EAAiB,CAC3B,MAAM,CAAO,CACf,CACF,EAOa,EAAb,cAAsC,CAAS,CAC7C,YAAY,EAAiB,CAC3B,MAAM,CAAO,CACf,CACF,EAea,EAAb,cAAuC,CAAS,CAC9C,UACA,MAEA,YAAY,EAAiB,EAAoE,CAC/F,MAAM,EAAS,CAAE,MAAO,EAAQ,KAAM,CAAC,EACvC,KAAK,UAAY,EAAQ,UACzB,KAAK,MAAQ,EAAQ,KACvB,CACF,EAKA,SAAgB,EAAmB,EAA0B,EAA4B,CACvF,EAAA,MAAS,IAAI,EAAM,UAAU,wBAAwB,EAAM,MAAM,IAAK,EAAM,KAAK,EAEjF,EAAQ,cACN,IAAI,YAAY,YAAa,CAC3B,QAAS,GACT,SAAU,GACV,OAAQ,CACV,CAAC,CACH,CACF,CAKA,IAAa,EAAb,cAAqC,CAAS,CAAC,EAElC,EAAa,CACxB,gBAAkB,GAAwB,WAAW,EAAI,qDACzD,kCAAoC,GAClC,+BAA+B,EAAI,8BACrC,kBAAmB,+BACnB,kBAAmB,EAAa,IAA0B,kCAAkC,EAAI,aAAa,IAC7G,oBAAqB,EAAa,IAAwB,yCAAyC,EAAI,QAAQ,EAAI,GACnH,sBAAwB,GACtB,kCAAkC,EAAQ,oCAC5C,kBAAoB,GAA4B,uBAAuB,IACvE,sBAAuB,wDACvB,mBAAoB,gFACpB,kBAAmB,EAAa,IAA6B,0BAA0B,EAAI,MAAM,EAAO,KAAK;CAAI,GACnH,EAYA,SAAgB,EAAU,EAAoB,EAAoC,CAChF,GAAI,CAAC,EAAW,MAAM,IAAI,EAAiB,EAAW,kBAAkB,CAAO,CAAC,CAClF"}
package/dist/errors.d.ts CHANGED
@@ -20,8 +20,9 @@ export declare class OreInternalError extends OreError {
20
20
  * - `'setup'` — synchronous setup() threw
21
21
  * - `'async-setup'` — async setup() promise rejected
22
22
  * - `'mounted'` — an onMounted callback threw
23
+ * - `'form-reset'` — an onFormReset callback threw
23
24
  */
24
- export type OreErrorPhase = 'async-setup' | 'mounted' | 'setup';
25
+ export type OreErrorPhase = 'async-setup' | 'form-reset' | 'mounted' | 'setup';
25
26
  /**
26
27
  * Structured error thrown by the Ore runtime when component setup fails.
27
28
  * Provides component name and original cause for debugging.
@@ -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nB,MAAM,KAAG,MAAM;;;qCAGpB,MAAM,UAAU,MAAM,EAAE,KAAG,MAAM;CACjD,CAAC;AAEX;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAEhF"}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { error as logError } from './_dev';\n\n// ─── Structured error types ───────────────────────────────────────────────────\n\n/** Base class for all Ore errors. Use `instanceof OreError` to catch any Ore-originated error. */\nexport class OreError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is OreError {\n return err instanceof OreError;\n }\n}\n\n/** Thrown when Ore API is called incorrectly (e.g. outside setup, duplicate define, invalid prop). */\nexport class OreApiError extends OreError {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * Thrown when an internal invariant fails — e.g. compiled template metadata no\n * longer matching the DOM it was cloned from. Distinct from `OreApiError`: this\n * is never the caller's fault, it signals a bug in ore itself. See `invariant()`.\n */\nexport class OreInternalError extends OreError {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * The phase in which a component error occurred.\n * - `'setup'` — synchronous setup() threw\n * - `'async-setup'` — async setup() promise rejected\n * - `'mounted'` — an onMounted callback threw\n */\nexport type OreErrorPhase = 'async-setup' | 'mounted' | 'setup';\n\n/**\n * Structured error thrown by the Ore runtime when component setup fails.\n * Provides component name and original cause for debugging.\n */\nexport class OreLifecycleError extends OreError {\n readonly component: string;\n readonly phase: OreErrorPhase;\n\n constructor(message: string, options: { cause: Error; component: string; phase: OreErrorPhase }) {\n super(message, { cause: options.cause });\n this.component = options.component;\n this.phase = options.phase;\n }\n}\n\n/**\n * Report a runtime error via the ore:error event and console.\n */\nexport function reportRuntimeError(error: OreLifecycleError, element: HTMLElement): void {\n logError(`<${error.component}> setup error (phase: ${error.phase}):`, error.cause);\n\n element.dispatchEvent(\n new CustomEvent('ore:error', {\n bubbles: true,\n composed: true,\n detail: error,\n }),\n );\n}\n\n// ─── Error message constants ─────────────────────────────────────────────────\n\n/** Thrown by `waitFor` and `waitForEvent` in the testing sub-path when a condition is not met within the timeout. */\nexport class OreTimeoutError extends OreError {}\n\nexport const ORE_ERRORS = {\n defineDuplicate: (tag: string): string => `define('${tag}') called twice — custom element already registered`,\n defineFieldRequiresFormAssociated: (tag: string): string =>\n `useField() requires define('${tag}', { formAssociated: true })`,\n defineRequiresTag: 'define() requires a tag name',\n eachDuplicateKey: (key: string, index: number): string => `each() received duplicate key \"${key}\" at index ${index}`,\n injectStrictFailed: (key: string, tag: string): string => `injectStrict() could not resolve key \"${key}\" in <${tag}>`,\n invalidDynamicTagName: (tagName: string): string =>\n `html\\`...\\`: dynamic tag name \"${tagName}\" is not a valid HTML element name`,\n invariantViolated: (message: string): string => `invariant violated: ${message}`,\n lifecycleOutsideSetup: 'Lifecycle hooks must be called during component setup',\n propInvalidReflect: 'Structured props cannot use reflect:true — use prop.json() with reflect:false',\n validationFailed: (tag: string, errors: string[]): string => `Validation failed for <${tag}>:\\n${errors.join('\\n')}`,\n} as const;\n\n/**\n * Assert an internal invariant that must always hold — e.g. compiled template\n * metadata staying in sync with the DOM it was cloned from. A failed invariant\n * means a bug in ore itself, never user input, so it throws `OreInternalError`\n * unconditionally (every build, never gated like `_dev.ts`'s `warn()`).\n *\n * Narrowing caveat: `asserts condition` only narrows the exact expression\n * passed in. Assign to a local `const` first — `invariant(el.parentNode, msg)`\n * does not narrow later reads of `el.parentNode`.\n */\nexport function invariant(condition: unknown, message: string): asserts condition {\n if (!condition) throw new OreInternalError(ORE_ERRORS.invariantViolated(message));\n}\n"],"mappings":"kCAKA,IAAa,EAAb,MAAa,UAAiB,KAAM,CAClC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAA+B,CACvC,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAAiC,CAAS,CACxC,YAAY,EAAiB,CAC3B,MAAM,CAAO,CACf,CACF,EAOa,EAAb,cAAsC,CAAS,CAC7C,YAAY,EAAiB,CAC3B,MAAM,CAAO,CACf,CACF,EAca,EAAb,cAAuC,CAAS,CAC9C,UACA,MAEA,YAAY,EAAiB,EAAoE,CAC/F,MAAM,EAAS,CAAE,MAAO,EAAQ,KAAM,CAAC,EACvC,KAAK,UAAY,EAAQ,UACzB,KAAK,MAAQ,EAAQ,KACvB,CACF,EAKA,SAAgB,EAAmB,EAA0B,EAA4B,CACvF,EAAS,IAAI,EAAM,UAAU,wBAAwB,EAAM,MAAM,IAAK,EAAM,KAAK,EAEjF,EAAQ,cACN,IAAI,YAAY,YAAa,CAC3B,QAAS,GACT,SAAU,GACV,OAAQ,CACV,CAAC,CACH,CACF,CAKA,IAAa,EAAb,cAAqC,CAAS,CAAC,EAElC,EAAa,CACxB,gBAAkB,GAAwB,WAAW,EAAI,qDACzD,kCAAoC,GAClC,+BAA+B,EAAI,8BACrC,kBAAmB,+BACnB,kBAAmB,EAAa,IAA0B,kCAAkC,EAAI,aAAa,IAC7G,oBAAqB,EAAa,IAAwB,yCAAyC,EAAI,QAAQ,EAAI,GACnH,sBAAwB,GACtB,kCAAkC,EAAQ,oCAC5C,kBAAoB,GAA4B,uBAAuB,IACvE,sBAAuB,wDACvB,mBAAoB,gFACpB,kBAAmB,EAAa,IAA6B,0BAA0B,EAAI,MAAM,EAAO,KAAK;CAAI,GACnH,EAYA,SAAgB,EAAU,EAAoB,EAAoC,CAChF,GAAI,CAAC,EAAW,MAAM,IAAI,EAAiB,EAAW,kBAAkB,CAAO,CAAC,CAClF"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { error as logError } from './_dev';\n\n// ─── Structured error types ───────────────────────────────────────────────────\n\n/** Base class for all Ore errors. Use `instanceof OreError` to catch any Ore-originated error. */\nexport class OreError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is OreError {\n return err instanceof OreError;\n }\n}\n\n/** Thrown when Ore API is called incorrectly (e.g. outside setup, duplicate define, invalid prop). */\nexport class OreApiError extends OreError {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * Thrown when an internal invariant fails — e.g. compiled template metadata no\n * longer matching the DOM it was cloned from. Distinct from `OreApiError`: this\n * is never the caller's fault, it signals a bug in ore itself. See `invariant()`.\n */\nexport class OreInternalError extends OreError {\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * The phase in which a component error occurred.\n * - `'setup'` — synchronous setup() threw\n * - `'async-setup'` — async setup() promise rejected\n * - `'mounted'` — an onMounted callback threw\n * - `'form-reset'` — an onFormReset callback threw\n */\nexport type OreErrorPhase = 'async-setup' | 'form-reset' | 'mounted' | 'setup';\n\n/**\n * Structured error thrown by the Ore runtime when component setup fails.\n * Provides component name and original cause for debugging.\n */\nexport class OreLifecycleError extends OreError {\n readonly component: string;\n readonly phase: OreErrorPhase;\n\n constructor(message: string, options: { cause: Error; component: string; phase: OreErrorPhase }) {\n super(message, { cause: options.cause });\n this.component = options.component;\n this.phase = options.phase;\n }\n}\n\n/**\n * Report a runtime error via the ore:error event and console.\n */\nexport function reportRuntimeError(error: OreLifecycleError, element: HTMLElement): void {\n logError(`<${error.component}> setup error (phase: ${error.phase}):`, error.cause);\n\n element.dispatchEvent(\n new CustomEvent('ore:error', {\n bubbles: true,\n composed: true,\n detail: error,\n }),\n );\n}\n\n// ─── Error message constants ─────────────────────────────────────────────────\n\n/** Thrown by `waitFor` and `waitForEvent` in the testing sub-path when a condition is not met within the timeout. */\nexport class OreTimeoutError extends OreError {}\n\nexport const ORE_ERRORS = {\n defineDuplicate: (tag: string): string => `define('${tag}') called twice — custom element already registered`,\n defineFieldRequiresFormAssociated: (tag: string): string =>\n `useField() requires define('${tag}', { formAssociated: true })`,\n defineRequiresTag: 'define() requires a tag name',\n eachDuplicateKey: (key: string, index: number): string => `each() received duplicate key \"${key}\" at index ${index}`,\n injectStrictFailed: (key: string, tag: string): string => `injectStrict() could not resolve key \"${key}\" in <${tag}>`,\n invalidDynamicTagName: (tagName: string): string =>\n `html\\`...\\`: dynamic tag name \"${tagName}\" is not a valid HTML element name`,\n invariantViolated: (message: string): string => `invariant violated: ${message}`,\n lifecycleOutsideSetup: 'Lifecycle hooks must be called during component setup',\n propInvalidReflect: 'Structured props cannot use reflect:true — use prop.json() with reflect:false',\n validationFailed: (tag: string, errors: string[]): string => `Validation failed for <${tag}>:\\n${errors.join('\\n')}`,\n} as const;\n\n/**\n * Assert an internal invariant that must always hold — e.g. compiled template\n * metadata staying in sync with the DOM it was cloned from. A failed invariant\n * means a bug in ore itself, never user input, so it throws `OreInternalError`\n * unconditionally (every build, never gated like `_dev.ts`'s `warn()`).\n *\n * Narrowing caveat: `asserts condition` only narrows the exact expression\n * passed in. Assign to a local `const` first — `invariant(el.parentNode, msg)`\n * does not narrow later reads of `el.parentNode`.\n */\nexport function invariant(condition: unknown, message: string): asserts condition {\n if (!condition) throw new OreInternalError(ORE_ERRORS.invariantViolated(message));\n}\n"],"mappings":"kCAKA,IAAa,EAAb,MAAa,UAAiB,KAAM,CAClC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAA+B,CACvC,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAAiC,CAAS,CACxC,YAAY,EAAiB,CAC3B,MAAM,CAAO,CACf,CACF,EAOa,EAAb,cAAsC,CAAS,CAC7C,YAAY,EAAiB,CAC3B,MAAM,CAAO,CACf,CACF,EAea,EAAb,cAAuC,CAAS,CAC9C,UACA,MAEA,YAAY,EAAiB,EAAoE,CAC/F,MAAM,EAAS,CAAE,MAAO,EAAQ,KAAM,CAAC,EACvC,KAAK,UAAY,EAAQ,UACzB,KAAK,MAAQ,EAAQ,KACvB,CACF,EAKA,SAAgB,EAAmB,EAA0B,EAA4B,CACvF,EAAS,IAAI,EAAM,UAAU,wBAAwB,EAAM,MAAM,IAAK,EAAM,KAAK,EAEjF,EAAQ,cACN,IAAI,YAAY,YAAa,CAC3B,QAAS,GACT,SAAU,GACV,OAAQ,CACV,CAAC,CACH,CACF,CAKA,IAAa,EAAb,cAAqC,CAAS,CAAC,EAElC,EAAa,CACxB,gBAAkB,GAAwB,WAAW,EAAI,qDACzD,kCAAoC,GAClC,+BAA+B,EAAI,8BACrC,kBAAmB,+BACnB,kBAAmB,EAAa,IAA0B,kCAAkC,EAAI,aAAa,IAC7G,oBAAqB,EAAa,IAAwB,yCAAyC,EAAI,QAAQ,EAAI,GACnH,sBAAwB,GACtB,kCAAkC,EAAQ,oCAC5C,kBAAoB,GAA4B,uBAAuB,IACvE,sBAAuB,wDACvB,mBAAoB,gFACpB,kBAAmB,EAAa,IAA6B,0BAA0B,EAAI,MAAM,EAAO,KAAK;CAAI,GACnH,EAYA,SAAgB,EAAU,EAAoB,EAAoC,CAChF,GAAI,CAAC,EAAW,MAAM,IAAI,EAAiB,EAAW,kBAAkB,CAAO,CAAC,CAClF"}
@@ -1,2 +1,2 @@
1
- const e=require("../_dev.cjs"),t=require("../errors.cjs"),n=require("../runtime.cjs");require("@vielzeug/ripple");var r=new WeakMap,i=i=>{let a=i.el??n.getHost();if(!a.constructor.formAssociated)throw new t.OreApiError(t.ORE_ERRORS.defineFieldRequiresFormAssociated(a.localName));if(r.has(a))throw new t.OreApiError(`useField() was already called on <${a.localName}>. Call it only once per component.`);let o=a.attachInternals();r.set(a,o),n.onCleanup(()=>r.delete(a));let s=i.toFormValue??(e=>e==null?i.emptyStringForNull?``:null:e instanceof File||e instanceof FormData?e:String(e));n.watchEffect(()=>{o.setFormValue(s(i.value.value))});let c=i.disabled;if(c)if(!(`states`in o))e.warn(`useField(): ElementInternals.states (CustomStateSet) is not available in this environment — disabled state tracking skipped.`);else{let e=o.states;n.watchEffect(()=>{c.value?e.add(`disabled`):e.delete(`disabled`)})}return{checkValidity:()=>o.checkValidity(),internals:o,reportValidity:()=>o.reportValidity(),setCustomValidity:e=>e?o.setValidity({customError:!0},e):o.setValidity({}),setValidity:o.setValidity.bind(o)}};exports.useField=i;
1
+ const e=require("../_dev.cjs"),t=require("../errors.cjs"),n=require("../runtime.cjs");require("@vielzeug/ripple");var r=new WeakMap,i=i=>{let a=i.el??n.getHost();if(!a.constructor.formAssociated)throw new t.OreApiError(t.ORE_ERRORS.defineFieldRequiresFormAssociated(a.localName));if(r.has(a))throw new t.OreApiError(`useField() was already called on <${a.localName}>. Call it only once per component.`);let o=a.attachInternals();r.set(a,o),n.onCleanup(()=>r.delete(a));let s=i.toFormValue??(e=>e==null?i.emptyStringForNull?``:null:e instanceof File||e instanceof FormData?e:String(e));n.watchEffect(()=>{o.setFormValue(s(i.value.value))});let c=i.disabled;if(c)if(!(`states`in o))e.warn(`useField(): ElementInternals.states (CustomStateSet) is not available in this environment — disabled state tracking skipped.`);else{let e=o.states;n.watchEffect(()=>{c.value?e.add(`disabled`):e.delete(`disabled`)})}return i.validity&&n.watchEffect(()=>{let t=i.validity?.value??{},n=Object.values(t).some(Boolean),r=i.validationMessage?.value??``;if(n&&!r){e.warn("useField(): `validity` has a truthy flag but `validationMessage` is empty — internals.setValidity() requires a non-empty message whenever any flag is true. Falling back to a generic message; pass `validationMessage` to customize it."),o.setValidity(t,`Invalid value.`);return}o.setValidity(t,r)}),i.onReset&&n.onFormReset(i.onReset),{checkValidity:()=>o.checkValidity(),internals:o,reportValidity:()=>o.reportValidity(),setCustomValidity:e=>e?o.setValidity({customError:!0},e):o.setValidity({}),setValidity:o.setValidity.bind(o)}};exports.useField=i;
2
2
  //# sourceMappingURL=field.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"field.cjs","names":[],"sources":["../../src/forms/field.ts"],"sourcesContent":["import { type Readable, type Signal } from '@vielzeug/ripple';\n\nimport { warn } from '../_dev';\nimport { OreApiError, ORE_ERRORS } from '../errors';\nimport { getHost, onCleanup, watchEffect } from '../runtime';\n\n/** @internal */\nconst internalsRegistry = new WeakMap<HTMLElement, ElementInternals>();\n\nexport type FormFieldOptions<T = unknown> = {\n disabled?: Readable<boolean>;\n /**\n * The host element to attach `ElementInternals` to.\n * Defaults to the element currently being set up via `getHost()`.\n * Pass this explicitly when calling `useField` from a composable that is\n * not called directly during `setup()` (e.g. a helper factory function).\n */\n el?: HTMLElement;\n /**\n * When `true`, a `null` or `undefined` value is submitted as an empty string\n * (`''`) instead of `null`. This keeps the field's key present in `FormData`\n * even when the value is absent — useful when the server expects the field to\n * always be included.\n *\n * @default false\n */\n emptyStringForNull?: boolean;\n toFormValue?: (value: T) => File | FormData | string | null;\n value: Signal<T> | Readable<T>;\n};\n\nexport type FormFieldHandle = {\n checkValidity: () => boolean;\n readonly internals: ElementInternals;\n reportValidity: () => boolean;\n setCustomValidity: (message: string) => void;\n setValidity: ElementInternals['setValidity'];\n};\n\nexport const useField = <T = unknown>(options: FormFieldOptions<T>): FormFieldHandle => {\n const host = options.el ?? getHost();\n const ctor = host.constructor as typeof HTMLElement & { formAssociated?: boolean };\n\n if (!ctor.formAssociated) {\n throw new OreApiError(ORE_ERRORS.defineFieldRequiresFormAssociated(host.localName));\n }\n\n if (internalsRegistry.has(host)) {\n throw new OreApiError(`useField() was already called on <${host.localName}>. Call it only once per component.`);\n }\n\n const internals = host.attachInternals();\n\n internalsRegistry.set(host, internals);\n onCleanup(() => internalsRegistry.delete(host));\n\n const toFormValue =\n options.toFormValue ??\n ((v: T): File | FormData | string | null => {\n if (v == null) return options.emptyStringForNull ? '' : null;\n\n if (v instanceof File || v instanceof FormData) return v;\n\n return String(v);\n });\n\n watchEffect(() => {\n internals.setFormValue(toFormValue(options.value.value));\n });\n\n const disabled = options.disabled;\n\n if (disabled) {\n if (!('states' in internals)) {\n warn(\n 'useField(): ElementInternals.states (CustomStateSet) is not available in this environment — disabled state tracking skipped.',\n );\n } else {\n const states = internals.states as CustomStateSet;\n\n watchEffect(() => {\n if (disabled.value) states.add('disabled');\n else states.delete('disabled');\n });\n }\n }\n\n const checkValidity = () => internals.checkValidity();\n const reportValidity = () => internals.reportValidity();\n const setCustomValidity = (message: string) =>\n message ? internals.setValidity({ customError: true }, message) : internals.setValidity({});\n\n return {\n checkValidity,\n internals,\n reportValidity,\n setCustomValidity,\n setValidity: internals.setValidity.bind(internals),\n };\n};\n"],"mappings":"kHAOA,IAAM,EAAoB,IAAI,QAgCjB,EAAyB,GAAkD,CACtF,IAAM,EAAO,EAAQ,IAAM,EAAA,QAAQ,EAGnC,GAAI,CAFS,EAAK,YAER,eACR,MAAM,IAAI,EAAA,YAAY,EAAA,WAAW,kCAAkC,EAAK,SAAS,CAAC,EAGpF,GAAI,EAAkB,IAAI,CAAI,EAC5B,MAAM,IAAI,EAAA,YAAY,qCAAqC,EAAK,UAAU,oCAAoC,EAGhH,IAAM,EAAY,EAAK,gBAAgB,EAEvC,EAAkB,IAAI,EAAM,CAAS,EACrC,EAAA,cAAgB,EAAkB,OAAO,CAAI,CAAC,EAE9C,IAAM,EACJ,EAAQ,cACN,GACI,GAAK,KAAa,EAAQ,mBAAqB,GAAK,KAEpD,aAAa,MAAQ,aAAa,SAAiB,EAEhD,OAAO,CAAC,GAGnB,EAAA,gBAAkB,CAChB,EAAU,aAAa,EAAY,EAAQ,MAAM,KAAK,CAAC,CACzD,CAAC,EAED,IAAM,EAAW,EAAQ,SAEzB,GAAI,EACF,GAAI,EAAE,WAAY,GAChB,EAAA,KACE,8HACF,MACK,CACL,IAAM,EAAS,EAAU,OAEzB,EAAA,gBAAkB,CACZ,EAAS,MAAO,EAAO,IAAI,UAAU,EACpC,EAAO,OAAO,UAAU,CAC/B,CAAC,CACH,CAQF,MAAO,CACL,kBAN0B,EAAU,cAAc,EAOlD,YACA,mBAP2B,EAAU,eAAe,EAQpD,kBAPyB,GACzB,EAAU,EAAU,YAAY,CAAE,YAAa,EAAK,EAAG,CAAO,EAAI,EAAU,YAAY,CAAC,CAAC,EAO1F,YAAa,EAAU,YAAY,KAAK,CAAS,CACnD,CACF"}
1
+ {"version":3,"file":"field.cjs","names":[],"sources":["../../src/forms/field.ts"],"sourcesContent":["import { type Readable, type Signal } from '@vielzeug/ripple';\n\nimport { warn } from '../_dev';\nimport { OreApiError, ORE_ERRORS } from '../errors';\nimport { getHost, onCleanup, onFormReset, watchEffect } from '../runtime';\n\n/** @internal */\nconst internalsRegistry = new WeakMap<HTMLElement, ElementInternals>();\n\nexport type FormFieldOptions<T = unknown> = {\n disabled?: Readable<boolean>;\n /**\n * The host element to attach `ElementInternals` to.\n * Defaults to the element currently being set up via `getHost()`.\n * Pass this explicitly when calling `useField` from a composable that is\n * not called directly during `setup()` (e.g. a helper factory function).\n */\n el?: HTMLElement;\n /**\n * When `true`, a `null` or `undefined` value is submitted as an empty string\n * (`''`) instead of `null`. This keeps the field's key present in `FormData`\n * even when the value is absent — useful when the server expects the field to\n * always be included.\n *\n * @default false\n */\n emptyStringForNull?: boolean;\n /**\n * Called when the ancestor `<form>` is reset (see `onFormReset`). Use to restore\n * whatever local state backs `value` — `useField` itself owns no field state to reset.\n */\n onReset?: () => void;\n toFormValue?: (value: T) => File | FormData | string | null;\n /**\n * Recomputed reactively and passed straight to `internals.setValidity()` — `null`\n * (or omitting `validity` entirely) means always valid. Pair with `validationMessage`.\n *\n * @example\n * ```ts\n * validity: computed(() => (required.value && isBlank(value.value)) ? { valueMissing: true } : null),\n * validationMessage: computed(() => (required.value && isBlank(value.value)) ? 'Required.' : ''),\n * ```\n */\n validationMessage?: Readable<string>;\n validity?: Readable<ValidityStateFlags | null>;\n value: Signal<T> | Readable<T>;\n};\n\nexport type FormFieldHandle = {\n checkValidity: () => boolean;\n readonly internals: ElementInternals;\n reportValidity: () => boolean;\n setCustomValidity: (message: string) => void;\n setValidity: ElementInternals['setValidity'];\n};\n\nexport const useField = <T = unknown>(options: FormFieldOptions<T>): FormFieldHandle => {\n const host = options.el ?? getHost();\n const ctor = host.constructor as typeof HTMLElement & { formAssociated?: boolean };\n\n if (!ctor.formAssociated) {\n throw new OreApiError(ORE_ERRORS.defineFieldRequiresFormAssociated(host.localName));\n }\n\n if (internalsRegistry.has(host)) {\n throw new OreApiError(`useField() was already called on <${host.localName}>. Call it only once per component.`);\n }\n\n const internals = host.attachInternals();\n\n internalsRegistry.set(host, internals);\n onCleanup(() => internalsRegistry.delete(host));\n\n const toFormValue =\n options.toFormValue ??\n ((v: T): File | FormData | string | null => {\n if (v == null) return options.emptyStringForNull ? '' : null;\n\n if (v instanceof File || v instanceof FormData) return v;\n\n return String(v);\n });\n\n watchEffect(() => {\n internals.setFormValue(toFormValue(options.value.value));\n });\n\n const disabled = options.disabled;\n\n if (disabled) {\n if (!('states' in internals)) {\n warn(\n 'useField(): ElementInternals.states (CustomStateSet) is not available in this environment — disabled state tracking skipped.',\n );\n } else {\n const states = internals.states as CustomStateSet;\n\n watchEffect(() => {\n if (disabled.value) states.add('disabled');\n else states.delete('disabled');\n });\n }\n }\n\n if (options.validity) {\n watchEffect(() => {\n const flags = options.validity?.value ?? {};\n // Per spec, ElementInternals.setValidity() throws if any flag is true and message is\n // empty — a caller-supplied `validity` with no matching `validationMessage` would crash\n // this effect in a real browser. Fail safe with a generic message instead of propagating\n // that crash, and say so loudly in dev so the real fix (pass validationMessage) gets made.\n const hasFlag = Object.values(flags).some(Boolean);\n const message = options.validationMessage?.value ?? '';\n\n if (hasFlag && !message) {\n warn(\n 'useField(): `validity` has a truthy flag but `validationMessage` is empty — internals.setValidity() ' +\n 'requires a non-empty message whenever any flag is true. Falling back to a generic message; pass ' +\n '`validationMessage` to customize it.',\n );\n internals.setValidity(flags, 'Invalid value.');\n\n return;\n }\n\n internals.setValidity(flags, message);\n });\n }\n\n if (options.onReset) onFormReset(options.onReset);\n\n const checkValidity = () => internals.checkValidity();\n const reportValidity = () => internals.reportValidity();\n const setCustomValidity = (message: string) =>\n message ? internals.setValidity({ customError: true }, message) : internals.setValidity({});\n\n return {\n checkValidity,\n internals,\n reportValidity,\n setCustomValidity,\n setValidity: internals.setValidity.bind(internals),\n };\n};\n"],"mappings":"kHAOA,IAAM,EAAoB,IAAI,QAiDjB,EAAyB,GAAkD,CACtF,IAAM,EAAO,EAAQ,IAAM,EAAA,QAAQ,EAGnC,GAAI,CAFS,EAAK,YAER,eACR,MAAM,IAAI,EAAA,YAAY,EAAA,WAAW,kCAAkC,EAAK,SAAS,CAAC,EAGpF,GAAI,EAAkB,IAAI,CAAI,EAC5B,MAAM,IAAI,EAAA,YAAY,qCAAqC,EAAK,UAAU,oCAAoC,EAGhH,IAAM,EAAY,EAAK,gBAAgB,EAEvC,EAAkB,IAAI,EAAM,CAAS,EACrC,EAAA,cAAgB,EAAkB,OAAO,CAAI,CAAC,EAE9C,IAAM,EACJ,EAAQ,cACN,GACI,GAAK,KAAa,EAAQ,mBAAqB,GAAK,KAEpD,aAAa,MAAQ,aAAa,SAAiB,EAEhD,OAAO,CAAC,GAGnB,EAAA,gBAAkB,CAChB,EAAU,aAAa,EAAY,EAAQ,MAAM,KAAK,CAAC,CACzD,CAAC,EAED,IAAM,EAAW,EAAQ,SAEzB,GAAI,EACF,GAAI,EAAE,WAAY,GAChB,EAAA,KACE,8HACF,MACK,CACL,IAAM,EAAS,EAAU,OAEzB,EAAA,gBAAkB,CACZ,EAAS,MAAO,EAAO,IAAI,UAAU,EACpC,EAAO,OAAO,UAAU,CAC/B,CAAC,CACH,CAmCF,OAhCI,EAAQ,UACV,EAAA,gBAAkB,CAChB,IAAM,EAAQ,EAAQ,UAAU,OAAS,CAAC,EAKpC,EAAU,OAAO,OAAO,CAAK,CAAC,CAAC,KAAK,OAAO,EAC3C,EAAU,EAAQ,mBAAmB,OAAS,GAEpD,GAAI,GAAW,CAAC,EAAS,CACvB,EAAA,KACE,0OAGF,EACA,EAAU,YAAY,EAAO,gBAAgB,EAE7C,MACF,CAEA,EAAU,YAAY,EAAO,CAAO,CACtC,CAAC,EAGC,EAAQ,SAAS,EAAA,YAAY,EAAQ,OAAO,EAOzC,CACL,kBAN0B,EAAU,cAAc,EAOlD,YACA,mBAP2B,EAAU,eAAe,EAQpD,kBAPyB,GACzB,EAAU,EAAU,YAAY,CAAE,YAAa,EAAK,EAAG,CAAO,EAAI,EAAU,YAAY,CAAC,CAAC,EAO1F,YAAa,EAAU,YAAY,KAAK,CAAS,CACnD,CACF"}
@@ -17,7 +17,24 @@ export type FormFieldOptions<T = unknown> = {
17
17
  * @default false
18
18
  */
19
19
  emptyStringForNull?: boolean;
20
+ /**
21
+ * Called when the ancestor `<form>` is reset (see `onFormReset`). Use to restore
22
+ * whatever local state backs `value` — `useField` itself owns no field state to reset.
23
+ */
24
+ onReset?: () => void;
20
25
  toFormValue?: (value: T) => File | FormData | string | null;
26
+ /**
27
+ * Recomputed reactively and passed straight to `internals.setValidity()` — `null`
28
+ * (or omitting `validity` entirely) means always valid. Pair with `validationMessage`.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * validity: computed(() => (required.value && isBlank(value.value)) ? { valueMissing: true } : null),
33
+ * validationMessage: computed(() => (required.value && isBlank(value.value)) ? 'Required.' : ''),
34
+ * ```
35
+ */
36
+ validationMessage?: Readable<string>;
37
+ validity?: Readable<ValidityStateFlags | null>;
21
38
  value: Signal<T> | Readable<T>;
22
39
  };
23
40
  export type FormFieldHandle = {
@@ -1 +1 @@
1
- {"version":3,"file":"field.d.ts","sourceRoot":"","sources":["../../src/forms/field.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAE,KAAK,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAS9D,MAAM,MAAM,gBAAgB,CAAC,CAAC,GAAG,OAAO,IAAI;IAC1C,QAA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AAG,QAAQ,GAAG,MAAM,GAAG,IAAI,CAAC;IAC5D;;;;;;;;;OASG;IACH,iBAAiB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,QAAQ,CAAC,EAAE,QAAQ,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;IAC/C,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,aAAa,EAAE,MAAM,OAAO,CAAC;IAC7B,QAAQ,CAAC,SAAS,EAAE,gBAAgB,CAAC;IACrC,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,iBAAiB,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7C,WAAW,EAAE,gBAAgB,CAAC,aAAa,CAAC,CAAC;CAC9C,CAAC;AAEF,eAAO,MAAM,QAAQ,GAAI,CAAC,GAAG,OAAO,EAAE,SAAS,gBAAgB,CAAC,CAAC,CAAC,KAAG,eAuFpE,CAAC"}
@@ -1,2 +1,2 @@
1
- import{warn as e}from"../_dev.js";import{ORE_ERRORS as t,OreApiError as n}from"../errors.js";import{getHost as r,onCleanup as i,watchEffect as a}from"../runtime.js";import"@vielzeug/ripple";var o=new WeakMap,s=s=>{let c=s.el??r();if(!c.constructor.formAssociated)throw new n(t.defineFieldRequiresFormAssociated(c.localName));if(o.has(c))throw new n(`useField() was already called on <${c.localName}>. Call it only once per component.`);let l=c.attachInternals();o.set(c,l),i(()=>o.delete(c));let u=s.toFormValue??(e=>e==null?s.emptyStringForNull?``:null:e instanceof File||e instanceof FormData?e:String(e));a(()=>{l.setFormValue(u(s.value.value))});let d=s.disabled;if(d)if(!(`states`in l))e(`useField(): ElementInternals.states (CustomStateSet) is not available in this environment — disabled state tracking skipped.`);else{let e=l.states;a(()=>{d.value?e.add(`disabled`):e.delete(`disabled`)})}return{checkValidity:()=>l.checkValidity(),internals:l,reportValidity:()=>l.reportValidity(),setCustomValidity:e=>e?l.setValidity({customError:!0},e):l.setValidity({}),setValidity:l.setValidity.bind(l)}};export{s as useField};
1
+ import{warn as e}from"../_dev.js";import{ORE_ERRORS as t,OreApiError as n}from"../errors.js";import{getHost as r,onCleanup as i,onFormReset as a,watchEffect as o}from"../runtime.js";import"@vielzeug/ripple";var s=new WeakMap,c=c=>{let l=c.el??r();if(!l.constructor.formAssociated)throw new n(t.defineFieldRequiresFormAssociated(l.localName));if(s.has(l))throw new n(`useField() was already called on <${l.localName}>. Call it only once per component.`);let u=l.attachInternals();s.set(l,u),i(()=>s.delete(l));let d=c.toFormValue??(e=>e==null?c.emptyStringForNull?``:null:e instanceof File||e instanceof FormData?e:String(e));o(()=>{u.setFormValue(d(c.value.value))});let f=c.disabled;if(f)if(!(`states`in u))e(`useField(): ElementInternals.states (CustomStateSet) is not available in this environment — disabled state tracking skipped.`);else{let e=u.states;o(()=>{f.value?e.add(`disabled`):e.delete(`disabled`)})}return c.validity&&o(()=>{let t=c.validity?.value??{},n=Object.values(t).some(Boolean),r=c.validationMessage?.value??``;if(n&&!r){e("useField(): `validity` has a truthy flag but `validationMessage` is empty — internals.setValidity() requires a non-empty message whenever any flag is true. Falling back to a generic message; pass `validationMessage` to customize it."),u.setValidity(t,`Invalid value.`);return}u.setValidity(t,r)}),c.onReset&&a(c.onReset),{checkValidity:()=>u.checkValidity(),internals:u,reportValidity:()=>u.reportValidity(),setCustomValidity:e=>e?u.setValidity({customError:!0},e):u.setValidity({}),setValidity:u.setValidity.bind(u)}};export{c as useField};
2
2
  //# sourceMappingURL=field.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"field.js","names":[],"sources":["../../src/forms/field.ts"],"sourcesContent":["import { type Readable, type Signal } from '@vielzeug/ripple';\n\nimport { warn } from '../_dev';\nimport { OreApiError, ORE_ERRORS } from '../errors';\nimport { getHost, onCleanup, watchEffect } from '../runtime';\n\n/** @internal */\nconst internalsRegistry = new WeakMap<HTMLElement, ElementInternals>();\n\nexport type FormFieldOptions<T = unknown> = {\n disabled?: Readable<boolean>;\n /**\n * The host element to attach `ElementInternals` to.\n * Defaults to the element currently being set up via `getHost()`.\n * Pass this explicitly when calling `useField` from a composable that is\n * not called directly during `setup()` (e.g. a helper factory function).\n */\n el?: HTMLElement;\n /**\n * When `true`, a `null` or `undefined` value is submitted as an empty string\n * (`''`) instead of `null`. This keeps the field's key present in `FormData`\n * even when the value is absent — useful when the server expects the field to\n * always be included.\n *\n * @default false\n */\n emptyStringForNull?: boolean;\n toFormValue?: (value: T) => File | FormData | string | null;\n value: Signal<T> | Readable<T>;\n};\n\nexport type FormFieldHandle = {\n checkValidity: () => boolean;\n readonly internals: ElementInternals;\n reportValidity: () => boolean;\n setCustomValidity: (message: string) => void;\n setValidity: ElementInternals['setValidity'];\n};\n\nexport const useField = <T = unknown>(options: FormFieldOptions<T>): FormFieldHandle => {\n const host = options.el ?? getHost();\n const ctor = host.constructor as typeof HTMLElement & { formAssociated?: boolean };\n\n if (!ctor.formAssociated) {\n throw new OreApiError(ORE_ERRORS.defineFieldRequiresFormAssociated(host.localName));\n }\n\n if (internalsRegistry.has(host)) {\n throw new OreApiError(`useField() was already called on <${host.localName}>. Call it only once per component.`);\n }\n\n const internals = host.attachInternals();\n\n internalsRegistry.set(host, internals);\n onCleanup(() => internalsRegistry.delete(host));\n\n const toFormValue =\n options.toFormValue ??\n ((v: T): File | FormData | string | null => {\n if (v == null) return options.emptyStringForNull ? '' : null;\n\n if (v instanceof File || v instanceof FormData) return v;\n\n return String(v);\n });\n\n watchEffect(() => {\n internals.setFormValue(toFormValue(options.value.value));\n });\n\n const disabled = options.disabled;\n\n if (disabled) {\n if (!('states' in internals)) {\n warn(\n 'useField(): ElementInternals.states (CustomStateSet) is not available in this environment — disabled state tracking skipped.',\n );\n } else {\n const states = internals.states as CustomStateSet;\n\n watchEffect(() => {\n if (disabled.value) states.add('disabled');\n else states.delete('disabled');\n });\n }\n }\n\n const checkValidity = () => internals.checkValidity();\n const reportValidity = () => internals.reportValidity();\n const setCustomValidity = (message: string) =>\n message ? internals.setValidity({ customError: true }, message) : internals.setValidity({});\n\n return {\n checkValidity,\n internals,\n reportValidity,\n setCustomValidity,\n setValidity: internals.setValidity.bind(internals),\n };\n};\n"],"mappings":"8LAOA,IAAM,EAAoB,IAAI,QAgCjB,EAAyB,GAAkD,CACtF,IAAM,EAAO,EAAQ,IAAM,EAAQ,EAGnC,GAAI,CAFS,EAAK,YAER,eACR,MAAM,IAAI,EAAY,EAAW,kCAAkC,EAAK,SAAS,CAAC,EAGpF,GAAI,EAAkB,IAAI,CAAI,EAC5B,MAAM,IAAI,EAAY,qCAAqC,EAAK,UAAU,oCAAoC,EAGhH,IAAM,EAAY,EAAK,gBAAgB,EAEvC,EAAkB,IAAI,EAAM,CAAS,EACrC,MAAgB,EAAkB,OAAO,CAAI,CAAC,EAE9C,IAAM,EACJ,EAAQ,cACN,GACI,GAAK,KAAa,EAAQ,mBAAqB,GAAK,KAEpD,aAAa,MAAQ,aAAa,SAAiB,EAEhD,OAAO,CAAC,GAGnB,MAAkB,CAChB,EAAU,aAAa,EAAY,EAAQ,MAAM,KAAK,CAAC,CACzD,CAAC,EAED,IAAM,EAAW,EAAQ,SAEzB,GAAI,EACF,GAAI,EAAE,WAAY,GAChB,EACE,8HACF,MACK,CACL,IAAM,EAAS,EAAU,OAEzB,MAAkB,CACZ,EAAS,MAAO,EAAO,IAAI,UAAU,EACpC,EAAO,OAAO,UAAU,CAC/B,CAAC,CACH,CAQF,MAAO,CACL,kBAN0B,EAAU,cAAc,EAOlD,YACA,mBAP2B,EAAU,eAAe,EAQpD,kBAPyB,GACzB,EAAU,EAAU,YAAY,CAAE,YAAa,EAAK,EAAG,CAAO,EAAI,EAAU,YAAY,CAAC,CAAC,EAO1F,YAAa,EAAU,YAAY,KAAK,CAAS,CACnD,CACF"}
1
+ {"version":3,"file":"field.js","names":[],"sources":["../../src/forms/field.ts"],"sourcesContent":["import { type Readable, type Signal } from '@vielzeug/ripple';\n\nimport { warn } from '../_dev';\nimport { OreApiError, ORE_ERRORS } from '../errors';\nimport { getHost, onCleanup, onFormReset, watchEffect } from '../runtime';\n\n/** @internal */\nconst internalsRegistry = new WeakMap<HTMLElement, ElementInternals>();\n\nexport type FormFieldOptions<T = unknown> = {\n disabled?: Readable<boolean>;\n /**\n * The host element to attach `ElementInternals` to.\n * Defaults to the element currently being set up via `getHost()`.\n * Pass this explicitly when calling `useField` from a composable that is\n * not called directly during `setup()` (e.g. a helper factory function).\n */\n el?: HTMLElement;\n /**\n * When `true`, a `null` or `undefined` value is submitted as an empty string\n * (`''`) instead of `null`. This keeps the field's key present in `FormData`\n * even when the value is absent — useful when the server expects the field to\n * always be included.\n *\n * @default false\n */\n emptyStringForNull?: boolean;\n /**\n * Called when the ancestor `<form>` is reset (see `onFormReset`). Use to restore\n * whatever local state backs `value` — `useField` itself owns no field state to reset.\n */\n onReset?: () => void;\n toFormValue?: (value: T) => File | FormData | string | null;\n /**\n * Recomputed reactively and passed straight to `internals.setValidity()` — `null`\n * (or omitting `validity` entirely) means always valid. Pair with `validationMessage`.\n *\n * @example\n * ```ts\n * validity: computed(() => (required.value && isBlank(value.value)) ? { valueMissing: true } : null),\n * validationMessage: computed(() => (required.value && isBlank(value.value)) ? 'Required.' : ''),\n * ```\n */\n validationMessage?: Readable<string>;\n validity?: Readable<ValidityStateFlags | null>;\n value: Signal<T> | Readable<T>;\n};\n\nexport type FormFieldHandle = {\n checkValidity: () => boolean;\n readonly internals: ElementInternals;\n reportValidity: () => boolean;\n setCustomValidity: (message: string) => void;\n setValidity: ElementInternals['setValidity'];\n};\n\nexport const useField = <T = unknown>(options: FormFieldOptions<T>): FormFieldHandle => {\n const host = options.el ?? getHost();\n const ctor = host.constructor as typeof HTMLElement & { formAssociated?: boolean };\n\n if (!ctor.formAssociated) {\n throw new OreApiError(ORE_ERRORS.defineFieldRequiresFormAssociated(host.localName));\n }\n\n if (internalsRegistry.has(host)) {\n throw new OreApiError(`useField() was already called on <${host.localName}>. Call it only once per component.`);\n }\n\n const internals = host.attachInternals();\n\n internalsRegistry.set(host, internals);\n onCleanup(() => internalsRegistry.delete(host));\n\n const toFormValue =\n options.toFormValue ??\n ((v: T): File | FormData | string | null => {\n if (v == null) return options.emptyStringForNull ? '' : null;\n\n if (v instanceof File || v instanceof FormData) return v;\n\n return String(v);\n });\n\n watchEffect(() => {\n internals.setFormValue(toFormValue(options.value.value));\n });\n\n const disabled = options.disabled;\n\n if (disabled) {\n if (!('states' in internals)) {\n warn(\n 'useField(): ElementInternals.states (CustomStateSet) is not available in this environment — disabled state tracking skipped.',\n );\n } else {\n const states = internals.states as CustomStateSet;\n\n watchEffect(() => {\n if (disabled.value) states.add('disabled');\n else states.delete('disabled');\n });\n }\n }\n\n if (options.validity) {\n watchEffect(() => {\n const flags = options.validity?.value ?? {};\n // Per spec, ElementInternals.setValidity() throws if any flag is true and message is\n // empty — a caller-supplied `validity` with no matching `validationMessage` would crash\n // this effect in a real browser. Fail safe with a generic message instead of propagating\n // that crash, and say so loudly in dev so the real fix (pass validationMessage) gets made.\n const hasFlag = Object.values(flags).some(Boolean);\n const message = options.validationMessage?.value ?? '';\n\n if (hasFlag && !message) {\n warn(\n 'useField(): `validity` has a truthy flag but `validationMessage` is empty — internals.setValidity() ' +\n 'requires a non-empty message whenever any flag is true. Falling back to a generic message; pass ' +\n '`validationMessage` to customize it.',\n );\n internals.setValidity(flags, 'Invalid value.');\n\n return;\n }\n\n internals.setValidity(flags, message);\n });\n }\n\n if (options.onReset) onFormReset(options.onReset);\n\n const checkValidity = () => internals.checkValidity();\n const reportValidity = () => internals.reportValidity();\n const setCustomValidity = (message: string) =>\n message ? internals.setValidity({ customError: true }, message) : internals.setValidity({});\n\n return {\n checkValidity,\n internals,\n reportValidity,\n setCustomValidity,\n setValidity: internals.setValidity.bind(internals),\n };\n};\n"],"mappings":"+MAOA,IAAM,EAAoB,IAAI,QAiDjB,EAAyB,GAAkD,CACtF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YAAY,KAAK,CAAS,CACnD,CACF"}
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./types/bindings.cjs"),n=require("./runtime.cjs"),r=require("./context.cjs"),i=require("./props.cjs"),a=require("./utils/css.cjs"),o=require("./define.cjs"),s=require("./slots.cjs"),c=require("./host-bind.cjs"),l=require("./aria.cjs"),u=require("./utils/emit.cjs"),d=require("./template/instantiator.cjs");require("./template.cjs");const f=require("./utils/id.cjs");exports.OreApiError=e.OreApiError,exports.OreError=e.OreError,exports.OreInternalError=e.OreInternalError,exports.OreLifecycleError=e.OreLifecycleError,exports.OreTimeoutError=e.OreTimeoutError,exports.aria=l.aria,exports.bind=c.bind,exports.createContext=r.createContext,exports.createId=f.createId,exports.createStableId=f.createStableId,exports.css=a.css,exports.define=o.define,exports.getHost=n.getHost,exports.html=d.html,exports.inject=r.inject,exports.injectStrict=r.injectStrict,exports.onCleanup=n.onCleanup,exports.onElement=n.onElement,exports.onEvent=n.onEvent,exports.onMounted=n.onMounted,exports.prop=i.prop,exports.provide=r.provide,exports.ref=t.ref,exports.resetIdCounter=f.resetIdCounter,exports.useEmit=u.useEmit,exports.useSlots=s.useSlots,exports.watchEffect=n.watchEffect;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./types/bindings.cjs"),n=require("./runtime.cjs"),r=require("./context.cjs"),i=require("./props.cjs"),a=require("./utils/css.cjs"),o=require("./define.cjs"),s=require("./slots.cjs"),c=require("./host-bind.cjs"),l=require("./aria.cjs"),u=require("./utils/emit.cjs"),d=require("./template/instantiator.cjs");require("./template.cjs");const f=require("./utils/id.cjs");exports.OreApiError=e.OreApiError,exports.OreError=e.OreError,exports.OreInternalError=e.OreInternalError,exports.OreLifecycleError=e.OreLifecycleError,exports.OreTimeoutError=e.OreTimeoutError,exports.aria=l.aria,exports.bind=c.bind,exports.createContext=r.createContext,exports.createId=f.createId,exports.createStableId=f.createStableId,exports.css=a.css,exports.define=o.define,exports.getHost=n.getHost,exports.html=d.html,exports.inject=r.inject,exports.injectStrict=r.injectStrict,exports.onCleanup=n.onCleanup,exports.onElement=n.onElement,exports.onEvent=n.onEvent,exports.onFormReset=n.onFormReset,exports.onMounted=n.onMounted,exports.prop=i.prop,exports.provide=r.provide,exports.ref=t.ref,exports.resetIdCounter=f.resetIdCounter,exports.useEmit=u.useEmit,exports.useSlots=s.useSlots,exports.watchEffect=n.watchEffect;
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ export { createContext, inject, injectStrict, provide, type InjectionKey } from
6
6
  export { useSlots, type ComponentSlots } from './slots';
7
7
  export { aria, type AriaConfig } from './aria';
8
8
  export { bind, type BindOptions, type HostBindConfig, type HostBindFn, type HostBindingValue, type ReflectConfig, } from './host-bind';
9
- export { getHost, onCleanup, onElement, onEvent, onMounted, type OnMountedCallback, watchEffect } from './runtime';
9
+ export { getHost, onCleanup, onElement, onEvent, onFormReset, type OnFormResetCallback, onMounted, type OnMountedCallback, watchEffect, } from './runtime';
10
10
  export { useEmit, type EmitFn } from './utils/emit';
11
11
  export { html } from './template';
12
12
  export { css, type CSSResult } from './utils/css';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,QAAQ,EACR,KAAK,aAAa,EAClB,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,GAChB,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAE5E,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,EAAE,KAAK,Y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AM,EAAE,YAAY,EAAE,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5F,OAAO,EAAE,QAAQ,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAExD,OAAO,EAAE,IAAI,EAAE,KAAK,UAAU,EAAE,MAAM,QAAQ,CAAC;AAE/C,OAAO,EACL,IAAI,EACJ,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,UAAU,EACf,KAAK,gBAAgB,EACrB,KAAK,aAAa,GACnB,MAAM,aAAa,CAAC;AAGrB,OAAO,EACL,OAAO,EACP,SAAS,EACT,SAAS,EACT,OAAO,EACP,WAAW,EACX,KAAK,mBAAmB,EACxB,SAAS,EACT,KAAK,iBAAiB,EACtB,WAAW,GACZ,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAElC,OAAO,EAAE,GAAG,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEtE,OAAO,EAAE,GAAG,EAAE,KAAK,eAAe,EAAE,KAAK,UAAU,EAAE,KAAK,GAAG,EAAE,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{OreApiError as e,OreError as t,OreInternalError as n,OreLifecycleError as r,OreTimeoutError as i}from"./errors.js";import{ref as a}from"./types/bindings.js";import{getHost as o,onCleanup as s,onElement as c,onEvent as l,onMounted as u,watchEffect as d}from"./runtime.js";import{createContext as f,inject as p,injectStrict as m,provide as h}from"./context.js";import{prop as g}from"./props.js";import{css as _}from"./utils/css.js";import{define as v}from"./define.js";import{useSlots as y}from"./slots.js";import{bind as b}from"./host-bind.js";import{aria as x}from"./aria.js";import{useEmit as S}from"./utils/emit.js";import{html as C}from"./template/instantiator.js";import"./template.js";import{createId as w,createStableId as T,resetIdCounter as E}from"./utils/id.js";export{e as OreApiError,t as OreError,n as OreInternalError,r as OreLifecycleError,i as OreTimeoutError,x as aria,b as bind,f as createContext,w as createId,T as createStableId,_ as css,v as define,o as getHost,C as html,p as inject,m as injectStrict,s as onCleanup,c as onElement,l as onEvent,u as onMounted,g as prop,h as provide,a as ref,E as resetIdCounter,S as useEmit,y as useSlots,d as watchEffect};
1
+ import{OreApiError as e,OreError as t,OreInternalError as n,OreLifecycleError as r,OreTimeoutError as i}from"./errors.js";import{ref as a}from"./types/bindings.js";import{getHost as o,onCleanup as s,onElement as c,onEvent as l,onFormReset as u,onMounted as d,watchEffect as f}from"./runtime.js";import{createContext as p,inject as m,injectStrict as h,provide as g}from"./context.js";import{prop as _}from"./props.js";import{css as v}from"./utils/css.js";import{define as y}from"./define.js";import{useSlots as b}from"./slots.js";import{bind as x}from"./host-bind.js";import{aria as S}from"./aria.js";import{useEmit as C}from"./utils/emit.js";import{html as w}from"./template/instantiator.js";import"./template.js";import{createId as T,createStableId as E,resetIdCounter as D}from"./utils/id.js";export{e as OreApiError,t as OreError,n as OreInternalError,r as OreLifecycleError,i as OreTimeoutError,S as aria,x as bind,p as createContext,T as createId,E as createStableId,v as css,y as define,o as getHost,w as html,m as inject,h as injectStrict,s as onCleanup,c as onElement,l as onEvent,u as onFormReset,d as onMounted,_ as prop,g as provide,a as ref,D as resetIdCounter,C as useEmit,b as useSlots,f as watchEffect};