aitu-app 0.6.78 → 0.6.80
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/assets/CanvasAudioPlayer-CSFENxi6.js +2 -0
- package/assets/ChatDrawer-CWZQP5R5.css +1 -0
- package/assets/ChatDrawer-sVEVW11M.js +11 -0
- package/assets/ChatMessagesArea-Cnb94V8-.js +7 -0
- package/assets/ChatMessagesArea-PlF5AwzD.css +1 -0
- package/assets/DeferredAIInputBar-D99l6sBS.js +8 -0
- package/assets/DrawnixDeferredFeatures-78cIu-ev.js +2 -0
- package/assets/{KnowledgeBaseContent-DcX5Jofx.js → KnowledgeBaseContent-DZ-1fPZa.js} +10 -10
- package/assets/{MVCreator-DllHozYg.js → MVCreator-BV8KDR6E.js} +8 -8
- package/assets/ModelBenchmarkWorkbench-DL6r0Z_5.js +2 -0
- package/assets/MusicAnalyzer-D9Bpmhym.css +1 -0
- package/assets/{MusicAnalyzer-DDeT6g3c.js → MusicAnalyzer-DQtjf36o.js} +2 -2
- package/assets/{MusicAnalyzer-CHcQ5t4P.js → MusicAnalyzer-u_5sy56T.js} +1 -1
- package/assets/PromptHistoryTool-B-ktaOpK.js +2 -0
- package/assets/PromptHistoryTool-BH7hq916.css +1 -0
- package/assets/ResizableDivider-BpUFdkte.js +1 -0
- package/assets/TaskQueuePanel-BLD1r7_I.js +1 -0
- package/assets/{VideoAnalyzer-BSLz1FaI.js → VideoAnalyzer-Bjv9pyDs.js} +2 -2
- package/assets/ai-generation-preferences-service-BSpgVCHz.js +1 -0
- package/assets/arc-CnA_FoJK.js +1 -0
- package/assets/{arc-BU2KKCa_.js → arc-DDvk_-VM.js} +1 -1
- package/assets/{batch-image-generation-Bg68r_Ql.js → batch-image-generation-N-lwbjRE.js} +3 -3
- package/assets/{blockDiagram-38ab4fdb-BCGEnMME.js → blockDiagram-38ab4fdb-B2G4wjZe.js} +6 -6
- package/assets/{blockDiagram-38ab4fdb-CsZR5uC5.js → blockDiagram-38ab4fdb-DBkZWrKk.js} +1 -1
- package/assets/{browser-DpICcNby.js → browser-ZXTF4AKv.js} +1 -1
- package/assets/{c4Diagram-3d4e48cf-9fuiuFdV.js → c4Diagram-3d4e48cf-BFg-wccg.js} +1 -1
- package/assets/{c4Diagram-3d4e48cf-WM4wd_GR.js → c4Diagram-3d4e48cf-CmyNnfip.js} +1 -1
- package/assets/{canvas-insertion-CdUQF7IV.js → canvas-insertion-CKIoVZ9a.js} +1 -1
- package/assets/channel-BQh3J7kz.js +1 -0
- package/assets/channel-CPsF_uSp.js +1 -0
- package/assets/{classDiagram-70f12bd4-DcYDedz1.js → classDiagram-70f12bd4-BoP-e23u.js} +2 -2
- package/assets/{classDiagram-70f12bd4-CBVHTwQu.js → classDiagram-70f12bd4-UTHJc2XA.js} +1 -1
- package/assets/classDiagram-v2-f2320105-BeBc2H-D.js +2 -0
- package/assets/{classDiagram-v2-f2320105-jpCwaHEd.js → classDiagram-v2-f2320105-Bjwz5ljW.js} +1 -1
- package/assets/{clipper-jvd5rF5a.js → clipper-NoHaeWV4.js} +1 -1
- package/assets/clone-CA2KqVCK.js +1 -0
- package/assets/createText-2e5e7dd3-Bsu7vT-L.js +8 -0
- package/assets/{createText-2e5e7dd3-x5lOIwut.js → createText-2e5e7dd3-DrWUfa-s.js} +1 -1
- package/assets/{edges-e0da2a9e-CbrF4nbD.js → edges-e0da2a9e-B9sYOHRt.js} +1 -1
- package/assets/{edges-e0da2a9e-Ch6PBwWs.js → edges-e0da2a9e-DX4IQMED.js} +1 -1
- package/assets/{erDiagram-9861fffd-DSlNVuAZ.js → erDiagram-9861fffd-B-LfsIMf.js} +1 -1
- package/assets/{erDiagram-9861fffd-Bq07elcI.js → erDiagram-9861fffd-DPdud_LA.js} +1 -1
- package/assets/{flowDb-956e92f1-Ti5YC4Vv.js → flowDb-956e92f1-C3xKlizM.js} +1 -1
- package/assets/{flowDb-956e92f1-BqPCJlZp.js → flowDb-956e92f1-Ck5oiEta.js} +1 -1
- package/assets/{flowDiagram-66a62f08-CPDuG3rY.js → flowDiagram-66a62f08-Bkt2NoHM.js} +4 -4
- package/assets/{flowDiagram-66a62f08-D3GSABFi.js → flowDiagram-66a62f08-CJnxo6dI.js} +1 -1
- package/assets/flowDiagram-v2-96b9c2cf-MnwxRDMO.js +1 -0
- package/assets/flowDiagram-v2-96b9c2cf-U7nNPvdl.js +1 -0
- package/assets/{flowchart-elk-definition-4a651766-BH09NeLA.js → flowchart-elk-definition-4a651766-2XkrsdKI.js} +2 -2
- package/assets/{flowchart-elk-definition-4a651766-BLaLPCDV.js → flowchart-elk-definition-4a651766-ec8y1a8S.js} +1 -1
- package/assets/{ganttDiagram-c361ad54-DL9ZeaEc.js → ganttDiagram-c361ad54-1TA0mZY_.js} +3 -3
- package/assets/{ganttDiagram-c361ad54-Sp9M1KHP.js → ganttDiagram-c361ad54-D-OrVtXV.js} +3 -3
- package/assets/{gitGraphDiagram-72cf32ee-BWwmRKo-.js → gitGraphDiagram-72cf32ee-Blt3RsBD.js} +1 -1
- package/assets/{gitGraphDiagram-72cf32ee-BSf1fsDV.js → gitGraphDiagram-72cf32ee-CKf6xgO1.js} +1 -1
- package/assets/{graph-g-2U7grQ.js → graph-CUYgHJmb.js} +1 -1
- package/assets/{graph--nPw8zXQ.js → graph-WeSRtsZO.js} +1 -1
- package/assets/{index-ZrVeQUWo.js → index--MqiaN5t.js} +1 -1
- package/assets/{index-C5eu4uSl.js → index-0b_TeH8L.js} +11 -11
- package/assets/{index-3862675e-BXwbZ2pz.js → index-3862675e-C2ipEQC8.js} +1 -1
- package/assets/{index-3862675e-D6Zy95zZ.js → index-3862675e-CeX6VlsU.js} +1 -1
- package/assets/{index-CLJUfzvO.js → index-B-J0JJak.js} +1 -1
- package/assets/{index-TkfyNewx.js → index-B7Hj7g41.js} +1 -1
- package/assets/{index-eZfwJ9bV.js → index-BS_v5cOh.js} +1 -1
- package/assets/index-Btk31p7r.js +1 -0
- package/assets/{index-DH12_HTj.js → index-C-Samsu3.js} +2 -2
- package/assets/index-C-llNX01.js +1 -0
- package/assets/index-C8c9icsH.js +2 -0
- package/assets/{index-D7b5fX1d.js → index-CAn2jfNg.js} +1 -1
- package/assets/{index-Dz8sghkK.js → index-CK2zt94U.js} +1 -1
- package/assets/{index-CfgvFFx3.js → index-CP51k4n6.js} +17 -17
- package/assets/{index-DI0OV6F8.js → index-CXBhIy30.js} +1 -1
- package/assets/index-C_Mj1wbj.js +2 -0
- package/assets/{index-BwSnJN93.js → index-CbfE0MBd.js} +1 -1
- package/assets/{index-C3qD42ws.js → index-CjeDxq0c.js} +1 -1
- package/assets/{index-DqMndQiP.js → index-Ct7OFnWK.js} +1 -1
- package/assets/{index-BaCHOxhI.js → index-CxxUIkx1.js} +1 -1
- package/assets/{index-B2dttXd7.js → index-D2Kc-3MO.js} +1 -1
- package/assets/{index-Bq8mPedC.js → index-DK0XEByD.js} +1 -1
- package/assets/{index-DllL1sx1.js → index-DQcV2DYj.js} +1 -1
- package/assets/{index-BP77pG9S.js → index-DSKRBuhn.js} +73 -73
- package/assets/{index-BXzGHPXz.js → index-DXqL8NRE.js} +2 -2
- package/assets/{index-B7V7-Vxz.js → index-DcLrRIlS.js} +1 -1
- package/assets/{index-D4pIkh3S.js → index-DdA-dF0D.js} +1 -1
- package/assets/{index-QkP3EC02.js → index-DdxTnVj5.js} +1 -1
- package/assets/{index-CmyOpFTN.js → index-DmrnShhc.js} +1 -1
- package/assets/{index-Bti3m-iW.js → index-QO0uGVDP.js} +1 -1
- package/assets/{index-BPR_DyGD.js → index-aIKXDB1M.js} +1 -1
- package/assets/{index-DIiIUyb-.js → index-n6JhNACm.js} +1 -1
- package/assets/{index-BWrcsh8u.js → index-qbS_W7PW.js} +1 -1
- package/assets/index-v7iKPBEu.css +1 -0
- package/assets/{infoDiagram-f8f76790-DpFqCCNv.js → infoDiagram-f8f76790-DEWQ3NXc.js} +1 -1
- package/assets/{infoDiagram-f8f76790-G2JpJJP7.js → infoDiagram-f8f76790-u_qjHFCm.js} +3 -3
- package/assets/{journeyDiagram-49397b02-DLLTobRM.js → journeyDiagram-49397b02-C8A30CBr.js} +1 -1
- package/assets/{journeyDiagram-49397b02-BdESGMrv.js → journeyDiagram-49397b02-hQJfqZih.js} +1 -1
- package/assets/{layout-WSR0vNPO.js → layout-CFKTKeqQ.js} +1 -1
- package/assets/{layout-CVkuImk4.js → layout-DvRyabpG.js} +1 -1
- package/assets/{line-D3bnG227.js → line-C72F34Po.js} +1 -1
- package/assets/{line-DQuMJveY.js → line-W5R41tQ1.js} +1 -1
- package/assets/{linear-CciP-97N.js → linear-7FXykgHM.js} +1 -1
- package/assets/{linear-Z6vFvuwc.js → linear-CVyOPUvz.js} +1 -1
- package/assets/main-BO0HWBB1.js +42 -0
- package/assets/{main-8DNjLY6L.css → main-DAuE07rf.css} +1 -1
- package/assets/{mermaid.core-CwZQb0ud.js → mermaid.core-2VcXhn43.js} +4 -4
- package/assets/{mindmap-definition-fc14e90a-BnJ8OOTI.js → mindmap-definition-fc14e90a-CcVXKGg4.js} +1 -1
- package/assets/{mindmap-definition-fc14e90a-CxQMydCW.js → mindmap-definition-fc14e90a-DRDYXe84.js} +2 -2
- package/assets/model-benchmark-launcher-C2qBiDlM.js +1 -0
- package/assets/{photo-wall-splitter-BZ88W5Zy.js → photo-wall-splitter-CFntSOdS.js} +1 -1
- package/assets/{pieDiagram-8a3498a8-BSDdkTeu.js → pieDiagram-8a3498a8-Be9dl9pU.js} +1 -1
- package/assets/{pieDiagram-8a3498a8-D6VtAoja.js → pieDiagram-8a3498a8-DXZOJYBv.js} +5 -5
- package/assets/ppt-generation-B5fKT_by.js +48 -0
- package/assets/{quadrantDiagram-120e2f19-C8k2xuBd.js → quadrantDiagram-120e2f19-DoU7aQSp.js} +3 -3
- package/assets/{quadrantDiagram-120e2f19-BbFV0VXY.js → quadrantDiagram-120e2f19-l5K9mx26.js} +1 -1
- package/assets/{requirementDiagram-deff3bca-C3xMdzJV.js → requirementDiagram-deff3bca-DN_87Wxe.js} +1 -1
- package/assets/{requirementDiagram-deff3bca-CpjqKjYZ.js → requirementDiagram-deff3bca-DOooq7kx.js} +1 -1
- package/assets/retry-image-BmIVuAVu.js +6 -0
- package/assets/{sankeyDiagram-04a897e0-Bjvig9bW.js → sankeyDiagram-04a897e0-BB33nO6_.js} +1 -1
- package/assets/{sankeyDiagram-04a897e0-BBJJgsFv.js → sankeyDiagram-04a897e0-CCa0hwml.js} +2 -2
- package/assets/{sequenceDiagram-704730f1-PFC_9IFI.js → sequenceDiagram-704730f1-CNhXZiix.js} +1 -1
- package/assets/{sequenceDiagram-704730f1-DX1MmBN_.js → sequenceDiagram-704730f1-ZqQ1QrY-.js} +1 -1
- package/assets/settings-dialog-BFuWTeQR.js +1 -0
- package/assets/{skill-dsl-parser-syNWYxFu.js → skill-dsl-parser-b-aB3P5u.js} +1 -1
- package/assets/{stateDiagram-587899a1-Dc3mI_B_.js → stateDiagram-587899a1-BBlOIJr7.js} +1 -1
- package/assets/{stateDiagram-587899a1-SFMUVAam.js → stateDiagram-587899a1-BhomZ0AN.js} +1 -1
- package/assets/{stateDiagram-v2-d93cdb3a-P4Yt2p_j.js → stateDiagram-v2-d93cdb3a-BpJsgMa0.js} +1 -1
- package/assets/stateDiagram-v2-d93cdb3a-CuOn9du2.js +1 -0
- package/assets/{styles-6aaf32cf-C3jnr3hV.js → styles-6aaf32cf-C2WEewoA.js} +1 -1
- package/assets/{styles-6aaf32cf-b6AdP7fu.js → styles-6aaf32cf-CTtf8moq.js} +1 -1
- package/assets/{styles-9a916d00-BUiD9iBe.js → styles-9a916d00-44Xi2-39.js} +1 -1
- package/assets/{styles-9a916d00-ii0XTdIm.js → styles-9a916d00-DUU3VgNe.js} +4 -4
- package/assets/{styles-c10674c1-DbTSpy3W.js → styles-c10674c1--AhWSGg7.js} +1 -1
- package/assets/styles-c10674c1-DS-wE3tK.js +116 -0
- package/assets/{svgDrawCommon-08f97a94-D4gIV05W.js → svgDrawCommon-08f97a94-CXcvtSSy.js} +1 -1
- package/assets/{svgDrawCommon-08f97a94-BK6lD4D6.js → svgDrawCommon-08f97a94-Dyqh4V2s.js} +1 -1
- package/assets/{timeline-definition-85554ec2-Bl2y548G.js → timeline-definition-85554ec2-k788753O.js} +1 -1
- package/assets/{timeline-definition-85554ec2-CWKg_JxG.js → timeline-definition-85554ec2-sw6-UuBe.js} +1 -1
- package/assets/tool-windows-BEnZdJqF.js +2948 -0
- package/assets/{tool-windows-CUNbW1Tz.css → tool-windows-D61Le6TE.css} +1 -1
- package/assets/ttd-dialog-BJzXAZ0l.js +99 -0
- package/assets/useCharacters-DRBoWvvj.css +1 -0
- package/assets/useCharacters-gsV4K8Hn.js +2 -0
- package/assets/{useWorkflowSubmission-BizuDmuw.js → useWorkflowSubmission-XRR21P6Y.js} +10 -10
- package/assets/{video-analyze-6v3Y-rUE.js → video-analyze-CpbnpSiI.js} +1 -1
- package/assets/{video-generation-DnmTlWnm.js → video-generation-BXhS7x-a.js} +2 -2
- package/assets/video-recovery-service-6G2lkWcu.js +1 -0
- package/assets/workflow-generation-utils-CYxtSHl0.js +3 -0
- package/assets/workflow-submission-service-DygSzydV.js +4 -0
- package/assets/{xychartDiagram-e933f94c-CJX9_9WF.js → xychartDiagram-e933f94c-CvTTDwPb.js} +3 -3
- package/assets/{xychartDiagram-e933f94c-Cep8CQEH.js → xychartDiagram-e933f94c-Ga9zi9ha.js} +1 -1
- package/changelog.json +45 -0
- package/idle-prefetch-manifest.json +310 -306
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +10 -10
- package/sitemap.xml +37 -0
- package/sw-debug/app.js +269 -156
- package/sw-debug/backup-restore.js +235 -103
- package/sw-debug/crypto-helper.js +116 -120
- package/sw-debug/duplex-client.js +33 -19
- package/sw-debug/gist-management.js +938 -655
- package/sw-debug/sw-communication.js +87 -50
- package/sw.js +5 -5
- package/version.json +7 -17
- package/assets/CanvasAudioPlayer-DutgwdiU.js +0 -2
- package/assets/ChatDrawer-0jNvKIoI.css +0 -1
- package/assets/ChatDrawer-E6Fog16I.js +0 -11
- package/assets/ChatMessagesArea-Bgwiz_XP.js +0 -250
- package/assets/ChatMessagesArea-DyR_wHFQ.css +0 -1
- package/assets/DeferredAIInputBar-CPkD8Cv9.js +0 -8
- package/assets/DrawnixDeferredFeatures-Cul76-88.js +0 -2
- package/assets/ModelBenchmarkWorkbench-Dv9SNYTi.js +0 -2
- package/assets/MusicAnalyzer-DhtRGpAp.css +0 -1
- package/assets/ResizableDivider-CaG9JQbJ.js +0 -1
- package/assets/TaskQueuePanel-BNhNzGp5.js +0 -1
- package/assets/ai-generation-preferences-service-BF7QkuJp.js +0 -1
- package/assets/arc-DmGoDCEL.js +0 -1
- package/assets/channel-CZjE-WNp.js +0 -1
- package/assets/channel-SXZD6bG3.js +0 -1
- package/assets/classDiagram-v2-f2320105-CsxWGkSy.js +0 -2
- package/assets/clone-C4mvvMDb.js +0 -1
- package/assets/createText-2e5e7dd3-CkXS3l7I.js +0 -5
- package/assets/flowDiagram-v2-96b9c2cf-BCcJ-cre.js +0 -1
- package/assets/flowDiagram-v2-96b9c2cf-DCVaFEgV.js +0 -1
- package/assets/index-3eqA7Bag.js +0 -1
- package/assets/index-7Q-aiwln.js +0 -4
- package/assets/index-B1XP5g7P.css +0 -1
- package/assets/index-BHPTfCZM.js +0 -1
- package/assets/index-BqHZCcen.js +0 -2
- package/assets/index-DcZrElEK.js +0 -2
- package/assets/index-gQ7LgvSv.js +0 -12
- package/assets/main-BFEkxCOK.js +0 -56
- package/assets/model-benchmark-launcher-Ct3lYXVq.js +0 -1
- package/assets/ppt-generation-FzjP_rp0.js +0 -48
- package/assets/settings-dialog-CQM4v791.js +0 -1
- package/assets/stateDiagram-v2-d93cdb3a-DmnBjHpC.js +0 -1
- package/assets/styles-c10674c1-Bt89Yy8Q.js +0 -116
- package/assets/tool-windows-DOIu9TAD.js +0 -2975
- package/assets/ttd-dialog-DI4kQSg8.js +0 -99
- package/assets/useCharacters-Chv4Ky7x.js +0 -7
- package/assets/useCharacters-OrDbG69o.css +0 -1
- package/assets/video-recovery-service-BeRoh0s2.js +0 -1
- package/assets/workflow-generation-utils-me381Cax.js +0 -3
- package/assets/workflow-submission-service-YOpo7g37.js +0 -4
package/sw.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var sw=(function(D){"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 ae(n){return n instanceof Error?n.name||"Error":"Unknown error"}const Et="sw-task-queue",mn=3,_="tasks",$="config",x="workflows",N="chat-workflows",M="pending-tool-requests",P="pending-dom-operations",G="task-step-mappings",V="pending-canvas-operations",xs=[_,$,x,N,M,P,G,V];function Ns(){return new Promise(n=>{const e=indexedDB.open(Et);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,mn))},e.onerror=()=>{n(mn)}})}function Gs(n){const e=[];for(const t of xs)n.objectStoreNames.contains(t)||e.push(t);return e}function Fs(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(Et,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($)||n.createObjectStore($,{keyPath:"key"}),!n.objectStoreNames.contains(x)){const e=n.createObjectStore(x,{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(M)||n.createObjectStore(M,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(P)){const e=n.createObjectStore(P,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(G)||n.createObjectStore(G,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains(V)||n.createObjectStore(V,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function Us(){const n=await Ns();return new Promise((e,t)=>{const s=indexedDB.open(Et,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=Gs(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),Fs(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;bn(o)}})}class Hs{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=Us()),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 f=i.transaction(_,"readonly").objectStore(_).index("createdAt"),b=a==="desc"?"prev":"next",h=f.openCursor(null,b),p=[];let d=0,m=0;h.onerror=()=>l(h.error),h.onsuccess=S=>{const E=S.target.result;if(!E){c({tasks:p,total:m,hasMore:m>t+p.length});return}const A=E.value,j=!r||A.status===r,oe=!o||A.type===o;j&&oe&&(m++,d<t?d++:p.length<s&&p.push(A)),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($,"readonly").objectStore($).get(e);i.onsuccess=()=>{const c=i.result;if(!c){s(null);return}const{key:l,...u}=c;s(u)},i.onerror=()=>r(i.error)})}catch(t){return console.error("[SWStorage] Failed to get config:",ae(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const a=s.transaction($,"readwrite");a.objectStore($).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:",ae(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($,"readwrite");o.objectStore($).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($,"readonly").objectStore($).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(x,"readwrite").objectStore(x).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(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 workflow:",t),null}}async getAllWorkflows(){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 workflows:",e),[]}}async getWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(x,"readonly").objectStore(x).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(x,"readwrite").objectStore(x).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(M,"readwrite").objectStore(M).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(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 tool requests:",e),[]}}async getPendingToolRequestsByWorkflow(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 tool requests by workflow:",t),[]}}async getPendingToolRequest(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 tool request:",t),null}}async deletePendingToolRequest(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 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(M,"readwrite"),c=a.objectStore(M).openCursor();let l=0;c.onsuccess=()=>{const u=c.result;u&&(u.value.createdAt<s&&(u.delete(),l++),u.continue())},a.oncomplete=()=>{l>0&&console.log(`[SWStorage] Cleaned up ${l} stale pending tool requests`),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(P,"readwrite").objectStore(P).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(P,"readonly").objectStore(P).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(P,"readonly").objectStore(P).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(P,"readonly").objectStore(P).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(P,"readonly").objectStore(P).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(P,"readwrite").objectStore(P).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(G,"readwrite").objectStore(G).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(G,"readonly").objectStore(G).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(G,"readonly").objectStore(G).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(G,"readonly").objectStore(G).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(G,"readwrite").objectStore(G).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(V,"readwrite").objectStore(V).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(V,"readonly").objectStore(V).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(V,"readonly").objectStore(V).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(V,"readwrite").objectStore(V).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 f=t.transaction(_,"readonly").objectStore(_).index("createdAt"),b=[],h=f.openCursor(null,"next");h.onsuccess=()=>{const p=h.result;if(!p){c(b);return}const d=p.value;d.archived||b.push(d),p.continue()},h.onerror=()=>l(h.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 u=t.transaction(_,"readwrite"),g=u.objectStore(_);for(const f of a)f.archived=!0,f.updatedAt=i,g.put(f);u.oncomplete=()=>{console.log(`[SWStorage] Archived ${a.length} old tasks`),c(a.length)},u.onerror=()=>l(u.error)})}catch(t){return console.error("[SWStorage] Failed to archive old tasks:",t),0}}}const wn=new Hs,qs=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function Tt(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=>Tt(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();qs.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=Tt(s)}return e}return n}let Xe=!1;const js=500,ie=[];let Dt=0;function yn(){return Xe}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"],We=new Map;function Cn(n){const e=Xe;Xe=n,!n&&e&&(ie.length=0,We.clear(),Dt=0)}function _t(){return Xe}function zs(n){if(!yn()||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 $s(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 Rt(n,e,t,s,r){if(r||!zs(n))return"";const o=$s(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++Dt}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:En(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(Vs(i),Xs(n)){const c=Ys(e);c&&We.set(c,{entry:i,startTime:Date.now()})}return a}function Vs(n){ie.unshift(n),ie.length>js&&ie.pop()}function At(n,e,t,s){if(!yn())return"";const r=We.get(n);if(r){r.entry.response=En(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return We.delete(n),o}return""}function Ye(){return[...ie]}function Ks(){ie.length=0,We.clear(),Dt=0}function Xs(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 Ys(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 Tt(e)}catch{return"[Non-serializable data]"}}function Qs(){const n={total:ie.length,sent:0,received:0,byType:{}};for(const e of ie)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const Lt=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:Ks,getAllLogs:Ye,getLogStats:Qs,isPostMessageLoggerDebugMode:_t,logReceivedMessage:Rt,setPostMessageLoggerDebugMode:Cn,updateRequestWithResponse:At},Symbol.toStringTag,{value:"Module"}));function Js(){return typeof window<"u"?window:typeof self<"u"?self:{}}function Zs(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 er="postmessage-duplex",tr="1.2.0",Qe=Js();var Y,ce;Qe.__POSTMESSAGE_DUPLEX__||(Qe.__POSTMESSAGE_DUPLEX__={}),Qe.__POSTMESSAGE_DUPLEX__.version=tr,Qe.__POSTMESSAGE_DUPLEX__.name=er,(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"})(Y||(Y={})),(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"})(ce||(ce={}));class le 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,le)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class nr{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 sr{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 rr{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 Dn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const Z=n=>({valid:0,error:n});function or(n){if(!Dn(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(Y).includes(a)?"data"in e&&e.data!==void 0&&!Dn(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 Je(n){return"ret"in n&&typeof n.ret=="number"}function ar(n){return n.msg==="ready"}function ir(n){return n._broadcast==1&&typeof n.cmdname=="string"}function cr(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const vt=[],ee=[];function _n(n){ee.length>=200&&ee.shift(),ee.push(n)}function Rn(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 lr extends rr{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 nr,this.rateLimiter=new sr((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,vt.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{_n({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?Rn(i,"ok"):_n({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{Rn(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=cr(e);if(t>this.maxMessageSize){const s=new le(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ce.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):Je(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=or(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:Je(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(!ir(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:Y.Success,data:o})}catch(o){const a=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:Y.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(!ar(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}),Je(e)||this.sendMessage({requestId:t,ret:Y.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!Je(e)&&(this.log("warn","No registered handler for:",s||t),this.sendMessage({requestId:t,ret:Y.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 le("Cannot publish: channel has been destroyed",ce.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:Y.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=vt.findIndex(r=>r.deref()===t);s!==-1&&vt.splice(s,1)})(this);const e=new le("Channel has been destroyed",ce.ConnectionDestroyed);for(const[t,s]of this.callbackMap)try{s.reject({ret:Y.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 Q{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 Q.instance||(Q.instance=new Q),Q.instance}static resetInstance(){Q.instance&&(Q.instance.shutdown(),Q.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(u){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",i.id,u)}}return a}catch(o){return console.error("[ServiceWorkerHub] broadcastToType error:",o),0}}}Object.defineProperty(Q,"instance",{enumerable:1,configurable:1,writable:1,value:null});class w extends lr{static enableGlobalRouting(e){w.useGlobalRouting=1,w.unknownClientCallback=e??null,w.globalListenerSetup||(self.addEventListener("message",w.globalMessageHandler),w.globalListenerSetup=1)}static disableGlobalRouting(){w.useGlobalRouting=0,w.globalListenerSetup&&(self.removeEventListener("message",w.globalMessageHandler),w.globalListenerSetup=0)}static setupHub(e={}){if(w.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");w.hubOptions=e,w.hubInitialized=1,Q.getInstance().setup(e,s=>w.createFromWorker(s)),w.enableGlobalRouting((s,r)=>{const o=w.createFromWorker(s);w.setupChannelHandlers(o,s),o.handleMessage(r)}),w.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(w.cleanupIntervalId=setInterval(()=>w.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){w.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 w.clientMeta.set(t,s),(o=(r=w.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:w.clientMeta.size}}),w.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:w.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of w.globalSubscribeMap)e.subscribe(s,async o=>{const a=w.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 w.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:w.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 w.channelsByClientId)if(!r.has(o)){const a=w.channelsByClientId.get(o);a&&a.destroy(),w.clientMeta.delete(o),(t=(e=w.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!w.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=w.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(!w.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=w.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=w.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(u){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",i.id,u)}}return a}catch(o){return console.error("[ServiceWorkerChannel] broadcastToType error:",o),0}}static getClientInfo(e){return w.clientMeta.get(e)}static getAllClients(){return new Map(w.clientMeta)}static getClientsByType(e){const t=[];for(const s of w.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.`),w.globalSubscribeMap.set(e,t);for(const[s,r]of w.channelsByClientId)r.subscribe(e,async o=>{const a=w.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:a})})}static unsubscribeGlobal(e){w.globalSubscribeMap.delete(e);for(const t of w.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&w.useGlobalRouting&&w.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&w.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return w.channelsByClientId.get(e)}static hasChannel(e){return w.channelsByClientId.has(e)}static getChannelCount(){return w.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(w.useGlobalRouting)return void(w.globalListenerSetup||(self.addEventListener("message",w.globalMessageHandler),w.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(w.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=Zs(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===Y.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 le("Heartbeat detection failed",ce.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 le("All reconnection attempts failed",ce.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 le("Handshake timeout",ce.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 w(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 w(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 w.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(w,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(w,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(w,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(w,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(w,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(w,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(w,"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=w.channelsByClientId.get(t);s?s.handleMessage(n):w.unknownClientCallback&&w.unknownClientCallback(t,n)}});function ur(n,e,t){return Promise.race([n,new Promise(s=>setTimeout(()=>s(t),e))])}const T={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_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"},_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(),w.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{const e=await wn.cleanupStalePendingToolRequests();e>0&&console.log(`[ChannelManager] Cleaned up ${e} stale pending tool requests`)}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:w.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=Ye().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=_t()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=Rt(`RPC:${e}`,{params:o,requestId:i},t);this.broadcastPostMessageLog(u)}try{const u=await s(o);try{JSON.stringify(u)}catch(g){throw console.error(`[SW wrapRpcHandler] ${e} result serialization failed:`,g),new Error(`Result serialization failed: ${g}`)}if(c&&i){const g=At(i,{result:u},Date.now()-a);g&&this.broadcastPostMessageLog(g)}return u}catch(u){if(console.error(`[SW wrapRpcHandler] ${e} error:`,u),c&&i){const g=At(i,null,Date.now()-a,String(u));g&&this.broadcastPostMessageLog(g)}throw u}}}createSubscribeMap(e){return{[T.THUMBNAIL_GENERATE]:this.wrapRpcHandler(T.THUMBNAIL_GENERATE,e,t=>this.handleThumbnailGenerate(t)),[T.CRASH_SNAPSHOT]:async t=>{const s=this.unwrapRpcData(t);return this.handleCrashSnapshot(s)},[T.CRASH_HEARTBEAT]:async t=>{const s=this.unwrapRpcData(t);return this.handleHeartbeat(s)},[T.CONSOLE_REPORT]:async t=>{const s=this.unwrapRpcData(t);return this.handleConsoleReport(s)},[T.DEBUG_GET_STATUS]:async()=>this.handleDebugGetStatus(),[T.DEBUG_ENABLE]:async()=>this.handleDebugEnable(),[T.DEBUG_DISABLE]:async()=>this.handleDebugDisable(),[T.DEBUG_GET_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLogs(s)},[T.DEBUG_CLEAR_LOGS]:async()=>this.handleDebugClearLogs(),[T.DEBUG_GET_CONSOLE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetConsoleLogs(s)},[T.DEBUG_CLEAR_CONSOLE_LOGS]:async()=>this.handleDebugClearConsoleLogs(),[T.DEBUG_GET_POSTMESSAGE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetPostMessageLogs(s)},[T.DEBUG_CLEAR_POSTMESSAGE_LOGS]:async()=>this.handleDebugClearPostMessageLogs(),[T.DEBUG_GET_CRASH_SNAPSHOTS]:async()=>this.handleDebugGetCrashSnapshots(),[T.DEBUG_CLEAR_CRASH_SNAPSHOTS]:async()=>this.handleDebugClearCrashSnapshots(),[T.DEBUG_GET_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogs(s)},[T.DEBUG_GET_LLM_API_LOG_BY_ID]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogById(s==null?void 0:s.logId)},[T.DEBUG_CLEAR_LLM_API_LOGS]:async()=>this.handleDebugClearLLMApiLogs(),[T.DEBUG_DELETE_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugDeleteLLMApiLogs(s)},[T.DEBUG_GET_CACHE_ENTRIES]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetCacheEntries(s)},[T.DEBUG_GET_CACHE_STATS]:async()=>this.handleDebugGetCacheStats(),[T.DEBUG_EXPORT_LOGS]:async()=>this.handleDebugExportLogs(),[T.CDN_GET_STATUS]:async()=>this.handleCDNGetStatus(),[T.CDN_RESET_STATUS]:async()=>this.handleCDNResetStatus(),[T.CDN_HEALTH_CHECK]:async()=>this.handleCDNHealthCheck(),[T.UPGRADE_GET_STATUS]:async()=>this.handleUpgradeGetStatus(),[T.UPGRADE_FORCE]:async()=>this.handleUpgradeForce(),[T.CACHE_DELETE]:async t=>{const s=this.unwrapRpcData(t);return this.handleCacheDelete(s)},[T.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(()=>q),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){try{const{saveCrashSnapshot:t}=await Promise.resolve().then(()=>R);return await t(e.snapshot),{success:!0}}catch(t){return console.error("[SWChannelManager] Crash snapshot save failed:",t),{success:!1,error:t.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){try{const{addConsoleLog:t}=await Promise.resolve().then(()=>R),s=e.logArgs??[],o=(Array.isArray(s)?s.map(a=>this.serializeLogArg(a)):[this.serializeLogArg(s)]).join(" ");return t({logLevel:e.logLevel,logMessage:o||"-"}),{success:!0}}catch(t){return{success:!1,error:t.message}}}async handleDebugGetStatus(){try{const{getDebugStatus:e,getCacheStats:t}=await Promise.resolve().then(()=>R),s=e(),r=await t();return{...s,enabled:s.debugModeEnabled,cacheStats:r}}catch{return{debugModeEnabled:!1}}}async handleDebugEnable(){try{const{enableDebugMode:e,getDebugStatus:t}=await Promise.resolve().then(()=>R);await e();const s=t();return this.sendDebugStatusChanged(!0),{success:!0,status:s}}catch{return{success:!1}}}async handleDebugDisable(){try{const{disableDebugMode:e,getDebugStatus:t}=await Promise.resolve().then(()=>R);await e();const s=t();return this.sendDebugStatusChanged(!1),{success:!0,status:s}}catch{return{success:!1}}}async handleDebugGetLogs(e){try{const{getDebugLogs:t,getInternalFetchLogs:s}=await Promise.resolve().then(()=>R),{limit:r=100,offset:o=0,filter:a}=e||{},i=s().map(f=>({...f,type:"fetch"})),c=t(),l=new Map;for(const f of c)l.set(f.id,f);for(const f of i)l.set(f.id,f);let u=Array.from(l.values()).sort((f,b)=>b.timestamp-f.timestamp);return a&&(a.type&&(u=u.filter(f=>f.type===a.type)),a.status&&(u=u.filter(f=>f.status===a.status))),{logs:u.slice(o,o+r),total:u.length,offset:o,limit:r}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||100}}}async handleDebugClearLogs(){try{const{clearDebugLogs:e}=await Promise.resolve().then(()=>R);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){try{const{loadConsoleLogsFromDB:t}=await Promise.resolve().then(()=>R),{limit:s=500,offset:r=0,filter:o}=e||{};let a=await t();if(o&&(o.logLevel&&(a=a.filter(c=>c.logLevel===o.logLevel)),o.search)){const c=o.search.toLowerCase();a=a.filter(l=>{var u,g;return((u=l.logMessage)==null?void 0:u.toLowerCase().includes(c))||((g=l.logStack)==null?void 0:g.toLowerCase().includes(c))})}return{logs:a.slice(r,r+s),total:a.length,offset:r,limit:s}}catch(t){return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||500,error:String(t)}}}async handleDebugClearConsoleLogs(){try{const{clearConsoleLogs:e,clearAllConsoleLogs:t}=await Promise.resolve().then(()=>R);return e(),await t(),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>Lt),{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(u=>{var g;return(g=u.messageType)==null?void 0:g.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(()=>Lt);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){try{const{getCrashSnapshots:e}=await Promise.resolve().then(()=>R),t=await e();return{snapshots:t,total:t.length}}catch(e){return{snapshots:[],total:0,error:String(e)}}}async handleDebugClearCrashSnapshots(){try{const{clearCrashSnapshots:e}=await Promise.resolve().then(()=>R);return await 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(()=>De);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(()=>De);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(()=>De);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(()=>De);return{success:!0,deletedCount:await t(e.logIds)}}catch{return{success:!1,deletedCount:0}}}async handleDebugGetCacheEntries(e){try{const{IMAGE_CACHE_NAME:t}=await Promise.resolve().then(()=>R),{cacheName:s=t,limit:r=50,offset:o=0}=e||{},a=await caches.open(s),i=await a.keys(),c=[];for(let l=o;l<Math.min(o+r,i.length);l++){const u=i[l],g=await a.match(u);if(g){const f=g.headers.get("sw-cache-date"),b=g.headers.get("sw-cache-created-at")||f,h=g.headers.get("sw-image-size")||g.headers.get("content-length");c.push({url:u.url,cacheDate:f?parseInt(f):void 0,cacheCreatedAt:b?parseInt(b):void 0,size:h?parseInt(h):void 0})}}return{cacheName:s,entries:c,total:i.length,offset:o,limit:r}}catch(t){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(t)}}}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 u=await a.match(l);if(u){const g=u.headers.get("content-length");g&&(c+=parseInt(g))}}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(){try{const{getDebugStatus:e,getDebugLogs:t,loadConsoleLogsFromDB:s,APP_VERSION:r}=await Promise.resolve().then(()=>R),{getAllLogs:o}=await Promise.resolve().then(()=>Lt),a=await s(),i=o(),c=t();return{exportTime:new Date().toISOString(),swVersion:r,status:e(),fetchLogs:c,consoleLogs:a,postmessageLogs:i}}catch{return{exportTime:new Date().toISOString(),swVersion:"unknown",status:{},fetchLogs:[],consoleLogs:[],postmessageLogs:[]}}}async handleCDNGetStatus(){try{const{getCDNStatusReport:e}=await Promise.resolve().then(()=>R);return{status:e()}}catch{return{status:{}}}}async handleCDNResetStatus(){try{const{resetCDNStatus:e}=await Promise.resolve().then(()=>R);return e(),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){try{const{performHealthCheck:e,APP_VERSION:t}=await Promise.resolve().then(()=>R),s=await e(t);return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){try{const{APP_VERSION:e}=await Promise.resolve().then(()=>R);return{version:e}}catch{return{version:"unknown"}}}async handleUpgradeForce(){try{self.skipWaiting();const{APP_VERSION:t}=await Promise.resolve().then(()=>R);return this.sendSWUpdated(t),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){try{const{deleteCacheByUrl:t}=await Promise.resolve().then(()=>R);return await t(e.url),this.sendCacheDeleted(e.url),{success:!0}}catch(t){return{success:!1,error:String(t)}}}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})}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 ur(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 Ze=_e,et=null;function An(n){return et||(et=Ze.getInstance(n)),et}function O(){return et}const dr=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:T,SWChannelManager:Ze,SW_EVENTS:F,getChannelManager:O,initChannelManager:An},Symbol.toStringTag,{value:"Module"}));function tt(n){Cn(n)}const hr=[];let Ln=!1;function Be(n){Ln=n}function Mt(){return Ln}function Pt(){return[...hr]}const gr=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:Pt,isDebugFetchEnabled:Mt,setDebugFetchEnabled:Be},Symbol.toStringTag,{value:"Module"})),fr=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),W={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"},pr={jsdelivr:{baseTimeout:60*1e3,maxTimeout:300*1e3},unpkg:{baseTimeout:600*1e3,maxTimeout:3600*1e3}},nt=[{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,It=!1,st=null;function vn(n=!1){n&&be.clear(),nt.forEach(e=>{be.has(e.name)||be.set(e.name,{name:e.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}vn();function mr(n){return n==="jsdelivr"||n==="unpkg"||n==="local"}function Mn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!mr(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 Pn(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=W.preferenceCacheExpiry}async function br(){if(typeof caches>"u")return null;try{const e=await(await caches.open(W.preferenceCacheName)).match(W.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 kt(){It||(st||(st=(async()=>{te=await br(),It=!0,st=null})()),await st)}async function In(n){if(te=Mn(n),It=!0,!(typeof caches>"u"))try{const e=await caches.open(W.preferenceCacheName);if(!te){await e.delete(W.preferenceCacheKey);return}await e.put(W.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 Ot(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 ue(n,e){const t=be.get(n);if(t)if(t.failCount++,t.lastCheckTime=Date.now(),t.lastFailureReason=e,t.failCount>=W.failThreshold){t.isHealthy=!1;const s=On(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 kn(n,e){const t=pr[n]??{baseTimeout:W.degradeTimeout,maxTimeout:W.degradeTimeout},r=2**Math.max(0,e-W.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function On(n){const e=kn(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function Wt(n,e={}){const t=be.get(n);if(!t)return!1;if(t.isHealthy)return!0;if(e.ignoreCooldown)return console.log(`[CDN Fallback] Ignoring cooldown for ${n}, probing CDN directly`),!0;const s=Date.now(),r=kn(n,t.failCount);return s-t.lastCheckTime>r?(console.log(`[CDN Fallback] Trying to recover ${n} after ${r}ms cooldown...`),!0):!1}function wr(n,e={}){const t=te;return!t||!Pn(t,n)||t.cdn==="local"?null:Wt(t.cdn,e)?t.cdn:null}function Wn(n,e={}){const t=n?wr(n,e):null;return nt.filter(s=>s.enabled&&Wt(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 Bn(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 xn(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function yr(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}`:n.name==="unpkg"?`https://unpkg.com/${r.replace(/^\/npm\//,"")}`:null:null}function Bt(n,e,t){const s=yr(n,t);if(s)return s;const r=Bn(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function xt(n,e=W.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 Nt(n,e){const t=Bn(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function Nn(n,e,t){try{const s=Nt(e,n);console.log(`[CDN Fallback] Trying local server: ${s}`);const r=await xt(s,t);return r.ok?(console.log("[CDN Fallback] Success from local server"),{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 Gn(n,e,t,s){for(const r of n){const o=Bt(r,e,t);try{console.log(`[CDN Fallback] Trying ${r.name}: ${o}`);const a=await xt(o,s);if(!a.ok){ue(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await Sr(a,r.name))continue;return Ot(r.name),console.log(`[CDN Fallback] Success from ${r.name}`),{response:a,source:r.name,targetUrl:o}}catch(a){const i=a instanceof Error&&a.name==="AbortError"?"timeout":"network-error";ue(r.name,i),console.warn(`[CDN Fallback] ${r.name} failed:`,a)}}return null}async function Sr(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 ue(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 ue(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 u=new TextDecoder().decode(l.slice(0,200)),g=u.includes("<!DOCTYPE")||u.includes("<html")||u.includes("<HTML")||u.includes("Not Found")||u.includes("404");if(o&&g)return ue(e,"html-error-page"),console.warn(`[CDN Fallback] ${e} returned HTML instead of ${t}`),!1}}}catch{}return!0}async function Gt(n,e,t,s={}){if(fr)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;await kt();const{preferLocal:r=!1,localTimeout:o=W.localFetchTimeout,requestKind:a="interactive-runtime"}=s,i=a==="background-prefetch",c=s.cdnTimeout??(a==="background-prefetch"?W.backgroundFetchTimeout:W.fetchTimeout);if(r){const f=await Nn(n,t,o);if(f)return{...f,targetUrl:Nt(t,n)}}const l=Wn(e,{ignoreCooldown:i}),u=await Gn(l,e,n,c);if(u)return u;if(!r){const f=await Nn(n,t,o);if(f)return{...f,targetUrl:Nt(t,n)}}const g=nt.filter(f=>f.enabled&&!l.some(b=>b.name===f.name));if(g.length>0){console.warn(`[CDN Fallback] Local origin failed, forcing CDN recovery probe for: ${n}`);const f=await Gn(g,e,n,c);if(f)return f}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function Ft(n){await kt();const e=new Map;for(const t of nt){if(!t.enabled)continue;const s=Bt(t,n,t.healthCheckPath);try{const r=await xt(s,5e3),o=r.ok;e.set(t.name,o),o?Ot(t.name):ue(t.name,`status:${r.status}`)}catch{e.set(t.name,!1),ue(t.name,"health-check-failed")}}return e}function rt(){const n=Pn(te)?te==null?void 0:te.cdn:null;return Array.from(be.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,...On(t)}))}function Ut(){vn(!0),console.log("[CDN Fallback] All CDN status reset")}const Cr=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:Bt,ensureCDNPreferenceLoaded:kt,extractVersionFromCDNPath:xn,fetchFromCDNWithFallback:Gt,getAvailableCDNs:Wn,getCDNStatusReport:rt,isCDNAvailable:Wt,markCDNFailure:ue,markCDNSuccess:Ot,performHealthCheck:Ft,resetCDNStatus:Ut,setCDNPreference:In},Symbol.toStringTag,{value:"Module"}));function Ht(n){return n==="/"||n==="/index.html"}const Er=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"];function Tr(n,e){return Ht(e)?!0:n==="navigate"&&!e.endsWith(".html")}function Dr(n){return Ht(n)}function Fn(n){return Ht(n)?!0:Er.some(e=>n.endsWith(e))}function _r(n){return!Fn(n)}const U=self;An(U).setDebugClientCountChangedCallback(Hr);const ne={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function ot(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 Rr(){console.log=(...n)=>{ne.log(...n),Mt()&&!ot(n)&&at("log",n)},console.info=(...n)=>{ne.info(...n),Mt()&&!ot(n)&&at("info",n)},console.warn=(...n)=>{ne.warn(...n),ot(n)||at("warn",n)},console.error=(...n)=>{ne.error(...n),ot(n)||at("error",n)}}function Ar(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 at(n,e){try{const{message:t,stack:s}=Ar(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof qt=="function"&&qt({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){ne.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let qt=null;Rr(),Promise.resolve().then(()=>De).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=O();t&&t.sendDebugLLMLog(e)})});const C="0.6.78",it=new URL("./",self.location.href),jt=it.pathname,zt=`drawnix-v${C}`,L="drawnix-images",Re=`drawnix-static-v${C}`,ct="drawnix-fonts",se="sw-cache-date",we="sw-cache-created-at",$t="x-sw-source",Vt="x-sw-revision",Kt="x-sw-app-version",Un="x-sw-fetch-target",Lr="ServiceWorkerDB",vr=2,Ae="failedDomains",Le="versionState",Hn="app-version-state",qn="/__aitu_cache__/",jn="/__aitu_generated__/audio/",Mr="/asset-library/",xe=location.hostname==="localhost"||location.hostname==="127.0.0.1";function B(n){return new URL(n.replace(/^\//,""),it)}function ve(n){return jt!=="/"&&n.startsWith(jt)?`/${n.slice(jt.length)}`:n}const Pr=[{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"}],Ir=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,kr=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Xt=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,Or=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 Yt(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)Or.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const z=new Map,ye=new Map,zn=30*1e3,Ne=new Map,H=new Map,Wr=300*1e3,$n=10,Me=new Set,Pe=new Set,Br=3600*1e3,Qt=new Map;function Vn(n){Pe.add(n),Qt.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function xr(n){if(!Pe.has(n))return!1;const e=Qt.get(n);return e&&Date.now()-e>Br?(Pe.delete(n),Qt.delete(n),!1):!0}const J=[],Kn=7,K=[],Nr=500;let I=!1;function k(n){if(!I)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return K.unshift(t),K.length>Nr&&K.pop(),Xn(t),e}function v(n,e){if(!I||!n)return;const t=K.find(s=>s.id===n);t&&(Object.assign(t,e),Xn(t))}function Xn(n){const e=O();e&&e.sendDebugLog(n)}function lt(){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 Gr(n){try{const e=await lt(),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 Yn(){try{await Qn();const n=await lt(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-Kn*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 u=l.value;u.timestamp>=r&&c.push(u),l.continue()}else n.close(),o(c)},i.onerror=()=>{n.close(),a(i.error)}})}catch(n){return console.warn("Service Worker: 无法加载控制台日志:",n),[]}}async function Qn(){try{const n=await lt(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-Kn*24*60*60*1e3,o=IDBKeyRange.upperBound(r);return new Promise((a,i)=>{const c=s.openCursor(o);let l=0;c.onsuccess=()=>{const u=c.result;u?(u.delete(),l++,u.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 Jn(){try{const n=await lt(),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 Zn=500;function Jt(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};Gr(r),J.unshift(r),J.length>Zn&&(J.length=Zn),I&&Fr(r)}qt=Jt;function Fr(n){const e=O();e&&e.sendConsoleLog(n)}function Ur(){let n=0;return H.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function es(){return{version:C,cacheNames:[zt,L,Re,ct],pendingImageRequests:z.size,pendingVideoRequests:Ne.size,videoBlobCacheSize:H.size,videoBlobCacheTotalBytes:Ur(),completedImageRequestsSize:ye.size,failedDomainsCount:Me.size,failedDomains:Array.from(Me),corsFailedDomainsCount:Pe.size,corsFailedDomains:Array.from(Pe),debugLogsCount:K.length,consoleLogsCount:J.length,debugModeEnabled:I,memoryStats:{pendingRequestsMapSize:z.size,completedRequestsMapSize:ye.size,videoBlobCacheMapSize:H.size,failedDomainsSetSize:Me.size,corsFailedDomainsSetSize:Pe.size,debugLogsArraySize:K.length,consoleLogsArraySize:J.length}}}function Zt(){return K}function ts(){K.length=0}function ns(){J.length=0}function en(){I||(I=!0,Be(!0),tt(!0),ne.log("Service Worker: Debug mode enabled (debug page connected)"))}function tn(){I&&(I=!1,Be(!1),tt(!1),J.length=0,K.length=0,ne.log("Service Worker: Debug mode disabled (no debug pages)"))}function Hr(n){n>0?en():tn()}function ss(n){for(const e of Pr)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function qr(n,e){return Ir.test(n.pathname)||e.destination==="image"||ss(n)!==null}function jr(n,e){return kr.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function zr(n,e){return Xt.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function $r(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 Vr(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function rs(n){return`drawnix-static-v${n}`}function os(){return{committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function as(n){const e=n||{},t=typeof e.committedVersion=="string"&&e.committedVersion?e.committedVersion:C,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 ut(){return new Promise((n,e)=>{const t=indexedDB.open(Lr,vr);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(Le)||r.createObjectStore(Le,{keyPath:"key"})}})}async function Ge(){try{const n=await ut();return await new Promise((e,t)=>{const o=n.transaction([Le],"readonly").objectStore(Le).get(Hn);o.onerror=()=>t(o.error),o.onsuccess=()=>{const a=o.result;e(as((a==null?void 0:a.state)||os()))}})}catch(n){return console.warn("Service Worker: 无法读取版本状态:",n),os()}}async function Kr(n){const e=as(n);try{const t=await ut();await new Promise((s,r)=>{const o=t.transaction([Le],"readwrite");o.objectStore(Le).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 Ge(),t=typeof n=="function"?n(e):n;return Kr({...e,...t,updatedAt:Date.now()})}async function de(n){const e=await Ge(),t={type:"SW_VERSION_STATE",...e,swVersion:C};if(n)return n.postMessage(t),e;const s=await U.clients.matchAll({type:"window",includeUncontrolled:!0});for(const r of s)r.postMessage(t);return e}async function Xr(){try{const n=await ut();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 Yr(n){try{const e=await ut();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 Qr(n){if(!n){await Se({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();return}await Se(t=>({committedVersion:t.committedVersion||C,pendingVersion:C,pendingReadyAt:Date.now(),upgradeState:"ready"}));const e=O();e&&e.sendSWNewVersionReady(C),await de()}async function Jr(n){try{const e=await n.keys();if(e.length<=10)return;const t=[];for(const a of e)try{const i=await n.match(a);if(i){const c=i.headers.get(se),l=i.headers.get("sw-image-size");t.push({request:a,cacheDate:c?parseInt(c):0,imageSize:l?parseInt(l):0})}}catch(i){console.warn("Service Worker: Error reading cache entry:",i)}t.sort((a,i)=>a.cacheDate-i.cacheDate);const s=Math.max(1,Math.floor(t.length*.25));let r=0,o=0;for(let a=0;a<s&&a<t.length;a++)try{await n.delete(t[a].request),r++,o+=t[a].imageSize}catch(i){console.warn("Service Worker: Error deleting cache entry:",i)}}catch(e){console.warn("Service Worker: Cache cleanup failed:",e)}}const is=2,nn=1500,sn=2500,Zr=8e3,eo=5e3,to=6e4,Ce=5e3,no=600*1e3,so=["offline-static-assets"],ro="disabled-in-development";let Fe=0,cs=0;const Ue=new Set,He=new Set,qe=new Set,dt=new Map;let ls=Promise.resolve(),je=null,ze=0,he=!1,ht=!1;function y(n,e){if(e===void 0){console.info(`[SWDebug] ${n}`);return}console.info(`[SWDebug] ${n}`,e)}function us(){return rt().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 ds(n,e,t){console.warn("[SW Static 503]",{stage:n,requestUrl:e.url,destination:e.destination,mode:e.mode,unavailableCDNs:us(),...t})}let rn={phase:"idle",percent:0,completed:0,total:0,failed:0,version:C,updatedAt:Date.now()};async function hs(n){const e={type:"SW_BOOT_PROGRESS",...rn};if(n){n.postMessage(e);return}const t=await U.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e)}function Ee(n,e){rn={...rn,...n,version:C,updatedAt:Date.now()},hs(e)}async function oo(){try{const n=await fetch(B("precache-manifest.json").href,{cache:"reload"});if(!n.ok)return y("loadPrecacheManifest: response not ok",{status:n.status,statusText:n.statusText}),null;const e=await n.json();return y("loadPrecacheManifest: loaded",{version:e.version,fileCount:e.files.length}),e.version&&e.version!==C?(y("loadPrecacheManifest: version mismatch",{manifestVersion:e.version,workerVersion:C}),null):e.files}catch(n){return y("loadPrecacheManifest: failed",{error:ae(n)}),null}}let Ie=null,Te=0,ge=null;function $e(){return xe}async function ao(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 io(){if($e())return y("loadIdlePrefetchManifest: skipped in development mode"),null;const n=B("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 ao(e.clone());return y("loadIdlePrefetchManifest: response not ok",{manifestUrl:n,status:e.status,statusText:e.statusText,contentType:t,preview:a}),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 y("loadIdlePrefetchManifest: html fallback detected",{manifestUrl:n,status:e.status,contentType:t,preview:r}),null;let o;try{o=JSON.parse(s)}catch(a){return y("loadIdlePrefetchManifest: invalid json",{manifestUrl:n,contentType:t,error:ae(a),preview:r}),null}return!o||typeof o!="object"||!o.groups?(y("loadIdlePrefetchManifest: invalid manifest shape",{manifestUrl:n,contentType:t,preview:r}),null):o.version&&o.version!==C?(y("loadIdlePrefetchManifest: version mismatch",{manifestUrl:n,manifestVersion:o.version,workerVersion:C}),null):(y("loadIdlePrefetchManifest: loaded",{manifestUrl:n,version:o.version,defaults:o.defaults||[],groupEntryCounts:Object.fromEntries(Object.entries(o.groups).map(([a,i])=>[a,i.length]))}),o)}catch(e){return y("loadIdlePrefetchManifest: failed",{manifestUrl:n,error:ae(e)}),null}}async function gt(){if($e())return Te=0,ge=ro,Ie=null,null;const n=Date.now();if(!Ie){if(Te>0&&n-Te<Ce){const e=Ce-(n-Te);return y("getIdlePrefetchManifest: retry cooldown active",{retryAfterMs:e,lastFailureReason:ge}),null}Ie=io().then(e=>e?(Te=0,ge=null,e):(Te=Date.now(),ge="manifest-missing-or-invalid",Ie=null,null)).catch(e=>{throw Te=Date.now(),ge=ae(e),Ie=null,e})}return Ie}async function on(n){const e={type:"SW_IDLE_PREFETCH_STATUS",completedGroups:Array.from(qe),version:C,updatedAt:Date.now()};if(n){y("broadcast idle prefetch status to target client",{clientId:n.id,completedGroups:e.completedGroups}),n.postMessage(e);return}const t=await U.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e);y("broadcast idle prefetch status to all clients",{clientCount:t.length,completedGroups:e.completedGroups})}function co(n,e){return`${n}@${e}`}async function ft(n){try{return(await n.keys()).length}catch{return-1}}function pt(n,e){const t=ls.catch(()=>{}).then(async()=>{y("idle prefetch task start",{label:n});try{await e()}finally{y("idle prefetch task done",{label:n})}});return ls=t.catch(s=>{console.warn("[SWDebug] idle prefetch task failed",{label:n,error:ae(s)})}),t}function lo(n){return Math.min(to,eo*2**Math.max(0,n-1))}function gs(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),so.forEach(r),Object.keys(n.groups).forEach(r),t}function fs(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 u=!1;for(const g of l){const f=co(g.url,g.revision);if(Ue.has(f)||(u=!0,He.has(f)))continue;const b=dt.get(f);if(b&&b.nextRetryAt>t){a+=1;const h=Math.max(0,b.nextRetryAt-t);i=i===null?h:Math.min(i,h);continue}s.set(f,g)}u?o.push(c):r.push(c)}return{completedGroups:r,pendingGroups:o,queue:Array.from(s.entries()),coolingEntries:a,nextRetryDelayMs:i}}function an(n,e=sn){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(je!==null){if(ze<=s){y("scheduleIdlePrefetchSweep skipped: earlier timer already exists",{reason:n,scheduledInMs:Math.max(0,ze-Date.now()),requestedDelayMs:t});return}clearTimeout(je),je=null,ze=0}ze=s,je=self.setTimeout(()=>{je=null,ze=0,pt(`idle-sweep:${n}`,async()=>{await wt(`scheduled:${n}`)})},t),y("scheduleIdlePrefetchSweep queued",{reason:n,delayMs:t})}function uo(){return Fe===0?!1:Date.now()-Fe<nn}function ho(){if(Fe===0)return Promise.resolve();const n=Date.now()-Fe,e=Math.max(0,nn-n)+100;return y("waitForIdlePrefetchWindow: delaying idle prefetch",{elapsedMs:n,waitMs:e,recentFetchWindowMs:nn}),new Promise(t=>{setTimeout(t,e)})}function go(n,e){const t=ve(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-cs<Zr?!1:(cs=s,!0)}function fo(n){return Fn(ve(n))}function ps(n,e){return xe||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||fo(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 po(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${e.replace(/^\/npm\/aitu-app@[^/]+\//,"/").replace(/^\/aitu-app@[^/]+\//,"/")}${t}`}function mo(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${ve(e)}${t}`}function mt(n){const e=new URL(n,self.location.origin),t=po(mo(`${e.pathname}${e.search}`)),s=B(t);return{requestUrl:e,resourcePath:t,cacheKey:s.href,originFetchUrl:s.href}}function Ve(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&ps(n,e)}function bo(n,e){const t=new Headers(n.headers);return t.set($t,e.source),t.set(Vt,e.revision),t.set(Kt,e.appVersion||C),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 cn(n,e,t,s){const r=bo(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 y("findStaticResponseInOldCaches: normalized key hit",{cacheName:r,requestUrl:n.url,normalizedCacheKey:i}),c}}catch{}return null}async function wo(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 yo(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 So(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function ms(n,e,t){try{const s=mt(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(Vt),l=r.headers.get(Kt);if(c===t&&l===C)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(_r(ve(s.requestUrl.pathname))){const c=await Gt(s.resourcePath,C,it.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&&Ve(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 cn(n,s.cacheKey,o,{source:a,revision:t,fetchTarget:i,appVersion:C}),s.resourcePath==="/index.html"){const c=B("/").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 Co(n,e){const s=[],r=e.length;let o=0,a=0;const i=await ft(n);y("precacheStaticFiles start",{total:r,concurrency:6,cacheEntriesBefore:i,sampleUrls:e.slice(0,8).map(b=>b.url)}),Ee({phase:"precache",total:r,completed:0,failed:0,percent:r>0?0:100,message:r>0?`正在预热启动资源(0/${r})...`:"没有需要预热的启动资源"});for(let b=0;b<e.length;b+=6){const h=e.slice(b,b+6),p=await Promise.allSettled(h.map(({url:m,revision:S})=>ms(n,m,S))),d=[];for(const m of p)if(m.status==="fulfilled"){const S={url:m.value.url,success:m.value.success,skipped:m.value.skipped,source:m.value.source,status:m.value.status,error:m.value.error};s.push(S),d.push(S),o+=1,m.value.success||(a+=1)}else{const S={success:!1,error:String(m.reason)};s.push(S),d.push(S),o+=1,a+=1}y("precacheStaticFiles batch done",{completed:o,total:r,batchSize:h.length,batchSuccess:d.filter(m=>m.success).length,batchSkipped:d.filter(m=>m.skipped).length,batchFailed:d.filter(m=>!m.success).length,batchSources:Object.fromEntries(Array.from(d.reduce((m,S)=>{const E=S.source||"unknown";return m.set(E,(m.get(E)||0)+1),m},new Map))),batchErrors:d.filter(m=>!m.success).slice(0,5).map(m=>({url:m.url,status:m.status,error:m.error}))}),Ee({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 c=s.filter(b=>b.success).length,l=s.length-c,u=s.filter(b=>b.success&&b.source&&b.source!=="server").length,g=s.filter(b=>b.success&&b.source==="server").length,f=await ft(n);return y("precacheStaticFiles finished",{total:r,successCount:c,failCount:l,cdnCount:u,serverCount:g,cacheEntriesBefore:i,cacheEntriesAfter:f}),{total:r,successCount:c,failCount:l,cdnCount:u,serverCount:g}}async function bs(n){if(y("prefetchIdleGroups start",{groupNames:n}),n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await gt();if(!e)return y("prefetchIdleGroups aborted: manifest missing"),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};y("prefetchIdleGroups manifest summary",{requestedGroups:n,groupEntryCounts:Object.fromEntries(n.map(u=>{var g;return[u,((g=e.groups[u])==null?void 0:g.length)||0]})),defaults:e.defaults||[]});const t=new Set(qe),s=fs(e,n);if(s.completedGroups.forEach(u=>qe.add(u)),s.queue.length===0)return y("prefetchIdleGroups no ready files",{groupNames:n,completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs,completedEntries:Ue.size,activeEntries:He.size}),{completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,queuedEntries:0,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs};const r=await caches.open(Re),o=await ft(r),a=s.queue;y("prefetchIdleGroups queue prepared",{groupNames:n,totalCandidates:s.queue.length,queuedEntries:a.length,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,cacheEntriesBefore:o,sampleUrls:a.slice(0,8).map(([,u])=>u.url)});for(let u=0;u<a.length;u+=is){for(;uo();)await ho();const g=a.slice(u,u+is);g.forEach(([h])=>He.add(h));const f=await Promise.allSettled(g.map(([,{url:h,revision:p}])=>ms(r,h,p))),b=[];f.forEach((h,p)=>{const[d]=g[p];if(He.delete(d),h.status==="fulfilled"&&h.value.success)dt.delete(d),Ue.add(d);else{const m=dt.get(d),S=((m==null?void 0:m.count)||0)+1,E=lo(S);dt.set(d,{count:S,nextRetryAt:Date.now()+E,lastError:h.status==="fulfilled"?h.value.error:String(h.reason),lastStatus:h.status==="fulfilled"?h.value.status:void 0})}h.status==="fulfilled"?b.push({url:h.value.url,success:h.value.success,skipped:h.value.skipped,source:h.value.source,status:h.value.status,error:h.value.error}):b.push({success:!1,error:String(h.reason)})}),y("prefetchIdleGroups batch done",{groupNames:n,batchStart:u,batchSize:g.length,batchSuccess:b.filter(h=>h.success).length,batchSkipped:b.filter(h=>h.skipped).length,batchFailed:b.filter(h=>!h.success).length,batchSources:Object.fromEntries(Array.from(b.reduce((h,p)=>{const d=p.source||"unknown";return h.set(d,(h.get(d)||0)+1),h},new Map))),batchErrors:b.filter(h=>!h.success).slice(0,5).map(h=>({url:h.url,status:h.status,error:h.error})),completedEntries:Ue.size,activeEntries:He.size})}const i=fs(e,n),c=i.completedGroups.filter(u=>!t.has(u));c.forEach(u=>qe.add(u));const l=await ft(r);return y("prefetchIdleGroups finished",{groupNames:n,newlyCompletedGroups:c,pendingGroups:i.pendingGroups,completedEntries:Ue.size,cacheEntriesBefore:o,cacheEntriesAfter:l,completedGroups:Array.from(qe),coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}),{completedGroups:c,pendingGroups:i.pendingGroups,queuedEntries:a.length,coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}}async function wt(n,e=[]){if($e())return y("prefetchPendingIdleGroups skipped: disabled in development",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const t=await gt();if(!t)return an(`${n}:manifest-missing`,Ce),y("prefetchPendingIdleGroups skipped: manifest missing",{reason:n,preferredGroups:e,retryDelayMs:Ce,lastFailureReason:ge}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:Ce};const s=gs(t,e);if(s.length===0)return y("prefetchPendingIdleGroups skipped: no groups",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};y("prefetchPendingIdleGroups start",{reason:n,preferredGroups:e,orderedGroups:s,groupEntryCounts:Object.fromEntries(s.map(o=>{var a;return[o,((a=t.groups[o])==null?void 0:a.length)||0]}))});const r=await bs(s);return r.completedGroups.length>0&&await on(),r.pendingGroups.length>0&&an(`${n}:pending`,r.nextRetryDelayMs??sn),y("prefetchPendingIdleGroups done",{reason:n,preferredGroups:e,orderedGroups:s,summary:r}),r}async function Eo(){var t;if($e()){y("prefetchDefaultIdleGroups skipped: disabled in development");return}const n=await gt();if(!n){an("default-groups:manifest-missing",Ce),y("prefetchDefaultIdleGroups skipped: manifest missing",{retryDelayMs:Ce,lastFailureReason:ge});return}const e=(t=n==null?void 0:n.defaults)==null?void 0:t.filter(s=>typeof s=="string"&&s.length>0);if(!e||e.length===0){y("prefetchDefaultIdleGroups skipped: no default groups");return}await wt("default-groups",e)}async function To(){if($e()){y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: disabled in development");return}const n=Date.now();let e=0,t=null;for(;;){if(!t){const a=await gt();if(!a){const i=Date.now()-n;y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: manifest unavailable",{elapsedMs:i,lastFailureReason:ge});return}if(t=gs(a),t.length===0){y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: no groups");return}}e+=1;const s=await bs(t);if(s.completedGroups.length>0&&await on(),s.pendingGroups.length===0){y("prewarmAllIdlePrefetchGroupsForUpdateReady complete",{orderedGroups:t,iteration:e,elapsedMs:Date.now()-n});return}const r=Date.now()-n;if(r>=no)throw new Error(`idle-prefetch incomplete after ${r}ms: pending groups ${s.pendingGroups.join(", ")}`);const o=Math.max(250,s.nextRetryDelayMs??(s.queuedEntries>0?sn:1e3));y("prewarmAllIdlePrefetchGroupsForUpdateReady waiting next round",{orderedGroups:t,iteration:e,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,queuedEntries:s.queuedEntries,waitMs:o,elapsedMs:r}),await new Promise(a=>{setTimeout(a,o)})}}U.addEventListener("install",n=>{y("install event received",{version:C}),he=!!U.registration.active,ht=!he,he||U.skipWaiting(),Ee({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await Xr(),await Se(e=>({committedVersion:e.committedVersion||C,pendingVersion:he?C:null,pendingReadyAt:null,upgradeState:he?"prewarming":"idle"})),await de();try{const e=await oo();if(e&&e.length>0){const t=await caches.open(Re),s=await Co(t,e);if(he&&s.failCount>0)throw new Error(`precache incomplete: ${s.failCount}/${s.total} files failed`)}else xe&&Ee({phase:"development",percent:100,completed:0,total:0,failed:0,message:"开发模式下跳过静态预缓存"});he&&await To(),await Qr(he)}catch(e){await Se(t=>({committedVersion:t.committedVersion||C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"})),await de(),Ee({phase:"error",message:`启动资源预热失败:${ae(e)}`}),console.warn("Service Worker: Precache failed:",e)}})())}),U.addEventListener("activate",n=>{y("activate event received",{version:C}),Ee({phase:"activating",percent:100,message:"启动缓存服务正在接管页面..."}),n.waitUntil((async()=>{await Ge(),await Se({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();try{const{ensureCDNPreferenceLoaded:t}=await Promise.resolve().then(()=>Cr);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}ht?(y("activate: before clients.claim"),await U.clients.claim(),y("activate: after clients.claim")):y("activate: skip clients.claim for staged update"),setTimeout(()=>{y("activate: scheduling default idle prefetch"),pt("default-groups",async()=>Eo())},800);const e=O();e&&(e.sendSWActivated(C),y("activate: sent sw:activated broadcast")),Ee({phase:"activated",percent:100,message:"启动缓存服务已就绪"})})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(i=>i.startsWith("drawnix-images-v")&&i!==L);if(t.length>0){const i=await caches.open(L);for(const c of t)try{const l=await caches.open(c),u=await l.keys();for(const g of u){const f=await l.match(g);f&&await i.put(g,f)}await caches.delete(c)}catch(l){console.warn(`Failed to migrate cache ${c}:`,l)}}const s=await Ge(),r=rs(s.committedVersion||C),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==Re&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==zt&&i!==L&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(Re);await Ao(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),Qn().catch(i=>{console.warn("Failed to cleanup expired console logs:",i)}),wn.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function Do(n){if(I){const e=O();e&&e.sendPostMessageLog(n)}}async function _o(n,e,t,s){if(xe)return null;try{const r=mt(e.url),o=await Gt(t,s,it.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:us()}),null;const a=new URL(e.url);if(Ve(e,a,o.response))return null;const i=await cn(n,r.cacheKey,o.response,{source:o.source,revision:"runtime",fetchTarget:o.targetUrl,appVersion:s});return r.cacheKey!==e.url&&y("tryFetchStaticResourceFromCDN: cached under normalized key",{requestUrl:e.url,normalizedCacheKey:r.cacheKey,resourcePath:t,source:o.source,fetchTarget:o.targetUrl}),i}catch(r){return console.warn("[SW CDN] CDN fallback failed:",r),null}}function Ro(n){const e=n.headers.get($t)||void 0,t=n.headers.get(Un)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function ws(n,e,t=C){const s=e.headers.get($t),r=e.headers.get(Vt),o=e.headers.get(Kt);if(!s||!r||!o){const i=new URL(n.url);return!(e.ok&&!Ve(n,i,e))}if(o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr"&&s!=="unpkg")return!0;const a=new URL(n.url);return Ve(n,a,e)}async function Ao(n){const e=await n.keys();for(const t of e)try{const s=await n.match(t);s&&ws(t,s)&&await n.delete(t)}catch(s){console.warn("Service Worker: Failed to inspect static cache entry:",s)}}U.addEventListener("message",n=>{var a,i,c,l,u,g,f,b,h,p;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=((u=n.source)==null?void 0:u.id)||"",s=((g=n.source)==null?void 0:g.url)||"",r=((f=n.data)==null?void 0:f.cmdname)||((b=n.data)==null?void 0:b.requestId)&&((h=n.data)==null?void 0:h.ret)!==void 0;let o="";if(_t()&&!r&&(o=Rt(e,n.data,t,s,(p=n.data)==null?void 0:p.__internal__),o&&I)){const m=Ye().find(S=>S.id===o);m&&Do(m)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:d,mediaType:m,blob:S,mimeType:E}=n.data;if(d&&m&&S){const A=new Blob([S],{type:E||(m==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:j}=await Promise.resolve().then(()=>q);j(A,d,m)})()}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==="SW_BOOT_PROGRESS_GET"){const d=n.source;y("message: SW_BOOT_PROGRESS_GET",{clientId:(d==null?void 0:d.id)??null}),hs(d);return}if(n.data&&n.data.type==="GET_VERSION_STATE"){const d=n.source;y("message: GET_VERSION_STATE",{clientId:(d==null?void 0:d.id)??null}),n.waitUntil(de(d));return}if(n.data&&n.data.type==="SW_IDLE_PREFETCH_STATUS_GET"){const d=n.source;y("message: SW_IDLE_PREFETCH_STATUS_GET",{clientId:(d==null?void 0:d.id)??null}),on(d);return}if(n.data&&n.data.type==="SW_PREFETCH_GROUPS"){const d=Array.isArray(n.data.groups)?n.data.groups.filter(m=>typeof m=="string"):[];y("message: SW_PREFETCH_GROUPS",{groups:d}),n.waitUntil(pt(`message:${d.join(",")||"empty"}`,async()=>{await wt(`message:${d.join(",")||"empty"}`,d)}));return}if(n.data&&(n.data.type==="COMMIT_UPGRADE"||n.data.type==="SKIP_WAITING")){const d=n.source;y("message: COMMIT_UPGRADE",{clientId:(d==null?void 0:d.id)??null}),n.waitUntil((async()=>{ht=!0,await Se({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(d),U.skipWaiting();const m=O();m&&m.sendSWUpdated(C)})())}else if(n.data&&n.data.type==="FORCE_UPGRADE")n.waitUntil((async()=>{ht=!0,await Se({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(n.source),U.skipWaiting();const d=O();d&&d.sendSWUpdated(C)})());else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:d}=n.data;d&&un(d).then(()=>{const m=O();m&&m.sendCacheDeleted(d)}).catch(m=>{console.error("Service Worker: Failed to delete cache:",m)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:d}=n.data;d&&Array.isArray(d)&&Io(d).then(()=>{}).catch(m=>{console.error("Service Worker: Failed to batch delete caches:",m)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")ko().then(()=>{}).catch(d=>{console.error("Service Worker: Failed to clear all cache:",d)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){I=!0,Be(!0),tt(!0),ne.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const d=O();d&&d.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){I=!1,Be(!1),tt(!1),J.length=0,K.length=0,ne.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const d=O();d&&d.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:d}=await Promise.resolve().then(()=>De),m=await d(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:m})}catch(d){console.error("[SW] Failed to get LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:d}=await Promise.resolve().then(()=>De);await d();const m=n.source;m&&m.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(d){console.error("[SW] Failed to clear LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const d=n.source;d&&d.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:I,swVersion:C,logs:K.slice(-100),consoleLogs:J.slice(-100)});return}if(n.data&&n.data.type==="SW_DEBUG_GET_LOGS"){(async()=>{try{const{getInternalFetchLogs:d}=await Promise.resolve().then(()=>gr),m=Zt(),S=d(),E=n.source;E&&E.postMessage({type:"SW_DEBUG_LOGS",logs:[...m,...S.map(A=>({...A,type:"fetch"}))]})}catch(d){console.error("[SW] Failed to get fetch logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const d=n.source;d&&d.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:J})}catch(d){console.error("[SW] Failed to get console logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const d=Ye(),m=n.source;m&&m.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:d})}catch(d){console.error("[SW] Failed to get postmessage logs:",d)}})();return}});const Lo="MemorySnapshotDB",fe="snapshots",ys=50;async function ln(){return new Promise((n,e)=>{const t=indexedDB.open(Lo,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(fe)){const o=r.createObjectStore(fe,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function Ss(n){try{const e=await ln(),t=e.transaction(fe,"readwrite"),s=t.objectStore(fe);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>ys){const i=s.index("timestamp").openCursor();let c=0;const l=o-ys;i.onsuccess=u=>{const g=u.target.result;g&&c<l&&(s.delete(g.value.id),c++,g.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 Cs(){try{const n=await ln(),s=n.transaction(fe,"readonly").objectStore(fe).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 Es(){try{const n=await ln(),e=n.transaction(fe,"readwrite");e.objectStore(fe).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 vo=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function Mo(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Po(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 u=s.transaction(r,"readonly");for(const g of r){const f=u.objectStore(g),b=f.count();b.onsuccess=()=>{const h=b.result;if(o+=h,h>0){const p=f.openCursor();let d=0;p.onsuccess=m=>{const S=m.target.result;if(S&&d<l)a+=Mo(S.value),i++,d++,S.continue();else if(c++,c===r.length){s.close();const E=i>0?a/i:0,A=Math.round(E*o);e({count:o,totalSize:A})}},p.onerror=()=>{if(c++,c===r.length){s.close();const m=i>0?a/i:0,S=Math.round(m*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 h=i>0?a/i:0,p=Math.round(h*o);e({count:o,totalSize:p})}}}}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 Ts(){const n={},e=[zt,L,Re,ct];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 u=l.headers.get("sw-image-size")||l.headers.get("content-length");u&&(i+=parseInt(u))}}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 vo)try{const s=await Po(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function un(n){try{await(await caches.open(L)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function Io(n){try{const e=await caches.open(L);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 ko(){try{const n=await caches.open(L),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 Ds(n,e,t){try{const s=O();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}async function Oo(){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=O();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const re=new Map,_s=300*1e3,Rs=500;function Wo(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 Bo(n){const e=re.get(n);return e?Date.now()-e>_s?(re.delete(n),!1):!0:!1}function As(n){if(Wo(n)){if(re.size>=Rs){const e=Date.now();for(const[t,s]of re)e-s>_s&&re.delete(t);if(re.size>=Rs){const t=Array.from(re.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)re.delete(r)}}re.set(n,Date.now())}}U.addEventListener("fetch",n=>{const e=new URL(n.request.url),t=Date.now();if(e.protocol!=="http:"&&e.protocol!=="https:"){k({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(Fe=t,go(n,e)){const s=`${e.pathname}${e.search}`;y("fetch: enqueue idle prefetch recheck",{clientId:n.clientId,requestUrl:s}),n.waitUntil(pt(`fetch-recheck:${s}`,async()=>{await wt(`fetch:${s}`)}))}if(e.pathname.startsWith(qn)||e.pathname.startsWith(jn)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(No(n.request).then(r=>(v(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw v(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(Mr)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Go(n.request).then(r=>(v(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw v(s,{error:String(r),duration:Date.now()-t}),r}));return}if(!(e.hostname.endsWith(".posthog.com")||e.hostname.endsWith(".sentry.io")||e.hostname.endsWith(".ingest.sentry.io"))){if(e.hostname==="cdn.i666.fun"){k({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")){k({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")){k({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(xr(e.hostname)){k({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&&zr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=k({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(Fo(n.request).then(a=>(v(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,cached:a.headers.has(se),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 v(o,{error:String(a),duration:Date.now()-s}),a}));return}if(jr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=k({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(Uo(n.request).then(a=>(v(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 v(o,{error:String(a),duration:Date.now()-s}),a}));return}if($r(e,n.request)){const s=Date.now(),r=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(xo(n.request).then(o=>(v(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 v(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&qr(e,n.request)){if(Bo(n.request.url)){k({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=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(zo(n.request).then(o=>(o.status===404&&As(n.request.url),v(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 As(n.request.url),v(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=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(Ho(n.request).then(i=>{const c=Ro(i);return v(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
|
|
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 re(n){return n instanceof Error?n.name||"Error":"Unknown error"}const _t="sw-task-queue",mn=3,_="tasks",z="config",N="workflows",F="chat-workflows",L="pending-tool-requests",v="pending-dom-operations",G="task-step-mappings",$="pending-canvas-operations",Gs=[_,z,N,F,L,v,G,$];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(N)){const e=n.createObjectStore(N,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(F)){const e=n.createObjectStore(F,{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(v)){const e=n.createObjectStore(v,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(G)||n.createObjectStore(G,{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),f=[];let g=0,w=0;p.onerror=()=>l(p.error),p.onsuccess=S=>{const E=S.target.result;if(!E){c({tasks:f,total:w,hasMore:w>t+f.length});return}const x=E.value,H=!r||x.status===r,se=!o||x.type===o;H&&se&&(w++,g<t?g++:f.length<s&&f.push(x)),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,...d}=c;s(d)},i.onerror=()=>r(i.error)})}catch(t){return console.error("[SWStorage] Failed to get config:",re(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:",re(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(N,"readwrite").objectStore(N).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(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 workflow:",t),null}}async getAllWorkflows(){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 workflows:",e),[]}}async getWorkflowsByStatus(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 workflows by status:",t),[]}}async deleteWorkflow(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 workflow:",t)}}async saveChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(F,"readwrite").objectStore(F).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(F,"readonly").objectStore(F).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(F,"readonly").objectStore(F).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(F,"readonly").objectStore(F).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(F,"readwrite").objectStore(F).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 d=c.result;d&&(d.value.createdAt<s&&(d.delete(),l++),d.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(v,"readwrite").objectStore(v).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(v,"readonly").objectStore(v).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(v,"readonly").objectStore(v).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(v,"readonly").objectStore(v).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(v,"readonly").objectStore(v).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(v,"readwrite").objectStore(v).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(G,"readwrite").objectStore(G).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(G,"readonly").objectStore(G).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(G,"readonly").objectStore(G).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(G,"readonly").objectStore(G).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(G,"readwrite").objectStore(G).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 f=p.result;if(!f){c(b);return}const g=f.value;g.archived||b.push(g),f.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 d=t.transaction(_,"readwrite"),h=d.objectStore(_);for(const u of a)u.archived=!0,u.updatedAt=i,h.put(u);d.oncomplete=()=>{c(a.length)},d.onerror=()=>l(d.error)})}catch(t){return console.error("[SWStorage] Failed to archive old tasks:",t),0}}}const wn=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 Ve=!1;const Vs=500,oe=[];let At=0;function yn(){return Ve}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=Ve;Ve=n,!n&&e&&(oe.length=0,Oe.clear(),At=0)}function Rt(){return Ve}function Ks(n){if(!yn()||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 vt(n,e,t,s){if(!yn())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 Ke(){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 Mt=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:Qs,getAllLogs:Ke,getLogStats:er,isPostMessageLoggerDebugMode:Rt,logReceivedMessage:Lt,setPostMessageLoggerDebugMode:Cn,updateRequestWithResponse:vt},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",Xe=tr();var X,ae;Xe.__POSTMESSAGE_DUPLEX__||(Xe.__POSTMESSAGE_DUPLEX__={}),Xe.__POSTMESSAGE_DUPLEX__.version=rr,Xe.__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 J=n=>({valid:0,error:n});function cr(n){if(!_n(n))return J("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"?J("requestId must be a string"):s&&typeof e.cmdname!="string"?J("cmdname must be a string"):r&&typeof e.msg!="string"?J("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)?J("data must be an object"):"_senderKey"in e&&e._senderKey!==void 0&&typeof e._senderKey!="string"?J("_senderKey must be a string"):!("time"in e)||e.time===void 0||typeof e.time=="number"&&Number.isFinite(e.time)?{valid:1,message:e}:J("time must be a finite number"):J("ret must be a valid ReturnCode"):J("Message must have requestId, cmdname, or msg field");var a}function Ye(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 Pt=[],Z=[];function Dn(n){Z.length>=200&&Z.shift(),Z.push(n)}function An(n,e){for(let t=Z.length-1;t>=0;t--)if(Z[t].requestId===n&&Z[t].status==="pending"){Z[t].status=e,Z[t].duration=Date.now()-Z[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,Pt.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):Ye(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:Ye(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}),Ye(e)||this.sendMessage({requestId:t,ret:X.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!Ye(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=Pt.findIndex(r=>r.deref()===t);s!==-1&&Pt.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(d){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",i.id,d)}}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(d){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",i.id,d)}}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"},k={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"},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 wn.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=Ke().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 d=Lt(`RPC:${e}`,{params:o,requestId:i},t);this.broadcastPostMessageLog(d)}try{const d=await s(o);try{JSON.stringify(d)}catch(h){throw console.error(`[SW wrapRpcHandler] ${e} result serialization failed:`,h),new Error(`Result serialization failed: ${h}`)}if(c&&i){const h=vt(i,{result:d},Date.now()-a);h&&this.broadcastPostMessageLog(h)}return d}catch(d){if(console.error(`[SW wrapRpcHandler] ${e} error:`,d),c&&i){const h=vt(i,null,Date.now()-a,String(d));h&&this.broadcastPostMessageLog(h)}throw d}}}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){try{const{saveCrashSnapshot:t}=await Promise.resolve().then(()=>A);return await t(e.snapshot),{success:!0}}catch(t){return console.error("[SWChannelManager] Crash snapshot save failed:",t),{success:!1,error:t.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){try{const{addConsoleLog:t}=await Promise.resolve().then(()=>A),s=e.logArgs??[],o=(Array.isArray(s)?s.map(a=>this.serializeLogArg(a)):[this.serializeLogArg(s)]).join(" ");return t({logLevel:e.logLevel,logMessage:o||"-"}),{success:!0}}catch(t){return{success:!1,error:t.message}}}async handleDebugGetStatus(){try{const{getDebugStatus:e,getCacheStats:t}=await Promise.resolve().then(()=>A),s=e(),r=await t();return{...s,enabled:s.debugModeEnabled,cacheStats:r}}catch{return{debugModeEnabled:!1}}}async handleDebugEnable(){try{const{enableDebugMode:e,getDebugStatus:t}=await Promise.resolve().then(()=>A);await e();const s=t();return this.sendDebugStatusChanged(!0),{success:!0,status:s}}catch{return{success:!1}}}async handleDebugDisable(){try{const{disableDebugMode:e,getDebugStatus:t}=await Promise.resolve().then(()=>A);await e();const s=t();return this.sendDebugStatusChanged(!1),{success:!0,status:s}}catch{return{success:!1}}}async handleDebugGetLogs(e){try{const{getDebugLogs:t,getInternalFetchLogs:s}=await Promise.resolve().then(()=>A),{limit:r=100,offset:o=0,filter:a}=e||{},i=s().map(u=>({...u,type:"fetch"})),c=t(),l=new Map;for(const u of c)l.set(u.id,u);for(const u of i)l.set(u.id,u);let d=Array.from(l.values()).sort((u,b)=>b.timestamp-u.timestamp);return a&&(a.type&&(d=d.filter(u=>u.type===a.type)),a.status&&(d=d.filter(u=>u.status===a.status))),{logs:d.slice(o,o+r),total:d.length,offset:o,limit:r}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||100}}}async handleDebugClearLogs(){try{const{clearDebugLogs:e}=await Promise.resolve().then(()=>A);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){try{const{loadConsoleLogsFromDB:t}=await Promise.resolve().then(()=>A),{limit:s=500,offset:r=0,filter:o}=e||{};let a=await t();if(o&&(o.logLevel&&(a=a.filter(c=>c.logLevel===o.logLevel)),o.search)){const c=o.search.toLowerCase();a=a.filter(l=>{var d,h;return((d=l.logMessage)==null?void 0:d.toLowerCase().includes(c))||((h=l.logStack)==null?void 0:h.toLowerCase().includes(c))})}return{logs:a.slice(r,r+s),total:a.length,offset:r,limit:s}}catch(t){return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||500,error:String(t)}}}async handleDebugClearConsoleLogs(){try{const{clearConsoleLogs:e,clearAllConsoleLogs:t}=await Promise.resolve().then(()=>A);return e(),await t(),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>Mt),{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(d=>{var h;return(h=d.messageType)==null?void 0:h.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(()=>Mt);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){try{const{getCrashSnapshots:e}=await Promise.resolve().then(()=>A),t=await e();return{snapshots:t,total:t.length}}catch(e){return{snapshots:[],total:0,error:String(e)}}}async handleDebugClearCrashSnapshots(){try{const{clearCrashSnapshots:e}=await Promise.resolve().then(()=>A);return await 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){try{const{IMAGE_CACHE_NAME:t}=await Promise.resolve().then(()=>A),{cacheName:s=t,limit:r=50,offset:o=0}=e||{},a=await caches.open(s),i=await a.keys(),c=[];for(let l=o;l<Math.min(o+r,i.length);l++){const d=i[l],h=await a.match(d);if(h){const u=h.headers.get("sw-cache-date"),b=h.headers.get("sw-cache-created-at")||u,p=h.headers.get("sw-image-size")||h.headers.get("content-length");c.push({url:d.url,cacheDate:u?parseInt(u):void 0,cacheCreatedAt:b?parseInt(b):void 0,size:p?parseInt(p):void 0})}}return{cacheName:s,entries:c,total:i.length,offset:o,limit:r}}catch(t){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(t)}}}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 d=await a.match(l);if(d){const h=d.headers.get("content-length");h&&(c+=parseInt(h))}}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(){try{const{getDebugStatus:e,getDebugLogs:t,loadConsoleLogsFromDB:s,APP_VERSION:r}=await Promise.resolve().then(()=>A),{getAllLogs:o}=await Promise.resolve().then(()=>Mt),a=await s(),i=o(),c=t();return{exportTime:new Date().toISOString(),swVersion:r,status:e(),fetchLogs:c,consoleLogs:a,postmessageLogs:i}}catch{return{exportTime:new Date().toISOString(),swVersion:"unknown",status:{},fetchLogs:[],consoleLogs:[],postmessageLogs:[]}}}async handleCDNGetStatus(){try{const{getCDNStatusReport:e}=await Promise.resolve().then(()=>A);return{status:e()}}catch{return{status:{}}}}async handleCDNResetStatus(){try{const{resetCDNStatus:e}=await Promise.resolve().then(()=>A);return e(),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){try{const{performHealthCheck:e,APP_VERSION:t}=await Promise.resolve().then(()=>A),s=await e(t);return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){try{const{APP_VERSION:e}=await Promise.resolve().then(()=>A);return{version:e}}catch{return{version:"unknown"}}}async handleUpgradeForce(){try{self.skipWaiting();const{APP_VERSION:t}=await Promise.resolve().then(()=>A);return this.sendSWUpdated(t),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){try{const{deleteCacheByUrl:t}=await Promise.resolve().then(()=>A);return await t(e.url),this.sendCacheDeleted(e.url),{success:!0}}catch(t){return{success:!1,error:String(t)}}}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(k.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheImageCacheFailed(e,t){this.broadcastToAll(k.CACHE_IMAGE_CACHE_FAILED,{url:e,error:t})}sendCacheDeleted(e){this.broadcastToAll(k.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(k.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(k.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(k.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(k.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(k.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(k.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(k.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(k.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(k.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(k.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 Qe=Te,Je=null;function Rn(n){return Je||(Je=Qe.getInstance(n)),Je}function M(){return Je}const fr=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:C,SWChannelManager:Qe,SW_EVENTS:k,getChannelManager:M,initChannelManager:Rn},Symbol.toStringTag,{value:"Module"}));function Ze(n){Cn(n)}const pr=[];let Ln=!1;function We(n){Ln=n}function It(){return Ln}function kt(){return[...pr]}const mr=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:kt,isDebugFetchEnabled:It,setDebugFetchEnabled:We},Symbol.toStringTag,{value:"Module"})),br=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),O={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},unpkg:{baseTimeout:600*1e3,maxTimeout:3600*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 ee=null,Ot=!1,tt=null;function vn(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()})})}vn();function yr(n){return n==="jsdelivr"||n==="unpkg"||n==="local"}function Mn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!yr(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 Pn(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=O.preferenceCacheExpiry}async function Sr(){if(typeof caches>"u")return null;try{const e=await(await caches.open(O.preferenceCacheName)).match(O.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 Wt(){Ot||(tt||(tt=(async()=>{ee=await Sr(),Ot=!0,tt=null})()),await tt)}async function In(n){if(ee=Mn(n),Ot=!0,!(typeof caches>"u"))try{const e=await caches.open(O.preferenceCacheName);if(!ee){await e.delete(O.preferenceCacheKey);return}await e.put(O.preferenceCacheKey,new Response(JSON.stringify(ee),{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 Bt(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>=O.failThreshold){t.isHealthy=!1;const s=On(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 kn(n,e){const t=wr[n]??{baseTimeout:O.degradeTimeout,maxTimeout:O.degradeTimeout},r=2**Math.max(0,e-O.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function On(n){const e=kn(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function xt(n,e={}){const t=be.get(n);if(!t)return!1;if(t.isHealthy||e.ignoreCooldown)return!0;const s=Date.now(),r=kn(n,t.failCount);return s-t.lastCheckTime>r}function Cr(n,e={}){const t=ee;return!t||!Pn(t,n)||t.cdn==="local"?null:xt(t.cdn,e)?t.cdn:null}function Wn(n,e={}){const t=n?Cr(n,e):null;return et.filter(s=>s.enabled&&xt(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 Bn(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 xn(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function Er(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}`:n.name==="unpkg"?`https://unpkg.com/${r.replace(/^\/npm\//,"")}`:null:null}function Nt(n,e,t){const s=Er(n,t);if(s)return s;const r=Bn(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function Ft(n,e=O.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 Gt(n,e){const t=Bn(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function Nn(n,e,t){try{const s=Gt(e,n),r=await Ft(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 Fn(n,e,t,s){for(const r of n){const o=Nt(r,e,t);try{const a=await Ft(o,s);if(!a.ok){ce(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await Tr(a,r.name))continue;return Bt(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 Tr(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 d=new TextDecoder().decode(l.slice(0,200)),h=d.includes("<!DOCTYPE")||d.includes("<html")||d.includes("<HTML")||d.includes("Not Found")||d.includes("404");if(o&&h)return ce(e,"html-error-page"),console.warn(`[CDN Fallback] ${e} returned HTML instead of ${t}`),!1}}}catch{}return!0}async function Ut(n,e,t,s={}){if(br)return null;await Wt();const{preferLocal:r=!1,localTimeout:o=O.localFetchTimeout,requestKind:a="interactive-runtime"}=s,i=a==="background-prefetch",c=s.cdnTimeout??(a==="background-prefetch"?O.backgroundFetchTimeout:O.fetchTimeout);if(r){const u=await Nn(n,t,o);if(u)return{...u,targetUrl:Gt(t,n)}}const l=Wn(e,{ignoreCooldown:i}),d=await Fn(l,e,n,c);if(d)return d;if(!r){const u=await Nn(n,t,o);if(u)return{...u,targetUrl:Gt(t,n)}}const h=et.filter(u=>u.enabled&&!l.some(b=>b.name===u.name));if(h.length>0){console.warn(`[CDN Fallback] Local origin failed, forcing CDN recovery probe for: ${n}`);const u=await Fn(h,e,n,c);if(u)return u}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function Ht(n){await Wt();const e=new Map;for(const t of et){if(!t.enabled)continue;const s=Nt(t,n,t.healthCheckPath);try{const r=await Ft(s,5e3),o=r.ok;e.set(t.name,o),o?Bt(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=Pn(ee)?ee==null?void 0:ee.cdn:null;return Array.from(be.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,...On(t)}))}function qt(){vn(!0)}const _r=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:Nt,ensureCDNPreferenceLoaded:Wt,extractVersionFromCDNPath:xn,fetchFromCDNWithFallback:Ut,getAvailableCDNs:Wn,getCDNStatusReport:nt,isCDNAvailable:xt,markCDNFailure:ce,markCDNSuccess:Bt,performHealthCheck:Ht,resetCDNStatus:qt,setCDNPreference:In},Symbol.toStringTag,{value:"Module"}));function jt(n){return n==="/"||n==="/index.html"}const Dr=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"];function Ar(n,e){return jt(e)?!0:n==="navigate"&&!e.endsWith(".html")}function Rr(n){return jt(n)}function Gn(n){return jt(n)?!0:Dr.some(e=>n.endsWith(e))}function Lr(n){return!Gn(n)}const W=self;Rn(W).setDebugClientCountChangedCallback(zr);const te={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 vr(){console.log=(...n)=>{te.log(...n),It()&&!st(n)&&rt("log",n)},console.info=(...n)=>{te.info(...n),It()&&!st(n)&&rt("info",n)},console.warn=(...n)=>{te.warn(...n),st(n)||rt("warn",n)},console.error=(...n)=>{te.error(...n),st(n)||rt("error",n)}}function Mr(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}=Mr(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof zt=="function"&&zt({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){te.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let zt=null;vr(),Promise.resolve().then(()=>Ee).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=M();t&&t.sendDebugLLMLog(e)})});const y="0.6.80",ot=new URL("./",self.location.href),$t=ot.pathname,Vt=`drawnix-v${y}`,D="drawnix-images",_e=`drawnix-static-v${y}`,at="drawnix-fonts",le="sw-cache-date",we="sw-cache-created-at",Kt="x-sw-source",Xt="x-sw-revision",Yt="x-sw-app-version",Un="x-sw-fetch-target",Pr="ServiceWorkerDB",Ir=2,De="failedDomains",Ae="versionState",Hn="app-version-state",qn="/__aitu_cache__/",jn="/__aitu_generated__/audio/",kr="/asset-library/",Be=location.hostname==="localhost"||location.hostname==="127.0.0.1";function B(n){return new URL(n.replace(/^\//,""),ot)}function Re(n){return $t!=="/"&&n.startsWith($t)?`/${n.slice($t.length)}`:n}const Or=[{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"}],Wr=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,Br=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Qt=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,xr=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 it(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)xr.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const q=new Map,ye=new Map,zn=30*1e3,ue=new Map,$n=300*1e3,Vn=500,xe=new Map,U=new Map,Nr=300*1e3,Kn=10,Le=new Set,ve=new Set,Fr=3600*1e3,Jt=new Map;function Xn(n){ve.add(n),Jt.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function Gr(n){if(!ve.has(n))return!1;const e=Jt.get(n);return e&&Date.now()-e>Fr?(ve.delete(n),Jt.delete(n),!1):!0}const Q=[],Yn=7,V=[],Ur=500;let P=!1;function I(n){if(!P)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return V.unshift(t),V.length>Ur&&V.pop(),Qn(t),e}function R(n,e){if(!P||!n)return;const t=V.find(s=>s.id===n);t&&(Object.assign(t,e),Qn(t))}function Qn(n){const e=M();e&&e.sendDebugLog(n)}function ct(){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 Hr(n){try{const e=await ct(),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 ct(),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 d=l.value;d.timestamp>=r&&c.push(d),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 ct(),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 d=c.result;d?(d.delete(),l++,d.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 ct(),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 Zt(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(P||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};Hr(r),Q.unshift(r),Q.length>ts&&(Q.length=ts),P&&qr(r)}zt=Zt;function qr(n){const e=M();e&&e.sendConsoleLog(n)}function jr(){let n=0;return U.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function ns(){return{version:y,cacheNames:[Vt,D,_e,at],pendingImageRequests:q.size,pendingVideoRequests:xe.size,videoBlobCacheSize:U.size,videoBlobCacheTotalBytes:jr(),completedImageRequestsSize:ye.size,failedDomainsCount:Le.size,failedDomains:Array.from(Le),corsFailedDomainsCount:ve.size,corsFailedDomains:Array.from(ve),debugLogsCount:V.length,consoleLogsCount:Q.length,debugModeEnabled:P,memoryStats:{pendingRequestsMapSize:q.size,completedRequestsMapSize:ye.size,videoBlobCacheMapSize:U.size,failedDomainsSetSize:Le.size,corsFailedDomainsSetSize:ve.size,debugLogsArraySize:V.length,consoleLogsArraySize:Q.length}}}function en(){return V}function ss(){V.length=0}function rs(){Q.length=0}function tn(){P||(P=!0,We(!0),Ze(!0),te.log("Service Worker: Debug mode enabled (debug page connected)"))}function nn(){P&&(P=!1,We(!1),Ze(!1),Q.length=0,V.length=0,te.log("Service Worker: Debug mode disabled (no debug pages)"))}function zr(n){n>0?tn():nn()}function os(n){for(const e of Or)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function $r(n,e){return Wr.test(n.pathname)||e.destination==="image"||os(n)!==null}function Vr(n,e){return Br.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function Kr(n,e){return Qt.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function Xr(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 Yr(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function as(n){return`drawnix-static-v${n}`}function is(){return{committedVersion:y,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function cs(n){const e=n||{},t=typeof e.committedVersion=="string"&&e.committedVersion?e.committedVersion:y,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 lt(){return new Promise((n,e)=>{const t=indexedDB.open(Pr,Ir);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 Ne(){try{const n=await lt();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 Qr(n){const e=cs(n);try{const t=await lt();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 Ne(),t=typeof n=="function"?n(e):n;return Qr({...e,...t,updatedAt:Date.now()})}async function de(n){const e=await Ne(),t={type:"SW_VERSION_STATE",...e,swVersion:y};if(n)return n.postMessage(t),e;const s=await W.clients.matchAll({type:"window",includeUncontrolled:!0});for(const r of s)r.postMessage(t);return e}async function Jr(){try{const n=await lt();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 Zr(n){try{const e=await lt();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 eo(n){if(!n){await Se({committedVersion:y,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();return}await Se(t=>({committedVersion:t.committedVersion||y,pendingVersion:y,pendingReadyAt:Date.now(),upgradeState:"ready"}));const e=M();e&&e.sendSWNewVersionReady(y),await de()}const ls=2,us=1500,sn=2500,to=8e3,no=5e3,so=6e4,ut=5e3,ro=600*1e3,oo=["offline-static-assets"];let Fe=0,ds=0;const Ge=new Set,Ue=new Set,He=new Set,dt=new Map;let hs=Promise.resolve(),qe=null,ht=0,he=!1,gt=!1;function pa(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 rn={phase:"idle",percent:0,completed:0,total:0,failed:0,version:y,updatedAt:Date.now()};async function ps(n){const e={type:"SW_BOOT_PROGRESS",...rn};if(n){n.postMessage(e);return}const t=await W.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e)}function Ce(n,e){rn={...rn,...n,version:y,updatedAt:Date.now()},ps(e)}async function ao(){try{const n=await fetch(B("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!==y?(e.version,null):e.files}catch(n){return re(n),null}}let Me=null,Pe=0;function je(){return Be}async function io(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 co(){if(je())return null;const n=B("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 io(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 re(a),null}return!o||typeof o!="object"||!o.groups?null:o.version&&o.version!==y?(o.version,null):(o.version,o.defaults,Object.fromEntries(Object.entries(o.groups).map(([a,i])=>[a,i.length])),o)}catch(e){return re(e),null}}async function ft(){if(je())return Pe=0,Me=null,null;const n=Date.now();if(!Me){if(Pe>0&&n-Pe<ut)return null;Me=co().then(e=>e?(Pe=0,e):(Pe=Date.now(),Me=null,null)).catch(e=>{throw Pe=Date.now(),re(e),Me=null,e})}return Me}async function on(n){const e={type:"SW_IDLE_PREFETCH_STATUS",completedGroups:Array.from(He),version:y,updatedAt:Date.now()};if(n){n.id,e.completedGroups,n.postMessage(e);return}const t=await W.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e);t.length,e.completedGroups}function lo(n,e){return`${n}@${e}`}async function pt(n){try{return(await n.keys()).length}catch{return-1}}function mt(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:re(s)})}),t}function uo(n){return Math.min(so,no*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),oo.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 d=!1;for(const h of l){const u=lo(h.url,h.revision);if(Ge.has(u)||(d=!0,Ue.has(u)))continue;const b=dt.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,h)}d?o.push(c):r.push(c)}return{completedGroups:r,pendingGroups:o,queue:Array.from(s.entries()),coolingEntries:a,nextRetryDelayMs:i}}function an(n,e=sn){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(qe!==null){if(ht<=s)return;clearTimeout(qe),qe=null,ht=0}ht=s,qe=self.setTimeout(()=>{qe=null,ht=0,mt(`idle-sweep:${n}`,async()=>{await yt(`scheduled:${n}`)})},t)}function ho(){return Fe===0?!1:Date.now()-Fe<us}function go(){if(Fe===0)return Promise.resolve();const n=Date.now()-Fe,e=Math.max(0,us-n)+100;return new Promise(t=>{setTimeout(t,e)})}function fo(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<to?!1:(ds=s,!0)}function po(n){return Gn(Re(n))}function ws(n,e){return Be||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||po(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 mo(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${e.replace(/^\/npm\/aitu-app@[^/]+\//,"/").replace(/^\/aitu-app@[^/]+\//,"/")}${t}`}function bo(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${Re(e)}${t}`}function bt(n){const e=new URL(n,self.location.origin),t=mo(bo(`${e.pathname}${e.search}`)),s=B(t);return{requestUrl:e,resourcePath:t,cacheKey:s.href,originFetchUrl:s.href}}function ze(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&ws(n,e)}function wo(n,e){const t=new Headers(n.headers);return t.set(Kt,e.source),t.set(Xt,e.revision),t.set(Yt,e.appVersion||y),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 cn(n,e,t,s){const r=wo(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 yo(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 So(n,e){const t=bt(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 Co(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function ys(n,e,t){try{const s=bt(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(Xt),l=r.headers.get(Yt);if(c===t&&l===y)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(Lr(Re(s.requestUrl.pathname))){const c=await Ut(s.resourcePath,y,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&&ze(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 cn(n,s.cacheKey,o,{source:a,revision:t,fetchTarget:i,appVersion:y}),s.resourcePath==="/index.html"){const c=B("/").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 Eo(n,e){const s=[],r=e.length;let o=0,a=0;await pt(n),e.slice(0,8).map(h=>h.url),Ce({phase:"precache",total:r,completed:0,failed:0,percent:r>0?0:100,message:r>0?`正在预热启动资源(0/${r})...`:"没有需要预热的启动资源"});for(let h=0;h<e.length;h+=6){const u=e.slice(h,h+6),b=await Promise.allSettled(u.map(({url:f,revision:g})=>ys(n,f,g))),p=[];for(const f of b)if(f.status==="fulfilled"){const g={url:f.value.url,success:f.value.success,skipped:f.value.skipped,source:f.value.source,status:f.value.status,error:f.value.error};s.push(g),p.push(g),o+=1,f.value.success||(a+=1)}else{const g={success:!1,error:String(f.reason)};s.push(g),p.push(g),o+=1,a+=1}u.length,p.filter(f=>f.success).length,p.filter(f=>f.skipped).length,p.filter(f=>!f.success).length,Object.fromEntries(Array.from(p.reduce((f,g)=>{const w=g.source||"unknown";return f.set(w,(f.get(w)||0)+1),f},new Map))),p.filter(f=>!f.success).slice(0,5).map(f=>({url:f.url,status:f.status,error:f.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(h=>h.success).length,c=s.length-i,l=s.filter(h=>h.success&&h.source&&h.source!=="server").length,d=s.filter(h=>h.success&&h.source==="server").length;return await pt(n),{total:r,successCount:i,failCount:c,cdnCount:l,serverCount:d}}async function Ss(n){if(n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await ft();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(He),s=bs(e,n);if(s.completedGroups.forEach(c=>He.add(c)),s.queue.length===0)return Ge.size,Ue.size,{completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,queuedEntries:0,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs};const r=await caches.open(_e);await pt(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(;ho();)await go();const l=o.slice(c,c+ls);l.forEach(([u])=>Ue.add(u));const d=await Promise.allSettled(l.map(([,{url:u,revision:b}])=>ys(r,u,b))),h=[];d.forEach((u,b)=>{const[p]=l[b];if(Ue.delete(p),u.status==="fulfilled"&&u.value.success)dt.delete(p),Ge.add(p);else{const f=dt.get(p),g=((f==null?void 0:f.count)||0)+1,w=uo(g);dt.set(p,{count:g,nextRetryAt:Date.now()+w,lastError:u.status==="fulfilled"?u.value.error:String(u.reason),lastStatus:u.status==="fulfilled"?u.value.status:void 0})}u.status==="fulfilled"?h.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}):h.push({success:!1,error:String(u.reason)})}),l.length,h.filter(u=>u.success).length,h.filter(u=>u.skipped).length,h.filter(u=>!u.success).length,Object.fromEntries(Array.from(h.reduce((u,b)=>{const p=b.source||"unknown";return u.set(p,(u.get(p)||0)+1),u},new Map))),h.filter(u=>!u.success).slice(0,5).map(u=>({url:u.url,status:u.status,error:u.error})),Ge.size,Ue.size}const a=bs(e,n),i=a.completedGroups.filter(c=>!t.has(c));return i.forEach(c=>He.add(c)),await pt(r),Ge.size,Array.from(He),{completedGroups:i,pendingGroups:a.pendingGroups,queuedEntries:o.length,coolingEntries:a.coolingEntries,nextRetryDelayMs:a.nextRetryDelayMs}}async function yt(n,e=[]){if(je())return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const t=await ft();if(!t)return an(`${n}:manifest-missing`,ut),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:ut};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 on(),r.pendingGroups.length>0&&an(`${n}:pending`,r.nextRetryDelayMs??sn),r}async function To(){var t;if(je())return;const n=await ft();if(!n){an("default-groups:manifest-missing",ut);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 _o(){if(je())return;const n=Date.now();let e=null;for(;;){if(!e){const o=await ft();if(!o||(e=ms(o),e.length===0))return}const t=await Ss(e);if(t.completedGroups.length>0&&await on(),t.pendingGroups.length===0)return;const s=Date.now()-n;if(s>=ro)throw new Error(`idle-prefetch incomplete after ${s}ms: pending groups ${t.pendingGroups.join(", ")}`);const r=Math.max(250,t.nextRetryDelayMs??(t.queuedEntries>0?sn:1e3));t.pendingGroups,t.coolingEntries,t.queuedEntries,await new Promise(o=>{setTimeout(o,r)})}}W.addEventListener("install",n=>{he=!!W.registration.active,gt=!he,he||W.skipWaiting(),Ce({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await Jr(),await Se(e=>({committedVersion:e.committedVersion||y,pendingVersion:he?y:null,pendingReadyAt:null,upgradeState:he?"prewarming":"idle"})),await de();try{const e=await ao();if(e&&e.length>0){const t=await caches.open(_e),s=await Eo(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 _o(),await eo(he)}catch(e){await Se(t=>({committedVersion:t.committedVersion||y,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"})),await de(),Ce({phase:"error",message:`启动资源预热失败:${re(e)}`}),console.warn("Service Worker: Precache failed:",e)}})())}),W.addEventListener("activate",n=>{Ce({phase:"activating",percent:100,message:"启动缓存服务正在接管页面..."}),n.waitUntil((async()=>{await Ne(),await Se({committedVersion:y,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();try{const{ensureCDNPreferenceLoaded:t}=await Promise.resolve().then(()=>_r);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}gt&&await W.clients.claim(),setTimeout(()=>{mt("default-groups",async()=>To())},800);const e=M();e&&e.sendSWActivated(y),Ce({phase:"activated",percent:100,message:"启动缓存服务已就绪"})})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(i=>i.startsWith("drawnix-images-v")&&i!==D);if(t.length>0){const i=await caches.open(D);for(const c of t)try{const l=await caches.open(c),d=await l.keys();for(const h of d){const u=await l.match(h);u&&await i.put(h,u)}await caches.delete(c)}catch(l){console.warn(`Failed to migrate cache ${c}:`,l)}}const s=await Ne(),r=as(s.committedVersion||y),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==_e&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==Vt&&i!==D&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(_e);await Lo(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)}),wn.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function Do(n){if(P){const e=M();e&&e.sendPostMessageLog(n)}}async function Ao(n,e,t,s){if(Be)return null;try{const r=bt(e.url),o=await Ut(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(ze(e,a,o.response))return null;const i=await cn(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 Ro(n){const e=n.headers.get(Kt)||void 0,t=n.headers.get(Un)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function Cs(n,e,t=y){const s=e.headers.get(Kt),r=e.headers.get(Xt),o=e.headers.get(Yt);if(!s||!r||!o){const i=new URL(n.url);return!(e.ok&&!ze(n,i,e))}if(o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr"&&s!=="unpkg")return!0;const a=new URL(n.url);return ze(n,a,e)}async function Lo(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)}}W.addEventListener("message",n=>{var a,i,c,l,d,h,u,b,p,f;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=((d=n.source)==null?void 0:d.id)||"",s=((h=n.source)==null?void 0:h.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,(f=n.data)==null?void 0:f.__internal__),o&&P)){const w=Ke().find(S=>S.id===o);w&&Do(w)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:g,mediaType:w,blob:S,mimeType:E}=n.data;if(g&&w&&S){const x=new Blob([S],{type:E||(w==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:H}=await Promise.resolve().then(()=>j);H(x,g,w)})()}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==="SW_BOOT_PROGRESS_GET"){const g=n.source;g==null||g.id,ps(g);return}if(n.data&&n.data.type==="GET_VERSION_STATE"){const g=n.source;g==null||g.id,n.waitUntil(de(g));return}if(n.data&&n.data.type==="SW_IDLE_PREFETCH_STATUS_GET"){const g=n.source;g==null||g.id,on(g);return}if(n.data&&n.data.type==="SW_PREFETCH_GROUPS"){const g=Array.isArray(n.data.groups)?n.data.groups.filter(w=>typeof w=="string"):[];n.waitUntil(mt(`message:${g.join(",")||"empty"}`,async()=>{await yt(`message:${g.join(",")||"empty"}`,g)}));return}if(n.data&&n.data.type==="CLAIM_CLIENTS"){n.waitUntil(W.clients.claim());return}if(n.data&&(n.data.type==="COMMIT_UPGRADE"||n.data.type==="SKIP_WAITING")){const g=n.source;g==null||g.id,n.waitUntil((async()=>{gt=!0,await Se({committedVersion:y,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(g),W.skipWaiting();const w=M();w&&w.sendSWUpdated(y)})())}else if(n.data&&n.data.type==="FORCE_UPGRADE")n.waitUntil((async()=>{gt=!0,await Se({committedVersion:y,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(n.source),W.skipWaiting();const g=M();g&&g.sendSWUpdated(y)})());else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:g}=n.data;g&&un(g).then(()=>{const w=M();w&&w.sendCacheDeleted(g)}).catch(w=>{console.error("Service Worker: Failed to delete cache:",w)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:g}=n.data;g&&Array.isArray(g)&&ko(g).then(()=>{}).catch(w=>{console.error("Service Worker: Failed to batch delete caches:",w)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")Oo().then(()=>{}).catch(g=>{console.error("Service Worker: Failed to clear all cache:",g)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){P=!0,We(!0),Ze(!0),te.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const g=M();g&&g.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){P=!1,We(!1),Ze(!1),Q.length=0,V.length=0,te.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const g=M();g&&g.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:g}=await Promise.resolve().then(()=>Ee),w=await g(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:w})}catch(g){console.error("[SW] Failed to get LLM API logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:g}=await Promise.resolve().then(()=>Ee);await g();const w=n.source;w&&w.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(g){console.error("[SW] Failed to clear LLM API logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const g=n.source;g&&g.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:P,swVersion:y,logs:V.slice(-100),consoleLogs:Q.slice(-100)});return}if(n.data&&n.data.type==="SW_DEBUG_GET_LOGS"){(async()=>{try{const{getInternalFetchLogs:g}=await Promise.resolve().then(()=>mr),w=en(),S=g(),E=n.source;E&&E.postMessage({type:"SW_DEBUG_LOGS",logs:[...w,...S.map(x=>({...x,type:"fetch"}))]})}catch(g){console.error("[SW] Failed to get fetch logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const g=n.source;g&&g.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:Q})}catch(g){console.error("[SW] Failed to get console logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const g=Ke(),w=n.source;w&&w.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:g})}catch(g){console.error("[SW] Failed to get postmessage logs:",g)}})();return}});const vo="MemorySnapshotDB",ge="snapshots",Es=50;async function ln(){return new Promise((n,e)=>{const t=indexedDB.open(vo,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 ln(),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=d=>{const h=d.target.result;h&&c<l&&(s.delete(h.value.id),c++,h.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 ln(),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 ln(),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 Mo=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function Po(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Io(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 d=s.transaction(r,"readonly");for(const h of r){const u=d.objectStore(h),b=u.count();b.onsuccess=()=>{const p=b.result;if(o+=p,p>0){const f=u.openCursor();let g=0;f.onsuccess=w=>{const S=w.target.result;if(S&&g<l)a+=Po(S.value),i++,g++,S.continue();else if(c++,c===r.length){s.close();const E=i>0?a/i:0,x=Math.round(E*o);e({count:o,totalSize:x})}},f.onerror=()=>{if(c++,c===r.length){s.close();const w=i>0?a/i:0,S=Math.round(w*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,f=Math.round(p*o);e({count:o,totalSize:f})}}}}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=[Vt,D,_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 d=l.headers.get("sw-image-size")||l.headers.get("content-length");d&&(i+=parseInt(d))}}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 Mo)try{const s=await Io(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function un(n){try{await(await caches.open(D)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function ko(n){try{const e=await caches.open(D);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 Oo(){try{const n=await caches.open(D),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 Wo(n,e,t){try{const s=M();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}function Bo(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=it(new URL(n,self.location.origin)).toString();if(!Bo(t))return;const s=M();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 xo(){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=M();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const ne=new Map,Rs=300*1e3,Ls=500;function No(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 Fo(n){const e=ne.get(n);return e?Date.now()-e>Rs?(ne.delete(n),!1):!0:!1}function vs(n){if(No(n)){if(ne.size>=Ls){const e=Date.now();for(const[t,s]of ne)e-s>Rs&&ne.delete(t);if(ne.size>=Ls){const t=Array.from(ne.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)ne.delete(r)}}ne.set(n,Date.now())}}W.addEventListener("fetch",n=>{const e=new URL(n.request.url),t=Date.now();if(e.protocol!=="http:"&&e.protocol!=="https:"){I({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(Fe=t,fo(n,e)){const s=`${e.pathname}${e.search}`;n.clientId,n.waitUntil(mt(`fetch-recheck:${s}`,async()=>{await yt(`fetch:${s}`)}))}if(e.pathname.startsWith(qn)||e.pathname.startsWith(jn)){const s=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(Uo(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(kr)){const s=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Ho(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"){I({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")){I({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")){I({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(Gr(e.hostname)){I({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&&Kr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=I({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(Vr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=I({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(Xr(e,n.request)){const s=Date.now(),r=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(Go(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&&$r(e,n.request)){if(Fo(n.request.url)){I({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=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(Ko(n.request).then(o=>(o.status===404&&vs(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 vs(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=I({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=Ro(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(P){if(Yr(e)){I({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=I({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((h,u)=>{a[u]=h}),["POST","PUT","PATCH"].includes(n.request.method))try{const h=n.request.headers.get("content-type")||"";h.includes("application/json")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):h.includes("application/x-www-form-urlencoded")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):o=`[${h||"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
|
-
${o}`:`XHR/API request (${n.request.method})`});const i=await fetch(n.request),c=i.clone();let l;const
|
|
5
|
+
${o}`:`XHR/API request (${n.request.method})`});const i=await fetch(n.request),c=i.clone();let l;const d={};i.headers.forEach((h,u)=>{d[u]=h});try{const h=i.headers.get("content-type")||"";h.includes("application/json")||h.includes("text/")?(l=await c.text(),l.length>5e3&&(l=l.substring(0,5e3)+"... (truncated)")):l=`[${h||"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:d,size:parseInt(i.headers.get("content-length")||"0"),details:o?`XHR/API request (${n.request.method})
|
|
6
6
|
|
|
7
7
|
Request Body:
|
|
8
8
|
${o}
|
|
@@ -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 v(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function xo(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(ct),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(se,i),a.set(we,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(ct)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function dn(n,e={}){return fetch(n,e)}async function No(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/")||Xt.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",u=new URL(t.toString());u.searchParams.delete("thumbnail"),u.searchParams.delete("bypass_sw"),u.searchParams.delete("direct_fetch"),u.searchParams.delete("_retry");const{findThumbnailWithFallback:g,createThumbnailResponse:f}=await Promise.resolve().then(()=>q),b=await g(u.toString(),l,[t.pathname]);if(b){const h=await b.response.blob();return f(h)}}try{const l=await caches.open(L);let u=await l.match(n.url);if(u||(u=await l.match(t.pathname)),u){const g=await u.blob();if(c&&!o){const{generateThumbnailAsync:f}=await Promise.resolve().then(()=>q);f(g,t.pathname,"image")}return o?ke(g,s,e):r?Ke(g,s,e):new Response(g,{status:200,statusText:"OK",headers:{"Content-Type":g.type||"image/png","Content-Length":g.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error("Service Worker: Media not found in cache:",{fullUrl:n.url,pathname:t.pathname}),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 Go(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:u}=await Promise.resolve().then(()=>q),g=await l(r,c,[r]);if(g){const f=await g.response.blob();return u(f)}}try{const l=await(await caches.open(L)).match(r);if(l){const u=await l.blob(),g=t.pathname.match(/\.(mp4|webm|mov)$/i),f=Xt.test(t.pathname);if(i&&!g){const{generateThumbnailAsync:b}=await Promise.resolve().then(()=>q);b(u,r,"image")}return g&&s?ke(u,s,e):f?Ke(u,s,e):new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":u.type||"application/octet-stream","Content-Length":u.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error(`Service Worker [Asset-${e}]: Asset not found in cache:`,r),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 Fo(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10),s=n.headers.get("range"),o=Yt(e).toString();try{const a=await caches.open(L);let i=await a.match(o);if(!i&&o!==n.url&&(i=await a.match(n.url)),i)try{const h=await i.clone().blob();return Ke(h,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(h=>{console.warn(`Service Worker [Audio-${t}]: Failed to cache opaque audio response:`,h)}),l;const u=await l.blob(),g=l.headers.get("Content-Type")||u.type||"audio/mpeg",f=Date.now().toString(),b=new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":g,"Content-Length":u.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length",[se]:f,[we]:f,"sw-image-size":u.size.toString()}});return await a.put(o,b.clone()),Ke(u,s,t,g)}catch(a){console.error(`Service Worker [Audio-${t}]: Audio loading failed:`,a);const i=await caches.open(L);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 Ke(l,s,t)}catch{return c}return new Response("Audio loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const yt=Symbol("VIDEO_LOAD_ERROR");async function Uo(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=Yt(e),c=i.toString();if(a){const f=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:b,createThumbnailResponse:h}=await Promise.resolve().then(()=>q),p=await b(c,f);if(p){const d=await p.response.blob();return h(d)}return(async()=>{try{const{generateThumbnailAsync:d}=await Promise.resolve().then(()=>q);d(new Blob([],{type:"video/mp4"}),c,"video",[f])}catch{return}})(),new Response("Thumbnail not ready",{status:404,statusText:"Thumbnail Not Ready",headers:{"Content-Type":"text/plain","Cache-Control":"no-store"}})}const l=Ne.get(c);if(l){l.count=(l.count||1)+1;const f=await l.promise;if(f===yt)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(f===null){const b={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,b)}return ke(f,s,t)}if(H.has(c)){const f=H.get(c);if(f)return f.timestamp=Date.now(),ke(f.blob,s,t)}try{const b=await(await caches.open(L)).match(c);if(b){const h=await b.blob();return h.size/(1024*1024)<50&&H.set(c,{blob:h,timestamp:Date.now()}),ke(h,s,t)}}catch{}const u=(async()=>{try{const f={method:"GET",mode:"cors",credentials:"omit",cache:"default"},b=new URL(i),h=await fetch(b,f);if(!h.ok)return yt;if(h.status===206)return null;const p=await h.blob();if(p.size/(1024*1024)<50){H.set(c,{blob:p,timestamp:Date.now()});try{const m=await caches.open(L),S=new Response(p,{headers:{"Content-Type":p.type||"video/mp4","Content-Length":p.size.toString(),[se]:Date.now().toString(),[we]:Date.now().toString(),"sw-video-size":p.size.toString()}});await m.put(c,S);const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>q);E(p,c,"video")}catch{}}return p}catch{return yt}})();Ne.set(c,{promise:u,timestamp:Date.now(),count:1,requestId:t}),u.finally(()=>{Ne.get(c)&&Ne.delete(c)});const g=await u;if(g===yt)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(g===null){const f={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,f)}return ke(g,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function ke(n,e,t){return Ls(n,e,t,n.type||"video/mp4")}function Ke(n,e,t,s){return Ls(n,e,t,s||n.type||"audio/mpeg")}function Ls(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 Ho(n){const e=new URL(n.url),t=mt(n.url),s=t.cacheKey,r=ve(e.pathname),o=Tr(n.mode,r),i=(await Ge()).committedVersion||C,c=rs(i),l=await caches.open(c);if(xe)try{const h=await dn(n);if(h&&h.status===200&&n.url.startsWith("http"))return l.put(n,h.clone()),h;if(!h.ok){let p=await l.match(n);return!p&&o&&(p=await l.match(B("/").href),p||(p=await l.match(B("index.html").href))),p||h}return h}catch{let p=await l.match(n);return!p&&o&&(p=await l.match(B("/").href),p||(p=await l.match(B("index.html").href))),p||(o?vs():new Response("Resource unavailable",{status:503}))}if(o){let h=await l.match(n);if(h||(h=await l.match(B("/").href)),h||(h=await l.match(B("index.html").href)),!h){const p=await caches.keys();for(const d of p)if(d.startsWith("drawnix-static-v"))try{const m=await caches.open(d);if(h=await m.match(n)||await m.match(B("/").href)||await m.match(B("index.html").href),h)break}catch{}}if(h)return h;try{const p=await dn(n,{cache:"reload"});if(p&&p.status===200&&n.url.startsWith("http")&&i===C){l.put(n,p.clone());const d=new URL(n.url);if(Dr(ve(d.pathname))){const m=B("/").href,S=B("index.html").href;n.url!==m&&l.put(m,p.clone()),n.url!==S&&l.put(S,p.clone())}return p}return p}catch{return vs()}}const{response:u,matchedBy:g}=await yo(l,n);if(u){if(!ws(n,u,i))return g==="normalized"&&y("handleStaticRequest: normalized static cache hit",{requestUrl:n.url,normalizedCacheKey:s}),u;await So(l,n,s)}const f=t.resourcePath;if(ps(n,e)){n.url!==s&&y("handleStaticRequest: cross-origin static cache miss",{requestUrl:n.url,normalizedCacheKey:s,resourcePath:f,committedVersion:i});const h=await bt(n,[s]);if(h)return h;const p=await wo(n,[s]);if(p)return p;const d=xn(e.pathname),m=d||i,S=await _o(l,n,f,m);return S||(ds("smart-cdn-resource-failed",n,{resourcePath:f,committedVersion:i,hasEmbeddedVersion:!!d,attemptedVersion:m}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}try{const h=await dn(n);if(Ve(n,e,h)){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const d=await bt(n,[s]);return d||new Response("Resource not found",{status:404,statusText:"Not Found"})}if(h&&h.status===200&&n.url.startsWith("http")&&i===C)return await cn(l,n,h,{source:"server",revision:"runtime",appVersion:i});if(h.status>=400){const d=await bt(n,[s]);if(d)return d}return h}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const p=await bt(n,[s]);return p||(ds("origin-fetch-exception",n,{resourcePath:f,committedVersion:i}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}}function vs(){return new Response(`<!DOCTYPE html>
|
|
14
|
+
${l}`}),i}catch(r){throw R(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function Go(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(we,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 dn(n,e={}){return fetch(n,e)}function St(n,e){const t=new URL(n.url);for(const s of["thumbnail","bypass_sw","direct_fetch","_retry"])t.searchParams.delete(s);return Array.from(new Set([e.pathname,t.toString(),n.url]))}async function Ms(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 Uo(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/")||Qt.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",d=new URL(t.toString());d.searchParams.delete("thumbnail"),d.searchParams.delete("bypass_sw"),d.searchParams.delete("direct_fetch"),d.searchParams.delete("_retry");const{findThumbnailWithFallback:h,createThumbnailResponse:u}=await Promise.resolve().then(()=>j),b=await h(d.toString(),l,[t.pathname]);if(b){const p=await caches.open(D),f=St(new Request(d.toString()),d);await Ms(p,f)||await fe(d.toString(),"thumbnail_exists_original_missing");const g=await b.response.blob();return u(g)}}try{const l=await caches.open(D);let d;for(const h of St(n,t))if(d=await l.match(h),d)break;if(d){const h=await d.blob();if(c&&!o){const{generateThumbnailAsync:u}=await Promise.resolve().then(()=>j);u(h,t.pathname,"image")}return o?Ie(h,s,e):r?$e(h,s,e):new Response(h,{status:200,statusText:"OK",headers:{"Content-Type":h.type||"image/png","Content-Length":h.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 Ho(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:d}=await Promise.resolve().then(()=>j),h=await l(r,c,[r]);if(h){const u=await caches.open(D),b=St(new Request(t.toString(),{method:n.method}),t);await Ms(u,b)||await fe(t.pathname,"thumbnail_exists_original_missing");const p=await h.response.blob();return d(p)}}try{const c=await caches.open(D);let l;for(const d of St(n,t))if(l=await c.match(d),l)break;if(l){const d=await l.blob(),h=t.pathname.match(/\.(mp4|webm|mov)$/i),u=Qt.test(t.pathname);if(i&&!h){const{generateThumbnailAsync:b}=await Promise.resolve().then(()=>j);b(d,r,"image")}return h&&s?Ie(d,s,e):u?$e(d,s,e):new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":d.type||"application/octet-stream","Content-Length":d.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=it(e).toString();try{const a=await caches.open(D);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 $e(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 d=await l.blob(),h=l.headers.get("Content-Type")||d.type||"audio/mpeg",u=Date.now().toString(),b=new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":h,"Content-Length":d.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length",[le]:u,[we]:u,"sw-image-size":d.size.toString()}});return await a.put(o,b.clone()),$e(d,s,t,h)}catch(a){console.error(`Service Worker [Audio-${t}]: Audio loading failed:`,a);const i=await caches.open(D);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 $e(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 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=it(e),c=i.toString();if(a){const u=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:b,createThumbnailResponse:p}=await Promise.resolve().then(()=>j),f=await b(c,u);if(f){const g=await f.response.blob();return p(g)}return(async()=>{try{const{generateThumbnailAsync:g}=await Promise.resolve().then(()=>j);g(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 Ie(u,s,t)}if(U.has(c)){const u=U.get(c);if(u)return u.timestamp=Date.now(),Ie(u.blob,s,t)}try{const b=await(await caches.open(D)).match(c);if(b){const p=await b.blob();return p.size/(1024*1024)<50&&U.set(c,{blob:p,timestamp:Date.now()}),Ie(p,s,t)}}catch{}const d=(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 f=await p.blob();if(f.size/(1024*1024)<50){U.set(c,{blob:f,timestamp:Date.now()});try{const w=await caches.open(D),S=new Response(f,{headers:{"Content-Type":f.type||"video/mp4","Content-Length":f.size.toString(),[le]:Date.now().toString(),[we]:Date.now().toString(),"sw-video-size":f.size.toString()}});await w.put(c,S);const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(f,c,"video")}catch{}}return f}catch{return Ct}})();xe.set(c,{promise:d,timestamp:Date.now(),count:1,requestId:t}),d.finally(()=>{xe.get(c)&&xe.delete(c)});const h=await d;if(h===Ct)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(h===null){const u={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,u)}return Ie(h,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function Ie(n,e,t){return Ps(n,e,t,n.type||"video/mp4")}function $e(n,e,t,s){return Ps(n,e,t,s||n.type||"audio/mpeg")}function Ps(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=bt(n.url),s=t.cacheKey,r=Re(e.pathname),o=Ar(n.mode,r),i=(await Ne()).committedVersion||y,c=as(i),l=await caches.open(c);if(Be)try{const p=await dn(n);if(p&&p.status===200&&n.url.startsWith("http"))return l.put(n,p.clone()),p;if(!p.ok){let f=await l.match(n);return!f&&o&&(f=await l.match(B("/").href),f||(f=await l.match(B("index.html").href))),f||p}return p}catch{let f=await l.match(n);return!f&&o&&(f=await l.match(B("/").href),f||(f=await l.match(B("index.html").href))),f||(o?Is():new Response("Resource unavailable",{status:503}))}if(o){let p=await l.match(n);if(p||(p=await l.match(B("/").href)),p||(p=await l.match(B("index.html").href)),!p){const f=await caches.keys();for(const g of f)if(g.startsWith("drawnix-static-v"))try{const w=await caches.open(g);if(p=await w.match(n)||await w.match(B("/").href)||await w.match(B("index.html").href),p)break}catch{}}if(p)return p;try{const f=await dn(n,{cache:"reload"});if(f&&f.status===200&&n.url.startsWith("http")&&i===y){l.put(n,f.clone());const g=new URL(n.url);if(Rr(Re(g.pathname))){const w=B("/").href,S=B("index.html").href;n.url!==w&&l.put(w,f.clone()),n.url!==S&&l.put(S,f.clone())}return f}return f}catch{return Is()}}const{response:d,matchedBy:h}=await So(l,n);if(d){if(!Cs(n,d,i))return h==="normalized"&&(n.url,void 0),d;await Co(l,n,s)}const u=t.resourcePath;if(ws(n,e)){n.url!==s&&(n.url,void 0);const p=await wt(n,[s]);if(p)return p;const f=await yo(n,[s]);if(f)return f;const g=xn(e.pathname),w=g||i,S=await Ao(l,n,u,w);return S||(fs("smart-cdn-resource-failed",n,{resourcePath:u,committedVersion:i,hasEmbeddedVersion:!!g,attemptedVersion:w}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}try{const p=await dn(n);if(ze(n,e,p)){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const g=await wt(n,[s]);return g||new Response("Resource not found",{status:404,statusText:"Not Found"})}if(p&&p.status===200&&n.url.startsWith("http")&&i===y)return await cn(l,n,p,{source:"server",revision:"runtime",appVersion:i});if(p.status>=400){const g=await wt(n,[s]);if(g)return g}return p}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const f=await wt(n,[s]);return f||(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 Is(){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 v(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,Ms=3e4;function Ps(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function qo(){const n=Date.now(),e=[];if(H.forEach((t,s)=>{n-t.timestamp>Wr&&e.push(s)}),e.length>0&&e.forEach(t=>H.delete(t)),H.size>$n){const t=Array.from(H.entries()).sort((o,a)=>o[1].timestamp-a[1].timestamp),s=H.size-$n,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>H.delete(o))}}function jo(){const n=Date.now(),e=[];z.forEach((s,r)=>{n-s.timestamp>Ms&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>z.delete(s)));const t=[];ye.forEach((s,r)=>{n-s.timestamp>zn&&t.push(r)}),t.length>0&&t.forEach(s=>ye.delete(s)),qo()}async function zo(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=Yt(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:f,createThumbnailResponse:b}=await Promise.resolve().then(()=>q),h=await f(l,a,[n.url,c.url]);if(h){const p=await h.response.blob();return b(p)}}const u=ye.get(l);if(u){if(Date.now()-u.timestamp<zn)return u.response.clone();ye.delete(l)}if(z.has(l)){const f=z.get(l);if(f){const b=Date.now()-f.timestamp;if(b>Ms)console.warn(`Service Worker [${e}]: 发现过期的 pending 请求 (${b}ms),清理并重新发起:`,l),z.delete(l);else{f.count=(f.count||1)+1,f.duplicateRequestIds=f.duplicateRequestIds||[],f.duplicateRequestIds.push(e);try{const h=await Ps(f.promise,hn,"Image request timeout");return h&&h.clone?h.clone():h}catch(h){if(h.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 重复请求等待超时,清理并返回超时响应让前端直接加载`),z.delete(l),Is(n.url,e);throw h}}}}jo();const g=$o(c,n.url,l,e,s,o?a:void 0);z.set(l,{promise:g,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),g.then(f=>{f&&f.ok&&ye.set(l,{response:f.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{z.get(l)&&z.delete(l)});try{return await Ps(g,hn,"Image request timeout")}catch(f){if(f.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${hn}ms),清理并返回超时响应让前端直接加载:`,n.url),z.delete(l),Is(n.url,e);throw f}}catch(e){throw e}}function Is(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 $o(n,e,t,s,r=!1,o){try{const a=await caches.open(L);if(!r){let p=await a.match(n);if(p||(p=await a.match(n.url)),!p&&e!==n.url&&(p=await a.match(e)),p||(p=await a.match(t)),p){const m=await p.clone().blob();if(m.size===0)console.warn(`Service Worker [${s}]: 检测到空缓存,删除并重新获取:`,e),await a.delete(n);else{if(o){const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>q);E(m,n.url,"image")}const S=p.headers.get(se);if(S){const E=Date.now(),A=p.headers.get(we)||S,j=new Response(m,{status:p.status,statusText:p.statusText,headers:{...Object.fromEntries(p.headers.entries()),[se]:E.toString(),[we]:A}});return n.url.startsWith("http")&&(await a.put(t,j.clone()),e!==t&&await a.delete(e)),j}else{const E=new Response(m,{status:p.status,statusText:p.statusText,headers:{...Object.fromEntries(p.headers.entries()),[se]:Date.now().toString(),[we]: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=ss(i);let l=null,u=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),Me.has(c.hostname)&&(u=!0));let g;const f=[{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;u?b=[l]:(b=[e],l&&b.push(l));let h=null;for(let p=0;p<b.length;p++){const d=b[p],m=p>0;for(const S of f)try{let E,A=!1;for(let j=0;j<=2;j++)try{if(g=await fetch(d,S),g&&(g.status!==0||g.type==="opaque"))break}catch(oe){E=oe;const Oe=oe.message||"";if(Oe.includes("CORS")||Oe.includes("cross-origin")||Oe.includes("Access-Control-Allow-Origin")||Oe.includes("Failed to fetch")||Oe.includes("NetworkError")||Oe.includes("TypeError")){A=!0;break}j<2&&await new Promise(ua=>setTimeout(ua,Math.pow(2,j)*1e3))}if(A){const j=new URL(d).hostname;Vn(j);try{const oe=await fetch(e,{mode:"no-cors",credentials:"omit",referrerPolicy:"no-referrer"});if(oe.type==="opaque")return oe}catch(oe){console.warn(`Service Worker [${s}]: no-cors 模式也失败:`,oe)}return new Response(null,{status:200,headers:{"Content-Type":"image/png","X-SW-CORS-Bypass":"true"}})}if(g&&(g.status!==0||g.type==="opaque"))break;E&&(h=E)}catch(E){h=E;continue}if(g&&(g.status!==0||g.type==="opaque"))break;c&&c.fallbackDomain&&p===0&&!u&&(Me.add(c.hostname),Yr(c.hostname).catch(S=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",S)}))}if(!g||g.status===0&&g.type!=="opaque"){let p="All fetch attempts failed";return c&&c.fallbackDomain&&(u?p=`备用域名${c.fallbackDomain}也失败了`:p=`All fetch attempts failed for both ${c.hostname} and ${c.fallbackDomain} domains`),console.error(`Service Worker [${s}]: ${p}`,h),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(g.type==="opaque"){const p=new URL(e).hostname;return Vn(p),g}if(g.ok){const d=await g.clone().blob(),m=d.size/(1024*1024),S=new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":g.headers.get("Content-Type")||"image/png","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*","Cache-Control":"max-age=3153600000",[se]:Date.now().toString(),[we]:Date.now().toString(),"sw-image-size":d.size.toString()}});try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await Ds(t,d.size,d.type),await Oo();const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>q);E(d,t,"image")}}catch(E){console.warn(`Service Worker: Failed to cache normal response (${m.toFixed(2)}MB, 可能超出存储限制):`,E),await Jr(a);try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await Ds(t,d.size,d.type);const{generateThumbnailAsync:A}=await Promise.resolve().then(()=>q);A(d,t,"image")}}catch(A){console.error("Service Worker: Still failed to cache after cleanup:",A)}}return S}throw new Error(`HTTP ${g.status}: ${g.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")?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 R=Object.freeze(Object.defineProperty({__proto__:null,APP_VERSION:C,IMAGE_CACHE_NAME:L,addConsoleLog:Jt,clearAllConsoleLogs:Jn,clearConsoleLogs:ns,clearCrashSnapshots:Es,clearDebugLogs:ts,deleteCacheByUrl:un,disableDebugMode:tn,enableDebugMode:en,getCDNStatusReport:rt,getCacheStats:Ts,getCrashSnapshots:Cs,getDebugLogs:Zt,getDebugStatus:es,getInternalFetchLogs:Pt,loadConsoleLogsFromDB:Yn,performHealthCheck:Ft,resetCDNStatus:Ut,saveCrashSnapshot:Ss},Symbol.toStringTag,{value:"Module"})),St="drawnix-images-thumb",ks=128,gn=400,Vo=.8;function Ko(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 Os(n,e,t=["small","large"]){try{for(const s of t)await Xo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Xo(n,e,t){try{const s=t==="large"?gn:ks,r=fn(e,t),o=await caches.open(St);let a=await o.match(r);if(!a){const d=new Request(r,{method:"GET"});a=await o.match(d)}if(!a)try{const d=new URL(r);a=await o.match(d.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(d){if(d instanceof Error&&d.name==="InvalidStateError")return;throw d}const{width:l,height:u}=Ko(c.width,c.height,s),g=new OffscreenCanvas(l,u),f=g.getContext("2d");if(!f){console.warn("[ThumbnailUtils] Failed to get canvas context");return}try{f.drawImage(c,0,0,l,u)}finally{c.close()}const b=await g.convertToBlob({type:"image/jpeg",quality:Vo}),h=()=>new Response(b,{headers:{"Content-Type":"image/jpeg","Content-Length":b.size.toString()}}),p=new Request(r,{method:"GET"});await o.put(p,h()),await o.put(r,h());try{const d=new URL(r);(d.pathname.startsWith("/__aitu_cache__/")||d.pathname.startsWith("/asset-library/"))&&await o.put(r,h())}catch{}}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Ws(n,e,t=["small","large"]){try{for(const s of t)await Yo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function Yo(n,e,t){try{const s=fn(e,t),r=await caches.open(St);let o=await r.match(s);if(!o){const u=new Request(s,{method:"GET"});o=await r.match(u)}if(!o)try{const u=new URL(s);o=await r.match(u.pathname)}catch{}if(o)return;const i=await Qo(e,n,t==="large"?gn:ks);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 u=new URL(s);(u.pathname.startsWith("/__aitu_cache__/")||u.pathname.startsWith("/asset-library/"))&&await r.put(s,c())}catch{}}catch(s){console.warn(`[ThumbnailUtils] ❌ Failed to generate ${t} video thumbnail:`,s)}}async function Qo(n,e,t=gn){const{getChannelManager:s}=await Promise.resolve().then(()=>dr),r=s();if(!r||r.getConnectedClientCount()===0)return console.warn("[ThumbnailUtils] No connected clients for video thumbnail generation"),null;const o=await r.requestVideoThumbnail(n,3e4,t);if(!o)return null;try{return await(await fetch(o)).blob()}catch(a){return console.warn("[ThumbnailUtils] Failed to convert thumbnail URL to blob:",a),null}}async function pn(n,e,t){try{const s=await caches.open(St),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 Jo(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 Zo(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 ea(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await Os(n,e,s):await Ws(n,e,s)}catch(r){console.warn(`[ThumbnailUtils] Failed to generate ${t} thumbnail:`,r)}})()}const q=Object.freeze(Object.defineProperty({__proto__:null,IMAGE_CACHE_NAME_THUMB:St,createThumbnailResponse:Zo,findThumbnail:pn,findThumbnailWithFallback:Jo,generateImageThumbnail:Os,generateThumbnailAsync:ea,generateVideoThumbnail:Ws},Symbol.toStringTag,{value:"Module"})),pe=[],ta="llm-api-logs",na=4,X="logs";function Ct(){return new Promise((n,e)=>{const t=indexedDB.open(ta,na);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(X))a=r.createObjectStore(X,{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(X),o<4&&!a.indexNames.contains("taskId")&&(a.createIndex("taskId","taskId",{unique:!1}),console.log("[LLMApiLogger] Created taskId index during upgrade to v4")))}}})}async function Bs(){try{const s=(await Ct()).transaction(X,"readonly").objectStore(X).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 sa(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 ra(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 oa(n=1,e=20,t){let s=await Bs();t!=null&&t.taskType&&(s=s.filter(c=>ra(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(sa),total:r,page:n,pageSize:e,totalPages:o}}async function aa(n){const e=pe.find(t=>t.id===n);if(e)return e;try{const r=(await Ct()).transaction(X,"readonly").objectStore(X);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 ia(){pe.length=0;try{const e=(await Ct()).transaction(X,"readwrite");e.objectStore(X).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 ca(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 Ct()).transaction(X,"readwrite"),a=o.objectStore(X);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 la(n){}const De=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:ia,deleteLLMApiLogs:ca,getAllLLMApiLogs:Bs,getLLMApiLogById:aa,getLLMApiLogsPaginated:oa,setLLMApiLogBroadcast:la},Symbol.toStringTag,{value:"Module"}));return D.APP_VERSION=C,D.IMAGE_CACHE_NAME=L,D.addConsoleLog=Jt,D.clearAllConsoleLogs=Jn,D.clearConsoleLogs=ns,D.clearCrashSnapshots=Es,D.clearDebugLogs=ts,D.deleteCacheByUrl=un,D.disableDebugMode=tn,D.enableDebugMode=en,D.getCDNStatusReport=rt,D.getCacheStats=Ts,D.getCrashSnapshots=Cs,D.getDebugLogs=Zt,D.getDebugStatus=es,D.getInternalFetchLogs=Pt,D.loadConsoleLogsFromDB=Yn,D.performHealthCheck=Ft,D.resetCDNStatus=Ut,D.saveCrashSnapshot=Ss,Object.defineProperty(D,Symbol.toStringTag,{value:"Module"}),D})({});
|
|
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 $o(){const n=Date.now(),e=[];if(U.forEach((t,s)=>{n-t.timestamp>Nr&&e.push(s)}),e.length>0&&e.forEach(t=>U.delete(t)),U.size>Kn){const t=Array.from(U.entries()).sort((o,a)=>o[1].timestamp-a[1].timestamp),s=U.size-Kn,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>U.delete(o))}}function Vo(){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=[];ye.forEach((s,r)=>{n-s.timestamp>zn&&t.push(r)}),t.length>0&&t.forEach(s=>ye.delete(s)),$o()}async function Ko(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=it(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 f=await p.response.blob();return b(f)}}const d=ye.get(l);if(d){if(Date.now()-d.timestamp<zn)return d.response.clone();ye.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}}}}Vo();const h=Xo(c,n.url,l,e,s,o?a:void 0);q.set(l,{promise:h,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),h.then(u=>{u&&u.ok&&ye.set(l,{response:u.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{q.get(l)&&q.delete(l)});try{return await Os(h,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 Xo(n,e,t,s,r=!1,o){try{const a=await caches.open(D);if(!r){let f=await a.match(n);if(f||(f=await a.match(n.url)),!f&&e!==n.url&&(f=await a.match(e)),f||(f=await a.match(t)),f){const w=await f.clone().blob();if(w.size===0)console.warn(`Service Worker [${s}]: 检测到空缓存,删除并重新获取:`,e),await a.delete(n);else{if(o){const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(w,n.url,"image")}const S=f.headers.get(le);if(S){const E=Date.now(),x=f.headers.get(we)||S,H=new Response(w,{status:f.status,statusText:f.statusText,headers:{...Object.fromEntries(f.headers.entries()),[le]:E.toString(),[we]:x}});return n.url.startsWith("http")&&(await a.put(t,H.clone()),e!==t&&await a.delete(e)),H}else{const E=new Response(w,{status:f.status,statusText:f.statusText,headers:{...Object.fromEntries(f.headers.entries()),[le]:Date.now().toString(),[we]: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,d=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),Le.has(c.hostname)&&(d=!0));let h;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;d?b=[l]:(b=[e],l&&b.push(l));let p=null;for(let f=0;f<b.length;f++){const g=b[f],w=f>0;for(const S of u)try{let E,x=!1;for(let H=0;H<=2;H++)try{if(h=await fetch(g,S),h&&(h.status!==0||h.type==="opaque"))break}catch(se){E=se;const ke=se.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")){x=!0;break}H<2&&await new Promise(ga=>setTimeout(ga,Math.pow(2,H)*1e3))}if(x){const H=new URL(g).hostname;Xn(H);try{const se=await fetch(e,{mode:"no-cors",credentials:"omit",referrerPolicy:"no-referrer"});if(se.type==="opaque")return await fe(e,"cors_opaque"),se}catch(se){console.warn(`Service Worker [${s}]: no-cors 模式也失败:`,se)}return await fe(e,"cors_fetch_failed"),new Response(null,{status:200,headers:{"Content-Type":"image/png","X-SW-CORS-Bypass":"true"}})}if(h&&(h.status!==0||h.type==="opaque"))break;E&&(p=E)}catch(E){p=E;continue}if(h&&(h.status!==0||h.type==="opaque"))break;c&&c.fallbackDomain&&f===0&&!d&&(Le.add(c.hostname),Zr(c.hostname).catch(S=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",S)}))}if(!h||h.status===0&&h.type!=="opaque"){let f="All fetch attempts failed";return c&&c.fallbackDomain&&(d?f=`备用域名${c.fallbackDomain}也失败了`:f=`All fetch attempts failed for both ${c.hostname} and ${c.fallbackDomain} domains`),console.error(`Service Worker [${s}]: ${f}`,p),await fe(t,f),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(h.type==="opaque"){const f=new URL(e).hostname;return Xn(f),await fe(t,"cors_opaque"),h}if(h.ok){const g=await h.clone().blob(),w=g.size/(1024*1024),S=new Response(g,{status:200,statusText:"OK",headers:{"Content-Type":h.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(),[we]:Date.now().toString(),"sw-image-size":g.size.toString()}});try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await Wo(t,g.size,g.type),await xo();const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>j);E(g,t,"image")}}catch(E){console.warn(`Service Worker: Failed to cache normal response (${w.toFixed(2)}MB, 可能超出存储限制):`,E),await fe(t,String(E))}return S}throw new Error(`HTTP ${h.status}: ${h.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 A=Object.freeze(Object.defineProperty({__proto__:null,APP_VERSION:y,IMAGE_CACHE_NAME:D,addConsoleLog:Zt,clearAllConsoleLogs:es,clearConsoleLogs:rs,clearCrashSnapshots:Ds,clearDebugLogs:ss,deleteCacheByUrl:un,disableDebugMode:nn,enableDebugMode:tn,getCDNStatusReport:nt,getCacheStats:As,getCrashSnapshots:_s,getDebugLogs:en,getDebugStatus:ns,getInternalFetchLogs:kt,loadConsoleLogsFromDB:Jn,performHealthCheck:Ht,resetCDNStatus:qt,saveCrashSnapshot:Ts},Symbol.toStringTag,{value:"Module"})),Et="drawnix-images-thumb",Bs=128,gn=400,Yo=.8;function Qo(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 xs(n,e,t=["small","large"]){try{for(const s of t)await Jo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Jo(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 g=new Request(r,{method:"GET"});a=await o.match(g)}if(!a)try{const g=new URL(r);a=await o.match(g.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(g){if(g instanceof Error&&g.name==="InvalidStateError")return;throw g}const{width:l,height:d}=Qo(c.width,c.height,s),h=new OffscreenCanvas(l,d),u=h.getContext("2d");if(!u){console.warn("[ThumbnailUtils] Failed to get canvas context");return}try{u.drawImage(c,0,0,l,d)}finally{c.close()}const b=await h.convertToBlob({type:"image/jpeg",quality:Yo}),p=()=>new Response(b,{headers:{"Content-Type":"image/jpeg","Content-Length":b.size.toString()}}),f=new Request(r,{method:"GET"});await o.put(f,p()),await o.put(r,p());try{const g=new URL(r);(g.pathname.startsWith("/__aitu_cache__/")||g.pathname.startsWith("/asset-library/"))&&await o.put(r,p())}catch{}}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Ns(n,e,t=["small","large"]){try{for(const s of t)await Zo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function Zo(n,e,t){try{const s=fn(e,t),r=await caches.open(Et);let o=await r.match(s);if(!o){const d=new Request(s,{method:"GET"});o=await r.match(d)}if(!o)try{const d=new URL(s);o=await r.match(d.pathname)}catch{}if(o)return;const i=await ea(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 d=new URL(s);(d.pathname.startsWith("/__aitu_cache__/")||d.pathname.startsWith("/asset-library/"))&&await r.put(s,c())}catch{}}catch(s){console.warn(`[ThumbnailUtils] ❌ Failed to generate ${t} video thumbnail:`,s)}}async function ea(n,e,t=gn){const{getChannelManager:s}=await Promise.resolve().then(()=>fr),r=s();if(!r||r.getConnectedClientCount()===0)return console.warn("[ThumbnailUtils] No connected clients for video thumbnail generation"),null;const o=await r.requestVideoThumbnail(n,3e4,t);if(!o)return null;try{return await(await fetch(o)).blob()}catch(a){return console.warn("[ThumbnailUtils] Failed to convert thumbnail URL to blob:",a),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 ta(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 na(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 sa(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await xs(n,e,s):await Ns(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:na,findThumbnail:pn,findThumbnailWithFallback:ta,generateImageThumbnail:xs,generateThumbnailAsync:sa,generateVideoThumbnail:Ns},Symbol.toStringTag,{value:"Module"})),pe=[],ra="llm-api-logs",oa=4,K="logs";function Tt(){return new Promise((n,e)=>{const t=indexedDB.open(ra,oa);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 aa(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 ia(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 ca(n=1,e=20,t){let s=await Fs();t!=null&&t.taskType&&(s=s.filter(c=>ia(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(aa),total:r,page:n,pageSize:e,totalPages:o}}async function la(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 ua(){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 da(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 ha(n){}const Ee=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:ua,deleteLLMApiLogs:da,getAllLLMApiLogs:Fs,getLLMApiLogById:la,getLLMApiLogsPaginated:ca,setLLMApiLogBroadcast:ha},Symbol.toStringTag,{value:"Module"}));return T.APP_VERSION=y,T.IMAGE_CACHE_NAME=D,T.addConsoleLog=Zt,T.clearAllConsoleLogs=es,T.clearConsoleLogs=rs,T.clearCrashSnapshots=Ds,T.clearDebugLogs=ss,T.deleteCacheByUrl=un,T.disableDebugMode=nn,T.enableDebugMode=tn,T.getCDNStatusReport=nt,T.getCacheStats=As,T.getCrashSnapshots=_s,T.getDebugLogs=en,T.getDebugStatus=ns,T.getInternalFetchLogs=kt,T.loadConsoleLogsFromDB=Jn,T.performHealthCheck=Ht,T.resetCDNStatus=qt,T.saveCrashSnapshot=Ts,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"}),T})({});
|