@hyperfixi/core 2.3.1 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/dom-processor.d.ts +8 -4
- package/dist/api/hyperscript-api.d.ts +5 -1
- package/dist/ast-utils/index.js +25320 -94
- package/dist/ast-utils/index.mjs +25320 -94
- package/dist/ast-utils/interchange/types.d.ts +7 -1
- package/dist/behaviors/index.js +54 -100
- package/dist/behaviors/index.mjs +54 -100
- package/dist/bundle-generator/index.js +19 -2
- package/dist/bundle-generator/index.mjs +19 -2
- package/dist/bundle-generator/parser-templates.d.ts +1 -1
- package/dist/bundle-generator/template-capabilities.d.ts +1 -1
- package/dist/chunks/bridge-C4d3blZX.js +2 -0
- package/dist/chunks/browser-modular-BwIRlrTM.js +2 -0
- package/dist/chunks/feature-eventsource-BpZvPy_K.js +2 -0
- package/dist/chunks/{feature-sockets-ClOH7vk7.js → feature-sockets-CrYvjZ4j.js} +2 -2
- package/dist/chunks/feature-webworker-BSYguEIW.js +2 -0
- package/dist/chunks/index-Beno_SBy.js +2 -0
- package/dist/commands/advanced/async.d.ts +6 -2
- package/dist/commands/advanced/js.d.ts +1 -1
- package/dist/commands/animation/start-view-transition.d.ts +24 -0
- package/dist/commands/async/fetch.d.ts +6 -1
- package/dist/commands/control-flow/repeat.d.ts +2 -0
- package/dist/commands/data/clear.d.ts +23 -0
- package/dist/commands/data/set.d.ts +6 -0
- package/dist/commands/dom/close.d.ts +19 -0
- package/dist/commands/dom/empty.d.ts +19 -0
- package/dist/commands/dom/open.d.ts +21 -0
- package/dist/commands/dom/reset.d.ts +19 -0
- package/dist/commands/dom/select.d.ts +19 -0
- package/dist/commands/dom/swap.d.ts +7 -4
- package/dist/commands/events/trigger.d.ts +1 -1
- package/dist/commands/execution/blur.d.ts +19 -0
- package/dist/commands/execution/call.d.ts +1 -2
- package/dist/commands/execution/focus.d.ts +19 -0
- package/dist/commands/helpers/element-resolution.d.ts +2 -2
- package/dist/commands/helpers/event-waiting.d.ts +1 -1
- package/dist/commands/helpers/numeric-target-parser.d.ts +7 -0
- package/dist/commands/index.d.ts +34 -2
- package/dist/commands/index.js +19352 -4845
- package/dist/commands/index.mjs +19320 -4846
- package/dist/commands/navigation/go.d.ts +3 -0
- package/dist/commands/navigation/scroll-to.d.ts +26 -0
- package/dist/commands/utility/beep.d.ts +2 -2
- package/dist/commands/utility/breakpoint.d.ts +19 -0
- package/dist/commands/utility/pick.d.ts +11 -2
- package/dist/compatibility/browser-bundle-modular.d.ts +2 -2
- package/dist/compatibility/browser-bundle-multilingual.d.ts +1 -1
- package/dist/compatibility/browser-bundle-semantic-complete.d.ts +3 -3
- package/dist/compatibility/browser-bundle.d.ts +13 -6
- package/dist/compatibility/browser-modular.d.ts +1 -3
- package/dist/core/expression-evaluator.d.ts +4 -4
- package/dist/core/expression-registry.d.ts +8 -0
- package/dist/expressions/bundles/common-expressions.d.ts +2 -2
- package/dist/expressions/bundles/core-expressions.d.ts +2 -2
- package/dist/expressions/bundles/full-expressions.d.ts +2 -2
- package/dist/expressions/bundles/index.d.ts +3 -3
- package/dist/expressions/collection/index.d.ts +35 -0
- package/dist/expressions/conversion/impl/index.d.ts +1 -1
- package/dist/expressions/index.d.ts +4 -3
- package/dist/expressions/index.js +1117 -1590
- package/dist/expressions/index.mjs +1113 -1586
- package/dist/expressions/logical/index.d.ts +2 -0
- package/dist/expressions/mathematical/index.d.ts +11 -0
- package/dist/expressions/shared/index.d.ts +1 -1
- package/dist/expressions/shared/number-utils.d.ts +1 -0
- package/dist/htmx/htmx-attribute-processor.d.ts +37 -1
- package/dist/htmx/htmx-translator.d.ts +2 -0
- package/dist/htmx/i18n-hooks.d.ts +15 -0
- package/dist/htmx/i18n-orchestrator.d.ts +15 -0
- package/dist/htmx/lang-resolver.d.ts +3 -0
- package/dist/htmx/sse.d.ts +60 -0
- package/dist/htmx/ws.d.ts +59 -0
- package/dist/hyperfixi-browser-classic-i18n.js +2 -0
- package/dist/hyperfixi-browser-minimal.js +1 -0
- package/dist/hyperfixi-browser-standard.js +2 -0
- package/dist/hyperfixi-browser.js +2 -0
- package/dist/hyperfixi-classic-i18n.js +1 -1
- package/dist/hyperfixi-hx-v4.js +1 -0
- package/dist/hyperfixi-hx.js +1 -1
- package/dist/hyperfixi-hybrid-complete.js +1 -1
- package/dist/hyperfixi-hybrid-hx.js +1 -0
- package/dist/hyperfixi-minimal.js +1 -1
- package/dist/hyperfixi-multilingual.js +1 -1
- package/dist/hyperfixi-standard.js +1 -1
- package/dist/hyperfixi.js +1 -1
- package/dist/hyperfixi.mjs +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +43591 -45060
- package/dist/index.min.js +1 -1
- package/dist/index.mjs +43588 -45061
- package/dist/lib/index.d.ts +2 -2
- package/dist/lib/morph-adapter.d.ts +0 -13
- package/dist/lib/swap-executor.d.ts +0 -10
- package/dist/lib/view-transitions.d.ts +1 -30
- package/dist/lokascript-browser-classic-i18n.js +1 -1
- package/dist/lokascript-browser-minimal.js +1 -1
- package/dist/lokascript-browser-standard.js +1 -1
- package/dist/lokascript-browser.js +1 -1
- package/dist/lokascript-hybrid-complete.js +1 -1
- package/dist/lokascript-hybrid-hx.js +1 -1
- package/dist/lokascript-multilingual.js +1 -1
- package/dist/lsp-metadata.d.ts +9 -4
- package/dist/lsp-metadata.js +187 -3
- package/dist/lsp-metadata.mjs +185 -4
- package/dist/metadata.d.ts +1 -1
- package/dist/metadata.js +3 -3
- package/dist/metadata.mjs +3 -3
- package/dist/multilingual/bridge.d.ts +1 -1
- package/dist/multilingual/index.js +79 -22
- package/dist/multilingual/index.mjs +79 -22
- package/dist/parser/command-parsers/animation-commands.d.ts +1 -0
- package/dist/parser/command-parsers/utility-commands.d.ts +1 -0
- package/dist/parser/extensions.d.ts +51 -0
- package/dist/parser/full-parser.js +1224 -899
- package/dist/parser/full-parser.mjs +1224 -899
- package/dist/parser/helpers/ast-helpers.d.ts +1 -0
- package/dist/parser/helpers/parsing-helpers.d.ts +4 -0
- package/dist/parser/parser-types.d.ts +8 -28
- package/dist/parser/parser.d.ts +3 -7
- package/dist/parser/pratt-parser.d.ts +0 -3
- package/dist/parser/runtime.d.ts +4 -0
- package/dist/parser/semantic-integration.d.ts +17 -0
- package/dist/parser/types.d.ts +7 -1
- package/dist/reference/index.js +91 -0
- package/dist/reference/index.mjs +91 -0
- package/dist/registry/index.js +12866 -5876
- package/dist/registry/index.mjs +12866 -5876
- package/dist/registry/universal-types.d.ts +2 -1
- package/dist/runtime/command-adapter.d.ts +23 -16
- package/dist/runtime/plugin.d.ts +14 -0
- package/dist/runtime/runtime-base.d.ts +32 -7
- package/dist/runtime/runtime-factory.d.ts +3 -3
- package/dist/runtime/runtime.d.ts +2 -2
- package/dist/test-setup.d.ts +1 -0
- package/dist/types/base-types.d.ts +3 -0
- package/dist/types/feature-types.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/package.json +26 -20
- package/vocab/htmx/ar.js +60 -0
- package/vocab/htmx/bn.js +49 -0
- package/vocab/htmx/de.js +60 -0
- package/vocab/htmx/en.js +21 -0
- package/vocab/htmx/es.js +60 -0
- package/vocab/htmx/fr.js +59 -0
- package/vocab/htmx/he.js +40 -0
- package/vocab/htmx/hi.js +60 -0
- package/vocab/htmx/id.js +57 -0
- package/vocab/htmx/it.js +58 -0
- package/vocab/htmx/ja.js +60 -0
- package/vocab/htmx/ko.js +60 -0
- package/vocab/htmx/ms.js +35 -0
- package/vocab/htmx/pl.js +60 -0
- package/vocab/htmx/pt.js +60 -0
- package/vocab/htmx/qu.js +60 -0
- package/vocab/htmx/ru.js +60 -0
- package/vocab/htmx/sw.js +59 -0
- package/vocab/htmx/th.js +49 -0
- package/vocab/htmx/tl.js +33 -0
- package/vocab/htmx/tr.js +60 -0
- package/vocab/htmx/uk.js +60 -0
- package/vocab/htmx/vi.js +51 -0
- package/vocab/htmx/zh.js +60 -0
- package/dist/bundles/test-minimal.d.ts +0 -3
- package/dist/bundles/test-standard.d.ts +0 -3
- package/dist/chunks/bridge-Clbh_xAj.js +0 -2
- package/dist/chunks/browser-modular-DIOxQqhV.js +0 -2
- package/dist/chunks/feature-eventsource-B5F2-H1r.js +0 -2
- package/dist/chunks/feature-webworker-3bAp0ac9.js +0 -2
- package/dist/chunks/index-DcxoRUBe.js +0 -2
- package/dist/compatibility/browser-bundle-minimal.d.ts +0 -8
- package/dist/compatibility/browser-bundle-standard.d.ts +0 -8
- package/dist/compatibility/hyperscript-tests/test-adapter.d.ts +0 -13
- package/dist/core/base-expression-evaluator.d.ts +0 -74
- package/dist/core/binary-expression-evaluator.d.ts +0 -7
- package/dist/core/call-expression-evaluator.d.ts +0 -7
- package/dist/core/configurable-expression-evaluator.d.ts +0 -5
- package/dist/core/lazy-expression-evaluator.d.ts +0 -22
- package/dist/core/parser.d.ts +0 -21
- package/dist/core/selector-evaluator.d.ts +0 -15
- package/dist/core/template-literal-evaluator.d.ts +0 -5
- package/dist/expressions/comparison/index.d.ts +0 -80
- package/dist/expressions/comparison/utils.d.ts +0 -2
- package/dist/expressions/conversion/impl/bridge.d.ts +0 -117
- package/dist/expressions/logical/impl/pattern-matching.d.ts +0 -58
- package/dist/expressions/positional/impl/bridge.d.ts +0 -95
- package/dist/expressions/property/index.d.ts +0 -55
- package/dist/expressions/references/impl/bridge.d.ts +0 -54
- package/dist/extensions/index.d.ts +0 -3
- package/dist/extensions/tailwind.d.ts +0 -22
- package/dist/mod.d.ts +0 -63
- package/dist/parser/expression-parser.d.ts +0 -6
- package/dist/runtime/runtime-experimental.d.ts +0 -18
- package/dist/scripts/code-generator.d.ts +0 -64
- package/dist/scripts/generate-missing-commands.d.ts +0 -4
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{v as e,z as t}from"./feature-sockets-CrYvjZ4j.js";function n(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const r=e.object({source:t.object({url:e.string().min(1),withCredentials:e.boolean().default(!1),headers:t.record(e.string(),e.string()).default({}),retry:e.object({enabled:e.boolean().default(!0),maxAttempts:e.number().default(5),delay:e.number().default(3e3),backoff:t.enum(["linear","exponential"]).default("exponential"),maxDelay:e.number().default(3e4)}).default({}),timeout:e.object({enabled:e.boolean().default(!0),duration:e.number().default(6e4)}).default({})}),eventHandlers:e.array(e.object({event:e.string().min(1),commands:e.array(e.any()).min(1),filter:e.string().optional(),options:t.object({throttle:e.number().optional(),debounce:e.number().optional()}).optional()})).default([]),messageProcessing:e.object({format:t.enum(["text","json","raw"]).default("text"),validation:t.object({enabled:e.boolean().default(!0),schema:e.any().optional()}).default({}),buffer:e.object({enabled:e.boolean().default(!0),maxSize:e.number().min(0).default(100),flushInterval:e.number().default(1e3)}).default({})}).default({}),context:e.object({variables:t.record(e.string(),e.any()).default({}),me:e.any().optional(),it:e.any().optional(),target:e.any().optional()}).default({}),options:e.object({enableAutoConnect:e.boolean().default(!0),enableMessageBuffer:e.boolean().default(!0),enableErrorHandling:e.boolean().default(!0),maxConnections:e.number().default(1),connectionTimeout:e.number().default(3e4)}).default({}),environment:t.enum(["frontend","backend","universal"]).default("frontend"),debug:e.boolean().default(!1)}),s=e.object({contextId:e.string(),timestamp:e.number(),category:e.literal("Frontend"),capabilities:e.array(e.string()),state:t.enum(["ready","connecting","connected","disconnecting","disconnected","error"]),connection:t.object({connect:e.any(),disconnect:e.any(),reconnect:e.any(),getState:e.any(),getConnectionInfo:e.any(),isConnected:e.any()}),events:e.object({addHandler:e.any(),removeHandler:e.any(),getHandlers:e.any(),emit:e.any()}),messages:e.object({getHistory:e.any(),getBuffer:e.any(),flushBuffer:e.any(),clearHistory:e.any(),subscribe:e.any(),unsubscribe:e.any()}),errors:e.object({handle:e.any(),getErrorHistory:e.any(),clearErrors:e.any(),setErrorHandler:e.any()})});class o{constructor(){this.name="eventsourceFeature",this.category="Frontend",this.description="Type-safe Server-Sent Events management feature with connection handling, message processing, and comprehensive error recovery",this.inputSchema=r,this.outputType="Context",this.evaluationHistory=[],this.connections=new Map,this.messageHistory=[],this.eventHandlers=new Map,this.messageBuffers=new Map,this.errorHistory=[],this.throttleTimers=new Map,this.debounceTimers=new Map,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["sse-connection","event-listening","background-processing"],dependencies:["eventsource-api","stream-processing","connection-management"],returnTypes:["Context"],examples:[{input:'{ source: { url: "/api/events" }, eventHandlers: [{ event: "message", commands: [{ name: "processUpdate" }] }] }',description:"Create Server-Sent Events connection for real-time updates",expectedOutput:"TypedEventSourceContext with SSE connection and message handling"},{input:'{ source: { url: "/api/notifications", retry: { maxAttempts: 10 } }, messageProcessing: { format: "json" } }',description:"SSE connection with automatic retry and JSON message processing",expectedOutput:"Event source context with robust reconnection and data parsing"},{input:'{ source: { url: "/api/metrics" }, messageProcessing: { buffer: { enabled: true, maxSize: 500 } } }',description:"High-volume SSE with message buffering for performance",expectedOutput:"Buffered event source for handling high-frequency updates"}],relatedExpressions:[],relatedContexts:["socketsFeature","onFeature","executionContext"],frameworkDependencies:["eventsource-api","hyperscript-runtime"],environmentRequirements:{browser:!0,server:!1,nodejs:!1},performance:{averageTime:15,complexity:"O(n)"}},this.documentation={summary:"Creates and manages Server-Sent Events connections for real-time data streaming with type-safe message handling, automatic reconnection, and comprehensive error recovery",parameters:[{name:"sourceConfig",type:"EventSourceInput",description:"SSE configuration including server URL, event handlers, message processing options, and connection settings",optional:!1,examples:['{ source: { url: "/api/events" }, eventHandlers: [{ event: "message", commands: [{ name: "update" }] }] }','{ source: { url: "/api/stream", withCredentials: true }, messageProcessing: { format: "json" } }','{ source: { url: "/api/feed" }, messageProcessing: { buffer: { enabled: true, maxSize: 100 } } }']}],returns:{type:"EventSourceContext",description:"Server-Sent Events management context with connection lifecycle, message processing, buffer management, and error recovery capabilities",examples:["context.connection.connect() → establish SSE connection","context.messages.getHistory(50) → get last 50 messages","context.connection.reconnect() → reconnect after failure","context.messages.flushBuffer() → process buffered messages"]},examples:[{title:"Basic SSE connection",code:'const sseContext = await createEventSourceFeature({ source: { url: "/api/updates" } })',explanation:"Create Server-Sent Events connection for real-time updates",output:"SSE context ready for receiving server events"},{title:"JSON message processing",code:'await sseContext.events.addHandler("user-update", { name: "updateUserInterface", args: [] })',explanation:"Add handler for specific event types with JSON parsing",output:"Event-driven SSE with structured data processing"},{title:"Buffered high-frequency events",code:"await sseContext.messages.flushBuffer() // Process accumulated messages",explanation:"Batch process high-frequency events for performance",output:"Efficient handling of rapid event streams"}],seeAlso:["socketsFeature","onFeature","streamProcessing","realTimeUpdates"],tags:["server-sent-events","real-time","streaming","events","connection-management","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const r=await this.initializeConfig(e),s={contextId:"eventsource-"+Date.now(),timestamp:t,category:"Frontend",capabilities:["sse-connection","message-processing","event-handling","automatic-reconnection","error-recovery"],state:"ready",connection:{connect:this.createConnectionEstablisher(r),disconnect:this.createConnectionDisconnector(),reconnect:this.createConnectionReconnector(),getState:this.createStateGetter(),getConnectionInfo:this.createConnectionInfoGetter(),isConnected:this.createConnectionChecker()},events:{addHandler:this.createEventHandlerAdder(),removeHandler:this.createEventHandlerRemover(),getHandlers:this.createEventHandlerGetter(),emit:this.createEventEmitter()},messages:{getHistory:this.createMessageHistoryGetter(),getBuffer:this.createBufferGetter(),flushBuffer:this.createBufferFlusher(),clearHistory:this.createHistoryClearer(),subscribe:this.createMessageSubscriber(),unsubscribe:this.createMessageUnsubscriber()},errors:{handle:this.createErrorHandler(),getErrorHistory:this.createErrorHistoryGetter(),clearErrors:this.createErrorClearer(),setErrorHandler:this.createErrorHandlerSetter()}};return!1!==e.options?.enableAutoConnect&&await this.createConnection(e.source,e.context||{}),this.trackPerformance(t,!0,s),{success:!0,value:s,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:"EventSource feature initialization failed: "+(e instanceof Error?e.message:e+""),suggestions:["Verify EventSource URL is accessible","Check browser supports Server-Sent Events","Ensure server supports SSE with proper headers","Validate event configuration parameters"]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,errors:[{type:"invalid-input",message:"Input must be an object",suggestions:[]}],suggestions:["Provide a valid EventSource configuration object"]};const t=e,n=[],r=[];if(void 0!==t.messageProcessing?.buffer?.maxSize&&0>t.messageProcessing.buffer.maxSize&&(n.push({type:"invalid-input",code:"invalid-buffer-size",message:"Buffer size must be non-negative (0 = unlimited)",path:"messageProcessing.buffer.maxSize",suggestions:[]}),r.push("Set buffer maxSize to 0 for unlimited or positive number for limit")),t.eventHandlers&&Array.isArray(t.eventHandlers))for(const e of t.eventHandlers)e.commands&&Array.isArray(e.commands)&&0===e.commands.length&&(n.push({type:"empty-config",code:"empty-commands-array",message:"Event handler commands array cannot be empty",path:"eventHandlers.commands",suggestions:[]}),r.push("Add at least one command to execute for event handler"));if(n.length>0)return{isValid:!1,errors:n,suggestions:r};const s=e;if(s.source&&"string"==typeof s.source.url&&s.source.url||(n.push({type:"invalid-input",code:"missing-eventsource-url",message:"Source configuration must include an EventSource URL",path:"source.url",suggestions:[]}),r.push('Provide an EventSource URL (e.g., "https://api.example.com/events")')),s.source&&"string"==typeof s.source.url&&s.source.url&&(this.isValidEventSourceURL(s.source.url)||(n.push({type:"invalid-input",code:"invalid-eventsource-url",message:`Invalid EventSource URL: "${s.source.url}"`,path:"source.url",suggestions:[]}),r.push("Use valid HTTP/HTTPS URL for EventSource connection")),s.source.retry&&(0>s.source.retry.maxAttempts&&(n.push({type:"invalid-input",code:"invalid-retry-attempts",message:"Retry max attempts must be non-negative",path:"source.retry.maxAttempts",suggestions:[]}),r.push("Set maxAttempts to 0 for no retry or positive number for retry limit")),0>s.source.retry.delay&&(n.push({type:"invalid-input",code:"invalid-retry-delay",message:"Retry delay must be non-negative",path:"source.retry.delay",suggestions:[]}),r.push("Set retry delay to positive number in milliseconds")),s.source.retry.delay>s.source.retry.maxDelay&&(n.push({type:"validation-error",message:"Max delay must be greater than or equal to delay",path:"source.retry.maxDelay",suggestions:[]}),r.push("Set maxDelay to be greater than or equal to delay"))),s.source.timeout&&1e3>s.source.timeout.duration&&(n.push({type:"invalid-input",code:"invalid-timeout-duration",message:"Timeout duration must be at least 1000ms",path:"source.timeout.duration",suggestions:[]}),r.push("Set timeout duration to at least 1000ms for proper operation"))),s.options&&(1>s.options.maxConnections&&(n.push({type:"invalid-input",code:"invalid-max-connections",message:"maxConnections must be at least 1",path:"options.maxConnections",suggestions:[]}),r.push("Set maxConnections to at least 1")),1e3>s.options.connectionTimeout&&(n.push({type:"invalid-input",code:"invalid-connection-timeout",message:"Connection timeout must be at least 1000ms",path:"options.connectionTimeout",suggestions:[]}),r.push("Set connection timeout to at least 1000ms for proper operation"))),s.eventHandlers&&s.eventHandlers.length>0)for(const e of s.eventHandlers)if(e.options?.throttle&&e.options?.debounce&&(n.push({type:"schema-validation",code:"conflicting-performance-options",message:"Cannot use both throttle and debounce simultaneously",path:"eventHandlers.options",suggestions:[]}),r.push("Choose either throttle OR debounce, not both")),e.filter)try{Function("event","return "+e.filter)}catch(t){n.push({type:"invalid-input",code:"invalid-filter-expression",message:"Invalid filter expression: "+e.filter,path:"eventHandlers.filter",suggestions:[]}),r.push("Use valid JavaScript expression for event filtering")}return"undefined"==typeof EventSource&&(n.push({type:"runtime-error",message:"Server-Sent Events are not supported in this environment",suggestions:[]}),r.push("EventSource requires a browser environment")),{isValid:0===n.length,errors:n,suggestions:r}}catch(e){return{isValid:!1,errors:[{type:"schema-validation",suggestions:[],message:e instanceof Error?e.message:"Invalid input format"}],suggestions:["Ensure input matches EventSourceInput schema","Check source configuration structure","Verify event handlers and message processing configurations"]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async createConnection(e,t){const r=`connection-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,s={id:r,url:e.url,eventSource:null,state:"connecting",createdAt:Date.now(),lastMessageTime:0,messageCount:0,errorCount:0,retryAttempts:0,maxRetryAttempts:e.retry?.maxAttempts||5};try{return s.eventSource=new EventSource(e.url,{withCredentials:e.withCredentials||!1}),s.eventSource.onopen=e=>{s.state="connected",s.connectedAt=Date.now(),s.retryAttempts=0,this.handleConnectionOpen(s,e)},s.eventSource.onmessage=e=>{s.messageCount++,s.lastMessageTime=Date.now(),this.handleMessage(s,e)},s.eventSource.onerror=e=>{s.errorCount++,s.state="error",this.handleConnectionError(s,e)},this.connections.set(r,s),s}catch(t){throw s.state="error",s.errorCount++,n(this.errorHistory,{error:t,timestamp:Date.now(),context:{connection:s,sourceConfig:e}}),t}}handleConnectionOpen(e,t){this.processEventHandlers(e.id,"open",t)}handleMessage(e,t){const r={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,connectionId:e.id,event:t.type,data:t.data,timestamp:Date.now(),format:this.detectMessageFormat(t.data),...t.lastEventId&&{lastEventId:t.lastEventId},...t.origin&&{origin:t.origin}};n(this.messageHistory,r);const s=this.messageBuffers.get(e.id);s&&(s.messages.push(r),s.maxSize>0&&s.messages.length>s.maxSize&&s.messages.shift()),this.processEventHandlers(e.id,"message",t)}handleConnectionError(e,t){n(this.errorHistory,{error:Error("EventSource connection error"),timestamp:Date.now(),context:{connection:e,event:t}}),this.processEventHandlers(e.id,"error",t),e.maxRetryAttempts>e.retryAttempts&&this.scheduleReconnection(e)}scheduleReconnection(e){e.retryAttempts++;setTimeout(()=>{this.attemptReconnection(e)},3e3*e.retryAttempts)}async attemptReconnection(e){try{e.eventSource&&e.eventSource.close(),e.state="connecting",e.eventSource=new EventSource(e.url),e.eventSource.onopen=t=>{e.state="connected",e.connectedAt=Date.now(),e.retryAttempts=0,this.handleConnectionOpen(e,t)},e.eventSource.onmessage=t=>{e.messageCount++,e.lastMessageTime=Date.now(),this.handleMessage(e,t)},e.eventSource.onerror=t=>{e.errorCount++,e.state="error",this.handleConnectionError(e,t)}}catch(t){n(this.errorHistory,{error:t,timestamp:Date.now(),context:{connection:e,reconnectAttempt:e.retryAttempts}})}}processEventHandlers(e,t,n){const r=Array.from(this.eventHandlers.values()).filter(n=>n.connectionId===e&&n.eventType===t&&n.isActive);for(const e of r)this.executeEventHandler(e,n)}async executeEventHandler(e,t){try{if(e.filter&&!this.testEventFilter(t,e.filter))return;if(e.options?.throttle&&this.isThrottled(e.id,e.options.throttle))return;if(e.options?.debounce)return void this.applyDebounce(e.id,e.options.debounce,()=>{this.executeCommands(e.commands,{event:t})});await this.executeCommands(e.commands,{event:t}),e.executionCount++,e.lastExecutionTime=Date.now()}catch(r){n(this.errorHistory,{error:r,timestamp:Date.now(),context:{handler:e,event:t}})}}async executeCommands(e,t){const n={success:!0,executed:e.length};for(const n of e)"object"==typeof n&&n.name&&await this.executeBasicCommand(n,t);return n}async executeBasicCommand(e,t){e.name}isValidEventSourceURL(e){try{const t=new URL(e,window?.location?.href);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}detectMessageFormat(e){if("string"==typeof e)try{return JSON.parse(e),"json"}catch{return"text"}return"raw"}testEventFilter(e,t){try{let n=this.filterCache.get(t);return n||(n=Function("event","return "+t),this.filterCache.set(t,n)),!!n(e)}catch{return!0}}isThrottled(e,t){const n=this.throttleTimers.get(e)||0,r=Date.now();return t>r-n||(this.throttleTimers.set(e,r),!1)}applyDebounce(e,t,n){const r=this.debounceTimers.get(e);r&&clearTimeout(r);const s=setTimeout(n,t);this.debounceTimers.set(e,s)}createConnectionEstablisher(e){return async t=>{const n=t||e;return await this.createConnection(n,{})}}createConnectionDisconnector(){return async e=>{const t=this.connections.get(e);return!!t&&(t.state="disconnecting",t.eventSource&&(t.eventSource.close(),t.eventSource=null),t.state="disconnected",t.disconnectedAt=Date.now(),!0)}}createConnectionReconnector(){return async e=>{const t=this.connections.get(e);return!!t&&(await this.attemptReconnection(t),!0)}}createStateGetter(){return e=>{const t=this.connections.get(e);return t?t.state:"disconnected"}}createConnectionInfoGetter(){return e=>{const t=this.connections.get(e);return t?{id:t.id,url:t.url,state:t.state,createdAt:t.createdAt,connectedAt:t.connectedAt,messageCount:t.messageCount,errorCount:t.errorCount,retryAttempts:t.retryAttempts}:null}}createConnectionChecker(){return e=>{const t=this.connections.get(e);return!!t&&"connected"===t.state}}createEventHandlerAdder(){return async(e,t,n)=>{const r=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`;return this.eventHandlers.set(r,{id:r,connectionId:e,eventType:t,commands:[n],isActive:!0,executionCount:0,lastExecutionTime:0}),r}}createEventHandlerRemover(){return e=>this.eventHandlers.delete(e)}createEventHandlerGetter(){return e=>e?Array.from(this.eventHandlers.values()).filter(t=>t.connectionId===e):Array.from(this.eventHandlers.values())}createEventEmitter(){return async(e,t,n)=>!0}createMessageHistoryGetter(){return(e,t)=>{let n=this.messageHistory;return e&&(n=n.filter(t=>t.connectionId===e)),t&&(n=n.slice(-t)),n}}createBufferGetter(){return e=>{const t=this.messageBuffers.get(e);return t?t.messages.slice():[]}}createBufferFlusher(){return async e=>{const t=this.messageBuffers.get(e);if(!t||0===t.messages.length)return[];const n=t.messages.slice();return t.messages.length=0,t.lastFlushTime=Date.now(),n}}createHistoryClearer(){return e=>(this.messageHistory=e?this.messageHistory.filter(t=>t.connectionId!==e):[],!0)}createMessageSubscriber(){return async(e,t)=>{const n=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`;return this.eventHandlers.set(n,{id:n,connectionId:"",eventType:e,commands:[t],isActive:!0,executionCount:0,lastExecutionTime:0}),n}}createMessageUnsubscriber(){return e=>this.eventHandlers.delete(e)}createErrorHandler(){return async(e,t)=>(n(this.errorHistory,{error:e,timestamp:Date.now(),context:t}),!0)}createErrorHistoryGetter(){return e=>e?this.errorHistory.slice(-e):this.errorHistory.slice()}createErrorClearer(){return()=>(this.errorHistory=[],!0)}createErrorHandlerSetter(){return e=>!0}dispose(){for(const e of this.connections.values())e.eventSource&&(e.eventSource.close(),e.eventSource=null);this.connections.clear();for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(const e of this.throttleTimers.values())clearTimeout(e);this.throttleTimers.clear(),this.eventHandlers.clear(),this.messageBuffers.clear(),this.filterCache.clear(),this.messageHistory=[],this.errorHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,r){n(this.evaluationHistory,{input:{},output:r,success:t,duration:Date.now()-e,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalConnections:this.connections.size,totalMessages:this.messageHistory.length,totalErrors:this.errorHistory.length,totalEventHandlers:this.eventHandlers.size,bufferedMessages:Array.from(this.messageBuffers.values()).reduce((e,t)=>e+t.messages.length,0)}}}function a(){return new o}async function i(e,t){return(new o).initialize({source:{url:"",withCredentials:!1,headers:{},retry:{enabled:!0,maxAttempts:5,delay:3e3,backoff:"exponential",maxDelay:3e4},timeout:{enabled:!0,duration:6e4},...e},eventHandlers:[],messageProcessing:{format:"text",validation:{enabled:!0},buffer:{enabled:!0,maxSize:100,flushInterval:1e3}},context:{variables:{}},options:{enableAutoConnect:!0,enableMessageBuffer:!0,enableErrorHandling:!0,maxConnections:1,connectionTimeout:3e4},environment:"frontend",debug:!1,...t})}const c=new o;export{r as EventSourceInputSchema,s as EventSourceOutputSchema,o as TypedEventSourceFeatureImplementation,i as createEventSource,a as createEventSourceFeature,c as enhancedEventSourceImplementation};
|
|
2
|
+
//# sourceMappingURL=feature-eventsource-BpZvPy_K.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e,t,n,s=[]){return{type:e,message:t,suggestions:s,...n&&{path:n}}}const t="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let n;function s(){return n({validate:e=>({success:!0,data:e})})}function r(a,o){if(t)return s();const i=n({validate:t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{success:!1,error:e("type-mismatch","Expected object, received "+typeof t)};const n=t,s={};if(o?.strict){const t=Object.keys(a),s=Object.keys(n).filter(e=>!t.includes(e));if(s.length>0)return{success:!1,error:e("runtime-error","Unexpected properties: "+s.join(", "))}}for(const[t,r]of Object.entries(a)){const a=n[t];if(!(t in n)&&!r._isOptional)return{success:!1,error:e("missing-argument",`Required field "${t}" is missing`,t)};const o=r.validate(a);if(!o.success){return{success:!1,error:e("validation-error",o.error.message||`Field "${t}" validation failed`,o.error.path?`${t}.${o.error.path}`:t)}}void 0!==o.data&&(s[t]=o.data)}return{success:!0,data:s}}});return i.strict=()=>r(a,{strict:!0}),i}function a(r,a="Custom validation failed"){return t?s():n({validate:t=>r(t)?{success:!0,data:t}:{success:!1,error:e("runtime-error",a)}})}n=function(t){return t.describe||(t.describe=function(e){return this.description=e,this}),t.safeParse||(t.safeParse=function(e){const t=this.validate(e);return t.success?{success:!0,data:t.data}:{success:!1,error:{errors:t.error?[t.error]:[]}}}),t.parse||(t.parse=function(e){const t=this.validate(e);if(t.success&&void 0!==t.data)return t.data;throw Error(t.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const e=this.validate.bind(this),t={...this,_isOptional:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return n(t)}),t.min||(t.min=function(t){const s=this.validate.bind(this),r={...this,validate:n=>{const r=s(n);return r.success&&"string"==typeof r.data&&t>r.data.length?{success:!1,error:e("runtime-error",`String must be at least ${t} characters long`)}:r}};return n(r)}),t.max||(t.max=function(t){const s=this.validate.bind(this),r={...this,validate:n=>{const r=s(n);return r.success&&"string"==typeof r.data&&r.data.length>t?{success:!1,error:e("runtime-error",`String must be at most ${t} characters long`)}:r}};return n(r)}),t.default||(t.default=function(e){const t=this.validate.bind(this),s={...this,_defaultValue:e,_hasDefault:!0,validate:n=>void 0===n?{success:!0,data:e}:t(n)};return n(s)}),t.rest||(t.rest=function(e){return this}),t.refine||(t.refine=function(t,s){const r=this.validate.bind(this),a={...this,validate:n=>{const a=r(n);return a.success?t(a.data)?a:{success:!1,error:e("runtime-error",s||"Refinement validation failed")}:a}};return n(a)}),new Proxy(t,{get:(e,t,n)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,n):function(...e){return n}})};const o={string:r=>function(r={}){return t?s():n({validate:t=>r.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:e("type-mismatch","Expected string, received "+typeof t)}:void 0!==r.minLength&&r.minLength>t.length?{success:!1,error:e("runtime-error",`String must be at least ${r.minLength} characters long`)}:void 0!==r.maxLength&&t.length>r.maxLength?{success:!1,error:e("runtime-error",`String must be at most ${r.maxLength} characters long`)}:r.pattern&&!r.pattern.test(t)?r.pattern.source.startsWith("^")&&r.pattern.source.endsWith("$")?{success:!1,error:e("runtime-error",`Expected "${r.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:e("missing-argument","String does not match required pattern")}:{success:!0,data:t},...r.description&&{description:r.description}})}(r||{}),number:r=>function(r={}){return t?s():n({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:e("type-mismatch","Expected number, received "+typeof t)}:void 0!==r.min&&r.min>n?{success:!1,error:e("runtime-error","Number must be at least "+r.min)}:void 0!==r.max&&n>r.max?{success:!1,error:e("runtime-error","Number must be at most "+r.max)}:{success:!0,data:n}}})}(r||{}),boolean:()=>t?s():n({validate:t=>"boolean"!=typeof t?{success:!1,error:e("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}}),object:e=>r(e),array:r=>function(r){return t?s():n({validate:t=>{if(!Array.isArray(t))return{success:!1,error:e("type-mismatch","Expected array, received "+typeof t)};const n=[];for(let s=0;t.length>s;s++){const a=r.validate(t[s]);if(!a.success)return{success:!1,error:e("runtime-error",a.error.message,a.error.path?`${s}.${a.error.path}`:""+s)};n.push(a.data)}return{success:!0,data:n}}})}(r),tuple:r=>function(r){return t?s():n({validate:t=>{if(!Array.isArray(t))return{success:!1,error:e("type-mismatch","Expected array, received "+typeof t)};if(t.length!==r.length)return{success:!1,error:e("runtime-error",`Expected tuple of length ${r.length}, received length ${t.length}`)};const n=[];for(let s=0;r.length>s;s++){const a=r[s].validate(t[s]);if(!a.success)return{success:!1,error:e("runtime-error",a.error.message,a.error.path?`${s}.${a.error.path}`:""+s)};n.push(a.data)}return{success:!0,data:n}}})}(r),union:r=>function(r){return t?s():n({validate:t=>{const n=[];for(const e of r){const s=e.validate(t);if(s.success)return s;n.push(s.error.message)}return{success:!1,error:e("type-mismatch","Value does not match any union type")}}})}(r),literal:r=>{return a=r,t?s():n({validate:t=>t===a?{success:!0,data:t}:{success:!1,error:e("runtime-error",`Expected ${JSON.stringify(a)}, received ${JSON.stringify(t)}`)}});var a},custom:(e,t)=>a(e,t),record:(r,a)=>function(r,a){return t?s():n({validate:t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{success:!1,error:e("type-mismatch","Expected record object, received "+typeof t)};const n=t,s={};for(const[t,o]of Object.entries(n)){const n=r.validate(t);if(!n.success)return{success:!1,error:e("invalid-argument",`Invalid key "${t}": ${n.error.message}`,t)};const i=a.validate(o);if(!i.success)return{success:!1,error:e("runtime-error",i.error.message,i.error.path?`${t}.${i.error.path}`:t)};s[t]=i.data}return{success:!0,data:s}}})}(r,a),enum:r=>function(r){return t?s():n({validate:t=>"string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t?{success:!1,error:e("type-mismatch","Expected string, received "+typeof t)}:r.includes(t)?{success:!0,data:t}:{success:!1,error:e("runtime-error",`Expected one of [${r.join(", ")}], received "${t}"`)}})}(r),function:()=>a(e=>"function"==typeof e,"Expected function"),unknown:()=>s(),any:()=>s(),null:()=>a(e=>null===e,"Expected null"),undefined:()=>a(e=>void 0===e,"Expected undefined"),instanceOf:e=>a(t=>t instanceof e,"Expected instance of "+e.name),instanceof:e=>a(t=>t instanceof e,"Expected instance of "+e.name)},i=o;function c(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const u=o.object({socket:i.object({url:o.string().url(),protocols:o.array(o.string()).default([]),reconnect:i.object({enabled:o.boolean().default(!0),maxAttempts:o.number().default(5),delay:o.number().default(1e3),backoff:i.enum(["linear","exponential"]).default("exponential"),maxDelay:o.number().default(3e4)}).default({}),heartbeat:o.object({enabled:o.boolean().default(!1),interval:o.number().default(3e4),message:o.string().default("ping"),timeout:o.number().default(5e3)}).default({}),compression:o.boolean().default(!1),binaryType:i.enum(["blob","arraybuffer"]).default("blob")}),eventHandlers:o.array(o.object({event:i.enum(["open","close","error","message"]),filter:o.string().optional(),commands:o.array(o.any()),options:i.object({once:o.boolean().default(!1),debounce:o.number().optional(),throttle:o.number().optional()}).default({})})).default([]),messageHandling:o.object({format:i.enum(["json","text","binary"]).default("json"),validation:i.object({enabled:o.boolean().default(!0),schema:o.any().optional()}).default({}),queue:o.object({enabled:o.boolean().default(!0),maxSize:o.number().default(100),persistence:o.boolean().default(!1)}).default({})}).default({}),context:o.object({variables:i.record(o.string(),o.any()).default({}),me:o.any().optional(),it:o.any().optional(),target:o.any().optional()}).default({}),options:o.object({enableAutoConnect:o.boolean().default(!0),enableMessageQueue:o.boolean().default(!0),enableErrorHandling:o.boolean().default(!0),maxConnections:o.number().default(5),connectionTimeout:o.number().default(1e4)}).default({}),environment:i.enum(["frontend","backend","universal"]).default("frontend"),debug:o.boolean().default(!1)}),l=o.object({contextId:o.string(),timestamp:o.number(),category:o.literal("Frontend"),capabilities:o.array(o.string()),state:i.enum(["ready","connecting","connected","disconnecting","disconnected","error"]),connection:i.object({connect:o.any(),disconnect:o.any(),reconnect:o.any(),isConnected:o.any(),getState:o.any(),getConnectionInfo:o.any()}),messaging:o.object({send:o.any(),sendJSON:o.any(),sendBinary:o.any(),subscribe:o.any(),unsubscribe:o.any(),getMessageHistory:o.any()}),events:o.object({addHandler:o.any(),removeHandler:o.any(),emit:o.any(),getHandlers:o.any()}),queue:o.object({add:o.any(),process:o.any(),clear:o.any(),getSize:o.any(),getPending:o.any()}),errors:o.object({handle:o.any(),getErrorHistory:o.any(),clearErrors:o.any(),setErrorHandler:o.any()})});class d{constructor(){this.name="socketsFeature",this.category="Frontend",this.description="Type-safe WebSocket management feature with reconnection, message queuing, and comprehensive error handling",this.inputSchema=u,this.outputType="Context",this.evaluationHistory=[],this.connections=new Map,this.eventHandlers=new Map,this.messageQueue=new Map,this.messageHistory=[],this.errorHistory=[],this.throttleTimers=new Map,this.debounceTimers=new Map,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["network-connection","websocket-management","message-transmission","reconnection-logic"],dependencies:["websocket-api","network-connection","message-serialization","event-system"],returnTypes:["Context"],examples:[{input:'{ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "processMessage" }] }] }',description:"Connect to WebSocket server and handle incoming messages",expectedOutput:"TypedSocketsContext with connection management and message handling"},{input:'{ socket: { url: "wss://chat.example.com", reconnect: { enabled: true, maxAttempts: 10 } }, messageHandling: { format: "json" } }',description:"Chat WebSocket with auto-reconnection and JSON message handling",expectedOutput:"Resilient WebSocket connection with automatic recovery"},{input:'{ socket: { url: "wss://data.example.com", heartbeat: { enabled: true, interval: 30000 } }, messageHandling: { queue: { enabled: true } } }',description:"Data WebSocket with heartbeat monitoring and message queuing",expectedOutput:"Monitored connection with reliable message delivery"}],relatedContexts:["onFeature","behaviorFeature","eventSourceFeature"],relatedExpressions:[],frameworkDependencies:["websocket-api","network-stack"],environmentRequirements:{browser:!0,server:!0,nodejs:!0},performance:{averageTime:25.4,complexity:"O(n)"}},this.documentation={summary:"Creates type-safe WebSocket connections for hyperscript with automatic reconnection, message queuing, and comprehensive error handling",parameters:[{name:"socketsConfig",type:"SocketsInput",description:"WebSocket configuration including URL, protocols, reconnection settings, and event handlers",optional:!1,examples:['{ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "handleMessage" }] }] }','{ socket: { url: "wss://chat.com", reconnect: { maxAttempts: 5 } }, messageHandling: { format: "json" } }','{ socket: { url: "wss://realtime.com", heartbeat: { enabled: true } }, options: { enableAutoConnect: true } }']}],returns:{type:"SocketsContext",description:"WebSocket management context with connection control, messaging, and event handling capabilities",examples:["context.connection.connect() → establish WebSocket connection",'context.messaging.sendJSON({data: "value"}) → send JSON message','context.events.addHandler("message", handler) → add message handler',"context.queue.add(message) → queue message for delivery"]},examples:[{title:"Basic WebSocket connection",code:'const socketsContext = await createSocketsFeature({ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "processData" }] }] })',explanation:"Create WebSocket connection with message processing",output:"Connected WebSocket with automatic message handling"},{title:"Resilient chat connection",code:"await socketsContext.connection.connect({ reconnect: { enabled: true, maxAttempts: 10 }, heartbeat: { enabled: true } })",explanation:"Establish chat connection with reconnection and heartbeat monitoring",output:"Robust WebSocket suitable for real-time chat applications"},{title:"Send structured data",code:'await socketsContext.messaging.sendJSON({ type: "chat", message: "Hello", userId: 123 })',explanation:"Send JSON-formatted message through WebSocket",output:"Structured message transmitted with automatic serialization"}],seeAlso:["onFeature","eventSourceFeature","networkManagement","realTimeData"],tags:["websockets","realtime","networking","messaging","reconnection","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=await this.initializeConfig(e),s=this.validate(e);if(!s.isValid)return{success:!1,error:s.errors[0]};const r={contextId:"sockets-"+Date.now(),timestamp:t,category:"Frontend",capabilities:["websocket-connection","message-handling","reconnection-management","queue-management","event-handling","error-recovery"],state:"ready",connection:{connect:this.createConnectionEstablisher(n),disconnect:this.createConnectionTerminator(),reconnect:this.createReconnector(),isConnected:this.createConnectionChecker(),getState:this.createStateGetter(),getConnectionInfo:this.createConnectionInfoGetter()},messaging:{send:this.createMessageSender(),sendJSON:this.createJSONSender(),sendBinary:this.createBinarySender(),subscribe:this.createMessageSubscriber(),unsubscribe:this.createMessageUnsubscriber(),getMessageHistory:this.createMessageHistoryGetter()},events:{addHandler:this.createEventHandlerAdder(),removeHandler:this.createEventHandlerRemover(),emit:this.createEventEmitter(),getHandlers:this.createHandlerGetter()},queue:{add:this.createQueueAdder(),process:this.createQueueProcessor(),clear:this.createQueueClearer(),getSize:this.createQueueSizeGetter(),getPending:this.createPendingGetter()},errors:{handle:this.createErrorHandler(),getErrorHistory:this.createErrorHistoryGetter(),clearErrors:this.createErrorClearer(),setErrorHandler:this.createErrorHandlerSetter()}};return e.options?.enableAutoConnect&&e.socket&&await this.createSocketConnection(e.socket,e.eventHandlers,e.context),this.trackPerformance(t,!0,r),{success:!0,value:r,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:"Sockets feature initialization failed: "+(e instanceof Error?e.message:e+""),suggestions:["Verify WebSocket URL is valid and accessible","Check network connectivity and firewall settings","Ensure WebSocket server supports specified protocols","Validate event handler configurations are correct"]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,errors:[{type:"invalid-input",message:"Input must be an object",suggestions:[]}],suggestions:["Provide a valid WebSocket configuration object"]};const t=this.inputSchema.parse(e),n=[],s=[],r=t;if(r.socket?.url)try{const e=new URL(r.socket.url);["ws:","wss:"].includes(e.protocol)||(n.push({type:"invalid-input",code:"invalid-websocket-protocol",message:"WebSocket URL must use ws:// or wss:// protocol",path:"socket.url",suggestions:[]}),s.push("Use ws:// for local development or wss:// for secure connections"))}catch(e){n.push({type:"invalid-input",code:"invalid-websocket-url",message:"Invalid WebSocket URL: "+r.socket.url,path:"socket.url",suggestions:[]}),s.push('Provide a valid WebSocket URL (e.g., "wss://api.example.com/ws")')}return r.socket?.reconnect&&(0>r.socket.reconnect.maxAttempts&&(n.push({type:"invalid-input",code:"invalid-reconnect-attempts",message:"Max reconnection attempts must be non-negative",path:"socket.reconnect.maxAttempts",suggestions:[]}),s.push("Set maxAttempts to 0 or positive number (0 = no reconnection)")),0>r.socket.reconnect.delay&&(n.push({type:"invalid-input",code:"invalid-reconnect-delay",message:"Reconnection delay must be non-negative",path:"socket.reconnect.delay",suggestions:[]}),s.push("Set delay to positive number in milliseconds")),r.socket.reconnect.delay>r.socket.reconnect.maxDelay&&(n.push({type:"validation-error",message:"Max delay must be greater than or equal to initial delay",path:"socket.reconnect.maxDelay",suggestions:[]}),s.push("Ensure maxDelay >= delay for proper backoff behavior"))),r.socket?.heartbeat?.enabled&&(r.socket.heartbeat.interval>0||(n.push({type:"invalid-input",code:"invalid-heartbeat-interval",message:"Heartbeat interval must be positive",path:"socket.heartbeat.interval",suggestions:[]}),s.push("Set heartbeat interval to positive number in milliseconds")),r.socket.heartbeat.timeout>0||(n.push({type:"invalid-input",code:"invalid-heartbeat-timeout",message:"Heartbeat timeout must be positive",path:"socket.heartbeat.timeout",suggestions:[]}),s.push("Set heartbeat timeout to positive number in milliseconds")),r.socket.heartbeat.interval>r.socket.heartbeat.timeout||(n.push({type:"validation-error",message:"Heartbeat timeout must be less than interval",path:"socket.heartbeat",suggestions:[]}),s.push("Ensure timeout < interval for proper heartbeat detection"))),r.eventHandlers&&r.eventHandlers.forEach((e,t)=>{if(e.filter)try{Function("message","event","return "+e.filter)}catch(r){n.push({type:"invalid-input",code:"invalid-filter-expression",message:"Invalid filter expression: "+e.filter,path:`eventHandlers[${t}].filter`,suggestions:[]}),s.push("Use valid JavaScript expression for message filtering")}e.options?.throttle&&e.options?.debounce&&(n.push({type:"schema-validation",code:"conflicting-performance-options",message:"Cannot use both throttle and debounce on the same event handler",path:`eventHandlers[${t}].options`,suggestions:[]}),s.push("Choose either throttle OR debounce, not both")),e.commands&&0!==e.commands.length||(n.push({type:"empty-config",code:"empty-commands-array",message:"Event handler must have at least one command",path:`eventHandlers[${t}].commands`,suggestions:[]}),s.push("Add at least one command to execute when event occurs"))}),r.messageHandling?.queue&&0>r.messageHandling.queue.maxSize&&(n.push({type:"invalid-input",code:"invalid-queue-size",message:"Queue max size must be non-negative (0 = unlimited)",path:"messageHandling.queue.maxSize",suggestions:[]}),s.push("Set queue maxSize to non-negative number (0 for unlimited)")),r.options?.maxConnections>0||(n.push({type:"invalid-input",code:"invalid-max-connections",message:"Max connections must be positive",path:"options.maxConnections",suggestions:[]}),s.push("Set maxConnections to positive number")),r.options?.connectionTimeout>0||(n.push({type:"invalid-input",code:"invalid-connection-timeout",message:"Connection timeout must be positive",path:"options.connectionTimeout",suggestions:[]}),s.push("Set connectionTimeout to positive number in milliseconds")),{isValid:0===n.length,errors:n,suggestions:s}}catch(e){return{isValid:!1,errors:[{type:"schema-validation",suggestions:[],message:e instanceof Error?e.message:"Invalid input format"}],suggestions:["Ensure input matches SocketsInput schema","Check WebSocket configuration structure","Verify event handler and message handling configurations are valid"]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async createSocketConnection(e,t,n){const s=`socket-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,r={id:s,url:e.url,protocols:e.protocols||[],websocket:null,state:"disconnected",reconnectAttempts:0,totalReconnects:0,messagesSent:0,messagesReceived:0};this.connections.set(s,r),this.messageQueue.set(s,[]);for(const e of t)await this.registerEventHandler(s,e);return r}async registerEventHandler(e,t){const n=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,s={id:n,event:t.event,filter:t.filter,commands:t.commands||[],options:t.options||{},isActive:!0,executionCount:0,lastExecutionTime:0};return this.eventHandlers.set(n,s),s}async connectWebSocket(e){const t=this.connections.get(e);if(!t)return!1;try{return t.state="connecting","undefined"!=typeof WebSocket?(t.websocket=new WebSocket(t.url,t.protocols),t.websocket.onopen=()=>this.handleWebSocketOpen(e),t.websocket.onclose=t=>this.handleWebSocketClose(e,t),t.websocket.onerror=t=>this.handleWebSocketError(e,t),t.websocket.onmessage=t=>this.handleWebSocketMessage(e,t)):(t.state="connected",t.connectedAt=Date.now(),await this.executeEventHandlers(e,"open",null)),!0}catch(n){return t.state="error",t.lastError=n,await this.executeEventHandlers(e,"error",n),!1}}async handleWebSocketOpen(e){const t=this.connections.get(e);t&&(t.state="connected",t.connectedAt=Date.now(),t.reconnectAttempts=0,await this.executeEventHandlers(e,"open",null),await this.processQueuedMessages(e))}async handleWebSocketClose(e,t){const n=this.connections.get(e);n&&(n.state="disconnected",n.disconnectedAt=Date.now(),await this.executeEventHandlers(e,"close",t))}async handleWebSocketError(e,t){const n=this.connections.get(e);n&&(n.state="error",n.lastError=Error("WebSocket error occurred"),await this.executeEventHandlers(e,"error",t))}async handleWebSocketMessage(e,t){const n=this.connections.get(e);if(!n)return;n.messagesReceived++;const s={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,connectionId:e,type:"incoming",data:t.data,format:this.detectMessageFormat(t.data),timestamp:Date.now(),size:this.calculateMessageSize(t.data),validated:!0};c(this.messageHistory,s),await this.executeEventHandlers(e,"message",t)}async executeEventHandlers(e,t,n){const s=Array.from(this.eventHandlers.values()).filter(e=>e.event===t&&e.isActive);for(const e of s)try{if(e.filter&&!this.testMessageFilter(n,e.filter))continue;if(e.options.throttle&&this.isThrottled(e.id,e.options.throttle))continue;if(e.options.debounce){this.applyDebounce(e.id,e.options.debounce,()=>{this.executeHandlerCommands(e,n)});continue}await this.executeHandlerCommands(e,n),e.executionCount++,e.lastExecutionTime=Date.now(),e.options.once&&(e.isActive=!1)}catch(t){c(this.errorHistory,{error:t,timestamp:Date.now(),context:{handler:e,eventData:n}})}}async executeHandlerCommands(e,t){const n={success:!0,executed:e.commands.length};for(const n of e.commands)"object"==typeof n&&n.name&&await this.executeBasicCommand(n,{eventData:t});return n}async executeBasicCommand(e,t){e.name}detectMessageFormat(e){if(e instanceof ArrayBuffer||e instanceof Blob)return"binary";if("string"==typeof e)try{return JSON.parse(e),"json"}catch{return"text"}return"text"}calculateMessageSize(e){return e instanceof ArrayBuffer?e.byteLength:e instanceof Blob?e.size:"string"==typeof e?new Blob([e]).size:0}testMessageFilter(e,t){try{let n=this.filterCache.get(t);return n||(n=Function("message","event","return "+t),this.filterCache.set(t,n)),!!n(e?.data,e)}catch{return!0}}isThrottled(e,t){const n=this.throttleTimers.get(e)||0,s=Date.now();return t>s-n||(this.throttleTimers.set(e,s),!1)}applyDebounce(e,t,n){const s=this.debounceTimers.get(e);s&&clearTimeout(s);const r=setTimeout(n,t);this.debounceTimers.set(e,r)}async processQueuedMessages(e){const t=this.messageQueue.get(e);if(!t||0===t.length)return;const n=this.connections.get(e);if(!n||"connected"!==n.state)return;const s=[];for(const n of t)try{await this.sendMessage(e,n.data,n.format)}catch(e){n.attempts++,n.lastAttempt=Date.now(),n.error=e,n.maxAttempts>n.attempts?s.push(n):c(this.errorHistory,{error:Error(`Message ${n.id} dropped after ${n.maxAttempts} failed attempts`),timestamp:Date.now(),context:{messageId:n.id,data:n.data,format:n.format}})}t.length=0,t.push(...s)}async sendMessage(e,t,n){const s=this.connections.get(e);if(!s||!s.websocket||"connected"!==s.state)return await this.queueMessage(e,t,n),!1;try{let r;switch(n){case"json":r=JSON.stringify(t);break;case"binary":r=t instanceof ArrayBuffer?t:new ArrayBuffer(0);break;default:r=t+""}if(s.websocket.readyState===WebSocket.OPEN){s.websocket.send(r),s.messagesSent++;const a={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,connectionId:e,type:"outgoing",data:t,format:n,timestamp:Date.now(),size:this.calculateMessageSize(r),validated:!0};return c(this.messageHistory,a),!0}return!1}catch(s){return await this.queueMessage(e,t,n),!1}}async queueMessage(e,t,n){const s=this.messageQueue.get(e);if(!s)return;const r={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,data:t,format:n,timestamp:Date.now(),attempts:0,maxAttempts:3};s.push(r);s.length>100&&s.shift()}createConnectionEstablisher(e){return async e=>{if("string"==typeof e)return await this.connectWebSocket(e);{const t=e||{url:"wss://localhost:8080",protocols:[],reconnect:{enabled:!0},heartbeat:{enabled:!1},compression:!1,binaryType:"blob"},n=await this.createSocketConnection(t,[],{});return await this.connectWebSocket(n.id)}}}createConnectionTerminator(){return async e=>{const t=this.connections.get(e);return!!t&&(t.state="disconnecting",t.websocket&&t.websocket.close(),t.state="disconnected",t.disconnectedAt=Date.now(),await this.executeEventHandlers(e,"close",null),!0)}}createReconnector(){return async e=>{const t=this.connections.get(e);return!!t&&(t.websocket&&t.websocket.close(),t.reconnectAttempts++,t.totalReconnects++,await this.connectWebSocket(e))}}createConnectionChecker(){return e=>{const t=this.connections.get(e);return"connected"===t?.state||!1}}createStateGetter(){return e=>{const t=this.connections.get(e);return t?.state||"disconnected"}}createConnectionInfoGetter(){return e=>{const t=this.connections.get(e);if(!t)return null;return{connectionId:t.id,...void 0!==t.connectedAt&&{connectedAt:t.connectedAt},totalReconnects:t.totalReconnects,messagesSent:t.messagesSent,messagesReceived:t.messagesReceived,bytesTransmitted:0,bytesReceived:0,averageLatency:0,errorCount:this.errorHistory.filter(t=>t.context?.connectionId===e).length,uptime:t.connectedAt?Date.now()-t.connectedAt:0}}}createMessageSender(){return async(e,t,n="text")=>await this.sendMessage(e,t,n)}createJSONSender(){return async(e,t)=>await this.sendMessage(e,t,"json")}createBinarySender(){return async(e,t)=>await this.sendMessage(e,t,"binary")}createMessageSubscriber(){return(e,t)=>this.registerEventHandler("*",{event:e,commands:[t]})}createMessageUnsubscriber(){return e=>this.eventHandlers.delete(e)}createMessageHistoryGetter(){return(e,t)=>{let n=this.messageHistory;return e&&(n=n.filter(t=>t.connectionId===e)),t&&(n=n.slice(-t)),n}}createEventHandlerAdder(){return async(e,t,n)=>await this.registerEventHandler(e,{event:t,commands:[n],options:{}})}createEventHandlerRemover(){return e=>this.eventHandlers.delete(e)}createEventEmitter(){return async(e,t,n)=>(await this.executeEventHandlers(e,t,n),!0)}createHandlerGetter(){return e=>e?Array.from(this.eventHandlers.values()).filter(t=>t.id.includes(e)):Array.from(this.eventHandlers.values())}createQueueAdder(){return async(e,t,n="json")=>(await this.queueMessage(e,t,n),!0)}createQueueProcessor(){return async e=>(await this.processQueuedMessages(e),!0)}createQueueClearer(){return e=>{const t=this.messageQueue.get(e);return!!t&&(t.length=0,!0)}}createQueueSizeGetter(){return e=>{const t=this.messageQueue.get(e);return t?t.length:0}}createPendingGetter(){return e=>{const t=this.messageQueue.get(e);return t?t.slice():[]}}createErrorHandler(){return async(e,t)=>(c(this.errorHistory,{error:e,timestamp:Date.now(),context:{connectionId:t}}),!0)}createErrorHistoryGetter(){return e=>e?this.errorHistory.slice(-e):this.errorHistory.slice()}createErrorClearer(){return()=>(this.errorHistory=[],!0)}createErrorHandlerSetter(){return e=>!0}dispose(){for(const e of this.connections.values())e.websocket&&e.websocket.close();this.connections.clear();for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(const e of this.throttleTimers.values())clearTimeout(e);this.throttleTimers.clear(),this.eventHandlers.clear(),this.messageQueue.clear(),this.filterCache.clear(),this.messageHistory=[],this.errorHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,n){const s=Date.now()-e;c(this.evaluationHistory,{input:{},output:n,success:t,duration:s,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalConnections:this.connections.size,totalHandlers:this.eventHandlers.size,totalMessages:this.messageHistory.length,totalErrors:this.errorHistory.length,queuedMessages:Array.from(this.messageQueue.values()).reduce((e,t)=>e+t.length,0)}}}const m=new d;var h=Object.freeze({__proto__:null,SocketsInputSchema:u,SocketsOutputSchema:l,TypedSocketsFeatureImplementation:d,createSockets:async function(e,t){return(new d).initialize({socket:{url:"wss://localhost:8080",protocols:[],reconnect:{enabled:!0,maxAttempts:5,delay:1e3,backoff:"exponential",maxDelay:3e4},heartbeat:{enabled:!1,interval:3e4,message:"ping",timeout:5e3},compression:!1,binaryType:"blob",...e},eventHandlers:[],messageHandling:{format:"json",validation:{enabled:!0},queue:{enabled:!0,maxSize:100,persistence:!1}},context:{variables:{}},options:{enableAutoConnect:!0,enableMessageQueue:!0,enableErrorHandling:!0,maxConnections:5,connectionTimeout:1e4},environment:"frontend",debug:!1,...t})},createSocketsFeature:function(){return new d},enhancedSocketsImplementation:m});export{h as s,o as v,i as z};
|
|
2
|
-
//# sourceMappingURL=feature-sockets-
|
|
1
|
+
function e(e,t,n,s=[]){return{type:e,message:t,suggestions:s,...n&&{path:n}}}const t="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let n;function s(){return n({validate:e=>({success:!0,data:e})})}function r(a,o){if(t)return s();const i=n({validate:t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{success:!1,error:e("type-mismatch","Expected object, received "+typeof t)};const n=t,s={};if(o?.strict){const t=Object.keys(a),s=Object.keys(n).filter(e=>!t.includes(e));if(s.length>0)return{success:!1,error:e("runtime-error","Unexpected properties: "+s.join(", "))}}for(const[t,r]of Object.entries(a)){const a=n[t];if(!(t in n)&&!r._isOptional)return{success:!1,error:e("missing-argument",`Required field "${t}" is missing`,t)};const o=r.validate(a);if(!o.success){return{success:!1,error:e("validation-error",o.error.message||`Field "${t}" validation failed`,o.error.path?`${t}.${o.error.path}`:t)}}void 0!==o.data&&(s[t]=o.data)}return{success:!0,data:s}}});return i.strict=()=>r(a,{strict:!0}),i}function a(r,a="Custom validation failed"){return t?s():n({validate:t=>r(t)?{success:!0,data:t}:{success:!1,error:e("runtime-error",a)}})}n=function(t){return t.describe||(t.describe=function(e){return this.description=e,this}),t.safeParse||(t.safeParse=function(e){const t=this.validate(e);return t.success?{success:!0,data:t.data}:{success:!1,error:{errors:t.error?[t.error]:[]}}}),t.parse||(t.parse=function(e){const t=this.validate(e);if(t.success&&void 0!==t.data)return t.data;throw Error(t.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const e=this.validate.bind(this),t={...this,_isOptional:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return n(t)}),t.min||(t.min=function(t){const s=this.validate.bind(this),r={...this,validate:n=>{const r=s(n);return r.success&&"string"==typeof r.data&&t>r.data.length?{success:!1,error:e("runtime-error",`String must be at least ${t} characters long`)}:r}};return n(r)}),t.max||(t.max=function(t){const s=this.validate.bind(this),r={...this,validate:n=>{const r=s(n);return r.success&&"string"==typeof r.data&&r.data.length>t?{success:!1,error:e("runtime-error",`String must be at most ${t} characters long`)}:r}};return n(r)}),t.default||(t.default=function(e){const t=this.validate.bind(this),s={...this,_defaultValue:e,_hasDefault:!0,validate:n=>void 0===n?{success:!0,data:e}:t(n)};return n(s)}),t.rest||(t.rest=function(e){return this}),t.refine||(t.refine=function(t,s){const r=this.validate.bind(this),a={...this,validate:n=>{const a=r(n);return a.success?t(a.data)?a:{success:!1,error:e("runtime-error",s||"Refinement validation failed")}:a}};return n(a)}),new Proxy(t,{get:(e,t,n)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,n):function(...e){return n}})};const o={string:r=>function(r={}){return t?s():n({validate:t=>r.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:e("type-mismatch","Expected string, received "+typeof t)}:void 0!==r.minLength&&r.minLength>t.length?{success:!1,error:e("runtime-error",`String must be at least ${r.minLength} characters long`)}:void 0!==r.maxLength&&t.length>r.maxLength?{success:!1,error:e("runtime-error",`String must be at most ${r.maxLength} characters long`)}:r.pattern&&!r.pattern.test(t)?r.pattern.source.startsWith("^")&&r.pattern.source.endsWith("$")?{success:!1,error:e("runtime-error",`Expected "${r.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:e("missing-argument","String does not match required pattern")}:{success:!0,data:t},...r.description&&{description:r.description}})}(r||{}),number:r=>function(r={}){return t?s():n({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:e("type-mismatch","Expected number, received "+typeof t)}:void 0!==r.min&&r.min>n?{success:!1,error:e("runtime-error","Number must be at least "+r.min)}:void 0!==r.max&&n>r.max?{success:!1,error:e("runtime-error","Number must be at most "+r.max)}:{success:!0,data:n}}})}(r||{}),boolean:()=>t?s():n({validate:t=>"boolean"!=typeof t?{success:!1,error:e("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}}),object:e=>r(e),array:r=>function(r){return t?s():n({validate:t=>{if(!Array.isArray(t))return{success:!1,error:e("type-mismatch","Expected array, received "+typeof t)};const n=[];for(let s=0;t.length>s;s++){const a=r.validate(t[s]);if(!a.success)return{success:!1,error:e("runtime-error",a.error.message,a.error.path?`${s}.${a.error.path}`:""+s)};n.push(a.data)}return{success:!0,data:n}}})}(r),tuple:r=>function(r){return t?s():n({validate:t=>{if(!Array.isArray(t))return{success:!1,error:e("type-mismatch","Expected array, received "+typeof t)};if(t.length!==r.length)return{success:!1,error:e("runtime-error",`Expected tuple of length ${r.length}, received length ${t.length}`)};const n=[];for(let s=0;r.length>s;s++){const a=r[s].validate(t[s]);if(!a.success)return{success:!1,error:e("runtime-error",a.error.message,a.error.path?`${s}.${a.error.path}`:""+s)};n.push(a.data)}return{success:!0,data:n}}})}(r),union:r=>function(r){return t?s():n({validate:t=>{const n=[];for(const e of r){const s=e.validate(t);if(s.success)return s;n.push(s.error.message)}return{success:!1,error:e("type-mismatch","Value does not match any union type")}}})}(r),literal:r=>{return a=r,t?s():n({validate:t=>t===a?{success:!0,data:t}:{success:!1,error:e("runtime-error",`Expected ${JSON.stringify(a)}, received ${JSON.stringify(t)}`)}});var a},custom:(e,t)=>a(e,t),record:(r,a)=>function(r,a){return t?s():n({validate:t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{success:!1,error:e("type-mismatch","Expected record object, received "+typeof t)};const n=t,s={};for(const[t,o]of Object.entries(n)){const n=r.validate(t);if(!n.success)return{success:!1,error:e("invalid-argument",`Invalid key "${t}": ${n.error.message}`,t)};const i=a.validate(o);if(!i.success)return{success:!1,error:e("runtime-error",i.error.message,i.error.path?`${t}.${i.error.path}`:t)};s[t]=i.data}return{success:!0,data:s}}})}(r,a),enum:r=>function(r){return t?s():n({validate:t=>"string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t?{success:!1,error:e("type-mismatch","Expected string, received "+typeof t)}:r.includes(t)?{success:!0,data:t}:{success:!1,error:e("runtime-error",`Expected one of [${r.join(", ")}], received "${t}"`)}})}(r),function:()=>a(e=>"function"==typeof e,"Expected function"),unknown:()=>s(),any:()=>s(),null:()=>a(e=>null===e,"Expected null"),undefined:()=>a(e=>void 0===e,"Expected undefined"),instanceOf:e=>a(t=>t instanceof e,"Expected instance of "+e.name),instanceof:e=>a(t=>t instanceof e,"Expected instance of "+e.name)},i=o;function c(e,t,n=1e3){e.push(t),e.length>n&&e.shift()}const u=o.object({socket:i.object({url:o.string().url(),protocols:o.array(o.string()).default([]),reconnect:i.object({enabled:o.boolean().default(!0),maxAttempts:o.number().default(5),delay:o.number().default(1e3),backoff:i.enum(["linear","exponential"]).default("exponential"),maxDelay:o.number().default(3e4)}).default({}),heartbeat:o.object({enabled:o.boolean().default(!1),interval:o.number().default(3e4),message:o.string().default("ping"),timeout:o.number().default(5e3)}).default({}),compression:o.boolean().default(!1),binaryType:i.enum(["blob","arraybuffer"]).default("blob")}),eventHandlers:o.array(o.object({event:i.enum(["open","close","error","message"]),filter:o.string().optional(),commands:o.array(o.any()),options:i.object({once:o.boolean().default(!1),debounce:o.number().optional(),throttle:o.number().optional()}).default({})})).default([]),messageHandling:o.object({format:i.enum(["json","text","binary"]).default("json"),validation:i.object({enabled:o.boolean().default(!0),schema:o.any().optional()}).default({}),queue:o.object({enabled:o.boolean().default(!0),maxSize:o.number().default(100),persistence:o.boolean().default(!1)}).default({})}).default({}),context:o.object({variables:i.record(o.string(),o.any()).default({}),me:o.any().optional(),it:o.any().optional(),target:o.any().optional()}).default({}),options:o.object({enableAutoConnect:o.boolean().default(!0),enableMessageQueue:o.boolean().default(!0),enableErrorHandling:o.boolean().default(!0),maxConnections:o.number().default(5),connectionTimeout:o.number().default(1e4)}).default({}),environment:i.enum(["frontend","backend","universal"]).default("frontend"),debug:o.boolean().default(!1)}),l=o.object({contextId:o.string(),timestamp:o.number(),category:o.literal("Frontend"),capabilities:o.array(o.string()),state:i.enum(["ready","connecting","connected","disconnecting","disconnected","error"]),connection:i.object({connect:o.any(),disconnect:o.any(),reconnect:o.any(),isConnected:o.any(),getState:o.any(),getConnectionInfo:o.any()}),messaging:o.object({send:o.any(),sendJSON:o.any(),sendBinary:o.any(),subscribe:o.any(),unsubscribe:o.any(),getMessageHistory:o.any()}),events:o.object({addHandler:o.any(),removeHandler:o.any(),emit:o.any(),getHandlers:o.any()}),queue:o.object({add:o.any(),process:o.any(),clear:o.any(),getSize:o.any(),getPending:o.any()}),errors:o.object({handle:o.any(),getErrorHistory:o.any(),clearErrors:o.any(),setErrorHandler:o.any()})});class d{constructor(){this.name="socketsFeature",this.category="Frontend",this.description="Type-safe WebSocket management feature with reconnection, message queuing, and comprehensive error handling",this.inputSchema=u,this.outputType="Context",this.evaluationHistory=[],this.connections=new Map,this.eventHandlers=new Map,this.messageQueue=new Map,this.messageHistory=[],this.errorHistory=[],this.throttleTimers=new Map,this.debounceTimers=new Map,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["network-connection","websocket-management","message-transmission","reconnection-logic"],dependencies:["websocket-api","network-connection","message-serialization","event-system"],returnTypes:["Context"],examples:[{input:'{ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "processMessage" }] }] }',description:"Connect to WebSocket server and handle incoming messages",expectedOutput:"TypedSocketsContext with connection management and message handling"},{input:'{ socket: { url: "wss://chat.example.com", reconnect: { enabled: true, maxAttempts: 10 } }, messageHandling: { format: "json" } }',description:"Chat WebSocket with auto-reconnection and JSON message handling",expectedOutput:"Resilient WebSocket connection with automatic recovery"},{input:'{ socket: { url: "wss://data.example.com", heartbeat: { enabled: true, interval: 30000 } }, messageHandling: { queue: { enabled: true } } }',description:"Data WebSocket with heartbeat monitoring and message queuing",expectedOutput:"Monitored connection with reliable message delivery"}],relatedContexts:["onFeature","behaviorFeature","eventSourceFeature"],relatedExpressions:[],frameworkDependencies:["websocket-api","network-stack"],environmentRequirements:{browser:!0,server:!0,nodejs:!0},performance:{averageTime:25.4,complexity:"O(n)"}},this.documentation={summary:"Creates type-safe WebSocket connections for hyperscript with automatic reconnection, message queuing, and comprehensive error handling",parameters:[{name:"socketsConfig",type:"SocketsInput",description:"WebSocket configuration including URL, protocols, reconnection settings, and event handlers",optional:!1,examples:['{ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "handleMessage" }] }] }','{ socket: { url: "wss://chat.com", reconnect: { maxAttempts: 5 } }, messageHandling: { format: "json" } }','{ socket: { url: "wss://realtime.com", heartbeat: { enabled: true } }, options: { enableAutoConnect: true } }']}],returns:{type:"SocketsContext",description:"WebSocket management context with connection control, messaging, and event handling capabilities",examples:["context.connection.connect() → establish WebSocket connection",'context.messaging.sendJSON({data: "value"}) → send JSON message','context.events.addHandler("message", handler) → add message handler',"context.queue.add(message) → queue message for delivery"]},examples:[{title:"Basic WebSocket connection",code:'const socketsContext = await createSocketsFeature({ socket: { url: "wss://api.example.com/ws" }, eventHandlers: [{ event: "message", commands: [{ name: "processData" }] }] })',explanation:"Create WebSocket connection with message processing",output:"Connected WebSocket with automatic message handling"},{title:"Resilient chat connection",code:"await socketsContext.connection.connect({ reconnect: { enabled: true, maxAttempts: 10 }, heartbeat: { enabled: true } })",explanation:"Establish chat connection with reconnection and heartbeat monitoring",output:"Robust WebSocket suitable for real-time chat applications"},{title:"Send structured data",code:'await socketsContext.messaging.sendJSON({ type: "chat", message: "Hello", userId: 123 })',explanation:"Send JSON-formatted message through WebSocket",output:"Structured message transmitted with automatic serialization"}],seeAlso:["onFeature","eventSourceFeature","networkManagement","realTimeData"],tags:["websockets","realtime","networking","messaging","reconnection","type-safe","enhanced-pattern"]}}async initialize(e){const t=Date.now();try{const n=await this.initializeConfig(e),s=this.validate(e);if(!s.isValid)return{success:!1,error:s.errors[0]};const r={contextId:"sockets-"+Date.now(),timestamp:t,category:"Frontend",capabilities:["websocket-connection","message-handling","reconnection-management","queue-management","event-handling","error-recovery"],state:"ready",connection:{connect:this.createConnectionEstablisher(n),disconnect:this.createConnectionTerminator(),reconnect:this.createReconnector(),isConnected:this.createConnectionChecker(),getState:this.createStateGetter(),getConnectionInfo:this.createConnectionInfoGetter()},messaging:{send:this.createMessageSender(),sendJSON:this.createJSONSender(),sendBinary:this.createBinarySender(),subscribe:this.createMessageSubscriber(),unsubscribe:this.createMessageUnsubscriber(),getMessageHistory:this.createMessageHistoryGetter()},events:{addHandler:this.createEventHandlerAdder(),removeHandler:this.createEventHandlerRemover(),emit:this.createEventEmitter(),getHandlers:this.createHandlerGetter()},queue:{add:this.createQueueAdder(),process:this.createQueueProcessor(),clear:this.createQueueClearer(),getSize:this.createQueueSizeGetter(),getPending:this.createPendingGetter()},errors:{handle:this.createErrorHandler(),getErrorHistory:this.createErrorHistoryGetter(),clearErrors:this.createErrorClearer(),setErrorHandler:this.createErrorHandlerSetter()}};return e.options?.enableAutoConnect&&e.socket&&await this.createSocketConnection(e.socket,e.eventHandlers,e.context),this.trackPerformance(t,!0,r),{success:!0,value:r,type:"object"}}catch(e){return this.trackPerformance(t,!1),{success:!1,error:{type:"runtime-error",message:"Sockets feature initialization failed: "+(e instanceof Error?e.message:e+""),suggestions:["Verify WebSocket URL is valid and accessible","Check network connectivity and firewall settings","Ensure WebSocket server supports specified protocols","Validate event handler configurations are correct"]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,errors:[{type:"invalid-input",message:"Input must be an object",suggestions:[]}],suggestions:["Provide a valid WebSocket configuration object"]};const t=e,n=[],s=[];if(t.socket&&"string"==typeof t.socket.url&&t.socket.url||(n.push({type:"invalid-input",code:"missing-websocket-url",message:"Socket configuration must include a WebSocket URL",path:"socket.url",suggestions:[]}),s.push('Provide a WebSocket URL (e.g., "wss://api.example.com/ws")')),t.socket?.url)try{const e=new URL(t.socket.url);["ws:","wss:"].includes(e.protocol)||(n.push({type:"invalid-input",code:"invalid-websocket-protocol",message:"WebSocket URL must use ws:// or wss:// protocol",path:"socket.url",suggestions:[]}),s.push("Use ws:// for local development or wss:// for secure connections"))}catch(e){n.push({type:"invalid-input",code:"invalid-websocket-url",message:"Invalid WebSocket URL: "+t.socket.url,path:"socket.url",suggestions:[]}),s.push('Provide a valid WebSocket URL (e.g., "wss://api.example.com/ws")')}return t.socket?.reconnect&&(0>t.socket.reconnect.maxAttempts&&(n.push({type:"invalid-input",code:"invalid-reconnect-attempts",message:"Max reconnection attempts must be non-negative",path:"socket.reconnect.maxAttempts",suggestions:[]}),s.push("Set maxAttempts to 0 or positive number (0 = no reconnection)")),0>t.socket.reconnect.delay&&(n.push({type:"invalid-input",code:"invalid-reconnect-delay",message:"Reconnection delay must be non-negative",path:"socket.reconnect.delay",suggestions:[]}),s.push("Set delay to positive number in milliseconds")),t.socket.reconnect.delay>t.socket.reconnect.maxDelay&&(n.push({type:"validation-error",message:"Max delay must be greater than or equal to initial delay",path:"socket.reconnect.maxDelay",suggestions:[]}),s.push("Ensure maxDelay >= delay for proper backoff behavior"))),t.socket?.heartbeat?.enabled&&(t.socket.heartbeat.interval>0||(n.push({type:"invalid-input",code:"invalid-heartbeat-interval",message:"Heartbeat interval must be positive",path:"socket.heartbeat.interval",suggestions:[]}),s.push("Set heartbeat interval to positive number in milliseconds")),t.socket.heartbeat.timeout>0||(n.push({type:"invalid-input",code:"invalid-heartbeat-timeout",message:"Heartbeat timeout must be positive",path:"socket.heartbeat.timeout",suggestions:[]}),s.push("Set heartbeat timeout to positive number in milliseconds")),t.socket.heartbeat.interval>t.socket.heartbeat.timeout||(n.push({type:"validation-error",message:"Heartbeat timeout must be less than interval",path:"socket.heartbeat",suggestions:[]}),s.push("Ensure timeout < interval for proper heartbeat detection"))),t.eventHandlers&&t.eventHandlers.forEach((e,t)=>{if(e.filter)try{Function("message","event","return "+e.filter)}catch(r){n.push({type:"invalid-input",code:"invalid-filter-expression",message:"Invalid filter expression: "+e.filter,path:`eventHandlers[${t}].filter`,suggestions:[]}),s.push("Use valid JavaScript expression for message filtering")}e.options?.throttle&&e.options?.debounce&&(n.push({type:"schema-validation",code:"conflicting-performance-options",message:"Cannot use both throttle and debounce on the same event handler",path:`eventHandlers[${t}].options`,suggestions:[]}),s.push("Choose either throttle OR debounce, not both")),e.commands&&0!==e.commands.length||(n.push({type:"empty-config",code:"empty-commands-array",message:"Event handler must have at least one command",path:`eventHandlers[${t}].commands`,suggestions:[]}),s.push("Add at least one command to execute when event occurs"))}),t.messageHandling?.queue&&0>t.messageHandling.queue.maxSize&&(n.push({type:"invalid-input",code:"invalid-queue-size",message:"Queue max size must be non-negative (0 = unlimited)",path:"messageHandling.queue.maxSize",suggestions:[]}),s.push("Set queue maxSize to non-negative number (0 for unlimited)")),t.options?.maxConnections>0||(n.push({type:"invalid-input",code:"invalid-max-connections",message:"Max connections must be positive",path:"options.maxConnections",suggestions:[]}),s.push("Set maxConnections to positive number")),t.options?.connectionTimeout>0||(n.push({type:"invalid-input",code:"invalid-connection-timeout",message:"Connection timeout must be positive",path:"options.connectionTimeout",suggestions:[]}),s.push("Set connectionTimeout to positive number in milliseconds")),{isValid:0===n.length,errors:n,suggestions:s}}catch(e){return{isValid:!1,errors:[{type:"schema-validation",suggestions:[],message:e instanceof Error?e.message:"Invalid input format"}],suggestions:["Ensure input matches SocketsInput schema","Check WebSocket configuration structure","Verify event handler and message handling configurations are valid"]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async createSocketConnection(e,t,n){const s=`socket-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,r={id:s,url:e.url,protocols:e.protocols||[],websocket:null,state:"disconnected",reconnectAttempts:0,totalReconnects:0,messagesSent:0,messagesReceived:0};this.connections.set(s,r),this.messageQueue.set(s,[]);for(const e of t)await this.registerEventHandler(s,e);return r}async registerEventHandler(e,t){const n=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,s={id:n,event:t.event,filter:t.filter,commands:t.commands||[],options:t.options||{},isActive:!0,executionCount:0,lastExecutionTime:0};return this.eventHandlers.set(n,s),s}async connectWebSocket(e){const t=this.connections.get(e);if(!t)return!1;try{return t.state="connecting","undefined"!=typeof WebSocket?(t.websocket=new WebSocket(t.url,t.protocols),t.websocket.onopen=()=>this.handleWebSocketOpen(e),t.websocket.onclose=t=>this.handleWebSocketClose(e,t),t.websocket.onerror=t=>this.handleWebSocketError(e,t),t.websocket.onmessage=t=>this.handleWebSocketMessage(e,t)):(t.state="connected",t.connectedAt=Date.now(),await this.executeEventHandlers(e,"open",null)),!0}catch(n){return t.state="error",t.lastError=n,await this.executeEventHandlers(e,"error",n),!1}}async handleWebSocketOpen(e){const t=this.connections.get(e);t&&(t.state="connected",t.connectedAt=Date.now(),t.reconnectAttempts=0,await this.executeEventHandlers(e,"open",null),await this.processQueuedMessages(e))}async handleWebSocketClose(e,t){const n=this.connections.get(e);n&&(n.state="disconnected",n.disconnectedAt=Date.now(),await this.executeEventHandlers(e,"close",t))}async handleWebSocketError(e,t){const n=this.connections.get(e);n&&(n.state="error",n.lastError=Error("WebSocket error occurred"),await this.executeEventHandlers(e,"error",t))}async handleWebSocketMessage(e,t){const n=this.connections.get(e);if(!n)return;n.messagesReceived++;const s={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,connectionId:e,type:"incoming",data:t.data,format:this.detectMessageFormat(t.data),timestamp:Date.now(),size:this.calculateMessageSize(t.data),validated:!0};c(this.messageHistory,s),await this.executeEventHandlers(e,"message",t)}async executeEventHandlers(e,t,n){const s=Array.from(this.eventHandlers.values()).filter(e=>e.event===t&&e.isActive);for(const e of s)try{if(e.filter&&!this.testMessageFilter(n,e.filter))continue;if(e.options.throttle&&this.isThrottled(e.id,e.options.throttle))continue;if(e.options.debounce){this.applyDebounce(e.id,e.options.debounce,()=>{this.executeHandlerCommands(e,n)});continue}await this.executeHandlerCommands(e,n),e.executionCount++,e.lastExecutionTime=Date.now(),e.options.once&&(e.isActive=!1)}catch(t){c(this.errorHistory,{error:t,timestamp:Date.now(),context:{handler:e,eventData:n}})}}async executeHandlerCommands(e,t){const n={success:!0,executed:e.commands.length};for(const n of e.commands)"object"==typeof n&&n.name&&await this.executeBasicCommand(n,{eventData:t});return n}async executeBasicCommand(e,t){e.name}detectMessageFormat(e){if(e instanceof ArrayBuffer||e instanceof Blob)return"binary";if("string"==typeof e)try{return JSON.parse(e),"json"}catch{return"text"}return"text"}calculateMessageSize(e){return e instanceof ArrayBuffer?e.byteLength:e instanceof Blob?e.size:"string"==typeof e?new Blob([e]).size:0}testMessageFilter(e,t){try{let n=this.filterCache.get(t);return n||(n=Function("message","event","return "+t),this.filterCache.set(t,n)),!!n(e?.data,e)}catch{return!0}}isThrottled(e,t){const n=this.throttleTimers.get(e)||0,s=Date.now();return t>s-n||(this.throttleTimers.set(e,s),!1)}applyDebounce(e,t,n){const s=this.debounceTimers.get(e);s&&clearTimeout(s);const r=setTimeout(n,t);this.debounceTimers.set(e,r)}async processQueuedMessages(e){const t=this.messageQueue.get(e);if(!t||0===t.length)return;const n=this.connections.get(e);if(!n||"connected"!==n.state)return;const s=[];for(const n of t)try{await this.sendMessage(e,n.data,n.format)}catch(e){n.attempts++,n.lastAttempt=Date.now(),n.error=e,n.maxAttempts>n.attempts?s.push(n):c(this.errorHistory,{error:Error(`Message ${n.id} dropped after ${n.maxAttempts} failed attempts`),timestamp:Date.now(),context:{messageId:n.id,data:n.data,format:n.format}})}t.length=0,t.push(...s)}async sendMessage(e,t,n){const s=this.connections.get(e);if(!s||!s.websocket||"connected"!==s.state)return await this.queueMessage(e,t,n),!1;try{let r;switch(n){case"json":r=JSON.stringify(t);break;case"binary":r=t instanceof ArrayBuffer?t:new ArrayBuffer(0);break;default:r=t+""}if(s.websocket.readyState===WebSocket.OPEN){s.websocket.send(r),s.messagesSent++;const a={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,connectionId:e,type:"outgoing",data:t,format:n,timestamp:Date.now(),size:this.calculateMessageSize(r),validated:!0};return c(this.messageHistory,a),!0}return!1}catch(s){return await this.queueMessage(e,t,n),!1}}async queueMessage(e,t,n){const s=this.messageQueue.get(e);if(!s)return;const r={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,data:t,format:n,timestamp:Date.now(),attempts:0,maxAttempts:3};s.push(r);s.length>100&&s.shift()}createConnectionEstablisher(e){return async e=>{if("string"==typeof e)return await this.connectWebSocket(e);{const t=e||{url:"wss://localhost:8080",protocols:[],reconnect:{enabled:!0},heartbeat:{enabled:!1},compression:!1,binaryType:"blob"},n=await this.createSocketConnection(t,[],{});return await this.connectWebSocket(n.id)}}}createConnectionTerminator(){return async e=>{const t=this.connections.get(e);return!!t&&(t.state="disconnecting",t.websocket&&t.websocket.close(),t.state="disconnected",t.disconnectedAt=Date.now(),await this.executeEventHandlers(e,"close",null),!0)}}createReconnector(){return async e=>{const t=this.connections.get(e);return!!t&&(t.websocket&&t.websocket.close(),t.reconnectAttempts++,t.totalReconnects++,await this.connectWebSocket(e))}}createConnectionChecker(){return e=>{const t=this.connections.get(e);return"connected"===t?.state||!1}}createStateGetter(){return e=>{const t=this.connections.get(e);return t?.state||"disconnected"}}createConnectionInfoGetter(){return e=>{const t=this.connections.get(e);if(!t)return null;return{connectionId:t.id,...void 0!==t.connectedAt&&{connectedAt:t.connectedAt},totalReconnects:t.totalReconnects,messagesSent:t.messagesSent,messagesReceived:t.messagesReceived,bytesTransmitted:0,bytesReceived:0,averageLatency:0,errorCount:this.errorHistory.filter(t=>t.context?.connectionId===e).length,uptime:t.connectedAt?Date.now()-t.connectedAt:0}}}createMessageSender(){return async(e,t,n="text")=>await this.sendMessage(e,t,n)}createJSONSender(){return async(e,t)=>await this.sendMessage(e,t,"json")}createBinarySender(){return async(e,t)=>await this.sendMessage(e,t,"binary")}createMessageSubscriber(){return(e,t)=>this.registerEventHandler("*",{event:e,commands:[t]})}createMessageUnsubscriber(){return e=>this.eventHandlers.delete(e)}createMessageHistoryGetter(){return(e,t)=>{let n=this.messageHistory;return e&&(n=n.filter(t=>t.connectionId===e)),t&&(n=n.slice(-t)),n}}createEventHandlerAdder(){return async(e,t,n)=>await this.registerEventHandler(e,{event:t,commands:[n],options:{}})}createEventHandlerRemover(){return e=>this.eventHandlers.delete(e)}createEventEmitter(){return async(e,t,n)=>(await this.executeEventHandlers(e,t,n),!0)}createHandlerGetter(){return e=>e?Array.from(this.eventHandlers.values()).filter(t=>t.id.includes(e)):Array.from(this.eventHandlers.values())}createQueueAdder(){return async(e,t,n="json")=>(await this.queueMessage(e,t,n),!0)}createQueueProcessor(){return async e=>(await this.processQueuedMessages(e),!0)}createQueueClearer(){return e=>{const t=this.messageQueue.get(e);return!!t&&(t.length=0,!0)}}createQueueSizeGetter(){return e=>{const t=this.messageQueue.get(e);return t?t.length:0}}createPendingGetter(){return e=>{const t=this.messageQueue.get(e);return t?t.slice():[]}}createErrorHandler(){return async(e,t)=>(c(this.errorHistory,{error:e,timestamp:Date.now(),context:{connectionId:t}}),!0)}createErrorHistoryGetter(){return e=>e?this.errorHistory.slice(-e):this.errorHistory.slice()}createErrorClearer(){return()=>(this.errorHistory=[],!0)}createErrorHandlerSetter(){return e=>!0}dispose(){for(const e of this.connections.values())e.websocket&&e.websocket.close();this.connections.clear();for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(const e of this.throttleTimers.values())clearTimeout(e);this.throttleTimers.clear(),this.eventHandlers.clear(),this.messageQueue.clear(),this.filterCache.clear(),this.messageHistory=[],this.errorHistory=[],this.evaluationHistory=[]}trackPerformance(e,t,n){c(this.evaluationHistory,{input:{},output:n,success:t,duration:Date.now()-e,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,t)=>e+t.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalConnections:this.connections.size,totalHandlers:this.eventHandlers.size,totalMessages:this.messageHistory.length,totalErrors:this.errorHistory.length,queuedMessages:Array.from(this.messageQueue.values()).reduce((e,t)=>e+t.length,0)}}}const m=new d;var h=Object.freeze({__proto__:null,SocketsInputSchema:u,SocketsOutputSchema:l,TypedSocketsFeatureImplementation:d,createSockets:async function(e,t){return(new d).initialize({socket:{url:"wss://localhost:8080",protocols:[],reconnect:{enabled:!0,maxAttempts:5,delay:1e3,backoff:"exponential",maxDelay:3e4},heartbeat:{enabled:!1,interval:3e4,message:"ping",timeout:5e3},compression:!1,binaryType:"blob",...e},eventHandlers:[],messageHandling:{format:"json",validation:{enabled:!0},queue:{enabled:!0,maxSize:100,persistence:!1}},context:{variables:{}},options:{enableAutoConnect:!0,enableMessageQueue:!0,enableErrorHandling:!0,maxConnections:5,connectionTimeout:1e4},environment:"frontend",debug:!1,...t})},createSocketsFeature:function(){return new d},enhancedSocketsImplementation:m});export{h as s,o as v,i as z};
|
|
2
|
+
//# sourceMappingURL=feature-sockets-CrYvjZ4j.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{v as e,z as r}from"./feature-sockets-CrYvjZ4j.js";function t(e,r,t=1e3){e.push(r),e.length>t&&e.shift()}const s=e.object({worker:r.object({script:e.string().min(1),type:r.enum(["module","classic"]).default("classic"),name:e.string().optional(),credentials:r.enum(["omit","same-origin","include"]).default("same-origin"),inline:e.boolean().default(!1)}),messaging:e.object({format:r.enum(["json","text","binary"]).default("json"),serialization:r.enum(["structured-clone","json"]).default("structured-clone"),transferables:e.array(e.string()).default([]),validation:r.object({enabled:e.boolean().default(!0),schema:e.any().optional()}).default({}),queue:e.object({enabled:e.boolean().default(!0),maxSize:e.number().min(0).default(100),persistence:e.boolean().default(!1)}).default({})}).default({}),eventHandlers:e.array(e.object({event:r.enum(["message","error","messageerror"]),commands:e.array(e.any()).min(1),filter:e.string().optional(),options:r.object({throttle:e.number().optional(),debounce:e.number().optional()}).optional()})).default([]),context:e.object({variables:r.record(e.string(),e.any()).default({}),me:e.any().optional(),it:e.any().optional(),target:e.any().optional()}).default({}),options:e.object({enableAutoStart:e.boolean().default(!0),enableMessageQueue:e.boolean().default(!0),enableErrorHandling:e.boolean().default(!0),maxWorkers:e.number().default(4),workerTimeout:e.number().default(3e4),terminationTimeout:e.number().default(5e3)}).default({}),environment:r.enum(["frontend","backend","universal"]).default("frontend"),debug:e.boolean().default(!1)}),n=e.object({contextId:e.string(),timestamp:e.number(),category:e.literal("Frontend"),capabilities:e.array(e.string()),state:r.enum(["ready","starting","running","terminating","terminated","error"]),workers:r.object({create:e.any(),terminate:e.any(),restart:e.any(),getWorker:e.any(),listWorkers:e.any(),getWorkerInfo:e.any()}),messaging:e.object({send:e.any(),sendJSON:e.any(),sendBinary:e.any(),broadcast:e.any(),getMessageHistory:e.any(),subscribe:e.any(),unsubscribe:e.any()}),events:e.object({addHandler:e.any(),removeHandler:e.any(),getHandlers:e.any(),emit:e.any()}),queue:e.object({add:e.any(),process:e.any(),getSize:e.any(),getPending:e.any(),clear:e.any()}),errors:e.object({handle:e.any(),getErrorHistory:e.any(),clearErrors:e.any(),setErrorHandler:e.any()})});class a{constructor(){this.name="webworkerFeature",this.category="Frontend",this.description="Type-safe Web Worker management feature with message handling, event processing, and comprehensive error management",this.inputSchema=s,this.outputType="Context",this.evaluationHistory=[],this.workers=new Map,this.messageHistory=[],this.eventHandlers=new Map,this.messageQueue=new Map,this.errorHistory=[],this.throttleTimers=new Map,this.debounceTimers=new Map,this.filterCache=new Map,this.metadata={category:"Frontend",complexity:"complex",sideEffects:["worker-creation","message-passing","background-execution"],dependencies:["web-worker-api","message-channel","transferable-objects"],returnTypes:["Context"],examples:[{input:'{ worker: { script: "./worker.js" }, messaging: { format: "json" } }',description:"Create a Web Worker for background JavaScript execution",expectedOutput:"TypedWebWorkerContext with worker management and message handling"},{input:'{ worker: { script: "self.onmessage = e => self.postMessage(e.data * 2)", inline: true } }',description:"Create inline worker for simple calculations",expectedOutput:"Worker context with inline script execution"},{input:'{ worker: { script: "./data-processor.js", type: "module" }, messaging: { transferables: ["ArrayBuffer"] } }',description:"Module worker with transferable object support for large data processing",expectedOutput:"High-performance worker context with zero-copy data transfer"}],relatedExpressions:[],relatedContexts:["socketsFeature","onFeature","executionContext"],frameworkDependencies:["web-worker-api","hyperscript-runtime"],environmentRequirements:{browser:!0,server:!1,nodejs:!1},performance:{averageTime:25,complexity:"O(n)"}},this.documentation={summary:"Creates and manages Web Workers for background JavaScript execution with type-safe message handling, event processing, and comprehensive error recovery",parameters:[{name:"workerConfig",type:"WebWorkerInput",description:"Web Worker configuration including script source, messaging format, event handlers, and performance options",optional:!1,examples:['{ worker: { script: "./worker.js" }, messaging: { format: "json" } }','{ worker: { script: "worker-code", inline: true }, options: { maxWorkers: 2 } }','{ worker: { script: "./module-worker.js", type: "module" }, messaging: { transferables: ["ArrayBuffer"] } }']}],returns:{type:"WebWorkerContext",description:"Web Worker management context with worker lifecycle, message handling, queue management, and error recovery capabilities",examples:["context.workers.create(config) → worker instance ID","context.messaging.sendJSON(workerId, data) → send JSON message to worker","context.queue.add(workerId, message) → queue message for worker","context.workers.terminate(workerId) → gracefully terminate worker"]},examples:[{title:"Basic worker creation",code:'const workerContext = await createWebWorkerFeature({ worker: { script: "./calc-worker.js" } })',explanation:"Create a Web Worker for background calculations",output:"Worker context with calculation worker ready"},{title:"Message passing with transferables",code:'await workerContext.messaging.sendBinary(workerId, arrayBuffer, ["ArrayBuffer"])',explanation:"Send large binary data to worker using transferable objects for zero-copy transfer",output:"High-performance message transfer without copying data"},{title:"Worker event handling",code:'await workerContext.events.addHandler(workerId, "message", { name: "processResult", args: [] })',explanation:"Add event handler for worker messages with command execution",output:"Event-driven worker communication with hyperscript integration"}],seeAlso:["socketsFeature","onFeature","messagingSystem","backgroundExecution"],tags:["webworkers","background-execution","message-passing","transferables","type-safe","enhanced-pattern"]}}async initialize(e){const r=Date.now();try{const t=this.validate(e);if(!t.isValid)return{success:!1,error:t.errors[0]};const s=await this.initializeConfig(e),n={contextId:"webworker-"+Date.now(),timestamp:r,category:"Frontend",capabilities:["worker-management","message-handling","background-execution","transferable-objects","error-recovery"],state:"ready",workers:{create:this.createWorkerCreator(s),terminate:this.createWorkerTerminator(),restart:this.createWorkerRestarter(),getWorker:this.createWorkerGetter(),listWorkers:this.createWorkerLister(),getWorkerInfo:this.createWorkerInfoGetter()},messaging:{send:this.createMessageSender(),sendJSON:this.createJSONSender(),sendBinary:this.createBinarySender(),broadcast:this.createBroadcaster(),getMessageHistory:this.createMessageHistoryGetter(),subscribe:this.createMessageSubscriber(),unsubscribe:this.createMessageUnsubscriber()},events:{addHandler:this.createEventHandlerAdder(),removeHandler:this.createEventHandlerRemover(),getHandlers:this.createEventHandlerGetter(),emit:this.createEventEmitter()},queue:{add:this.createQueueAdder(),process:this.createQueueProcessor(),getSize:this.createQueueSizeGetter(),getPending:this.createPendingGetter(),clear:this.createQueueClearer()},errors:{handle:this.createErrorHandler(),getErrorHistory:this.createErrorHistoryGetter(),clearErrors:this.createErrorClearer(),setErrorHandler:this.createErrorHandlerSetter()}};return e.worker.script&&!1!==e.options?.enableAutoStart&&await this.createWorker(e.worker,e.context||{}),this.trackPerformance(r,!0,n),{success:!0,value:n,type:"object"}}catch(e){return this.trackPerformance(r,!1),{success:!1,error:{type:"runtime-error",message:"WebWorker feature initialization failed: "+(e instanceof Error?e.message:e+""),suggestions:["Verify worker script URL is accessible","Check browser supports Web Workers","Ensure script has valid JavaScript syntax","Validate worker configuration parameters"]}}}}validate(e){try{if(!e||"object"!=typeof e)return{isValid:!1,errors:[{type:"invalid-input",message:"Input must be an object",suggestions:[]}],suggestions:["Provide a valid Web Worker configuration object"]};const r=e,t=[],s=[];if(void 0!==r.messaging?.queue?.maxSize&&0>r.messaging.queue.maxSize&&(t.push({type:"invalid-input",code:"invalid-queue-size",message:"Queue size must be non-negative (0 = unlimited)",path:"messaging.queue.maxSize",suggestions:[]}),s.push("Set queue maxSize to 0 for unlimited or positive number for limit")),r.eventHandlers&&Array.isArray(r.eventHandlers))for(const e of r.eventHandlers)e.commands&&Array.isArray(e.commands)&&0===e.commands.length&&(t.push({type:"empty-config",code:"empty-commands-array",message:"Event handler commands array cannot be empty",path:"eventHandlers.commands",suggestions:[]}),s.push("Add at least one command to execute for event handler"));if(t.length>0)return{isValid:!1,errors:t,suggestions:s};const n=e;if(n.worker&&"string"==typeof n.worker.script&&n.worker.script||(t.push({type:"invalid-input",code:"missing-worker-script",message:"Worker configuration must include a script URL or inline source",path:"worker.script",suggestions:[]}),s.push('Provide a worker script URL (e.g., "./worker.js") or inline script')),n.worker&&"string"==typeof n.worker.script&&n.worker.script&&(n.worker.inline||this.isValidWorkerScript(n.worker.script)||(t.push({type:"invalid-input",code:"invalid-worker-script",message:`Invalid worker script: "${n.worker.script}"`,path:"worker.script",suggestions:[]}),s.push("Provide valid JavaScript file URL or inline script code")),n.worker.inline))try{"module"===n.worker.type&&n.worker.script.includes("import")||Function(n.worker.script)}catch(e){t.push({type:"syntax-error",code:"invalid-inline-script",message:"Invalid inline script syntax: "+n.worker.script,path:"worker.script",suggestions:[]}),s.push("Ensure inline script has valid JavaScript syntax")}if(n.options&&(1>n.options.maxWorkers&&(t.push({type:"invalid-input",code:"invalid-max-workers",message:"maxWorkers must be at least 1",path:"options.maxWorkers",suggestions:[]}),s.push("Set maxWorkers to at least 1")),1e3>n.options.workerTimeout&&(t.push({type:"invalid-input",code:"invalid-worker-timeout",message:"Worker timeout must be at least 1000ms",path:"options.workerTimeout",suggestions:[]}),s.push("Set worker timeout to at least 1000ms for proper operation")),1e3>n.options.terminationTimeout&&(t.push({type:"invalid-input",code:"invalid-termination-timeout",message:"Termination timeout must be at least 1000ms",path:"options.terminationTimeout",suggestions:[]}),s.push("Set termination timeout to at least 1000ms for graceful shutdown"))),n.eventHandlers&&n.eventHandlers.length>0)for(const e of n.eventHandlers)if(e.options?.throttle&&e.options?.debounce&&(t.push({type:"schema-validation",code:"conflicting-performance-options",message:"Cannot use both throttle and debounce simultaneously",path:"eventHandlers.options",suggestions:[]}),s.push("Choose either throttle OR debounce, not both")),e.filter)try{Function("message","return "+e.filter)}catch(r){t.push({type:"invalid-input",code:"invalid-filter-expression",message:"Invalid filter expression: "+e.filter,path:"eventHandlers.filter",suggestions:[]}),s.push("Use valid JavaScript expression for message filtering")}return"undefined"==typeof Worker&&(t.push({type:"runtime-error",message:"Web Workers are not supported in this environment",suggestions:[]}),s.push("Web Workers require a browser environment")),{isValid:0===t.length,errors:t,suggestions:s}}catch(e){return{isValid:!1,errors:[{type:"schema-validation",suggestions:[],message:e instanceof Error?e.message:"Invalid input format"}],suggestions:["Ensure input matches WebWorkerInput schema","Check worker configuration structure","Verify messaging and event handler configurations"]}}}async initializeConfig(e){return{...e.options,environment:e.environment,debug:e.debug,initialized:Date.now()}}async createWorker(e,r){const t=`worker-${Date.now()}-${Math.random().toString(36).substring(2,11)}`;let s;if(e.inline){const r=new Blob([e.script],{type:"application/javascript"}),n=URL.createObjectURL(r);s=new Worker(n,{type:e.type||"classic",name:e.name||t}),setTimeout(()=>URL.revokeObjectURL(n),0)}else s=new Worker(e.script,{type:e.type||"classic",name:e.name||t});const n={id:t,name:e.name,worker:s,script:e.script,type:e.type||"classic",state:"starting",createdAt:Date.now(),lastMessageTime:0,messageCount:0,errorCount:0,isTerminating:!1};return s.onmessage=e=>{n.messageCount++,n.lastMessageTime=Date.now(),this.handleWorkerMessage(n,e)},s.onerror=e=>{n.errorCount++,n.state="error",this.handleWorkerError(n,e)},s.onmessageerror=e=>{n.errorCount++,this.handleWorkerMessageError(n,e)},this.workers.set(t,n),n.state="running",n}handleWorkerMessage(e,r){const s={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,workerId:e.id,type:"incoming",data:r.data,timestamp:Date.now(),format:this.detectMessageFormat(r.data)};t(this.messageHistory,s),this.processEventHandlers(e.id,"message",r)}handleWorkerError(e,r){t(this.errorHistory,{error:Error("Worker error: "+r.message),timestamp:Date.now(),context:{worker:e,event:r}}),this.processEventHandlers(e.id,"error",r)}handleWorkerMessageError(e,r){t(this.errorHistory,{error:Error("Worker message error: Failed to deserialize message"),timestamp:Date.now(),context:{worker:e,event:r}}),this.processEventHandlers(e.id,"messageerror",r)}processEventHandlers(e,r,t){const s=Array.from(this.eventHandlers.values()).filter(t=>t.workerId===e&&t.eventType===r&&t.isActive);for(const e of s)this.executeEventHandler(e,t)}async executeEventHandler(e,r){try{if(e.filter&&!this.testMessageFilter(r,e.filter))return;if(e.options?.throttle&&this.isThrottled(e.id,e.options.throttle))return;if(e.options?.debounce)return void this.applyDebounce(e.id,e.options.debounce,()=>{this.executeCommands(e.commands,{event:r})});await this.executeCommands(e.commands,{event:r}),e.executionCount++,e.lastExecutionTime=Date.now()}catch(s){t(this.errorHistory,{error:s,timestamp:Date.now(),context:{handler:e,event:r}})}}async executeCommands(e,r){const t={success:!0,executed:e.length};for(const t of e)"object"==typeof t&&t.name&&await this.executeBasicCommand(t,r);return t}async executeBasicCommand(e,r){e.name}isValidWorkerScript(e){return!(!e.startsWith("http://")&&!e.startsWith("https://"))||!!(e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))}detectMessageFormat(e){return e instanceof ArrayBuffer||e instanceof Uint8Array?"binary":"string"==typeof e?"text":"json"}testMessageFilter(e,r){try{let t=this.filterCache.get(r);return t||(t=Function("message","return "+r),this.filterCache.set(r,t)),!!t(e)}catch{return!0}}isThrottled(e,r){const t=this.throttleTimers.get(e)||0,s=Date.now();return r>s-t||(this.throttleTimers.set(e,s),!1)}applyDebounce(e,r,t){const s=this.debounceTimers.get(e);s&&clearTimeout(s);const n=setTimeout(t,r);this.debounceTimers.set(e,n)}createWorkerCreator(e){return async r=>{if(this.workers.size>=(e.maxWorkers||4))throw Error("Maximum number of workers reached");return await this.createWorker(r,{})}}createWorkerTerminator(){return async(e,r)=>{const t=this.workers.get(e);if(!t)return!1;t.isTerminating=!0,t.state="terminating";return setTimeout(()=>{"terminating"===t.state&&(t.worker.terminate(),t.state="terminated",this.workers.delete(e))},r||5e3),!0}}createWorkerRestarter(){return async e=>{const r=this.workers.get(e);if(!r)return!1;r.worker.terminate(),this.workers.delete(e);return(await this.createWorker({script:r.script,type:r.type,name:r.name,inline:!1},{})).id}}createWorkerGetter(){return e=>this.workers.get(e)||null}createWorkerLister(){return()=>Array.from(this.workers.keys())}createWorkerInfoGetter(){return e=>{const r=this.workers.get(e);return r?{id:r.id,name:r.name,state:r.state,createdAt:r.createdAt,messageCount:r.messageCount,errorCount:r.errorCount,lastMessageTime:r.lastMessageTime}:null}}createMessageSender(){return async(e,r,s)=>{const n=this.workers.get(e);if(!n||"running"!==n.state)return!1;try{n.worker.postMessage(r,s||[]);const a={id:`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,workerId:e,type:"outgoing",data:r,...s&&{transferables:s},timestamp:Date.now(),format:this.detectMessageFormat(r)};return t(this.messageHistory,a),!0}catch(s){return t(this.errorHistory,{error:s,timestamp:Date.now(),context:{workerId:e,data:r}}),!1}}}createJSONSender(){return async(e,r)=>await this.createMessageSender()(e,r)}createBinarySender(){return async(e,r)=>{const t=r instanceof ArrayBuffer?[r]:[];return await this.createMessageSender()(e,r,t)}}createBroadcaster(){return async(e,r)=>{const t=[];for(const s of this.workers.keys()){const n=await this.createMessageSender()(s,e,r);t.push(n)}return t.every(e=>e)}}createMessageHistoryGetter(){return(e,r)=>{let t=this.messageHistory;return e&&(t=t.filter(r=>r.workerId===e)),r&&(t=t.slice(-r)),t}}createMessageSubscriber(){return async(e,r)=>{const t=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`;return this.eventHandlers.set(t,{id:t,workerId:"",eventType:e,commands:[r],isActive:!0,executionCount:0,lastExecutionTime:0}),t}}createMessageUnsubscriber(){return e=>this.eventHandlers.delete(e)}createEventHandlerAdder(){return async(e,r,t)=>{const s=`handler-${Date.now()}-${Math.random().toString(36).substring(2,11)}`;return this.eventHandlers.set(s,{id:s,workerId:e,eventType:r,commands:[t],isActive:!0,executionCount:0,lastExecutionTime:0}),s}}createEventHandlerRemover(){return e=>this.eventHandlers.delete(e)}createEventHandlerGetter(){return e=>e?Array.from(this.eventHandlers.values()).filter(r=>r.workerId===e):Array.from(this.eventHandlers.values())}createEventEmitter(){return async(e,r,t)=>!0}createQueueAdder(){return async(e,r)=>{this.messageQueue.has(e)||this.messageQueue.set(e,[]);return this.messageQueue.get(e).push({id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,workerId:e,type:"outgoing",data:r,timestamp:Date.now(),format:this.detectMessageFormat(r)}),!0}}createQueueProcessor(){return async e=>{const r=this.messageQueue.get(e);if(!r||0===r.length)return!0;const s=this.workers.get(e);if(!s||"running"!==s.state)return!1;try{for(const e of r)s.worker.postMessage(e.data),t(this.messageHistory,e);return r.length=0,!0}catch(s){return t(this.errorHistory,{error:s,timestamp:Date.now(),context:{workerId:e,queueSize:r.length}}),!1}}}createQueueSizeGetter(){return e=>{const r=this.messageQueue.get(e);return r?r.length:0}}createPendingGetter(){return e=>{const r=this.messageQueue.get(e);return r?r.slice():[]}}createQueueClearer(){return e=>{const r=this.messageQueue.get(e);return!!r&&(r.length=0,!0)}}createErrorHandler(){return async(e,r)=>(t(this.errorHistory,{error:e,timestamp:Date.now(),context:r}),!0)}createErrorHistoryGetter(){return e=>e?this.errorHistory.slice(-e):this.errorHistory.slice()}createErrorClearer(){return()=>(this.errorHistory=[],!0)}createErrorHandlerSetter(){return e=>!0}dispose(){for(const e of this.workers.values())e.worker.terminate();this.workers.clear();for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(const e of this.throttleTimers.values())clearTimeout(e);this.throttleTimers.clear(),this.eventHandlers.clear(),this.messageQueue.clear(),this.filterCache.clear(),this.messageHistory=[],this.errorHistory=[],this.evaluationHistory=[]}trackPerformance(e,r,s){t(this.evaluationHistory,{input:{},output:s,success:r,duration:Date.now()-e,timestamp:e})}getPerformanceMetrics(){return{totalInitializations:this.evaluationHistory.length,successRate:this.evaluationHistory.filter(e=>e.success).length/Math.max(this.evaluationHistory.length,1),averageDuration:this.evaluationHistory.reduce((e,r)=>e+r.duration,0)/Math.max(this.evaluationHistory.length,1),lastEvaluationTime:this.evaluationHistory[this.evaluationHistory.length-1]?.timestamp||0,evaluationHistory:this.evaluationHistory.slice(-10),totalWorkers:this.workers.size,totalMessages:this.messageHistory.length,totalErrors:this.errorHistory.length,totalEventHandlers:this.eventHandlers.size,queuedMessages:Array.from(this.messageQueue.values()).reduce((e,r)=>e+r.length,0)}}}function o(){return new a}async function i(e,r){return(new a).initialize({worker:{script:"",type:"classic",credentials:"same-origin",inline:!1,...e},messaging:{format:"json",serialization:"structured-clone",transferables:[],validation:{enabled:!0},queue:{enabled:!0,maxSize:100,persistence:!1}},eventHandlers:[],context:{variables:{}},options:{enableAutoStart:!0,enableMessageQueue:!0,enableErrorHandling:!0,maxWorkers:4,workerTimeout:3e4,terminationTimeout:5e3},environment:"frontend",debug:!1,...r})}const c=new a;export{a as TypedWebWorkerFeatureImplementation,s as WebWorkerInputSchema,n as WebWorkerOutputSchema,i as createWebWorker,o as createWebWorkerFeature,c as enhancedWebWorkerImplementation};
|
|
2
|
+
//# sourceMappingURL=feature-webworker-BSYguEIW.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
let t=null;async function n(){if(!t)try{t=await import("./browser-modular-BwIRlrTM.js").then(function(t){return t.j})}catch{throw Error("@lokascript/framework is required for LSE support. Install it: npm install @lokascript/framework")}return t}function r(){if(t)return!0;try{return require.resolve("@lokascript/framework"),!0}catch{return!1}}async function a(t,r){return(await n()).parseExplicit(t,r)}async function o(t){return(await n()).isExplicitSyntax(t)}async function i(t){return(await n()).renderExplicit(t)}async function e(t){return(await n()).fromInterchangeNode(t)}async function c(t){return(await n()).toProtocolJSON(t)}async function u(t){return(await n()).fromProtocolJSON(t)}async function s(t){return(await n()).validateProtocolJSON(t)}async function f(t){return(await n()).toEnvelopeJSON(t)}async function l(t){return(await n()).fromEnvelopeJSON(t)}async function w(t){return(await n()).isEnvelope(t)}async function p(t){return(await n()).semanticNodeToRuntimeAST(t)}export{l as fromEnvelopeJSON,e as fromInterchangeNode,u as fromProtocolJSON,w as isEnvelope,o as isExplicitSyntax,r as isLSEAvailable,a as parseExplicit,i as renderExplicit,p as semanticNodeToRuntimeAST,f as toEnvelopeJSON,c as toProtocolJSON,s as validateProtocolJSON};
|
|
2
|
+
//# sourceMappingURL=index-Beno_SBy.js.map
|
|
@@ -2,12 +2,16 @@ import type { ExecutionContext, TypedExecutionContext } from '../../types/core';
|
|
|
2
2
|
import type { ASTNode, ExpressionNode } from '../../types/base-types';
|
|
3
3
|
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
4
4
|
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
5
|
+
type AsyncCommandItem = ASTNode | ((context: TypedExecutionContext) => unknown | Promise<unknown>) | {
|
|
6
|
+
name?: string;
|
|
7
|
+
execute(context: TypedExecutionContext): unknown | Promise<unknown>;
|
|
8
|
+
};
|
|
5
9
|
export interface AsyncCommandInput {
|
|
6
|
-
commands:
|
|
10
|
+
commands: AsyncCommandItem[];
|
|
7
11
|
}
|
|
8
12
|
export interface AsyncCommandOutput {
|
|
9
13
|
commandCount: number;
|
|
10
|
-
results:
|
|
14
|
+
results: unknown[];
|
|
11
15
|
executed: boolean;
|
|
12
16
|
duration: number;
|
|
13
17
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ExecutionContext, TypedExecutionContext } from '../../types/core';
|
|
2
|
+
import type { ASTNode, ExpressionNode } from '../../types/base-types';
|
|
3
|
+
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
4
|
+
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
5
|
+
export interface StartViewTransitionInput {
|
|
6
|
+
transitionName?: string;
|
|
7
|
+
body: ASTNode[];
|
|
8
|
+
}
|
|
9
|
+
export interface StartViewTransitionOutput {
|
|
10
|
+
usedViewTransition: boolean;
|
|
11
|
+
commandsExecuted: number;
|
|
12
|
+
}
|
|
13
|
+
export declare class StartViewTransitionCommand implements DecoratedCommand {
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly metadata: CommandMetadata;
|
|
16
|
+
parseInput(raw: {
|
|
17
|
+
args: ASTNode[];
|
|
18
|
+
modifiers: Record<string, ExpressionNode>;
|
|
19
|
+
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<StartViewTransitionInput>;
|
|
20
|
+
execute(input: StartViewTransitionInput, context: TypedExecutionContext): Promise<StartViewTransitionOutput>;
|
|
21
|
+
}
|
|
22
|
+
export declare const createStartViewTransitionCommand: () => StartViewTransitionCommand;
|
|
23
|
+
export default StartViewTransitionCommand;
|
|
24
|
+
//# sourceMappingURL=start-view-transition.d.ts.map
|
|
@@ -9,16 +9,21 @@ export interface FetchResponseTypeConfig {
|
|
|
9
9
|
}
|
|
10
10
|
export declare function registerFetchResponseType(name: string, config: FetchResponseTypeConfig): void;
|
|
11
11
|
export declare function getCustomResponseType(name: string): FetchResponseTypeConfig | undefined;
|
|
12
|
+
export declare function registerFetchThrowsOn(patterns: RegExp[]): void;
|
|
13
|
+
export declare function resetFetchThrowsOn(): void;
|
|
14
|
+
export declare function shouldThrowOnStatus(status: number): boolean;
|
|
12
15
|
export interface FetchCommandInput {
|
|
13
16
|
url: string;
|
|
14
17
|
responseType: string;
|
|
15
18
|
options: RequestInit;
|
|
19
|
+
throwOnError?: boolean;
|
|
16
20
|
}
|
|
21
|
+
export type FetchResponseData = string | Response | Blob | ArrayBuffer | DocumentFragment | HTMLElement | null | unknown;
|
|
17
22
|
export interface FetchCommandOutput {
|
|
18
23
|
status: number;
|
|
19
24
|
statusText: string;
|
|
20
25
|
headers: Headers;
|
|
21
|
-
data:
|
|
26
|
+
data: FetchResponseData;
|
|
22
27
|
url: string;
|
|
23
28
|
duration: number;
|
|
24
29
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ExecutionContext, TypedExecutionContext, ASTNode, ExpressionNode } from '../../types/base-types';
|
|
2
|
+
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
3
|
+
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
4
|
+
export type ClearCommandInput = {
|
|
5
|
+
type: 'variable';
|
|
6
|
+
name: string;
|
|
7
|
+
} | {
|
|
8
|
+
type: 'form-fields';
|
|
9
|
+
targets: HTMLElement[];
|
|
10
|
+
};
|
|
11
|
+
export declare class ClearCommand implements DecoratedCommand {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly metadata: CommandMetadata;
|
|
14
|
+
parseInput(raw: {
|
|
15
|
+
args: ASTNode[];
|
|
16
|
+
modifiers: Record<string, ExpressionNode>;
|
|
17
|
+
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<ClearCommandInput>;
|
|
18
|
+
execute(input: ClearCommandInput, context: TypedExecutionContext): Promise<void>;
|
|
19
|
+
validate(input: unknown): input is ClearCommandInput;
|
|
20
|
+
}
|
|
21
|
+
export declare const createClearCommand: () => ClearCommand;
|
|
22
|
+
export default ClearCommand;
|
|
23
|
+
//# sourceMappingURL=clear.d.ts.map
|
|
@@ -2,6 +2,7 @@ import type { ExecutionContext, TypedExecutionContext } from '../../types/core';
|
|
|
2
2
|
import type { ASTNode, ExpressionNode } from '../../types/base-types.ts';
|
|
3
3
|
import type { ExpressionEvaluator } from '../../core/expression-evaluator.ts';
|
|
4
4
|
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
5
|
+
import { type NodeWriterFn } from '../../parser/extensions';
|
|
5
6
|
export type SetCommandInput = {
|
|
6
7
|
type: 'variable';
|
|
7
8
|
name: string;
|
|
@@ -30,6 +31,11 @@ export type SetCommandInput = {
|
|
|
30
31
|
container: Record<string, unknown>;
|
|
31
32
|
property: string;
|
|
32
33
|
value: unknown;
|
|
34
|
+
} | {
|
|
35
|
+
type: 'node-write';
|
|
36
|
+
node: ASTNode;
|
|
37
|
+
value: unknown;
|
|
38
|
+
writer: NodeWriterFn;
|
|
33
39
|
};
|
|
34
40
|
export interface SetCommandOutput {
|
|
35
41
|
target: string | HTMLElement;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ExecutionContext, TypedExecutionContext, ASTNode, ExpressionNode } from '../../types/base-types';
|
|
2
|
+
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
3
|
+
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
4
|
+
export interface CloseCommandInput {
|
|
5
|
+
targets: HTMLElement[];
|
|
6
|
+
}
|
|
7
|
+
export declare class CloseCommand implements DecoratedCommand {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly metadata: CommandMetadata;
|
|
10
|
+
parseInput(raw: {
|
|
11
|
+
args: ASTNode[];
|
|
12
|
+
modifiers: Record<string, ExpressionNode>;
|
|
13
|
+
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<CloseCommandInput>;
|
|
14
|
+
execute(input: CloseCommandInput, _context: TypedExecutionContext): Promise<void>;
|
|
15
|
+
validate(input: unknown): input is CloseCommandInput;
|
|
16
|
+
}
|
|
17
|
+
export declare const createCloseCommand: () => CloseCommand;
|
|
18
|
+
export default CloseCommand;
|
|
19
|
+
//# sourceMappingURL=close.d.ts.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ExecutionContext, TypedExecutionContext, ASTNode, ExpressionNode } from '../../types/base-types';
|
|
2
|
+
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
3
|
+
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
4
|
+
export interface EmptyCommandInput {
|
|
5
|
+
targets: HTMLElement[];
|
|
6
|
+
}
|
|
7
|
+
export declare class EmptyCommand implements DecoratedCommand {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly metadata: CommandMetadata;
|
|
10
|
+
parseInput(raw: {
|
|
11
|
+
args: ASTNode[];
|
|
12
|
+
modifiers: Record<string, ExpressionNode>;
|
|
13
|
+
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<EmptyCommandInput>;
|
|
14
|
+
execute(input: EmptyCommandInput, _context: TypedExecutionContext): Promise<void>;
|
|
15
|
+
validate(input: unknown): input is EmptyCommandInput;
|
|
16
|
+
}
|
|
17
|
+
export declare const createEmptyCommand: () => EmptyCommand;
|
|
18
|
+
export default EmptyCommand;
|
|
19
|
+
//# sourceMappingURL=empty.d.ts.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ExecutionContext, TypedExecutionContext, ASTNode, ExpressionNode } from '../../types/base-types';
|
|
2
|
+
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
3
|
+
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
4
|
+
export type OpenDialogMode = 'modal' | 'non-modal';
|
|
5
|
+
export interface OpenCommandInput {
|
|
6
|
+
targets: HTMLElement[];
|
|
7
|
+
dialogMode: OpenDialogMode;
|
|
8
|
+
}
|
|
9
|
+
export declare class OpenCommand implements DecoratedCommand {
|
|
10
|
+
readonly name: string;
|
|
11
|
+
readonly metadata: CommandMetadata;
|
|
12
|
+
parseInput(raw: {
|
|
13
|
+
args: ASTNode[];
|
|
14
|
+
modifiers: Record<string, ExpressionNode>;
|
|
15
|
+
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<OpenCommandInput>;
|
|
16
|
+
execute(input: OpenCommandInput, _context: TypedExecutionContext): Promise<void>;
|
|
17
|
+
validate(input: unknown): input is OpenCommandInput;
|
|
18
|
+
}
|
|
19
|
+
export declare const createOpenCommand: () => OpenCommand;
|
|
20
|
+
export default OpenCommand;
|
|
21
|
+
//# sourceMappingURL=open.d.ts.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ExecutionContext, TypedExecutionContext, ASTNode, ExpressionNode } from '../../types/base-types';
|
|
2
|
+
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
3
|
+
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
4
|
+
export interface ResetCommandInput {
|
|
5
|
+
targets: HTMLElement[];
|
|
6
|
+
}
|
|
7
|
+
export declare class ResetCommand implements DecoratedCommand {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly metadata: CommandMetadata;
|
|
10
|
+
parseInput(raw: {
|
|
11
|
+
args: ASTNode[];
|
|
12
|
+
modifiers: Record<string, ExpressionNode>;
|
|
13
|
+
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<ResetCommandInput>;
|
|
14
|
+
execute(input: ResetCommandInput, _context: TypedExecutionContext): Promise<void>;
|
|
15
|
+
validate(input: unknown): input is ResetCommandInput;
|
|
16
|
+
}
|
|
17
|
+
export declare const createResetCommand: () => ResetCommand;
|
|
18
|
+
export default ResetCommand;
|
|
19
|
+
//# sourceMappingURL=reset.d.ts.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ExecutionContext, TypedExecutionContext, ASTNode, ExpressionNode } from '../../types/base-types';
|
|
2
|
+
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
3
|
+
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
4
|
+
export interface SelectCommandInput {
|
|
5
|
+
targets: HTMLElement[];
|
|
6
|
+
}
|
|
7
|
+
export declare class SelectCommand implements DecoratedCommand {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly metadata: CommandMetadata;
|
|
10
|
+
parseInput(raw: {
|
|
11
|
+
args: ASTNode[];
|
|
12
|
+
modifiers: Record<string, ExpressionNode>;
|
|
13
|
+
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<SelectCommandInput>;
|
|
14
|
+
execute(input: SelectCommandInput, _context: TypedExecutionContext): Promise<void>;
|
|
15
|
+
validate(input: unknown): input is SelectCommandInput;
|
|
16
|
+
}
|
|
17
|
+
export declare const createSelectCommand: () => SelectCommand;
|
|
18
|
+
export default SelectCommand;
|
|
19
|
+
//# sourceMappingURL=select.d.ts.map
|
|
@@ -6,11 +6,14 @@ import type { MorphOptions } from '../../lib/morph-adapter';
|
|
|
6
6
|
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
7
7
|
export type { SwapStrategy } from '../../lib/swap-executor';
|
|
8
8
|
export interface SwapCommandInput {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
variant?: 'dom' | 'variable';
|
|
10
|
+
targets?: HTMLElement[];
|
|
11
|
+
content?: string | HTMLElement | null;
|
|
12
|
+
strategy?: SwapStrategy;
|
|
12
13
|
morphOptions?: MorphOptions;
|
|
13
14
|
useViewTransition?: boolean;
|
|
15
|
+
leftName?: string;
|
|
16
|
+
rightName?: string;
|
|
14
17
|
}
|
|
15
18
|
export declare class SwapCommand implements DecoratedCommand {
|
|
16
19
|
readonly name: string;
|
|
@@ -19,7 +22,7 @@ export declare class SwapCommand implements DecoratedCommand {
|
|
|
19
22
|
args: ASTNode[];
|
|
20
23
|
modifiers: Record<string, ExpressionNode>;
|
|
21
24
|
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<SwapCommandInput>;
|
|
22
|
-
execute(input: SwapCommandInput,
|
|
25
|
+
execute(input: SwapCommandInput, context: TypedExecutionContext): Promise<void>;
|
|
23
26
|
}
|
|
24
27
|
export declare class MorphCommand implements DecoratedCommand {
|
|
25
28
|
readonly name: string;
|
|
@@ -7,7 +7,7 @@ export type { EventOptions } from '../helpers/event-helpers';
|
|
|
7
7
|
export type EventDispatchMode = 'trigger' | 'send';
|
|
8
8
|
export interface EventDispatchInput {
|
|
9
9
|
eventName: string;
|
|
10
|
-
detail?:
|
|
10
|
+
detail?: unknown;
|
|
11
11
|
targets: EventTarget[];
|
|
12
12
|
options: EventOptions;
|
|
13
13
|
mode: EventDispatchMode;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ExecutionContext, TypedExecutionContext, ASTNode, ExpressionNode } from '../../types/base-types';
|
|
2
|
+
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
3
|
+
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
4
|
+
export interface BlurCommandInput {
|
|
5
|
+
targets: HTMLElement[];
|
|
6
|
+
}
|
|
7
|
+
export declare class BlurCommand implements DecoratedCommand {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly metadata: CommandMetadata;
|
|
10
|
+
parseInput(raw: {
|
|
11
|
+
args: ASTNode[];
|
|
12
|
+
modifiers: Record<string, ExpressionNode>;
|
|
13
|
+
}, evaluator: ExpressionEvaluator, context: ExecutionContext): Promise<BlurCommandInput>;
|
|
14
|
+
execute(input: BlurCommandInput, _context: TypedExecutionContext): Promise<void>;
|
|
15
|
+
validate(input: unknown): input is BlurCommandInput;
|
|
16
|
+
}
|
|
17
|
+
export declare const createBlurCommand: () => BlurCommand;
|
|
18
|
+
export default BlurCommand;
|
|
19
|
+
//# sourceMappingURL=blur.d.ts.map
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { ExecutionContext, TypedExecutionContext } from '../../types/core';
|
|
2
2
|
import type { ASTNode, ExpressionNode } from '../../types/base-types';
|
|
3
|
-
import type { ExpressionEvaluator } from '../../core/expression-evaluator';
|
|
4
3
|
import { type DecoratedCommand, type CommandMetadata } from '../decorators';
|
|
5
4
|
export interface CallCommandInput {
|
|
6
5
|
expression: any;
|
|
@@ -16,7 +15,7 @@ export declare class CallCommand implements DecoratedCommand {
|
|
|
16
15
|
parseInput(raw: {
|
|
17
16
|
args: ASTNode[];
|
|
18
17
|
modifiers: Record<string, ExpressionNode>;
|
|
19
|
-
}, _evaluator:
|
|
18
|
+
}, _evaluator: unknown, _context: ExecutionContext): Promise<CallCommandInput>;
|
|
20
19
|
execute(input: CallCommandInput, context: TypedExecutionContext): Promise<CallCommandOutput>;
|
|
21
20
|
}
|
|
22
21
|
export declare const createCallCommand: () => CallCommand;
|