@mostfeatured/dbi 0.2.9 → 0.2.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/methods/hookInteractionListeners.d.ts.map +1 -1
- package/dist/src/methods/hookInteractionListeners.js +0 -2
- package/dist/src/methods/hookInteractionListeners.js.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/index.d.ts.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/index.js +3 -17
- package/dist/src/types/Components/HTMLComponentsV2/index.js.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteParser.d.ts.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteParser.js +16 -24
- package/dist/src/types/Components/HTMLComponentsV2/svelteParser.js.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteRenderer.d.ts.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteRenderer.js +109 -151
- package/dist/src/types/Components/HTMLComponentsV2/svelteRenderer.js.map +1 -1
- package/dist/test/index.js +1 -4
- package/dist/test/index.js.map +1 -1
- package/package.json +1 -1
- package/src/methods/hookInteractionListeners.ts +0 -2
- package/src/types/Components/HTMLComponentsV2/index.ts +3 -19
- package/src/types/Components/HTMLComponentsV2/svelteParser.ts +16 -25
- package/src/types/Components/HTMLComponentsV2/svelteRenderer.ts +128 -153
- package/test/index.ts +1 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"svelteRenderer.js","sourceRoot":"","sources":["../../../../../src/types/Components/HTMLComponentsV2/svelteRenderer.ts"],"names":[],"mappings":";;AAqBA,sDA8GC;AA+LD,sEASC;;AA3UD,8CAA0C;AAG1C,qCAAiD;AACjD,iDAAuH;AACvH,uDAAiC;AAajC;;GAEG;AACI,KAAK,UAAU,qBAAqB,CACzC,GAAwB,EACxB,MAAc,EACd,OAAe,EACf,UAA+B,EAAE;IAEjC,MAAM,EAAE,IAAI,GAAG,EAAE,EAAE,GAAG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M,CAAC,CAAC;gBACV,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;QAC7D,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;QACzE,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED;;GAEG;AACI,KAAK,UAAU,6BAA6B,CACjD,GAAwB,EACxB,QAAgB,EAChB,OAAe,EACf,UAA+B,EAAE;IAEjC,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB,MAAM,MAAM,GAAG,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAClD,OAAO,MAAM,qBAAqB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { compile } from \"svelte/compiler\";\r\nimport { DBI } from \"../../../DBI\";\r\nimport { NamespaceEnums } from \"../../../../generated/namespaceData\";\r\nimport { parseHTMLComponentsV2 } from \"./parser\";\r\nimport { parseSvelteComponent, createHandlerContext, SvelteComponentInfo, HandlerContextResult } from \"./svelteParser\";\r\nimport * as stuffs from \"stuffs\";\r\n\r\nexport interface SvelteRenderOptions {\r\n data?: Record<string, any>;\r\n ttl?: number;\r\n}\r\n\r\nexport interface SvelteRenderResult {\r\n components: any[];\r\n handlers: Map<string, { handlerFn: Function, context: any }>;\r\n componentInfo: SvelteComponentInfo;\r\n}\r\n\r\n/**\r\n * Compile and render a Svelte component to Discord components\r\n */\r\nexport async function renderSvelteComponent(\r\n dbi: DBI<NamespaceEnums>,\r\n source: string,\r\n dbiName: string,\r\n options: SvelteRenderOptions = {}\r\n): Promise<SvelteRenderResult> {\r\n const { data = {}, ttl = 0 } = options;\r\n\r\n // Parse the Svelte component to extract handlers\r\n // This also injects auto-generated names into elements without name attribute\r\n const componentInfo = await parseSvelteComponent(source, data);\r\n\r\n // Use the processed source (with auto-generated names injected)\r\n const processedSource = componentInfo.processedSource;\r\n\r\n // Compile the Svelte component for SSR\r\n const compiled = compile(processedSource, {\r\n generate: \"server\",\r\n css: \"injected\",\r\n dev: false,\r\n } as any);\r\n\r\n // Create a module context for the compiled code\r\n let html = \"\";\r\n try {\r\n const moduleContext = createModuleContext(dbi, data, ttl);\r\n const componentModule = evaluateCompiledComponent(compiled.js.code, moduleContext);\r\n\r\n // Render the component with props (include data in props)\r\n const renderResult = componentModule.render({ ...data, data });\r\n html = renderResult.html || renderResult.body || \"\";\r\n\r\n // Debug: Log rendered HTML\r\n if (process.env.DEBUG_SVELTE) {\r\n console.log(\"Rendered HTML:\", html);\r\n }\r\n } catch (error) {\r\n console.error(\"Error rendering Svelte component:\", error);\r\n throw error;\r\n }\r\n\r\n console.log(\"Rendered HTML:\", html);\r\n\r\n // For Svelte mode, inject state into interactive elements as a ref\r\n // Reuse existing ref if data already has one, otherwise create new\r\n if (data && Object.keys(data).length > 0) {\r\n let stateRefId: string;\r\n\r\n // Check if data already has a $ref (from previous render)\r\n if (data.$ref && typeof data.$ref === 'string') {\r\n stateRefId = data.$ref;\r\n // Update the existing ref's value with new data\r\n const existingRef = dbi.data.refs.get(stateRefId);\r\n if (existingRef) {\r\n existingRef.value = data;\r\n existingRef.at = Date.now(); // Refresh timestamp\r\n } else {\r\n // Ref expired or was deleted, create new one with same ID\r\n dbi.data.refs.set(stateRefId, { at: Date.now(), value: data, ttl });\r\n }\r\n } else {\r\n // Create a new ref for the state\r\n stateRefId = stuffs.randomString(8);\r\n data.$ref = stateRefId; // Store ref ID in data for future updates\r\n dbi.data.refs.set(stateRefId, { at: Date.now(), value: data, ttl });\r\n }\r\n\r\n // Add state ref to all elements with name attribute (buttons, selects)\r\n html = html.replace(/<button([^>]*name=\"[^\"]*\"[^>]*)>/g, (match, attrs) => {\r\n // Check if it already has data attributes\r\n if (attrs.includes('data-1:')) return match;\r\n return `<button${attrs} data-1:ref=\"${stateRefId}\">`;\r\n });\r\n // Also handle select elements\r\n html = html.replace(/<(string-select|user-select|role-select|channel-select|mentionable-select)([^>]*name=\"[^\"]*\"[^>]*)>/g, (match, tag, attrs) => {\r\n if (attrs.includes('data-1:')) return match;\r\n return `<${tag}${attrs} data-1:ref=\"${stateRefId}\">`;\r\n });\r\n }\r\n\r\n console.log(\"HTML with state:\", html);\r\n\r\n // Parse the rendered HTML to Discord components\r\n const components = parseHTMLComponentsV2(dbi, html, dbiName, { data, ttl });\r\n\r\n console.log(\"Parsed Components:\", JSON.stringify(components, null, 2));\r\n\r\n // Create handler context (also captures $effect callbacks)\r\n const handlerContext = createHandlerContext(componentInfo.scriptContent, data);\r\n const handlers = new Map<string, { handlerFn: Function, context: any }>();\r\n\r\n // Run effects on initial render\r\n handlerContext.runEffects();\r\n\r\n // Map handlers to component names\r\n componentInfo.handlers.forEach((handlerInfo, componentName) => {\r\n const handlerFn = handlerContext.handlers[handlerInfo.handlerName];\r\n if (handlerFn && typeof handlerFn === \"function\") {\r\n handlers.set(componentName, {\r\n handlerFn,\r\n context: data\r\n });\r\n }\r\n });\r\n\r\n return {\r\n components,\r\n handlers,\r\n componentInfo\r\n };\r\n}\r\n\r\n/**\r\n * Create a module context for evaluating the compiled Svelte component\r\n */\r\nfunction createModuleContext(dbi: DBI<NamespaceEnums>, data: Record<string, any>, ttl: number) {\r\n return {\r\n // Store objects in refs for later retrieval in handlers\r\n // This is used internally by the parser when converting to Discord components\r\n __storeRef: (obj: any) => {\r\n let id = stuffs.randomString(8);\r\n dbi.data.refs.set(id, { at: Date.now(), value: obj, ttl });\r\n return id;\r\n },\r\n\r\n // DBI instance for advanced usage\r\n __dbi: dbi,\r\n\r\n // All data context available\r\n ...data,\r\n data, // Also expose as 'data' prop\r\n };\r\n}\r\n\r\n/**\r\n * Evaluate the compiled Svelte component code\r\n */\r\nfunction evaluateCompiledComponent(code: string, context: Record<string, any>): any {\r\n try {\r\n // Aggressively strip ALL import statements\r\n // Svelte 5 generates imports with special chars like $ that need careful handling\r\n let processedCode = code;\r\n\r\n // Remove all lines that start with 'import' (most reliable approach)\r\n processedCode = processedCode\r\n .split('\\n')\r\n .filter(line => !line.trim().startsWith('import '))\r\n .join('\\n');\r\n\r\n // Also remove 'export default' and replace with assignment\r\n processedCode = processedCode.replace(/export\\s+default\\s+/g, 'module.exports = ');\r\n\r\n // Create exports object\r\n const exports: any = {};\r\n const module = { exports };\r\n\r\n // Provide Svelte 5 server runtime functions\r\n // The compiled code references these via the $ namespace\r\n const $: any = {\r\n // Escape functions\r\n escape: (str: any) => String(str)\r\n .replace(/&/g, \"&\")\r\n .replace(/</g, \"<\")\r\n .replace(/>/g, \">\")\r\n .replace(/\"/g, \""\")\r\n .replace(/'/g, \"'\"),\r\n escape_text: (str: any) => String(str)\r\n .replace(/&/g, \"&\")\r\n .replace(/</g, \"<\")\r\n .replace(/>/g, \">\"),\r\n escape_attribute_value: (str: any) => String(str)\r\n .replace(/\"/g, \""\")\r\n .replace(/'/g, \"'\"),\r\n // Array helpers for {#each}\r\n ensure_array_like: (value: any) => {\r\n if (Array.isArray(value)) return value;\r\n if (value == null) return [];\r\n if (typeof value === 'object' && Symbol.iterator in value) {\r\n return Array.from(value);\r\n }\r\n return [value];\r\n },\r\n // Renderer methods\r\n component: (fn: Function) => fn,\r\n push: (content: string) => content,\r\n pop: () => { },\r\n attr: (name: string, value: any, is_boolean?: boolean) => {\r\n if (is_boolean && !value) return '';\r\n if (value == null) return '';\r\n return ` ${name}=\"${String(value)}\"`;\r\n },\r\n spread_attributes: (attrs: Record<string, any>) => {\r\n return Object.entries(attrs)\r\n .map(([key, value]) => ` ${key}=\"${String(value)}\"`)\r\n .join('');\r\n },\r\n spread_props: (props: Record<string, any>) => props,\r\n bind_props: (props: Record<string, any>, names: string[]) => {\r\n const result: any = {};\r\n names.forEach(name => {\r\n if (name in props) result[name] = props[name];\r\n });\r\n return result;\r\n },\r\n stringify: (value: any) => JSON.stringify(value),\r\n store_get: (store: any) => store,\r\n unsubscribe_stores: () => { },\r\n // Control flow\r\n each: (items: any[], fn: Function) => {\r\n return items.map((item, index) => fn(item, index)).join('');\r\n },\r\n // Lifecycle\r\n tick: () => Promise.resolve(),\r\n flush: () => { },\r\n // Validation\r\n validate_component: (component: any) => component,\r\n validate_store: (store: any) => store,\r\n // Misc\r\n noop: () => { },\r\n run: (fn: Function) => fn(),\r\n run_all: (fns: Function[]) => fns.forEach(f => f()),\r\n is_promise: (value: any) => value && typeof value.then === 'function',\r\n missing_component: { $$render: () => '' },\r\n };\r\n\r\n // Create renderer object that accumulates HTML\r\n let html = '';\r\n const $$renderer: any = {\r\n out: '',\r\n head: '',\r\n component: (fn: Function) => {\r\n return fn($$renderer);\r\n },\r\n push: (content: string) => {\r\n html += content;\r\n return $$renderer;\r\n },\r\n pop: () => $$renderer,\r\n element: (tag: string, fn: Function) => {\r\n html += `<${tag}`;\r\n fn();\r\n html += `>`;\r\n return $$renderer;\r\n },\r\n close: (tag: string) => {\r\n html += `</${tag}>`;\r\n return $$renderer;\r\n },\r\n };\r\n\r\n // Create a function wrapper with all context and Svelte runtime\r\n // Include lifecycle stubs - these are no-ops in SSR but need to be defined\r\n const allContext = {\r\n ...context,\r\n $,\r\n $$renderer,\r\n module,\r\n exports,\r\n // Lifecycle stubs for SSR (actual lifecycle runs in handler context)\r\n onMount: (fn: Function) => { /* SSR no-op, real onMount runs in handler context */ },\r\n onDestroy: (fn: Function) => { /* SSR no-op, real onDestroy runs in handler context */ },\r\n };\r\n\r\n const contextKeys = Object.keys(allContext);\r\n const contextValues = Object.values(allContext);\r\n\r\n // Wrap in IIFE\r\n const wrappedCode = `\r\n (function(${contextKeys.join(\", \")}) {\r\n ${processedCode}\r\n return module.exports;\r\n })\r\n `;\r\n\r\n // Evaluate the code\r\n const func = eval(wrappedCode);\r\n const component = func(...contextValues);\r\n\r\n // Return a render function\r\n return {\r\n render: (props: any) => {\r\n html = '';\r\n try {\r\n component($$renderer, props);\r\n return { html, head: '', css: { code: '', map: null } };\r\n } catch (e) {\r\n console.error('Component render error:', e);\r\n throw e;\r\n }\r\n }\r\n };\r\n } catch (error) {\r\n console.error(\"Error evaluating compiled component:\", error);\r\n console.error(\"Code preview (first 500 chars):\", code.substring(0, 500));\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Render a Svelte component from a file\r\n */\r\nexport async function renderSvelteComponentFromFile(\r\n dbi: DBI<NamespaceEnums>,\r\n filePath: string,\r\n dbiName: string,\r\n options: SvelteRenderOptions = {}\r\n): Promise<SvelteRenderResult> {\r\n const fs = require(\"fs\");\r\n const source = fs.readFileSync(filePath, \"utf-8\");\r\n return await renderSvelteComponent(dbi, source, dbiName, options);\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"svelteRenderer.js","sourceRoot":"","sources":["../../../../../src/types/Components/HTMLComponentsV2/svelteRenderer.ts"],"names":[],"mappings":";;AAsBA,sDAoGC;AA+KD,sEASC;;AAlTD,8CAA0C;AAG1C,qCAAiD;AACjD,iDAAuH;AACvH,uDAAiC;AACjC,+CAAyB;AAazB;;GAEG;AACI,KAAK,UAAU,qBAAqB,CACzC,GAAwB,EACxB,MAAc,EACd,OAAe,EACf,UAA+B,EAAE;IAEjC,MAAM,EAAE,IAAI,GAAG,EAAE,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,OAAO,CAAC;IAEvC,iDAAiD;IACjD,8EAA8E;IAC9E,MAAM,aAAa,GAAG,MAAM,IAAA,mCAAoB,EAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAE/D,gEAAgE;IAChE,MAAM,eAAe,GAAG,aAAa,CAAC,eAAe,CAAC;IAEtD,kDAAkD;IAClD,MAAM,QAAQ,GAAG,IAAA,kBAAO,EAAC,eAAe,EAAE;QACxC,QAAQ,EAAE,QAAQ;QAClB,GAAG,EAAE,UAAU;QACf,GAAG,EAAE,KAAK;KACJ,CAA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\"../../../DBI\";\r\nimport { NamespaceEnums } from \"../../../../generated/namespaceData\";\r\nimport { parseHTMLComponentsV2 } from \"./parser\";\r\nimport { parseSvelteComponent, createHandlerContext, SvelteComponentInfo, HandlerContextResult } from \"./svelteParser\";\r\nimport * as stuffs from \"stuffs\";\r\nimport * as vm from \"vm\";\r\n\r\nexport interface SvelteRenderOptions {\r\n data?: Record<string, any>;\r\n ttl?: number;\r\n}\r\n\r\nexport interface SvelteRenderResult {\r\n components: any[];\r\n handlers: Map<string, { handlerFn: Function, context: any }>;\r\n componentInfo: SvelteComponentInfo;\r\n}\r\n\r\n/**\r\n * Compile and render a Svelte component to Discord components\r\n */\r\nexport async function renderSvelteComponent(\r\n dbi: DBI<NamespaceEnums>,\r\n source: string,\r\n dbiName: string,\r\n options: SvelteRenderOptions = {}\r\n): Promise<SvelteRenderResult> {\r\n const { data = {}, ttl = 0 } = options;\r\n\r\n // Parse the Svelte component to extract handlers\r\n // This also injects auto-generated names into elements without name attribute\r\n const componentInfo = await parseSvelteComponent(source, data);\r\n\r\n // Use the processed source (with auto-generated names injected)\r\n const processedSource = componentInfo.processedSource;\r\n\r\n // Compile the Svelte component for SSR (Svelte 5)\r\n const compiled = compile(processedSource, {\r\n generate: \"server\",\r\n css: \"injected\",\r\n dev: false,\r\n } as any);\r\n\r\n // Create a module context for the compiled code\r\n let html = \"\";\r\n try {\r\n const moduleContext = createModuleContext(dbi, data, ttl);\r\n const Component = evaluateCompiledComponent(compiled.js.code, moduleContext);\r\n\r\n // Svelte 5 SSR: Use render from svelte/server\r\n const { render } = require(\"svelte/server\");\r\n // Pass data properties as top-level props (Svelte 5 expects flat props object)\r\n const renderResult = render(Component, { props: data });\r\n html = renderResult.body || \"\";\r\n } catch (error) {\r\n throw error;\r\n }\r\n\r\n // For Svelte mode, inject state into interactive elements as a ref\r\n // Reuse existing ref if data already has one, otherwise create new\r\n if (data && Object.keys(data).length > 0) {\r\n let stateRefId: string;\r\n\r\n // Check if data already has a $ref (from previous render)\r\n if (data.$ref && typeof data.$ref === 'string') {\r\n stateRefId = data.$ref;\r\n // Update the existing ref's value with new data\r\n const existingRef = dbi.data.refs.get(stateRefId);\r\n if (existingRef) {\r\n existingRef.value = data;\r\n existingRef.at = Date.now(); // Refresh timestamp\r\n } else {\r\n // Ref expired or was deleted, create new one with same ID\r\n dbi.data.refs.set(stateRefId, { at: Date.now(), value: data, ttl });\r\n }\r\n } else {\r\n // Create a new ref for the state\r\n stateRefId = stuffs.randomString(8);\r\n data.$ref = stateRefId; // Store ref ID in data for future updates\r\n dbi.data.refs.set(stateRefId, { at: Date.now(), value: data, ttl });\r\n }\r\n\r\n // Add state ref to all elements with name attribute (buttons, selects)\r\n html = html.replace(/<button([^>]*name=\"[^\"]*\"[^>]*)>/g, (match, attrs) => {\r\n // Check if it already has data attributes\r\n if (attrs.includes('data-1:')) return match;\r\n return `<button${attrs} data-1:ref=\"${stateRefId}\">`;\r\n });\r\n // Also handle select elements\r\n html = html.replace(/<(string-select|user-select|role-select|channel-select|mentionable-select)([^>]*name=\"[^\"]*\"[^>]*)>/g, (match, tag, attrs) => {\r\n if (attrs.includes('data-1:')) return match;\r\n return `<${tag}${attrs} data-1:ref=\"${stateRefId}\">`;\r\n });\r\n }\r\n\r\n // Parse the rendered HTML to Discord components\r\n const components = parseHTMLComponentsV2(dbi, html, dbiName, { data, ttl });\r\n\r\n // Create handler context (also captures $effect callbacks)\r\n const handlerContext = createHandlerContext(componentInfo.scriptContent, data);\r\n const handlers = new Map<string, { handlerFn: Function, context: any }>();\r\n\r\n // Run effects on initial render\r\n handlerContext.runEffects();\r\n\r\n // Map handlers to component names\r\n componentInfo.handlers.forEach((handlerInfo, componentName) => {\r\n const handlerFn = handlerContext.handlers[handlerInfo.handlerName];\r\n if (handlerFn && typeof handlerFn === \"function\") {\r\n handlers.set(componentName, {\r\n handlerFn,\r\n context: data\r\n });\r\n }\r\n });\r\n\r\n return {\r\n components,\r\n handlers,\r\n componentInfo\r\n };\r\n}\r\n\r\n/**\r\n * Create a module context for evaluating the compiled Svelte component\r\n */\r\nfunction createModuleContext(dbi: DBI<NamespaceEnums>, data: Record<string, any>, ttl: number) {\r\n return {\r\n // Store objects in refs for later retrieval in handlers\r\n // This is used internally by the parser when converting to Discord components\r\n __storeRef: (obj: any) => {\r\n let id = stuffs.randomString(8);\r\n dbi.data.refs.set(id, { at: Date.now(), value: obj, ttl });\r\n return id;\r\n },\r\n\r\n // DBI instance for advanced usage\r\n __dbi: dbi,\r\n\r\n // All data context available\r\n ...data,\r\n data, // Also expose as 'data' prop\r\n };\r\n}\r\n\r\n/**\r\n * Evaluate the compiled Svelte component code\r\n */\r\nfunction evaluateCompiledComponent(code: string, context: Record<string, any>): any {\r\n try {\r\n // Load Svelte 5 internal runtime\r\n const svelteInternal = require(\"svelte/internal/server\");\r\n\r\n // Process the code to work in our context\r\n let processedCode = code;\r\n\r\n // Collect external modules to inject into sandbox\r\n const externalModules: Record<string, any> = {};\r\n\r\n // Replace svelte internal imports\r\n processedCode = processedCode.replace(\r\n /import\\s*\\*\\s*as\\s*(\\w+)\\s*from\\s*[\"']svelte\\/internal\\/server[\"'];?/g,\r\n 'const $1 = __svelteInternal;'\r\n );\r\n processedCode = processedCode.replace(\r\n /import\\s*\\{([^}]+)\\}\\s*from\\s*[\"']svelte\\/internal\\/server[\"'];?/g,\r\n (match, imports) => {\r\n const importList = imports.split(',').map((i: string) => i.trim());\r\n return `const { ${importList.join(', ')} } = __svelteInternal;`;\r\n }\r\n );\r\n\r\n // Handle external module imports (default imports)\r\n processedCode = processedCode.replace(\r\n /import\\s+(\\w+)\\s+from\\s*[\"']([^\"']+)[\"'];?/g,\r\n (match, varName, modulePath) => {\r\n // Skip svelte imports\r\n if (modulePath.startsWith('svelte')) return '';\r\n try {\r\n const mod = require(modulePath);\r\n externalModules[varName] = mod.default || mod;\r\n return `const ${varName} = __externalModules.${varName};`;\r\n } catch (e) {\r\n return '';\r\n }\r\n }\r\n );\r\n\r\n // Handle named imports from external modules\r\n processedCode = processedCode.replace(\r\n /import\\s*\\{([^}]+)\\}\\s*from\\s*[\"']([^\"']+)[\"'];?/g,\r\n (match, imports, modulePath) => {\r\n // Skip svelte imports\r\n if (modulePath.startsWith('svelte')) return '';\r\n try {\r\n const mod = require(modulePath);\r\n const importList = imports.split(',').map((i: string) => i.trim());\r\n importList.forEach((importName: string) => {\r\n const [name, alias] = importName.split(' as ').map(s => s.trim());\r\n externalModules[alias || name] = mod[name] || mod.default?.[name];\r\n });\r\n return importList.map((importName: string) => {\r\n const [name, alias] = importName.split(' as ').map(s => s.trim());\r\n return `const ${alias || name} = __externalModules.${alias || name};`;\r\n }).join('\\n');\r\n } catch (e) {\r\n return '';\r\n }\r\n }\r\n );\r\n\r\n // Handle namespace imports from external modules\r\n processedCode = processedCode.replace(\r\n /import\\s*\\*\\s*as\\s*(\\w+)\\s*from\\s*[\"']([^\"']+)[\"'];?/g,\r\n (match, varName, modulePath) => {\r\n // Skip svelte imports\r\n if (modulePath.startsWith('svelte')) return '';\r\n try {\r\n const mod = require(modulePath);\r\n externalModules[varName] = mod;\r\n return `const ${varName} = __externalModules.${varName};`;\r\n } catch (e) {\r\n return '';\r\n }\r\n }\r\n );\r\n\r\n // Remove any remaining import statements\r\n processedCode = processedCode\r\n .split('\\n')\r\n .filter(line => !line.trim().startsWith('import '))\r\n .join('\\n');\r\n\r\n // Replace 'export default' with assignment\r\n processedCode = processedCode.replace(/export\\s+default\\s+/g, '__exports.default = ');\r\n // Replace 'export function' with assignment\r\n processedCode = processedCode.replace(/export\\s+function\\s+(\\w+)/g, '__exports.$1 = function $1');\r\n // Replace 'export const' with assignment\r\n processedCode = processedCode.replace(/export\\s+const\\s+(\\w+)/g, '__exports.$1 = ');\r\n // Replace 'export let' with assignment \r\n processedCode = processedCode.replace(/export\\s+let\\s+(\\w+)/g, '__exports.$1 = ');\r\n\r\n // Create the sandbox context\r\n const __exports: any = {};\r\n // Svelte lifecycle functions - no-ops for SSR\r\n const svelteLifecycle = {\r\n onMount: () => () => { }, // Returns cleanup function\r\n onDestroy: () => { },\r\n beforeUpdate: () => { },\r\n afterUpdate: () => { },\r\n tick: () => Promise.resolve(),\r\n untrack: (fn: () => any) => fn(),\r\n createEventDispatcher: () => () => { },\r\n };\r\n\r\n // Note: Svelte 5 runes ($state, $derived, etc.) are compile-time features\r\n // The compiler transforms them, so we don't need runtime implementations.\r\n // The `$` variable is used by compiled code as the svelte/internal/server namespace.\r\n\r\n const sandbox = {\r\n __svelteInternal: svelteInternal,\r\n __externalModules: externalModules,\r\n $: svelteInternal, // Direct alias for compiled Svelte code that uses `$`\r\n __exports,\r\n console,\r\n ...svelteLifecycle,\r\n ...context,\r\n };\r\n\r\n // Wrap code in IIFE\r\n const wrappedCode = `\r\n (function() {\r\n ${processedCode}\r\n })();\r\n `;\r\n\r\n // Run in VM context for better isolation\r\n vm.createContext(sandbox);\r\n vm.runInContext(wrappedCode, sandbox);\r\n\r\n // Return the component\r\n const Component = sandbox.__exports.default;\r\n\r\n if (!Component) {\r\n throw new Error(\"Svelte component did not export a default component\");\r\n }\r\n\r\n return Component;\r\n } catch (error) {\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Render a Svelte component from a file\r\n */\r\nexport async function renderSvelteComponentFromFile(\r\n dbi: DBI<NamespaceEnums>,\r\n filePath: string,\r\n dbiName: string,\r\n options: SvelteRenderOptions = {}\r\n): Promise<SvelteRenderResult> {\r\n const fs = require(\"fs\");\r\n const source = fs.readFileSync(filePath, \"utf-8\");\r\n return await renderSvelteComponent(dbi, source, dbiName, options);\r\n}\r\n"]}
|
package/dist/test/index.js
CHANGED
|
@@ -27,10 +27,7 @@ dbi.register(({ ChatInput, HTMLComponentsV2 }) => {
|
|
|
27
27
|
HTMLComponentsV2({
|
|
28
28
|
name: "product-showcase",
|
|
29
29
|
mode: 'svelte',
|
|
30
|
-
file: path_1.default.join(__dirname, "product-showcase.svelte")
|
|
31
|
-
onExecute(ctx) {
|
|
32
|
-
console.log("Product showcase interaction:", ctx.data[0]);
|
|
33
|
-
}
|
|
30
|
+
file: path_1.default.join(__dirname, "product-showcase.svelte")
|
|
34
31
|
});
|
|
35
32
|
// Test command
|
|
36
33
|
ChatInput({
|
package/dist/test/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../test/index.ts"],"names":[],"mappings":";;;AAAA,gCAAmC;AACnC,wDAAwB;AAExB,MAAM,GAAG,GAAG,IAAA,eAAS,EAAC,QAAQ,EAAE;IAC9B,OAAO,EAAE;QACP,KAAK,EAAE,qBAAqB;QAC5B,OAAO,EAAE;YACP,OAAO,EAAE;gBACP,eAAe;gBACf,QAAQ;gBACR,gBAAgB;gBAChB,uBAAuB;aACxB;SACF;KACF;IACD,UAAU,EAAE;QACV,SAAS,EAAE;YACT,GAAG,EAAE,KAAK,GAAG,EAAE,EAAE,aAAa;YAC9B,KAAK,EAAE,KAAK,CAAC,mBAAmB;SACjC;KACF;CACF,CAAC,CAAC;AAEH,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,EAAE,gBAAgB,EAAE,EAAE,EAAE;IAC/C,6CAA6C;IAC7C,gBAAgB,CAAC;QACf,IAAI,EAAE,kBAAkB;QACxB,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../test/index.ts"],"names":[],"mappings":";;;AAAA,gCAAmC;AACnC,wDAAwB;AAExB,MAAM,GAAG,GAAG,IAAA,eAAS,EAAC,QAAQ,EAAE;IAC9B,OAAO,EAAE;QACP,KAAK,EAAE,qBAAqB;QAC5B,OAAO,EAAE;YACP,OAAO,EAAE;gBACP,eAAe;gBACf,QAAQ;gBACR,gBAAgB;gBAChB,uBAAuB;aACxB;SACF;KACF;IACD,UAAU,EAAE;QACV,SAAS,EAAE;YACT,GAAG,EAAE,KA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D,KAAK,EAAE,EAAE;oBACT,KAAK,EAAE,gDAAgD;oBACvD,QAAQ,EAAE,WAAW;oBACrB,MAAM,EAAE,GAAG;oBACX,KAAK,EAAE,EAAE;iBACV;aACF,CAAC;YAEF,uFAAuF;YACvF,2EAA2E;YAC3E,MAAM,QAAQ,CAAC,IAAI,CAAC,WAAW,EAAE;gBAC/B,IAAI,EAAE;oBACJ,QAAQ;oBACR,YAAY,EAAE,CAAC;oBACf,IAAI,EAAE,EAAE;oBACR,IAAI,EAAE,QAAQ;oBACd,WAAW,EAAE,CAAC;iBACf;aACF,CAAC,CAAC;QACL,CAAC;KACF,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,UAAU,CAAC,GAAG,EAAE;IACd,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC9B,GAAG,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;QACnB,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAA;QAC3C,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAC3B,GAAG,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;YACpB,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;QACxD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,EAAE,GAAG,CAAC,CAAC","sourcesContent":["import { createDBI } from \"../src\";\r\nimport path from \"path\";\r\n\r\nconst dbi = createDBI(\"svelte\", {\r\n discord: {\r\n token: \"YOUR_BOT_TOKEN_HERE\",\r\n options: {\r\n intents: [\r\n \"GuildMessages\",\r\n \"Guilds\",\r\n \"MessageContent\",\r\n \"GuildMessageReactions\"\r\n ],\r\n }\r\n },\r\n references: {\r\n autoClear: {\r\n ttl: 60000 * 60, // 60 minutes\r\n check: 60000 // every 60 seconds\r\n }\r\n }\r\n});\r\n\r\ndbi.register(({ ChatInput, HTMLComponentsV2 }) => {\r\n // Svelte product showcase with Components V2\r\n HTMLComponentsV2({\r\n name: \"product-showcase\",\r\n mode: 'svelte',\r\n file: path.join(__dirname, \"product-showcase.svelte\")\r\n });\r\n\r\n // Test command\r\n ChatInput({\r\n name: \"test-svelte\",\r\n description: \"Test Svelte product showcase\",\r\n async onExecute({ interaction, dbi }) {\r\n const showcase = dbi.interaction(\"product-showcase\") as any;\r\n\r\n const products = [\r\n {\r\n name: \"Gaming Keyboard\",\r\n description: \"RGB mechanical keyboard with Cherry MX switches\",\r\n price: 149,\r\n image: \"https://cdn.discordapp.com/embed/avatars/0.png\",\r\n category: \"Electronics\",\r\n rating: 4.8,\r\n stock: 25\r\n },\r\n {\r\n name: \"Wireless Mouse\",\r\n description: \"Ergonomic wireless mouse with 16000 DPI sensor\",\r\n price: 79,\r\n image: \"https://cdn.discordapp.com/embed/avatars/1.png\",\r\n category: \"Electronics\",\r\n rating: 4.5,\r\n stock: 42\r\n },\r\n {\r\n name: \"USB-C Hub\",\r\n description: \"7-in-1 USB-C hub with HDMI, USB 3.0, and SD card reader\",\r\n price: 59,\r\n image: \"https://cdn.discordapp.com/embed/avatars/2.png\",\r\n category: \"Accessories\",\r\n rating: 4.3,\r\n stock: 18\r\n },\r\n {\r\n name: \"Monitor Stand\",\r\n description: \"Adjustable monitor stand with cable management\",\r\n price: 89,\r\n image: \"https://cdn.discordapp.com/embed/avatars/3.png\",\r\n category: \"Furniture\",\r\n rating: 4.6,\r\n stock: 31\r\n }\r\n ];\r\n\r\n // Use send() method - this sends the message AND initializes lifecycle hooks (onMount)\r\n // The interval in onMount will start immediately after the message is sent\r\n await showcase.send(interaction, {\r\n data: {\r\n products,\r\n currentIndex: 0,\r\n cart: [],\r\n view: 'browse',\r\n elapsedTime: 0\r\n }\r\n });\r\n }\r\n });\r\n});\r\n\r\nsetTimeout(() => {\r\n console.log(\"Loading DBI...\");\r\n dbi.load().then(() => {\r\n dbi.publish(\"Guild\", \"1341841733511806978\")\r\n console.log(\"DBI loaded.\");\r\n dbi.login().then(() => {\r\n console.log(\"Bot is running with Svelte components!\");\r\n });\r\n });\r\n}, 100);"]}
|
package/package.json
CHANGED
|
@@ -235,8 +235,6 @@ export function hookInteractionListeners(dbi: DBI<NamespaceEnums>): () => any {
|
|
|
235
235
|
if (dbiInter.type === "HTMLComponentsV2") {
|
|
236
236
|
// For HTMLComponentsV2, first element of data is the element name (button name, etc.)
|
|
237
237
|
const elementName = data?.[0];
|
|
238
|
-
console.log("[Hook] HTMLComponentsV2 interaction found, elementName:", elementName);
|
|
239
|
-
console.log("[Hook] onExecute exists:", typeof dbiInter.onExecute);
|
|
240
238
|
|
|
241
239
|
if (dbi.config.strict) {
|
|
242
240
|
// @ts-ignore
|
|
@@ -83,17 +83,10 @@ export class DBIHTMLComponentsV2<TNamespace extends NamespaceEnums> extends DBIB
|
|
|
83
83
|
private async _initSvelteComponent() {
|
|
84
84
|
if (this.template && !this.svelteComponentInfo) {
|
|
85
85
|
this.svelteComponentInfo = await parseSvelteComponent(this.template);
|
|
86
|
-
|
|
87
|
-
// Debug log
|
|
88
|
-
console.log(`[Svelte] Component "${this.name}" registered with handlers:`,
|
|
89
|
-
Array.from(this.svelteComponentInfo.handlers.entries())
|
|
90
|
-
);
|
|
91
86
|
}
|
|
92
87
|
}
|
|
93
88
|
|
|
94
89
|
private _handleExecute(ctx: IDBIHTMLComponentsV2ExecuteCtx<TNamespace>) {
|
|
95
|
-
console.log("[Svelte] onExecute called with data:", ctx.data);
|
|
96
|
-
|
|
97
90
|
// Call user's onExecute callback first if provided
|
|
98
91
|
if (this._userOnExecute) {
|
|
99
92
|
this._userOnExecute(ctx);
|
|
@@ -102,18 +95,15 @@ export class DBIHTMLComponentsV2<TNamespace extends NamespaceEnums> extends DBIB
|
|
|
102
95
|
// If using Svelte mode, find and execute the handler
|
|
103
96
|
if (this.mode === 'svelte' && this.svelteComponentInfo) {
|
|
104
97
|
const [elementName, ...handlerData] = ctx.data;
|
|
105
|
-
console.log("[Svelte] Element name:", elementName, "Handler data:", handlerData);
|
|
106
98
|
|
|
107
99
|
if (typeof elementName === 'string') {
|
|
108
100
|
// Find the handler info for this element
|
|
109
101
|
const handlerInfo = this.svelteComponentInfo.handlers.get(elementName);
|
|
110
|
-
console.log("[Svelte] Handler info:", handlerInfo);
|
|
111
102
|
|
|
112
103
|
if (handlerInfo) {
|
|
113
104
|
// Extract current state from handlerData (refs that were passed)
|
|
114
105
|
// The second element in data array contains the current state
|
|
115
106
|
const currentState = handlerData[0] || {} as Record<string, any>;
|
|
116
|
-
console.log("[Svelte] Current state:", currentState);
|
|
117
107
|
|
|
118
108
|
// Get ref id for lifecycle tracking (if available)
|
|
119
109
|
const refId = (currentState as any)?.$ref || null;
|
|
@@ -136,7 +126,6 @@ export class DBIHTMLComponentsV2<TNamespace extends NamespaceEnums> extends DBIB
|
|
|
136
126
|
);
|
|
137
127
|
|
|
138
128
|
const handlerFn = handlerContext.handlers[handlerInfo.handlerName];
|
|
139
|
-
console.log("[Svelte] Handler function:", handlerFn ? "found" : "not found", handlerInfo.handlerName);
|
|
140
129
|
|
|
141
130
|
if (handlerFn && typeof handlerFn === 'function') {
|
|
142
131
|
try {
|
|
@@ -195,13 +184,9 @@ export class DBIHTMLComponentsV2<TNamespace extends NamespaceEnums> extends DBIB
|
|
|
195
184
|
handlerContext.flushRender();
|
|
196
185
|
}
|
|
197
186
|
} catch (error) {
|
|
198
|
-
|
|
187
|
+
// Handler execution failed
|
|
199
188
|
}
|
|
200
|
-
} else {
|
|
201
|
-
console.warn(`Handler function '${handlerInfo.handlerName}' not found for element '${elementName}'`);
|
|
202
189
|
}
|
|
203
|
-
} else {
|
|
204
|
-
console.warn(`No handler info found for element '${elementName}'`);
|
|
205
190
|
}
|
|
206
191
|
}
|
|
207
192
|
}
|
|
@@ -259,8 +244,8 @@ export class DBIHTMLComponentsV2<TNamespace extends NamespaceEnums> extends DBIB
|
|
|
259
244
|
async send(target: any, options: TDBIHTMLComponentsV2SendOptions = {}): Promise<any> {
|
|
260
245
|
const { data = {}, flags = ["IsComponentsV2"], content, ephemeral, reply, followUp } = options;
|
|
261
246
|
|
|
262
|
-
// Render components
|
|
263
|
-
const components = this.toJSON({ data });
|
|
247
|
+
// Render components (toJSON is async)
|
|
248
|
+
const components = await this.toJSON({ data });
|
|
264
249
|
|
|
265
250
|
// Build message options
|
|
266
251
|
const messageOptions: any = { components, flags };
|
|
@@ -352,7 +337,6 @@ export class DBIHTMLComponentsV2<TNamespace extends NamespaceEnums> extends DBIB
|
|
|
352
337
|
const refId = typeof refOrData === 'string' ? refOrData : refOrData?.$ref;
|
|
353
338
|
|
|
354
339
|
if (!refId) {
|
|
355
|
-
console.warn("[Svelte] Cannot destroy: no ref ID provided");
|
|
356
340
|
return false;
|
|
357
341
|
}
|
|
358
342
|
|
|
@@ -361,7 +361,7 @@ function loadModules(imports: ImportInfo[]): { modules: Record<string, any>; var
|
|
|
361
361
|
declarations.push(`var ${varName} = __modules__["${varName}"];`);
|
|
362
362
|
}
|
|
363
363
|
} catch (err) {
|
|
364
|
-
|
|
364
|
+
// Module import failed
|
|
365
365
|
}
|
|
366
366
|
}
|
|
367
367
|
|
|
@@ -484,7 +484,6 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
484
484
|
// Check for rate limit (429)
|
|
485
485
|
if (err.status === 429 || (err.message && err.message.includes('rate limit'))) {
|
|
486
486
|
var retryAfter = err.retry_after || err.retryAfter || 1;
|
|
487
|
-
console.log("[Svelte] Rate limited, waiting " + retryAfter + "s before retry");
|
|
488
487
|
__isRateLimited__ = true;
|
|
489
488
|
__rateLimitEndTime__ = Date.now() + (retryAfter * 1000);
|
|
490
489
|
|
|
@@ -494,13 +493,11 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
494
493
|
if (retryCount < maxRetries) {
|
|
495
494
|
resolve(__safeEdit__(editFn, retryCount + 1));
|
|
496
495
|
} else {
|
|
497
|
-
console.error("[Svelte] Max retries reached after rate limit");
|
|
498
496
|
resolve();
|
|
499
497
|
}
|
|
500
498
|
}, retryAfter * 1000);
|
|
501
499
|
});
|
|
502
500
|
}
|
|
503
|
-
console.error("[Svelte] Edit error:", err.message);
|
|
504
501
|
return Promise.resolve();
|
|
505
502
|
});
|
|
506
503
|
}
|
|
@@ -542,8 +539,8 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
542
539
|
}
|
|
543
540
|
|
|
544
541
|
// Actual render execution
|
|
545
|
-
function __executeRender__() {
|
|
546
|
-
var components = __component__.toJSON({ data: __data__ });
|
|
542
|
+
async function __executeRender__() {
|
|
543
|
+
var components = await __component__.toJSON({ data: __data__ });
|
|
547
544
|
|
|
548
545
|
// Try to use current interaction if available
|
|
549
546
|
if (__ctx__ && __ctx__.interaction) {
|
|
@@ -573,7 +570,7 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
573
570
|
});
|
|
574
571
|
}
|
|
575
572
|
} catch (err) {
|
|
576
|
-
|
|
573
|
+
// Silently fail
|
|
577
574
|
}
|
|
578
575
|
}
|
|
579
576
|
|
|
@@ -587,7 +584,6 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
587
584
|
});
|
|
588
585
|
}
|
|
589
586
|
|
|
590
|
-
console.error("[Svelte] Cannot render: no interaction or message context");
|
|
591
587
|
return Promise.resolve();
|
|
592
588
|
}
|
|
593
589
|
|
|
@@ -680,7 +676,7 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
680
676
|
__throttledRender__(false);
|
|
681
677
|
}
|
|
682
678
|
}).catch(function(err) {
|
|
683
|
-
|
|
679
|
+
// Silently fail
|
|
684
680
|
});
|
|
685
681
|
}
|
|
686
682
|
return result;
|
|
@@ -718,30 +714,30 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
718
714
|
|
|
719
715
|
// Helper: Force update message using interaction.update (for button clicks without reply)
|
|
720
716
|
// Helper: Force update message using interaction.update (for button clicks without reply)
|
|
721
|
-
function update() {
|
|
717
|
+
async function update() {
|
|
722
718
|
if (!__ctx__ || !__ctx__.interaction) {
|
|
723
|
-
console.error("[Svelte] Cannot update: no interaction context");
|
|
724
719
|
return Promise.resolve();
|
|
725
720
|
}
|
|
726
721
|
__autoRenderEnabled__ = false; // Disable auto-render since manual update called
|
|
722
|
+
var components = await __component__.toJSON({ data: __data__ });
|
|
727
723
|
return __safeEdit__(function() {
|
|
728
724
|
return __ctx__.interaction.update({
|
|
729
|
-
components:
|
|
725
|
+
components: components,
|
|
730
726
|
flags: ["IsComponentsV2"],
|
|
731
727
|
});
|
|
732
728
|
});
|
|
733
729
|
}
|
|
734
730
|
|
|
735
731
|
// Helper: Force re-render message using message.edit (after reply/followUp)
|
|
736
|
-
function rerender() {
|
|
732
|
+
async function rerender() {
|
|
737
733
|
if (!__ctx__ || !__ctx__.interaction || !__ctx__.interaction.message) {
|
|
738
|
-
console.error("[Svelte] Cannot rerender: no message context");
|
|
739
734
|
return Promise.resolve();
|
|
740
735
|
}
|
|
741
736
|
__autoRenderEnabled__ = false; // Disable auto-render since manual rerender called
|
|
737
|
+
var components = await __component__.toJSON({ data: __data__ });
|
|
742
738
|
return __safeEdit__(function() {
|
|
743
739
|
return __ctx__.interaction.message.edit({
|
|
744
|
-
components:
|
|
740
|
+
components: components,
|
|
745
741
|
flags: ["IsComponentsV2"],
|
|
746
742
|
});
|
|
747
743
|
});
|
|
@@ -800,7 +796,7 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
800
796
|
__destroyCallbacks__.push(result);
|
|
801
797
|
}
|
|
802
798
|
} catch (err) {
|
|
803
|
-
|
|
799
|
+
// Mount callback failed
|
|
804
800
|
}
|
|
805
801
|
}
|
|
806
802
|
}
|
|
@@ -811,7 +807,7 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
811
807
|
try {
|
|
812
808
|
__destroyCallbacks__[i]();
|
|
813
809
|
} catch (err) {
|
|
814
|
-
|
|
810
|
+
// Destroy callback failed
|
|
815
811
|
}
|
|
816
812
|
}
|
|
817
813
|
// Clear pending timeouts
|
|
@@ -842,10 +838,6 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
842
838
|
};
|
|
843
839
|
`;
|
|
844
840
|
|
|
845
|
-
console.log("[Svelte] Processed script:", processedScript);
|
|
846
|
-
console.log("[Svelte] Wrapped script:", wrappedScript);
|
|
847
|
-
console.log("[Svelte] Initial data:", initialData);
|
|
848
|
-
|
|
849
841
|
// Create the factory function
|
|
850
842
|
const factoryFunc = new Function('console', wrappedScript);
|
|
851
843
|
const createHandlers = factoryFunc(console);
|
|
@@ -863,7 +855,7 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
863
855
|
try {
|
|
864
856
|
effect();
|
|
865
857
|
} catch (error) {
|
|
866
|
-
|
|
858
|
+
// Effect failed
|
|
867
859
|
}
|
|
868
860
|
}
|
|
869
861
|
};
|
|
@@ -882,8 +874,7 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
882
874
|
setInHandler: result.setInHandler || (() => { })
|
|
883
875
|
};
|
|
884
876
|
} catch (error) {
|
|
885
|
-
|
|
886
|
-
console.error("Processed script:", scriptContent);
|
|
877
|
+
// Silently fail and return fallback
|
|
887
878
|
}
|
|
888
879
|
|
|
889
880
|
// Function to run all effects (fallback)
|
|
@@ -892,7 +883,7 @@ export function createHandlerContext(scriptContent: string, initialData: Record<
|
|
|
892
883
|
try {
|
|
893
884
|
effect();
|
|
894
885
|
} catch (error) {
|
|
895
|
-
|
|
886
|
+
// Effect failed
|
|
896
887
|
}
|
|
897
888
|
}
|
|
898
889
|
};
|