@axhub/genie 0.2.11 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/api-docs.html +2 -2
  2. package/dist/assets/App-Clb2COtW.js +274 -0
  3. package/dist/assets/ImagePlaygroundPage-DqhMSbM8.js +106 -0
  4. package/dist/assets/ImagePlaygroundPage-MEn3NN80.css +1 -0
  5. package/dist/assets/ReviewApp-CDcLYe-u.js +1 -0
  6. package/dist/assets/{_basePickBy-BDnj7-0Z.js → _basePickBy-jUZsM51q.js} +1 -1
  7. package/dist/assets/{_baseUniq-Bl0JKOyl.js → _baseUniq-BXglE6_v.js} +1 -1
  8. package/dist/assets/{arc-DY-4Kev3.js → arc-D-oFCFBv.js} +1 -1
  9. package/dist/assets/{architectureDiagram-2XIMDMQ5-qw7crNVd.js → architectureDiagram-2XIMDMQ5-DC8bAnQt.js} +1 -1
  10. package/dist/assets/{blockDiagram-WCTKOSBZ-B9xg7ep3.js → blockDiagram-WCTKOSBZ-C4semIRc.js} +1 -1
  11. package/dist/assets/{c4Diagram-IC4MRINW-H9xp3ytb.js → c4Diagram-IC4MRINW-FHj1QO3y.js} +1 -1
  12. package/dist/assets/channel-BF4woPXX.js +1 -0
  13. package/dist/assets/{chunk-4BX2VUAB-B3EVDUxI.js → chunk-4BX2VUAB-D-LjsQ_s.js} +1 -1
  14. package/dist/assets/{chunk-55IACEB6-CGv945ef.js → chunk-55IACEB6-DI3j_d7A.js} +1 -1
  15. package/dist/assets/{chunk-FMBD7UC4-uAT4CKWM.js → chunk-FMBD7UC4-BEVnaLFN.js} +1 -1
  16. package/dist/assets/{chunk-JSJVCQXG-Cbvlpkf7.js → chunk-JSJVCQXG-CSxpcErk.js} +1 -1
  17. package/dist/assets/{chunk-KX2RTZJC-CcqIuGat.js → chunk-KX2RTZJC-BbuhDN4h.js} +1 -1
  18. package/dist/assets/{chunk-NQ4KR5QH-CgrcsRuX.js → chunk-NQ4KR5QH-C3x61XQa.js} +1 -1
  19. package/dist/assets/{chunk-QZHKN3VN-Cx0APOoV.js → chunk-QZHKN3VN-DxWOFtPh.js} +1 -1
  20. package/dist/assets/{chunk-WL4C6EOR-BbZirvBk.js → chunk-WL4C6EOR-Bt2OauD2.js} +1 -1
  21. package/dist/assets/classDiagram-VBA2DB6C-D2kHlnQ7.js +1 -0
  22. package/dist/assets/classDiagram-v2-RAHNMMFH-D2kHlnQ7.js +1 -0
  23. package/dist/assets/clone-CqBvwCJW.js +1 -0
  24. package/dist/assets/{cose-bilkent-S5V4N54A-CrvmGFLD.js → cose-bilkent-S5V4N54A-Dexadrue.js} +1 -1
  25. package/dist/assets/{dagre-KLK3FWXG-C-W6VPjS.js → dagre-KLK3FWXG-F9U4X2xC.js} +1 -1
  26. package/dist/assets/{diagram-E7M64L7V-IP2q3bL0.js → diagram-E7M64L7V-B3V17aH3.js} +1 -1
  27. package/dist/assets/{diagram-IFDJBPK2-CQaL-XyV.js → diagram-IFDJBPK2-CdHAmLL1.js} +1 -1
  28. package/dist/assets/{diagram-P4PSJMXO-BxBLThfv.js → diagram-P4PSJMXO-CrTNfk8K.js} +1 -1
  29. package/dist/assets/{erDiagram-INFDFZHY-Dyl7bJTt.js → erDiagram-INFDFZHY-vDh9SWK9.js} +1 -1
  30. package/dist/assets/{flowDiagram-PKNHOUZH-B7NFMgFK.js → flowDiagram-PKNHOUZH-DpltMg7L.js} +1 -1
  31. package/dist/assets/{ganttDiagram-A5KZAMGK-hReWSDu2.js → ganttDiagram-A5KZAMGK-COTk2xur.js} +1 -1
  32. package/dist/assets/{gitGraphDiagram-K3NZZRJ6-gVgcr0ST.js → gitGraphDiagram-K3NZZRJ6-BNV7bvvj.js} +1 -1
  33. package/dist/assets/{graph-DNDiJhTn.js → graph-Dkeg9oys.js} +1 -1
  34. package/dist/assets/{highlighted-body-TPN3WLV5-DclLmTou.js → highlighted-body-TPN3WLV5-DaiQEBwR.js} +1 -1
  35. package/dist/assets/index-DgGmiqsP.css +1 -0
  36. package/dist/assets/index-DvA901Vs.js +2 -0
  37. package/dist/assets/{infoDiagram-LFFYTUFH-CqQOOzDA.js → infoDiagram-LFFYTUFH-CZioW3Gt.js} +1 -1
  38. package/dist/assets/{ishikawaDiagram-PHBUUO56-CZ0iLiHg.js → ishikawaDiagram-PHBUUO56-BbqR3i1B.js} +1 -1
  39. package/dist/assets/{journeyDiagram-4ABVD52K-DdfYKfNh.js → journeyDiagram-4ABVD52K-wfb-WHzl.js} +1 -1
  40. package/dist/assets/{kanban-definition-K7BYSVSG-C5Vf32u6.js → kanban-definition-K7BYSVSG-B3c4y3VN.js} +1 -1
  41. package/dist/assets/{layout-rvTEu2KS.js → layout-Xr9Z2VGF.js} +1 -1
  42. package/dist/assets/{linear-CD9SiYze.js → linear-JBmzAJtl.js} +1 -1
  43. package/dist/assets/{mermaid-O7DHMXV3-OZ8qWWwa.js → mermaid-O7DHMXV3-fDuyNLKe.js} +230 -222
  44. package/dist/assets/{mindmap-definition-YRQLILUH-CQxrLNVc.js → mindmap-definition-YRQLILUH-B5NTN_jD.js} +1 -1
  45. package/dist/assets/{pieDiagram-SKSYHLDU-XgAUByWg.js → pieDiagram-SKSYHLDU-CuO98GVu.js} +1 -1
  46. package/dist/assets/{quadrantDiagram-337W2JSQ-CH16ls7G.js → quadrantDiagram-337W2JSQ-LL3f4vLf.js} +1 -1
  47. package/dist/assets/{requirementDiagram-Z7DCOOCP-B_kQO06L.js → requirementDiagram-Z7DCOOCP-Di-2O6LH.js} +1 -1
  48. package/dist/assets/{sankeyDiagram-WA2Y5GQK-ofe78CyS.js → sankeyDiagram-WA2Y5GQK-9lHqrXqR.js} +1 -1
  49. package/dist/assets/{sequenceDiagram-2WXFIKYE-Ckbxwny6.js → sequenceDiagram-2WXFIKYE-BQu-SoGr.js} +1 -1
  50. package/dist/assets/{stateDiagram-RAJIS63D-DNtzCk14.js → stateDiagram-RAJIS63D-BUxvd2BC.js} +1 -1
  51. package/dist/assets/stateDiagram-v2-FVOUBMTO-CDVexTiR.js +1 -0
  52. package/dist/assets/{timeline-definition-YZTLITO2-zT6CklKt.js → timeline-definition-YZTLITO2-oP47UEU6.js} +1 -1
  53. package/dist/assets/{treemap-KZPCXAKY-y0U2c3xG.js → treemap-KZPCXAKY-BRjDo2aE.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-CMHSJ_9p.js → vendor-codemirror-BiCeS-y4.js} +1 -1
  55. package/dist/assets/{vendor-react-xmA_f8ig.js → vendor-react-DVlYPmi3.js} +1 -1
  56. package/dist/assets/{vennDiagram-LZ73GAT5-xKj3SjYG.js → vennDiagram-LZ73GAT5-DrRqcDqo.js} +1 -1
  57. package/dist/assets/{xychartDiagram-JWTSCODW-Da_qyEoX.js → xychartDiagram-JWTSCODW-DUXrymAi.js} +1 -1
  58. package/dist/index.html +4 -4
  59. package/package.json +25 -6
  60. package/scripts/refresh-acp-default-capabilities.mjs +160 -0
  61. package/server/acp-runtime/client.js +1137 -181
  62. package/server/acp-runtime/command-overrides.js +48 -0
  63. package/server/acp-runtime/index.js +576 -16
  64. package/server/acp-runtime/registry.js +6 -4
  65. package/server/acp-runtime/session-store.js +235 -92
  66. package/server/database/db.js +12 -3
  67. package/server/external-agent/ws.js +212 -11
  68. package/server/index.js +145 -52
  69. package/server/projects-watcher-config.js +4 -0
  70. package/server/projects.js +466 -125
  71. package/server/routes/cc-connect.js +5 -4
  72. package/server/routes/codex.js +24 -0
  73. package/server/routes/commands.js +144 -1
  74. package/server/routes/runs.js +641 -0
  75. package/server/routes/session-core.js +357 -109
  76. package/server/session-core/eventStore.js +0 -121
  77. package/server/session-core/providerAdapters.js +644 -163
  78. package/server/session-core/providerDiscovery.js +66 -38
  79. package/server/session-core/runRegistry.js +244 -0
  80. package/server/session-core/runtimeState.js +75 -3
  81. package/server/session-core/runtimeWriter.js +132 -10
  82. package/server/utils/codexImagePlayground.js +479 -0
  83. package/server/utils/localTerminal.js +56 -0
  84. package/server/utils/shellCommand.js +70 -0
  85. package/shared/acpCapabilities.js +393 -0
  86. package/shared/acpDefaultCapabilities.generated.json +141 -0
  87. package/shared/conversationEvents.js +425 -121
  88. package/dist/assets/App-VH1wNUHs.js +0 -259
  89. package/dist/assets/ReviewApp-D_9EN4TM.js +0 -1
  90. package/dist/assets/channel-CyNUnRfc.js +0 -1
  91. package/dist/assets/classDiagram-VBA2DB6C-DxBtyz2A.js +0 -1
  92. package/dist/assets/classDiagram-v2-RAHNMMFH-DxBtyz2A.js +0 -1
  93. package/dist/assets/clone-C341l3d0.js +0 -1
  94. package/dist/assets/index-DBkz_W_P.css +0 -1
  95. package/dist/assets/index-DdRyoXKh.js +0 -2
  96. package/dist/assets/stateDiagram-v2-FVOUBMTO-B3VPhiE1.js +0 -1
@@ -0,0 +1,106 @@
1
+ import{j as s}from"./vendor-codemirror-BiCeS-y4.js";import{R as rn,c as Dc,a as g,d as fr}from"./vendor-react-DVlYPmi3.js";import{g as Uc,a as Oc}from"./App-Clb2COtW.js";import"./index-DvA901Vs.js";import"./mermaid-O7DHMXV3-fDuyNLKe.js";import"./vendor-xterm-DfaPXD3y.js";const Eo=e=>{let t;const r=new Set,n=(f,m)=>{const u=typeof f=="function"?f(t):f;if(!Object.is(u,t)){const h=t;t=m??(typeof u!="object"||u===null)?u:Object.assign({},t,u),r.forEach(x=>x(t,h))}},a=()=>t,c={setState:n,getState:a,getInitialState:()=>l,subscribe:f=>(r.add(f),()=>r.delete(f))},l=t=e(n,a,c);return c},Bc=e=>e?Eo(e):Eo,$c=e=>e;function Fc(e,t=$c){const r=rn.useSyncExternalStore(e.subscribe,rn.useCallback(()=>t(e.getState()),[e,t]),rn.useCallback(()=>t(e.getInitialState()),[e,t]));return rn.useDebugValue(r),r}const Co=e=>{const t=Bc(e),r=n=>Fc(t,n);return Object.assign(r,t),r},zc=e=>e?Co(e):Co;function zi(e,t){let r;try{r=e()}catch{return}return{getItem:a=>{var o;const i=l=>l===null?null:JSON.parse(l,void 0),c=(o=r.getItem(a))!=null?o:null;return c instanceof Promise?c.then(i):i(c)},setItem:(a,o)=>r.setItem(a,JSON.stringify(o,void 0)),removeItem:a=>r.removeItem(a)}}const ka=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then(n){return ka(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return ka(n)(r)}}}},Hc=(e,t)=>(r,n,a)=>{let o={storage:zi(()=>window.localStorage),partialize:d=>d,version:0,merge:(d,p)=>({...p,...d}),...t},i=!1,c=0;const l=new Set,f=new Set;let m=o.storage;if(!m)return e((...d)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),r(...d)},n,a);const u=()=>{const d=o.partialize({...n()});return m.setItem(o.name,{state:d,version:o.version})},h=a.setState;a.setState=(d,p)=>(h(d,p),u());const x=e((...d)=>(r(...d),u()),n,a);a.getInitialState=()=>x;let y;const b=()=>{var d,p;if(!m)return;const w=++c;i=!1,l.forEach(j=>{var P;return j((P=n())!=null?P:x)});const v=((p=o.onRehydrateStorage)==null?void 0:p.call(o,(d=n())!=null?d:x))||void 0;return ka(m.getItem.bind(m))(o.name).then(j=>{if(j)if(typeof j.version=="number"&&j.version!==o.version){if(o.migrate){const P=o.migrate(j.state,j.version);return P instanceof Promise?P.then(C=>[!0,C]):[!0,P]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,j.state];return[!1,void 0]}).then(j=>{var P;if(w!==c)return;const[C,$]=j;if(y=o.merge($,(P=n())!=null?P:x),r(y,!0),C)return u()}).then(()=>{w===c&&(v?.(n(),void 0),y=n(),i=!0,f.forEach(j=>j(y)))}).catch(j=>{w===c&&v?.(void 0,j)})};return a.persist={setOptions:d=>{o={...o,...d},d.storage&&(m=d.storage)},clearStorage:()=>{m?.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>b(),hasHydrated:()=>i,onHydrate:d=>(l.add(d),()=>{l.delete(d)}),onFinishHydration:d=>(f.add(d),()=>{f.delete(d)})},o.skipHydration||b(),y||x},qc=Hc,Xt={size:"auto",quality:"auto",output_format:"png",output_compression:null,moderation:"auto",n:1};function un(e){return String.prototype.trim.call("")}const Fr=un()||"https://api.openai.com/v1",Yn=un()==="true",At="gpt-image-2",ws="gpt-5.5",Zt="https://fal.run",on="openai/gpt-image-2",Us="default-openai",Vn=600,Hi=new Set(["openai","fal"]),ln={generationPath:"images/generations",editPath:"images/edits",taskPath:"images/tasks/{task_id}"},Os={model:"$profile.model",prompt:"$prompt",size:"$params.size",quality:"$params.quality",output_format:"$params.output_format",moderation:"$params.moderation",output_compression:"$params.output_compression",n:"$params.n"},Ha=Os,qr={imageUrlPaths:["data.*.url"],b64JsonPaths:["data.*.b64_json"]},qi=[{field:"image[]",source:"inputImages",array:!0},{field:"mask",source:"mask"}];function Wc(e){return e==="http-image"}function Wi(e,t){return(typeof e=="string"&&e.trim()?e:t).trim().replace(/^\/+/,"").replace(/^v1\//,"")}function Is(e){if(!e||typeof e!="object")return;const t=Object.entries(e).filter(r=>typeof r[0]=="string"&&["string","number","boolean"].includes(typeof r[1])).map(([r,n])=>[r,String(n)]);return t.length?Object.fromEntries(t):void 0}function fn(e,t){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&!!r.trim()).map(r=>r.trim()):t}function qt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ki(e,t="POST"){return e==="GET"||e==="POST"?e:t}function Kc(e,t="json"){return e==="multipart"?"multipart":t}function Yc(e,t){return qt(e)?e:t}function Vc(e,t=[]){if(!Array.isArray(e))return t;const r=e.map(n=>!qt(n)||typeof n.field!="string"||!n.field.trim()||n.source!=="inputImages"&&n.source!=="mask"?null:{field:n.field.trim(),source:n.source,array:!!n.array}).filter(n=>!!n);return r.length?r:t}function Yi(e,t=qr){const r=qt(e)?e:{},n=fn(r.imageUrlPaths,t.imageUrlPaths??[]),a=fn(r.b64JsonPaths,t.b64JsonPaths??[]);return{imageUrlPaths:n,b64JsonPaths:a}}function Mo(e,t){const r=qt(e)?e:{},n=Kc(r.contentType,t.contentType??"json");return{path:Wi(r.path,t.path),method:Ki(r.method,t.method??"POST"),contentType:n,query:Is(r.query)??t.query,body:Yc(r.body,t.body??(n==="multipart"?Ha:Os)),files:n==="multipart"?Vc(r.files,t.files):void 0,taskIdPath:typeof r.taskIdPath=="string"&&r.taskIdPath.trim()?r.taskIdPath.trim():t.taskIdPath,result:Yi(r.result,t.result??qr)}}function Xc(e,t){if(!qt(e)&&!t)return;const r=qt(e)?e:{},n=Wi(r.path,ln.taskPath),a=typeof r.statusPath=="string"&&r.statusPath.trim()?r.statusPath.trim():t?.statusPath;if(a)return{path:n,method:Ki(r.method,"GET"),query:Is(r.query)??t?.query,intervalSeconds:typeof r.intervalSeconds=="number"&&Number.isFinite(r.intervalSeconds)?Math.max(1,r.intervalSeconds):t?.intervalSeconds??5,statusPath:a,successValues:fn(r.successValues,["SUCCESS","succeeded","completed","COMPLETED"]),failureValues:fn(r.failureValues,["FAILURE","failed","error","FAILED","cancelled"]),errorPath:typeof r.errorPath=="string"&&r.errorPath.trim()?r.errorPath.trim():t?.errorPath,result:Yi(r.result,qr)}}function Jc(e){if(e.template!=="openai-compatible"&&e.template!=="openai-compatible-async")return null;const t=e.template==="openai-compatible-async",r=typeof e.taskResultPath=="string"&&e.taskResultPath.trim()?e.taskResultPath.trim():"data.data";return{id:e.id,name:e.name,template:"http-image",submit:{path:e.generationPath??ln.generationPath,method:"POST",contentType:"json",query:t?Is(e.submitQuery)??{async:"true"}:void 0,body:Os,taskIdPath:t?e.taskIdPath??"data":void 0,result:qr},editSubmit:{path:e.editPath??ln.editPath,method:"POST",contentType:"multipart",query:t?Is(e.submitQuery)??{async:"true"}:void 0,body:Ha,files:qi,taskIdPath:t?e.taskIdPath??"data":void 0,result:qr},poll:t?{path:e.taskPath??ln.taskPath,method:"GET",statusPath:e.taskStatusPath??"data.status",successValues:fn(e.taskSuccessValues,["SUCCESS","succeeded","completed","COMPLETED"]),failureValues:fn(e.taskFailureValues,["FAILURE","failed","error","FAILED"]),errorPath:"data.fail_reason",intervalSeconds:typeof e.pollIntervalSeconds=="number"?e.pollIntervalSeconds:5,result:{imageUrlPaths:[`${r}.data.*.url`],b64JsonPaths:[`${r}.data.*.b64_json`]}}:void 0}}function Gc(e,t){const r=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"custom";let n=`custom-${r}`,a=2;for(;t.has(n)||Hi.has(n);)n=`custom-${r}-${a}`,a+=1;return t.add(n),n}function Bs(e,t=new Set){if(!e||typeof e!="object")return null;const r=e,n=Jc(r)??r,a=n.template==null?"http-image":Wc(n.template)?n.template:null;if(!a||!qt(n.submit))return null;const o=typeof n.name=="string"&&n.name.trim()?n.name.trim():"自定义服务商",i=typeof n.id=="string"&&n.id.trim()&&!Hi.has(n.id.trim())&&!t.has(n.id.trim())?n.id.trim():Gc(o,t);return t.add(i),{id:i,name:o,template:a,submit:Mo(n.submit,{path:ln.generationPath,method:"POST",contentType:"json",body:Os,result:qr}),editSubmit:qt(n.editSubmit)?Mo(n.editSubmit,{path:ln.editPath,method:"POST",contentType:"multipart",body:Ha,files:qi,result:qr}):void 0,poll:Xc(n.poll)}}function Vi(e){const t=new Set;return(Array.isArray(e)?e:[]).map(n=>Bs(n,t)).filter(n=>!!n)}function kr(e={}){return{id:Us,name:"默认",provider:"openai",baseUrl:Fr,apiKey:"",model:At,timeout:Vn,apiMode:"images",codexCli:!1,apiProxy:Yn,...e}}function Xi(e={}){return{id:`fal-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,name:"新配置",provider:"fal",baseUrl:Zt,apiKey:"",model:on,timeout:Vn,apiMode:"images",codexCli:!1,apiProxy:!1,...e}}function na(e,t,r){const n={...e.providerDrafts,[e.provider]:{baseUrl:e.baseUrl,model:e.model,apiMode:e.apiMode,codexCli:e.codexCli,apiProxy:e.apiProxy,responseFormatB64Json:e.responseFormatB64Json}},a=n[t];if(t==="fal")return{...e,provider:t,baseUrl:a?.baseUrl??Zt,model:a?.model??on,apiMode:a?.apiMode??"images",codexCli:!1,apiProxy:!1,responseFormatB64Json:a?.responseFormatB64Json,providerDrafts:n};if(r){const o=e.provider==="fal";return{...e,provider:r.id,baseUrl:a?.baseUrl??(o?Fr:e.baseUrl||Fr),model:a?.model??(o?At:e.model||At),apiMode:a?.apiMode??"images",codexCli:!1,apiProxy:!1,responseFormatB64Json:a?.responseFormatB64Json,providerDrafts:n}}return{...e,provider:t,baseUrl:a?.baseUrl??Fr,model:a?.model??At,apiMode:a?.apiMode??e.apiMode,codexCli:a?.codexCli??e.codexCli,apiProxy:a?.apiProxy??Yn,responseFormatB64Json:a?.responseFormatB64Json,providerDrafts:n}}function Qc(e,t,r){if(!qt(e))return;const n=t==="fal"?Xi():kr(),a=typeof e.baseUrl=="string"?e.baseUrl:void 0,o=typeof e.model=="string"&&e.model.trim()?e.model:void 0,i=e.apiMode==="responses"?"responses":e.apiMode==="images"?"images":void 0;if(t==="fal"||t==="openai"||r.has(t))return{baseUrl:t==="fal"?a?.trim().replace(/\/+$/,"")||Zt:a,model:o,apiMode:i,codexCli:typeof e.codexCli=="boolean"?e.codexCli:n.codexCli,apiProxy:typeof e.apiProxy=="boolean"?e.apiProxy:n.apiProxy,responseFormatB64Json:e.responseFormatB64Json===!0?!0:void 0}}function Zc(e,t){if(!qt(e))return;const r=Object.entries(e).map(([n,a])=>[n,Qc(a,n,t)]).filter(n=>!!n[1]);return r.length?Object.fromEntries(r):void 0}function Ji(e,t,r=new Set){const n=e&&typeof e=="object"?e:{},a=typeof n.provider=="string"?n.provider:"",o=a==="fal"||r.has(a)?a:"openai",i=o==="fal"?Xi(t):kr(t),c=n.apiMode==="responses"?"responses":"images",l=typeof n.baseUrl=="string"?n.baseUrl:i.baseUrl;return{...i,id:typeof n.id=="string"&&n.id.trim()?n.id:i.id,name:typeof n.name=="string"&&n.name.trim()?n.name:i.name,provider:o,baseUrl:o==="fal"?l.trim().replace(/\/+$/,"")||Zt:l,apiKey:typeof n.apiKey=="string"?n.apiKey:i.apiKey,model:typeof n.model=="string"&&n.model.trim()?n.model:i.model,timeout:typeof n.timeout=="number"&&Number.isFinite(n.timeout)?n.timeout:i.timeout,apiMode:c,codexCli:!!n.codexCli,apiProxy:typeof n.apiProxy=="boolean"?n.apiProxy:i.apiProxy,responseFormatB64Json:n.responseFormatB64Json===!0?!0:void 0,providerDrafts:Zc(n.providerDrafts,r)}}function ed(e){if(!qt(e))return;const t=typeof e.baseUrl=="string"?e.baseUrl.trim():"";if(t&&(t.startsWith("[")||t.includes("](")))throw new Error("JSON 包含 Markdown 链接,请粘贴纯文本");if(typeof e.apiMode=="string"&&e.apiMode!=="images"&&e.apiMode!=="responses")throw new Error("apiMode 格式无效,应为 images 或 responses")}function ue(e){const t=e&&typeof e=="object"?e:{},r=Vi(t.customProviders),n=new Set(r.map(l=>l.id)),a=kr({baseUrl:typeof t.baseUrl=="string"?t.baseUrl:Fr,apiKey:typeof t.apiKey=="string"?t.apiKey:"",model:typeof t.model=="string"&&t.model.trim()?t.model:At,timeout:typeof t.timeout=="number"&&Number.isFinite(t.timeout)?t.timeout:Vn,apiMode:t.apiMode==="responses"?"responses":"images",codexCli:!!t.codexCli,apiProxy:typeof t.apiProxy=="boolean"?t.apiProxy:Yn,responseFormatB64Json:t.responseFormatB64Json===!0?!0:void 0}),o=Array.isArray(t.profiles)&&t.profiles.length?t.profiles.map(l=>Ji(l,void 0,n)):[a],i=typeof t.activeProfileId=="string"&&o.some(l=>l.id===t.activeProfileId)?t.activeProfileId:o[0].id,c=o.find(l=>l.id===i)??o[0];return{baseUrl:c.baseUrl,apiKey:c.apiKey,model:c.model,timeout:c.timeout,apiMode:c.apiMode,codexCli:c.codexCli,apiProxy:c.apiProxy,customProviders:r,providerOrder:Array.isArray(t.providerOrder)?t.providerOrder.map(String):void 0,clearInputAfterSubmit:typeof t.clearInputAfterSubmit=="boolean"?t.clearInputAfterSubmit:!1,persistInputOnRestart:typeof t.persistInputOnRestart=="boolean"?t.persistInputOnRestart:!0,reuseTaskApiProfileTemporarily:typeof t.reuseTaskApiProfileTemporarily=="boolean"?t.reuseTaskApiProfileTemporarily:!1,alwaysShowRetryButton:typeof t.alwaysShowRetryButton=="boolean"?t.alwaysShowRetryButton:!1,enterSubmit:typeof t.enterSubmit=="boolean"?t.enterSubmit:!1,profiles:o,activeProfileId:i}}function Xn(e,t){return ue(e).customProviders.find(n=>n.id===t)??null}function sa(e,t){return t==="fal"?"fal.ai":t==="openai"?"OpenAI":Xn(e,t)?.name??t}function Ro(e,t){return t==="openai"||!!Xn(e,t)}function td(e){const t=e.trim(),r=t.match(/^```[^\r\n]*\r?\n([\s\S]*?)\r?\n```$/);return r?r[1].trim():t}function rd(e,t=[]){let r;try{r=JSON.parse(td(e))}catch{throw new Error("JSON 格式无效")}if(!r||typeof r!="object")throw new Error("JSON 根节点必须是对象");const n=r;if(Array.isArray(n.customProviders)){const i=Vi(n.customProviders);if(i.length===0)throw new Error("customProviders 数组中没有有效的服务商配置");const c=new Set(i.map(f=>f.id)),l=Array.isArray(n.profiles)?n.profiles.map(f=>(ed(f),f)).map(f=>Ji(f,void 0,c)).filter(f=>c.has(f.provider)):[];return{customProviders:i,profiles:l}}const a=new Set(t.map(i=>i.id)),o=Bs(r,a);if(o)return{customProviders:[o],profiles:[]};throw new Error("无法识别该 JSON。请粘贴自定义服务商配置。")}function et(e){const t=e&&typeof e=="object"?e:{},r=ue(e),n=r.profiles.find(a=>a.id===r.activeProfileId)??r.profiles[0]??kr();return{...n,baseUrl:typeof t.baseUrl=="string"?t.baseUrl:n.baseUrl,apiKey:typeof t.apiKey=="string"?t.apiKey:n.apiKey,model:typeof t.model=="string"&&t.model.trim()?t.model:n.model,timeout:typeof t.timeout=="number"&&Number.isFinite(t.timeout)?t.timeout:n.timeout,apiMode:t.apiMode==="images"||t.apiMode==="responses"?t.apiMode:n.apiMode,codexCli:typeof t.codexCli=="boolean"?t.codexCli:n.codexCli,apiProxy:typeof t.apiProxy=="boolean"?t.apiProxy:n.apiProxy}}function Ao(e){return e.name.trim()?e.provider!=="fal"&&!e.baseUrl.trim()?"缺少 API URL":e.apiKey.trim()?e.model.trim()?null:"缺少模型 ID":"缺少 API Key":"缺少名称"}function nd(e){return e.id===Us&&e.name==="默认"&&e.provider==="openai"&&e.baseUrl===Fr&&e.apiKey===""&&e.model===At&&e.timeout===Vn&&e.apiMode==="images"&&e.codexCli===!1&&e.apiProxy===Yn}function sd(e){return e.customProviders.length===0&&e.profiles.length===1&&e.activeProfileId===Us&&nd(e.profiles[0])}function ad(e,t){let r=`${e}-imported-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;for(;t.has(r);)r=`${e}-imported-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;return t.add(r),r}function Wr(e){return JSON.stringify([e.provider,e.baseUrl.trim().replace(/\/+$/,"").toLowerCase(),e.apiKey.trim(),e.model.trim(),e.apiMode])}function Ps(e){return JSON.stringify([e.provider,e.baseUrl.trim().replace(/\/+$/,"").toLowerCase(),e.model.trim(),e.apiMode])}function od(e,t){const r=Wr(t);if(e.some(a=>Wr(a)===r))return!0;if(t.apiKey.trim())return!1;const n=Ps(t);return e.some(a=>Ps(a)===n)}function id(e){const t=new Set;return e.filter(r=>{const n=Wr(r);return t.has(n)?!1:(t.add(n),!0)})}function Dn(e){return JSON.stringify([e.name,e.template??"http-image",e.submit,e.editSubmit??null,e.poll??null])}function ld(e,t){const r=[...e],n=new Map,a=new Set(r.map(i=>i.id)),o=new Map(r.map(i=>[Dn(i),i.id]));for(const i of t){const c=o.get(Dn(i));if(c){n.set(i.id,c);continue}const l=Bs(i,a);l&&(n.set(i.id,l.id),r.push(l),o.set(Dn(l),l.id))}return{providers:r,providerIdMap:n}}function Gi(e,t,r=[]){const n=ue(e),a=r.find(m=>m.id===t.provider),o=a?n.customProviders.find(m=>Dn(m)===Dn(a))?.id??t.provider:t.provider,i={...t,provider:o},c=Wr(i),l=n.profiles.find(m=>Wr(m)===c);if(l)return l;if(i.apiKey.trim())return null;const f=Ps(i);return n.profiles.find(m=>Ps(m)===f)??null}function qa(e,t){const r=ue(e),n=ue(t),a=ue({...n,profiles:id(n.profiles)});if(sd(r))return a;const o=new Set(r.profiles.map(u=>u.id)),i=new Set(r.profiles.map(Wr)),{providers:c,providerIdMap:l}=ld(r.customProviders,a.customProviders),f=a.profiles.map(u=>l.has(u.provider)?{...u,provider:l.get(u.provider)??u.provider}:u).filter(u=>!i.has(Wr(u))&&!od(r.profiles,u)).map(u=>({...u,id:ad(u.provider,o)})),m=[...r.profiles,...f];return ue({...r,customProviders:c,profiles:m,activeProfileId:r.activeProfileId})}const Ct=ue({baseUrl:Fr,apiKey:"",model:At,timeout:Vn,apiMode:"images",codexCli:!1,apiProxy:Yn,customProviders:[],clearInputAfterSubmit:!1,persistInputOnRestart:!0,reuseTaskApiProfileTemporarily:!1,alwaysShowRetryButton:!1,enterSubmit:!1}),ja=new EventTarget,Ia="dismiss-tooltips";function Ht(){ja.dispatchEvent(new Event(Ia))}function Qi(e){return ja.addEventListener(Ia,e),()=>ja.removeEventListener(Ia,e)}const Zi="⁣",el="⁤",$s=/\u2063@图(\d+)\u2064/g;function Jn(e){return`@图${e+1}`}function Wa(e){return`${Zi}${Jn(e)}${el}`}function vr(e){return e.replace(/[\u2063\u2064]/g,"")}function nn(e,t){let r=0;for(let n=0;n<e.length;n++)if(!(e[n]===Zi||e[n]===el)){if(r>=t)return n;r++}return e.length}function cd(e,t){for(const r of e.matchAll($s)){if(r.index==null)continue;const n=vr(e.slice(0,r.index)).length,a=n+Jn(Number(r[1])-1).length;if(t>n&&t<=a)return!0}return!1}function _o(e,t,r){if(r.length===0)return null;const n=e.slice(0,t),a=n.lastIndexOf("@");if(a<0)return null;const o=n.slice(a+1);return/\s/.test(o)?null:{start:a,query:o}}function dd(e,t){const r=e.trim().toLowerCase();if(!r)return!0;const n=String(t+1),a=`图${n}`;return n.includes(r)||a.toLowerCase().includes(r)}function Lo(e,t,r,n){const a=nn(e,t),o=nn(e,r),i=Wa(n),c=Jn(n);return{prompt:`${e.slice(0,a)}${i}${e.slice(o)}`,cursor:t+c.length}}function wn(e,t,r,n={}){return e.replace($s,(a,o)=>{const i=t[Number(o)-1];if(!i)return a;const c=n[i.id]??i.id,l=r.findIndex(f=>f.id===c);return l>=0?Wa(l):"@已移除图片"})}function ud(e,t){const r=[];let n=0;for(const a of e.matchAll($s)){const o=Jn(Number(a[1])-1),i=Number(a[1])-1;!t[i]||a.index==null||(a.index>n&&r.push({type:"text",text:vr(e.slice(n,a.index))}),r.push({type:"mention",text:o,imageIndex:i}),n=a.index+a[0].length)}return n<e.length&&r.push({type:"text",text:vr(e.slice(n))}),r.length>0?r:[{type:"text",text:vr(e)}]}function fd(e,t){return e.replace($s,(r,n)=>{const a=Number(n)-1;return t!=null&&(a<0||a>=t)?vr(r):`[image ${n}]`})}const Do="gpt-image-playground",md=2,mn="tasks",tr="images",jr="thumbnails",hd=720,gd=.9,Qt=2,tl=Qt;let rl=null;function nl(e){return typeof e!="string"?null:e.trim().replace(/[\\/]+$/,"")||null}function pd(e){return encodeURIComponent(e)}function xd(e=rl){const t=nl(e);return t?`${Do}:project:${pd(t)}`:Do}function bd(e){rl=nl(e)}function Ka(){return new Promise((e,t)=>{const r=indexedDB.open(xd(),md);r.onupgradeneeded=n=>{const a=n.target.result;a.objectStoreNames.contains(mn)||a.createObjectStore(mn,{keyPath:"id"}),a.objectStoreNames.contains(tr)||a.createObjectStore(tr,{keyPath:"id"}),a.objectStoreNames.contains(jr)||a.createObjectStore(jr,{keyPath:"id"})},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function nr(e,t,r){return Ka().then(n=>new Promise((a,o)=>{const c=n.transaction(e,t).objectStore(e),l=r(c);l.onsuccess=()=>a(l.result),l.onerror=()=>o(l.error)}))}function Ya(){return nr(mn,"readonly",e=>e.getAll())}function Gn(e){return nr(mn,"readwrite",t=>t.put(e))}function sl(e){return nr(mn,"readwrite",t=>t.delete(e))}function yd(){return nr(mn,"readwrite",e=>e.clear())}function hn(e){return nr(tr,"readonly",t=>t.get(e))}function Va(e){return nr(jr,"readonly",t=>t.get(e))}async function wd(e){const t=await Va(e);return t?.thumbnailVersion===Qt?t:void 0}function $n(e){return nr(jr,"readwrite",t=>t.put(e))}async function al(e){const t=await Va(e);if(t?.thumbnailVersion===Qt){const i=await hn(e);return i&&(!i.width||!i.height)&&t.width&&t.height&&await cn({...i,width:t.width,height:t.height}),t}const r=await hn(e);if(!r)return;const n=r;if(n.thumbnailDataUrl&&n.thumbnailVersion===Qt){const i={id:e,thumbnailDataUrl:n.thumbnailDataUrl,width:n.width,height:n.height,thumbnailVersion:Qt};return await $n(i),(!r.width||!r.height)&&i.width&&i.height&&await cn({...r,width:i.width,height:i.height}),i}const a=await Pa(r.dataUrl);if(!a.thumbnailDataUrl)return;const o={id:e,thumbnailDataUrl:a.thumbnailDataUrl,width:a.width,height:a.height,thumbnailVersion:Qt};return await $n(o),a.width&&a.height&&(r.width!==a.width||r.height!==a.height)&&await cn({...r,width:a.width,height:a.height}),o}function vd(){return nr(tr,"readonly",e=>e.getAll())}function kd(){return nr(tr,"readonly",e=>e.getAllKeys()).then(e=>e.map(String))}function cn(e){return nr(tr,"readwrite",t=>t.put(e))}function Xa(e){return Ka().then(t=>new Promise((r,n)=>{const a=t.transaction([tr,jr],"readwrite");a.objectStore(tr).delete(e),a.objectStore(jr).delete(e),a.oncomplete=()=>r(void 0),a.onerror=()=>n(a.error)}))}function jd(){return Ka().then(e=>new Promise((t,r)=>{const n=e.transaction([tr,jr],"readwrite");n.objectStore(tr).clear(),n.objectStore(jr).clear(),n.oncomplete=()=>t(void 0),n.onerror=()=>r(n.error)}))}async function Id(e){if(!globalThis.crypto?.subtle)return Pd(e);const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Pd(e){let t=2166136261,r=16777619;for(let n=0;n<e.length;n++){const a=e.charCodeAt(n);t^=a,t=Math.imul(t,16777619),r^=a,r=Math.imul(r,668265261)}return`fallback-${(t>>>0).toString(16).padStart(8,"0")}${(r>>>0).toString(16).padStart(8,"0")}`}async function Ir(e,t="upload"){const r=await Id(e),n=await hn(r);if(n){if((await Va(r))?.thumbnailVersion!==Qt){const a=await Pa(n.dataUrl);a.width&&a.height&&(n.width!==a.width||n.height!==a.height)&&await cn({...n,width:a.width,height:a.height}),a.thumbnailDataUrl&&await $n({id:r,thumbnailDataUrl:a.thumbnailDataUrl,width:a.width,height:a.height,thumbnailVersion:Qt})}}else{const a=await Pa(e);await cn({id:r,dataUrl:e,createdAt:Date.now(),source:t,width:a.width,height:a.height}),a.thumbnailDataUrl&&await $n({id:r,thumbnailDataUrl:a.thumbnailDataUrl,width:a.width,height:a.height,thumbnailVersion:Qt})}return r}function Sd(e){return new Promise((t,r)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>r(new Error("图片加载失败")),n.src=e})}async function Nd(e){const t=await Sd(e),r=t.naturalWidth,n=t.naturalHeight;if(r<=0||n<=0)throw new Error("图片尺寸无效");const a=Math.min(1,hd/Math.max(r,n)),o=document.createElement("canvas");o.width=Math.max(1,Math.round(r*a)),o.height=Math.max(1,Math.round(n*a));const i=o.getContext("2d");if(!i)throw new Error("当前浏览器不支持 Canvas");return i.drawImage(t,0,0,o.width,o.height),{thumbnailDataUrl:o.toDataURL("image/webp",gd),width:r,height:n,thumbnailVersion:Qt}}async function Pa(e){try{return await Nd(e)}catch{return{}}}var Dr={},Qr={},aa={},vn={},Uo;function ol(){return Uo||(Uo=1,function(e){var t=vn&&vn.__awaiter||function(o,i,c,l){function f(m){return m instanceof c?m:new c(function(u){u(m)})}return new(c||(c=Promise))(function(m,u){function h(b){try{y(l.next(b))}catch(d){u(d)}}function x(b){try{y(l.throw(b))}catch(d){u(d)}}function y(b){b.done?m(b.value):f(b.value).then(h,x)}y((l=l.apply(o,i||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.TARGET_URL_HEADER=void 0,e.withMiddleware=r,e.withProxy=a;function r(...o){const i=c=>typeof c=="function";return c=>t(this,void 0,void 0,function*(){let l=Object.assign({},c);for(const f of o.filter(i))l=yield f(l);return l})}e.TARGET_URL_HEADER="x-fal-target-url";function n(o){const i={isBrowser:typeof window<"u"&&typeof window.document<"u"};return typeof o=="function"?o(i):o==="always"?!0:i.isBrowser}function a(o){return i=>i.headers&&e.TARGET_URL_HEADER in i.headers||!n(o.when)?Promise.resolve(i):Promise.resolve(Object.assign(Object.assign({},i),{url:o.targetUrl,headers:Object.assign(Object.assign({},i.headers||{}),{[e.TARGET_URL_HEADER]:i.url})}))}}(vn)),vn}var $t={},oa={},Oo;function Ja(){return Oo||(Oo=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.RUNNER_HINT_HEADER=e.QUEUE_PRIORITY_HEADER=e.REQUEST_TIMEOUT_TYPE_HEADER=e.REQUEST_TIMEOUT_HEADER=e.MIN_REQUEST_TIMEOUT_SECONDS=void 0,e.validateTimeoutHeader=t,e.buildTimeoutHeaders=r,e.MIN_REQUEST_TIMEOUT_SECONDS=1,e.REQUEST_TIMEOUT_HEADER="x-fal-request-timeout",e.REQUEST_TIMEOUT_TYPE_HEADER="x-fal-request-timeout-type",e.QUEUE_PRIORITY_HEADER="x-fal-queue-priority",e.RUNNER_HINT_HEADER="x-fal-runner-hint";function t(n){if(typeof n!="number"||isNaN(n))throw new Error(`Timeout must be a number, got ${n}`);if(n<=e.MIN_REQUEST_TIMEOUT_SECONDS)throw new Error(`Timeout must be greater than ${e.MIN_REQUEST_TIMEOUT_SECONDS} seconds`);return n.toString()}function r(n){return n===void 0?{}:{[e.REQUEST_TIMEOUT_HEADER]:t(n)}}}(oa)),oa}var Bo;function Xr(){if(Bo)return $t;Bo=1;var e=$t&&$t.__awaiter||function(c,l,f,m){function u(h){return h instanceof f?h:new f(function(x){x(h)})}return new(f||(f=Promise))(function(h,x){function y(p){try{d(m.next(p))}catch(w){x(w)}}function b(p){try{d(m.throw(p))}catch(w){x(w)}}function d(p){p.done?h(p.value):u(p.value).then(y,b)}d((m=m.apply(c,l||[])).next())})};Object.defineProperty($t,"__esModule",{value:!0}),$t.ValidationError=$t.ApiError=void 0,$t.defaultResponseHandler=o,$t.resultResponseHandler=i;const t=Ja(),r="x-fal-request-id";class n extends Error{constructor({message:l,status:f,body:m,requestId:u,timeoutType:h}){super(l),this.name="ApiError",this.status=f,this.body=m,this.requestId=u||"",this.timeoutType=h}get isUserTimeout(){return this.status===504&&this.timeoutType==="user"}}$t.ApiError=n;class a extends n{constructor(l){super(l),this.name="ValidationError"}get fieldErrors(){return typeof this.body.detail=="string"?[{loc:["body"],msg:this.body.detail,type:"value_error"}]:this.body.detail||[]}getFieldErrors(l){return this.fieldErrors.filter(f=>f.loc[f.loc.length-1]===l)}}$t.ValidationError=a;function o(c){return e(this,void 0,void 0,function*(){var l;const{status:f,statusText:m}=c,u=(l=c.headers.get("Content-Type"))!==null&&l!==void 0?l:"",h=c.headers.get(r)||void 0,x=c.headers.get(t.REQUEST_TIMEOUT_TYPE_HEADER)||void 0;if(!c.ok){if(u.includes("application/json")){const y=yield c.json(),b=f===422?a:n;throw new b({message:y.message||m,status:f,body:y,requestId:h,timeoutType:x})}throw new n({message:`HTTP ${f}: ${m}`,status:f,requestId:h,timeoutType:x})}return u.includes("application/json")?c.json():u.includes("text/html")?c.text():u.includes("application/octet-stream")?c.arrayBuffer():c.text()})}function i(c){return e(this,void 0,void 0,function*(){return{data:yield o(c),requestId:c.headers.get(r)||""}})}return $t}var kn={},Tt={},$o;function Tr(){if($o)return Tt;$o=1;var e=Tt&&Tt.__awaiter||function(u,h,x,y){function b(d){return d instanceof x?d:new x(function(p){p(d)})}return new(x||(x=Promise))(function(d,p){function w(P){try{j(y.next(P))}catch(C){p(C)}}function v(P){try{j(y.throw(P))}catch(C){p(C)}}function j(P){P.done?d(P.value):b(P.value).then(w,v)}j((y=y.apply(u,h||[])).next())})};Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.ensureEndpointIdFormat=t,Tt.parseEndpointId=n,Tt.resolveEndpointPath=a,Tt.isValidUrl=o,Tt.throttle=i,Tt.isReact=l,Tt.isPlainObject=f,Tt.sleep=m;function t(u){if(u.split("/").length>1)return u;const[,x,y]=/^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(u)||[];if(x&&y)return`${x}/${y}`;throw new Error(`Invalid app id: ${u}. Must be in the format <appOwner>/<appId>`)}const r=["workflows","comfy"];function n(u){const x=t(u).split("/");return r.includes(x[0])?{owner:x[1],alias:x[2],path:x.slice(3).join("/")||void 0,namespace:x[0]}:{owner:x[0],alias:x[1],path:x.slice(2).join("/")||void 0}}function a(u,h,x){if(h)return`/${h.replace(/^\/+/,"")}`;if(!u.endsWith(x))return x}function o(u){try{const{host:h}=new URL(u);return/(fal\.(ai|run))$/.test(h)}catch{return!1}}function i(u,h,x=!1){let y,b;return(...d)=>{!b&&x?(u(...d),b=Date.now()):(y&&clearTimeout(y),y=setTimeout(()=>{Date.now()-b>=h&&(u(...d),b=Date.now())},h-(Date.now()-b)))}}let c;function l(){if(c===void 0){const u=new Error().stack;c=!!u&&(u.includes("node_modules/react-dom/")||u.includes("node_modules/next/"))}return c}function f(u){return!!u&&Object.getPrototypeOf(u)===Object.prototype}function m(u){return e(this,void 0,void 0,function*(){return new Promise(h=>setTimeout(h,u))})}return Tt}var Fo;function Fs(){return Fo||(Fo=1,function(e){var t=kn&&kn.__awaiter||function(c,l,f,m){function u(h){return h instanceof f?h:new f(function(x){x(h)})}return new(f||(f=Promise))(function(h,x){function y(p){try{d(m.next(p))}catch(w){x(w)}}function b(p){try{d(m.throw(p))}catch(w){x(w)}}function d(p){p.done?h(p.value):u(p.value).then(y,b)}d((m=m.apply(c,l||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_RETRY_OPTIONS=e.DEFAULT_RETRYABLE_STATUS_CODES=void 0,e.isRetryableError=a,e.calculateBackoffDelay=o,e.executeWithRetry=i;const r=Xr(),n=Tr();e.DEFAULT_RETRYABLE_STATUS_CODES=[429,502,503,504],e.DEFAULT_RETRY_OPTIONS={maxRetries:3,baseDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:e.DEFAULT_RETRYABLE_STATUS_CODES,enableJitter:!0};function a(c,l){return!(c instanceof r.ApiError)||c.isUserTimeout?!1:l.includes(c.status)}function o(c,l,f,m,u){const h=Math.min(l*Math.pow(m,c),f);if(u){const x=.25*h*(Math.random()*2-1);return Math.max(0,h+x)}return h}function i(c,l,f){return t(this,void 0,void 0,function*(){const m={totalAttempts:0,totalDelay:0};let u;for(let h=0;h<=l.maxRetries;h++){m.totalAttempts++;try{return{result:yield c(),metrics:m}}catch(x){if(u=x,m.lastError=x,h===l.maxRetries||!a(x,l.retryableStatusCodes))throw x;const y=o(h,l.baseDelay,l.maxDelay,l.backoffMultiplier,l.enableJitter);m.totalDelay+=y,f&&f(h+1,x,y),yield(0,n.sleep)(y)}}throw u})}}(kn)),kn}var jn={};const Td="@fal-ai/client",Ed="1.10.0",Cd={name:Td,version:Ed};var zo;function Ga(){if(zo)return jn;zo=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.isBrowser=e,jn.getUserAgent=r;function e(){return typeof window<"u"&&typeof window.document<"u"}let t=null;function r(){if(t!==null)return t;const n=Cd;return t=`${n.name}/${n.version}`,t}return jn}var Ho;function Qa(){return Ho||(Ho=1,function(e){var t={};Object.defineProperty(e,"__esModule",{value:!0}),e.credentialsFromEnv=void 0,e.resolveDefaultFetch=i,e.createConfig=m,e.getRestApiUrl=u;const r=ol(),n=Xr(),a=Fs(),o=Ga();function i(){if(typeof fetch>"u")throw new Error("Your environment does not support fetch. Please provide your own fetch implementation.");return fetch}function c(){return typeof process<"u"&&t&&(typeof t.FAL_KEY<"u"||typeof t.FAL_KEY_ID<"u"&&typeof t.FAL_KEY_SECRET<"u")}const l=()=>{if(c())return typeof t.FAL_KEY<"u"?t.FAL_KEY:t.FAL_KEY_ID?`${t.FAL_KEY_ID}:${t.FAL_KEY_SECRET}`:void 0};e.credentialsFromEnv=l;const f={credentials:e.credentialsFromEnv,suppressLocalCredentialsWarning:!1,requestMiddleware:h=>Promise.resolve(h),responseHandler:n.defaultResponseHandler,retry:a.DEFAULT_RETRY_OPTIONS};function m(h){var x;let y=Object.assign(Object.assign(Object.assign({},f),h),{fetch:(x=h.fetch)!==null&&x!==void 0?x:i(),retry:Object.assign(Object.assign({},a.DEFAULT_RETRY_OPTIONS),h.retry||{})});if(h.proxyUrl){const w=typeof h.proxyUrl=="string"?{url:h.proxyUrl}:h.proxyUrl;y=Object.assign(Object.assign({},y),{requestMiddleware:(0,r.withMiddleware)(y.requestMiddleware,(0,r.withProxy)({targetUrl:w.url,when:w.when}))})}const{credentials:b,suppressLocalCredentialsWarning:d}=y,p=typeof b=="function"?b():b;return(0,o.isBrowser)()&&p&&!d&&console.warn("The fal credentials are exposed in the browser's environment. That's not recommended for production use cases."),y}function u(){return"https://rest.fal.ai"}}(aa)),aa}var lr={},cr={},qo;function Qn(){if(qo)return cr;qo=1;var e=cr&&cr.__awaiter||function(l,f,m,u){function h(x){return x instanceof m?x:new m(function(y){y(x)})}return new(m||(m=Promise))(function(x,y){function b(w){try{p(u.next(w))}catch(v){y(v)}}function d(w){try{p(u.throw(w))}catch(v){y(v)}}function p(w){w.done?x(w.value):h(w.value).then(b,d)}p((u=u.apply(l,f||[])).next())})},t=cr&&cr.__rest||function(l,f){var m={};for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&f.indexOf(u)<0&&(m[u]=l[u]);if(l!=null&&typeof Object.getOwnPropertySymbols=="function")for(var h=0,u=Object.getOwnPropertySymbols(l);h<u.length;h++)f.indexOf(u[h])<0&&Object.prototype.propertyIsEnumerable.call(l,u[h])&&(m[u[h]]=l[u[h]]);return m};Object.defineProperty(cr,"__esModule",{value:!0}),cr.dispatchRequest=i,cr.buildUrl=c;const r=Fs(),n=Ga(),a=Tr(),o=typeof navigator<"u"&&navigator?.userAgent==="Cloudflare-Workers";function i(l){return e(this,void 0,void 0,function*(){var f;const{targetUrl:m,input:u,config:h,options:x={}}=l,{credentials:y,requestMiddleware:b,responseHandler:d,fetch:p}=h,w=Object.assign(Object.assign({},h.retry),x.retry||{}),v=()=>e(this,void 0,void 0,function*(){var P,C,$;const R=(0,n.isBrowser)()?{}:{"User-Agent":(0,n.getUserAgent)()},N=typeof y=="function"?y():y,{method:Q,url:L,headers:H}=yield b({method:((C=(P=l.method)!==null&&P!==void 0?P:x.method)!==null&&C!==void 0?C:"post").toUpperCase(),url:m,headers:l.headers}),q=N?{Authorization:`Key ${N}`}:{},F=Object.assign(Object.assign(Object.assign(Object.assign({},q),{Accept:"application/json","Content-Type":"application/json"}),R),H??{}),{responseHandler:Y,retry:A}=x,U=t(x,["responseHandler","retry"]),J=yield p(L,Object.assign(Object.assign(Object.assign(Object.assign({},U),{method:Q,headers:Object.assign(Object.assign({},F),($=U.headers)!==null&&$!==void 0?$:{})}),!o&&{mode:"cors"}),{signal:x.signal,body:Q.toLowerCase()!=="get"&&u?JSON.stringify(u):void 0}));return yield(Y??d)(J)});let j;for(let P=0;P<=w.maxRetries;P++)try{return yield v()}catch(C){if(j=C,P===w.maxRetries||!(0,r.isRetryableError)(C,w.retryableStatusCodes)||((f=x.signal)===null||f===void 0?void 0:f.aborted))throw C;const R=(0,r.calculateBackoffDelay)(P,w.baseDelay,w.maxDelay,w.backoffMultiplier,w.enableJitter);yield(0,a.sleep)(R)}throw j})}function c(l,f={}){var m,u;const h=((m=f.method)!==null&&m!==void 0?m:"post").toLowerCase(),x=((u=f.path)!==null&&u!==void 0?u:"").replace(/^\//,"").replace(/\/{2,}/,"/"),y=f.input,b=Object.assign(Object.assign({},f.query||{}),h==="get"?y:{}),d=Object.keys(b).length>0?`?${new URLSearchParams(b).toString()}`:"";if((0,a.isValidUrl)(l))return`${l.endsWith("/")?l:`${l}/`}${x}${d}`;const p=(0,a.ensureEndpointIdFormat)(l);return`${`https://${f.subdomain?`${f.subdomain}.`:""}fal.run/${p}/${x}`.replace(/\/$/,"")}${d}`}return cr}var In={},Wo;function il(){return Wo||(Wo=1,function(e){var t=In&&In.__awaiter||function(b,d,p,w){function v(j){return j instanceof p?j:new p(function(P){P(j)})}return new(p||(p=Promise))(function(j,P){function C(N){try{R(w.next(N))}catch(Q){P(Q)}}function $(N){try{R(w.throw(N))}catch(Q){P(Q)}}function R(N){N.done?j(N.value):v(N.value).then(C,$)}R((w=w.apply(b,d||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.OBJECT_LIFECYCYLE_PREFERENCE_HEADER=void 0,e.getExpirationDurationSeconds=i,e.buildObjectLifecycleHeaders=l,e.createStorageClient=y;const r=Qa(),n=Qn(),a=Tr();e.OBJECT_LIFECYCYLE_PREFERENCE_HEADER="x-fal-object-lifecycle-preference";const o={never:void 0,immediate:60,"1h":3600,"1d":86400,"7d":604800,"30d":2592e3,"1y":31536e3};function i(b){const{expiresIn:d}=b;if(d!==void 0)return typeof d=="number"?d:o[d]}function c(b){if(!b)return;const d=i(b),p={};return d!==void 0&&(p.expiration_duration_seconds=d),b.initialAcl!==void 0&&(p.initial_acl=b.initialAcl),Object.keys(p).length>0?p:void 0}function l(b){const d=c(b);return d?{[e.OBJECT_LIFECYCYLE_PREFERENCE_HEADER]:JSON.stringify(d)}:{}}function f(b){var d;const[,p]=b.split("/");return(d=p.split(/[-;]/)[0])!==null&&d!==void 0?d:"bin"}function m(b,d,p,w){return t(this,void 0,void 0,function*(){const v=b.name||`${Date.now()}.${f(p)}`,j={},P=c(w);return P&&(j["X-Fal-Object-Lifecycle"]=JSON.stringify(P)),yield(0,n.dispatchRequest)({method:"POST",targetUrl:`${(0,r.getRestApiUrl)()}/storage/upload/initiate?storage_type=fal-cdn-v3`,input:{content_type:p,file_name:v},config:d,headers:j})})}function u(b,d,p,w){return t(this,void 0,void 0,function*(){const v=b.name||`${Date.now()}.${f(p)}`,j={},P=c(w);return P&&(j["X-Fal-Object-Lifecycle"]=JSON.stringify(P)),yield(0,n.dispatchRequest)({method:"POST",targetUrl:`${(0,r.getRestApiUrl)()}/storage/upload/initiate-multipart?storage_type=fal-cdn-v3`,input:{content_type:p,file_name:v},config:d,headers:j})})}function h(b,d,p){return t(this,arguments,void 0,function*(w,v,j,P=3){if(P===0)throw new Error("Part upload failed, retries exhausted");const{fetch:C,responseHandler:$}=j;try{const R=yield C(w,{method:"PUT",body:v});return yield $(R)}catch{return yield h(w,v,j,P-1)}})}function x(b,d,p){return t(this,void 0,void 0,function*(){const{fetch:w,responseHandler:v}=d,j=b.type||"application/octet-stream",{upload_url:P,file_url:C}=yield u(b,d,j,p),$=10*1024*1024,R=Math.ceil(b.size/$),N=new URL(P),Q=[];for(let q=0;q<R;q++){const F=q*$,Y=Math.min(F+$,b.size),A=b.slice(F,Y),U=q+1,J=`${N.origin}${N.pathname}/${U}${N.search}`;Q.push(yield h(J,A,d))}const L=`${N.origin}${N.pathname}/complete${N.search}`,H=yield w(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:Q.map(q=>({partNumber:q.partNumber,etag:q.etag}))})});return yield v(H),C})}function y({config:b}){const d={upload:(p,w)=>t(this,void 0,void 0,function*(){const v=w?.lifecycle;if(p.size>94371840)return yield x(p,b,v);const j=p.type||"application/octet-stream",{fetch:P,responseHandler:C}=b,{upload_url:$,file_url:R}=yield m(p,b,j,v),N=yield P($,{method:"PUT",body:p,headers:{"Content-Type":p.type||"application/octet-stream"}});return yield C(N),R}),transformInput:p=>t(this,void 0,void 0,function*(){if(Array.isArray(p))return Promise.all(p.map(w=>d.transformInput(w)));if(p instanceof Blob)return yield d.upload(p);if((0,a.isPlainObject)(p)){const v=Object.entries(p).map(P=>t(this,[P],void 0,function*([C,$]){return[C,yield d.transformInput($)]})),j=yield Promise.all(v);return Object.fromEntries(j)}return p})};return d}}(In)),In}var Lt={},ps={},Ko;function Md(){if(Ko)return ps;Ko=1,Object.defineProperty(ps,"__esModule",{value:!0});function e(n){let a,o,i,c,l,f,m;return u(),{feed:h,reset:u};function u(){a=!0,o="",i=0,c=-1,l=void 0,f=void 0,m=""}function h(y){o=o?o+y:y,a&&r(o)&&(o=o.slice(t.length)),a=!1;const b=o.length;let d=0,p=!1;for(;d<b;){p&&(o[d]===`
2
+ `&&++d,p=!1);let w=-1,v=c,j;for(let P=i;w<0&&P<b;++P)j=o[P],j===":"&&v<0?v=P-d:j==="\r"?(p=!0,w=P-d):j===`
3
+ `&&(w=P-d);if(w<0){i=b-d,c=v;break}else i=0,c=-1;x(o,d,v,w),d+=w+1}d===b?o="":d>0&&(o=o.slice(d))}function x(y,b,d,p){if(p===0){m.length>0&&(n({type:"event",id:l,event:f||void 0,data:m.slice(0,-1)}),m="",l=void 0),f=void 0;return}const w=d<0,v=y.slice(b,b+(w?p:d));let j=0;w?j=p:y[b+d+1]===" "?j=d+2:j=d+1;const P=b+j,C=p-j,$=y.slice(P,P+C).toString();if(v==="data")m+=$?"".concat($,`
4
+ `):`
5
+ `;else if(v==="event")f=$;else if(v==="id"&&!$.includes("\0"))l=$;else if(v==="retry"){const R=parseInt($,10);Number.isNaN(R)||n({type:"reconnect-interval",value:R})}}}const t=[239,187,191];function r(n){return t.every((a,o)=>n.charCodeAt(o)===a)}return ps.createParser=e,ps}var Pn={},Yo;function ll(){return Yo||(Yo=1,function(e){var t=Pn&&Pn.__awaiter||function(i,c,l,f){function m(u){return u instanceof l?u:new l(function(h){h(u)})}return new(l||(l=Promise))(function(u,h){function x(d){try{b(f.next(d))}catch(p){h(p)}}function y(d){try{b(f.throw(d))}catch(p){h(p)}}function b(d){d.done?u(d.value):m(d.value).then(x,y)}b((f=f.apply(i,c||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.TOKEN_EXPIRATION_SECONDS=void 0,e.getTemporaryAuthToken=o;const r=Qa(),n=Qn(),a=Tr();e.TOKEN_EXPIRATION_SECONDS=120;function o(i,c){return t(this,void 0,void 0,function*(){const l=(0,a.parseEndpointId)(i),f=yield(0,n.dispatchRequest)({method:"POST",targetUrl:`${(0,r.getRestApiUrl)()}/tokens/`,config:c,input:{allowed_apps:[l.alias],token_expiration:e.TOKEN_EXPIRATION_SECONDS}});return typeof f!="string"&&f.detail?f.detail:f})}}(Pn)),Pn}var Vo;function cl(){if(Vo)return Lt;Vo=1;var e=Lt&&Lt.__awaiter||function(h,x,y,b){function d(p){return p instanceof y?p:new y(function(w){w(p)})}return new(y||(y=Promise))(function(p,w){function v(C){try{P(b.next(C))}catch($){w($)}}function j(C){try{P(b.throw(C))}catch($){w($)}}function P(C){C.done?p(C.value):d(C.value).then(v,j)}P((b=b.apply(h,x||[])).next())})},t=Lt&&Lt.__await||function(h){return this instanceof t?(this.v=h,this):new t(h)},r=Lt&&Lt.__asyncGenerator||function(h,x,y){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var b=y.apply(h,x||[]),d,p=[];return d={},v("next"),v("throw"),v("return",w),d[Symbol.asyncIterator]=function(){return this},d;function w(N){return function(Q){return Promise.resolve(Q).then(N,$)}}function v(N,Q){b[N]&&(d[N]=function(L){return new Promise(function(H,q){p.push([N,L,H,q])>1||j(N,L)})},Q&&(d[N]=Q(d[N])))}function j(N,Q){try{P(b[N](Q))}catch(L){R(p[0][3],L)}}function P(N){N.value instanceof t?Promise.resolve(N.value.v).then(C,$):R(p[0][2],N)}function C(N){j("next",N)}function $(N){j("throw",N)}function R(N,Q){N(Q),p.shift(),p.length&&j(p[0][0],p[0][1])}};Object.defineProperty(Lt,"__esModule",{value:!0}),Lt.FalStream=void 0,Lt.createStreamingClient=u;const n=Md(),a=ll(),o=Qn(),i=Xr(),c=Tr(),l="text/event-stream",f=15*1e3;class m{constructor(x,y,b){var d;this.listeners=new Map,this.buffer=[],this.currentData=void 0,this.lastEventTimestamp=0,this.streamClosed=!1,this._requestId=null,this.abortController=new AbortController,this.start=()=>e(this,void 0,void 0,function*(){var p,w,v;const{endpointId:j,options:P}=this,{input:C,method:$="post",connectionMode:R="server",tokenProvider:N}=P;try{if(R==="client"){const Q=(0,c.ensureEndpointIdFormat)(j),L=(p=(0,c.resolveEndpointPath)(j,void 0,"/stream"))!==null&&p!==void 0?p:"",q=yield(N?()=>N(`${Q}${L}`):()=>(console.warn('[fal.stream] Using the default token provider is deprecated. Please provide a `tokenProvider` function when using `connectionMode: "client"`. See https://docs.fal.ai/fal-client/authentication for more information.'),(0,a.getTemporaryAuthToken)(j,this.config)))(),{fetch:F}=this.config,Y=new URL(this.url);Y.searchParams.set("fal_jwt_token",q);const A=yield F(Y.toString(),{method:$.toUpperCase(),headers:{accept:(w=P.accept)!==null&&w!==void 0?w:l,"content-type":"application/json"},body:C&&$!=="get"?JSON.stringify(C):void 0,signal:this.abortController.signal});return this._requestId=A.headers.get("x-fal-request-id"),yield this.handleResponse(A)}return yield(0,o.dispatchRequest)({method:$.toUpperCase(),targetUrl:this.url,input:C,config:this.config,options:{headers:{accept:(v=P.accept)!==null&&v!==void 0?v:l},responseHandler:Q=>e(this,void 0,void 0,function*(){return this._requestId=Q.headers.get("x-fal-request-id"),yield this.handleResponse(Q)}),signal:this.abortController.signal}})}catch(Q){this.handleError(Q)}}),this.handleResponse=p=>e(this,void 0,void 0,function*(){var w,v;if(!p.ok){try{yield(0,i.defaultResponseHandler)(p)}catch(L){this.emit("error",L)}return}const j=p.body;if(!j){this.emit("error",new i.ApiError({message:"Response body is empty.",status:400,body:void 0,requestId:this._requestId||void 0}));return}if(!((w=p.headers.get("content-type"))!==null&&w!==void 0?w:"").startsWith(l)){const L=j.getReader(),H=()=>{L.read().then(({done:q,value:F})=>{if(q){this.emit("done",this.currentData);return}this.buffer.push(F),this.currentData=F,this.emit("data",F),H()})};H();return}const C=new TextDecoder("utf-8"),$=p.body.getReader(),R=(0,n.createParser)(L=>{if(L.type==="event"){const H=L.data;try{const q=JSON.parse(H);this.buffer.push(q),this.currentData=q,this.emit("data",q),this.emit("message",q)}catch(q){this.emit("error",q)}}}),N=(v=this.options.timeout)!==null&&v!==void 0?v:f,Q=()=>e(this,void 0,void 0,function*(){const{value:L,done:H}=yield $.read();this.lastEventTimestamp=Date.now(),R.feed(C.decode(L)),Date.now()-this.lastEventTimestamp>N&&this.emit("error",new i.ApiError({message:`Event stream timed out after ${(N/1e3).toFixed(0)} seconds with no messages.`,status:408,requestId:this._requestId||void 0})),H?this.emit("done",this.currentData):Q().catch(this.handleError)});Q().catch(this.handleError)}),this.handleError=p=>{var w;if(p.name==="AbortError"||this.signal.aborted)return;const v=p instanceof i.ApiError?p:new i.ApiError({message:(w=p.message)!==null&&w!==void 0?w:"An unknown error occurred",status:500,requestId:this._requestId||void 0});this.emit("error",v)},this.on=(p,w)=>{var v;this.listeners.has(p)||this.listeners.set(p,[]),(v=this.listeners.get(p))===null||v===void 0||v.push(w)},this.emit=(p,w)=>{const v=this.listeners.get(p)||[];for(const j of v)j(w)},this.done=()=>e(this,void 0,void 0,function*(){return this.donePromise}),this.abort=p=>{this.streamClosed||this.abortController.abort(p)},this.endpointId=x,this.config=y,this.url=(d=b.url)!==null&&d!==void 0?d:(0,o.buildUrl)(x,{path:(0,c.resolveEndpointPath)(x,void 0,"/stream"),query:b.queryParams}),this.options=b,this.donePromise=new Promise((p,w)=>{this.streamClosed&&w(new i.ApiError({message:"Streaming connection is already closed.",status:400,body:void 0,requestId:this._requestId||void 0})),this.signal.addEventListener("abort",()=>{var v;p((v=this.currentData)!==null&&v!==void 0?v:{})}),this.on("done",v=>{this.streamClosed=!0,p(v)}),this.on("error",v=>{this.streamClosed=!0,w(v)})}),b.signal&&b.signal.addEventListener("abort",()=>{this.abortController.abort()}),this.start().catch(this.handleError)}[Symbol.asyncIterator](){return r(this,arguments,function*(){let y=!0;const b=()=>y=!1;for(this.on("error",b),this.on("done",b);y||this.buffer.length>0;){const d=this.buffer.shift();d&&(yield yield t(d)),yield t(new Promise(p=>setTimeout(p,16)))}})}get signal(){return this.abortController.signal}get requestId(){return this._requestId}}Lt.FalStream=m;function u({config:h,storage:x}){return{stream(y,b){return e(this,void 0,void 0,function*(){const d=b.input?yield x.transformInput(b.input):void 0;return new m(y,h,Object.assign(Object.assign({},b),{input:d}))})}}}return Lt}var Xo;function Rd(){if(Xo)return lr;Xo=1;var e=lr&&lr.__awaiter||function(x,y,b,d){function p(w){return w instanceof b?w:new b(function(v){v(w)})}return new(b||(b=Promise))(function(w,v){function j($){try{C(d.next($))}catch(R){v(R)}}function P($){try{C(d.throw($))}catch(R){v(R)}}function C($){$.done?w($.value):p($.value).then(j,P)}C((d=d.apply(x,y||[])).next())})},t=lr&&lr.__rest||function(x,y){var b={};for(var d in x)Object.prototype.hasOwnProperty.call(x,d)&&y.indexOf(d)<0&&(b[d]=x[d]);if(x!=null&&typeof Object.getOwnPropertySymbols=="function")for(var p=0,d=Object.getOwnPropertySymbols(x);p<d.length;p++)y.indexOf(d[p])<0&&Object.prototype.propertyIsEnumerable.call(x,d[p])&&(b[d[p]]=x[d[p]]);return b};Object.defineProperty(lr,"__esModule",{value:!0}),lr.createQueueClient=void 0;const r=Ja(),n=Qn(),a=Xr(),o=Fs(),i=il(),c=cl(),l=Tr(),f=500,m={maxRetries:3,baseDelay:1e3,maxDelay:6e4,retryableStatusCodes:o.DEFAULT_RETRYABLE_STATUS_CODES},u={maxRetries:5,baseDelay:1e3,maxDelay:3e4,retryableStatusCodes:[...o.DEFAULT_RETRYABLE_STATUS_CODES,500]},h=({config:x,storage:y})=>{const b={submit(d,p){return e(this,void 0,void 0,function*(){const{webhookUrl:w,priority:v,hint:j,startTimeout:P,headers:C,storageSettings:$}=p,R=t(p,["webhookUrl","priority","hint","startTimeout","headers","storageSettings"]),N=p.input?yield y.transformInput(p.input):void 0,Q=Object.fromEntries(Object.entries(C??{}).map(([L,H])=>[L.toLowerCase(),H]));return(0,n.dispatchRequest)({method:p.method,targetUrl:(0,n.buildUrl)(d,Object.assign(Object.assign({},R),{subdomain:"queue",query:w?{fal_webhook:w}:void 0})),headers:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Q),(0,i.buildObjectLifecycleHeaders)($)),{[r.QUEUE_PRIORITY_HEADER]:v??"normal"}),j&&{[r.RUNNER_HINT_HEADER]:j}),(0,r.buildTimeoutHeaders)(P)),input:N,config:x,options:{signal:p.abortSignal,retry:m}})})},status(d,p){return e(this,arguments,void 0,function*(w,{requestId:v,logs:j=!1,abortSignal:P}){const C=(0,l.parseEndpointId)(w),$=C.namespace?`${C.namespace}/`:"";return(0,n.dispatchRequest)({method:"get",targetUrl:(0,n.buildUrl)(`${$}${C.owner}/${C.alias}`,{subdomain:"queue",query:{logs:j?"1":"0"},path:`/requests/${v}/status`}),config:x,options:{signal:P,retry:u}})})},streamStatus(d,p){return e(this,arguments,void 0,function*(w,{requestId:v,logs:j=!1,connectionMode:P}){const C=(0,l.parseEndpointId)(w),$=C.namespace?`${C.namespace}/`:"",R={logs:j?"1":"0"},N=(0,n.buildUrl)(`${$}${C.owner}/${C.alias}`,{subdomain:"queue",path:`/requests/${v}/status/stream`,query:R});return new c.FalStream(w,x,{url:N,method:"get",connectionMode:P,queryParams:R})})},subscribeToStatus(d,p){return e(this,void 0,void 0,function*(){const w=p.requestId,v=p.timeout;let j;const P=()=>{};if(p.mode==="streaming"){const C=yield b.streamStatus(d,{requestId:w,logs:p.logs,connectionMode:"connectionMode"in p?p.connectionMode:void 0}),$=[];v&&(j=setTimeout(()=>{throw C.abort(),b.cancel(d,{requestId:w}).catch(P),new Error(`Client timed out waiting for the request to complete after ${v}ms`)},v)),C.on("data",N=>{p.onQueueUpdate&&("logs"in N&&Array.isArray(N.logs)&&N.logs.length>0&&$.push(...N.logs),p.onQueueUpdate("logs"in N?Object.assign(Object.assign({},N),{logs:$}):N))});const R=yield C.done();return j&&clearTimeout(j),R}return new Promise((C,$)=>{var R;let N;const Q="pollInterval"in p&&typeof p.pollInterval=="number"&&(R=p.pollInterval)!==null&&R!==void 0?R:f,L=()=>{j&&clearTimeout(j),N&&clearTimeout(N)};v&&(j=setTimeout(()=>{L(),b.cancel(d,{requestId:w}).catch(P),$(new Error(`Client timed out waiting for the request to complete after ${v}ms`))},v));const H=()=>e(this,void 0,void 0,function*(){var q;try{const F=yield b.status(d,{requestId:w,logs:(q=p.logs)!==null&&q!==void 0?q:!1,abortSignal:p.abortSignal});if(p.onQueueUpdate&&p.onQueueUpdate(F),F.status==="COMPLETED"){L(),C(F);return}N=setTimeout(H,Q)}catch(F){L(),$(F)}});H().catch($)})})},result(d,p){return e(this,arguments,void 0,function*(w,{requestId:v,abortSignal:j}){const P=(0,l.parseEndpointId)(w),C=P.namespace?`${P.namespace}/`:"";return(0,n.dispatchRequest)({method:"get",targetUrl:(0,n.buildUrl)(`${C}${P.owner}/${P.alias}`,{subdomain:"queue",path:`/requests/${v}`}),config:Object.assign(Object.assign({},x),{responseHandler:a.resultResponseHandler}),options:{signal:j,retry:m}})})},cancel(d,p){return e(this,arguments,void 0,function*(w,{requestId:v,abortSignal:j}){const P=(0,l.parseEndpointId)(w),C=P.namespace?`${P.namespace}/`:"";yield(0,n.dispatchRequest)({method:"put",targetUrl:(0,n.buildUrl)(`${C}${P.owner}/${P.alias}`,{subdomain:"queue",path:`/requests/${v}/cancel`}),config:x,options:{signal:j}})})}};return b};return lr.createQueueClient=h,lr}var Zr={};function Ad(e){const t=e.length;let r=0,n=0;for(;n<t;){let a=e.charCodeAt(n++);if((a&4294967168)===0){r++;continue}else if((a&4294965248)===0)r+=2;else{if(a>=55296&&a<=56319&&n<t){const o=e.charCodeAt(n);(o&64512)===56320&&(++n,a=((a&1023)<<10)+(o&1023)+65536)}(a&4294901760)===0?r+=3:r+=4}}return r}function _d(e,t,r){const n=e.length;let a=r,o=0;for(;o<n;){let i=e.charCodeAt(o++);if((i&4294967168)===0){t[a++]=i;continue}else if((i&4294965248)===0)t[a++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&o<n){const c=e.charCodeAt(o);(c&64512)===56320&&(++o,i=((i&1023)<<10)+(c&1023)+65536)}(i&4294901760)===0?(t[a++]=i>>12&15|224,t[a++]=i>>6&63|128):(t[a++]=i>>18&7|240,t[a++]=i>>12&63|128,t[a++]=i>>6&63|128)}t[a++]=i&63|128}}const Ld=new TextEncoder,Dd=50;function Ud(e,t,r){Ld.encodeInto(e,t.subarray(r))}function Od(e,t,r){e.length>Dd?Ud(e,t,r):_d(e,t,r)}const Bd=4096;function dl(e,t,r){let n=t;const a=n+r,o=[];let i="";for(;n<a;){const c=e[n++];if((c&128)===0)o.push(c);else if((c&224)===192){const l=e[n++]&63;o.push((c&31)<<6|l)}else if((c&240)===224){const l=e[n++]&63,f=e[n++]&63;o.push((c&31)<<12|l<<6|f)}else if((c&248)===240){const l=e[n++]&63,f=e[n++]&63,m=e[n++]&63;let u=(c&7)<<18|l<<12|f<<6|m;u>65535&&(u-=65536,o.push(u>>>10&1023|55296),u=56320|u&1023),o.push(u)}else o.push(c);o.length>=Bd&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const $d=new TextDecoder,Fd=200;function zd(e,t,r){const n=e.subarray(t,t+r);return $d.decode(n)}function Hd(e,t,r){return r>Fd?zd(e,t,r):dl(e,t,r)}class _n{type;data;constructor(t,r){this.type=t,this.data=r}}class kt extends Error{constructor(t){super(t);const r=Object.create(kt.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:kt.name})}}const Sn=4294967295;function qd(e,t,r){const n=r/4294967296,a=r;e.setUint32(t,n),e.setUint32(t+4,a)}function ul(e,t,r){const n=Math.floor(r/4294967296),a=r;e.setUint32(t,n),e.setUint32(t+4,a)}function fl(e,t){const r=e.getInt32(t),n=e.getUint32(t+4);return r*4294967296+n}function Wd(e,t){const r=e.getUint32(t),n=e.getUint32(t+4);return r*4294967296+n}const ml=-1,Kd=4294967296-1,Yd=17179869184-1;function hl({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=Yd)if(t===0&&e<=Kd){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{const r=e/4294967296,n=e&4294967295,a=new Uint8Array(8),o=new DataView(a.buffer);return o.setUint32(0,t<<2|r&3),o.setUint32(4,n),a}else{const r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,t),ul(n,4,e),r}}function gl(e){const t=e.getTime(),r=Math.floor(t/1e3),n=(t-r*1e3)*1e6,a=Math.floor(n/1e9);return{sec:r+a,nsec:n-a*1e9}}function pl(e){if(e instanceof Date){const t=gl(e);return hl(t)}else return null}function xl(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const r=t.getUint32(0),n=t.getUint32(4),a=(r&3)*4294967296+n,o=r>>>2;return{sec:a,nsec:o}}case 12:{const r=fl(t,4),n=t.getUint32(0);return{sec:r,nsec:n}}default:throw new kt(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function bl(e){const t=xl(e);return new Date(t.sec*1e3+t.nsec/1e6)}const Vd={type:ml,encode:pl,decode:bl};class Zn{static defaultCodec=new Zn;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Vd)}register({type:t,encode:r,decode:n}){if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{const a=-1-t;this.builtInEncoders[a]=r,this.builtInDecoders[a]=n}}tryToEncode(t,r){for(let n=0;n<this.builtInEncoders.length;n++){const a=this.builtInEncoders[n];if(a!=null){const o=a(t,r);if(o!=null){const i=-1-n;return new _n(i,o)}}}for(let n=0;n<this.encoders.length;n++){const a=this.encoders[n];if(a!=null){const o=a(t,r);if(o!=null){const i=n;return new _n(i,o)}}}return t instanceof _n?t:null}decode(t,r,n){const a=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return a?a(t,r,n):new _n(r,t)}}function Xd(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function Sa(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Xd(e)?new Uint8Array(e):Uint8Array.from(e)}const Jd=100,Gd=2048;class zs{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??Zn.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??Jd,this.initialBufferSize=t?.initialBufferSize??Gd,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new zs({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,r)}ensureBufferSizeToWrite(t){const r=this.pos+t;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(t){const r=new ArrayBuffer(t),n=new Uint8Array(r),a=new DataView(r);n.set(this.bytes),this.view=a,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(t){t===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){const n=Ad(t);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),Od(t,this.bytes,this.pos),this.pos+=n}encodeObject(t,r){const n=this.extensionCodec.tryToEncode(t,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,r);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){const r=t.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);const n=Sa(t);this.writeU8a(n)}encodeArray(t,r){const n=t.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const a of t)this.doEncode(a,r+1)}countWithoutUndefined(t,r){let n=0;for(const a of r)t[a]!==void 0&&n++;return n}encodeMap(t,r){const n=Object.keys(t);this.sortKeys&&n.sort();const a=this.ignoreUndefined?this.countWithoutUndefined(t,n):n.length;if(a<16)this.writeU8(128+a);else if(a<65536)this.writeU8(222),this.writeU16(a);else if(a<4294967296)this.writeU8(223),this.writeU32(a);else throw new Error(`Too large map object: ${a}`);for(const o of n){const i=t[o];this.ignoreUndefined&&i===void 0||(this.encodeString(o),this.doEncode(i,r+1))}}encodeExtension(t){if(typeof t.data=="function"){const n=t.data(this.pos+6),a=n.length;if(a>=4294967296)throw new Error(`Too large extension object: ${a}`);this.writeU8(201),this.writeU32(a),this.writeI8(t.type),this.writeU8a(n);return}const r=t.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){const r=t.length;this.ensureBufferSizeToWrite(r),this.bytes.set(t,this.pos),this.pos+=r}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),qd(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),ul(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}function Qd(e,t){return new zs(t).encodeSharedRef(e)}function ia(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const Zd=16,eu=16;class tu{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=Zd,r=eu){this.maxKeyLength=t,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(t){return t>0&&t<=this.maxKeyLength}find(t,r,n){const a=this.caches[n-1];e:for(const o of a){const i=o.bytes;for(let c=0;c<n;c++)if(i[c]!==t[r+c])continue e;return o.str}return null}store(t,r){const n=this.caches[t.length-1],a={bytes:t,str:r};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=a:n.push(a)}decode(t,r,n){const a=this.find(t,r,n);if(a!=null)return this.hit++,a;this.miss++;const o=dl(t,r,n),i=Uint8Array.prototype.slice.call(t,r,r+n);return this.store(i,o),o}}const Na="array",Un="map_key",yl="map_value",ru=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new kt("The type of key must be string or number but "+typeof e)};class nu{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){const r=this.getUninitializedStateFromPool();r.type=Na,r.position=0,r.size=t,r.array=new Array(t)}pushMapState(t){const r=this.getUninitializedStateFromPool();r.type=Un,r.readCount=0,r.size=t,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===Na){const n=t;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(t.type===Un||t.type===yl){const n=t;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Nn=-1,Za=new DataView(new ArrayBuffer(0)),su=new Uint8Array(Za.buffer);try{Za.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Jo=new RangeError("Insufficient data"),au=new tu;class Er{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Za;bytes=su;headByte=Nn;stack=new nu;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??Zn.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??Sn,this.maxBinLength=t?.maxBinLength??Sn,this.maxArrayLength=t?.maxArrayLength??Sn,this.maxMapLength=t?.maxMapLength??Sn,this.maxExtLength=t?.maxExtLength??Sn,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:au,this.mapKeyConverter=t?.mapKeyConverter??ru}clone(){return new Er({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Nn,this.stack.reset()}setBuffer(t){const r=Sa(t);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===Nn&&!this.hasRemaining(1))this.setBuffer(t);else{const r=this.bytes.subarray(this.pos),n=Sa(t),a=new Uint8Array(r.length+n.length);a.set(r),a.set(n,r.length),this.setBuffer(a)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){const{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);const r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let r=!1,n;for await(const c of t){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{n=this.doDecodeSync(),r=!0}catch(l){if(!(l instanceof RangeError))throw l}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:a,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${ia(a)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,r){if(this.entered){yield*this.clone().decodeMultiAsync(t,r);return}try{this.entered=!0;let n=r,a=-1;for await(const o of t){if(r&&a===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),n&&(a=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--a!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const t=this.readHeadByte();let r;if(t>=224)r=t-256;else if(t<192)if(t<128)r=t;else if(t<144){const a=t-128;if(a!==0){this.pushMapState(a),this.complete();continue e}else r={}}else if(t<160){const a=t-144;if(a!==0){this.pushArrayState(a),this.complete();continue e}else r=[]}else{const a=t-160;r=this.decodeString(a,0)}else if(t===192)r=null;else if(t===194)r=!1;else if(t===195)r=!0;else if(t===202)r=this.readF32();else if(t===203)r=this.readF64();else if(t===204)r=this.readU8();else if(t===205)r=this.readU16();else if(t===206)r=this.readU32();else if(t===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(t===208)r=this.readI8();else if(t===209)r=this.readI16();else if(t===210)r=this.readI32();else if(t===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(t===217){const a=this.lookU8();r=this.decodeString(a,1)}else if(t===218){const a=this.lookU16();r=this.decodeString(a,2)}else if(t===219){const a=this.lookU32();r=this.decodeString(a,4)}else if(t===220){const a=this.readU16();if(a!==0){this.pushArrayState(a),this.complete();continue e}else r=[]}else if(t===221){const a=this.readU32();if(a!==0){this.pushArrayState(a),this.complete();continue e}else r=[]}else if(t===222){const a=this.readU16();if(a!==0){this.pushMapState(a),this.complete();continue e}else r={}}else if(t===223){const a=this.readU32();if(a!==0){this.pushMapState(a),this.complete();continue e}else r={}}else if(t===196){const a=this.lookU8();r=this.decodeBinary(a,1)}else if(t===197){const a=this.lookU16();r=this.decodeBinary(a,2)}else if(t===198){const a=this.lookU32();r=this.decodeBinary(a,4)}else if(t===212)r=this.decodeExtension(1,0);else if(t===213)r=this.decodeExtension(2,0);else if(t===214)r=this.decodeExtension(4,0);else if(t===215)r=this.decodeExtension(8,0);else if(t===216)r=this.decodeExtension(16,0);else if(t===199){const a=this.lookU8();r=this.decodeExtension(a,1)}else if(t===200){const a=this.lookU16();r=this.decodeExtension(a,2)}else if(t===201){const a=this.lookU32();r=this.decodeExtension(a,4)}else throw new kt(`Unrecognized type byte: ${ia(t)}`);this.complete();const n=this.stack;for(;n.length>0;){const a=n.top();if(a.type===Na)if(a.array[a.position]=r,a.position++,a.position===a.size)r=a.array,n.release(a);else continue e;else if(a.type===Un){if(r==="__proto__")throw new kt("The key __proto__ is not allowed");a.key=this.mapKeyConverter(r),a.type=yl;continue e}else if(a.map[a.key]=r,a.readCount++,a.readCount===a.size)r=a.map,n.release(a);else{a.key=null,a.type=Un;continue e}}return r}}readHeadByte(){return this.headByte===Nn&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Nn}readArraySize(){const t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new kt(`Unrecognized array type byte: ${ia(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new kt(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new kt(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,r):this.decodeBinary(t,r)}decodeUtf8String(t,r){if(t>this.maxStrLength)throw new kt(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+t)throw Jo;const n=this.pos+r;let a;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(t)?a=this.keyDecoder.decode(this.bytes,n,t):a=Hd(this.bytes,n,t),this.pos+=r+t,a}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Un:!1}decodeBinary(t,r){if(t>this.maxBinLength)throw new kt(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+r))throw Jo;const n=this.pos+r,a=this.bytes.subarray(n,n+t);return this.pos+=r+t,a}decodeExtension(t,r){if(t>this.maxExtLength)throw new kt(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+r),a=this.decodeBinary(t,r+1);return this.extensionCodec.decode(a,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){const t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){const t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){const t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){const t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){const t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){const t=Wd(this.view,this.pos);return this.pos+=8,t}readI64(){const t=fl(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){const t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){const t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){const t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){const t=this.view.getFloat64(this.pos);return this.pos+=8,t}}function ou(e,t){return new Er(t).decode(e)}function iu(e,t){return new Er(t).decodeMulti(e)}function lu(e){return e[Symbol.asyncIterator]!=null}async function*cu(e){const t=e.getReader();try{for(;;){const{done:r,value:n}=await t.read();if(r)return;yield n}}finally{t.releaseLock()}}function eo(e){return lu(e)?e:cu(e)}async function du(e,t){const r=eo(e);return new Er(t).decodeAsync(r)}function uu(e,t){const r=eo(e);return new Er(t).decodeArrayStream(r)}function fu(e,t){const r=eo(e);return new Er(t).decodeStream(r)}const mu=Object.freeze(Object.defineProperty({__proto__:null,DecodeError:kt,Decoder:Er,EXT_TIMESTAMP:ml,Encoder:zs,ExtData:_n,ExtensionCodec:Zn,decode:ou,decodeArrayStream:uu,decodeAsync:du,decodeMulti:iu,decodeMultiStream:fu,decodeTimestampExtension:bl,decodeTimestampToTimeSpec:xl,encode:Qd,encodeDateToTimeSpec:gl,encodeTimeSpecToTimestamp:hl,encodeTimestampExtension:pl},Symbol.toStringTag,{value:"Module"})),hu=Dc(mu);var Et={},Go;function gu(){if(Go)return Et;Go=1,Object.defineProperty(Et,"__esModule",{value:!0});function e(D){return{enumerable:!0,value:D}}function t(D){return{enumerable:!0,writable:!0,value:D}}let r={},n=()=>!0,a=()=>({}),o=D=>D,i=(D,W,K,O)=>D.apply(K,O)&&W.apply(K,O),c=(D,W,K,[O,z])=>W.call(K,D.call(K,O,z),z),l=(D,W)=>Object.freeze(Object.create(D,W));function f(D,W,K){return D.reduce((O,z)=>function(...T){return K(O,z,this,T)},W)}function m(D){return l(this,{fn:e(D)})}let u={},h=m.bind(u),x=D=>h((W,K)=>!!~D(W,K)&&W),y={},b=m.bind(y);function d(D,W){return W.filter(K=>D.isPrototypeOf(K))}function p(D,W,...K){let O=f(d(y,K).map(T=>T.fn),n,i),z=f(d(u,K).map(T=>T.fn),o,c);return l(this,{from:e(D),to:e(W),guards:e(O),reducers:e(z)})}let w={},v={},j=p.bind(w),P=p.bind(v,null);function C(D,W,K){return Y(W,D,K,this.immediates)||D}function $(D){let W=new Map;for(let K of D)W.has(K.from)||W.set(K.from,[]),W.get(K.from).push(K);return W}let R={enter:o};function N(...D){let W=d(w,D),K=d(v,D),O={final:e(D.length===0),transitions:e($(W))};return K.length&&(O.immediates=e(K),O.enter=e(C)),l(R,O)}let Q={enter(D,W,K){let O=this.fn.call(W,W.context,K);return q.isPrototypeOf(O)?l(L,{machine:e(O),transitions:e(this.transitions)}).enter(D,W,K):(O.then(z=>W.send({type:"done",data:z})).catch(z=>W.send({type:"error",error:z})),D)}},L={enter(D,W,K){if(W.child=J(this.machine,O=>{W.onChange(O),W.child==O&&O.machine.state.value.final&&(delete W.child,W.send({type:"done",data:O.context}))},W.context,K),W.child.machine.state.value.final){let O=W.child.context;return delete W.child,Y(W,D,{type:"done",data:O},this.transitions.get("done"))}return D}};function H(D,...W){let K=e($(W));return q.isPrototypeOf(D)?l(L,{machine:e(D),transitions:K}):l(Q,{fn:e(D),transitions:K})}let q={get state(){return{name:this.current,value:this.states[this.current]}}};function F(D,W,K=a){return typeof D!="string"&&(K=W||a,W=D,D=Object.keys(W)[0]),r._create&&r._create(D,W),l(q,{context:e(K),current:e(D),states:e(W)})}function Y(D,W,K,O){let{context:z}=D;for(let{to:T,guards:V,reducers:Z}of O)if(V(z,K)){D.context=Z.call(D,z,K);let ee=W.original||W,oe=l(ee,{current:e(T),original:{value:ee}});return r._onEnter&&r._onEnter(W,T,D.context,z,K),oe.state.value.enter(oe,D,K)}}function A(D,W){let K=W.type||W,{machine:O}=D,{value:z,name:T}=O.state;return z.transitions.has(K)?Y(D,O,W,z.transitions.get(K))||O:(r._send&&r._send(K,T),O)}let U={send(D){this.machine=A(this,D),this.onChange(this)}};function J(D,W,K,O){let z=Object.create(U,{machine:t(D),context:t(D.context(K,O)),onChange:e(W)});return z.send=z.send.bind(z),z.machine=z.machine.state.value.enter(z.machine,z,O),z}return Et.action=x,Et.createMachine=F,Et.d=r,Et.guard=b,Et.immediate=P,Et.interpret=J,Et.invoke=H,Et.reduce=h,Et.state=N,Et.transition=j,Et}var Qo;function pu(){if(Qo)return Zr;Qo=1;var e=Zr&&Zr.__awaiter||function(A,U,J,D){function W(K){return K instanceof J?K:new J(function(O){O(K)})}return new(J||(J=Promise))(function(K,O){function z(Z){try{V(D.next(Z))}catch(ee){O(ee)}}function T(Z){try{V(D.throw(Z))}catch(ee){O(ee)}}function V(Z){Z.done?K(Z.value):W(Z.value).then(z,T)}V((D=D.apply(A,U||[])).next())})};Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.createRealtimeClient=Y;const t=hu,r=gu(),n=ll(),a=Xr(),o=Ga(),i=Tr(),c=()=>({enqueuedMessage:void 0});function l(A){return A.token!==void 0}function f(A){return!l(A)}function m(A,U){return Object.assign(Object.assign({},A),{enqueuedMessage:U.message})}function u(A){return A.websocket&&A.websocket.readyState===WebSocket.OPEN&&A.websocket.close(),Object.assign(Object.assign({},A),{websocket:void 0})}function h(A,U){return A.websocket&&A.websocket.readyState===WebSocket.OPEN?(U.message instanceof Uint8Array||typeof U.message=="string"?A.websocket.send(U.message):A.websocket.send((0,t.encode)(U.message)),Object.assign(Object.assign({},A),{enqueuedMessage:void 0})):Object.assign(Object.assign({},A),{enqueuedMessage:U.message})}function x(A){return Object.assign(Object.assign({},A),{token:void 0})}function y(A,U){return Object.assign(Object.assign({},A),{token:U.token})}function b(A,U){return Object.assign(Object.assign({},A),{websocket:U.websocket})}const d=(0,r.createMachine)("idle",{idle:(0,r.state)((0,r.transition)("send","connecting",(0,r.reduce)(m)),(0,r.transition)("close","idle",(0,r.reduce)(u))),connecting:(0,r.state)((0,r.transition)("connecting","connecting"),(0,r.transition)("connected","active",(0,r.reduce)(b)),(0,r.transition)("connectionClosed","idle",(0,r.reduce)(u)),(0,r.transition)("send","connecting",(0,r.reduce)(m)),(0,r.transition)("close","idle",(0,r.reduce)(u)),(0,r.immediate)("authRequired",(0,r.guard)(f))),authRequired:(0,r.state)((0,r.transition)("initiateAuth","authInProgress"),(0,r.transition)("send","authRequired",(0,r.reduce)(m)),(0,r.transition)("close","idle",(0,r.reduce)(u))),authInProgress:(0,r.state)((0,r.transition)("authenticated","connecting",(0,r.reduce)(y)),(0,r.transition)("unauthorized","idle",(0,r.reduce)(x),(0,r.reduce)(u)),(0,r.transition)("send","authInProgress",(0,r.reduce)(m)),(0,r.transition)("close","idle",(0,r.reduce)(u))),active:(0,r.state)((0,r.transition)("send","active",(0,r.reduce)(h)),(0,r.transition)("authenticated","active",(0,r.reduce)(y)),(0,r.transition)("unauthorized","idle",(0,r.reduce)(x)),(0,r.transition)("connectionClosed","idle",(0,r.reduce)(x),(0,r.reduce)(u)),(0,r.transition)("close","idle",(0,r.reduce)(x),(0,r.reduce)(u)))},c);function p(A,{token:U,maxBuffering:J,path:D}){var W;if(J!==void 0&&(J<1||J>60))throw new Error("The `maxBuffering` must be between 1 and 60 (inclusive)");const K=new URLSearchParams({fal_jwt_token:U});J!==void 0&&K.set("max_buffering",J.toFixed(0));const O=(0,i.ensureEndpointIdFormat)(A),z=(W=(0,i.resolveEndpointPath)(A,D,"/realtime"))!==null&&W!==void 0?W:"";return`wss://fal.run/${O}${z}?${K.toString()}`}const w=128;function v(A){return A.status==="error"&&A.error==="Unauthorized"}const j={NORMAL_CLOSURE:1e3},P=new Map,C=new Map;function $(A,U,J){if(!P.has(A)){const D=(0,r.interpret)(d,J);P.set(A,{service:D,throttledSend:U>0?(0,i.throttle)(D.send,U,!0):D.send})}return P.get(A)}const R=()=>{},N={send:R,close:R};function Q(A){return A.status!=="error"&&A.type!=="x-fal-message"&&!L(A)}function L(A){return A.type==="x-fal-error"}function H(A){return e(this,void 0,void 0,function*(){if(typeof A=="string")return JSON.parse(A);const U=J=>e(this,void 0,void 0,function*(){return J instanceof Uint8Array?J:J instanceof Blob?new Uint8Array(yield J.arrayBuffer()):new Uint8Array(J)});return A instanceof ArrayBuffer||A instanceof Uint8Array?(0,t.decode)(yield U(A)):A instanceof Blob?(0,t.decode)(yield U(A)):A})}function q(A){return A instanceof Uint8Array?A:(0,t.encode)(A)}function F({data:A,decodeMessage:U,onResult:J,onError:D,send:W}){const K=O=>{if(v(O)){W({type:"unauthorized",error:new Error("Unauthorized")});return}if(Q(O)){J(O);return}if(L(O)){if(O.error==="TIMEOUT")return;D(new a.ApiError({message:`${O.error}: ${O.reason}`,status:400,body:O}));return}};Promise.resolve(U?U(A):A).then(K).catch(O=>{var z;D(new a.ApiError({message:(z=O?.message)!==null&&z!==void 0?z:"Failed to decode realtime message",status:400}))})}function Y({config:A}){return{connect(U,J){const{clientOnly:D=(0,i.isReact)()&&!(0,o.isBrowser)(),connectionKey:W=crypto.randomUUID(),maxBuffering:K,path:O,throttleInterval:z=w,encodeMessage:T,decodeMessage:V,tokenProvider:Z,tokenExpirationSeconds:ee}=J;if(D&&!(0,o.isBrowser)())return N;const oe=T??(je=>q(je)),ye=V??(je=>H(je));let fe,be,xe,ke=0;C.set(W,{decodeMessage:ye,onError:J.onError,onResult:J.onResult});const ne=()=>C.get(W),ve=$(W,z,({context:je,machine:Oe,send:Ke})=>{var It;const{enqueuedMessage:rt,token:vt,websocket:Ye}=je;if(be=rt,Oe.current==="active"&&rt&&Ye?.readyState===WebSocket.OPEN&&Ke({type:"send",message:rt}),Oe.current==="authRequired"&&vt===void 0&&fe!==Oe.current){Ke({type:"initiateAuth"}),ke++;const ze=ke,Ie=(0,i.ensureEndpointIdFormat)(U),Ce=(It=(0,i.resolveEndpointPath)(U,O,"/realtime"))!==null&&It!==void 0?It:"",Le=Z?()=>Z(`${Ie}${Ce}`):()=>(console.warn("[fal.realtime] Using the default token provider is deprecated. Please provide a `tokenProvider` function to `fal.realtime.connect()`. See https://docs.fal.ai/model-apis/client#client-side-usage-with-token-provider for more information."),(0,n.getTemporaryAuthToken)(U,A)),He=Z?ee:n.TOKEN_EXPIRATION_SECONDS,Te=He!==void 0?()=>{clearTimeout(xe);const Ve=Math.round(He*.9*1e3);xe=setTimeout(()=>{ze===ke&&Le().then(Je=>{ze===ke&&(queueMicrotask(()=>{Ke({type:"authenticated",token:Je})}),Te())}).catch(()=>{if(ze!==ke)return;const Je=Math.round(He*.05*1e3);xe=setTimeout(()=>{Te()},Je)})},Ve)}:R;Le().then(Ve=>{queueMicrotask(()=>{Ke({type:"authenticated",token:Ve})}),Te()}).catch(Ve=>{queueMicrotask(()=>{Ke({type:"unauthorized",error:Ve})})})}if(Oe.current==="connecting"&&fe!==Oe.current&&vt!==void 0){const ze=new WebSocket(p(U,{token:vt,maxBuffering:K,path:O}));ze.onopen=()=>{var Ie,Ce;Ke({type:"connected",websocket:ze});const Le=(Ce=(Ie=ve.service.context)===null||Ie===void 0?void 0:Ie.enqueuedMessage)!==null&&Ce!==void 0?Ce:be;Le&&(ze.send(oe(Le)),ve.service.context=Object.assign(Object.assign({},ve.service.context),{enqueuedMessage:void 0}))},ze.onclose=Ie=>{if(Ie.code!==j.NORMAL_CLOSURE){const{onError:Ce=R}=ne();Ce(new a.ApiError({message:`Error closing the connection: ${Ie.reason}`,status:Ie.code}))}Ke({type:"connectionClosed",code:Ie.code})},ze.onerror=Ie=>{const{onError:Ce=R}=ne();Ce(new a.ApiError({message:"Unknown error",status:500}))},ze.onmessage=Ie=>{const{decodeMessage:Ce=ye,onResult:Le,onError:He=R}=ne();F({data:Ie.data,decodeMessage:Ce,onResult:Le,onError:He,send:Ke})}}fe==="active"&&Oe.current!=="active"&&(clearTimeout(xe),xe=void 0),fe=Oe.current});return{send:je=>{ve.throttledSend({type:"send",message:oe(je)})},close:()=>{ve.service.send({type:"close"})}}}}}return Zr}var Zo;function ei(){if(Zo)return Qr;Zo=1;var e=Qr&&Qr.__awaiter||function(m,u,h,x){function y(b){return b instanceof h?b:new h(function(d){d(b)})}return new(h||(h=Promise))(function(b,d){function p(j){try{v(x.next(j))}catch(P){d(P)}}function w(j){try{v(x.throw(j))}catch(P){d(P)}}function v(j){j.done?b(j.value):y(j.value).then(p,w)}v((x=x.apply(m,u||[])).next())})};Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.createFalClient=f;const t=Qa(),r=Ja(),n=Rd(),a=pu(),o=Qn(),i=Xr(),c=il(),l=cl();function f(m={}){const u=(0,t.createConfig)(m),h=(0,c.createStorageClient)({config:u}),x=(0,n.createQueueClient)({config:u,storage:h}),y=(0,l.createStreamingClient)({config:u,storage:h}),b=(0,a.createRealtimeClient)({config:u});return{queue:x,realtime:b,storage:h,streaming:y,stream:y.stream,run(d){return e(this,arguments,void 0,function*(p,w={}){const v=w.input?yield h.transformInput(w.input):void 0;return(0,o.dispatchRequest)({method:w.method,targetUrl:(0,o.buildUrl)(p,w),input:v,headers:Object.assign(Object.assign({},(0,c.buildObjectLifecycleHeaders)(w.storageSettings)),(0,r.buildTimeoutHeaders)(w.startTimeout)),config:Object.assign(Object.assign({},u),{responseHandler:i.resultResponseHandler}),options:{signal:w.abortSignal,retry:{maxRetries:3,baseDelay:500,maxDelay:15e3}}})})},subscribe:(d,p)=>e(this,void 0,void 0,function*(){const{request_id:w}=yield x.submit(d,p);return p.onEnqueue&&p.onEnqueue(w),yield x.subscribeToStatus(d,Object.assign({requestId:w},p)),x.result(d,{requestId:w})})}}return Qr}var Tn={},ti;function xu(){if(ti)return Tn;ti=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.isQueueStatus=e,Tn.isCompletedQueueStatus=t;function e(r){return r&&r.status&&r.response_url}function t(r){return e(r)&&r.status==="COMPLETED"}return Tn}var ri;function bu(){return ri||(ri=1,function(e){var t=Dr&&Dr.__createBinding||(Object.create?function(f,m,u,h){h===void 0&&(h=u);var x=Object.getOwnPropertyDescriptor(m,u);(!x||("get"in x?!m.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return m[u]}}),Object.defineProperty(f,h,x)}:function(f,m,u,h){h===void 0&&(h=u),f[h]=m[u]}),r=Dr&&Dr.__exportStar||function(f,m){for(var u in f)u!=="default"&&!Object.prototype.hasOwnProperty.call(m,u)&&t(m,f,u)};Object.defineProperty(e,"__esModule",{value:!0}),e.fal=e.parseEndpointId=e.isRetryableError=e.ValidationError=e.ApiError=e.withProxy=e.withMiddleware=e.createFalClient=void 0;const n=ei();var a=ei();Object.defineProperty(e,"createFalClient",{enumerable:!0,get:function(){return a.createFalClient}});var o=ol();Object.defineProperty(e,"withMiddleware",{enumerable:!0,get:function(){return o.withMiddleware}}),Object.defineProperty(e,"withProxy",{enumerable:!0,get:function(){return o.withProxy}});var i=Xr();Object.defineProperty(e,"ApiError",{enumerable:!0,get:function(){return i.ApiError}}),Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return i.ValidationError}});var c=Fs();Object.defineProperty(e,"isRetryableError",{enumerable:!0,get:function(){return c.isRetryableError}}),r(xu(),e);var l=Tr();Object.defineProperty(e,"parseEndpointId",{enumerable:!0,get:function(){return l.parseEndpointId}}),e.fal=function(){let m=(0,n.createFalClient)();return{config(u){m=(0,n.createFalClient)(u)},get queue(){return m.queue},get realtime(){return m.realtime},get storage(){return m.storage},get streaming(){return m.streaming},run(u,h){return m.run(u,h)},subscribe(u,h){return m.subscribe(u,h)},stream(u,h){return m.stream(u,h)}}}()}(Dr)),Dr}var Ss=bu();const es={png:"image/png",jpeg:"image/jpeg",webp:"image/webp"},yu=50*1024*1024,wu=512*1024*1024;function mr(e){return typeof e=="string"&&/^https?:\/\//i.test(e)}function Fn(e){return typeof e=="string"&&e.startsWith("data:")}function Ur(e,t){return e.startsWith("data:")?e:`data:${t};base64,${e}`}function ni(e){return`${(e/1024/1024).toFixed(1)} MiB`}function gn(e){return e.length}function Ns(e){const t=e.indexOf(",");if(t<0)return e.length;const r=e.slice(0,t),n=e.slice(t+1);if(!/;base64/i.test(r))return decodeURIComponent(n).length;const a=n.replace(/\s/g,""),o=a.endsWith("==")?2:a.endsWith("=")?1:0;return Math.max(0,Math.floor(a.length*3/4)-o)}function wl(e,t,r){if(t>r)throw new Error(`${e}过大:${ni(t)},上限为 ${ni(r)}`)}function ts(e){wl("图像输入有效负载总大小",e,wu)}function Pr(e,t){wl(e,t,yu)}async function vu(e,t){const r=new Uint8Array(await e.arrayBuffer());let n="";for(let a=0;a<r.length;a+=32768){const o=r.subarray(a,a+32768);n+=String.fromCharCode(...o)}return`data:${e.type||t};base64,${btoa(n)}`}const vs=" 可点链接按钮复制结果链接,或尝试开启「返回 Base64 图片数据」避免此问题。";async function ku(e,t=8e3){const r=new AbortController,n=setTimeout(()=>r.abort(),t);try{return(await fetch(e,{method:"GET",mode:"no-cors",cache:"no-store",signal:r.signal})).type==="opaque"?"opaque":"reachable"}catch{return"failed"}finally{clearTimeout(n)}}async function to(e,t,r){if(Fn(e))return e;let n;try{n=await fetch(e,{cache:"no-store",signal:r})}catch(o){throw o instanceof TypeError?await ku(e)==="opaque"?new Error(`图片已生成,但因服务商未允许跨域,图片链接下载失败。${vs}`):typeof navigator<"u"&&navigator.onLine===!1?new Error(`图片链接下载失败(网络不可用)。${vs}`):new Error(`图片链接下载失败(可能因跨域限制、链接过期或网络异常)。${vs}`):o}if(!n.ok)throw new Error(`图片 URL 下载失败:HTTP ${n.status}`);const a=await n.blob();return vu(a,t)}async function Hs(e){let t=`HTTP ${e.status}`;try{const r=await e.json();r.error?.message?t=r.error.message:typeof r.detail=="string"?t=r.detail:Array.isArray(r.detail)?t=r.detail.map(n=>typeof n=="string"?n:JSON.stringify(n)).join(`
6
+ `):typeof r.error=="string"?t=r.error:r.message&&(t=r.message)}catch{try{t=await e.text()}catch{}}return t}function vl(e){if(!e||typeof e!="object")return{};const t=e,r={};return typeof t.size=="string"&&(r.size=t.size),(t.quality==="auto"||t.quality==="low"||t.quality==="medium"||t.quality==="high")&&(r.quality=t.quality),(t.output_format==="png"||t.output_format==="jpeg"||t.output_format==="webp")&&(r.output_format=t.output_format),typeof t.output_compression=="number"&&(r.output_compression=t.output_compression),(t.moderation==="auto"||t.moderation==="low")&&(r.moderation=t.moderation),typeof t.n=="number"&&(r.n=t.n),r}function Kr(...e){const t=Object.assign({},...e.filter(r=>r&&Object.keys(r).length));return Object.keys(t).length?t:void 0}const ju={width:1360,height:1024};function Iu(e,t){const r=e.trim().replace(/^\/+/,"").replace(/\/+$/,"")||"openai/gpt-image-2";return t&&!r.endsWith("/edit")?`${r}/edit`:r}async function Pu(e){const t=e.match(/^(\d+)x(\d+)$/);return t?{width:Number(t[1]),height:Number(t[2])}:ju}function Su(e){return e==="auto"?"high":e}function kl(e){const t=e.baseUrl.trim().replace(/\/+$/,"")||Zt,r={credentials:e.apiKey,suppressLocalCredentialsWarning:!0};t!==Zt&&(r.proxyUrl=t),Ss.fal.config(r)}async function Nu(e){const t=e.inputImageDataUrls.length>0,r={prompt:e.prompt,image_size:t&&e.params.size==="auto"?"auto":await Pu(e.params.size),quality:Su(e.params.quality),num_images:Math.min(4,Math.max(1,e.params.n||1)),output_format:e.params.output_format};return t&&(r.image_urls=e.inputImageDataUrls),e.maskDataUrl&&(r.mask_url=e.maskDataUrl),r}function Tu(e,t){if(typeof e=="string")return mr(e)||Fn(e)?e:Ur(e,t);if(!e||typeof e!="object")return null;const r=e;return mr(r.url)||Fn(r.url)?r.url:typeof r.b64_json=="string"?Ur(r.b64_json,t):typeof r.base64=="string"?Ur(r.base64,t):typeof r.data=="string"?Ur(r.data,t):null}function Eu(e){if(!e||typeof e!="object")return;const t=e,r=typeof t.width=="number"?t.width:null,n=typeof t.height=="number"?t.height:null;if(!(!r||!n||!Number.isFinite(r)||!Number.isFinite(n)))return{size:`${Math.round(r)}x${Math.round(n)}`}}async function Cu(e,t,r,n){const a=[];Array.isArray(e.images)&&a.push(...e.images),e.image&&a.push(e.image),e.url&&a.push(e.url);const o=[],i=[];try{for(const c of a){const l=Tu(c,t);l&&(mr(l)&&i.push(l),o.push({image:mr(l)?await to(l,t,n):l,actualParams:Eu(c),rawImageUrl:mr(l)?l:void 0}))}}catch(c){throw i.length>0&&c instanceof Error&&(c.rawImageUrls=i),c}if(!o.length){const c=new Error(r?`${r} 没有返回可识别的图片数据,请查看原始响应内容确认实际返回的数据结构。如果当前接口与 fal.ai 格式不兼容,建议创建并使用「自定义服务商」配置。`:"fal.ai 未返回可用图片数据");throw r&&(c.rawResponsePayload=JSON.stringify(e,null,2)),c}return o}async function jl(e,t,r,n){const a=es[t.output_format]||"image/png",o=await Cu(e,a,r,n),i=Kr(o[0]?.actualParams),c=o.map(l=>l.rawImageUrl).filter(l=>!!l);return{images:o.map(l=>l.image),actualParams:i,actualParamsList:o.map(l=>l.actualParams),revisedPrompts:o.map(()=>{}),...c.length?{rawImageUrls:c}:{}}}function Il(e){const t=e&&typeof e=="object"&&"body"in e?e.body:null;if(!t||typeof t!="object")return null;const r=t.detail;if(typeof r=="string"&&r.trim())return r;if(Array.isArray(r)){const a=r.map(o=>{if(typeof o=="string")return o;if(o&&typeof o=="object"){const i=o;if(typeof i.msg=="string"&&i.msg.trim())return i.msg;if(typeof i.message=="string"&&i.message.trim())return i.message}return null}).filter(o=>!!o);if(a.length)return a.join(`
7
+ `)}const n=t.message;return typeof n=="string"&&n.trim()?n:null}function Pl(e){const t=e.baseUrl.trim().replace(/\/+$/,"");return!t||t===Zt?null:t.replace(/^https?:\/\//,"")}async function Mu(e,t,r,n){kl(e),await Ss.fal.queue.subscribeToStatus(t,{requestId:r,logs:!0});const a=await Ss.fal.queue.result(t,{requestId:r});return jl(a.data,n,Pl(e))}async function Ru(e,t){try{e.maskDataUrl&&(Pr("遮罩主图文件",Ns(e.inputImageDataUrls[0]??"")),Pr("遮罩文件",Ns(e.maskDataUrl))),ts(e.inputImageDataUrls.reduce((c,l)=>c+gn(l),0)+(e.maskDataUrl?gn(e.maskDataUrl):0)),kl(t);const r=e.inputImageDataUrls.length>0,n=Iu(t.model,r),a=await Nu(e),o=await Ss.fal.subscribe(n,{input:a,logs:!0,onEnqueue:c=>{e.onFalRequestEnqueued?.({requestId:c,endpoint:n})}}),i=o.data;return e.onFalRequestEnqueued?.({requestId:o.requestId,endpoint:n}),jl(i,e.params,Pl(t))}catch(r){const n=Il(r);throw n?new Error(n):r}}function Au(e,t){const r=e.find(n=>n.id===t);if(!r)throw new Error("遮罩主图已不存在,请重新选择遮罩区域");return r}function _u(e,t){return[Au(e,t),...e.filter(n=>n.id!==t)]}function Lu(e){let t=0,r=0;const n=e.data.length/4;for(let a=3;a<e.data.length;a+=4)e.data[a]<255&&t++,e.data[a]===0&&r++;return t===0?"empty":r===n?"full":"partial"}function Du(e){if(e==="empty")throw new Error("请先涂抹需要编辑的区域")}async function Sr(e){return new Promise((t,r)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>r(new Error("图片加载失败")),n.src=e})}async function ro(e,t="image/png"){const n=await(await fetch(e)).blob();return n.type?n:new Blob([await n.arrayBuffer()],{type:t})}async function no(e){const t=await Sr(e),r=document.createElement("canvas");r.width=t.naturalWidth,r.height=t.naturalHeight;const n=r.getContext("2d");if(!n)throw new Error("当前浏览器不支持 Canvas");return n.drawImage(t,0,0),so(r,"image/png")}async function Sl(e){const t=await ro(e,"image/png");return t.type!=="image/png"?no(e):t}async function so(e,t="image/png",r){return new Promise((n,a)=>{e.toBlob(o=>{o?n(o):a(new Error("图片导出失败"))},t,r)})}async function Uu(e,t){const[r,n]=await Promise.all([Sr(e),Sr(t)]);if(r.naturalWidth!==n.naturalWidth||r.naturalHeight!==n.naturalHeight)throw new Error("遮罩尺寸与遮罩主图不一致,请重新绘制遮罩");const a=document.createElement("canvas");a.width=r.naturalWidth,a.height=r.naturalHeight;const o=a.getContext("2d",{willReadFrequently:!0});if(!o)throw new Error("当前浏览器不支持 Canvas");o.drawImage(r,0,0);const i=Lu(o.getImageData(0,0,a.width,a.height));return Du(i),i}async function ao(e,t){const[r,n]=await Promise.all([Sr(e),Sr(t)]);if(r.naturalWidth!==n.naturalWidth||r.naturalHeight!==n.naturalHeight)throw new Error("遮罩尺寸与遮罩主图不一致,请重新绘制遮罩");const a=document.createElement("canvas");a.width=r.naturalWidth,a.height=r.naturalHeight;const o=a.getContext("2d",{willReadFrequently:!0});if(!o)throw new Error("当前浏览器不支持 Canvas");o.drawImage(r,0,0);const i=document.createElement("canvas");i.width=n.naturalWidth,i.height=n.naturalHeight;const c=i.getContext("2d",{willReadFrequently:!0});if(!c)throw new Error("当前浏览器不支持 Canvas");c.drawImage(n,0,0);const l=c.getImageData(0,0,i.width,i.height),f=o.createImageData(a.width,a.height);for(let h=0;h<l.data.length;h+=4){const x=255-l.data[h+3];f.data[h]=59,f.data[h+1]=130,f.data[h+2]=246,f.data[h+3]=Math.round(x*.58)}const m=document.createElement("canvas");m.width=a.width,m.height=a.height;const u=m.getContext("2d");if(!u)throw new Error("当前浏览器不支持 Canvas");return u.putImageData(f,0,0),o.drawImage(m,0,0),a.toDataURL("image/png")}const Ou="/api-proxy";function Ts(e){const t=e.trim();if(!t)return"";const r=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//.test(t)?t:`https://${t}`;try{const n=new URL(r),a=n.pathname.split("/").filter(Boolean),o=a.indexOf("v1"),i=o>=0?a.slice(0,o+1):a.length?[...a,"v1"]:[],c=i.length?`/${i.join("/")}`:"";return`${n.origin}${c}`}catch{return t.replace(/\/+$/,"")}}function zn(e,t,r,n=!1){const a=Ts(e),o=t.replace(/^\/+/,""),i=a.endsWith("/v1")?o:["v1",o].join("/");return n?`${r?.prefix??Ou}/${i}`:a?`${a}/${i}`:`/${i}`}function Bu(e,t){return null}function Cr(){return Bu(typeof __DEV_PROXY_CONFIG__>"u"?null:__DEV_PROXY_CONFIG__)}function oo(e=Cr()){return un()==="true"||!!e?.enabled}function Nl(e=Cr()){return un()==="true"&&oo(e)}function Tl(e,t=Cr()){return oo(t)&&(e||Nl(t))}const El="Use the following text as the complete prompt. Do not rewrite it:";function Cl(e,t){if(!t||!Object.keys(t).length)return e;const r=new URLSearchParams;for(const[n,a]of Object.entries(t))r.set(n,a);return`${e}${e.includes("?")?"&":"?"}${r.toString()}`}function $u(e){return{generationPath:"images/generations",editPath:"images/edits"}}function Or(e,t){return t?t.split(".").filter(Boolean).reduce((r,n)=>{if(r!=null){if(/^\d+$/.test(n)&&Array.isArray(r))return r[Number(n)];if(typeof r=="object")return r[n]}},e):e}function si(e,t){if(!t)return[e];const r=t.split(".").filter(Boolean);let n=[e];for(const a of r){const o=[];for(const i of n)if(i!=null){if(a==="*"){Array.isArray(i)?o.push(...i):typeof i=="object"&&o.push(...Object.values(i));continue}if(/^\d+$/.test(a)&&Array.isArray(i)){o.push(i[Number(a)]);continue}typeof i=="object"&&o.push(i[a])}n=o}return n.flatMap(a=>Array.isArray(a)?a:[a]).filter(a=>a!=null)}function qs(e){return{Authorization:`Bearer ${e.apiKey}`}}function Fu(e,t,r,n){const a={type:"image_generation",action:t?"edit":"generate",size:e.size,output_format:e.output_format};return r.codexCli||(a.quality=e.quality),e.output_format!=="png"&&e.output_compression!=null&&(a.output_compression=e.output_compression),n&&(a.input_image_mask={image_url:n}),a}function zu(e,t){const r=`${El}
8
+ ${e}`;return t.length?[{role:"user",content:[{type:"input_text",text:r},...t.map(n=>({type:"input_image",image_url:n}))]}]:r}function Hu(e,t){const r=e.output;if(!Array.isArray(r)||!r.length){const a=new Error("接口未返回图片数据");throw a.rawResponsePayload=JSON.stringify(e,null,2),a}const n=[];for(const a of r){if(a?.type!=="image_generation_call")continue;const o=a.result;typeof o=="string"&&o.trim()&&n.push({image:Ur(o,t),actualParams:Kr(vl(a)),revisedPrompt:typeof a.revised_prompt=="string"?a.revised_prompt:void 0})}if(!n.length){const a=new Error("接口没有返回可识别的图片数据,请查看原始响应内容确认服务商实际返回的数据结构。如果使用的是中转或兼容接口,建议创建并使用「自定义服务商」配置。");throw a.rawResponsePayload=JSON.stringify(e,null,2),a}return n}async function qu(e,t,r){const n=e.data;if(!Array.isArray(n)||!n.length){const l=new Error("接口没有返回图片数据,请查看原始响应内容确认服务商实际返回的数据结构。如果使用的是中转或兼容接口,建议创建并使用「自定义服务商」配置。");throw l.rawResponsePayload=JSON.stringify(e,null,2),l}const a=[],o=n.map(l=>l.url).filter(mr),i=[];try{for(const l of n){const f=l.b64_json;if(f){a.push(Ur(f,t)),i.push(typeof l.revised_prompt=="string"?l.revised_prompt:void 0);continue}(mr(l.url)||Fn(l.url))&&(a.push(await to(l.url,t,r)),i.push(typeof l.revised_prompt=="string"?l.revised_prompt:void 0))}}catch(l){throw o.length>0&&l instanceof Error&&(l.rawImageUrls=o),l}if(!a.length){const l=new Error("接口没有返回可识别的图片数据,请查看原始响应内容确认服务商实际返回的数据结构。如果使用的是中转或兼容接口,建议创建并使用「自定义服务商」配置。");throw l.rawResponsePayload=JSON.stringify(e,null,2),l}const c=Kr(vl(e));return{images:a,actualParams:c,actualParamsList:a.map(()=>c),revisedPrompts:i,...o.length?{rawImageUrls:o}:{}}}async function Wu(e,t,r){return r?n0(e,t,r):t.apiMode==="responses"?s0(e,t):Ku(e,t)}async function Ku(e,t,r){const n=e.params.n>0?e.params.n:1;return t.codexCli&&n>1?Yu(e,t,n):Ml(e,t)}async function Yu(e,t,r,n){const a={...e,params:{...e.params,n:1,quality:"auto"}},o=await Promise.allSettled(Array.from({length:r}).map(()=>Ml(a,t))),i=o.filter(h=>h.status==="fulfilled").map(h=>h.value);if(i.length===0){const h=o.find(x=>x.status==="rejected");throw h?h.reason:new Error("所有并发请求均失败")}const c=i.flatMap(h=>h.images),l=i.flatMap(h=>h.actualParamsList?.length?h.actualParamsList:h.images.map(()=>h.actualParams)),f=i.flatMap(h=>h.revisedPrompts?.length?h.revisedPrompts:h.images.map(()=>{})),m=i.flatMap(h=>h.rawImageUrls??[]),u=Kr(i[0]?.actualParams??{},{n:c.length});return{images:c,actualParams:u,actualParamsList:l,revisedPrompts:f,...m.length?{rawImageUrls:m}:{}}}async function Ml(e,t,r){const{prompt:n,params:a,inputImageDataUrls:o}=e,i=t.codexCli?`${El}
9
+ ${n}`:n,c=o.length>0,l=es[a.output_format]||"image/png",f=Cr(),m=Tl(t.apiProxy,f),u=qs(t),h=$u(),x=new AbortController,y=setTimeout(()=>x.abort(),t.timeout*1e3);try{let b;if(c){const d=new FormData;d.append("model",t.model),d.append("prompt",i),d.append("size",a.size),d.append("output_format",a.output_format),d.append("moderation",a.moderation),t.codexCli||d.append("quality",a.quality),a.output_format!=="png"&&a.output_compression!=null&&d.append("output_compression",String(a.output_compression)),a.n>1&&d.append("n",String(a.n)),t.responseFormatB64Json&&d.append("response_format","b64_json");const p=[];for(let v=0;v<o.length;v++){const j=o[v],P=e.maskDataUrl&&v===0?await no(j):await ro(j);p.push(P)}const w=e.maskDataUrl?await Sl(e.maskDataUrl):null;e.maskDataUrl&&(Pr("遮罩主图文件",p[0]?.size??0),Pr("遮罩文件",w?.size??0)),ts(p.reduce((v,j)=>v+j.size,0)+(w?.size??0));for(let v=0;v<p.length;v++){const j=p[v],P=j.type.split("/")[1]||"png";d.append("image[]",j,`input-${v+1}.${P}`)}w&&d.append("mask",w,"mask.png"),b=await fetch(zn(t.baseUrl,h.editPath,f,m),{method:"POST",headers:u,cache:"no-store",body:d,signal:x.signal})}else{const d={model:t.model,prompt:i,size:a.size,output_format:a.output_format,moderation:a.moderation};t.codexCli||(d.quality=a.quality),a.output_format!=="png"&&a.output_compression!=null&&(d.output_compression=a.output_compression),a.n>1&&(d.n=a.n),t.responseFormatB64Json&&(d.response_format="b64_json"),b=await fetch(zn(t.baseUrl,h.generationPath,f,m),{method:"POST",headers:{...u,"Content-Type":"application/json"},cache:"no-store",body:JSON.stringify(d),signal:x.signal})}if(!b.ok)throw new Error(await Hs(b));return qu(await b.json(),l,x.signal)}finally{clearTimeout(y)}}function Vu(e,t){return new Promise((r,n)=>{if(t.aborted){n(new DOMException("Aborted","AbortError"));return}const a=setTimeout(r,e);t.addEventListener("abort",()=>{clearTimeout(a),n(new DOMException("Aborted","AbortError"))},{once:!0})})}function Xu(e,t){const r=Or(e,t.statusPath),n=typeof r=="string"?r:String(r??"");return t.successValues.includes(n)?"success":t.failureValues.includes(n)?"failure":"pending"}function ai(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError")return!0;const t=e instanceof Error?e.message:String(e);return/abort|network|failed to fetch|fetch failed|load failed|timeout|连接|断开|中断/i.test(t)}function Ju(e){return e===408||e===429||e>=500}function Gu(e,t){return e.replace(/\{task_id\}/g,encodeURIComponent(t)).replace(/\{taskId\}/g,encodeURIComponent(t))}function Hn(e,t){if(typeof e=="string"&&e.startsWith("$"))return Or(t,e.slice(1));if(Array.isArray(e))return e.map(r=>Hn(r,t)).filter(r=>r!=null);if(e&&typeof e=="object"){const r=Object.entries(e).map(([n,a])=>[n,Hn(a,t)]).filter(([,n])=>n!=null&&(!Array.isArray(n)||n.length>0));return Object.fromEntries(r)}return e}function Qu(e,t){return{profile:t,prompt:e.prompt,params:e.params,inputImages:{dataUrls:e.inputImageDataUrls.length?e.inputImageDataUrls:void 0,count:e.inputImageDataUrls.length},mask:{dataUrl:e.maskDataUrl}}}function Zu(e,t){if(!e)return;const r=Object.entries(e).map(([n,a])=>[n,Hn(a,t)]).filter(([,n])=>n!=null&&String(n)!=="").map(([n,a])=>[n,String(a)]);return r.length?Object.fromEntries(r):void 0}async function e0(e,t,r){const n=new FormData,a=Hn(e.body??{},r);if(a&&typeof a=="object"&&!Array.isArray(a)){for(const[f,m]of Object.entries(a))if(m!=null)if(Array.isArray(m))for(const u of m)n.append(f,String(u));else n.append(f,String(m))}const o=e.files?.some(f=>f.source==="inputImages"),i=e.files?.some(f=>f.source==="mask"),c=[];if(o)for(let f=0;f<t.inputImageDataUrls.length;f++){const m=t.inputImageDataUrls[f],u=t.maskDataUrl&&f===0?await no(m):await ro(m);c.push(u)}const l=i&&t.maskDataUrl?await Sl(t.maskDataUrl):null;t.maskDataUrl&&(o||i)&&(Pr("遮罩主图文件",c[0]?.size??0),Pr("遮罩文件",l?.size??0)),ts(c.reduce((f,m)=>f+m.size,0)+(l?.size??0));for(const f of e.files??[])if(f.source==="inputImages")for(let m=0;m<c.length;m++){const u=c[m],h=u.type.split("/")[1]||"png";n.append(f.field,u,`input-${m+1}.${h}`)}else f.source==="mask"&&l&&n.append(f.field,l,"mask.png");return n}async function Rl(e,t,r,n){const a=[],o=(t.imageUrlPaths??[]).flatMap(c=>si(e,c).filter(l=>mr(l)||Fn(l))),i=o.filter(mr);try{for(const c of t.b64JsonPaths??[])for(const l of si(e,c))typeof l=="string"&&l.trim()&&a.push(Ur(l,r));for(const c of o)a.push(await to(c,r,n))}catch(c){throw i.length>0&&c instanceof Error&&(c.rawImageUrls=i),c}if(!a.length){const c=new Error("接口没有返回可识别的图片数据,请查看原始响应内容确认接口实际返回的数据结构,并根据 API 文档调整「自定义服务商」配置中的结果提取路径。");throw c.rawResponsePayload=JSON.stringify(e,null,2),c}return{images:a,...i.length?{rawImageUrls:i}:{}}}async function t0(e,t,r,n){const a=Cr(),o=qs(r),i=Qu(t,r),c=e.method??"POST",l=e.contentType??"json",f=Cl(e.path,Zu(e.query,i)),m={...o};let u;if(c!=="GET")if(l==="multipart"){const x=await e0(e,t,i);r.responseFormatB64Json&&x.append("response_format","b64_json"),u=x}else{ts(t.inputImageDataUrls.reduce((y,b)=>y+gn(b),0)+(t.maskDataUrl?gn(t.maskDataUrl):0)),m["Content-Type"]="application/json";const x=Hn(e.body??{},i);r.responseFormatB64Json&&x&&typeof x=="object"&&!Array.isArray(x)&&(x.response_format="b64_json"),u=JSON.stringify(x)}const h=await fetch(zn(r.baseUrl,f,a,!1),{method:c,headers:m,cache:"no-store",body:u,signal:n.signal});if(!h.ok)throw new Error(await Hs(h));return h.json()}async function Al(e,t,r,n,a){const o=Cr(),i=qs(e);let c=!0;for(;;){c?c=!1:a?await Vu((t.intervalSeconds??5)*1e3,a):await new Promise(u=>setTimeout(u,(t.intervalSeconds??5)*1e3));const l=Cl(Gu(t.path,r),t.query);let f;try{const u=await fetch(zn(e.baseUrl,l,o,!1),{method:t.method??"GET",headers:i,cache:"no-store",signal:a});if(!u.ok){if(Ju(u.status))continue;throw new Error(await Hs(u))}f=await u.json()}catch(u){if(!a?.aborted&&ai(u))continue;throw u}const m=Xu(f,t);if(m==="failure"){const u=Or(f,t.errorPath)||Or(f,"message")||Or(f,"data.fail_reason")||Or(f,"error.message");throw new Error(typeof u=="string"&&u.trim()?u:"异步任务失败")}if(m==="success")try{return await Rl(f,t.result,n,a)}catch(u){if(!a?.aborted&&ai(u))continue;throw u}}}async function r0(e,t,r,n){if(!t.poll)throw new Error("自定义异步任务缺少 poll 配置");const a=es[n.output_format]||"image/png";return Al(e,t.poll,r,a)}async function n0(e,t,r){const{params:n,inputImageDataUrls:a}=e,o=a.length>0,i=es[n.output_format]||"image/png",c=new AbortController;let l=setTimeout(()=>c.abort(),t.timeout*1e3);try{const f=o&&r.editSubmit?r.editSubmit:r.submit,m=await t0(f,e,t,c),u=f.taskIdPath?Or(m,f.taskIdPath):void 0,h=typeof u=="string"?u.trim():String(u??"").trim();if(f.taskIdPath&&!h){const x=new Error("无法从响应中提取异步任务 ID,请查看原始响应内容确认接口实际返回的数据结构,并根据 API 文档调整「自定义服务商」配置中的 taskIdPath。");throw x.rawResponsePayload=JSON.stringify(m,null,2),x}if(!h)return Rl(m,f.result??{},i,c.signal);if(!r.poll)throw new Error("异步接口返回了 task_id,但服务商配置缺少 poll");return e.onCustomTaskEnqueued?.({taskId:h}),l&&(clearTimeout(l),l=null),Al(t,r.poll,h,i,c.signal)}finally{l&&clearTimeout(l)}}async function s0(e,t){const r=e.params.n>0?e.params.n:1;if(r===1)return oi(e,t);const n=Array.from({length:r}).map(()=>oi(e,t)),a=await Promise.allSettled(n),o=a.filter(u=>u.status==="fulfilled").map(u=>u.value);if(o.length===0){const u=a.find(h=>h.status==="rejected");throw u?u.reason:new Error("所有并发请求均失败")}const i=o.flatMap(u=>u.images),c=o.flatMap(u=>u.actualParamsList?.length?u.actualParamsList:u.images.map(()=>u.actualParams)),l=o.flatMap(u=>u.revisedPrompts?.length?u.revisedPrompts:u.images.map(()=>{})),f=o.flatMap(u=>u.rawImageUrls??[]),m=Kr(o[0]?.actualParams??{},i.length===e.params.n?{n:e.params.n}:{n:i.length});return{images:i,actualParams:m,actualParamsList:c,revisedPrompts:l,...f.length?{rawImageUrls:f}:{}}}async function oi(e,t){const{prompt:r,params:n,inputImageDataUrls:a}=e,o=es[n.output_format]||"image/png",i=Cr(),c=Tl(t.apiProxy,i),l=qs(t),f=new AbortController,m=setTimeout(()=>f.abort(),t.timeout*1e3);try{e.maskDataUrl&&(Pr("遮罩主图文件",Ns(a[0]??"")),Pr("遮罩文件",Ns(e.maskDataUrl))),ts(a.reduce((d,p)=>d+gn(p),0)+(e.maskDataUrl?gn(e.maskDataUrl):0));const u={model:t.model,input:zu(r,a),tools:[Fu(n,a.length>0,t,e.maskDataUrl)],tool_choice:"required"},h=await fetch(zn(t.baseUrl,"responses",i,c),{method:"POST",headers:{...l,"Content-Type":"application/json"},cache:"no-store",body:JSON.stringify(u),signal:f.signal});if(!h.ok)throw new Error(await Hs(h));const x=await h.json(),y=Hu(x,o),b=Kr(y[0]?.actualParams??{});return{images:y.map(d=>d.image),actualParams:b,actualParamsList:y.map(d=>Kr(d.actualParams??{})),revisedPrompts:y.map(d=>d.revisedPrompt)}}finally{clearTimeout(m)}}async function a0(e){const t=et(e.settings);return t.provider==="fal"?Ru(e,t):Wu(e,t,Xn(e.settings,t.provider))}const o0=/^\s*(\d+)\s*[xX×]\s*(\d+)\s*$/,i0=/^\s*(\d+(?:\.\d+)?)\s*[:xX×]\s*(\d+(?:\.\d+)?)\s*$/,Dt=16,ii=3840,xs=3,li=655360,ci=8294400;function sn(e,t){return Math.max(t,Math.round(e/t)*t)}function bs(e,t){return Math.max(t,Math.floor(e/t)*t)}function di(e,t){return Math.max(t,Math.ceil(e/t)*t)}function l0(e,t){let r=sn(e,Dt),n=sn(t,Dt);const a=i=>{r=bs(r*i,Dt),n=bs(n*i,Dt)},o=i=>{r=di(r*i,Dt),n=di(n*i,Dt)};for(let i=0;i<4;i++){const c=Math.max(r,n);c>ii&&a(ii/c),r/n>xs?r=bs(n*xs,Dt):n/r>xs&&(n=bs(r*xs,Dt));const l=r*n;l>ci?a(Math.sqrt(ci/l)):l<li&&o(Math.sqrt(li/l))}return{width:r,height:n}}function Yr(e){const t=e.trim(),r=t.match(o0);if(!r)return t;const{width:n,height:a}=l0(Number(r[1]),Number(r[2]));return`${n}x${a}`}function _l(e){const t=e.match(i0);if(!t)return null;const r=Number(t[1]),n=Number(t[2]);return!Number.isFinite(r)||!Number.isFinite(n)||r<=0||n<=0?null:{width:r,height:n}}function Ll(e,t){const r=Math.round(e),n=Math.round(t);if(!Number.isFinite(r)||!Number.isFinite(n)||r<=0||n<=0)return"";const a=(y,b)=>b===0?y:a(b,y%b),o=a(r,n),i=r/o,c=n/o,l=`${i}:${c}`,f=[[1,1],[4,3],[3,4],[3,2],[2,3],[16,9],[9,16],[21,9],[9,21]];for(const[y,b]of f)if(i===y&&c===b)return l;const m=r/n;if(Math.abs(m-1)<=.18)return"≈1:1";const h=f.map(([y,b])=>{const d=y/b;return{label:`${y}:${b}`,delta:Math.abs(m-d)/d}}).sort((y,b)=>y.delta-b.delta)[0];if(h&&h.delta<=.01)return`≈${h.label}`;const x=Array.from({length:12},(y,b)=>b+1).flatMap(y=>Array.from({length:12},(b,d)=>d+1).map(b=>{const d=y/b,p=Math.abs(m-d)/d;return{label:`${y}:${b}`,delta:p,score:p+(y+b)*.002}})).filter(y=>y.label!==l).sort((y,b)=>y.score-b.score)[0];return x&&x.delta<=.04?`≈${x.label}`:l}function Dl(e,t){const r=_l(t);if(!r)return null;const{width:n,height:a}=r;if(n===a){const l=e==="1K"?1024:e==="2K"?2048:3840;return Yr(`${l}x${l}`)}if(e==="1K"){const f=n>a?sn(1024*n/a,Dt):1024,m=n>a?1024:sn(1024*a/n,Dt);return`${f}x${m}`}const o=e==="2K"?2048:3840,i=n>a?o:sn(o*n/a,Dt),c=n>a?sn(o*a/n,Dt):o;return Yr(`${i}x${c}`)}const Ta="1360x1024",c0=4,d0=10;function Ul(e){return et(e).provider==="fal"?c0:d0}function Ws(e,t,r={}){const n=et(t),a=Ul(t),o={...e,size:Yr(e.size)||Xt.size,n:Math.min(a,Math.max(1,e.n||Xt.n))};return n.provider==="openai"&&n.codexCli&&(o.quality=Xt.quality),n.provider==="fal"&&(!r.hasInputImages&&o.size==="auto"&&(o.size=Ta),o.quality==="auto"&&(o.quality="high"),o.moderation=Xt.moderation,o.output_compression=Xt.output_compression),o.output_format==="png"&&(o.output_compression=Xt.output_compression),o}function Ol(e,t){const r={};for(const n of Object.keys(t))e[n]!==t[n]&&(r[n]=t[n]);return r}const Bl=["settings","apiUrl","apiKey","codexCli","apiMode","model","apiProxy"];function ui(e){return JSON.stringify([e.provider,e.baseUrl.trim().replace(/\/+$/,"").toLowerCase(),e.apiKey.trim(),e.model.trim(),e.apiMode])}function u0(e){let t=`openai-url-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;for(;e.has(t);)t=`openai-url-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;return t}function fi(e){if(e===null)return;const t=e.trim().toLowerCase();if(["true","1","yes","on"].includes(t))return!0;if(["false","0","no","off"].includes(t))return!1}function mi(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return{customProviders:t.customProviders,profiles:t.profiles}}function f0(e){const t=e.get("settings");if(!t)return null;try{const r=JSON.parse(t);return r&&typeof r=="object"&&"settings"in r?mi(r.settings??null):mi(r)}catch{return null}}function m0(e,t){if(!t||typeof t!="object"||Array.isArray(t))return e;const r=t;if(!Array.isArray(r.profiles)||r.profiles.length===0)return e;const n=ue({customProviders:r.customProviders,profiles:r.profiles}),a=n.profiles[0],o=Gi(e,a,n.customProviders);return o?ue({...e,activeProfileId:o.id}):e}function $l(e){return Bl.some(t=>e.has(t))}function h0(e){for(const t of Bl)e.delete(t)}function g0(e,t){return $l(t)?!1:!ue(e).profiles.some(n=>n.apiKey.trim())}function Fl(e,t,r={}){const n=f0(t),a=t.get("apiUrl"),o=t.get("apiKey"),i=t.get("codexCli"),c=t.get("apiMode"),l=t.get("model"),f=t.get("apiProxy"),m=c==="images"||c==="responses"?c:void 0,u=a!==null||o!==null||i!==null||m!==void 0||l!==null||f!==null,h=n==null?ue(e):m0(qa(e,n),n);if(u){const x=m??"images",y=kr({id:u0(new Set(h.profiles.map(w=>w.id))),name:r.legacyProfileName||"URL 参数配置",apiMode:x,model:x==="responses"?ws:At});a!==null&&(y.baseUrl=Ts(a.trim())),o!==null&&(y.apiKey=o.trim()),l!==null&&l.trim()&&(y.model=l.trim());const b=fi(i),d=fi(f);b!==void 0&&(y.codexCli=b),d!==void 0&&(y.apiProxy=d);const p=h.profiles.find(w=>ui(w)===ui(y));return ue(p?{...h,activeProfileId:p.id}:{...h,profiles:[...h.profiles,y],activeProfileId:y.id})}return n==null?{}:h}var Fe=Uint8Array,Rt=Uint16Array,io=Int32Array,Ks=new Fe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ys=new Fe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ea=new Fe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),zl=function(e,t){for(var r=new Rt(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var a=new io(r[30]),n=1;n<30;++n)for(var o=r[n];o<r[n+1];++o)a[o]=o-r[n]<<5|n;return{b:r,r:a}},Hl=zl(Ks,2),ql=Hl.b,Ca=Hl.r;ql[28]=258,Ca[258]=28;var Wl=zl(Ys,0),p0=Wl.b,hi=Wl.r,Ma=new Rt(32768);for(var Ae=0;Ae<32768;++Ae){var pr=(Ae&43690)>>1|(Ae&21845)<<1;pr=(pr&52428)>>2|(pr&13107)<<2,pr=(pr&61680)>>4|(pr&3855)<<4,Ma[Ae]=((pr&65280)>>8|(pr&255)<<8)>>1}var er=function(e,t,r){for(var n=e.length,a=0,o=new Rt(t);a<n;++a)e[a]&&++o[e[a]-1];var i=new Rt(t);for(a=1;a<t;++a)i[a]=i[a-1]+o[a-1]<<1;var c;if(r){c=new Rt(1<<t);var l=15-t;for(a=0;a<n;++a)if(e[a])for(var f=a<<4|e[a],m=t-e[a],u=i[e[a]-1]++<<m,h=u|(1<<m)-1;u<=h;++u)c[Ma[u]>>l]=f}else for(c=new Rt(n),a=0;a<n;++a)e[a]&&(c[a]=Ma[i[e[a]-1]++]>>15-e[a]);return c},Nr=new Fe(288);for(var Ae=0;Ae<144;++Ae)Nr[Ae]=8;for(var Ae=144;Ae<256;++Ae)Nr[Ae]=9;for(var Ae=256;Ae<280;++Ae)Nr[Ae]=7;for(var Ae=280;Ae<288;++Ae)Nr[Ae]=8;var qn=new Fe(32);for(var Ae=0;Ae<32;++Ae)qn[Ae]=5;var x0=er(Nr,9,0),b0=er(Nr,9,1),y0=er(qn,5,0),w0=er(qn,5,1),la=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Ft=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},ca=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},lo=function(e){return(e+7)/8|0},rs=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new Fe(e.subarray(t,r))},v0=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],yt=function(e,t,r){var n=new Error(t||v0[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,yt),!r)throw n;return n},k0=function(e,t,r,n){var a=e.length,o=n?n.length:0;if(!a||t.f&&!t.l)return r||new Fe(0);var i=!r,c=i||t.i!=2,l=t.i;i&&(r=new Fe(a*3));var f=function(be){var xe=r.length;if(be>xe){var ke=new Fe(Math.max(xe*2,be));ke.set(r),r=ke}},m=t.f||0,u=t.p||0,h=t.b||0,x=t.l,y=t.d,b=t.m,d=t.n,p=a*8;do{if(!x){m=Ft(e,u,1);var w=Ft(e,u+1,3);if(u+=3,w)if(w==1)x=b0,y=w0,b=9,d=5;else if(w==2){var C=Ft(e,u,31)+257,$=Ft(e,u+10,15)+4,R=C+Ft(e,u+5,31)+1;u+=14;for(var N=new Fe(R),Q=new Fe(19),L=0;L<$;++L)Q[Ea[L]]=Ft(e,u+L*3,7);u+=$*3;for(var H=la(Q),q=(1<<H)-1,F=er(Q,H,1),L=0;L<R;){var Y=F[Ft(e,u,q)];u+=Y&15;var v=Y>>4;if(v<16)N[L++]=v;else{var A=0,U=0;for(v==16?(U=3+Ft(e,u,3),u+=2,A=N[L-1]):v==17?(U=3+Ft(e,u,7),u+=3):v==18&&(U=11+Ft(e,u,127),u+=7);U--;)N[L++]=A}}var J=N.subarray(0,C),D=N.subarray(C);b=la(J),d=la(D),x=er(J,b,1),y=er(D,d,1)}else yt(1);else{var v=lo(u)+4,j=e[v-4]|e[v-3]<<8,P=v+j;if(P>a){l&&yt(0);break}c&&f(h+j),r.set(e.subarray(v,P),h),t.b=h+=j,t.p=u=P*8,t.f=m;continue}if(u>p){l&&yt(0);break}}c&&f(h+131072);for(var W=(1<<b)-1,K=(1<<d)-1,O=u;;O=u){var A=x[ca(e,u)&W],z=A>>4;if(u+=A&15,u>p){l&&yt(0);break}if(A||yt(2),z<256)r[h++]=z;else if(z==256){O=u,x=null;break}else{var T=z-254;if(z>264){var L=z-257,V=Ks[L];T=Ft(e,u,(1<<V)-1)+ql[L],u+=V}var Z=y[ca(e,u)&K],ee=Z>>4;Z||yt(3),u+=Z&15;var D=p0[ee];if(ee>3){var V=Ys[ee];D+=ca(e,u)&(1<<V)-1,u+=V}if(u>p){l&&yt(0);break}c&&f(h+131072);var oe=h+T;if(h<D){var ye=o-D,fe=Math.min(D,oe);for(ye+h<0&&yt(3);h<fe;++h)r[h]=n[ye+h]}for(;h<oe;++h)r[h]=r[h-D]}}t.l=x,t.p=O,t.b=h,t.f=m,x&&(m=1,t.m=b,t.d=y,t.n=d)}while(!m);return h!=r.length&&i?rs(r,0,h):r.subarray(0,h)},dr=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},En=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},da=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var a=r.length,o=r.slice();if(!a)return{t:Yl,l:0};if(a==1){var i=new Fe(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(P,C){return P.f-C.f}),r.push({s:-1,f:25001});var c=r[0],l=r[1],f=0,m=1,u=2;for(r[0]={s:-1,f:c.f+l.f,l:c,r:l};m!=a-1;)c=r[r[f].f<r[u].f?f++:u++],l=r[f!=m&&r[f].f<r[u].f?f++:u++],r[m++]={s:-1,f:c.f+l.f,l:c,r:l};for(var h=o[0].s,n=1;n<a;++n)o[n].s>h&&(h=o[n].s);var x=new Rt(h+1),y=Ra(r[m-1],x,0);if(y>t){var n=0,b=0,d=y-t,p=1<<d;for(o.sort(function(C,$){return x[$.s]-x[C.s]||C.f-$.f});n<a;++n){var w=o[n].s;if(x[w]>t)b+=p-(1<<y-x[w]),x[w]=t;else break}for(b>>=d;b>0;){var v=o[n].s;x[v]<t?b-=1<<t-x[v]++-1:++n}for(;n>=0&&b;--n){var j=o[n].s;x[j]==t&&(--x[j],++b)}y=t}return{t:new Fe(x),l:y}},Ra=function(e,t,r){return e.s==-1?Math.max(Ra(e.l,t,r+1),Ra(e.r,t,r+1)):t[e.s]=r},gi=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Rt(++t),n=0,a=e[0],o=1,i=function(l){r[n++]=l},c=1;c<=t;++c)if(e[c]==a&&c!=t)++o;else{if(!a&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(a),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(a);o=1,a=e[c]}return{c:r.subarray(0,n),n:t}},Cn=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},Kl=function(e,t,r){var n=r.length,a=lo(t+2);e[a]=n&255,e[a+1]=n>>8,e[a+2]=e[a]^255,e[a+3]=e[a+1]^255;for(var o=0;o<n;++o)e[a+o+4]=r[o];return(a+4+n)*8},pi=function(e,t,r,n,a,o,i,c,l,f,m){dr(t,m++,r),++a[256];for(var u=da(a,15),h=u.t,x=u.l,y=da(o,15),b=y.t,d=y.l,p=gi(h),w=p.c,v=p.n,j=gi(b),P=j.c,C=j.n,$=new Rt(19),R=0;R<w.length;++R)++$[w[R]&31];for(var R=0;R<P.length;++R)++$[P[R]&31];for(var N=da($,7),Q=N.t,L=N.l,H=19;H>4&&!Q[Ea[H-1]];--H);var q=f+5<<3,F=Cn(a,Nr)+Cn(o,qn)+i,Y=Cn(a,h)+Cn(o,b)+i+14+3*H+Cn($,Q)+2*$[16]+3*$[17]+7*$[18];if(l>=0&&q<=F&&q<=Y)return Kl(t,m,e.subarray(l,l+f));var A,U,J,D;if(dr(t,m,1+(Y<F)),m+=2,Y<F){A=er(h,x,0),U=h,J=er(b,d,0),D=b;var W=er(Q,L,0);dr(t,m,v-257),dr(t,m+5,C-1),dr(t,m+10,H-4),m+=14;for(var R=0;R<H;++R)dr(t,m+3*R,Q[Ea[R]]);m+=3*H;for(var K=[w,P],O=0;O<2;++O)for(var z=K[O],R=0;R<z.length;++R){var T=z[R]&31;dr(t,m,W[T]),m+=Q[T],T>15&&(dr(t,m,z[R]>>5&127),m+=z[R]>>12)}}else A=x0,U=Nr,J=y0,D=qn;for(var R=0;R<c;++R){var V=n[R];if(V>255){var T=V>>18&31;En(t,m,A[T+257]),m+=U[T+257],T>7&&(dr(t,m,V>>23&31),m+=Ks[T]);var Z=V&31;En(t,m,J[Z]),m+=D[Z],Z>3&&(En(t,m,V>>5&8191),m+=Ys[Z])}else En(t,m,A[V]),m+=U[V]}return En(t,m,A[256]),m+U[256]},j0=new io([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Yl=new Fe(0),I0=function(e,t,r,n,a,o){var i=o.z||e.length,c=new Fe(n+i+5*(1+Math.ceil(i/7e3))+a),l=c.subarray(n,c.length-a),f=o.l,m=(o.r||0)&7;if(t){m&&(l[0]=o.r>>3);for(var u=j0[t-1],h=u>>13,x=u&8191,y=(1<<r)-1,b=o.p||new Rt(32768),d=o.h||new Rt(y+1),p=Math.ceil(r/3),w=2*p,v=function(ne){return(e[ne]^e[ne+1]<<p^e[ne+2]<<w)&y},j=new io(25e3),P=new Rt(288),C=new Rt(32),$=0,R=0,N=o.i||0,Q=0,L=o.w||0,H=0;N+2<i;++N){var q=v(N),F=N&32767,Y=d[q];if(b[F]=Y,d[q]=F,L<=N){var A=i-N;if(($>7e3||Q>24576)&&(A>423||!f)){m=pi(e,l,0,j,P,C,R,Q,H,N-H,m),Q=$=R=0,H=N;for(var U=0;U<286;++U)P[U]=0;for(var U=0;U<30;++U)C[U]=0}var J=2,D=0,W=x,K=F-Y&32767;if(A>2&&q==v(N-K))for(var O=Math.min(h,A)-1,z=Math.min(32767,N),T=Math.min(258,A);K<=z&&--W&&F!=Y;){if(e[N+J]==e[N+J-K]){for(var V=0;V<T&&e[N+V]==e[N+V-K];++V);if(V>J){if(J=V,D=K,V>O)break;for(var Z=Math.min(K,V-2),ee=0,U=0;U<Z;++U){var oe=N-K+U&32767,ye=b[oe],fe=oe-ye&32767;fe>ee&&(ee=fe,Y=oe)}}}F=Y,Y=b[F],K+=F-Y&32767}if(D){j[Q++]=268435456|Ca[J]<<18|hi[D];var be=Ca[J]&31,xe=hi[D]&31;R+=Ks[be]+Ys[xe],++P[257+be],++C[xe],L=N+J,++$}else j[Q++]=e[N],++P[e[N]]}}for(N=Math.max(N,L);N<i;++N)j[Q++]=e[N],++P[e[N]];m=pi(e,l,f,j,P,C,R,Q,H,N-H,m),f||(o.r=m&7|l[m/8|0]<<3,m-=7,o.h=d,o.p=b,o.i=N,o.w=L)}else{for(var N=o.w||0;N<i+f;N+=65535){var ke=N+65535;ke>=i&&(l[m/8|0]=f,ke=i),m=Kl(l,m+1,e.subarray(N,ke))}o.i=i}return rs(c,0,n+lo(m)+a)},P0=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var r=t,n=9;--n;)r=(r&1&&-306674912)^r>>>1;e[t]=r}return e}(),S0=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=P0[r&255^t[n]]^r>>>8;e=r},d:function(){return~e}}},N0=function(e,t,r,n,a){if(!a&&(a={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new Fe(o.length+e.length);i.set(o),i.set(e,o.length),e=i,a.w=o.length}return I0(e,t.level==null?6:t.level,t.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,n,a)},Vl=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var n in t)r[n]=t[n];return r},Gt=function(e,t){return e[t]|e[t+1]<<8},zt=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},ua=function(e,t){return zt(e,t)+zt(e,t+4)*4294967296},st=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function T0(e,t){return N0(e,t||{},0,0)}function E0(e,t){return k0(e,{i:2},t&&t.out,t&&t.dictionary)}var Xl=function(e,t,r,n){for(var a in e){var o=e[a],i=t+a,c=n;Array.isArray(o)&&(c=Vl(n,o[1]),o=o[0]),o instanceof Fe?r[i]=[o,c]:(r[i+="/"]=[new Fe(0),c],Xl(o,i,r,n))}},xi=typeof TextEncoder<"u"&&new TextEncoder,Aa=typeof TextDecoder<"u"&&new TextDecoder,C0=0;try{Aa.decode(Yl,{stream:!0}),C0=1}catch{}var M0=function(e){for(var t="",r=0;;){var n=e[r++],a=(n>127)+(n>223)+(n>239);if(r+a>e.length)return{s:t,r:rs(e,r-1)};a?a==3?(n=((n&15)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,t+=String.fromCharCode(55296|n>>10,56320|n&1023)):a&1?t+=String.fromCharCode((n&31)<<6|e[r++]&63):t+=String.fromCharCode((n&15)<<12|(e[r++]&63)<<6|e[r++]&63):t+=String.fromCharCode(n)}};function _a(e,t){var r;if(xi)return xi.encode(e);for(var n=e.length,a=new Fe(e.length+(e.length>>1)),o=0,i=function(f){a[o++]=f},r=0;r<n;++r){if(o+5>a.length){var c=new Fe(o+8+(n-r<<1));c.set(a),a=c}var l=e.charCodeAt(r);l<128||t?i(l):l<2048?(i(192|l>>6),i(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|e.charCodeAt(++r)&1023,i(240|l>>18),i(128|l>>12&63),i(128|l>>6&63),i(128|l&63)):(i(224|l>>12),i(128|l>>6&63),i(128|l&63))}return rs(a,0,o)}function Jl(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}else{if(Aa)return Aa.decode(e);var a=M0(e),o=a.s,r=a.r;return r.length&&yt(8),o}}var R0=function(e,t){return t+30+Gt(e,t+26)+Gt(e,t+28)},A0=function(e,t,r){var n=Gt(e,t+28),a=Jl(e.subarray(t+46,t+46+n),!(Gt(e,t+8)&2048)),o=t+46+n,i=zt(e,t+20),c=r&&i==4294967295?_0(e,o):[i,zt(e,t+24),zt(e,t+42)],l=c[0],f=c[1],m=c[2];return[Gt(e,t+10),l,f,a,o+Gt(e,t+30)+Gt(e,t+32),m]},_0=function(e,t){for(;Gt(e,t)!=1;t+=4+Gt(e,t+2));return[ua(e,t+12),ua(e,t+4),ua(e,t+20)]},La=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&yt(9),t+=n+4}return t},bi=function(e,t,r,n,a,o,i,c){var l=n.length,f=r.extra,m=c&&c.length,u=La(f);st(e,t,i!=null?33639248:67324752),t+=4,i!=null&&(e[t++]=20,e[t++]=r.os),e[t]=20,t+=2,e[t++]=r.flag<<1|(o<0&&8),e[t++]=a&&8,e[t++]=r.compression&255,e[t++]=r.compression>>8;var h=new Date(r.mtime==null?Date.now():r.mtime),x=h.getFullYear()-1980;if((x<0||x>119)&&yt(10),st(e,t,x<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),t+=4,o!=-1&&(st(e,t,r.crc),st(e,t+4,o<0?-o-2:o),st(e,t+8,r.size)),st(e,t+12,l),st(e,t+14,u),t+=16,i!=null&&(st(e,t,m),st(e,t+6,r.attrs),st(e,t+10,i),t+=14),e.set(n,t),t+=l,u)for(var y in f){var b=f[y],d=b.length;st(e,t,+y),st(e,t+2,d),e.set(b,t+4),t+=4+d}return m&&(e.set(c,t),t+=m),t},L0=function(e,t,r,n,a){st(e,t,101010256),st(e,t+8,r),st(e,t+10,r),st(e,t+12,n),st(e,t+16,a)};function D0(e,t){t||(t={});var r={},n=[];Xl(e,"",r,t);var a=0,o=0;for(var i in r){var c=r[i],l=c[0],f=c[1],m=f.level==0?0:8,u=_a(i),h=u.length,x=f.comment,y=x&&_a(x),b=y&&y.length,d=La(f.extra);h>65535&&yt(11);var p=m?T0(l,f):l,w=p.length,v=S0();v.p(l),n.push(Vl(f,{size:l.length,crc:v.d(),c:p,f:u,m:y,u:h!=i.length||y&&x.length!=b,o:a,compression:m})),a+=30+h+d+w,o+=76+2*(h+d)+(b||0)+w}for(var j=new Fe(o+22),P=a,C=o-a,$=0;$<n.length;++$){var u=n[$];bi(j,u.o,u,u.f,u.u,u.c.length);var R=30+u.f.length+La(u.extra);j.set(u.c,u.o+R),bi(j,a,u,u.f,u.u,u.c.length,u.o,u.m),a+=16+R+(u.m?u.m.length:0)}return L0(j,a,n.length,C,P),j}function U0(e,t){for(var r={},n=e.length-22;zt(e,n)!=101010256;--n)(!n||e.length-n>65558)&&yt(13);var a=Gt(e,n+8);if(!a)return{};var o=zt(e,n+16),i=o==4294967295||a==65535;if(i){var c=zt(e,n-12);i=zt(e,c)==101075792,i&&(a=zt(e,c+32),o=zt(e,c+48))}for(var l=0;l<a;++l){var f=A0(e,o,i),m=f[0],u=f[1],h=f[2],x=f[3],y=f[4],b=f[5],d=R0(e,b);o=y,m?m==8?r[x]=E0(e.subarray(d,d+u),{out:new Fe(h)}):yt(14,"unknown compression type "+m):r[x]=rs(e,d,d+u)}return r}const Mt=new Map,Ut=new Map,Vr=new Map,Es=new Set,ks=new Map;let fa=!1,Da=null;const O0=8,B0=80,$0=4,F0=1e4,z0=1e4,Wn=50,On=new Map,Bn=new Map,Cs=new Map,H0="请求中断",Ua="gpt-image-playground",ma=new Map;function q0(){return typeof globalThis.localStorage<"u"?globalThis.localStorage:{getItem:e=>ma.get(e)??null,setItem:(e,t)=>{ma.set(e,t)},removeItem:e=>{ma.delete(e)}}}function Gl(e){return typeof e!="string"?null:e.trim().replace(/[\\/]+$/,"")||null}function W0(e){return encodeURIComponent(e)}function K0(e){const t=Gl(e);return t?`${Ua}:project:${W0(t)}`:Ua}function Y0(e){return`请求超时:超过 ${e} 秒仍未完成,请稍后重试或提高超时时间。`}function pn(e){const t=Mt.get(e);return t&&(Mt.delete(e),Mt.set(e,t)),t}function rr(e,t){for(Mt.delete(e),Mt.set(e,t);Mt.size>O0;){const r=Mt.keys().next().value;if(r==null)break;Mt.delete(r)}}function co(e){const t=Ut.get(e);if(t?.thumbnailVersion===tl)return Ut.delete(e),Ut.set(e,t),t;t&&Ut.delete(e)}function Vs(e,t){if(t.thumbnailVersion===tl)for(Ut.delete(e),Ut.set(e,t);Ut.size>B0;){const r=Ut.keys().next().value;if(r==null)break;Ut.delete(r)}}async function Ot(e){const t=pn(e);if(t)return t;const r=await hn(e);if(r)return rr(e,r.dataUrl),r.dataUrl}async function V0(e){const t=co(e);if(t)return t;const r=await wd(e);if(!r?.thumbnailDataUrl){uo([e],"visible");return}const n={dataUrl:r.thumbnailDataUrl,width:r.width,height:r.height,thumbnailVersion:r.thumbnailVersion};return Vs(e,n),n}function X0(e,t){let r=ks.get(e);return r||(r=new Set,ks.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&ks.delete(e)}}function J0(e,t){ks.get(e)?.forEach(r=>r(t))}function uo(e,t="background"){for(const r of e){if(co(r)||Es.has(r))continue;(!Vr.get(r)||t==="visible")&&Vr.set(r,t)}fo()}function fo(){if(fa||Vr.size===0)return;fa=!0;const e=()=>{fa=!1,G0()};"requestIdleCallback"in window?window.requestIdleCallback(e,{timeout:2e3}):globalThis.setTimeout(e,250)}async function G0(){if(Es.size>0)return;const e=await Q0();for(const t of e)tf(t);Vr.size>0&&fo()}async function Q0(){const e=Z0().slice(0,$0);if(e.length===0)return[];const t=await Promise.all(e.map(async a=>{const o=await hn(a);return{width:o?.width,height:o?.height}})),r=ef(t),n=e.slice(0,r);for(const a of n)Vr.delete(a);return n}function Z0(){const e=[],t=[];for(const[r,n]of Vr)n==="visible"?e.push(r):t.push(r);return[...e,...t]}function ef(e){let t=0;for(const{width:n,height:a}of e){if(!n||!a)return 1;t=Math.max(t,n*a/1e6)}const r=t;return r>=8?1:r>=4?2:r>=2?3:4}function tf(e){Es.add(e),(async()=>{if(co(e))return;const t=await al(e);t?.thumbnailDataUrl&&(Vs(e,{dataUrl:t.thumbnailDataUrl,width:t.width,height:t.height,thumbnailVersion:t.thumbnailVersion}),J0(e,{dataUrl:t.thumbnailDataUrl,width:t.width,height:t.height}))})().catch(()=>{}).finally(()=>{Es.delete(e),fo()})}function yi(e,t){if(!t)return e;const r=e.findIndex(o=>o.id===t);if(r<=0)return e;const n=[...e],[a]=n.splice(r,1);return n.unshift(a),n}function Kn(e){return e.reduce((t,r)=>t+(r.status==="done"?r.outputImages.length:0),0)}function rf(e){const t=Kn(e);E.setState(r=>r.supportPromptDismissed?{}:t<=Wn?{supportPromptSkippedForImportedData:!1}:r.supportPromptOpen?{}:{supportPromptSkippedForImportedData:!0})}function nf(e){const t=Kn(e);E.setState(r=>r.supportPromptDismissed||r.supportPromptOpen?{}:t<=Wn?{supportPromptSkippedForImportedData:!1}:r.supportPromptSkippedForImportedData?{}:{supportPromptOpen:!0})}function sf(e,t,r){const n=E.getState();if(n.supportPromptDismissed||n.supportPromptOpen||n.supportPromptSkippedForImportedData)return;const a=e.find(l=>l.id===r),o=t.find(l=>l.id===r);if(!o||a?.status==="done"||o.status!=="done"||o.outputImages.length===0)return;const i=Kn(e),c=Kn(t);i<=Wn&&c>Wn&&E.setState({supportPromptOpen:!0})}function af(e){const t=ue(e.settings);return{settings:t,params:e.params,...t.persistInputOnRestart?{prompt:e.prompt,inputImages:e.inputImages.map(r=>({id:r.id,dataUrl:""}))}:{},dismissedCodexCliPrompts:e.dismissedCodexCliPrompts,supportPromptDismissed:e.supportPromptDismissed,supportPromptOpen:e.supportPromptOpen,supportPromptSkippedForImportedData:e.supportPromptSkippedForImportedData}}function Ql(e,t){if(!e||typeof e!="object")return t;const r=e,n=ue(r.settings??t.settings);return{...t,...r,settings:n,supportPromptDismissed:!!r.supportPromptDismissed,supportPromptOpen:!!r.supportPromptOpen,supportPromptSkippedForImportedData:!!r.supportPromptSkippedForImportedData,prompt:n.persistInputOnRestart&&typeof r.prompt=="string"?r.prompt:"",inputImages:n.persistInputOnRestart&&Array.isArray(r.inputImages)?r.inputImages:[]}}const E=zc()(qc((e,t)=>({settings:{...Ct},setSettings:r=>e(n=>{const a=ue(n.settings),o=r,i=o.baseUrl!==void 0||o.apiKey!==void 0||o.model!==void 0||o.timeout!==void 0||o.apiMode!==void 0||o.codexCli!==void 0||o.apiProxy!==void 0,c=ue({...a,...o});i&&o.profiles===void 0&&(c.profiles=c.profiles.map(m=>m.id===c.activeProfileId?{...m,baseUrl:o.baseUrl??m.baseUrl,apiKey:o.apiKey??m.apiKey,model:o.model??m.model,timeout:o.timeout??m.timeout,apiMode:o.apiMode==="images"||o.apiMode==="responses"?o.apiMode:m.apiMode,codexCli:o.codexCli??m.codexCli,apiProxy:o.apiProxy??m.apiProxy}:m));const l=ue(c),f=n.reusedTaskApiProfileId&&l.activeProfileId===n.reusedTaskApiProfileId;return{settings:l,...f?{reusedTaskApiProfileId:null,reusedTaskApiProfileName:null,reusedTaskApiProfileMissing:!1}:{}}}),dismissedCodexCliPrompts:[],dismissCodexCliPrompt:r=>e(n=>({dismissedCodexCliPrompts:n.dismissedCodexCliPrompts.includes(r)?n.dismissedCodexCliPrompts:[...n.dismissedCodexCliPrompts,r]})),prompt:"",setPrompt:r=>e({prompt:r}),inputImages:[],addInputImage:r=>e(n=>n.inputImages.find(a=>a.id===r.id)?n:{inputImages:[...n.inputImages,r]}),removeInputImage:r=>e(n=>{const a=n.inputImages[r],o=n.inputImages.filter((c,l)=>l!==r),i=a?.id===n.maskDraft?.targetImageId;return{inputImages:o,prompt:wn(n.prompt,n.inputImages,o),...i?{maskDraft:null,maskEditorImageId:null}:{}}}),clearInputImages:()=>e(r=>{for(const n of r.inputImages)Mt.delete(n.id);return{inputImages:[],prompt:wn(r.prompt,r.inputImages,[]),maskDraft:null,maskEditorImageId:null}}),setInputImages:(r,n)=>e(a=>{const o=yi(r,a.maskDraft?.targetImageId),i=!!a.maskDraft&&!o.some(c=>c.id===a.maskDraft?.targetImageId);return{inputImages:o,prompt:wn(a.prompt,a.inputImages,o,n?.equivalentImageIds),...i?{maskDraft:null,maskEditorImageId:null}:{}}}),moveInputImage:(r,n)=>e(a=>{const o=[...a.inputImages];if(r<0||r>=o.length)return a;const i=a.maskDraft?.targetImageId;if(i&&o[r]?.id===i)return a;const c=i&&o.some(u=>u.id===i)?1:0,l=Math.max(c,Math.min(o.length,n)),f=r<l?l-1:l;if(f===r)return a;const[m]=o.splice(r,1);return o.splice(f,0,m),{inputImages:o,prompt:wn(a.prompt,a.inputImages,o)}}),maskDraft:null,setMaskDraft:r=>e(n=>{const a=yi(n.inputImages,r?.targetImageId);return{maskDraft:r,inputImages:a,prompt:wn(n.prompt,n.inputImages,a)}}),clearMaskDraft:()=>e({maskDraft:null}),maskEditorImageId:null,setMaskEditorImageId:r=>{r&&Ht(),e({maskEditorImageId:r})},params:{...Xt},setParams:r=>e(n=>({params:{...n.params,...r}})),reusedTaskApiProfileId:null,reusedTaskApiProfileName:null,reusedTaskApiProfileMissing:!1,setReusedTaskApiProfile:(r,n=!1,a=null)=>e({reusedTaskApiProfileId:r,reusedTaskApiProfileName:a,reusedTaskApiProfileMissing:n}),tasks:[],setTasks:r=>e(()=>({tasks:r,...Kn(r)<=Wn?{supportPromptSkippedForImportedData:!1}:{}})),searchQuery:"",setSearchQuery:r=>e({searchQuery:r}),filterStatus:"all",setFilterStatus:r=>e({filterStatus:r}),filterFavorite:!1,setFilterFavorite:r=>e({filterFavorite:r}),selectedTaskIds:[],setSelectedTaskIds:r=>e(n=>({selectedTaskIds:typeof r=="function"?r(n.selectedTaskIds):r})),toggleTaskSelection:(r,n)=>e(a=>{const o=a.selectedTaskIds.includes(r),i=n!==void 0?n:!o;return i===o?a:{selectedTaskIds:i?[...a.selectedTaskIds,r]:a.selectedTaskIds.filter(c=>c!==r)}}),clearSelection:()=>e({selectedTaskIds:[]}),detailTaskId:null,setDetailTaskId:r=>{r&&Ht(),e({detailTaskId:r})},lightboxImageId:null,lightboxImageList:[],setLightboxImageId:(r,n)=>{r&&Ht(),e({lightboxImageId:r,lightboxImageList:n??(r?[r]:[])})},showSettings:!1,setShowSettings:r=>{r&&Ht(),e({showSettings:r})},supportPromptOpen:!1,supportPromptDismissed:!1,supportPromptSkippedForImportedData:!1,setSupportPromptOpen:r=>e({supportPromptOpen:r}),dismissSupportPrompt:()=>e({supportPromptOpen:!1,supportPromptDismissed:!0}),toast:null,showToast:(r,n="info")=>{e({toast:{message:r,type:n}}),setTimeout(()=>{e(a=>a.toast?.message===r?{toast:null}:a)},3e3)},confirmDialog:null,setConfirmDialog:r=>{r&&Ht(),e({confirmDialog:r})}}),{name:Ua,storage:zi(q0),partialize:af,merge:Ql,skipHydration:!0}));async function of(e){Da=Gl(e),bd(e);const t=K0(e);E.persist.setOptions({name:t});const r=E.persist.getOptions().storage,n=r?await r.getItem(t):null,a=E.getInitialState(),o=n?.state?Ql(n.state,a):a;E.setState(o,!0)}let lf=0;function Zl(){return Date.now().toString(36)+(++lf).toString(36)+Math.random().toString(36).slice(2,6)}function ec(e){const t=et(e);return`${t.baseUrl}
10
+ ${t.apiKey}`}function cf(e){return(e.apiProvider??"openai")!=="fal"}function mo(e){return e.status==="running"&&cf(e)}function df(e,t,r){const n=Xn(e,t);return n?.poll?!!(r&&n.editSubmit?n.editSubmit:n.submit).taskIdPath:!1}function uf(e,t=Date.now()){const r=[];return{tasks:e.map(a=>{if(!mo(a)||a.customTaskId)return a;const o={...a,status:"error",error:H0,falRecoverable:!1,finishedAt:t,elapsed:Math.max(0,t-a.createdAt)};return r.push(o),o}),interruptedTasks:r}}function Oa(e){const t=Cs.get(e);t&&clearTimeout(t),Cs.delete(e)}function ff(e,t,r=Date.now()){const n=E.getState().tasks.find(a=>a.id===e);return!n||!mo(n)?!1:(wt(e,{status:"error",error:t,falRecoverable:!1,finishedAt:r,elapsed:Math.max(0,r-n.createdAt)}),!0)}function mf(e,t){Oa(e);const r=E.getState().tasks.find(i=>i.id===e);if(!r||!mo(r))return;const n=Math.max(0,t*1e3),a=Math.max(0,n-(Date.now()-r.createdAt)),o=setTimeout(()=>{Cs.delete(e),ff(e,Y0(t))&&E.getState().showToast("OpenAI 任务请求超时","error")},a);Cs.set(e,o)}function Ba(e=!1,t="接口返回的提示词已被改写"){const r=E.getState(),n=r.settings,a=ec(n);!e&&(n.codexCli||r.dismissedCodexCliPrompts.includes(a))||r.setConfirmDialog({title:"检测到 Codex CLI API",message:`${t},当前 API 来源很可能是 Codex CLI。
11
+
12
+ 是否开启 Codex CLI 兼容模式?开启后会禁用在此处无效的质量参数,并在 Images API 多图生成时使用并发请求,解决该 API 数量参数无效的问题。同时,提示词文本开头会加入简短的不改写要求,避免模型重写提示词,偏离原意。`,confirmText:"开启",action:()=>{const o=E.getState();o.dismissCodexCliPrompt(a),o.setSettings({codexCli:!0})},cancelAction:()=>E.getState().dismissCodexCliPrompt(a)})}function hf(e,t){const r=xn(e,t);if(r?.provider==="fal")return r;const n=ue(e),a=et(n);return a.provider==="fal"?a:n.profiles.find(o=>o.provider==="fal"&&(o.name===t.apiProfileName||o.model===t.apiModel))??n.profiles.find(o=>o.provider==="fal")??null}function gf(e,t){const r=t.apiProvider;if(!r||r==="openai"||r==="fal")return null;const n=xn(e,t);if(n?.provider===r)return n;const a=ue(e),o=et(a);return o.provider===r?o:a.profiles.find(i=>i.provider===r&&(i.name===t.apiProfileName||i.model===t.apiModel))??a.profiles.find(i=>i.provider===r)??null}function xn(e,t){const r=ue(e),n=t.apiProvider;if(t.apiProfileId){const o=r.profiles.find(i=>i.id===t.apiProfileId);return o&&(!n||o.provider===n)?o:null}if(!n)return null;const a=r.profiles.filter(o=>o.provider===n);if(!a.length)return null;if(t.apiProfileName){const o=a.find(i=>i.name===t.apiProfileName);if(o)return o}if(t.apiModel){const o=a.filter(i=>i.model===t.apiModel);if(o.length===1)return o[0]}return a.length===1?a[0]:null}function Ms(e,t){const r=ue(e);return ue({...r,baseUrl:t.baseUrl,apiKey:t.apiKey,model:t.model,timeout:t.timeout,apiMode:t.apiMode,codexCli:t.codexCli,apiProxy:t.apiProxy,profiles:r.profiles.map(n=>n.id===t.id?t:n),activeProfileId:t.id})}function pf(e,t){return t?ue(e).profiles.find(r=>r.id===t)??null:null}function tc(e){return e.apiProfileName||e.apiModel||"未知配置"}function xf(){try{if(typeof localStorage>"u")return;const e=localStorage.getItem("auth-token");return e?{Authorization:`Bearer ${e}`}:void 0}catch{return}}async function rc(e={}){const t=E.getState(),r=ue(t.settings);if(e.silent&&r.profiles.some(n=>n.apiKey.trim()))return r;try{const n=xf(),a=new URLSearchParams;Da&&a.set("projectPath",Da);const o=`/api/codex/image-playground/launch${a.toString()?`?${a.toString()}`:""}`,i=await fetch(o,{cache:"no-store",...n?{headers:n}:{}}),c=await i.json();if(!i.ok||!c?.success)throw new Error(c?.error||`同步失败:${i.status}`);const l=c.launch;if(!l?.ready||!l?.url){const h=l?.warnings?.[0]?.message||"未找到本地 Codex 图片 API 配置";throw new Error(h)}const f=typeof window>"u"?"http://localhost":window.location.origin,m=new URL(l.url,f).searchParams,u=ue(Fl(t.settings,m,{legacyProfileName:"本地 Codex 配置"}));return t.setSettings(u),e.silent||t.showToast("已同步本地 Codex 配置","success"),u}catch(n){return e.silent||t.showToast(n instanceof Error?n.message:String(n),"error"),null}}function $a(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError")return!0;const t=e instanceof Error?e.message:String(e);return/abort|network|failed to fetch|fetch failed|load failed|timeout|连接|断开|中断/i.test(t)}function bf(e){if(e instanceof TypeError){const t=e.message.toLowerCase();return/failed to fetch|fetch failed|load failed|networkerror|network request failed/i.test(t)}return!1}function yf(e,t,r){if(!bf(e))return null;const n=xn(r,t),a=Math.max(0,(Date.now()-t.createdAt)/1e3),o=n?.apiProxy??r.apiProxy;return a<=15?o?"提示:请求立即失败,请检查 API 代理服务是否正常运行。":"提示:接口可能不支持浏览器跨域请求,可开启 API 代理解决。":a>=55&&a<=75?"提示:请求等待约 60 秒后被断开,这通常是 Nginx 等反向代理的默认超时,而非接口本身报错。可调大代理的超时时间(如 proxy_read_timeout),或降低图片尺寸/质量后重试。":a>=110&&a<=140?"提示:请求等待约 120 秒后被断开,这通常是 Cloudflare 等 CDN/网关的超时限制,而非接口本身报错。如果使用 Cloudflare,可考虑升级套餐或使用不经过 CDN 的直连地址。":"提示:请求等待较长时间后被断开,通常是反向代理或网关的超时限制,而非接口本身报错。可检查代理超时设置,或降低图片尺寸/质量后重试。"}function ho(e){if(!(e instanceof Error))return{};const t="rawImageUrls"in e?e.rawImageUrls:void 0,r="rawResponsePayload"in e?e.rawResponsePayload:void 0;return{rawImageUrls:Array.isArray(t)&&t.length?t.filter(n=>typeof n=="string"):void 0,rawResponsePayload:typeof r=="string"?r:void 0}}function wi(e){const t=On.get(e);t&&clearTimeout(t),On.delete(e)}function Rs(e,t=F0){if(On.has(e))return;const r=setTimeout(()=>{On.delete(e),kf(e)},t);On.set(e,r)}function vi(e){const t=Bn.get(e);t&&clearTimeout(t),Bn.delete(e)}function go(e,t=z0){if(Bn.has(e))return;const r=setTimeout(()=>{Bn.delete(e),Nf(e)},t);Bn.set(e,r)}function As(e){return!!(e&&Object.keys(e).length>0)}function _s(e){return e?.find(As)}function po(e,t){const r=t?.reduce((n,a,o)=>{const i=e[o];return i&&As(a)&&(n[i]=a),n},{});return r&&Object.keys(r).length>0?r:void 0}async function wf(e){if(!(typeof Image>"u"))return new Promise(t=>{let r=!1;const n=new Image,a=i=>{r||(r=!0,clearTimeout(o),t(i))},o=setTimeout(()=>a(void 0),2e3);n.onload=()=>{n.naturalWidth>0&&n.naturalHeight>0?a({size:`${n.naturalWidth}x${n.naturalHeight}`}):a(void 0)},n.onerror=()=>a(void 0),n.src=e,n.complete&&n.naturalWidth>0&&n.naturalHeight>0&&a({size:`${n.naturalWidth}x${n.naturalHeight}`})})}async function xo(e){return Promise.all(e.map(t=>wf(t)))}async function nc(e,t){if(t?.length===e.length&&t.every(As))return t;const r=await xo(e);return e.map((n,a)=>As(t?.[a])?t?.[a]:r[a])}async function vf(e,t){const r=E.getState().tasks.find(o=>o.id===e.id);if(!r||r.status==="done")return;const n=await nc(t.images,t.actualParamsList),a=[];for(const o of t.images){const i=await Ir(o,"generated");rr(i,o),a.push(i)}wt(e.id,{outputImages:a,actualParams:_s(n),actualParamsByImage:po(a,n),revisedPromptByImage:void 0,status:"done",error:null,falRecoverable:!1,finishedAt:Date.now(),elapsed:Date.now()-e.createdAt}),E.getState().showToast(`fal.ai 任务已恢复,共 ${a.length} 张图片`,"success")}async function kf(e){const{settings:t,tasks:r}=E.getState(),n=r.find(o=>o.id===e);if(!n||n.apiProvider!=="fal"||!n.falRequestId||!n.falEndpoint||n.status==="done")return;const a=hf(t,n);if(!a){Rs(e);return}try{const o=await Mu(a,n.falEndpoint,n.falRequestId,n.params);wi(e),await vf(n,o);return}catch(o){if($a(o)){Rs(e);return}wi(e),wt(e,{status:"error",error:Il(o)??(o instanceof Error?o.message:String(o)),...ho(o),falRecoverable:!1,finishedAt:Date.now(),elapsed:Date.now()-n.createdAt})}}async function jf(){const e=await Ya(),{tasks:t,interruptedTasks:r}=uf(e);await Promise.all(r.map(l=>Gn(l))),E.getState().setTasks(t),nf(t);for(const l of t)l.apiProvider==="fal"&&l.falRequestId&&l.falEndpoint&&(l.status==="running"||l.falRecoverable)&&Rs(l.id,0),l.customTaskId&&(l.status==="running"||l.customRecoverable)&&go(l.id,0);const n=new Set,a=E.getState().inputImages;for(const l of a)n.add(l.id);for(const l of t){for(const f of l.inputImageIds||[])n.add(f);l.maskImageId&&n.add(l.maskImageId);for(const f of l.outputImages||[])n.add(f)}const o=await kd(),i=[];for(const l of o)n.has(l)?i.push(l):await Xa(l);uo(i);const c=[];for(const l of a){if(l.dataUrl){c.push(l),rr(l.id,l.dataUrl);continue}const f=await hn(l.id);f?.dataUrl&&(c.push({...l,dataUrl:f.dataUrl}),rr(l.id,f.dataUrl))}(c.length!==a.length||c.some((l,f)=>l.dataUrl!==a[f]?.dataUrl))&&E.getState().setInputImages(c)}async function Br(e={}){const{settings:t,prompt:r,inputImages:n,maskDraft:a,params:o,reusedTaskApiProfileId:i,reusedTaskApiProfileName:c,reusedTaskApiProfileMissing:l,showToast:f,setConfirmDialog:m}=E.getState(),u=ue(t);let h=et(t),x=Ms(u,h);if(u.reuseTaskApiProfileTemporarily&&(i||l)){const C=pf(u,i);if(C)h=C,x=Ms(u,C);else if(e.useCurrentApiProfileWhenReusedMissing)E.getState().setReusedTaskApiProfile(null);else{m({title:"找不到 API 配置",message:`找不到复用任务所使用的 API 配置「${c||"未知配置"}」,要使用当前的 API 配置「${h.name}」提交任务吗?`,confirmText:"使用当前配置提交",cancelText:"放弃提交",action:()=>{Br({...e,useCurrentApiProfileWhenReusedMissing:!0})}});return}}if(Ao(h)){f(`请先完善请求 API 配置:${Ao(h)}`,"error"),E.getState().setShowSettings(!0);return}if(!r.trim()){f("请输入提示词","error");return}let y=n,b=null,d=null;if(a)try{if(y=_u(n,a.targetImageId),await Uu(a.maskDataUrl,y[0].dataUrl)==="full"&&!e.allowFullMask){m({title:"确认编辑整张图片?",message:"当前遮罩覆盖了整张图片,提交后可能会重绘全部内容。是否继续?",confirmText:"继续提交",tone:"warning",action:()=>{Br({allowFullMask:!0})}});return}b=await Ir(a.maskDataUrl,"mask"),rr(b,a.maskDataUrl),d=a.targetImageId}catch(C){n.some($=>$.id===a.targetImageId)||E.getState().clearMaskDraft(),f(C instanceof Error?C.message:String(C),"error");return}for(const C of y)await Ir(C.dataUrl);const p=Ws(o,x,{hasInputImages:y.length>0}),w=Ol(o,p);Object.keys(w).length&&E.getState().setParams(w);const v=Zl(),j={id:v,prompt:r.trim(),params:p,apiProvider:h.provider,apiProfileId:h.id,apiProfileName:h.name,apiModel:h.model,inputImageIds:y.map(C=>C.id),maskTargetImageId:d,maskImageId:b,outputImages:[],status:"running",error:null,createdAt:Date.now(),finishedAt:null,elapsed:null},P=E.getState().tasks;E.getState().setTasks([j,...P]),await Gn(j),t.clearInputAfterSubmit&&(E.getState().setPrompt(""),E.getState().clearInputImages()),E.getState().setReusedTaskApiProfile(null),sc(v)}async function sc(e){const{settings:t}=E.getState(),r=E.getState().tasks.find(f=>f.id===e);if(!r)return;const n=xn(t,r);if(!n&&r.apiProfileId){wt(e,{status:"error",error:"找不到此任务所使用的 API 配置。",falRecoverable:!1,customRecoverable:!1,finishedAt:Date.now(),elapsed:Date.now()-r.createdAt});return}const a=n??et(t),o=Ms(t,a),i=r.apiProvider??a.provider;let c=r.falRequestId&&r.falEndpoint?{requestId:r.falRequestId,endpoint:r.falEndpoint}:null,l=r.customTaskId?{taskId:r.customTaskId}:null;i!=="fal"&&!df(o,i,r.inputImageIds.length>0)&&mf(e,a.timeout);try{const f=[];for(const R of r.inputImageIds){const N=await Ot(R);if(!N)throw new Error("输入图片已不存在");f.push(N)}let m;if(r.maskImageId&&(m=await Ot(r.maskImageId),!m))throw new Error("遮罩图片已不存在");const u=await a0({settings:o,prompt:fd(r.prompt,f.length),params:r.params,inputImageDataUrls:f,maskDataUrl:m,onFalRequestEnqueued:R=>{c=R,wt(e,{falRequestId:R.requestId,falEndpoint:R.endpoint,falRecoverable:!1})},onCustomTaskEnqueued:R=>{l=R,wt(e,{customTaskId:R.taskId,customRecoverable:!1})}}),h=E.getState().tasks.find(R=>R.id===e);if(!h||h.status!=="running")return;const x=[];for(const R of u.images){const N=await Ir(R,"generated");rr(N,R),x.push(N)}const y=i!=="fal"&&i!=="openai"&&!!l,b=i==="fal"?await nc(u.images,u.actualParamsList):y?await xo(u.images):u.actualParamsList,d=i==="fal"||y?_s(b):{...u.actualParams,n:x.length},p=i!=="fal"&&!y,w=po(x,b),v=p?u.revisedPrompts?.reduce((R,N,Q)=>{const L=x[Q];return L&&N&&N.trim()&&(R[L]=N),R},{}):void 0,j=p&&u.revisedPrompts?.some(R=>R?.trim()&&R.trim()!==r.prompt.trim()),P=p&&u.revisedPrompts?.some(R=>R?.trim());i==="openai"&&!a.codexCli&&(j?Ba():P||Ba(!1,"接口没有返回官方 API 会返回的部分信息"));const C=E.getState().tasks.find(R=>R.id===e);if(!C||C.status!=="running")return;Oa(e),wt(e,{outputImages:x,rawImageUrls:u.rawImageUrls?.length?u.rawImageUrls:void 0,actualParams:d,actualParamsByImage:w,revisedPromptByImage:v&&Object.keys(v).length>0?v:void 0,status:"done",finishedAt:Date.now(),elapsed:Date.now()-r.createdAt,falRecoverable:!1,customRecoverable:!1}),E.getState().showToast(`生成完成,共 ${x.length} 张图片`,"success");const $=E.getState().maskDraft;m&&$&&$.targetImageId===r.maskTargetImageId&&$.maskDataUrl===m&&E.getState().clearMaskDraft()}catch(f){Oa(e);const m=E.getState().tasks.find(x=>x.id===e)??r;if(m.status!=="running")return;const u=c??(m.falRequestId&&m.falEndpoint?{requestId:m.falRequestId,endpoint:m.falEndpoint}:null),h=l??(m.customTaskId?{taskId:m.customTaskId}:null);if(m.apiProvider==="fal"&&u&&$a(f))wt(e,{status:"error",error:"与 fal.ai 的连接已断开,之后会继续查询任务结果。",falRequestId:u.requestId,falEndpoint:u.endpoint,falRecoverable:!0,finishedAt:Date.now(),elapsed:Date.now()-r.createdAt}),Rs(e);else if(h&&$a(f))wt(e,{status:"error",error:"与自定义异步任务的连接已断开,之后会继续查询任务结果。",customTaskId:h.taskId,customRecoverable:!0,finishedAt:Date.now(),elapsed:Date.now()-r.createdAt}),go(e);else{let x=f instanceof Error?f.message:String(f);const y=yf(f,m,E.getState().settings);y&&!x.includes(vs)&&(x+=`
13
+ ${y}`),wt(e,{status:"error",error:x,...ho(f),falRecoverable:!1,customRecoverable:!1,finishedAt:Date.now(),elapsed:Date.now()-r.createdAt}),E.getState().setDetailTaskId(e)}}finally{for(const f of r.inputImageIds)Mt.delete(f)}}function wt(e,t){const{tasks:r,setTasks:n}=E.getState(),a=r.map(i=>i.id===e?{...i,...t}:i);n(a),sf(r,a,e);const o=a.find(i=>i.id===e);o&&Gn(o)}async function ac(e){const{settings:t}=E.getState(),r=et(t),n=Ws(e.params,t,{hasInputImages:e.inputImageIds.length>0}),a=Zl(),o={id:a,prompt:e.prompt,params:n,apiProvider:r.provider,apiProfileId:r.id,apiProfileName:r.name,apiModel:r.model,inputImageIds:[...e.inputImageIds],maskTargetImageId:e.maskTargetImageId??null,maskImageId:e.maskImageId??null,outputImages:[],status:"running",error:null,createdAt:Date.now(),finishedAt:null,elapsed:null},i=E.getState().tasks;E.getState().setTasks([o,...i]),await Gn(o),sc(a)}async function oc(e){const{settings:t,setPrompt:r,setParams:n,setInputImages:a,setMaskDraft:o,clearMaskDraft:i,showToast:c,setConfirmDialog:l,setReusedTaskApiProfile:f}=E.getState(),m=ue(t),u=et(t),h=m.reuseTaskApiProfileTemporarily?xn(m,e):null,x=!!(h&&h.id!==u.id),y=m.reuseTaskApiProfileTemporarily&&!h,b=h?.name??tc(e),d=x&&h?Ms(m,h):m;n(Ws(e.params,d,{hasInputImages:e.inputImageIds.length>0})),f(x&&h?h.id:null,y,b),i();const p=[];for(const v of e.inputImageIds){const j=await Ot(v);j&&p.push({id:v,dataUrl:j})}a(p),r(e.prompt);const w=e.maskTargetImageId??(e.maskImageId?e.inputImageIds[0]:null);if(w&&e.maskImageId&&p.some(v=>v.id===w)){const v=await Ot(e.maskImageId);v?o({targetImageId:w,maskDataUrl:v,updatedAt:Date.now()}):i()}else i();if(y){l({title:"找不到 API 配置",message:`找不到复用任务所使用的 API 配置「${b}」,要使用当前的 API 配置「${u.name}」提交任务吗?`,confirmText:"使用当前配置提交",cancelText:"放弃提交",action:()=>{Br({useCurrentApiProfileWhenReusedMissing:!0})}});return}c(x&&h?`已临时复用该任务的 API 配置「${h.name}」`:"已复用配置到输入框","success")}async function ic(e){const{inputImages:t,addInputImage:r,settings:n,showToast:a,setReusedTaskApiProfile:o}=E.getState();if(!e.outputImages?.length)return;let i=0;for(const x of e.outputImages){if(t.find(b=>b.id===x))continue;const y=await Ot(x);y&&(r({id:x,dataUrl:y}),i++)}const c=ue(n),l=et(c),f=c.reuseTaskApiProfileTemporarily?xn(c,e):null,m=!!(f&&f.id!==l.id),u=c.reuseTaskApiProfileTemporarily&&!f,h=f?.name??tc(e);o(m&&f?f.id:null,u,h),a(m&&f?`已添加 ${i} 张输出图到输入,并临时复用该任务的 API 配置「${f.name}」`:`已添加 ${i} 张输出图到输入`,"success")}async function If(e){const{tasks:t,setTasks:r,inputImages:n,showToast:a,clearSelection:o,selectedTaskIds:i}=E.getState();if(!e.length)return;const c=new Set(e),l=t.filter(h=>!c.has(h.id)),f=new Set;for(const h of t)if(c.has(h.id)){for(const x of h.inputImageIds||[])f.add(x);h.maskImageId&&f.add(h.maskImageId);for(const x of h.outputImages||[])f.add(x)}r(l);for(const h of e)await sl(h);const m=new Set;for(const h of l){for(const x of h.inputImageIds||[])m.add(x);h.maskImageId&&m.add(h.maskImageId);for(const x of h.outputImages||[])m.add(x)}for(const h of n)m.add(h.id);for(const h of f)m.has(h)||(await Xa(h),Mt.delete(h),Ut.delete(h));const u=i.filter(h=>!c.has(h));u.length!==i.length&&E.getState().setSelectedTaskIds(u),a(`已删除 ${e.length} 条记录`,"success")}async function lc(e){const{tasks:t,setTasks:r,inputImages:n,showToast:a}=E.getState(),o=new Set([...e.inputImageIds||[],...e.maskImageId?[e.maskImageId]:[],...e.outputImages||[]]),i=t.filter(l=>l.id!==e.id);r(i),await sl(e.id);const c=new Set;for(const l of i){for(const f of l.inputImageIds||[])c.add(f);l.maskImageId&&c.add(l.maskImageId);for(const f of l.outputImages||[])c.add(f)}for(const l of n)c.add(l.id);for(const l of o)c.has(l)||(await Xa(l),Mt.delete(l),Ut.delete(l));a("记录已删除","success")}async function Pf(e={clearConfig:!0,clearTasks:!0}){const{setTasks:t,clearInputImages:r,clearMaskDraft:n,setSettings:a,setParams:o,showToast:i}=E.getState();e.clearTasks&&(await yd(),await jd(),Mt.clear(),Ut.clear(),Vr.clear(),t([]),E.setState({supportPromptOpen:!1,supportPromptSkippedForImportedData:!1}),r(),n()),e.clearConfig&&(E.setState({dismissedCodexCliPrompts:[],supportPromptDismissed:!1}),a({...Ct}),o({...Xt})),i("所选数据已清空","success")}function ki(e){const r=e.match(/^data:image\/(\w+);base64,/)?.[1]??"png",n=e.replace(/^data:[^;]+;base64,/,""),a=atob(n),o=new Uint8Array(a.length);for(let i=0;i<a.length;i++)o[i]=a.charCodeAt(i);return{ext:r,bytes:o}}function ji(e,t){const r=t.split(".").pop()?.toLowerCase()??"png",a={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp"}[r]??"image/png";let o="";for(let i=0;i<e.length;i++)o+=String.fromCharCode(e[i]);return`data:${a};base64,${btoa(o)}`}async function Sf(e,t){const r=E.getState().tasks.find(o=>o.id===e.id);if(!r||r.status==="done")return;const n=await xo(t.images),a=[];for(const o of t.images){const i=await Ir(o,"generated");rr(i,o),a.push(i)}wt(e.id,{outputImages:a,actualParams:_s(n),actualParamsByImage:po(a,n),revisedPromptByImage:void 0,status:"done",error:null,customRecoverable:!1,finishedAt:Date.now(),elapsed:Date.now()-e.createdAt}),E.getState().showToast(`自定义异步任务已恢复,共 ${a.length} 张图片`,"success")}async function Nf(e){const{settings:t,tasks:r}=E.getState(),n=r.find(i=>i.id===e);if(!n||!n.customTaskId||n.status==="done")return;const a=gf(t,n),o=n.apiProvider?Xn(t,n.apiProvider):null;if(!a||!o?.poll){go(e);return}try{const i=await r0(a,o,n.customTaskId,n.params);vi(e),await Sf(n,i)}catch(i){vi(e),wt(e,{status:"error",error:i instanceof Error?i.message:String(i),...ho(i),customRecoverable:!1,finishedAt:Date.now(),elapsed:Date.now()-n.createdAt})}}function Tf(e){const t=r=>String(r).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}_${t(e.getHours())}-${t(e.getMinutes())}-${t(e.getSeconds())}`}async function Ef(e={exportConfig:!0,exportTasks:!0}){try{const t=e.exportTasks?await Ya():[],r=e.exportTasks?await vd():[],{settings:n}=E.getState(),a=Date.now(),o=new Map;if(e.exportTasks)for(const y of t)for(const b of[...y.inputImageIds||[],...y.maskImageId?[y.maskImageId]:[],...y.outputImages||[]]){const d=o.get(b);(d==null||y.createdAt<d)&&o.set(b,y.createdAt)}const i={},c={},l={};if(e.exportTasks)for(const y of r){const{ext:b,bytes:d}=ki(y.dataUrl),p=`images/${y.id}.${b}`,w=y.createdAt??o.get(y.id)??a;i[y.id]={path:p,createdAt:w,source:y.source,width:y.width,height:y.height},l[p]=[d,{mtime:new Date(w)}];const v=await al(y.id);if(v?.thumbnailDataUrl){const{ext:j,bytes:P}=ki(v.thumbnailDataUrl),C=`thumbnails/${y.id}.${j}`;i[y.id].width=i[y.id].width??v.width,i[y.id].height=i[y.id].height??v.height,c[y.id]={path:C,width:v.width,height:v.height,thumbnailVersion:v.thumbnailVersion},l[C]=[P,{mtime:new Date(w)}],Vs(y.id,{dataUrl:v.thumbnailDataUrl,width:v.width,height:v.height,thumbnailVersion:v.thumbnailVersion})}}const f={version:3,exportedAt:new Date(a).toISOString()};e.exportConfig&&(f.settings=n),e.exportTasks&&(f.tasks=t,f.imageFiles=i,f.thumbnailFiles=c),l["manifest.json"]=[_a(JSON.stringify(f,null,2)),{mtime:new Date(a)}];const m=D0(l,{level:6}),u=new Blob([m.buffer],{type:"application/zip"}),h=URL.createObjectURL(u),x=document.createElement("a");x.href=h,x.download=`gpt-image-playground-${Tf(new Date(a))}.zip`,x.click(),URL.revokeObjectURL(h),E.getState().showToast("数据已导出","success")}catch(t){E.getState().showToast(`导出失败:${t instanceof Error?t.message:String(t)}`,"error")}}async function Cf(e,t={importConfig:!0,importTasks:!0}){try{const r=await e.arrayBuffer(),n=U0(new Uint8Array(r)),a=n["manifest.json"];if(!a)throw new Error("ZIP 中缺少 manifest.json");const o=JSON.parse(Jl(a)),i=[];if(t.importTasks&&o.tasks&&o.imageFiles){for(const[f,m]of Object.entries(o.imageFiles)){const u=n[m.path];if(!u)continue;const h=ji(u,m.path);await cn({id:f,dataUrl:h,createdAt:m.createdAt,source:m.source,width:m.width,height:m.height}),rr(f,h),i.push(f)}for(const[f,m]of Object.entries(o.thumbnailFiles??{})){const u=n[m.path];if(!u)continue;const h=ji(u,m.path);await $n({id:f,thumbnailDataUrl:h,width:m.width,height:m.height,thumbnailVersion:m.thumbnailVersion}),Vs(f,{dataUrl:h,width:m.width,height:m.height,thumbnailVersion:m.thumbnailVersion})}for(const f of o.tasks)await Gn(f);const l=await Ya();E.getState().setTasks(l),rf(l),uo(i)}if(t.importConfig&&o.settings){const l=E.getState();l.setSettings(qa(l.settings,o.settings))}let c="数据已成功导入";return t.importTasks&&o.tasks?c=`已导入 ${o.tasks.length} 条记录`:t.importConfig&&o.settings&&(c="配置已成功导入"),E.getState().showToast(c,"success"),!0}catch(r){return E.getState().showToast(`导入失败:${r instanceof Error?r.message:String(r)}`,"error"),!1}}async function Mf(e){if(!e.type.startsWith("image/"))return;const t=await Af(e),r=await Ir(t,"upload");rr(r,t),E.getState().addInputImage({id:r,dataUrl:t})}async function Rf(e){const r=await(await fetch(e)).blob();if(!r.type.startsWith("image/"))throw new Error("不是有效的图片");const n=await _f(r),a=await Ir(n,"upload");rr(a,n),E.getState().addInputImage({id:a,dataUrl:n})}function Af(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=r,n.readAsDataURL(e)})}function _f(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=r,n.readAsDataURL(e)})}const Ii="docker-api-url-migration-notice-v1";function Lf(){const e=E(t=>t.setConfirmDialog);g.useEffect(()=>{if(un()!=="true"||un()!=="true"||localStorage.getItem(Ii)==="true")return;const t=()=>{localStorage.setItem(Ii,"true")};e({title:"Docker 部署配置变更",message:"当前版本已将 Docker 环境变量 `API_URL` 拆分为 `DEFAULT_API_URL` 和 `API_PROXY_URL`。\n\n`DEFAULT_API_URL` 只用于前端设置中的默认 API 地址;`API_PROXY_URL` 只用于容器内 Nginx 的 API 代理转发目标。\n\n为避免升级后立即失效,旧的 `API_URL` 会自动同时作为两个新变量的兜底值。建议后续更新 docker run 或 docker-compose 配置,显式使用新变量。",confirmText:"我知道了",showCancel:!1,icon:"info",minConfirmDelayMs:3e3,action:t,cancelAction:t})},[e])}const cc="CookSleep/gpt_image_playground",Df=`https://api.github.com/repos/${cc}/releases/latest`;function Uf(e,t){const r=e.split(".").map(o=>Number.parseInt(o,10)||0),n=t.split(".").map(o=>Number.parseInt(o,10)||0),a=Math.max(r.length,n.length);for(let o=0;o<a;o+=1){const i=(r[o]??0)-(n[o]??0);if(i!==0)return i}return 0}function Of(){const[e,t]=g.useState(null),[r,n]=g.useState(()=>sessionStorage.getItem("version-dismissed")==="true");return g.useEffect(()=>{let i=!1;return fetch(Df,{headers:{Accept:"application/vnd.github.v3+json"}}).then(c=>{if(!c.ok)throw new Error(`HTTP ${c.status}`);return c.json()}).then(c=>{if(i)return;const l=c.tag_name??"",f=l.replace(/^v/,"");f&&Uf(f,"0.3.5")>0&&t({tag:l,url:c.html_url??`https://github.com/${cc}/releases/latest`})}).catch(()=>{}),()=>{i=!0}},[]),{hasUpdate:e!==null&&!r,latestRelease:e,dismiss:()=>{n(!0),sessionStorage.setItem("version-dismissed","true")}}}function yr(){const[e,t]=g.useState(!1),r=g.useRef(null),n=g.useRef(!1),a=g.useCallback(()=>{r.current!=null&&(window.clearTimeout(r.current),r.current=null)},[]),o=g.useCallback(()=>{a(),n.current=!0,t(!1)},[a]);g.useEffect(()=>()=>{a()},[a]),g.useEffect(()=>Qi(o),[o]);const i=g.useCallback(()=>{n.current=!1,t(!0)},[]),c=g.useCallback(()=>{t(!1)},[]);return{visible:e,handlers:{onMouseEnter:i,onMouseLeave:c,onFocus:i,onBlur:c,onClick:()=>{a(),r.current=window.setTimeout(()=>{n.current||t(!0),r.current=null},300)},onTouchEnd:a,onTouchCancel:a},dismiss:o}}function jt({visible:e,children:t,className:r=""}){const n=g.useRef(null),a=g.useRef(null),[o,i]=g.useState(null),[c,l]=g.useState(!1);g.useEffect(()=>{if(!e){l(!1);return}return Qi(()=>l(!0))},[e]);const f=e&&!c;return g.useEffect(()=>{if(!f){i(null);return}const m=()=>{const u=n.current?.parentElement,h=a.current;if(!u||!h)return;const x=8,y=8,b=u.getBoundingClientRect();if(!u.getClientRects().length||b.width===0&&b.height===0){i(null);return}const d=h.getBoundingClientRect(),p=b.left+b.width/2,w=Math.max(x,window.innerWidth-d.width-x),v=Math.min(Math.max(p-d.width/2,x),w),j=b.top-d.height-y,P=j>=x?"top":"bottom",C=P==="top"?j:b.bottom+y;i({left:v,top:C,arrowLeft:p-v,placement:P})};return m(),window.addEventListener("resize",m),window.addEventListener("scroll",m,!0),()=>{window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0)}},[f,t]),s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:n,className:"hidden","aria-hidden":!0}),f&&fr.createPortal(s.jsxs("div",{ref:a,className:`fixed pointer-events-none rounded-lg bg-gray-800 px-3 py-2 text-xs font-normal text-white shadow-lg ${r}`,style:{left:o?.left??0,top:o?.top??0,visibility:o?"visible":"hidden",zIndex:120},children:[t,s.jsx("div",{className:`absolute left-0 border-4 border-transparent ${o?.placement==="bottom"?"bottom-full border-b-gray-800":"top-full border-t-gray-800"}`,style:{left:o?.arrowLeft??0,transform:"translateX(-50%)"}})]}),document.body)]})}const br=[];let Bf=0;function $f(e){e.key==="Escape"&&br.length!==0&&(e.preventDefault(),br[br.length-1].handler())}let Pi=!1;function Ff(){Pi||(Pi=!0,window.addEventListener("keydown",$f))}function Jr(e,t){const r=g.useRef(null),n=g.useRef(t);n.current=t,g.useEffect(()=>{if(!e){if(r.current!==null){const o=br.findIndex(i=>i.id===r.current);o!==-1&&br.splice(o,1),r.current=null}return}Ff();const a=Bf++;return r.current=a,br.push({id:a,handler:()=>n.current()}),()=>{const o=br.findIndex(i=>i.id===a);o!==-1&&br.splice(o,1),r.current=null}},[e])}let Mn=0,Si="",Ni="",Ti="";function zf(e,t){if(!(e instanceof Node)||!t)return null;const r=Array.isArray(t)?t:[t];for(const n of r){const a=n.current;if(a?.contains(e))return a}return null}function Mr(e,t){g.useEffect(()=>{if(!e)return;Mn===0&&(Si=document.body.style.overflow,Ni=document.body.style.overscrollBehavior,Ti=document.documentElement.style.overscrollBehavior,document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",document.documentElement.style.overscrollBehavior="none"),Mn+=1;const r=n=>{zf(n.target,t)||n.preventDefault()};return document.addEventListener("wheel",r,{capture:!0,passive:!1}),document.addEventListener("touchmove",r,{capture:!0,passive:!1}),()=>{document.removeEventListener("wheel",r,{capture:!0}),document.removeEventListener("touchmove",r,{capture:!0}),Mn=Math.max(0,Mn-1),Mn===0&&(document.body.style.overflow=Si,document.body.style.overscrollBehavior=Ni,document.documentElement.style.overscrollBehavior=Ti)}},[e,t])}function Hf(){const[e,t]=g.useState(window.innerWidth<640);return g.useEffect(()=>{const r=()=>t(window.innerWidth<640);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function qf({onClose:e}){const t=Hf(),r=g.useRef(null);return Jr(!0,e),Mr(!0,r),fr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[100] flex items-center justify-center p-4",onClick:e,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{ref:r,className:"relative z-10 w-full max-w-md rounded-3xl border border-white/50 bg-white/95 p-5 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10 flex flex-col max-h-[85vh] custom-scrollbar",onClick:n=>n.stopPropagation(),children:[s.jsxs("div",{className:"mb-5 flex items-center justify-between gap-4",children:[s.jsxs("h3",{className:"text-base font-semibold text-gray-800 dark:text-gray-100 flex items-center gap-2",children:[s.jsxs("svg",{className:"w-5 h-5 text-blue-500",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("path",{d:"M12 17h.01"})]}),"操作指南"]}),s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("button",{onClick:e,className:"rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})})]}),s.jsx("div",{className:"flex-1 overflow-y-auto overscroll-contain mb-6 text-sm text-gray-600 dark:text-gray-300 space-y-6 custom-scrollbar pr-2",children:t?s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h7"})}),"多选记录"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("p",{children:["在历史记录卡片上",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"左右滑动"}),"即可选中或取消选中该卡片。"]})})]}),s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"批量操作"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("p",{children:["选中一条或多条记录后,页面底部会出现操作栏,支持",s.jsx("strong",{className:"text-gray-500 dark:text-gray-400 font-medium",children:"取消选择"}),"、",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"全选当前可见记录"}),"、",s.jsx("strong",{className:"text-yellow-500 dark:text-yellow-400 font-medium",children:"批量收藏"}),"、",s.jsx("strong",{className:"text-green-500 dark:text-green-400 font-medium",children:"批量下载"}),",和",s.jsx("strong",{className:"text-red-500 dark:text-red-400 font-medium",children:"批量删除"}),"。"]})})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h7"})}),"多选记录"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("ul",{className:"list-disc pl-4 space-y-2",children:[s.jsxs("li",{children:["使用鼠标在空白处",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"拖拽框选"}),"。"]}),s.jsxs("li",{children:["按住 ",s.jsx("kbd",{className:"px-1.5 py-0.5 rounded-md bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-xs font-sans",children:"Ctrl"})," 或 ",s.jsx("kbd",{className:"px-1.5 py-0.5 rounded-md bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-xs font-sans",children:"⌘"})," 并点击卡片,可添加或移除单项。"]}),s.jsx("li",{children:"再次框选已选中的卡片会将其取消选中。"}),s.jsx("li",{children:"点击卡片外任意空白处可取消所有选择。"})]})})]}),s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"批量操作"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("p",{children:["选中一条或多条记录后,页面底部会出现操作栏,支持",s.jsx("strong",{className:"text-gray-500 dark:text-gray-400 font-medium",children:"取消选择"}),"、",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"全选当前可见记录"}),"、",s.jsx("strong",{className:"text-yellow-500 dark:text-yellow-400 font-medium",children:"批量收藏"}),"、",s.jsx("strong",{className:"text-green-500 dark:text-green-400 font-medium",children:"批量下载"}),",和",s.jsx("strong",{className:"text-red-500 dark:text-red-400 font-medium",children:"批量删除"}),"。"]})})]})]})}),s.jsx("div",{className:"pt-4 border-t border-gray-200 dark:border-white/[0.08] flex justify-center",children:s.jsxs("a",{href:"https://github.com/CookSleep/gpt_image_playground",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm font-medium text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors group",children:[s.jsx("svg",{className:"w-5 h-5 group-hover:scale-110 transition-transform",viewBox:"0 0 24 24",fill:"currentColor",children:s.jsx("path",{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"})}),"@CookSleep"]})})]})]}),document.body)}function Ei(){const e=window.navigator;return window.matchMedia("(display-mode: standalone)").matches||e.standalone===!0}function Wf(e){if(e?.startsWith("/")&&!e.startsWith("//"))return e;const t=window;return(typeof t.__ROUTER_BASENAME__=="string"?t.__ROUTER_BASENAME__.trim().replace(/\/+$/,""):"")||"/"}function Kf({returnPath:e=null}){const t=E(p=>p.setShowSettings),r=E(p=>p.setConfirmDialog),{hasUpdate:n,latestRelease:a,dismiss:o}=Of(),[i,c]=g.useState(!1),[l,f]=g.useState(null),[m,u]=g.useState(Ei),h=yr(),x=yr(),y=yr(),b=yr();g.useEffect(()=>{const p=v=>{v.preventDefault(),f(v),u(!1)},w=()=>{f(null),u(!0)};return window.addEventListener("beforeinstallprompt",p),window.addEventListener("appinstalled",w),()=>{window.removeEventListener("beforeinstallprompt",p),window.removeEventListener("appinstalled",w)}},[]);const d=async()=>{if(l){const p=l;f(null);try{await p.prompt();const w=await p.userChoice;u(w.outcome==="accepted")}catch{u(Ei())}}else{const p=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;r(p?{title:"安装为应用",message:"在 Safari 浏览器中,点击底部「分享」按钮,选择「添加到主屏幕」即可安装此应用。",showCancel:!1,confirmText:"我知道了",icon:"info",action:()=>{}}:{title:"安装为应用",message:`请在浏览器的菜单中选择「添加到主屏幕」或「安装应用」。
14
+
15
+ (如果在微信等内置浏览器中,请先在外部浏览器打开)`,showCancel:!1,confirmText:"我知道了",icon:"info",action:()=>{}})}};return s.jsxs(s.Fragment,{children:[s.jsx("header",{"data-no-drag-select":!0,className:"safe-area-top fixed top-0 left-0 right-0 z-40 bg-white/80 dark:bg-gray-950/80 backdrop-blur border-b border-gray-200 dark:border-white/[0.08]",children:s.jsxs("div",{className:"safe-area-x safe-header-inner max-w-7xl mx-auto flex items-center justify-between",children:[s.jsxs("div",{className:"flex flex-1 min-w-0 items-center gap-2 pr-2",children:[s.jsxs("div",{className:"relative shrink-0",...x.handlers,children:[s.jsx("button",{type:"button",onClick:()=>{Ht(),window.location.assign(Wf(e))},className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors","aria-label":"返回对话首页",children:s.jsxs("svg",{className:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"M19 12H5"}),s.jsx("path",{d:"M12 19l-7-7 7-7"})]})}),s.jsx(jt,{visible:x.visible,className:"whitespace-nowrap",children:"返回对话首页"})]}),s.jsxs("h1",{className:"inline-flex items-start relative",children:[s.jsx("span",{className:"text-[17px] sm:text-lg font-bold tracking-tight text-gray-800 dark:text-gray-100",children:"GPTImage2"}),n&&a&&s.jsx("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",onClick:o,className:"absolute -right-1 -top-1 translate-x-full -translate-y-1/4 px-1 py-0.5 rounded-[4px] border border-red-500/30 text-[9px] font-black bg-red-500 text-white hover:bg-red-600 transition-all animate-fade-in leading-none shadow-sm",title:`新版本 ${a.tag}`,children:"NEW"})]})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[!m&&s.jsxs("div",{className:"relative",...h.handlers,children:[s.jsx("button",{onClick:()=>{Ht(),d()},className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors","aria-label":"安装为应用",children:s.jsxs("svg",{className:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("polyline",{points:"7 10 12 15 17 10"}),s.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})}),s.jsx(jt,{visible:h.visible,className:"whitespace-nowrap",children:"安装为应用"})]}),s.jsxs("div",{className:"relative",...y.handlers,children:[s.jsx("button",{onClick:()=>{Ht(),c(!0)},className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors","aria-label":"操作指南",children:s.jsxs("svg",{className:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("path",{d:"M12 17h.01"})]})}),s.jsx(jt,{visible:y.visible,className:"whitespace-nowrap",children:"操作指南"})]}),s.jsxs("div",{className:"relative",...b.handlers,children:[s.jsx("button",{onClick:()=>t(!0),className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors","aria-label":"设置",children:s.jsxs("svg",{className:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}),s.jsx(jt,{visible:b.visible,className:"whitespace-nowrap",children:"设置"})]})]})]})}),s.jsx("div",{className:"safe-area-top invisible pointer-events-none","aria-hidden":"true",children:s.jsx("div",{className:"safe-header-inner"})}),i&&s.jsx(qf,{onClose:()=>c(!1)})]})}const Ci=8,Yf=/(auto|scroll|hidden|clip)/,an=240;function Vf(e,t=an){const r=e.getBoundingClientRect();let n=window.innerHeight-r.bottom-Ci,a=e.parentElement;for(;a&&a!==document.body;){const o=window.getComputedStyle(a);if(Yf.test(`${o.overflow} ${o.overflowY}`)){const i=a.getBoundingClientRect();n=Math.min(n,i.bottom-r.bottom-Ci)}a=a.parentElement}return Math.max(0,Math.min(t,Math.floor(n)))}function Jt(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function Ls(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function dc(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function wr(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}function uc(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})}function Xf(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})})}function Jf(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"})})}function Gf(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})})}function bo(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function fc(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})})}function js(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"})})}function Qf(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v6h6M20 20v-6h-6M5.64 16.36A8 8 0 0018.36 18M18.36 7.64A8 8 0 005.64 6"})})}function Zf(e){return s.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",...e,children:s.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function Ds(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8h16M4 16h16"})})}function zr({value:e,onChange:t,onReorder:r,options:n,disabled:a,className:o}){const[i,c]=g.useState(!1),[l,f]=g.useState(an),[m,u]=g.useState("bottom"),[h,x]=g.useState(null),[y,b]=g.useState(null),[d,p]=g.useState(null),[w,v]=g.useState(null),j=g.useRef(null),P=g.useRef(null),C=g.useRef(null),$=g.useRef(null),R=n.find(L=>L.value===e);g.useEffect(()=>()=>{P.current&&clearInterval(P.current)},[]),g.useEffect(()=>{if(!w)return;const L=Y=>{Y.preventDefault()},H={passive:!1,capture:!0},q=document.body.style.overflow,F=document.body.style.overscrollBehavior;return document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",window.addEventListener("touchmove",L,H),()=>{document.body.style.overflow=q,document.body.style.overscrollBehavior=F,window.removeEventListener("touchmove",L,H)}},[w]),g.useEffect(()=>{const L=H=>{C.current&&!C.current.contains(H.target)&&c(!1)};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[]),g.useEffect(()=>{if(!i)return;const L=()=>{if(!$.current)return;const H=$.current,q=H.getBoundingClientRect();let F=window.innerHeight-q.bottom-8,Y=q.top-8,A=H.parentElement;for(;A&&A!==document.body;){const D=window.getComputedStyle(A);if(/(auto|scroll|hidden|clip)/.test(`${D.overflow} ${D.overflowY}`)){const W=A.getBoundingClientRect();F=Math.min(F,W.bottom-q.bottom-8),Y=Math.min(Y,q.top-W.top-8)}A=A.parentElement}let U="bottom",J=an;F<120&&Y>F?(U="top",J=Math.min(an,Math.floor(Y))):(U="bottom",J=Math.min(an,Math.floor(F))),u(U),f(Math.max(0,J))};return L(),window.addEventListener("resize",L),window.addEventListener("scroll",L,!0),()=>{window.removeEventListener("resize",L),window.removeEventListener("scroll",L,!0)}},[i]);const N=L=>{a||(L.preventDefault(),L.stopPropagation(),c(!i))},Q=()=>{j.current=null,v(null),x(null),b(null),p(null),P.current&&(clearInterval(P.current),P.current=null)};return s.jsxs("div",{ref:C,className:"relative w-full",children:[s.jsxs("div",{ref:$,onClick:N,className:`flex items-center justify-between gap-1 w-full cursor-pointer select-none ${o??""} ${a?"!opacity-50 !cursor-not-allowed !bg-gray-100/50 dark:!bg-white/[0.05]":""}`,children:[s.jsx("span",{className:"truncate",children:R?.label??e}),s.jsx(uc,{className:`w-3.5 h-3.5 flex-shrink-0 text-gray-400 dark:text-gray-500 transition-transform duration-200 ${i?"rotate-180":""}`})]}),i&&s.jsx("div",{className:`absolute z-50 w-full overflow-hidden overflow-y-auto rounded-xl border border-gray-200/60 bg-white/95 py-1 shadow-[0_8px_30px_rgb(0,0,0,0.12)] ring-1 ring-black/5 backdrop-blur-xl dark:border-white/[0.08] dark:bg-gray-900/95 dark:shadow-[0_8px_30px_rgb(0,0,0,0.3)] dark:ring-white/10 custom-scrollbar ${m==="top"?"bottom-full mb-1.5 animate-dropdown-up":"top-full mt-1.5 animate-dropdown-down"}`,style:{maxHeight:l},children:n.map(L=>s.jsxs("div",{"data-option-value":String(L.value),draggable:L.draggable,onDragStart:H=>{L.draggable&&(x(L.value),H.dataTransfer.effectAllowed="move",H.dataTransfer.setData("text/plain",String(L.value)))},onDragOver:H=>{if(!L.draggable||!h)return;H.preventDefault(),H.dataTransfer.dropEffect="move";const q=H.currentTarget,F=q.getBoundingClientRect(),Y=H.clientY<F.top+F.height/2?"before":"after";(y!==L.value||d!==Y)&&(b(L.value),p(Y));const A=q.parentElement;if(A){const U=A.getBoundingClientRect(),J=30;H.clientY<U.top+J?A.scrollTop-=10:H.clientY>U.bottom-J&&(A.scrollTop+=10)}},onDragEnd:()=>{x(null),b(null),p(null)},onDrop:H=>{if(!L.draggable||!r)return;H.preventDefault(),x(null),b(null),p(null);const q=H.dataTransfer.getData("text/plain"),F=n.find(Y=>String(Y.value)===q);F&&F.value!==L.value&&r(F.value,L.value,d)},onTouchStart:H=>{if(!L.draggable||!H.target.closest("[data-drag-handle]"))return;const F=H.touches[0],Y=H.currentTarget.getBoundingClientRect();H.stopPropagation(),j.current={value:L.value,startX:F.clientX,startY:F.clientY,moved:!1},x(L.value),v({label:L.label,x:F.clientX,y:F.clientY,width:Y.width,height:Y.height,offsetX:F.clientX-Y.left,offsetY:F.clientY-Y.top})},onTouchMove:H=>{const q=j.current;if(!q||!L.draggable)return;const F=H.touches[0];if(!q.moved)if(Math.abs(F.clientX-q.startX)>5||Math.abs(F.clientY-q.startY)>5)q.moved=!0;else return;H.preventDefault(),v(D=>D&&{...D,x:F.clientX,y:F.clientY});const Y=document.getElementById("touch-drag-preview");Y&&(Y.style.pointerEvents="none");const U=document.elementFromPoint(F.clientX,F.clientY)?.closest("[data-option-value]");if(U){const D=U.getAttribute("data-option-value");if(D){const W=n.find(K=>String(K.value)===D);if(W&&W.draggable){const K=U.getBoundingClientRect(),O=F.clientY<K.top+K.height/2?"before":"after";(y!==W.value||d!==O)&&(b(W.value),p(O))}}}const J=U?.closest(".custom-scrollbar");if(J){const D=J.getBoundingClientRect(),W=30;P.current&&(clearInterval(P.current),P.current=null),F.clientY<D.top+W?P.current=window.setInterval(()=>{J.scrollTop-=5},16):F.clientY>D.bottom-W&&(P.current=window.setInterval(()=>{J.scrollTop+=5},16))}},onTouchEnd:H=>{const q=j.current;if(!q||!q.moved){Q();return}H.preventDefault(),r&&y!==null&&y!==q.value&&r(q.value,y,d),Q()},onTouchCancel:Q,onClick:H=>{H.target.closest("button, [data-drag-handle]")||(H.preventDefault(),t(L.value),c(!1))},className:`relative flex cursor-pointer items-center justify-between gap-2 px-3 py-2 text-xs transition-colors ${h===L.value?"opacity-40 bg-gray-100 dark:bg-white/[0.04]":L.variant==="action"?"font-semibold text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-500/10":L.variant==="danger"?"font-semibold text-red-500 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-500/10":L.value===e?"bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 font-medium":"text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-white/[0.06]"}`,children:[y===L.value&&d==="before"&&h!==L.value&&s.jsx("div",{className:"absolute -top-[1px] left-0 right-0 h-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),y===L.value&&d==="after"&&h!==L.value&&s.jsx("div",{className:"absolute -bottom-[1px] left-0 right-0 h-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[L.draggable&&s.jsx("div",{"data-drag-handle":!0,className:"flex cursor-grab active:cursor-grabbing items-center justify-center text-gray-400 opacity-60 transition-opacity hover:opacity-100 dark:text-gray-500",style:{touchAction:"none"},title:"拖拽排序",children:s.jsx(Ds,{className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"min-w-0 truncate",children:L.label})]}),L.actions?.length?s.jsx("span",{className:"ml-auto flex shrink-0 items-center gap-1",children:L.actions.map(H=>s.jsx("button",{type:"button",title:H.label,onPointerDown:q=>{q.stopPropagation()},onClick:q=>{q.preventDefault(),q.stopPropagation(),H.onClick(),c(!1)},className:`rounded-md p-1.5 transition flex items-center justify-center ${H.variant==="danger"?"text-red-500 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-500/10":"text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.08] dark:hover:text-gray-200"}`,children:H.label==="编辑"?s.jsx(bo,{className:"w-3.5 h-3.5"}):H.label==="删除"?s.jsx(Ls,{className:"w-3.5 h-3.5"}):H.label},H.label))}):null,L.variant==="action"&&s.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:s.jsx(dc,{className:"h-4 w-4"})})]},L.value))}),w&&fr.createPortal(s.jsx("div",{id:"touch-drag-preview",className:"fixed pointer-events-none z-[110] flex items-center justify-between gap-2 rounded-xl bg-white/95 px-3 py-2 text-xs text-gray-700 shadow-xl ring-1 ring-black/5 backdrop-blur-xl dark:bg-gray-900/95 dark:text-gray-300 dark:ring-white/10",style:{left:w.x-w.offsetX,top:w.y-w.offsetY,width:w.width,minHeight:w.height},children:s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[s.jsx(Ds,{className:"h-3.5 w-3.5 shrink-0 text-gray-400 dark:text-gray-500"}),s.jsx("span",{className:"min-w-0 truncate",children:w.label})]})}),document.body)]})}function em(){const e=E(i=>i.searchQuery),t=E(i=>i.setSearchQuery),r=E(i=>i.filterStatus),n=E(i=>i.setFilterStatus),a=E(i=>i.filterFavorite),o=E(i=>i.setFilterFavorite);return s.jsxs("div",{"data-no-drag-select":!0,className:"mt-6 mb-4 flex gap-3",children:[s.jsxs("div",{className:"flex gap-2 flex-shrink-0 z-20",children:[s.jsx("button",{onClick:()=>o(!a),className:`p-2.5 rounded-xl border transition-all ${a?"border-yellow-400 bg-yellow-50 dark:bg-yellow-500/10 text-yellow-500":"border-gray-200 dark:border-white/[0.08] bg-white dark:bg-gray-900 text-gray-400 hover:bg-gray-50 dark:hover:bg-white/[0.06]"}`,title:a?"取消只看收藏":"只看收藏",children:s.jsx("svg",{className:"w-5 h-5",fill:a?"currentColor":"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})}),s.jsx("div",{className:"relative w-28",children:s.jsx(zr,{value:r,onChange:i=>n(i),options:[{label:"全部状态",value:"all"},{label:"已完成",value:"done"},{label:"生成中",value:"running"},{label:"失败",value:"error"}],className:"px-3 py-2.5 rounded-xl border border-gray-200 dark:border-white/[0.08] bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-white/[0.06] text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400 transition"})})]}),s.jsxs("div",{className:"relative flex-1 z-10",children:[s.jsx("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),s.jsx("input",{value:e,onChange:i=>t(i.target.value),type:"text",placeholder:"搜索提示词、参数...",className:"w-full pl-10 pr-4 py-2.5 rounded-xl border border-gray-200 dark:border-white/[0.08] bg-white dark:bg-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400 transition"})]})]})}function $r({value:e,className:t="",variant:r="highlight"}){const[n,a]=g.useState(!1),o=g.useRef(null),i=r==="normal"?"bg-gray-100 text-gray-500 dark:bg-white/[0.04] dark:text-gray-400":"bg-yellow-100 text-yellow-800 dark:bg-yellow-500/20 dark:text-yellow-300";g.useEffect(()=>()=>{o.current!=null&&window.clearTimeout(o.current)},[]);const c=()=>{o.current!=null&&(window.clearTimeout(o.current),o.current=null)};return s.jsxs("span",{className:`relative inline-flex cursor-help ${i} ${t}`,role:"button",tabIndex:0,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onFocus:()=>a(!0),onBlur:()=>a(!1),onClick:()=>a(!0),onTouchStart:()=>{c(),o.current=window.setTimeout(()=>{a(!0),o.current=null},450)},onTouchEnd:c,onTouchCancel:c,children:[e,s.jsx(jt,{visible:n,className:"whitespace-nowrap",children:"API 实际响应值"})]})}function Ln(e,t,r=e.actualParams){const n=e.params[t],a=r?.[t],o=a!=null,i=o?a:n,c=o&&n!=="auto"&&String(a)!==String(n);return{displayValue:String(i),isMismatch:c,requestedValue:String(n),isAutoResolved:o&&n==="auto"&&String(a)!==String(n)}}function en({task:e,paramKey:t,className:r="",actualParams:n}){const{displayValue:a,isMismatch:o,requestedValue:i,isAutoResolved:c}=Ln(e,t,n);return o?s.jsxs("span",{className:`inline-flex items-center gap-1 ${r}`,children:[s.jsx("span",{className:"text-gray-700 dark:text-gray-300",children:i}),s.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"|"}),s.jsx($r,{value:a,className:"rounded px-1 py-0.5"})]}):c?s.jsxs("span",{className:`inline-flex items-center gap-1 ${r}`,children:[s.jsx("span",{className:"text-gray-700 dark:text-gray-300",children:i}),s.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"|"}),s.jsx($r,{value:a,variant:"normal",className:"rounded px-1 py-0.5"})]}):s.jsx("span",{className:`text-gray-700 dark:text-gray-300 ${r}`,children:a})}function tm({task:e,onReuse:t,onEditOutputs:r,onDelete:n,onClick:a,isSelected:o}){const[i,c]=g.useState(""),[l,f]=g.useState(""),[m,u]=g.useState(""),[h,x]=g.useState(Date.now()),[y,b]=g.useState(0),[d,p]=g.useState(!1),[w,v]=g.useState(!1),[j,P]=g.useState(!1),C=E(ne=>ne.toggleTaskSelection),$=E(ne=>ne.settings),R=g.useRef(null),N=g.useRef(null),Q=g.useRef(0),L=g.useRef(!1),H=ne=>ne instanceof Element&&!!ne.closest("[data-tag-scroll-area]"),q=ne=>{if(H(ne.target)){R.current=null,L.current=!1,p(!1),b(0),P(!1);return}N.current!=null&&(window.clearTimeout(N.current),N.current=null),R.current={x:ne.touches[0].clientX,y:ne.touches[0].clientY},L.current=!1,v(!!o),P(!1),p(!0)},F=ne=>{if(H(ne.target)||!R.current)return;const ve=ne.touches[0].clientX-R.current.x,_e=ne.touches[0].clientY-R.current.y;if(Math.abs(ve)>Math.abs(_e)&&Math.abs(ve)>10){L.current=!0,ne.preventDefault();const ft=Math.max(-60,Math.min(60,ve));b(ft),P(Math.abs(ve)>=40)}},Y=ne=>{if(H(ne.target)){R.current=null,L.current=!1,p(!1),b(0),P(!1);return}if(p(!1),b(0),!R.current)return;const ve=ne.changedTouches[0].clientX-R.current.x;R.current=null;const _e=L.current&&Math.abs(ve)>40;L.current=!1,P(_e),N.current=window.setTimeout(()=>{P(!1),N.current=null},220),_e&&(Q.current=Date.now()+350,ne.preventDefault(),ne.stopPropagation(),C(e.id))},A=()=>{R.current=null,L.current=!1,p(!1),b(0),P(!1)};g.useEffect(()=>()=>{N.current!=null&&window.clearTimeout(N.current)},[]),g.useEffect(()=>{if(e.status!=="running"&&!(e.status==="error"&&(e.falRecoverable||e.customRecoverable)))return;const ne=setInterval(()=>x(Date.now()),1e3);return x(Date.now()),()=>clearInterval(ne)},[e.customRecoverable,e.falRecoverable,e.status]),g.useEffect(()=>{f(""),u(""),c("");let ne=!1;const ve=e.outputImages?.[0];let _e;const ft=je=>{ne||(c(je.dataUrl),je.width&&je.height&&(f(Ll(je.width,je.height)),u(`${je.width}×${je.height}`)))};return ve&&(_e=X0(ve,ft),V0(ve).then(je=>{ne||!je||ft(je)}).catch(()=>{ne||c("")})),()=>{ne=!0,_e?.()}},[e.outputImages]);const U=(()=>{let ne;if(e.status==="running"||e.falRecoverable||e.customRecoverable)ne=Math.floor((h-e.createdAt)/1e3);else if(e.elapsed!=null)ne=Math.floor(e.elapsed/1e3);else return"00:00";const ve=String(Math.floor(ne/60)).padStart(2,"0"),_e=String(ne%60).padStart(2,"0");return`${ve}:${_e}`})(),D=Math.abs(y)>=40||j,W=e.status==="error"&&e.falRecoverable,K=e.status==="error"&&e.customRecoverable,O=e.status==="running"||W||K,z=D?w?"bg-gray-500 dark:bg-gray-600":"bg-blue-500":"bg-gray-200 dark:bg-gray-700",T=Ln(e,"quality"),V=e.params.quality!=="auto"||T.isMismatch,Z=Ln(e,"size"),ee=e.params.size!=="auto"||Z.isMismatch,oe=Ln(e,"output_format"),ye=e.params.output_format!=="png"||oe.isMismatch,fe=Ln(e,"n"),be=e.params.n>1||fe.isMismatch,xe=e.apiProvider==="fal"?on:At,ke=e.apiModel&&e.apiModel!==xe;return s.jsxs("div",{className:"relative rounded-xl",children:[s.jsx("div",{className:`absolute inset-0 rounded-xl flex items-center transition-opacity duration-200 pointer-events-none ${d||y||j?"opacity-100":"opacity-0"} ${z} ${y>0?"justify-start pl-6":"justify-end pr-6"}`,children:s.jsx("svg",{className:`w-8 h-8 transition-transform duration-150 ${D?"scale-110 text-white":"scale-90 text-white/60"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:w&&D?s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"}):s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),s.jsxs("div",{className:`relative bg-white dark:bg-gray-900 rounded-xl border overflow-hidden cursor-pointer duration-200 hover:shadow-lg dark:hover:bg-gray-800/80 ${d?"transition-[box-shadow,border-color,background-color]":"transition-[box-shadow,border-color,background-color,transform]"} ${e.status==="running"?"border-blue-400 generating":o?"border-blue-500 shadow-md ring-2 ring-blue-500/50":"border-gray-200 dark:border-white/[0.08] hover:border-gray-300 dark:hover:border-white/[0.18]"}`,style:{transform:y?`translateX(${y}px)`:void 0},onClick:ne=>{if(Date.now()<Q.current){ne.preventDefault(),ne.stopPropagation();return}a(ne)},onTouchStart:q,onTouchMove:F,onTouchEnd:Y,onTouchCancel:A,children:[o&&s.jsx("div",{className:"absolute top-2 right-2 z-10 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center shadow-sm",children:s.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),s.jsxs("div",{className:"flex h-40",children:[s.jsxs("div",{className:"w-40 min-w-[10rem] h-full bg-gray-100 dark:bg-black/20 relative flex items-center justify-center overflow-hidden flex-shrink-0",children:[e.status==="running"&&s.jsxs("div",{className:"flex flex-col items-center gap-2",children:[s.jsxs("svg",{className:"w-8 h-8 text-blue-400 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),s.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"生成中..."})]}),e.status==="error"&&W&&s.jsxs("div",{className:"flex flex-col items-center gap-1 px-2",children:[s.jsx("svg",{className:"w-7 h-7 text-yellow-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),s.jsx("span",{className:"text-xs text-yellow-500 text-center leading-tight",children:"重连中"})]}),e.status==="error"&&!W&&s.jsxs("div",{className:"flex flex-col items-center gap-1 px-2",children:[s.jsx("svg",{className:"w-7 h-7 text-red-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx("span",{className:"text-xs text-red-400 text-center leading-tight",children:"失败"})]}),e.status==="done"&&i&&s.jsxs(s.Fragment,{children:[s.jsx("img",{src:i,"data-image-id":e.outputImages[0],className:"saveable-image w-full h-full object-cover",loading:"lazy",alt:""}),e.outputImages.length>1&&s.jsx("span",{className:"absolute bottom-1 right-1 bg-black/60 text-white text-xs px-1.5 py-0.5 rounded",children:e.outputImages.length})]}),e.status==="done"&&!i&&s.jsx("svg",{className:"w-8 h-8 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),s.jsx("div",{className:"absolute top-1.5 left-1.5 flex items-center gap-1",children:O||e.status!=="done"||!l||!m?s.jsxs("span",{className:"flex items-center gap-1 bg-black/50 text-white text-[10px] sm:text-xs px-1.5 py-0.5 rounded backdrop-blur-sm font-mono",children:[s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),U]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"bg-black/50 text-white text-[10px] sm:text-xs px-1.5 py-0.5 rounded backdrop-blur-sm font-mono",children:l}),s.jsx("span",{className:"bg-black/50 text-white/90 text-[10px] sm:text-xs px-1.5 py-0.5 rounded backdrop-blur-sm font-medium",children:m})]})})]}),s.jsxs("div",{className:"flex-1 p-3 flex flex-col min-w-0",children:[s.jsx("div",{className:"flex-1 min-h-0 mb-2 overflow-hidden",children:s.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300 leading-relaxed line-clamp-3",children:e.prompt||"(无提示词)"})}),s.jsxs("div",{className:"mt-auto flex flex-col gap-1.5",children:[s.jsxs("div",{"data-tag-scroll-area":!0,className:"flex overflow-x-auto hide-scrollbar pt-0.5 gap-1.5 whitespace-nowrap mask-edge-r min-w-0 pr-2",onTouchStart:ne=>ne.stopPropagation(),onTouchMove:ne=>ne.stopPropagation(),onTouchEnd:ne=>ne.stopPropagation(),onTouchCancel:ne=>ne.stopPropagation(),children:[(e.apiProfileName||e.apiProvider)&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 text-xs flex-shrink-0",title:e.apiProfileName||e.apiProvider,children:[s.jsx(fc,{className:"w-3 h-3 flex-shrink-0 text-gray-400"}),s.jsx("span",{className:"truncate max-w-[8rem]",children:e.apiProfileName||e.apiProvider})]}),ke&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 text-xs flex-shrink-0",title:e.apiModel,children:[s.jsx("svg",{className:"w-3 h-3 flex-shrink-0 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"})}),s.jsx("span",{className:"truncate max-w-[8rem]",children:e.apiModel})]}),e.maskImageId&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 text-xs flex-shrink-0",children:[s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"})}),"局部重绘"]}),V&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-xs flex-shrink-0",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"质量"}),T.isMismatch?s.jsx($r,{value:T.displayValue,className:"px-1 rounded-sm"}):s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:T.displayValue})]}),ee&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-xs flex-shrink-0",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"尺寸"}),Z.isMismatch?s.jsx($r,{value:Z.displayValue,className:"px-1 rounded-sm"}):s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:Z.displayValue})]}),ye&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-xs flex-shrink-0",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"格式"}),oe.isMismatch?s.jsx($r,{value:oe.displayValue,className:"px-1 rounded-sm"}):s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:oe.displayValue})]}),be&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-xs flex-shrink-0",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"数量"}),fe.isMismatch?s.jsx($r,{value:fe.displayValue,className:"px-1 rounded-sm"}):s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:fe.displayValue})]})]}),s.jsxs("div",{className:"flex w-full items-center justify-between flex-shrink-0 mt-0.5 sm:w-auto sm:justify-end sm:gap-1",onClick:ne=>ne.stopPropagation(),children:[(e.status==="error"&&!W||$.alwaysShowRetryButton)&&s.jsx("button",{onClick:()=>ac(e),className:"p-1.5 rounded-md hover:bg-blue-50 dark:hover:bg-blue-950/30 text-gray-400 hover:text-blue-500 transition",title:"重试任务",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),s.jsx("button",{onClick:()=>wt(e.id,{isFavorite:!e.isFavorite}),className:`p-1.5 rounded-md transition ${e.isFavorite?"text-yellow-400 hover:bg-yellow-50 dark:hover:bg-yellow-500/10":"text-gray-400 hover:text-yellow-400 hover:bg-yellow-50 dark:hover:bg-yellow-500/10"}`,title:e.isFavorite?"取消收藏":"收藏记录",children:s.jsx("svg",{className:"w-4 h-4",fill:e.isFavorite?"currentColor":"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})}),s.jsx("button",{onClick:t,className:"p-1.5 rounded-md hover:bg-blue-50 dark:hover:bg-blue-950/30 text-gray-400 hover:text-blue-500 transition",title:"复用配置",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"})})}),s.jsx("button",{onClick:r,className:"p-1.5 rounded-md hover:bg-green-50 dark:hover:bg-green-950/30 text-gray-400 hover:text-green-500 transition disabled:opacity-30",title:"编辑输出",disabled:!e.outputImages?.length,children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}),s.jsx("button",{onClick:n,className:"p-1.5 rounded-md hover:bg-red-50 dark:hover:bg-red-950/30 text-gray-400 hover:text-red-500 transition",title:"删除记录",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]})]})]})]})]})]})}function rm(){const e=E(F=>F.tasks),t=E(F=>F.searchQuery),r=E(F=>F.filterStatus),n=E(F=>F.filterFavorite),a=E(F=>F.setDetailTaskId),o=E(F=>F.setConfirmDialog),i=E(F=>F.selectedTaskIds),c=E(F=>F.setSelectedTaskIds),l=E(F=>F.clearSelection),f=g.useRef(null),m=g.useRef(null),[u,h]=g.useState(null),x=g.useRef(!1),y=g.useRef(null),b=g.useRef(null),d=g.useRef(!1),p=g.useRef(null),w=g.useRef(null),v=g.useRef(0),j=g.useRef(0),P=g.useRef(!1),C=g.useRef(!1),$=g.useRef([]),R=/Mac|iPod|iPhone|iPad/.test(navigator.platform),N=g.useMemo(()=>{const F=[...e].sort((A,U)=>U.createdAt-A.createdAt),Y=t.trim().toLowerCase();return F.filter(A=>{if(n&&!A.isFavorite||!(r==="all"||A.status===r))return!1;if(!Y)return!0;const J=(A.prompt||"").toLowerCase(),D=JSON.stringify(A.params).toLowerCase();return J.includes(Y)||D.includes(Y)})},[e,t,r,n]),Q=F=>{o({title:"删除记录",message:"确定要删除这条记录吗?关联的图片资源也会被清理(如果没有其他任务引用)。",action:()=>lc(F)})},L=(F,Y)=>({pageX:F+window.scrollX,pageY:Y+window.scrollY}),H=(F,Y,A,U)=>{const J=L(Y,A);P.current=!!F.closest(".task-card-wrapper"),C.current=U,$.current=[...E.getState().selectedTaskIds],x.current=!0,d.current=!1,y.current=J,b.current={x:Y,y:A},document.body.classList.add("select-none"),document.body.classList.add("drag-selecting"),h({startPageX:J.pageX,startPageY:J.pageY,currentPageX:J.pageX,currentPageY:J.pageY})},q=(F,Y)=>{const A=y.current;if(!A||!m.current)return;const U=Math.min(A.pageX,F),J=Math.max(A.pageX,F),D=Math.min(A.pageY,Y),W=Math.max(A.pageY,Y),K=m.current.querySelectorAll(".task-card-wrapper"),O=new Set($.current),z=new Set($.current);K.forEach(T=>{const V=T.getBoundingClientRect(),Z=T.getAttribute("data-task-id");if(!Z)return;const ee=V.left+window.scrollX,oe=V.right+window.scrollX,ye=V.top+window.scrollY,fe=V.bottom+window.scrollY;U<oe&&J>ee&&D<fe&&W>ye?z.has(Z)?O.delete(Z):O.add(Z):z.has(Z)||O.delete(Z)}),c(Array.from(O))};return g.useEffect(()=>{const F=()=>{p.current&&(clearInterval(p.current),p.current=null),w.current=null},Y=z=>{p.current&&w.current===z||(F(),w.current=z,p.current=window.setInterval(()=>{window.scrollBy({top:z*15,behavior:"instant"})},16))},A=(z=!1,T=!1)=>{x.current&&(document.body.classList.remove("select-none"),document.body.classList.remove("drag-selecting")),x.current&&z&&!d.current&&!P.current&&!C.current&&l(),x.current&&T&&d.current&&(j.current=Date.now()+250),F(),x.current=!1,y.current=null,b.current=null,h(null)},U=z=>z.target instanceof Element?z.target:document.elementFromPoint(z.clientX,z.clientY),J=z=>{if(z.button!==0)return;const T=U(z);if(!T||!T.closest("[data-drag-select-surface]")||T.closest("[data-input-bar]")||T.closest("[data-no-drag-select], [data-lightbox-root]")||T.closest("button, a, input, textarea, select"))return;const V=R?z.metaKey:z.ctrlKey;H(T,z.clientX,z.clientY,V),z.preventDefault()},D=z=>{if(!x.current||!y.current)return;const T=y.current,V=L(z.clientX,z.clientY);if(b.current={x:z.clientX,y:z.clientY},Math.hypot(V.pageX-T.pageX,V.pageY-T.pageY)<6&&!d.current)return;d.current=!0,h({startPageX:T.pageX,startPageY:T.pageY,currentPageX:V.pageX,currentPageY:V.pageY}),q(V.pageX,V.pageY),z.preventDefault();const ee=40;z.clientY<ee?Y(-1):z.clientY>window.innerHeight-ee?Y(1):F()},W=()=>{if(!x.current||!y.current||!b.current||!d.current)return;const z=L(b.current.x,b.current.y),T=y.current;h({startPageX:T.pageX,startPageY:T.pageY,currentPageX:z.pageX,currentPageY:z.pageY}),q(z.pageX,z.pageY)},K=z=>{if(!x.current)return;if((z.buttons&1)===0){A();return}if(!d.current||!z.ctrlKey&&!z.metaKey)return;z.preventDefault();const T=Date.now();if(T-v.current>3e3){v.current=T;const V=R?"⌘":"Ctrl";E.getState().showToast(`松开 ${V} 键使用滚轮,或拖至边缘自动滚动`,"info")}},O=()=>{A(!0,!0)};return document.addEventListener("mousedown",J,!0),document.addEventListener("mousemove",D,!0),document.addEventListener("mouseup",O,!0),document.addEventListener("wheel",K,{capture:!0,passive:!1}),window.addEventListener("scroll",W,!0),()=>{F(),document.removeEventListener("mousedown",J,!0),document.removeEventListener("mousemove",D,!0),document.removeEventListener("mouseup",O,!0),document.removeEventListener("wheel",K,!0),window.removeEventListener("scroll",W,!0)}},[l,R]),N.length?s.jsxs("div",{ref:f,"data-task-grid-root":!0,className:"relative min-h-[50vh]",children:[s.jsx("div",{ref:m,className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 pb-10",children:N.map(F=>s.jsx("div",{className:"task-card-wrapper","data-task-id":F.id,children:s.jsx(tm,{task:F,onClick:Y=>{if(Date.now()<j.current){Y.preventDefault();return}j.current=0,(R?Y.metaKey:Y.ctrlKey)?E.getState().toggleTaskSelection(F.id):(i.length>0&&l(),a(F.id))},onReuse:()=>oc(F),onEditOutputs:()=>ic(F),onDelete:()=>Q(F),isSelected:i.includes(F.id)})},F.id))}),u&&s.jsx("div",{className:"fixed bg-blue-500/20 border border-blue-500/50 pointer-events-none z-[30]",style:{left:Math.min(u.startPageX,u.currentPageX)-window.scrollX,top:Math.min(u.startPageY,u.currentPageY)-window.scrollY,width:Math.abs(u.currentPageX-u.startPageX),height:Math.abs(u.currentPageY-u.startPageY)}})]}):s.jsx("div",{className:"text-center py-20 text-gray-400 dark:text-gray-500",children:t||n?s.jsx("p",{className:"text-sm",children:"没有找到匹配的记录"}):s.jsxs(s.Fragment,{children:[s.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 text-gray-200 dark:text-gray-700",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),s.jsx("p",{className:"text-sm",children:"输入提示词开始生成图片"})]})})}function ha(e){if(!e||!e.isConnected||typeof e.getBoundingClientRect!="function")return null;try{return e.getBoundingClientRect()}catch{return null}}const mc=["1K","2K","4K"],Mi=`由于模型限制,最终输出会自动规整到合法尺寸:
16
+ 宽高均为 16 的倍数,最大边长 3840px,宽高比不超过 3:1,总像素限制为 655360-8294400。`,hc=[{label:"1:1",value:"1:1"},{label:"3:2",value:"3:2"},{label:"2:3",value:"2:3"},{label:"16:9",value:"16:9"},{label:"9:16",value:"9:16"},{label:"4:3",value:"4:3"},{label:"3:4",value:"3:4"},{label:"21:9",value:"21:9"}];function nm(e){const t=e.match(/^\s*(\d+)\s*[xX×]\s*(\d+)\s*$/);return t?{width:t[1],height:t[2]}:null}function sm(e){const t=Yr(e);for(const r of mc)for(const n of hc)if(Dl(r,n.value)===t)return{tier:r,ratio:n.value};return null}function am({currentSize:e,onSelect:t,onClose:r,allowAuto:n=!0}){Mr(!0);const a=sm(e),o=nm(e),[i,c]=g.useState(()=>!e||e==="auto"?n?"auto":"ratio":a?"ratio":"resolution"),[l,f]=g.useState(a?.tier??"1K"),[m,u]=g.useState(a?.ratio??(n?"1:1":"4:3")),[h,x]=g.useState("16:9"),[y,b]=g.useState(o?.width??"1024"),[d,p]=g.useState(o?.height??"1024"),[w,v]=g.useState(!1),j=g.useRef(null);g.useEffect(()=>()=>{j.current!=null&&window.clearTimeout(j.current)},[]);const P=m==="custom"?h:m,C=_l(h),$=m!=="custom"||!!C,R=!!(m==="custom"&&C&&Math.max(C.width,C.height)/Math.min(C.width,C.height)>3),N=g.useMemo(()=>{if(i==="auto")return"auto";if(i==="ratio"){const U=Dl(l,P);return U?Yr(U):""}if(i==="resolution"){const U=parseInt(y,10),J=parseInt(d,10);return Number.isFinite(U)&&Number.isFinite(J)&&U>0&&J>0?Yr(`${U}x${J}`):""}return""},[i,l,P,y,d]),Q=g.useMemo(()=>{if(!N||N==="auto")return!1;if(i==="ratio"&&m==="custom")return R;if(i==="resolution"){const U=parseInt(y,10),J=parseInt(d,10);if(Number.isFinite(U)&&Number.isFinite(J)&&U>0&&J>0)return`${U}x${J}`!==N}return!1},[i,m,R,y,d,N]),L=()=>v(!0),H=()=>{v(!1),q()},q=()=>{j.current!=null&&(window.clearTimeout(j.current),j.current=null)},F=()=>{j.current=window.setTimeout(()=>{v(!0),j.current=null},450)},Y=()=>{N&&(t(N),r())},A=U=>`rounded-xl border px-3 py-2 text-sm transition ${U?"border-blue-400 bg-blue-50 text-blue-600 dark:border-blue-500/50 dark:bg-blue-500/10 dark:text-blue-300":"border-gray-200/70 bg-white/60 text-gray-600 hover:bg-gray-50 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-300 dark:hover:bg-white/[0.06]"}`;return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[70] flex items-center justify-center p-4",onClick:r,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{className:"relative z-10 w-full max-w-md rounded-3xl border border-white/50 bg-white/95 p-5 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10",onClick:U=>U.stopPropagation(),children:[s.jsxs("div",{className:"mb-5 flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-base font-semibold text-gray-800 dark:text-gray-100",children:"设置图像尺寸"}),s.jsxs("p",{className:"mt-1 text-xs text-gray-400 dark:text-gray-500",children:["当前:",e||"auto"]})]}),s.jsx("button",{onClick:r,className:"rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex rounded-xl bg-gray-100/80 p-1 dark:bg-white/[0.04]",children:[n&&s.jsx("button",{onClick:()=>c("auto"),className:`flex-1 rounded-lg py-1.5 text-sm font-medium transition ${i==="auto"?"bg-white text-gray-800 shadow-sm dark:bg-gray-700 dark:text-gray-100":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`,children:"自动"}),s.jsx("button",{onClick:()=>c("ratio"),className:`flex-1 rounded-lg py-1.5 text-sm font-medium transition ${i==="ratio"?"bg-white text-gray-800 shadow-sm dark:bg-gray-700 dark:text-gray-100":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`,children:"按比例"}),s.jsx("button",{onClick:()=>c("resolution"),className:`flex-1 rounded-lg py-1.5 text-sm font-medium transition ${i==="resolution"?"bg-white text-gray-800 shadow-sm dark:bg-gray-700 dark:text-gray-100":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`,children:"自定义宽高"})]}),s.jsxs("div",{className:"h-[320px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-white/10 pr-1 -mr-1",children:[i==="auto"&&s.jsx("div",{className:"flex h-full animate-fade-in items-center justify-center pt-8 pb-4 text-center",children:s.jsxs("div",{children:[s.jsx("div",{className:"mb-3 inline-flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 text-blue-500 dark:bg-blue-500/10",children:s.jsx("svg",{className:"h-6 w-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),s.jsx("h4",{className:"text-sm font-medium text-gray-800 dark:text-gray-200",children:"自动尺寸"}),s.jsxs("p",{className:"mt-1 text-xs text-gray-400 dark:text-gray-500",children:["不向模型传递具体的分辨率参数",s.jsx("br",{}),"由模型自己决定生成尺寸"]})]})}),i==="ratio"&&s.jsxs("div",{className:"space-y-5 animate-fade-in",children:[s.jsxs("section",{children:[s.jsx("div",{className:"mb-2 text-xs font-medium text-gray-400 dark:text-gray-500",children:"基准分辨率"}),s.jsx("div",{className:"grid grid-cols-3 gap-2",children:mc.map(U=>s.jsx("button",{className:A(l===U),onClick:()=>f(U),children:U},U))})]}),s.jsxs("section",{children:[s.jsx("div",{className:"mb-2 text-xs font-medium text-gray-400 dark:text-gray-500",children:"图像比例"}),s.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[hc.map(U=>s.jsx("button",{className:A(m===U.value),onClick:()=>u(U.value),children:U.label},U.value)),s.jsx("button",{className:`${A(m==="custom")} col-span-4`,onClick:()=>u("custom"),children:"自定义比例"})]})]}),m==="custom"&&s.jsxs("label",{className:"block animate-fade-in",children:[s.jsx("span",{className:"mb-2 block text-xs font-medium text-gray-400 dark:text-gray-500",children:"输入自定义比例"}),s.jsx("input",{value:h,onChange:U=>x(U.target.value),placeholder:"例如 5:4 / 2.39:1",className:`w-full rounded-xl border px-3 py-2 text-sm outline-none transition ${$?"border-gray-200/70 bg-white/60 text-gray-700 focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50":"border-red-300 bg-white/60 text-gray-700 focus:border-red-400 dark:border-red-500/40 dark:bg-white/[0.03] dark:text-gray-200"}`})]})]}),i==="resolution"&&s.jsxs("div",{className:"space-y-5 animate-fade-in",children:[s.jsxs("section",{children:[s.jsx("div",{className:"mb-4 text-xs font-medium text-gray-400 dark:text-gray-500",children:"输入具体像素值"}),s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("label",{className:"flex-1",children:[s.jsx("span",{className:"mb-1.5 block text-xs text-gray-500 dark:text-gray-400",children:"宽度 (Width)"}),s.jsx("input",{type:"number",value:y,onChange:U=>b(U.target.value),className:"w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50",placeholder:"例如 1024"})]}),s.jsx("div",{className:"mt-5 text-gray-300 dark:text-gray-600",children:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),s.jsxs("label",{className:"flex-1",children:[s.jsx("span",{className:"mb-1.5 block text-xs text-gray-500 dark:text-gray-400",children:"高度 (Height)"}),s.jsx("input",{type:"number",value:d,onChange:U=>p(U.target.value),className:"w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50",placeholder:"例如 1024"})]})]})]}),s.jsx("div",{className:"rounded-xl border border-gray-200/80 bg-gray-50/80 p-3 text-xs text-gray-600 dark:border-white/[0.05] dark:bg-white/[0.02] dark:text-gray-400",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("svg",{className:"mt-[2px] h-4 w-4 flex-shrink-0 text-blue-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx("div",{className:"whitespace-pre-line leading-relaxed",children:Mi})]})})]})]}),s.jsxs("div",{className:"rounded-2xl bg-gray-50 px-4 py-3 dark:bg-white/[0.03]",children:[s.jsx("div",{className:"text-xs text-gray-400 dark:text-gray-500",children:"将使用"}),s.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[s.jsx("span",{className:"font-mono text-lg font-semibold text-gray-800 dark:text-gray-100",children:N||"尺寸无效"}),Q&&s.jsxs("div",{className:"relative flex items-center",onMouseEnter:L,onMouseLeave:H,onTouchStart:F,onTouchEnd:q,onTouchCancel:H,onClick:L,children:[s.jsx("svg",{className:"w-5 h-5 text-yellow-500 cursor-pointer",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx(jt,{visible:w,className:"w-56 whitespace-pre-line text-center",children:Mi})]})]})]})]}),s.jsxs("div",{className:"mt-5 flex gap-2",children:[s.jsx("button",{onClick:r,className:"flex-1 rounded-xl bg-gray-100 px-4 py-2.5 text-sm text-gray-600 transition hover:bg-gray-200 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1]",children:"取消"}),s.jsx("button",{onClick:Y,disabled:!N,className:"flex-1 rounded-xl bg-blue-500 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:"确定"})]})]})]})}function Xs(e){return e.textContent?.length??0}function Fa(e){return e.nodeType===Node.TEXT_NODE?e.textContent?.length??0:e instanceof HTMLElement&&e.classList.contains("mention-tag")?Xs(e):Array.from(e.childNodes).reduce((t,r)=>t+Fa(r),0)}function ga(e,t){let r=0,n=!1;const a=o=>{if(!n){if(o===t){n=!0;return}if(o.nodeType===Node.TEXT_NODE){r+=o.textContent?.length??0;return}if(o instanceof HTMLElement&&o.classList.contains("mention-tag")){r+=Xs(o);return}o.childNodes.forEach(a)}};return e.childNodes.forEach(a),r}function om(e,t){const n=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(".mention-tag");return n&&e.contains(n)?n:null}function im(e,t,r){try{const n=document.createRange();return n.selectNodeContents(e),n.setEnd(t,r),n.toString().length}catch{return Xs(e)}}function za(e,t,r,n,a){if(t===e){let c=0;for(const l of Array.from(e.childNodes).slice(0,r))c+=Fa(l);return c}if(!e.contains(t)){const c=e.compareDocumentPosition(t);if(c&Node.DOCUMENT_POSITION_PRECEDING)return 0;if(c&Node.DOCUMENT_POSITION_FOLLOWING)return e.textContent?.length??0;if(t.contains(e)){const f=Array.from(t.childNodes).indexOf(e);return r<=f?0:e.textContent?.length??0}return n==="start"?0:e.textContent?.length??0}const o=om(e,t);if(o){const c=ga(e,o),l=Xs(o);if(!a)return n==="start"?c:c+l;const f=im(o,t,r);return c+(f<l/2?0:l)}if(t.nodeType===Node.TEXT_NODE)return ga(e,t)+r;const i=t.nodeType===Node.ELEMENT_NODE?t:null;if(i){let c=i===e?0:ga(e,i);for(const l of Array.from(i.childNodes).slice(0,r))c+=Fa(l);return c}return e.textContent?.length??0}function Ri(e){const t=window.getSelection();if(!t||t.rangeCount===0)return e.textContent?.length??0;try{const r=t.getRangeAt(0);return e.contains(r.startContainer)?za(e,r.startContainer,r.startOffset,"start",r.collapsed):e.textContent?.length??0}catch{return e.textContent?.length??0}}function Rn(e){const t=window.getSelection();if(!t||t.rangeCount===0){const r=e.textContent?.length??0;return{start:r,end:r}}try{const r=t.getRangeAt(0),n=za(e,r.startContainer,r.startOffset,"start",r.collapsed),a=r.collapsed?n:za(e,r.endContainer,r.endOffset,"end",!1);return{start:n,end:a}}catch{const r=e.textContent?.length??0;return{start:r,end:r}}}function lm(e){let t="";const r=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.textContent??"";return}if(n instanceof HTMLElement&&n.classList.contains("mention-tag")){t+=n.dataset.mentionText??n.textContent??"";return}n.childNodes.forEach(r)};return e.childNodes.forEach(r),t.replace(/\r\n?/g,`
17
+ `)}function tn(e){const t=e.querySelectorAll(".mention-tag"),r=window.getSelection();if(!r||r.rangeCount===0){t.forEach(a=>a.classList.remove("selected"));return}const n=r.getRangeAt(0);if(n.collapsed){t.forEach(a=>a.classList.remove("selected"));return}t.forEach(a=>{let o=!1;try{o=n.intersectsNode(a)}catch{o=!1}a.classList.toggle("selected",o)})}function pa(e,t){const r=window.getSelection();if(!r)return;const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let a=t,o=null;for(;n.nextNode();){o=n.currentNode;const i=o.parentElement?.closest(".mention-tag");if(i){if(a<=o.length){const c=document.createRange();a<o.length/2?c.setStartBefore(i):c.setStartAfter(i),c.collapse(!0),r.removeAllRanges(),r.addRange(c);return}a-=o.length;continue}if(a<=o.length){const c=document.createRange();c.setStart(o,a),c.collapse(!0),r.removeAllRanges(),r.addRange(c);return}a-=o.length}if(o){const i=document.createRange();i.setStart(o,o.length),i.collapse(!0),r.removeAllRanges(),r.addRange(i)}}function Kt({visible:e,text:t}){return e?s.jsx(jt,{visible:!0,className:"z-10 whitespace-nowrap",children:t}):null}const Yt=16;function cm(){const[e,t]=g.useState(window.innerWidth<640);return g.useEffect(()=>{const r=()=>t(window.innerWidth<640);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function dm(){const e=E(I=>I.prompt),t=E(I=>I.setPrompt),r=E(I=>I.inputImages),n=E(I=>I.removeInputImage),a=E(I=>I.clearInputImages),o=E(I=>I.params),i=E(I=>I.setParams),c=E(I=>I.settings),l=E(I=>I.reusedTaskApiProfileId),f=E(I=>I.setShowSettings),m=E(I=>I.setLightboxImageId),u=E(I=>I.showToast),h=E(I=>I.setConfirmDialog),x=E(I=>I.selectedTaskIds),y=E(I=>I.setSelectedTaskIds),b=E(I=>I.clearSelection),d=E(I=>I.tasks),p=E(I=>I.filterStatus),w=E(I=>I.filterFavorite),v=E(I=>I.searchQuery),j=g.useMemo(()=>{const I=[...d].sort((G,ae)=>ae.createdAt-G.createdAt),_=v.trim().toLowerCase();return I.filter(G=>{if(w&&!G.isFavorite||!(p==="all"||G.status===p))return!1;if(!_)return!0;const ce=(G.prompt||"").toLowerCase(),pe=JSON.stringify(G.params).toLowerCase();return ce.includes(_)||pe.includes(_)})},[d,v,p,w]),P=g.useCallback(()=>{x.length===j.length&&j.length>0?b():y(j.map(I=>I.id))},[x.length,j,b,y]),C=g.useCallback(()=>{const I=d.filter(ae=>x.includes(ae.id)),G=!(I.length>0&&I.every(ae=>ae.isFavorite));h({title:G?"批量收藏":"批量取消收藏",message:G?`确定要收藏选中的 ${x.length} 条记录吗?`:`确定要取消收藏选中的 ${x.length} 条记录吗?`,confirmText:G?"确认收藏":"确认取消",action:()=>{x.forEach(ae=>{wt(ae,{isFavorite:G})}),b()}})},[d,x,b,h]),$=g.useCallback(()=>{h({title:"批量删除",message:`确定要删除选中的 ${x.length} 条记录吗?`,action:()=>{If(x)}})},[x,h]),R=g.useCallback(async()=>{const _=d.filter(ce=>x.includes(ce.id)).flatMap(ce=>ce.outputImages||[]);if(_.length===0){u("选中的记录没有图片","info");return}u(`开始下载 ${_.length} 张图片...`,"info");let G=0,ae=0;for(const ce of _)try{let pe=pn(ce);if(pe||(pe=await Ot(ce)),!pe){ae++;continue}const _r=await(await fetch(pe)).blob(),hs=URL.createObjectURL(_r),Lr=document.createElement("a");Lr.href=hs;const ta=_r.type.split("/")[1]||"png";Lr.download=`image-${Date.now()}-${G}.${ta}`,document.body.appendChild(Lr),Lr.click(),document.body.removeChild(Lr),URL.revokeObjectURL(hs),G++,await new Promise(ra=>setTimeout(ra,100))}catch(pe){console.error(pe),ae++}ae>0?u(`下载完成: 成功 ${G},失败 ${ae}`,"info"):u(`成功下载 ${G} 张图片`,"success"),b()},[d,x,u,b]),N=E(I=>I.maskDraft);E(I=>I.clearMaskDraft);const Q=E(I=>I.setMaskEditorImageId),L=E(I=>I.moveInputImage),H=g.useRef(null),q=g.useRef(null),F=g.useRef(null),Y=g.useRef(null),A=g.useRef(42),[U,J]=g.useState(!1),[D,W]=g.useState(!1),[K,O]=g.useState(!1),[z,T]=g.useState(!1),[V,Z]=g.useState(!1),[ee,oe]=g.useState(!1),[ye,fe]=g.useState(!1),[be,xe]=g.useState(null),[ke,ne]=g.useState(!1),[ve,_e]=g.useState(!1),[ft,je]=g.useState(""),[Oe,Ke]=g.useState(null),[It,rt]=g.useState(null),[vt,Ye]=g.useState(0),[ze,Ie]=g.useState(!1),[Ce,Le]=g.useState(null),He=g.useRef(null),Te=g.useRef({startY:0,moved:!1}),Ve=g.useRef(null),Je=g.useRef({index:null,startX:0,startY:0,moved:!1}),mt=g.useRef(null),nt=g.useRef(null),ht=g.useRef(!1),at=g.useRef(!1),Xe=g.useRef(!1),tt=g.useRef(null),[gt,S]=g.useState(0),[he,Pe]=g.useState(0),ge=g.useRef(!1),Me=g.useRef(null),ot=g.useRef(null),Pt=g.useRef(null),_t=g.useRef(null),sr=g.useRef(null),it=g.useRef(null),[Bt,St]=g.useState(o.output_compression==null?"":String(o.output_compression)),[lt,ar]=g.useState(String(o.n)),[hr,gr]=g.useState(!1),[qe,M]=g.useState(!1),X=g.useRef(0),te=cm(),ie=g.useMemo(()=>et(c),[c]),me=g.useMemo(()=>c.reuseTaskApiProfileTemporarily&&l?c.profiles.find(I=>I.id===l)??ie:ie,[ie,l,c]),de=g.useMemo(()=>me.id===ie.id?c:ue({...c,activeProfileId:me.id}),[me.id,ie.id,c]),Se=!!me.apiKey,We=!!(e.trim()&&Se),De=me.provider==="fal",ct=me.apiMode==="responses"||De,dt=o.output_format==="png"||De,Nt=Ul(de),Wt=De&&r.length===0,pt=De?`fal.ai 最大请求数量为 ${Nt}`:`OpenAI 最大请求数量为 ${Nt}`,xt=Wt&&o.size==="auto"?Ta:Yr(o.size)||Xt.size,Rr=De?[{label:"low",value:"low"},{label:"medium",value:"medium"},{label:"high",value:"high"}]:[{label:"auto",value:"auto"},{label:"low",value:"low"},{label:"medium",value:"medium"},{label:"high",value:"high"}],Re=r.length>=Yt,Ge=N?r.find(I=>I.id===N.targetImageId)??null:null,ns=Ge?r.filter(I=>I.id!==Ge.id):r,ss=gt,Js=vr(e),as=cd(e,ss)?null:_o(Js,ss,r),ir=as?r.map((I,_)=>({img:I,index:_})).filter(({index:I})=>dd(as.query,I)):[],os=!ze&&ir.length>0,is=g.useCallback(I=>{const _=q.current,G=_?Ri(_):e.length,ae=_o(vr(e),G,r);if(Ie(!0),Ye(0),!ae)return;const ce=Lo(e,ae.start,G,I);at.current=!1,t(ce.prompt),window.setTimeout(()=>{q.current&&(q.current.focus(),pa(q.current,ce.cursor))},0)},[r,e,t]),bn=g.useCallback(I=>{const _=q.current,G=_?Rn(_):{start:e.length,end:e.length},ae=nn(e,G.start),ce=nn(e,G.end),pe=`${e.slice(0,ae)}${I}${e.slice(ce)}`,ut=G.start+I.length;t(pe),window.setTimeout(()=>{q.current&&(q.current.focus(),pa(q.current,ut))},0)},[e,t]);g.useEffect(()=>{St(o.output_compression==null?"":String(o.output_compression))},[o.output_compression]),g.useEffect(()=>{ar(String(o.n))},[o.n]),g.useEffect(()=>{const I=Ws(o,de,{hasInputImages:r.length>0}),_=Ol(o,I);Object.keys(_).length&&i(_)},[r.length,o,de,i]),g.useEffect(()=>()=>{Me.current!=null&&window.clearTimeout(Me.current),ot.current!=null&&window.clearTimeout(ot.current),_t.current!=null&&window.clearTimeout(_t.current),Pt.current!=null&&window.clearTimeout(Pt.current),sr.current!=null&&window.clearTimeout(sr.current),tt.current?.(),it.current!=null&&window.clearTimeout(it.current)},[]),g.useEffect(()=>{let I=!1;if(!N||!Ge){je("");return}return ao(Ge.dataUrl,N.maskDataUrl).then(_=>{I||je(_)}).catch(()=>{I||je("")}),()=>{I=!0}},[N,Ge?.id,Ge?.dataUrl]);const Gs=g.useCallback(()=>{if(Bt.trim()===""){St(""),i({output_compression:null});return}const I=Number(Bt);if(Number.isNaN(I)){St(o.output_compression==null?"":String(o.output_compression));return}St(String(I)),i({output_compression:I})},[Bt,o.output_compression,i]),Qs=g.useCallback(()=>{M(!1),it.current!=null&&(window.clearTimeout(it.current),it.current=null);const I=Number(lt),_=lt.trim()===""?Xt.n:Number.isNaN(I)?o.n:I,G=Math.min(Nt,Math.max(1,_));ar(String(G)),i({n:G})},[lt,Nt,o.n,i]),Gr=g.useCallback(()=>{M(!0),it.current!=null&&window.clearTimeout(it.current),it.current=window.setTimeout(()=>{M(!1),it.current=null},2e3)},[]),ls=g.useCallback(()=>{M(!1),it.current!=null&&(window.clearTimeout(it.current),it.current=null)},[]),Zs=g.useCallback(I=>{ar(I);const _=Number(I);!Number.isNaN(_)&&_>Nt?Gr():ls()},[ls,Nt,Gr]),cs=g.useCallback(I=>{const _=Number(lt),G=Number.isNaN(_)?o.n:_;!hr||G<Nt||(I(),Gr())},[lt,hr,Nt,o.n,Gr]),ds=()=>{ct&&Z(!0)},k=()=>{Z(!1),B()},B=()=>{ot.current!=null&&(window.clearTimeout(ot.current),ot.current=null)},re=()=>{ct&&(ot.current=window.setTimeout(()=>{Z(!0),ot.current=null},450))},se=()=>T(!0),le=()=>{T(!1),we()},we=()=>{Me.current!=null&&(window.clearTimeout(Me.current),Me.current=null)},Be=()=>{Me.current=window.setTimeout(()=>{T(!0),Me.current=null},450)},Qe=()=>{(c.codexCli||De)&&fe(!0)},Ue=()=>{Wt&&oe(!0)},Ze=()=>{oe(!1),bt()},bt=()=>{Pt.current!=null&&(window.clearTimeout(Pt.current),Pt.current=null)},bc=()=>{Wt&&(Pt.current=window.setTimeout(()=>{oe(!0),Pt.current=null},450))},vo=()=>{fe(!1),ko()},ko=()=>{_t.current!=null&&(window.clearTimeout(_t.current),_t.current=null)},yc=()=>{!c.codexCli&&!De||(_t.current=window.setTimeout(()=>{fe(!0),_t.current=null},450))},yn=()=>{sr.current!=null&&(window.clearTimeout(sr.current),sr.current=null)},wc=I=>xe(I),us=()=>{Xe.current||(xe(null),yn())},jo=()=>{Xe.current=!1,tt.current?.(),tt.current=null,xe(null),yn()},Io=I=>{if(Xe.current){xe(I);return}Xe.current=!0,xe(I);const _=()=>{window.removeEventListener("mouseup",_),window.removeEventListener("pointerup",_),window.removeEventListener("dragend",_),tt.current===_&&(tt.current=null,Xe.current=!1,xe(null),yn())};tt.current=_,window.addEventListener("mouseup",_),window.addEventListener("pointerup",_),window.addEventListener("dragend",_)},Po=async I=>{try{const _=E.getState().inputImages.length;if(_>=Yt){E.getState().showToast(`参考图数量已达上限(${Yt} 张),无法继续添加`,"error");return}const G=Yt-_,ae=Array.from(I).filter(ut=>ut.type.startsWith("image/")),ce=ae.slice(0,G),pe=ae.length-ce.length;for(const ut of ce)await Mf(ut);pe>0&&E.getState().showToast(`已达上限 ${Yt} 张,${pe} 张图片被丢弃`,"error")}catch(_){E.getState().showToast(`图片添加失败:${_ instanceof Error?_.message:String(_)}`,"error")}},fs=g.useRef(Po);fs.current=Po;const vc=async I=>{await fs.current(I.target.files||[]),I.target.value=""},kc=I=>{if(os){if(I.key==="ArrowDown"){I.preventDefault(),Ye(_=>(_+1)%ir.length);return}if(I.key==="ArrowUp"){I.preventDefault(),Ye(_=>(_-1+ir.length)%ir.length);return}if(I.key==="Enter"&&!I.shiftKey||I.key==="Tab"){I.preventDefault(),is(ir[vt]?.index??ir[0].index);return}if(I.key==="Escape"){I.preventDefault(),Ye(0),q.current?.blur();return}}if(I.key==="Enter"){I.preventDefault();const _=I.ctrlKey||I.metaKey;c.enterSubmit?I.shiftKey?bn(`
18
+ `):_||We&&Br():_?We&&Br():bn(`
19
+ `);return}},jc=I=>{const _=I.clipboardData.getData("text/plain");_&&(Array.from(I.clipboardData.items).some(G=>G.type.startsWith("image/"))||(I.preventDefault(),bn(_.replace(/\r\n?/g,`
20
+ `))))},Ic=I=>{const _=q.current;if(!_)return;const G=Rn(_);if(G.start===G.end)return;const ae=nn(e,G.start),ce=nn(e,G.end),pe=vr(e.slice(ae,ce)),ut=/^\s*@图\d+\s*$/.test(pe)?pe.trim():pe;I.preventDefault(),I.clipboardData.setData("text/plain",ut)};g.useEffect(()=>{const I=_=>{const G=_.clipboardData?.items;if(!G)return;const ae=[];for(const ce of Array.from(G))if(ce.type.startsWith("image/")){const pe=ce.getAsFile();pe&&ae.push(pe)}ae.length>0&&(_.preventDefault(),fs.current(ae))};return document.addEventListener("paste",I),()=>document.removeEventListener("paste",I)},[]),g.useEffect(()=>{const I=ce=>{ce.preventDefault(),ce.stopPropagation(),X.current++,ce.dataTransfer?.types.includes("Files")&&J(!0)},_=ce=>{ce.preventDefault(),ce.stopPropagation()},G=ce=>{ce.preventDefault(),ce.stopPropagation(),X.current--,X.current===0&&J(!1)},ae=ce=>{ce.preventDefault(),ce.stopPropagation(),X.current=0,J(!1);const pe=ce.dataTransfer?.files;pe&&pe.length>0&&fs.current(pe)};return document.addEventListener("dragenter",I),document.addEventListener("dragover",_),document.addEventListener("dragleave",G),document.addEventListener("drop",ae),()=>{document.removeEventListener("dragenter",I),document.removeEventListener("dragover",_),document.removeEventListener("dragleave",G),document.removeEventListener("drop",ae)}},[]);const Ar=g.useCallback(()=>{const I=q.current;if(!I)return;const G=(Y.current?.offsetHeight??0)+140,ae=Math.max(window.innerHeight*.4-G,80);I.style.transition="none",I.style.height="0",I.style.overflowY="hidden";const ce=I.scrollHeight,ut=Math.max(ce,42),_r=ut>ae?ae:ut;I.style.height=A.current+"px",I.offsetHeight,I.style.transition="height 150ms ease, border-color 200ms, box-shadow 200ms",I.style.height=_r+"px",I.style.overflowY=ut>ae?"auto":"hidden",A.current=_r},[]);g.useEffect(()=>{const I=q.current;if(!I)return;if(at.current){at.current=!1;return}const _=ud(e,r),G=e?_.map(ae=>ae.type==="mention"?`<span contenteditable="false" class="mention-tag" data-mention-text="${Wa(ae.imageIndex)}">${ae.text}</span>`:ae.text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")).join(""):"";I.innerHTML!==G&&(I.innerHTML=G)},[e,r]),g.useEffect(()=>{Ar()},[e,r,Ar]),g.useEffect(()=>{const I=()=>{const _=q.current;if(!_)return;const G=window.getSelection();if(!G||G.rangeCount===0)return;const ae=G.getRangeAt(0);try{if(!ae.intersectsNode(_)){tn(_);return}}catch{return}const ce=Rn(_);S(ce.start),tn(_);const pe=ae.getBoundingClientRect(),ut=_.getBoundingClientRect();pe.width===0&&pe.height===0||Pe(pe.left-ut.left)};return document.addEventListener("selectionchange",I),()=>document.removeEventListener("selectionchange",I)},[]),g.useEffect(()=>{Ar()},[r.length,!!N,ft,Ar]),g.useEffect(()=>(window.addEventListener("resize",Ar),()=>window.removeEventListener("resize",Ar)),[Ar]),g.useEffect(()=>{const I=He.current;if(!I)return;const _=ce=>{Te.current={startY:ce.touches[0].clientY,moved:!1}},G=ce=>{const pe=ce.touches[0].clientY-Te.current.startY;Math.abs(pe)>10&&(Te.current.moved=!0),pe>30&&ne(!0),pe<-30&&ne(!1)},ae=()=>{Te.current.moved||ne(ce=>!ce)};return I.addEventListener("touchstart",_,{passive:!0}),I.addEventListener("touchmove",G,{passive:!0}),I.addEventListener("touchend",ae),()=>{I.removeEventListener("touchstart",_),I.removeEventListener("touchmove",G),I.removeEventListener("touchend",ae)}},[]);const ea="px-3 py-1.5 rounded-xl border border-gray-200/60 dark:border-white/[0.08] bg-white/50 dark:bg-white/[0.03] hover:bg-white dark:hover:bg-white/[0.06] text-xs transition-all duration-200 shadow-sm",Pc=I=>{const _=document.elementFromPoint(I.clientX,I.clientY)?.closest("[data-input-image-index]");if(!_)return null;const G=Number(_.dataset.inputImageIndex);if(!Number.isInteger(G))return null;const ae=ha(_);return ae?I.clientX<ae.left+ae.width/2?G:G+1:null},Sc=I=>Math.max(Ge?1:0,Math.min(r.length,I)),Nc=I=>{if(!Ge)return!1;const _=document.querySelector('[data-input-image-index="0"]');if(!_)return!1;const G=ha(_);return G?I<G.left+G.width/2:!1},ms=()=>{Ke(null),rt(null),Ve.current=null,mt.current=null,Je.current={index:null,startX:0,startY:0,moved:!1},Le(null),nt.current?.remove(),nt.current=null,us()};g.useEffect(()=>{if(!Ce)return;const I=document.body.style.overflow,_=document.body.style.overscrollBehavior;return document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",()=>{document.body.style.overflow=I,document.body.style.overscrollBehavior=_}},[Ce]);const Tc=I=>{const _=I.dataTransfer.getData("text/plain"),G=Number(_);return Number.isInteger(G)?G:null},So=(I,_)=>{const G=Ve.current;if(G!==null&&Ge&&(I===0||_!=null&&Nc(_))){wc(Ge.id),mt.current=null,rt(null);return}G!==null&&us();const ae=I==null?null:Sc(I),pe=G!==null&&ae!==null&&(ae===G||ae===G+1)?null:ae;mt.current=pe,rt(pe)},Ec=(I,_)=>{const G=N?.targetImageId===I.id,ae=!Ge||G,ce=G?"遮罩图必须为第一张图":"",pe=G&&ft?ft:I.dataUrl,ut=Oe===_,_r=_===r.length-1,hs=It===_&&Oe!==_,Lr=It===r.length&&_r&&Oe!==_,ta=Ne=>{if(G){Io(I.id),Ne.preventDefault();return}us(),Ve.current=_,Ke(_),Ne.dataTransfer.effectAllowed="move",Ne.dataTransfer.setData("text/plain",String(_));const Ee=document.createElement("div");Ee.style.cssText="position:fixed;left:-1000px;top:-1000px;width:52px;height:52px;border-radius:12px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.25);";const $e=document.createElement("img");$e.src=pe,$e.style.cssText="width:52px;height:52px;object-fit:cover;display:block;",Ee.appendChild($e),document.body.appendChild(Ee),nt.current=Ee,Ne.dataTransfer.setDragImage(Ee,26,26)},ra=Ne=>{Ne.preventDefault(),Ne.dataTransfer.dropEffect="move";const Ee=Ve.current;if(Ee===null||Ee===_)return;const $e=ha(Ne.currentTarget);$e&&So(Ne.clientX<$e.left+$e.width/2?_:_+1,Ne.clientX)},Mc=Ne=>{Ne.preventDefault();const Ee=Ve.current??Tc(Ne),$e=mt.current;Ee!==null&&$e!==null&&L(Ee,$e),ms()},Rc=Ne=>{if(G){const $e=Ne.touches[0];Je.current={index:_,startX:$e.clientX,startY:$e.clientY,moved:!1};return}const Ee=Ne.touches[0];Ve.current=_,Je.current={index:_,startX:Ee.clientX,startY:Ee.clientY,moved:!1},Le(null)},Ac=Ne=>{const Ee=Ne.touches[0],$e=Je.current;if($e.index===null)return;if(G){(Math.abs(Ee.clientX-$e.startX)>6||Math.abs(Ee.clientY-$e.startY)>6)&&(Ne.preventDefault(),Io(I.id));return}$e.moved=!0,yn(),xe(null),ht.current=!0,Ne.preventDefault(),Ke($e.index),Le({src:pe,x:Ee.clientX,y:Ee.clientY});const gs=Pc(Ee);So(gs,Ee.clientX)},_c=Ne=>{const Ee=Je.current;yn(),Ee.index!==null&&mt.current!==null&&(Ne.preventDefault(),L(Ee.index,mt.current),window.setTimeout(()=>{ht.current=!1},0)),ms(),jo()},Lc=()=>{ht.current=!1,jo(),ms()};return s.jsxs("div",{"data-input-image-index":_,className:`relative group inline-block h-[52px] w-[52px] shrink-0 self-start transition-opacity ${ut?"opacity-40":""}`,style:{touchAction:G?"auto":"none"},draggable:!te,onMouseLeave:us,onDragStart:ta,onDragOver:ra,onDrop:Mc,onDragEnd:ms,onTouchStart:Rc,onTouchMove:Ac,onTouchEnd:_c,onTouchCancel:Lc,onContextMenu:Ne=>{Ne.preventDefault();const Ee=q.current,$e=Ee?Ri(Ee):e.length,gs=Lo(e,$e,$e,_);at.current=!1,t(gs.prompt),window.setTimeout(()=>{q.current&&(q.current.focus(),pa(q.current,gs.cursor))},0)},children:[s.jsx(Kt,{visible:be===I.id&&!!ce&&(!te||G),text:ce}),hs&&s.jsx("div",{className:"absolute -left-[5px] top-0 bottom-0 w-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),Lr&&s.jsx("div",{className:"absolute -right-[5px] top-0 bottom-0 w-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),s.jsxs("div",{className:`relative w-[52px] h-[52px] rounded-xl overflow-hidden shadow-sm cursor-grab active:cursor-grabbing select-none ${G?"border-2 border-blue-500":"border border-gray-200 dark:border-white/[0.08]"}`,onClick:()=>{if(!ht.current){if(G){Q(I.id);return}Ge&&!ge.current&&(ge.current=!0,u("只能有一张遮罩图","info")),m(I.id,r.map(Ne=>Ne.id))}},children:[pe&&s.jsx("div",{className:"h-full w-full overflow-hidden rounded-xl",children:s.jsx("img",{src:pe,className:"w-full h-full object-cover hover:opacity-90 transition-opacity pointer-events-none",alt:""})}),G&&s.jsx("span",{className:"absolute left-1 top-1 rounded bg-blue-500/90 px-1.5 py-0.5 text-[8px] leading-none text-white font-bold tracking-wider backdrop-blur-sm z-10 pointer-events-none",children:"MASK"}),s.jsx("span",{className:"absolute bottom-1 left-1 flex h-4 w-4 items-center justify-center rounded-full bg-black/55 text-[9px] font-semibold text-white backdrop-blur-sm z-10 pointer-events-none",children:_+1}),ae&&s.jsx("button",{className:"absolute inset-0 w-full h-full bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer z-20 focus:outline-none border-none",onClick:Ne=>{Ne.stopPropagation(),Q(I.id)},title:G?"编辑遮罩":"添加遮罩",children:s.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"})})})]}),!G&&s.jsx("span",{className:"absolute right-0 top-0 flex h-5 w-5 translate-x-1/2 -translate-y-1/2 cursor-pointer items-center justify-center rounded-full bg-red-500 text-white opacity-0 shadow-md transition-opacity hover:bg-red-600 group-hover:opacity-100 z-30",onClick:Ne=>{Ne.stopPropagation(),n(_)},children:s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M6 18L18 6M6 6l12 12"})})})]},I.id)},Cc=()=>s.jsxs("button",{onClick:()=>h({title:Ge?"清空全部输入图":"清空参考图",message:Ge?`确定要清空遮罩主图、${ns.length} 张参考图和当前遮罩吗?`:`确定要清空全部 ${r.length} 张参考图吗?`,action:()=>a()}),className:"w-[52px] h-[52px] rounded-xl border border-dashed border-gray-300 dark:border-white/[0.08] flex flex-col items-center justify-center gap-0.5 text-gray-400 dark:text-gray-500 hover:text-red-500 hover:border-red-300 hover:bg-red-50/50 dark:hover:bg-red-950/30 transition-all cursor-pointer flex-shrink-0",title:Ge?"清空遮罩主图、参考图和遮罩":"清空全部参考图",children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),s.jsx("span",{className:"text-[8px] leading-none",children:Ge?"清空全部":"清空"})]}),No=()=>s.jsxs("div",{ref:Y,children:[s.jsxs("div",{className:"grid grid-cols-[repeat(auto-fill,52px)] justify-between gap-x-2 gap-y-3 mb-3",children:[r.map((I,_)=>Ec(I,_)),Cc()]}),Ce?.src&&fr.createPortal(s.jsx("div",{className:"fixed z-[140] h-[52px] w-[52px] overflow-hidden rounded-xl shadow-xl pointer-events-none opacity-90",style:{left:Ce.x,top:Ce.y,transform:"translate(-50%, -50%)"},children:s.jsx("img",{src:Ce.src,className:"h-full w-full object-cover",alt:""})}),document.body)]}),To=I=>s.jsxs("div",{className:`grid ${I} gap-2 text-xs flex-1`,children:[s.jsxs("label",{className:"relative flex flex-col gap-0.5",onMouseEnter:Ue,onMouseLeave:Ze,onTouchStart:bc,onTouchEnd:bt,onTouchCancel:Ze,onClick:Ue,children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500 ml-1",children:"尺寸"}),s.jsx("button",{type:"button",onClick:()=>{Ht(),_e(!0)},className:"px-3 py-1.5 rounded-xl border border-gray-200/60 dark:border-white/[0.08] bg-white/50 dark:bg-white/[0.03] hover:bg-white dark:hover:bg-white/[0.06] focus:outline-none text-xs text-left transition-all duration-200 shadow-sm font-mono",title:"选择尺寸",children:xt}),s.jsx(Kt,{visible:Wt&&ee,text:s.jsxs(s.Fragment,{children:["fal.ai 的文生图模式不支持 ",s.jsx("code",{className:"rounded bg-white/10 px-1 py-0.5 font-mono",children:"auto"})," 参数"]})})]}),s.jsxs("label",{className:"relative flex flex-col gap-0.5",onMouseEnter:Qe,onMouseLeave:vo,onTouchStart:yc,onTouchEnd:ko,onTouchCancel:vo,onClick:Qe,children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500 ml-1",children:"质量"}),s.jsx(zr,{value:c.codexCli?"auto":De&&o.quality==="auto"?"high":o.quality,onChange:_=>{c.codexCli||i({quality:_})},options:Rr,disabled:c.codexCli,className:c.codexCli?"px-3 py-1.5 rounded-xl border border-gray-200/60 dark:border-white/[0.08] bg-gray-100/50 dark:bg-white/[0.05] opacity-50 cursor-not-allowed text-xs transition-all duration-200 shadow-sm":ea}),s.jsx(Kt,{visible:(c.codexCli||De)&&ye,text:De?s.jsxs(s.Fragment,{children:["fal.ai 不支持 ",s.jsx("code",{className:"rounded bg-white/10 px-1 py-0.5 font-mono",children:"auto"})," 质量参数"]}):"Codex CLI 不支持质量参数"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500 ml-1",children:"格式"}),s.jsx(zr,{value:o.output_format,onChange:_=>i({output_format:_}),options:[{label:"PNG",value:"png"},{label:"JPEG",value:"jpeg"},{label:"WebP",value:"webp"}],className:ea})]}),s.jsxs("label",{className:"relative flex flex-col gap-0.5",onMouseEnter:se,onMouseLeave:le,onTouchStart:Be,onTouchEnd:we,onTouchCancel:le,onClick:se,children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500 ml-1",children:"压缩率"}),s.jsx("input",{value:Bt,onChange:_=>St(_.target.value),onBlur:Gs,disabled:dt,type:"number",min:0,max:100,placeholder:"0-100",className:`px-3 py-1.5 rounded-xl border border-gray-200/60 dark:border-white/[0.08] focus:outline-none text-xs transition-all duration-200 shadow-sm ${dt?"bg-gray-100/50 dark:bg-white/[0.05] opacity-50 cursor-not-allowed":"bg-white/50 dark:bg-white/[0.03]"}`}),s.jsx(Kt,{visible:z,text:De?"fal.ai 不支持压缩率参数":"仅 JPEG 和 WebP 支持压缩率"})]}),s.jsxs("label",{className:"relative flex flex-col gap-0.5",onMouseEnter:ds,onMouseLeave:k,onTouchStart:re,onTouchEnd:B,onTouchCancel:k,onClick:ds,children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500 ml-1",children:"审核"}),s.jsx(zr,{value:ct?"auto":o.moderation,onChange:_=>{ct||i({moderation:_})},options:[{label:"auto",value:"auto"},{label:"low",value:"low"}],disabled:ct,className:ct?"px-3 py-1.5 rounded-xl border border-gray-200/60 dark:border-white/[0.08] bg-gray-100/50 dark:bg-white/[0.05] opacity-50 cursor-not-allowed text-xs transition-all duration-200 shadow-sm":ea}),s.jsx(Kt,{visible:ct&&V,text:De?"fal.ai 不支持审核参数":"Responses API 不支持审核参数"})]}),s.jsxs("label",{className:"relative flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500 ml-1",children:"数量"}),s.jsx("input",{value:lt,onChange:_=>Zs(_.target.value),onFocus:()=>gr(!0),onBlur:()=>{gr(!1),Qs()},onKeyDown:_=>{_.key==="ArrowUp"&&cs(()=>_.preventDefault())},onWheel:_=>{_.deltaY<0&&cs(()=>_.preventDefault())},type:"number",min:1,max:Nt,className:"px-3 py-1.5 rounded-xl border border-gray-200/60 dark:border-white/[0.08] bg-white/50 dark:bg-white/[0.03] focus:outline-none text-xs transition-all duration-200 shadow-sm"}),s.jsx(Kt,{visible:qe,text:pt})]})]});return s.jsxs(s.Fragment,{children:[U&&s.jsx("div",{className:"fixed inset-0 z-[100] bg-white/60 dark:bg-gray-900/60 backdrop-blur-md flex flex-col items-center justify-center pointer-events-none",children:s.jsxs("div",{className:"flex flex-col items-center gap-4 p-8 rounded-3xl",children:[s.jsx("div",{className:`w-20 h-20 rounded-full border-2 border-dashed flex items-center justify-center ${Re?"bg-red-50 dark:bg-red-500/10 border-red-300":"bg-blue-50 dark:bg-blue-500/10 border-blue-400"}`,children:Re?s.jsx("svg",{className:"w-10 h-10 text-red-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"})}):s.jsx("svg",{className:"w-10 h-10 text-blue-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),s.jsx("div",{className:"text-center",children:Re?s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"text-lg font-semibold text-red-500",children:["已达上限 ",Yt," 张"]}),s.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"请先移除部分参考图后再添加"})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-lg font-semibold text-gray-700 dark:text-gray-200",children:"释放以添加参考图"}),s.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"支持 JPG、PNG、WebP 等格式"})]})})]})}),ve&&s.jsx(am,{currentSize:Wt&&o.size==="auto"?Ta:o.size,onSelect:I=>i({size:I}),onClose:()=>_e(!1),allowAuto:!Wt}),s.jsxs("div",{"data-input-bar":!0,className:"fixed bottom-4 sm:bottom-6 left-1/2 -translate-x-1/2 z-30 w-full max-w-4xl px-3 sm:px-4 transition-all duration-300",children:[x.length>0&&s.jsx("div",{className:"flex justify-center mb-3",children:s.jsxs("div",{className:"bg-white/90 dark:bg-gray-800/90 backdrop-blur shadow-[0_8px_30px_rgb(0,0,0,0.12)] dark:shadow-lg rounded-full flex items-center p-1 border border-gray-200/50 dark:border-white/10 pointer-events-auto",children:[s.jsx("button",{onClick:b,className:"p-2 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors",title:"取消选择",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx("button",{onClick:P,className:"p-2 text-blue-500 dark:text-blue-400 hover:text-blue-600 dark:hover:text-blue-300 transition-colors",title:x.length===j.length&&j.length>0?"取消全选":"全选当前可见",children:x.length===j.length&&j.length>0?s.jsxs("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]}):s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:s.jsx("path",{strokeDasharray:"4 4",d:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2z"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx("button",{onClick:C,className:"p-2 text-yellow-500 dark:text-yellow-400 hover:text-yellow-600 dark:hover:text-yellow-300 transition-colors",title:"收藏/取消收藏",children:x.length>0&&x.every(I=>d.find(_=>_.id===I)?.isFavorite)?s.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})}):s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:s.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx("button",{onClick:R,className:"p-2 text-green-500 dark:text-green-400 hover:text-green-600 dark:hover:text-green-300 transition-colors",title:"批量下载",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx("button",{onClick:$,className:"p-2 text-red-500 dark:text-red-400 hover:text-red-600 dark:hover:text-red-300 transition-colors",title:"删除选中",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]})}),s.jsxs("div",{ref:F,className:"bg-white/70 dark:bg-gray-900/70 backdrop-blur-2xl border border-white/50 dark:border-white/[0.08] shadow-[0_8px_30px_rgb(0,0,0,0.08)] dark:shadow-[0_8px_30px_rgb(0,0,0,0.3)] rounded-2xl sm:rounded-3xl p-3 sm:p-4 ring-1 ring-black/5 dark:ring-white/10",children:[s.jsx("div",{ref:He,className:"sm:hidden flex justify-center pt-0.5 pb-2 -mt-1 cursor-pointer touch-none",onClick:()=>ne(I=>!I),children:s.jsx("div",{className:`w-10 h-1 rounded-full bg-gray-300 dark:bg-white/[0.06] transition-transform duration-200 ${ke?"scale-x-75":""}`})}),r.length>0&&(te?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`collapse-section${ke?" collapsed":""}`,children:s.jsx("div",{className:"collapse-inner",children:No()})}),ke&&s.jsx("div",{className:"text-xs text-gray-400 dark:text-gray-500 mb-2 ml-1",children:N?`1 张遮罩主图 · ${ns.length} 张参考图`:`${r.length} 张参考图`})]}):No()),s.jsxs("div",{className:"relative",children:[os&&s.jsxs("div",{style:{left:`${he}px`},className:"absolute bottom-full z-50 mb-2 w-64 overflow-hidden rounded-2xl border border-gray-200/70 bg-white/95 p-1.5 shadow-xl ring-1 ring-black/5 backdrop-blur-xl dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10",children:[s.jsx("div",{className:"px-2 pb-1 pt-0.5 text-[11px] text-gray-400 dark:text-gray-500",children:"选择当前参考图"}),s.jsx("div",{className:"max-h-56 overflow-y-auto custom-scrollbar",children:ir.map(({img:I,index:_},G)=>s.jsxs("button",{type:"button",onMouseDown:ae=>{ae.preventDefault(),is(_)},onMouseEnter:()=>Ye(G),className:`flex w-full items-center gap-2 rounded-xl px-2 py-1.5 text-left text-xs transition-colors ${G===vt?"bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-300":"text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-white/[0.06]"}`,children:[s.jsx("span",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-lg border border-gray-200/70 dark:border-white/[0.08]",children:s.jsx("img",{src:I.dataUrl,className:"h-full w-full object-cover",alt:""})}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:Jn(_)})]},I.id))})]}),s.jsx("div",{ref:q,contentEditable:!0,suppressContentEditableWarning:!0,onInput:I=>{at.current=!0;const _=I.currentTarget,G=Rn(_);S(G.start),tn(_);const ae=lm(_);t(ae),Ye(0),Ie(!1)},onSelect:I=>{const _=I.currentTarget,G=Rn(_);S(G.start),tn(_),Ye(0),Ie(!1)},onKeyDown:kc,onPaste:jc,onCopy:Ic,onClick:I=>{const _=q.current;if(!_)return;const G=I.target;if(G.classList.contains("mention-tag")){const ae=window.getSelection();if(ae){const ce=document.createRange();ce.selectNode(G),ae.removeAllRanges(),ae.addRange(ce),tn(_)}return}tn(_)},"data-placeholder":"描述你想生成的图片,可输入 @ 指定当前参考图...",className:"min-h-[42px] w-full whitespace-pre-wrap break-words rounded-2xl border border-gray-200/60 bg-white/50 px-4 py-3 text-sm leading-relaxed shadow-sm outline-none transition-[border-color,box-shadow] duration-200 focus:ring-1 focus:ring-blue-300/40 empty:before:pointer-events-none empty:before:text-gray-400 empty:before:content-[attr(data-placeholder)] dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-100 dark:focus:ring-blue-500/30 dark:empty:before:text-gray-500"})]}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"hidden sm:flex items-end justify-between gap-3",children:[To("grid-cols-6"),s.jsxs("div",{className:"flex gap-2 flex-shrink-0 mb-0.5",children:[s.jsxs("div",{className:"relative",onMouseEnter:()=>O(!0),onMouseLeave:()=>O(!1),children:[s.jsx(Kt,{visible:Re&&K,text:`参考图数量已达上限(${Yt} 张),无法继续添加`}),s.jsx("button",{onClick:()=>!Re&&H.current?.click(),className:`p-2.5 rounded-xl transition-all shadow-sm ${Re?"bg-gray-200 dark:bg-white/[0.04] text-gray-300 dark:text-gray-500 cursor-not-allowed":"bg-gray-200 dark:bg-white/[0.06] hover:bg-gray-300 dark:hover:bg-white/[0.1] text-gray-500 dark:text-gray-300 hover:shadow"}`,title:Re?`已达上限 ${Yt} 张`:"添加参考图",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})})]}),s.jsxs("div",{className:"relative",onMouseEnter:()=>W(!0),onMouseLeave:()=>W(!1),children:[s.jsx(Kt,{visible:!Se&&D,text:"尚未完成 API 配置,请在右上角设置中进行"}),s.jsx("button",{onClick:()=>Se?Br():f(!0),disabled:Se?!We:!1,className:`p-2.5 rounded-xl transition-all shadow-sm hover:shadow ${Se?"bg-blue-500 text-white hover:bg-blue-600 disabled:bg-gray-300 dark:disabled:bg-white/[0.04] disabled:opacity-50 disabled:cursor-not-allowed":"bg-gray-300 dark:bg-white/[0.06] text-white cursor-pointer"}`,title:Se?N?"遮罩编辑 (Ctrl+Enter)":"生成 (Ctrl+Enter)":"请先配置 API",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 7l5 5m0 0l-5 5m5-5H6"})})})]})]})]}),s.jsxs("div",{className:"sm:hidden flex flex-col gap-2",children:[s.jsx("div",{className:`collapse-section${ke?" collapsed":""}`,children:s.jsxs("div",{className:"collapse-inner",children:[To("grid-cols-2"),s.jsx("div",{className:"h-2"})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative",onMouseEnter:()=>O(!0),onMouseLeave:()=>O(!1),children:[s.jsx(Kt,{visible:Re&&K,text:`参考图数量已达上限(${Yt} 张),无法继续添加`}),s.jsx("button",{onClick:()=>!Re&&H.current?.click(),className:`p-2.5 rounded-xl transition-all shadow-sm flex-shrink-0 ${Re?"bg-gray-200 dark:bg-white/[0.04] text-gray-300 dark:text-gray-500 cursor-not-allowed":"bg-gray-200 dark:bg-white/[0.06] hover:bg-gray-300 dark:hover:bg-white/[0.1] text-gray-500 dark:text-gray-300"}`,title:Re?`已达上限 ${Yt} 张`:"添加参考图",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})})]}),s.jsxs("div",{className:"relative flex-1",onMouseEnter:()=>W(!0),onMouseLeave:()=>W(!1),children:[s.jsx(Kt,{visible:!Se&&D,text:"尚未完成 API 配置,请在右上角设置中进行"}),s.jsxs("button",{onClick:()=>Se?Br():f(!0),disabled:Se?!We:!1,className:`w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-medium transition-all shadow-sm ${Se?"bg-blue-500 text-white hover:bg-blue-600 disabled:bg-gray-300 dark:disabled:bg-white/[0.04] disabled:opacity-50 disabled:cursor-not-allowed":"bg-gray-300 dark:bg-white/[0.06] text-white cursor-pointer"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 7l5 5m0 0l-5 5m5-5H6"})}),N?"遮罩编辑":"生成图像"]})]})]})]})]}),s.jsx("input",{ref:H,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:vc})]})]})]})}async function xr(e){let t=null;if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(e);return}catch(r){t=r}if(!um(e))throw t??new Error("Clipboard API is not available")}async function gc(e){if(!navigator.clipboard?.write||typeof ClipboardItem>"u")throw new Error("Clipboard image API is not available");await navigator.clipboard.write([new ClipboardItem({[e.type]:e})])}function Vt(e,t){return fm()&&mm(t)?"复制失败:内嵌页面未授予剪贴板权限":e}function um(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select(),t.setSelectionRange(0,t.value.length);try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(t)}}function fm(){try{return window.self!==window.top}catch{return!0}}function mm(e){return e instanceof Error?e.name==="NotAllowedError"||/permission|permissions policy|not allowed|denied/i.test(e.message):!1}function hm(){const e=E(S=>S.tasks),t=E(S=>S.detailTaskId),r=E(S=>S.setDetailTaskId),n=E(S=>S.setLightboxImageId);E(S=>S.setMaskEditorImageId);const a=E(S=>S.setConfirmDialog),o=E(S=>S.showToast),i=E(S=>S.settings),c=E(S=>S.dismissedCodexCliPrompts),[l,f]=g.useState(0),[m,u]=g.useState({}),[h,x]=g.useState({}),[y,b]=g.useState({}),[d,p]=g.useState({}),[w,v]=g.useState(""),[j,P]=g.useState(Date.now()),[C,$]=g.useState(!1),[R,N]=g.useState(!1),Q=g.useRef(null),L=g.useRef(null),H=g.useRef(null),q=g.useRef(null),F=g.useRef(null),[Y,A]=g.useState(8),U=g.useRef(!1),J=g.useRef(!1),D=yr(),W=yr(),K=yr(),O=yr(),z=()=>{const S=window.getSelection();S&&!S.isCollapsed&&S.removeAllRanges()},T=g.useMemo(()=>e.find(S=>S.id===t)??null,[e,t]);Jr(!!T,()=>r(null)),Mr(!!T,[H,q,F]),g.useEffect(()=>{f(0)},[t]),g.useEffect(()=>{if(T?.status!=="running"&&!(T?.status==="error"&&(T.falRecoverable||T.customRecoverable)))return;const S=window.setInterval(()=>P(Date.now()),1e3);return P(Date.now()),()=>window.clearInterval(S)},[T?.customRecoverable,T?.falRecoverable,T?.status]),g.useEffect(()=>{if(!T){u({}),x({}),b({}),p({});return}let S=!1;const he=[...new Set([...T.inputImageIds||[],...T.maskImageId?[T.maskImageId]:[]])],Pe={};for(const ge of he){const Me=pn(ge);Me&&(Pe[ge]=Me)}u(Pe);for(const ge of he)Pe[ge]||Ot(ge).then(Me=>{!S&&Me&&u(ot=>({...ot,[ge]:Me}))});return()=>{S=!0}},[T]);const V=T?.outputImages?.[l]||"",Z=V&&h[V]||"",ee=T?.maskTargetImageId||null,oe=ee&&m[ee]||"",ye=T?.maskImageId&&m[T.maskImageId]||"",fe=T?.inputImageIds??[];if(g.useEffect(()=>{if(!V){x({});return}let S=!1;const he=ge=>{S||x({[V]:ge})},Pe=pn(V);return Pe?he(Pe):Ot(V).then(ge=>{ge&&he(ge)}).catch(()=>{S||x({})}),()=>{S=!0}},[V]),g.useEffect(()=>{const S=()=>{const he=Q.current,Pe=L.current;if(!he||!Pe)return;const ge=he.getBoundingClientRect(),Me=Pe.getBoundingClientRect();A(Math.max(8,Me.left-ge.left))};return S(),window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[Z]),g.useEffect(()=>{let S=!1;if(v(""),!(!oe||!ye))return ao(oe,ye).then(he=>{S||v(he)}).catch(()=>{S||v("")}),()=>{S=!0}},[oe,ye]),!T)return null;const be=T.outputImages?.length||0,xe=V?y[V]:"",ke=V?d[V]:"",ne=V?T.actualParamsByImage?.[V]:void 0,ve=V?T.revisedPromptByImage?.[V]?.trim():"",_e=!!(ve&&ve!==T.prompt.trim()),ft=ec(i),je=i.codexCli||c.includes(ft),Oe=T.apiProvider,It=!!((Oe??"openai")==="openai"&&V&&(!ve||_e)&&!je),rt=Oe==="fal"?"fal.ai":Oe?"OpenAI":"未知",vt=T.apiProfileName||"未知",Ye=T.apiModel||"未知",ze=!!(T.apiProvider||T.apiProfileName||T.apiModel),Ie=T.status==="error"&&T.falRecoverable,Ce=T.status==="error"&&T.customRecoverable,Le=T.rawImageUrls??[],He=S=>S?new Date(S).toLocaleString("zh-CN"):"",Te=()=>{if(T.status==="running"||Ie||Ce){const ge=Math.max(0,Math.floor((j-T.createdAt)/1e3)),Me=String(Math.floor(ge/60)).padStart(2,"0"),ot=String(ge%60).padStart(2,"0");return`${Me}:${ot}`}if(T.elapsed==null)return null;const S=Math.floor(T.elapsed/1e3),he=String(Math.floor(S/60)).padStart(2,"0"),Pe=String(S%60).padStart(2,"0");return`${he}:${Pe}`},Ve=()=>{oc(T),r(null)},Je=()=>{ic(T),r(null)},mt=()=>{r(null),a({title:"删除记录",message:"确定要删除这条记录吗?关联的图片资源也会被清理(如果没有其他任务引用)。",action:()=>lc(T)})},nt=()=>{wt(T.id,{isFavorite:!T.isFavorite})},ht=async()=>{const S=T.error||"生成失败";try{await xr(S),o("完整报错已复制","success")}catch(he){o(Vt("复制报错失败",he),"error")}},at=async()=>{if(T.prompt)try{await xr(T.prompt),o("提示词已复制","success")}catch(S){o(Vt("复制提示词失败",S),"error")}},Xe=()=>{Ba(!0,ve?"接口返回的提示词已被改写":"接口没有返回官方 API 会返回的部分信息")},tt=async()=>{const S=fe[0],he=S?m[S]:"";if(he)try{const ge=await(await fetch(he)).blob();await gc(ge),o("参考图已复制","success")}catch(Pe){console.error(Pe),o(Vt("复制参考图失败",Pe),"error")}},gt=()=>{ac(T),r(null)};return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-50 flex items-center justify-center p-4",onClick:()=>r(null),children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{ref:H,className:"relative bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] rounded-3xl shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col md:flex-row z-10 ring-1 ring-black/5 dark:ring-white/10 animate-modal-in",onClick:S=>S.stopPropagation(),children:[s.jsx("div",{className:"flex h-14 items-center justify-end px-4 md:hidden",children:s.jsx("button",{onClick:()=>r(null),className:"p-1 rounded-full hover:bg-gray-100 dark:hover:bg-white/[0.06] transition text-gray-400","aria-label":"关闭",children:s.jsx(wr,{className:"w-6 h-6"})})}),s.jsxs("div",{ref:Q,className:"md:w-1/2 w-full h-64 md:h-auto bg-gray-100 dark:bg-black/20 relative flex items-center justify-center flex-shrink-0 min-h-[16rem]",children:[T.status==="done"&&be>0&&Z&&s.jsxs(s.Fragment,{children:[s.jsx("img",{ref:L,src:Z,"data-image-id":V,className:"saveable-image max-w-[calc(100%-2rem)] max-h-[calc(100%-2rem)] object-contain cursor-pointer",onLoad:()=>{const S=Q.current,he=L.current;if(!S||!he)return;V&&he.naturalWidth>0&&he.naturalHeight>0&&(b(Me=>({...Me,[V]:Ll(he.naturalWidth,he.naturalHeight)})),p(Me=>({...Me,[V]:`${he.naturalWidth}×${he.naturalHeight}`})));const Pe=S.getBoundingClientRect(),ge=he.getBoundingClientRect();A(Math.max(8,ge.left-Pe.left))},onClick:()=>n(T.outputImages[l],T.outputImages),alt:""}),s.jsx("div",{"data-selectable-text":!0,className:"absolute top-[15px] flex items-center gap-1.5",style:{left:Y},children:xe&&ke?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"bg-black/50 text-white text-xs px-2 py-0.5 rounded backdrop-blur-sm font-mono",children:xe}),s.jsx("span",{className:"bg-black/50 text-white/90 text-xs px-2 py-0.5 rounded backdrop-blur-sm font-medium",children:ke})]}):Te()&&s.jsxs("span",{className:"flex items-center gap-1 bg-black/50 text-white text-xs px-2 py-0.5 rounded backdrop-blur-sm font-mono",children:[s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),Te()]})}),be>1&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>f((l-1+be)%be),className:"absolute left-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full bg-black/30 text-white hover:bg-black/50 transition",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("button",{onClick:()=>f((l+1)%be),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full bg-black/30 text-white hover:bg-black/50 transition",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}),s.jsxs("span",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 bg-black/50 text-white text-xs px-2 py-0.5 rounded-full",children:[l+1," / ",be]})]})]}),(T.status==="running"||Ie)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"absolute left-4 top-4 flex items-center gap-1 bg-black/50 text-white text-xs px-2 py-0.5 rounded backdrop-blur-sm font-mono",children:[s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),Te()]}),T.status==="running"&&s.jsxs("svg",{className:"w-10 h-10 text-blue-400 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})]}),T.status==="error"&&Ie&&s.jsxs("div",{className:"w-full max-w-md px-4 text-center",children:[s.jsx("svg",{className:"w-10 h-10 text-yellow-400 mx-auto mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),s.jsx("p",{className:"text-sm font-medium text-yellow-500",children:"重连中"})]}),T.status==="error"&&!Ie&&s.jsxs("div",{className:"w-full max-w-md px-4 text-center",children:[s.jsx("svg",{className:"w-10 h-10 text-red-400 mx-auto mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx("p",{className:"overflow-hidden whitespace-pre-line text-sm leading-6 text-red-500 break-words",style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4},children:T.error||"生成失败"}),s.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...D.handlers,onClick:S=>{D.handlers.onClick(),ht()},className:"inline-flex items-center justify-center rounded-full border border-red-200/80 bg-white/80 px-3 py-1.5 text-red-500 transition hover:bg-red-50 dark:border-red-400/20 dark:bg-white/[0.04] dark:hover:bg-red-500/10","aria-label":"复制完整报错",children:s.jsx(Jt,{className:"h-4 w-4"})}),s.jsx(jt,{visible:D.visible,className:"whitespace-nowrap",children:"复制完整报错"})]}),T.rawResponsePayload&&s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...K.handlers,onClick:S=>{Ht(),N(!0)},className:"inline-flex items-center justify-center rounded-full border border-purple-200/80 bg-purple-50 px-3 py-1.5 text-purple-600 transition hover:bg-purple-100 dark:border-purple-500/20 dark:bg-purple-500/10 dark:text-purple-400 dark:hover:bg-purple-500/20","aria-label":"查看原始响应",children:s.jsx(fc,{className:"h-4 w-4"})}),s.jsx(jt,{visible:K.visible,className:"whitespace-nowrap",children:"查看原始响应"})]}),T.rawImageUrls&&T.rawImageUrls.length>0&&s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...W.handlers,onClick:async S=>{if(T.rawImageUrls.length===1){W.handlers.onClick();try{await xr(T.rawImageUrls[0]),o("图片链接已复制","success")}catch(he){o(Vt("复制链接失败",he),"error")}}else Ht(),$(!0)},className:"inline-flex items-center justify-center rounded-full border border-green-200/80 bg-green-50 px-3 py-1.5 text-green-600 transition hover:bg-green-100 dark:border-green-500/20 dark:bg-green-500/10 dark:text-green-400 dark:hover:bg-green-500/20","aria-label":"复制图片链接",children:s.jsx(js,{className:"h-4 w-4"})}),s.jsx(jt,{visible:W.visible,className:"whitespace-nowrap",children:"复制图片链接"})]}),s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...O.handlers,onClick:S=>{O.handlers.onClick(),gt()},className:"inline-flex items-center justify-center rounded-full border border-blue-200/80 bg-white/80 px-3 py-1.5 text-blue-500 transition hover:bg-blue-50 dark:border-blue-400/20 dark:bg-white/[0.04] dark:hover:bg-blue-500/10","aria-label":"重试任务",children:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),s.jsx(jt,{visible:O.visible,className:"whitespace-nowrap",children:"重试任务"})]})]})]})]}),s.jsxs("div",{className:"md:w-1/2 w-full p-5 overflow-y-auto overscroll-contain flex flex-col",children:[s.jsx("button",{onClick:()=>r(null),className:"absolute top-3 right-3 hidden p-1 rounded-full hover:bg-gray-100 dark:hover:bg-white/[0.06] transition text-gray-400 z-10 md:block","aria-label":"关闭",children:s.jsx(wr,{className:"w-5 h-5"})}),s.jsxs("div",{"data-selectable-text":!0,className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsx("h3",{className:"text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider",children:"输入内容"}),T.prompt&&s.jsx("button",{onClick:at,className:"p-1 rounded text-gray-400 hover:bg-gray-100 dark:text-gray-500 dark:hover:bg-white/[0.06] transition",title:"复制提示词",children:s.jsx(Jt,{className:"h-4 w-4"})}),It&&s.jsx("span",{className:"relative inline-flex",children:s.jsx("button",{type:"button",className:"p-1 rounded text-amber-500 hover:bg-amber-50 dark:text-yellow-300 dark:hover:bg-yellow-500/10 transition",onClick:Xe,"aria-label":"提示词已被改写",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"})})})})]}),s.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300 leading-relaxed whitespace-pre-wrap mb-4",children:T.prompt||"(无提示词)"}),_e&&ve&&s.jsx("div",{className:"mb-4",children:s.jsx($r,{value:ve,className:"max-w-full rounded px-2 py-1 text-left text-xs leading-relaxed whitespace-pre-wrap"})}),fe.length>0&&s.jsxs("div",{className:"mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsx("h3",{className:"text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider",children:"参考图"}),s.jsx("button",{onClick:tt,className:"p-1 rounded text-gray-400 hover:bg-gray-100 dark:text-gray-500 dark:hover:bg-white/[0.06] transition",title:"复制参考图",children:s.jsx(Jt,{className:"h-4 w-4"})})]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:fe.map(S=>{const he=S===ee,Pe=he&&w?w:m[S]||"";return s.jsx("div",{className:"relative group inline-block",children:s.jsxs("div",{className:`relative w-16 h-16 rounded-lg overflow-hidden border cursor-pointer hover:opacity-80 transition ${he?"border-blue-500 border-2 shadow-sm":"border-gray-200 dark:border-white/[0.08]"}`,onClick:()=>n(S,fe),children:[Pe&&s.jsx("img",{src:Pe,"data-image-id":S,className:"w-full h-full object-cover",alt:""}),he&&s.jsx("span",{className:"absolute left-1 top-1 rounded bg-blue-500/90 px-1.5 py-0.5 text-[8px] leading-none text-white font-bold tracking-wider backdrop-blur-sm z-10 pointer-events-none",children:"MASK"})]})},S)})})]}),s.jsx("h3",{className:"text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-2",children:"参数配置"}),ze&&s.jsxs("div",{className:"mb-2 rounded-lg bg-gray-50 px-3 py-2 text-xs dark:bg-white/[0.03]",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"来源"}),s.jsx("br",{}),s.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-200",children:rt}),s.jsxs("span",{className:"text-gray-400 dark:text-gray-500",children:[" · ",vt," · ",Ye]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs mb-4",children:[s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"尺寸"}),s.jsx("br",{}),s.jsx(en,{task:T,paramKey:"size",className:"font-medium",actualParams:ne})]}),s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"质量"}),s.jsx("br",{}),s.jsx(en,{task:T,paramKey:"quality",className:"font-medium",actualParams:ne})]}),s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"格式"}),s.jsx("br",{}),s.jsx(en,{task:T,paramKey:"output_format",className:"font-medium",actualParams:ne})]}),s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"审核"}),s.jsx("br",{}),s.jsx(en,{task:T,paramKey:"moderation",className:"font-medium",actualParams:ne})]}),s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"数量"}),s.jsx("br",{}),s.jsx(en,{task:T,paramKey:"n",className:"font-medium"})]}),T.params.output_compression!=null&&s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"压缩率"}),s.jsx("br",{}),s.jsx(en,{task:T,paramKey:"output_compression",className:"font-medium",actualParams:ne})]})]}),s.jsxs("div",{className:"text-xs text-gray-400 dark:text-gray-500 mb-4",children:[s.jsxs("span",{children:["创建于 ",He(T.createdAt)]}),Te()&&s.jsxs("span",{children:[" · 耗时 ",Te()]})]})]}),s.jsxs("div",{className:"grid grid-cols-4 sm:flex gap-2 pt-4 border-t border-gray-100 dark:border-white/[0.08]",children:[s.jsxs("button",{onClick:Ve,className:"col-span-2 sm:flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-500/20 transition text-sm font-medium whitespace-nowrap",children:[s.jsx("svg",{className:"w-4 h-4 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"})}),"复用配置"]}),s.jsxs("button",{onClick:Je,disabled:!be,className:"col-span-2 sm:flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl bg-green-50 dark:bg-green-500/10 text-green-600 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-500/20 disabled:opacity-40 disabled:cursor-not-allowed transition text-sm font-medium whitespace-nowrap",children:[s.jsx(bo,{className:"w-4 h-4 flex-shrink-0"}),"编辑输出"]}),s.jsxs("button",{onClick:mt,className:"col-span-3 sm:flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl bg-red-50 dark:bg-red-500/10 text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-500/20 transition text-sm font-medium whitespace-nowrap",children:[s.jsx(Ls,{className:"w-4 h-4 flex-shrink-0"}),"删除记录"]}),s.jsx("button",{onClick:nt,className:`col-span-1 sm:flex-none sm:w-11 w-full flex items-center justify-center rounded-xl transition ${T.isFavorite?"bg-yellow-50 text-yellow-500 hover:bg-yellow-100 dark:bg-yellow-500/10 dark:hover:bg-yellow-500/20":"bg-gray-50 text-gray-400 hover:bg-yellow-50 hover:text-yellow-500 dark:bg-white/[0.04] dark:hover:bg-yellow-500/10"}`,title:T.isFavorite?"取消收藏":"收藏记录",children:s.jsx("svg",{className:"w-5 h-5",fill:T.isFavorite?"currentColor":"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})})]})]})]}),C&&Le.length>0&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4 backdrop-blur-sm sm:p-6",onPointerDown:S=>{U.current=S.target===S.currentTarget},onClick:S=>{S.stopPropagation(),U.current&&S.target===S.currentTarget&&$(!1),U.current=!1},children:s.jsxs("div",{ref:q,className:"flex w-full max-w-2xl max-h-[90vh] flex-col overflow-hidden rounded-2xl bg-white shadow-xl dark:bg-[#1c1c1e]",onClick:S=>S.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-gray-100 px-5 py-4 dark:border-white/[0.08] shrink-0",children:[s.jsxs("h3",{className:"text-base font-semibold text-gray-900 dark:text-white",children:["原始图片链接 (",Le.length,")"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:async()=>{try{await xr(Le.join(`
21
+ `)),o("复制成功","success")}catch(S){o(Vt("复制失败",S),"error")}},className:"flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg bg-gray-50 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.08] transition-colors text-xs font-medium",children:[s.jsx(Jt,{className:"w-3.5 h-3.5"}),"全部复制"]}),s.jsx("button",{type:"button",onClick:()=>$(!1),className:"rounded-full p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:hover:bg-white/[0.08] dark:hover:text-gray-300 transition-colors",children:s.jsx(wr,{className:"w-5 h-5"})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 sm:p-5 bg-gray-50/50 dark:bg-black/20 overscroll-contain",children:s.jsx("div",{className:"space-y-2.5",children:Le.map((S,he)=>s.jsxs("div",{className:"group flex items-center gap-3 p-3 sm:p-4 rounded-xl bg-white dark:bg-[#1c1c1e] border border-gray-100 dark:border-white/[0.06] shadow-sm hover:shadow-md transition-all",children:[s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-1",children:[s.jsxs("div",{className:"text-xs font-medium text-gray-400 dark:text-gray-500",children:["图片 ",he+1]}),s.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300 truncate select-text",title:S,children:S})]}),s.jsxs("button",{type:"button",onClick:async()=>{try{await xr(S),o("复制成功","success")}catch(Pe){o(Vt("复制失败",Pe),"error")}},className:"flex-shrink-0 p-2 sm:px-3 sm:py-1.5 flex items-center justify-center gap-1.5 rounded-lg bg-gray-50 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.08] transition-colors text-xs font-medium border border-transparent dark:border-white/[0.04]",title:"复制链接",children:[s.jsx(Jt,{className:"w-4 h-4 sm:w-3.5 sm:h-3.5"}),s.jsx("span",{className:"hidden sm:inline",children:"复制"})]})]},he))})})]})}),R&&T?.rawResponsePayload&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4 backdrop-blur-sm sm:p-6",onPointerDown:S=>{J.current=S.target===S.currentTarget},onClick:S=>{S.stopPropagation(),J.current&&S.target===S.currentTarget&&N(!1),J.current=!1},children:s.jsxs("div",{ref:F,className:"flex w-full max-w-3xl max-h-[90vh] flex-col overflow-hidden rounded-2xl bg-white shadow-xl dark:bg-[#1c1c1e]",onPointerDown:S=>{S.target.closest("[data-selectable-text]")||z()},onClick:S=>S.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-gray-100 px-5 py-4 dark:border-white/[0.08] shrink-0",children:[s.jsx("h3",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"原始响应数据"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:async()=>{try{await xr(T.rawResponsePayload),o("复制成功","success")}catch(S){o(Vt("复制失败",S),"error")}},className:"flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg bg-gray-50 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.08] transition-colors text-xs font-medium",children:[s.jsx(Jt,{className:"w-3.5 h-3.5"}),"全部复制"]}),s.jsx("button",{type:"button",onClick:()=>N(!1),className:"rounded-full p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:hover:bg-white/[0.08] dark:hover:text-gray-300 transition-colors",children:s.jsx(wr,{className:"w-5 h-5"})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-5 bg-gray-50/50 dark:bg-black/20 overscroll-contain",children:s.jsx("pre",{"data-selectable-text":!0,className:"text-[11px] sm:text-xs text-gray-600 dark:text-gray-300 font-mono whitespace-pre-wrap break-all select-text",children:T.rawResponsePayload.replace(/"(b64_json|base64|data)":\s*"[^"]+"/g,'"$1": "<base64_data>"')})})]})})]})}const xa=1,ba=10;function ya(e,t,r){return Math.max(t,Math.min(r,e))}function gm(){const e=E(w=>w.lightboxImageId),t=E(w=>w.lightboxImageList),r=E(w=>w.setLightboxImageId),n=E(w=>w.maskDraft),a=E(w=>w.tasks),[o,i]=g.useState(""),[c,l]=g.useState(""),[f,m]=g.useState(""),u=g.useCallback(()=>r(null),[r]);Jr(!!e,u),Mr(!!e),g.useEffect(()=>{let w=!1;if(!e){i("");return}i("");const v=e,j=pn(v);return j?i(j):Ot(v).then(P=>{!w&&P&&i(P)}),()=>{w=!0}},[e]),g.useEffect(()=>{let w=!1;if(!e){l("");return}if(n?.targetImageId===e){l(n.maskDataUrl);return}l("");const v=a.find(j=>j.maskTargetImageId===e&&j.maskImageId);if(v?.maskImageId){const j=v.maskImageId,P=pn(j);P?l(P):Ot(j).then(C=>{!w&&C&&l(C)})}else l("");return()=>{w=!0}},[e,n?.targetImageId,n?.maskDataUrl,a]),g.useEffect(()=>{let w=!1;if(!o||!c){m("");return}return ao(o,c).then(v=>{w||m(v)}).catch(()=>{w||m("")}),()=>{w=!0}},[o,c]);const h=e?t.indexOf(e):-1,x=t.length,y=x>1,b=g.useCallback(w=>{if(t.length===0)return;const v=(w%t.length+t.length)%t.length;r(t[v],t)},[t,r]),d=g.useCallback(()=>{y&&b(h-1)},[y,h,b]),p=g.useCallback(()=>{y&&b(h+1)},[y,h,b]);return g.useEffect(()=>{if(!e||!y)return;const w=v=>{v.key==="ArrowLeft"&&(v.preventDefault(),d()),v.key==="ArrowRight"&&(v.preventDefault(),p())};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[e,y,d,p]),!e||!o?null:s.jsx(pm,{src:o,imageId:e,maskPreviewSrc:f,onClose:u,showNav:y,currentIndex:h,total:x,onPrev:d,onNext:p})}function pm({src:e,imageId:t,maskPreviewSrc:r,onClose:n,showNav:a,currentIndex:o,total:i,onPrev:c,onNext:l}){const f=g.useRef(null),m=g.useRef(1),u=g.useRef(0),h=g.useRef(0),[,x]=g.useState(0),y=g.useCallback(()=>x(O=>O+1),[]),[b,d]=g.useState(!1),p=g.useRef(null),w=g.useRef({active:!1,startX:0,startY:0,baseTx:0,baseTy:0}),v=g.useRef({active:!1,startDist:0,startScale:1,startTx:0,startTy:0,midX:0,midY:0}),j=g.useRef({time:0,x:0,y:0}),P=g.useRef(!1),C=g.useRef(!1),$=g.useRef(!1),R=g.useRef(!1);g.useEffect(()=>{m.current=1,u.current=0,h.current=0,y()},[e,y]),g.useEffect(()=>{const O=()=>{R.current=!0};return window.addEventListener("image-context-menu-dismiss-lightbox-click",O),()=>window.removeEventListener("image-context-menu-dismiss-lightbox-click",O)},[]);const N=g.useCallback(()=>{const O=f.current?.getBoundingClientRect();return O?{cx:O.left+O.width/2,cy:O.top+O.height/2}:{cx:0,cy:0}},[]),Q=g.useCallback((O,z,T)=>{const V=ya(O,xa,ba);m.current=V,u.current=V<=1?0:z,h.current=V<=1?0:T,V>1?(d(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>d(!1),1500)):(d(!1),p.current&&clearTimeout(p.current)),y()},[y]);g.useEffect(()=>{const O=f.current;if(!O)return;const z=T=>{T.preventDefault();const V=m.current,Z=u.current,ee=h.current,oe=O.getBoundingClientRect(),ye=T.clientX-oe.left-oe.width/2,fe=T.clientY-oe.top-oe.height/2,be=T.deltaY<0?1.15:1/1.15,xe=ya(V*be,xa,ba),ke=xe/V;Q(xe,ye-ke*(ye-Z),fe-ke*(fe-ee))};return O.addEventListener("wheel",z,{passive:!1}),()=>O.removeEventListener("wheel",z)},[Q]),g.useEffect(()=>{const O=f.current;if(!O)return;const z=Z=>{Z.button===0&&($.current=!1,!(m.current<=1)&&(Z.preventDefault(),w.current={active:!0,startX:Z.clientX,startY:Z.clientY,baseTx:u.current,baseTy:h.current}))},T=Z=>{const ee=w.current;if(!ee.active)return;const oe=Z.clientX-ee.startX,ye=Z.clientY-ee.startY;(Math.abs(oe)>3||Math.abs(ye)>3)&&($.current=!0),Q(m.current,ee.baseTx+oe,ee.baseTy+ye)},V=()=>{w.current.active=!1};return O.addEventListener("mousedown",z),window.addEventListener("mousemove",T),window.addEventListener("mouseup",V),()=>{O.removeEventListener("mousedown",z),window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",V)}},[Q]);const L=g.useCallback(O=>{if(R.current){R.current=!1,O.stopPropagation();return}$.current||m.current>1&&O.target instanceof HTMLImageElement||n()},[n]),H=g.useCallback(O=>{if(O.stopPropagation(),m.current>1)Q(1,0,0);else{const{cx:z,cy:T}=N(),V=O.clientX-z,Z=O.clientY-T;Q(3,-V*2,-Z*2)}},[Q,N]);g.useEffect(()=>{const O=f.current;if(!O)return;const z=Z=>{if(Z.touches.length===2){Z.preventDefault(),P.current=!0,j.current={time:0,x:0,y:0};const[ee,oe]=[Z.touches[0],Z.touches[1]],ye=Math.hypot(ee.clientX-oe.clientX,ee.clientY-oe.clientY),{cx:fe,cy:be}=N();v.current={active:!0,startDist:ye,startScale:m.current,startTx:u.current,startTy:h.current,midX:(ee.clientX+oe.clientX)/2-fe,midY:(ee.clientY+oe.clientY)/2-be},w.current.active=!1}else if(Z.touches.length===1){const ee=Z.touches[0],oe=Date.now(),ye=j.current;if(C.current=Z.target instanceof HTMLImageElement,oe-ye.time<300&&Math.abs(ee.clientX-ye.x)<30&&Math.abs(ee.clientY-ye.y)<30){if(Z.preventDefault(),m.current>1)Q(1,0,0);else{const{cx:fe,cy:be}=N(),xe=ee.clientX-fe,ke=ee.clientY-be;Q(3,-xe*2,-ke*2)}j.current={time:0,x:0,y:0};return}j.current={time:oe,x:ee.clientX,y:ee.clientY},m.current>1&&C.current&&(Z.preventDefault(),w.current={active:!0,startX:ee.clientX,startY:ee.clientY,baseTx:u.current,baseTy:h.current})}},T=Z=>{if(v.current.active&&Z.touches.length===2){Z.preventDefault();const[ee,oe]=[Z.touches[0],Z.touches[1]],ye=Math.hypot(ee.clientX-oe.clientX,ee.clientY-oe.clientY),fe=v.current,be=ya(fe.startScale*(ye/fe.startDist),xa,ba),xe=be/fe.startScale;Q(be,fe.midX-xe*(fe.midX-fe.startTx),fe.midY-xe*(fe.midY-fe.startTy))}else if(w.current.active&&Z.touches.length===1){Z.preventDefault();const ee=Z.touches[0],oe=w.current;Q(m.current,oe.baseTx+ee.clientX-oe.startX,oe.baseTy+ee.clientY-oe.startY)}},V=Z=>{if(Z.touches.length<2&&(v.current.active=!1),Z.touches.length===0){if(w.current.active=!1,P.current){P.current=!1,j.current={time:0,x:0,y:0};return}if(m.current<=1||!C.current){const ee=j.current;ee.time>0&&Date.now()-ee.time<300&&setTimeout(()=>{j.current.time===ee.time&&n()},310)}}};return O.addEventListener("touchstart",z,{passive:!1}),O.addEventListener("touchmove",T,{passive:!1}),O.addEventListener("touchend",V),()=>{O.removeEventListener("touchstart",z),O.removeEventListener("touchmove",T),O.removeEventListener("touchend",V)}},[Q,N,n]);const q=m.current,F=u.current,Y=h.current,A=q>1,U=w.current.active||v.current.active,J=Math.round(q*100),D="absolute top-1/2 -translate-y-1/2 p-2 rounded-full bg-black/40 text-white hover:bg-black/60 transition-all z-10 backdrop-blur-sm";return s.jsxs("div",{ref:f,"data-lightbox-root":!0,className:"fixed inset-0 z-[60] flex items-center justify-center select-none",style:{cursor:A?U?"grabbing":"grab":"pointer"},onClick:L,onDoubleClick:H,children:[s.jsx("div",{className:"absolute inset-0 bg-black/70 backdrop-blur-md animate-fade-in"}),s.jsx("div",{className:"relative animate-zoom-in",children:s.jsxs("div",{className:"relative flex items-center justify-center",style:{transform:`translate(${F}px, ${Y}px) scale(${q})`,transition:U?"none":"transform 0.2s ease-out",willChange:"transform"},children:[s.jsx("img",{src:e,"data-image-id":t,className:"saveable-image max-w-[85vw] max-h-[85vh] object-contain rounded-lg shadow-2xl",onDragStart:O=>O.preventDefault(),alt:""}),r&&s.jsx("img",{src:r,className:"absolute inset-0 w-full h-full object-contain rounded-lg pointer-events-none",alt:""})]})}),a&&!A&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:`${D} left-3 sm:left-5`,onClick:O=>{O.stopPropagation(),W()},children:s.jsx("svg",{className:"w-5 h-5 sm:w-6 sm:h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("button",{className:`${D} right-3 sm:right-5`,onClick:O=>{O.stopPropagation(),K()},children:s.jsx("svg",{className:"w-5 h-5 sm:w-6 sm:h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]}),b&&A&&J!==100&&s.jsx("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 pointer-events-none",children:s.jsxs("span",{className:"px-3 py-1.5 bg-black/50 text-white/80 text-xs rounded-full backdrop-blur-sm transition-opacity duration-500",children:[J,"%"]})}),a&&!A&&s.jsx("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 pointer-events-none",children:s.jsxs("span",{className:"px-3 py-1.5 bg-black/50 text-white/80 text-xs rounded-full backdrop-blur-sm",children:[o+1," / ",i]})})]});function W(){c()}function K(){l()}}function ur({checked:e,onChange:t,label:r,tone:n="primary",className:a,...o}){const i=n==="danger"?"border-red-300/60 checked:bg-red-500 checked:border-red-500 focus:ring-red-500/20 dark:border-red-500/30":"border-gray-300 checked:bg-blue-500 checked:border-blue-500 focus:ring-blue-500/20 dark:border-white/15";return s.jsxs("label",{className:`flex items-center gap-2 cursor-pointer group ${a||""}`,children:[s.jsxs("div",{className:"relative flex items-center justify-center",children:[s.jsx("input",{type:"checkbox",checked:e,onChange:c=>t(c.target.checked),className:`peer appearance-none w-4 h-4 rounded-[4px] border bg-white focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-offset-white dark:bg-white/5 dark:focus:ring-offset-gray-900 transition-all cursor-pointer ${i}`,...o}),s.jsx("svg",{className:"absolute w-2.5 h-2.5 pointer-events-none opacity-0 peer-checked:opacity-100 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})]}),r&&s.jsx("span",{className:"text-[13px] font-medium text-gray-700 dark:text-gray-200 group-hover:text-gray-900 dark:group-hover:text-white transition-colors",children:r})]})}function wa(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`}const Ai="__add_custom_provider__",pc="gpt-image-playground.copy-import-url-options",ys={includeApiKey:!1,useNewApiAddress:!1,useNewApiKey:!0,useNewApiModel:!1};function _i(){if(typeof window>"u")return ys;try{const e=window.localStorage.getItem(pc);if(!e)return ys;const t=JSON.parse(e);return!t||typeof t!="object"?ys:{includeApiKey:!1,useNewApiAddress:!!t.useNewApiAddress,useNewApiKey:t.useNewApiKey===void 0?!0:!!t.useNewApiKey,useNewApiModel:!!t.useNewApiModel}}catch{return ys}}function xm(e){if(!(typeof window>"u"))try{window.localStorage.setItem(pc,JSON.stringify({useNewApiAddress:e.useNewApiAddress,useNewApiKey:e.useNewApiKey,useNewApiModel:e.useNewApiModel}))}catch{}}const bm={name:"自定义服务商",submit:{path:"images/generations",method:"POST",contentType:"json",body:{model:"$profile.model",prompt:"$prompt",size:"$params.size",quality:"$params.quality",output_format:"$params.output_format",moderation:"$params.moderation",output_compression:"$params.output_compression",n:"$params.n"},result:{imageUrlPaths:["data.*.url"],b64JsonPaths:["data.*.b64_json"]}},editSubmit:{path:"images/edits",method:"POST",contentType:"multipart",body:{model:"$profile.model",prompt:"$prompt",size:"$params.size",quality:"$params.quality",output_format:"$params.output_format",moderation:"$params.moderation",output_compression:"$params.output_compression",n:"$params.n"},files:[{field:"image[]",source:"inputImages",array:!0},{field:"mask",source:"mask"}],result:{imageUrlPaths:["data.*.url"],b64JsonPaths:["data.*.b64_json"]}}};function Li(){return{json:JSON.stringify(bm,null,2)}}function Di(e){return{json:JSON.stringify({name:e.name,submit:e.submit,editSubmit:e.editSubmit,poll:e.poll},null,2)}}function ym(e){return JSON.parse(e.json)}function wm(e){const t=kr({id:e.id,name:"新配置"});return e.name==="新配置"&&e.provider==="openai"&&e.baseUrl===Ct.baseUrl&&e.apiKey===""&&e.model===At&&e.timeout===Ct.timeout&&e.apiMode==="images"&&e.codexCli===!1&&e.apiProxy===t.apiProxy}function vm(e,t,r){const n=r.profiles.map(a=>Gi(e,a,r.customProviders)).find(a=>a!=null&&t.has(a.id));return n||(e.profiles.find(a=>!t.has(a.id))??e.profiles[0])}const km=`# 角色
22
+ 你是 API 文档解析助手。你的任务是根据用户提供的图像生成 API 文档,生成本应用可导入的自定义服务商配置 JSON。
23
+
24
+ # 工作流程
25
+ 1. 先向用户索要 API 文档链接或完整文档文本。
26
+ 2. 如果当前环境支持读取链接,主动读取;否则要求用户粘贴文档内容。
27
+ 3. 在未获得文档前不要猜测,不要生成占位配置。
28
+ 4. 从文档中判断提交接口、图生图接口、异步任务查询接口、状态值、结果图片路径。
29
+ 5. 如果文档中明确了默认模型 ID 或 API Base URL,在 profiles 中填入;如果未明确模型 ID,model 使用 "gpt-image-2";如果未明确 API Base URL,baseUrl 留空,由用户稍后填写。
30
+ 6. 输出最终 JSON;不要索要 API Key。
31
+
32
+ # 输出结构
33
+ 输出 JSON 包含两个顶层字段:
34
+ - customProviders:自定义服务商 Manifest 数组,每项描述一个服务商的接口映射规则。
35
+ - profiles:API 配置数组,每项描述一个可直接使用的连接配置,引用 customProviders 中的服务商。
36
+
37
+ ## customProviders 元素(Manifest)
38
+ 每个元素的顶层字段:id、name、submit、editSubmit、poll。
39
+ id 是服务商的唯一标识,用于 profiles 中的 provider 字段引用,建议使用 custom-{英文短名} 格式。
40
+ submit 是文生图提交配置,必填。
41
+ editSubmit 是图生图或局部重绘提交配置,可选。如果文生图和图生图使用同一个 JSON 接口,可以省略 editSubmit,并在 submit.body 中加入 image_urls。
42
+ poll 是异步任务查询配置,可选;同步接口不要写 poll。
43
+
44
+ submit/editSubmit 字段:
45
+ - path:接口路径,不带开头斜杠,不带 /v1/ 前缀,例如 images/generations 或 tasks/{task_id}。
46
+ - method:GET 或 POST,默认 POST。
47
+ - contentType:json 或 multipart。
48
+ - query:提交 query 参数对象,可选,例如 {"async":"true"}。
49
+ - body:请求体模板对象。
50
+ - files:multipart 文件字段数组,仅 contentType=multipart 时使用。
51
+ - taskIdPath:提交响应里的任务 ID JSON 路径;同步接口不要写。
52
+ - result:同步响应图片提取规则。
53
+
54
+ poll 字段:
55
+ - path:任务查询路径,使用 {task_id} 占位,例如 images/tasks/{task_id} 或 tasks/{task_id}。
56
+ - method:GET 或 POST,默认 GET。
57
+ - query:查询 query 参数对象,可选。
58
+ - intervalSeconds:轮询间隔秒数。
59
+ - statusPath:查询响应状态字段路径。
60
+ - successValues:成功状态值数组。
61
+ - failureValues:失败状态值数组。
62
+ - errorPath:失败原因路径,可选。
63
+ - result:成功后图片提取规则。
64
+
65
+ result 字段:
66
+ - imageUrlPaths:图片 URL 路径数组,支持 * 通配数组。例如 data.*.url、data.result.images.*.url.*。
67
+ - b64JsonPaths:base64 图片路径数组,支持 * 通配数组。例如 data.*.b64_json。
68
+
69
+ body 模板变量:
70
+ - $profile.model:用户在设置里填写的模型 ID。
71
+ - $prompt:当前提示词。
72
+ - $params.size、$params.quality、$params.output_format、$params.output_compression、$params.moderation、$params.n:应用内参数。
73
+ - $inputImages.dataUrls:参考图 data URL 数组;没有参考图时会自动省略该字段。
74
+ - $mask.dataUrl:遮罩图 data URL;没有遮罩时会自动省略该字段。
75
+
76
+ multipart files 示例:
77
+ - {"field":"image[]","source":"inputImages","array":true}
78
+ - {"field":"mask","source":"mask"}
79
+
80
+ ## profiles 元素
81
+ 每个元素的字段:
82
+ - name:配置名称,方便用户识别。
83
+ - provider:对应 customProviders 中某个元素的 id。
84
+ - baseUrl:API Base URL。如果文档明确给出,填入完整基础地址;否则留空字符串 ""。
85
+ - model:模型 ID。如果 API 文档明确了默认模型,填入该值;否则使用 "gpt-image-2"。
86
+ - apiMode:固定为 "images"。
87
+
88
+ profiles 中不要包含 apiKey(用户导入后自行填写)。
89
+
90
+ # 输出要求
91
+ - 最终回复只包含一个 \`\`\`json 代码块,代码块内是 JSON 对象。
92
+ - JSON 对象必须包含 customProviders 和 profiles 两个顶层字段。
93
+ - 代码块外不要附加解释文字。
94
+ - 不要输出 API Key、Authorization header。
95
+ - 如果文档返回 task_id,就必须配置 taskIdPath 和 poll。
96
+ - 如果结果 URL 是数组,路径必须写到数组元素,例如 data.result.images.*.url.*。
97
+
98
+ ## 同步接口示例
99
+ {"customProviders":[{"id":"custom-example-sync","name":"示例同步服务商","submit":{"path":"images/generations","method":"POST","contentType":"json","body":{"model":"$profile.model","prompt":"$prompt","size":"$params.size","quality":"$params.quality","output_format":"$params.output_format","moderation":"$params.moderation","output_compression":"$params.output_compression","n":"$params.n"},"result":{"imageUrlPaths":["data.*.url"],"b64JsonPaths":["data.*.b64_json"]}},"editSubmit":{"path":"images/edits","method":"POST","contentType":"multipart","body":{"model":"$profile.model","prompt":"$prompt","size":"$params.size","quality":"$params.quality","output_format":"$params.output_format","moderation":"$params.moderation","output_compression":"$params.output_compression","n":"$params.n"},"files":[{"field":"image[]","source":"inputImages","array":true},{"field":"mask","source":"mask"}],"result":{"imageUrlPaths":["data.*.url"],"b64JsonPaths":["data.*.b64_json"]}}}],"profiles":[{"name":"示例同步服务商","provider":"custom-example-sync","baseUrl":"https://api.example.com/v1","model":"example-model-v1","apiMode":"images"}]}
100
+
101
+ ## 异步接口示例
102
+ {"customProviders":[{"id":"custom-example-async","name":"示例异步服务商","submit":{"path":"images/generations","method":"POST","contentType":"json","query":{"async":"true"},"body":{"model":"$profile.model","prompt":"$prompt","size":"$params.size","n":"$params.n"},"taskIdPath":"data"},"editSubmit":{"path":"images/edits","method":"POST","contentType":"multipart","query":{"async":"true"},"body":{"model":"$profile.model","prompt":"$prompt","size":"$params.size","n":"$params.n"},"files":[{"field":"image[]","source":"inputImages","array":true}],"taskIdPath":"data"},"poll":{"path":"images/tasks/{task_id}","method":"GET","intervalSeconds":5,"statusPath":"data.status","successValues":["SUCCESS"],"failureValues":["FAILURE"],"errorPath":"data.fail_reason","result":{"imageUrlPaths":["data.data.data.*.url"],"b64JsonPaths":["data.data.data.*.b64_json"]}}}],"profiles":[{"name":"示例异步服务商","provider":"custom-example-async","baseUrl":"","model":"gpt-image-2","apiMode":"images"}]}
103
+
104
+ ## 统一任务接口示例
105
+ {"customProviders":[{"id":"custom-example-task","name":"示例任务服务商","submit":{"path":"images/generations","method":"POST","contentType":"json","body":{"model":"$profile.model","prompt":"$prompt","n":"$params.n","size":"$params.size","resolution":"2k","quality":"$params.quality","image_urls":"$inputImages.dataUrls"},"taskIdPath":"data.0.task_id"},"poll":{"path":"tasks/{task_id}","method":"GET","query":{"language":"zh"},"intervalSeconds":5,"statusPath":"data.status","successValues":["completed"],"failureValues":["failed","cancelled"],"errorPath":"data.error.message","result":{"imageUrlPaths":["data.result.images.*.url.*"],"b64JsonPaths":[]}}}],"profiles":[{"name":"示例任务服务商","provider":"custom-example-task","baseUrl":"","model":"gpt-image-2","apiMode":"images"}]}`;function jm(){const e=E(k=>k.showSettings),t=E(k=>k.setShowSettings),r=E(k=>k.settings),n=E(k=>k.setSettings),a=E(k=>k.reusedTaskApiProfileId),o=E(k=>k.setReusedTaskApiProfile),i=E(k=>k.setConfirmDialog),c=E(k=>k.showToast),l=g.useRef(null),f=g.useRef(null),m=g.useRef(null),u=g.useRef(null),h=g.useRef(null),x=g.useRef(null),y=g.useRef(null),b=g.useRef(null),[d,p]=g.useState(ue(r)),[w,v]=g.useState(String(et(r).timeout)),[j,P]=g.useState(!1),[C,$]=g.useState(!1),[R,N]=g.useState(an),[Q,L]=g.useState(!1),[H,q]=g.useState(null),[F,Y]=g.useState(Li()),[A,U]=g.useState(null),[J,D]=g.useState(!1),[W,K]=g.useState(!1),[O,z]=g.useState(!1),[T,V]=g.useState("general"),[Z,ee]=g.useState(!0),[oe,ye]=g.useState(!0),[fe,be]=g.useState(!0),[xe,ke]=g.useState(!0),[ne,ve]=g.useState(!0),[_e,ft]=g.useState(!0),[je,Oe]=g.useState(!1),[Ke,It]=g.useState(!1),[rt,vt]=g.useState(!1),[Ye,ze]=g.useState(null),[Ie,Ce]=g.useState(null),[Le,He]=g.useState(null),[Te,Ve]=g.useState(null),Je=g.useRef(null),[mt,nt]=g.useState(null),[ht,at]=g.useState(_i),Xe=Cr(),tt=oo(Xe),gt=Nl(Xe),S=d.profiles.find(k=>k.id===d.activeProfileId)??d.profiles[0]??et(d),he=S.provider==="openai"&&(gt||S.apiProxy),Pe=tt&&S.provider==="openai"&&he,ge=Ro(d,S.provider),Me=ge||S.provider==="fal",ot=d.customProviders.find(k=>k.id===S.provider),Pt=["openai","fal",...d.customProviders.map(k=>k.id)],_t=d.providerOrder||Pt,sr=[{label:"OpenAI 兼容接口",value:"openai",draggable:!0},{label:"fal.ai",value:"fal",draggable:!0},...d.customProviders.map(k=>({label:k.name,value:k.id,draggable:!0,actions:[{label:"编辑",onClick:()=>Qs(k)},{label:"删除",variant:"danger",onClick:()=>ls(k)}]}))],it=[{label:"创建自定义服务商",value:Ai,variant:"action"},...sr.sort((k,B)=>{const re=_t.indexOf(String(k.value)),se=_t.indexOf(String(B.value)),le=re!==-1?re:Pt.indexOf(String(k.value)),we=se!==-1?se:Pt.indexOf(String(B.value));return le-we})],Bt=k=>k==="responses"?ws:At,St=g.useRef(!1);g.useEffect(()=>{if(!e){St.current=!1;return}if(St.current)return;St.current=!0;const k=ue(r),B=k.reuseTaskApiProfileTemporarily&&a&&k.profiles.some(se=>se.id===a)?ue({...k,activeProfileId:a}):k,re=ue({...B,profiles:B.profiles.map(se=>({...se,apiProxy:se.provider==="openai"&&tt?gt||se.apiProxy:!1}))});p(re),v(String(et(re).timeout))},[tt,gt,e,r,a]),g.useEffect(()=>{v(String(S.timeout))},[S.id,S.timeout]);const lt=g.useCallback(()=>{m.current&&N(Vf(m.current))},[]);g.useEffect(()=>{if(!C)return;const k=B=>{f.current?.contains(B.target)||$(!1)};return lt(),document.addEventListener("pointerdown",k),window.addEventListener("resize",lt),window.addEventListener("scroll",lt,!0),()=>{document.removeEventListener("pointerdown",k),window.removeEventListener("resize",lt),window.removeEventListener("scroll",lt,!0)}},[C,lt]),g.useEffect(()=>()=>{u.current!=null&&window.clearTimeout(u.current),h.current!=null&&window.clearTimeout(h.current),x.current!=null&&window.clearTimeout(x.current)},[]),g.useEffect(()=>{if(!Te)return;const k=le=>{le.preventDefault()},B={passive:!1,capture:!0},re=document.body.style.overflow,se=document.body.style.overscrollBehavior;return document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",window.addEventListener("touchmove",k,B),()=>{document.body.style.overflow=re,document.body.style.overscrollBehavior=se,window.removeEventListener("touchmove",k,B)}},[Te]);const ar=()=>{u.current!=null&&(window.clearTimeout(u.current),u.current=null)},hr=()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)},gr=()=>{x.current!=null&&(window.clearTimeout(x.current),x.current=null)},qe=k=>{const B=k.profiles.map(le=>{const we=le.provider==="fal"?le.baseUrl.trim().replace(/\/+$/,"")||Zt:Ts(le.baseUrl.trim()||Ct.baseUrl),Be=le.provider==="fal"?on:Bt(le.apiMode);return{...le,name:le.name.trim()||(le.id===Us?"默认":"新配置"),baseUrl:we,model:le.model.trim()||Be,timeout:Number(le.timeout)||Ct.timeout,apiProxy:le.provider==="openai"&&tt?gt||le.apiProxy:!1,codexCli:le.provider==="openai"?le.codexCli:!1}}),re=kr({id:wa("openai")}),se=ue({...k,profiles:B.length?B:[re],activeProfileId:B.some(le=>le.id===k.activeProfileId)?k.activeProfileId:B[0]?.id??re.id});p(se),n(se)},M=k=>{at(B=>{const re={...B,...k,includeApiKey:!1};return xm(re),re})},X=(k,B)=>{const re=new URL(window.location.href);if(re.search="",re.hash="",k.provider==="openai"){const Be=k.baseUrl.trim()||Ct.baseUrl;re.searchParams.set("apiUrl",B.useNewApiAddress&&!B.includeApiKey?"{address}":Ts(Be)),B.includeApiKey&&k.apiKey.trim()?re.searchParams.set("apiKey",k.apiKey.trim()):!B.includeApiKey&&B.useNewApiKey&&re.searchParams.set("apiKey","{key}"),re.searchParams.set("apiMode",k.apiMode);const Qe=k.model.trim()||Bt(k.apiMode);re.searchParams.set("model",!B.includeApiKey&&B.useNewApiModel?"{model}":Qe),k.codexCli&&re.searchParams.set("codexCli","true");let Ue=re.toString();return B.includeApiKey||(B.useNewApiAddress&&(Ue=Ue.replace("%7Baddress%7D","{address}")),B.useNewApiKey&&(Ue=Ue.replace("%7Bkey%7D","{key}")),B.useNewApiModel&&(Ue=Ue.replace("%7Bmodel%7D","{model}"))),Ue}const se=d.customProviders.find(Be=>Be.id===k.provider),le={...k,apiKey:B.includeApiKey?k.apiKey:""};B.includeApiKey||(B.useNewApiAddress&&(le.baseUrl="{address}"),B.useNewApiKey&&(le.apiKey="{key}"),B.useNewApiModel&&(le.model="{model}")),re.searchParams.set("settings",JSON.stringify({customProviders:se?[se]:[],profiles:[le]}));let we=re.toString();return B.includeApiKey||(B.useNewApiAddress&&(we=we.replace(/%7Baddress%7D/g,"{address}")),B.useNewApiKey&&(we=we.replace(/%7Bkey%7D/g,"{key}")),B.useNewApiModel&&(we=we.replace(/%7Bmodel%7D/g,"{model}"))),we},te=async(k,B)=>{try{await xr(X(k,B)),c(B.includeApiKey?"导入 URL 已复制(包含 API Key)":"导入 URL 已复制","success"),nt(null)}catch(re){c(Vt("复制导入 URL 失败",re),"error")}},ie=k=>{$(!1),D(!1),nt(k),at(_i())},me=k=>({...d,profiles:d.profiles.map(B=>B.id===S.id?{...B,...k}:B)}),de=(k,B=!1)=>{const re=me(k);p(re),B&&qe(re)},Se=k=>{const B=me(k);qe(B)},We=()=>{const k=Number(w),B=w.trim()===""||Number.isNaN(k)?Ct.timeout:k,re={...d,profiles:ge?d.profiles.map(se=>se.id===S.id?{...se,timeout:B}:se):d.profiles};qe(re),t(!1)},or=g.useCallback(()=>{if(!Ro(d,S.provider))return;const k=Number(w),B=w.trim()===""?Ct.timeout:Number.isNaN(k)?S.timeout:k;v(String(B)),de({timeout:B},!0)},[d,S.id,S.provider,S.timeout,w]);if(Jr(e,We),Mr(e,Q?b:y),!e)return null;const De=async k=>{const B=k.target.files?.[0];if(B){Oe(!0);try{if(await Cf(B,{importConfig:fe,importTasks:xe})){const se=ue(E.getState().settings);p(se),v(String(et(se).timeout)),$(!1)}}finally{Oe(!1)}}k.target.value=""},ct=async()=>{await Pf({clearConfig:ne,clearTasks:_e});const k=ue(E.getState().settings);p(k),v(String(et(k).timeout)),$(!1)},dt=async()=>{vt(!0);try{const k=await rc();k&&(o(null),p(k),v(String(et(k).timeout)),$(!1))}finally{vt(!1)}},Nt=()=>{o(null);const k=kr({id:wa("openai"),name:"新配置"}),B=ue({...d,profiles:[...d.profiles,k],activeProfileId:k.id});qe(B),$(!1)},Wt=()=>{o(null),K(!1);const k={...S,id:wa(S.provider==="openai"?"openai":"profile"),name:`${S.name}(复制)`},B=ue({...d,profiles:[...d.profiles,k],activeProfileId:k.id});qe(B),$(!1)},pt=k=>{o(null);const B=ue({...d,activeProfileId:k});qe(B),$(!1)},xt=(k,B)=>{ze(B),k.dataTransfer.effectAllowed="move",k.dataTransfer.setData("text/plain",B)},Rr=(k,B)=>{k.preventDefault(),k.dataTransfer.dropEffect="move";const re=k.currentTarget,se=re.getBoundingClientRect(),le=k.clientY<se.top+se.height/2?"before":"after";(Ie!==B||Le!==le)&&(Ce(B),He(le));const we=re.closest(".custom-scrollbar");if(we){const Be=we.getBoundingClientRect(),Qe=30;k.clientY<Be.top+Qe?we.scrollTop-=10:k.clientY>Be.bottom-Qe&&(we.scrollTop+=10)}},Re=()=>{ze(null),Ce(null),He(null),Ve(null),Je.current=null},Ge=(k,B,re)=>{if(!k||k===B)return;const se=d.profiles.findIndex(Ze=>Ze.id===k),le=d.profiles.findIndex(Ze=>Ze.id===B);if(se<0||le<0)return;const we=[...d.profiles],[Be]=we.splice(se,1);let Qe=le;re==="after"&&Qe++,se<le&&Qe--,we.splice(Qe,0,Be);const Ue=ue({...d,profiles:we});qe(Ue)},ns=(k,B)=>{k.preventDefault(),Ge(k.dataTransfer.getData("text/plain"),B,Le),Re()},ss=(k,B)=>{if(!k.target.closest("[data-drag-handle]"))return;const re=k.touches[0],se=k.currentTarget.getBoundingClientRect();k.preventDefault(),k.stopPropagation(),Je.current={id:B.id,startX:re.clientX,startY:re.clientY,moved:!1},ze(B.id),Ve({label:B.name,providerLabel:sa(d,B.provider),x:re.clientX,y:re.clientY,width:se.width,height:se.height,offsetX:re.clientX-se.left,offsetY:re.clientY-se.top})},Js=k=>{const B=Je.current;if(!B)return;const re=k.touches[0];if(!B.moved)if(Math.abs(re.clientX-B.startX)>5||Math.abs(re.clientY-B.startY)>5)B.moved=!0;else return;k.preventDefault(),Ve(Ze=>Ze&&{...Ze,x:re.clientX,y:re.clientY});const le=document.elementFromPoint(re.clientX,re.clientY)?.closest("[data-profile-id]");if(!le)return;const we=le.getAttribute("data-profile-id");if(!we)return;const Be=le.getBoundingClientRect(),Qe=re.clientY<Be.top+Be.height/2?"before":"after";Ce(we),He(Qe);const Ue=le.closest(".custom-scrollbar");if(Ue){const Ze=Ue.getBoundingClientRect(),bt=30;re.clientY<Ze.top+bt?Ue.scrollTop-=10:re.clientY>Ze.bottom-bt&&(Ue.scrollTop+=10)}},as=k=>{const B=Je.current;B&&(B.moved&&Ie&&Ie!==B.id&&(k.preventDefault(),Ge(B.id,Ie,Le)),Re())},ir=k=>{if(d.profiles.length<=1)return;k===a&&o(null);const B=d.profiles.filter(se=>se.id!==k),re=ue({...d,profiles:B,activeProfileId:d.activeProfileId===k?B[0].id:d.activeProfileId});qe(re)},os=(k,B,re)=>{const se=d.providerOrder||["openai","fal",...d.customProviders.map(bt=>bt.id)],le=se.indexOf(String(k)),we=se.indexOf(String(B));if(le<0||we<0)return;const Be=[...se],[Qe]=Be.splice(le,1);let Ue=we;re==="after"&&Ue++,le<we&&Ue--,Be.splice(Ue,0,Qe);const Ze=ue({...d,providerOrder:Be});qe(Ze)},is=k=>{if(k===Ai){q(null),Y(Li()),L(!0),U(null);return}const B=String(k),re=d.customProviders.find(se=>se.id===B);de(na(S,B,re),!0)},bn=k=>{Y(B=>({...B,...k})),U(null)},Gs=()=>{const k=ym(F),B=new Set(d.customProviders.filter(se=>se.id!==H).map(se=>se.id)),re=Bs(H&&k&&typeof k=="object"?{...k,id:H}:k,B);if(!re)throw new Error("自定义服务商配置无效");return re};function Qs(k){q(k.id),Y(Di(k)),L(!0),U(null)}const Gr=()=>{try{const k=Gs();if(H){const se=ue({...d,customProviders:d.customProviders.map(le=>le.id===H?k:le)});qe(se),L(!1),q(null),U(null),c("服务商配置已更新","success");return}const B=na(S,k.id,k),re=ue({...d,customProviders:[...d.customProviders,k],profiles:d.profiles.map(se=>se.id===S.id?B:se)});qe(re),L(!1),q(null),U(null)}catch(k){U(k instanceof Error?k.message:String(k))}};function ls(k){i({title:"删除服务商",message:`确定要删除自定义服务商「${k.name}」吗?正在使用它的配置会切回 OpenAI 兼容接口。`,action:()=>Zs(k)})}function Zs(k){const B=k.id,re=ue({...d,customProviders:d.customProviders.filter(se=>se.id!==B),profiles:d.profiles.map(se=>se.provider===B?na(se,"openai"):se)});qe(re),c("服务商已删除","success")}const cs=async()=>{try{await xr(km),c("LLM 生成提示词已复制","success")}catch(k){c(Vt("复制 LLM 生成提示词失败",k),"error")}},ds=async()=>{It(!0);try{const k=await navigator.clipboard.readText();if(!k.trim())throw new Error("剪贴板为空");const B=rd(k,d.customProviders);if(B.profiles.length>0){const se=new Set(d.profiles.map(bt=>bt.id)),le=qa(d,B),we=vm(le,se,B),Be=se.has(we.id),Qe=!H&&wm(S)&&!Be,Ue=!Qe&&Be,Ze=ue(Qe?{...le,profiles:le.profiles.filter(bt=>bt.id===S.id||bt.id!==we.id).map(bt=>bt.id===S.id?{...we,id:S.id}:bt),activeProfileId:S.id}:{...le,activeProfileId:we.id});p(Ze),n(Ze),v(String(et(Ze).timeout)),L(!1),q(null),U(null),c(Qe?"已覆盖当前空配置":Ue?"已存在相同配置,已切换到已有配置":"JSON 配置已导入并切换","success");return}const re=B.customProviders[0];Y(Di(re)),U(null),c("JSON 配置已导入","success")}catch(k){const B=k instanceof Error?k.message:String(k);U(null),k instanceof Error&&k.name==="NotAllowedError"?c("无法读取剪贴板,请允许浏览器访问剪贴板,或直接粘贴到输入框中","error"):c(B,"error")}finally{It(!1)}};return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[70] flex items-center justify-center p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in",onClick:We}),s.jsxs("div",{ref:y,className:"relative z-10 w-full max-w-3xl rounded-3xl border border-white/50 bg-white/95 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10 flex h-[85vh] sm:h-[600px] flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between shrink-0 p-5 border-b border-gray-100 dark:border-white/[0.08]",children:[s.jsxs("h3",{className:"text-lg font-bold text-gray-800 dark:text-gray-100 flex items-center gap-2",children:[s.jsxs("svg",{className:"w-5 h-5 text-blue-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),"设置"]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"text-sm text-gray-400 dark:text-gray-500 font-mono select-none",children:["v","0.3.5"]}),s.jsx("button",{onClick:We,className:"rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(wr,{className:"h-5 w-5"})})]})]}),s.jsxs("div",{className:"flex flex-1 min-h-0 flex-col sm:flex-row",children:[s.jsx("div",{className:"w-full sm:w-48 shrink-0 flex flex-col border-b sm:border-b-0 sm:border-r border-gray-100 dark:border-white/[0.08] bg-gray-50/50 dark:bg-white/[0.02]",children:s.jsxs("nav",{className:"flex-1 overflow-x-auto sm:overflow-y-auto custom-scrollbar p-3 space-x-1 sm:space-x-0 sm:space-y-1 flex sm:flex-col",children:[s.jsxs("button",{onClick:()=>V("general"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${T==="general"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 6v6l4 2m6-2a10 10 0 11-20 0 10 10 0 0120 0z"})}),"习惯配置"]}),s.jsxs("button",{onClick:()=>V("api"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${T==="api"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"})}),"API 配置"]}),s.jsxs("button",{onClick:()=>V("data"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${T==="data"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"})}),"数据管理"]}),s.jsxs("button",{onClick:()=>V("about"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${T==="about"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"关于"]})]})}),s.jsx("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 bg-transparent relative overflow-hidden",children:s.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain custom-scrollbar p-5 sm:p-6",children:[T==="general"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"hidden sm:block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"任务提交方式"}),s.jsx("div",{className:"w-32",children:s.jsx(zr,{value:d.enterSubmit?"enter":"ctrl-enter",onChange:k=>qe({...d,enterSubmit:k==="enter"}),options:[{label:"Enter",value:"enter"},{label:navigator.userAgent.includes("Mac")?"Cmd + Enter":"Ctrl + Enter",value:"ctrl-enter"}],className:"w-full px-3 py-1.5 rounded-xl border border-gray-200/60 dark:border-white/[0.08] bg-white/50 dark:bg-white/[0.03] hover:bg-white dark:hover:bg-white/[0.06] text-xs transition-all duration-200 shadow-sm text-gray-700 dark:text-gray-200 outline-none"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"选择 Enter 提交时,使用 Shift + Enter 换行;否则直接 Enter 换行。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"提交任务后清空输入框"}),s.jsx("button",{type:"button",onClick:()=>qe({...d,clearInputAfterSubmit:!d.clearInputAfterSubmit}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${d.clearInputAfterSubmit?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":d.clearInputAfterSubmit,"aria-label":"提交任务后清空输入框",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${d.clearInputAfterSubmit?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,提交成功创建任务时会清空提示词和参考图。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"重启后加载上次的输入框"}),s.jsx("button",{type:"button",onClick:()=>qe({...d,persistInputOnRestart:!d.persistInputOnRestart}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${d.persistInputOnRestart?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":d.persistInputOnRestart,"aria-label":"重启后加载上次的输入框",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${d.persistInputOnRestart?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"关闭后,不再持久化提示词和参考图,下次启动会使用空输入框。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"复用配置时临时复用该任务的 API 配置"}),s.jsx("button",{type:"button",onClick:()=>qe({...d,reuseTaskApiProfileTemporarily:!d.reuseTaskApiProfileTemporarily}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${d.reuseTaskApiProfileTemporarily?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":d.reuseTaskApiProfileTemporarily,"aria-label":"复用配置时临时复用该任务的 API 配置",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${d.reuseTaskApiProfileTemporarily?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,复用历史任务时会临时使用该任务的 API 配置,找不到该配置时提交会提示;关闭后,会继续使用当前的 API 配置。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"成功任务仍然展示重试按钮"}),s.jsx("button",{type:"button",onClick:()=>qe({...d,alwaysShowRetryButton:!d.alwaysShowRetryButton}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${d.alwaysShowRetryButton?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":d.alwaysShowRetryButton,"aria-label":"成功任务仍然展示重试按钮",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${d.alwaysShowRetryButton?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,即使任务成功生成,也会在任务卡片和详情页显示重试按钮。"})]})]}),T==="api"&&s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"rounded-2xl border border-blue-100/80 bg-blue-50/40 p-4 shadow-sm dark:border-blue-500/15 dark:bg-blue-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"本地 Codex 配置"}),s.jsx("div",{"data-selectable-text":!0,className:"mt-1 text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:"从本机 Codex 配置读取图片 API 地址与 Key,并切换为当前配置。"})]}),s.jsxs("button",{type:"button",onClick:dt,disabled:rt,className:"inline-flex shrink-0 items-center justify-center gap-2 rounded-xl bg-blue-500 px-3.5 py-2 text-xs font-semibold text-white shadow-sm transition hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-60",children:[s.jsx(Qf,{className:`h-4 w-4 ${rt?"animate-spin":""}`}),rt?"同步中...":"同步本地"]})]})}),s.jsxs("div",{children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"当前配置"}),s.jsxs("span",{className:"relative inline-flex",children:[s.jsx("button",{type:"button",onClick:()=>ie(S),onMouseEnter:()=>D(!0),onMouseLeave:()=>D(!1),onFocus:()=>D(!0),onBlur:()=>D(!1),onTouchStart:()=>{ar(),u.current=window.setTimeout(()=>{D(!0),u.current=null},450)},onTouchEnd:ar,onTouchCancel:ar,className:"flex h-5 w-5 items-center justify-center rounded-md text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":`复制导入配置「${S.name}」的 URL`,children:s.jsx(js,{className:"h-3.5 w-3.5"})}),s.jsx(jt,{visible:J,className:"whitespace-nowrap",children:"复制导入 URL"})]}),s.jsxs("span",{className:"relative inline-flex",children:[s.jsx("button",{type:"button",onClick:Wt,onMouseEnter:()=>K(!0),onMouseLeave:()=>K(!1),onFocus:()=>K(!0),onBlur:()=>K(!1),onTouchStart:()=>{hr(),h.current=window.setTimeout(()=>{K(!0),h.current=null},450)},onTouchEnd:hr,onTouchCancel:hr,className:"flex h-5 w-5 items-center justify-center rounded-md text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":`复制一份配置「${S.name}」`,children:s.jsx(Jt,{className:"h-3.5 w-3.5"})}),s.jsx(jt,{visible:W,className:"whitespace-nowrap",children:"复制当前配置"})]})]}),s.jsxs("div",{ref:f,className:"relative",children:[s.jsxs("button",{ref:m,type:"button",onClick:()=>{C||lt(),$(!C)},className:"flex w-full min-w-0 items-center justify-between gap-2 rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-sm text-gray-700 outline-none transition hover:bg-gray-50 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:hover:bg-white/[0.06]",title:S.name,children:[s.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:"min-w-0 truncate",children:S.name}),s.jsx("span",{className:"shrink-0 rounded bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-600 dark:bg-blue-500/10 dark:text-blue-400",children:sa(d,S.provider)})]}),s.jsx(uc,{className:`w-3.5 h-3.5 flex-shrink-0 text-gray-400 dark:text-gray-500 transition-transform duration-200 ${C?"rotate-180":""}`})]}),C&&s.jsx(s.Fragment,{children:s.jsxs("div",{className:"absolute right-0 top-full z-50 mt-1.5 w-full overflow-hidden overflow-y-auto rounded-xl border border-gray-200/60 bg-white/95 py-1 shadow-[0_8px_30px_rgb(0,0,0,0.12)] ring-1 ring-black/5 backdrop-blur-xl animate-dropdown-down dark:border-white/[0.08] dark:bg-gray-900/95 dark:shadow-[0_8px_30px_rgb(0,0,0,0.3)] dark:ring-white/10 custom-scrollbar",style:{maxHeight:R},children:[s.jsxs("button",{type:"button",onClick:k=>{k.preventDefault(),Nt()},className:"flex w-full cursor-pointer items-center justify-between gap-2 px-3 py-2 text-left text-xs font-medium text-blue-600 transition-colors hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-500/10",children:[s.jsx("span",{className:"truncate font-semibold",children:"创建新配置"}),s.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:s.jsx(dc,{className:"h-4 w-4"})})]}),s.jsx("div",{children:d.profiles.map(k=>s.jsxs("div",{"data-profile-id":k.id,title:k.name,draggable:!0,onDragStart:B=>xt(B,k.id),onDragOver:B=>Rr(B,k.id),onDrop:B=>ns(B,k.id),onDragEnd:Re,onTouchStart:B=>ss(B,k),onTouchMove:Js,onTouchEnd:as,onTouchCancel:Re,onClick:B=>{B.target.closest("[data-drag-handle]")||(B.preventDefault(),pt(k.id))},className:`relative group flex w-full cursor-pointer items-center justify-between px-3 py-2 text-left text-xs transition-colors ${Ye===k.id?"opacity-40 bg-gray-100 dark:bg-white/[0.04]":k.id===S.id?"bg-blue-50 font-medium text-blue-600 dark:bg-blue-500/10 dark:text-blue-400":"text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-white/[0.06]"}`,children:[Ie===k.id&&Le==="before"&&Ye!==k.id&&s.jsx("div",{className:"absolute -top-[1px] left-0 right-0 h-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),Ie===k.id&&Le==="after"&&Ye!==k.id&&s.jsx("div",{className:"absolute -bottom-[1px] left-0 right-0 h-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[s.jsx("div",{"data-drag-handle":!0,className:"flex cursor-grab active:cursor-grabbing items-center justify-center text-gray-400 opacity-60 transition-opacity hover:opacity-100 dark:text-gray-500",style:{touchAction:"none"},title:"拖拽排序",children:s.jsx(Ds,{className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"min-w-0 truncate",children:k.name}),s.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] shrink-0 ${k.id===S.id?"bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300":"bg-gray-100 text-gray-500 dark:bg-white/[0.08] dark:text-gray-400"}`,children:sa(d,k.provider)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx("button",{type:"button",onClick:B=>{B.preventDefault(),B.stopPropagation(),ie(k)},className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-400 opacity-60 transition-all hover:bg-gray-100 hover:text-gray-600 hover:opacity-100 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":`复制导入配置「${k.name}」的 URL`,title:"复制导入 URL",children:s.jsx(js,{className:"h-3.5 w-3.5"})}),d.profiles.length>1&&s.jsx("button",{type:"button",onClick:B=>{B.preventDefault(),B.stopPropagation(),i({title:"删除配置",message:`确定要删除配置「${k.name}」吗?`,action:()=>ir(k.id)})},className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-400 opacity-60 transition-all hover:bg-red-50 hover:text-red-500 hover:opacity-100 dark:hover:bg-red-500/10","aria-label":"删除配置",children:s.jsx(Ls,{className:"h-3.5 w-3.5"})})]})]},k.id))})]})})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"配置名称"}),s.jsx("input",{value:S.name,onChange:k=>de({name:k.target.value}),onBlur:k=>Se({name:k.target.value}),type:"text",className:"w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50"})]}),s.jsxs("div",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"服务商类型"}),s.jsx(zr,{value:S.provider,onChange:is,onReorder:os,options:it,className:"w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50"})]}),Me&&s.jsxs("label",{className:"block",children:[s.jsx("div",{className:"mb-1.5 flex items-center justify-between",children:s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"API URL"})}),s.jsx("input",{value:S.baseUrl,onChange:k=>de({baseUrl:k.target.value}),onBlur:k=>Se({baseUrl:k.target.value}),type:"text",disabled:Pe,placeholder:S.provider==="fal"?Zt:Ct.baseUrl,className:`w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50 ${Pe?"opacity-50 cursor-not-allowed":""}`}),s.jsx("div",{"data-selectable-text":!0,className:"mt-1.5 min-h-[22px] flex items-center text-xs text-gray-500 dark:text-gray-500",children:Pe?s.jsx("span",{className:"text-yellow-600 dark:text-yellow-500",children:"已开启代理,实际请求目标由部署端决定,此处设置被忽略。"}):S.provider==="fal"?s.jsxs("span",{children:["默认使用 ",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:Zt}),";填写自定义地址时将作为 fal.ai 代理 URL。"]}):s.jsxs("span",{children:["支持通过查询参数覆盖:",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"?apiUrl="})]})})]}),S.provider==="openai"&&s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"Codex CLI 兼容模式"}),s.jsx("button",{type:"button",onClick:()=>de({codexCli:!S.codexCli},!0),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${S.codexCli?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":S.codexCli,"aria-label":"Codex CLI 兼容模式",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${S.codexCli?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:["开启后应用 Codex CLI 实际支持的参数。支持查询参数覆盖:",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"codexCli=true"}),"。"]})]}),tt&&S.provider==="openai"&&s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"API 代理"}),s.jsx("button",{type:"button",onClick:()=>{gt||de({apiProxy:!S.apiProxy},!0)},disabled:gt,className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${he?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"} ${gt?"cursor-not-allowed opacity-70":""}`,role:"switch","aria-checked":he,"aria-label":"API 代理",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${he?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:gt?"当前部署已锁定 API 代理为开启,API URL 设置会被忽略。":"当前部署提供同源代理时默认开启,可手动关闭。开启后用于解决浏览器跨域限制,API URL 设置会被忽略。"})]}),s.jsxs("div",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"API Key"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{value:S.apiKey,onChange:k=>de({apiKey:k.target.value}),onBlur:k=>Se({apiKey:k.target.value}),type:j?"text":"password",placeholder:S.provider==="fal"?"FAL_KEY":"sk-...",className:"w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2.5 pr-10 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50"}),s.jsx("button",{type:"button",onClick:()=>P(k=>!k),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 transition-colors",tabIndex:-1,children:j?s.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}):s.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs text-gray-500 dark:text-gray-500",children:["支持通过查询参数覆盖:",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"?apiKey="})]})]}),S.provider==="openai"&&s.jsxs("div",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"API 接口"}),s.jsx(zr,{value:S.apiMode??Ct.apiMode,onChange:k=>{const B=k,re=S.model===At||S.model===ws?Bt(B):S.model;de({apiMode:B,model:re},!0)},options:[{label:"Images API (/v1/images)",value:"images"},{label:"Responses API (/v1/responses)",value:"responses"}],className:"w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50"}),s.jsxs("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs text-gray-500 dark:text-gray-500",children:["支持通过查询参数覆盖:",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"apiMode=images"})," 或 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"apiMode=responses"}),"。"]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"模型 ID"}),s.jsx("input",{value:S.model,onChange:k=>de({model:k.target.value}),onBlur:k=>Se({model:k.target.value}),type:"text",placeholder:S.provider==="fal"?on:Bt(S.apiMode??Ct.apiMode),className:"w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50"}),s.jsxs("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs text-gray-500 dark:text-gray-500",children:[S.provider==="fal"?s.jsxs(s.Fragment,{children:["当前适配 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:on}),"。"]}):ot?s.jsxs(s.Fragment,{children:["当前使用 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:ot.name}),"。"]}):(S.apiMode??Ct.apiMode)==="responses"?s.jsxs(s.Fragment,{children:["Responses API 需要使用支持 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"image_generation"})," 工具的文本模型,例如 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:ws}),"。"]}):s.jsxs(s.Fragment,{children:["Images API 需要使用 GPT Image 模型,例如 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:At}),"。"]}),S.provider==="openai"&&s.jsxs(s.Fragment,{children:["支持通过查询参数覆盖:",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"?model="}),"。"]})]})]}),ge&&s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"返回 Base64 图片数据"}),s.jsx("button",{type:"button",onClick:()=>de({responseFormatB64Json:!S.responseFormatB64Json},!0),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${S.responseFormatB64Json?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":!!S.responseFormatB64Json,"aria-label":"返回 Base64 图片数据",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${S.responseFormatB64Json?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:["开启后在请求体中追加 ",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"response_format: b64_json"}),",尝试使接口直接返回 Base64 编码的图片数据而非 URL。"]})]}),ge&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"请求超时 (秒)"}),s.jsx("input",{value:w,onChange:k=>v(k.target.value),onBlur:or,type:"number",min:10,max:600,className:"w-full rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50"})]})]}),T==="data"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-2xl bg-gray-50/80 p-4 border border-gray-200/60 dark:bg-white/[0.02] dark:border-white/[0.05] flex items-start gap-3",children:[s.jsx("svg",{className:"w-5 h-5 text-blue-500 shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})}),s.jsx("div",{className:"text-[13px] leading-relaxed text-gray-500 dark:text-gray-400",children:"所有的配置、任务记录和生成的图片均仅保存在您的浏览器本地(除非您使用的服务商存储了它们)。如果您需要清理浏览器站点数据、重置浏览器或使用其他设备,请先导出备份。"})]}),s.jsxs("div",{className:"rounded-2xl border border-gray-100 bg-white p-4 dark:border-white/[0.06] dark:bg-white/[0.02] space-y-4 shadow-sm",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(Xf,{className:"w-4 h-4 text-gray-700 dark:text-gray-300"}),s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"导出数据"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-3",children:[s.jsx(ur,{checked:Z,onChange:ee,label:"包含配置"}),s.jsx(ur,{checked:oe,onChange:ye,label:"包含任务和图片"})]}),s.jsx("button",{onClick:()=>Ef({exportConfig:Z,exportTasks:oe}),disabled:!Z&&!oe,className:"w-full rounded-xl bg-gray-100/80 px-4 py-2.5 text-sm font-medium text-gray-700 transition-all hover:bg-gray-200 hover:text-gray-900 disabled:opacity-50 disabled:hover:bg-gray-100/80 disabled:hover:text-gray-700 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white dark:disabled:hover:bg-white/[0.06] dark:disabled:hover:text-gray-300 flex items-center justify-center gap-2",children:"导出所选数据"})]}),s.jsxs("div",{className:"rounded-2xl border border-gray-100 bg-white p-4 dark:border-white/[0.06] dark:bg-white/[0.02] space-y-4 shadow-sm",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(Jf,{className:"w-4 h-4 text-gray-700 dark:text-gray-300"}),s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"导入数据"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-3",children:[s.jsx(ur,{checked:fe,onChange:be,label:"包含配置"}),s.jsx(ur,{checked:xe,onChange:ke,label:"包含任务和图片"})]}),s.jsx("button",{onClick:()=>l.current?.click(),disabled:!fe&&!xe||je,className:"w-full rounded-xl bg-gray-100/80 px-4 py-2.5 text-sm font-medium text-gray-700 transition-all hover:bg-gray-200 hover:text-gray-900 disabled:opacity-50 disabled:hover:bg-gray-100/80 disabled:hover:text-gray-700 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white dark:disabled:hover:bg-white/[0.06] dark:disabled:hover:text-gray-300 flex items-center justify-center gap-2",children:je?s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"导入中..."]}):"从 ZIP 导入所选数据"}),s.jsx("input",{ref:l,type:"file",accept:".zip",className:"hidden",onChange:De})]}),s.jsxs("div",{className:"rounded-2xl border border-red-100/50 bg-red-50/30 p-4 dark:border-red-500/10 dark:bg-red-500/5 space-y-4 shadow-sm",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(Ls,{className:"w-4 h-4 text-red-500/90 dark:text-red-400"}),s.jsx("h4",{className:"text-sm font-bold text-red-500/90 dark:text-red-400",children:"清除数据"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-3",children:[s.jsx(ur,{checked:ne,onChange:ve,label:"包含配置",tone:"danger"}),s.jsx(ur,{checked:_e,onChange:ft,label:"包含任务和图片",tone:"danger"})]}),s.jsx("button",{onClick:()=>i({title:"清空所选数据",message:"确定要清空所选的数据吗?此操作不可恢复。",action:()=>ct()}),disabled:!ne&&!_e,className:"w-full rounded-xl border border-red-200/60 bg-red-50/50 px-4 py-2.5 text-sm font-medium text-red-500 transition-all hover:bg-red-50 hover:border-red-200 hover:text-red-600 disabled:opacity-50 disabled:hover:bg-red-50/50 disabled:hover:border-red-200/60 disabled:hover:text-red-500 dark:border-red-500/15 dark:bg-red-500/5 dark:text-red-400 dark:hover:bg-red-500/10 dark:hover:border-red-500/30 dark:hover:text-red-300 dark:disabled:hover:bg-red-500/5 dark:disabled:hover:border-red-500/15 dark:disabled:hover:text-red-400",children:"清空所选数据"})]})]}),T==="about"&&s.jsxs("div",{className:"flex h-full min-h-[300px] flex-col items-center justify-center pb-8 px-6",children:[s.jsxs("a",{href:"https://github.com/CookSleep/gpt_image_playground",target:"_blank",rel:"noopener noreferrer",className:"group flex flex-col items-center outline-none",children:[s.jsx("div",{className:"mb-5 flex h-[88px] w-[88px] items-center justify-center rounded-full border border-gray-200/80 bg-gray-50/50 text-gray-800 transition-colors group-hover:bg-gray-100 dark:border-white/[0.08] dark:bg-white/[0.02] dark:text-gray-100 dark:group-hover:bg-white/[0.06]",children:s.jsx(Zf,{className:"h-11 w-11"})}),s.jsx("h4",{className:"text-[17px] font-bold text-gray-800 dark:text-gray-100",children:"GPT Image Playground"}),s.jsx("p",{className:"mt-1.5 text-[13px] text-gray-500 transition-colors group-hover:text-gray-700 dark:text-gray-400 dark:group-hover:text-gray-300",children:"@CookSleep"})]}),s.jsx("p",{className:"mt-8 mb-6 max-w-[360px] text-center text-[13px] leading-relaxed text-gray-500 dark:text-gray-400",children:"本项目的成长离不开每一位用户的使用、反馈、贡献与支持,感谢一路有你。"}),s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-3",children:[s.jsxs("a",{href:"https://github.com/CookSleep/gpt_image_playground/issues",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 whitespace-nowrap rounded-xl bg-gray-100/80 px-5 py-2.5 text-sm font-medium text-gray-700 transition-all hover:bg-gray-200 hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white",children:[s.jsx("svg",{className:"h-4 w-4 opacity-70",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"})}),"反馈问题"]}),s.jsxs("a",{href:"https://www.ifdian.net/a/cooksleep",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 whitespace-nowrap rounded-xl bg-gray-100/80 px-5 py-2.5 text-sm font-medium text-gray-700 transition-all hover:bg-gray-200 hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white",children:[s.jsx("svg",{className:"h-4 w-4 opacity-70",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"})}),"赞助作者"]})]})]})]})})]})]}),Q&&fr.createPortal(s.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in",onClick:()=>{L(!1),q(null)}}),s.jsxs("div",{className:"relative z-10 w-full max-w-md rounded-3xl border border-white/50 bg-white/95 p-5 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10 flex flex-col h-[85vh] sm:h-[680px] max-h-[90vh] overflow-hidden",children:[s.jsxs("div",{className:"mb-5 flex items-center justify-between gap-4 shrink-0",children:[s.jsx("h3",{className:"text-base font-bold text-gray-800 dark:text-gray-100",children:H?"编辑自定义服务商":"创建自定义服务商"}),s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("button",{type:"button",onClick:()=>{L(!1),q(null)},className:"rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(wr,{className:"h-5 w-5"})})})]}),s.jsxs("div",{ref:b,className:"flex-1 flex flex-col min-h-0 px-1 -mx-1 pb-2",children:[s.jsxs("div",{className:"mb-6 shrink-0 rounded-2xl bg-gray-50/80 p-4 border border-gray-200/60 dark:bg-white/[0.02] dark:border-white/[0.05]",children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5 text-sm font-medium text-gray-800 dark:text-gray-200",children:[s.jsx("svg",{className:"h-4 w-4 text-blue-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"AI 一键生成与导入"]}),s.jsx("div",{"data-selectable-text":!0,className:"mb-4 text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:"复制提示词发给 LLM,可根据 API 文档自动生成完整的配置(包含服务商、模型、URL 等)。复制 LLM 输出的 JSON 后,点击“从剪贴板粘贴并导入”即可一键生效。"}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"relative inline-flex",children:[s.jsxs("button",{type:"button",onClick:cs,"aria-label":"复制用于生成完整导入 JSON 的 LLM 提示词",onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),onFocus:()=>z(!0),onBlur:()=>z(!1),onTouchStart:()=>{gr(),x.current=window.setTimeout(()=>{z(!0),x.current=null},450)},onTouchEnd:gr,onTouchCancel:gr,className:"flex items-center gap-1.5 rounded-xl bg-white px-3 py-2 text-xs font-medium text-gray-700 shadow-sm border border-gray-200/80 transition hover:bg-gray-50 hover:text-gray-900 dark:bg-white/[0.05] dark:border-white/[0.08] dark:text-gray-300 dark:hover:bg-white/[0.08] dark:hover:text-white",children:[s.jsx(js,{className:"h-3.5 w-3.5"}),"复制生成提示词"]}),s.jsx(jt,{visible:O,className:"w-56 whitespace-normal text-center",children:"生成完整的服务商和配置信息,包含模型和接口地址,导入后只需填入 API Key。"})]}),s.jsx("button",{type:"button",onClick:ds,disabled:Ke,className:"flex items-center gap-1.5 rounded-xl bg-white px-3 py-2 text-xs font-medium text-gray-700 shadow-sm border border-gray-200/80 transition hover:bg-gray-50 hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-white/[0.05] dark:border-white/[0.08] dark:text-gray-300 dark:hover:bg-white/[0.08] dark:hover:text-white",children:Ke?s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"w-3.5 h-3.5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"导入中..."]}):"从剪贴板粘贴并导入"})]})]}),s.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:s.jsxs("label",{className:"flex-1 flex flex-col min-h-0",children:[s.jsx("span",{className:"mb-1 shrink-0 block text-xs text-gray-500 dark:text-gray-400",children:"手动编辑 (仅接口映射 Manifest)"}),s.jsx("textarea",{value:F.json,onChange:k=>bn({json:k.target.value}),spellCheck:!1,className:"flex-1 min-h-[150px] w-full resize-none rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 font-mono text-xs leading-relaxed text-gray-700 outline-none transition focus:border-blue-300 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-200 dark:focus:border-blue-500/50 custom-scrollbar"})]})}),A&&s.jsx("div",{"data-selectable-text":!0,className:"shrink-0 mt-2 rounded-lg bg-red-50 px-3 py-2 text-xs text-red-500 dark:bg-red-500/10 dark:text-red-300",children:A})]}),s.jsxs("div",{className:"mt-4 flex justify-end gap-2 shrink-0",children:[s.jsx("button",{type:"button",onClick:()=>{L(!1),q(null)},className:"rounded-xl bg-gray-100 px-4 py-2 text-sm text-gray-600 transition hover:bg-gray-200 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1]",children:"取消"}),s.jsx("button",{type:"button",onClick:Gr,className:"rounded-xl bg-blue-500 px-4 py-2 text-sm font-medium text-white transition hover:bg-blue-600",children:H?"保存修改":"创建并使用"})]})]})]}),document.body),Te&&fr.createPortal(s.jsx("div",{className:"fixed pointer-events-none z-[110] flex items-center justify-between gap-2 rounded-xl bg-white/95 px-3 py-2 text-xs text-gray-700 shadow-xl ring-1 ring-black/5 backdrop-blur-xl dark:bg-gray-900/95 dark:text-gray-300 dark:ring-white/10",style:{left:Te.x-Te.offsetX,top:Te.y-Te.offsetY,width:Te.width,minHeight:Te.height},children:s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[s.jsx(Ds,{className:"h-3.5 w-3.5 shrink-0 text-gray-400 dark:text-gray-500"}),s.jsx("span",{className:"min-w-0 truncate",children:Te.label}),s.jsx("span",{className:"shrink-0 rounded bg-gray-100 px-1.5 py-0.5 text-[10px] text-gray-500 dark:bg-white/[0.08] dark:text-gray-400",children:Te.providerLabel})]})}),document.body),mt&&fr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[110] flex items-center justify-center p-4",onClick:()=>nt(null),children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{className:"relative bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] rounded-3xl shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] max-w-sm w-full p-6 z-10 ring-1 ring-black/5 dark:ring-white/10 animate-confirm-in",onClick:k=>k.stopPropagation(),children:[s.jsx("button",{type:"button",onClick:()=>nt(null),className:"absolute right-4 top-4 shrink-0 rounded-full p-1.5 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(wr,{className:"h-5 w-5"})}),s.jsxs("h3",{className:"mb-3 pr-8 flex items-start gap-2.5 text-base font-bold text-gray-800 dark:text-gray-100 leading-snug",children:[s.jsx(Jt,{className:"h-5 w-5 shrink-0 text-blue-500 mt-0.5"}),s.jsxs("span",{children:["复制导入配置「",mt.name,"」的 URL"]})]}),s.jsx("div",{className:"text-[13px] text-gray-500 dark:text-gray-400 mb-5 leading-relaxed",children:"是否包含 API Key?如果选择「不包含」,可额外配置是否使用 New API 变量。"}),!ht.includeApiKey&&s.jsxs("div",{className:"mb-6 rounded-2xl bg-gray-50/80 p-4 dark:bg-white/[0.03] ring-1 ring-black/5 dark:ring-white/5",children:[s.jsx("div",{className:"text-[13px] font-bold text-gray-700 dark:text-gray-300 mb-3.5",children:"New API 变量配置"}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(ur,{checked:ht.useNewApiAddress,onChange:k=>M({useNewApiAddress:k}),label:s.jsxs(s.Fragment,{children:["使用 ",s.jsx("code",{className:"mx-0.5 rounded bg-gray-100 px-1.5 py-0.5 text-[0.85em] font-mono text-gray-700 dark:bg-white/[0.08] dark:text-gray-200",children:"{address}"})," (不含 /v1)"]})}),s.jsx(ur,{checked:ht.useNewApiKey,onChange:k=>M({useNewApiKey:k}),label:s.jsxs(s.Fragment,{children:["使用 ",s.jsx("code",{className:"mx-0.5 rounded bg-gray-100 px-1.5 py-0.5 text-[0.85em] font-mono text-gray-700 dark:bg-white/[0.08] dark:text-gray-200",children:"{key}"})]})}),s.jsx(ur,{checked:ht.useNewApiModel,onChange:k=>M({useNewApiModel:k}),label:s.jsxs(s.Fragment,{children:["使用 ",s.jsx("code",{className:"mx-0.5 rounded bg-gray-100 px-1.5 py-0.5 text-[0.85em] font-mono text-gray-700 dark:bg-white/[0.08] dark:text-gray-200",children:"{model}"})]})})]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{onClick:()=>{const k={...ht,includeApiKey:!1};te(mt,k)},className:"flex-1 py-2 rounded-xl border border-gray-200 dark:border-white/[0.08] text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/[0.06] transition",children:"不包含"}),s.jsx("button",{onClick:()=>{const k={...ht,includeApiKey:!0};te(mt,k)},className:"flex-1 py-2 rounded-xl bg-blue-500 text-white text-sm font-medium hover:bg-blue-600 transition shadow-sm shadow-blue-500/20",children:"包含 API Key"})]})]})]}),document.body)]})}function Im(e){return e.split(/(`[^`]+`|「[^」]+」)/g).map((t,r)=>t.startsWith("`")&&t.endsWith("`")?s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 text-[0.85em] text-gray-700 dark:bg-white/[0.06] dark:text-gray-200",children:t.slice(1,-1)},r):t.startsWith("「")&&t.endsWith("」")?s.jsx("strong",{className:"font-semibold text-gray-700 dark:text-gray-200",children:t},r):t)}function Pm(){const e=E(u=>u.confirmDialog),t=E(u=>u.setConfirmDialog),[r,n]=g.useState(!0);g.useEffect(()=>{const u=e?.minConfirmDelayMs??0;if(!e||u<=0){n(!0);return}n(!1);const h=window.setTimeout(()=>n(!0),u);return()=>window.clearTimeout(h)},[e]);const a=()=>{r&&t(null)},o=()=>{e?.cancelAction?.(),a()};if(Jr(!!e&&r,a),Mr(!!e),!e)return null;const i=e.title.includes("删除")||e.title.includes("清空"),c=e.tone??(i?"danger":void 0),l=c==="warning"?"bg-orange-500 hover:bg-orange-600":c==="danger"?"bg-red-500 hover:bg-red-600":"bg-blue-500 hover:bg-blue-600",f=e.confirmText??(i?"确认删除":"确认"),m=e.cancelText??"取消";return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[110] flex items-center justify-center p-4",onClick:a,children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{className:"relative bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] rounded-3xl shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] max-w-sm w-full p-6 z-10 ring-1 ring-black/5 dark:ring-white/10 animate-confirm-in",onClick:u=>u.stopPropagation(),children:[s.jsxs("h3",{className:"mb-2 flex items-center gap-2 text-base font-bold text-gray-800 dark:text-gray-100",children:[e.icon==="info"&&s.jsxs("svg",{className:"h-5 w-5 shrink-0 text-blue-500",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("path",{d:"M12 8h.01"})]}),e.icon==="copy"&&s.jsx(Jt,{className:"h-5 w-5 shrink-0 text-blue-500"}),e.title]}),s.jsx("p",{className:`text-sm text-gray-500 dark:text-gray-400 mb-6 leading-relaxed whitespace-pre-line ${e.messageAlign==="center"?"text-center":""}`,children:Im(e.message)}),s.jsxs("div",{className:"flex gap-2",children:[e.showCancel!==!1&&s.jsx("button",{onClick:o,className:"flex-1 py-2 rounded-lg border border-gray-200 dark:border-white/[0.08] text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/[0.06] transition",children:m}),s.jsx("button",{onClick:()=>{r&&(e.action(),t(null))},disabled:!r,className:`flex-1 py-2 rounded-lg text-white text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60 ${l}`,children:f})]})]})]})}function Sm(){const e=E(r=>r.toast);if(!e)return null;const t=()=>{switch(e.type){case"success":return s.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-green-100 dark:bg-green-900/50 text-green-600 dark:text-green-400",children:s.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M5 13l4 4L19 7"})})});case"error":return s.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-red-100 dark:bg-red-900/50 text-red-600 dark:text-red-400",children:s.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M6 18L18 6M6 6l12 12"})})});default:return s.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-400",children:s.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})})}};return s.jsx("div",{className:"fixed bottom-24 left-1/2 z-[120] pointer-events-none toast-enter",children:s.jsxs("div",{className:"flex items-center gap-2.5 w-max max-w-[calc(100vw-32px)] sm:max-w-[min(28rem,60vw)] px-5 py-3.5 bg-white/95 dark:bg-gray-900/95 backdrop-blur-xl border border-gray-200/60 dark:border-white/[0.08] rounded-full shadow-[0_8px_30px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_30px_rgb(0,0,0,0.3)] ring-1 ring-black/5 dark:ring-white/10 text-sm font-medium text-gray-700 dark:text-gray-300",children:[s.jsx("span",{className:"flex-shrink-0",children:t()}),s.jsx("span",{className:"leading-5 whitespace-pre-line text-center",children:e.message})]})})}const Nm=1920,Tm=16;function Ui(e,t){return Math.max(t,Math.floor(e/t)*t)}function Em(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(String(n.result)),n.onerror=()=>r(n.error??new Error("图片导出失败")),n.readAsDataURL(e)})}function Cm(e,t,r=Nm,n=Tm){const a=Math.max(e,t);if(a<=r)return{width:e,height:t,scale:1,wasResized:!1};const o=r/a;return{width:Ui(e*o,n),height:Ui(t*o,n),scale:o,wasResized:!0}}async function Mm(e){const t=await Sr(e),r=Cm(t.naturalWidth,t.naturalHeight),n=/^data:image\/png(?:[;,]|$)/i.test(e);if(!r.wasResized&&n)return{...r,dataUrl:e,originalWidth:t.naturalWidth,originalHeight:t.naturalHeight,wasConvertedToPng:!1};const a=document.createElement("canvas");a.width=r.width,a.height=r.height;const o=a.getContext("2d");if(!o)throw new Error("当前浏览器不支持 Canvas");o.drawImage(t,0,0,r.width,r.height);const i=await so(a,"image/png");return{...r,dataUrl:await Em(i),originalWidth:t.naturalWidth,originalHeight:t.naturalHeight,wasConvertedToPng:!0}}function Rm(e,t,r){const n=[];let a=!1;for(const o of e){if(o.id===t){a||(n.push(r),a=!0);continue}if(o.id===r.id){a||(n.push(r),a=!0);continue}n.push(o)}return a?n:[r,...n]}const Hr=1,yo=6;function dn(e,t,r){return Math.min(r,Math.max(t,e))}function wo(e,t){const r=dn(e.scale,Hr,yo);return r===Hr?{scale:r,x:0,y:0}:{scale:r,x:dn(e.x,t.width*(1-r),0),y:dn(e.y,t.height*(1-r),0)}}function xc(e,t,r,n){const a={x:(t.x-e.x)/e.scale,y:(t.y-e.y)/e.scale},o=dn(r,Hr,yo);return wo({scale:o,x:t.x-a.x*o,y:t.y-a.y*o},n)}function Am(e){const t={x:(e.startCentroid.x-e.startTransform.x)/e.startTransform.scale,y:(e.startCentroid.y-e.startTransform.y)/e.startTransform.scale},r=e.startDistance>0?e.nextDistance/e.startDistance:1,n=dn(e.startTransform.scale*r,Hr,yo);return wo({scale:n,x:e.nextCentroid.x-t.x*n,y:e.nextCentroid.y-t.y*n},e.viewportSize)}function _m(e,t,r){return{x:(t.x-e.left)/e.width*r.width,y:(t.y-e.top)/e.height*r.height}}function Lm(e,t,r){if(!r||e.width<=0||e.height<=0)return{scale:Hr,x:0,y:0};const n=t.height*.42,a=dn(n/e.height,Hr,3);return xc({scale:Hr,x:0,y:0},{x:e.width/2,y:e.height/2},a,e)}const An={scale:1,x:0,y:0};function Oi(e,t){return _m(e.getBoundingClientRect(),{x:t.clientX,y:t.clientY},{width:e.width,height:e.height})}function Bi(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function $i(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function Fi(e){const t=Array.from(e.values());return t.length>=2?[t[0],t[1]]:null}function va(e){const t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("当前浏览器不支持 Canvas");t.globalCompositeOperation="source-over",t.clearRect(0,0,e.width,e.height),t.fillStyle="#fff",t.fillRect(0,0,e.width,e.height)}function Dm(e,t){const r=e.naturalWidth/e.naturalHeight,n=t.width/t.height;if(Math.abs(r-n)>.001)throw new Error("遮罩尺寸与当前图片不一致");const a=t.getContext("2d",{willReadFrequently:!0});if(!a)throw new Error("当前浏览器不支持 Canvas");a.clearRect(0,0,t.width,t.height),a.imageSmoothingEnabled=!0,a.imageSmoothingQuality="high",a.drawImage(e,0,0,t.width,t.height)}function Um(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(String(n.result)),n.onerror=()=>r(n.error??new Error("图片导出失败")),n.readAsDataURL(e)})}function Om(){const e=E(M=>M.maskEditorImageId),t=E(M=>M.setMaskEditorImageId),r=E(M=>M.maskDraft),n=E(M=>M.setMaskDraft),a=E(M=>M.clearMaskDraft),o=E(M=>M.setConfirmDialog),i=E(M=>M.showToast),c=g.useRef(null),l=g.useRef(null),f=g.useRef(null),m=g.useRef(null),u=g.useRef(null),h=g.useRef(null),x=g.useRef(null),y=g.useRef(null),b=g.useRef(null),d=g.useRef(null),p=g.useRef(null),w=g.useRef(null),v=g.useRef(new Map),j=g.useRef(null),P=g.useRef(null),C=g.useRef([]),$=g.useRef([]),R=g.useRef(null),N=g.useRef(0),Q=g.useRef(0),L=g.useRef(0),H=g.useRef(An),[q,F]=g.useState(""),[Y,A]=g.useState(null),[U,J]=g.useState("brush"),[D,W]=g.useState(64),[K,O]=g.useState(!1),[z,T]=g.useState(An),[V,Z]=g.useState(!1),[ee,oe]=g.useState(!1),[ye,fe]=g.useState({undo:0,redo:0}),[be,xe]=g.useState(null),[ke,ne]=g.useState(!1),[ve,_e]=g.useState(!1),[ft,je]=g.useState(!1),[Oe,Ke]=g.useState(null),[It,rt]=g.useState(!1),vt=()=>{ee||t(null)};Jr(!!e,vt),Mr(!!e),g.useEffect(()=>()=>{d.current!=null&&window.clearTimeout(d.current)},[]);const Ye=()=>rt(!0),ze=()=>{rt(!1),Ie()},Ie=()=>{d.current!=null&&(window.clearTimeout(d.current),d.current=null)},Ce=()=>{d.current=window.setTimeout(()=>{rt(!0),d.current=null},450)},Le=()=>{o({title:"移除遮罩",message:"确定要撤销对这张图片的所有涂抹并移除遮罩吗?",tone:"danger",action:()=>{a(),t(null),i("已移除遮罩","success")}})};function He(M){const X=h.current,te=X?wo(M,{width:X.clientWidth,height:X.clientHeight}):M;H.current=te,T(te)}function Te(){const M=h.current,X=u.current,te=window.matchMedia("(max-width: 1023px)").matches;if(!M||!X){He(An);return}He(Lm({width:M.clientWidth,height:M.clientHeight},{width:X.clientWidth,height:X.clientHeight},te))}function Ve(){if(p.current==null)return;const M=C.current.pop();M&&S(M),p.current=null,w.current=null,nt()}function Je(){const M=Fi(v.current),X=h.current;if(!M||!X)return;const te=X.getBoundingClientRect(),ie=$i(M[0],M[1]);j.current={startTransform:H.current,startCentroid:{x:ie.x-te.left,y:ie.y-te.top},startDistance:Bi(M[0],M[1])}}function mt(){const M=Fi(v.current),X=j.current,te=h.current;if(!M||!X||!te)return;const ie=te.getBoundingClientRect(),me=$i(M[0],M[1]);He(Am({startTransform:X.startTransform,startCentroid:X.startCentroid,nextCentroid:{x:me.x-ie.left,y:me.y-ie.top},startDistance:X.startDistance,nextDistance:Bi(M[0],M[1]),viewportSize:{width:te.clientWidth,height:te.clientHeight}}))}function nt(){fe({undo:C.current.length,redo:$.current.length})}function ht(){const M=f.current,X=l.current;if(!M||!X)return;const te=X.getContext("2d");te&&(R.current=null,te.save(),te.clearRect(0,0,X.width,X.height),te.globalCompositeOperation="source-over",te.fillStyle="rgba(59, 130, 246, 0.58)",te.fillRect(0,0,X.width,X.height),te.globalCompositeOperation="destination-out",te.drawImage(M,0,0),te.restore())}function at(){R.current==null&&(R.current=window.requestAnimationFrame(ht))}function Xe(M){const X=m.current,te=u.current,ie=h.current,me=f.current,de=X?.getContext("2d");if(!X||!de||!te||!ie||!me)return;const Se=window.devicePixelRatio||1,We=te.clientWidth,or=te.clientHeight;if((X.width!==Math.round(We*Se)||X.height!==Math.round(or*Se))&&(X.width=Math.round(We*Se),X.height=Math.round(or*Se)),de.setTransform(Se,0,0,Se,0,0),de.clearRect(0,0,We,or),!M)return;const De=H.current.scale,ct=te.getBoundingClientRect(),dt=ie.getBoundingClientRect(),Nt=dt.left-ct.left,Wt=dt.top-ct.top,pt=Nt+M.x/me.width*ie.clientWidth*De+H.current.x,xt=Wt+M.y/me.height*ie.clientHeight*De+H.current.y,Rr=D/2/me.width*ie.clientWidth*De;de.save(),de.lineWidth=1,de.beginPath(),de.arc(pt,xt,Rr,0,Math.PI*2),de.strokeStyle="rgba(255, 255, 255, 0.9)",de.stroke(),de.strokeStyle="rgba(0, 0, 0, 0.4)",de.beginPath(),de.arc(pt,xt,Rr+1,0,Math.PI*2),de.stroke(),de.beginPath(),de.arc(pt,xt,Math.max(0,Rr-1),0,Math.PI*2),de.stroke();const Re=5;de.strokeStyle="rgba(255, 255, 255, 0.95)",de.beginPath(),de.moveTo(pt-Re,xt),de.lineTo(pt+Re,xt),de.moveTo(pt,xt-Re),de.lineTo(pt,xt+Re),de.stroke(),de.strokeStyle="rgba(0, 0, 0, 0.55)",de.beginPath(),de.moveTo(pt-Re,xt),de.lineTo(pt+Re,xt),de.moveTo(pt,xt-Re),de.lineTo(pt,xt+Re),de.stroke(),de.restore()}function tt(){const M=h.current,X=f.current;if(!M||!X)return null;const te=H.current;return{x:(M.clientWidth/2-te.x)/te.scale/M.clientWidth*X.width,y:(M.clientHeight/2-te.y)/te.scale/M.clientHeight*X.height}}function gt(){const M=f.current,X=M?.getContext("2d",{willReadFrequently:!0});!M||!X||(C.current.push(X.getImageData(0,0,M.width,M.height)),C.current.length>40&&C.current.shift(),$.current=[],nt())}function S(M){const X=f.current,te=X?.getContext("2d",{willReadFrequently:!0});!X||!te||(te.putImageData(M,0,0),at())}function he(M,X=U){const te=f.current,ie=te?.getContext("2d");!te||!ie||(ie.save(),ie.globalCompositeOperation=X==="brush"?"destination-out":"source-over",ie.fillStyle="#fff",ie.beginPath(),ie.arc(M.x,M.y,D/2,0,Math.PI*2),ie.fill(),ie.restore(),at())}function Pe(M,X,te=U){const ie=f.current,me=ie?.getContext("2d");!ie||!me||(me.save(),me.globalCompositeOperation=te==="brush"?"destination-out":"source-over",me.strokeStyle="#fff",me.lineWidth=D,me.lineCap="round",me.lineJoin="round",me.beginPath(),me.moveTo(M.x,M.y),me.lineTo(X.x,X.y),me.stroke(),me.restore(),at())}if(g.useEffect(()=>{if(!e){L.current=0;return}const M=Q.current+1;return Q.current=M,L.current=M,()=>{L.current===M&&(L.current=0)}},[e]),g.useEffect(()=>{if(!e){R.current!=null&&(window.cancelAnimationFrame(R.current),R.current=null),F(""),A(null),Z(!1),v.current.clear(),j.current=null,P.current=null,je(!1),H.current=An,T(An),C.current=[],$.current=[],nt();return}const M=e;let X=!1;Z(!0),F(""),A(null),C.current=[],$.current=[],nt();async function te(){try{const ie=await Ot(M);if(X)return;if(!ie){i("图片已不存在,无法编辑遮罩","error"),t(null);return}const me=await Mm(ie),de=await Sr(me.dataUrl);if(X)return;const Se={width:me.width,height:me.height},We=c.current,or=l.current,De=f.current;if(!We||!or||!De)return;for(const dt of[We,or,De])dt.width=Se.width,dt.height=Se.height;const ct=We.getContext("2d");if(!ct)throw new Error("当前浏览器不支持 Canvas");if(ct.clearRect(0,0,We.width,We.height),ct.drawImage(de,0,0),va(De),r?.targetImageId===M)try{const dt=await Sr(r.maskDataUrl);if(X)return;Dm(dt,De)}catch(dt){va(De),i(`遮罩草稿加载失败,已重置为空白遮罩:${dt instanceof Error?dt.message:String(dt)}`,"error")}at(),F(me.dataUrl),A(Se),me.wasResized&&i(`已为遮罩编辑按官方要求调整图片尺寸:
106
+ ${me.originalWidth}×${me.originalHeight} → ${me.width}×${me.height}`,"info"),requestAnimationFrame(()=>Te())}catch(ie){X||(i(ie instanceof Error?ie.message:String(ie),"error"),t(null))}finally{X||Z(!1)}}return te(),()=>{X=!0,R.current!=null&&(window.cancelAnimationFrame(R.current),R.current=null),p.current=null,w.current=null,v.current.clear(),j.current=null,P.current=null,je(!1)}},[e,r,t,i]),g.useEffect(()=>{Xe(ve?null:K&&!ke&&Y?tt():be)},[D,z,be,ke,K,Y,ve]),g.useEffect(()=>{if(!e)return;const M=ie=>{ie.altKey&&_e(!0)},X=ie=>{ie.key==="Alt"&&_e(!1)},te=()=>_e(!1);return window.addEventListener("keydown",M),window.addEventListener("keyup",X),window.addEventListener("blur",te),()=>{window.removeEventListener("keydown",M),window.removeEventListener("keyup",X),window.removeEventListener("blur",te)}},[e]),g.useEffect(()=>{if(!K)return;const M=X=>{const te=x.current,ie=b.current;te?.contains(X.target)||ie?.contains(X.target)||(O(!1),Ke(null))};return document.addEventListener("pointerdown",M,!0),()=>document.removeEventListener("pointerdown",M,!0)},[K]),g.useEffect(()=>{const M=h.current;if(!M||typeof ResizeObserver>"u")return;const X=new ResizeObserver(()=>{He(H.current)});return X.observe(M),()=>X.disconnect()},[Y]),!e)return null;const ge=!!(q&&Y&&!V),Me=ye.undo>0&&ge&&!ee,ot=ye.redo>0&&ge&&!ee,Pt=z.scale>1.01||Math.abs(z.x)>1||Math.abs(z.y)>1,_t=M=>{if(!ge||ee||M.pointerType!=="touch"&&M.button!==0)return;M.preventDefault(),O(!1),Ke(null);const X=M.currentTarget;if(M.altKey){X.hasPointerCapture(M.pointerId)||X.setPointerCapture(M.pointerId),P.current={pointerId:M.pointerId,startPoint:{x:M.clientX,y:M.clientY},startTransform:H.current},je(!0),Xe(null);return}if(v.current.set(M.pointerId,{x:M.clientX,y:M.clientY}),X.hasPointerCapture(M.pointerId)||X.setPointerCapture(M.pointerId),v.current.size>=2){Ve(),Je();return}p.current=M.pointerId,gt();const te=Oi(X,M);w.current=te,he(te)},sr=M=>{const X=Oi(M.currentTarget,M);M.pointerType!=="touch"&&(ne(!0),xe(X),Xe(M.altKey||ve?null:X));const te=P.current;if(te?.pointerId===M.pointerId){if(!h.current)return;M.preventDefault(),He({scale:te.startTransform.scale,x:te.startTransform.x+M.clientX-te.startPoint.x,y:te.startTransform.y+M.clientY-te.startPoint.y});return}if(v.current.has(M.pointerId)&&v.current.set(M.pointerId,{x:M.clientX,y:M.clientY}),j.current&&v.current.size>=2){M.preventDefault(),mt();return}p.current!==M.pointerId||!w.current||!ge||ee||(M.preventDefault(),Pe(w.current,X),w.current=X)},it=()=>{ne(!1),xe(null),Xe(null)},Bt=M=>{if(!M.altKey||!ge||ee)return;const X=h.current;if(!X)return;M.preventDefault();const te=X.getBoundingClientRect(),ie={x:M.clientX-te.left,y:M.clientY-te.top},me=Math.exp(-M.deltaY*.002);He(xc(H.current,ie,H.current.scale*me,{width:X.clientWidth,height:X.clientHeight}))},St=M=>{M.currentTarget.hasPointerCapture(M.pointerId)&&M.currentTarget.releasePointerCapture(M.pointerId),v.current.delete(M.pointerId),j.current&&(v.current.size>=2?Je():j.current=null),P.current?.pointerId===M.pointerId&&(P.current=null,je(!1)),p.current===M.pointerId&&(p.current=null,w.current=null,be&&Xe(be))},lt=()=>{const M=f.current,X=M?.getContext("2d",{willReadFrequently:!0}),te=C.current.pop();!M||!X||!te||($.current.push(X.getImageData(0,0,M.width,M.height)),S(te),nt())},ar=()=>{const M=f.current,X=M?.getContext("2d",{willReadFrequently:!0}),te=$.current.pop();!M||!X||!te||(C.current.push(X.getImageData(0,0,M.width,M.height)),S(te),nt())},hr=()=>{const M=f.current;!M||!ge||ee||(gt(),va(M),at())},gr=async()=>{const M=f.current,X=L.current;if(!M||!q||!e||!ge||ee||!X)return;const te=++N.current,ie=e;try{oe(!0);const me=await so(M,"image/png"),de=await Um(me),Se=await Ir(q,"upload");if(N.current!==te||L.current!==X||E.getState().maskEditorImageId!==ie)return;const We=E.getState();We.setInputImages(Rm(We.inputImages,ie,{id:Se,dataUrl:q}),{equivalentImageIds:{[ie]:Se}}),n({targetImageId:Se,maskDataUrl:de,updatedAt:Date.now()}),t(null),i("遮罩已保存","success")}catch(me){if(N.current!==te||L.current!==X||E.getState().maskEditorImageId!==ie)return;i(me instanceof Error?me.message:String(me),"error")}finally{N.current===te&&oe(!1)}},qe=()=>{const M=y.current?.getBoundingClientRect();M&&(ne(!1),xe(null),Y&&Xe(tt()),Ke({left:M.left+M.width/2,bottom:window.innerHeight-M.top+8}),O(X=>!X))};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[80] flex flex-col bg-gray-50 dark:bg-gray-900 animate-modal-in",children:[s.jsxs("div",{className:"flex-none flex items-center justify-between px-4 py-3 border-b border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-950 z-20",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{onClick:vt,disabled:ee,className:"p-2 -ml-2 text-gray-500 hover:bg-gray-100 rounded-lg dark:text-gray-400 dark:hover:bg-gray-800 transition",title:"取消",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),s.jsxs("div",{className:"relative flex items-center gap-1.5",children:[s.jsx("h2",{className:"text-sm font-medium text-gray-700 dark:text-gray-200",id:"mask-editor-title",children:"编辑遮罩"}),s.jsx("button",{type:"button",onClick:Ye,onMouseEnter:Ye,onMouseLeave:ze,onTouchStart:Ce,onTouchEnd:Ie,onTouchCancel:ze,className:"flex h-6 w-6 items-center justify-center rounded-full text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-300","aria-label":"遮罩编辑说明",title:"遮罩编辑说明",children:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),It&&s.jsxs("div",{className:"absolute left-0 top-full mt-2 w-64 rounded-xl border border-gray-200/80 bg-white px-3 py-2 text-xs leading-5 text-gray-600 shadow-lg dark:border-white/[0.08] dark:bg-gray-900 dark:text-gray-300",children:[s.jsx("div",{className:"absolute -top-1.5 left-16 h-3 w-3 rotate-45 border-l border-t border-gray-200/80 bg-white dark:border-white/[0.08] dark:bg-gray-900"}),"根据官方文档说明,此功能仅基于提示词,无法完全控制模型编辑区域"]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r?.targetImageId===e&&s.jsx("button",{onClick:Le,className:"flex h-8 items-center gap-1.5 px-4 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition",children:"移除遮罩"}),s.jsx("button",{onClick:gr,disabled:!ge||ee,className:"flex h-8 items-center gap-1.5 px-4 text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 rounded-lg disabled:opacity-50 transition",children:ee?"保存中...":"保存"})]})]}),s.jsxs("div",{ref:u,className:"flex-1 relative flex items-center justify-center overflow-hidden bg-gray-100/50 dark:bg-black/50 p-0 pb-[76px] sm:p-6 sm:pb-[100px]",style:{containerType:"size"},children:[V&&s.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-white/50 text-sm text-gray-500 backdrop-blur-sm dark:bg-gray-900/50 dark:text-gray-300",children:"正在载入图片..."}),s.jsx("div",{ref:h,className:"relative max-h-full max-w-full sm:rounded-xl shadow-inner sm:ring-1 ring-black/5 touch-none dark:bg-black/50 dark:ring-white/5",onWheel:Bt,style:{aspectRatio:Y?`${Y.width} / ${Y.height}`:"1 / 1",width:Y?`min(100%, 100cqh * ${Y.width/Y.height})`:"520px",maxHeight:"100%"},children:s.jsxs("div",{className:"absolute inset-0 will-change-transform",style:{transform:`matrix(${z.scale}, 0, 0, ${z.scale}, ${z.x}, ${z.y})`,transformOrigin:"0 0"},children:[s.jsx("canvas",{ref:c,className:"absolute inset-0 h-full w-full"}),s.jsx("canvas",{ref:l,className:"absolute inset-0 h-full w-full pointer-events-none"}),s.jsx("canvas",{ref:f,className:"absolute inset-0 h-full w-full touch-none select-none opacity-0",style:{cursor:ft?"grabbing":ve?"grab":be?"none":"crosshair"},onPointerDown:_t,onPointerMove:sr,onPointerUp:St,onPointerCancel:St,onLostPointerCapture:St,onPointerLeave:it})]})}),s.jsx("canvas",{ref:m,className:"absolute inset-0 h-full w-full pointer-events-none"})]}),s.jsx("div",{className:"absolute bottom-4 sm:bottom-8 left-1/2 -translate-x-1/2 flex items-center justify-center z-20 pointer-events-none w-full px-2 sm:px-4",children:s.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 px-2 sm:px-3 py-1.5 sm:py-2 bg-white/95 dark:bg-[#0f0f0f]/95 backdrop-blur-md border border-gray-200/80 dark:border-white/5 rounded-2xl sm:rounded-[1.25rem] shadow-2xl pointer-events-auto",children:[s.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-3",children:[s.jsxs("div",{className:"flex items-center bg-gray-100/80 dark:bg-[#232325]/80 p-1 rounded-xl sm:rounded-[14px]",children:[s.jsx("button",{className:`p-2 sm:p-2.5 rounded-lg sm:rounded-xl transition-all ${U==="brush"?"bg-white shadow-sm text-blue-500 dark:bg-[#323338] dark:text-blue-400 dark:shadow-none":"text-gray-500 hover:text-gray-700 dark:text-[#8a8a8e] dark:hover:text-gray-200"}`,onClick:()=>J("brush"),disabled:!ge||ee,title:"画笔",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"})})}),s.jsx("button",{className:`p-2 sm:p-2.5 rounded-lg sm:rounded-xl transition-all ${U==="eraser"?"bg-white shadow-sm text-blue-500 dark:bg-[#323338] dark:text-blue-400 dark:shadow-none":"text-gray-500 hover:text-gray-700 dark:text-[#8a8a8e] dark:hover:text-gray-200"}`,onClick:()=>J("eraser"),disabled:!ge||ee,title:"橡皮",children:s.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsxs("g",{transform:"translate(0, 1) rotate(-45 12 12)",children:[s.jsx("path",{fill:"currentColor",d:"M4 10a2 2 0 0 1 2-2h7v8H6a2 2 0 0 1-2-2z"}),s.jsx("rect",{x:"4",y:"8",width:"16",height:"8",rx:"2"})]}),s.jsx("path",{d:"M8 21h12"})]})})]}),s.jsx("div",{ref:x,className:"relative flex items-center justify-center",children:s.jsx("button",{ref:y,onClick:qe,className:`flex items-center justify-center w-10 h-10 sm:w-[46px] sm:h-[46px] rounded-xl sm:rounded-[14px] transition-all border ${K?"bg-blue-50 border-blue-200 text-blue-600 dark:bg-[#323338] dark:border-gray-600 dark:text-blue-400":"bg-white border-gray-200/80 text-gray-700 hover:bg-gray-50 dark:bg-transparent dark:border-[#323338] dark:text-[#e0e0e0] dark:hover:border-gray-500"}`,disabled:!ge||ee,title:"调节笔刷大小",children:s.jsx("span",{className:"text-[14px] sm:text-[15px] font-semibold tracking-tight",children:D})})})]}),s.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-2 sm:ml-1",children:[s.jsx("button",{onClick:lt,disabled:!Me,className:"p-2 sm:p-2.5 text-gray-500 hover:bg-gray-100 rounded-lg sm:rounded-xl disabled:opacity-30 dark:text-[#8a8a8e] dark:hover:bg-white/10 dark:hover:text-gray-200 transition-all",title:"撤销",children:s.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 7v6h6"}),s.jsx("path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"})]})}),s.jsx("button",{onClick:ar,disabled:!ot,className:"p-2 sm:p-2.5 text-gray-500 hover:bg-gray-100 rounded-lg sm:rounded-xl disabled:opacity-30 dark:text-[#8a8a8e] dark:hover:bg-white/10 dark:hover:text-gray-200 transition-all",title:"重做",children:s.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M21 7v6h-6"}),s.jsx("path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7"})]})}),s.jsx("div",{className:"w-px h-4 sm:h-5 bg-gray-300 dark:bg-[#323338] mx-1"}),s.jsx("button",{onClick:Te,disabled:!ge||ee||!Pt,className:"p-2 sm:p-2.5 text-gray-500 hover:bg-gray-100 rounded-lg sm:rounded-xl disabled:opacity-30 dark:text-[#8a8a8e] dark:hover:bg-white/10 dark:hover:text-gray-200 transition-all",title:"重置视图",children:s.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M4 14h6v6"}),s.jsx("path",{d:"M20 10h-6V4"}),s.jsx("path",{d:"M14 10l7-7"}),s.jsx("path",{d:"M3 21l7-7"})]})}),s.jsx("button",{onClick:hr,disabled:!ge||ee,className:"p-2 sm:p-2.5 text-gray-500 hover:bg-gray-100 rounded-lg sm:rounded-xl disabled:opacity-30 dark:text-[#8a8a8e] dark:hover:bg-white/10 dark:hover:text-gray-200 transition-all",title:"清空遮罩",children:s.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 6h18"}),s.jsx("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),s.jsx("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})]})})]})]})})]}),K&&Oe&&fr.createPortal(s.jsx("div",{ref:b,className:"fixed z-[100] h-44 w-14 -translate-x-1/2 bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700",style:{left:Oe.left,bottom:Oe.bottom},children:s.jsx("input",{type:"range",min:8,max:220,value:D,onChange:M=>{const X=Number(M.target.value);W(X),!ke&&Y&&Xe(tt())},className:"absolute left-1/2 top-1/2 h-5 w-32 -translate-x-1/2 -translate-y-1/2 -rotate-90 accent-blue-500 cursor-ns-resize",disabled:!ge||ee})}),document.body)]})}function Bm(){const[e,t]=g.useState(null),r=E(d=>d.showToast),n=E(d=>d.inputImages),a=E(d=>d.setDetailTaskId),o=E(d=>d.setLightboxImageId),i=E(d=>d.setMaskEditorImageId),c=g.useRef(null);if(g.useEffect(()=>{if($m())return;const d=p=>{const w=p.target;if(w&&w.tagName==="IMG"){const v=w;if(!v.src)return;const j=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,P=window.matchMedia("(pointer: coarse)").matches;if(j&&P)return;p.preventDefault(),t({src:v.src,imageId:v.dataset.imageId,x:p.clientX,y:p.clientY})}};return window.addEventListener("contextmenu",d),()=>{window.removeEventListener("contextmenu",d)}},[]),g.useEffect(()=>{if(!e)return;const d=p=>{c.current&&p.target instanceof Node&&c.current.contains(p.target)||(p.target instanceof Element&&p.target.closest("[data-lightbox-root]")&&window.dispatchEvent(new Event("image-context-menu-dismiss-lightbox-click")),t(null))};return window.addEventListener("mousedown",d,{capture:!0}),window.addEventListener("touchstart",d,{capture:!0}),window.addEventListener("wheel",d,{capture:!0}),window.addEventListener("scroll",d,{capture:!0}),window.addEventListener("resize",d),()=>{window.removeEventListener("mousedown",d,{capture:!0}),window.removeEventListener("touchstart",d,{capture:!0}),window.removeEventListener("wheel",d,{capture:!0}),window.removeEventListener("scroll",d,{capture:!0}),window.removeEventListener("resize",d)}},[e]),!e)return null;const l=async()=>e.imageId?await Ot(e.imageId)??e.src:e.src,f=async d=>{d.stopPropagation(),t(null);try{const p=await l(),v=await(await fetch(p)).blob();await gc(v),r("图片已复制","success")}catch(p){console.error(p),r(Vt("复制失败",p),"error")}},m=async d=>{d.stopPropagation(),t(null);try{const p=await l(),v=await(await fetch(p)).blob(),j=URL.createObjectURL(v),P=document.createElement("a");P.href=j;const C=v.type.split("/")[1]||"png";P.download=`image-${Date.now()}.${C}`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(j),r("开始下载","success")}catch(p){console.error(p),r("下载失败","error")}},u=async d=>{if(d.stopPropagation(),t(null),n.length>=16){r("参考图数量已达上限(16 张),无法继续添加","error");return}try{const p=await l();await Rf(p),a(null),o(null),i(null),r("已加入参考图","success")}catch(p){console.error(p),r(`加入参考图失败:${p instanceof Error?p.message:String(p)}`,"error")}};let h=e.x,x=e.y;const y=120,b=128;return h+y>window.innerWidth&&(h-=y),x+b>window.innerHeight&&(x-=b),s.jsxs("div",{ref:c,className:"fixed z-[9999] bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-100 dark:border-gray-700 py-1 w-[120px] overflow-hidden animate-fade-in",style:{left:h,top:x},onContextMenu:d=>d.preventDefault(),children:[s.jsxs("button",{onClick:f,className:"w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",children:[s.jsx(Jt,{className:"w-4 h-4 flex-shrink-0"}),"复制"]}),s.jsxs("button",{onClick:m,className:"w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",children:[s.jsx(Gf,{className:"w-4 h-4 flex-shrink-0"}),"下载"]}),s.jsxs("button",{onClick:u,className:"w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",children:[s.jsx(bo,{className:"w-4 h-4 flex-shrink-0"}),"编辑"]})]})}function $m(){try{return window.self!==window.top}catch{return!0}}function Fm(){const e=E(f=>f.supportPromptOpen),t=E(f=>f.dismissSupportPrompt),r=E(f=>f.confirmDialog),n=E(f=>f.detailTaskId),a=E(f=>f.lightboxImageId),o=E(f=>f.showSettings),i=E(f=>f.maskEditorImageId),l=e&&!!!(r||n||a||o||i);return Jr(l,t),Mr(l),l?fr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[70] flex items-center justify-center p-4",onClick:t,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{className:"relative z-10 w-full max-w-sm rounded-[2rem] border border-white/50 bg-white/95 p-6 pb-7 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10 flex flex-col",onClick:f=>f.stopPropagation(),children:[s.jsx("div",{className:"absolute right-4 top-4",children:s.jsx("button",{type:"button",onClick:t,className:"rounded-full p-2 text-gray-400 transition-colors hover:bg-gray-200 hover:text-gray-600 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(wr,{className:"h-5 w-5"})})}),s.jsx("div",{className:"mb-5 mt-4 flex justify-center",children:s.jsx("div",{className:"flex h-20 w-20 items-center justify-center rounded-[1.5rem] bg-[#f4f0ff] text-[#946ce6] dark:bg-[#946ce6]/10 dark:text-[#bba3f2]",children:s.jsx("svg",{className:"h-10 w-10",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"})})})}),s.jsx("h3",{className:"mb-3 text-center text-xl font-bold text-gray-800 dark:text-gray-100",children:"感谢使用 🎉"}),s.jsxs("p",{className:"mb-8 px-2 text-center text-[15px] leading-relaxed text-gray-500 dark:text-gray-400",children:["你已经成功生成了超过 ",s.jsx("strong",{className:"font-semibold text-gray-800 dark:text-gray-200",children:"50"})," 张图片!",s.jsx("br",{}),"如果这个工具对你有所帮助,",s.jsx("br",{}),"欢迎赞助作者,或反馈分享你的建议。"]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:[s.jsxs("a",{href:"https://www.ifdian.net/a/cooksleep",target:"_blank",rel:"noopener noreferrer",onClick:t,className:"flex w-full sm:w-auto flex-1 items-center justify-center gap-2 rounded-2xl bg-[#946ce6] px-5 py-3.5 text-[15px] font-semibold text-white transition-all hover:bg-[#8358dc] active:scale-[0.98] dark:bg-[#946ce6] dark:hover:bg-[#a885ee]",children:[s.jsx("svg",{className:"h-4 w-4",fill:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{d:"M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"})}),"赞助作者"]}),s.jsxs("a",{href:"https://github.com/CookSleep/gpt_image_playground/issues",target:"_blank",rel:"noopener noreferrer",onClick:t,className:"flex w-full sm:w-auto flex-1 items-center justify-center gap-2 rounded-2xl bg-[#f4f4f5] px-5 py-3.5 text-[15px] font-semibold text-gray-600 transition-all hover:bg-gray-200 active:scale-[0.98] dark:bg-[#27272a] dark:text-gray-300 dark:hover:bg-[#3f3f46]",children:[s.jsx("svg",{className:"h-[18px] w-[18px] opacity-70",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"})}),"反馈问题"]})]})]})]}),document.body):null}function zm({returnPath:e=null,storageNamespace:t=null}){const r=E(n=>n.setSettings);return Lf(),g.useEffect(()=>{let n=!1;return(async()=>{if(await of(t),n)return;const a=new URLSearchParams(window.location.search),o=E.getState().settings,i=g0(o,a),c=Fl(o,a);if(r(c),$l(a)){h0(a);const l=a.toString(),f=`${window.location.pathname}${l?`?${l}`:""}${window.location.hash}`;window.history.replaceState(null,"",f)}i&&rc({silent:!0}),await jf()})(),()=>{n=!0}},[r,t]),g.useEffect(()=>{const n=a=>{a.target?.closest("img")&&a.preventDefault()};return document.addEventListener("dragstart",n),()=>document.removeEventListener("dragstart",n)},[]),s.jsxs(s.Fragment,{children:[s.jsx(Kf,{returnPath:e}),s.jsx("main",{"data-home-main":!0,"data-drag-select-surface":!0,className:"pb-48",children:s.jsxs("div",{className:"safe-area-x max-w-7xl mx-auto",children:[s.jsx(em,{}),s.jsx(rm,{})]})}),s.jsx(dm,{}),s.jsx(hm,{}),s.jsx(gm,{}),s.jsx(jm,{}),s.jsx(Pm,{}),s.jsx(Fm,{}),s.jsx(Sm,{}),s.jsx(Om,{}),s.jsx(Bm,{})]})}function Xm(){const e=rn.useMemo(()=>{const r=typeof window<"u"&&window.__ROUTER_BASENAME__||"",n=typeof window<"u"?window.location.search:"";return Uc(n,{basename:r})},[]),t=rn.useMemo(()=>{const r=typeof window<"u"&&window.__ROUTER_BASENAME__||"",n=typeof window<"u"?window.location.search:"";return Oc(n,{basename:r})},[]);return s.jsx(zm,{returnPath:e,storageNamespace:t})}export{Xm as default};