@mostfeatured/dbi 0.2.32 → 0.2.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/types/Components/HTMLComponentsV2/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AACrE,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAgB,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAQ7G,OAAO,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAcpJ,MAAM,MAAM,2BAA2B,CAAC,UAAU,SAAS,cAAc,IAAI,IAAI,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,aAAa,GAAG,MAAM,GAAG,SAAS,GAAG,YAAY,GAAG,sBAAsB,GAAG,gBAAgB,GAAG,cAAc,CAAC,GAAG;IAC/P;;OAEG;IACH,IAAI,CAAC,EAAE,QAAQ,GAAG,KAAK,CAAC;IACxB;;OAEG;IACH,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,8BAA8B,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC;CACvE,CAAC;AAEF,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAC5B,CAAA;AAED,MAAM,WAAW,+BAA+B;IAC9C,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,OAAO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UAAU,IAAI,MAAM;IAapB,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAM;CACvB"}
@@ -130,11 +130,27 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
130
130
  const pendingKey = modalInteraction.customId;
131
131
  const pendingModal = this._pendingModals.get(pendingKey);
132
132
  if (pendingModal) {
133
- // Resolve the promise with fields and interaction
133
+ // Create a rerender function that can update the original message after modal submit
134
+ const component = this;
135
+ const rerender = async () => {
136
+ // Re-render the component with current data
137
+ const components = await component.toJSON({ data: currentState });
138
+ // Try to get the original message from the modal interaction
139
+ // Modal interactions have a 'message' property pointing to the original message
140
+ const originalMessage = modalInteraction.message;
141
+ if (originalMessage && originalMessage.edit) {
142
+ await originalMessage.edit({
143
+ components,
144
+ flags: ["IsComponentsV2"],
145
+ });
146
+ }
147
+ };
148
+ // Resolve the promise with fields, interaction, ctx, and rerender function
134
149
  pendingModal.resolve({
135
150
  fields,
136
151
  interaction: modalInteraction,
137
- ctx: ctx
152
+ ctx: ctx,
153
+ rerender
138
154
  });
139
155
  this._pendingModals.delete(pendingKey);
140
156
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/types/Components/HTMLComponentsV2/index.ts"],"names":[],"mappings":";;;;AAEA,mDAA6G;AAC7G,qCAAiD;AACjD,qDAA4G;AAC5G,iDAAkG;AAClG,+CAAoJ;AACpJ,oDAAoB;AAEpB,oDAAoD;AACpD,6CAAoJ;AAA3I,kHAAA,mBAAmB,OAAA;AAAE,yHAAA,0BAA0B,OAAA;AAAE,yHAAA,0BAA0B,OAAA;AAEpF;;;GAGG;AACH,SAAS,oBAAoB,CAAC,KAAU,EAAE,MAAe,EAAE,aAAsB,EAAE,UAAkB;IACnG,oCAAoC;IACpC,IAAI,IAAA,wCAA0B,EAAC,KAAK,CAAC,EAAE,CAAC;QACtC,OAAO,IAAA,iCAAmB,EAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,CA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AAC,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;qBAC9E,CAAC;oBACF,MAAM;gBAER,KAAK,CAAC,EAAE,iBAAiB;oBACvB,MAAM,CAAC,QAAQ,CAAC,GAAG,SAAS,CAAC,MAAM,IAAI,EAAE,CAAC;oBAC1C,MAAM;gBAER,KAAK,EAAE,EAAE,cAAc;oBACrB,2CAA2C;oBAC3C,MAAM,CAAC,QAAQ,CAAC,GAAG,SAAS,CAAC,WAAW,IAAI,EAAE,CAAC;oBAC/C,MAAM;YACV,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACH,UAAU;QACR,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,KAAK,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACpD,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;gBACvB,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,CAAC;YACD,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACjC,KAAK,EAAE,CAAC;QACV,CAAC;QACD,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,QAAQ,GAAW,EAAE,CAAC;CACvB;AA/pBD,kDA+pBC","sourcesContent":["import { NamespaceEnums } from \"../../../../generated/namespaceData\";\r\nimport { DBI } from \"../../../DBI\";\r\nimport { DBIBaseInteraction, DBIRateLimit, IDBIBaseExecuteCtx, TDBIReferencedData } from \"../../Interaction\";\r\nimport { parseHTMLComponentsV2 } from \"./parser\";\r\nimport { renderSvelteComponent, renderSvelteComponentFromFile, SvelteRenderResult } from \"./svelteRenderer\";\r\nimport { parseSvelteComponent, createHandlerContext, HandlerContextResult } from \"./svelteParser\";\r\nimport { createEnhancedError, isComponentValidationError, parseDiscordComponentError, ComponentErrorInfo, ParsedDiscordError } from \"./errorParser\";\r\nimport fs from \"fs\";\r\n\r\n// Re-export error parser utilities for external use\r\nexport { createEnhancedError, isComponentValidationError, parseDiscordComponentError, ComponentErrorInfo, ParsedDiscordError } from \"./errorParser\";\r\n\r\n/**\r\n * Parse Discord API error and provide helpful context about which HTML element caused the error\r\n * Uses the enhanced error parser for detailed, developer-friendly messages\r\n */\r\nfunction parseDiscordAPIError(error: any, source?: string, componentName?: string, components?: any[]): Error {\r\n // Use the new enhanced error parser\r\n if (isComponentValidationError(error)) {\r\n return createEnhancedError(error, components, source, componentName);\r\n }\r\n return error;\r\n}\r\n\r\nexport type TDBIHTMLComponentsV2Omitted<TNamespace extends NamespaceEnums> = Omit<DBIHTMLComponentsV2<TNamespace>, \"type\" | \"dbi\" | \"toJSON\" | \"description\" | \"send\" | \"destroy\" | \"destroyAll\" | \"__lastRenderModals__\" | \"_pendingModals\" | \"_initPromise\"> & {\r\n /**\r\n * Use 'svelte' for Svelte 5 components, 'eta' for Eta templates (default)\r\n */\r\n mode?: 'svelte' | 'eta';\r\n /**\r\n * Callback executed when the component interaction is triggered\r\n */\r\n onExecute?: (ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>) => void;\r\n};\r\n\r\nexport type TDBIHTMLComponentsV2ToJSONArgs = {\r\n data?: Record<string, any>;\r\n}\r\n\r\nexport interface TDBIHTMLComponentsV2SendOptions {\r\n data?: Record<string, any>;\r\n flags?: string[];\r\n content?: string;\r\n ephemeral?: boolean;\r\n /** If true, uses interaction.reply(). If false or unset, auto-detects based on target type */\r\n reply?: boolean;\r\n /** If true, uses interaction.followUp() instead of reply() */\r\n followUp?: boolean;\r\n}\r\n\r\n/**\r\n * Result object returned by send() method\r\n * Includes the Discord message and a render() method for manual re-rendering\r\n */\r\nexport interface TDBIHTMLComponentsV2SendResult {\r\n /** The Discord message object returned from send/reply/followUp */\r\n message: any;\r\n /** The data object with reactive state (includes $ref) */\r\n data: Record<string, any>;\r\n /** Manually trigger a re-render of the component */\r\n render: () => Promise<void>;\r\n /** Destroy this component instance (clears intervals, timers, removes ref) */\r\n destroy: () => boolean;\r\n}\r\n\r\nexport interface IDBIHTMLComponentsV2ExecuteCtx<TNamespace extends NamespaceEnums> extends IDBIBaseExecuteCtx<TNamespace> {\r\n data: TDBIReferencedData[];\r\n}\r\n\r\nexport class DBIHTMLComponentsV2<TNamespace extends NamespaceEnums> extends DBIBaseInteraction<TNamespace> {\r\n template?: string;\r\n file?: string;\r\n mode: 'svelte' | 'eta' = 'eta';\r\n private svelteComponentInfo: any = null;\r\n private _userOnExecute?: (ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>) => void;\r\n /** The directory of the source file (used for resolving relative imports) */\r\n private _sourceDir?: string;\r\n\r\n // Store handler contexts per ref for lifecycle management\r\n // Key: ref id, Value: handlerContext with lifecycle hooks\r\n private _activeContexts: Map<string, any> = new Map();\r\n\r\n // Store pending modal promises for await showModal() support\r\n // Key: modal customId, Value: { resolve, reject } functions\r\n _pendingModals: Map<string, { resolve: (result: any) => void; reject: (error: any) => void }> = new Map();\r\n\r\n // Track initialization promise\r\n private _initPromise: Promise<void> | null = null;\r\n\r\n constructor(dbi: DBI<TNamespace>, args: TDBIHTMLComponentsV2Omitted<TNamespace>) {\r\n // Store user's onExecute callback before passing to super\r\n const userOnExecute = (args as any).onExecute;\r\n\r\n // Remove onExecute from args so it doesn't override the class method\r\n const argsWithoutOnExecute = { ...args };\r\n delete (argsWithoutOnExecute as any).onExecute;\r\n\r\n super(dbi, {\r\n ...(argsWithoutOnExecute as any),\r\n type: \"HTMLComponentsV2\",\r\n });\r\n this.template = args.template || (args.file ? fs.readFileSync(args.file, \"utf-8\") : undefined);\r\n this.file = args.file;\r\n this.name = args.name;\r\n this.handlers = args.handlers || [];\r\n this.mode = args.mode || 'eta';\r\n\r\n // Store source directory for resolving relative imports in Svelte components\r\n if (this.file) {\r\n const path = require(\"path\");\r\n this._sourceDir = path.dirname(path.resolve(this.file));\r\n }\r\n\r\n // Store user's onExecute callback if provided\r\n if (userOnExecute) {\r\n this._userOnExecute = userOnExecute;\r\n }\r\n\r\n // Pre-extract Svelte handlers at registration time (lazy loaded)\r\n if (this.mode === 'svelte' && this.template) {\r\n // Store the promise so we can await it in _handleExecute\r\n this._initPromise = this._initSvelteComponent();\r\n }\r\n\r\n // Re-assign onExecute method after super() call because parent class sets it to undefined\r\n this.onExecute = this._handleExecute.bind(this);\r\n }\r\n\r\n private async _initSvelteComponent() {\r\n if (this.template && !this.svelteComponentInfo) {\r\n this.svelteComponentInfo = await parseSvelteComponent(this.template);\r\n }\r\n }\r\n\r\n private async _handleExecute(ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>) {\r\n // Wait for Svelte component initialization if not yet completed\r\n if (this._initPromise) {\r\n await this._initPromise;\r\n }\r\n\r\n // Call user's onExecute callback first if provided\r\n if (this._userOnExecute) {\r\n this._userOnExecute(ctx);\r\n }\r\n\r\n // If using Svelte mode, find and execute the handler\r\n if (this.mode === 'svelte' && this.svelteComponentInfo) {\r\n const [elementName, ...handlerData] = ctx.data;\r\n\r\n if (typeof elementName === 'string') {\r\n // Check if this is a modal submit (elementName is the modal id)\r\n const modalHandlerInfo = this.svelteComponentInfo.modalHandlers.get(elementName);\r\n\r\n if (modalHandlerInfo) {\r\n // This is a modal submit - execute the onsubmit handler (or just resolve promise if no handler)\r\n this._executeModalSubmit(ctx, elementName, modalHandlerInfo.onsubmitHandler, handlerData);\r\n return;\r\n }\r\n\r\n // Find the handler info for this element (button, select, etc.)\r\n let handlerInfo = this.svelteComponentInfo.handlers.get(elementName);\r\n\r\n // If not found by exact match, try prefix matching for dynamic names (from {#each})\r\n if (!handlerInfo) {\r\n for (const [key, info] of this.svelteComponentInfo.handlers) {\r\n if (info.isDynamicName && elementName.startsWith(key + '_')) {\r\n handlerInfo = info;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (handlerInfo) {\r\n this._executeElementHandler(ctx, handlerInfo, handlerData);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Execute a modal submit handler\r\n */\r\n private _executeModalSubmit(\r\n ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>,\r\n modalId: string,\r\n handlerName: string | undefined,\r\n handlerData: any[]\r\n ) {\r\n // Extract current state from handlerData (refs that were passed)\r\n const currentState = handlerData[0] || {} as Record<string, any>;\r\n\r\n // Get ref id for lifecycle tracking (if available)\r\n const refId = (currentState as any)?.$ref || null;\r\n\r\n // Extract all field values from modal interaction (text inputs, selects, file uploads, etc.)\r\n const modalInteraction = ctx.interaction as any;\r\n const fields = this._extractModalFields(modalInteraction);\r\n\r\n // Check if there's a pending promise for this modal (from await showModal())\r\n // Use the modal's customId to find the pending promise\r\n const pendingKey = modalInteraction.customId;\r\n const pendingModal = this._pendingModals.get(pendingKey);\r\n\r\n if (pendingModal) {\r\n // Resolve the promise with fields and interaction\r\n pendingModal.resolve({\r\n fields,\r\n interaction: modalInteraction,\r\n ctx: ctx\r\n });\r\n this._pendingModals.delete(pendingKey);\r\n }\r\n\r\n // If no onsubmit handler defined, just return (promise-based usage)\r\n if (!handlerName) {\r\n return;\r\n }\r\n\r\n // Create handler context for modal submit\r\n const handlerContext = createHandlerContext(\r\n this.svelteComponentInfo!.scriptContent,\r\n typeof currentState === 'object' ? currentState : {},\r\n this,\r\n ctx,\r\n this._sourceDir,\r\n this.svelteComponentInfo!.inlineHandlers\r\n );\r\n\r\n const handlerFn = handlerContext.handlers[handlerName];\r\n\r\n if (handlerFn && typeof handlerFn === 'function') {\r\n try {\r\n // Store context for lifecycle management\r\n if (refId) {\r\n const existingContext = this._activeContexts.get(refId);\r\n if (existingContext && existingContext.destroyCallbacks) {\r\n handlerContext.destroyCallbacks.push(...existingContext.destroyCallbacks);\r\n }\r\n this._activeContexts.set(refId, handlerContext);\r\n }\r\n\r\n handlerContext.setInHandler(true);\r\n\r\n try {\r\n // Call handler with ctx and fields object\r\n handlerFn.call(this, handlerContext.wrappedCtx, fields, ...handlerData.slice(1));\r\n } finally {\r\n handlerContext.setInHandler(false);\r\n }\r\n\r\n handlerContext.runEffects();\r\n\r\n if (handlerContext.hasPendingRender()) {\r\n handlerContext.flushRender();\r\n }\r\n } catch (error) {\r\n // Re-throw the error so it's visible to the developer\r\n console.error(`[DBI-Svelte] Modal handler \"${handlerName}\" failed:`, error);\r\n throw error;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Execute an element handler (button, select, etc.)\r\n */\r\n private _executeElementHandler(\r\n ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>,\r\n handlerInfo: any,\r\n handlerData: any[]\r\n ) {\r\n // Extract current state from handlerData (refs that were passed)\r\n // The second element in data array contains the current state\r\n const currentState = handlerData[0] || {} as Record<string, any>;\r\n\r\n // Get ref id for lifecycle tracking (if available)\r\n const refId = (currentState as any)?.$ref || null;\r\n\r\n // Check if this is first execution for this ref\r\n const isFirstExecution = refId && !this._activeContexts.has(refId);\r\n\r\n // Get existing context if any (to preserve lifecycle callbacks like intervals)\r\n const existingContext = refId ? this._activeContexts.get(refId) : null;\r\n\r\n // Create a NEW handler context for each execution with the current state\r\n // This ensures each interaction has its own isolated state\r\n // Pass 'this' so handlers can access component methods like toJSON()\r\n // Pass ctx so handlers can access ctx.interaction, ctx.data, ctx.locale, etc.\r\n const handlerContext = createHandlerContext(\r\n this.svelteComponentInfo!.scriptContent,\r\n typeof currentState === 'object' ? currentState : {},\r\n this,\r\n ctx,\r\n this._sourceDir,\r\n this.svelteComponentInfo!.inlineHandlers\r\n );\r\n\r\n const handlerFn = handlerContext.handlers[handlerInfo.handlerName];\r\n\r\n if (handlerFn && typeof handlerFn === 'function') {\r\n try {\r\n // Store context for lifecycle management\r\n if (refId) {\r\n // If there's an existing context, transfer its destroy callbacks to the new context\r\n // This preserves intervals/timers created in onMount\r\n if (existingContext && existingContext.destroyCallbacks) {\r\n // Merge existing destroy callbacks (don't run them!)\r\n handlerContext.destroyCallbacks.push(...existingContext.destroyCallbacks);\r\n }\r\n\r\n this._activeContexts.set(refId, handlerContext);\r\n\r\n // Wrap $unRef to call onDestroy when ref is deleted (only wrap once)\r\n const stateObj = currentState as any;\r\n if (stateObj.$unRef && !stateObj.__unRefWrapped__) {\r\n const originalUnRef = stateObj.$unRef.bind(stateObj);\r\n stateObj.$unRef = () => {\r\n // Run destroy callbacks before unref\r\n const ctx = this._activeContexts.get(refId);\r\n if (ctx && ctx.runDestroy) {\r\n ctx.runDestroy();\r\n }\r\n this._activeContexts.delete(refId);\r\n return originalUnRef();\r\n };\r\n stateObj.__unRefWrapped__ = true;\r\n }\r\n }\r\n\r\n // Run onMount callbacks only on first execution\r\n if (isFirstExecution && handlerContext.runMount) {\r\n handlerContext.runMount();\r\n }\r\n\r\n // Mark that we're inside handler execution (prevents auto-render during handler)\r\n handlerContext.setInHandler(true);\r\n\r\n try {\r\n // Bind 'this' to the DBIHTMLComponentsV2 instance so handlers can use this.toJSON()\r\n // Pass wrappedCtx so handlers use the proxy-wrapped ctx that tracks interaction calls\r\n // This ensures __asyncInteractionCalled__ flag is set when handler calls ctx.interaction.reply() etc.\r\n handlerFn.call(this, handlerContext.wrappedCtx, ...handlerData.slice(1));\r\n } finally {\r\n // Always reset handler execution flag\r\n handlerContext.setInHandler(false);\r\n }\r\n\r\n // Run effects after handler execution (state may have changed)\r\n handlerContext.runEffects();\r\n\r\n // If there are pending data changes and no interaction method was called,\r\n // flush the render now (synchronously uses interaction.update)\r\n if (handlerContext.hasPendingRender()) {\r\n handlerContext.flushRender();\r\n }\r\n } catch (error) {\r\n // Re-throw the error so it's visible to the developer\r\n console.error(`[DBI-Svelte] Handler \"${handlerInfo.handlerName}\" failed:`, error);\r\n throw error;\r\n }\r\n }\r\n }\r\n\r\n // Store last render's modals for showModal() to access\r\n // Note: Used internally by handler context, not truly private\r\n __lastRenderModals__: Map<string, any> | null = null;\r\n\r\n override async toJSON(arg: TDBIHTMLComponentsV2ToJSONArgs = {}): Promise<any> {\r\n if (this.mode === 'svelte' && this.template) {\r\n // Render Svelte component\r\n const result = await renderSvelteComponent(\r\n this.dbi as any,\r\n this.template,\r\n this.name,\r\n {\r\n data: arg.data,\r\n ttl: this.ttl\r\n }\r\n );\r\n\r\n // Store modals for showModal() to access\r\n this.__lastRenderModals__ = result.modals;\r\n\r\n return result.components;\r\n } else {\r\n // Use Eta template parsing (default)\r\n return parseHTMLComponentsV2(\r\n this.dbi as any,\r\n this.template!,\r\n this.name,\r\n {\r\n data: arg.data,\r\n ttl: this.ttl\r\n }\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Send the component to an interaction or channel and initialize lifecycle hooks (onMount)\r\n * This is the recommended way to send Svelte components with intervals/timers\r\n * \r\n * @param target - Discord interaction or channel to send to\r\n * @param options - Send options including data, flags, content\r\n * \r\n * @example\r\n * ```ts\r\n * const showcase = dbi.interaction(\"product-showcase\");\r\n * \r\n * // Send as interaction reply\r\n * await showcase.send(interaction, { data: { count: 0 } });\r\n * \r\n * // Send to a channel directly\r\n * const result = await showcase.send(channel, { data: { count: 0 } });\r\n * \r\n * // Send as followUp (if already replied)\r\n * const result = await showcase.send(interaction, { data: { count: 0 }, followUp: true });\r\n * \r\n * // Manual re-render from outside\r\n * await result.render();\r\n * ```\r\n */\r\n async send(target: any, options: TDBIHTMLComponentsV2SendOptions = {}): Promise<TDBIHTMLComponentsV2SendResult> {\r\n // Wait for Svelte component initialization if not yet completed\r\n if (this._initPromise) {\r\n await this._initPromise;\r\n }\r\n\r\n const { data = {}, flags = [\"IsComponentsV2\"], content, ephemeral, reply, followUp } = options;\r\n\r\n // Render components (toJSON is async) - this also creates $ref in data if not present\r\n const components = await this.toJSON({ data });\r\n\r\n // Build message options\r\n const messageOptions: any = { components, flags };\r\n if (content) messageOptions.content = content;\r\n if (ephemeral) messageOptions.flags = [...flags, \"Ephemeral\"];\r\n\r\n // Detect target type and send accordingly\r\n let message: any;\r\n const isInteraction = target.reply && target.user; // Interactions have both reply method and user property\r\n const isChannel = target.send && !target.user; // Channels have send but no user\r\n\r\n try {\r\n if (isInteraction) {\r\n if (followUp) {\r\n message = await target.followUp(messageOptions);\r\n } else {\r\n message = await target.reply(messageOptions);\r\n }\r\n } else if (isChannel) {\r\n message = await target.send(messageOptions);\r\n } else {\r\n throw new Error(\"Invalid target: must be an interaction or channel\");\r\n }\r\n } catch (error: any) {\r\n // Check if it's a Discord API error and enhance it with helpful context\r\n if (error.code || error.rawError || (error.message && error.message.includes('Invalid Form Body'))) {\r\n const source = this.file ? fs.readFileSync(this.file, 'utf-8') : this.template;\r\n throw parseDiscordAPIError(error, source, this.name, components);\r\n }\r\n throw error;\r\n }\r\n\r\n // If Svelte mode, create initial handler context and run onMount\r\n // After toJSON, data.$ref is guaranteed to exist (created in renderSvelteComponent)\r\n if (this.mode === 'svelte' && this.svelteComponentInfo && data.$ref) {\r\n const refId = data.$ref;\r\n\r\n // Create handler context with a fake ctx that has the message\r\n const fakeCtx = {\r\n interaction: {\r\n replied: true,\r\n deferred: false,\r\n message: message,\r\n }\r\n };\r\n\r\n const handlerContext = createHandlerContext(\r\n this.svelteComponentInfo.scriptContent,\r\n data,\r\n this,\r\n fakeCtx,\r\n this._sourceDir,\r\n this.svelteComponentInfo.inlineHandlers\r\n );\r\n\r\n // Store the context for lifecycle management\r\n this._activeContexts.set(refId, handlerContext);\r\n\r\n // Wrap $unRef to call onDestroy when ref is deleted\r\n if (data.$unRef) {\r\n const originalUnRef = data.$unRef.bind(data);\r\n data.$unRef = () => {\r\n if (handlerContext.runDestroy) {\r\n handlerContext.runDestroy();\r\n }\r\n this._activeContexts.delete(refId);\r\n return originalUnRef();\r\n };\r\n }\r\n\r\n // Run onMount callbacks\r\n handlerContext.runMount();\r\n\r\n // Run initial effects\r\n handlerContext.runEffects();\r\n\r\n // Return result object with render() method for manual re-rendering\r\n const component = this;\r\n return {\r\n message,\r\n data,\r\n render: async () => {\r\n // Run pre-render callbacks (async)\r\n await handlerContext.runPreRender();\r\n\r\n // Re-render the component\r\n const components = await component.toJSON({ data });\r\n await message.edit({\r\n components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n\r\n // Run after-render callbacks\r\n handlerContext.runAfterRender();\r\n },\r\n destroy: () => component.destroy(data)\r\n } as TDBIHTMLComponentsV2SendResult;\r\n }\r\n\r\n // For non-Svelte mode, return simple result object\r\n return {\r\n message,\r\n data,\r\n render: async () => {\r\n const components = await this.toJSON({ data });\r\n await message.edit({\r\n components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n },\r\n destroy: () => this.destroy(data)\r\n } as TDBIHTMLComponentsV2SendResult;\r\n }\r\n\r\n /**\r\n * Destroy a component instance by ref ID or data object\r\n * This runs onDestroy callbacks (clears intervals/timers) and removes the ref\r\n * \r\n * @param refOrData - Either a ref ID string or the data object with $ref\r\n * @returns true if destroyed, false if not found\r\n * \r\n * @example\r\n * ```ts\r\n * // Destroy by data object\r\n * showcase.destroy(data);\r\n * \r\n * // Destroy by ref ID\r\n * showcase.destroy(data.$ref);\r\n * \r\n * // Destroy all active instances of this component\r\n * showcase.destroyAll();\r\n * ```\r\n */\r\n destroy(refOrData: string | Record<string, any>): boolean {\r\n const refId = typeof refOrData === 'string' ? refOrData : refOrData?.$ref;\r\n\r\n if (!refId) {\r\n return false;\r\n }\r\n\r\n const context = this._activeContexts.get(refId);\r\n if (context) {\r\n // Run destroy callbacks (clears intervals, timers, etc.)\r\n if (context.runDestroy) {\r\n context.runDestroy();\r\n }\r\n this._activeContexts.delete(refId);\r\n }\r\n\r\n // Also delete from DBI refs store\r\n this.dbi.data.refs.delete(refId);\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Extract all field values from a modal interaction\r\n * Supports text inputs, select menus (string, user, role, mentionable, channel), and file uploads\r\n * \r\n * Returns an object where keys are the custom_id of each component and values are:\r\n * - For text inputs: string value\r\n * - For string selects: string[] of selected values\r\n * - For user selects: string[] of user IDs\r\n * - For role selects: string[] of role IDs\r\n * - For mentionable selects: { users: string[], roles: string[] }\r\n * - For channel selects: string[] of channel IDs\r\n * - For file uploads: attachment objects array\r\n */\r\n private _extractModalFields(modalInteraction: any): Record<string, any> {\r\n const fields: Record<string, any> = {};\r\n\r\n // Handle classic text input fields via ModalSubmitFields\r\n if (modalInteraction.fields && modalInteraction.fields.fields) {\r\n for (const [customId, field] of modalInteraction.fields.fields) {\r\n // Text input - field.value is the string\r\n // For select menus, value might be an array\r\n fields[customId] = field.values || field.value;\r\n }\r\n }\r\n\r\n // Handle new modal components from interaction.data.components\r\n // The new modal structure uses Label wrappers with nested components\r\n const data = modalInteraction.data || (modalInteraction as any).data;\r\n if (data && data.components) {\r\n this._extractFieldsFromComponents(data.components, fields);\r\n }\r\n\r\n // Also check for components directly on the interaction (some Discord.js versions)\r\n if (modalInteraction.components && Array.isArray(modalInteraction.components)) {\r\n this._extractFieldsFromInteractionComponents(modalInteraction.components, fields);\r\n }\r\n\r\n return fields;\r\n }\r\n\r\n /**\r\n * Extract fields from Discord.js style interaction components (ActionRow objects)\r\n */\r\n private _extractFieldsFromInteractionComponents(components: any[], fields: Record<string, any>) {\r\n for (const row of components) {\r\n // ActionRow has components property\r\n const rowComponents = row.components || [];\r\n for (const component of rowComponents) {\r\n const customId = component.customId || component.custom_id || component.id;\r\n if (!customId) continue;\r\n\r\n // Check component type\r\n const type = component.type;\r\n\r\n // Text Input (type 4)\r\n if (type === 4 || component.value !== undefined) {\r\n fields[customId] = component.value || '';\r\n }\r\n\r\n // Select menus (types 3, 5, 6, 7, 8) - check for values array\r\n if (component.values !== undefined) {\r\n fields[customId] = component.values;\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Recursively extract field values from component structure\r\n */\r\n private _extractFieldsFromComponents(components: any[], fields: Record<string, any>) {\r\n for (const component of components) {\r\n const type = component.type;\r\n // Support both custom_id and id for backward compatibility\r\n const customId = component.custom_id || component.id;\r\n\r\n // Type 18 = Label/Field - can have nested component or components\r\n if (type === 18) {\r\n if (component.component) {\r\n this._extractFieldsFromComponents([component.component], fields);\r\n }\r\n if (component.components) {\r\n this._extractFieldsFromComponents(component.components, fields);\r\n }\r\n continue;\r\n }\r\n\r\n // Type 1 = Action Row - has nested components array\r\n if (type === 1 && component.components) {\r\n this._extractFieldsFromComponents(component.components, fields);\r\n continue;\r\n }\r\n\r\n if (!customId) continue;\r\n\r\n switch (type) {\r\n case 4: // Text Input\r\n fields[customId] = component.value || '';\r\n break;\r\n\r\n case 3: // String Select\r\n fields[customId] = component.values || [];\r\n break;\r\n\r\n case 5: // User Select\r\n fields[customId] = component.values || [];\r\n break;\r\n\r\n case 6: // Role Select\r\n fields[customId] = component.values || [];\r\n break;\r\n\r\n case 7: // Mentionable Select - can have both users and roles\r\n // Discord returns resolved data for mentionables\r\n fields[customId] = {\r\n values: component.values || [],\r\n users: component.resolved?.users ? Object.keys(component.resolved.users) : [],\r\n roles: component.resolved?.roles ? Object.keys(component.resolved.roles) : []\r\n };\r\n break;\r\n\r\n case 8: // Channel Select\r\n fields[customId] = component.values || [];\r\n break;\r\n\r\n case 19: // File Upload\r\n // File uploads come through as attachments\r\n fields[customId] = component.attachments || [];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Destroy all active instances of this component\r\n * Useful for cleanup when the bot shuts down or component is unloaded\r\n * \r\n * @returns Number of instances destroyed\r\n */\r\n destroyAll(): number {\r\n let count = 0;\r\n for (const [refId, context] of this._activeContexts) {\r\n if (context.runDestroy) {\r\n context.runDestroy();\r\n }\r\n this.dbi.data.refs.delete(refId);\r\n count++;\r\n }\r\n this._activeContexts.clear();\r\n return count;\r\n }\r\n\r\n handlers?: any[] = [];\r\n}"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/types/Components/HTMLComponentsV2/index.ts"],"names":[],"mappings":";;;;AAEA,mDAA6G;AAC7G,qCAAiD;AACjD,qDAA4G;AAC5G,iDAAkG;AAClG,+CAAoJ;AACpJ,oDAAoB;AAEpB,oDAAoD;AACpD,6CAAoJ;AAA3I,kHAAA,mBAAmB,OAAA;AAAE,yHAAA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AK,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACpD,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;gBACvB,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,CAAC;YACD,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACjC,KAAK,EAAE,CAAC;QACV,CAAC;QACD,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,QAAQ,GAAW,EAAE,CAAC;CACvB;AAlrBD,kDAkrBC","sourcesContent":["import { NamespaceEnums } from \"../../../../generated/namespaceData\";\r\nimport { DBI } from \"../../../DBI\";\r\nimport { DBIBaseInteraction, DBIRateLimit, IDBIBaseExecuteCtx, TDBIReferencedData } from \"../../Interaction\";\r\nimport { parseHTMLComponentsV2 } from \"./parser\";\r\nimport { renderSvelteComponent, renderSvelteComponentFromFile, SvelteRenderResult } from \"./svelteRenderer\";\r\nimport { parseSvelteComponent, createHandlerContext, HandlerContextResult } from \"./svelteParser\";\r\nimport { createEnhancedError, isComponentValidationError, parseDiscordComponentError, ComponentErrorInfo, ParsedDiscordError } from \"./errorParser\";\r\nimport fs from \"fs\";\r\n\r\n// Re-export error parser utilities for external use\r\nexport { createEnhancedError, isComponentValidationError, parseDiscordComponentError, ComponentErrorInfo, ParsedDiscordError } from \"./errorParser\";\r\n\r\n/**\r\n * Parse Discord API error and provide helpful context about which HTML element caused the error\r\n * Uses the enhanced error parser for detailed, developer-friendly messages\r\n */\r\nfunction parseDiscordAPIError(error: any, source?: string, componentName?: string, components?: any[]): Error {\r\n // Use the new enhanced error parser\r\n if (isComponentValidationError(error)) {\r\n return createEnhancedError(error, components, source, componentName);\r\n }\r\n return error;\r\n}\r\n\r\nexport type TDBIHTMLComponentsV2Omitted<TNamespace extends NamespaceEnums> = Omit<DBIHTMLComponentsV2<TNamespace>, \"type\" | \"dbi\" | \"toJSON\" | \"description\" | \"send\" | \"destroy\" | \"destroyAll\" | \"__lastRenderModals__\" | \"_pendingModals\" | \"_initPromise\"> & {\r\n /**\r\n * Use 'svelte' for Svelte 5 components, 'eta' for Eta templates (default)\r\n */\r\n mode?: 'svelte' | 'eta';\r\n /**\r\n * Callback executed when the component interaction is triggered\r\n */\r\n onExecute?: (ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>) => void;\r\n};\r\n\r\nexport type TDBIHTMLComponentsV2ToJSONArgs = {\r\n data?: Record<string, any>;\r\n}\r\n\r\nexport interface TDBIHTMLComponentsV2SendOptions {\r\n data?: Record<string, any>;\r\n flags?: string[];\r\n content?: string;\r\n ephemeral?: boolean;\r\n /** If true, uses interaction.reply(). If false or unset, auto-detects based on target type */\r\n reply?: boolean;\r\n /** If true, uses interaction.followUp() instead of reply() */\r\n followUp?: boolean;\r\n}\r\n\r\n/**\r\n * Result object returned by send() method\r\n * Includes the Discord message and a render() method for manual re-rendering\r\n */\r\nexport interface TDBIHTMLComponentsV2SendResult {\r\n /** The Discord message object returned from send/reply/followUp */\r\n message: any;\r\n /** The data object with reactive state (includes $ref) */\r\n data: Record<string, any>;\r\n /** Manually trigger a re-render of the component */\r\n render: () => Promise<void>;\r\n /** Destroy this component instance (clears intervals, timers, removes ref) */\r\n destroy: () => boolean;\r\n}\r\n\r\nexport interface IDBIHTMLComponentsV2ExecuteCtx<TNamespace extends NamespaceEnums> extends IDBIBaseExecuteCtx<TNamespace> {\r\n data: TDBIReferencedData[];\r\n}\r\n\r\nexport class DBIHTMLComponentsV2<TNamespace extends NamespaceEnums> extends DBIBaseInteraction<TNamespace> {\r\n template?: string;\r\n file?: string;\r\n mode: 'svelte' | 'eta' = 'eta';\r\n private svelteComponentInfo: any = null;\r\n private _userOnExecute?: (ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>) => void;\r\n /** The directory of the source file (used for resolving relative imports) */\r\n private _sourceDir?: string;\r\n\r\n // Store handler contexts per ref for lifecycle management\r\n // Key: ref id, Value: handlerContext with lifecycle hooks\r\n private _activeContexts: Map<string, any> = new Map();\r\n\r\n // Store pending modal promises for await showModal() support\r\n // Key: modal customId, Value: { resolve, reject } functions\r\n _pendingModals: Map<string, { resolve: (result: any) => void; reject: (error: any) => void }> = new Map();\r\n\r\n // Track initialization promise\r\n private _initPromise: Promise<void> | null = null;\r\n\r\n constructor(dbi: DBI<TNamespace>, args: TDBIHTMLComponentsV2Omitted<TNamespace>) {\r\n // Store user's onExecute callback before passing to super\r\n const userOnExecute = (args as any).onExecute;\r\n\r\n // Remove onExecute from args so it doesn't override the class method\r\n const argsWithoutOnExecute = { ...args };\r\n delete (argsWithoutOnExecute as any).onExecute;\r\n\r\n super(dbi, {\r\n ...(argsWithoutOnExecute as any),\r\n type: \"HTMLComponentsV2\",\r\n });\r\n this.template = args.template || (args.file ? fs.readFileSync(args.file, \"utf-8\") : undefined);\r\n this.file = args.file;\r\n this.name = args.name;\r\n this.handlers = args.handlers || [];\r\n this.mode = args.mode || 'eta';\r\n\r\n // Store source directory for resolving relative imports in Svelte components\r\n if (this.file) {\r\n const path = require(\"path\");\r\n this._sourceDir = path.dirname(path.resolve(this.file));\r\n }\r\n\r\n // Store user's onExecute callback if provided\r\n if (userOnExecute) {\r\n this._userOnExecute = userOnExecute;\r\n }\r\n\r\n // Pre-extract Svelte handlers at registration time (lazy loaded)\r\n if (this.mode === 'svelte' && this.template) {\r\n // Store the promise so we can await it in _handleExecute\r\n this._initPromise = this._initSvelteComponent();\r\n }\r\n\r\n // Re-assign onExecute method after super() call because parent class sets it to undefined\r\n this.onExecute = this._handleExecute.bind(this);\r\n }\r\n\r\n private async _initSvelteComponent() {\r\n if (this.template && !this.svelteComponentInfo) {\r\n this.svelteComponentInfo = await parseSvelteComponent(this.template);\r\n }\r\n }\r\n\r\n private async _handleExecute(ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>) {\r\n // Wait for Svelte component initialization if not yet completed\r\n if (this._initPromise) {\r\n await this._initPromise;\r\n }\r\n\r\n // Call user's onExecute callback first if provided\r\n if (this._userOnExecute) {\r\n this._userOnExecute(ctx);\r\n }\r\n\r\n // If using Svelte mode, find and execute the handler\r\n if (this.mode === 'svelte' && this.svelteComponentInfo) {\r\n const [elementName, ...handlerData] = ctx.data;\r\n\r\n if (typeof elementName === 'string') {\r\n // Check if this is a modal submit (elementName is the modal id)\r\n const modalHandlerInfo = this.svelteComponentInfo.modalHandlers.get(elementName);\r\n\r\n if (modalHandlerInfo) {\r\n // This is a modal submit - execute the onsubmit handler (or just resolve promise if no handler)\r\n this._executeModalSubmit(ctx, elementName, modalHandlerInfo.onsubmitHandler, handlerData);\r\n return;\r\n }\r\n\r\n // Find the handler info for this element (button, select, etc.)\r\n let handlerInfo = this.svelteComponentInfo.handlers.get(elementName);\r\n\r\n // If not found by exact match, try prefix matching for dynamic names (from {#each})\r\n if (!handlerInfo) {\r\n for (const [key, info] of this.svelteComponentInfo.handlers) {\r\n if (info.isDynamicName && elementName.startsWith(key + '_')) {\r\n handlerInfo = info;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (handlerInfo) {\r\n this._executeElementHandler(ctx, handlerInfo, handlerData);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Execute a modal submit handler\r\n */\r\n private _executeModalSubmit(\r\n ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>,\r\n modalId: string,\r\n handlerName: string | undefined,\r\n handlerData: any[]\r\n ) {\r\n // Extract current state from handlerData (refs that were passed)\r\n const currentState = handlerData[0] || {} as Record<string, any>;\r\n\r\n // Get ref id for lifecycle tracking (if available)\r\n const refId = (currentState as any)?.$ref || null;\r\n\r\n // Extract all field values from modal interaction (text inputs, selects, file uploads, etc.)\r\n const modalInteraction = ctx.interaction as any;\r\n const fields = this._extractModalFields(modalInteraction);\r\n\r\n // Check if there's a pending promise for this modal (from await showModal())\r\n // Use the modal's customId to find the pending promise\r\n const pendingKey = modalInteraction.customId;\r\n const pendingModal = this._pendingModals.get(pendingKey);\r\n\r\n if (pendingModal) {\r\n // Create a rerender function that can update the original message after modal submit\r\n const component = this;\r\n const rerender = async () => {\r\n // Re-render the component with current data\r\n const components = await component.toJSON({ data: currentState });\r\n\r\n // Try to get the original message from the modal interaction\r\n // Modal interactions have a 'message' property pointing to the original message\r\n const originalMessage = modalInteraction.message;\r\n\r\n if (originalMessage && originalMessage.edit) {\r\n await originalMessage.edit({\r\n components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n }\r\n };\r\n\r\n // Resolve the promise with fields, interaction, ctx, and rerender function\r\n pendingModal.resolve({\r\n fields,\r\n interaction: modalInteraction,\r\n ctx: ctx,\r\n rerender\r\n });\r\n this._pendingModals.delete(pendingKey);\r\n }\r\n\r\n // If no onsubmit handler defined, just return (promise-based usage)\r\n if (!handlerName) {\r\n return;\r\n }\r\n\r\n // Create handler context for modal submit\r\n const handlerContext = createHandlerContext(\r\n this.svelteComponentInfo!.scriptContent,\r\n typeof currentState === 'object' ? currentState : {},\r\n this,\r\n ctx,\r\n this._sourceDir,\r\n this.svelteComponentInfo!.inlineHandlers\r\n );\r\n\r\n const handlerFn = handlerContext.handlers[handlerName];\r\n\r\n if (handlerFn && typeof handlerFn === 'function') {\r\n try {\r\n // Store context for lifecycle management\r\n if (refId) {\r\n const existingContext = this._activeContexts.get(refId);\r\n if (existingContext && existingContext.destroyCallbacks) {\r\n handlerContext.destroyCallbacks.push(...existingContext.destroyCallbacks);\r\n }\r\n this._activeContexts.set(refId, handlerContext);\r\n }\r\n\r\n handlerContext.setInHandler(true);\r\n\r\n try {\r\n // Call handler with ctx and fields object\r\n handlerFn.call(this, handlerContext.wrappedCtx, fields, ...handlerData.slice(1));\r\n } finally {\r\n handlerContext.setInHandler(false);\r\n }\r\n\r\n handlerContext.runEffects();\r\n\r\n if (handlerContext.hasPendingRender()) {\r\n handlerContext.flushRender();\r\n }\r\n } catch (error) {\r\n // Re-throw the error so it's visible to the developer\r\n console.error(`[DBI-Svelte] Modal handler \"${handlerName}\" failed:`, error);\r\n throw error;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Execute an element handler (button, select, etc.)\r\n */\r\n private _executeElementHandler(\r\n ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>,\r\n handlerInfo: any,\r\n handlerData: any[]\r\n ) {\r\n // Extract current state from handlerData (refs that were passed)\r\n // The second element in data array contains the current state\r\n const currentState = handlerData[0] || {} as Record<string, any>;\r\n\r\n // Get ref id for lifecycle tracking (if available)\r\n const refId = (currentState as any)?.$ref || null;\r\n\r\n // Check if this is first execution for this ref\r\n const isFirstExecution = refId && !this._activeContexts.has(refId);\r\n\r\n // Get existing context if any (to preserve lifecycle callbacks like intervals)\r\n const existingContext = refId ? this._activeContexts.get(refId) : null;\r\n\r\n // Create a NEW handler context for each execution with the current state\r\n // This ensures each interaction has its own isolated state\r\n // Pass 'this' so handlers can access component methods like toJSON()\r\n // Pass ctx so handlers can access ctx.interaction, ctx.data, ctx.locale, etc.\r\n const handlerContext = createHandlerContext(\r\n this.svelteComponentInfo!.scriptContent,\r\n typeof currentState === 'object' ? currentState : {},\r\n this,\r\n ctx,\r\n this._sourceDir,\r\n this.svelteComponentInfo!.inlineHandlers\r\n );\r\n\r\n const handlerFn = handlerContext.handlers[handlerInfo.handlerName];\r\n\r\n if (handlerFn && typeof handlerFn === 'function') {\r\n try {\r\n // Store context for lifecycle management\r\n if (refId) {\r\n // If there's an existing context, transfer its destroy callbacks to the new context\r\n // This preserves intervals/timers created in onMount\r\n if (existingContext && existingContext.destroyCallbacks) {\r\n // Merge existing destroy callbacks (don't run them!)\r\n handlerContext.destroyCallbacks.push(...existingContext.destroyCallbacks);\r\n }\r\n\r\n this._activeContexts.set(refId, handlerContext);\r\n\r\n // Wrap $unRef to call onDestroy when ref is deleted (only wrap once)\r\n const stateObj = currentState as any;\r\n if (stateObj.$unRef && !stateObj.__unRefWrapped__) {\r\n const originalUnRef = stateObj.$unRef.bind(stateObj);\r\n stateObj.$unRef = () => {\r\n // Run destroy callbacks before unref\r\n const ctx = this._activeContexts.get(refId);\r\n if (ctx && ctx.runDestroy) {\r\n ctx.runDestroy();\r\n }\r\n this._activeContexts.delete(refId);\r\n return originalUnRef();\r\n };\r\n stateObj.__unRefWrapped__ = true;\r\n }\r\n }\r\n\r\n // Run onMount callbacks only on first execution\r\n if (isFirstExecution && handlerContext.runMount) {\r\n handlerContext.runMount();\r\n }\r\n\r\n // Mark that we're inside handler execution (prevents auto-render during handler)\r\n handlerContext.setInHandler(true);\r\n\r\n try {\r\n // Bind 'this' to the DBIHTMLComponentsV2 instance so handlers can use this.toJSON()\r\n // Pass wrappedCtx so handlers use the proxy-wrapped ctx that tracks interaction calls\r\n // This ensures __asyncInteractionCalled__ flag is set when handler calls ctx.interaction.reply() etc.\r\n handlerFn.call(this, handlerContext.wrappedCtx, ...handlerData.slice(1));\r\n } finally {\r\n // Always reset handler execution flag\r\n handlerContext.setInHandler(false);\r\n }\r\n\r\n // Run effects after handler execution (state may have changed)\r\n handlerContext.runEffects();\r\n\r\n // If there are pending data changes and no interaction method was called,\r\n // flush the render now (synchronously uses interaction.update)\r\n if (handlerContext.hasPendingRender()) {\r\n handlerContext.flushRender();\r\n }\r\n } catch (error) {\r\n // Re-throw the error so it's visible to the developer\r\n console.error(`[DBI-Svelte] Handler \"${handlerInfo.handlerName}\" failed:`, error);\r\n throw error;\r\n }\r\n }\r\n }\r\n\r\n // Store last render's modals for showModal() to access\r\n // Note: Used internally by handler context, not truly private\r\n __lastRenderModals__: Map<string, any> | null = null;\r\n\r\n override async toJSON(arg: TDBIHTMLComponentsV2ToJSONArgs = {}): Promise<any> {\r\n if (this.mode === 'svelte' && this.template) {\r\n // Render Svelte component\r\n const result = await renderSvelteComponent(\r\n this.dbi as any,\r\n this.template,\r\n this.name,\r\n {\r\n data: arg.data,\r\n ttl: this.ttl\r\n }\r\n );\r\n\r\n // Store modals for showModal() to access\r\n this.__lastRenderModals__ = result.modals;\r\n\r\n return result.components;\r\n } else {\r\n // Use Eta template parsing (default)\r\n return parseHTMLComponentsV2(\r\n this.dbi as any,\r\n this.template!,\r\n this.name,\r\n {\r\n data: arg.data,\r\n ttl: this.ttl\r\n }\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Send the component to an interaction or channel and initialize lifecycle hooks (onMount)\r\n * This is the recommended way to send Svelte components with intervals/timers\r\n * \r\n * @param target - Discord interaction or channel to send to\r\n * @param options - Send options including data, flags, content\r\n * \r\n * @example\r\n * ```ts\r\n * const showcase = dbi.interaction(\"product-showcase\");\r\n * \r\n * // Send as interaction reply\r\n * await showcase.send(interaction, { data: { count: 0 } });\r\n * \r\n * // Send to a channel directly\r\n * const result = await showcase.send(channel, { data: { count: 0 } });\r\n * \r\n * // Send as followUp (if already replied)\r\n * const result = await showcase.send(interaction, { data: { count: 0 }, followUp: true });\r\n * \r\n * // Manual re-render from outside\r\n * await result.render();\r\n * ```\r\n */\r\n async send(target: any, options: TDBIHTMLComponentsV2SendOptions = {}): Promise<TDBIHTMLComponentsV2SendResult> {\r\n // Wait for Svelte component initialization if not yet completed\r\n if (this._initPromise) {\r\n await this._initPromise;\r\n }\r\n\r\n const { data = {}, flags = [\"IsComponentsV2\"], content, ephemeral, reply, followUp } = options;\r\n\r\n // Render components (toJSON is async) - this also creates $ref in data if not present\r\n const components = await this.toJSON({ data });\r\n\r\n // Build message options\r\n const messageOptions: any = { components, flags };\r\n if (content) messageOptions.content = content;\r\n if (ephemeral) messageOptions.flags = [...flags, \"Ephemeral\"];\r\n\r\n // Detect target type and send accordingly\r\n let message: any;\r\n const isInteraction = target.reply && target.user; // Interactions have both reply method and user property\r\n const isChannel = target.send && !target.user; // Channels have send but no user\r\n\r\n try {\r\n if (isInteraction) {\r\n if (followUp) {\r\n message = await target.followUp(messageOptions);\r\n } else {\r\n message = await target.reply(messageOptions);\r\n }\r\n } else if (isChannel) {\r\n message = await target.send(messageOptions);\r\n } else {\r\n throw new Error(\"Invalid target: must be an interaction or channel\");\r\n }\r\n } catch (error: any) {\r\n // Check if it's a Discord API error and enhance it with helpful context\r\n if (error.code || error.rawError || (error.message && error.message.includes('Invalid Form Body'))) {\r\n const source = this.file ? fs.readFileSync(this.file, 'utf-8') : this.template;\r\n throw parseDiscordAPIError(error, source, this.name, components);\r\n }\r\n throw error;\r\n }\r\n\r\n // If Svelte mode, create initial handler context and run onMount\r\n // After toJSON, data.$ref is guaranteed to exist (created in renderSvelteComponent)\r\n if (this.mode === 'svelte' && this.svelteComponentInfo && data.$ref) {\r\n const refId = data.$ref;\r\n\r\n // Create handler context with a fake ctx that has the message\r\n const fakeCtx = {\r\n interaction: {\r\n replied: true,\r\n deferred: false,\r\n message: message,\r\n }\r\n };\r\n\r\n const handlerContext = createHandlerContext(\r\n this.svelteComponentInfo.scriptContent,\r\n data,\r\n this,\r\n fakeCtx,\r\n this._sourceDir,\r\n this.svelteComponentInfo.inlineHandlers\r\n );\r\n\r\n // Store the context for lifecycle management\r\n this._activeContexts.set(refId, handlerContext);\r\n\r\n // Wrap $unRef to call onDestroy when ref is deleted\r\n if (data.$unRef) {\r\n const originalUnRef = data.$unRef.bind(data);\r\n data.$unRef = () => {\r\n if (handlerContext.runDestroy) {\r\n handlerContext.runDestroy();\r\n }\r\n this._activeContexts.delete(refId);\r\n return originalUnRef();\r\n };\r\n }\r\n\r\n // Run onMount callbacks\r\n handlerContext.runMount();\r\n\r\n // Run initial effects\r\n handlerContext.runEffects();\r\n\r\n // Return result object with render() method for manual re-rendering\r\n const component = this;\r\n return {\r\n message,\r\n data,\r\n render: async () => {\r\n // Run pre-render callbacks (async)\r\n await handlerContext.runPreRender();\r\n\r\n // Re-render the component\r\n const components = await component.toJSON({ data });\r\n await message.edit({\r\n components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n\r\n // Run after-render callbacks\r\n handlerContext.runAfterRender();\r\n },\r\n destroy: () => component.destroy(data)\r\n } as TDBIHTMLComponentsV2SendResult;\r\n }\r\n\r\n // For non-Svelte mode, return simple result object\r\n return {\r\n message,\r\n data,\r\n render: async () => {\r\n const components = await this.toJSON({ data });\r\n await message.edit({\r\n components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n },\r\n destroy: () => this.destroy(data)\r\n } as TDBIHTMLComponentsV2SendResult;\r\n }\r\n\r\n /**\r\n * Destroy a component instance by ref ID or data object\r\n * This runs onDestroy callbacks (clears intervals/timers) and removes the ref\r\n * \r\n * @param refOrData - Either a ref ID string or the data object with $ref\r\n * @returns true if destroyed, false if not found\r\n * \r\n * @example\r\n * ```ts\r\n * // Destroy by data object\r\n * showcase.destroy(data);\r\n * \r\n * // Destroy by ref ID\r\n * showcase.destroy(data.$ref);\r\n * \r\n * // Destroy all active instances of this component\r\n * showcase.destroyAll();\r\n * ```\r\n */\r\n destroy(refOrData: string | Record<string, any>): boolean {\r\n const refId = typeof refOrData === 'string' ? refOrData : refOrData?.$ref;\r\n\r\n if (!refId) {\r\n return false;\r\n }\r\n\r\n const context = this._activeContexts.get(refId);\r\n if (context) {\r\n // Run destroy callbacks (clears intervals, timers, etc.)\r\n if (context.runDestroy) {\r\n context.runDestroy();\r\n }\r\n this._activeContexts.delete(refId);\r\n }\r\n\r\n // Also delete from DBI refs store\r\n this.dbi.data.refs.delete(refId);\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Extract all field values from a modal interaction\r\n * Supports text inputs, select menus (string, user, role, mentionable, channel), and file uploads\r\n * \r\n * Returns an object where keys are the custom_id of each component and values are:\r\n * - For text inputs: string value\r\n * - For string selects: string[] of selected values\r\n * - For user selects: string[] of user IDs\r\n * - For role selects: string[] of role IDs\r\n * - For mentionable selects: { users: string[], roles: string[] }\r\n * - For channel selects: string[] of channel IDs\r\n * - For file uploads: attachment objects array\r\n */\r\n private _extractModalFields(modalInteraction: any): Record<string, any> {\r\n const fields: Record<string, any> = {};\r\n\r\n // Handle classic text input fields via ModalSubmitFields\r\n if (modalInteraction.fields && modalInteraction.fields.fields) {\r\n for (const [customId, field] of modalInteraction.fields.fields) {\r\n // Text input - field.value is the string\r\n // For select menus, value might be an array\r\n fields[customId] = field.values || field.value;\r\n }\r\n }\r\n\r\n // Handle new modal components from interaction.data.components\r\n // The new modal structure uses Label wrappers with nested components\r\n const data = modalInteraction.data || (modalInteraction as any).data;\r\n if (data && data.components) {\r\n this._extractFieldsFromComponents(data.components, fields);\r\n }\r\n\r\n // Also check for components directly on the interaction (some Discord.js versions)\r\n if (modalInteraction.components && Array.isArray(modalInteraction.components)) {\r\n this._extractFieldsFromInteractionComponents(modalInteraction.components, fields);\r\n }\r\n\r\n return fields;\r\n }\r\n\r\n /**\r\n * Extract fields from Discord.js style interaction components (ActionRow objects)\r\n */\r\n private _extractFieldsFromInteractionComponents(components: any[], fields: Record<string, any>) {\r\n for (const row of components) {\r\n // ActionRow has components property\r\n const rowComponents = row.components || [];\r\n for (const component of rowComponents) {\r\n const customId = component.customId || component.custom_id || component.id;\r\n if (!customId) continue;\r\n\r\n // Check component type\r\n const type = component.type;\r\n\r\n // Text Input (type 4)\r\n if (type === 4 || component.value !== undefined) {\r\n fields[customId] = component.value || '';\r\n }\r\n\r\n // Select menus (types 3, 5, 6, 7, 8) - check for values array\r\n if (component.values !== undefined) {\r\n fields[customId] = component.values;\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Recursively extract field values from component structure\r\n */\r\n private _extractFieldsFromComponents(components: any[], fields: Record<string, any>) {\r\n for (const component of components) {\r\n const type = component.type;\r\n // Support both custom_id and id for backward compatibility\r\n const customId = component.custom_id || component.id;\r\n\r\n // Type 18 = Label/Field - can have nested component or components\r\n if (type === 18) {\r\n if (component.component) {\r\n this._extractFieldsFromComponents([component.component], fields);\r\n }\r\n if (component.components) {\r\n this._extractFieldsFromComponents(component.components, fields);\r\n }\r\n continue;\r\n }\r\n\r\n // Type 1 = Action Row - has nested components array\r\n if (type === 1 && component.components) {\r\n this._extractFieldsFromComponents(component.components, fields);\r\n continue;\r\n }\r\n\r\n if (!customId) continue;\r\n\r\n switch (type) {\r\n case 4: // Text Input\r\n fields[customId] = component.value || '';\r\n break;\r\n\r\n case 3: // String Select\r\n fields[customId] = component.values || [];\r\n break;\r\n\r\n case 5: // User Select\r\n fields[customId] = component.values || [];\r\n break;\r\n\r\n case 6: // Role Select\r\n fields[customId] = component.values || [];\r\n break;\r\n\r\n case 7: // Mentionable Select - can have both users and roles\r\n // Discord returns resolved data for mentionables\r\n fields[customId] = {\r\n values: component.values || [],\r\n users: component.resolved?.users ? Object.keys(component.resolved.users) : [],\r\n roles: component.resolved?.roles ? Object.keys(component.resolved.roles) : []\r\n };\r\n break;\r\n\r\n case 8: // Channel Select\r\n fields[customId] = component.values || [];\r\n break;\r\n\r\n case 19: // File Upload\r\n // File uploads come through as attachments\r\n fields[customId] = component.attachments || [];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Destroy all active instances of this component\r\n * Useful for cleanup when the bot shuts down or component is unloaded\r\n * \r\n * @returns Number of instances destroyed\r\n */\r\n destroyAll(): number {\r\n let count = 0;\r\n for (const [refId, context] of this._activeContexts) {\r\n if (context.runDestroy) {\r\n context.runDestroy();\r\n }\r\n this.dbi.data.refs.delete(refId);\r\n count++;\r\n }\r\n this._activeContexts.clear();\r\n return count;\r\n }\r\n\r\n handlers?: any[] = [];\r\n}"]}
@@ -1 +1 @@
1
- {"version":3,"file":"svelteParser.d.ts","sourceRoot":"","sources":["../../../../../src/types/Components/HTMLComponentsV2/svelteParser.ts"],"names":[],"mappings":"AAwHA,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,uEAAuE;IACvE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,qFAAqF;IACrF,aAAa,CAAC,EAAE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: ''}
351
351
  // 1. Remove handler attributes (onclick, onchange, handler) - they shouldn't be in final HTML
352
352
  // 2. Inject auto-generated names for elements that need them
353
353
  //
354
- // We need to apply these in reverse position order to maintain correct offsets
354
+ // We apply removals first, then insertions, adjusting positions as we go
355
355
  let processedSource = source;
356
- const modifications = [];
357
- // Add attribute removals
358
- for (const { start, end } of attributesToRemove) {
359
- // Also remove any leading whitespace before the attribute
356
+ // First, apply all attribute removals (sorted by position descending)
357
+ // Don't eat leading whitespace - just remove the attribute itself
358
+ const sortedRemovals = [...attributesToRemove].sort((a, b) => b.start - a.start);
359
+ for (const { start, end } of sortedRemovals) {
360
+ // Remove one leading space if present (to avoid double spaces)
360
361
  let actualStart = start;
361
- while (actualStart > 0 && (source[actualStart - 1] === ' ' || source[actualStart - 1] === '\t')) {
362
+ if (actualStart > 0 && source[actualStart - 1] === ' ') {
362
363
  actualStart--;
363
364
  }
364
- modifications.push({ type: 'remove', start: actualStart, end, sortKey: actualStart });
365
+ processedSource = processedSource.slice(0, actualStart) + processedSource.slice(end);
365
366
  }
366
- // Add name injections
367
+ // Now re-parse the modified source to get correct positions for name injections
368
+ // Instead of re-parsing, we'll calculate the offset adjustments
369
+ // But this is complex - simpler approach: just work with the modified source directly
370
+ // Since we removed attributes, we need to re-identify elements that need names
371
+ // The safest approach: use regex to find elements without name attributes and add them
372
+ // For elements that need names, find them in the processed source and inject names
367
373
  for (const { node, name, eachContext } of elementsNeedingNames) {
368
- // Find the position right after the opening tag name
369
- // e.g., <button ...> -> insert after "button"
370
- const tagEnd = node.start + 1 + node.name.length; // +1 for '<'
374
+ const tagName = node.name.toLowerCase();
371
375
  let nameAttrValue;
372
376
  if (eachContext && eachContext.length > 0) {
373
- // Inside {#each} - generate dynamic name expression using loop variables
374
- // Build a unique key from all nested loop contexts
375
- // Priority: item.id > item.name > index
376
377
  const keyParts = [name];
377
378
  for (let i = 0; i < eachContext.length; i++) {
378
379
  const ctx = eachContext[i];
379
- // Use index variable if available, otherwise use a property from iter var
380
380
  if (ctx.indexVar) {
381
381
  keyParts.push(`\${${ctx.indexVar}}`);
382
382
  }
383
383
  else {
384
- // Try common unique identifiers: id, name, key, value
385
- // Using the iter var directly as fallback
386
384
  keyParts.push(`\${${ctx.iterVar}?.id ?? ${ctx.iterVar}?.name ?? ${ctx.iterVar}?.key ?? ${ctx.iterVar}?.value ?? JSON.stringify(${ctx.iterVar}).slice(0,20)}`);
387
385
  }
388
386
  }
389
- // Use backtick template literal for dynamic name
390
387
  nameAttrValue = `{\`${keyParts.join('_')}\`}`;
391
388
  }
392
389
  else {
393
- // Static name - use quotes
394
390
  nameAttrValue = `"${name}"`;
395
391
  }
396
- modifications.push({ type: 'insert', position: tagEnd, content: ` name=${nameAttrValue}`, sortKey: tagEnd });
397
- }
398
- // Sort by position descending so we don't mess up offsets
399
- // For same position, insertions should come before removals
400
- modifications.sort((a, b) => {
401
- if (b.sortKey !== a.sortKey)
402
- return b.sortKey - a.sortKey;
403
- // Same position: insert before remove (so remove accounts for inserted content if needed)
404
- return a.type === 'insert' ? -1 : 1;
405
- });
406
- // Apply all modifications
407
- for (const mod of modifications) {
408
- if (mod.type === 'remove') {
409
- processedSource = processedSource.slice(0, mod.start) + processedSource.slice(mod.end);
410
- }
411
- else {
412
- processedSource = processedSource.slice(0, mod.position) + mod.content + processedSource.slice(mod.position);
413
- }
392
+ // Find this element in the processed source and add name attribute
393
+ // Match the tag without a name attribute
394
+ const tagRegex = new RegExp(`(<${tagName})(?![^>]*\\bname[=\\s])([^>]*>)`, 'i');
395
+ processedSource = processedSource.replace(tagRegex, `$1 name=${nameAttrValue}$2`);
414
396
  }
415
397
  // Extract declared props from $props() destructuring
416
398
  const declaredProps = [];
@@ -1 +1 @@
1
- {"version":3,"file":"svelteParser.js","sourceRoot":"","sources":["../../../../../src/types/Components/HTMLComponentsV2/svelteParser.ts"],"names":[],"mappings":";;AAoKA,oDA+YC;AAmHD,0DAwHC;AAKD,sDAiBC;AAuID,oDAi0BC;AA1vDD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C,MAAM,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QACzD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IAED,yDAAyD;IACzD,MAAM,iBAAiB,GAAG,gDAAgD,CAAC;IAC3E,OAAO,CAAC,KAAK,GAAG,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QACzD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IAED,+CAA+C;IAC/C,MAAM,kBAAkB,GAAG,8DAA8D,CAAC;IAC1F,OAAO,CAAC,KAAK,GAAG,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QAC1D,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IAED,kEAAkE;IAClE,MAAM,gBAAgB,GAAG,wDAAwD,CAAC;IAClF,OAAO,CAAC,KAAK,GAAG,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QACxD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IAED,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,oBAAoB;AAClD,CAAC","sourcesContent":["import * as stuffs from \"stuffs\";\r\n\r\n// Lazy imports to avoid issues with package managers that don't properly hoist dependencies\r\nlet _parse: typeof import(\"svelte/compiler\").parse;\r\n\r\nasync function ensureImports() {\r\n if (!_parse) {\r\n const svelteCompiler = await import(\"svelte/compiler\");\r\n _parse = svelteCompiler.parse;\r\n }\r\n}\r\n\r\n/**\r\n * Context passed to walker callback containing parent information\r\n */\r\ninterface WalkContext {\r\n /** Stack of parent nodes from root to current */\r\n parents: any[];\r\n /** Information about enclosing {#each} blocks */\r\n eachBlocks: Array<{\r\n node: any;\r\n /** The iteration variable name (e.g., \"item\" in {#each items as item}) */\r\n iterVar: string;\r\n /** The index variable name if specified (e.g., \"i\" in {#each items as item, i}) */\r\n indexVar?: string;\r\n /** Expression for unique key (iterVar.id, iterVar.name, or index) */\r\n keyExpr: string;\r\n }>;\r\n}\r\n\r\n/**\r\n * Simple AST walker for Svelte AST nodes with parent tracking\r\n */\r\nfunction walkSvelteAst(node: any, callback: (node: any, context: WalkContext) => void, context?: WalkContext) {\r\n if (!node || typeof node !== 'object') return;\r\n\r\n // Initialize context if not provided\r\n const ctx: WalkContext = context || { parents: [], eachBlocks: [] };\r\n\r\n callback(node, ctx);\r\n\r\n // Create new context for children with this node as parent\r\n const childContext: WalkContext = {\r\n parents: [...ctx.parents, node],\r\n eachBlocks: [...ctx.eachBlocks]\r\n };\r\n\r\n // If this is an EachBlock, add it to the context for children\r\n if (node.type === 'EachBlock') {\r\n const iterVar = node.context?.name || node.context?.type === 'Identifier' ? node.context.name : 'item';\r\n const indexVar = node.index;\r\n\r\n // Determine best key expression for unique naming\r\n // Priority: explicit key > iter.id > iter.name > index > counter\r\n let keyExpr = indexVar || `__idx_${ctx.eachBlocks.length}`;\r\n\r\n childContext.eachBlocks = [...ctx.eachBlocks, {\r\n node,\r\n iterVar,\r\n indexVar,\r\n keyExpr\r\n }];\r\n }\r\n\r\n // Walk children based on node type\r\n if (node.children && Array.isArray(node.children)) {\r\n for (const child of node.children) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n }\r\n if (node.fragment && node.fragment.nodes) {\r\n for (const child of node.fragment.nodes) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n }\r\n if (node.nodes && Array.isArray(node.nodes)) {\r\n for (const child of node.nodes) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n }\r\n // Handle {#each} body\r\n if (node.body && node.type === 'EachBlock') {\r\n if (node.body.nodes) {\r\n for (const child of node.body.nodes) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n } else if (Array.isArray(node.body)) {\r\n for (const child of node.body) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n } else {\r\n walkSvelteAst(node.body, callback, childContext);\r\n }\r\n } else if (node.body) {\r\n if (Array.isArray(node.body)) {\r\n for (const child of node.body) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n } else {\r\n walkSvelteAst(node.body, callback, childContext);\r\n }\r\n }\r\n // Handle other potential child properties\r\n if (node.else) {\r\n walkSvelteAst(node.else, callback, childContext);\r\n }\r\n if (node.consequent) {\r\n walkSvelteAst(node.consequent, callback, childContext);\r\n }\r\n if (node.alternate) {\r\n walkSvelteAst(node.alternate, callback, childContext);\r\n }\r\n if (node.then) {\r\n walkSvelteAst(node.then, callback, childContext);\r\n }\r\n if (node.catch) {\r\n walkSvelteAst(node.catch, callback, childContext);\r\n }\r\n}\r\n\r\nexport interface SvelteHandlerInfo {\r\n name: string;\r\n handlerName: string;\r\n eventType: string; // onclick, onchange, onsubmit, etc.\r\n element: string; // button, string-select, components (for modal), etc.\r\n /** If this is an inline handler, contains the extracted source code */\r\n inlineCode?: string;\r\n /** Whether this handler is an inline arrow function or function expression */\r\n isInline?: boolean;\r\n /** Whether this handler has a dynamic name (inside {#each}) - use prefix matching */\r\n isDynamicName?: boolean;\r\n}\r\n\r\nexport interface ModalHandlerInfo {\r\n modalId: string;\r\n onsubmitHandler?: string; // Handler function name for onsubmit\r\n}\r\n\r\nexport interface SvelteValidationWarning {\r\n type: 'missing-data' | 'unused-data' | 'undefined-handler' | 'syntax-error' | 'runtime-error';\r\n message: string;\r\n details?: string;\r\n}\r\n\r\nexport interface SvelteComponentInfo {\r\n handlers: Map<string, SvelteHandlerInfo>;\r\n /** Modal onsubmit handlers keyed by modal id */\r\n modalHandlers: Map<string, ModalHandlerInfo>;\r\n scriptContent: string;\r\n processedSource: string; // Source with auto-generated names injected\r\n /** Props extracted from $props() destructuring */\r\n declaredProps: string[];\r\n /** Props that have default values (don't require data) */\r\n propsWithDefaults: string[];\r\n /** Function names declared in the script */\r\n declaredFunctions: string[];\r\n /** Inline handler code extracted from template (keyed by generated handler name) */\r\n inlineHandlers: Map<string, string>;\r\n}\r\n\r\n/**\r\n * Parse a Svelte component and extract event handlers\r\n * Also injects auto-generated names into elements that have handlers but no name\r\n */\r\nexport async function parseSvelteComponent(source: string, data?: Record<string, any>): Promise<SvelteComponentInfo> {\r\n await ensureImports();\r\n\r\n let ast;\r\n try {\r\n ast = _parse(source);\r\n } catch (parseError: any) {\r\n // Format Svelte parse error with helpful details\r\n const errorMessage = parseError.message || 'Unknown parse error';\r\n const location = parseError.start || parseError.loc;\r\n let details = errorMessage;\r\n\r\n if (location) {\r\n const lines = source.split('\\n');\r\n const lineNum = location.line || 1;\r\n const column = location.column || 0;\r\n const errorLine = lines[lineNum - 1] || '';\r\n const prevLine = lines[lineNum - 2] || '';\r\n const nextLine = lines[lineNum] || '';\r\n\r\n details = `\r\nSvelte Parse Error at line ${lineNum}, column ${column}:\r\n${errorMessage}\r\n\r\n${lineNum > 1 ? `${lineNum - 1} | ${prevLine}\\n` : ''}${lineNum} | ${errorLine}\r\n${' '.repeat(String(lineNum).length + 3 + column)}^\r\n${nextLine ? `${lineNum + 1} | ${nextLine}` : ''}\r\n`.trim();\r\n }\r\n\r\n const enhancedError = new Error(`[DBI-Svelte] Failed to parse Svelte component:\\n${details}`);\r\n (enhancedError as any).originalError = parseError;\r\n (enhancedError as any).type = 'svelte-parse-error';\r\n throw enhancedError;\r\n }\r\n\r\n const handlers = new Map<string, SvelteHandlerInfo>();\r\n const modalHandlers = new Map<string, ModalHandlerInfo>();\r\n let scriptContent = \"\";\r\n\r\n // Extract script content\r\n if (ast.instance) {\r\n scriptContent = source.substring(ast.instance.content.start, ast.instance.content.end);\r\n }\r\n\r\n // Track elements that need auto-generated names (node -> name mapping)\r\n // We'll inject these into the source after the walk\r\n const elementsNeedingNames: Array<{\r\n node: any;\r\n name: string;\r\n handlerName: string;\r\n eventType: string;\r\n element: string;\r\n /** If inside {#each}, contains info for dynamic name generation */\r\n eachContext?: Array<{\r\n iterVar: string;\r\n indexVar?: string;\r\n keyExpr: string;\r\n }>;\r\n }> = [];\r\n let autoNameCounter = 0;\r\n\r\n // Track inline handlers (arrow functions or function expressions in event attributes)\r\n const inlineHandlers = new Map<string, string>();\r\n let inlineHandlerCounter = 0;\r\n\r\n // Track handler attributes to remove from source (handler, onclick, onchange, etc.)\r\n const attributesToRemove: Array<{ start: number; end: number }> = [];\r\n\r\n // Walk through HTML nodes to find event handlers\r\n walkSvelteAst(ast.html || ast.fragment, (node: any, walkContext: WalkContext) => {\r\n if (node.type === \"Element\" || node.type === \"InlineComponent\" || node.type === \"RegularElement\" || node.type === \"Component\") {\r\n const attributes = node.attributes || [];\r\n const nodeName = node.name.toLowerCase();\r\n\r\n // Special handling for <components type=\"modal\"> elements\r\n if (nodeName === \"components\") {\r\n const typeAttr = attributes.find((attr: any) =>\r\n attr.type === \"Attribute\" && attr.name === \"type\"\r\n );\r\n const typeValue = typeAttr ? getAttributeValue(typeAttr) : null;\r\n\r\n if (typeValue === \"modal\") {\r\n // This is a modal definition - extract id and onsubmit handler\r\n const idAttr = attributes.find((attr: any) =>\r\n attr.type === \"Attribute\" && attr.name === \"id\"\r\n );\r\n const modalId = idAttr ? getAttributeValue(idAttr) : null;\r\n\r\n if (modalId) {\r\n const modalInfo: ModalHandlerInfo = { modalId };\r\n\r\n // Find onsubmit handler\r\n for (const attr of attributes) {\r\n const isOnSubmit = (attr.type === \"Attribute\" && attr.name === \"onsubmit\") ||\r\n (attr.type === \"EventHandler\" && attr.name === \"submit\");\r\n\r\n if (isOnSubmit) {\r\n let handlerName = \"\";\r\n\r\n if (attr.type === \"Attribute\" && Array.isArray(attr.value)) {\r\n const exprValue = attr.value.find((v: any) => v.type === \"ExpressionTag\" || v.type === \"MustacheTag\");\r\n if (exprValue && exprValue.expression) {\r\n if (exprValue.expression.type === \"Identifier\") {\r\n handlerName = exprValue.expression.name;\r\n } else if (exprValue.expression.type === \"CallExpression\" && exprValue.expression.callee) {\r\n handlerName = exprValue.expression.callee.name;\r\n }\r\n }\r\n } else if (attr.expression) {\r\n if (attr.expression.type === \"Identifier\") {\r\n handlerName = attr.expression.name;\r\n } else if (attr.expression.type === \"CallExpression\" && attr.expression.callee) {\r\n handlerName = attr.expression.callee.name;\r\n }\r\n }\r\n\r\n if (handlerName) {\r\n modalInfo.onsubmitHandler = handlerName;\r\n }\r\n\r\n // Track this attribute for removal from source (onsubmit shouldn't be in HTML)\r\n if (attr.start !== undefined && attr.end !== undefined) {\r\n attributesToRemove.push({ start: attr.start, end: attr.end });\r\n }\r\n break;\r\n }\r\n }\r\n\r\n modalHandlers.set(modalId, modalInfo);\r\n }\r\n }\r\n return; // Don't process <components> as regular elements\r\n }\r\n\r\n // Find name attribute\r\n const nameAttr = attributes.find((attr: any) =>\r\n attr.type === \"Attribute\" && attr.name === \"name\"\r\n );\r\n\r\n // Check if element has an onclick/onchange/handler and get the handler info\r\n let foundHandler: { eventType: string; handlerName: string; inlineCode?: string; isInline?: boolean } | null = null;\r\n\r\n for (const attr of attributes) {\r\n const isEventHandler = attr.type === \"EventHandler\";\r\n const isOnAttribute = attr.type === \"Attribute\" && attr.name && attr.name.startsWith(\"on\");\r\n const isHandlerAttribute = attr.type === \"Attribute\" && attr.name === \"handler\";\r\n\r\n if (isEventHandler || isOnAttribute || isHandlerAttribute) {\r\n // For \"handler\" attribute, use the element type to determine eventType\r\n // button -> onclick, select -> onchange\r\n let eventType = attr.name;\r\n if (isHandlerAttribute) {\r\n const elementName = node.name.toLowerCase();\r\n if (elementName === \"button\") {\r\n eventType = \"onclick\";\r\n } else if (elementName.includes(\"select\")) {\r\n eventType = \"onchange\";\r\n } else {\r\n eventType = \"handler\"; // fallback\r\n }\r\n }\r\n let handlerName = \"\";\r\n let inlineCode: string | undefined;\r\n let isInline = false;\r\n\r\n if (attr.type === \"Attribute\" && Array.isArray(attr.value)) {\r\n const exprValue = attr.value.find((v: any) => v.type === \"ExpressionTag\" || v.type === \"MustacheTag\");\r\n if (exprValue && exprValue.expression) {\r\n if (exprValue.expression.type === \"Identifier\") {\r\n handlerName = exprValue.expression.name;\r\n } else if (exprValue.expression.type === \"CallExpression\" && exprValue.expression.callee) {\r\n handlerName = exprValue.expression.callee.name;\r\n } else if (exprValue.expression.type === \"ArrowFunctionExpression\" || exprValue.expression.type === \"FunctionExpression\") {\r\n // Inline arrow function or function expression - extract the code\r\n isInline = true;\r\n handlerName = `__inline_handler_${inlineHandlerCounter++}`;\r\n // Extract the source code from the expression\r\n const expr = exprValue.expression;\r\n if (expr.start !== undefined && expr.end !== undefined) {\r\n inlineCode = source.substring(expr.start, expr.end);\r\n }\r\n }\r\n }\r\n } else if (attr.expression) {\r\n if (attr.expression.type === \"Identifier\") {\r\n handlerName = attr.expression.name;\r\n } else if (attr.expression.type === \"CallExpression\" && attr.expression.callee) {\r\n handlerName = attr.expression.callee.name;\r\n } else if (attr.expression.type === \"MemberExpression\") {\r\n handlerName = extractMemberExpressionName(attr.expression);\r\n } else if (attr.expression.type === \"ArrowFunctionExpression\" || attr.expression.type === \"FunctionExpression\") {\r\n // Inline arrow function or function expression - extract the code\r\n isInline = true;\r\n handlerName = `__inline_handler_${inlineHandlerCounter++}`;\r\n // Extract the source code from the expression\r\n const expr = attr.expression;\r\n if (expr.start !== undefined && expr.end !== undefined) {\r\n inlineCode = source.substring(expr.start, expr.end);\r\n }\r\n }\r\n }\r\n\r\n if (handlerName) {\r\n foundHandler = { eventType, handlerName, inlineCode, isInline };\r\n // If it's an inline handler, store the code\r\n if (isInline && inlineCode) {\r\n inlineHandlers.set(handlerName, inlineCode);\r\n }\r\n // Track this attribute for removal from source\r\n if (attr.start !== undefined && attr.end !== undefined) {\r\n attributesToRemove.push({ start: attr.start, end: attr.end });\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (!foundHandler) return; // No handler found, skip\r\n\r\n let componentName: string;\r\n const isInsideEach = walkContext.eachBlocks.length > 0;\r\n\r\n if (nameAttr) {\r\n componentName = getAttributeValue(nameAttr);\r\n } else {\r\n // No name attribute - generate one\r\n // If inside {#each}, we need a DYNAMIC name using the loop variable\r\n const positionKey = `${node.name.toLowerCase()}_${autoNameCounter++}`;\r\n\r\n if (isInsideEach) {\r\n // Inside {#each} - we'll inject a dynamic name expression\r\n // The actual name will be generated at runtime using loop variables\r\n componentName = `__auto_${positionKey}`;\r\n } else {\r\n // Not in loop - use static deterministic name\r\n // If data is provided, use/store in $autoNames for persistence across re-renders\r\n if (data) {\r\n if (!data.$autoNames) {\r\n data.$autoNames = {};\r\n }\r\n if (!data.$autoNames[positionKey]) {\r\n data.$autoNames[positionKey] = `__auto_${positionKey}`;\r\n }\r\n componentName = data.$autoNames[positionKey];\r\n } else {\r\n componentName = `__auto_${positionKey}`;\r\n }\r\n }\r\n\r\n // Track this element for source injection\r\n elementsNeedingNames.push({\r\n node,\r\n name: componentName,\r\n handlerName: foundHandler.handlerName,\r\n eventType: foundHandler.eventType,\r\n element: node.name.toLowerCase(),\r\n eachContext: isInsideEach ? walkContext.eachBlocks.map(b => ({\r\n iterVar: b.iterVar,\r\n indexVar: b.indexVar,\r\n keyExpr: b.keyExpr\r\n })) : undefined\r\n });\r\n }\r\n\r\n // Add to handlers map\r\n handlers.set(componentName, {\r\n name: componentName,\r\n handlerName: foundHandler.handlerName,\r\n eventType: foundHandler.eventType,\r\n element: node.name.toLowerCase(),\r\n inlineCode: foundHandler.inlineCode,\r\n isInline: foundHandler.isInline,\r\n isDynamicName: isInsideEach,\r\n });\r\n }\r\n });\r\n\r\n // Process source modifications:\r\n // 1. Remove handler attributes (onclick, onchange, handler) - they shouldn't be in final HTML\r\n // 2. Inject auto-generated names for elements that need them\r\n // \r\n // We need to apply these in reverse position order to maintain correct offsets\r\n let processedSource = source;\r\n\r\n // Collect all modifications with their positions\r\n type SourceModification =\r\n | { type: 'remove'; start: number; end: number; sortKey: number }\r\n | { type: 'insert'; position: number; content: string; sortKey: number };\r\n\r\n const modifications: SourceModification[] = [];\r\n\r\n // Add attribute removals\r\n for (const { start, end } of attributesToRemove) {\r\n // Also remove any leading whitespace before the attribute\r\n let actualStart = start;\r\n while (actualStart > 0 && (source[actualStart - 1] === ' ' || source[actualStart - 1] === '\\t')) {\r\n actualStart--;\r\n }\r\n modifications.push({ type: 'remove', start: actualStart, end, sortKey: actualStart });\r\n }\r\n\r\n // Add name injections\r\n for (const { node, name, eachContext } of elementsNeedingNames) {\r\n // Find the position right after the opening tag name\r\n // e.g., <button ...> -> insert after \"button\"\r\n const tagEnd = node.start + 1 + node.name.length; // +1 for '<'\r\n\r\n let nameAttrValue: string;\r\n\r\n if (eachContext && eachContext.length > 0) {\r\n // Inside {#each} - generate dynamic name expression using loop variables\r\n // Build a unique key from all nested loop contexts\r\n // Priority: item.id > item.name > index\r\n const keyParts: string[] = [name];\r\n\r\n for (let i = 0; i < eachContext.length; i++) {\r\n const ctx = eachContext[i];\r\n // Use index variable if available, otherwise use a property from iter var\r\n if (ctx.indexVar) {\r\n keyParts.push(`\\${${ctx.indexVar}}`);\r\n } else {\r\n // Try common unique identifiers: id, name, key, value\r\n // Using the iter var directly as fallback\r\n keyParts.push(`\\${${ctx.iterVar}?.id ?? ${ctx.iterVar}?.name ?? ${ctx.iterVar}?.key ?? ${ctx.iterVar}?.value ?? JSON.stringify(${ctx.iterVar}).slice(0,20)}`);\r\n }\r\n }\r\n\r\n // Use backtick template literal for dynamic name\r\n nameAttrValue = `{\\`${keyParts.join('_')}\\`}`;\r\n } else {\r\n // Static name - use quotes\r\n nameAttrValue = `\"${name}\"`;\r\n }\r\n\r\n modifications.push({ type: 'insert', position: tagEnd, content: ` name=${nameAttrValue}`, sortKey: tagEnd });\r\n }\r\n\r\n // Sort by position descending so we don't mess up offsets\r\n // For same position, insertions should come before removals\r\n modifications.sort((a, b) => {\r\n if (b.sortKey !== a.sortKey) return b.sortKey - a.sortKey;\r\n // Same position: insert before remove (so remove accounts for inserted content if needed)\r\n return a.type === 'insert' ? -1 : 1;\r\n });\r\n\r\n // Apply all modifications\r\n for (const mod of modifications) {\r\n if (mod.type === 'remove') {\r\n processedSource = processedSource.slice(0, mod.start) + processedSource.slice(mod.end);\r\n } else {\r\n processedSource = processedSource.slice(0, mod.position) + mod.content + processedSource.slice(mod.position);\r\n }\r\n }\r\n\r\n // Extract declared props from $props() destructuring\r\n const declaredProps: string[] = [];\r\n const propsWithDefaults: string[] = [];\r\n const propsMatch = scriptContent.match(/(?:const|let)\\s+\\{([\\s\\S]*?)\\}\\s*=\\s*\\$props\\(\\)/);\r\n if (propsMatch) {\r\n const propsContent = propsMatch[1];\r\n // Remove comments first\r\n const cleanedContent = propsContent\r\n .replace(/\\/\\/.*$/gm, '')\r\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\r\n const props = parsePropsContent(cleanedContent);\r\n for (const prop of props) {\r\n if (prop.name) {\r\n declaredProps.push(prop.name);\r\n if (prop.defaultValue !== undefined) {\r\n propsWithDefaults.push(prop.name);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Extract declared function names\r\n const declaredFunctions: string[] = [];\r\n const funcRegex = /(?:async\\s+)?function\\s+(\\w+)\\s*\\(/g;\r\n let funcMatch;\r\n while ((funcMatch = funcRegex.exec(scriptContent)) !== null) {\r\n declaredFunctions.push(funcMatch[1]);\r\n }\r\n // Also match arrow functions assigned to variables: const/let/var name = (async) () =>\r\n const arrowRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>/g;\r\n while ((funcMatch = arrowRegex.exec(scriptContent)) !== null) {\r\n declaredFunctions.push(funcMatch[1]);\r\n }\r\n\r\n return {\r\n handlers,\r\n modalHandlers,\r\n scriptContent,\r\n processedSource,\r\n declaredProps,\r\n propsWithDefaults,\r\n declaredFunctions,\r\n inlineHandlers\r\n };\r\n}\r\n\r\n/**\r\n * Extract the full name from a MemberExpression (e.g., obj.method)\r\n */\r\nfunction extractMemberExpressionName(expr: any): string {\r\n if (expr.type === \"Identifier\") {\r\n return expr.name;\r\n }\r\n if (expr.type === \"MemberExpression\") {\r\n const object = extractMemberExpressionName(expr.object);\r\n const property = expr.property.name || expr.property.value;\r\n return `${object}.${property}`;\r\n }\r\n return \"\";\r\n}\r\n\r\n/**\r\n * Get the value from an attribute\r\n */\r\nfunction getAttributeValue(attr: any): string {\r\n if (!attr.value) return \"\";\r\n\r\n if (Array.isArray(attr.value)) {\r\n // Static text value\r\n if (attr.value[0]?.type === \"Text\") {\r\n return attr.value[0].data;\r\n }\r\n // Expression value\r\n if (attr.value[0]?.expression) {\r\n return extractExpressionValue(attr.value[0].expression);\r\n }\r\n }\r\n\r\n return \"\";\r\n}\r\n\r\n/**\r\n * Extract value from an expression\r\n */\r\nfunction extractExpressionValue(expr: any): string {\r\n if (expr.type === \"Identifier\") {\r\n return expr.name;\r\n }\r\n if (expr.type === \"Literal\") {\r\n return String(expr.value);\r\n }\r\n return \"\";\r\n}\r\n\r\n/**\r\n * Parse $props() destructuring content with proper brace/bracket counting\r\n * Handles nested objects like: { name, options = { a: 1, b: [1, 2] }, count = 0 }\r\n */\r\nfunction parsePropsContent(content: string): Array<{ name: string; defaultValue?: string }> {\r\n const props: Array<{ name: string; defaultValue?: string }> = [];\r\n let current = '';\r\n let braceCount = 0;\r\n let bracketCount = 0;\r\n let parenCount = 0;\r\n let inString: string | null = null;\r\n\r\n for (let i = 0; i <= content.length; i++) {\r\n const char = content[i];\r\n const prevChar = i > 0 ? content[i - 1] : '';\r\n\r\n // Handle string boundaries\r\n if ((char === '\"' || char === \"'\" || char === '`') && prevChar !== '\\\\') {\r\n if (inString === char) {\r\n inString = null;\r\n } else if (!inString) {\r\n inString = char;\r\n }\r\n }\r\n\r\n // Only process structural characters when not in a string\r\n if (!inString) {\r\n if (char === '{') braceCount++;\r\n else if (char === '}') braceCount--;\r\n else if (char === '[') bracketCount++;\r\n else if (char === ']') bracketCount--;\r\n else if (char === '(') parenCount++;\r\n else if (char === ')') parenCount--;\r\n\r\n // Split on comma only when at top level (no nested braces/brackets/parens)\r\n if ((char === ',' || i === content.length) && braceCount === 0 && bracketCount === 0 && parenCount === 0) {\r\n const trimmed = current.trim();\r\n if (trimmed) {\r\n // Parse \"name = defaultValue\" or just \"name\"\r\n const equalsIndex = trimmed.indexOf('=');\r\n if (equalsIndex > 0) {\r\n const name = trimmed.substring(0, equalsIndex).trim();\r\n const defaultValue = trimmed.substring(equalsIndex + 1).trim();\r\n props.push({ name, defaultValue });\r\n } else {\r\n props.push({ name: trimmed });\r\n }\r\n }\r\n current = '';\r\n continue;\r\n }\r\n }\r\n\r\n if (i < content.length) {\r\n current += char;\r\n }\r\n }\r\n\r\n return props;\r\n}\r\n\r\n/**\r\n * Validate a Svelte component and return warnings\r\n * Call this during development/registration to catch potential issues early\r\n */\r\nexport function validateSvelteComponent(\r\n componentInfo: SvelteComponentInfo,\r\n data: Record<string, any> = {},\r\n componentName: string = 'unknown'\r\n): SvelteValidationWarning[] {\r\n const warnings: SvelteValidationWarning[] = [];\r\n\r\n // Skip internal props/data keys (used by the framework)\r\n const internalKeys = ['$ref', '$unRef', '__unRefWrapped__', '$autoNames', 'data'];\r\n\r\n // 1. Check for props declared but not provided in data (missing required data)\r\n // Skip props that have default values - they don't require data\r\n for (const prop of componentInfo.declaredProps) {\r\n if (internalKeys.includes(prop)) continue;\r\n if (componentInfo.propsWithDefaults.includes(prop)) continue; // Has default, not required\r\n if (!(prop in data)) {\r\n warnings.push({\r\n type: 'missing-data',\r\n message: `[${componentName}] Prop \"${prop}\" is declared in $props() without a default value but not provided in data`,\r\n details: `Add \"${prop}\" to your data object or provide a default value in $props()`\r\n });\r\n }\r\n }\r\n\r\n // 2. Check for data provided but not declared in props (potential typo or unused)\r\n for (const key of Object.keys(data)) {\r\n if (internalKeys.includes(key)) continue;\r\n if (key.startsWith('$')) continue; // Skip all $-prefixed internal keys\r\n if (!componentInfo.declaredProps.includes(key)) {\r\n warnings.push({\r\n type: 'unused-data',\r\n message: `[${componentName}] Data key \"${key}\" is provided but not declared in $props()`,\r\n details: `This data won't be accessible in the component. Add it to $props() destructuring.`\r\n });\r\n }\r\n }\r\n\r\n // 3. Check for undefined handlers referenced in elements\r\n // Skip inline handlers (they are extracted from template, not defined in script)\r\n for (const [elementName, handlerInfo] of componentInfo.handlers) {\r\n // Skip inline handlers - they are defined in the template, not the script\r\n if (handlerInfo.isInline) continue;\r\n if (!componentInfo.declaredFunctions.includes(handlerInfo.handlerName)) {\r\n warnings.push({\r\n type: 'undefined-handler',\r\n message: `[${componentName}] Handler \"${handlerInfo.handlerName}\" referenced by <${handlerInfo.element} name=\"${elementName}\"> is not defined`,\r\n details: `Make sure to define \"function ${handlerInfo.handlerName}(ctx) { ... }\" in your script`\r\n });\r\n }\r\n }\r\n\r\n // 4. Check for undefined modal submit handlers\r\n for (const [modalId, modalInfo] of componentInfo.modalHandlers) {\r\n if (modalInfo.onsubmitHandler && !componentInfo.declaredFunctions.includes(modalInfo.onsubmitHandler)) {\r\n warnings.push({\r\n type: 'undefined-handler',\r\n message: `[${componentName}] Modal submit handler \"${modalInfo.onsubmitHandler}\" for modal \"${modalId}\" is not defined`,\r\n details: `Make sure to define \"function ${modalInfo.onsubmitHandler}(ctx, fields) { ... }\" in your script`\r\n });\r\n }\r\n }\r\n\r\n // 5. Check for modal handler signatures (ctx parameter is optional for regular handlers)\r\n // Only modal handlers MUST have fields parameter to access submitted data\r\n const handlerFunctionRegex = /(?:async\\s+)?function\\s+(\\w+)\\s*\\(\\s*(\\w*)\\s*(?:,\\s*(\\w+))?\\s*\\)/g;\r\n let match;\r\n const scriptContent = componentInfo.scriptContent;\r\n\r\n while ((match = handlerFunctionRegex.exec(scriptContent)) !== null) {\r\n const funcName = match[1];\r\n const firstParam = match[2];\r\n const secondParam = match[3];\r\n\r\n // Only check modal handlers - they need 'fields' param to access form data\r\n const isModalHandler = Array.from(componentInfo.modalHandlers.values()).some(m => m.onsubmitHandler === funcName);\r\n\r\n if (isModalHandler && !secondParam) {\r\n warnings.push({\r\n type: 'syntax-error',\r\n message: `[${componentName}] Modal handler \"${funcName}\" should have \"ctx\" and \"fields\" parameters`,\r\n details: `Change to \"function ${funcName}(ctx, fields) { ... }\" to receive submitted form data`\r\n });\r\n }\r\n }\r\n\r\n // 6. Check for common template mistakes\r\n const templateContent = componentInfo.processedSource;\r\n\r\n // Check for onclick= without braces (common mistake)\r\n const badOnClickRegex = /onclick\\s*=\\s*[\"']([^\"']+)[\"']/gi;\r\n while ((match = badOnClickRegex.exec(templateContent)) !== null) {\r\n if (!match[1].startsWith('{')) {\r\n warnings.push({\r\n type: 'syntax-error',\r\n message: `[${componentName}] onclick handler should use curly braces: onclick={${match[1]}}`,\r\n details: `String values are not valid for event handlers. Use onclick={handlerName} syntax.`\r\n });\r\n }\r\n }\r\n\r\n // Check for undefined variables in {expression} blocks (basic check)\r\n const expressionRegex = /\\{([^}]+)\\}/g;\r\n const knownIdentifiers = new Set([\r\n ...componentInfo.declaredProps,\r\n ...componentInfo.declaredFunctions,\r\n // Common Svelte/JS globals\r\n 'true', 'false', 'null', 'undefined', 'console', 'Math', 'JSON', 'Array', 'Object',\r\n 'Date', 'Number', 'String', 'Boolean', 'Promise', 'Map', 'Set',\r\n // Common Svelte constructs\r\n '#if', '/if', '#each', '/each', '#await', '/await', ':else', ':then', ':catch',\r\n '@html', '@debug', '@const'\r\n ]);\r\n\r\n // Add variables from script (let, const, var declarations)\r\n const varDeclRegex = /(?:let|const|var)\\s+(\\w+)/g;\r\n while ((match = varDeclRegex.exec(scriptContent)) !== null) {\r\n knownIdentifiers.add(match[1]);\r\n }\r\n\r\n return warnings;\r\n}\r\n\r\n/**\r\n * Log validation warnings to console with colors\r\n */\r\nexport function logValidationWarnings(warnings: SvelteValidationWarning[]): void {\r\n if (warnings.length === 0) return;\r\n\r\n console.warn(`\\n⚠️ Svelte Component Validation Warnings (${warnings.length}):`);\r\n\r\n for (const warning of warnings) {\r\n const icon = warning.type === 'missing-data' ? '❌' :\r\n warning.type === 'unused-data' ? '⚠️' :\r\n warning.type === 'undefined-handler' ? '🔗' :\r\n warning.type === 'syntax-error' ? '💥' : '⚡';\r\n\r\n console.warn(` ${icon} ${warning.message}`);\r\n if (warning.details) {\r\n console.warn(` └─ ${warning.details}`);\r\n }\r\n }\r\n console.warn('');\r\n}\r\n\r\nexport interface HandlerContextResult {\r\n handlers: Record<string, Function>;\r\n effects: Function[];\r\n runEffects: () => void;\r\n hasPendingRender: () => boolean;\r\n flushRender: () => Promise<void>;\r\n wrappedCtx: any; // Proxy-wrapped ctx for passing to handlers\r\n // Lifecycle hooks\r\n mountCallbacks: Function[];\r\n destroyCallbacks: Function[];\r\n preRenderCallbacks: Function[];\r\n afterRenderCallbacks: Function[];\r\n runMount: () => void;\r\n runDestroy: () => void;\r\n runPreRender: () => Promise<void>;\r\n runAfterRender: () => void;\r\n // Handler execution tracking\r\n setInHandler: (value: boolean) => void;\r\n // Manual render function\r\n render: (immediate?: boolean) => Promise<void>;\r\n}\r\n\r\n/**\r\n * Parse import statements from script and extract module info\r\n */\r\ninterface ImportInfo {\r\n moduleName: string;\r\n imports: { name: string; alias?: string }[];\r\n isDefault: boolean;\r\n defaultName?: string;\r\n}\r\n\r\nfunction parseImports(script: string): { imports: ImportInfo[]; cleanedScript: string } {\r\n const imports: ImportInfo[] = [];\r\n\r\n // Match: import { a, b as c } from \"module\"\r\n // Match: import name from \"module\"\r\n // Match: import * as name from \"module\"\r\n const importRegex = /import\\s+(?:(\\w+)\\s*,?\\s*)?(?:\\{\\s*([^}]+)\\s*\\})?(?:\\*\\s+as\\s+(\\w+))?\\s+from\\s+[\"']([^\"']+)[\"'];?/g;\r\n\r\n let cleanedScript = script;\r\n let match;\r\n\r\n while ((match = importRegex.exec(script)) !== null) {\r\n const [fullMatch, defaultImport, namedImports, namespaceImport, moduleName] = match;\r\n\r\n // Skip svelte internal imports - we provide these ourselves\r\n if (moduleName === 'svelte' || moduleName.startsWith('svelte/')) {\r\n cleanedScript = cleanedScript.replace(fullMatch, '');\r\n continue;\r\n }\r\n\r\n const importInfo: ImportInfo = {\r\n moduleName,\r\n imports: [],\r\n isDefault: false\r\n };\r\n\r\n // Default import: import name from \"module\"\r\n if (defaultImport) {\r\n importInfo.isDefault = true;\r\n importInfo.defaultName = defaultImport;\r\n }\r\n\r\n // Namespace import: import * as name from \"module\"\r\n if (namespaceImport) {\r\n importInfo.isDefault = true;\r\n importInfo.defaultName = namespaceImport;\r\n }\r\n\r\n // Named imports: import { a, b as c } from \"module\"\r\n if (namedImports) {\r\n const parts = namedImports.split(',').map(s => s.trim()).filter(Boolean);\r\n for (const part of parts) {\r\n const aliasMatch = part.match(/^(\\w+)\\s+as\\s+(\\w+)$/);\r\n if (aliasMatch) {\r\n importInfo.imports.push({ name: aliasMatch[1], alias: aliasMatch[2] });\r\n } else {\r\n importInfo.imports.push({ name: part });\r\n }\r\n }\r\n }\r\n\r\n imports.push(importInfo);\r\n cleanedScript = cleanedScript.replace(fullMatch, '');\r\n }\r\n\r\n return { imports, cleanedScript };\r\n}\r\n\r\n/**\r\n * Load modules and create injection variables\r\n */\r\nfunction loadModules(imports: ImportInfo[], sourceDir?: string): { modules: Record<string, any>; varDeclarations: string } {\r\n const modules: Record<string, any> = {};\r\n const declarations: string[] = [];\r\n const path = require(\"path\");\r\n\r\n for (const importInfo of imports) {\r\n try {\r\n // Resolve relative paths from source file directory\r\n const resolvedPath = importInfo.moduleName.startsWith('.') && sourceDir\r\n ? path.resolve(sourceDir, importInfo.moduleName)\r\n : importInfo.moduleName;\r\n // Try to require the module\r\n const mod = require(resolvedPath);\r\n\r\n if (importInfo.isDefault && importInfo.defaultName) {\r\n // Default or namespace import\r\n modules[importInfo.defaultName] = mod.default || mod;\r\n declarations.push(`var ${importInfo.defaultName} = __modules__[\"${importInfo.defaultName}\"];`);\r\n }\r\n\r\n // Named imports\r\n for (const imp of importInfo.imports) {\r\n const varName = imp.alias || imp.name;\r\n modules[varName] = mod[imp.name];\r\n declarations.push(`var ${varName} = __modules__[\"${varName}\"];`);\r\n }\r\n } catch (err) {\r\n // Module import failed\r\n }\r\n }\r\n\r\n return { modules, varDeclarations: declarations.join('\\n') };\r\n}\r\n\r\n/**\r\n * Create a handler context from script content\r\n * This evaluates the Svelte script and returns the handler functions and effects\r\n * @param sourceDir - The directory of the source file (used for resolving relative imports)\r\n * @param inlineHandlers - Map of inline handler names to their source code (extracted from template)\r\n */\r\nexport function createHandlerContext(scriptContent: string, initialData: Record<string, any> = {}, component?: any, ctx?: any, sourceDir?: string, inlineHandlers?: Map<string, string>): HandlerContextResult {\r\n const handlers: Record<string, Function> = {};\r\n const effects: Function[] = [];\r\n\r\n try {\r\n // Parse and extract imports first\r\n const { imports, cleanedScript } = parseImports(scriptContent);\r\n const { modules, varDeclarations } = loadModules(imports, sourceDir);\r\n\r\n // Extract only function declarations from the script\r\n const functionNames = extractFunctionNames(cleanedScript);\r\n\r\n // Extract $effect calls and convert them to collectable functions\r\n const effectBodies = extractEffectBodies(cleanedScript);\r\n\r\n // Process script to be safe for evaluation:\r\n // 1. Remove reactive declarations (let x = $state(...))\r\n // 2. Remove $props destructuring\r\n // 3. Convert $effect to __registerEffect__\r\n // 4. Keep only function declarations\r\n\r\n // First, remove comments from the script to avoid regex issues with braces in comments\r\n let scriptWithoutComments = cleanedScript\r\n // Remove single-line comments (but preserve the newline)\r\n .replace(/\\/\\/.*$/gm, '')\r\n // Remove multi-line comments\r\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\r\n\r\n let processedScript = scriptWithoutComments\r\n // Remove $state declarations completely or make them var\r\n .replace(/(?:const|let)\\s+(\\w+)\\s*=\\s*\\$state\\(([^)]*)\\);?/g, 'var $1 = $2;')\r\n // Remove $derived declarations but keep the value\r\n .replace(/(?:const|let)\\s+(\\w+)\\s*=\\s*\\$derived\\(([^)]+)\\);?/g, 'var $1 = $2;')\r\n // Convert $effect calls to __registerEffect__ calls\r\n .replace(/\\$effect\\s*\\(\\s*((?:function\\s*\\([^)]*\\)|\\([^)]*\\)\\s*=>|\\(\\)\\s*=>)[^}]*\\{[\\s\\S]*?\\}\\s*)\\);?/g, '__registerEffect__($1);')\r\n // Simpler $effect pattern: $effect(() => { ... })\r\n .replace(/\\$effect\\s*\\(\\s*\\(\\)\\s*=>\\s*\\{([\\s\\S]*?)\\}\\s*\\);?/g, '__registerEffect__(function() {$1});');\r\n\r\n // Handle $props destructuring with proper brace counting (supports nested objects like { options = { a: 1 } })\r\n processedScript = processedScript.replace(/(?:const|let)\\s+\\{([\\s\\S]*?)\\}\\s*=\\s*\\$props\\(\\);?/g, (match) => {\r\n // Find the opening brace after 'const' or 'let'\r\n const letIndex = match.indexOf('{');\r\n if (letIndex === -1) return match;\r\n\r\n // Use brace counting to find the matching closing brace\r\n let braceCount = 0;\r\n let startIndex = letIndex;\r\n let endIndex = -1;\r\n\r\n for (let i = startIndex; i < match.length; i++) {\r\n if (match[i] === '{') braceCount++;\r\n else if (match[i] === '}') {\r\n braceCount--;\r\n if (braceCount === 0) {\r\n endIndex = i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (endIndex === -1) return match;\r\n\r\n // Extract the content between braces\r\n const content = match.substring(startIndex + 1, endIndex);\r\n\r\n // Parse props with proper handling of nested braces\r\n const props = parsePropsContent(content);\r\n\r\n // Generate prop accessors that read from data at access time\r\n // Use a special pattern: define both the initial var AND a __propGetters__ object\r\n // that inline handlers can use to get current values\r\n const propDefs = props.map(prop => {\r\n if (!prop.name || prop.name === 'data') return '';\r\n if (prop.defaultValue !== undefined) {\r\n return `var ${prop.name} = data.${prop.name} ?? ${prop.defaultValue}; __propGetters__.${prop.name} = function() { return data.${prop.name} ?? ${prop.defaultValue}; };`;\r\n }\r\n return `var ${prop.name} = data.${prop.name}; __propGetters__.${prop.name} = function() { return data.${prop.name}; };`;\r\n }).filter(Boolean).join('\\n');\r\n\r\n return propDefs;\r\n });\r\n\r\n // Add module variable declarations at the beginning of processed script\r\n if (varDeclarations) {\r\n processedScript = varDeclarations + '\\n\\n' + processedScript;\r\n }\r\n\r\n // Wrap everything in an IIFE that takes data and component as parameters\r\n // This ensures data and 'this' are always available in the function scope\r\n // Also provides helper functions: render(), update() and rerender()\r\n // Data is wrapped in a Proxy for automatic reactivity\r\n // Interaction methods (reply, followUp, deferReply) are wrapped to auto-render after completion\r\n const wrappedScript = `\r\n return function(__data__, __component__, __ctx__, __modules__) {\r\n __modules__ = __modules__ || {};\r\n var self = __component__;\r\n var __effects__ = [];\r\n var __renderPending__ = false;\r\n var __autoRenderEnabled__ = true;\r\n var __hasDataChanges__ = false;\r\n \r\n // Prop getters for accessing current data values (used by inline handlers)\r\n var __propGetters__ = {};\r\n \r\n // Lifecycle callbacks\r\n var __mountCallbacks__ = [];\r\n var __destroyCallbacks__ = [];\r\n var __preRenderCallbacks__ = [];\r\n var __afterRenderCallbacks__ = [];\r\n var __isMounted__ = false;\r\n \r\n // Store last message reference for background updates (intervals, timeouts)\r\n var __lastMessage__ = __ctx__?.interaction?.message || null;\r\n \r\n // Throttle configuration\r\n var __throttleMinInterval__ = 250; // Minimum ms between renders\r\n var __lastRenderTime__ = 0;\r\n var __pendingRenderTimeout__ = null;\r\n var __isRateLimited__ = false;\r\n var __rateLimitEndTime__ = 0;\r\n \r\n function __registerEffect__(fn) {\r\n __effects__.push(fn);\r\n }\r\n \r\n // Lifecycle: onMount - called when component is first rendered\r\n // If callback returns a function, that function is called on destroy\r\n function onMount(fn) {\r\n __mountCallbacks__.push(fn);\r\n }\r\n \r\n // Lifecycle: onDestroy - called when ref is cleaned up\r\n function onDestroy(fn) {\r\n __destroyCallbacks__.push(fn);\r\n }\r\n \r\n // Lifecycle: onPreRender - called before each render (async, awaited)\r\n function onPreRender(fn) {\r\n __preRenderCallbacks__.push(fn);\r\n }\r\n \r\n // Lifecycle: onAfterRender - called after each render completes\r\n function onAfterRender(fn) {\r\n __afterRenderCallbacks__.push(fn);\r\n }\r\n \r\n // Run all pre-render callbacks (async)\r\n async function __runPreRender__() {\r\n for (var i = 0; i < __preRenderCallbacks__.length; i++) {\r\n try {\r\n await __preRenderCallbacks__[i]();\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] Pre-render callback failed:\", err);\r\n throw err;\r\n }\r\n }\r\n }\r\n \r\n // Run all after-render callbacks\r\n function __runAfterRender__() {\r\n for (var i = 0; i < __afterRenderCallbacks__.length; i++) {\r\n try {\r\n __afterRenderCallbacks__[i]();\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] After-render callback failed:\", err);\r\n throw err;\r\n }\r\n }\r\n }\r\n \r\n // Modal store - stores rendered modal definitions\r\n var __modals__ = new Map();\r\n \r\n // Register a modal (called internally when modals are parsed)\r\n function __registerModal__(modalId, modalDef) {\r\n __modals__.set(modalId, modalDef);\r\n }\r\n \r\n // Show a modal by ID and return a Promise that resolves with the submitted fields\r\n // Modal definitions are rendered from <components type=\"modal\" id=\"xxx\">\r\n // Usage: \r\n // await showModal(\"edit-product\"); // Just show, use onsubmit handler\r\n // const { fields, interaction } = await showModal(\"edit-product\"); // Get response\r\n // await showModal(\"edit-product\", { timeout: 60000 }); // 60 second timeout\r\n // await showModal(\"edit-product\", { timeout: 0 }); // No timeout (unlimited)\r\n function showModal(modalId, options) {\r\n if (!__ctx__ || !__ctx__.interaction) {\r\n return Promise.reject(new Error(\"showModal requires an interaction context\"));\r\n }\r\n \r\n // Default timeout: 10 minutes (600000ms), 0 = no timeout\r\n var timeout = (options && typeof options.timeout === 'number') ? options.timeout : 600000;\r\n \r\n // Disable auto-render IMMEDIATELY since we're showing a modal\r\n // This prevents flushRender from trying to update after modal is shown\r\n __autoRenderEnabled__ = false;\r\n __asyncInteractionCalled__ = true;\r\n \r\n // Create a promise that will be resolved when modal is submitted\r\n return new Promise(async function(resolve, reject) {\r\n var timeoutId = null;\r\n var modal = null;\r\n \r\n try {\r\n // Re-render to get latest modal definitions (reactive)\r\n var renderResult = await __component__.toJSON({ data: __data__ });\r\n \r\n // Get modals from the render result stored on component\r\n var modals = __component__.__lastRenderModals__;\r\n if (!modals) {\r\n reject(new Error(\"No modals defined in this component. Use <components type=\\\\\"modal\\\\\" id=\\\\\"...\\\\\">\")); \r\n return;\r\n }\r\n \r\n modal = modals.get(modalId);\r\n if (!modal) {\r\n reject(new Error(\"Modal '\" + modalId + \"' not found. Available modals: \" + Array.from(modals.keys()).join(\", \")));\r\n return;\r\n }\r\n \r\n // Wrapped resolve/reject to clear timeout\r\n var wrappedResolve = function(result) {\r\n if (timeoutId) clearTimeout(timeoutId);\r\n resolve(result);\r\n };\r\n var wrappedReject = function(error) {\r\n if (timeoutId) clearTimeout(timeoutId);\r\n reject(error);\r\n };\r\n \r\n // Store the promise resolver in component's pending modals map\r\n // This will be resolved when modal submit interaction is received\r\n __component__._pendingModals.set(modal.customId, { resolve: wrappedResolve, reject: wrappedReject });\r\n \r\n // Set up timeout if enabled (timeout > 0)\r\n if (timeout > 0) {\r\n timeoutId = setTimeout(function() {\r\n // Clean up pending modal\r\n __component__._pendingModals.delete(modal.customId);\r\n reject(new Error(\"Modal '\" + modalId + \"' timed out after \" + timeout + \"ms\"));\r\n }, timeout);\r\n }\r\n \r\n // Show the modal using the interaction\r\n var i = __ctx__.interaction;\r\n \r\n // Modal must be shown immediately - no deferral allowed\r\n await i.showModal({\r\n title: modal.title,\r\n customId: modal.customId,\r\n components: modal.components\r\n });\r\n \r\n // Note: Promise resolves later when modal is submitted\r\n // If you don't await for the response, the promise just hangs (which is fine)\r\n } catch (err) {\r\n // Clean up pending modal and timeout if show failed\r\n if (timeoutId) clearTimeout(timeoutId);\r\n if (modal && modal.customId) {\r\n __component__._pendingModals.delete(modal.customId);\r\n }\r\n reject(new Error(\"Failed to show modal: \" + (err.message || err)));\r\n }\r\n });\r\n }\r\n \r\n // Rate-limit aware edit function with retry and enhanced error handling\r\n function __safeEdit__(editFn, retryCount, componentsForError) {\r\n retryCount = retryCount || 0;\r\n var maxRetries = 3;\r\n \r\n return editFn().then(function(result) {\r\n return result;\r\n }).catch(function(err) {\r\n // Check for rate limit (429)\r\n if (err.status === 429 || (err.message && err.message.includes('rate limit'))) {\r\n var retryAfter = err.retry_after || err.retryAfter || 1;\r\n __isRateLimited__ = true;\r\n __rateLimitEndTime__ = Date.now() + (retryAfter * 1000);\r\n \r\n return new Promise(function(resolve) {\r\n setTimeout(function() {\r\n __isRateLimited__ = false;\r\n if (retryCount < maxRetries) {\r\n resolve(__safeEdit__(editFn, retryCount + 1, componentsForError));\r\n } else {\r\n resolve();\r\n }\r\n }, retryAfter * 1000);\r\n });\r\n }\r\n \r\n // Check if it's a component validation error and enhance it\r\n if (err.code === 50035 || err.rawError?.code === 50035 || \r\n (err.message && (err.message.includes('Invalid Form Body') || err.message.includes('BASE_TYPE')))) {\r\n // Create enhanced error message\r\n var errorMsg = err.message || '';\r\n var enhancedMsg = '\\\\n╔══════════════════════════════════════════════════════════════╗\\\\n';\r\n enhancedMsg += '║ Discord Components V2 Validation Error ║\\\\n';\r\n enhancedMsg += '╠══════════════════════════════════════════════════════════════╣\\\\n';\r\n \r\n // Parse error paths from message\r\n var errorLines = errorMsg.split('\\\\n');\r\n for (var i = 0; i < errorLines.length; i++) {\r\n var line = errorLines[i];\r\n var match = line.match(/([\\\\w\\\\[\\\\]\\\\.]+)\\\\[([A-Z_]+)\\\\]:\\\\s*(.+)/);\r\n if (match) {\r\n var path = match[1];\r\n var code = match[2];\r\n var msg = match[3];\r\n \r\n enhancedMsg += '║\\\\n';\r\n enhancedMsg += '║ ❌ Path: ' + path + '\\\\n';\r\n enhancedMsg += '║ ├─ Code: ' + code + '\\\\n';\r\n enhancedMsg += '║ ├─ Message: ' + msg + '\\\\n';\r\n \r\n // Add helpful hints based on error code\r\n if (code === 'BASE_TYPE_REQUIRED') {\r\n enhancedMsg += '║ └─ Fix: This field is required - check if the element has all required attributes\\\\n';\r\n } else if (code === 'BASE_TYPE_BAD_LENGTH') {\r\n enhancedMsg += '║ └─ Fix: Wrong number of items - Discord has min/max limits for components\\\\n';\r\n } else if (code.includes('MAX_LENGTH') || code.includes('MIN_LENGTH')) {\r\n enhancedMsg += '║ └─ Fix: Content length issue - adjust text or number of items\\\\n';\r\n }\r\n }\r\n }\r\n \r\n enhancedMsg += '║\\\\n';\r\n enhancedMsg += '╚══════════════════════════════════════════════════════════════╝';\r\n \r\n var enhancedError = new Error('[DBI-Svelte] Component validation error:\\\\n' + enhancedMsg + '\\\\n\\\\nOriginal: ' + errorMsg);\r\n enhancedError.originalError = err;\r\n enhancedError.type = 'discord-component-validation';\r\n throw enhancedError;\r\n }\r\n \r\n // Re-throw other errors\r\n throw err;\r\n });\r\n }\r\n \r\n // Throttled render - ensures minimum interval between renders\r\n function __throttledRender__(immediate) {\r\n var now = Date.now();\r\n var timeSinceLastRender = now - __lastRenderTime__;\r\n var waitTime = 0;\r\n \r\n // If rate limited, calculate wait time\r\n if (__isRateLimited__ && __rateLimitEndTime__ > now) {\r\n waitTime = Math.max(waitTime, __rateLimitEndTime__ - now);\r\n }\r\n \r\n // If within throttle interval, schedule for later\r\n if (!immediate && timeSinceLastRender < __throttleMinInterval__) {\r\n waitTime = Math.max(waitTime, __throttleMinInterval__ - timeSinceLastRender);\r\n }\r\n \r\n // Clear any pending render\r\n if (__pendingRenderTimeout__) {\r\n clearTimeout(__pendingRenderTimeout__);\r\n __pendingRenderTimeout__ = null;\r\n }\r\n \r\n if (waitTime > 0) {\r\n return new Promise(function(resolve) {\r\n __pendingRenderTimeout__ = setTimeout(function() {\r\n __pendingRenderTimeout__ = null;\r\n __lastRenderTime__ = Date.now();\r\n resolve(__executeRender__());\r\n }, waitTime);\r\n });\r\n }\r\n \r\n __lastRenderTime__ = now;\r\n return __executeRender__();\r\n }\r\n \r\n // Actual render execution\r\n async function __executeRender__() {\r\n // Run pre-render callbacks (async, awaited)\r\n await __runPreRender__();\r\n \r\n var components = await __component__.toJSON({ data: __data__ });\r\n var result;\r\n \r\n // Try to use current interaction if available\r\n if (__ctx__ && __ctx__.interaction) {\r\n try {\r\n var i = __ctx__.interaction;\r\n \r\n // Update last message reference\r\n if (i.message) {\r\n __lastMessage__ = i.message;\r\n }\r\n \r\n // Check if interaction was deferred (our flag) or Discord.js flags\r\n if (i.replied || i.deferred || __interactionDeferred__) {\r\n // Already replied/deferred, use message.edit with rate limit handling\r\n result = await __safeEdit__(function() {\r\n return i.message.edit({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n }, 0, components);\r\n } else {\r\n // Not replied yet, use update with rate limit handling\r\n result = await __safeEdit__(function() {\r\n return i.update({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n }, 0, components);\r\n }\r\n \r\n // Run after-render callbacks\r\n __runAfterRender__();\r\n return result;\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] Render failed:\", err);\r\n throw err;\r\n }\r\n }\r\n \r\n // Fallback: Use last message reference (for intervals/timeouts outside interaction)\r\n if (__lastMessage__) {\r\n result = await __safeEdit__(function() {\r\n return __lastMessage__.edit({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n }, 0, components);\r\n \r\n // Run after-render callbacks\r\n __runAfterRender__();\r\n return result;\r\n }\r\n \r\n return Promise.resolve();\r\n }\r\n \r\n // Helper: Auto-detect whether to use update() or rerender()\r\n // If interaction was already replied/deferred, use message.edit\r\n // Otherwise use interaction.update\r\n function render(immediate) {\r\n return __throttledRender__(immediate);\r\n }\r\n \r\n // Track if we're inside a handler execution\r\n var __inHandlerExecution__ = false;\r\n \r\n // Track pending low-priority updates (from intervals/timeouts)\r\n var __pendingLowPriorityRender__ = false;\r\n \r\n // Mark that we have pending data changes\r\n function __markDataChanged__() {\r\n __hasDataChanges__ = true;\r\n \r\n // If we're NOT inside a handler (e.g., interval/timeout), trigger render immediately\r\n // The throttle will prevent too many renders\r\n if (!__inHandlerExecution__ && __autoRenderEnabled__ && __lastMessage__) {\r\n __hasDataChanges__ = false;\r\n __throttledRender__(false);\r\n }\r\n }\r\n \r\n // Low-priority update - used for background tasks like intervals\r\n // If a handler is currently running, skip this update (the handler's update will include our changes)\r\n function lowPriorityUpdate(callback) {\r\n if (__inHandlerExecution__) {\r\n // Handler is running - just update data, skip render\r\n // The handler will render when it finishes\r\n if (callback) callback();\r\n return;\r\n }\r\n \r\n // No handler running - proceed with update\r\n if (callback) callback();\r\n }\r\n \r\n // Flush pending render (called after interaction methods complete)\r\n function __flushRender__() {\r\n if (__hasDataChanges__ && __autoRenderEnabled__) {\r\n __hasDataChanges__ = false;\r\n render();\r\n }\r\n }\r\n \r\n // Create reactive proxy for data\r\n // Also properly forwards Object.keys/values/entries operations\r\n function __createReactiveProxy__(target, path) {\r\n if (typeof target !== 'object' || target === null) return target;\r\n \r\n return new Proxy(target, {\r\n get: function(obj, prop) {\r\n var value = obj[prop];\r\n // Wrap nested objects in proxy too\r\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\r\n return __createReactiveProxy__(value, path + '.' + String(prop));\r\n }\r\n return value;\r\n },\r\n set: function(obj, prop, value) {\r\n var oldValue = obj[prop];\r\n obj[prop] = value;\r\n // Only mark as changed if value actually changed\r\n if (oldValue !== value) {\r\n __markDataChanged__();\r\n }\r\n return true;\r\n },\r\n // Forward Object.keys/values/entries operations\r\n ownKeys: function(target) {\r\n return Reflect.ownKeys(target);\r\n },\r\n getOwnPropertyDescriptor: function(target, prop) {\r\n return Reflect.getOwnPropertyDescriptor(target, prop);\r\n },\r\n has: function(target, prop) {\r\n return Reflect.has(target, prop);\r\n }\r\n });\r\n }\r\n \r\n // Wrap data in reactive proxy\r\n var data = __createReactiveProxy__(__data__, 'data');\r\n \r\n // Track if an async interaction method was called\r\n var __asyncInteractionCalled__ = false;\r\n \r\n // Track if interaction was deferred (deferUpdate/deferReply)\r\n var __interactionDeferred__ = false;\r\n \r\n // Wrap interaction methods to auto-render after completion\r\n var interaction = null;\r\n var ctx = null;\r\n \r\n if (__ctx__ && __ctx__.interaction) {\r\n var originalInteraction = __ctx__.interaction;\r\n \r\n // Create a proxy for interaction that wraps reply/followUp/deferReply\r\n // Also properly forwards Object.keys/values/entries operations\r\n // Uses Reflect.get to properly handle getters with correct 'this' binding\r\n interaction = new Proxy(originalInteraction, {\r\n get: function(target, prop, receiver) {\r\n // Use Reflect.get to properly handle getters (like 'roles', 'users', etc.)\r\n // This ensures 'this' context is correct for Discord.js Collection getters\r\n var value = Reflect.get(target, prop, target);\r\n \r\n // Wrap methods that \"consume\" the interaction (reply, followUp, defer)\r\n if (prop === 'reply' || prop === 'followUp' || prop === 'deferReply' || prop === 'deferUpdate') {\r\n return function() {\r\n // Mark that async interaction was called - this prevents sync flush at handler end\r\n __asyncInteractionCalled__ = true;\r\n \r\n // Mark as deferred for deferUpdate/deferReply\r\n if (prop === 'deferUpdate' || prop === 'deferReply') {\r\n __interactionDeferred__ = true;\r\n }\r\n \r\n var result = value.apply(target, arguments);\r\n // After the reply completes, flush any pending renders using throttled render\r\n if (result && typeof result.then === 'function') {\r\n result.then(function() {\r\n if (__hasDataChanges__ && __autoRenderEnabled__) {\r\n __hasDataChanges__ = false;\r\n // Use throttled render which handles rate limits\r\n __throttledRender__(false);\r\n }\r\n }).catch(function(err) {\r\n console.error(\"[DBI-Svelte] Render after \" + prop + \" failed:\", err);\r\n });\r\n }\r\n return result;\r\n };\r\n }\r\n \r\n // Wrap update method - this one renders directly, no need to flush after\r\n if (prop === 'update') {\r\n return function() {\r\n __autoRenderEnabled__ = false; // Disable auto since we're doing manual update\r\n __asyncInteractionCalled__ = true;\r\n return value.apply(target, arguments);\r\n };\r\n }\r\n \r\n // Bind functions to original target\r\n if (typeof value === 'function') {\r\n return value.bind(target);\r\n }\r\n \r\n return value;\r\n },\r\n // Forward Object.keys/values/entries operations\r\n ownKeys: function(target) {\r\n return Reflect.ownKeys(target);\r\n },\r\n getOwnPropertyDescriptor: function(target, prop) {\r\n return Reflect.getOwnPropertyDescriptor(target, prop);\r\n },\r\n has: function(target, prop) {\r\n return Reflect.has(target, prop);\r\n }\r\n });\r\n \r\n // Create wrapped ctx with the proxied interaction\r\n // Also properly forwards Object.keys/values/entries operations\r\n ctx = new Proxy(__ctx__, {\r\n get: function(target, prop, receiver) {\r\n if (prop === 'interaction') {\r\n return interaction;\r\n }\r\n // Use Reflect.get for proper getter handling\r\n return Reflect.get(target, prop, target);\r\n },\r\n // Forward Object.keys/values/entries operations\r\n ownKeys: function(target) {\r\n return Reflect.ownKeys(target);\r\n },\r\n getOwnPropertyDescriptor: function(target, prop) {\r\n return Reflect.getOwnPropertyDescriptor(target, prop);\r\n },\r\n has: function(target, prop) {\r\n return Reflect.has(target, prop);\r\n }\r\n });\r\n }\r\n \r\n // Helper: Force update message using interaction.update (for button clicks without reply)\r\n // Helper: Force update message using interaction.update (for button clicks without reply)\r\n async function update() {\r\n if (!__ctx__ || !__ctx__.interaction) {\r\n return Promise.resolve();\r\n }\r\n __autoRenderEnabled__ = false; // Disable auto-render since manual update called\r\n var components = await __component__.toJSON({ data: __data__ });\r\n return __safeEdit__(function() {\r\n return __ctx__.interaction.update({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n });\r\n }\r\n \r\n // Helper: Force re-render message using message.edit (after reply/followUp)\r\n async function rerender() {\r\n if (!__ctx__ || !__ctx__.interaction || !__ctx__.interaction.message) {\r\n return Promise.resolve();\r\n }\r\n __autoRenderEnabled__ = false; // Disable auto-render since manual rerender called\r\n var components = await __component__.toJSON({ data: __data__ });\r\n return __safeEdit__(function() {\r\n return __ctx__.interaction.message.edit({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n });\r\n }\r\n \r\n // Helper: Disable auto-render (for handlers that don't need UI update)\r\n function noRender() {\r\n __autoRenderEnabled__ = false;\r\n }\r\n \r\n // Helper: Set throttle interval (minimum ms between renders)\r\n function setThrottle(ms) {\r\n __throttleMinInterval__ = ms;\r\n }\r\n \r\n // Helper: Destroy this component instance (clears intervals, timers, removes ref)\r\n // Call this when you want to clean up the component manually\r\n function destroy() {\r\n // Run all destroy callbacks (clears intervals, timers, etc.)\r\n __runDestroy__();\r\n \r\n // Clear the ref from DBI store if available\r\n if (__data__ && __data__.$ref && __component__ && __component__.dbi) {\r\n __component__.dbi.data.refs.delete(__data__.$ref);\r\n }\r\n \r\n // Disable further auto-renders\r\n __autoRenderEnabled__ = false;\r\n }\r\n \r\n // Check if there are pending data changes that need SYNC render\r\n // Returns false if async interaction was called (reply/followUp will handle render)\r\n function __hasPendingRender__() {\r\n return __hasDataChanges__ && __autoRenderEnabled__ && !__asyncInteractionCalled__;\r\n }\r\n \r\n // Synchronous flush for when handler completes without async interaction\r\n // Only called when no reply/followUp was made - uses throttled render\r\n function __syncFlushRender__() {\r\n if (__hasDataChanges__ && __autoRenderEnabled__ && !__asyncInteractionCalled__) {\r\n __hasDataChanges__ = false;\r\n return __throttledRender__(true); // immediate=true for sync flush\r\n }\r\n return Promise.resolve();\r\n }\r\n \r\n // Run all mount callbacks, if callback returns a function add it to destroy callbacks\r\n function __runMount__() {\r\n if (__isMounted__) return;\r\n __isMounted__ = true;\r\n for (var i = 0; i < __mountCallbacks__.length; i++) {\r\n try {\r\n var result = __mountCallbacks__[i]();\r\n // If mount callback returns a function, add it to destroy callbacks\r\n if (typeof result === 'function') {\r\n __destroyCallbacks__.push(result);\r\n }\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] onMount callback failed:\", err);\r\n throw err;\r\n }\r\n }\r\n }\r\n \r\n // Run all destroy callbacks\r\n function __runDestroy__() {\r\n for (var i = 0; i < __destroyCallbacks__.length; i++) {\r\n try {\r\n __destroyCallbacks__[i]();\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] onDestroy callback failed:\", err);\r\n throw err;\r\n }\r\n }\r\n // Clear pending timeouts\r\n if (__pendingRenderTimeout__) {\r\n clearTimeout(__pendingRenderTimeout__);\r\n __pendingRenderTimeout__ = null;\r\n }\r\n }\r\n \r\n // Set handler execution flag\r\n function __setInHandler__(value) {\r\n __inHandlerExecution__ = value;\r\n }\r\n \r\n ${processedScript}\r\n \r\n // Inline handlers from template (extracted arrow functions/function expressions)\r\n ${Array.from(inlineHandlers || new Map()).map(([name, code]) => {\r\n // Wrap the inline code as a named function\r\n // If it's an arrow function, convert to regular function for proper 'this' binding\r\n if (code.trim().startsWith('async')) {\r\n // async arrow function or async function\r\n if (code.includes('=>')) {\r\n // async arrow function: async (ctx) => { ... } or async () => { ... }\r\n return `var ${name} = ${code};`;\r\n } else {\r\n // async function expression: async function(ctx) { ... }\r\n return `var ${name} = ${code};`;\r\n }\r\n } else if (code.includes('=>')) {\r\n // Regular arrow function: (ctx) => { ... } or () => { ... }\r\n return `var ${name} = ${code};`;\r\n } else {\r\n // Regular function expression: function(ctx) { ... }\r\n return `var ${name} = ${code};`;\r\n }\r\n }).join('\\n')}\r\n \r\n return { \r\n handlers: { ${[...functionNames, ...Array.from(inlineHandlers || new Map()).map(([name]) => name)].filter(Boolean).join(\", \")} },\r\n effects: __effects__,\r\n hasPendingRender: __hasPendingRender__,\r\n flushRender: __syncFlushRender__,\r\n wrappedCtx: ctx,\r\n mountCallbacks: __mountCallbacks__,\r\n destroyCallbacks: __destroyCallbacks__,\r\n preRenderCallbacks: __preRenderCallbacks__,\r\n afterRenderCallbacks: __afterRenderCallbacks__,\r\n runMount: __runMount__,\r\n runDestroy: __runDestroy__,\r\n runPreRender: __runPreRender__,\r\n runAfterRender: __runAfterRender__,\r\n setInHandler: __setInHandler__,\r\n render: render\r\n };\r\n };\r\n `;\r\n\r\n // Create the factory function\r\n const factoryFunc = new Function('console', wrappedScript);\r\n const createHandlers = factoryFunc(console);\r\n\r\n // Execute with the actual data, component, ctx, and imported modules to get handlers with proper closure\r\n let result;\r\n try {\r\n result = createHandlers(initialData, component, ctx, modules);\r\n } catch (execError) {\r\n throw execError;\r\n }\r\n\r\n Object.assign(handlers, result.handlers || {});\r\n effects.push(...(result.effects || []));\r\n\r\n // Return full result including render helpers\r\n // Function to run all effects\r\n const runEffects = () => {\r\n for (const effect of effects) {\r\n try {\r\n effect();\r\n } catch (error) {\r\n // Effect failed\r\n }\r\n }\r\n };\r\n\r\n return {\r\n handlers,\r\n effects,\r\n runEffects,\r\n hasPendingRender: result.hasPendingRender || (() => false),\r\n flushRender: result.flushRender || (() => Promise.resolve()),\r\n wrappedCtx: result.wrappedCtx || ctx,\r\n mountCallbacks: result.mountCallbacks || [],\r\n destroyCallbacks: result.destroyCallbacks || [],\r\n preRenderCallbacks: result.preRenderCallbacks || [],\r\n afterRenderCallbacks: result.afterRenderCallbacks || [],\r\n runMount: result.runMount || (() => { }),\r\n runDestroy: result.runDestroy || (() => { }),\r\n runPreRender: result.runPreRender || (async () => { }),\r\n runAfterRender: result.runAfterRender || (() => { }),\r\n setInHandler: result.setInHandler || (() => { }),\r\n render: result.render || (() => Promise.resolve())\r\n };\r\n } catch (error) {\r\n // Re-throw the error so it's visible to the developer\r\n console.error(\"[DBI-Svelte] createHandlerContext failed:\", error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Extract $effect callback bodies from script content\r\n */\r\nfunction extractEffectBodies(script: string): string[] {\r\n const bodies: string[] = [];\r\n // Match $effect(() => { ... }) or $effect(function() { ... })\r\n const effectRegex = /\\$effect\\s*\\(\\s*(?:(?:function\\s*\\([^)]*\\)|\\([^)]*\\)\\s*=>|\\(\\)\\s*=>)\\s*\\{([\\s\\S]*?)\\})\\s*\\)/g;\r\n let match;\r\n while ((match = effectRegex.exec(script)) !== null) {\r\n bodies.push(match[1]);\r\n }\r\n return bodies;\r\n}\r\n\r\n/**\r\n * Extract function names from script content (excluding effect callbacks)\r\n */\r\nfunction extractFunctionNames(script: string): string[] {\r\n const names: string[] = [];\r\n\r\n // Match function declarations: function name() {}\r\n const functionDeclRegex = /function\\s+(\\w+)\\s*\\(/g;\r\n let match;\r\n while ((match = functionDeclRegex.exec(script)) !== null) {\r\n names.push(match[1]);\r\n }\r\n\r\n // Match function expressions: const name = function() {}\r\n const functionExprRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*function\\s*\\(/g;\r\n while ((match = functionExprRegex.exec(script)) !== null) {\r\n names.push(match[1]);\r\n }\r\n\r\n // Match arrow functions: const name = () => {}\r\n const arrowFunctionRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>/g;\r\n while ((match = arrowFunctionRegex.exec(script)) !== null) {\r\n names.push(match[1]);\r\n }\r\n\r\n // Match arrow functions without parentheses: const name = x => {}\r\n const simpleArrowRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\w+\\s*=>/g;\r\n while ((match = simpleArrowRegex.exec(script)) !== null) {\r\n names.push(match[1]);\r\n }\r\n\r\n return [...new Set(names)]; // Remove duplicates\r\n}\r\n"]}
1
+ {"version":3,"file":"svelteParser.js","sourceRoot":"","sources":["../../../../../src/types/Components/HTMLComponentsV2/svelteParser.ts"],"names":[],"mappings":";;AAoKA,oDAsXC;AAmHD,0DAwHC;AAKD,sDAiBC;AAuID,oDAi0BC;AAjuDD,4FAA4F;AAC5F,IAAI,MAA8C,CAAC;AAEnD,KAAK,UAAU,aAAa;IAC1B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,cAAc,GAAG,wDAAa,iBAAiB,GAAC,CAAC;QACvD,MAAM,GAAG,cAAc,CAAC,KAAK,CAAC;IAChC,CAAC;AACH,CAAC;AAoBD;;GAEG;AACH,SAAS,aAAa,CAAC,IAAS,EAAE,QAAmD,EAAE,OAAqB;IAC1G,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO;IAE9C,qCAAqC;IACrC,MAAM,GAAG,GAAgB,OAAO,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;IAEpE,QAAQ,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAEpB,2DAA2D;IAC3D,MAAM,YAAY,GAAgB;QAChC,OAAO,EAAE,CAAC,GAAG,GAAG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B,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QACzD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IAED,+CAA+C;IAC/C,MAAM,kBAAkB,GAAG,8DAA8D,CAAC;IAC1F,OAAO,CAAC,KAAK,GAAG,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QAC1D,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IAED,kEAAkE;IAClE,MAAM,gBAAgB,GAAG,wDAAwD,CAAC;IAClF,OAAO,CAAC,KAAK,GAAG,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QACxD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IAED,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,oBAAoB;AAClD,CAAC","sourcesContent":["import * as stuffs from \"stuffs\";\r\n\r\n// Lazy imports to avoid issues with package managers that don't properly hoist dependencies\r\nlet _parse: typeof import(\"svelte/compiler\").parse;\r\n\r\nasync function ensureImports() {\r\n if (!_parse) {\r\n const svelteCompiler = await import(\"svelte/compiler\");\r\n _parse = svelteCompiler.parse;\r\n }\r\n}\r\n\r\n/**\r\n * Context passed to walker callback containing parent information\r\n */\r\ninterface WalkContext {\r\n /** Stack of parent nodes from root to current */\r\n parents: any[];\r\n /** Information about enclosing {#each} blocks */\r\n eachBlocks: Array<{\r\n node: any;\r\n /** The iteration variable name (e.g., \"item\" in {#each items as item}) */\r\n iterVar: string;\r\n /** The index variable name if specified (e.g., \"i\" in {#each items as item, i}) */\r\n indexVar?: string;\r\n /** Expression for unique key (iterVar.id, iterVar.name, or index) */\r\n keyExpr: string;\r\n }>;\r\n}\r\n\r\n/**\r\n * Simple AST walker for Svelte AST nodes with parent tracking\r\n */\r\nfunction walkSvelteAst(node: any, callback: (node: any, context: WalkContext) => void, context?: WalkContext) {\r\n if (!node || typeof node !== 'object') return;\r\n\r\n // Initialize context if not provided\r\n const ctx: WalkContext = context || { parents: [], eachBlocks: [] };\r\n\r\n callback(node, ctx);\r\n\r\n // Create new context for children with this node as parent\r\n const childContext: WalkContext = {\r\n parents: [...ctx.parents, node],\r\n eachBlocks: [...ctx.eachBlocks]\r\n };\r\n\r\n // If this is an EachBlock, add it to the context for children\r\n if (node.type === 'EachBlock') {\r\n const iterVar = node.context?.name || node.context?.type === 'Identifier' ? node.context.name : 'item';\r\n const indexVar = node.index;\r\n\r\n // Determine best key expression for unique naming\r\n // Priority: explicit key > iter.id > iter.name > index > counter\r\n let keyExpr = indexVar || `__idx_${ctx.eachBlocks.length}`;\r\n\r\n childContext.eachBlocks = [...ctx.eachBlocks, {\r\n node,\r\n iterVar,\r\n indexVar,\r\n keyExpr\r\n }];\r\n }\r\n\r\n // Walk children based on node type\r\n if (node.children && Array.isArray(node.children)) {\r\n for (const child of node.children) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n }\r\n if (node.fragment && node.fragment.nodes) {\r\n for (const child of node.fragment.nodes) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n }\r\n if (node.nodes && Array.isArray(node.nodes)) {\r\n for (const child of node.nodes) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n }\r\n // Handle {#each} body\r\n if (node.body && node.type === 'EachBlock') {\r\n if (node.body.nodes) {\r\n for (const child of node.body.nodes) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n } else if (Array.isArray(node.body)) {\r\n for (const child of node.body) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n } else {\r\n walkSvelteAst(node.body, callback, childContext);\r\n }\r\n } else if (node.body) {\r\n if (Array.isArray(node.body)) {\r\n for (const child of node.body) {\r\n walkSvelteAst(child, callback, childContext);\r\n }\r\n } else {\r\n walkSvelteAst(node.body, callback, childContext);\r\n }\r\n }\r\n // Handle other potential child properties\r\n if (node.else) {\r\n walkSvelteAst(node.else, callback, childContext);\r\n }\r\n if (node.consequent) {\r\n walkSvelteAst(node.consequent, callback, childContext);\r\n }\r\n if (node.alternate) {\r\n walkSvelteAst(node.alternate, callback, childContext);\r\n }\r\n if (node.then) {\r\n walkSvelteAst(node.then, callback, childContext);\r\n }\r\n if (node.catch) {\r\n walkSvelteAst(node.catch, callback, childContext);\r\n }\r\n}\r\n\r\nexport interface SvelteHandlerInfo {\r\n name: string;\r\n handlerName: string;\r\n eventType: string; // onclick, onchange, onsubmit, etc.\r\n element: string; // button, string-select, components (for modal), etc.\r\n /** If this is an inline handler, contains the extracted source code */\r\n inlineCode?: string;\r\n /** Whether this handler is an inline arrow function or function expression */\r\n isInline?: boolean;\r\n /** Whether this handler has a dynamic name (inside {#each}) - use prefix matching */\r\n isDynamicName?: boolean;\r\n}\r\n\r\nexport interface ModalHandlerInfo {\r\n modalId: string;\r\n onsubmitHandler?: string; // Handler function name for onsubmit\r\n}\r\n\r\nexport interface SvelteValidationWarning {\r\n type: 'missing-data' | 'unused-data' | 'undefined-handler' | 'syntax-error' | 'runtime-error';\r\n message: string;\r\n details?: string;\r\n}\r\n\r\nexport interface SvelteComponentInfo {\r\n handlers: Map<string, SvelteHandlerInfo>;\r\n /** Modal onsubmit handlers keyed by modal id */\r\n modalHandlers: Map<string, ModalHandlerInfo>;\r\n scriptContent: string;\r\n processedSource: string; // Source with auto-generated names injected\r\n /** Props extracted from $props() destructuring */\r\n declaredProps: string[];\r\n /** Props that have default values (don't require data) */\r\n propsWithDefaults: string[];\r\n /** Function names declared in the script */\r\n declaredFunctions: string[];\r\n /** Inline handler code extracted from template (keyed by generated handler name) */\r\n inlineHandlers: Map<string, string>;\r\n}\r\n\r\n/**\r\n * Parse a Svelte component and extract event handlers\r\n * Also injects auto-generated names into elements that have handlers but no name\r\n */\r\nexport async function parseSvelteComponent(source: string, data?: Record<string, any>): Promise<SvelteComponentInfo> {\r\n await ensureImports();\r\n\r\n let ast;\r\n try {\r\n ast = _parse(source);\r\n } catch (parseError: any) {\r\n // Format Svelte parse error with helpful details\r\n const errorMessage = parseError.message || 'Unknown parse error';\r\n const location = parseError.start || parseError.loc;\r\n let details = errorMessage;\r\n\r\n if (location) {\r\n const lines = source.split('\\n');\r\n const lineNum = location.line || 1;\r\n const column = location.column || 0;\r\n const errorLine = lines[lineNum - 1] || '';\r\n const prevLine = lines[lineNum - 2] || '';\r\n const nextLine = lines[lineNum] || '';\r\n\r\n details = `\r\nSvelte Parse Error at line ${lineNum}, column ${column}:\r\n${errorMessage}\r\n\r\n${lineNum > 1 ? `${lineNum - 1} | ${prevLine}\\n` : ''}${lineNum} | ${errorLine}\r\n${' '.repeat(String(lineNum).length + 3 + column)}^\r\n${nextLine ? `${lineNum + 1} | ${nextLine}` : ''}\r\n`.trim();\r\n }\r\n\r\n const enhancedError = new Error(`[DBI-Svelte] Failed to parse Svelte component:\\n${details}`);\r\n (enhancedError as any).originalError = parseError;\r\n (enhancedError as any).type = 'svelte-parse-error';\r\n throw enhancedError;\r\n }\r\n\r\n const handlers = new Map<string, SvelteHandlerInfo>();\r\n const modalHandlers = new Map<string, ModalHandlerInfo>();\r\n let scriptContent = \"\";\r\n\r\n // Extract script content\r\n if (ast.instance) {\r\n scriptContent = source.substring(ast.instance.content.start, ast.instance.content.end);\r\n }\r\n\r\n // Track elements that need auto-generated names (node -> name mapping)\r\n // We'll inject these into the source after the walk\r\n const elementsNeedingNames: Array<{\r\n node: any;\r\n name: string;\r\n handlerName: string;\r\n eventType: string;\r\n element: string;\r\n /** If inside {#each}, contains info for dynamic name generation */\r\n eachContext?: Array<{\r\n iterVar: string;\r\n indexVar?: string;\r\n keyExpr: string;\r\n }>;\r\n }> = [];\r\n let autoNameCounter = 0;\r\n\r\n // Track inline handlers (arrow functions or function expressions in event attributes)\r\n const inlineHandlers = new Map<string, string>();\r\n let inlineHandlerCounter = 0;\r\n\r\n // Track handler attributes to remove from source (handler, onclick, onchange, etc.)\r\n const attributesToRemove: Array<{ start: number; end: number }> = [];\r\n\r\n // Walk through HTML nodes to find event handlers\r\n walkSvelteAst(ast.html || ast.fragment, (node: any, walkContext: WalkContext) => {\r\n if (node.type === \"Element\" || node.type === \"InlineComponent\" || node.type === \"RegularElement\" || node.type === \"Component\") {\r\n const attributes = node.attributes || [];\r\n const nodeName = node.name.toLowerCase();\r\n\r\n // Special handling for <components type=\"modal\"> elements\r\n if (nodeName === \"components\") {\r\n const typeAttr = attributes.find((attr: any) =>\r\n attr.type === \"Attribute\" && attr.name === \"type\"\r\n );\r\n const typeValue = typeAttr ? getAttributeValue(typeAttr) : null;\r\n\r\n if (typeValue === \"modal\") {\r\n // This is a modal definition - extract id and onsubmit handler\r\n const idAttr = attributes.find((attr: any) =>\r\n attr.type === \"Attribute\" && attr.name === \"id\"\r\n );\r\n const modalId = idAttr ? getAttributeValue(idAttr) : null;\r\n\r\n if (modalId) {\r\n const modalInfo: ModalHandlerInfo = { modalId };\r\n\r\n // Find onsubmit handler\r\n for (const attr of attributes) {\r\n const isOnSubmit = (attr.type === \"Attribute\" && attr.name === \"onsubmit\") ||\r\n (attr.type === \"EventHandler\" && attr.name === \"submit\");\r\n\r\n if (isOnSubmit) {\r\n let handlerName = \"\";\r\n\r\n if (attr.type === \"Attribute\" && Array.isArray(attr.value)) {\r\n const exprValue = attr.value.find((v: any) => v.type === \"ExpressionTag\" || v.type === \"MustacheTag\");\r\n if (exprValue && exprValue.expression) {\r\n if (exprValue.expression.type === \"Identifier\") {\r\n handlerName = exprValue.expression.name;\r\n } else if (exprValue.expression.type === \"CallExpression\" && exprValue.expression.callee) {\r\n handlerName = exprValue.expression.callee.name;\r\n }\r\n }\r\n } else if (attr.expression) {\r\n if (attr.expression.type === \"Identifier\") {\r\n handlerName = attr.expression.name;\r\n } else if (attr.expression.type === \"CallExpression\" && attr.expression.callee) {\r\n handlerName = attr.expression.callee.name;\r\n }\r\n }\r\n\r\n if (handlerName) {\r\n modalInfo.onsubmitHandler = handlerName;\r\n }\r\n\r\n // Track this attribute for removal from source (onsubmit shouldn't be in HTML)\r\n if (attr.start !== undefined && attr.end !== undefined) {\r\n attributesToRemove.push({ start: attr.start, end: attr.end });\r\n }\r\n break;\r\n }\r\n }\r\n\r\n modalHandlers.set(modalId, modalInfo);\r\n }\r\n }\r\n return; // Don't process <components> as regular elements\r\n }\r\n\r\n // Find name attribute\r\n const nameAttr = attributes.find((attr: any) =>\r\n attr.type === \"Attribute\" && attr.name === \"name\"\r\n );\r\n\r\n // Check if element has an onclick/onchange/handler and get the handler info\r\n let foundHandler: { eventType: string; handlerName: string; inlineCode?: string; isInline?: boolean } | null = null;\r\n\r\n for (const attr of attributes) {\r\n const isEventHandler = attr.type === \"EventHandler\";\r\n const isOnAttribute = attr.type === \"Attribute\" && attr.name && attr.name.startsWith(\"on\");\r\n const isHandlerAttribute = attr.type === \"Attribute\" && attr.name === \"handler\";\r\n\r\n if (isEventHandler || isOnAttribute || isHandlerAttribute) {\r\n // For \"handler\" attribute, use the element type to determine eventType\r\n // button -> onclick, select -> onchange\r\n let eventType = attr.name;\r\n if (isHandlerAttribute) {\r\n const elementName = node.name.toLowerCase();\r\n if (elementName === \"button\") {\r\n eventType = \"onclick\";\r\n } else if (elementName.includes(\"select\")) {\r\n eventType = \"onchange\";\r\n } else {\r\n eventType = \"handler\"; // fallback\r\n }\r\n }\r\n let handlerName = \"\";\r\n let inlineCode: string | undefined;\r\n let isInline = false;\r\n\r\n if (attr.type === \"Attribute\" && Array.isArray(attr.value)) {\r\n const exprValue = attr.value.find((v: any) => v.type === \"ExpressionTag\" || v.type === \"MustacheTag\");\r\n if (exprValue && exprValue.expression) {\r\n if (exprValue.expression.type === \"Identifier\") {\r\n handlerName = exprValue.expression.name;\r\n } else if (exprValue.expression.type === \"CallExpression\" && exprValue.expression.callee) {\r\n handlerName = exprValue.expression.callee.name;\r\n } else if (exprValue.expression.type === \"ArrowFunctionExpression\" || exprValue.expression.type === \"FunctionExpression\") {\r\n // Inline arrow function or function expression - extract the code\r\n isInline = true;\r\n handlerName = `__inline_handler_${inlineHandlerCounter++}`;\r\n // Extract the source code from the expression\r\n const expr = exprValue.expression;\r\n if (expr.start !== undefined && expr.end !== undefined) {\r\n inlineCode = source.substring(expr.start, expr.end);\r\n }\r\n }\r\n }\r\n } else if (attr.expression) {\r\n if (attr.expression.type === \"Identifier\") {\r\n handlerName = attr.expression.name;\r\n } else if (attr.expression.type === \"CallExpression\" && attr.expression.callee) {\r\n handlerName = attr.expression.callee.name;\r\n } else if (attr.expression.type === \"MemberExpression\") {\r\n handlerName = extractMemberExpressionName(attr.expression);\r\n } else if (attr.expression.type === \"ArrowFunctionExpression\" || attr.expression.type === \"FunctionExpression\") {\r\n // Inline arrow function or function expression - extract the code\r\n isInline = true;\r\n handlerName = `__inline_handler_${inlineHandlerCounter++}`;\r\n // Extract the source code from the expression\r\n const expr = attr.expression;\r\n if (expr.start !== undefined && expr.end !== undefined) {\r\n inlineCode = source.substring(expr.start, expr.end);\r\n }\r\n }\r\n }\r\n\r\n if (handlerName) {\r\n foundHandler = { eventType, handlerName, inlineCode, isInline };\r\n // If it's an inline handler, store the code\r\n if (isInline && inlineCode) {\r\n inlineHandlers.set(handlerName, inlineCode);\r\n }\r\n // Track this attribute for removal from source\r\n if (attr.start !== undefined && attr.end !== undefined) {\r\n attributesToRemove.push({ start: attr.start, end: attr.end });\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (!foundHandler) return; // No handler found, skip\r\n\r\n let componentName: string;\r\n const isInsideEach = walkContext.eachBlocks.length > 0;\r\n\r\n if (nameAttr) {\r\n componentName = getAttributeValue(nameAttr);\r\n } else {\r\n // No name attribute - generate one\r\n // If inside {#each}, we need a DYNAMIC name using the loop variable\r\n const positionKey = `${node.name.toLowerCase()}_${autoNameCounter++}`;\r\n\r\n if (isInsideEach) {\r\n // Inside {#each} - we'll inject a dynamic name expression\r\n // The actual name will be generated at runtime using loop variables\r\n componentName = `__auto_${positionKey}`;\r\n } else {\r\n // Not in loop - use static deterministic name\r\n // If data is provided, use/store in $autoNames for persistence across re-renders\r\n if (data) {\r\n if (!data.$autoNames) {\r\n data.$autoNames = {};\r\n }\r\n if (!data.$autoNames[positionKey]) {\r\n data.$autoNames[positionKey] = `__auto_${positionKey}`;\r\n }\r\n componentName = data.$autoNames[positionKey];\r\n } else {\r\n componentName = `__auto_${positionKey}`;\r\n }\r\n }\r\n\r\n // Track this element for source injection\r\n elementsNeedingNames.push({\r\n node,\r\n name: componentName,\r\n handlerName: foundHandler.handlerName,\r\n eventType: foundHandler.eventType,\r\n element: node.name.toLowerCase(),\r\n eachContext: isInsideEach ? walkContext.eachBlocks.map(b => ({\r\n iterVar: b.iterVar,\r\n indexVar: b.indexVar,\r\n keyExpr: b.keyExpr\r\n })) : undefined\r\n });\r\n }\r\n\r\n // Add to handlers map\r\n handlers.set(componentName, {\r\n name: componentName,\r\n handlerName: foundHandler.handlerName,\r\n eventType: foundHandler.eventType,\r\n element: node.name.toLowerCase(),\r\n inlineCode: foundHandler.inlineCode,\r\n isInline: foundHandler.isInline,\r\n isDynamicName: isInsideEach,\r\n });\r\n }\r\n });\r\n\r\n // Process source modifications:\r\n // 1. Remove handler attributes (onclick, onchange, handler) - they shouldn't be in final HTML\r\n // 2. Inject auto-generated names for elements that need them\r\n // \r\n // We apply removals first, then insertions, adjusting positions as we go\r\n let processedSource = source;\r\n\r\n // First, apply all attribute removals (sorted by position descending)\r\n // Don't eat leading whitespace - just remove the attribute itself\r\n const sortedRemovals = [...attributesToRemove].sort((a, b) => b.start - a.start);\r\n for (const { start, end } of sortedRemovals) {\r\n // Remove one leading space if present (to avoid double spaces)\r\n let actualStart = start;\r\n if (actualStart > 0 && source[actualStart - 1] === ' ') {\r\n actualStart--;\r\n }\r\n processedSource = processedSource.slice(0, actualStart) + processedSource.slice(end);\r\n }\r\n\r\n // Now re-parse the modified source to get correct positions for name injections\r\n // Instead of re-parsing, we'll calculate the offset adjustments\r\n // But this is complex - simpler approach: just work with the modified source directly\r\n\r\n // Since we removed attributes, we need to re-identify elements that need names\r\n // The safest approach: use regex to find elements without name attributes and add them\r\n\r\n // For elements that need names, find them in the processed source and inject names\r\n for (const { node, name, eachContext } of elementsNeedingNames) {\r\n const tagName = node.name.toLowerCase();\r\n\r\n let nameAttrValue: string;\r\n if (eachContext && eachContext.length > 0) {\r\n const keyParts: string[] = [name];\r\n for (let i = 0; i < eachContext.length; i++) {\r\n const ctx = eachContext[i];\r\n if (ctx.indexVar) {\r\n keyParts.push(`\\${${ctx.indexVar}}`);\r\n } else {\r\n keyParts.push(`\\${${ctx.iterVar}?.id ?? ${ctx.iterVar}?.name ?? ${ctx.iterVar}?.key ?? ${ctx.iterVar}?.value ?? JSON.stringify(${ctx.iterVar}).slice(0,20)}`);\r\n }\r\n }\r\n nameAttrValue = `{\\`${keyParts.join('_')}\\`}`;\r\n } else {\r\n nameAttrValue = `\"${name}\"`;\r\n }\r\n\r\n // Find this element in the processed source and add name attribute\r\n // Match the tag without a name attribute\r\n const tagRegex = new RegExp(`(<${tagName})(?![^>]*\\\\bname[=\\\\s])([^>]*>)`, 'i');\r\n processedSource = processedSource.replace(tagRegex, `$1 name=${nameAttrValue}$2`);\r\n }\r\n\r\n // Extract declared props from $props() destructuring\r\n const declaredProps: string[] = [];\r\n const propsWithDefaults: string[] = [];\r\n const propsMatch = scriptContent.match(/(?:const|let)\\s+\\{([\\s\\S]*?)\\}\\s*=\\s*\\$props\\(\\)/);\r\n if (propsMatch) {\r\n const propsContent = propsMatch[1];\r\n // Remove comments first\r\n const cleanedContent = propsContent\r\n .replace(/\\/\\/.*$/gm, '')\r\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\r\n const props = parsePropsContent(cleanedContent);\r\n for (const prop of props) {\r\n if (prop.name) {\r\n declaredProps.push(prop.name);\r\n if (prop.defaultValue !== undefined) {\r\n propsWithDefaults.push(prop.name);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Extract declared function names\r\n const declaredFunctions: string[] = [];\r\n const funcRegex = /(?:async\\s+)?function\\s+(\\w+)\\s*\\(/g;\r\n let funcMatch;\r\n while ((funcMatch = funcRegex.exec(scriptContent)) !== null) {\r\n declaredFunctions.push(funcMatch[1]);\r\n }\r\n // Also match arrow functions assigned to variables: const/let/var name = (async) () =>\r\n const arrowRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>/g;\r\n while ((funcMatch = arrowRegex.exec(scriptContent)) !== null) {\r\n declaredFunctions.push(funcMatch[1]);\r\n }\r\n\r\n return {\r\n handlers,\r\n modalHandlers,\r\n scriptContent,\r\n processedSource,\r\n declaredProps,\r\n propsWithDefaults,\r\n declaredFunctions,\r\n inlineHandlers\r\n };\r\n}\r\n\r\n/**\r\n * Extract the full name from a MemberExpression (e.g., obj.method)\r\n */\r\nfunction extractMemberExpressionName(expr: any): string {\r\n if (expr.type === \"Identifier\") {\r\n return expr.name;\r\n }\r\n if (expr.type === \"MemberExpression\") {\r\n const object = extractMemberExpressionName(expr.object);\r\n const property = expr.property.name || expr.property.value;\r\n return `${object}.${property}`;\r\n }\r\n return \"\";\r\n}\r\n\r\n/**\r\n * Get the value from an attribute\r\n */\r\nfunction getAttributeValue(attr: any): string {\r\n if (!attr.value) return \"\";\r\n\r\n if (Array.isArray(attr.value)) {\r\n // Static text value\r\n if (attr.value[0]?.type === \"Text\") {\r\n return attr.value[0].data;\r\n }\r\n // Expression value\r\n if (attr.value[0]?.expression) {\r\n return extractExpressionValue(attr.value[0].expression);\r\n }\r\n }\r\n\r\n return \"\";\r\n}\r\n\r\n/**\r\n * Extract value from an expression\r\n */\r\nfunction extractExpressionValue(expr: any): string {\r\n if (expr.type === \"Identifier\") {\r\n return expr.name;\r\n }\r\n if (expr.type === \"Literal\") {\r\n return String(expr.value);\r\n }\r\n return \"\";\r\n}\r\n\r\n/**\r\n * Parse $props() destructuring content with proper brace/bracket counting\r\n * Handles nested objects like: { name, options = { a: 1, b: [1, 2] }, count = 0 }\r\n */\r\nfunction parsePropsContent(content: string): Array<{ name: string; defaultValue?: string }> {\r\n const props: Array<{ name: string; defaultValue?: string }> = [];\r\n let current = '';\r\n let braceCount = 0;\r\n let bracketCount = 0;\r\n let parenCount = 0;\r\n let inString: string | null = null;\r\n\r\n for (let i = 0; i <= content.length; i++) {\r\n const char = content[i];\r\n const prevChar = i > 0 ? content[i - 1] : '';\r\n\r\n // Handle string boundaries\r\n if ((char === '\"' || char === \"'\" || char === '`') && prevChar !== '\\\\') {\r\n if (inString === char) {\r\n inString = null;\r\n } else if (!inString) {\r\n inString = char;\r\n }\r\n }\r\n\r\n // Only process structural characters when not in a string\r\n if (!inString) {\r\n if (char === '{') braceCount++;\r\n else if (char === '}') braceCount--;\r\n else if (char === '[') bracketCount++;\r\n else if (char === ']') bracketCount--;\r\n else if (char === '(') parenCount++;\r\n else if (char === ')') parenCount--;\r\n\r\n // Split on comma only when at top level (no nested braces/brackets/parens)\r\n if ((char === ',' || i === content.length) && braceCount === 0 && bracketCount === 0 && parenCount === 0) {\r\n const trimmed = current.trim();\r\n if (trimmed) {\r\n // Parse \"name = defaultValue\" or just \"name\"\r\n const equalsIndex = trimmed.indexOf('=');\r\n if (equalsIndex > 0) {\r\n const name = trimmed.substring(0, equalsIndex).trim();\r\n const defaultValue = trimmed.substring(equalsIndex + 1).trim();\r\n props.push({ name, defaultValue });\r\n } else {\r\n props.push({ name: trimmed });\r\n }\r\n }\r\n current = '';\r\n continue;\r\n }\r\n }\r\n\r\n if (i < content.length) {\r\n current += char;\r\n }\r\n }\r\n\r\n return props;\r\n}\r\n\r\n/**\r\n * Validate a Svelte component and return warnings\r\n * Call this during development/registration to catch potential issues early\r\n */\r\nexport function validateSvelteComponent(\r\n componentInfo: SvelteComponentInfo,\r\n data: Record<string, any> = {},\r\n componentName: string = 'unknown'\r\n): SvelteValidationWarning[] {\r\n const warnings: SvelteValidationWarning[] = [];\r\n\r\n // Skip internal props/data keys (used by the framework)\r\n const internalKeys = ['$ref', '$unRef', '__unRefWrapped__', '$autoNames', 'data'];\r\n\r\n // 1. Check for props declared but not provided in data (missing required data)\r\n // Skip props that have default values - they don't require data\r\n for (const prop of componentInfo.declaredProps) {\r\n if (internalKeys.includes(prop)) continue;\r\n if (componentInfo.propsWithDefaults.includes(prop)) continue; // Has default, not required\r\n if (!(prop in data)) {\r\n warnings.push({\r\n type: 'missing-data',\r\n message: `[${componentName}] Prop \"${prop}\" is declared in $props() without a default value but not provided in data`,\r\n details: `Add \"${prop}\" to your data object or provide a default value in $props()`\r\n });\r\n }\r\n }\r\n\r\n // 2. Check for data provided but not declared in props (potential typo or unused)\r\n for (const key of Object.keys(data)) {\r\n if (internalKeys.includes(key)) continue;\r\n if (key.startsWith('$')) continue; // Skip all $-prefixed internal keys\r\n if (!componentInfo.declaredProps.includes(key)) {\r\n warnings.push({\r\n type: 'unused-data',\r\n message: `[${componentName}] Data key \"${key}\" is provided but not declared in $props()`,\r\n details: `This data won't be accessible in the component. Add it to $props() destructuring.`\r\n });\r\n }\r\n }\r\n\r\n // 3. Check for undefined handlers referenced in elements\r\n // Skip inline handlers (they are extracted from template, not defined in script)\r\n for (const [elementName, handlerInfo] of componentInfo.handlers) {\r\n // Skip inline handlers - they are defined in the template, not the script\r\n if (handlerInfo.isInline) continue;\r\n if (!componentInfo.declaredFunctions.includes(handlerInfo.handlerName)) {\r\n warnings.push({\r\n type: 'undefined-handler',\r\n message: `[${componentName}] Handler \"${handlerInfo.handlerName}\" referenced by <${handlerInfo.element} name=\"${elementName}\"> is not defined`,\r\n details: `Make sure to define \"function ${handlerInfo.handlerName}(ctx) { ... }\" in your script`\r\n });\r\n }\r\n }\r\n\r\n // 4. Check for undefined modal submit handlers\r\n for (const [modalId, modalInfo] of componentInfo.modalHandlers) {\r\n if (modalInfo.onsubmitHandler && !componentInfo.declaredFunctions.includes(modalInfo.onsubmitHandler)) {\r\n warnings.push({\r\n type: 'undefined-handler',\r\n message: `[${componentName}] Modal submit handler \"${modalInfo.onsubmitHandler}\" for modal \"${modalId}\" is not defined`,\r\n details: `Make sure to define \"function ${modalInfo.onsubmitHandler}(ctx, fields) { ... }\" in your script`\r\n });\r\n }\r\n }\r\n\r\n // 5. Check for modal handler signatures (ctx parameter is optional for regular handlers)\r\n // Only modal handlers MUST have fields parameter to access submitted data\r\n const handlerFunctionRegex = /(?:async\\s+)?function\\s+(\\w+)\\s*\\(\\s*(\\w*)\\s*(?:,\\s*(\\w+))?\\s*\\)/g;\r\n let match;\r\n const scriptContent = componentInfo.scriptContent;\r\n\r\n while ((match = handlerFunctionRegex.exec(scriptContent)) !== null) {\r\n const funcName = match[1];\r\n const firstParam = match[2];\r\n const secondParam = match[3];\r\n\r\n // Only check modal handlers - they need 'fields' param to access form data\r\n const isModalHandler = Array.from(componentInfo.modalHandlers.values()).some(m => m.onsubmitHandler === funcName);\r\n\r\n if (isModalHandler && !secondParam) {\r\n warnings.push({\r\n type: 'syntax-error',\r\n message: `[${componentName}] Modal handler \"${funcName}\" should have \"ctx\" and \"fields\" parameters`,\r\n details: `Change to \"function ${funcName}(ctx, fields) { ... }\" to receive submitted form data`\r\n });\r\n }\r\n }\r\n\r\n // 6. Check for common template mistakes\r\n const templateContent = componentInfo.processedSource;\r\n\r\n // Check for onclick= without braces (common mistake)\r\n const badOnClickRegex = /onclick\\s*=\\s*[\"']([^\"']+)[\"']/gi;\r\n while ((match = badOnClickRegex.exec(templateContent)) !== null) {\r\n if (!match[1].startsWith('{')) {\r\n warnings.push({\r\n type: 'syntax-error',\r\n message: `[${componentName}] onclick handler should use curly braces: onclick={${match[1]}}`,\r\n details: `String values are not valid for event handlers. Use onclick={handlerName} syntax.`\r\n });\r\n }\r\n }\r\n\r\n // Check for undefined variables in {expression} blocks (basic check)\r\n const expressionRegex = /\\{([^}]+)\\}/g;\r\n const knownIdentifiers = new Set([\r\n ...componentInfo.declaredProps,\r\n ...componentInfo.declaredFunctions,\r\n // Common Svelte/JS globals\r\n 'true', 'false', 'null', 'undefined', 'console', 'Math', 'JSON', 'Array', 'Object',\r\n 'Date', 'Number', 'String', 'Boolean', 'Promise', 'Map', 'Set',\r\n // Common Svelte constructs\r\n '#if', '/if', '#each', '/each', '#await', '/await', ':else', ':then', ':catch',\r\n '@html', '@debug', '@const'\r\n ]);\r\n\r\n // Add variables from script (let, const, var declarations)\r\n const varDeclRegex = /(?:let|const|var)\\s+(\\w+)/g;\r\n while ((match = varDeclRegex.exec(scriptContent)) !== null) {\r\n knownIdentifiers.add(match[1]);\r\n }\r\n\r\n return warnings;\r\n}\r\n\r\n/**\r\n * Log validation warnings to console with colors\r\n */\r\nexport function logValidationWarnings(warnings: SvelteValidationWarning[]): void {\r\n if (warnings.length === 0) return;\r\n\r\n console.warn(`\\n⚠️ Svelte Component Validation Warnings (${warnings.length}):`);\r\n\r\n for (const warning of warnings) {\r\n const icon = warning.type === 'missing-data' ? '❌' :\r\n warning.type === 'unused-data' ? '⚠️' :\r\n warning.type === 'undefined-handler' ? '🔗' :\r\n warning.type === 'syntax-error' ? '💥' : '⚡';\r\n\r\n console.warn(` ${icon} ${warning.message}`);\r\n if (warning.details) {\r\n console.warn(` └─ ${warning.details}`);\r\n }\r\n }\r\n console.warn('');\r\n}\r\n\r\nexport interface HandlerContextResult {\r\n handlers: Record<string, Function>;\r\n effects: Function[];\r\n runEffects: () => void;\r\n hasPendingRender: () => boolean;\r\n flushRender: () => Promise<void>;\r\n wrappedCtx: any; // Proxy-wrapped ctx for passing to handlers\r\n // Lifecycle hooks\r\n mountCallbacks: Function[];\r\n destroyCallbacks: Function[];\r\n preRenderCallbacks: Function[];\r\n afterRenderCallbacks: Function[];\r\n runMount: () => void;\r\n runDestroy: () => void;\r\n runPreRender: () => Promise<void>;\r\n runAfterRender: () => void;\r\n // Handler execution tracking\r\n setInHandler: (value: boolean) => void;\r\n // Manual render function\r\n render: (immediate?: boolean) => Promise<void>;\r\n}\r\n\r\n/**\r\n * Parse import statements from script and extract module info\r\n */\r\ninterface ImportInfo {\r\n moduleName: string;\r\n imports: { name: string; alias?: string }[];\r\n isDefault: boolean;\r\n defaultName?: string;\r\n}\r\n\r\nfunction parseImports(script: string): { imports: ImportInfo[]; cleanedScript: string } {\r\n const imports: ImportInfo[] = [];\r\n\r\n // Match: import { a, b as c } from \"module\"\r\n // Match: import name from \"module\"\r\n // Match: import * as name from \"module\"\r\n const importRegex = /import\\s+(?:(\\w+)\\s*,?\\s*)?(?:\\{\\s*([^}]+)\\s*\\})?(?:\\*\\s+as\\s+(\\w+))?\\s+from\\s+[\"']([^\"']+)[\"'];?/g;\r\n\r\n let cleanedScript = script;\r\n let match;\r\n\r\n while ((match = importRegex.exec(script)) !== null) {\r\n const [fullMatch, defaultImport, namedImports, namespaceImport, moduleName] = match;\r\n\r\n // Skip svelte internal imports - we provide these ourselves\r\n if (moduleName === 'svelte' || moduleName.startsWith('svelte/')) {\r\n cleanedScript = cleanedScript.replace(fullMatch, '');\r\n continue;\r\n }\r\n\r\n const importInfo: ImportInfo = {\r\n moduleName,\r\n imports: [],\r\n isDefault: false\r\n };\r\n\r\n // Default import: import name from \"module\"\r\n if (defaultImport) {\r\n importInfo.isDefault = true;\r\n importInfo.defaultName = defaultImport;\r\n }\r\n\r\n // Namespace import: import * as name from \"module\"\r\n if (namespaceImport) {\r\n importInfo.isDefault = true;\r\n importInfo.defaultName = namespaceImport;\r\n }\r\n\r\n // Named imports: import { a, b as c } from \"module\"\r\n if (namedImports) {\r\n const parts = namedImports.split(',').map(s => s.trim()).filter(Boolean);\r\n for (const part of parts) {\r\n const aliasMatch = part.match(/^(\\w+)\\s+as\\s+(\\w+)$/);\r\n if (aliasMatch) {\r\n importInfo.imports.push({ name: aliasMatch[1], alias: aliasMatch[2] });\r\n } else {\r\n importInfo.imports.push({ name: part });\r\n }\r\n }\r\n }\r\n\r\n imports.push(importInfo);\r\n cleanedScript = cleanedScript.replace(fullMatch, '');\r\n }\r\n\r\n return { imports, cleanedScript };\r\n}\r\n\r\n/**\r\n * Load modules and create injection variables\r\n */\r\nfunction loadModules(imports: ImportInfo[], sourceDir?: string): { modules: Record<string, any>; varDeclarations: string } {\r\n const modules: Record<string, any> = {};\r\n const declarations: string[] = [];\r\n const path = require(\"path\");\r\n\r\n for (const importInfo of imports) {\r\n try {\r\n // Resolve relative paths from source file directory\r\n const resolvedPath = importInfo.moduleName.startsWith('.') && sourceDir\r\n ? path.resolve(sourceDir, importInfo.moduleName)\r\n : importInfo.moduleName;\r\n // Try to require the module\r\n const mod = require(resolvedPath);\r\n\r\n if (importInfo.isDefault && importInfo.defaultName) {\r\n // Default or namespace import\r\n modules[importInfo.defaultName] = mod.default || mod;\r\n declarations.push(`var ${importInfo.defaultName} = __modules__[\"${importInfo.defaultName}\"];`);\r\n }\r\n\r\n // Named imports\r\n for (const imp of importInfo.imports) {\r\n const varName = imp.alias || imp.name;\r\n modules[varName] = mod[imp.name];\r\n declarations.push(`var ${varName} = __modules__[\"${varName}\"];`);\r\n }\r\n } catch (err) {\r\n // Module import failed\r\n }\r\n }\r\n\r\n return { modules, varDeclarations: declarations.join('\\n') };\r\n}\r\n\r\n/**\r\n * Create a handler context from script content\r\n * This evaluates the Svelte script and returns the handler functions and effects\r\n * @param sourceDir - The directory of the source file (used for resolving relative imports)\r\n * @param inlineHandlers - Map of inline handler names to their source code (extracted from template)\r\n */\r\nexport function createHandlerContext(scriptContent: string, initialData: Record<string, any> = {}, component?: any, ctx?: any, sourceDir?: string, inlineHandlers?: Map<string, string>): HandlerContextResult {\r\n const handlers: Record<string, Function> = {};\r\n const effects: Function[] = [];\r\n\r\n try {\r\n // Parse and extract imports first\r\n const { imports, cleanedScript } = parseImports(scriptContent);\r\n const { modules, varDeclarations } = loadModules(imports, sourceDir);\r\n\r\n // Extract only function declarations from the script\r\n const functionNames = extractFunctionNames(cleanedScript);\r\n\r\n // Extract $effect calls and convert them to collectable functions\r\n const effectBodies = extractEffectBodies(cleanedScript);\r\n\r\n // Process script to be safe for evaluation:\r\n // 1. Remove reactive declarations (let x = $state(...))\r\n // 2. Remove $props destructuring\r\n // 3. Convert $effect to __registerEffect__\r\n // 4. Keep only function declarations\r\n\r\n // First, remove comments from the script to avoid regex issues with braces in comments\r\n let scriptWithoutComments = cleanedScript\r\n // Remove single-line comments (but preserve the newline)\r\n .replace(/\\/\\/.*$/gm, '')\r\n // Remove multi-line comments\r\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\r\n\r\n let processedScript = scriptWithoutComments\r\n // Remove $state declarations completely or make them var\r\n .replace(/(?:const|let)\\s+(\\w+)\\s*=\\s*\\$state\\(([^)]*)\\);?/g, 'var $1 = $2;')\r\n // Remove $derived declarations but keep the value\r\n .replace(/(?:const|let)\\s+(\\w+)\\s*=\\s*\\$derived\\(([^)]+)\\);?/g, 'var $1 = $2;')\r\n // Convert $effect calls to __registerEffect__ calls\r\n .replace(/\\$effect\\s*\\(\\s*((?:function\\s*\\([^)]*\\)|\\([^)]*\\)\\s*=>|\\(\\)\\s*=>)[^}]*\\{[\\s\\S]*?\\}\\s*)\\);?/g, '__registerEffect__($1);')\r\n // Simpler $effect pattern: $effect(() => { ... })\r\n .replace(/\\$effect\\s*\\(\\s*\\(\\)\\s*=>\\s*\\{([\\s\\S]*?)\\}\\s*\\);?/g, '__registerEffect__(function() {$1});');\r\n\r\n // Handle $props destructuring with proper brace counting (supports nested objects like { options = { a: 1 } })\r\n processedScript = processedScript.replace(/(?:const|let)\\s+\\{([\\s\\S]*?)\\}\\s*=\\s*\\$props\\(\\);?/g, (match) => {\r\n // Find the opening brace after 'const' or 'let'\r\n const letIndex = match.indexOf('{');\r\n if (letIndex === -1) return match;\r\n\r\n // Use brace counting to find the matching closing brace\r\n let braceCount = 0;\r\n let startIndex = letIndex;\r\n let endIndex = -1;\r\n\r\n for (let i = startIndex; i < match.length; i++) {\r\n if (match[i] === '{') braceCount++;\r\n else if (match[i] === '}') {\r\n braceCount--;\r\n if (braceCount === 0) {\r\n endIndex = i;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (endIndex === -1) return match;\r\n\r\n // Extract the content between braces\r\n const content = match.substring(startIndex + 1, endIndex);\r\n\r\n // Parse props with proper handling of nested braces\r\n const props = parsePropsContent(content);\r\n\r\n // Generate prop accessors that read from data at access time\r\n // Use a special pattern: define both the initial var AND a __propGetters__ object\r\n // that inline handlers can use to get current values\r\n const propDefs = props.map(prop => {\r\n if (!prop.name || prop.name === 'data') return '';\r\n if (prop.defaultValue !== undefined) {\r\n return `var ${prop.name} = data.${prop.name} ?? ${prop.defaultValue}; __propGetters__.${prop.name} = function() { return data.${prop.name} ?? ${prop.defaultValue}; };`;\r\n }\r\n return `var ${prop.name} = data.${prop.name}; __propGetters__.${prop.name} = function() { return data.${prop.name}; };`;\r\n }).filter(Boolean).join('\\n');\r\n\r\n return propDefs;\r\n });\r\n\r\n // Add module variable declarations at the beginning of processed script\r\n if (varDeclarations) {\r\n processedScript = varDeclarations + '\\n\\n' + processedScript;\r\n }\r\n\r\n // Wrap everything in an IIFE that takes data and component as parameters\r\n // This ensures data and 'this' are always available in the function scope\r\n // Also provides helper functions: render(), update() and rerender()\r\n // Data is wrapped in a Proxy for automatic reactivity\r\n // Interaction methods (reply, followUp, deferReply) are wrapped to auto-render after completion\r\n const wrappedScript = `\r\n return function(__data__, __component__, __ctx__, __modules__) {\r\n __modules__ = __modules__ || {};\r\n var self = __component__;\r\n var __effects__ = [];\r\n var __renderPending__ = false;\r\n var __autoRenderEnabled__ = true;\r\n var __hasDataChanges__ = false;\r\n \r\n // Prop getters for accessing current data values (used by inline handlers)\r\n var __propGetters__ = {};\r\n \r\n // Lifecycle callbacks\r\n var __mountCallbacks__ = [];\r\n var __destroyCallbacks__ = [];\r\n var __preRenderCallbacks__ = [];\r\n var __afterRenderCallbacks__ = [];\r\n var __isMounted__ = false;\r\n \r\n // Store last message reference for background updates (intervals, timeouts)\r\n var __lastMessage__ = __ctx__?.interaction?.message || null;\r\n \r\n // Throttle configuration\r\n var __throttleMinInterval__ = 250; // Minimum ms between renders\r\n var __lastRenderTime__ = 0;\r\n var __pendingRenderTimeout__ = null;\r\n var __isRateLimited__ = false;\r\n var __rateLimitEndTime__ = 0;\r\n \r\n function __registerEffect__(fn) {\r\n __effects__.push(fn);\r\n }\r\n \r\n // Lifecycle: onMount - called when component is first rendered\r\n // If callback returns a function, that function is called on destroy\r\n function onMount(fn) {\r\n __mountCallbacks__.push(fn);\r\n }\r\n \r\n // Lifecycle: onDestroy - called when ref is cleaned up\r\n function onDestroy(fn) {\r\n __destroyCallbacks__.push(fn);\r\n }\r\n \r\n // Lifecycle: onPreRender - called before each render (async, awaited)\r\n function onPreRender(fn) {\r\n __preRenderCallbacks__.push(fn);\r\n }\r\n \r\n // Lifecycle: onAfterRender - called after each render completes\r\n function onAfterRender(fn) {\r\n __afterRenderCallbacks__.push(fn);\r\n }\r\n \r\n // Run all pre-render callbacks (async)\r\n async function __runPreRender__() {\r\n for (var i = 0; i < __preRenderCallbacks__.length; i++) {\r\n try {\r\n await __preRenderCallbacks__[i]();\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] Pre-render callback failed:\", err);\r\n throw err;\r\n }\r\n }\r\n }\r\n \r\n // Run all after-render callbacks\r\n function __runAfterRender__() {\r\n for (var i = 0; i < __afterRenderCallbacks__.length; i++) {\r\n try {\r\n __afterRenderCallbacks__[i]();\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] After-render callback failed:\", err);\r\n throw err;\r\n }\r\n }\r\n }\r\n \r\n // Modal store - stores rendered modal definitions\r\n var __modals__ = new Map();\r\n \r\n // Register a modal (called internally when modals are parsed)\r\n function __registerModal__(modalId, modalDef) {\r\n __modals__.set(modalId, modalDef);\r\n }\r\n \r\n // Show a modal by ID and return a Promise that resolves with the submitted fields\r\n // Modal definitions are rendered from <components type=\"modal\" id=\"xxx\">\r\n // Usage: \r\n // await showModal(\"edit-product\"); // Just show, use onsubmit handler\r\n // const { fields, interaction } = await showModal(\"edit-product\"); // Get response\r\n // await showModal(\"edit-product\", { timeout: 60000 }); // 60 second timeout\r\n // await showModal(\"edit-product\", { timeout: 0 }); // No timeout (unlimited)\r\n function showModal(modalId, options) {\r\n if (!__ctx__ || !__ctx__.interaction) {\r\n return Promise.reject(new Error(\"showModal requires an interaction context\"));\r\n }\r\n \r\n // Default timeout: 10 minutes (600000ms), 0 = no timeout\r\n var timeout = (options && typeof options.timeout === 'number') ? options.timeout : 600000;\r\n \r\n // Disable auto-render IMMEDIATELY since we're showing a modal\r\n // This prevents flushRender from trying to update after modal is shown\r\n __autoRenderEnabled__ = false;\r\n __asyncInteractionCalled__ = true;\r\n \r\n // Create a promise that will be resolved when modal is submitted\r\n return new Promise(async function(resolve, reject) {\r\n var timeoutId = null;\r\n var modal = null;\r\n \r\n try {\r\n // Re-render to get latest modal definitions (reactive)\r\n var renderResult = await __component__.toJSON({ data: __data__ });\r\n \r\n // Get modals from the render result stored on component\r\n var modals = __component__.__lastRenderModals__;\r\n if (!modals) {\r\n reject(new Error(\"No modals defined in this component. Use <components type=\\\\\"modal\\\\\" id=\\\\\"...\\\\\">\")); \r\n return;\r\n }\r\n \r\n modal = modals.get(modalId);\r\n if (!modal) {\r\n reject(new Error(\"Modal '\" + modalId + \"' not found. Available modals: \" + Array.from(modals.keys()).join(\", \")));\r\n return;\r\n }\r\n \r\n // Wrapped resolve/reject to clear timeout\r\n var wrappedResolve = function(result) {\r\n if (timeoutId) clearTimeout(timeoutId);\r\n resolve(result);\r\n };\r\n var wrappedReject = function(error) {\r\n if (timeoutId) clearTimeout(timeoutId);\r\n reject(error);\r\n };\r\n \r\n // Store the promise resolver in component's pending modals map\r\n // This will be resolved when modal submit interaction is received\r\n __component__._pendingModals.set(modal.customId, { resolve: wrappedResolve, reject: wrappedReject });\r\n \r\n // Set up timeout if enabled (timeout > 0)\r\n if (timeout > 0) {\r\n timeoutId = setTimeout(function() {\r\n // Clean up pending modal\r\n __component__._pendingModals.delete(modal.customId);\r\n reject(new Error(\"Modal '\" + modalId + \"' timed out after \" + timeout + \"ms\"));\r\n }, timeout);\r\n }\r\n \r\n // Show the modal using the interaction\r\n var i = __ctx__.interaction;\r\n \r\n // Modal must be shown immediately - no deferral allowed\r\n await i.showModal({\r\n title: modal.title,\r\n customId: modal.customId,\r\n components: modal.components\r\n });\r\n \r\n // Note: Promise resolves later when modal is submitted\r\n // If you don't await for the response, the promise just hangs (which is fine)\r\n } catch (err) {\r\n // Clean up pending modal and timeout if show failed\r\n if (timeoutId) clearTimeout(timeoutId);\r\n if (modal && modal.customId) {\r\n __component__._pendingModals.delete(modal.customId);\r\n }\r\n reject(new Error(\"Failed to show modal: \" + (err.message || err)));\r\n }\r\n });\r\n }\r\n \r\n // Rate-limit aware edit function with retry and enhanced error handling\r\n function __safeEdit__(editFn, retryCount, componentsForError) {\r\n retryCount = retryCount || 0;\r\n var maxRetries = 3;\r\n \r\n return editFn().then(function(result) {\r\n return result;\r\n }).catch(function(err) {\r\n // Check for rate limit (429)\r\n if (err.status === 429 || (err.message && err.message.includes('rate limit'))) {\r\n var retryAfter = err.retry_after || err.retryAfter || 1;\r\n __isRateLimited__ = true;\r\n __rateLimitEndTime__ = Date.now() + (retryAfter * 1000);\r\n \r\n return new Promise(function(resolve) {\r\n setTimeout(function() {\r\n __isRateLimited__ = false;\r\n if (retryCount < maxRetries) {\r\n resolve(__safeEdit__(editFn, retryCount + 1, componentsForError));\r\n } else {\r\n resolve();\r\n }\r\n }, retryAfter * 1000);\r\n });\r\n }\r\n \r\n // Check if it's a component validation error and enhance it\r\n if (err.code === 50035 || err.rawError?.code === 50035 || \r\n (err.message && (err.message.includes('Invalid Form Body') || err.message.includes('BASE_TYPE')))) {\r\n // Create enhanced error message\r\n var errorMsg = err.message || '';\r\n var enhancedMsg = '\\\\n╔══════════════════════════════════════════════════════════════╗\\\\n';\r\n enhancedMsg += '║ Discord Components V2 Validation Error ║\\\\n';\r\n enhancedMsg += '╠══════════════════════════════════════════════════════════════╣\\\\n';\r\n \r\n // Parse error paths from message\r\n var errorLines = errorMsg.split('\\\\n');\r\n for (var i = 0; i < errorLines.length; i++) {\r\n var line = errorLines[i];\r\n var match = line.match(/([\\\\w\\\\[\\\\]\\\\.]+)\\\\[([A-Z_]+)\\\\]:\\\\s*(.+)/);\r\n if (match) {\r\n var path = match[1];\r\n var code = match[2];\r\n var msg = match[3];\r\n \r\n enhancedMsg += '║\\\\n';\r\n enhancedMsg += '║ ❌ Path: ' + path + '\\\\n';\r\n enhancedMsg += '║ ├─ Code: ' + code + '\\\\n';\r\n enhancedMsg += '║ ├─ Message: ' + msg + '\\\\n';\r\n \r\n // Add helpful hints based on error code\r\n if (code === 'BASE_TYPE_REQUIRED') {\r\n enhancedMsg += '║ └─ Fix: This field is required - check if the element has all required attributes\\\\n';\r\n } else if (code === 'BASE_TYPE_BAD_LENGTH') {\r\n enhancedMsg += '║ └─ Fix: Wrong number of items - Discord has min/max limits for components\\\\n';\r\n } else if (code.includes('MAX_LENGTH') || code.includes('MIN_LENGTH')) {\r\n enhancedMsg += '║ └─ Fix: Content length issue - adjust text or number of items\\\\n';\r\n }\r\n }\r\n }\r\n \r\n enhancedMsg += '║\\\\n';\r\n enhancedMsg += '╚══════════════════════════════════════════════════════════════╝';\r\n \r\n var enhancedError = new Error('[DBI-Svelte] Component validation error:\\\\n' + enhancedMsg + '\\\\n\\\\nOriginal: ' + errorMsg);\r\n enhancedError.originalError = err;\r\n enhancedError.type = 'discord-component-validation';\r\n throw enhancedError;\r\n }\r\n \r\n // Re-throw other errors\r\n throw err;\r\n });\r\n }\r\n \r\n // Throttled render - ensures minimum interval between renders\r\n function __throttledRender__(immediate) {\r\n var now = Date.now();\r\n var timeSinceLastRender = now - __lastRenderTime__;\r\n var waitTime = 0;\r\n \r\n // If rate limited, calculate wait time\r\n if (__isRateLimited__ && __rateLimitEndTime__ > now) {\r\n waitTime = Math.max(waitTime, __rateLimitEndTime__ - now);\r\n }\r\n \r\n // If within throttle interval, schedule for later\r\n if (!immediate && timeSinceLastRender < __throttleMinInterval__) {\r\n waitTime = Math.max(waitTime, __throttleMinInterval__ - timeSinceLastRender);\r\n }\r\n \r\n // Clear any pending render\r\n if (__pendingRenderTimeout__) {\r\n clearTimeout(__pendingRenderTimeout__);\r\n __pendingRenderTimeout__ = null;\r\n }\r\n \r\n if (waitTime > 0) {\r\n return new Promise(function(resolve) {\r\n __pendingRenderTimeout__ = setTimeout(function() {\r\n __pendingRenderTimeout__ = null;\r\n __lastRenderTime__ = Date.now();\r\n resolve(__executeRender__());\r\n }, waitTime);\r\n });\r\n }\r\n \r\n __lastRenderTime__ = now;\r\n return __executeRender__();\r\n }\r\n \r\n // Actual render execution\r\n async function __executeRender__() {\r\n // Run pre-render callbacks (async, awaited)\r\n await __runPreRender__();\r\n \r\n var components = await __component__.toJSON({ data: __data__ });\r\n var result;\r\n \r\n // Try to use current interaction if available\r\n if (__ctx__ && __ctx__.interaction) {\r\n try {\r\n var i = __ctx__.interaction;\r\n \r\n // Update last message reference\r\n if (i.message) {\r\n __lastMessage__ = i.message;\r\n }\r\n \r\n // Check if interaction was deferred (our flag) or Discord.js flags\r\n if (i.replied || i.deferred || __interactionDeferred__) {\r\n // Already replied/deferred, use message.edit with rate limit handling\r\n result = await __safeEdit__(function() {\r\n return i.message.edit({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n }, 0, components);\r\n } else {\r\n // Not replied yet, use update with rate limit handling\r\n result = await __safeEdit__(function() {\r\n return i.update({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n }, 0, components);\r\n }\r\n \r\n // Run after-render callbacks\r\n __runAfterRender__();\r\n return result;\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] Render failed:\", err);\r\n throw err;\r\n }\r\n }\r\n \r\n // Fallback: Use last message reference (for intervals/timeouts outside interaction)\r\n if (__lastMessage__) {\r\n result = await __safeEdit__(function() {\r\n return __lastMessage__.edit({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n }, 0, components);\r\n \r\n // Run after-render callbacks\r\n __runAfterRender__();\r\n return result;\r\n }\r\n \r\n return Promise.resolve();\r\n }\r\n \r\n // Helper: Auto-detect whether to use update() or rerender()\r\n // If interaction was already replied/deferred, use message.edit\r\n // Otherwise use interaction.update\r\n function render(immediate) {\r\n return __throttledRender__(immediate);\r\n }\r\n \r\n // Track if we're inside a handler execution\r\n var __inHandlerExecution__ = false;\r\n \r\n // Track pending low-priority updates (from intervals/timeouts)\r\n var __pendingLowPriorityRender__ = false;\r\n \r\n // Mark that we have pending data changes\r\n function __markDataChanged__() {\r\n __hasDataChanges__ = true;\r\n \r\n // If we're NOT inside a handler (e.g., interval/timeout), trigger render immediately\r\n // The throttle will prevent too many renders\r\n if (!__inHandlerExecution__ && __autoRenderEnabled__ && __lastMessage__) {\r\n __hasDataChanges__ = false;\r\n __throttledRender__(false);\r\n }\r\n }\r\n \r\n // Low-priority update - used for background tasks like intervals\r\n // If a handler is currently running, skip this update (the handler's update will include our changes)\r\n function lowPriorityUpdate(callback) {\r\n if (__inHandlerExecution__) {\r\n // Handler is running - just update data, skip render\r\n // The handler will render when it finishes\r\n if (callback) callback();\r\n return;\r\n }\r\n \r\n // No handler running - proceed with update\r\n if (callback) callback();\r\n }\r\n \r\n // Flush pending render (called after interaction methods complete)\r\n function __flushRender__() {\r\n if (__hasDataChanges__ && __autoRenderEnabled__) {\r\n __hasDataChanges__ = false;\r\n render();\r\n }\r\n }\r\n \r\n // Create reactive proxy for data\r\n // Also properly forwards Object.keys/values/entries operations\r\n function __createReactiveProxy__(target, path) {\r\n if (typeof target !== 'object' || target === null) return target;\r\n \r\n return new Proxy(target, {\r\n get: function(obj, prop) {\r\n var value = obj[prop];\r\n // Wrap nested objects in proxy too\r\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\r\n return __createReactiveProxy__(value, path + '.' + String(prop));\r\n }\r\n return value;\r\n },\r\n set: function(obj, prop, value) {\r\n var oldValue = obj[prop];\r\n obj[prop] = value;\r\n // Only mark as changed if value actually changed\r\n if (oldValue !== value) {\r\n __markDataChanged__();\r\n }\r\n return true;\r\n },\r\n // Forward Object.keys/values/entries operations\r\n ownKeys: function(target) {\r\n return Reflect.ownKeys(target);\r\n },\r\n getOwnPropertyDescriptor: function(target, prop) {\r\n return Reflect.getOwnPropertyDescriptor(target, prop);\r\n },\r\n has: function(target, prop) {\r\n return Reflect.has(target, prop);\r\n }\r\n });\r\n }\r\n \r\n // Wrap data in reactive proxy\r\n var data = __createReactiveProxy__(__data__, 'data');\r\n \r\n // Track if an async interaction method was called\r\n var __asyncInteractionCalled__ = false;\r\n \r\n // Track if interaction was deferred (deferUpdate/deferReply)\r\n var __interactionDeferred__ = false;\r\n \r\n // Wrap interaction methods to auto-render after completion\r\n var interaction = null;\r\n var ctx = null;\r\n \r\n if (__ctx__ && __ctx__.interaction) {\r\n var originalInteraction = __ctx__.interaction;\r\n \r\n // Create a proxy for interaction that wraps reply/followUp/deferReply\r\n // Also properly forwards Object.keys/values/entries operations\r\n // Uses Reflect.get to properly handle getters with correct 'this' binding\r\n interaction = new Proxy(originalInteraction, {\r\n get: function(target, prop, receiver) {\r\n // Use Reflect.get to properly handle getters (like 'roles', 'users', etc.)\r\n // This ensures 'this' context is correct for Discord.js Collection getters\r\n var value = Reflect.get(target, prop, target);\r\n \r\n // Wrap methods that \"consume\" the interaction (reply, followUp, defer)\r\n if (prop === 'reply' || prop === 'followUp' || prop === 'deferReply' || prop === 'deferUpdate') {\r\n return function() {\r\n // Mark that async interaction was called - this prevents sync flush at handler end\r\n __asyncInteractionCalled__ = true;\r\n \r\n // Mark as deferred for deferUpdate/deferReply\r\n if (prop === 'deferUpdate' || prop === 'deferReply') {\r\n __interactionDeferred__ = true;\r\n }\r\n \r\n var result = value.apply(target, arguments);\r\n // After the reply completes, flush any pending renders using throttled render\r\n if (result && typeof result.then === 'function') {\r\n result.then(function() {\r\n if (__hasDataChanges__ && __autoRenderEnabled__) {\r\n __hasDataChanges__ = false;\r\n // Use throttled render which handles rate limits\r\n __throttledRender__(false);\r\n }\r\n }).catch(function(err) {\r\n console.error(\"[DBI-Svelte] Render after \" + prop + \" failed:\", err);\r\n });\r\n }\r\n return result;\r\n };\r\n }\r\n \r\n // Wrap update method - this one renders directly, no need to flush after\r\n if (prop === 'update') {\r\n return function() {\r\n __autoRenderEnabled__ = false; // Disable auto since we're doing manual update\r\n __asyncInteractionCalled__ = true;\r\n return value.apply(target, arguments);\r\n };\r\n }\r\n \r\n // Bind functions to original target\r\n if (typeof value === 'function') {\r\n return value.bind(target);\r\n }\r\n \r\n return value;\r\n },\r\n // Forward Object.keys/values/entries operations\r\n ownKeys: function(target) {\r\n return Reflect.ownKeys(target);\r\n },\r\n getOwnPropertyDescriptor: function(target, prop) {\r\n return Reflect.getOwnPropertyDescriptor(target, prop);\r\n },\r\n has: function(target, prop) {\r\n return Reflect.has(target, prop);\r\n }\r\n });\r\n \r\n // Create wrapped ctx with the proxied interaction\r\n // Also properly forwards Object.keys/values/entries operations\r\n ctx = new Proxy(__ctx__, {\r\n get: function(target, prop, receiver) {\r\n if (prop === 'interaction') {\r\n return interaction;\r\n }\r\n // Use Reflect.get for proper getter handling\r\n return Reflect.get(target, prop, target);\r\n },\r\n // Forward Object.keys/values/entries operations\r\n ownKeys: function(target) {\r\n return Reflect.ownKeys(target);\r\n },\r\n getOwnPropertyDescriptor: function(target, prop) {\r\n return Reflect.getOwnPropertyDescriptor(target, prop);\r\n },\r\n has: function(target, prop) {\r\n return Reflect.has(target, prop);\r\n }\r\n });\r\n }\r\n \r\n // Helper: Force update message using interaction.update (for button clicks without reply)\r\n // Helper: Force update message using interaction.update (for button clicks without reply)\r\n async function update() {\r\n if (!__ctx__ || !__ctx__.interaction) {\r\n return Promise.resolve();\r\n }\r\n __autoRenderEnabled__ = false; // Disable auto-render since manual update called\r\n var components = await __component__.toJSON({ data: __data__ });\r\n return __safeEdit__(function() {\r\n return __ctx__.interaction.update({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n });\r\n }\r\n \r\n // Helper: Force re-render message using message.edit (after reply/followUp)\r\n async function rerender() {\r\n if (!__ctx__ || !__ctx__.interaction || !__ctx__.interaction.message) {\r\n return Promise.resolve();\r\n }\r\n __autoRenderEnabled__ = false; // Disable auto-render since manual rerender called\r\n var components = await __component__.toJSON({ data: __data__ });\r\n return __safeEdit__(function() {\r\n return __ctx__.interaction.message.edit({\r\n components: components,\r\n flags: [\"IsComponentsV2\"],\r\n });\r\n });\r\n }\r\n \r\n // Helper: Disable auto-render (for handlers that don't need UI update)\r\n function noRender() {\r\n __autoRenderEnabled__ = false;\r\n }\r\n \r\n // Helper: Set throttle interval (minimum ms between renders)\r\n function setThrottle(ms) {\r\n __throttleMinInterval__ = ms;\r\n }\r\n \r\n // Helper: Destroy this component instance (clears intervals, timers, removes ref)\r\n // Call this when you want to clean up the component manually\r\n function destroy() {\r\n // Run all destroy callbacks (clears intervals, timers, etc.)\r\n __runDestroy__();\r\n \r\n // Clear the ref from DBI store if available\r\n if (__data__ && __data__.$ref && __component__ && __component__.dbi) {\r\n __component__.dbi.data.refs.delete(__data__.$ref);\r\n }\r\n \r\n // Disable further auto-renders\r\n __autoRenderEnabled__ = false;\r\n }\r\n \r\n // Check if there are pending data changes that need SYNC render\r\n // Returns false if async interaction was called (reply/followUp will handle render)\r\n function __hasPendingRender__() {\r\n return __hasDataChanges__ && __autoRenderEnabled__ && !__asyncInteractionCalled__;\r\n }\r\n \r\n // Synchronous flush for when handler completes without async interaction\r\n // Only called when no reply/followUp was made - uses throttled render\r\n function __syncFlushRender__() {\r\n if (__hasDataChanges__ && __autoRenderEnabled__ && !__asyncInteractionCalled__) {\r\n __hasDataChanges__ = false;\r\n return __throttledRender__(true); // immediate=true for sync flush\r\n }\r\n return Promise.resolve();\r\n }\r\n \r\n // Run all mount callbacks, if callback returns a function add it to destroy callbacks\r\n function __runMount__() {\r\n if (__isMounted__) return;\r\n __isMounted__ = true;\r\n for (var i = 0; i < __mountCallbacks__.length; i++) {\r\n try {\r\n var result = __mountCallbacks__[i]();\r\n // If mount callback returns a function, add it to destroy callbacks\r\n if (typeof result === 'function') {\r\n __destroyCallbacks__.push(result);\r\n }\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] onMount callback failed:\", err);\r\n throw err;\r\n }\r\n }\r\n }\r\n \r\n // Run all destroy callbacks\r\n function __runDestroy__() {\r\n for (var i = 0; i < __destroyCallbacks__.length; i++) {\r\n try {\r\n __destroyCallbacks__[i]();\r\n } catch (err) {\r\n console.error(\"[DBI-Svelte] onDestroy callback failed:\", err);\r\n throw err;\r\n }\r\n }\r\n // Clear pending timeouts\r\n if (__pendingRenderTimeout__) {\r\n clearTimeout(__pendingRenderTimeout__);\r\n __pendingRenderTimeout__ = null;\r\n }\r\n }\r\n \r\n // Set handler execution flag\r\n function __setInHandler__(value) {\r\n __inHandlerExecution__ = value;\r\n }\r\n \r\n ${processedScript}\r\n \r\n // Inline handlers from template (extracted arrow functions/function expressions)\r\n ${Array.from(inlineHandlers || new Map()).map(([name, code]) => {\r\n // Wrap the inline code as a named function\r\n // If it's an arrow function, convert to regular function for proper 'this' binding\r\n if (code.trim().startsWith('async')) {\r\n // async arrow function or async function\r\n if (code.includes('=>')) {\r\n // async arrow function: async (ctx) => { ... } or async () => { ... }\r\n return `var ${name} = ${code};`;\r\n } else {\r\n // async function expression: async function(ctx) { ... }\r\n return `var ${name} = ${code};`;\r\n }\r\n } else if (code.includes('=>')) {\r\n // Regular arrow function: (ctx) => { ... } or () => { ... }\r\n return `var ${name} = ${code};`;\r\n } else {\r\n // Regular function expression: function(ctx) { ... }\r\n return `var ${name} = ${code};`;\r\n }\r\n }).join('\\n')}\r\n \r\n return { \r\n handlers: { ${[...functionNames, ...Array.from(inlineHandlers || new Map()).map(([name]) => name)].filter(Boolean).join(\", \")} },\r\n effects: __effects__,\r\n hasPendingRender: __hasPendingRender__,\r\n flushRender: __syncFlushRender__,\r\n wrappedCtx: ctx,\r\n mountCallbacks: __mountCallbacks__,\r\n destroyCallbacks: __destroyCallbacks__,\r\n preRenderCallbacks: __preRenderCallbacks__,\r\n afterRenderCallbacks: __afterRenderCallbacks__,\r\n runMount: __runMount__,\r\n runDestroy: __runDestroy__,\r\n runPreRender: __runPreRender__,\r\n runAfterRender: __runAfterRender__,\r\n setInHandler: __setInHandler__,\r\n render: render\r\n };\r\n };\r\n `;\r\n\r\n // Create the factory function\r\n const factoryFunc = new Function('console', wrappedScript);\r\n const createHandlers = factoryFunc(console);\r\n\r\n // Execute with the actual data, component, ctx, and imported modules to get handlers with proper closure\r\n let result;\r\n try {\r\n result = createHandlers(initialData, component, ctx, modules);\r\n } catch (execError) {\r\n throw execError;\r\n }\r\n\r\n Object.assign(handlers, result.handlers || {});\r\n effects.push(...(result.effects || []));\r\n\r\n // Return full result including render helpers\r\n // Function to run all effects\r\n const runEffects = () => {\r\n for (const effect of effects) {\r\n try {\r\n effect();\r\n } catch (error) {\r\n // Effect failed\r\n }\r\n }\r\n };\r\n\r\n return {\r\n handlers,\r\n effects,\r\n runEffects,\r\n hasPendingRender: result.hasPendingRender || (() => false),\r\n flushRender: result.flushRender || (() => Promise.resolve()),\r\n wrappedCtx: result.wrappedCtx || ctx,\r\n mountCallbacks: result.mountCallbacks || [],\r\n destroyCallbacks: result.destroyCallbacks || [],\r\n preRenderCallbacks: result.preRenderCallbacks || [],\r\n afterRenderCallbacks: result.afterRenderCallbacks || [],\r\n runMount: result.runMount || (() => { }),\r\n runDestroy: result.runDestroy || (() => { }),\r\n runPreRender: result.runPreRender || (async () => { }),\r\n runAfterRender: result.runAfterRender || (() => { }),\r\n setInHandler: result.setInHandler || (() => { }),\r\n render: result.render || (() => Promise.resolve())\r\n };\r\n } catch (error) {\r\n // Re-throw the error so it's visible to the developer\r\n console.error(\"[DBI-Svelte] createHandlerContext failed:\", error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Extract $effect callback bodies from script content\r\n */\r\nfunction extractEffectBodies(script: string): string[] {\r\n const bodies: string[] = [];\r\n // Match $effect(() => { ... }) or $effect(function() { ... })\r\n const effectRegex = /\\$effect\\s*\\(\\s*(?:(?:function\\s*\\([^)]*\\)|\\([^)]*\\)\\s*=>|\\(\\)\\s*=>)\\s*\\{([\\s\\S]*?)\\})\\s*\\)/g;\r\n let match;\r\n while ((match = effectRegex.exec(script)) !== null) {\r\n bodies.push(match[1]);\r\n }\r\n return bodies;\r\n}\r\n\r\n/**\r\n * Extract function names from script content (excluding effect callbacks)\r\n */\r\nfunction extractFunctionNames(script: string): string[] {\r\n const names: string[] = [];\r\n\r\n // Match function declarations: function name() {}\r\n const functionDeclRegex = /function\\s+(\\w+)\\s*\\(/g;\r\n let match;\r\n while ((match = functionDeclRegex.exec(script)) !== null) {\r\n names.push(match[1]);\r\n }\r\n\r\n // Match function expressions: const name = function() {}\r\n const functionExprRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*function\\s*\\(/g;\r\n while ((match = functionExprRegex.exec(script)) !== null) {\r\n names.push(match[1]);\r\n }\r\n\r\n // Match arrow functions: const name = () => {}\r\n const arrowFunctionRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>/g;\r\n while ((match = arrowFunctionRegex.exec(script)) !== null) {\r\n names.push(match[1]);\r\n }\r\n\r\n // Match arrow functions without parentheses: const name = x => {}\r\n const simpleArrowRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\w+\\s*=>/g;\r\n while ((match = simpleArrowRegex.exec(script)) !== null) {\r\n names.push(match[1]);\r\n }\r\n\r\n return [...new Set(names)]; // Remove duplicates\r\n}\r\n"]}
@@ -268,6 +268,16 @@ declare global {
268
268
  interaction: import("discord.js").ModalSubmitInteraction;
269
269
  /** Full execution context */
270
270
  ctx: any;
271
+ /**
272
+ * Re-render the original message after modal submit.
273
+ * Use this to update the UI after processing modal data.
274
+ * @example
275
+ * const { fields, interaction, rerender } = await showModal("my-modal");
276
+ * await interaction.deferUpdate();
277
+ * // ... process data ...
278
+ * await rerender(); // Updates the original message
279
+ */
280
+ rerender: () => Promise<void>;
271
281
  }
272
282
 
273
283
  /**
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "tslib": "^2.6.3"
16
16
  },
17
17
  "name": "@mostfeatured/dbi",
18
- "version": "0.2.32",
18
+ "version": "0.2.34",
19
19
  "main": "dist/src/index.js",
20
20
  "types": "dist/src/index.d.ts",
21
21
  "typesVersions": {