aitu-app 0.9.2 → 0.9.3
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/README.md +3 -3
- package/assets/{CanvasAudioPlayer-C_USx5uz.js → CanvasAudioPlayer-BKMfe-GO.js} +2 -2
- package/assets/{ComicCreator-qGQaXp7h.js → ComicCreator-D5HnnPYu.js} +3 -3
- package/assets/DeferredAIInputBar-CVXfAbVO.css +1 -0
- package/assets/DeferredAIInputBar-Ce250DxA.js +107 -0
- package/assets/{DrawnixDeferredFeatures-Hy_-quZ1.js → DrawnixDeferredFeatures-ue9KjDJ6.js} +2 -2
- package/assets/{KnowledgeBaseContent-DSKNA70H.js → KnowledgeBaseContent-YCNU2vP8.js} +5 -5
- package/assets/{MVCreator-C3iClDLU.js → MVCreator-uWWF5q7x.js} +4 -4
- package/assets/{ModelBenchmarkWorkbench-BxwdcZ0q.js → ModelBenchmarkWorkbench-Bm75hOT0.js} +2 -2
- package/assets/{MusicAnalyzer-f_T6_YPJ.js → MusicAnalyzer-BXe6y3_p.js} +1 -1
- package/assets/ParametersDropdown-BE58BbHs.css +1 -0
- package/assets/{ParametersDropdown-CTSN3ClD.js → ParametersDropdown-wKdOCk_p.js} +1 -1
- package/assets/{PromptHistoryTool-DV-8RSdz.js → PromptHistoryTool-BRMlnlE1.js} +2 -2
- package/assets/{ResizableDivider-CUQBmPpx.js → ResizableDivider-tAq9KErj.js} +1 -1
- package/assets/{TaskQueuePanel-CtjY1W4t.js → TaskQueuePanel-D4PA4azU.js} +1 -1
- package/assets/{VideoAnalyzer-BBVBSONO.js → VideoAnalyzer-CVqV3zd3.js} +3 -3
- package/assets/{VideoAnalyzer-BmAjGvN8.js → VideoAnalyzer-gVfFvd5A.js} +1 -1
- package/assets/{ai-chat-BO5vbKZW.js → ai-chat-D_s8vs6j.js} +45 -45
- package/assets/{ai-chat-DyV67c_f.css → ai-chat-_KImIteT.css} +1 -1
- package/assets/{ai-generation-preferences-service-ZmPTR-wz.js → ai-generation-preferences-service-rBqGBu1Z.js} +1 -1
- package/assets/{batch-image-generation-BLBSv-t6.js → batch-image-generation-BHunNwyR.js} +6 -6
- package/assets/{diagram-engines-CSzW_-6N.js → diagram-engines-y0JSIEUO.js} +3 -3
- package/assets/{editor-engines-C573k8UM.js → editor-engines-Cc9_gvTn.js} +1 -1
- package/assets/{index-BT-rxxI3.js → index-BECJnoIM.js} +1 -1
- package/assets/{index-jxwTv7c1.js → index-BOOKwIS8.js} +1 -1
- package/assets/{index-N8asYyaz.js → index-Co0sFz6V.js} +2 -2
- package/assets/{index-IHNaVKGH.js → index-CrsvRs42.js} +1 -1
- package/assets/{index-Dw_8lcIi.js → index-Dthb4yKS.js} +1 -1
- package/assets/{index.es-BLXvmueB.js → index.es-l6CUS7uC.js} +1 -1
- package/assets/{jspdf.es.min-DxWvbkh4.js → jspdf.es.min-vSonSXg8.js} +3 -3
- package/assets/{markdown-to-drawnix-BVFYnimo.js → markdown-to-drawnix-CkXxETO6.js} +3 -3
- package/assets/{mermaid-to-drawnix-nGs2aeZ7.js → mermaid-to-drawnix-CiiYHL53.js} +3 -3
- package/assets/{model-benchmark-launcher-DAWoSySc.js → model-benchmark-launcher-EfxZ9z3O.js} +1 -1
- package/assets/{photo-wall-splitter-CCUURzGk.js → photo-wall-splitter-BJ5RLX6n.js} +1 -1
- package/assets/{prompt-utils-MF_LILNU.js → prompt-utils-7NlWAivq.js} +1 -1
- package/assets/{settings-dialog-Ac7R-_CG.js → settings-dialog-CBNPo-wJ.js} +1 -1
- package/assets/{skill-dsl-parser-Do9iAYbB.js → skill-dsl-parser-9CW3IgX7.js} +1 -1
- package/assets/{startup-app-CKHrOmQ0.css → startup-app-BJH8E5sr.css} +1 -1
- package/assets/{startup-app-eD_rQhSh.js → startup-app-M6vjXkRC.js} +509 -504
- package/assets/{task-sync-BJVOunRa.js → task-sync-B01Tbv7m.js} +1 -1
- package/assets/{tool-windows-CmgL3thd.js → tool-windows-Cf62DjP-.js} +21 -21
- package/assets/ttd-dialog-O1oaoYry.js +6 -0
- package/assets/{ttd-dialog-submit-shortcut-C2lJygXA.js → ttd-dialog-submit-shortcut-rkvbdHF7.js} +1 -1
- package/assets/{useCharacters-BAKE4TeJ.js → useCharacters-BVPiqeuF.js} +1 -1
- package/assets/{useMediaViewer-BGw5RkSR.js → useMediaViewer-Be0fy5RZ.js} +1 -1
- package/assets/{useWorkflowSubmission-iAPmKke9.js → useWorkflowSubmission-BwYRubj-.js} +9 -9
- package/assets/{video-recovery-service-CW7bErP2.js → video-recovery-service-CUmfssNZ.js} +1 -1
- package/assets/{workflow-generation-utils-DhIVnOHO.js → workflow-generation-utils-362XEGgT.js} +3 -3
- package/assets/{workflow-submission-service-Ce0cpj8E.js → workflow-submission-service-Dk47OkGu.js} +2 -2
- package/changelog.json +18 -13
- package/idle-prefetch-manifest.json +286 -286
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +6 -6
- package/sw.js +1 -1
- package/version.json +3 -4
- package/assets/DeferredAIInputBar-CPykEFYX.css +0 -1
- package/assets/DeferredAIInputBar-LmZGQCLT.js +0 -107
- package/assets/ParametersDropdown-b2oWAycj.css +0 -1
- package/assets/ttd-dialog-B12v0SVY.js +0 -6
package/sw.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var sw=(function(T){"use strict";var me=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(me||{});me.IMAGE+"",me.VIDEO+"",me.AUDIO+"",me.CHARACTER+"",me.INSPIRATION_BOARD+"",me.CHAT+"";function J(n){return n instanceof Error?n.name||"Error":"Unknown error"}const _t="sw-task-queue",mn=3,_="tasks",z="config",B="workflows",N="chat-workflows",L="pending-tool-requests",M="pending-dom-operations",x="task-step-mappings",$="pending-canvas-operations",Gs=[_,z,B,N,L,M,x,$];function Us(){return new Promise(n=>{const e=indexedDB.open(_t);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,mn))},e.onerror=()=>{n(mn)}})}function Hs(n){const e=[];for(const t of Gs)n.objectStoreNames.contains(t)||e.push(t);return e}function qs(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(_t,s);r.onerror=()=>{console.error("[SWStorage] Failed to repair DB:",r.error),t(r.error)},r.onsuccess=()=>{e(r.result)},r.onupgradeneeded=o=>{const a=o.target.result;bn(a)}})}function bn(n){if(!n.objectStoreNames.contains(_)){const e=n.createObjectStore(_,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("type","type",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(z)||n.createObjectStore(z,{keyPath:"key"}),!n.objectStoreNames.contains(B)){const e=n.createObjectStore(B,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(N)){const e=n.createObjectStore(N,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(L)||n.createObjectStore(L,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(M)){const e=n.createObjectStore(M,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(x)||n.createObjectStore(x,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains($)||n.createObjectStore($,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function js(){const n=await Us();return new Promise((e,t)=>{const s=indexedDB.open(_t,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=Hs(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),qs(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;bn(o)}})}class zs{constructor(){this.dbPromise=null,this.pendingTaskSaves=new Map,this.batchSaveTimer=null,this.batchSavePromises=new Map,this.BATCH_SAVE_DELAY=50}async getDB(){return this.dbPromise||(this.dbPromise=js()),this.dbPromise}async flushPendingTaskSaves(){this.batchSaveTimer&&(clearTimeout(this.batchSaveTimer),this.batchSaveTimer=null);const e=Array.from(this.pendingTaskSaves.values()),t=new Map(this.batchSavePromises);if(this.pendingTaskSaves.clear(),this.batchSavePromises.clear(),e.length!==0)try{const s=await this.getDB();await new Promise((r,o)=>{const a=s.transaction(_,"readwrite"),i=a.objectStore(_);for(const c of e)i.put(c);a.oncomplete=()=>{t.forEach(({resolve:c})=>c()),r()},a.onerror=()=>{const c=a.error;t.forEach(({reject:l})=>l(c)),o(c)}})}catch(s){console.error("[SWStorage] Failed to batch save tasks:",s),t.forEach(({reject:r})=>r(s))}}async saveTask(e){return new Promise((t,s)=>{this.pendingTaskSaves.set(e.id,e),this.batchSavePromises.set(e.id,{resolve:t,reject:s}),this.batchSaveTimer||(this.batchSaveTimer=setTimeout(()=>{this.flushPendingTaskSaves()},this.BATCH_SAVE_DELAY))})}async saveTaskImmediate(e){this.pendingTaskSaves.delete(e.id);const t=this.batchSavePromises.get(e.id);t&&this.batchSavePromises.delete(e.id);try{const s=await this.getDB();await new Promise((r,o)=>{const c=s.transaction(_,"readwrite").objectStore(_).put(e);c.onerror=()=>o(c.error),c.onsuccess=()=>r()}),t&&t.resolve()}catch(s){throw console.error("[SWStorage] Failed to save task:",s),t&&t.reject(s),s}}async getTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(_,"readonly").objectStore(_).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get task:",t),null}}async getAllTasks(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(_,"readonly").objectStore(_).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all tasks:",e),[]}}async getTasksByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(_,"readonly").objectStore(_).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get tasks by status:",t),[]}}async getTasksPaginated(e){const{offset:t,limit:s,status:r,type:o,sortOrder:a="desc"}=e;try{const i=await this.getDB();return new Promise((c,l)=>{const u=i.transaction(_,"readonly").objectStore(_).index("createdAt"),b=a==="desc"?"prev":"next",p=u.openCursor(null,b),g=[];let f=0,y=0;p.onerror=()=>l(p.error),p.onsuccess=S=>{const E=S.target.result;if(!E){c({tasks:g,total:y,hasMore:y>t+g.length});return}const W=E.value,U=!r||W.status===r,re=!o||W.type===o;U&&re&&(y++,f<t?f++:g.length<s&&g.push(W)),E.continue()}})}catch(i){return console.error("[SWStorage] Failed to get paginated tasks:",i),{tasks:[],total:0,hasMore:!1}}}async deleteTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(_,"readwrite").objectStore(_).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete task:",t)}}async getConfig(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(z,"readonly").objectStore(z).get(e);i.onsuccess=()=>{const c=i.result;if(!c){s(null);return}const{key:l,...h}=c;s(h)},i.onerror=()=>r(i.error)})}catch(t){return console.error("[SWStorage] Failed to get config:",J(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const a=s.transaction(z,"readwrite");a.objectStore(z).put({key:e,...t,updatedAt:Date.now()}),a.oncomplete=()=>r(),a.onerror=()=>o(a.error)})}catch(s){throw console.error("[SWStorage] Failed to save config:",J(s)),s}}async loadConfig(){const e=await this.getConfig("gemini"),t=await this.getConfig("video");return{geminiConfig:e,videoConfig:t}}async saveAllConfig(e,t){await this.saveConfig("gemini",e),await this.saveConfig("video",t)}async saveSystemPrompt(e){try{const t=await this.getDB();return new Promise((s,r)=>{const o=t.transaction(z,"readwrite");o.objectStore(z).put({key:"systemPrompt",value:e,updatedAt:Date.now()}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.error("[SWStorage] Failed to save system prompt:",t)}}async getSystemPrompt(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(z,"readonly").objectStore(z).get("systemPrompt");a.onsuccess=()=>{const i=a.result;t((i==null?void 0:i.value)||null)},a.onerror=()=>s(a.error)})}catch(e){return console.error("[SWStorage] Failed to get system prompt:",e),null}}async saveWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(B,"readwrite").objectStore(B).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save workflow:",t)}}async getWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(B,"readonly").objectStore(B).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get workflow:",t),null}}async getAllWorkflows(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(B,"readonly").objectStore(B).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all workflows:",e),[]}}async getWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(B,"readonly").objectStore(B).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get workflows by status:",t),[]}}async deleteWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(B,"readwrite").objectStore(B).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete workflow:",t)}}async saveChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(N,"readwrite").objectStore(N).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save chat workflow:",t)}}async getChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(N,"readonly").objectStore(N).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get chat workflow:",t),null}}async getAllChatWorkflows(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(N,"readonly").objectStore(N).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all chat workflows:",e),[]}}async getChatWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(N,"readonly").objectStore(N).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get chat workflows by status:",t),[]}}async deleteChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(N,"readwrite").objectStore(N).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete chat workflow:",t)}}async savePendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(L,"readwrite").objectStore(L).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending tool request:",t)}}async getAllPendingToolRequests(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(L,"readonly").objectStore(L).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending tool requests:",e),[]}}async getPendingToolRequestsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(L,"readonly").objectStore(L).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending tool requests by workflow:",t),[]}}async getPendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(L,"readonly").objectStore(L).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get pending tool request:",t),null}}async deletePendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(L,"readwrite").objectStore(L).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending tool request:",t)}}async deletePendingToolRequestsByWorkflow(e){try{const t=await this.getPendingToolRequestsByWorkflow(e);for(const s of t)await this.deletePendingToolRequest(s.requestId)}catch(t){console.error("[SWStorage] Failed to delete pending tool requests by workflow:",t)}}async cleanupStalePendingToolRequests(e=36e5){try{const t=await this.getDB(),s=Date.now()-e;return new Promise((r,o)=>{const a=t.transaction(L,"readwrite"),c=a.objectStore(L).openCursor();let l=0;c.onsuccess=()=>{const h=c.result;h&&(h.value.createdAt<s&&(h.delete(),l++),h.continue())},a.oncomplete=()=>{r(l)},a.onerror=()=>o(a.error)})}catch(t){return console.error("[SWStorage] Failed to cleanup stale pending tool requests:",t),0}}async savePendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(M,"readwrite").objectStore(M).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending DOM operation:",t)}}async getAllPendingDomOperations(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(M,"readonly").objectStore(M).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending DOM operations:",e),[]}}async getPendingDomOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(M,"readonly").objectStore(M).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by workflow:",t),[]}}async getPendingDomOperationsByChatId(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(M,"readonly").objectStore(M).index("chatId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by chat ID:",t),[]}}async getPendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(M,"readonly").objectStore(M).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operation:",t),null}}async deletePendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(M,"readwrite").objectStore(M).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending DOM operation:",t)}}async deletePendingDomOperationsByWorkflow(e){try{const t=await this.getPendingDomOperationsByWorkflow(e);for(const s of t)await this.deletePendingDomOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending DOM operations by workflow:",t)}}async deletePendingDomOperationsByChatId(e){try{const t=await this.getPendingDomOperationsByChatId(e);for(const s of t)await this.deletePendingDomOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending DOM operations by chat ID:",t)}}async saveTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(x,"readwrite").objectStore(x).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save task-step mapping:",t)}}async getAllTaskStepMappings(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(x,"readonly").objectStore(x).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all task-step mappings:",e),[]}}async getTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(x,"readonly").objectStore(x).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get task-step mapping:",t),null}}async getTaskStepMappingsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(x,"readonly").objectStore(x).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get task-step mappings by workflow:",t),[]}}async deleteTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(x,"readwrite").objectStore(x).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete task-step mapping:",t)}}async deleteTaskStepMappingsByWorkflow(e){try{const t=await this.getTaskStepMappingsByWorkflow(e);for(const s of t)await this.deleteTaskStepMapping(s.taskId)}catch(t){console.error("[SWStorage] Failed to delete task-step mappings by workflow:",t)}}async savePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction($,"readwrite").objectStore($).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending canvas operation:",t)}}async getAllPendingCanvasOperations(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction($,"readonly").objectStore($).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending canvas operations:",e),[]}}async getPendingCanvasOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction($,"readonly").objectStore($).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending canvas operations by workflow:",t),[]}}async deletePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction($,"readwrite").objectStore($).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending canvas operation:",t)}}async deletePendingCanvasOperationsByWorkflow(e){try{const t=await this.getPendingCanvasOperationsByWorkflow(e);for(const s of t)await this.deletePendingCanvasOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending canvas operations by workflow:",t)}}async archiveOldTasks(e=100){try{const t=await this.getDB(),s=await new Promise((c,l)=>{const u=t.transaction(_,"readonly").objectStore(_).index("createdAt"),b=[],p=u.openCursor(null,"next");p.onsuccess=()=>{const g=p.result;if(!g){c(b);return}const f=g.value;f.archived||b.push(f),g.continue()},p.onerror=()=>l(p.error)}),r=s.length-e;if(r<=0)return 0;const o=["completed","failed","cancelled"],a=s.filter(c=>o.includes(c.status)).slice(0,r);if(a.length===0)return 0;const i=Date.now();return new Promise((c,l)=>{const h=t.transaction(_,"readwrite"),d=h.objectStore(_);for(const u of a)u.archived=!0,u.updatedAt=i,d.put(u);h.oncomplete=()=>{c(a.length)},h.onerror=()=>l(h.error)})}catch(t){return console.error("[SWStorage] Failed to archive old tasks:",t),0}}}const yn=new zs,$s=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function Dt(n){if(!n)return n;if(typeof n=="string")return n.toLowerCase().startsWith("bearer ")||n.length>30&&/^[a-zA-Z0-9-_]+$/.test(n)&&!n.includes("-")?"[REDACTED]":n;if(Array.isArray(n))return n.map(e=>Dt(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();$s.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=Dt(s)}return e}return n}let Ke=!1;const Vs=500,oe=[];let At=0;function wn(){return Ke}const Sn=["SW_DEBUG_ENABLE","SW_DEBUG_DISABLE","SW_DEBUG_GET_STATUS","SW_DEBUG_CLEAR_LOGS","SW_DEBUG_CLEAR_CONSOLE_LOGS","SW_DEBUG_GET_CONSOLE_LOGS","SW_DEBUG_EXPORT_LOGS","SW_DEBUG_HEARTBEAT","SW_DEBUG_STATUS","SW_DEBUG_ENABLED","SW_DEBUG_DISABLED","SW_DEBUG_LOG","SW_DEBUG_LOGS","SW_DEBUG_LOGS_CLEARED","SW_CONSOLE_LOG","SW_DEBUG_CONSOLE_LOGS","SW_DEBUG_CONSOLE_LOGS_CLEARED","SW_POSTMESSAGE_LOG","SW_DEBUG_POSTMESSAGE_LOGS","SW_DEBUG_POSTMESSAGE_LOGS_CLEARED","SW_DEBUG_NEW_CRASH_SNAPSHOT","SW_DEBUG_CRASH_SNAPSHOTS","SW_DEBUG_CRASH_SNAPSHOTS_CLEARED","SW_DEBUG_GET_CRASH_SNAPSHOTS","SW_DEBUG_CLEAR_CRASH_SNAPSHOTS","CRASH_SNAPSHOT","debug:log","debug:llmLog","debug:statusChanged","debug:enable","debug:disable","debug:getStatus","debug:getLogs","debug:clearLogs","debug:getConsoleLogs","debug:clearConsoleLogs","debug:getPostMessageLogs","debug:clearPostMessageLogs","debug:getCrashSnapshots","debug:clearCrashSnapshots","debug:getLLMApiLogs","debug:clearLLMApiLogs","debug:getCacheStats","debug:exportLogs","debug:newCrashSnapshot","console:log","console:report","postmessage:log","postmessage:logBatch","crash:snapshot","crash:heartbeat"],Oe=new Map;function Cn(n){const e=Ke;Ke=n,!n&&e&&(oe.length=0,Oe.clear(),At=0)}function Rt(){return Ke}function Ks(n){if(!wn()||n==="unknown"||Sn.includes(n))return!1;if(n.startsWith("RPC:")){let e=n.slice(4);if(e.endsWith(":response")?e=e.slice(0,-9):e.endsWith(":error")&&(e=e.slice(0,-6)),Sn.includes(e))return!1}return!0}function Xs(n){if(!n)return{};let e="other";return n.includes("sw-debug")?e="debug":(n.includes("localhost")||n.includes("127.0.0.1")||!n.includes("chrome-extension")&&!n.includes("moz-extension"))&&(e="main"),{clientType:e,clientUrl:new URL(n).pathname+new URL(n).search}}function Lt(n,e,t,s,r){if(r||!Ks(n))return"";const o=Xs(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++At}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:En(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(Ys(i),Js(n)){const c=Zs(e);c&&Oe.set(c,{entry:i,startTime:Date.now()})}return a}function Ys(n){oe.unshift(n),oe.length>Vs&&oe.pop()}function Mt(n,e,t,s){if(!wn())return"";const r=Oe.get(n);if(r){r.entry.response=En(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return Oe.delete(n),o}return""}function Xe(){return[...oe]}function Qs(){oe.length=0,Oe.clear(),At=0}function Js(n){return n.startsWith("RPC:")&&!n.endsWith(":response")&&!n.endsWith(":error")?!0:["TASK_SUBMIT","TASK_CANCEL","TASK_RETRY","TASK_DELETE","TASK_GET_","WORKFLOW_SUBMIT","WORKFLOW_CANCEL","WORKFLOW_GET_","CHAT_START","MCP_TOOL_EXECUTE","MAIN_THREAD_TOOL_REQUEST"].some(t=>n.includes(t))}function Zs(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function En(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return Dt(e)}catch{return"[Non-serializable data]"}}function er(){const n={total:oe.length,sent:0,received:0,byType:{}};for(const e of oe)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const vt=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:Qs,getAllLogs:Xe,getLogStats:er,isPostMessageLoggerDebugMode:Rt,logReceivedMessage:Lt,setPostMessageLoggerDebugMode:Cn,updateRequestWithResponse:Mt},Symbol.toStringTag,{value:"Module"}));function tr(){return typeof window<"u"?window:typeof self<"u"?self:{}}function nr(n){return JSON.parse(JSON.stringify(n))}function Tn(n){const e=Date.now().toString(36);let t;if(typeof crypto<"u"&&crypto.getRandomValues){const s=new Uint32Array(2);crypto.getRandomValues(s),t=s[0].toString(36)+s[1].toString(36)}else t=Math.floor(1e10*Math.random()).toString(36);return`${n}${e}${t}_`}const sr="postmessage-duplex",rr="1.2.0",Ye=tr();var X,ae;Ye.__POSTMESSAGE_DUPLEX__||(Ye.__POSTMESSAGE_DUPLEX__={}),Ye.__POSTMESSAGE_DUPLEX__.version=rr,Ye.__POSTMESSAGE_DUPLEX__.name=sr,(function(n){n[n.Success=0]="Success",n[n.ReceiverCallbackError=-1]="ReceiverCallbackError",n[n.SendCallbackError=-2]="SendCallbackError",n[n.NoSubscribe=-3]="NoSubscribe",n[n.TimeOut=-99]="TimeOut"})(X||(X={})),(function(n){n.ConnectionDestroyed="CONNECTION_DESTROYED",n.ConnectionTimeout="CONNECTION_TIMEOUT",n.MethodCallTimeout="METHOD_CALL_TIMEOUT",n.MethodNotFound="METHOD_NOT_FOUND",n.TransmissionFailed="TRANSMISSION_FAILED",n.MessageSizeExceeded="MESSAGE_SIZE_EXCEEDED",n.RateLimitExceeded="RATE_LIMIT_EXCEEDED",n.HandlerError="HANDLER_ERROR",n.InvalidMessage="INVALID_MESSAGE",n.OriginMismatch="ORIGIN_MISMATCH",n.HeartbeatFailed="HEARTBEAT_FAILED",n.ReconnectFailed="RECONNECT_FAILED",n.HandshakeFailed="HANDSHAKE_FAILED",n.ServiceWorkerUnavailable="SERVICE_WORKER_UNAVAILABLE"})(ae||(ae={}));class ie extends Error{constructor(e,t,s){super(e),Object.defineProperty(this,"code",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"details",{enumerable:1,configurable:1,writable:1,value:void 0}),this.name="ChannelError",this.code=t,this.details=s,Error.captureStackTrace&&Error.captureStackTrace(this,ie)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class or{constructor(){Object.defineProperty(this,"timeouts",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timer",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"nextDeadline",{enumerable:1,configurable:1,writable:1,value:1/0}),Object.defineProperty(this,"destroyed",{enumerable:1,configurable:1,writable:1,value:0})}add(e,t,s){if(this.destroyed)return;const r=Date.now()+t;this.timeouts.set(e,{deadline:r,callback:s}),r<this.nextDeadline&&this.reschedule(r)}remove(e){return this.timeouts.delete(e)}has(e){return this.timeouts.has(e)}get size(){return this.timeouts.size}reschedule(e){this.timer!==null&&clearTimeout(this.timer),this.nextDeadline=e;const t=Math.max(0,e-Date.now());this.timer=setTimeout(()=>this.processTimeouts(),t)}processTimeouts(){if(this.destroyed)return;const e=Date.now(),t=[];for(const[s,{deadline:r,callback:o}]of this.timeouts)r<=e&&(t.push(o),this.timeouts.delete(s));for(const s of t)try{s()}catch(r){console.error("[TimeoutManager] Callback error:",r)}this.scheduleNext()}scheduleNext(){if(this.timeouts.size===0)return this.nextDeadline=1/0,void(this.timer=null);let e=1/0;for(const{deadline:t}of this.timeouts.values())t<e&&(e=t);e<1/0&&this.reschedule(e)}destroy(){this.destroyed=1,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}}class ar{constructor(e,t=1e3){Object.defineProperty(this,"limit",{enumerable:1,configurable:1,writable:1,value:e}),Object.defineProperty(this,"windowMs",{enumerable:1,configurable:1,writable:1,value:t}),Object.defineProperty(this,"timestamps",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"head",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"tail",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"count",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"enabled",{enumerable:1,configurable:1,writable:1,value:void 0}),this.enabled=e>0,this.timestamps=this.enabled?new Array(e).fill(0):[]}tryAcquire(){if(!this.enabled)return 1;const e=Date.now(),t=e-this.windowMs;for(;this.count>0&&this.timestamps[this.head]<=t;)this.head=(this.head+1)%this.limit,this.count--;return this.count>=this.limit?0:(this.timestamps[this.tail]=e,this.tail=(this.tail+1)%this.limit,this.count++,1)}getCurrentCount(){if(!this.enabled)return 0;const e=Date.now()-this.windowMs;let t=0,s=this.head;for(let r=0;r<this.count;r++)this.timestamps[s]>e&&t++,s=(s+1)%this.limit;return t}getRemainingCapacity(){return this.enabled?Math.max(0,this.limit-this.getCurrentCount()):1/0}getTimeUntilAvailable(){if(!this.enabled||this.count<this.limit)return 0;const e=Date.now()-this.windowMs;let t=this.head;for(;t!==this.tail;){if(this.timestamps[t]>e)return this.timestamps[t]-e;t=(t+1)%this.limit}return 0}isLimited(){return this.enabled?this.getCurrentCount()>=this.limit:0}reset(){this.head=0,this.tail=0,this.count=0,this.enabled&&this.timestamps.fill(0)}getLimit(){return this.limit}getWindowMs(){return this.windowMs}isEnabled(){return this.enabled}}class ir{constructor(){Object.defineProperty(this,"eventHandlers",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"eventsEnabled",{enumerable:1,configurable:1,writable:1,value:1})}on(e,t){let s=this.eventHandlers.get(e);return s||(s=new Set,this.eventHandlers.set(e,s)),s.add(t),()=>{s==null||s.delete(t),(s==null?void 0:s.size)===0&&this.eventHandlers.delete(e)}}once(e,t){const s=r=>{this.off(e,s),t(r)};return this.on(e,s)}off(e,t){const s=this.eventHandlers.get(e);if(!s)return 0;const r=s.delete(t);return s.size===0&&this.eventHandlers.delete(e),r}offAll(e){e?this.eventHandlers.delete(e):this.eventHandlers.clear()}emit(e,t){if(!this.eventsEnabled)return;const s=this.eventHandlers.get(e);if(s)for(const r of[...s])try{r(t)}catch(o){console.error(`[ChannelEventEmitter] Error in ${e} handler:`,o)}}hasListeners(e){const t=this.eventHandlers.get(e);return t!==void 0&&t.size>0}listenerCount(e){var t;return((t=this.eventHandlers.get(e))==null?void 0:t.size)??0}setEventsEnabled(e){this.eventsEnabled=e}destroyEventEmitter(){this.eventHandlers.clear(),this.eventsEnabled=0}}function _n(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const Z=n=>({valid:0,error:n});function cr(n){if(!_n(n))return Z("Message must be an object");const e=n,t="requestId"in e,s="cmdname"in e,r="msg"in e,o="ret"in e;return t||s||r?t&&typeof e.requestId!="string"?Z("requestId must be a string"):s&&typeof e.cmdname!="string"?Z("cmdname must be a string"):r&&typeof e.msg!="string"?Z("msg must be a string"):!o||typeof(a=e.ret)=="number"&&Object.values(X).includes(a)?"data"in e&&e.data!==void 0&&!_n(e.data)?Z("data must be an object"):"_senderKey"in e&&e._senderKey!==void 0&&typeof e._senderKey!="string"?Z("_senderKey must be a string"):!("time"in e)||e.time===void 0||typeof e.time=="number"&&Number.isFinite(e.time)?{valid:1,message:e}:Z("time must be a finite number"):Z("ret must be a valid ReturnCode"):Z("Message must have requestId, cmdname, or msg field");var a}function Qe(n){return"ret"in n&&typeof n.ret=="number"}function lr(n){return n.msg==="ready"}function ur(n){return n._broadcast==1&&typeof n.cmdname=="string"}function dr(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const It=[],ee=[];function Dn(n){ee.length>=200&&ee.shift(),ee.push(n)}function An(n,e){for(let t=ee.length-1;t>=0;t--)if(ee[t].requestId===n&&ee[t].status==="pending"){ee[t].status=e,ee[t].duration=Date.now()-ee[t].timestamp;break}}class hr extends ir{constructor(e){if(super(),Object.defineProperty(this,"baseKey",{enumerable:1,configurable:1,writable:1,value:""}),Object.defineProperty(this,"peerKey",{enumerable:1,configurable:1,writable:1,value:""}),Object.defineProperty(this,"reqTime",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"callbackMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"subscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"broadcastHandlers",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timeout",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"isReady",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"isDestroyed",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"postTasks",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"bindOnMessage",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"console",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"maxMessageSize",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"timeoutManager",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"rateLimiter",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"strictValidation",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"requestCmdMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"isProcessingBatch",{enumerable:1,configurable:1,writable:1,value:0}),this.timeout=(e==null?void 0:e.timeout)??5e3,this.console=(e==null?void 0:e.log)??(typeof window<"u"?window.console:console),this.maxMessageSize=(e==null?void 0:e.maxMessageSize)??1048576,this.strictValidation=(e==null?void 0:e.strictValidation)??1,this.timeoutManager=new or,this.rateLimiter=new ar((e==null?void 0:e.rateLimit)??100,1e3),e==null?void 0:e.subscribeMap)for(const s in e.subscribeMap)this.subscribeMap.set(s,e.subscribeMap[s]);var t;this.bindOnMessage=this.onMessage.bind(this),t=this,It.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{Dn({direction:"send",cmdname:s,requestId:r,status:"pending",timestamp:Date.now(),dataSummary:""})}),t.on("message:received",({cmdname:s,requestId:r,isResponse:o})=>{const a=s||"",i=r||"";o?An(i,"ok"):Dn({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{An(r,"timeout")}),t.on("error",({context:s})=>{}),t.on("destroy",()=>{})}checkRateLimit(){if(!this.rateLimiter.isEnabled())return 1;if(!this.rateLimiter.tryAcquire()){const e=this.rateLimiter.getCurrentCount(),t=this.rateLimiter.getLimit();return this.log("warn","Rate limit exceeded:",e,"/",t,"messages per second"),this.emit("rate:limited",{currentCount:e,limit:t}),0}return 1}validateMessageSize(e){if(this.maxMessageSize<=0)return;const t=dr(e);if(t>this.maxMessageSize){const s=new ie(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ae.MessageSizeExceeded,{size:t,limit:this.maxMessageSize});throw this.emit("error",{error:s,context:"validateMessageSize"}),s}}init(){this.setupMessageListener(),this.sendMessage({requestId:this.baseKey+this.reqTime,msg:"ready",_senderKey:this.baseKey})}log(e,...t){var s,r;(r=(s=this.console)==null?void 0:s[e])==null||r.call(s,`[${this.channelType}]: `,...t)}isFromPeer(e){return this.peerKey?e._senderKey&&e._senderKey!==this.peerKey?(this.log("log","Message from non-paired channel, ignored",e._senderKey,"expected:",this.peerKey),0):Qe(e)&&e.requestId&&!e.requestId.startsWith(this.baseKey)?0:1:1}sendMessage(e,t){this.validateMessageSize(e),this.checkRateLimit()?(e.time=Date.now(),e._senderKey=this.baseKey,this.sendRawMessage(e,t)):this.log("warn","Message dropped due to rate limiting")}async onMessage(e){if(this.log("log","onMessage",e.data),!this.isValidSource(e))return;if(this.strictValidation){const o=cr(e.data);if(!o.valid)return this.log("warn","Invalid message structure:",o.error),void this.emit("validation:failed",{reason:o.error,data:e.data})}const t=e.data;if(!t||!this.isFromPeer(t))return;this.emit("message:received",{cmdname:t.cmdname||"",requestId:t.requestId||"",isResponse:Qe(t)});const{requestId:s,cmdname:r}=t;this.handleResponseMessage(t,s)||this.handleBroadcastMessage(t,r)||await this.handleSubscriptionMessage(t,s,r)||this.handleReadyMessage(t,s)||this.handleUnhandledMessage(t,s,r)}handleResponseMessage(e,t){const s=t?this.callbackMap.get(t):void 0;return s&&t?(this.timeoutManager.remove(t),this.requestCmdMap.delete(t),s.resolve(e),this.deleteCallback(t),1):0}handleBroadcastMessage(e,t){if(!ur(e))return 0;const s=t?this.broadcastHandlers.get(t):void 0;if(s)try{s({cmdname:t,data:e.data})}catch(r){const o=r instanceof Error?r.message:String(r);this.emit("error",{error:r instanceof Error?r:new Error(o),context:`broadcast:${t}`})}return 1}async handleSubscriptionMessage(e,t,s){if(!s)return 0;const r=this.subscribeMap.get(s);if(!r)return 0;try{const o=await r(e);this.sendMessage({requestId:t,ret:X.Success,data:o})}catch(o){const a=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:X.ReceiverCallbackError,msg:a||"unknown error"}),this.emit("error",{error:o instanceof Error?o:new Error(a),context:`handler:${s}`})}return 1}handleReadyMessage(e,t){if(!lr(e))return 0;const{_senderKey:s}=e;return s&&!this.peerKey&&(this.peerKey=s,this.log("log","Point-to-point pairing established","self:",this.baseKey,"peer:",this.peerKey)),this.isReady=1,this.executePosts(),this.emit("ready",{peerKey:this.peerKey}),Qe(e)||this.sendMessage({requestId:t,ret:X.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!Qe(e)&&(this.log("warn","No registered handler for:",s||t),this.sendMessage({requestId:t,ret:X.NoSubscribe}))}postMessage(e,t){try{this.sendMessage(e,t),this.emit("message:sent",{cmdname:e.cmdname||"",requestId:e.requestId||""})}catch(s){this.log("error",s,e),this.emit("error",{error:s instanceof Error?s:new Error(String(s)),context:"postMessage"})}}publish(e,t,s){if(this.isDestroyed)return Promise.reject(new ie("Cannot publish: channel has been destroyed",ae.ConnectionDestroyed,{cmdname:e}));const r=this.baseKey+ ++this.reqTime,o={requestId:r,cmdname:e,data:t};this.requestCmdMap.set(r,e);const a=new Promise((i,c)=>{this.callbackMap.set(r,{resolve:i,reject:c})});return this.log("log","publish",this.isReady,this.postTasks.size),this.isReady?this.doPublish(o,s):this.postTasks.set(r,{data:o,prm:a,options:s}),a}doPublish(e,t){const{requestId:s,cmdname:r}=e,o=(t==null?void 0:t.timeout)??this.timeout;this.timeoutManager.add(s,o,()=>{const a=this.callbackMap.get(s);if(a){const i={req:e,requestId:s,ret:X.TimeOut,time:Date.now(),msg:"timeout"};this.log("error","postmessage timeout",i),this.emit("timeout",{requestId:s,cmdname:r,timeoutMs:o}),a.resolve(i),this.deleteCallback(s),this.requestCmdMap.delete(s)}}),this.postMessage(e,t==null?void 0:t.transferables)}deleteCallback(e){this.callbackMap.delete(e),this.postTasks.delete(e),this.timeoutManager.remove(e)}executePosts(){this.postTasks.size===0||this.isProcessingBatch||(this.isProcessingBatch=1,queueMicrotask(()=>{this.processBatch(),this.isProcessingBatch=0}))}processBatch(){const e=Array.from(this.postTasks.entries());for(const[t,s]of e)this.postTasks.has(t)&&(t.startsWith("_broadcast_")?(this.doBroadcast(s.data,s.options),this.postTasks.delete(t)):this.doPublish(s.data,s.options))}call(e,t,s){return this.publish(e,t,s)}subscribe(e,t){return this.subscribeMap.has(e)&&this.log("warn",`${e} has been subscribed`),this.subscribeMap.set(e,t),this}unSubscribe(e){return this.subscribeMap.delete(e),this}subscribeOnce(e,t){return this.subscribe(e,async s=>(this.unSubscribe(e),t(s)))}broadcast(e,t,s){if(this.isDestroyed)return void this.log("warn","Cannot broadcast: channel has been destroyed");const r={cmdname:e,data:t,time:Date.now(),_broadcast:1};if(this.log("log","broadcast",e,this.isReady),this.isReady)this.doBroadcast(r,s);else{const o=`_broadcast_${Date.now()}_${Math.random()}`;this.postTasks.set(o,{data:r,prm:Promise.resolve({}),options:s})}}doBroadcast(e,t){try{this.sendMessage(e,t==null?void 0:t.transferables),this.emit("broadcast:sent",{cmdname:e.cmdname})}catch(s){this.log("error","broadcast error",s,e),this.emit("error",{error:s instanceof Error?s:new Error(String(s)),context:"broadcast"})}}onBroadcast(e,t){return this.broadcastHandlers.has(e)&&this.log("warn",`Broadcast handler for ${e} already registered, replacing`),this.broadcastHandlers.set(e,t),this}offBroadcast(e){return this.broadcastHandlers.delete(e),this}getPeerKey(){return this.peerKey}getRateLimitStats(){return{current:this.rateLimiter.getCurrentCount(),limit:this.rateLimiter.getLimit(),remaining:this.rateLimiter.getRemainingCapacity()}}getPendingCount(){return this.callbackMap.size}destroy(){if(this.isDestroyed)return;this.isDestroyed=1,this.emit("destroy",{reason:"explicit"}),(function(t){const s=It.findIndex(r=>r.deref()===t);s!==-1&&It.splice(s,1)})(this);const e=new ie("Channel has been destroyed",ae.ConnectionDestroyed);for(const[t,s]of this.callbackMap)try{s.reject({ret:X.SendCallbackError,msg:e.message})}catch(r){this.log("warn","Error rejecting pending request:",t,r)}this.removeMessageListener(),this.subscribeMap.clear(),this.broadcastHandlers.clear(),this.postTasks.clear(),this.callbackMap.clear(),this.requestCmdMap.clear(),this.timeoutManager.destroy(),this.rateLimiter.reset(),this.destroyEventEmitter(),this.isReady=0,this.peerKey=""}}class Y{constructor(){Object.defineProperty(this,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"initialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"options",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(this,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"channelFactory",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"globalMessageHandler",{enumerable:1,configurable:1,writable:1,value:e=>{const t=e.source,s=t==null?void 0:t.id;if(!s)return;const r=this.channelsByClientId.get(s);r?r.handleMessage(e):this.unknownClientCallback&&this.unknownClientCallback(s,e)}})}static getInstance(){return Y.instance||(Y.instance=new Y),Y.instance}static resetInstance(){Y.instance&&(Y.instance.shutdown(),Y.instance=null)}setup(e,t){if(this.initialized)return void console.warn("[ServiceWorkerHub] Already initialized");this.options=e,this.channelFactory=t,this.initialized=1,this.registerBuiltInHandlers(),this.setupLifecycleEvents();const s=e.cleanupInterval??3e4;s>0&&(this.cleanupIntervalId=setInterval(()=>this.cleanupInactiveClients(),s))}shutdown(){this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.globalListenerSetup&&(self.removeEventListener("message",this.globalMessageHandler),this.globalListenerSetup=0);for(const e of this.channelsByClientId.values())try{e.destroy()}catch{}this.channelsByClientId.clear(),this.clientMeta.clear(),this.globalSubscribeMap.clear(),this.initialized=0}isInitialized(){return this.initialized}getOptions(){return this.options}enableGlobalRouting(e){this.unknownClientCallback=e??null,this.globalListenerSetup||(self.addEventListener("message",this.globalMessageHandler),this.globalListenerSetup=1)}disableGlobalRouting(){this.globalListenerSetup&&(self.removeEventListener("message",this.globalMessageHandler),this.globalListenerSetup=0)}isGlobalRoutingEnabled(){return this.globalListenerSetup}registerChannel(e,t){this.channelsByClientId.set(e,t),this.applyGlobalHandlersToChannel(t,e)}unregisterChannel(e){var t,s;this.channelsByClientId.delete(e),this.clientMeta.delete(e),(s=(t=this.options).onClientDisconnect)==null||s.call(t,e)}getChannel(e){return this.channelsByClientId.get(e)}hasChannel(e){return this.channelsByClientId.has(e)}getChannelCount(){return this.channelsByClientId.size}createChannelForClient(e){if(!this.channelFactory)return console.warn("[ServiceWorkerHub] No channel factory configured"),null;const t=this.channelFactory(e);return this.registerChannel(e,t),t}registerClientMeta(e,t){var r,o;const s={clientId:e,appType:t.appType,appName:t.appName,connectedAt:new Date().toISOString()};return this.clientMeta.set(e,s),(o=(r=this.options).onClientConnect)==null||o.call(r,e,s),s}getClientMeta(e){return this.clientMeta.get(e)}getAllClientMeta(){return new Map(this.clientMeta)}getClientsByType(e){const t=[];for(const s of this.clientMeta.values())s.appType===e&&t.push(s);return t}subscribeGlobal(e,t){e.startsWith("__")&&console.warn(`[ServiceWorkerHub] Handler name '${e}' uses reserved prefix '__'.`),this.globalSubscribeMap.set(e,t);for(const[s,r]of this.channelsByClientId)this.applyHandlerToChannel(r,s,e,t)}unsubscribeGlobal(e){this.globalSubscribeMap.delete(e);for(const t of this.channelsByClientId.values())t.unSubscribe(e)}applyGlobalHandlersToChannel(e,t){for(const[s,r]of this.globalSubscribeMap)this.applyHandlerToChannel(e,t,s,r)}applyHandlerToChannel(e,t,s,r){e.subscribe(s,async o=>{const a=this.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:a})})}registerBuiltInHandlers(){this.globalSubscribeMap.set("__register__",({data:e,clientId:t})=>(this.registerClientMeta(t,{appType:e.appType,appName:e.appName}),{success:1,clientId:t,totalClients:this.clientMeta.size})),this.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:this.channelsByClientId.size}))}setupLifecycleEvents(){self.addEventListener("install",e=>{typeof self.skipWaiting=="function"&&self.skipWaiting()}),self.addEventListener("activate",e=>{const t=(async()=>{var s;typeof((s=self.clients)==null?void 0:s.claim)=="function"&&await self.clients.claim(),await this.notifyAllClientsSwActivated()})();typeof e.waitUntil=="function"&&e.waitUntil(t)})}async notifyAllClientsSwActivated(){try{const e=await self.clients.matchAll();for(const t of e)t.postMessage({cmdname:"__sw-activated__",data:{version:this.options.version},_broadcast:1})}catch(e){console.error("[ServiceWorkerHub] Error notifying clients:",e)}}async cleanupInactiveClients(){var e,t;try{const s=await self.clients.matchAll(),r=new Set(s.map(o=>o.id));for(const[o,a]of this.channelsByClientId)r.has(o)||(a.destroy(),this.channelsByClientId.delete(o),this.clientMeta.delete(o),(t=(e=this.options).onClientDisconnect)==null||t.call(e,o))}catch(s){console.error("[ServiceWorkerHub] Cleanup error:",s)}}async broadcastToAll(e,t,s){if(!this.initialized)return console.warn("[ServiceWorkerHub] Not initialized"),0;try{const r=await self.clients.matchAll();let o=0;for(const a of r){if(s&&a.id===s)continue;const i=this.channelsByClientId.get(a.id);if(i)try{i.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",a.id,c)}}return o}catch(r){return console.error("[ServiceWorkerHub] broadcastToAll error:",r),0}}async broadcastToType(e,t,s,r){if(!this.initialized)return console.warn("[ServiceWorkerHub] Not initialized"),0;try{const o=await self.clients.matchAll();let a=0;for(const i of o){if(r&&i.id===r)continue;const c=this.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=this.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(h){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",i.id,h)}}return a}catch(o){return console.error("[ServiceWorkerHub] broadcastToType error:",o),0}}}Object.defineProperty(Y,"instance",{enumerable:1,configurable:1,writable:1,value:null});class m extends hr{static enableGlobalRouting(e){m.useGlobalRouting=1,m.unknownClientCallback=e??null,m.globalListenerSetup||(self.addEventListener("message",m.globalMessageHandler),m.globalListenerSetup=1)}static disableGlobalRouting(){m.useGlobalRouting=0,m.globalListenerSetup&&(self.removeEventListener("message",m.globalMessageHandler),m.globalListenerSetup=0)}static setupHub(e={}){if(m.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");m.hubOptions=e,m.hubInitialized=1,Y.getInstance().setup(e,s=>m.createFromWorker(s)),m.enableGlobalRouting((s,r)=>{const o=m.createFromWorker(s);m.setupChannelHandlers(o,s),o.handleMessage(r)}),m.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(m.cleanupIntervalId=setInterval(()=>m.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){m.globalSubscribeMap.set("__register__",({data:e,clientId:t})=>{var r,o;const s={clientId:t,appType:e.appType,appName:e.appName,connectedAt:new Date().toISOString()};return m.clientMeta.set(t,s),(o=(r=m.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:m.clientMeta.size}}),m.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:m.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of m.globalSubscribeMap)e.subscribe(s,async o=>{const a=m.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:a})})}static setupLifecycleEvents(){self.addEventListener("install",()=>{typeof self.skipWaiting=="function"&&self.skipWaiting()}),self.addEventListener("activate",e=>{const t=(async()=>{var s;typeof((s=self.clients)==null?void 0:s.claim)=="function"&&await self.clients.claim(),await m.notifyAllClientsSwActivated()})();typeof e.waitUntil=="function"&&e.waitUntil(t)})}static async notifyAllClientsSwActivated(){try{const e=await self.clients.matchAll();for(const t of e)t.postMessage({cmdname:"__sw-activated__",data:{version:m.hubOptions.version},_broadcast:1})}catch(e){console.error("[ServiceWorkerChannel] Error notifying clients:",e)}}static async cleanupInactiveClients(){var e,t;try{const s=await self.clients.matchAll(),r=new Set(s.map(o=>o.id));for(const[o]of m.channelsByClientId)if(!r.has(o)){const a=m.channelsByClientId.get(o);a&&a.destroy(),m.clientMeta.delete(o),(t=(e=m.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!m.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const r=await self.clients.matchAll();let o=0;for(const a of r){if(s&&a.id===s)continue;const i=m.channelsByClientId.get(a.id);if(i)try{i.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",a.id,c)}}return o}catch(r){return console.error("[ServiceWorkerChannel] broadcastToAll error:",r),0}}static async broadcastToType(e,t,s,r){if(!m.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const o=await self.clients.matchAll();let a=0;for(const i of o){if(r&&i.id===r)continue;const c=m.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=m.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(h){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",i.id,h)}}return a}catch(o){return console.error("[ServiceWorkerChannel] broadcastToType error:",o),0}}static getClientInfo(e){return m.clientMeta.get(e)}static getAllClients(){return new Map(m.clientMeta)}static getClientsByType(e){const t=[];for(const s of m.clientMeta.values())s.appType===e&&t.push(s);return t}static subscribeGlobal(e,t){e.startsWith("__")&&console.warn(`[ServiceWorkerChannel] Handler name '${e}' uses reserved prefix '__'. This may conflict with internal handlers.`),m.globalSubscribeMap.set(e,t);for(const[s,r]of m.channelsByClientId)r.subscribe(e,async o=>{const a=m.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:a})})}static unsubscribeGlobal(e){m.globalSubscribeMap.delete(e);for(const t of m.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&m.useGlobalRouting&&m.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&m.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return m.channelsByClientId.get(e)}static hasChannel(e){return m.channelsByClientId.has(e)}static getChannelCount(){return m.channelsByClientId.size}handleMessage(e){return this.onMessage(e)}constructor(e,t){if(super(t),Object.defineProperty(this,"channelType",{enumerable:1,configurable:1,writable:1,value:"ServiceWorkerChannel"}),Object.defineProperty(this,"isWorkerSide",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"worker",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"clientId",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"swContainer",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"l",{enumerable:1,configurable:1,writable:1,value:"connecting"}),Object.defineProperty(this,"lastSuccessfulMessageTime",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"heartbeatIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"missedHeartbeatCount",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"isReconnecting",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"reconnectAttempt",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"connectionOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(this,"boundControllerChangeHandler",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"boundStateChangeHandler",{enumerable:1,configurable:1,writable:1,value:null}),this.isWorkerSide=(t==null?void 0:t.isWorkerSide)??0,this.isWorkerSide){if(typeof e!="string")throw new Error("Service Worker 端必须传入 clientId 字符串");this.clientId=e,this.baseKey=Tn("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=Tn("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(m.useGlobalRouting)return void(m.globalListenerSetup||(self.addEventListener("message",m.globalMessageHandler),m.globalListenerSetup=1));self.addEventListener("message",this.bindOnMessage)}else(e=this.swContainer)==null||e.addEventListener("message",this.bindOnMessage)}removeMessageListener(){var e;if(this.unregisterFromGlobalRouter(),this.isWorkerSide){if(m.useGlobalRouting)return;self.removeEventListener("message",this.bindOnMessage)}else(e=this.swContainer)==null||e.removeEventListener("message",this.bindOnMessage)}sendRawMessage(e,t){var s,r;try{const o=nr(e);this.isWorkerSide?this.sendToClient(o,t):t&&t.length>0?(s=this.worker)==null||s.postMessage(o,t):(r=this.worker)==null||r.postMessage(o)}catch(o){this.log("error","sendMessage error",o,e)}}async sendToClient(e,t){const s=this.clientId;if(s)try{const r=await self.clients.get(s);r?t&&t.length>0?r.postMessage(e,t):r.postMessage(e):this.log("warn","Client not found:",s)}catch(r){this.log("error","sendToClient error",r)}else this.log("error","No clientId available")}isValidSource(e){if(this.isWorkerSide){const t=e.source;return(t==null?void 0:t.id)===this.clientId}return 1}log(e,...t){var r,o;const s=this.isWorkerSide?"worker":"page";(o=(r=this.console)==null?void 0:r[e])==null||o.call(r,`[ServiceWorkerChannel](${s}): `,...t)}getClientId(){return this.clientId}isWorkerAvailable(){var e;return this.isWorkerSide||((e=this.worker)==null?void 0:e.state)==="activated"}async refreshWorker(){if(this.isWorkerSide)throw new Error("refreshWorker() can only be called on page side");const e=(await navigator.serviceWorker.ready).active||navigator.serviceWorker.controller;e?(this.worker=e,this.peerKey="",this.isReady=0,this.sendMessage({requestId:this.baseKey+this.reqTime,msg:"ready",_senderKey:this.baseKey})):console.warn("[ServiceWorkerChannel] No active Service Worker found during refresh")}get connectionState(){return this.l}get isConnected(){return this.l==="connected"}updateLastMessageTime(){this.lastSuccessfulMessageTime=Date.now()}setConnectionState(e,t){if(this.l===e)return;const s=this.l;switch(this.l=e,this.log("log",`Connection state: ${s} -> ${e}`),e){case"connected":this.missedHeartbeatCount=0,this.reconnectAttempt=0,this.emit("connected",{isReconnect:s==="reconnecting"});break;case"disconnected":this.emit("disconnected",{reason:(t==null?void 0:t.reason)||"error",error:t==null?void 0:t.error});break;case"reconnecting":this.emit("reconnecting",{attempt:(t==null?void 0:t.attempt)||this.reconnectAttempt,maxAttempts:this.connectionOptions.maxReconnectAttempts||5,nextRetryIn:(t==null?void 0:t.nextRetryIn)||0})}}startHeartbeat(){if(this.isWorkerSide)return;const e=this.connectionOptions.heartbeatInterval??3e4;e<=0||(this.stopHeartbeat(),this.heartbeatIntervalId=setInterval(()=>{this.performHeartbeat()},e),this.log("log",`Heartbeat started with interval ${e}ms`))}stopHeartbeat(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null)}async performHeartbeat(){const e=this.connectionOptions.heartbeatInterval??3e4;if(this.connectionOptions.smartHeartbeat!=0&&this.lastSuccessfulMessageTime>0&&Date.now()-this.lastSuccessfulMessageTime<e)return this.missedHeartbeatCount=0,void this.emit("heartbeat",{success:1,missedCount:0});const t=this.connectionOptions.heartbeatTimeout??5e3,s=Date.now();try{if((await this.publish("__ping__",{},{timeout:t})).ret===X.Success){const r=Date.now()-s;this.missedHeartbeatCount=0,this.updateLastMessageTime(),this.emit("heartbeat",{success:1,latencyMs:r,missedCount:0}),this.l==="reconnecting"&&this.setConnectionState("connected")}else this.handleHeartbeatFailure()}catch(r){this.handleHeartbeatFailure(r instanceof Error?r:void 0)}}handleHeartbeatFailure(e){this.missedHeartbeatCount++;const t=this.connectionOptions.maxMissedHeartbeats??3;this.emit("heartbeat",{success:0,missedCount:this.missedHeartbeatCount}),this.log("warn",`Heartbeat failed (${this.missedHeartbeatCount}/${t})`),this.missedHeartbeatCount>=t&&(this.log("error","Connection lost: heartbeat threshold exceeded"),this.setConnectionState("disconnected",{reason:"heartbeat_failed",error:e||new ie("Heartbeat detection failed",ae.HeartbeatFailed,{missedCount:this.missedHeartbeatCount})}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect())}async attemptReconnect(){if(this.isReconnecting||this.isDestroyed)return;const e=this.connectionOptions.maxReconnectAttempts??5;if(e<=0)return;this.isReconnecting=1,this.reconnectAttempt=0;const t=this.connectionOptions.reconnectBaseDelay??1e3,s=this.connectionOptions.maxReconnectDelay??3e4;for(;this.reconnectAttempt<e&&!this.isDestroyed;){this.reconnectAttempt++;const r=Math.min(t*Math.pow(2,this.reconnectAttempt-1),s);if(this.setConnectionState("reconnecting",{attempt:this.reconnectAttempt,nextRetryIn:r}),await this.delay(r),this.isDestroyed)break;try{return await this.refreshWorker(),this.isReady||await this.waitForReady(this.connectionOptions.handshakeTimeout??1e4),(this.connectionOptions.appType||this.connectionOptions.appName)&&await this.publish("__register__",{appType:this.connectionOptions.appType,appName:this.connectionOptions.appName}),this.missedHeartbeatCount=0,this.setConnectionState("connected"),this.updateLastMessageTime(),this.isReconnecting=0,void this.log("log","Reconnection successful")}catch(o){this.log("warn",`Reconnection attempt ${this.reconnectAttempt} failed:`,o)}}this.isReconnecting=0,this.emit("reconnect:failed",{attempts:this.reconnectAttempt,lastError:new ie("All reconnection attempts failed",ae.ReconnectFailed,{attempts:this.reconnectAttempt})})}waitForReady(e){return new Promise((t,s)=>{if(this.isReady)return void t();const r=setTimeout(()=>{this.off("ready",o),s(new ie("Handshake timeout",ae.HandshakeFailed))},e),o=()=>{clearTimeout(r),t()};this.once("ready",o)})}delay(e){return new Promise(t=>setTimeout(t,e))}setupSwLifecycleListeners(){this.isWorkerSide||typeof navigator>"u"||(this.boundControllerChangeHandler=()=>{this.log("log","Service Worker controller changed"),this.handleControllerChange()},navigator.serviceWorker.addEventListener("controllerchange",this.boundControllerChangeHandler),this.worker&&(this.boundStateChangeHandler=()=>{var e;this.handleStateChange((e=this.worker)==null?void 0:e.state)},this.worker.addEventListener("statechange",this.boundStateChangeHandler)))}removeSwLifecycleListeners(){var e;this.boundControllerChangeHandler&&((e=navigator.serviceWorker)==null||e.removeEventListener("controllerchange",this.boundControllerChangeHandler),this.boundControllerChangeHandler=null),this.boundStateChangeHandler&&this.worker&&(this.worker.removeEventListener("statechange",this.boundStateChangeHandler),this.boundStateChangeHandler=null)}handleControllerChange(){this.l==="connected"&&this.setConnectionState("disconnected",{reason:"controller_changed"}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect()}handleStateChange(e){this.log("log","Service Worker state changed:",e),e==="redundant"&&(this.l==="connected"&&this.setConnectionState("disconnected",{reason:"sw_terminated"}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect())}static async createFromPage(e){if(!("serviceWorker"in navigator))throw new Error("Service Worker is not supported in this browser");if(e!=null&&e.swUrl)try{const l={};e.swScope&&(l.scope=e.swScope),await navigator.serviceWorker.register(e.swUrl,l)}catch(l){throw console.error("[ServiceWorkerChannel] Failed to register Service Worker:",l),l}const t=(await navigator.serviceWorker.ready).active||navigator.serviceWorker.controller;if(!t)throw new Error("No active Service Worker found");const s=new m(t,e);s.connectionOptions=e||{};const r=(e==null?void 0:e.appType)||(e==null?void 0:e.appName);let o=0,a=0;const i=async()=>{if(!a){a=1;try{await s.publish("__register__",{appType:e==null?void 0:e.appType,appName:e==null?void 0:e.appName}),o=1,s.updateLastMessageTime()}catch(l){console.warn("[ServiceWorkerChannel] Auto-registration failed:",l)}finally{a=0}}},c=()=>{s.setConnectionState("connected"),s.updateLastMessageTime(),s.startHeartbeat(),s.setupSwLifecycleListeners()};return r?s.isReady?(i(),c()):s.once("ready",()=>{i(),c()}):s.isReady?c():s.once("ready",c),(e==null?void 0:e.autoReconnect)!=0&&s.onBroadcast("__sw-activated__",async({data:l})=>{s.emit("sw-activated",{version:l==null?void 0:l.version}),s.setConnectionState("disconnected",{reason:"controller_changed"}),r&&(await s.refreshWorker(),o=0,await i()),s.setConnectionState("connected"),s.updateLastMessageTime()}),s.on("message:received",({isResponse:l})=>{l&&s.updateLastMessageTime()}),s}static createFromWorker(e,t){return new m(e,{...t,isWorkerSide:1})}static createFromEvent(e,t){const s=e.source;if(!(s!=null&&s.id))throw new Error("Invalid message event: no client source");return m.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(m,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(m,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(m,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(m,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(m,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(m,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(m,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(m,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(m,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(m,"globalMessageHandler",{enumerable:1,configurable:1,writable:1,value:n=>{const e=n.source,t=e==null?void 0:e.id;if(!t)return;const s=m.channelsByClientId.get(t);s?s.handleMessage(n):m.unknownClientCallback&&m.unknownClientCallback(t,n)}});function gr(n,e,t){return Promise.race([n,new Promise(s=>setTimeout(()=>s(t),e))])}const C={THUMBNAIL_GENERATE:"thumbnail:generate",CRASH_SNAPSHOT:"crash:snapshot",CRASH_HEARTBEAT:"crash:heartbeat",CONSOLE_REPORT:"console:report",DEBUG_GET_STATUS:"debug:getStatus",DEBUG_ENABLE:"debug:enable",DEBUG_DISABLE:"debug:disable",DEBUG_GET_LOGS:"debug:getLogs",DEBUG_CLEAR_LOGS:"debug:clearLogs",DEBUG_GET_CONSOLE_LOGS:"debug:getConsoleLogs",DEBUG_CLEAR_CONSOLE_LOGS:"debug:clearConsoleLogs",DEBUG_GET_POSTMESSAGE_LOGS:"debug:getPostMessageLogs",DEBUG_CLEAR_POSTMESSAGE_LOGS:"debug:clearPostMessageLogs",DEBUG_GET_CRASH_SNAPSHOTS:"debug:getCrashSnapshots",DEBUG_CLEAR_CRASH_SNAPSHOTS:"debug:clearCrashSnapshots",DEBUG_GET_LLM_API_LOGS:"debug:getLLMApiLogs",DEBUG_GET_LLM_API_LOG_BY_ID:"debug:getLLMApiLogById",DEBUG_CLEAR_LLM_API_LOGS:"debug:clearLLMApiLogs",DEBUG_DELETE_LLM_API_LOGS:"debug:deleteLLMApiLogs",DEBUG_GET_CACHE_ENTRIES:"debug:getCacheEntries",DEBUG_GET_CACHE_STATS:"debug:getCacheStats",DEBUG_EXPORT_LOGS:"debug:exportLogs",CDN_GET_STATUS:"cdn:getStatus",CDN_RESET_STATUS:"cdn:resetStatus",CDN_HEALTH_CHECK:"cdn:healthCheck",UPGRADE_GET_STATUS:"upgrade:getStatus",UPGRADE_FORCE:"upgrade:force",CACHE_DELETE:"cache:delete",PING:"ping"},F={CACHE_IMAGE_CACHED:"cache:imageCached",CACHE_IMAGE_CACHE_FAILED:"cache:imageCacheFailed",CACHE_DELETED:"cache:deleted",CACHE_QUOTA_WARNING:"cache:quotaWarning",SW_NEW_VERSION_READY:"sw:newVersionReady",SW_ACTIVATED:"sw:activated",SW_UPDATED:"sw:updated",CONSOLE_LOG:"console:log",DEBUG_LOG:"debug:log",DEBUG_LLM_LOG:"debug:llmLog",DEBUG_STATUS_CHANGED:"debug:statusChanged",DEBUG_NEW_CRASH_SNAPSHOT:"debug:newCrashSnapshot",POSTMESSAGE_LOG_BATCH:"postmessage:logBatch"};let Pt={};function fr(n){Pt={...Pt,...n}}function D(){return Pt}const Te=class Te{constructor(e){this.channels=new Map,this.onDebugClientCountChanged=null,this.postMessageLogBuffer=[],this.postMessageLogTimer=null,this.POSTMESSAGE_LOG_BATCH_INTERVAL=500,this.sw=e,this.channels.clear(),m.enableGlobalRouting((t,s)=>{var o;this.ensureChannel(t);const r=(o=this.channels.get(t))==null?void 0:o.channel;r&&r.handleMessage(s)}),setInterval(()=>{this.cleanupDisconnectedClients().catch(()=>{}),this.cleanupStalePendingRequests().catch(()=>{})},6e4)}async cleanupStalePendingRequests(){try{await yn.cleanupStalePendingToolRequests()}catch(e){console.warn("[ChannelManager] Failed to cleanup stale pending requests:",e)}}setDebugClientCountChangedCallback(e){this.onDebugClientCountChanged=e}getDebugClientCount(){let e=0;for(const t of this.channels.values())t.isDebugClient&&e++;return e}async isDebugClient(e){try{const t=await this.sw.clients.get(e);if(t&&t.url)return t.url.includes("sw-debug")}catch{}return!1}static getInstance(e){return Te.instance||(Te.instance=new Te(e)),Te.instance}ensureChannel(e){let t=this.channels.get(e);return t||(t={channel:m.createFromWorker(e,{timeout:12e4,subscribeMap:this.createSubscribeMap(e),log:{log:()=>{},warn:()=>{},error:()=>{}}}),clientId:e,createdAt:Date.now(),isDebugClient:!1},this.channels.set(e,t),this.checkAndUpdateDebugClient(e)),t.channel}async checkAndUpdateDebugClient(e){var r;const t=await this.isDebugClient(e),s=this.channels.get(e);s&&t&&(s.isDebugClient=!0,(r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}hasAnyClientChannel(){return this.channels.size>0}unwrapRpcData(e){return e&&typeof e=="object"&&"cmdname"in e?e.data:e}broadcastPostMessageLog(e){if(!e)return;const s=Xe().find(r=>r.id===e);s&&this.sendPostMessageLog(s)}wrapRpcHandler(e,t,s){return async r=>{var l;const o=this.unwrapRpcData(r),a=Date.now(),i=r==null?void 0:r.requestId,c=Rt()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const h=Lt(`RPC:${e}`,{params:o,requestId:i},t);this.broadcastPostMessageLog(h)}try{const h=await s(o);try{JSON.stringify(h)}catch(d){throw console.error(`[SW wrapRpcHandler] ${e} result serialization failed:`,d),new Error(`Result serialization failed: ${d}`)}if(c&&i){const d=Mt(i,{result:h},Date.now()-a);d&&this.broadcastPostMessageLog(d)}return h}catch(h){if(console.error(`[SW wrapRpcHandler] ${e} error:`,h),c&&i){const d=Mt(i,null,Date.now()-a,String(h));d&&this.broadcastPostMessageLog(d)}throw h}}}createSubscribeMap(e){return{[C.THUMBNAIL_GENERATE]:this.wrapRpcHandler(C.THUMBNAIL_GENERATE,e,t=>this.handleThumbnailGenerate(t)),[C.CRASH_SNAPSHOT]:async t=>{const s=this.unwrapRpcData(t);return this.handleCrashSnapshot(s)},[C.CRASH_HEARTBEAT]:async t=>{const s=this.unwrapRpcData(t);return this.handleHeartbeat(s)},[C.CONSOLE_REPORT]:async t=>{const s=this.unwrapRpcData(t);return this.handleConsoleReport(s)},[C.DEBUG_GET_STATUS]:async()=>this.handleDebugGetStatus(),[C.DEBUG_ENABLE]:async()=>this.handleDebugEnable(),[C.DEBUG_DISABLE]:async()=>this.handleDebugDisable(),[C.DEBUG_GET_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLogs(s)},[C.DEBUG_CLEAR_LOGS]:async()=>this.handleDebugClearLogs(),[C.DEBUG_GET_CONSOLE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetConsoleLogs(s)},[C.DEBUG_CLEAR_CONSOLE_LOGS]:async()=>this.handleDebugClearConsoleLogs(),[C.DEBUG_GET_POSTMESSAGE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetPostMessageLogs(s)},[C.DEBUG_CLEAR_POSTMESSAGE_LOGS]:async()=>this.handleDebugClearPostMessageLogs(),[C.DEBUG_GET_CRASH_SNAPSHOTS]:async()=>this.handleDebugGetCrashSnapshots(),[C.DEBUG_CLEAR_CRASH_SNAPSHOTS]:async()=>this.handleDebugClearCrashSnapshots(),[C.DEBUG_GET_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogs(s)},[C.DEBUG_GET_LLM_API_LOG_BY_ID]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogById(s==null?void 0:s.logId)},[C.DEBUG_CLEAR_LLM_API_LOGS]:async()=>this.handleDebugClearLLMApiLogs(),[C.DEBUG_DELETE_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugDeleteLLMApiLogs(s)},[C.DEBUG_GET_CACHE_ENTRIES]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetCacheEntries(s)},[C.DEBUG_GET_CACHE_STATS]:async()=>this.handleDebugGetCacheStats(),[C.DEBUG_EXPORT_LOGS]:async()=>this.handleDebugExportLogs(),[C.CDN_GET_STATUS]:async()=>this.handleCDNGetStatus(),[C.CDN_RESET_STATUS]:async()=>this.handleCDNResetStatus(),[C.CDN_HEALTH_CHECK]:async()=>this.handleCDNHealthCheck(),[C.UPGRADE_GET_STATUS]:async()=>this.handleUpgradeGetStatus(),[C.UPGRADE_FORCE]:async()=>this.handleUpgradeForce(),[C.CACHE_DELETE]:async t=>{const s=this.unwrapRpcData(t);return this.handleCacheDelete(s)},[C.PING]:async()=>this.handlePing()}}async handleThumbnailGenerate(e){try{const{url:t,mediaType:s,blob:r,mimeType:o,sizes:a}=e,{generateThumbnailAsync:i}=await Promise.resolve().then(()=>j),c=new Blob([r],{type:o||(s==="video"?"video/mp4":"image/png")});return i(c,t,s,a),{success:!0}}catch(t){return console.error("[SWChannelManager] Thumbnail generation failed:",t),{success:!1,error:t.message}}}async handleCrashSnapshot(e){var t,s;try{return await((s=(t=D()).saveCrashSnapshot)==null?void 0:s.call(t,e.snapshot)),{success:!0}}catch(r){return console.error("[SWChannelManager] Crash snapshot save failed:",r),{success:!1,error:r.message}}}async handleHeartbeat(e){return{success:!0}}serializeLogArg(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)}async handleConsoleReport(e){var t,s;try{const r=e.logArgs??[],a=(Array.isArray(r)?r.map(i=>this.serializeLogArg(i)):[this.serializeLogArg(r)]).join(" ");return(s=(t=D()).addConsoleLog)==null||s.call(t,{logLevel:e.logLevel,logMessage:a||"-"}),{success:!0}}catch(r){return{success:!1,error:r.message}}}async handleDebugGetStatus(){var e;try{const t=D(),s=((e=t.getDebugStatus)==null?void 0:e.call(t))||{},r=t.getCacheStats?await t.getCacheStats():void 0;return{...s,enabled:s.debugModeEnabled,cacheStats:r}}catch{return{debugModeEnabled:!1}}}async handleDebugEnable(){var e,t;try{const s=D();await((e=s.enableDebugMode)==null?void 0:e.call(s));const r=((t=s.getDebugStatus)==null?void 0:t.call(s))||{};return this.sendDebugStatusChanged(!0),{success:!0,status:r}}catch{return{success:!1}}}async handleDebugDisable(){var e,t;try{const s=D();await((e=s.disableDebugMode)==null?void 0:e.call(s));const r=((t=s.getDebugStatus)==null?void 0:t.call(s))||{};return this.sendDebugStatusChanged(!1),{success:!0,status:r}}catch{return{success:!1}}}async handleDebugGetLogs(e){var t,s;try{const r=D(),{limit:o=100,offset:a=0,filter:i}=e||{},c=(((t=r.getInternalFetchLogs)==null?void 0:t.call(r))||[]).map(b=>({...b,type:"fetch"})),l=((s=r.getDebugLogs)==null?void 0:s.call(r))||[],h=new Map;for(const b of l){const p=b.id;typeof p=="string"&&h.set(p,b)}for(const b of c){const p=b.id;typeof p=="string"&&h.set(p,b)}let d=Array.from(h.values()).sort((b,p)=>p.timestamp-b.timestamp);return i&&(i.type&&(d=d.filter(b=>b.type===i.type)),i.status&&(d=d.filter(b=>b.status===i.status))),{logs:d.slice(a,a+o),total:d.length,offset:a,limit:o}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||100}}}async handleDebugClearLogs(){var e,t;try{return(t=(e=D()).clearDebugLogs)==null||t.call(e),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){var t,s;try{const{limit:r=500,offset:o=0,filter:a}=e||{};let i=await(((s=(t=D()).loadConsoleLogsFromDB)==null?void 0:s.call(t))||Promise.resolve([]));if(a&&(a.logLevel&&(i=i.filter(l=>l.logLevel===a.logLevel)),a.search)){const l=a.search.toLowerCase();i=i.filter(h=>{var d,u;return((d=h.logMessage)==null?void 0:d.toLowerCase().includes(l))||((u=h.logStack)==null?void 0:u.toLowerCase().includes(l))})}return{logs:i.slice(o,o+r),total:i.length,offset:o,limit:r}}catch(r){return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||500,error:String(r)}}}async handleDebugClearConsoleLogs(){var e,t;try{const s=D();return(e=s.clearConsoleLogs)==null||e.call(s),await((t=s.clearAllConsoleLogs)==null?void 0:t.call(s)),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>vt),{limit:r=200,offset:o=0,filter:a}=e||{};let i=t();if(a&&(a.direction&&(i=i.filter(l=>l.direction===a.direction)),a.messageType)){const l=a.messageType.toLowerCase();i=i.filter(h=>{var d;return(d=h.messageType)==null?void 0:d.toLowerCase().includes(l)})}return{logs:i.slice(o,o+r),total:i.length,offset:o,limit:r,stats:s()}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||200}}}async handleDebugClearPostMessageLogs(){try{const{clearLogs:e}=await Promise.resolve().then(()=>vt);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){var e,t;try{const s=await(((t=(e=D()).getCrashSnapshots)==null?void 0:t.call(e))||Promise.resolve([]));return{snapshots:s,total:s.length}}catch(s){return{snapshots:[],total:0,error:String(s)}}}async handleDebugClearCrashSnapshots(){var e,t;try{return await((t=(e=D()).clearCrashSnapshots)==null?void 0:t.call(e)),{success:!0}}catch{return{success:!1}}}async handleDebugGetLLMApiLogs(e){try{const t=typeof(e==null?void 0:e.page)=="number"?e.page:Number(e==null?void 0:e.page)||1,s=typeof(e==null?void 0:e.pageSize)=="number"?e.pageSize:Number(e==null?void 0:e.pageSize)||20,r={taskType:typeof(e==null?void 0:e.taskType)=="string"?e.taskType:void 0,status:typeof(e==null?void 0:e.status)=="string"?e.status:void 0},{getLLMApiLogsPaginated:o}=await Promise.resolve().then(()=>Ee);return await o(t,s,r)}catch(t){return console.error("[SWChannelManager] handleDebugGetLLMApiLogs error:",t),{logs:[],total:0,page:1,pageSize:20,totalPages:0,error:String(t)}}}async handleDebugGetLLMApiLogById(e){try{if(!e)return{log:null,error:"Missing logId"};const{getLLMApiLogById:t}=await Promise.resolve().then(()=>Ee);return{log:await t(e)}}catch(t){return console.error("[SWChannelManager] handleDebugGetLLMApiLogById error:",t),{log:null,error:String(t)}}}async handleDebugClearLLMApiLogs(){try{const{clearAllLLMApiLogs:e}=await Promise.resolve().then(()=>Ee);return await e(),{success:!0}}catch{return{success:!1}}}async handleDebugDeleteLLMApiLogs(e){try{if(!(e!=null&&e.logIds)||e.logIds.length===0)return{success:!1,deletedCount:0};const{deleteLLMApiLogs:t}=await Promise.resolve().then(()=>Ee);return{success:!0,deletedCount:await t(e.logIds)}}catch{return{success:!1,deletedCount:0}}}async handleDebugGetCacheEntries(e){var t,s;try{const{cacheName:r=((s=(t=D()).getImageCacheName)==null?void 0:s.call(t))||"drawnix-images",limit:o=50,offset:a=0}=e||{},i=await caches.open(r),c=await i.keys(),l=[];for(let h=a;h<Math.min(a+o,c.length);h++){const d=c[h],u=await i.match(d);if(u){const b=u.headers.get("sw-cache-date"),p=u.headers.get("sw-cache-created-at")||b,g=u.headers.get("sw-image-size")||u.headers.get("content-length");l.push({url:d.url,cacheDate:b?parseInt(b):void 0,cacheCreatedAt:p?parseInt(p):void 0,size:g?parseInt(g):void 0})}}return{cacheName:r,entries:l,total:c.length,offset:a,limit:o}}catch(r){return{cacheName:(e==null?void 0:e.cacheName)||"",entries:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||50,error:String(r)}}}async handleDebugGetCacheStats(){try{const e=await caches.keys(),t=[];let s=0,r=0;for(const o of e){const a=await caches.open(o),i=await a.keys();let c=0;for(const l of i){const h=await a.match(l);if(h){const d=h.headers.get("content-length");d&&(c+=parseInt(d))}}t.push({name:o,count:i.length,size:c}),s+=i.length,r+=c}return{stats:{caches:t,totalCount:s,totalSize:r}}}catch(e){return{stats:{caches:[],totalCount:0,totalSize:0},error:String(e)}}}async handleDebugExportLogs(){var e,t,s,r;try{const o=D(),{getAllLogs:a}=await Promise.resolve().then(()=>vt),i=await(((e=o.loadConsoleLogsFromDB)==null?void 0:e.call(o))||Promise.resolve([])),c=a(),l=((t=o.getDebugLogs)==null?void 0:t.call(o))||[];return{exportTime:new Date().toISOString(),swVersion:((s=o.getAppVersion)==null?void 0:s.call(o))||"unknown",status:((r=o.getDebugStatus)==null?void 0:r.call(o))||{},fetchLogs:l,consoleLogs:i,postmessageLogs:c}}catch{return{exportTime:new Date().toISOString(),swVersion:"unknown",status:{},fetchLogs:[],consoleLogs:[],postmessageLogs:[]}}}async handleCDNGetStatus(){var e,t;try{return{status:((t=(e=D()).getCDNStatusReport)==null?void 0:t.call(e))||{}}}catch{return{status:{}}}}async handleCDNResetStatus(){var e,t;try{return(t=(e=D()).resetCDNStatus)==null||t.call(e),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){var e;try{const t=D(),s=t.performHealthCheck?await t.performHealthCheck(((e=t.getAppVersion)==null?void 0:e.call(t))||"unknown"):new Map;return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){var e,t;try{return{version:((t=(e=D()).getAppVersion)==null?void 0:t.call(e))||"unknown"}}catch{return{version:"unknown"}}}async handleUpgradeForce(){var e,t;try{return self.skipWaiting(),this.sendSWUpdated(((t=(e=D()).getAppVersion)==null?void 0:t.call(e))||"unknown"),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){var t,s;try{return await((s=(t=D()).deleteCacheByUrl)==null?void 0:s.call(t,e.url)),this.sendCacheDeleted(e.url),{success:!0}}catch(r){return{success:!1,error:String(r)}}}async handlePing(){return{success:!0}}broadcastToAll(e,t){this.channels.forEach(s=>{s.channel.broadcast(e,t)})}broadcastToOthers(e,t,s){this.channels.forEach(r=>{r.clientId!==s&&r.channel.broadcast(e,t)})}publishToClient(e,t,s){const r=this.channels.get(e);r&&r.channel.broadcast(t,s)}sendCacheImageCached(e,t,s){this.broadcastToAll(F.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheImageCacheFailed(e,t){this.broadcastToAll(F.CACHE_IMAGE_CACHE_FAILED,{url:e,error:t})}sendCacheDeleted(e){this.broadcastToAll(F.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(F.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(F.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(F.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(F.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(F.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(F.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(F.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(F.DEBUG_LLM_LOG,{log:e})}sendPostMessageLog(e){this.postMessageLogBuffer.push(e),this.postMessageLogTimer||(this.postMessageLogTimer=setTimeout(()=>{this.flushPostMessageLogs()},this.POSTMESSAGE_LOG_BATCH_INTERVAL))}flushPostMessageLogs(){if(this.postMessageLogTimer=null,this.postMessageLogBuffer.length===0)return;const e=this.postMessageLogBuffer;this.postMessageLogBuffer=[],this.broadcastToAll(F.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(F.DEBUG_NEW_CRASH_SNAPSHOT,{snapshot:e})}async requestVideoThumbnail(e,t=3e4,s){const r=Array.from(this.channels.values()).sort((o,a)=>o.isDebugClient===a.isDebugClient?a.createdAt-o.createdAt:o.isDebugClient?1:-1);if(r.length===0)return null;for(const o of r)try{const a=await gr(o.channel.call("thumbnail:generate",{url:e,maxSize:s}),t,"Video thumbnail generation timeout");if(!a||a.ret!==0)continue;const i=a.data;if(i!=null&&i.error||!(i!=null&&i.thumbnailUrl))continue;return i.thumbnailUrl}catch{continue}return null}getConnectedClients(){return Array.from(this.channels.keys())}getConnectedClientCount(){return this.channels.size}async cleanupDisconnectedClients(){var r;const e=await this.sw.clients.matchAll({type:"window"}),t=new Set(e.map(o=>o.id));let s=!1;for(const[o,a]of this.channels)t.has(o)||(a.isDebugClient&&(s=!0),this.channels.delete(o));s&&((r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}};Te.instance=null;let kt=Te,Je=null;function pr(n){return Je||(Je=kt.getInstance(n)),Je}function v(){return Je}function Ze(n){Cn(n)}const mr=[];let Rn=!1;function We(n){Rn=n}function Ot(){return Rn}function Wt(){return[...mr]}const br=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:Wt,isDebugFetchEnabled:Ot,setDebugFetchEnabled:We},Symbol.toStringTag,{value:"Module"})),yr=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),k={packageName:"aitu-app",healthCheckInterval:300*1e3,degradeTimeout:60*1e3,failThreshold:3,fetchTimeout:1500,backgroundFetchTimeout:8e3,localFetchTimeout:5e3,preferenceCacheExpiry:3600*1e3,preferenceCacheName:"drawnix-cdn-v1",preferenceCacheKey:typeof location<"u"?new URL("/__sw__/cdn-preference",location.origin).href:"https://opentu.local/__sw__/cdn-preference"},wr={jsdelivr:{baseTimeout:60*1e3,maxTimeout:300*1e3}},et=[{name:"jsdelivr",urlTemplate:"https://cdn.jsdelivr.net/npm/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:1}],be=new Map;let te=null,Bt=!1,tt=null;function Ln(n=!1){n&&be.clear(),et.forEach(e=>{be.has(e.name)||be.set(e.name,{name:e.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}Ln();function Sr(n){return n==="jsdelivr"||n==="local"}function Mn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!Sr(t)||typeof s!="string"||s.trim()==="")return null;const r=Number(e.latency),o=Number(e.timestamp);return{cdn:t,version:s.trim(),latency:Number.isFinite(r)&&r>=0?r:0,timestamp:Number.isFinite(o)&&o>0?o:Date.now()}}function vn(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=k.preferenceCacheExpiry}async function Cr(){if(typeof caches>"u")return null;try{const e=await(await caches.open(k.preferenceCacheName)).match(k.preferenceCacheKey);return e!=null&&e.ok?Mn(await e.json()):null}catch(n){return console.warn("[CDN Fallback] Failed to read persisted CDN preference:",n),null}}async function Nt(){Bt||(tt||(tt=(async()=>{te=await Cr(),Bt=!0,tt=null})()),await tt)}async function In(n){if(te=Mn(n),Bt=!0,!(typeof caches>"u"))try{const e=await caches.open(k.preferenceCacheName);if(!te){await e.delete(k.preferenceCacheKey);return}await e.put(k.preferenceCacheKey,new Response(JSON.stringify(te),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}}))}catch(e){console.warn("[CDN Fallback] Failed to persist CDN preference:",e)}}function xt(n){const e=be.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now(),e.lastFailureReason=void 0)}function ce(n,e){const t=be.get(n);if(t)if(t.failCount++,t.lastCheckTime=Date.now(),t.lastFailureReason=e,t.failCount>=k.failThreshold){t.isHealthy=!1;const s=kn(t);console.warn(`[CDN Fallback] ${n} marked as unhealthy after ${t.failCount} failures, cooldown=${s.cooldownMs}ms, reason=${e??"unknown"}`)}else console.warn(`[CDN Fallback] ${n} failure count=${t.failCount}, reason=${e??"unknown"}`)}function Pn(n,e){const t=wr[n]??{baseTimeout:k.degradeTimeout,maxTimeout:k.degradeTimeout},r=2**Math.max(0,e-k.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function kn(n){const e=Pn(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function Ft(n,e={}){const t=be.get(n);if(!t)return!1;if(t.isHealthy||e.ignoreCooldown)return!0;const s=Date.now(),r=Pn(n,t.failCount);return s-t.lastCheckTime>r}function Er(n,e={}){const t=te;return!t||!vn(t,n)||t.cdn==="local"?null:Ft(t.cdn,e)?t.cdn:null}function On(n,e={}){const t=n?Er(n,e):null;return et.filter(s=>s.enabled&&Ft(s.name,e)).sort((s,r)=>t&&s.name===t&&r.name!==t?-1:t&&r.name===t&&s.name!==t?1:s.priority-r.priority)}function Wn(n){const e=String(n||"").trim();if(!e)return e;let t=e;try{if(/^https?:\/\//i.test(t)){const s=new URL(t);t=`${s.pathname}${s.search}`}}catch{}return t=t.replace(/^\/?npm\/aitu-app@[^/]+\//,"/").replace(/^\/?aitu-app@[^/]+\//,"/"),t}function Bn(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function Tr(n,e){const t=String(e||"").trim();if(!t)return null;let s=t;try{if(/^https?:\/\//i.test(s)){const o=new URL(s);s=`${o.pathname}${o.search}`}}catch{}const r=s.startsWith("/")?s:`/${s}`;return/^\/npm\/(?!aitu-app@)[^/]+@[^/]+\//.test(r)&&n.name==="jsdelivr"?`https://cdn.jsdelivr.net${r}`:null}function Gt(n,e,t){const s=Tr(n,t);if(s)return s;const r=Wn(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function Ut(n,e=k.fetchTimeout){const t=new AbortController,s=setTimeout(()=>t.abort(),e);try{return await fetch(n,{signal:t.signal,cache:"no-store"})}finally{clearTimeout(s)}}function Ht(n,e){const t=Wn(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function Nn(n,e,t){try{const s=Ht(e,n),r=await Ut(s,t);return r.ok?{response:r,source:"local"}:(console.warn(`[CDN Fallback] Local server returned ${r.status}`),null)}catch(s){return console.warn("[CDN Fallback] Local server failed:",s),null}}async function xn(n,e,t,s){for(const r of n){const o=Gt(r,e,t);try{const a=await Ut(o,s);if(!a.ok){ce(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await _r(a,r.name))continue;return xt(r.name),{response:a,source:r.name,targetUrl:o}}catch(a){const i=a instanceof Error&&a.name==="AbortError"?"timeout":"network-error";ce(r.name,i),console.warn(`[CDN Fallback] ${r.name} failed:`,a)}}return null}async function _r(n,e){var i;const t=n.headers.get("Content-Type")||"";if(!(t.includes("javascript")||t.includes("css")||t.includes("json")||t.includes("font")||t.includes("image")||t.includes("woff")||t.includes("application/octet-stream")))return ce(e,`invalid-content-type:${t}`),console.warn(`[CDN Fallback] ${e} invalid Content-Type: ${t}`),!1;const r=parseInt(n.headers.get("Content-Length")||"0",10),o=t.includes("javascript")||t.includes("css")||t.includes("json");if(o&&r>0&&r<50)return ce(e,`response-too-small:${r}`),console.warn(`[CDN Fallback] ${e} response too small: ${r} bytes`),!1;const a=n.clone();try{const c=(i=a.body)==null?void 0:i.getReader();if(c){const{value:l}=await c.read();if(c.cancel(),l){const h=new TextDecoder().decode(l.slice(0,200)),d=h.includes("<!DOCTYPE")||h.includes("<html")||h.includes("<HTML")||h.includes("Not Found")||h.includes("404");if(o&&d)return ce(e,"html-error-page"),console.warn(`[CDN Fallback] ${e} returned HTML instead of ${t}`),!1}}}catch{}return!0}async function qt(n,e,t,s={}){if(yr)return null;await Nt();const{preferLocal:r=!1,localTimeout:o=k.localFetchTimeout,requestKind:a="interactive-runtime"}=s,i=a==="background-prefetch",c=s.cdnTimeout??(a==="background-prefetch"?k.backgroundFetchTimeout:k.fetchTimeout);if(r){const u=await Nn(n,t,o);if(u)return{...u,targetUrl:Ht(t,n)}}const l=On(e,{ignoreCooldown:i}),h=await xn(l,e,n,c);if(h)return h;if(!r){const u=await Nn(n,t,o);if(u)return{...u,targetUrl:Ht(t,n)}}const d=et.filter(u=>u.enabled&&!l.some(b=>b.name===u.name));if(d.length>0){console.warn(`[CDN Fallback] Local origin failed, forcing CDN recovery probe for: ${n}`);const u=await xn(d,e,n,c);if(u)return u}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function jt(n){await Nt();const e=new Map;for(const t of et){if(!t.enabled)continue;const s=Gt(t,n,t.healthCheckPath);try{const r=await Ut(s,5e3),o=r.ok;e.set(t.name,o),o?xt(t.name):ce(t.name,`status:${r.status}`)}catch{e.set(t.name,!1),ce(t.name,"health-check-failed")}}return e}function nt(){const n=vn(te)?te==null?void 0:te.cdn:null;return Array.from(be.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,...kn(t)}))}function zt(){Ln(!0)}const Dr=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:Gt,ensureCDNPreferenceLoaded:Nt,extractVersionFromCDNPath:Bn,fetchFromCDNWithFallback:qt,getAvailableCDNs:On,getCDNStatusReport:nt,isCDNAvailable:Ft,markCDNFailure:ce,markCDNSuccess:xt,performHealthCheck:jt,resetCDNStatus:zt,setCDNPreference:In},Symbol.toStringTag,{value:"Module"}));function Fn(n){return n==="/"||n==="/index.html"}const Ar=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"],Rr="_lazy_chunk_retry",Lr="_t",Mr=600*1e3;function vr(n,e){return Fn(e)?!0:n==="navigate"&&!e.endsWith(".html")}function Gn(n){return Fn(n)?!0:Ar.some(e=>n.endsWith(e))}function Ir(n){return!Gn(n)}function Pr(n,e=Date.now()){const t=new URLSearchParams(n);if(t.get(Rr)!=="1")return!1;const s=Number(t.get(Lr));return!Number.isFinite(s)||s<=0?!0:e-s<=Mr}const O=self;pr(O).setDebugClientCountChangedCallback(Xr);const ne={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function st(n){var t;const e=((t=n[0])==null?void 0:t.toString())||"";return!!(e.includes("[ServiceWorkerChannel]")||e.includes("[BaseChannel]")||e.includes("Invalid message structure")||e.includes("broadcast:")||e.includes("publish:")||e.includes("subscribe:")||e.includes("[Main]")||e.includes("[SW Console Capture]")||e.includes("[SWChannelManager]")&&(e.includes("broadcast")||e.includes("sendConsoleLog")))}function kr(){console.log=(...n)=>{ne.log(...n),Ot()&&!st(n)&&rt("log",n)},console.info=(...n)=>{ne.info(...n),Ot()&&!st(n)&&rt("info",n)},console.warn=(...n)=>{ne.warn(...n),st(n)||rt("warn",n)},console.error=(...n)=>{ne.error(...n),st(n)||rt("error",n)}}function Or(n){let e;const t=[];for(const r of n)try{const o=r;if(r instanceof Error||r&&typeof r=="object"&&typeof o.message=="string")e=o.stack||e,t.push(`${o.name||"Error"}: ${o.message||""}`);else if(typeof r=="object"&&r!==null){const a=JSON.stringify(r);t.push(a==="{}"?String(r):a)}else t.push(String(r))}catch{t.push(String(r))}return{message:t.join(" ")||"(empty)",stack:e}}function rt(n,e){try{const{message:t,stack:s}=Or(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof $t=="function"&&$t({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){ne.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let $t=null;kr(),Promise.resolve().then(()=>Ee).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=v();t&&t.sendDebugLLMLog(e)})});const w="0.9.2",ot=new URL("./",self.location.href),Vt=ot.pathname,Kt=`drawnix-v${w}`,A="drawnix-images",_e=`drawnix-static-v${w}`,at="drawnix-fonts",le="sw-cache-date",ye="sw-cache-created-at",Xt="x-sw-source",Yt="x-sw-revision",Qt="x-sw-app-version",Un="x-sw-fetch-target",Wr="ServiceWorkerDB",Br=2;fr({saveCrashSnapshot:Ts,getDebugStatus:ns,addConsoleLog:en,getDebugLogs:tn,clearDebugLogs:ss,clearConsoleLogs:rs,enableDebugMode:nn,disableDebugMode:sn,loadConsoleLogsFromDB:Jn,clearAllConsoleLogs:es,getCrashSnapshots:_s,clearCrashSnapshots:Ds,getCacheStats:As,deleteCacheByUrl:dn,getInternalFetchLogs:Wt,getCDNStatusReport:nt,resetCDNStatus:zt,performHealthCheck:jt,getAppVersion:()=>w,getImageCacheName:()=>A,requestVideoThumbnail:async(n,e,t)=>{const s=v();return!s||s.getConnectedClientCount()===0?null:s.requestVideoThumbnail(n,e,t)}});const De="failedDomains",Ae="versionState",Hn="app-version-state",qn="/__aitu_cache__/",jn="/__aitu_generated__/audio/",Nr="/asset-library/",Be=location.hostname==="localhost"||location.hostname==="127.0.0.1";function H(n){return new URL(n.replace(/^\//,""),ot)}function Re(n){return Vt!=="/"&&n.startsWith(Vt)?`/${n.slice(Vt.length)}`:n}const xr=[{hostname:"google.datas.systems",pathPattern:"response_images",fallbackDomain:"cdn.i666.fun"},{hostname:"googlecdn2.datas.systems",pathPattern:"response_images",fallbackDomain:"googlecdn2.i666.fun"},{hostname:"filesystem.i666.fun",pathPattern:"response_images",fallbackDomain:"filesystem.i666.fun"}],Fr=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,Gr=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Jt=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,Ur=new Set(["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","_poster_retry","rand","_force","bypass_sw","direct_fetch","thumbnail","expires","signature","sig","token","policy","x-amz-algorithm","x-amz-credential","x-amz-date","x-amz-expires","x-amz-security-token","x-amz-signature","x-amz-signedheaders","x-goog-algorithm","x-goog-credential","x-goog-date","x-goog-expires","x-goog-signature","x-goog-signedheaders","ossaccesskeyid","x-oss-security-token","x-oss-signature-version","x-oss-credential","x-oss-date","x-oss-expires","x-oss-signature"]);function Ne(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)Ur.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const q=new Map,we=new Map,zn=30*1e3,ue=new Map,$n=300*1e3,Vn=500,xe=new Map,G=new Map,Hr=300*1e3,Kn=10,Le=new Set,Me=new Set,qr=3600*1e3,Zt=new Map;function Xn(n){Me.add(n),Zt.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function jr(n){if(!Me.has(n))return!1;const e=Zt.get(n);return e&&Date.now()-e>qr?(Me.delete(n),Zt.delete(n),!1):!0}const Q=[],Yn=7,V=[],zr=500;let I=!1;function P(n){if(!I)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return V.unshift(t),V.length>zr&&V.pop(),Qn(t),e}function R(n,e){if(!I||!n)return;const t=V.find(s=>s.id===n);t&&(Object.assign(t,e),Qn(t))}function Qn(n){const e=v();e&&e.sendDebugLog(n)}function it(){return new Promise((n,e)=>{const t=indexedDB.open("ConsoleLogDB",1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains("logs")){const o=r.createObjectStore("logs",{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("logLevel","logLevel",{unique:!1})}}})}async function $r(n){try{const e=await it(),t=e.transaction(["logs"],"readwrite");return t.objectStore("logs").add(n),new Promise((r,o)=>{t.oncomplete=()=>{e.close(),r()},t.onerror=()=>{e.close(),o(t.error)}})}catch(e){console.warn("Service Worker: 无法保存控制台日志:",e)}}async function Jn(){try{await Zn();const n=await it(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-Yn*24*60*60*1e3;return new Promise((o,a)=>{const i=s.openCursor(null,"prev"),c=[];i.onsuccess=()=>{const l=i.result;if(l){const h=l.value;h.timestamp>=r&&c.push(h),l.continue()}else n.close(),o(c)},i.onerror=()=>{n.close(),a(i.error)}})}catch(n){return console.warn("Service Worker: 无法加载控制台日志:",n),[]}}async function Zn(){try{const n=await it(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-Yn*24*60*60*1e3,o=IDBKeyRange.upperBound(r);return new Promise((a,i)=>{const c=s.openCursor(o);let l=0;c.onsuccess=()=>{const h=c.result;h?(h.delete(),l++,h.continue()):(n.close(),l>0,a(l))},c.onerror=()=>{n.close(),i(c.error)}})}catch(n){return console.warn("Service Worker: 无法清理过期日志:",n),0}}async function es(){try{const n=await it(),e=n.transaction(["logs"],"readwrite");return e.objectStore("logs").clear(),new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("Service Worker: 无法清空控制台日志:",n)}}const ts=500;function en(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(I||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};$r(r),Q.unshift(r),Q.length>ts&&(Q.length=ts),I&&Vr(r)}$t=en;function Vr(n){const e=v();e&&e.sendConsoleLog(n)}function Kr(){let n=0;return G.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function ns(){return{version:w,cacheNames:[Kt,A,_e,at],pendingImageRequests:q.size,pendingVideoRequests:xe.size,videoBlobCacheSize:G.size,videoBlobCacheTotalBytes:Kr(),completedImageRequestsSize:we.size,failedDomainsCount:Le.size,failedDomains:Array.from(Le),corsFailedDomainsCount:Me.size,corsFailedDomains:Array.from(Me),debugLogsCount:V.length,consoleLogsCount:Q.length,debugModeEnabled:I,memoryStats:{pendingRequestsMapSize:q.size,completedRequestsMapSize:we.size,videoBlobCacheMapSize:G.size,failedDomainsSetSize:Le.size,corsFailedDomainsSetSize:Me.size,debugLogsArraySize:V.length,consoleLogsArraySize:Q.length}}}function tn(){return V}function ss(){V.length=0}function rs(){Q.length=0}function nn(){I||(I=!0,We(!0),Ze(!0),ne.log("Service Worker: Debug mode enabled (debug page connected)"))}function sn(){I&&(I=!1,We(!1),Ze(!1),Q.length=0,V.length=0,ne.log("Service Worker: Debug mode disabled (no debug pages)"))}function Xr(n){n>0?nn():sn()}function os(n){for(const e of xr)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function Yr(n,e){return Fr.test(n.pathname)||e.destination==="image"||os(n)!==null}function Qr(n,e){return Gr.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function Jr(n,e){return Jt.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function Zr(n,e){return n.hostname==="fonts.googleapis.com"||n.hostname==="fonts.gstatic.com"?!0:/\.(woff|woff2|ttf|otf|eot)$/i.test(n.pathname)||e.destination==="font"}function eo(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function as(n){return`drawnix-static-v${n}`}function is(){return{committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function cs(n){const e=n||{},t=typeof e.committedVersion=="string"&&e.committedVersion?e.committedVersion:w,s=typeof e.pendingVersion=="string"&&e.pendingVersion?e.pendingVersion:null,r=typeof e.pendingReadyAt=="number"&&Number.isFinite(e.pendingReadyAt)?e.pendingReadyAt:null,o=e.upgradeState==="prewarming"||e.upgradeState==="ready"||e.upgradeState==="committing"?e.upgradeState:"idle";return{committedVersion:t,pendingVersion:s,pendingReadyAt:r,upgradeState:o,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:Date.now()}}function ct(){return new Promise((n,e)=>{const t=indexedDB.open(Wr,Br);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains(De)||r.createObjectStore(De,{keyPath:"domain"}),r.objectStoreNames.contains(Ae)||r.createObjectStore(Ae,{keyPath:"key"})}})}async function Fe(){try{const n=await ct();return await new Promise((e,t)=>{const o=n.transaction([Ae],"readonly").objectStore(Ae).get(Hn);o.onerror=()=>t(o.error),o.onsuccess=()=>{const a=o.result;e(cs((a==null?void 0:a.state)||is()))}})}catch(n){return console.warn("Service Worker: 无法读取版本状态:",n),is()}}async function to(n){const e=cs(n);try{const t=await ct();await new Promise((s,r)=>{const o=t.transaction([Ae],"readwrite");o.objectStore(Ae).put({key:Hn,state:e}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.warn("Service Worker: 无法写入版本状态:",t)}return e}async function Se(n){const e=await Fe(),t=typeof n=="function"?n(e):n;return to({...e,...t,updatedAt:Date.now()})}async function de(n){const e=await Fe(),t={type:"SW_VERSION_STATE",...e,swVersion:w};if(n)return n.postMessage(t),e;const s=await O.clients.matchAll({type:"window",includeUncontrolled:!0});for(const r of s)r.postMessage(t);return e}async function no(){try{const n=await ct();return await new Promise((e,t)=>{const o=n.transaction([De],"readonly").objectStore(De).getAll();o.onsuccess=()=>{o.result.forEach(i=>Le.add(i.domain)),e()},o.onerror=()=>t(o.error)})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function so(n){try{const e=await ct();return await new Promise((t,s)=>{const r=e.transaction([De],"readwrite");r.objectStore(De).put({domain:n,timestamp:Date.now()}),r.oncomplete=()=>t(),r.onerror=()=>s(r.error)})}catch(e){console.warn("Service Worker: 无法保存失败域名:",e)}}async function ro(n){if(!n){await Se({committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();return}await Se(t=>({committedVersion:t.committedVersion||w,pendingVersion:w,pendingReadyAt:Date.now(),upgradeState:"ready"}));const e=v();e&&e.sendSWNewVersionReady(w),await de()}const ls=2,us=1500,rn=2500,oo=8e3,ao=5e3,io=6e4,lt=5e3,co=600*1e3,lo=["offline-static-assets"];let Ge=0,ds=0;const Ue=new Set,He=new Set,qe=new Set,ut=new Map;let hs=Promise.resolve(),je=null,dt=0,he=!1,ht=!1;function wa(n,e){}function gs(){return nt().filter(n=>n.remainingCooldownMs>0&&!n.status.isHealthy).map(n=>({name:n.name,failCount:n.status.failCount,remainingCooldownMs:n.remainingCooldownMs,lastFailureReason:n.status.lastFailureReason}))}function fs(n,e,t){console.warn("[SW Static 503]",{stage:n,requestUrl:e.url,destination:e.destination,mode:e.mode,unavailableCDNs:gs(),...t})}let on={phase:"idle",percent:0,completed:0,total:0,failed:0,version:w,updatedAt:Date.now()};async function ps(n){const e={type:"SW_BOOT_PROGRESS",...on};if(n){n.postMessage(e);return}const t=await O.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e)}function Ce(n,e){on={...on,...n,version:w,updatedAt:Date.now()},ps(e)}async function uo(){try{const n=await fetch(H("precache-manifest.json").href,{cache:"reload"});if(!n.ok)return n.status,n.statusText,null;const e=await n.json();return e.version,e.files.length,e.version&&e.version!==w?(e.version,null):e.files}catch(n){return J(n),null}}let ve=null,Ie=0;function ze(){return Be}async function ho(n,e=200){try{const t=(await n.text()).replace(/\s+/g," ").trim();return t?t.slice(0,e):void 0}catch{return}}async function go(){if(ze())return null;const n=H("idle-prefetch-manifest.json").href;try{const e=await fetch(n,{cache:"reload"}),t=e.headers.get("content-type")||"";if(!e.ok){const a=await ho(e.clone());return e.status,e.statusText,null}const s=await e.text(),r=s.replace(/\s+/g," ").trim().slice(0,200);if(t.includes("text/html")||/<!DOCTYPE|<html|<HTML/i.test(r))return e.status,null;let o;try{o=JSON.parse(s)}catch(a){return J(a),null}return!o||typeof o!="object"||!o.groups?null:o.version&&o.version!==w?(o.version,null):(o.version,o.defaults,Object.fromEntries(Object.entries(o.groups).map(([a,i])=>[a,i.length])),o)}catch(e){return J(e),null}}async function gt(){if(ze())return Ie=0,ve=null,null;const n=Date.now();if(!ve){if(Ie>0&&n-Ie<lt)return null;ve=go().then(e=>e?(Ie=0,e):(Ie=Date.now(),ve=null,null)).catch(e=>{throw Ie=Date.now(),J(e),ve=null,e})}return ve}async function an(n){const e={type:"SW_IDLE_PREFETCH_STATUS",completedGroups:Array.from(qe),version:w,updatedAt:Date.now()};if(n){n.id,e.completedGroups,n.postMessage(e);return}const t=await O.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e);t.length,e.completedGroups}function fo(n,e){return`${n}@${e}`}async function ft(n){try{return(await n.keys()).length}catch{return-1}}function pt(n,e){const t=hs.catch(()=>{}).then(async()=>{try{await e()}finally{}});return hs=t.catch(s=>{console.warn("[SWDebug] idle prefetch task failed",{label:n,error:J(s)})}),t}function po(n){return Math.min(io,ao*2**Math.max(0,n-1))}function ms(n,e=[]){const t=[],s=new Set,r=o=>{!o||s.has(o)||(n.groups[o]||[]).length===0||(s.add(o),t.push(o))};return e.forEach(r),(n.defaults||[]).forEach(r),lo.forEach(r),Object.keys(n.groups).forEach(r),t}function bs(n,e){const t=Date.now(),s=new Map,r=[],o=[];let a=0,i=null;for(const c of e){const l=n.groups[c]||[];if(l.length===0)continue;let h=!1;for(const d of l){const u=fo(d.url,d.revision);if(Ue.has(u)||(h=!0,He.has(u)))continue;const b=ut.get(u);if(b&&b.nextRetryAt>t){a+=1;const p=Math.max(0,b.nextRetryAt-t);i=i===null?p:Math.min(i,p);continue}s.set(u,d)}h?o.push(c):r.push(c)}return{completedGroups:r,pendingGroups:o,queue:Array.from(s.entries()),coolingEntries:a,nextRetryDelayMs:i}}function cn(n,e=rn){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(je!==null){if(dt<=s)return;clearTimeout(je),je=null,dt=0}dt=s,je=self.setTimeout(()=>{je=null,dt=0,pt(`idle-sweep:${n}`,async()=>{await yt(`scheduled:${n}`)})},t)}function mo(){return Ge===0?!1:Date.now()-Ge<us}function bo(){if(Ge===0)return Promise.resolve();const n=Date.now()-Ge,e=Math.max(0,us-n)+100;return new Promise(t=>{setTimeout(t,e)})}function yo(n,e){const t=Re(e.pathname);if(n.request.method!=="GET"||!n.clientId||e.origin!==self.location.origin||e.pathname.startsWith(qn)||e.pathname.startsWith(jn)||t==="/sw.js"||t==="/precache-manifest.json"||t==="/idle-prefetch-manifest.json")return!1;const s=Date.now();return s-ds<oo?!1:(ds=s,!0)}function wo(n){return Gn(Re(n))}function ys(n,e){return Be||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||wo(e.pathname)?!1:!!(e.pathname.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg|woff|woff2|ttf|eot|json|ico)$/i)||n.destination==="script"||n.destination==="style"||n.destination==="image"||n.destination==="font")}function So(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${e.replace(/^\/npm\/aitu-app@[^/]+\//,"/").replace(/^\/aitu-app@[^/]+\//,"/")}${t}`}function Co(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${Re(e)}${t}`}function mt(n){const e=new URL(n,self.location.origin),t=So(Co(`${e.pathname}${e.search}`)),s=H(t);return{requestUrl:e,resourcePath:t,cacheKey:s.href,originFetchUrl:s.href}}function $e(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&ys(n,e)}function Eo(n,e){const t=new Headers(n.headers);return t.set(Xt,e.source),t.set(Yt,e.revision),t.set(Qt,e.appVersion||w),e.fetchTarget&&t.set(Un,e.fetchTarget),t.set("x-sw-cached-at",new Date().toISOString()),new Response(n.body,{status:n.status,statusText:n.statusText,headers:t})}async function ln(n,e,t,s){const r=Eo(t,s);return await n.put(e,r.clone()),r}async function bt(n,e=[]){const t=e.filter(r=>!!r&&r!==n.url),s=await caches.keys();for(const r of s)if(r.startsWith("drawnix-static-v"))try{const o=await caches.open(r),a=await o.match(n);if(a)return a;for(const i of t){const c=await o.match(i);if(c)return n.url,c}}catch{}return null}async function To(n,e=[]){const t=[n.url,...e].filter(Boolean);for(const s of t)try{const r=await fetch(s,{cache:"only-if-cached",mode:"same-origin"});if(r.ok)return r}catch{}return null}async function _o(n,e){const t=mt(e.url).cacheKey,s=await n.match(e);if(s)return{response:s,normalizedCacheKey:t,matchedBy:"request"};if(t!==e.url){const r=await n.match(t);if(r)return{response:r,normalizedCacheKey:t,matchedBy:"normalized"}}return{response:null,normalizedCacheKey:t,matchedBy:null}}async function Do(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function ws(n,e,t){try{const s=mt(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(Yt),l=r.headers.get(Qt);if(c===t&&l===w)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(Ir(Re(s.requestUrl.pathname))){const c=await qt(s.resourcePath,w,ot.href.replace(/\/$/,""),{preferLocal:!1,requestKind:"background-prefetch"});c!=null&&c.response.ok&&(o=c.response,a=c.source,i=c.targetUrl)}if(o||(o=await fetch(s.originFetchUrl,{cache:"reload"}),a="server",i=s.originFetchUrl),o.ok&&$e(new Request(s.cacheKey,{method:"GET"}),s.requestUrl,o))return{url:e,success:!1,status:404,error:"html-fallback-for-static-resource"};if(o.ok){if(await ln(n,s.cacheKey,o,{source:a,revision:t,fetchTarget:i,appVersion:w}),s.resourcePath==="/index.html"){const c=H("/").href,l=await n.match(s.cacheKey);l&&await n.put(c,l.clone())}return{url:e,success:!0,source:a}}return{url:e,success:!1,status:o.status}}catch(s){return{url:e,success:!1,error:String(s)}}}async function Ao(n,e){const s=[],r=e.length;let o=0,a=0;await ft(n),e.slice(0,8).map(d=>d.url),Ce({phase:"precache",total:r,completed:0,failed:0,percent:r>0?0:100,message:r>0?`正在预热启动资源(0/${r})...`:"没有需要预热的启动资源"});for(let d=0;d<e.length;d+=6){const u=e.slice(d,d+6),b=await Promise.allSettled(u.map(({url:g,revision:f})=>ws(n,g,f))),p=[];for(const g of b)if(g.status==="fulfilled"){const f={url:g.value.url,success:g.value.success,skipped:g.value.skipped,source:g.value.source,status:g.value.status,error:g.value.error};s.push(f),p.push(f),o+=1,g.value.success||(a+=1)}else{const f={success:!1,error:String(g.reason)};s.push(f),p.push(f),o+=1,a+=1}u.length,p.filter(g=>g.success).length,p.filter(g=>g.skipped).length,p.filter(g=>!g.success).length,Object.fromEntries(Array.from(p.reduce((g,f)=>{const y=f.source||"unknown";return g.set(y,(g.get(y)||0)+1),g},new Map))),p.filter(g=>!g.success).slice(0,5).map(g=>({url:g.url,status:g.status,error:g.error})),Ce({phase:"precache",total:r,completed:o,failed:a,percent:r>0?Math.round(o/r*100):100,message:r>0?`正在预热启动资源(${o}/${r}${a>0?`,${a} 项回退`:""})...`:"没有需要预热的启动资源"})}const i=s.filter(d=>d.success).length,c=s.length-i,l=s.filter(d=>d.success&&d.source&&d.source!=="server").length,h=s.filter(d=>d.success&&d.source==="server").length;return await ft(n),{total:r,successCount:i,failCount:c,cdnCount:l,serverCount:h}}async function Ss(n){if(n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await gt();if(!e)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};Object.fromEntries(n.map(c=>{var l;return[c,((l=e.groups[c])==null?void 0:l.length)||0]})),e.defaults;const t=new Set(qe),s=bs(e,n);if(s.completedGroups.forEach(c=>qe.add(c)),s.queue.length===0)return Ue.size,He.size,{completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,queuedEntries:0,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs};const r=await caches.open(_e);await ft(r);const o=s.queue;s.queue.length,o.length,o.slice(0,8).map(([,c])=>c.url);for(let c=0;c<o.length;c+=ls){for(;mo();)await bo();const l=o.slice(c,c+ls);l.forEach(([u])=>He.add(u));const h=await Promise.allSettled(l.map(([,{url:u,revision:b}])=>ws(r,u,b))),d=[];h.forEach((u,b)=>{const[p]=l[b];if(He.delete(p),u.status==="fulfilled"&&u.value.success)ut.delete(p),Ue.add(p);else{const g=ut.get(p),f=((g==null?void 0:g.count)||0)+1,y=po(f);ut.set(p,{count:f,nextRetryAt:Date.now()+y,lastError:u.status==="fulfilled"?u.value.error:String(u.reason),lastStatus:u.status==="fulfilled"?u.value.status:void 0})}u.status==="fulfilled"?d.push({url:u.value.url,success:u.value.success,skipped:u.value.skipped,source:u.value.source,status:u.value.status,error:u.value.error}):d.push({success:!1,error:String(u.reason)})}),l.length,d.filter(u=>u.success).length,d.filter(u=>u.skipped).length,d.filter(u=>!u.success).length,Object.fromEntries(Array.from(d.reduce((u,b)=>{const p=b.source||"unknown";return u.set(p,(u.get(p)||0)+1),u},new Map))),d.filter(u=>!u.success).slice(0,5).map(u=>({url:u.url,status:u.status,error:u.error})),Ue.size,He.size}const a=bs(e,n),i=a.completedGroups.filter(c=>!t.has(c));return i.forEach(c=>qe.add(c)),await ft(r),Ue.size,Array.from(qe),{completedGroups:i,pendingGroups:a.pendingGroups,queuedEntries:o.length,coolingEntries:a.coolingEntries,nextRetryDelayMs:a.nextRetryDelayMs}}async function yt(n,e=[]){if(ze())return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const t=await gt();if(!t)return cn(`${n}:manifest-missing`,lt),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:lt};const s=ms(t,e);if(s.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};Object.fromEntries(s.map(o=>{var a;return[o,((a=t.groups[o])==null?void 0:a.length)||0]}));const r=await Ss(s);return r.completedGroups.length>0&&await an(),r.pendingGroups.length>0&&cn(`${n}:pending`,r.nextRetryDelayMs??rn),r}async function Ro(){var t;if(ze())return;const n=await gt();if(!n){cn("default-groups:manifest-missing",lt);return}const e=(t=n==null?void 0:n.defaults)==null?void 0:t.filter(s=>typeof s=="string"&&s.length>0);!e||e.length===0||await yt("default-groups",e)}async function Lo(){if(ze())return;const n=Date.now();let e=null;for(;;){if(!e){const o=await gt();if(!o||(e=ms(o),e.length===0))return}const t=await Ss(e);if(t.completedGroups.length>0&&await an(),t.pendingGroups.length===0)return;const s=Date.now()-n;if(s>=co)throw new Error(`idle-prefetch incomplete after ${s}ms: pending groups ${t.pendingGroups.join(", ")}`);const r=Math.max(250,t.nextRetryDelayMs??(t.queuedEntries>0?rn:1e3));t.pendingGroups,t.coolingEntries,t.queuedEntries,await new Promise(o=>{setTimeout(o,r)})}}O.addEventListener("install",n=>{he=!!O.registration.active,ht=!he,he||O.skipWaiting(),Ce({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await no(),await Se(e=>({committedVersion:e.committedVersion||w,pendingVersion:he?w:null,pendingReadyAt:null,upgradeState:he?"prewarming":"idle"})),await de();try{const e=await uo();if(e&&e.length>0){const t=await caches.open(_e),s=await Ao(t,e);if(he&&s.failCount>0)throw new Error(`precache incomplete: ${s.failCount}/${s.total} files failed`)}else Be&&Ce({phase:"development",percent:100,completed:0,total:0,failed:0,message:"开发模式下跳过静态预缓存"});he&&await Lo(),await ro(he)}catch(e){await Se(t=>({committedVersion:t.committedVersion||w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"})),await de(),Ce({phase:"error",message:`启动资源预热失败:${J(e)}`}),console.warn("Service Worker: Precache failed:",e)}})())}),O.addEventListener("activate",n=>{Ce({phase:"activating",percent:100,message:"启动缓存服务正在接管页面..."}),n.waitUntil((async()=>{await Fe(),await Se({committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();try{const{ensureCDNPreferenceLoaded:t}=await Promise.resolve().then(()=>Dr);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}ht&&await O.clients.claim(),setTimeout(()=>{pt("default-groups",async()=>Ro())},800);const e=v();e&&e.sendSWActivated(w),Ce({phase:"activated",percent:100,message:"启动缓存服务已就绪"})})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(i=>i.startsWith("drawnix-images-v")&&i!==A);if(t.length>0){const i=await caches.open(A);for(const c of t)try{const l=await caches.open(c),h=await l.keys();for(const d of h){const u=await l.match(d);u&&await i.put(d,u)}await caches.delete(c)}catch(l){console.warn(`Failed to migrate cache ${c}:`,l)}}const s=await Fe(),r=as(s.committedVersion||w),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==_e&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==Kt&&i!==A&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(_e);await Po(i)}catch(i){console.warn("Failed to purge suspicious static cache entries:",i)}(o.length>0||a.length>0)&&setTimeout(async()=>{for(const i of[...o,...a])try{await caches.delete(i)}catch(c){console.warn("Failed to delete old cache:",i,c)}},3e4),Zn().catch(i=>{console.warn("Failed to cleanup expired console logs:",i)}),yn.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function Mo(n){if(I){const e=v();e&&e.sendPostMessageLog(n)}}async function vo(n,e,t,s){if(Be)return null;try{const r=mt(e.url),o=await qt(t,s,ot.href.replace(/\/$/,""),{preferLocal:!1,requestKind:"interactive-runtime"});if(!(o!=null&&o.response.ok))return console.warn("[SW CDN] Static resource unavailable from all fallback sources",{requestUrl:e.url,resourcePath:t,appVersion:s,unavailableCDNs:gs()}),null;const a=new URL(e.url);if($e(e,a,o.response))return null;const i=await ln(n,r.cacheKey,o.response,{source:o.source,revision:"runtime",fetchTarget:o.targetUrl,appVersion:s});return r.cacheKey!==e.url&&(e.url,r.cacheKey,o.source,o.targetUrl,void 0),i}catch(r){return console.warn("[SW CDN] CDN fallback failed:",r),null}}function Io(n){const e=n.headers.get(Xt)||void 0,t=n.headers.get(Un)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function Cs(n,e,t=w){const s=e.headers.get(Xt),r=e.headers.get(Yt),o=e.headers.get(Qt);if(!s||!r||!o){const i=new URL(n.url);return!(e.ok&&!$e(n,i,e))}if(o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr")return!0;const a=new URL(n.url);return $e(n,a,e)}async function Po(n){const e=await n.keys();for(const t of e)try{const s=await n.match(t);s&&Cs(t,s)&&await n.delete(t)}catch(s){console.warn("Service Worker: Failed to inspect static cache entry:",s)}}O.addEventListener("message",n=>{var a,i,c,l,h,d,u,b,p,g;const e=((a=n.data)==null?void 0:a.type)||((i=n.data)==null?void 0:i.cmdname)||((l=(c=n.data)==null?void 0:c.req)==null?void 0:l.cmdname)||"unknown",t=((h=n.source)==null?void 0:h.id)||"",s=((d=n.source)==null?void 0:d.url)||"",r=((u=n.data)==null?void 0:u.cmdname)||((b=n.data)==null?void 0:b.requestId)&&((p=n.data)==null?void 0:p.ret)!==void 0;let o="";if(Rt()&&!r&&(o=Lt(e,n.data,t,s,(g=n.data)==null?void 0:g.__internal__),o&&I)){const y=Xe().find(S=>S.id===o);y&&Mo(y)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:f,mediaType:y,blob:S,mimeType:E}=n.data;if(f&&y&&S){const W=new Blob([S],{type:E||(y==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:U}=await Promise.resolve().then(()=>j);U(W,f,y)})()}return}if(n.data&&n.data.type==="SW_CDN_SET_PREFERENCE"){n.waitUntil(In({cdn:n.data.cdn,latency:n.data.latency,timestamp:n.data.timestamp,version:n.data.version}));return}if(n.data&&n.data.type==="RECOVER_DYNAMIC_IMPORT_FAILURE"){n.waitUntil(caches.keys().then(f=>Promise.all(f.filter(y=>y.startsWith("drawnix-static-v")).map(y=>caches.delete(y))).then(()=>{n.data.appVersion,n.data.moduleKey})));return}if(n.data&&n.data.type==="SW_BOOT_PROGRESS_GET"){const f=n.source;f==null||f.id,ps(f);return}if(n.data&&n.data.type==="GET_VERSION_STATE"){const f=n.source;f==null||f.id,n.waitUntil(de(f));return}if(n.data&&n.data.type==="SW_IDLE_PREFETCH_STATUS_GET"){const f=n.source;f==null||f.id,an(f);return}if(n.data&&n.data.type==="SW_PREFETCH_GROUPS"){const f=Array.isArray(n.data.groups)?n.data.groups.filter(y=>typeof y=="string"):[];n.waitUntil(pt(`message:${f.join(",")||"empty"}`,async()=>{await yt(`message:${f.join(",")||"empty"}`,f)}));return}if(n.data&&n.data.type==="CLAIM_CLIENTS"){n.waitUntil(O.clients.claim());return}if(n.data&&(n.data.type==="COMMIT_UPGRADE"||n.data.type==="SKIP_WAITING")){const f=n.source;f==null||f.id,n.waitUntil((async()=>{ht=!0,await Se({committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(f),O.skipWaiting();const y=v();y&&y.sendSWUpdated(w)})())}else if(n.data&&n.data.type==="FORCE_UPGRADE")n.waitUntil((async()=>{ht=!0,await Se({committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(n.source),O.skipWaiting();const f=v();f&&f.sendSWUpdated(w)})());else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:f}=n.data;f&&dn(f).then(()=>{const y=v();y&&y.sendCacheDeleted(f)}).catch(y=>{console.error("Service Worker: Failed to delete cache:",y)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:f}=n.data;f&&Array.isArray(f)&&No(f).then(()=>{}).catch(y=>{console.error("Service Worker: Failed to batch delete caches:",y)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")xo().then(()=>{}).catch(f=>{console.error("Service Worker: Failed to clear all cache:",f)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){I=!0,We(!0),Ze(!0),ne.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const f=v();f&&f.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){I=!1,We(!1),Ze(!1),Q.length=0,V.length=0,ne.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const f=v();f&&f.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:f}=await Promise.resolve().then(()=>Ee),y=await f(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:y})}catch(f){console.error("[SW] Failed to get LLM API logs:",f)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:f}=await Promise.resolve().then(()=>Ee);await f();const y=n.source;y&&y.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(f){console.error("[SW] Failed to clear LLM API logs:",f)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const f=n.source;f&&f.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:I,swVersion:w,logs:V.slice(-100),consoleLogs:Q.slice(-100)});return}if(n.data&&n.data.type==="SW_DEBUG_GET_LOGS"){(async()=>{try{const{getInternalFetchLogs:f}=await Promise.resolve().then(()=>br),y=tn(),S=f(),E=n.source;E&&E.postMessage({type:"SW_DEBUG_LOGS",logs:[...y,...S.map(W=>({...W,type:"fetch"}))]})}catch(f){console.error("[SW] Failed to get fetch logs:",f)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const f=n.source;f&&f.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:Q})}catch(f){console.error("[SW] Failed to get console logs:",f)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const f=Xe(),y=n.source;y&&y.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:f})}catch(f){console.error("[SW] Failed to get postmessage logs:",f)}})();return}});const ko="MemorySnapshotDB",ge="snapshots",Es=50;async function un(){return new Promise((n,e)=>{const t=indexedDB.open(ko,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(ge)){const o=r.createObjectStore(ge,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function Ts(n){try{const e=await un(),t=e.transaction(ge,"readwrite"),s=t.objectStore(ge);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>Es){const i=s.index("timestamp").openCursor();let c=0;const l=o-Es;i.onsuccess=h=>{const d=h.target.result;d&&c<l&&(s.delete(d.value.id),c++,d.continue())}}},await new Promise((o,a)=>{t.oncomplete=()=>{e.close(),o()},t.onerror=()=>{e.close(),a(t.error)}})}catch(e){console.warn("[SW] Failed to save crash snapshot:",e)}}async function _s(){try{const n=await un(),s=n.transaction(ge,"readonly").objectStore(ge).index("timestamp");return new Promise((r,o)=>{const a=s.getAll();a.onsuccess=()=>{n.close();const i=a.result.sort((c,l)=>l.timestamp-c.timestamp);r(i)},a.onerror=()=>{n.close(),o(a.error)}})}catch(n){return console.warn("[SW] Failed to get crash snapshots:",n),[]}}async function Ds(){try{const n=await un(),e=n.transaction(ge,"readwrite");e.objectStore(ge).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("[SW] Failed to clear crash snapshots:",n)}}const Oo=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function Wo(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Bo(n){return new Promise(e=>{try{const t=indexedDB.open(n);t.onerror=()=>e({count:0,totalSize:0}),t.onsuccess=()=>{const s=t.result,r=Array.from(s.objectStoreNames);if(r.length===0){s.close(),e({count:0,totalSize:0});return}let o=0,a=0,i=0,c=0;const l=10;try{const h=s.transaction(r,"readonly");for(const d of r){const u=h.objectStore(d),b=u.count();b.onsuccess=()=>{const p=b.result;if(o+=p,p>0){const g=u.openCursor();let f=0;g.onsuccess=y=>{const S=y.target.result;if(S&&f<l)a+=Wo(S.value),i++,f++,S.continue();else if(c++,c===r.length){s.close();const E=i>0?a/i:0,W=Math.round(E*o);e({count:o,totalSize:W})}},g.onerror=()=>{if(c++,c===r.length){s.close();const y=i>0?a/i:0,S=Math.round(y*o);e({count:o,totalSize:S})}}}else c++,c===r.length&&(s.close(),e({count:o,totalSize:0}))},b.onerror=()=>{if(c++,c===r.length){s.close();const p=i>0?a/i:0,g=Math.round(p*o);e({count:o,totalSize:g})}}}}catch{s.close(),e({count:0,totalSize:0})}},t.onupgradeneeded=s=>{s.target.result.close();try{indexedDB.deleteDatabase(n)}catch{}e({count:0,totalSize:0})}}catch{e({count:0,totalSize:0})}})}async function As(){const n={},e=[Kt,A,_e,at];for(const t of e)try{const s=await caches.open(t),r=await s.keys();let o=0;const a=Math.min(r.length,100);let i=0;for(let c=0;c<a;c++){const l=await s.match(r[c]);if(l){const h=l.headers.get("sw-image-size")||l.headers.get("content-length");h&&(i+=parseInt(h))}}a>0&&r.length>a?o=Math.round(i/a*r.length):o=i,n[t]={count:r.length,totalSize:o,type:"cache"}}catch{n[t]={count:0,totalSize:0,type:"cache"}}for(const t of Oo)try{const s=await Bo(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function dn(n){try{await(await caches.open(A)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function No(n){try{const e=await caches.open(A);let t=0;for(const s of n)try{await e.delete(s),t++}catch(r){console.warn("Service Worker: Failed to delete cache in batch:",s,r)}}catch(e){throw console.error("Service Worker: Failed to batch delete caches:",e),e}}async function xo(){try{const n=await caches.open(A),e=await n.keys();for(const t of e)await n.delete(t)}catch(n){throw console.error("Service Worker: Failed to clear image cache:",n),n}}async function Fo(n,e,t){try{const s=v();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}function Go(n){const e=Date.now(),t=ue.get(n);if(t&&e-t<$n)return!1;if(ue.size>=Vn){for(const[s,r]of ue)e-r>$n&&ue.delete(s);if(ue.size>=Vn){const s=Array.from(ue.entries());s.sort((r,o)=>r[1]-o[1]);for(const[r]of s.slice(0,Math.floor(s.length/2)))ue.delete(r)}}return ue.set(n,e),!0}async function fe(n,e){try{const t=Ne(new URL(n,self.location.origin)).toString();if(!Go(t))return;const s=v();s&&s.sendCacheImageCacheFailed(t,e)}catch(t){console.warn("Service Worker: Failed to notify image cache failure:",{url:n,error:e,notifyError:t})}}async function Uo(){try{if(navigator.storage&&navigator.storage.estimate){const n=await navigator.storage.estimate(),e=n.usage||0,t=n.quota||0,s=t>0?e/t*100:0;if(s>90){console.warn("Service Worker: Storage quota warning:",{usage:e,quota:t,percentage:s});const r=v();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const se=new Map,Rs=300*1e3,Ls=500;function Ho(n){const e=n.match(/\/(\d{4})\/(\d{2})\/(\d{2})\//),t=n.match(/\/(\d{4})(\d{2})(\d{2})\//);let s=null;if(e?s=new Date(parseInt(e[1]),parseInt(e[2])-1,parseInt(e[3])):t&&(s=new Date(parseInt(t[1]),parseInt(t[2])-1,parseInt(t[3]))),!s)return!1;const r=new Date;return!(s.getFullYear()===r.getFullYear()&&s.getMonth()===r.getMonth()&&s.getDate()===r.getDate())}function qo(n){const e=se.get(n);return e?Date.now()-e>Rs?(se.delete(n),!1):!0:!1}function Ms(n){if(Ho(n)){if(se.size>=Ls){const e=Date.now();for(const[t,s]of se)e-s>Rs&&se.delete(t);if(se.size>=Ls){const t=Array.from(se.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)se.delete(r)}}se.set(n,Date.now())}}O.addEventListener("fetch",n=>{const e=new URL(n.request.url),t=Date.now();if(e.protocol!=="http:"&&e.protocol!=="https:"){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"other",details:`Skipped: non-http protocol (${e.protocol})`,status:0,duration:0});return}if(Ge=t,yo(n,e)){const s=`${e.pathname}${e.search}`;n.clientId,n.waitUntil(pt(`fetch-recheck:${s}`,async()=>{await yt(`fetch:${s}`)}))}if(e.pathname.startsWith(qn)||e.pathname.startsWith(jn)){const s=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(zo(n.request).then(r=>(R(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw R(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(Nr)){const s=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith($o(n.request).then(r=>(R(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw R(s,{error:String(r),duration:Date.now()-t}),r}));return}if(!e.hostname.endsWith(".posthog.com")){if(e.hostname==="cdn.i666.fun"){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: cdn.i666.fun (fallback domain)",status:0,duration:0});return}if(e.hostname.endsWith(".volces.com")||e.hostname.endsWith(".volccdn.com")){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: Volcengine domain (no CORS)",status:0,duration:0});return}if(e.hostname.endsWith(".aliyuncs.com")){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: Aliyun OSS domain (no CORS)",status:0,duration:0});return}if(jr(e.hostname)){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:`Passthrough: ${e.hostname} (CORS failed domain, auto-detected)`,status:0,duration:0});return}if(e.hostname!=="api.github.com"){if(e.origin!==location.origin&&Jr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"audio",headers:r?{range:r}:void 0,details:r?`Audio Range request: ${r}`:"External audio request"});n.respondWith(Vo(n.request).then(a=>(R(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,cached:a.headers.has(le),responseHeaders:{"content-type":a.headers.get("content-type")||"","content-length":a.headers.get("content-length")||"","content-range":a.headers.get("content-range")||""}}),a)).catch(a=>{throw R(o,{error:String(a),duration:Date.now()-s}),a}));return}if(Qr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"video",headers:r?{range:r}:void 0,details:r?`Video Range request: ${r}`:"Video request"});n.respondWith(Ko(n.request).then(a=>(R(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,responseHeaders:{"content-type":a.headers.get("content-type")||"","content-length":a.headers.get("content-length")||"","content-range":a.headers.get("content-range")||""}}),a)).catch(a=>{throw R(o,{error:String(a),duration:Date.now()-s}),a}));return}if(Zr(e,n.request)){const s=Date.now(),r=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(jo(n.request).then(o=>(R(r,{status:o.status,statusText:o.statusText,responseType:o.type,duration:Date.now()-s,cached:o.headers.has("sw-cache-date")}),o)).catch(o=>{throw R(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&Yr(e,n.request)){if(qo(n.request.url)){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"Skipped: recently failed URL (cached 404)",status:404,duration:0}),n.respondWith(new Response("",{status:404,statusText:"Not Found (cached)"}));return}const s=Date.now(),r=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(Jo(n.request).then(o=>(o.status===404&&Ms(n.request.url),R(r,{status:o.status,statusText:o.statusText,responseType:o.type,duration:Date.now()-s,cached:o.headers.has("sw-cache-date"),size:parseInt(o.headers.get("content-length")||"0")}),o)).catch(o=>{throw Ms(n.request.url),R(r,{error:String(o),duration:Date.now()-s}),o}));return}if(n.request.method==="GET"){const s=n.request.mode==="navigate",r=n.request.destination!=="";if(s||r){const o=Date.now(),a=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(Xo(n.request).then(i=>{const c=Io(i);return R(a,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-o,resourceSource:c.resourceSource,resourceFetchTarget:c.resourceFetchTarget,details:s?"Navigation request":[`Static resource (${n.request.destination})`,c.resourceSource?`来源: ${c.resourceSource}`:null,c.resourceFetchTarget?`实际拉取: ${c.resourceFetchTarget}`:null].filter(Boolean).join(`
|
|
1
|
+
var sw=(function(T){"use strict";var me=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(me||{});me.IMAGE+"",me.VIDEO+"",me.AUDIO+"",me.CHARACTER+"",me.INSPIRATION_BOARD+"",me.CHAT+"";function J(n){return n instanceof Error?n.name||"Error":"Unknown error"}const _t="sw-task-queue",mn=3,_="tasks",z="config",B="workflows",N="chat-workflows",L="pending-tool-requests",M="pending-dom-operations",x="task-step-mappings",$="pending-canvas-operations",Gs=[_,z,B,N,L,M,x,$];function Us(){return new Promise(n=>{const e=indexedDB.open(_t);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,mn))},e.onerror=()=>{n(mn)}})}function Hs(n){const e=[];for(const t of Gs)n.objectStoreNames.contains(t)||e.push(t);return e}function qs(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(_t,s);r.onerror=()=>{console.error("[SWStorage] Failed to repair DB:",r.error),t(r.error)},r.onsuccess=()=>{e(r.result)},r.onupgradeneeded=o=>{const a=o.target.result;bn(a)}})}function bn(n){if(!n.objectStoreNames.contains(_)){const e=n.createObjectStore(_,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("type","type",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(z)||n.createObjectStore(z,{keyPath:"key"}),!n.objectStoreNames.contains(B)){const e=n.createObjectStore(B,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(N)){const e=n.createObjectStore(N,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(L)||n.createObjectStore(L,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(M)){const e=n.createObjectStore(M,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(x)||n.createObjectStore(x,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains($)||n.createObjectStore($,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function js(){const n=await Us();return new Promise((e,t)=>{const s=indexedDB.open(_t,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=Hs(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),qs(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;bn(o)}})}class zs{constructor(){this.dbPromise=null,this.pendingTaskSaves=new Map,this.batchSaveTimer=null,this.batchSavePromises=new Map,this.BATCH_SAVE_DELAY=50}async getDB(){return this.dbPromise||(this.dbPromise=js()),this.dbPromise}async flushPendingTaskSaves(){this.batchSaveTimer&&(clearTimeout(this.batchSaveTimer),this.batchSaveTimer=null);const e=Array.from(this.pendingTaskSaves.values()),t=new Map(this.batchSavePromises);if(this.pendingTaskSaves.clear(),this.batchSavePromises.clear(),e.length!==0)try{const s=await this.getDB();await new Promise((r,o)=>{const a=s.transaction(_,"readwrite"),i=a.objectStore(_);for(const c of e)i.put(c);a.oncomplete=()=>{t.forEach(({resolve:c})=>c()),r()},a.onerror=()=>{const c=a.error;t.forEach(({reject:l})=>l(c)),o(c)}})}catch(s){console.error("[SWStorage] Failed to batch save tasks:",s),t.forEach(({reject:r})=>r(s))}}async saveTask(e){return new Promise((t,s)=>{this.pendingTaskSaves.set(e.id,e),this.batchSavePromises.set(e.id,{resolve:t,reject:s}),this.batchSaveTimer||(this.batchSaveTimer=setTimeout(()=>{this.flushPendingTaskSaves()},this.BATCH_SAVE_DELAY))})}async saveTaskImmediate(e){this.pendingTaskSaves.delete(e.id);const t=this.batchSavePromises.get(e.id);t&&this.batchSavePromises.delete(e.id);try{const s=await this.getDB();await new Promise((r,o)=>{const c=s.transaction(_,"readwrite").objectStore(_).put(e);c.onerror=()=>o(c.error),c.onsuccess=()=>r()}),t&&t.resolve()}catch(s){throw console.error("[SWStorage] Failed to save task:",s),t&&t.reject(s),s}}async getTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(_,"readonly").objectStore(_).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get task:",t),null}}async getAllTasks(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(_,"readonly").objectStore(_).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all tasks:",e),[]}}async getTasksByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(_,"readonly").objectStore(_).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get tasks by status:",t),[]}}async getTasksPaginated(e){const{offset:t,limit:s,status:r,type:o,sortOrder:a="desc"}=e;try{const i=await this.getDB();return new Promise((c,l)=>{const u=i.transaction(_,"readonly").objectStore(_).index("createdAt"),b=a==="desc"?"prev":"next",p=u.openCursor(null,b),g=[];let f=0,y=0;p.onerror=()=>l(p.error),p.onsuccess=S=>{const E=S.target.result;if(!E){c({tasks:g,total:y,hasMore:y>t+g.length});return}const W=E.value,U=!r||W.status===r,re=!o||W.type===o;U&&re&&(y++,f<t?f++:g.length<s&&g.push(W)),E.continue()}})}catch(i){return console.error("[SWStorage] Failed to get paginated tasks:",i),{tasks:[],total:0,hasMore:!1}}}async deleteTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(_,"readwrite").objectStore(_).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete task:",t)}}async getConfig(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(z,"readonly").objectStore(z).get(e);i.onsuccess=()=>{const c=i.result;if(!c){s(null);return}const{key:l,...h}=c;s(h)},i.onerror=()=>r(i.error)})}catch(t){return console.error("[SWStorage] Failed to get config:",J(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const a=s.transaction(z,"readwrite");a.objectStore(z).put({key:e,...t,updatedAt:Date.now()}),a.oncomplete=()=>r(),a.onerror=()=>o(a.error)})}catch(s){throw console.error("[SWStorage] Failed to save config:",J(s)),s}}async loadConfig(){const e=await this.getConfig("gemini"),t=await this.getConfig("video");return{geminiConfig:e,videoConfig:t}}async saveAllConfig(e,t){await this.saveConfig("gemini",e),await this.saveConfig("video",t)}async saveSystemPrompt(e){try{const t=await this.getDB();return new Promise((s,r)=>{const o=t.transaction(z,"readwrite");o.objectStore(z).put({key:"systemPrompt",value:e,updatedAt:Date.now()}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.error("[SWStorage] Failed to save system prompt:",t)}}async getSystemPrompt(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(z,"readonly").objectStore(z).get("systemPrompt");a.onsuccess=()=>{const i=a.result;t((i==null?void 0:i.value)||null)},a.onerror=()=>s(a.error)})}catch(e){return console.error("[SWStorage] Failed to get system prompt:",e),null}}async saveWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(B,"readwrite").objectStore(B).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save workflow:",t)}}async getWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(B,"readonly").objectStore(B).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get workflow:",t),null}}async getAllWorkflows(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(B,"readonly").objectStore(B).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all workflows:",e),[]}}async getWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(B,"readonly").objectStore(B).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get workflows by status:",t),[]}}async deleteWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(B,"readwrite").objectStore(B).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete workflow:",t)}}async saveChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(N,"readwrite").objectStore(N).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save chat workflow:",t)}}async getChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(N,"readonly").objectStore(N).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get chat workflow:",t),null}}async getAllChatWorkflows(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(N,"readonly").objectStore(N).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all chat workflows:",e),[]}}async getChatWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(N,"readonly").objectStore(N).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get chat workflows by status:",t),[]}}async deleteChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(N,"readwrite").objectStore(N).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete chat workflow:",t)}}async savePendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(L,"readwrite").objectStore(L).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending tool request:",t)}}async getAllPendingToolRequests(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(L,"readonly").objectStore(L).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending tool requests:",e),[]}}async getPendingToolRequestsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(L,"readonly").objectStore(L).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending tool requests by workflow:",t),[]}}async getPendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(L,"readonly").objectStore(L).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get pending tool request:",t),null}}async deletePendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(L,"readwrite").objectStore(L).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending tool request:",t)}}async deletePendingToolRequestsByWorkflow(e){try{const t=await this.getPendingToolRequestsByWorkflow(e);for(const s of t)await this.deletePendingToolRequest(s.requestId)}catch(t){console.error("[SWStorage] Failed to delete pending tool requests by workflow:",t)}}async cleanupStalePendingToolRequests(e=36e5){try{const t=await this.getDB(),s=Date.now()-e;return new Promise((r,o)=>{const a=t.transaction(L,"readwrite"),c=a.objectStore(L).openCursor();let l=0;c.onsuccess=()=>{const h=c.result;h&&(h.value.createdAt<s&&(h.delete(),l++),h.continue())},a.oncomplete=()=>{r(l)},a.onerror=()=>o(a.error)})}catch(t){return console.error("[SWStorage] Failed to cleanup stale pending tool requests:",t),0}}async savePendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(M,"readwrite").objectStore(M).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending DOM operation:",t)}}async getAllPendingDomOperations(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(M,"readonly").objectStore(M).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending DOM operations:",e),[]}}async getPendingDomOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(M,"readonly").objectStore(M).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by workflow:",t),[]}}async getPendingDomOperationsByChatId(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(M,"readonly").objectStore(M).index("chatId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by chat ID:",t),[]}}async getPendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(M,"readonly").objectStore(M).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operation:",t),null}}async deletePendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(M,"readwrite").objectStore(M).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending DOM operation:",t)}}async deletePendingDomOperationsByWorkflow(e){try{const t=await this.getPendingDomOperationsByWorkflow(e);for(const s of t)await this.deletePendingDomOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending DOM operations by workflow:",t)}}async deletePendingDomOperationsByChatId(e){try{const t=await this.getPendingDomOperationsByChatId(e);for(const s of t)await this.deletePendingDomOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending DOM operations by chat ID:",t)}}async saveTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(x,"readwrite").objectStore(x).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save task-step mapping:",t)}}async getAllTaskStepMappings(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction(x,"readonly").objectStore(x).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all task-step mappings:",e),[]}}async getTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(x,"readonly").objectStore(x).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.result||null)})}catch(t){return console.error("[SWStorage] Failed to get task-step mapping:",t),null}}async getTaskStepMappingsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(x,"readonly").objectStore(x).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get task-step mappings by workflow:",t),[]}}async deleteTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(x,"readwrite").objectStore(x).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete task-step mapping:",t)}}async deleteTaskStepMappingsByWorkflow(e){try{const t=await this.getTaskStepMappingsByWorkflow(e);for(const s of t)await this.deleteTaskStepMapping(s.taskId)}catch(t){console.error("[SWStorage] Failed to delete task-step mappings by workflow:",t)}}async savePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction($,"readwrite").objectStore($).put(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending canvas operation:",t)}}async getAllPendingCanvasOperations(){try{const e=await this.getDB();return new Promise((t,s)=>{const a=e.transaction($,"readonly").objectStore($).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending canvas operations:",e),[]}}async getPendingCanvasOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction($,"readonly").objectStore($).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending canvas operations by workflow:",t),[]}}async deletePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction($,"readwrite").objectStore($).delete(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending canvas operation:",t)}}async deletePendingCanvasOperationsByWorkflow(e){try{const t=await this.getPendingCanvasOperationsByWorkflow(e);for(const s of t)await this.deletePendingCanvasOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending canvas operations by workflow:",t)}}async archiveOldTasks(e=100){try{const t=await this.getDB(),s=await new Promise((c,l)=>{const u=t.transaction(_,"readonly").objectStore(_).index("createdAt"),b=[],p=u.openCursor(null,"next");p.onsuccess=()=>{const g=p.result;if(!g){c(b);return}const f=g.value;f.archived||b.push(f),g.continue()},p.onerror=()=>l(p.error)}),r=s.length-e;if(r<=0)return 0;const o=["completed","failed","cancelled"],a=s.filter(c=>o.includes(c.status)).slice(0,r);if(a.length===0)return 0;const i=Date.now();return new Promise((c,l)=>{const h=t.transaction(_,"readwrite"),d=h.objectStore(_);for(const u of a)u.archived=!0,u.updatedAt=i,d.put(u);h.oncomplete=()=>{c(a.length)},h.onerror=()=>l(h.error)})}catch(t){return console.error("[SWStorage] Failed to archive old tasks:",t),0}}}const yn=new zs,$s=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function Dt(n){if(!n)return n;if(typeof n=="string")return n.toLowerCase().startsWith("bearer ")||n.length>30&&/^[a-zA-Z0-9-_]+$/.test(n)&&!n.includes("-")?"[REDACTED]":n;if(Array.isArray(n))return n.map(e=>Dt(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();$s.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=Dt(s)}return e}return n}let Ke=!1;const Vs=500,oe=[];let At=0;function wn(){return Ke}const Sn=["SW_DEBUG_ENABLE","SW_DEBUG_DISABLE","SW_DEBUG_GET_STATUS","SW_DEBUG_CLEAR_LOGS","SW_DEBUG_CLEAR_CONSOLE_LOGS","SW_DEBUG_GET_CONSOLE_LOGS","SW_DEBUG_EXPORT_LOGS","SW_DEBUG_HEARTBEAT","SW_DEBUG_STATUS","SW_DEBUG_ENABLED","SW_DEBUG_DISABLED","SW_DEBUG_LOG","SW_DEBUG_LOGS","SW_DEBUG_LOGS_CLEARED","SW_CONSOLE_LOG","SW_DEBUG_CONSOLE_LOGS","SW_DEBUG_CONSOLE_LOGS_CLEARED","SW_POSTMESSAGE_LOG","SW_DEBUG_POSTMESSAGE_LOGS","SW_DEBUG_POSTMESSAGE_LOGS_CLEARED","SW_DEBUG_NEW_CRASH_SNAPSHOT","SW_DEBUG_CRASH_SNAPSHOTS","SW_DEBUG_CRASH_SNAPSHOTS_CLEARED","SW_DEBUG_GET_CRASH_SNAPSHOTS","SW_DEBUG_CLEAR_CRASH_SNAPSHOTS","CRASH_SNAPSHOT","debug:log","debug:llmLog","debug:statusChanged","debug:enable","debug:disable","debug:getStatus","debug:getLogs","debug:clearLogs","debug:getConsoleLogs","debug:clearConsoleLogs","debug:getPostMessageLogs","debug:clearPostMessageLogs","debug:getCrashSnapshots","debug:clearCrashSnapshots","debug:getLLMApiLogs","debug:clearLLMApiLogs","debug:getCacheStats","debug:exportLogs","debug:newCrashSnapshot","console:log","console:report","postmessage:log","postmessage:logBatch","crash:snapshot","crash:heartbeat"],Oe=new Map;function Cn(n){const e=Ke;Ke=n,!n&&e&&(oe.length=0,Oe.clear(),At=0)}function Rt(){return Ke}function Ks(n){if(!wn()||n==="unknown"||Sn.includes(n))return!1;if(n.startsWith("RPC:")){let e=n.slice(4);if(e.endsWith(":response")?e=e.slice(0,-9):e.endsWith(":error")&&(e=e.slice(0,-6)),Sn.includes(e))return!1}return!0}function Xs(n){if(!n)return{};let e="other";return n.includes("sw-debug")?e="debug":(n.includes("localhost")||n.includes("127.0.0.1")||!n.includes("chrome-extension")&&!n.includes("moz-extension"))&&(e="main"),{clientType:e,clientUrl:new URL(n).pathname+new URL(n).search}}function Lt(n,e,t,s,r){if(r||!Ks(n))return"";const o=Xs(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++At}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:En(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(Ys(i),Js(n)){const c=Zs(e);c&&Oe.set(c,{entry:i,startTime:Date.now()})}return a}function Ys(n){oe.unshift(n),oe.length>Vs&&oe.pop()}function Mt(n,e,t,s){if(!wn())return"";const r=Oe.get(n);if(r){r.entry.response=En(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return Oe.delete(n),o}return""}function Xe(){return[...oe]}function Qs(){oe.length=0,Oe.clear(),At=0}function Js(n){return n.startsWith("RPC:")&&!n.endsWith(":response")&&!n.endsWith(":error")?!0:["TASK_SUBMIT","TASK_CANCEL","TASK_RETRY","TASK_DELETE","TASK_GET_","WORKFLOW_SUBMIT","WORKFLOW_CANCEL","WORKFLOW_GET_","CHAT_START","MCP_TOOL_EXECUTE","MAIN_THREAD_TOOL_REQUEST"].some(t=>n.includes(t))}function Zs(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function En(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return Dt(e)}catch{return"[Non-serializable data]"}}function er(){const n={total:oe.length,sent:0,received:0,byType:{}};for(const e of oe)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const vt=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:Qs,getAllLogs:Xe,getLogStats:er,isPostMessageLoggerDebugMode:Rt,logReceivedMessage:Lt,setPostMessageLoggerDebugMode:Cn,updateRequestWithResponse:Mt},Symbol.toStringTag,{value:"Module"}));function tr(){return typeof window<"u"?window:typeof self<"u"?self:{}}function nr(n){return JSON.parse(JSON.stringify(n))}function Tn(n){const e=Date.now().toString(36);let t;if(typeof crypto<"u"&&crypto.getRandomValues){const s=new Uint32Array(2);crypto.getRandomValues(s),t=s[0].toString(36)+s[1].toString(36)}else t=Math.floor(1e10*Math.random()).toString(36);return`${n}${e}${t}_`}const sr="postmessage-duplex",rr="1.2.0",Ye=tr();var X,ae;Ye.__POSTMESSAGE_DUPLEX__||(Ye.__POSTMESSAGE_DUPLEX__={}),Ye.__POSTMESSAGE_DUPLEX__.version=rr,Ye.__POSTMESSAGE_DUPLEX__.name=sr,(function(n){n[n.Success=0]="Success",n[n.ReceiverCallbackError=-1]="ReceiverCallbackError",n[n.SendCallbackError=-2]="SendCallbackError",n[n.NoSubscribe=-3]="NoSubscribe",n[n.TimeOut=-99]="TimeOut"})(X||(X={})),(function(n){n.ConnectionDestroyed="CONNECTION_DESTROYED",n.ConnectionTimeout="CONNECTION_TIMEOUT",n.MethodCallTimeout="METHOD_CALL_TIMEOUT",n.MethodNotFound="METHOD_NOT_FOUND",n.TransmissionFailed="TRANSMISSION_FAILED",n.MessageSizeExceeded="MESSAGE_SIZE_EXCEEDED",n.RateLimitExceeded="RATE_LIMIT_EXCEEDED",n.HandlerError="HANDLER_ERROR",n.InvalidMessage="INVALID_MESSAGE",n.OriginMismatch="ORIGIN_MISMATCH",n.HeartbeatFailed="HEARTBEAT_FAILED",n.ReconnectFailed="RECONNECT_FAILED",n.HandshakeFailed="HANDSHAKE_FAILED",n.ServiceWorkerUnavailable="SERVICE_WORKER_UNAVAILABLE"})(ae||(ae={}));class ie extends Error{constructor(e,t,s){super(e),Object.defineProperty(this,"code",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"details",{enumerable:1,configurable:1,writable:1,value:void 0}),this.name="ChannelError",this.code=t,this.details=s,Error.captureStackTrace&&Error.captureStackTrace(this,ie)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class or{constructor(){Object.defineProperty(this,"timeouts",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timer",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"nextDeadline",{enumerable:1,configurable:1,writable:1,value:1/0}),Object.defineProperty(this,"destroyed",{enumerable:1,configurable:1,writable:1,value:0})}add(e,t,s){if(this.destroyed)return;const r=Date.now()+t;this.timeouts.set(e,{deadline:r,callback:s}),r<this.nextDeadline&&this.reschedule(r)}remove(e){return this.timeouts.delete(e)}has(e){return this.timeouts.has(e)}get size(){return this.timeouts.size}reschedule(e){this.timer!==null&&clearTimeout(this.timer),this.nextDeadline=e;const t=Math.max(0,e-Date.now());this.timer=setTimeout(()=>this.processTimeouts(),t)}processTimeouts(){if(this.destroyed)return;const e=Date.now(),t=[];for(const[s,{deadline:r,callback:o}]of this.timeouts)r<=e&&(t.push(o),this.timeouts.delete(s));for(const s of t)try{s()}catch(r){console.error("[TimeoutManager] Callback error:",r)}this.scheduleNext()}scheduleNext(){if(this.timeouts.size===0)return this.nextDeadline=1/0,void(this.timer=null);let e=1/0;for(const{deadline:t}of this.timeouts.values())t<e&&(e=t);e<1/0&&this.reschedule(e)}destroy(){this.destroyed=1,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}}class ar{constructor(e,t=1e3){Object.defineProperty(this,"limit",{enumerable:1,configurable:1,writable:1,value:e}),Object.defineProperty(this,"windowMs",{enumerable:1,configurable:1,writable:1,value:t}),Object.defineProperty(this,"timestamps",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"head",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"tail",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"count",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"enabled",{enumerable:1,configurable:1,writable:1,value:void 0}),this.enabled=e>0,this.timestamps=this.enabled?new Array(e).fill(0):[]}tryAcquire(){if(!this.enabled)return 1;const e=Date.now(),t=e-this.windowMs;for(;this.count>0&&this.timestamps[this.head]<=t;)this.head=(this.head+1)%this.limit,this.count--;return this.count>=this.limit?0:(this.timestamps[this.tail]=e,this.tail=(this.tail+1)%this.limit,this.count++,1)}getCurrentCount(){if(!this.enabled)return 0;const e=Date.now()-this.windowMs;let t=0,s=this.head;for(let r=0;r<this.count;r++)this.timestamps[s]>e&&t++,s=(s+1)%this.limit;return t}getRemainingCapacity(){return this.enabled?Math.max(0,this.limit-this.getCurrentCount()):1/0}getTimeUntilAvailable(){if(!this.enabled||this.count<this.limit)return 0;const e=Date.now()-this.windowMs;let t=this.head;for(;t!==this.tail;){if(this.timestamps[t]>e)return this.timestamps[t]-e;t=(t+1)%this.limit}return 0}isLimited(){return this.enabled?this.getCurrentCount()>=this.limit:0}reset(){this.head=0,this.tail=0,this.count=0,this.enabled&&this.timestamps.fill(0)}getLimit(){return this.limit}getWindowMs(){return this.windowMs}isEnabled(){return this.enabled}}class ir{constructor(){Object.defineProperty(this,"eventHandlers",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"eventsEnabled",{enumerable:1,configurable:1,writable:1,value:1})}on(e,t){let s=this.eventHandlers.get(e);return s||(s=new Set,this.eventHandlers.set(e,s)),s.add(t),()=>{s==null||s.delete(t),(s==null?void 0:s.size)===0&&this.eventHandlers.delete(e)}}once(e,t){const s=r=>{this.off(e,s),t(r)};return this.on(e,s)}off(e,t){const s=this.eventHandlers.get(e);if(!s)return 0;const r=s.delete(t);return s.size===0&&this.eventHandlers.delete(e),r}offAll(e){e?this.eventHandlers.delete(e):this.eventHandlers.clear()}emit(e,t){if(!this.eventsEnabled)return;const s=this.eventHandlers.get(e);if(s)for(const r of[...s])try{r(t)}catch(o){console.error(`[ChannelEventEmitter] Error in ${e} handler:`,o)}}hasListeners(e){const t=this.eventHandlers.get(e);return t!==void 0&&t.size>0}listenerCount(e){var t;return((t=this.eventHandlers.get(e))==null?void 0:t.size)??0}setEventsEnabled(e){this.eventsEnabled=e}destroyEventEmitter(){this.eventHandlers.clear(),this.eventsEnabled=0}}function _n(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const Z=n=>({valid:0,error:n});function cr(n){if(!_n(n))return Z("Message must be an object");const e=n,t="requestId"in e,s="cmdname"in e,r="msg"in e,o="ret"in e;return t||s||r?t&&typeof e.requestId!="string"?Z("requestId must be a string"):s&&typeof e.cmdname!="string"?Z("cmdname must be a string"):r&&typeof e.msg!="string"?Z("msg must be a string"):!o||typeof(a=e.ret)=="number"&&Object.values(X).includes(a)?"data"in e&&e.data!==void 0&&!_n(e.data)?Z("data must be an object"):"_senderKey"in e&&e._senderKey!==void 0&&typeof e._senderKey!="string"?Z("_senderKey must be a string"):!("time"in e)||e.time===void 0||typeof e.time=="number"&&Number.isFinite(e.time)?{valid:1,message:e}:Z("time must be a finite number"):Z("ret must be a valid ReturnCode"):Z("Message must have requestId, cmdname, or msg field");var a}function Qe(n){return"ret"in n&&typeof n.ret=="number"}function lr(n){return n.msg==="ready"}function ur(n){return n._broadcast==1&&typeof n.cmdname=="string"}function dr(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const It=[],ee=[];function Dn(n){ee.length>=200&&ee.shift(),ee.push(n)}function An(n,e){for(let t=ee.length-1;t>=0;t--)if(ee[t].requestId===n&&ee[t].status==="pending"){ee[t].status=e,ee[t].duration=Date.now()-ee[t].timestamp;break}}class hr extends ir{constructor(e){if(super(),Object.defineProperty(this,"baseKey",{enumerable:1,configurable:1,writable:1,value:""}),Object.defineProperty(this,"peerKey",{enumerable:1,configurable:1,writable:1,value:""}),Object.defineProperty(this,"reqTime",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"callbackMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"subscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"broadcastHandlers",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timeout",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"isReady",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"isDestroyed",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"postTasks",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"bindOnMessage",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"console",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"maxMessageSize",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"timeoutManager",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"rateLimiter",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"strictValidation",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"requestCmdMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"isProcessingBatch",{enumerable:1,configurable:1,writable:1,value:0}),this.timeout=(e==null?void 0:e.timeout)??5e3,this.console=(e==null?void 0:e.log)??(typeof window<"u"?window.console:console),this.maxMessageSize=(e==null?void 0:e.maxMessageSize)??1048576,this.strictValidation=(e==null?void 0:e.strictValidation)??1,this.timeoutManager=new or,this.rateLimiter=new ar((e==null?void 0:e.rateLimit)??100,1e3),e==null?void 0:e.subscribeMap)for(const s in e.subscribeMap)this.subscribeMap.set(s,e.subscribeMap[s]);var t;this.bindOnMessage=this.onMessage.bind(this),t=this,It.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{Dn({direction:"send",cmdname:s,requestId:r,status:"pending",timestamp:Date.now(),dataSummary:""})}),t.on("message:received",({cmdname:s,requestId:r,isResponse:o})=>{const a=s||"",i=r||"";o?An(i,"ok"):Dn({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{An(r,"timeout")}),t.on("error",({context:s})=>{}),t.on("destroy",()=>{})}checkRateLimit(){if(!this.rateLimiter.isEnabled())return 1;if(!this.rateLimiter.tryAcquire()){const e=this.rateLimiter.getCurrentCount(),t=this.rateLimiter.getLimit();return this.log("warn","Rate limit exceeded:",e,"/",t,"messages per second"),this.emit("rate:limited",{currentCount:e,limit:t}),0}return 1}validateMessageSize(e){if(this.maxMessageSize<=0)return;const t=dr(e);if(t>this.maxMessageSize){const s=new ie(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ae.MessageSizeExceeded,{size:t,limit:this.maxMessageSize});throw this.emit("error",{error:s,context:"validateMessageSize"}),s}}init(){this.setupMessageListener(),this.sendMessage({requestId:this.baseKey+this.reqTime,msg:"ready",_senderKey:this.baseKey})}log(e,...t){var s,r;(r=(s=this.console)==null?void 0:s[e])==null||r.call(s,`[${this.channelType}]: `,...t)}isFromPeer(e){return this.peerKey?e._senderKey&&e._senderKey!==this.peerKey?(this.log("log","Message from non-paired channel, ignored",e._senderKey,"expected:",this.peerKey),0):Qe(e)&&e.requestId&&!e.requestId.startsWith(this.baseKey)?0:1:1}sendMessage(e,t){this.validateMessageSize(e),this.checkRateLimit()?(e.time=Date.now(),e._senderKey=this.baseKey,this.sendRawMessage(e,t)):this.log("warn","Message dropped due to rate limiting")}async onMessage(e){if(this.log("log","onMessage",e.data),!this.isValidSource(e))return;if(this.strictValidation){const o=cr(e.data);if(!o.valid)return this.log("warn","Invalid message structure:",o.error),void this.emit("validation:failed",{reason:o.error,data:e.data})}const t=e.data;if(!t||!this.isFromPeer(t))return;this.emit("message:received",{cmdname:t.cmdname||"",requestId:t.requestId||"",isResponse:Qe(t)});const{requestId:s,cmdname:r}=t;this.handleResponseMessage(t,s)||this.handleBroadcastMessage(t,r)||await this.handleSubscriptionMessage(t,s,r)||this.handleReadyMessage(t,s)||this.handleUnhandledMessage(t,s,r)}handleResponseMessage(e,t){const s=t?this.callbackMap.get(t):void 0;return s&&t?(this.timeoutManager.remove(t),this.requestCmdMap.delete(t),s.resolve(e),this.deleteCallback(t),1):0}handleBroadcastMessage(e,t){if(!ur(e))return 0;const s=t?this.broadcastHandlers.get(t):void 0;if(s)try{s({cmdname:t,data:e.data})}catch(r){const o=r instanceof Error?r.message:String(r);this.emit("error",{error:r instanceof Error?r:new Error(o),context:`broadcast:${t}`})}return 1}async handleSubscriptionMessage(e,t,s){if(!s)return 0;const r=this.subscribeMap.get(s);if(!r)return 0;try{const o=await r(e);this.sendMessage({requestId:t,ret:X.Success,data:o})}catch(o){const a=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:X.ReceiverCallbackError,msg:a||"unknown error"}),this.emit("error",{error:o instanceof Error?o:new Error(a),context:`handler:${s}`})}return 1}handleReadyMessage(e,t){if(!lr(e))return 0;const{_senderKey:s}=e;return s&&!this.peerKey&&(this.peerKey=s,this.log("log","Point-to-point pairing established","self:",this.baseKey,"peer:",this.peerKey)),this.isReady=1,this.executePosts(),this.emit("ready",{peerKey:this.peerKey}),Qe(e)||this.sendMessage({requestId:t,ret:X.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!Qe(e)&&(this.log("warn","No registered handler for:",s||t),this.sendMessage({requestId:t,ret:X.NoSubscribe}))}postMessage(e,t){try{this.sendMessage(e,t),this.emit("message:sent",{cmdname:e.cmdname||"",requestId:e.requestId||""})}catch(s){this.log("error",s,e),this.emit("error",{error:s instanceof Error?s:new Error(String(s)),context:"postMessage"})}}publish(e,t,s){if(this.isDestroyed)return Promise.reject(new ie("Cannot publish: channel has been destroyed",ae.ConnectionDestroyed,{cmdname:e}));const r=this.baseKey+ ++this.reqTime,o={requestId:r,cmdname:e,data:t};this.requestCmdMap.set(r,e);const a=new Promise((i,c)=>{this.callbackMap.set(r,{resolve:i,reject:c})});return this.log("log","publish",this.isReady,this.postTasks.size),this.isReady?this.doPublish(o,s):this.postTasks.set(r,{data:o,prm:a,options:s}),a}doPublish(e,t){const{requestId:s,cmdname:r}=e,o=(t==null?void 0:t.timeout)??this.timeout;this.timeoutManager.add(s,o,()=>{const a=this.callbackMap.get(s);if(a){const i={req:e,requestId:s,ret:X.TimeOut,time:Date.now(),msg:"timeout"};this.log("error","postmessage timeout",i),this.emit("timeout",{requestId:s,cmdname:r,timeoutMs:o}),a.resolve(i),this.deleteCallback(s),this.requestCmdMap.delete(s)}}),this.postMessage(e,t==null?void 0:t.transferables)}deleteCallback(e){this.callbackMap.delete(e),this.postTasks.delete(e),this.timeoutManager.remove(e)}executePosts(){this.postTasks.size===0||this.isProcessingBatch||(this.isProcessingBatch=1,queueMicrotask(()=>{this.processBatch(),this.isProcessingBatch=0}))}processBatch(){const e=Array.from(this.postTasks.entries());for(const[t,s]of e)this.postTasks.has(t)&&(t.startsWith("_broadcast_")?(this.doBroadcast(s.data,s.options),this.postTasks.delete(t)):this.doPublish(s.data,s.options))}call(e,t,s){return this.publish(e,t,s)}subscribe(e,t){return this.subscribeMap.has(e)&&this.log("warn",`${e} has been subscribed`),this.subscribeMap.set(e,t),this}unSubscribe(e){return this.subscribeMap.delete(e),this}subscribeOnce(e,t){return this.subscribe(e,async s=>(this.unSubscribe(e),t(s)))}broadcast(e,t,s){if(this.isDestroyed)return void this.log("warn","Cannot broadcast: channel has been destroyed");const r={cmdname:e,data:t,time:Date.now(),_broadcast:1};if(this.log("log","broadcast",e,this.isReady),this.isReady)this.doBroadcast(r,s);else{const o=`_broadcast_${Date.now()}_${Math.random()}`;this.postTasks.set(o,{data:r,prm:Promise.resolve({}),options:s})}}doBroadcast(e,t){try{this.sendMessage(e,t==null?void 0:t.transferables),this.emit("broadcast:sent",{cmdname:e.cmdname})}catch(s){this.log("error","broadcast error",s,e),this.emit("error",{error:s instanceof Error?s:new Error(String(s)),context:"broadcast"})}}onBroadcast(e,t){return this.broadcastHandlers.has(e)&&this.log("warn",`Broadcast handler for ${e} already registered, replacing`),this.broadcastHandlers.set(e,t),this}offBroadcast(e){return this.broadcastHandlers.delete(e),this}getPeerKey(){return this.peerKey}getRateLimitStats(){return{current:this.rateLimiter.getCurrentCount(),limit:this.rateLimiter.getLimit(),remaining:this.rateLimiter.getRemainingCapacity()}}getPendingCount(){return this.callbackMap.size}destroy(){if(this.isDestroyed)return;this.isDestroyed=1,this.emit("destroy",{reason:"explicit"}),(function(t){const s=It.findIndex(r=>r.deref()===t);s!==-1&&It.splice(s,1)})(this);const e=new ie("Channel has been destroyed",ae.ConnectionDestroyed);for(const[t,s]of this.callbackMap)try{s.reject({ret:X.SendCallbackError,msg:e.message})}catch(r){this.log("warn","Error rejecting pending request:",t,r)}this.removeMessageListener(),this.subscribeMap.clear(),this.broadcastHandlers.clear(),this.postTasks.clear(),this.callbackMap.clear(),this.requestCmdMap.clear(),this.timeoutManager.destroy(),this.rateLimiter.reset(),this.destroyEventEmitter(),this.isReady=0,this.peerKey=""}}class Y{constructor(){Object.defineProperty(this,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"initialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"options",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(this,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"channelFactory",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"globalMessageHandler",{enumerable:1,configurable:1,writable:1,value:e=>{const t=e.source,s=t==null?void 0:t.id;if(!s)return;const r=this.channelsByClientId.get(s);r?r.handleMessage(e):this.unknownClientCallback&&this.unknownClientCallback(s,e)}})}static getInstance(){return Y.instance||(Y.instance=new Y),Y.instance}static resetInstance(){Y.instance&&(Y.instance.shutdown(),Y.instance=null)}setup(e,t){if(this.initialized)return void console.warn("[ServiceWorkerHub] Already initialized");this.options=e,this.channelFactory=t,this.initialized=1,this.registerBuiltInHandlers(),this.setupLifecycleEvents();const s=e.cleanupInterval??3e4;s>0&&(this.cleanupIntervalId=setInterval(()=>this.cleanupInactiveClients(),s))}shutdown(){this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.globalListenerSetup&&(self.removeEventListener("message",this.globalMessageHandler),this.globalListenerSetup=0);for(const e of this.channelsByClientId.values())try{e.destroy()}catch{}this.channelsByClientId.clear(),this.clientMeta.clear(),this.globalSubscribeMap.clear(),this.initialized=0}isInitialized(){return this.initialized}getOptions(){return this.options}enableGlobalRouting(e){this.unknownClientCallback=e??null,this.globalListenerSetup||(self.addEventListener("message",this.globalMessageHandler),this.globalListenerSetup=1)}disableGlobalRouting(){this.globalListenerSetup&&(self.removeEventListener("message",this.globalMessageHandler),this.globalListenerSetup=0)}isGlobalRoutingEnabled(){return this.globalListenerSetup}registerChannel(e,t){this.channelsByClientId.set(e,t),this.applyGlobalHandlersToChannel(t,e)}unregisterChannel(e){var t,s;this.channelsByClientId.delete(e),this.clientMeta.delete(e),(s=(t=this.options).onClientDisconnect)==null||s.call(t,e)}getChannel(e){return this.channelsByClientId.get(e)}hasChannel(e){return this.channelsByClientId.has(e)}getChannelCount(){return this.channelsByClientId.size}createChannelForClient(e){if(!this.channelFactory)return console.warn("[ServiceWorkerHub] No channel factory configured"),null;const t=this.channelFactory(e);return this.registerChannel(e,t),t}registerClientMeta(e,t){var r,o;const s={clientId:e,appType:t.appType,appName:t.appName,connectedAt:new Date().toISOString()};return this.clientMeta.set(e,s),(o=(r=this.options).onClientConnect)==null||o.call(r,e,s),s}getClientMeta(e){return this.clientMeta.get(e)}getAllClientMeta(){return new Map(this.clientMeta)}getClientsByType(e){const t=[];for(const s of this.clientMeta.values())s.appType===e&&t.push(s);return t}subscribeGlobal(e,t){e.startsWith("__")&&console.warn(`[ServiceWorkerHub] Handler name '${e}' uses reserved prefix '__'.`),this.globalSubscribeMap.set(e,t);for(const[s,r]of this.channelsByClientId)this.applyHandlerToChannel(r,s,e,t)}unsubscribeGlobal(e){this.globalSubscribeMap.delete(e);for(const t of this.channelsByClientId.values())t.unSubscribe(e)}applyGlobalHandlersToChannel(e,t){for(const[s,r]of this.globalSubscribeMap)this.applyHandlerToChannel(e,t,s,r)}applyHandlerToChannel(e,t,s,r){e.subscribe(s,async o=>{const a=this.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:a})})}registerBuiltInHandlers(){this.globalSubscribeMap.set("__register__",({data:e,clientId:t})=>(this.registerClientMeta(t,{appType:e.appType,appName:e.appName}),{success:1,clientId:t,totalClients:this.clientMeta.size})),this.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:this.channelsByClientId.size}))}setupLifecycleEvents(){self.addEventListener("install",e=>{typeof self.skipWaiting=="function"&&self.skipWaiting()}),self.addEventListener("activate",e=>{const t=(async()=>{var s;typeof((s=self.clients)==null?void 0:s.claim)=="function"&&await self.clients.claim(),await this.notifyAllClientsSwActivated()})();typeof e.waitUntil=="function"&&e.waitUntil(t)})}async notifyAllClientsSwActivated(){try{const e=await self.clients.matchAll();for(const t of e)t.postMessage({cmdname:"__sw-activated__",data:{version:this.options.version},_broadcast:1})}catch(e){console.error("[ServiceWorkerHub] Error notifying clients:",e)}}async cleanupInactiveClients(){var e,t;try{const s=await self.clients.matchAll(),r=new Set(s.map(o=>o.id));for(const[o,a]of this.channelsByClientId)r.has(o)||(a.destroy(),this.channelsByClientId.delete(o),this.clientMeta.delete(o),(t=(e=this.options).onClientDisconnect)==null||t.call(e,o))}catch(s){console.error("[ServiceWorkerHub] Cleanup error:",s)}}async broadcastToAll(e,t,s){if(!this.initialized)return console.warn("[ServiceWorkerHub] Not initialized"),0;try{const r=await self.clients.matchAll();let o=0;for(const a of r){if(s&&a.id===s)continue;const i=this.channelsByClientId.get(a.id);if(i)try{i.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",a.id,c)}}return o}catch(r){return console.error("[ServiceWorkerHub] broadcastToAll error:",r),0}}async broadcastToType(e,t,s,r){if(!this.initialized)return console.warn("[ServiceWorkerHub] Not initialized"),0;try{const o=await self.clients.matchAll();let a=0;for(const i of o){if(r&&i.id===r)continue;const c=this.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=this.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(h){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",i.id,h)}}return a}catch(o){return console.error("[ServiceWorkerHub] broadcastToType error:",o),0}}}Object.defineProperty(Y,"instance",{enumerable:1,configurable:1,writable:1,value:null});class m extends hr{static enableGlobalRouting(e){m.useGlobalRouting=1,m.unknownClientCallback=e??null,m.globalListenerSetup||(self.addEventListener("message",m.globalMessageHandler),m.globalListenerSetup=1)}static disableGlobalRouting(){m.useGlobalRouting=0,m.globalListenerSetup&&(self.removeEventListener("message",m.globalMessageHandler),m.globalListenerSetup=0)}static setupHub(e={}){if(m.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");m.hubOptions=e,m.hubInitialized=1,Y.getInstance().setup(e,s=>m.createFromWorker(s)),m.enableGlobalRouting((s,r)=>{const o=m.createFromWorker(s);m.setupChannelHandlers(o,s),o.handleMessage(r)}),m.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(m.cleanupIntervalId=setInterval(()=>m.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){m.globalSubscribeMap.set("__register__",({data:e,clientId:t})=>{var r,o;const s={clientId:t,appType:e.appType,appName:e.appName,connectedAt:new Date().toISOString()};return m.clientMeta.set(t,s),(o=(r=m.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:m.clientMeta.size}}),m.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:m.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of m.globalSubscribeMap)e.subscribe(s,async o=>{const a=m.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:a})})}static setupLifecycleEvents(){self.addEventListener("install",()=>{typeof self.skipWaiting=="function"&&self.skipWaiting()}),self.addEventListener("activate",e=>{const t=(async()=>{var s;typeof((s=self.clients)==null?void 0:s.claim)=="function"&&await self.clients.claim(),await m.notifyAllClientsSwActivated()})();typeof e.waitUntil=="function"&&e.waitUntil(t)})}static async notifyAllClientsSwActivated(){try{const e=await self.clients.matchAll();for(const t of e)t.postMessage({cmdname:"__sw-activated__",data:{version:m.hubOptions.version},_broadcast:1})}catch(e){console.error("[ServiceWorkerChannel] Error notifying clients:",e)}}static async cleanupInactiveClients(){var e,t;try{const s=await self.clients.matchAll(),r=new Set(s.map(o=>o.id));for(const[o]of m.channelsByClientId)if(!r.has(o)){const a=m.channelsByClientId.get(o);a&&a.destroy(),m.clientMeta.delete(o),(t=(e=m.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!m.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const r=await self.clients.matchAll();let o=0;for(const a of r){if(s&&a.id===s)continue;const i=m.channelsByClientId.get(a.id);if(i)try{i.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",a.id,c)}}return o}catch(r){return console.error("[ServiceWorkerChannel] broadcastToAll error:",r),0}}static async broadcastToType(e,t,s,r){if(!m.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const o=await self.clients.matchAll();let a=0;for(const i of o){if(r&&i.id===r)continue;const c=m.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=m.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(h){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",i.id,h)}}return a}catch(o){return console.error("[ServiceWorkerChannel] broadcastToType error:",o),0}}static getClientInfo(e){return m.clientMeta.get(e)}static getAllClients(){return new Map(m.clientMeta)}static getClientsByType(e){const t=[];for(const s of m.clientMeta.values())s.appType===e&&t.push(s);return t}static subscribeGlobal(e,t){e.startsWith("__")&&console.warn(`[ServiceWorkerChannel] Handler name '${e}' uses reserved prefix '__'. This may conflict with internal handlers.`),m.globalSubscribeMap.set(e,t);for(const[s,r]of m.channelsByClientId)r.subscribe(e,async o=>{const a=m.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:a})})}static unsubscribeGlobal(e){m.globalSubscribeMap.delete(e);for(const t of m.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&m.useGlobalRouting&&m.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&m.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return m.channelsByClientId.get(e)}static hasChannel(e){return m.channelsByClientId.has(e)}static getChannelCount(){return m.channelsByClientId.size}handleMessage(e){return this.onMessage(e)}constructor(e,t){if(super(t),Object.defineProperty(this,"channelType",{enumerable:1,configurable:1,writable:1,value:"ServiceWorkerChannel"}),Object.defineProperty(this,"isWorkerSide",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"worker",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"clientId",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"swContainer",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"l",{enumerable:1,configurable:1,writable:1,value:"connecting"}),Object.defineProperty(this,"lastSuccessfulMessageTime",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"heartbeatIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"missedHeartbeatCount",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"isReconnecting",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"reconnectAttempt",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"connectionOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(this,"boundControllerChangeHandler",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"boundStateChangeHandler",{enumerable:1,configurable:1,writable:1,value:null}),this.isWorkerSide=(t==null?void 0:t.isWorkerSide)??0,this.isWorkerSide){if(typeof e!="string")throw new Error("Service Worker 端必须传入 clientId 字符串");this.clientId=e,this.baseKey=Tn("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=Tn("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(m.useGlobalRouting)return void(m.globalListenerSetup||(self.addEventListener("message",m.globalMessageHandler),m.globalListenerSetup=1));self.addEventListener("message",this.bindOnMessage)}else(e=this.swContainer)==null||e.addEventListener("message",this.bindOnMessage)}removeMessageListener(){var e;if(this.unregisterFromGlobalRouter(),this.isWorkerSide){if(m.useGlobalRouting)return;self.removeEventListener("message",this.bindOnMessage)}else(e=this.swContainer)==null||e.removeEventListener("message",this.bindOnMessage)}sendRawMessage(e,t){var s,r;try{const o=nr(e);this.isWorkerSide?this.sendToClient(o,t):t&&t.length>0?(s=this.worker)==null||s.postMessage(o,t):(r=this.worker)==null||r.postMessage(o)}catch(o){this.log("error","sendMessage error",o,e)}}async sendToClient(e,t){const s=this.clientId;if(s)try{const r=await self.clients.get(s);r?t&&t.length>0?r.postMessage(e,t):r.postMessage(e):this.log("warn","Client not found:",s)}catch(r){this.log("error","sendToClient error",r)}else this.log("error","No clientId available")}isValidSource(e){if(this.isWorkerSide){const t=e.source;return(t==null?void 0:t.id)===this.clientId}return 1}log(e,...t){var r,o;const s=this.isWorkerSide?"worker":"page";(o=(r=this.console)==null?void 0:r[e])==null||o.call(r,`[ServiceWorkerChannel](${s}): `,...t)}getClientId(){return this.clientId}isWorkerAvailable(){var e;return this.isWorkerSide||((e=this.worker)==null?void 0:e.state)==="activated"}async refreshWorker(){if(this.isWorkerSide)throw new Error("refreshWorker() can only be called on page side");const e=(await navigator.serviceWorker.ready).active||navigator.serviceWorker.controller;e?(this.worker=e,this.peerKey="",this.isReady=0,this.sendMessage({requestId:this.baseKey+this.reqTime,msg:"ready",_senderKey:this.baseKey})):console.warn("[ServiceWorkerChannel] No active Service Worker found during refresh")}get connectionState(){return this.l}get isConnected(){return this.l==="connected"}updateLastMessageTime(){this.lastSuccessfulMessageTime=Date.now()}setConnectionState(e,t){if(this.l===e)return;const s=this.l;switch(this.l=e,this.log("log",`Connection state: ${s} -> ${e}`),e){case"connected":this.missedHeartbeatCount=0,this.reconnectAttempt=0,this.emit("connected",{isReconnect:s==="reconnecting"});break;case"disconnected":this.emit("disconnected",{reason:(t==null?void 0:t.reason)||"error",error:t==null?void 0:t.error});break;case"reconnecting":this.emit("reconnecting",{attempt:(t==null?void 0:t.attempt)||this.reconnectAttempt,maxAttempts:this.connectionOptions.maxReconnectAttempts||5,nextRetryIn:(t==null?void 0:t.nextRetryIn)||0})}}startHeartbeat(){if(this.isWorkerSide)return;const e=this.connectionOptions.heartbeatInterval??3e4;e<=0||(this.stopHeartbeat(),this.heartbeatIntervalId=setInterval(()=>{this.performHeartbeat()},e),this.log("log",`Heartbeat started with interval ${e}ms`))}stopHeartbeat(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null)}async performHeartbeat(){const e=this.connectionOptions.heartbeatInterval??3e4;if(this.connectionOptions.smartHeartbeat!=0&&this.lastSuccessfulMessageTime>0&&Date.now()-this.lastSuccessfulMessageTime<e)return this.missedHeartbeatCount=0,void this.emit("heartbeat",{success:1,missedCount:0});const t=this.connectionOptions.heartbeatTimeout??5e3,s=Date.now();try{if((await this.publish("__ping__",{},{timeout:t})).ret===X.Success){const r=Date.now()-s;this.missedHeartbeatCount=0,this.updateLastMessageTime(),this.emit("heartbeat",{success:1,latencyMs:r,missedCount:0}),this.l==="reconnecting"&&this.setConnectionState("connected")}else this.handleHeartbeatFailure()}catch(r){this.handleHeartbeatFailure(r instanceof Error?r:void 0)}}handleHeartbeatFailure(e){this.missedHeartbeatCount++;const t=this.connectionOptions.maxMissedHeartbeats??3;this.emit("heartbeat",{success:0,missedCount:this.missedHeartbeatCount}),this.log("warn",`Heartbeat failed (${this.missedHeartbeatCount}/${t})`),this.missedHeartbeatCount>=t&&(this.log("error","Connection lost: heartbeat threshold exceeded"),this.setConnectionState("disconnected",{reason:"heartbeat_failed",error:e||new ie("Heartbeat detection failed",ae.HeartbeatFailed,{missedCount:this.missedHeartbeatCount})}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect())}async attemptReconnect(){if(this.isReconnecting||this.isDestroyed)return;const e=this.connectionOptions.maxReconnectAttempts??5;if(e<=0)return;this.isReconnecting=1,this.reconnectAttempt=0;const t=this.connectionOptions.reconnectBaseDelay??1e3,s=this.connectionOptions.maxReconnectDelay??3e4;for(;this.reconnectAttempt<e&&!this.isDestroyed;){this.reconnectAttempt++;const r=Math.min(t*Math.pow(2,this.reconnectAttempt-1),s);if(this.setConnectionState("reconnecting",{attempt:this.reconnectAttempt,nextRetryIn:r}),await this.delay(r),this.isDestroyed)break;try{return await this.refreshWorker(),this.isReady||await this.waitForReady(this.connectionOptions.handshakeTimeout??1e4),(this.connectionOptions.appType||this.connectionOptions.appName)&&await this.publish("__register__",{appType:this.connectionOptions.appType,appName:this.connectionOptions.appName}),this.missedHeartbeatCount=0,this.setConnectionState("connected"),this.updateLastMessageTime(),this.isReconnecting=0,void this.log("log","Reconnection successful")}catch(o){this.log("warn",`Reconnection attempt ${this.reconnectAttempt} failed:`,o)}}this.isReconnecting=0,this.emit("reconnect:failed",{attempts:this.reconnectAttempt,lastError:new ie("All reconnection attempts failed",ae.ReconnectFailed,{attempts:this.reconnectAttempt})})}waitForReady(e){return new Promise((t,s)=>{if(this.isReady)return void t();const r=setTimeout(()=>{this.off("ready",o),s(new ie("Handshake timeout",ae.HandshakeFailed))},e),o=()=>{clearTimeout(r),t()};this.once("ready",o)})}delay(e){return new Promise(t=>setTimeout(t,e))}setupSwLifecycleListeners(){this.isWorkerSide||typeof navigator>"u"||(this.boundControllerChangeHandler=()=>{this.log("log","Service Worker controller changed"),this.handleControllerChange()},navigator.serviceWorker.addEventListener("controllerchange",this.boundControllerChangeHandler),this.worker&&(this.boundStateChangeHandler=()=>{var e;this.handleStateChange((e=this.worker)==null?void 0:e.state)},this.worker.addEventListener("statechange",this.boundStateChangeHandler)))}removeSwLifecycleListeners(){var e;this.boundControllerChangeHandler&&((e=navigator.serviceWorker)==null||e.removeEventListener("controllerchange",this.boundControllerChangeHandler),this.boundControllerChangeHandler=null),this.boundStateChangeHandler&&this.worker&&(this.worker.removeEventListener("statechange",this.boundStateChangeHandler),this.boundStateChangeHandler=null)}handleControllerChange(){this.l==="connected"&&this.setConnectionState("disconnected",{reason:"controller_changed"}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect()}handleStateChange(e){this.log("log","Service Worker state changed:",e),e==="redundant"&&(this.l==="connected"&&this.setConnectionState("disconnected",{reason:"sw_terminated"}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect())}static async createFromPage(e){if(!("serviceWorker"in navigator))throw new Error("Service Worker is not supported in this browser");if(e!=null&&e.swUrl)try{const l={};e.swScope&&(l.scope=e.swScope),await navigator.serviceWorker.register(e.swUrl,l)}catch(l){throw console.error("[ServiceWorkerChannel] Failed to register Service Worker:",l),l}const t=(await navigator.serviceWorker.ready).active||navigator.serviceWorker.controller;if(!t)throw new Error("No active Service Worker found");const s=new m(t,e);s.connectionOptions=e||{};const r=(e==null?void 0:e.appType)||(e==null?void 0:e.appName);let o=0,a=0;const i=async()=>{if(!a){a=1;try{await s.publish("__register__",{appType:e==null?void 0:e.appType,appName:e==null?void 0:e.appName}),o=1,s.updateLastMessageTime()}catch(l){console.warn("[ServiceWorkerChannel] Auto-registration failed:",l)}finally{a=0}}},c=()=>{s.setConnectionState("connected"),s.updateLastMessageTime(),s.startHeartbeat(),s.setupSwLifecycleListeners()};return r?s.isReady?(i(),c()):s.once("ready",()=>{i(),c()}):s.isReady?c():s.once("ready",c),(e==null?void 0:e.autoReconnect)!=0&&s.onBroadcast("__sw-activated__",async({data:l})=>{s.emit("sw-activated",{version:l==null?void 0:l.version}),s.setConnectionState("disconnected",{reason:"controller_changed"}),r&&(await s.refreshWorker(),o=0,await i()),s.setConnectionState("connected"),s.updateLastMessageTime()}),s.on("message:received",({isResponse:l})=>{l&&s.updateLastMessageTime()}),s}static createFromWorker(e,t){return new m(e,{...t,isWorkerSide:1})}static createFromEvent(e,t){const s=e.source;if(!(s!=null&&s.id))throw new Error("Invalid message event: no client source");return m.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(m,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(m,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(m,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(m,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(m,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(m,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(m,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(m,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(m,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(m,"globalMessageHandler",{enumerable:1,configurable:1,writable:1,value:n=>{const e=n.source,t=e==null?void 0:e.id;if(!t)return;const s=m.channelsByClientId.get(t);s?s.handleMessage(n):m.unknownClientCallback&&m.unknownClientCallback(t,n)}});function gr(n,e,t){return Promise.race([n,new Promise(s=>setTimeout(()=>s(t),e))])}const C={THUMBNAIL_GENERATE:"thumbnail:generate",CRASH_SNAPSHOT:"crash:snapshot",CRASH_HEARTBEAT:"crash:heartbeat",CONSOLE_REPORT:"console:report",DEBUG_GET_STATUS:"debug:getStatus",DEBUG_ENABLE:"debug:enable",DEBUG_DISABLE:"debug:disable",DEBUG_GET_LOGS:"debug:getLogs",DEBUG_CLEAR_LOGS:"debug:clearLogs",DEBUG_GET_CONSOLE_LOGS:"debug:getConsoleLogs",DEBUG_CLEAR_CONSOLE_LOGS:"debug:clearConsoleLogs",DEBUG_GET_POSTMESSAGE_LOGS:"debug:getPostMessageLogs",DEBUG_CLEAR_POSTMESSAGE_LOGS:"debug:clearPostMessageLogs",DEBUG_GET_CRASH_SNAPSHOTS:"debug:getCrashSnapshots",DEBUG_CLEAR_CRASH_SNAPSHOTS:"debug:clearCrashSnapshots",DEBUG_GET_LLM_API_LOGS:"debug:getLLMApiLogs",DEBUG_GET_LLM_API_LOG_BY_ID:"debug:getLLMApiLogById",DEBUG_CLEAR_LLM_API_LOGS:"debug:clearLLMApiLogs",DEBUG_DELETE_LLM_API_LOGS:"debug:deleteLLMApiLogs",DEBUG_GET_CACHE_ENTRIES:"debug:getCacheEntries",DEBUG_GET_CACHE_STATS:"debug:getCacheStats",DEBUG_EXPORT_LOGS:"debug:exportLogs",CDN_GET_STATUS:"cdn:getStatus",CDN_RESET_STATUS:"cdn:resetStatus",CDN_HEALTH_CHECK:"cdn:healthCheck",UPGRADE_GET_STATUS:"upgrade:getStatus",UPGRADE_FORCE:"upgrade:force",CACHE_DELETE:"cache:delete",PING:"ping"},F={CACHE_IMAGE_CACHED:"cache:imageCached",CACHE_IMAGE_CACHE_FAILED:"cache:imageCacheFailed",CACHE_DELETED:"cache:deleted",CACHE_QUOTA_WARNING:"cache:quotaWarning",SW_NEW_VERSION_READY:"sw:newVersionReady",SW_ACTIVATED:"sw:activated",SW_UPDATED:"sw:updated",CONSOLE_LOG:"console:log",DEBUG_LOG:"debug:log",DEBUG_LLM_LOG:"debug:llmLog",DEBUG_STATUS_CHANGED:"debug:statusChanged",DEBUG_NEW_CRASH_SNAPSHOT:"debug:newCrashSnapshot",POSTMESSAGE_LOG_BATCH:"postmessage:logBatch"};let Pt={};function fr(n){Pt={...Pt,...n}}function D(){return Pt}const Te=class Te{constructor(e){this.channels=new Map,this.onDebugClientCountChanged=null,this.postMessageLogBuffer=[],this.postMessageLogTimer=null,this.POSTMESSAGE_LOG_BATCH_INTERVAL=500,this.sw=e,this.channels.clear(),m.enableGlobalRouting((t,s)=>{var o;this.ensureChannel(t);const r=(o=this.channels.get(t))==null?void 0:o.channel;r&&r.handleMessage(s)}),setInterval(()=>{this.cleanupDisconnectedClients().catch(()=>{}),this.cleanupStalePendingRequests().catch(()=>{})},6e4)}async cleanupStalePendingRequests(){try{await yn.cleanupStalePendingToolRequests()}catch(e){console.warn("[ChannelManager] Failed to cleanup stale pending requests:",e)}}setDebugClientCountChangedCallback(e){this.onDebugClientCountChanged=e}getDebugClientCount(){let e=0;for(const t of this.channels.values())t.isDebugClient&&e++;return e}async isDebugClient(e){try{const t=await this.sw.clients.get(e);if(t&&t.url)return t.url.includes("sw-debug")}catch{}return!1}static getInstance(e){return Te.instance||(Te.instance=new Te(e)),Te.instance}ensureChannel(e){let t=this.channels.get(e);return t||(t={channel:m.createFromWorker(e,{timeout:12e4,subscribeMap:this.createSubscribeMap(e),log:{log:()=>{},warn:()=>{},error:()=>{}}}),clientId:e,createdAt:Date.now(),isDebugClient:!1},this.channels.set(e,t),this.checkAndUpdateDebugClient(e)),t.channel}async checkAndUpdateDebugClient(e){var r;const t=await this.isDebugClient(e),s=this.channels.get(e);s&&t&&(s.isDebugClient=!0,(r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}hasAnyClientChannel(){return this.channels.size>0}unwrapRpcData(e){return e&&typeof e=="object"&&"cmdname"in e?e.data:e}broadcastPostMessageLog(e){if(!e)return;const s=Xe().find(r=>r.id===e);s&&this.sendPostMessageLog(s)}wrapRpcHandler(e,t,s){return async r=>{var l;const o=this.unwrapRpcData(r),a=Date.now(),i=r==null?void 0:r.requestId,c=Rt()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const h=Lt(`RPC:${e}`,{params:o,requestId:i},t);this.broadcastPostMessageLog(h)}try{const h=await s(o);try{JSON.stringify(h)}catch(d){throw console.error(`[SW wrapRpcHandler] ${e} result serialization failed:`,d),new Error(`Result serialization failed: ${d}`)}if(c&&i){const d=Mt(i,{result:h},Date.now()-a);d&&this.broadcastPostMessageLog(d)}return h}catch(h){if(console.error(`[SW wrapRpcHandler] ${e} error:`,h),c&&i){const d=Mt(i,null,Date.now()-a,String(h));d&&this.broadcastPostMessageLog(d)}throw h}}}createSubscribeMap(e){return{[C.THUMBNAIL_GENERATE]:this.wrapRpcHandler(C.THUMBNAIL_GENERATE,e,t=>this.handleThumbnailGenerate(t)),[C.CRASH_SNAPSHOT]:async t=>{const s=this.unwrapRpcData(t);return this.handleCrashSnapshot(s)},[C.CRASH_HEARTBEAT]:async t=>{const s=this.unwrapRpcData(t);return this.handleHeartbeat(s)},[C.CONSOLE_REPORT]:async t=>{const s=this.unwrapRpcData(t);return this.handleConsoleReport(s)},[C.DEBUG_GET_STATUS]:async()=>this.handleDebugGetStatus(),[C.DEBUG_ENABLE]:async()=>this.handleDebugEnable(),[C.DEBUG_DISABLE]:async()=>this.handleDebugDisable(),[C.DEBUG_GET_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLogs(s)},[C.DEBUG_CLEAR_LOGS]:async()=>this.handleDebugClearLogs(),[C.DEBUG_GET_CONSOLE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetConsoleLogs(s)},[C.DEBUG_CLEAR_CONSOLE_LOGS]:async()=>this.handleDebugClearConsoleLogs(),[C.DEBUG_GET_POSTMESSAGE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetPostMessageLogs(s)},[C.DEBUG_CLEAR_POSTMESSAGE_LOGS]:async()=>this.handleDebugClearPostMessageLogs(),[C.DEBUG_GET_CRASH_SNAPSHOTS]:async()=>this.handleDebugGetCrashSnapshots(),[C.DEBUG_CLEAR_CRASH_SNAPSHOTS]:async()=>this.handleDebugClearCrashSnapshots(),[C.DEBUG_GET_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogs(s)},[C.DEBUG_GET_LLM_API_LOG_BY_ID]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogById(s==null?void 0:s.logId)},[C.DEBUG_CLEAR_LLM_API_LOGS]:async()=>this.handleDebugClearLLMApiLogs(),[C.DEBUG_DELETE_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugDeleteLLMApiLogs(s)},[C.DEBUG_GET_CACHE_ENTRIES]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetCacheEntries(s)},[C.DEBUG_GET_CACHE_STATS]:async()=>this.handleDebugGetCacheStats(),[C.DEBUG_EXPORT_LOGS]:async()=>this.handleDebugExportLogs(),[C.CDN_GET_STATUS]:async()=>this.handleCDNGetStatus(),[C.CDN_RESET_STATUS]:async()=>this.handleCDNResetStatus(),[C.CDN_HEALTH_CHECK]:async()=>this.handleCDNHealthCheck(),[C.UPGRADE_GET_STATUS]:async()=>this.handleUpgradeGetStatus(),[C.UPGRADE_FORCE]:async()=>this.handleUpgradeForce(),[C.CACHE_DELETE]:async t=>{const s=this.unwrapRpcData(t);return this.handleCacheDelete(s)},[C.PING]:async()=>this.handlePing()}}async handleThumbnailGenerate(e){try{const{url:t,mediaType:s,blob:r,mimeType:o,sizes:a}=e,{generateThumbnailAsync:i}=await Promise.resolve().then(()=>j),c=new Blob([r],{type:o||(s==="video"?"video/mp4":"image/png")});return i(c,t,s,a),{success:!0}}catch(t){return console.error("[SWChannelManager] Thumbnail generation failed:",t),{success:!1,error:t.message}}}async handleCrashSnapshot(e){var t,s;try{return await((s=(t=D()).saveCrashSnapshot)==null?void 0:s.call(t,e.snapshot)),{success:!0}}catch(r){return console.error("[SWChannelManager] Crash snapshot save failed:",r),{success:!1,error:r.message}}}async handleHeartbeat(e){return{success:!0}}serializeLogArg(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)}async handleConsoleReport(e){var t,s;try{const r=e.logArgs??[],a=(Array.isArray(r)?r.map(i=>this.serializeLogArg(i)):[this.serializeLogArg(r)]).join(" ");return(s=(t=D()).addConsoleLog)==null||s.call(t,{logLevel:e.logLevel,logMessage:a||"-"}),{success:!0}}catch(r){return{success:!1,error:r.message}}}async handleDebugGetStatus(){var e;try{const t=D(),s=((e=t.getDebugStatus)==null?void 0:e.call(t))||{},r=t.getCacheStats?await t.getCacheStats():void 0;return{...s,enabled:s.debugModeEnabled,cacheStats:r}}catch{return{debugModeEnabled:!1}}}async handleDebugEnable(){var e,t;try{const s=D();await((e=s.enableDebugMode)==null?void 0:e.call(s));const r=((t=s.getDebugStatus)==null?void 0:t.call(s))||{};return this.sendDebugStatusChanged(!0),{success:!0,status:r}}catch{return{success:!1}}}async handleDebugDisable(){var e,t;try{const s=D();await((e=s.disableDebugMode)==null?void 0:e.call(s));const r=((t=s.getDebugStatus)==null?void 0:t.call(s))||{};return this.sendDebugStatusChanged(!1),{success:!0,status:r}}catch{return{success:!1}}}async handleDebugGetLogs(e){var t,s;try{const r=D(),{limit:o=100,offset:a=0,filter:i}=e||{},c=(((t=r.getInternalFetchLogs)==null?void 0:t.call(r))||[]).map(b=>({...b,type:"fetch"})),l=((s=r.getDebugLogs)==null?void 0:s.call(r))||[],h=new Map;for(const b of l){const p=b.id;typeof p=="string"&&h.set(p,b)}for(const b of c){const p=b.id;typeof p=="string"&&h.set(p,b)}let d=Array.from(h.values()).sort((b,p)=>p.timestamp-b.timestamp);return i&&(i.type&&(d=d.filter(b=>b.type===i.type)),i.status&&(d=d.filter(b=>b.status===i.status))),{logs:d.slice(a,a+o),total:d.length,offset:a,limit:o}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||100}}}async handleDebugClearLogs(){var e,t;try{return(t=(e=D()).clearDebugLogs)==null||t.call(e),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){var t,s;try{const{limit:r=500,offset:o=0,filter:a}=e||{};let i=await(((s=(t=D()).loadConsoleLogsFromDB)==null?void 0:s.call(t))||Promise.resolve([]));if(a&&(a.logLevel&&(i=i.filter(l=>l.logLevel===a.logLevel)),a.search)){const l=a.search.toLowerCase();i=i.filter(h=>{var d,u;return((d=h.logMessage)==null?void 0:d.toLowerCase().includes(l))||((u=h.logStack)==null?void 0:u.toLowerCase().includes(l))})}return{logs:i.slice(o,o+r),total:i.length,offset:o,limit:r}}catch(r){return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||500,error:String(r)}}}async handleDebugClearConsoleLogs(){var e,t;try{const s=D();return(e=s.clearConsoleLogs)==null||e.call(s),await((t=s.clearAllConsoleLogs)==null?void 0:t.call(s)),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>vt),{limit:r=200,offset:o=0,filter:a}=e||{};let i=t();if(a&&(a.direction&&(i=i.filter(l=>l.direction===a.direction)),a.messageType)){const l=a.messageType.toLowerCase();i=i.filter(h=>{var d;return(d=h.messageType)==null?void 0:d.toLowerCase().includes(l)})}return{logs:i.slice(o,o+r),total:i.length,offset:o,limit:r,stats:s()}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||200}}}async handleDebugClearPostMessageLogs(){try{const{clearLogs:e}=await Promise.resolve().then(()=>vt);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){var e,t;try{const s=await(((t=(e=D()).getCrashSnapshots)==null?void 0:t.call(e))||Promise.resolve([]));return{snapshots:s,total:s.length}}catch(s){return{snapshots:[],total:0,error:String(s)}}}async handleDebugClearCrashSnapshots(){var e,t;try{return await((t=(e=D()).clearCrashSnapshots)==null?void 0:t.call(e)),{success:!0}}catch{return{success:!1}}}async handleDebugGetLLMApiLogs(e){try{const t=typeof(e==null?void 0:e.page)=="number"?e.page:Number(e==null?void 0:e.page)||1,s=typeof(e==null?void 0:e.pageSize)=="number"?e.pageSize:Number(e==null?void 0:e.pageSize)||20,r={taskType:typeof(e==null?void 0:e.taskType)=="string"?e.taskType:void 0,status:typeof(e==null?void 0:e.status)=="string"?e.status:void 0},{getLLMApiLogsPaginated:o}=await Promise.resolve().then(()=>Ee);return await o(t,s,r)}catch(t){return console.error("[SWChannelManager] handleDebugGetLLMApiLogs error:",t),{logs:[],total:0,page:1,pageSize:20,totalPages:0,error:String(t)}}}async handleDebugGetLLMApiLogById(e){try{if(!e)return{log:null,error:"Missing logId"};const{getLLMApiLogById:t}=await Promise.resolve().then(()=>Ee);return{log:await t(e)}}catch(t){return console.error("[SWChannelManager] handleDebugGetLLMApiLogById error:",t),{log:null,error:String(t)}}}async handleDebugClearLLMApiLogs(){try{const{clearAllLLMApiLogs:e}=await Promise.resolve().then(()=>Ee);return await e(),{success:!0}}catch{return{success:!1}}}async handleDebugDeleteLLMApiLogs(e){try{if(!(e!=null&&e.logIds)||e.logIds.length===0)return{success:!1,deletedCount:0};const{deleteLLMApiLogs:t}=await Promise.resolve().then(()=>Ee);return{success:!0,deletedCount:await t(e.logIds)}}catch{return{success:!1,deletedCount:0}}}async handleDebugGetCacheEntries(e){var t,s;try{const{cacheName:r=((s=(t=D()).getImageCacheName)==null?void 0:s.call(t))||"drawnix-images",limit:o=50,offset:a=0}=e||{},i=await caches.open(r),c=await i.keys(),l=[];for(let h=a;h<Math.min(a+o,c.length);h++){const d=c[h],u=await i.match(d);if(u){const b=u.headers.get("sw-cache-date"),p=u.headers.get("sw-cache-created-at")||b,g=u.headers.get("sw-image-size")||u.headers.get("content-length");l.push({url:d.url,cacheDate:b?parseInt(b):void 0,cacheCreatedAt:p?parseInt(p):void 0,size:g?parseInt(g):void 0})}}return{cacheName:r,entries:l,total:c.length,offset:a,limit:o}}catch(r){return{cacheName:(e==null?void 0:e.cacheName)||"",entries:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||50,error:String(r)}}}async handleDebugGetCacheStats(){try{const e=await caches.keys(),t=[];let s=0,r=0;for(const o of e){const a=await caches.open(o),i=await a.keys();let c=0;for(const l of i){const h=await a.match(l);if(h){const d=h.headers.get("content-length");d&&(c+=parseInt(d))}}t.push({name:o,count:i.length,size:c}),s+=i.length,r+=c}return{stats:{caches:t,totalCount:s,totalSize:r}}}catch(e){return{stats:{caches:[],totalCount:0,totalSize:0},error:String(e)}}}async handleDebugExportLogs(){var e,t,s,r;try{const o=D(),{getAllLogs:a}=await Promise.resolve().then(()=>vt),i=await(((e=o.loadConsoleLogsFromDB)==null?void 0:e.call(o))||Promise.resolve([])),c=a(),l=((t=o.getDebugLogs)==null?void 0:t.call(o))||[];return{exportTime:new Date().toISOString(),swVersion:((s=o.getAppVersion)==null?void 0:s.call(o))||"unknown",status:((r=o.getDebugStatus)==null?void 0:r.call(o))||{},fetchLogs:l,consoleLogs:i,postmessageLogs:c}}catch{return{exportTime:new Date().toISOString(),swVersion:"unknown",status:{},fetchLogs:[],consoleLogs:[],postmessageLogs:[]}}}async handleCDNGetStatus(){var e,t;try{return{status:((t=(e=D()).getCDNStatusReport)==null?void 0:t.call(e))||{}}}catch{return{status:{}}}}async handleCDNResetStatus(){var e,t;try{return(t=(e=D()).resetCDNStatus)==null||t.call(e),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){var e;try{const t=D(),s=t.performHealthCheck?await t.performHealthCheck(((e=t.getAppVersion)==null?void 0:e.call(t))||"unknown"):new Map;return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){var e,t;try{return{version:((t=(e=D()).getAppVersion)==null?void 0:t.call(e))||"unknown"}}catch{return{version:"unknown"}}}async handleUpgradeForce(){var e,t;try{return self.skipWaiting(),this.sendSWUpdated(((t=(e=D()).getAppVersion)==null?void 0:t.call(e))||"unknown"),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){var t,s;try{return await((s=(t=D()).deleteCacheByUrl)==null?void 0:s.call(t,e.url)),this.sendCacheDeleted(e.url),{success:!0}}catch(r){return{success:!1,error:String(r)}}}async handlePing(){return{success:!0}}broadcastToAll(e,t){this.channels.forEach(s=>{s.channel.broadcast(e,t)})}broadcastToOthers(e,t,s){this.channels.forEach(r=>{r.clientId!==s&&r.channel.broadcast(e,t)})}publishToClient(e,t,s){const r=this.channels.get(e);r&&r.channel.broadcast(t,s)}sendCacheImageCached(e,t,s){this.broadcastToAll(F.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheImageCacheFailed(e,t){this.broadcastToAll(F.CACHE_IMAGE_CACHE_FAILED,{url:e,error:t})}sendCacheDeleted(e){this.broadcastToAll(F.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(F.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(F.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(F.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(F.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(F.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(F.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(F.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(F.DEBUG_LLM_LOG,{log:e})}sendPostMessageLog(e){this.postMessageLogBuffer.push(e),this.postMessageLogTimer||(this.postMessageLogTimer=setTimeout(()=>{this.flushPostMessageLogs()},this.POSTMESSAGE_LOG_BATCH_INTERVAL))}flushPostMessageLogs(){if(this.postMessageLogTimer=null,this.postMessageLogBuffer.length===0)return;const e=this.postMessageLogBuffer;this.postMessageLogBuffer=[],this.broadcastToAll(F.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(F.DEBUG_NEW_CRASH_SNAPSHOT,{snapshot:e})}async requestVideoThumbnail(e,t=3e4,s){const r=Array.from(this.channels.values()).sort((o,a)=>o.isDebugClient===a.isDebugClient?a.createdAt-o.createdAt:o.isDebugClient?1:-1);if(r.length===0)return null;for(const o of r)try{const a=await gr(o.channel.call("thumbnail:generate",{url:e,maxSize:s}),t,"Video thumbnail generation timeout");if(!a||a.ret!==0)continue;const i=a.data;if(i!=null&&i.error||!(i!=null&&i.thumbnailUrl))continue;return i.thumbnailUrl}catch{continue}return null}getConnectedClients(){return Array.from(this.channels.keys())}getConnectedClientCount(){return this.channels.size}async cleanupDisconnectedClients(){var r;const e=await this.sw.clients.matchAll({type:"window"}),t=new Set(e.map(o=>o.id));let s=!1;for(const[o,a]of this.channels)t.has(o)||(a.isDebugClient&&(s=!0),this.channels.delete(o));s&&((r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}};Te.instance=null;let kt=Te,Je=null;function pr(n){return Je||(Je=kt.getInstance(n)),Je}function v(){return Je}function Ze(n){Cn(n)}const mr=[];let Rn=!1;function We(n){Rn=n}function Ot(){return Rn}function Wt(){return[...mr]}const br=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:Wt,isDebugFetchEnabled:Ot,setDebugFetchEnabled:We},Symbol.toStringTag,{value:"Module"})),yr=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),k={packageName:"aitu-app",healthCheckInterval:300*1e3,degradeTimeout:60*1e3,failThreshold:3,fetchTimeout:1500,backgroundFetchTimeout:8e3,localFetchTimeout:5e3,preferenceCacheExpiry:3600*1e3,preferenceCacheName:"drawnix-cdn-v1",preferenceCacheKey:typeof location<"u"?new URL("/__sw__/cdn-preference",location.origin).href:"https://opentu.local/__sw__/cdn-preference"},wr={jsdelivr:{baseTimeout:60*1e3,maxTimeout:300*1e3}},et=[{name:"jsdelivr",urlTemplate:"https://cdn.jsdelivr.net/npm/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:1}],be=new Map;let te=null,Bt=!1,tt=null;function Ln(n=!1){n&&be.clear(),et.forEach(e=>{be.has(e.name)||be.set(e.name,{name:e.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}Ln();function Sr(n){return n==="jsdelivr"||n==="local"}function Mn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!Sr(t)||typeof s!="string"||s.trim()==="")return null;const r=Number(e.latency),o=Number(e.timestamp);return{cdn:t,version:s.trim(),latency:Number.isFinite(r)&&r>=0?r:0,timestamp:Number.isFinite(o)&&o>0?o:Date.now()}}function vn(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=k.preferenceCacheExpiry}async function Cr(){if(typeof caches>"u")return null;try{const e=await(await caches.open(k.preferenceCacheName)).match(k.preferenceCacheKey);return e!=null&&e.ok?Mn(await e.json()):null}catch(n){return console.warn("[CDN Fallback] Failed to read persisted CDN preference:",n),null}}async function Nt(){Bt||(tt||(tt=(async()=>{te=await Cr(),Bt=!0,tt=null})()),await tt)}async function In(n){if(te=Mn(n),Bt=!0,!(typeof caches>"u"))try{const e=await caches.open(k.preferenceCacheName);if(!te){await e.delete(k.preferenceCacheKey);return}await e.put(k.preferenceCacheKey,new Response(JSON.stringify(te),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}}))}catch(e){console.warn("[CDN Fallback] Failed to persist CDN preference:",e)}}function xt(n){const e=be.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now(),e.lastFailureReason=void 0)}function ce(n,e){const t=be.get(n);if(t)if(t.failCount++,t.lastCheckTime=Date.now(),t.lastFailureReason=e,t.failCount>=k.failThreshold){t.isHealthy=!1;const s=kn(t);console.warn(`[CDN Fallback] ${n} marked as unhealthy after ${t.failCount} failures, cooldown=${s.cooldownMs}ms, reason=${e??"unknown"}`)}else console.warn(`[CDN Fallback] ${n} failure count=${t.failCount}, reason=${e??"unknown"}`)}function Pn(n,e){const t=wr[n]??{baseTimeout:k.degradeTimeout,maxTimeout:k.degradeTimeout},r=2**Math.max(0,e-k.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function kn(n){const e=Pn(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function Ft(n,e={}){const t=be.get(n);if(!t)return!1;if(t.isHealthy||e.ignoreCooldown)return!0;const s=Date.now(),r=Pn(n,t.failCount);return s-t.lastCheckTime>r}function Er(n,e={}){const t=te;return!t||!vn(t,n)||t.cdn==="local"?null:Ft(t.cdn,e)?t.cdn:null}function On(n,e={}){const t=n?Er(n,e):null;return et.filter(s=>s.enabled&&Ft(s.name,e)).sort((s,r)=>t&&s.name===t&&r.name!==t?-1:t&&r.name===t&&s.name!==t?1:s.priority-r.priority)}function Wn(n){const e=String(n||"").trim();if(!e)return e;let t=e;try{if(/^https?:\/\//i.test(t)){const s=new URL(t);t=`${s.pathname}${s.search}`}}catch{}return t=t.replace(/^\/?npm\/aitu-app@[^/]+\//,"/").replace(/^\/?aitu-app@[^/]+\//,"/"),t}function Bn(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function Tr(n,e){const t=String(e||"").trim();if(!t)return null;let s=t;try{if(/^https?:\/\//i.test(s)){const o=new URL(s);s=`${o.pathname}${o.search}`}}catch{}const r=s.startsWith("/")?s:`/${s}`;return/^\/npm\/(?!aitu-app@)[^/]+@[^/]+\//.test(r)&&n.name==="jsdelivr"?`https://cdn.jsdelivr.net${r}`:null}function Gt(n,e,t){const s=Tr(n,t);if(s)return s;const r=Wn(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function Ut(n,e=k.fetchTimeout){const t=new AbortController,s=setTimeout(()=>t.abort(),e);try{return await fetch(n,{signal:t.signal,cache:"no-store"})}finally{clearTimeout(s)}}function Ht(n,e){const t=Wn(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function Nn(n,e,t){try{const s=Ht(e,n),r=await Ut(s,t);return r.ok?{response:r,source:"local"}:(console.warn(`[CDN Fallback] Local server returned ${r.status}`),null)}catch(s){return console.warn("[CDN Fallback] Local server failed:",s),null}}async function xn(n,e,t,s){for(const r of n){const o=Gt(r,e,t);try{const a=await Ut(o,s);if(!a.ok){ce(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await _r(a,r.name))continue;return xt(r.name),{response:a,source:r.name,targetUrl:o}}catch(a){const i=a instanceof Error&&a.name==="AbortError"?"timeout":"network-error";ce(r.name,i),console.warn(`[CDN Fallback] ${r.name} failed:`,a)}}return null}async function _r(n,e){var i;const t=n.headers.get("Content-Type")||"";if(!(t.includes("javascript")||t.includes("css")||t.includes("json")||t.includes("font")||t.includes("image")||t.includes("woff")||t.includes("application/octet-stream")))return ce(e,`invalid-content-type:${t}`),console.warn(`[CDN Fallback] ${e} invalid Content-Type: ${t}`),!1;const r=parseInt(n.headers.get("Content-Length")||"0",10),o=t.includes("javascript")||t.includes("css")||t.includes("json");if(o&&r>0&&r<50)return ce(e,`response-too-small:${r}`),console.warn(`[CDN Fallback] ${e} response too small: ${r} bytes`),!1;const a=n.clone();try{const c=(i=a.body)==null?void 0:i.getReader();if(c){const{value:l}=await c.read();if(c.cancel(),l){const h=new TextDecoder().decode(l.slice(0,200)),d=h.includes("<!DOCTYPE")||h.includes("<html")||h.includes("<HTML")||h.includes("Not Found")||h.includes("404");if(o&&d)return ce(e,"html-error-page"),console.warn(`[CDN Fallback] ${e} returned HTML instead of ${t}`),!1}}}catch{}return!0}async function qt(n,e,t,s={}){if(yr)return null;await Nt();const{preferLocal:r=!1,localTimeout:o=k.localFetchTimeout,requestKind:a="interactive-runtime"}=s,i=a==="background-prefetch",c=s.cdnTimeout??(a==="background-prefetch"?k.backgroundFetchTimeout:k.fetchTimeout);if(r){const u=await Nn(n,t,o);if(u)return{...u,targetUrl:Ht(t,n)}}const l=On(e,{ignoreCooldown:i}),h=await xn(l,e,n,c);if(h)return h;if(!r){const u=await Nn(n,t,o);if(u)return{...u,targetUrl:Ht(t,n)}}const d=et.filter(u=>u.enabled&&!l.some(b=>b.name===u.name));if(d.length>0){console.warn(`[CDN Fallback] Local origin failed, forcing CDN recovery probe for: ${n}`);const u=await xn(d,e,n,c);if(u)return u}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function jt(n){await Nt();const e=new Map;for(const t of et){if(!t.enabled)continue;const s=Gt(t,n,t.healthCheckPath);try{const r=await Ut(s,5e3),o=r.ok;e.set(t.name,o),o?xt(t.name):ce(t.name,`status:${r.status}`)}catch{e.set(t.name,!1),ce(t.name,"health-check-failed")}}return e}function nt(){const n=vn(te)?te==null?void 0:te.cdn:null;return Array.from(be.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,...kn(t)}))}function zt(){Ln(!0)}const Dr=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:Gt,ensureCDNPreferenceLoaded:Nt,extractVersionFromCDNPath:Bn,fetchFromCDNWithFallback:qt,getAvailableCDNs:On,getCDNStatusReport:nt,isCDNAvailable:Ft,markCDNFailure:ce,markCDNSuccess:xt,performHealthCheck:jt,resetCDNStatus:zt,setCDNPreference:In},Symbol.toStringTag,{value:"Module"}));function Fn(n){return n==="/"||n==="/index.html"}const Ar=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"],Rr="_lazy_chunk_retry",Lr="_t",Mr=600*1e3;function vr(n,e){return Fn(e)?!0:n==="navigate"&&!e.endsWith(".html")}function Gn(n){return Fn(n)?!0:Ar.some(e=>n.endsWith(e))}function Ir(n){return!Gn(n)}function Pr(n,e=Date.now()){const t=new URLSearchParams(n);if(t.get(Rr)!=="1")return!1;const s=Number(t.get(Lr));return!Number.isFinite(s)||s<=0?!0:e-s<=Mr}const O=self;pr(O).setDebugClientCountChangedCallback(Xr);const ne={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function st(n){var t;const e=((t=n[0])==null?void 0:t.toString())||"";return!!(e.includes("[ServiceWorkerChannel]")||e.includes("[BaseChannel]")||e.includes("Invalid message structure")||e.includes("broadcast:")||e.includes("publish:")||e.includes("subscribe:")||e.includes("[Main]")||e.includes("[SW Console Capture]")||e.includes("[SWChannelManager]")&&(e.includes("broadcast")||e.includes("sendConsoleLog")))}function kr(){console.log=(...n)=>{ne.log(...n),Ot()&&!st(n)&&rt("log",n)},console.info=(...n)=>{ne.info(...n),Ot()&&!st(n)&&rt("info",n)},console.warn=(...n)=>{ne.warn(...n),st(n)||rt("warn",n)},console.error=(...n)=>{ne.error(...n),st(n)||rt("error",n)}}function Or(n){let e;const t=[];for(const r of n)try{const o=r;if(r instanceof Error||r&&typeof r=="object"&&typeof o.message=="string")e=o.stack||e,t.push(`${o.name||"Error"}: ${o.message||""}`);else if(typeof r=="object"&&r!==null){const a=JSON.stringify(r);t.push(a==="{}"?String(r):a)}else t.push(String(r))}catch{t.push(String(r))}return{message:t.join(" ")||"(empty)",stack:e}}function rt(n,e){try{const{message:t,stack:s}=Or(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof $t=="function"&&$t({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){ne.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let $t=null;kr(),Promise.resolve().then(()=>Ee).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=v();t&&t.sendDebugLLMLog(e)})});const w="0.9.3",ot=new URL("./",self.location.href),Vt=ot.pathname,Kt=`drawnix-v${w}`,A="drawnix-images",_e=`drawnix-static-v${w}`,at="drawnix-fonts",le="sw-cache-date",ye="sw-cache-created-at",Xt="x-sw-source",Yt="x-sw-revision",Qt="x-sw-app-version",Un="x-sw-fetch-target",Wr="ServiceWorkerDB",Br=2;fr({saveCrashSnapshot:Ts,getDebugStatus:ns,addConsoleLog:en,getDebugLogs:tn,clearDebugLogs:ss,clearConsoleLogs:rs,enableDebugMode:nn,disableDebugMode:sn,loadConsoleLogsFromDB:Jn,clearAllConsoleLogs:es,getCrashSnapshots:_s,clearCrashSnapshots:Ds,getCacheStats:As,deleteCacheByUrl:dn,getInternalFetchLogs:Wt,getCDNStatusReport:nt,resetCDNStatus:zt,performHealthCheck:jt,getAppVersion:()=>w,getImageCacheName:()=>A,requestVideoThumbnail:async(n,e,t)=>{const s=v();return!s||s.getConnectedClientCount()===0?null:s.requestVideoThumbnail(n,e,t)}});const De="failedDomains",Ae="versionState",Hn="app-version-state",qn="/__aitu_cache__/",jn="/__aitu_generated__/audio/",Nr="/asset-library/",Be=location.hostname==="localhost"||location.hostname==="127.0.0.1";function H(n){return new URL(n.replace(/^\//,""),ot)}function Re(n){return Vt!=="/"&&n.startsWith(Vt)?`/${n.slice(Vt.length)}`:n}const xr=[{hostname:"google.datas.systems",pathPattern:"response_images",fallbackDomain:"cdn.i666.fun"},{hostname:"googlecdn2.datas.systems",pathPattern:"response_images",fallbackDomain:"googlecdn2.i666.fun"},{hostname:"filesystem.i666.fun",pathPattern:"response_images",fallbackDomain:"filesystem.i666.fun"}],Fr=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,Gr=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Jt=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,Ur=new Set(["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","_poster_retry","rand","_force","bypass_sw","direct_fetch","thumbnail","expires","signature","sig","token","policy","x-amz-algorithm","x-amz-credential","x-amz-date","x-amz-expires","x-amz-security-token","x-amz-signature","x-amz-signedheaders","x-goog-algorithm","x-goog-credential","x-goog-date","x-goog-expires","x-goog-signature","x-goog-signedheaders","ossaccesskeyid","x-oss-security-token","x-oss-signature-version","x-oss-credential","x-oss-date","x-oss-expires","x-oss-signature"]);function Ne(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)Ur.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const q=new Map,we=new Map,zn=30*1e3,ue=new Map,$n=300*1e3,Vn=500,xe=new Map,G=new Map,Hr=300*1e3,Kn=10,Le=new Set,Me=new Set,qr=3600*1e3,Zt=new Map;function Xn(n){Me.add(n),Zt.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function jr(n){if(!Me.has(n))return!1;const e=Zt.get(n);return e&&Date.now()-e>qr?(Me.delete(n),Zt.delete(n),!1):!0}const Q=[],Yn=7,V=[],zr=500;let I=!1;function P(n){if(!I)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return V.unshift(t),V.length>zr&&V.pop(),Qn(t),e}function R(n,e){if(!I||!n)return;const t=V.find(s=>s.id===n);t&&(Object.assign(t,e),Qn(t))}function Qn(n){const e=v();e&&e.sendDebugLog(n)}function it(){return new Promise((n,e)=>{const t=indexedDB.open("ConsoleLogDB",1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains("logs")){const o=r.createObjectStore("logs",{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("logLevel","logLevel",{unique:!1})}}})}async function $r(n){try{const e=await it(),t=e.transaction(["logs"],"readwrite");return t.objectStore("logs").add(n),new Promise((r,o)=>{t.oncomplete=()=>{e.close(),r()},t.onerror=()=>{e.close(),o(t.error)}})}catch(e){console.warn("Service Worker: 无法保存控制台日志:",e)}}async function Jn(){try{await Zn();const n=await it(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-Yn*24*60*60*1e3;return new Promise((o,a)=>{const i=s.openCursor(null,"prev"),c=[];i.onsuccess=()=>{const l=i.result;if(l){const h=l.value;h.timestamp>=r&&c.push(h),l.continue()}else n.close(),o(c)},i.onerror=()=>{n.close(),a(i.error)}})}catch(n){return console.warn("Service Worker: 无法加载控制台日志:",n),[]}}async function Zn(){try{const n=await it(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-Yn*24*60*60*1e3,o=IDBKeyRange.upperBound(r);return new Promise((a,i)=>{const c=s.openCursor(o);let l=0;c.onsuccess=()=>{const h=c.result;h?(h.delete(),l++,h.continue()):(n.close(),l>0,a(l))},c.onerror=()=>{n.close(),i(c.error)}})}catch(n){return console.warn("Service Worker: 无法清理过期日志:",n),0}}async function es(){try{const n=await it(),e=n.transaction(["logs"],"readwrite");return e.objectStore("logs").clear(),new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("Service Worker: 无法清空控制台日志:",n)}}const ts=500;function en(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(I||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};$r(r),Q.unshift(r),Q.length>ts&&(Q.length=ts),I&&Vr(r)}$t=en;function Vr(n){const e=v();e&&e.sendConsoleLog(n)}function Kr(){let n=0;return G.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function ns(){return{version:w,cacheNames:[Kt,A,_e,at],pendingImageRequests:q.size,pendingVideoRequests:xe.size,videoBlobCacheSize:G.size,videoBlobCacheTotalBytes:Kr(),completedImageRequestsSize:we.size,failedDomainsCount:Le.size,failedDomains:Array.from(Le),corsFailedDomainsCount:Me.size,corsFailedDomains:Array.from(Me),debugLogsCount:V.length,consoleLogsCount:Q.length,debugModeEnabled:I,memoryStats:{pendingRequestsMapSize:q.size,completedRequestsMapSize:we.size,videoBlobCacheMapSize:G.size,failedDomainsSetSize:Le.size,corsFailedDomainsSetSize:Me.size,debugLogsArraySize:V.length,consoleLogsArraySize:Q.length}}}function tn(){return V}function ss(){V.length=0}function rs(){Q.length=0}function nn(){I||(I=!0,We(!0),Ze(!0),ne.log("Service Worker: Debug mode enabled (debug page connected)"))}function sn(){I&&(I=!1,We(!1),Ze(!1),Q.length=0,V.length=0,ne.log("Service Worker: Debug mode disabled (no debug pages)"))}function Xr(n){n>0?nn():sn()}function os(n){for(const e of xr)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function Yr(n,e){return Fr.test(n.pathname)||e.destination==="image"||os(n)!==null}function Qr(n,e){return Gr.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function Jr(n,e){return Jt.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function Zr(n,e){return n.hostname==="fonts.googleapis.com"||n.hostname==="fonts.gstatic.com"?!0:/\.(woff|woff2|ttf|otf|eot)$/i.test(n.pathname)||e.destination==="font"}function eo(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function as(n){return`drawnix-static-v${n}`}function is(){return{committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function cs(n){const e=n||{},t=typeof e.committedVersion=="string"&&e.committedVersion?e.committedVersion:w,s=typeof e.pendingVersion=="string"&&e.pendingVersion?e.pendingVersion:null,r=typeof e.pendingReadyAt=="number"&&Number.isFinite(e.pendingReadyAt)?e.pendingReadyAt:null,o=e.upgradeState==="prewarming"||e.upgradeState==="ready"||e.upgradeState==="committing"?e.upgradeState:"idle";return{committedVersion:t,pendingVersion:s,pendingReadyAt:r,upgradeState:o,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:Date.now()}}function ct(){return new Promise((n,e)=>{const t=indexedDB.open(Wr,Br);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains(De)||r.createObjectStore(De,{keyPath:"domain"}),r.objectStoreNames.contains(Ae)||r.createObjectStore(Ae,{keyPath:"key"})}})}async function Fe(){try{const n=await ct();return await new Promise((e,t)=>{const o=n.transaction([Ae],"readonly").objectStore(Ae).get(Hn);o.onerror=()=>t(o.error),o.onsuccess=()=>{const a=o.result;e(cs((a==null?void 0:a.state)||is()))}})}catch(n){return console.warn("Service Worker: 无法读取版本状态:",n),is()}}async function to(n){const e=cs(n);try{const t=await ct();await new Promise((s,r)=>{const o=t.transaction([Ae],"readwrite");o.objectStore(Ae).put({key:Hn,state:e}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.warn("Service Worker: 无法写入版本状态:",t)}return e}async function Se(n){const e=await Fe(),t=typeof n=="function"?n(e):n;return to({...e,...t,updatedAt:Date.now()})}async function de(n){const e=await Fe(),t={type:"SW_VERSION_STATE",...e,swVersion:w};if(n)return n.postMessage(t),e;const s=await O.clients.matchAll({type:"window",includeUncontrolled:!0});for(const r of s)r.postMessage(t);return e}async function no(){try{const n=await ct();return await new Promise((e,t)=>{const o=n.transaction([De],"readonly").objectStore(De).getAll();o.onsuccess=()=>{o.result.forEach(i=>Le.add(i.domain)),e()},o.onerror=()=>t(o.error)})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function so(n){try{const e=await ct();return await new Promise((t,s)=>{const r=e.transaction([De],"readwrite");r.objectStore(De).put({domain:n,timestamp:Date.now()}),r.oncomplete=()=>t(),r.onerror=()=>s(r.error)})}catch(e){console.warn("Service Worker: 无法保存失败域名:",e)}}async function ro(n){if(!n){await Se({committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();return}await Se(t=>({committedVersion:t.committedVersion||w,pendingVersion:w,pendingReadyAt:Date.now(),upgradeState:"ready"}));const e=v();e&&e.sendSWNewVersionReady(w),await de()}const ls=2,us=1500,rn=2500,oo=8e3,ao=5e3,io=6e4,lt=5e3,co=600*1e3,lo=["offline-static-assets"];let Ge=0,ds=0;const Ue=new Set,He=new Set,qe=new Set,ut=new Map;let hs=Promise.resolve(),je=null,dt=0,he=!1,ht=!1;function wa(n,e){}function gs(){return nt().filter(n=>n.remainingCooldownMs>0&&!n.status.isHealthy).map(n=>({name:n.name,failCount:n.status.failCount,remainingCooldownMs:n.remainingCooldownMs,lastFailureReason:n.status.lastFailureReason}))}function fs(n,e,t){console.warn("[SW Static 503]",{stage:n,requestUrl:e.url,destination:e.destination,mode:e.mode,unavailableCDNs:gs(),...t})}let on={phase:"idle",percent:0,completed:0,total:0,failed:0,version:w,updatedAt:Date.now()};async function ps(n){const e={type:"SW_BOOT_PROGRESS",...on};if(n){n.postMessage(e);return}const t=await O.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e)}function Ce(n,e){on={...on,...n,version:w,updatedAt:Date.now()},ps(e)}async function uo(){try{const n=await fetch(H("precache-manifest.json").href,{cache:"reload"});if(!n.ok)return n.status,n.statusText,null;const e=await n.json();return e.version,e.files.length,e.version&&e.version!==w?(e.version,null):e.files}catch(n){return J(n),null}}let ve=null,Ie=0;function ze(){return Be}async function ho(n,e=200){try{const t=(await n.text()).replace(/\s+/g," ").trim();return t?t.slice(0,e):void 0}catch{return}}async function go(){if(ze())return null;const n=H("idle-prefetch-manifest.json").href;try{const e=await fetch(n,{cache:"reload"}),t=e.headers.get("content-type")||"";if(!e.ok){const a=await ho(e.clone());return e.status,e.statusText,null}const s=await e.text(),r=s.replace(/\s+/g," ").trim().slice(0,200);if(t.includes("text/html")||/<!DOCTYPE|<html|<HTML/i.test(r))return e.status,null;let o;try{o=JSON.parse(s)}catch(a){return J(a),null}return!o||typeof o!="object"||!o.groups?null:o.version&&o.version!==w?(o.version,null):(o.version,o.defaults,Object.fromEntries(Object.entries(o.groups).map(([a,i])=>[a,i.length])),o)}catch(e){return J(e),null}}async function gt(){if(ze())return Ie=0,ve=null,null;const n=Date.now();if(!ve){if(Ie>0&&n-Ie<lt)return null;ve=go().then(e=>e?(Ie=0,e):(Ie=Date.now(),ve=null,null)).catch(e=>{throw Ie=Date.now(),J(e),ve=null,e})}return ve}async function an(n){const e={type:"SW_IDLE_PREFETCH_STATUS",completedGroups:Array.from(qe),version:w,updatedAt:Date.now()};if(n){n.id,e.completedGroups,n.postMessage(e);return}const t=await O.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e);t.length,e.completedGroups}function fo(n,e){return`${n}@${e}`}async function ft(n){try{return(await n.keys()).length}catch{return-1}}function pt(n,e){const t=hs.catch(()=>{}).then(async()=>{try{await e()}finally{}});return hs=t.catch(s=>{console.warn("[SWDebug] idle prefetch task failed",{label:n,error:J(s)})}),t}function po(n){return Math.min(io,ao*2**Math.max(0,n-1))}function ms(n,e=[]){const t=[],s=new Set,r=o=>{!o||s.has(o)||(n.groups[o]||[]).length===0||(s.add(o),t.push(o))};return e.forEach(r),(n.defaults||[]).forEach(r),lo.forEach(r),Object.keys(n.groups).forEach(r),t}function bs(n,e){const t=Date.now(),s=new Map,r=[],o=[];let a=0,i=null;for(const c of e){const l=n.groups[c]||[];if(l.length===0)continue;let h=!1;for(const d of l){const u=fo(d.url,d.revision);if(Ue.has(u)||(h=!0,He.has(u)))continue;const b=ut.get(u);if(b&&b.nextRetryAt>t){a+=1;const p=Math.max(0,b.nextRetryAt-t);i=i===null?p:Math.min(i,p);continue}s.set(u,d)}h?o.push(c):r.push(c)}return{completedGroups:r,pendingGroups:o,queue:Array.from(s.entries()),coolingEntries:a,nextRetryDelayMs:i}}function cn(n,e=rn){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(je!==null){if(dt<=s)return;clearTimeout(je),je=null,dt=0}dt=s,je=self.setTimeout(()=>{je=null,dt=0,pt(`idle-sweep:${n}`,async()=>{await yt(`scheduled:${n}`)})},t)}function mo(){return Ge===0?!1:Date.now()-Ge<us}function bo(){if(Ge===0)return Promise.resolve();const n=Date.now()-Ge,e=Math.max(0,us-n)+100;return new Promise(t=>{setTimeout(t,e)})}function yo(n,e){const t=Re(e.pathname);if(n.request.method!=="GET"||!n.clientId||e.origin!==self.location.origin||e.pathname.startsWith(qn)||e.pathname.startsWith(jn)||t==="/sw.js"||t==="/precache-manifest.json"||t==="/idle-prefetch-manifest.json")return!1;const s=Date.now();return s-ds<oo?!1:(ds=s,!0)}function wo(n){return Gn(Re(n))}function ys(n,e){return Be||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||wo(e.pathname)?!1:!!(e.pathname.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg|woff|woff2|ttf|eot|json|ico)$/i)||n.destination==="script"||n.destination==="style"||n.destination==="image"||n.destination==="font")}function So(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${e.replace(/^\/npm\/aitu-app@[^/]+\//,"/").replace(/^\/aitu-app@[^/]+\//,"/")}${t}`}function Co(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${Re(e)}${t}`}function mt(n){const e=new URL(n,self.location.origin),t=So(Co(`${e.pathname}${e.search}`)),s=H(t);return{requestUrl:e,resourcePath:t,cacheKey:s.href,originFetchUrl:s.href}}function $e(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&ys(n,e)}function Eo(n,e){const t=new Headers(n.headers);return t.set(Xt,e.source),t.set(Yt,e.revision),t.set(Qt,e.appVersion||w),e.fetchTarget&&t.set(Un,e.fetchTarget),t.set("x-sw-cached-at",new Date().toISOString()),new Response(n.body,{status:n.status,statusText:n.statusText,headers:t})}async function ln(n,e,t,s){const r=Eo(t,s);return await n.put(e,r.clone()),r}async function bt(n,e=[]){const t=e.filter(r=>!!r&&r!==n.url),s=await caches.keys();for(const r of s)if(r.startsWith("drawnix-static-v"))try{const o=await caches.open(r),a=await o.match(n);if(a)return a;for(const i of t){const c=await o.match(i);if(c)return n.url,c}}catch{}return null}async function To(n,e=[]){const t=[n.url,...e].filter(Boolean);for(const s of t)try{const r=await fetch(s,{cache:"only-if-cached",mode:"same-origin"});if(r.ok)return r}catch{}return null}async function _o(n,e){const t=mt(e.url).cacheKey,s=await n.match(e);if(s)return{response:s,normalizedCacheKey:t,matchedBy:"request"};if(t!==e.url){const r=await n.match(t);if(r)return{response:r,normalizedCacheKey:t,matchedBy:"normalized"}}return{response:null,normalizedCacheKey:t,matchedBy:null}}async function Do(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function ws(n,e,t){try{const s=mt(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(Yt),l=r.headers.get(Qt);if(c===t&&l===w)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(Ir(Re(s.requestUrl.pathname))){const c=await qt(s.resourcePath,w,ot.href.replace(/\/$/,""),{preferLocal:!1,requestKind:"background-prefetch"});c!=null&&c.response.ok&&(o=c.response,a=c.source,i=c.targetUrl)}if(o||(o=await fetch(s.originFetchUrl,{cache:"reload"}),a="server",i=s.originFetchUrl),o.ok&&$e(new Request(s.cacheKey,{method:"GET"}),s.requestUrl,o))return{url:e,success:!1,status:404,error:"html-fallback-for-static-resource"};if(o.ok){if(await ln(n,s.cacheKey,o,{source:a,revision:t,fetchTarget:i,appVersion:w}),s.resourcePath==="/index.html"){const c=H("/").href,l=await n.match(s.cacheKey);l&&await n.put(c,l.clone())}return{url:e,success:!0,source:a}}return{url:e,success:!1,status:o.status}}catch(s){return{url:e,success:!1,error:String(s)}}}async function Ao(n,e){const s=[],r=e.length;let o=0,a=0;await ft(n),e.slice(0,8).map(d=>d.url),Ce({phase:"precache",total:r,completed:0,failed:0,percent:r>0?0:100,message:r>0?`正在预热启动资源(0/${r})...`:"没有需要预热的启动资源"});for(let d=0;d<e.length;d+=6){const u=e.slice(d,d+6),b=await Promise.allSettled(u.map(({url:g,revision:f})=>ws(n,g,f))),p=[];for(const g of b)if(g.status==="fulfilled"){const f={url:g.value.url,success:g.value.success,skipped:g.value.skipped,source:g.value.source,status:g.value.status,error:g.value.error};s.push(f),p.push(f),o+=1,g.value.success||(a+=1)}else{const f={success:!1,error:String(g.reason)};s.push(f),p.push(f),o+=1,a+=1}u.length,p.filter(g=>g.success).length,p.filter(g=>g.skipped).length,p.filter(g=>!g.success).length,Object.fromEntries(Array.from(p.reduce((g,f)=>{const y=f.source||"unknown";return g.set(y,(g.get(y)||0)+1),g},new Map))),p.filter(g=>!g.success).slice(0,5).map(g=>({url:g.url,status:g.status,error:g.error})),Ce({phase:"precache",total:r,completed:o,failed:a,percent:r>0?Math.round(o/r*100):100,message:r>0?`正在预热启动资源(${o}/${r}${a>0?`,${a} 项回退`:""})...`:"没有需要预热的启动资源"})}const i=s.filter(d=>d.success).length,c=s.length-i,l=s.filter(d=>d.success&&d.source&&d.source!=="server").length,h=s.filter(d=>d.success&&d.source==="server").length;return await ft(n),{total:r,successCount:i,failCount:c,cdnCount:l,serverCount:h}}async function Ss(n){if(n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await gt();if(!e)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};Object.fromEntries(n.map(c=>{var l;return[c,((l=e.groups[c])==null?void 0:l.length)||0]})),e.defaults;const t=new Set(qe),s=bs(e,n);if(s.completedGroups.forEach(c=>qe.add(c)),s.queue.length===0)return Ue.size,He.size,{completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,queuedEntries:0,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs};const r=await caches.open(_e);await ft(r);const o=s.queue;s.queue.length,o.length,o.slice(0,8).map(([,c])=>c.url);for(let c=0;c<o.length;c+=ls){for(;mo();)await bo();const l=o.slice(c,c+ls);l.forEach(([u])=>He.add(u));const h=await Promise.allSettled(l.map(([,{url:u,revision:b}])=>ws(r,u,b))),d=[];h.forEach((u,b)=>{const[p]=l[b];if(He.delete(p),u.status==="fulfilled"&&u.value.success)ut.delete(p),Ue.add(p);else{const g=ut.get(p),f=((g==null?void 0:g.count)||0)+1,y=po(f);ut.set(p,{count:f,nextRetryAt:Date.now()+y,lastError:u.status==="fulfilled"?u.value.error:String(u.reason),lastStatus:u.status==="fulfilled"?u.value.status:void 0})}u.status==="fulfilled"?d.push({url:u.value.url,success:u.value.success,skipped:u.value.skipped,source:u.value.source,status:u.value.status,error:u.value.error}):d.push({success:!1,error:String(u.reason)})}),l.length,d.filter(u=>u.success).length,d.filter(u=>u.skipped).length,d.filter(u=>!u.success).length,Object.fromEntries(Array.from(d.reduce((u,b)=>{const p=b.source||"unknown";return u.set(p,(u.get(p)||0)+1),u},new Map))),d.filter(u=>!u.success).slice(0,5).map(u=>({url:u.url,status:u.status,error:u.error})),Ue.size,He.size}const a=bs(e,n),i=a.completedGroups.filter(c=>!t.has(c));return i.forEach(c=>qe.add(c)),await ft(r),Ue.size,Array.from(qe),{completedGroups:i,pendingGroups:a.pendingGroups,queuedEntries:o.length,coolingEntries:a.coolingEntries,nextRetryDelayMs:a.nextRetryDelayMs}}async function yt(n,e=[]){if(ze())return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const t=await gt();if(!t)return cn(`${n}:manifest-missing`,lt),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:lt};const s=ms(t,e);if(s.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};Object.fromEntries(s.map(o=>{var a;return[o,((a=t.groups[o])==null?void 0:a.length)||0]}));const r=await Ss(s);return r.completedGroups.length>0&&await an(),r.pendingGroups.length>0&&cn(`${n}:pending`,r.nextRetryDelayMs??rn),r}async function Ro(){var t;if(ze())return;const n=await gt();if(!n){cn("default-groups:manifest-missing",lt);return}const e=(t=n==null?void 0:n.defaults)==null?void 0:t.filter(s=>typeof s=="string"&&s.length>0);!e||e.length===0||await yt("default-groups",e)}async function Lo(){if(ze())return;const n=Date.now();let e=null;for(;;){if(!e){const o=await gt();if(!o||(e=ms(o),e.length===0))return}const t=await Ss(e);if(t.completedGroups.length>0&&await an(),t.pendingGroups.length===0)return;const s=Date.now()-n;if(s>=co)throw new Error(`idle-prefetch incomplete after ${s}ms: pending groups ${t.pendingGroups.join(", ")}`);const r=Math.max(250,t.nextRetryDelayMs??(t.queuedEntries>0?rn:1e3));t.pendingGroups,t.coolingEntries,t.queuedEntries,await new Promise(o=>{setTimeout(o,r)})}}O.addEventListener("install",n=>{he=!!O.registration.active,ht=!he,he||O.skipWaiting(),Ce({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await no(),await Se(e=>({committedVersion:e.committedVersion||w,pendingVersion:he?w:null,pendingReadyAt:null,upgradeState:he?"prewarming":"idle"})),await de();try{const e=await uo();if(e&&e.length>0){const t=await caches.open(_e),s=await Ao(t,e);if(he&&s.failCount>0)throw new Error(`precache incomplete: ${s.failCount}/${s.total} files failed`)}else Be&&Ce({phase:"development",percent:100,completed:0,total:0,failed:0,message:"开发模式下跳过静态预缓存"});he&&await Lo(),await ro(he)}catch(e){await Se(t=>({committedVersion:t.committedVersion||w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"})),await de(),Ce({phase:"error",message:`启动资源预热失败:${J(e)}`}),console.warn("Service Worker: Precache failed:",e)}})())}),O.addEventListener("activate",n=>{Ce({phase:"activating",percent:100,message:"启动缓存服务正在接管页面..."}),n.waitUntil((async()=>{await Fe(),await Se({committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();try{const{ensureCDNPreferenceLoaded:t}=await Promise.resolve().then(()=>Dr);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}ht&&await O.clients.claim(),setTimeout(()=>{pt("default-groups",async()=>Ro())},800);const e=v();e&&e.sendSWActivated(w),Ce({phase:"activated",percent:100,message:"启动缓存服务已就绪"})})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(i=>i.startsWith("drawnix-images-v")&&i!==A);if(t.length>0){const i=await caches.open(A);for(const c of t)try{const l=await caches.open(c),h=await l.keys();for(const d of h){const u=await l.match(d);u&&await i.put(d,u)}await caches.delete(c)}catch(l){console.warn(`Failed to migrate cache ${c}:`,l)}}const s=await Fe(),r=as(s.committedVersion||w),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==_e&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==Kt&&i!==A&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(_e);await Po(i)}catch(i){console.warn("Failed to purge suspicious static cache entries:",i)}(o.length>0||a.length>0)&&setTimeout(async()=>{for(const i of[...o,...a])try{await caches.delete(i)}catch(c){console.warn("Failed to delete old cache:",i,c)}},3e4),Zn().catch(i=>{console.warn("Failed to cleanup expired console logs:",i)}),yn.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function Mo(n){if(I){const e=v();e&&e.sendPostMessageLog(n)}}async function vo(n,e,t,s){if(Be)return null;try{const r=mt(e.url),o=await qt(t,s,ot.href.replace(/\/$/,""),{preferLocal:!1,requestKind:"interactive-runtime"});if(!(o!=null&&o.response.ok))return console.warn("[SW CDN] Static resource unavailable from all fallback sources",{requestUrl:e.url,resourcePath:t,appVersion:s,unavailableCDNs:gs()}),null;const a=new URL(e.url);if($e(e,a,o.response))return null;const i=await ln(n,r.cacheKey,o.response,{source:o.source,revision:"runtime",fetchTarget:o.targetUrl,appVersion:s});return r.cacheKey!==e.url&&(e.url,r.cacheKey,o.source,o.targetUrl,void 0),i}catch(r){return console.warn("[SW CDN] CDN fallback failed:",r),null}}function Io(n){const e=n.headers.get(Xt)||void 0,t=n.headers.get(Un)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function Cs(n,e,t=w){const s=e.headers.get(Xt),r=e.headers.get(Yt),o=e.headers.get(Qt);if(!s||!r||!o){const i=new URL(n.url);return!(e.ok&&!$e(n,i,e))}if(o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr")return!0;const a=new URL(n.url);return $e(n,a,e)}async function Po(n){const e=await n.keys();for(const t of e)try{const s=await n.match(t);s&&Cs(t,s)&&await n.delete(t)}catch(s){console.warn("Service Worker: Failed to inspect static cache entry:",s)}}O.addEventListener("message",n=>{var a,i,c,l,h,d,u,b,p,g;const e=((a=n.data)==null?void 0:a.type)||((i=n.data)==null?void 0:i.cmdname)||((l=(c=n.data)==null?void 0:c.req)==null?void 0:l.cmdname)||"unknown",t=((h=n.source)==null?void 0:h.id)||"",s=((d=n.source)==null?void 0:d.url)||"",r=((u=n.data)==null?void 0:u.cmdname)||((b=n.data)==null?void 0:b.requestId)&&((p=n.data)==null?void 0:p.ret)!==void 0;let o="";if(Rt()&&!r&&(o=Lt(e,n.data,t,s,(g=n.data)==null?void 0:g.__internal__),o&&I)){const y=Xe().find(S=>S.id===o);y&&Mo(y)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:f,mediaType:y,blob:S,mimeType:E}=n.data;if(f&&y&&S){const W=new Blob([S],{type:E||(y==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:U}=await Promise.resolve().then(()=>j);U(W,f,y)})()}return}if(n.data&&n.data.type==="SW_CDN_SET_PREFERENCE"){n.waitUntil(In({cdn:n.data.cdn,latency:n.data.latency,timestamp:n.data.timestamp,version:n.data.version}));return}if(n.data&&n.data.type==="RECOVER_DYNAMIC_IMPORT_FAILURE"){n.waitUntil(caches.keys().then(f=>Promise.all(f.filter(y=>y.startsWith("drawnix-static-v")).map(y=>caches.delete(y))).then(()=>{n.data.appVersion,n.data.moduleKey})));return}if(n.data&&n.data.type==="SW_BOOT_PROGRESS_GET"){const f=n.source;f==null||f.id,ps(f);return}if(n.data&&n.data.type==="GET_VERSION_STATE"){const f=n.source;f==null||f.id,n.waitUntil(de(f));return}if(n.data&&n.data.type==="SW_IDLE_PREFETCH_STATUS_GET"){const f=n.source;f==null||f.id,an(f);return}if(n.data&&n.data.type==="SW_PREFETCH_GROUPS"){const f=Array.isArray(n.data.groups)?n.data.groups.filter(y=>typeof y=="string"):[];n.waitUntil(pt(`message:${f.join(",")||"empty"}`,async()=>{await yt(`message:${f.join(",")||"empty"}`,f)}));return}if(n.data&&n.data.type==="CLAIM_CLIENTS"){n.waitUntil(O.clients.claim());return}if(n.data&&(n.data.type==="COMMIT_UPGRADE"||n.data.type==="SKIP_WAITING")){const f=n.source;f==null||f.id,n.waitUntil((async()=>{ht=!0,await Se({committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(f),O.skipWaiting();const y=v();y&&y.sendSWUpdated(w)})())}else if(n.data&&n.data.type==="FORCE_UPGRADE")n.waitUntil((async()=>{ht=!0,await Se({committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(n.source),O.skipWaiting();const f=v();f&&f.sendSWUpdated(w)})());else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:f}=n.data;f&&dn(f).then(()=>{const y=v();y&&y.sendCacheDeleted(f)}).catch(y=>{console.error("Service Worker: Failed to delete cache:",y)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:f}=n.data;f&&Array.isArray(f)&&No(f).then(()=>{}).catch(y=>{console.error("Service Worker: Failed to batch delete caches:",y)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")xo().then(()=>{}).catch(f=>{console.error("Service Worker: Failed to clear all cache:",f)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){I=!0,We(!0),Ze(!0),ne.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const f=v();f&&f.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){I=!1,We(!1),Ze(!1),Q.length=0,V.length=0,ne.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const f=v();f&&f.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:f}=await Promise.resolve().then(()=>Ee),y=await f(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:y})}catch(f){console.error("[SW] Failed to get LLM API logs:",f)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:f}=await Promise.resolve().then(()=>Ee);await f();const y=n.source;y&&y.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(f){console.error("[SW] Failed to clear LLM API logs:",f)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const f=n.source;f&&f.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:I,swVersion:w,logs:V.slice(-100),consoleLogs:Q.slice(-100)});return}if(n.data&&n.data.type==="SW_DEBUG_GET_LOGS"){(async()=>{try{const{getInternalFetchLogs:f}=await Promise.resolve().then(()=>br),y=tn(),S=f(),E=n.source;E&&E.postMessage({type:"SW_DEBUG_LOGS",logs:[...y,...S.map(W=>({...W,type:"fetch"}))]})}catch(f){console.error("[SW] Failed to get fetch logs:",f)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const f=n.source;f&&f.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:Q})}catch(f){console.error("[SW] Failed to get console logs:",f)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const f=Xe(),y=n.source;y&&y.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:f})}catch(f){console.error("[SW] Failed to get postmessage logs:",f)}})();return}});const ko="MemorySnapshotDB",ge="snapshots",Es=50;async function un(){return new Promise((n,e)=>{const t=indexedDB.open(ko,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(ge)){const o=r.createObjectStore(ge,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function Ts(n){try{const e=await un(),t=e.transaction(ge,"readwrite"),s=t.objectStore(ge);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>Es){const i=s.index("timestamp").openCursor();let c=0;const l=o-Es;i.onsuccess=h=>{const d=h.target.result;d&&c<l&&(s.delete(d.value.id),c++,d.continue())}}},await new Promise((o,a)=>{t.oncomplete=()=>{e.close(),o()},t.onerror=()=>{e.close(),a(t.error)}})}catch(e){console.warn("[SW] Failed to save crash snapshot:",e)}}async function _s(){try{const n=await un(),s=n.transaction(ge,"readonly").objectStore(ge).index("timestamp");return new Promise((r,o)=>{const a=s.getAll();a.onsuccess=()=>{n.close();const i=a.result.sort((c,l)=>l.timestamp-c.timestamp);r(i)},a.onerror=()=>{n.close(),o(a.error)}})}catch(n){return console.warn("[SW] Failed to get crash snapshots:",n),[]}}async function Ds(){try{const n=await un(),e=n.transaction(ge,"readwrite");e.objectStore(ge).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("[SW] Failed to clear crash snapshots:",n)}}const Oo=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function Wo(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Bo(n){return new Promise(e=>{try{const t=indexedDB.open(n);t.onerror=()=>e({count:0,totalSize:0}),t.onsuccess=()=>{const s=t.result,r=Array.from(s.objectStoreNames);if(r.length===0){s.close(),e({count:0,totalSize:0});return}let o=0,a=0,i=0,c=0;const l=10;try{const h=s.transaction(r,"readonly");for(const d of r){const u=h.objectStore(d),b=u.count();b.onsuccess=()=>{const p=b.result;if(o+=p,p>0){const g=u.openCursor();let f=0;g.onsuccess=y=>{const S=y.target.result;if(S&&f<l)a+=Wo(S.value),i++,f++,S.continue();else if(c++,c===r.length){s.close();const E=i>0?a/i:0,W=Math.round(E*o);e({count:o,totalSize:W})}},g.onerror=()=>{if(c++,c===r.length){s.close();const y=i>0?a/i:0,S=Math.round(y*o);e({count:o,totalSize:S})}}}else c++,c===r.length&&(s.close(),e({count:o,totalSize:0}))},b.onerror=()=>{if(c++,c===r.length){s.close();const p=i>0?a/i:0,g=Math.round(p*o);e({count:o,totalSize:g})}}}}catch{s.close(),e({count:0,totalSize:0})}},t.onupgradeneeded=s=>{s.target.result.close();try{indexedDB.deleteDatabase(n)}catch{}e({count:0,totalSize:0})}}catch{e({count:0,totalSize:0})}})}async function As(){const n={},e=[Kt,A,_e,at];for(const t of e)try{const s=await caches.open(t),r=await s.keys();let o=0;const a=Math.min(r.length,100);let i=0;for(let c=0;c<a;c++){const l=await s.match(r[c]);if(l){const h=l.headers.get("sw-image-size")||l.headers.get("content-length");h&&(i+=parseInt(h))}}a>0&&r.length>a?o=Math.round(i/a*r.length):o=i,n[t]={count:r.length,totalSize:o,type:"cache"}}catch{n[t]={count:0,totalSize:0,type:"cache"}}for(const t of Oo)try{const s=await Bo(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function dn(n){try{await(await caches.open(A)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function No(n){try{const e=await caches.open(A);let t=0;for(const s of n)try{await e.delete(s),t++}catch(r){console.warn("Service Worker: Failed to delete cache in batch:",s,r)}}catch(e){throw console.error("Service Worker: Failed to batch delete caches:",e),e}}async function xo(){try{const n=await caches.open(A),e=await n.keys();for(const t of e)await n.delete(t)}catch(n){throw console.error("Service Worker: Failed to clear image cache:",n),n}}async function Fo(n,e,t){try{const s=v();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}function Go(n){const e=Date.now(),t=ue.get(n);if(t&&e-t<$n)return!1;if(ue.size>=Vn){for(const[s,r]of ue)e-r>$n&&ue.delete(s);if(ue.size>=Vn){const s=Array.from(ue.entries());s.sort((r,o)=>r[1]-o[1]);for(const[r]of s.slice(0,Math.floor(s.length/2)))ue.delete(r)}}return ue.set(n,e),!0}async function fe(n,e){try{const t=Ne(new URL(n,self.location.origin)).toString();if(!Go(t))return;const s=v();s&&s.sendCacheImageCacheFailed(t,e)}catch(t){console.warn("Service Worker: Failed to notify image cache failure:",{url:n,error:e,notifyError:t})}}async function Uo(){try{if(navigator.storage&&navigator.storage.estimate){const n=await navigator.storage.estimate(),e=n.usage||0,t=n.quota||0,s=t>0?e/t*100:0;if(s>90){console.warn("Service Worker: Storage quota warning:",{usage:e,quota:t,percentage:s});const r=v();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const se=new Map,Rs=300*1e3,Ls=500;function Ho(n){const e=n.match(/\/(\d{4})\/(\d{2})\/(\d{2})\//),t=n.match(/\/(\d{4})(\d{2})(\d{2})\//);let s=null;if(e?s=new Date(parseInt(e[1]),parseInt(e[2])-1,parseInt(e[3])):t&&(s=new Date(parseInt(t[1]),parseInt(t[2])-1,parseInt(t[3]))),!s)return!1;const r=new Date;return!(s.getFullYear()===r.getFullYear()&&s.getMonth()===r.getMonth()&&s.getDate()===r.getDate())}function qo(n){const e=se.get(n);return e?Date.now()-e>Rs?(se.delete(n),!1):!0:!1}function Ms(n){if(Ho(n)){if(se.size>=Ls){const e=Date.now();for(const[t,s]of se)e-s>Rs&&se.delete(t);if(se.size>=Ls){const t=Array.from(se.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)se.delete(r)}}se.set(n,Date.now())}}O.addEventListener("fetch",n=>{const e=new URL(n.request.url),t=Date.now();if(e.protocol!=="http:"&&e.protocol!=="https:"){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"other",details:`Skipped: non-http protocol (${e.protocol})`,status:0,duration:0});return}if(Ge=t,yo(n,e)){const s=`${e.pathname}${e.search}`;n.clientId,n.waitUntil(pt(`fetch-recheck:${s}`,async()=>{await yt(`fetch:${s}`)}))}if(e.pathname.startsWith(qn)||e.pathname.startsWith(jn)){const s=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(zo(n.request).then(r=>(R(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw R(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(Nr)){const s=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith($o(n.request).then(r=>(R(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw R(s,{error:String(r),duration:Date.now()-t}),r}));return}if(!e.hostname.endsWith(".posthog.com")){if(e.hostname==="cdn.i666.fun"){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: cdn.i666.fun (fallback domain)",status:0,duration:0});return}if(e.hostname.endsWith(".volces.com")||e.hostname.endsWith(".volccdn.com")){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: Volcengine domain (no CORS)",status:0,duration:0});return}if(e.hostname.endsWith(".aliyuncs.com")){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: Aliyun OSS domain (no CORS)",status:0,duration:0});return}if(jr(e.hostname)){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:`Passthrough: ${e.hostname} (CORS failed domain, auto-detected)`,status:0,duration:0});return}if(e.hostname!=="api.github.com"){if(e.origin!==location.origin&&Jr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"audio",headers:r?{range:r}:void 0,details:r?`Audio Range request: ${r}`:"External audio request"});n.respondWith(Vo(n.request).then(a=>(R(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,cached:a.headers.has(le),responseHeaders:{"content-type":a.headers.get("content-type")||"","content-length":a.headers.get("content-length")||"","content-range":a.headers.get("content-range")||""}}),a)).catch(a=>{throw R(o,{error:String(a),duration:Date.now()-s}),a}));return}if(Qr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"video",headers:r?{range:r}:void 0,details:r?`Video Range request: ${r}`:"Video request"});n.respondWith(Ko(n.request).then(a=>(R(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,responseHeaders:{"content-type":a.headers.get("content-type")||"","content-length":a.headers.get("content-length")||"","content-range":a.headers.get("content-range")||""}}),a)).catch(a=>{throw R(o,{error:String(a),duration:Date.now()-s}),a}));return}if(Zr(e,n.request)){const s=Date.now(),r=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(jo(n.request).then(o=>(R(r,{status:o.status,statusText:o.statusText,responseType:o.type,duration:Date.now()-s,cached:o.headers.has("sw-cache-date")}),o)).catch(o=>{throw R(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&Yr(e,n.request)){if(qo(n.request.url)){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"Skipped: recently failed URL (cached 404)",status:404,duration:0}),n.respondWith(new Response("",{status:404,statusText:"Not Found (cached)"}));return}const s=Date.now(),r=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(Jo(n.request).then(o=>(o.status===404&&Ms(n.request.url),R(r,{status:o.status,statusText:o.statusText,responseType:o.type,duration:Date.now()-s,cached:o.headers.has("sw-cache-date"),size:parseInt(o.headers.get("content-length")||"0")}),o)).catch(o=>{throw Ms(n.request.url),R(r,{error:String(o),duration:Date.now()-s}),o}));return}if(n.request.method==="GET"){const s=n.request.mode==="navigate",r=n.request.destination!=="";if(s||r){const o=Date.now(),a=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(Xo(n.request).then(i=>{const c=Io(i);return R(a,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-o,resourceSource:c.resourceSource,resourceFetchTarget:c.resourceFetchTarget,details:s?"Navigation request":[`Static resource (${n.request.destination})`,c.resourceSource?`来源: ${c.resourceSource}`:null,c.resourceFetchTarget?`实际拉取: ${c.resourceFetchTarget}`:null].filter(Boolean).join(`
|
|
2
2
|
`)}),i}).catch(i=>{throw R(a,{error:String(i),duration:Date.now()-o}),i}));return}}if(I){if(eo(e)){P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"xhr",details:`Skipped SW debug interception for generateContent request (${n.request.method})`,duration:0});return}const s=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"xhr",details:`XHR/API request (${n.request.method})`});n.respondWith((async()=>{try{const r=n.request.clone();let o;const a={};if(n.request.headers.forEach((d,u)=>{a[u]=d}),["POST","PUT","PATCH"].includes(n.request.method))try{const d=n.request.headers.get("content-type")||"";d.includes("application/json")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):d.includes("application/x-www-form-urlencoded")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):o=`[${d||"binary data"}]`}catch{o="[unable to read body]"}R(s,{headers:a,details:o?`XHR/API request (${n.request.method})
|
|
3
3
|
|
|
4
4
|
Request Body:
|