aitu-app 0.9.2 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +3 -3
  2. package/assets/{CanvasAudioPlayer-C_USx5uz.js → CanvasAudioPlayer-Ct_DgaBm.js} +2 -2
  3. package/assets/{ComicCreator-qGQaXp7h.js → ComicCreator-DKTra9U8.js} +3 -3
  4. package/assets/DeferredAIInputBar-CVXfAbVO.css +1 -0
  5. package/assets/DeferredAIInputBar-PhYj6tMp.js +107 -0
  6. package/assets/{DrawnixDeferredFeatures-Hy_-quZ1.js → DrawnixDeferredFeatures-CJLKFMZ5.js} +2 -2
  7. package/assets/{KnowledgeBaseContent-DSKNA70H.js → KnowledgeBaseContent-CzMdi5z7.js} +5 -5
  8. package/assets/{MVCreator-C3iClDLU.js → MVCreator-C9B7mIHV.js} +4 -4
  9. package/assets/{ModelBenchmarkWorkbench-BxwdcZ0q.js → ModelBenchmarkWorkbench-6xOjIJ7d.js} +2 -2
  10. package/assets/{MusicAnalyzer-f_T6_YPJ.js → MusicAnalyzer-BAyF7Tj5.js} +1 -1
  11. package/assets/ParametersDropdown-BE58BbHs.css +1 -0
  12. package/assets/{ParametersDropdown-CTSN3ClD.js → ParametersDropdown-BYGI9vpw.js} +1 -1
  13. package/assets/{PromptHistoryTool-DV-8RSdz.js → PromptHistoryTool-BhlvCXOe.js} +2 -2
  14. package/assets/{ResizableDivider-CUQBmPpx.js → ResizableDivider-u_In_2xN.js} +1 -1
  15. package/assets/{TaskQueuePanel-CtjY1W4t.js → TaskQueuePanel-B3cxWAQs.js} +1 -1
  16. package/assets/{VideoAnalyzer-BBVBSONO.js → VideoAnalyzer-DrrVXlkN.js} +3 -3
  17. package/assets/{VideoAnalyzer-BmAjGvN8.js → VideoAnalyzer-kgj96vkW.js} +1 -1
  18. package/assets/{ai-chat-BO5vbKZW.js → ai-chat-DAYbvxd5.js} +45 -45
  19. package/assets/{ai-chat-DyV67c_f.css → ai-chat-_KImIteT.css} +1 -1
  20. package/assets/{ai-generation-preferences-service-ZmPTR-wz.js → ai-generation-preferences-service-Dq-zs34q.js} +1 -1
  21. package/assets/{batch-image-generation-BLBSv-t6.js → batch-image-generation-C-1xOmRp.js} +6 -6
  22. package/assets/{diagram-engines-CSzW_-6N.js → diagram-engines-8RYWC7Nz.js} +3 -3
  23. package/assets/{editor-engines-C573k8UM.js → editor-engines-CAqUMXhh.js} +1 -1
  24. package/assets/{index-IHNaVKGH.js → index-BdG67AG7.js} +1 -1
  25. package/assets/{index-Dw_8lcIi.js → index-BqMswj4C.js} +1 -1
  26. package/assets/{index-jxwTv7c1.js → index-CTI2DzUH.js} +1 -1
  27. package/assets/{index-N8asYyaz.js → index-DnLcFemk.js} +2 -2
  28. package/assets/{index-BT-rxxI3.js → index-DqnBwEVg.js} +1 -1
  29. package/assets/{index.es-BLXvmueB.js → index.es-BtMWS30S.js} +1 -1
  30. package/assets/{jspdf.es.min-DxWvbkh4.js → jspdf.es.min-vl4gYoCT.js} +3 -3
  31. package/assets/{markdown-to-drawnix-BVFYnimo.js → markdown-to-drawnix-DArr68va.js} +3 -3
  32. package/assets/{mermaid-to-drawnix-nGs2aeZ7.js → mermaid-to-drawnix-CBx1EkoC.js} +3 -3
  33. package/assets/{model-benchmark-launcher-DAWoSySc.js → model-benchmark-launcher-Co7SFFp7.js} +1 -1
  34. package/assets/{photo-wall-splitter-CCUURzGk.js → photo-wall-splitter-BE0IkZFn.js} +1 -1
  35. package/assets/{prompt-utils-MF_LILNU.js → prompt-utils-CK3zMEeZ.js} +1 -1
  36. package/assets/{settings-dialog-Ac7R-_CG.js → settings-dialog-6772jyIM.js} +1 -1
  37. package/assets/{skill-dsl-parser-Do9iAYbB.js → skill-dsl-parser-Bpkft7c5.js} +1 -1
  38. package/assets/{startup-app-CKHrOmQ0.css → startup-app-BJH8E5sr.css} +1 -1
  39. package/assets/{startup-app-eD_rQhSh.js → startup-app-BJxBOm58.js} +509 -504
  40. package/assets/{task-sync-BJVOunRa.js → task-sync-B6mWvAwh.js} +1 -1
  41. package/assets/{tool-windows-CmgL3thd.js → tool-windows-CijCWY1P.js} +21 -21
  42. package/assets/ttd-dialog-CifYf5R1.js +6 -0
  43. package/assets/{ttd-dialog-submit-shortcut-C2lJygXA.js → ttd-dialog-submit-shortcut-1ElB_nn1.js} +1 -1
  44. package/assets/{useCharacters-BAKE4TeJ.js → useCharacters-fKQX269T.js} +1 -1
  45. package/assets/{useMediaViewer-BGw5RkSR.js → useMediaViewer-Ta1D_gkW.js} +1 -1
  46. package/assets/{useWorkflowSubmission-iAPmKke9.js → useWorkflowSubmission--wov80Oe.js} +9 -9
  47. package/assets/{video-recovery-service-CW7bErP2.js → video-recovery-service-Dt3Fhpgq.js} +1 -1
  48. package/assets/{workflow-generation-utils-DhIVnOHO.js → workflow-generation-utils-DviVwGto.js} +3 -3
  49. package/assets/{workflow-submission-service-Ce0cpj8E.js → workflow-submission-service-DllQA8Yv.js} +2 -2
  50. package/changelog.json +31 -28
  51. package/idle-prefetch-manifest.json +280 -280
  52. package/manifest.json +3 -3
  53. package/package.json +1 -1
  54. package/precache-manifest.json +6 -6
  55. package/sw.js +4 -4
  56. package/version.json +3 -4
  57. package/assets/DeferredAIInputBar-CPykEFYX.css +0 -1
  58. package/assets/DeferredAIInputBar-LmZGQCLT.js +0 -107
  59. package/assets/ParametersDropdown-b2oWAycj.css +0 -1
  60. package/assets/ttd-dialog-B12v0SVY.js +0 -6
package/sw.js CHANGED
@@ -1,5 +1,5 @@
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(`
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})
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 At="sw-task-queue",Sn=3,_="tasks",z="config",B="workflows",N="chat-workflows",L="pending-tool-requests",M="pending-dom-operations",x="task-step-mappings",$="pending-canvas-operations",js=[_,z,B,N,L,M,x,$];function zs(){return new Promise(n=>{const e=indexedDB.open(At);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,Sn))},e.onerror=()=>{n(Sn)}})}function $s(n){const e=[];for(const t of js)n.objectStoreNames.contains(t)||e.push(t);return e}function Vs(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(At,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;Cn(a)}})}function Cn(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 Ks(){const n=await zs();return new Promise((e,t)=>{const s=indexedDB.open(At,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=$s(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),Vs(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;Cn(o)}})}class Xs{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=Ks()),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 En=new Xs,Ys=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function Rt(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=>Rt(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();Ys.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=Rt(s)}return e}return n}let Qe=!1;const Qs=500,oe=[];let Lt=0;function Tn(){return Qe}const _n=["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 Dn(n){const e=Qe;Qe=n,!n&&e&&(oe.length=0,Oe.clear(),Lt=0)}function Mt(){return Qe}function Js(n){if(!Tn()||n==="unknown"||_n.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)),_n.includes(e))return!1}return!0}function Zs(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 vt(n,e,t,s,r){if(r||!Js(n))return"";const o=Zs(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++Lt}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:An(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(er(i),nr(n)){const c=sr(e);c&&Oe.set(c,{entry:i,startTime:Date.now()})}return a}function er(n){oe.unshift(n),oe.length>Qs&&oe.pop()}function It(n,e,t,s){if(!Tn())return"";const r=Oe.get(n);if(r){r.entry.response=An(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return Oe.delete(n),o}return""}function Je(){return[...oe]}function tr(){oe.length=0,Oe.clear(),Lt=0}function nr(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 sr(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function An(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return Rt(e)}catch{return"[Non-serializable data]"}}function rr(){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 Pt=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:tr,getAllLogs:Je,getLogStats:rr,isPostMessageLoggerDebugMode:Mt,logReceivedMessage:vt,setPostMessageLoggerDebugMode:Dn,updateRequestWithResponse:It},Symbol.toStringTag,{value:"Module"}));function or(){return typeof window<"u"?window:typeof self<"u"?self:{}}function ar(n){return JSON.parse(JSON.stringify(n))}function Rn(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 ir="postmessage-duplex",cr="1.2.0",Ze=or();var X,ae;Ze.__POSTMESSAGE_DUPLEX__||(Ze.__POSTMESSAGE_DUPLEX__={}),Ze.__POSTMESSAGE_DUPLEX__.version=cr,Ze.__POSTMESSAGE_DUPLEX__.name=ir,(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 lr{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 ur{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 dr{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 Ln(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const Z=n=>({valid:0,error:n});function hr(n){if(!Ln(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&&!Ln(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 et(n){return"ret"in n&&typeof n.ret=="number"}function gr(n){return n.msg==="ready"}function fr(n){return n._broadcast==1&&typeof n.cmdname=="string"}function pr(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const kt=[],ee=[];function Mn(n){ee.length>=200&&ee.shift(),ee.push(n)}function vn(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 mr extends dr{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 lr,this.rateLimiter=new ur((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,kt.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{Mn({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?vn(i,"ok"):Mn({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{vn(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=pr(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):et(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=hr(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:et(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(!fr(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(!gr(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}),et(e)||this.sendMessage({requestId:t,ret:X.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!et(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=kt.findIndex(r=>r.deref()===t);s!==-1&&kt.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 mr{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=Rn("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=Rn("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=ar(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 br(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 Ot={};function yr(n){Ot={...Ot,...n}}function D(){return Ot}const _e=class _e{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 En.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 _e.instance||(_e.instance=new _e(e)),_e.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=Je().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=Mt()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const h=vt(`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=It(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=It(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(()=>Pt),{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(()=>Pt);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(()=>Te);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(()=>Te);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(()=>Te);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(()=>Te);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(()=>Pt),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 br(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()))}};_e.instance=null;let Wt=_e,tt=null;function wr(n){return tt||(tt=Wt.getInstance(n)),tt}function v(){return tt}function nt(n){Dn(n)}const Sr=[];let In=!1;function We(n){In=n}function Bt(){return In}function Nt(){return[...Sr]}const Cr=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:Nt,isDebugFetchEnabled:Bt,setDebugFetchEnabled:We},Symbol.toStringTag,{value:"Module"})),Er=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"},Tr={jsdelivr:{baseTimeout:60*1e3,maxTimeout:300*1e3}},st=[{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,xt=!1,rt=null;function Pn(n=!1){n&&be.clear(),st.forEach(e=>{be.has(e.name)||be.set(e.name,{name:e.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}Pn();function _r(n){return n==="jsdelivr"||n==="local"}function kn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!_r(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 On(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=k.preferenceCacheExpiry}async function Dr(){if(typeof caches>"u")return null;try{const e=await(await caches.open(k.preferenceCacheName)).match(k.preferenceCacheKey);return e!=null&&e.ok?kn(await e.json()):null}catch(n){return console.warn("[CDN Fallback] Failed to read persisted CDN preference:",n),null}}async function Ft(){xt||(rt||(rt=(async()=>{te=await Dr(),xt=!0,rt=null})()),await rt)}async function Wn(n){if(te=kn(n),xt=!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 Gt(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=Nn(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 Bn(n,e){const t=Tr[n]??{baseTimeout:k.degradeTimeout,maxTimeout:k.degradeTimeout},r=2**Math.max(0,e-k.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function Nn(n){const e=Bn(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function Ut(n,e={}){const t=be.get(n);if(!t)return!1;if(t.isHealthy||e.ignoreCooldown)return!0;const s=Date.now(),r=Bn(n,t.failCount);return s-t.lastCheckTime>r}function Ar(n,e={}){const t=te;return!t||!On(t,n)||t.cdn==="local"?null:Ut(t.cdn,e)?t.cdn:null}function xn(n,e={}){const t=n?Ar(n,e):null;return st.filter(s=>s.enabled&&Ut(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 Fn(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 Gn(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function Rr(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 Ht(n,e,t){const s=Rr(n,t);if(s)return s;const r=Fn(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function qt(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 jt(n,e){const t=Fn(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function Un(n,e,t){try{const s=jt(e,n),r=await qt(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 Hn(n,e,t,s){for(const r of n){const o=Ht(r,e,t);try{const a=await qt(o,s);if(!a.ok){ce(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await Lr(a,r.name))continue;return Gt(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 Lr(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 zt(n,e,t,s={}){if(Er)return null;await Ft();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 Un(n,t,o);if(u)return{...u,targetUrl:jt(t,n)}}const l=xn(e,{ignoreCooldown:i}),h=await Hn(l,e,n,c);if(h)return h;if(!r){const u=await Un(n,t,o);if(u)return{...u,targetUrl:jt(t,n)}}const d=st.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 Hn(d,e,n,c);if(u)return u}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function $t(n){await Ft();const e=new Map;for(const t of st){if(!t.enabled)continue;const s=Ht(t,n,t.healthCheckPath);try{const r=await qt(s,5e3),o=r.ok;e.set(t.name,o),o?Gt(t.name):ce(t.name,`status:${r.status}`)}catch{e.set(t.name,!1),ce(t.name,"health-check-failed")}}return e}function ot(){const n=On(te)?te==null?void 0:te.cdn:null;return Array.from(be.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,...Nn(t)}))}function Vt(){Pn(!0)}const Mr=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:Ht,ensureCDNPreferenceLoaded:Ft,extractVersionFromCDNPath:Gn,fetchFromCDNWithFallback:zt,getAvailableCDNs:xn,getCDNStatusReport:ot,isCDNAvailable:Ut,markCDNFailure:ce,markCDNSuccess:Gt,performHealthCheck:$t,resetCDNStatus:Vt,setCDNPreference:Wn},Symbol.toStringTag,{value:"Module"}));function qn(n){return n==="/"||n==="/index.html"}const vr=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"],Ir="_lazy_chunk_retry",Pr="_t",kr=600*1e3;function Or(n,e){return qn(e)?!0:n==="navigate"&&!e.endsWith(".html")}function jn(n){return qn(n)?!0:vr.some(e=>n.endsWith(e))}function Wr(n){return!jn(n)}function Br(n,e=Date.now()){const t=new URLSearchParams(n);if(t.get(Ir)!=="1")return!1;const s=Number(t.get(Pr));return!Number.isFinite(s)||s<=0?!0:e-s<=kr}const O=self;wr(O).setDebugClientCountChangedCallback(Zr);const ne={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function at(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 Nr(){console.log=(...n)=>{ne.log(...n),Bt()&&!at(n)&&it("log",n)},console.info=(...n)=>{ne.info(...n),Bt()&&!at(n)&&it("info",n)},console.warn=(...n)=>{ne.warn(...n),at(n)||it("warn",n)},console.error=(...n)=>{ne.error(...n),at(n)||it("error",n)}}function xr(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 it(n,e){try{const{message:t,stack:s}=xr(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof Kt=="function"&&Kt({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){ne.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let Kt=null;Nr(),Promise.resolve().then(()=>Te).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=v();t&&t.sendDebugLLMLog(e)})});const w="0.9.4",ct=new URL("./",self.location.href),Xt=ct.pathname,Yt=`drawnix-v${w}`,A="drawnix-images",De=`drawnix-static-v${w}`,lt="drawnix-fonts",le="sw-cache-date",ye="sw-cache-created-at",Qt="x-sw-source",Jt="x-sw-revision",Zt="x-sw-app-version",zn="x-sw-fetch-target",Fr="ServiceWorkerDB",Gr=2;yr({saveCrashSnapshot:Rs,getDebugStatus:as,addConsoleLog:nn,getDebugLogs:sn,clearDebugLogs:is,clearConsoleLogs:cs,enableDebugMode:rn,disableDebugMode:on,loadConsoleLogsFromDB:ns,clearAllConsoleLogs:rs,getCrashSnapshots:Ls,clearCrashSnapshots:Ms,getCacheStats:vs,deleteCacheByUrl:pn,getInternalFetchLogs:Nt,getCDNStatusReport:ot,resetCDNStatus:Vt,performHealthCheck:$t,getAppVersion:()=>w,getImageCacheName:()=>A,requestVideoThumbnail:async(n,e,t)=>{const s=v();return!s||s.getConnectedClientCount()===0?null:s.requestVideoThumbnail(n,e,t)}});const Ae="failedDomains",Re="versionState",$n="app-version-state",Vn="/__aitu_cache__/",Kn="/__aitu_generated__/audio/",Ur="/asset-library/",Be=location.hostname==="localhost"||location.hostname==="127.0.0.1";function H(n){return new URL(n.replace(/^\//,""),ct)}function Le(n){return Xt!=="/"&&n.startsWith(Xt)?`/${n.slice(Xt.length)}`:n}const Hr=[{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"}],qr=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,jr=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,en=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,zr=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)zr.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const q=new Map,we=new Map,Xn=30*1e3,ue=new Map,Yn=300*1e3,Qn=500,xe=new Map,G=new Map,$r=300*1e3,Jn=10,Me=new Set,ve=new Set,Vr=3600*1e3,tn=new Map;function Zn(n){ve.add(n),tn.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function Kr(n){if(!ve.has(n))return!1;const e=tn.get(n);return e&&Date.now()-e>Vr?(ve.delete(n),tn.delete(n),!1):!0}const Q=[],es=7,V=[],Xr=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>Xr&&V.pop(),ts(t),e}function R(n,e){if(!I||!n)return;const t=V.find(s=>s.id===n);t&&(Object.assign(t,e),ts(t))}function ts(n){const e=v();e&&e.sendDebugLog(n)}function ut(){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 Yr(n){try{const e=await ut(),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 ns(){try{await ss();const n=await ut(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-es*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 ss(){try{const n=await ut(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-es*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 rs(){try{const n=await ut(),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 os=500;function nn(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};Yr(r),Q.unshift(r),Q.length>os&&(Q.length=os),I&&Qr(r)}Kt=nn;function Qr(n){const e=v();e&&e.sendConsoleLog(n)}function Jr(){let n=0;return G.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function as(){return{version:w,cacheNames:[Yt,A,De,lt],pendingImageRequests:q.size,pendingVideoRequests:xe.size,videoBlobCacheSize:G.size,videoBlobCacheTotalBytes:Jr(),completedImageRequestsSize:we.size,failedDomainsCount:Me.size,failedDomains:Array.from(Me),corsFailedDomainsCount:ve.size,corsFailedDomains:Array.from(ve),debugLogsCount:V.length,consoleLogsCount:Q.length,debugModeEnabled:I,memoryStats:{pendingRequestsMapSize:q.size,completedRequestsMapSize:we.size,videoBlobCacheMapSize:G.size,failedDomainsSetSize:Me.size,corsFailedDomainsSetSize:ve.size,debugLogsArraySize:V.length,consoleLogsArraySize:Q.length}}}function sn(){return V}function is(){V.length=0}function cs(){Q.length=0}function rn(){I||(I=!0,We(!0),nt(!0),ne.log("Service Worker: Debug mode enabled (debug page connected)"))}function on(){I&&(I=!1,We(!1),nt(!1),Q.length=0,V.length=0,ne.log("Service Worker: Debug mode disabled (no debug pages)"))}function Zr(n){n>0?rn():on()}function ls(n){for(const e of Hr)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function eo(n,e){return qr.test(n.pathname)||e.destination==="image"||ls(n)!==null}function to(n,e){return jr.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function no(n,e){return en.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function so(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 ro(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function us(n){return`drawnix-static-v${n}`}function ds(){return{committedVersion:w,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function hs(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 dt(){return new Promise((n,e)=>{const t=indexedDB.open(Fr,Gr);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains(Ae)||r.createObjectStore(Ae,{keyPath:"domain"}),r.objectStoreNames.contains(Re)||r.createObjectStore(Re,{keyPath:"key"})}})}async function Fe(){try{const n=await dt();return await new Promise((e,t)=>{const o=n.transaction([Re],"readonly").objectStore(Re).get($n);o.onerror=()=>t(o.error),o.onsuccess=()=>{const a=o.result;e(hs((a==null?void 0:a.state)||ds()))}})}catch(n){return console.warn("Service Worker: 无法读取版本状态:",n),ds()}}async function oo(n){const e=hs(n);try{const t=await dt();await new Promise((s,r)=>{const o=t.transaction([Re],"readwrite");o.objectStore(Re).put({key:$n,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 oo({...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 ao(){try{const n=await dt();return await new Promise((e,t)=>{const o=n.transaction([Ae],"readonly").objectStore(Ae).getAll();o.onsuccess=()=>{o.result.forEach(i=>Me.add(i.domain)),e()},o.onerror=()=>t(o.error)})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function io(n){try{const e=await dt();return await new Promise((t,s)=>{const r=e.transaction([Ae],"readwrite");r.objectStore(Ae).put({domain:n,timestamp:Date.now()}),r.oncomplete=()=>t(),r.onerror=()=>s(r.error)})}catch(e){console.warn("Service Worker: 无法保存失败域名:",e)}}async function co(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 gs=2,fs=1500,an=2500,lo=8e3,uo=5e3,ho=6e4,ht=5e3,go=600*1e3,fo=["offline-static-assets"];let Ge=0,ps=0;const Ue=new Set,He=new Set,qe=new Set,gt=new Map;let ms=Promise.resolve(),je=null,ft=0,he=!1,pt=!1;function Ta(n,e){}function bs(){return ot().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 ys(n,e,t){console.warn("[SW Static 503]",{stage:n,requestUrl:e.url,destination:e.destination,mode:e.mode,unavailableCDNs:bs(),...t})}let cn={phase:"idle",percent:0,completed:0,total:0,failed:0,version:w,updatedAt:Date.now()};async function ws(n){const e={type:"SW_BOOT_PROGRESS",...cn};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){cn={...cn,...n,version:w,updatedAt:Date.now()},ws(e)}async function po(){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 Ie=null,Ee=0,ln=null;function ze(){return Be}function $e(n){ln=w,Ee=Date.now()}function un(){ln=null}function Ve(){return ln===w}async function mo(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 bo(){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 mo(e.clone());return e.status,e.statusText,(e.status===404||e.status===410)&&$e(`status:${e.status}`),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,$e("html-fallback"),null;let o;try{o=JSON.parse(s)}catch(a){return J(a),$e("invalid-json"),null}return!o||typeof o!="object"||!o.groups?($e("invalid-shape"),null):o.version&&o.version!==w?(o.version,$e(`version-mismatch:${o.version}`),null):(un(),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 mt(){if(ze())return Ee=0,Ie=null,un(),null;const n=Date.now();if(Ve())return null;if(!Ie){if(Ee>0&&n-Ee<ht)return null;Ie=bo().then(e=>{if(!e){const t=Ve();return Ee=Date.now(),Ie=t?Promise.resolve(null):null,null}return Ee=0,un(),e}).catch(e=>{throw Ee=Date.now(),J(e),Ie=null,e})}return Ie}async function dn(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 yo(n,e){return`${n}@${e}`}async function bt(n){try{return(await n.keys()).length}catch{return-1}}function Ke(n,e){const t=ms.catch(()=>{}).then(async()=>{try{await e()}finally{}});return ms=t.catch(s=>{console.warn("[SWDebug] idle prefetch task failed",{label:n,error:J(s)})}),t}function wo(n){return Math.min(ho,uo*2**Math.max(0,n-1))}function Ss(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),fo.forEach(r),Object.keys(n.groups).forEach(r),t}function Cs(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=yo(d.url,d.revision);if(Ue.has(u)||(h=!0,He.has(u)))continue;const b=gt.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 hn(n,e=an){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(je!==null){if(ft<=s)return;clearTimeout(je),je=null,ft=0}ft=s,je=self.setTimeout(()=>{je=null,ft=0,Ke(`idle-sweep:${n}`,async()=>{await St(`scheduled:${n}`)})},t)}function So(){return Ge===0?!1:Date.now()-Ge<fs}function Co(){if(Ge===0)return Promise.resolve();const n=Date.now()-Ge,e=Math.max(0,fs-n)+100;return new Promise(t=>{setTimeout(t,e)})}function Eo(n,e){if(Ve())return!1;const t=Le(e.pathname);if(n.request.method!=="GET"||!n.clientId||e.origin!==self.location.origin||e.pathname.startsWith(Vn)||e.pathname.startsWith(Kn)||t==="/sw.js"||t==="/precache-manifest.json"||t==="/idle-prefetch-manifest.json")return!1;const s=Date.now();return s-ps<lo?!1:(ps=s,!0)}function To(n){return jn(Le(n))}function Es(n,e){return Be||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||To(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 _o(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${e.replace(/^\/npm\/aitu-app@[^/]+\//,"/").replace(/^\/aitu-app@[^/]+\//,"/")}${t}`}function Do(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${Le(e)}${t}`}function yt(n){const e=new URL(n,self.location.origin),t=_o(Do(`${e.pathname}${e.search}`)),s=H(t);return{requestUrl:e,resourcePath:t,cacheKey:s.href,originFetchUrl:s.href}}function Xe(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&Es(n,e)}function Ao(n,e){const t=new Headers(n.headers);return t.set(Qt,e.source),t.set(Jt,e.revision),t.set(Zt,e.appVersion||w),e.fetchTarget&&t.set(zn,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 gn(n,e,t,s){const r=Ao(t,s);return await n.put(e,r.clone()),r}async function wt(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 Ro(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 Lo(n,e){const t=yt(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 Mo(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function Ts(n,e,t){try{const s=yt(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(Jt),l=r.headers.get(Zt);if(c===t&&l===w)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(Wr(Le(s.requestUrl.pathname))){const c=await zt(s.resourcePath,w,ct.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&&Xe(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 gn(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 vo(n,e){const s=[],r=e.length;let o=0,a=0;await bt(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})=>Ts(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 bt(n),{total:r,successCount:i,failCount:c,cdnCount:l,serverCount:h}}async function _s(n){if(n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await mt();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=Cs(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(De);await bt(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+=gs){for(;So();)await Co();const l=o.slice(c,c+gs);l.forEach(([u])=>He.add(u));const h=await Promise.allSettled(l.map(([,{url:u,revision:b}])=>Ts(r,u,b))),d=[];h.forEach((u,b)=>{const[p]=l[b];if(He.delete(p),u.status==="fulfilled"&&u.value.success)gt.delete(p),Ue.add(p);else{const g=gt.get(p),f=((g==null?void 0:g.count)||0)+1,y=wo(f);gt.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=Cs(e,n),i=a.completedGroups.filter(c=>!t.has(c));return i.forEach(c=>qe.add(c)),await bt(r),Ue.size,Array.from(qe),{completedGroups:i,pendingGroups:a.pendingGroups,queuedEntries:o.length,coolingEntries:a.coolingEntries,nextRetryDelayMs:a.nextRetryDelayMs}}async function St(n,e=[]){if(ze())return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const t=await mt();if(!t){const o=Ve();return o||hn(`${n}:manifest-missing`,ht),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:o?null:ht}}const s=Ss(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 _s(s);return r.completedGroups.length>0&&await dn(),r.pendingGroups.length>0&&hn(`${n}:pending`,r.nextRetryDelayMs??an),r}async function Io(){var t;if(ze())return;const n=await mt();if(!n){Ve()||hn("default-groups:manifest-missing",ht);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 St("default-groups",e)}async function Po(){if(ze())return;const n=Date.now();let e=null;for(;;){if(!e){const o=await mt();if(!o||(e=Ss(o),e.length===0))return}const t=await _s(e);if(t.completedGroups.length>0&&await dn(),t.pendingGroups.length===0)return;const s=Date.now()-n;if(s>=go)throw new Error(`idle-prefetch incomplete after ${s}ms: pending groups ${t.pendingGroups.join(", ")}`);const r=Math.max(250,t.nextRetryDelayMs??(t.queuedEntries>0?an:1e3));t.pendingGroups,t.coolingEntries,t.queuedEntries,await new Promise(o=>{setTimeout(o,r)})}}O.addEventListener("install",n=>{he=!!O.registration.active,pt=!he,he||O.skipWaiting(),Ce({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await ao(),await Se(e=>({committedVersion:e.committedVersion||w,pendingVersion:he?w:null,pendingReadyAt:null,upgradeState:he?"prewarming":"idle"})),await de();try{const e=await po();if(e&&e.length>0){const t=await caches.open(De),s=await vo(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&&Ke("update-ready-follow-up",async()=>{await Po()}),await co(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(()=>Mr);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}pt&&await O.clients.claim(),setTimeout(()=>{Ke("default-groups",async()=>Io())},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=us(s.committedVersion||w),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==De&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==Yt&&i!==A&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(De);await Bo(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),ss().catch(i=>{console.warn("Failed to cleanup expired console logs:",i)}),En.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function ko(n){if(I){const e=v();e&&e.sendPostMessageLog(n)}}async function Oo(n,e,t,s){if(Be)return null;try{const r=yt(e.url),o=await zt(t,s,ct.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:bs()}),null;const a=new URL(e.url);if(Xe(e,a,o.response))return null;const i=await gn(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 Wo(n){const e=n.headers.get(Qt)||void 0,t=n.headers.get(zn)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function Ds(n,e,t=w){const s=e.headers.get(Qt),r=e.headers.get(Jt),o=e.headers.get(Zt);if(!s||!r||!o){const i=new URL(n.url);return!(e.ok&&!Xe(n,i,e))}if(o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr")return!0;const a=new URL(n.url);return Xe(n,a,e)}async function Bo(n){const e=await n.keys();for(const t of e)try{const s=await n.match(t);s&&Ds(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(Mt()&&!r&&(o=vt(e,n.data,t,s,(g=n.data)==null?void 0:g.__internal__),o&&I)){const y=Je().find(S=>S.id===o);y&&ko(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(Wn({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,ws(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,dn(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(Ke(`message:${f.join(",")||"empty"}`,async()=>{await St(`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()=>{pt=!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()=>{pt=!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&&pn(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)&&Uo(f).then(()=>{}).catch(y=>{console.error("Service Worker: Failed to batch delete caches:",y)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")Ho().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),nt(!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),nt(!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(()=>Te),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(()=>Te);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(()=>Cr),y=sn(),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=Je(),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 No="MemorySnapshotDB",ge="snapshots",As=50;async function fn(){return new Promise((n,e)=>{const t=indexedDB.open(No,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 Rs(n){try{const e=await fn(),t=e.transaction(ge,"readwrite"),s=t.objectStore(ge);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>As){const i=s.index("timestamp").openCursor();let c=0;const l=o-As;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 Ls(){try{const n=await fn(),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 Ms(){try{const n=await fn(),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 xo=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function Fo(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Go(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+=Fo(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 vs(){const n={},e=[Yt,A,De,lt];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 xo)try{const s=await Go(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function pn(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 Uo(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 Ho(){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 qo(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 jo(n){const e=Date.now(),t=ue.get(n);if(t&&e-t<Yn)return!1;if(ue.size>=Qn){for(const[s,r]of ue)e-r>Yn&&ue.delete(s);if(ue.size>=Qn){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(!jo(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 zo(){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,Is=300*1e3,Ps=500;function $o(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 Vo(n){const e=se.get(n);return e?Date.now()-e>Is?(se.delete(n),!1):!0:!1}function ks(n){if($o(n)){if(se.size>=Ps){const e=Date.now();for(const[t,s]of se)e-s>Is&&se.delete(t);if(se.size>=Ps){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,Eo(n,e)){const s=`${e.pathname}${e.search}`;n.clientId,n.waitUntil(Ke(`fetch-recheck:${s}`,async()=>{await St(`fetch:${s}`)}))}if(e.pathname.startsWith(Vn)||e.pathname.startsWith(Kn)){const s=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(Xo(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(Ur)){const s=P({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Yo(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(Kr(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&&no(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(Qo(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(to(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(Jo(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(so(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(Ko(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&&eo(e,n.request)){if(Vo(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(na(n.request).then(o=>(o.status===404&&ks(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 ks(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(Zo(n.request).then(i=>{const c=Wo(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
+ `)}),i}).catch(i=>{throw R(a,{error:String(i),duration:Date.now()-o}),i}));return}}if(I){if(ro(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:
5
5
  ${o}`:`XHR/API request (${n.request.method})`});const i=await fetch(n.request),c=i.clone();let l;const h={};i.headers.forEach((d,u)=>{h[u]=d});try{const d=i.headers.get("content-type")||"";d.includes("application/json")||d.includes("text/")?(l=await c.text(),l.length>5e3&&(l=l.substring(0,5e3)+"... (truncated)")):l=`[${d||"binary data"}] (${i.headers.get("content-length")||"unknown"} bytes)`}catch{l="[unable to read response body]"}return R(s,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-t,responseHeaders:h,size:parseInt(i.headers.get("content-length")||"0"),details:o?`XHR/API request (${n.request.method})
@@ -11,7 +11,7 @@ Response Body:
11
11
  ${l}`:`XHR/API request (${n.request.method})
12
12
 
13
13
  Response Body:
14
- ${l}`}),i}catch(r){throw R(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function jo(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(at),s=await t.match(n);if(s)return s;const r=await fetch(n);if(r&&r.status===200){const o=r.clone(),a=new Headers(o.headers),i=Date.now().toString();a.set(le,i),a.set(ye,i);const c=new Response(o.body,{status:o.status,statusText:o.statusText,headers:a});t.put(n,c).catch(l=>{console.warn(`Service Worker [Font-${e}]: 缓存字体失败:`,l)})}return r}catch(t){console.error(`Service Worker [Font-${e}]: 字体请求失败:`,t);const r=await(await caches.open(at)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function wt(n,e={}){return fetch(n,e)}function St(n,e){const t=Ne(n.url),s=Re(e.pathname);return Array.from(new Set([s,e.pathname,t.toString(),n.url]))}async function vs(n,e){for(const t of e){const s=await n.match(t);if(s)try{if((await s.clone().blob()).size>0)return!0}catch{return!0}}return!1}async function zo(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname.includes("/audio/")||Jt.test(t.pathname),o=t.pathname.includes("/video/")||/\.(mp4|webm|mov)$/i.test(t.pathname),a=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),i=t.searchParams.has("_retry"),c=t.searchParams.has("thumbnail")&&!a&&!i;if(c){const l=t.searchParams.get("thumbnail")||"small",h=new URL(t.toString());h.searchParams.delete("thumbnail"),h.searchParams.delete("bypass_sw"),h.searchParams.delete("direct_fetch"),h.searchParams.delete("_retry");const{findThumbnailWithFallback:d,createThumbnailResponse:u}=await Promise.resolve().then(()=>j),b=await d(h.toString(),l,[t.pathname]);if(b){const p=await caches.open(A),g=St(new Request(h.toString()),h);await vs(p,g)||await fe(h.toString(),"thumbnail_exists_original_missing");const f=await b.response.blob();return u(f)}}try{const l=await caches.open(A);let h;for(const d of St(n,t))if(h=await l.match(d),h)break;if(h){const d=await h.blob();if(c&&!o){const{generateThumbnailAsync:u}=await Promise.resolve().then(()=>j);u(d,t.pathname,"image")}return o?Pe(d,s,e):r?Ve(d,s,e):new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":d.type||"image/png","Content-Length":d.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return new Response("Media not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(l){return console.error("Service Worker: Error handling cache URL request:",l),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function $o(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname,o=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),a=t.searchParams.has("_retry"),i=t.searchParams.has("thumbnail")&&!o&&!a;if(i){const c=t.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:l,createThumbnailResponse:h}=await Promise.resolve().then(()=>j),d=await l(r,c,[r]);if(d){const u=await caches.open(A),b=St(new Request(t.toString(),{method:n.method}),t);await vs(u,b)||await fe(t.pathname,"thumbnail_exists_original_missing");const p=await d.response.blob();return h(p)}}try{const c=await caches.open(A);let l;for(const h of St(n,t))if(l=await c.match(h),l)break;if(l){const h=await l.blob(),d=t.pathname.match(/\.(mp4|webm|mov)$/i),u=Jt.test(t.pathname);if(i&&!d){const{generateThumbnailAsync:b}=await Promise.resolve().then(()=>j);b(h,r,"image")}return d&&s?Pe(h,s,e):u?Ve(h,s,e):new Response(h,{status:200,statusText:"OK",headers:{"Content-Type":h.type||"application/octet-stream","Content-Length":h.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return new Response("Asset not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(c){return console.error(`Service Worker [Asset-${e}]: Error handling asset library request:`,c),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Vo(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10),s=n.headers.get("range"),o=Ne(e).toString();try{const a=await caches.open(A);let i=await a.match(o);if(!i&&o!==n.url&&(i=await a.match(n.url)),i)try{const p=await i.clone().blob();return Ve(p,s,t)}catch{return i}const c=new Headers(n.headers);c.delete("range");const l=await fetch(o,{method:"GET",headers:c,mode:n.mode,credentials:n.credentials,cache:"no-store",referrerPolicy:n.referrerPolicy||"no-referrer"});if(!l.ok)return l;if(l.type==="opaque")return a.put(o,l.clone()).catch(p=>{console.warn(`Service Worker [Audio-${t}]: Failed to cache opaque audio response:`,p)}),l;const h=await l.blob(),d=l.headers.get("Content-Type")||h.type||"audio/mpeg",u=Date.now().toString(),b=new Response(h,{status:200,statusText:"OK",headers:{"Content-Type":d,"Content-Length":h.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length",[le]:u,[ye]:u,"sw-image-size":h.size.toString()}});return await a.put(o,b.clone()),Ve(h,s,t,d)}catch(a){console.error(`Service Worker [Audio-${t}]: Audio loading failed:`,a);const i=await caches.open(A);let c=await i.match(o);if(!c&&o!==n.url&&(c=await i.match(n.url)),c)try{const l=await c.clone().blob();return Ve(l,s,t)}catch{return c}return new Response("Audio loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const Ct=Symbol("VIDEO_LOAD_ERROR");async function Ko(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10);try{const s=n.headers.get("range"),r=e.searchParams.has("bypass_sw")||e.searchParams.has("direct_fetch"),o=e.searchParams.has("_retry"),a=e.searchParams.has("thumbnail")&&!r&&!o,i=Ne(e),c=i.toString();if(a){const u=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:b,createThumbnailResponse:p}=await Promise.resolve().then(()=>j),g=await b(c,u);if(g){const f=await g.response.blob();return p(f)}return(async()=>{try{const{generateThumbnailAsync:f}=await Promise.resolve().then(()=>j);f(new Blob([],{type:"video/mp4"}),c,"video",[u])}catch{return}})(),new Response("Thumbnail not ready",{status:404,statusText:"Thumbnail Not Ready",headers:{"Content-Type":"text/plain","Cache-Control":"no-store"}})}const l=xe.get(c);if(l){l.count=(l.count||1)+1;const u=await l.promise;if(u===Ct)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(u===null){const b={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,b)}return Pe(u,s,t)}if(G.has(c)){const u=G.get(c);if(u)return u.timestamp=Date.now(),Pe(u.blob,s,t)}try{const b=await(await caches.open(A)).match(c);if(b){const p=await b.blob();return p.size/(1024*1024)<50&&G.set(c,{blob:p,timestamp:Date.now()}),Pe(p,s,t)}}catch{}const h=(async()=>{try{const u={method:"GET",mode:"cors",credentials:"omit",cache:"default"},b=new URL(i),p=await fetch(b,u);if(!p.ok)return Ct;if(p.status===206)return null;const g=await p.blob();if(g.size/(1024*1024)<50){G.set(c,{blob:g,timestamp:Date.now()});try{const y=await caches.open(A),S=new Response(g,{headers:{"Content-Type":g.type||"video/mp4","Content-Length":g.size.toString(),[le]:Date.now().toString(),[ye]:Date.now().toString(),"sw-video-size":g.size.toString()}});await y.put(c,S);const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(g,c,"video")}catch{}}return g}catch{return Ct}})();xe.set(c,{promise:h,timestamp:Date.now(),count:1,requestId:t}),h.finally(()=>{xe.get(c)&&xe.delete(c)});const d=await h;if(d===Ct)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(d===null){const u={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,u)}return Pe(d,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function Pe(n,e,t){return Is(n,e,t,n.type||"video/mp4")}function Ve(n,e,t,s){return Is(n,e,t,s||n.type||"audio/mpeg")}function Is(n,e,t,s){const r=n.size;if(!e)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":s,"Content-Length":r.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}});const o=e.match(/bytes=(\d+)-(\d*)/);if(!o)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":s,"Accept-Ranges":"bytes"}});const a=parseInt(o[1],10),i=o[2]?parseInt(o[2],10):r-1,c=n.slice(a,i+1),l=i-a+1;return new Response(c,{status:206,statusText:"Partial Content",headers:{"Content-Type":s,"Content-Range":`bytes ${a}-${i}/${r}`,"Content-Length":l.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}})}async function Xo(n){const e=new URL(n.url),t=mt(n.url),s=t.cacheKey,r=Re(e.pathname),o=vr(n.mode,r),i=(await Fe()).committedVersion||w,c=as(i),l=await caches.open(c);if(Be)try{const p=await wt(n);if(p&&p.status===200&&n.url.startsWith("http"))return l.put(n,p.clone()),p;if(!p.ok){let g=await l.match(n);return!g&&o&&(g=await l.match(H("/").href),g||(g=await l.match(H("index.html").href))),g||p}return p}catch{let g=await l.match(n);return!g&&o&&(g=await l.match(H("/").href),g||(g=await l.match(H("index.html").href))),g||(o?Ps():new Response("Resource unavailable",{status:503}))}if(o){if(Pr(e.search))try{const g=await wt(n,{cache:"reload"});if(g&&g.status===200&&n.url.startsWith("http"))return l.put(n,g.clone()),n.url,g;if(g)return g}catch(g){n.url,J(g)}let p=await l.match(n);if(p||(p=await l.match(H("/").href)),p||(p=await l.match(H("index.html").href)),!p){const g=await caches.keys();for(const f of g)if(f.startsWith("drawnix-static-v"))try{const y=await caches.open(f);if(p=await y.match(n)||await y.match(H("/").href)||await y.match(H("index.html").href),p)break}catch{}}if(p)return p;try{const g=await wt(n,{cache:"reload"});return g&&g.status===200&&n.url.startsWith("http")&&i===w&&l.put(n,g.clone()),g}catch{return Ps()}}const{response:h,matchedBy:d}=await _o(l,n);if(h){if(!Cs(n,h,i))return d==="normalized"&&(n.url,void 0),h;await Do(l,n,s)}const u=t.resourcePath;if(ys(n,e)){n.url!==s&&(n.url,void 0);const p=await bt(n,[s]);if(p)return p;const g=await To(n,[s]);if(g)return g;const f=Bn(e.pathname),y=f||i,S=await vo(l,n,u,y);return S||(fs("smart-cdn-resource-failed",n,{resourcePath:u,committedVersion:i,hasEmbeddedVersion:!!f,attemptedVersion:y}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}try{const p=await wt(n);if($e(n,e,p)){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const f=await bt(n,[s]);return f||new Response("Resource not found",{status:404,statusText:"Not Found"})}if(p&&p.status===200&&n.url.startsWith("http")&&i===w)return await ln(l,n,p,{source:"server",revision:"runtime",appVersion:i});if(p.status>=400){const f=await bt(n,[s]);if(f)return f}return p}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const g=await bt(n,[s]);return g||(fs("origin-fetch-exception",n,{resourcePath:u,committedVersion:i}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}}function Ps(){return new Response(`<!DOCTYPE html>
14
+ ${l}`}),i}catch(r){throw R(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function Ko(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(lt),s=await t.match(n);if(s)return s;const r=await fetch(n);if(r&&r.status===200){const o=r.clone(),a=new Headers(o.headers),i=Date.now().toString();a.set(le,i),a.set(ye,i);const c=new Response(o.body,{status:o.status,statusText:o.statusText,headers:a});t.put(n,c).catch(l=>{console.warn(`Service Worker [Font-${e}]: 缓存字体失败:`,l)})}return r}catch(t){console.error(`Service Worker [Font-${e}]: 字体请求失败:`,t);const r=await(await caches.open(lt)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function Ct(n,e={}){return fetch(n,e)}function Et(n,e){const t=Ne(n.url),s=Le(e.pathname);return Array.from(new Set([s,e.pathname,t.toString(),n.url]))}async function Os(n,e){for(const t of e){const s=await n.match(t);if(s)try{if((await s.clone().blob()).size>0)return!0}catch{return!0}}return!1}async function Xo(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname.includes("/audio/")||en.test(t.pathname),o=t.pathname.includes("/video/")||/\.(mp4|webm|mov)$/i.test(t.pathname),a=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),i=t.searchParams.has("_retry"),c=t.searchParams.has("thumbnail")&&!a&&!i;if(c){const l=t.searchParams.get("thumbnail")||"small",h=new URL(t.toString());h.searchParams.delete("thumbnail"),h.searchParams.delete("bypass_sw"),h.searchParams.delete("direct_fetch"),h.searchParams.delete("_retry");const{findThumbnailWithFallback:d,createThumbnailResponse:u}=await Promise.resolve().then(()=>j),b=await d(h.toString(),l,[t.pathname]);if(b){const p=await caches.open(A),g=Et(new Request(h.toString()),h);await Os(p,g)||await fe(h.toString(),"thumbnail_exists_original_missing");const f=await b.response.blob();return u(f)}}try{const l=await caches.open(A);let h;for(const d of Et(n,t))if(h=await l.match(d),h)break;if(h){const d=await h.blob();if(c&&!o){const{generateThumbnailAsync:u}=await Promise.resolve().then(()=>j);u(d,t.pathname,"image")}return o?Pe(d,s,e):r?Ye(d,s,e):new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":d.type||"image/png","Content-Length":d.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return new Response("Media not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(l){return console.error("Service Worker: Error handling cache URL request:",l),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Yo(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname,o=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),a=t.searchParams.has("_retry"),i=t.searchParams.has("thumbnail")&&!o&&!a;if(i){const c=t.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:l,createThumbnailResponse:h}=await Promise.resolve().then(()=>j),d=await l(r,c,[r]);if(d){const u=await caches.open(A),b=Et(new Request(t.toString(),{method:n.method}),t);await Os(u,b)||await fe(t.pathname,"thumbnail_exists_original_missing");const p=await d.response.blob();return h(p)}}try{const c=await caches.open(A);let l;for(const h of Et(n,t))if(l=await c.match(h),l)break;if(l){const h=await l.blob(),d=t.pathname.match(/\.(mp4|webm|mov)$/i),u=en.test(t.pathname);if(i&&!d){const{generateThumbnailAsync:b}=await Promise.resolve().then(()=>j);b(h,r,"image")}return d&&s?Pe(h,s,e):u?Ye(h,s,e):new Response(h,{status:200,statusText:"OK",headers:{"Content-Type":h.type||"application/octet-stream","Content-Length":h.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return new Response("Asset not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(c){return console.error(`Service Worker [Asset-${e}]: Error handling asset library request:`,c),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Qo(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10),s=n.headers.get("range"),o=Ne(e).toString();try{const a=await caches.open(A);let i=await a.match(o);if(!i&&o!==n.url&&(i=await a.match(n.url)),i)try{const p=await i.clone().blob();return Ye(p,s,t)}catch{return i}const c=new Headers(n.headers);c.delete("range");const l=await fetch(o,{method:"GET",headers:c,mode:n.mode,credentials:n.credentials,cache:"no-store",referrerPolicy:n.referrerPolicy||"no-referrer"});if(!l.ok)return l;if(l.type==="opaque")return a.put(o,l.clone()).catch(p=>{console.warn(`Service Worker [Audio-${t}]: Failed to cache opaque audio response:`,p)}),l;const h=await l.blob(),d=l.headers.get("Content-Type")||h.type||"audio/mpeg",u=Date.now().toString(),b=new Response(h,{status:200,statusText:"OK",headers:{"Content-Type":d,"Content-Length":h.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length",[le]:u,[ye]:u,"sw-image-size":h.size.toString()}});return await a.put(o,b.clone()),Ye(h,s,t,d)}catch(a){console.error(`Service Worker [Audio-${t}]: Audio loading failed:`,a);const i=await caches.open(A);let c=await i.match(o);if(!c&&o!==n.url&&(c=await i.match(n.url)),c)try{const l=await c.clone().blob();return Ye(l,s,t)}catch{return c}return new Response("Audio loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const Tt=Symbol("VIDEO_LOAD_ERROR");async function Jo(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10);try{const s=n.headers.get("range"),r=e.searchParams.has("bypass_sw")||e.searchParams.has("direct_fetch"),o=e.searchParams.has("_retry"),a=e.searchParams.has("thumbnail")&&!r&&!o,i=Ne(e),c=i.toString();if(a){const u=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:b,createThumbnailResponse:p}=await Promise.resolve().then(()=>j),g=await b(c,u);if(g){const f=await g.response.blob();return p(f)}return(async()=>{try{const{generateThumbnailAsync:f}=await Promise.resolve().then(()=>j);f(new Blob([],{type:"video/mp4"}),c,"video",[u])}catch{return}})(),new Response("Thumbnail not ready",{status:404,statusText:"Thumbnail Not Ready",headers:{"Content-Type":"text/plain","Cache-Control":"no-store"}})}const l=xe.get(c);if(l){l.count=(l.count||1)+1;const u=await l.promise;if(u===Tt)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(u===null){const b={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,b)}return Pe(u,s,t)}if(G.has(c)){const u=G.get(c);if(u)return u.timestamp=Date.now(),Pe(u.blob,s,t)}try{const b=await(await caches.open(A)).match(c);if(b){const p=await b.blob();return p.size/(1024*1024)<50&&G.set(c,{blob:p,timestamp:Date.now()}),Pe(p,s,t)}}catch{}const h=(async()=>{try{const u={method:"GET",mode:"cors",credentials:"omit",cache:"default"},b=new URL(i),p=await fetch(b,u);if(!p.ok)return Tt;if(p.status===206)return null;const g=await p.blob();if(g.size/(1024*1024)<50){G.set(c,{blob:g,timestamp:Date.now()});try{const y=await caches.open(A),S=new Response(g,{headers:{"Content-Type":g.type||"video/mp4","Content-Length":g.size.toString(),[le]:Date.now().toString(),[ye]:Date.now().toString(),"sw-video-size":g.size.toString()}});await y.put(c,S);const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(g,c,"video")}catch{}}return g}catch{return Tt}})();xe.set(c,{promise:h,timestamp:Date.now(),count:1,requestId:t}),h.finally(()=>{xe.get(c)&&xe.delete(c)});const d=await h;if(d===Tt)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(d===null){const u={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,u)}return Pe(d,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function Pe(n,e,t){return Ws(n,e,t,n.type||"video/mp4")}function Ye(n,e,t,s){return Ws(n,e,t,s||n.type||"audio/mpeg")}function Ws(n,e,t,s){const r=n.size;if(!e)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":s,"Content-Length":r.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}});const o=e.match(/bytes=(\d+)-(\d*)/);if(!o)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":s,"Accept-Ranges":"bytes"}});const a=parseInt(o[1],10),i=o[2]?parseInt(o[2],10):r-1,c=n.slice(a,i+1),l=i-a+1;return new Response(c,{status:206,statusText:"Partial Content",headers:{"Content-Type":s,"Content-Range":`bytes ${a}-${i}/${r}`,"Content-Length":l.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}})}async function Zo(n){const e=new URL(n.url),t=yt(n.url),s=t.cacheKey,r=Le(e.pathname),o=Or(n.mode,r),i=(await Fe()).committedVersion||w,c=us(i),l=await caches.open(c);if(Be)try{const p=await Ct(n);if(p&&p.status===200&&n.url.startsWith("http"))return l.put(n,p.clone()),p;if(!p.ok){let g=await l.match(n);return!g&&o&&(g=await l.match(H("/").href),g||(g=await l.match(H("index.html").href))),g||p}return p}catch{let g=await l.match(n);return!g&&o&&(g=await l.match(H("/").href),g||(g=await l.match(H("index.html").href))),g||(o?Bs():new Response("Resource unavailable",{status:503}))}if(o){if(Br(e.search))try{const g=await Ct(n,{cache:"reload"});if(g&&g.status===200&&n.url.startsWith("http"))return l.put(n,g.clone()),n.url,g;if(g)return g}catch(g){n.url,J(g)}let p=await l.match(n);if(p||(p=await l.match(H("/").href)),p||(p=await l.match(H("index.html").href)),!p){const g=await caches.keys();for(const f of g)if(f.startsWith("drawnix-static-v"))try{const y=await caches.open(f);if(p=await y.match(n)||await y.match(H("/").href)||await y.match(H("index.html").href),p)break}catch{}}if(p)return p;try{const g=await Ct(n,{cache:"reload"});return g&&g.status===200&&n.url.startsWith("http")&&i===w&&l.put(n,g.clone()),g}catch{return Bs()}}const{response:h,matchedBy:d}=await Lo(l,n);if(h){if(!Ds(n,h,i))return d==="normalized"&&(n.url,void 0),h;await Mo(l,n,s)}const u=t.resourcePath;if(Es(n,e)){n.url!==s&&(n.url,void 0);const p=await wt(n,[s]);if(p)return p;const g=await Ro(n,[s]);if(g)return g;const f=Gn(e.pathname),y=f||i,S=await Oo(l,n,u,y);return S||(ys("smart-cdn-resource-failed",n,{resourcePath:u,committedVersion:i,hasEmbeddedVersion:!!f,attemptedVersion:y}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}try{const p=await Ct(n);if(Xe(n,e,p)){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const f=await wt(n,[s]);return f||new Response("Resource not found",{status:404,statusText:"Not Found"})}if(p&&p.status===200&&n.url.startsWith("http")&&i===w)return await gn(l,n,p,{source:"server",revision:"runtime",appVersion:i});if(p.status>=400){const f=await wt(n,[s]);if(f)return f}return p}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const g=await wt(n,[s]);return g||(ys("origin-fetch-exception",n,{resourcePath:u,committedVersion:i}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}}function Bs(){return new Response(`<!DOCTYPE html>
15
15
  <html lang="zh-CN">
16
16
  <head>
17
17
  <meta charset="UTF-8">
@@ -52,4 +52,4 @@ ${l}`}),i}catch(r){throw R(s,{error:String(r),duration:Date.now()-t}),r}})());re
52
52
  <p>Opentu 是一个以画布工作区为底座的 AI 应用平台,当前无法访问时请检查网络或稍后再试。</p>
53
53
  <button onclick="location.reload()">重试</button>
54
54
  </body>
55
- </html>`,{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}const hn=15e3,ks=3e4;function Os(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function Yo(){const n=Date.now(),e=[];if(G.forEach((t,s)=>{n-t.timestamp>Hr&&e.push(s)}),e.length>0&&e.forEach(t=>G.delete(t)),G.size>Kn){const t=Array.from(G.entries()).sort((o,a)=>o[1].timestamp-a[1].timestamp),s=G.size-Kn,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>G.delete(o))}}function Qo(){const n=Date.now(),e=[];q.forEach((s,r)=>{n-s.timestamp>ks&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>q.delete(s)));const t=[];we.forEach((s,r)=>{n-s.timestamp>zn&&t.push(r)}),t.length>0&&t.forEach(s=>we.delete(s)),Yo()}async function Jo(n){try{const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),r=t.searchParams.has("_retry"),o=t.searchParams.has("thumbnail")&&!s&&!r,a=o&&t.searchParams.get("thumbnail")||"small",i=Ne(t),c=new Request(i.toString(),{method:n.method,headers:n.headers,mode:n.mode,credentials:n.credentials}),l=i.toString();if(o){const{findThumbnailWithFallback:u,createThumbnailResponse:b}=await Promise.resolve().then(()=>j),p=await u(l,a,[n.url,c.url]);if(p){const g=await p.response.blob();return b(g)}}const h=we.get(l);if(h){if(Date.now()-h.timestamp<zn)return h.response.clone();we.delete(l)}if(q.has(l)){const u=q.get(l);if(u){const b=Date.now()-u.timestamp;if(b>ks)console.warn(`Service Worker [${e}]: 发现过期的 pending 请求 (${b}ms),清理并重新发起:`,l),q.delete(l);else{u.count=(u.count||1)+1,u.duplicateRequestIds=u.duplicateRequestIds||[],u.duplicateRequestIds.push(e);try{const p=await Os(u.promise,hn,"Image request timeout");return p&&p.clone?p.clone():p}catch(p){if(p.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 重复请求等待超时,清理并返回超时响应让前端直接加载`),q.delete(l),Ws(n.url,e);throw p}}}}Qo();const d=Zo(c,n.url,l,e,s,o?a:void 0);q.set(l,{promise:d,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),d.then(u=>{u&&u.ok&&we.set(l,{response:u.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{q.get(l)&&q.delete(l)});try{return await Os(d,hn,"Image request timeout")}catch(u){if(u.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${hn}ms),清理并返回超时响应让前端直接加载:`,n.url),q.delete(l),Ws(n.url,e);throw u}}catch(e){throw e}}function Ws(n,e){return new Response("Image request timeout - use direct load",{status:504,statusText:"Gateway Timeout",headers:{"Content-Type":"text/plain","X-SW-Timeout":"true","X-SW-Original-URL":n,"Access-Control-Allow-Origin":"*"}})}async function Zo(n,e,t,s,r=!1,o){try{const a=await caches.open(A);if(!r){let g=await a.match(n);if(g||(g=await a.match(n.url)),!g&&e!==n.url&&(g=await a.match(e)),g||(g=await a.match(t)),g){const y=await g.clone().blob();if(y.size===0)console.warn(`Service Worker [${s}]: 检测到空缓存,删除并重新获取:`,e),await a.delete(n);else{if(o){const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(y,n.url,"image")}const S=g.headers.get(le);if(S){const E=Date.now(),W=g.headers.get(ye)||S,U=new Response(y,{status:g.status,statusText:g.statusText,headers:{...Object.fromEntries(g.headers.entries()),[le]:E.toString(),[ye]:W}});return n.url.startsWith("http")&&(await a.put(t,U.clone()),e!==t&&await a.delete(e)),U}else{const E=new Response(y,{status:g.status,statusText:g.statusText,headers:{...Object.fromEntries(g.headers.entries()),[le]:Date.now().toString(),[ye]:Date.now().toString()}});return n.url.startsWith("http")&&(await a.put(t,E.clone()),e!==t&&await a.delete(e)),E}}}}const i=new URL(e),c=os(i);let l=null,h=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),Le.has(c.hostname)&&(h=!0));let d;const u=[{method:"GET",mode:"cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"},{method:"GET",cache:"no-cache"},{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"}];let b;h?b=[l]:(b=[e],l&&b.push(l));let p=null;for(let g=0;g<b.length;g++){const f=b[g],y=g>0;for(const S of u)try{let E,W=!1;for(let U=0;U<=2;U++)try{if(d=await fetch(f,S),d&&(d.status!==0||d.type==="opaque"))break}catch(re){E=re;const ke=re.message||"";if(ke.includes("CORS")||ke.includes("cross-origin")||ke.includes("Access-Control-Allow-Origin")||ke.includes("Failed to fetch")||ke.includes("NetworkError")||ke.includes("TypeError")){W=!0;break}U<2&&await new Promise(ba=>setTimeout(ba,Math.pow(2,U)*1e3))}if(W){const U=new URL(f).hostname;Xn(U);try{const re=await fetch(e,{mode:"no-cors",credentials:"omit",referrerPolicy:"no-referrer"});if(re.type==="opaque")return await fe(e,"cors_opaque"),re}catch(re){console.warn(`Service Worker [${s}]: no-cors 模式也失败:`,re)}return await fe(e,"cors_fetch_failed"),new Response(null,{status:200,headers:{"Content-Type":"image/png","X-SW-CORS-Bypass":"true"}})}if(d&&(d.status!==0||d.type==="opaque"))break;E&&(p=E)}catch(E){p=E;continue}if(d&&(d.status!==0||d.type==="opaque"))break;c&&c.fallbackDomain&&g===0&&!h&&(Le.add(c.hostname),so(c.hostname).catch(S=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",S)}))}if(!d||d.status===0&&d.type!=="opaque"){let g="All fetch attempts failed";return c&&c.fallbackDomain&&(h?g=`备用域名${c.fallbackDomain}也失败了`:g=`All fetch attempts failed for both ${c.hostname} and ${c.fallbackDomain} domains`),console.error(`Service Worker [${s}]: ${g}`,p),await fe(t,g),new Response("Image load failed after all attempts",{status:404,statusText:"Image Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*"}})}if(d.type==="opaque"){const g=new URL(e).hostname;return Xn(g),await fe(t,"cors_opaque"),d}if(d.ok){const f=await d.clone().blob(),y=f.size/(1024*1024),S=new Response(f,{status:200,statusText:"OK",headers:{"Content-Type":d.headers.get("Content-Type")||"image/png","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*","Cache-Control":"max-age=3153600000",[le]:Date.now().toString(),[ye]:Date.now().toString(),"sw-image-size":f.size.toString()}});try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await Fo(t,f.size,f.type),await Uo();const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(f,t,"image")}}catch(E){console.warn(`Service Worker: Failed to cache normal response (${y.toFixed(2)}MB, 可能超出存储限制):`,E),await fe(t,String(E))}return S}throw new Error(`HTTP ${d.status}: ${d.statusText}`)}catch(a){const i=new URL(e);return a.message.includes("SSL_PROTOCOL_ERROR")||a.message.includes("ERR_SSL_PROTOCOL_ERROR")||a.message.includes("net::ERR_CERT")||a.message.includes("ERR_INSECURE_RESPONSE")?(console.warn("Service Worker: 检测到SSL/证书错误,尝试跳过Service Worker处理"),fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit"}).catch(()=>new Response("SSL Error - Image not accessible",{status:404,statusText:"SSL Protocol Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}))):i.pathname.match(/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i)||i.searchParams.has("_t")||i.searchParams.has("cache_buster")||i.searchParams.has("timestamp")?(await fe(e,String((a==null?void 0:a.message)||a)),new Response("Image not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}})):new Response(`Network Error: ${a.message}`,{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}})}}const Et="drawnix-images-thumb",Bs=128,gn=400,ea=.8;function ta(n,e,t){const s=n/e;let r=t,o=t;return s>1?o=t/s:r=t*s,{width:Math.round(r),height:Math.round(o)}}function fn(n,e){try{let t;try{t=new URL(n)}catch{t=new URL(n,self.location.origin)}return t.searchParams.delete("thumbnail"),t.searchParams.set("_thumb",e),t.toString()}catch{const t=n.includes("?")?"&":"?";return`${n.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/,"")}${t}_thumb=${e}`}}async function Ns(n,e,t=["small","large"]){try{for(const s of t)await na(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function na(n,e,t){try{const s=t==="large"?gn:Bs,r=fn(e,t),o=await caches.open(Et);let a=await o.match(r);if(!a){const f=new Request(r,{method:"GET"});a=await o.match(f)}if(!a)try{const f=new URL(r);a=await o.match(f.pathname)}catch{}if(a||n.size===0)return;const i=(n.type||"").toLowerCase();if(!i.startsWith("image/")&&i!=="")return;let c;try{c=await createImageBitmap(n)}catch(f){if(f instanceof Error&&f.name==="InvalidStateError")return;throw f}const{width:l,height:h}=ta(c.width,c.height,s),d=new OffscreenCanvas(l,h),u=d.getContext("2d");if(!u){console.warn("[ThumbnailUtils] Failed to get canvas context");return}try{u.drawImage(c,0,0,l,h)}finally{c.close()}const b=await d.convertToBlob({type:"image/jpeg",quality:ea}),p=()=>new Response(b,{headers:{"Content-Type":"image/jpeg","Content-Length":b.size.toString()}}),g=new Request(r,{method:"GET"});await o.put(g,p()),await o.put(r,p());try{const f=new URL(r);(f.pathname.startsWith("/__aitu_cache__/")||f.pathname.startsWith("/asset-library/"))&&await o.put(r,p())}catch{}}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function xs(n,e,t=["small","large"]){try{for(const s of t)await sa(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function sa(n,e,t){try{const s=fn(e,t),r=await caches.open(Et);let o=await r.match(s);if(!o){const h=new Request(s,{method:"GET"});o=await r.match(h)}if(!o)try{const h=new URL(s);o=await r.match(h.pathname)}catch{}if(o)return;const i=await ra(e,n,t==="large"?gn:Bs);if(!i){console.warn(`[ThumbnailUtils] Failed to generate ${t} video thumbnail from main thread`);return}const c=()=>new Response(i,{headers:{"Content-Type":"image/jpeg","Content-Length":i.size.toString()}}),l=new Request(s,{method:"GET"});await r.put(l,c()),await r.put(s,c());try{const h=new URL(s);(h.pathname.startsWith("/__aitu_cache__/")||h.pathname.startsWith("/asset-library/"))&&await r.put(s,c())}catch{}}catch(s){console.warn(`[ThumbnailUtils] ❌ Failed to generate ${t} video thumbnail:`,s)}}async function ra(n,e,t=gn){const s=D().requestVideoThumbnail;if(!s)return console.warn("[ThumbnailUtils] No connected clients for video thumbnail generation"),null;const r=await s(n,3e4,t);if(!r)return null;try{return await(await fetch(r)).blob()}catch(o){return console.warn("[ThumbnailUtils] Failed to convert thumbnail URL to blob:",o),null}}async function pn(n,e,t){try{const s=await caches.open(Et),r=fn(n,e);let o=await s.match(r);if(!o){const a=new Request(r,{method:"GET"});o=await s.match(a)}if(!o&&t)for(const a of t){const i=await s.match(a);if(i){o=i;break}}return o||null}catch(s){return console.warn("[ThumbnailUtils] Error finding thumbnail:",s),null}}async function oa(n,e,t){let s=await pn(n,e,t);if(s)return{response:s,size:e};const r=e==="small"?"large":"small";return s=await pn(n,r,t),s?{response:s,size:r}:null}function aa(n){return new Response(n,{status:200,headers:{"Content-Type":"image/jpeg","Content-Length":n.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}function ia(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await Ns(n,e,s):await xs(n,e,s)}catch(r){console.warn(`[ThumbnailUtils] Failed to generate ${t} thumbnail:`,r)}})()}const j=Object.freeze(Object.defineProperty({__proto__:null,IMAGE_CACHE_NAME_THUMB:Et,createThumbnailResponse:aa,findThumbnail:pn,findThumbnailWithFallback:oa,generateImageThumbnail:Ns,generateThumbnailAsync:ia,generateVideoThumbnail:xs},Symbol.toStringTag,{value:"Module"})),pe=[],ca="llm-api-logs",la=4,K="logs";function Tt(){return new Promise((n,e)=>{const t=indexedDB.open(ca,la);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result,o=s.oldVersion;let a;if(!r.objectStoreNames.contains(K))a=r.createObjectStore(K,{keyPath:"id"}),a.createIndex("timestamp","timestamp",{unique:!1}),a.createIndex("taskType","taskType",{unique:!1}),a.createIndex("status","status",{unique:!1}),a.createIndex("taskId","taskId",{unique:!1});else{const i=s.target.transaction;i&&(a=i.objectStore(K),o<4&&!a.indexNames.contains("taskId")&&a.createIndex("taskId","taskId",{unique:!1}))}}})}async function Fs(){try{const s=(await Tt()).transaction(K,"readonly").objectStore(K).index("timestamp");return new Promise((r,o)=>{const a=s.getAll();a.onsuccess=()=>{const i=a.result.reverse();r(i)},a.onerror=()=>{o(a.error)}})}catch(n){return console.warn("[LLMApiLogger] Failed to get logs from DB:",n),pe}}function ua(n){return{id:n.id,timestamp:n.timestamp,endpoint:n.endpoint,model:n.model,taskType:n.taskType,taskId:n.taskId,prompt:n.prompt?n.prompt.length>200?n.prompt.substring(0,200)+"...":n.prompt:void 0,status:n.status,httpStatus:n.httpStatus,duration:n.duration,errorMessage:n.errorMessage,hasReferenceImages:n.hasReferenceImages,referenceImageCount:n.referenceImageCount,resultType:n.resultType,resultCount:n.resultCount,resultUrl:n.resultUrl}}function da(n,e){if(!e)return!0;const t=n.taskType==="audio"&&(n.resultType==="lyrics"||/\/lyrics(?:\/|$)/i.test(n.endpoint||""));return e==="lyrics"?t:e==="audio"?n.taskType==="audio"&&!t:n.taskType===e}async function ha(n=1,e=20,t){let s=await Fs();t!=null&&t.taskType&&(s=s.filter(c=>da(c,t.taskType))),t!=null&&t.status&&(s=s.filter(c=>c.status===t.status));const r=s.length,o=Math.ceil(r/e),a=(n-1)*e;return{logs:s.slice(a,a+e).map(ua),total:r,page:n,pageSize:e,totalPages:o}}async function ga(n){const e=pe.find(t=>t.id===n);if(e)return e;try{const r=(await Tt()).transaction(K,"readonly").objectStore(K);return new Promise((o,a)=>{const i=r.get(n);i.onsuccess=()=>{o(i.result||null)},i.onerror=()=>{a(i.error)}})}catch(t){return console.warn("[LLMApiLogger] Failed to get log by id:",t),null}}async function fa(){pe.length=0;try{const e=(await Tt()).transaction(K,"readwrite");e.objectStore(K).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{s()},e.onerror=()=>{r(e.error)}})}catch(n){console.warn("[LLMApiLogger] Failed to clear logs from DB:",n)}}async function pa(n){if(!n||n.length===0)return 0;const e=new Set(n),t=pe.length;for(let r=pe.length-1;r>=0;r--)e.has(pe[r].id)&&pe.splice(r,1);const s=t-pe.length;try{const o=(await Tt()).transaction(K,"readwrite"),a=o.objectStore(K);for(const i of n)a.delete(i);await new Promise((i,c)=>{o.oncomplete=()=>{i()},o.onerror=()=>{c(o.error)}})}catch(r){console.warn("[LLMApiLogger] Failed to delete logs from DB:",r)}return s}function ma(n){}const Ee=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:fa,deleteLLMApiLogs:pa,getAllLLMApiLogs:Fs,getLLMApiLogById:ga,getLLMApiLogsPaginated:ha,setLLMApiLogBroadcast:ma},Symbol.toStringTag,{value:"Module"}));return T.APP_VERSION=w,T.IMAGE_CACHE_NAME=A,T.addConsoleLog=en,T.clearAllConsoleLogs=es,T.clearConsoleLogs=rs,T.clearCrashSnapshots=Ds,T.clearDebugLogs=ss,T.deleteCacheByUrl=dn,T.disableDebugMode=sn,T.enableDebugMode=nn,T.getCDNStatusReport=nt,T.getCacheStats=As,T.getCrashSnapshots=_s,T.getDebugLogs=tn,T.getDebugStatus=ns,T.getInternalFetchLogs=Wt,T.loadConsoleLogsFromDB=Jn,T.performHealthCheck=jt,T.resetCDNStatus=zt,T.saveCrashSnapshot=Ts,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"}),T})({});
55
+ </html>`,{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}const mn=15e3,Ns=3e4;function xs(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function ea(){const n=Date.now(),e=[];if(G.forEach((t,s)=>{n-t.timestamp>$r&&e.push(s)}),e.length>0&&e.forEach(t=>G.delete(t)),G.size>Jn){const t=Array.from(G.entries()).sort((o,a)=>o[1].timestamp-a[1].timestamp),s=G.size-Jn,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>G.delete(o))}}function ta(){const n=Date.now(),e=[];q.forEach((s,r)=>{n-s.timestamp>Ns&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>q.delete(s)));const t=[];we.forEach((s,r)=>{n-s.timestamp>Xn&&t.push(r)}),t.length>0&&t.forEach(s=>we.delete(s)),ea()}async function na(n){try{const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),r=t.searchParams.has("_retry"),o=t.searchParams.has("thumbnail")&&!s&&!r,a=o&&t.searchParams.get("thumbnail")||"small",i=Ne(t),c=new Request(i.toString(),{method:n.method,headers:n.headers,mode:n.mode,credentials:n.credentials}),l=i.toString();if(o){const{findThumbnailWithFallback:u,createThumbnailResponse:b}=await Promise.resolve().then(()=>j),p=await u(l,a,[n.url,c.url]);if(p){const g=await p.response.blob();return b(g)}}const h=we.get(l);if(h){if(Date.now()-h.timestamp<Xn)return h.response.clone();we.delete(l)}if(q.has(l)){const u=q.get(l);if(u){const b=Date.now()-u.timestamp;if(b>Ns)console.warn(`Service Worker [${e}]: 发现过期的 pending 请求 (${b}ms),清理并重新发起:`,l),q.delete(l);else{u.count=(u.count||1)+1,u.duplicateRequestIds=u.duplicateRequestIds||[],u.duplicateRequestIds.push(e);try{const p=await xs(u.promise,mn,"Image request timeout");return p&&p.clone?p.clone():p}catch(p){if(p.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 重复请求等待超时,清理并返回超时响应让前端直接加载`),q.delete(l),Fs(n.url,e);throw p}}}}ta();const d=sa(c,n.url,l,e,s,o?a:void 0);q.set(l,{promise:d,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),d.then(u=>{u&&u.ok&&we.set(l,{response:u.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{q.get(l)&&q.delete(l)});try{return await xs(d,mn,"Image request timeout")}catch(u){if(u.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${mn}ms),清理并返回超时响应让前端直接加载:`,n.url),q.delete(l),Fs(n.url,e);throw u}}catch(e){throw e}}function Fs(n,e){return new Response("Image request timeout - use direct load",{status:504,statusText:"Gateway Timeout",headers:{"Content-Type":"text/plain","X-SW-Timeout":"true","X-SW-Original-URL":n,"Access-Control-Allow-Origin":"*"}})}async function sa(n,e,t,s,r=!1,o){try{const a=await caches.open(A);if(!r){let g=await a.match(n);if(g||(g=await a.match(n.url)),!g&&e!==n.url&&(g=await a.match(e)),g||(g=await a.match(t)),g){const y=await g.clone().blob();if(y.size===0)console.warn(`Service Worker [${s}]: 检测到空缓存,删除并重新获取:`,e),await a.delete(n);else{if(o){const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(y,n.url,"image")}const S=g.headers.get(le);if(S){const E=Date.now(),W=g.headers.get(ye)||S,U=new Response(y,{status:g.status,statusText:g.statusText,headers:{...Object.fromEntries(g.headers.entries()),[le]:E.toString(),[ye]:W}});return n.url.startsWith("http")&&(await a.put(t,U.clone()),e!==t&&await a.delete(e)),U}else{const E=new Response(y,{status:g.status,statusText:g.statusText,headers:{...Object.fromEntries(g.headers.entries()),[le]:Date.now().toString(),[ye]:Date.now().toString()}});return n.url.startsWith("http")&&(await a.put(t,E.clone()),e!==t&&await a.delete(e)),E}}}}const i=new URL(e),c=ls(i);let l=null,h=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),Me.has(c.hostname)&&(h=!0));let d;const u=[{method:"GET",mode:"cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"},{method:"GET",cache:"no-cache"},{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"}];let b;h?b=[l]:(b=[e],l&&b.push(l));let p=null;for(let g=0;g<b.length;g++){const f=b[g],y=g>0;for(const S of u)try{let E,W=!1;for(let U=0;U<=2;U++)try{if(d=await fetch(f,S),d&&(d.status!==0||d.type==="opaque"))break}catch(re){E=re;const ke=re.message||"";if(ke.includes("CORS")||ke.includes("cross-origin")||ke.includes("Access-Control-Allow-Origin")||ke.includes("Failed to fetch")||ke.includes("NetworkError")||ke.includes("TypeError")){W=!0;break}U<2&&await new Promise(Ca=>setTimeout(Ca,Math.pow(2,U)*1e3))}if(W){const U=new URL(f).hostname;Zn(U);try{const re=await fetch(e,{mode:"no-cors",credentials:"omit",referrerPolicy:"no-referrer"});if(re.type==="opaque")return await fe(e,"cors_opaque"),re}catch(re){console.warn(`Service Worker [${s}]: no-cors 模式也失败:`,re)}return await fe(e,"cors_fetch_failed"),new Response(null,{status:200,headers:{"Content-Type":"image/png","X-SW-CORS-Bypass":"true"}})}if(d&&(d.status!==0||d.type==="opaque"))break;E&&(p=E)}catch(E){p=E;continue}if(d&&(d.status!==0||d.type==="opaque"))break;c&&c.fallbackDomain&&g===0&&!h&&(Me.add(c.hostname),io(c.hostname).catch(S=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",S)}))}if(!d||d.status===0&&d.type!=="opaque"){let g="All fetch attempts failed";return c&&c.fallbackDomain&&(h?g=`备用域名${c.fallbackDomain}也失败了`:g=`All fetch attempts failed for both ${c.hostname} and ${c.fallbackDomain} domains`),console.error(`Service Worker [${s}]: ${g}`,p),await fe(t,g),new Response("Image load failed after all attempts",{status:404,statusText:"Image Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*"}})}if(d.type==="opaque"){const g=new URL(e).hostname;return Zn(g),await fe(t,"cors_opaque"),d}if(d.ok){const f=await d.clone().blob(),y=f.size/(1024*1024),S=new Response(f,{status:200,statusText:"OK",headers:{"Content-Type":d.headers.get("Content-Type")||"image/png","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*","Cache-Control":"max-age=3153600000",[le]:Date.now().toString(),[ye]:Date.now().toString(),"sw-image-size":f.size.toString()}});try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await qo(t,f.size,f.type),await zo();const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(f,t,"image")}}catch(E){console.warn(`Service Worker: Failed to cache normal response (${y.toFixed(2)}MB, 可能超出存储限制):`,E),await fe(t,String(E))}return S}throw new Error(`HTTP ${d.status}: ${d.statusText}`)}catch(a){const i=new URL(e);return a.message.includes("SSL_PROTOCOL_ERROR")||a.message.includes("ERR_SSL_PROTOCOL_ERROR")||a.message.includes("net::ERR_CERT")||a.message.includes("ERR_INSECURE_RESPONSE")?(console.warn("Service Worker: 检测到SSL/证书错误,尝试跳过Service Worker处理"),fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit"}).catch(()=>new Response("SSL Error - Image not accessible",{status:404,statusText:"SSL Protocol Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}))):i.pathname.match(/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i)||i.searchParams.has("_t")||i.searchParams.has("cache_buster")||i.searchParams.has("timestamp")?(await fe(e,String((a==null?void 0:a.message)||a)),new Response("Image not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}})):new Response(`Network Error: ${a.message}`,{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}})}}const _t="drawnix-images-thumb",Gs=128,bn=400,ra=.8;function oa(n,e,t){const s=n/e;let r=t,o=t;return s>1?o=t/s:r=t*s,{width:Math.round(r),height:Math.round(o)}}function yn(n,e){try{let t;try{t=new URL(n)}catch{t=new URL(n,self.location.origin)}return t.searchParams.delete("thumbnail"),t.searchParams.set("_thumb",e),t.toString()}catch{const t=n.includes("?")?"&":"?";return`${n.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/,"")}${t}_thumb=${e}`}}async function Us(n,e,t=["small","large"]){try{for(const s of t)await aa(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function aa(n,e,t){try{const s=t==="large"?bn:Gs,r=yn(e,t),o=await caches.open(_t);let a=await o.match(r);if(!a){const f=new Request(r,{method:"GET"});a=await o.match(f)}if(!a)try{const f=new URL(r);a=await o.match(f.pathname)}catch{}if(a||n.size===0)return;const i=(n.type||"").toLowerCase();if(!i.startsWith("image/")&&i!=="")return;let c;try{c=await createImageBitmap(n)}catch(f){if(f instanceof Error&&f.name==="InvalidStateError")return;throw f}const{width:l,height:h}=oa(c.width,c.height,s),d=new OffscreenCanvas(l,h),u=d.getContext("2d");if(!u){console.warn("[ThumbnailUtils] Failed to get canvas context");return}try{u.drawImage(c,0,0,l,h)}finally{c.close()}const b=await d.convertToBlob({type:"image/jpeg",quality:ra}),p=()=>new Response(b,{headers:{"Content-Type":"image/jpeg","Content-Length":b.size.toString()}}),g=new Request(r,{method:"GET"});await o.put(g,p()),await o.put(r,p());try{const f=new URL(r);(f.pathname.startsWith("/__aitu_cache__/")||f.pathname.startsWith("/asset-library/"))&&await o.put(r,p())}catch{}}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Hs(n,e,t=["small","large"]){try{for(const s of t)await ia(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function ia(n,e,t){try{const s=yn(e,t),r=await caches.open(_t);let o=await r.match(s);if(!o){const h=new Request(s,{method:"GET"});o=await r.match(h)}if(!o)try{const h=new URL(s);o=await r.match(h.pathname)}catch{}if(o)return;const i=await ca(e,n,t==="large"?bn:Gs);if(!i){console.warn(`[ThumbnailUtils] Failed to generate ${t} video thumbnail from main thread`);return}const c=()=>new Response(i,{headers:{"Content-Type":"image/jpeg","Content-Length":i.size.toString()}}),l=new Request(s,{method:"GET"});await r.put(l,c()),await r.put(s,c());try{const h=new URL(s);(h.pathname.startsWith("/__aitu_cache__/")||h.pathname.startsWith("/asset-library/"))&&await r.put(s,c())}catch{}}catch(s){console.warn(`[ThumbnailUtils] ❌ Failed to generate ${t} video thumbnail:`,s)}}async function ca(n,e,t=bn){const s=D().requestVideoThumbnail;if(!s)return console.warn("[ThumbnailUtils] No connected clients for video thumbnail generation"),null;const r=await s(n,3e4,t);if(!r)return null;try{return await(await fetch(r)).blob()}catch(o){return console.warn("[ThumbnailUtils] Failed to convert thumbnail URL to blob:",o),null}}async function wn(n,e,t){try{const s=await caches.open(_t),r=yn(n,e);let o=await s.match(r);if(!o){const a=new Request(r,{method:"GET"});o=await s.match(a)}if(!o&&t)for(const a of t){const i=await s.match(a);if(i){o=i;break}}return o||null}catch(s){return console.warn("[ThumbnailUtils] Error finding thumbnail:",s),null}}async function la(n,e,t){let s=await wn(n,e,t);if(s)return{response:s,size:e};const r=e==="small"?"large":"small";return s=await wn(n,r,t),s?{response:s,size:r}:null}function ua(n){return new Response(n,{status:200,headers:{"Content-Type":"image/jpeg","Content-Length":n.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}function da(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await Us(n,e,s):await Hs(n,e,s)}catch(r){console.warn(`[ThumbnailUtils] Failed to generate ${t} thumbnail:`,r)}})()}const j=Object.freeze(Object.defineProperty({__proto__:null,IMAGE_CACHE_NAME_THUMB:_t,createThumbnailResponse:ua,findThumbnail:wn,findThumbnailWithFallback:la,generateImageThumbnail:Us,generateThumbnailAsync:da,generateVideoThumbnail:Hs},Symbol.toStringTag,{value:"Module"})),pe=[],ha="llm-api-logs",ga=4,K="logs";function Dt(){return new Promise((n,e)=>{const t=indexedDB.open(ha,ga);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result,o=s.oldVersion;let a;if(!r.objectStoreNames.contains(K))a=r.createObjectStore(K,{keyPath:"id"}),a.createIndex("timestamp","timestamp",{unique:!1}),a.createIndex("taskType","taskType",{unique:!1}),a.createIndex("status","status",{unique:!1}),a.createIndex("taskId","taskId",{unique:!1});else{const i=s.target.transaction;i&&(a=i.objectStore(K),o<4&&!a.indexNames.contains("taskId")&&a.createIndex("taskId","taskId",{unique:!1}))}}})}async function qs(){try{const s=(await Dt()).transaction(K,"readonly").objectStore(K).index("timestamp");return new Promise((r,o)=>{const a=s.getAll();a.onsuccess=()=>{const i=a.result.reverse();r(i)},a.onerror=()=>{o(a.error)}})}catch(n){return console.warn("[LLMApiLogger] Failed to get logs from DB:",n),pe}}function fa(n){return{id:n.id,timestamp:n.timestamp,endpoint:n.endpoint,model:n.model,taskType:n.taskType,taskId:n.taskId,prompt:n.prompt?n.prompt.length>200?n.prompt.substring(0,200)+"...":n.prompt:void 0,status:n.status,httpStatus:n.httpStatus,duration:n.duration,errorMessage:n.errorMessage,hasReferenceImages:n.hasReferenceImages,referenceImageCount:n.referenceImageCount,resultType:n.resultType,resultCount:n.resultCount,resultUrl:n.resultUrl}}function pa(n,e){if(!e)return!0;const t=n.taskType==="audio"&&(n.resultType==="lyrics"||/\/lyrics(?:\/|$)/i.test(n.endpoint||""));return e==="lyrics"?t:e==="audio"?n.taskType==="audio"&&!t:n.taskType===e}async function ma(n=1,e=20,t){let s=await qs();t!=null&&t.taskType&&(s=s.filter(c=>pa(c,t.taskType))),t!=null&&t.status&&(s=s.filter(c=>c.status===t.status));const r=s.length,o=Math.ceil(r/e),a=(n-1)*e;return{logs:s.slice(a,a+e).map(fa),total:r,page:n,pageSize:e,totalPages:o}}async function ba(n){const e=pe.find(t=>t.id===n);if(e)return e;try{const r=(await Dt()).transaction(K,"readonly").objectStore(K);return new Promise((o,a)=>{const i=r.get(n);i.onsuccess=()=>{o(i.result||null)},i.onerror=()=>{a(i.error)}})}catch(t){return console.warn("[LLMApiLogger] Failed to get log by id:",t),null}}async function ya(){pe.length=0;try{const e=(await Dt()).transaction(K,"readwrite");e.objectStore(K).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{s()},e.onerror=()=>{r(e.error)}})}catch(n){console.warn("[LLMApiLogger] Failed to clear logs from DB:",n)}}async function wa(n){if(!n||n.length===0)return 0;const e=new Set(n),t=pe.length;for(let r=pe.length-1;r>=0;r--)e.has(pe[r].id)&&pe.splice(r,1);const s=t-pe.length;try{const o=(await Dt()).transaction(K,"readwrite"),a=o.objectStore(K);for(const i of n)a.delete(i);await new Promise((i,c)=>{o.oncomplete=()=>{i()},o.onerror=()=>{c(o.error)}})}catch(r){console.warn("[LLMApiLogger] Failed to delete logs from DB:",r)}return s}function Sa(n){}const Te=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:ya,deleteLLMApiLogs:wa,getAllLLMApiLogs:qs,getLLMApiLogById:ba,getLLMApiLogsPaginated:ma,setLLMApiLogBroadcast:Sa},Symbol.toStringTag,{value:"Module"}));return T.APP_VERSION=w,T.IMAGE_CACHE_NAME=A,T.addConsoleLog=nn,T.clearAllConsoleLogs=rs,T.clearConsoleLogs=cs,T.clearCrashSnapshots=Ms,T.clearDebugLogs=is,T.deleteCacheByUrl=pn,T.disableDebugMode=on,T.enableDebugMode=rn,T.getCDNStatusReport=ot,T.getCacheStats=vs,T.getCrashSnapshots=Ls,T.getDebugLogs=sn,T.getDebugStatus=as,T.getInternalFetchLogs=Nt,T.loadConsoleLogsFromDB=ns,T.performHealthCheck=$t,T.resetCDNStatus=Vt,T.saveCrashSnapshot=Rs,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"}),T})({});