From 65d578e878f078e14cd5b010287f78cd55c1aeaf Mon Sep 17 00:00:00 2001 From: LiZhen <16621660628@163.com> Date: Wed, 1 May 2024 20:39:24 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BA=A4=E4=BA=92=E6=96=B9?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.css | 2 +- index.js | 39 +++++++++++++++++++-------------------- plugin.json | 2 +- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/index.css b/index.css index 37b9a32..b0d32e2 100644 --- a/index.css +++ b/index.css @@ -1 +1 @@ -.plugin-sample__custom-tab{background-color:var(--b3-theme-background);height:100%;width:100%;display:flex;justify-content:center;align-items:center}.plugin-sample__custom-dock{display:flex;justify-content:center;align-items:center}.plugin-sample__time{background:var(--b3-card-info-background);border-radius:4px;padding:2px 8px}.siyuan-ai__custom-tab{background-color:var(--b3-theme-background);height:100%;width:100%;display:flex;justify-content:center;align-items:center}.siyuan-ai__custom-dock{display:flex;justify-content:center;align-items:center}.config__panel.svelte-1fh5pey.svelte-1fh5pey.svelte-1fh5pey{height:100%}.config__panel.svelte-1fh5pey>ul.svelte-1fh5pey>li.svelte-1fh5pey{padding-left:1rem}@keyframes svelte-1170n0w-chat_slide-in__nvZgA{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-1170n0w-chat_slide-in-from-top__Q0KCt{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}.chat_chat-message__dg8rL.svelte-1170n0w{display:flex;flex-direction:row}.chat_chat-message__dg8rL.svelte-1170n0w:last-child{animation:svelte-1170n0w-chat_slide-in__nvZgA .3s ease}.chat_chat-message-header__Dny_K.svelte-1170n0w{margin-top:20px;display:flex;align-items:center}.chat_chat-message-container__O_X8_.svelte-1170n0w{max-width:var(--message-max-width);display:flex;flex-direction:column;align-items:flex-start}.chat_chat-message-avatar__3QeMq.svelte-1170n0w{position:relative}.chat_chat-message-item__dKqMl.svelte-1170n0w{box-sizing:border-box;max-width:100%;margin-top:10px;border-radius:10px;background-color:#0000000d;padding:10px;font-size:14px;-webkit-user-select:text;-moz-user-select:text;user-select:text;word-break:break-word;border:var(--border-in-light);position:relative;transition:all .3s ease}@keyframes svelte-1170n0w-mask_slide-in__unpXH{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-1170n0w-mask_slide-in-from-top__DOEYB{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-1170n0w-ui-lib_slide-in__1VMXW{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-1170n0w-ui-lib_slide-in-from-top__cfJKh{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_AMS-Regular.a79f1c31.woff2) format("woff2"),url(/_next/static/media/KaTeX_AMS-Regular.1608a09b.woff) format("woff"),url(/_next/static/media/KaTeX_AMS-Regular.4aafdb68.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Caligraphic-Bold.ec17d132.woff2) format("woff2"),url(/_next/static/media/KaTeX_Caligraphic-Bold.b6770918.woff) format("woff"),url(/_next/static/media/KaTeX_Caligraphic-Bold.cce5b8ec.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Caligraphic-Regular.55fac258.woff2) format("woff2"),url(/_next/static/media/KaTeX_Caligraphic-Regular.dad44a7f.woff) format("woff"),url(/_next/static/media/KaTeX_Caligraphic-Regular.07ef19e7.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Fraktur-Bold.d42a5579.woff2) format("woff2"),url(/_next/static/media/KaTeX_Fraktur-Bold.9f256b85.woff) format("woff"),url(/_next/static/media/KaTeX_Fraktur-Bold.b18f59e1.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Fraktur-Regular.d3c882a6.woff2) format("woff2"),url(/_next/static/media/KaTeX_Fraktur-Regular.7c187121.woff) format("woff"),url(/_next/static/media/KaTeX_Fraktur-Regular.ed38e79f.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Main-Bold.c3fb5ac2.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Bold.d181c465.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Bold.b74a1a8b.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(/_next/static/media/KaTeX_Main-BoldItalic.6f2bb1df.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-BoldItalic.e3f82f9d.woff) format("woff"),url(/_next/static/media/KaTeX_Main-BoldItalic.70d8b0a5.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_Main-Italic.8916142b.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Italic.9024d815.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Italic.47373d1e.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Main-Regular.0462f03b.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Regular.7f51fe03.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Regular.b7f8fe9b.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(/_next/static/media/KaTeX_Math-BoldItalic.572d331f.woff2) format("woff2"),url(/_next/static/media/KaTeX_Math-BoldItalic.f1035d8d.woff) format("woff"),url(/_next/static/media/KaTeX_Math-BoldItalic.a879cf83.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_Math-Italic.f28c23ac.woff2) format("woff2"),url(/_next/static/media/KaTeX_Math-Italic.5295ba48.woff) format("woff"),url(/_next/static/media/KaTeX_Math-Italic.939bc644.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_SansSerif-Bold.8c5b5494.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Bold.bf59d231.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Bold.94e1e8dc.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_SansSerif-Italic.3b1e59b3.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Italic.7c9bc82b.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Italic.b4c20c84.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_SansSerif-Regular.ba21ed5f.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Regular.74048478.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Regular.d4d7ba48.ttf) format("truetype")}@font-face{font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Script-Regular.03e9641d.woff2) format("woff2"),url(/_next/static/media/KaTeX_Script-Regular.07505710.woff) format("woff"),url(/_next/static/media/KaTeX_Script-Regular.fe9cbbe1.ttf) format("truetype")}@font-face{font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size1-Regular.eae34984.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size1-Regular.e1e279cb.woff) format("woff"),url(/_next/static/media/KaTeX_Size1-Regular.fabc004a.ttf) format("truetype")}@font-face{font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size2-Regular.5916a24f.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size2-Regular.57727022.woff) format("woff"),url(/_next/static/media/KaTeX_Size2-Regular.d6b476ec.ttf) format("truetype")}@font-face{font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size3-Regular.b4230e7e.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size3-Regular.9acaf01c.woff) format("woff"),url(/_next/static/media/KaTeX_Size3-Regular.a144ef58.ttf) format("truetype")}@font-face{font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size4-Regular.10d95fd3.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size4-Regular.7a996c9d.woff) format("woff"),url(/_next/static/media/KaTeX_Size4-Regular.fbccdabe.ttf) format("truetype")}@font-face{font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Typewriter-Regular.a8709e36.woff2) format("woff2"),url(/_next/static/media/KaTeX_Typewriter-Regular.6258592b.woff) format("woff"),url(/_next/static/media/KaTeX_Typewriter-Regular.d97aaf4a.ttf) format("truetype")}@keyframes svelte-1dpaqhi-chat_slide-in__nvZgA{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-1dpaqhi-chat_slide-in-from-top__Q0KCt{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}.chat_chat-message-user__ZtTEj.svelte-1dpaqhi.svelte-1dpaqhi.svelte-1dpaqhi{display:flex;flex-direction:row-reverse}.chat_chat-message-user__ZtTEj.svelte-1dpaqhi .chat_chat-message-header__Dny_K.svelte-1dpaqhi.svelte-1dpaqhi{flex-direction:row-reverse}.chat_chat-message-header__Dny_K.svelte-1dpaqhi.svelte-1dpaqhi.svelte-1dpaqhi{margin-top:20px;display:flex;align-items:center}.chat_chat-message-container__O_X8_.svelte-1dpaqhi.svelte-1dpaqhi.svelte-1dpaqhi{max-width:var(--message-max-width);display:flex;flex-direction:column;align-items:flex-start}.chat_chat-message-user__ZtTEj.svelte-1dpaqhi>.chat_chat-message-container__O_X8_.svelte-1dpaqhi.svelte-1dpaqhi{align-items:flex-end}.chat_chat-message-avatar__3QeMq.svelte-1dpaqhi.svelte-1dpaqhi.svelte-1dpaqhi{position:relative}.chat_chat-message-item__dKqMl.svelte-1dpaqhi.svelte-1dpaqhi.svelte-1dpaqhi{box-sizing:border-box;max-width:100%;margin-top:10px;border-radius:10px;background-color:#0000000d;padding:10px;font-size:14px;-webkit-user-select:text;-moz-user-select:text;user-select:text;word-break:break-word;border:var(--border-in-light);position:relative;transition:all .3s ease}.chat_chat-message-user__ZtTEj.svelte-1dpaqhi>.chat_chat-message-container__O_X8_.svelte-1dpaqhi>.chat_chat-message-item__dKqMl.svelte-1dpaqhi{background-color:var(--second)}.chat_chat-message-user__ZtTEj.svelte-1dpaqhi>.chat_chat-message-container__O_X8_.svelte-1dpaqhi>.chat_chat-message-item__dKqMl.svelte-1dpaqhi:hover{min-width:0}@keyframes svelte-1dpaqhi-mask_slide-in__unpXH{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-1dpaqhi-mask_slide-in-from-top__DOEYB{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-1dpaqhi-ui-lib_slide-in__1VMXW{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-1dpaqhi-ui-lib_slide-in-from-top__cfJKh{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_AMS-Regular.a79f1c31.woff2) format("woff2"),url(/_next/static/media/KaTeX_AMS-Regular.1608a09b.woff) format("woff"),url(/_next/static/media/KaTeX_AMS-Regular.4aafdb68.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Caligraphic-Bold.ec17d132.woff2) format("woff2"),url(/_next/static/media/KaTeX_Caligraphic-Bold.b6770918.woff) format("woff"),url(/_next/static/media/KaTeX_Caligraphic-Bold.cce5b8ec.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Caligraphic-Regular.55fac258.woff2) format("woff2"),url(/_next/static/media/KaTeX_Caligraphic-Regular.dad44a7f.woff) format("woff"),url(/_next/static/media/KaTeX_Caligraphic-Regular.07ef19e7.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Fraktur-Bold.d42a5579.woff2) format("woff2"),url(/_next/static/media/KaTeX_Fraktur-Bold.9f256b85.woff) format("woff"),url(/_next/static/media/KaTeX_Fraktur-Bold.b18f59e1.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Fraktur-Regular.d3c882a6.woff2) format("woff2"),url(/_next/static/media/KaTeX_Fraktur-Regular.7c187121.woff) format("woff"),url(/_next/static/media/KaTeX_Fraktur-Regular.ed38e79f.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Main-Bold.c3fb5ac2.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Bold.d181c465.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Bold.b74a1a8b.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(/_next/static/media/KaTeX_Main-BoldItalic.6f2bb1df.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-BoldItalic.e3f82f9d.woff) format("woff"),url(/_next/static/media/KaTeX_Main-BoldItalic.70d8b0a5.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_Main-Italic.8916142b.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Italic.9024d815.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Italic.47373d1e.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Main-Regular.0462f03b.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Regular.7f51fe03.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Regular.b7f8fe9b.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(/_next/static/media/KaTeX_Math-BoldItalic.572d331f.woff2) format("woff2"),url(/_next/static/media/KaTeX_Math-BoldItalic.f1035d8d.woff) format("woff"),url(/_next/static/media/KaTeX_Math-BoldItalic.a879cf83.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_Math-Italic.f28c23ac.woff2) format("woff2"),url(/_next/static/media/KaTeX_Math-Italic.5295ba48.woff) format("woff"),url(/_next/static/media/KaTeX_Math-Italic.939bc644.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_SansSerif-Bold.8c5b5494.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Bold.bf59d231.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Bold.94e1e8dc.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_SansSerif-Italic.3b1e59b3.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Italic.7c9bc82b.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Italic.b4c20c84.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_SansSerif-Regular.ba21ed5f.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Regular.74048478.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Regular.d4d7ba48.ttf) format("truetype")}@font-face{font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Script-Regular.03e9641d.woff2) format("woff2"),url(/_next/static/media/KaTeX_Script-Regular.07505710.woff) format("woff"),url(/_next/static/media/KaTeX_Script-Regular.fe9cbbe1.ttf) format("truetype")}@font-face{font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size1-Regular.eae34984.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size1-Regular.e1e279cb.woff) format("woff"),url(/_next/static/media/KaTeX_Size1-Regular.fabc004a.ttf) format("truetype")}@font-face{font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size2-Regular.5916a24f.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size2-Regular.57727022.woff) format("woff"),url(/_next/static/media/KaTeX_Size2-Regular.d6b476ec.ttf) format("truetype")}@font-face{font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size3-Regular.b4230e7e.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size3-Regular.9acaf01c.woff) format("woff"),url(/_next/static/media/KaTeX_Size3-Regular.a144ef58.ttf) format("truetype")}@font-face{font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size4-Regular.10d95fd3.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size4-Regular.7a996c9d.woff) format("woff"),url(/_next/static/media/KaTeX_Size4-Regular.fbccdabe.ttf) format("truetype")}@font-face{font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Typewriter-Regular.a8709e36.woff2) format("woff2"),url(/_next/static/media/KaTeX_Typewriter-Regular.6258592b.woff) format("woff"),url(/_next/static/media/KaTeX_Typewriter-Regular.d97aaf4a.ttf) format("truetype")}.chat_icon__Ly3TN.svelte-pnrkt6{display:flex;align-items:center;justify-content:center}.chat_chat-input-actions__mwYC_.svelte-pnrkt6{display:flex;flex-wrap:wrap}.chat_chat-input-send__GFQZo.svelte-pnrkt6{background-color:#1d93ab;color:#fff;position:absolute;right:30px;bottom:32px}.home_window-content__2WGYf.svelte-pnrkt6{width:var(--window-content-width);height:100%;display:flex;flex-direction:column}.button_icon-button__VwAMf.svelte-pnrkt6{background-color:var(--white);border-radius:10px;display:flex;align-items:center;justify-content:center;padding:10px;cursor:pointer;transition:all .3s ease;overflow:hidden;-webkit-user-select:none;-moz-user-select:none;user-select:none;outline:none;border:none;color:var(--black)}.button_icon-button-text__my76e.svelte-pnrkt6{font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.button_icon-button-text__my76e.svelte-pnrkt6:not(:first-child){margin-left:5px}@keyframes svelte-pnrkt6-chat_slide-in__nvZgA{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-pnrkt6-chat_slide-in-from-top__Q0KCt{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}.chat_chat__ZebHg.svelte-pnrkt6{display:flex;flex-direction:column;position:relative;height:100%}.chat_chat-body__QFv5x.svelte-pnrkt6{flex:1 1;overflow:auto;overflow-x:hidden;padding:20px 20px 40px;position:relative;overscroll-behavior:none}.chat_chat-input-panel__rO72m.svelte-pnrkt6{position:relative;width:100%;padding:10px 20px 20px;box-sizing:border-box;flex-direction:column;border-top:var(--border-in-light);box-shadow:var(--card-shadow)}.chat_chat-input-panel-inner___IQHi.svelte-pnrkt6{cursor:text;display:flex;flex:1 1;border-radius:10px;border:var(--border-in-light)}.chat_chat-input-panel-inner___IQHi.svelte-pnrkt6:has(.chat_chat-input__PQ_oF:focus){border:1px solid var(--primary)}.chat_chat-input__PQ_oF.svelte-pnrkt6{height:100%;width:100%;border-radius:10px;border:none;box-shadow:0 -2px 5px #00000008;background-color:var(--white);color:var(--black);font-family:inherit;padding:10px 90px 10px 14px;resize:none;outline:none;box-sizing:border-box;min-height:68px}.chat_chat-input-send__GFQZo.svelte-pnrkt6{background-color:var(--primary);color:#fff;position:absolute;right:30px;bottom:32px}@media only screen and (max-width: 600px){.chat_chat-input__PQ_oF.svelte-pnrkt6{font-size:16px}.chat_chat-input-send__GFQZo.svelte-pnrkt6{bottom:30px}}@keyframes svelte-pnrkt6-mask_slide-in__unpXH{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-pnrkt6-mask_slide-in-from-top__DOEYB{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}.button_icon-button__VwAMf.svelte-pnrkt6{border-radius:10px;display:flex;align-items:center;justify-content:center;padding:10px;cursor:pointer;transition:all .3s ease;-webkit-user-select:none;-moz-user-select:none;user-select:none;outline:none;border:none;color:#0bc6fa}.button_icon-button__VwAMf.button_primary__dwYZ6.svelte-pnrkt6{background-color:#1d95ad;color:#fff}@media only screen and (max-width: 600px){.button_icon-button__VwAMf.svelte-pnrkt6{padding:16px}}@keyframes svelte-pnrkt6-ui-lib_slide-in__1VMXW{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes svelte-pnrkt6-ui-lib_slide-in-from-top__cfJKh{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_AMS-Regular.a79f1c31.woff2) format("woff2"),url(/_next/static/media/KaTeX_AMS-Regular.1608a09b.woff) format("woff"),url(/_next/static/media/KaTeX_AMS-Regular.4aafdb68.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Caligraphic-Bold.ec17d132.woff2) format("woff2"),url(/_next/static/media/KaTeX_Caligraphic-Bold.b6770918.woff) format("woff"),url(/_next/static/media/KaTeX_Caligraphic-Bold.cce5b8ec.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Caligraphic-Regular.55fac258.woff2) format("woff2"),url(/_next/static/media/KaTeX_Caligraphic-Regular.dad44a7f.woff) format("woff"),url(/_next/static/media/KaTeX_Caligraphic-Regular.07ef19e7.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Fraktur-Bold.d42a5579.woff2) format("woff2"),url(/_next/static/media/KaTeX_Fraktur-Bold.9f256b85.woff) format("woff"),url(/_next/static/media/KaTeX_Fraktur-Bold.b18f59e1.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Fraktur-Regular.d3c882a6.woff2) format("woff2"),url(/_next/static/media/KaTeX_Fraktur-Regular.7c187121.woff) format("woff"),url(/_next/static/media/KaTeX_Fraktur-Regular.ed38e79f.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_Main-Bold.c3fb5ac2.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Bold.d181c465.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Bold.b74a1a8b.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(/_next/static/media/KaTeX_Main-BoldItalic.6f2bb1df.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-BoldItalic.e3f82f9d.woff) format("woff"),url(/_next/static/media/KaTeX_Main-BoldItalic.70d8b0a5.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_Main-Italic.8916142b.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Italic.9024d815.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Italic.47373d1e.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Main-Regular.0462f03b.woff2) format("woff2"),url(/_next/static/media/KaTeX_Main-Regular.7f51fe03.woff) format("woff"),url(/_next/static/media/KaTeX_Main-Regular.b7f8fe9b.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(/_next/static/media/KaTeX_Math-BoldItalic.572d331f.woff2) format("woff2"),url(/_next/static/media/KaTeX_Math-BoldItalic.f1035d8d.woff) format("woff"),url(/_next/static/media/KaTeX_Math-BoldItalic.a879cf83.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_Math-Italic.f28c23ac.woff2) format("woff2"),url(/_next/static/media/KaTeX_Math-Italic.5295ba48.woff) format("woff"),url(/_next/static/media/KaTeX_Math-Italic.939bc644.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:normal;font-weight:700;src:url(/_next/static/media/KaTeX_SansSerif-Bold.8c5b5494.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Bold.bf59d231.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Bold.94e1e8dc.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:italic;font-weight:400;src:url(/_next/static/media/KaTeX_SansSerif-Italic.3b1e59b3.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Italic.7c9bc82b.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Italic.b4c20c84.ttf) format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_SansSerif-Regular.ba21ed5f.woff2) format("woff2"),url(/_next/static/media/KaTeX_SansSerif-Regular.74048478.woff) format("woff"),url(/_next/static/media/KaTeX_SansSerif-Regular.d4d7ba48.ttf) format("truetype")}@font-face{font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Script-Regular.03e9641d.woff2) format("woff2"),url(/_next/static/media/KaTeX_Script-Regular.07505710.woff) format("woff"),url(/_next/static/media/KaTeX_Script-Regular.fe9cbbe1.ttf) format("truetype")}@font-face{font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size1-Regular.eae34984.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size1-Regular.e1e279cb.woff) format("woff"),url(/_next/static/media/KaTeX_Size1-Regular.fabc004a.ttf) format("truetype")}@font-face{font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size2-Regular.5916a24f.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size2-Regular.57727022.woff) format("woff"),url(/_next/static/media/KaTeX_Size2-Regular.d6b476ec.ttf) format("truetype")}@font-face{font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size3-Regular.b4230e7e.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size3-Regular.9acaf01c.woff) format("woff"),url(/_next/static/media/KaTeX_Size3-Regular.a144ef58.ttf) format("truetype")}@font-face{font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Size4-Regular.10d95fd3.woff2) format("woff2"),url(/_next/static/media/KaTeX_Size4-Regular.7a996c9d.woff) format("woff"),url(/_next/static/media/KaTeX_Size4-Regular.fbccdabe.ttf) format("truetype")}@font-face{font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(/_next/static/media/KaTeX_Typewriter-Regular.a8709e36.woff2) format("woff2"),url(/_next/static/media/KaTeX_Typewriter-Regular.6258592b.woff) format("woff"),url(/_next/static/media/KaTeX_Typewriter-Regular.d97aaf4a.ttf) format("truetype")}.config__panel.svelte-1jo4zii.svelte-1jo4zii.svelte-1jo4zii{height:100%}.config__panel.svelte-1jo4zii>ul.svelte-1jo4zii>li.svelte-1jo4zii{padding-left:1rem}.prompt_title.svelte-1jo4zii.svelte-1jo4zii.svelte-1jo4zii{text-align:center} +.plugin-sample__custom-tab{background-color:var(--b3-theme-background);height:100%;width:100%;display:flex;justify-content:center;align-items:center}.plugin-sample__custom-dock{display:flex;justify-content:center;align-items:center}.plugin-sample__time{background:var(--b3-card-info-background);border-radius:4px;padding:2px 8px}.siyuan-ai__custom-tab{background-color:var(--b3-theme-background);height:100%;width:100%;display:flex;justify-content:center;align-items:center}.siyuan-ai__custom-dock{display:flex;justify-content:center;align-items:center}.config__panel.svelte-1fh5pey.svelte-1fh5pey.svelte-1fh5pey{height:100%}.config__panel.svelte-1fh5pey>ul.svelte-1fh5pey>li.svelte-1fh5pey{padding-left:1rem} diff --git a/index.js b/index.js index 277093f..e9f95c6 100644 --- a/index.js +++ b/index.js @@ -1,20 +1,19 @@ -"use strict";var xo=Object.defineProperty;var Io=(n,e,t)=>e in n?xo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ee=(n,e,t)=>(Io(n,typeof e!="symbol"?e+"":e,t),t);const Ge=require("siyuan");function z(){}function Be(n,e){for(const t in e)n[t]=e[t];return n}function ki(n){return n()}function Pr(){return Object.create(null)}function ue(n){n.forEach(ki)}function Ci(n){return typeof n=="function"}function Te(n,e){return n!=n?e==e:n!==e||n&&typeof n=="object"||typeof n=="function"}function Lo(n){return Object.keys(n).length===0}function Ps(n,e,t,s){if(n){const r=Pi(n,e,t,s);return n[0](r)}}function Pi(n,e,t,s){return n[1]&&s?Be(t.ctx.slice(),n[1](s(e))):t.ctx}function vs(n,e,t,s){if(n[2]&&s){const r=n[2](s(t));if(e.dirty===void 0)return r;if(typeof r=="object"){const i=[],o=Math.max(e.dirty.length,r.length);for(let a=0;a32){const e=[],t=n.ctx.length/32;for(let s=0;sn.removeEventListener(e,t,s)}function g(n,e,t){t==null?n.removeAttribute(e):n.getAttribute(e)!==t&&n.setAttribute(e,t)}const No=["width","height"];function Ct(n,e){const t=Object.getOwnPropertyDescriptors(n.__proto__);for(const s in e)e[s]==null?n.removeAttribute(s):s==="style"?n.style.cssText=e[s]:s==="__value"?n.value=n[s]=e[s]:t[s]&&t[s].set&&No.indexOf(s)===-1?n[s]=e[s]:g(n,s,e[s])}function Ms(n){return n===""?null:+n}function Do(n){return Array.from(n.childNodes)}function tt(n,e){e=""+e,n.data!==e&&(n.data=e)}function jo(n,e){e=""+e,n.wholeText!==e&&(n.data=e)}function Bo(n,e,t){~Fo.indexOf(t)?jo(n,e):tt(n,e)}function Ue(n,e){n.value=e??""}function Vs(n,e,t,s){t==null?n.style.removeProperty(e):n.style.setProperty(e,t,s?"important":"")}function vr(n,e,t){for(let s=0;s{const r=n.$$.callbacks[e];if(r){const i=qo(e,t,{cancelable:s});return r.slice().forEach(o=>{o.call(n,i)}),!i.defaultPrevented}return!0}}function Qs(n,e){const t=n.$$.callbacks[e.type];t&&t.slice().forEach(s=>s.call(this,e))}const mt=[],Vt=[];let wt=[];const Ts=[],Wo=Promise.resolve();let xs=!1;function Go(){xs||(xs=!0,Wo.then(Oi))}function Mn(n){wt.push(n)}function Ri(n){Ts.push(n)}const hs=new Set;let dt=0;function Oi(){if(dt!==0)return;const n=Kt;do{try{for(;dtn.indexOf(s)===-1?e.push(s):t.push(s)),t.forEach(s=>s()),wt=e}const dn=new Set;let rt;function Pt(){rt={r:0,c:[],p:rt}}function vt(){rt.r||ue(rt.c),rt=rt.p}function q(n,e){n&&n.i&&(dn.delete(n),n.i(e))}function G(n,e,t,s){if(n&&n.o){if(dn.has(n))return;dn.add(n),rt.c.push(()=>{dn.delete(n),s&&(t&&n.d(1),s())}),n.o(e)}else s&&s()}function Xo(n,e){n.d(1),e.delete(n.key)}function Tn(n,e){G(n,1,1,()=>{e.delete(n.key)})}function zt(n,e,t,s,r,i,o,a,l,u,f,c){let h=n.length,b=i.length,d=h;const p={};for(;d--;)p[n[d].key]=d;const m=[],S=new Map,k=new Map,E=[];for(d=b;d--;){const v=c(r,i,d),L=t(v);let x=o.get(L);x?s&&E.push(()=>x.p(v,e)):(x=u(L,v),x.c()),S.set(L,m[d]=x),L in p&&k.set(L,Math.abs(d-p[L]))}const P=new Set,A=new Set;function F(v){q(v,1),v.m(a,f),o.set(v.key,v),f=v.first,b--}for(;h&&b;){const v=m[b-1],L=n[h-1],x=v.key,X=L.key;v===L?(f=v.first,h--,b--):S.has(X)?!o.has(x)||P.has(x)?F(v):A.has(X)?h--:k.get(x)>k.get(X)?(A.add(x),F(v)):(P.add(X),h--):(l(L,o),h--)}for(;h--;){const v=n[h];S.has(v.key)||l(v,o)}for(;b;)F(m[b-1]);return ue(E),m}function Ys(n,e){const t={},s={},r={$$scope:1};let i=n.length;for(;i--;){const o=n[i],a=e[i];if(a){for(const l in o)l in a||(s[l]=1);for(const l in a)r[l]||(t[l]=a[l],r[l]=1);n[i]=a}else for(const l in o)r[l]=1}for(const o in s)o in t||(t[o]=void 0);return t}function Mi(n,e,t){const s=n.$$.props[e];s!==void 0&&(n.$$.bound[s]=t,t(n.$$.ctx[s]))}function ie(n){n&&n.c()}function se(n,e,t,s){const{fragment:r,after_update:i}=n.$$;r&&r.m(e,t),s||Mn(()=>{const o=n.$$.on_mount.map(ki).filter(Ci);n.$$.on_destroy?n.$$.on_destroy.push(...o):ue(o),n.$$.on_mount=[]}),i.forEach(Mn)}function re(n,e){const t=n.$$;t.fragment!==null&&(Jo(t.after_update),ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function Ko(n,e){n.$$.dirty[0]===-1&&(mt.push(n),Go(),n.$$.dirty.fill(0)),n.$$.dirty[e/31|0]|=1<{const d=b.length?b[0]:h;return u.ctx&&r(u.ctx[c],u.ctx[c]=d)&&(!u.skip_bound&&u.bound[c]&&u.bound[c](d),f&&Ko(n,c)),h}):[],u.update(),f=!0,ue(u.before_update),u.fragment=s?s(u.ctx):!1,e.target){if(e.hydrate){const c=Do(e.target);u.fragment&&u.fragment.l(c),c.forEach(W)}else u.fragment&&u.fragment.c();e.intro&&q(n.$$.fragment),se(n,e.target,e.anchor,e.customElement),Oi()}Gt(l)}class Ie{$destroy(){re(this,1),this.$destroy=z}$on(e,t){if(!Ci(t))return z;const s=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return s.push(t),()=>{const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}$set(e){this.$$set&&!Lo(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}function Vo(n){let e,t,s,r,i,o=[{type:"button"},n[4],{class:s=["b3-button",n[3],n[2]].join(" ")},{style:n[1]}],a={};for(let l=0;l{t(4,e=Be(Be({},e),kt(c))),"text"in c&&t(5,o=c.text),"outline"in c&&t(6,a=c.outline),"backgroundColor"in c&&t(7,l=c.backgroundColor),"label"in c&&t(0,u=c.label)},n.$$.update=()=>{n.$$.dirty&64&&t(3,s=a?"b3-button--outline":""),n.$$.dirty&32&&t(2,r=o?"b3-button--text":""),n.$$.dirty&128&&t(1,i=l?`background-color: ${l}`:"")},e=kt(e),[u,i,r,s,e,o,a,l,f]}class Qe extends Ie{constructor(e){super(),xe(this,e,Qo,Vo,Te,{text:5,outline:6,backgroundColor:7,label:0})}}function Yo(n){let e,t,s,r=[n[1],{class:"b3-switch"},{type:"checkbox"}],i={};for(let o=0;o{t(1,e=Be(Be({},e),kt(o))),"value"in o&&t(0,s=o.value)},e=kt(e),[s,e,r,i]}class ea extends Ie{constructor(e){super(),xe(this,e,Zo,Yo,Te,{value:0})}}function ta(n){let e,t,s,r,i=[n[1],{class:t=[n[1].class,"b3-text-field"].join(" ")}],o={};for(let a=0;a{t(1,e=Be(Be({},e),kt(o))),"value"in o&&t(0,s=o.value)},e=kt(e),[s,e,r,i]}class sa extends Ie{constructor(e){super(),xe(this,e,na,ta,Te,{value:0})}}function Rr(n,e,t){const s=n.slice();return s[18]=e[t][0],s[19]=e[t][1],s}function ra(n){let e,t,s,r,i,o,a;return{c(){e=C("div"),t=C("input"),g(t,"class","b3-slider fn__size200"),g(t,"id","fontSize"),g(t,"min",s=n[7].min),g(t,"max",r=n[7].max),g(t,"step",i=n[7].step),g(t,"type","range"),g(e,"class","b3-tooltips b3-tooltips__n"),g(e,"aria-label",n[0])},m(l,u){J(l,e,u),y(e,t),Ue(t,n[0]),o||(a=[V(t,"change",n[16]),V(t,"input",n[16]),V(t,"change",n[9])],o=!0)},p(l,u){u&128&&s!==(s=l[7].min)&&g(t,"min",s),u&128&&r!==(r=l[7].max)&&g(t,"max",r),u&128&&i!==(i=l[7].step)&&g(t,"step",i),u&65&&Ue(t,l[0]),u&65&&g(e,"aria-label",l[0])},i:z,o:z,d(l){l&&W(e),o=!1,ue(a)}}}function ia(n){let e,t,s,r=Object.entries(n[6]),i=[];for(let o=0;on[15].call(e))},m(o,a){J(o,e,a);for(let l=0;lMi(e,"value",r)),e.$on("change",n[9]),{c(){ie(e.$$.fragment)},m(o,a){se(e,o,a),s=!0},p(o,a){const l={};a&16&&(l.id=o[4]),!t&&a&1&&(t=!0,l.value=o[0],Ri(()=>t=!1)),e.$set(l)},i(o){s||(q(e.$$.fragment,o),s=!0)},o(o){G(e.$$.fragment,o),s=!1},d(o){re(e,o)}}}function aa(n){let e,t,s,r;return{c(){e=C("button"),t=oe(n[0]),g(e,"class","b3-button b3-button--outline fn__flex-center fn__size200"),g(e,"id",n[4])},m(i,o){J(i,e,o),y(e,t),s||(r=V(e,"click",n[8]),s=!0)},p(i,o){o&1&&tt(t,i[0]),o&16&&g(e,"id",i[4])},i:z,o:z,d(i){i&&W(e),s=!1,r()}}}function la(n){let e,t,s;return{c(){e=C("input"),g(e,"class","b3-text-field fn__flex-center fn__size200"),g(e,"id",n[4]),g(e,"type","number")},m(r,i){J(r,e,i),Ue(e,n[0]),t||(s=[V(e,"input",n[13]),V(e,"change",n[9])],t=!0)},p(r,i){i&16&&g(e,"id",r[4]),i&65&&Ms(e.value)!==r[0]&&Ue(e,r[0])},i:z,o:z,d(r){r&&W(e),t=!1,ue(s)}}}function ca(n){let e,t,s;function r(o){n[12](o)}let i={class:"b3-text-field fn__flex-center fn__size200",rows:"6",placeholder:n[5]};return n[0]!==void 0&&(i.value=n[0]),e=new sa({props:i}),Vt.push(()=>Mi(e,"value",r)),e.$on("change",n[9]),{c(){ie(e.$$.fragment)},m(o,a){se(e,o,a),s=!0},p(o,a){const l={};a&32&&(l.placeholder=o[5]),!t&&a&1&&(t=!0,l.value=o[0],Ri(()=>t=!1)),e.$set(l)},i(o){s||(q(e.$$.fragment,o),s=!0)},o(o){G(e.$$.fragment,o),s=!1},d(o){re(e,o)}}}function ua(n){let e,t,s;return{c(){e=C("input"),g(e,"class","b3-text-field fn__flex-center fn__size200"),g(e,"id",n[4]),g(e,"placeholder",n[5])},m(r,i){J(r,e,i),Ue(e,n[0]),t||(s=[V(e,"input",n[11]),V(e,"change",n[9])],t=!0)},p(r,i){i&16&&g(e,"id",r[4]),i&32&&g(e,"placeholder",r[5]),i&65&&e.value!==r[0]&&Ue(e,r[0])},i:z,o:z,d(r){r&&W(e),t=!1,ue(s)}}}function fa(n){let e,t,s;return{c(){e=C("input"),g(e,"class","b3-switch fn__flex-center"),g(e,"id",n[4]),g(e,"type","checkbox")},m(r,i){J(r,e,i),e.checked=n[0],t||(s=[V(e,"change",n[10]),V(e,"change",n[9])],t=!0)},p(r,i){i&16&&g(e,"id",r[4]),i&65&&(e.checked=r[0])},i:z,o:z,d(r){r&&W(e),t=!1,ue(s)}}}function Or(n){let e,t=n[19]+"",s,r;return{c(){e=C("option"),s=oe(t),e.__value=r=n[18],e.value=e.__value},m(i,o){J(i,e,o),y(e,s)},p(i,o){o&64&&t!==(t=i[19]+"")&&tt(s,t),o&64&&r!==(r=i[18])&&(e.__value=r,e.value=e.__value)},d(i){i&&W(e)}}}function da(n){let e,t,s,r,i,o,a,l,u,f,c;const h=[fa,ua,ca,la,aa,oa,ia,ra],b=[];function d(p,m){return p[1]==="checkbox"?0:p[1]==="textinput"?1:p[1]==="textarea"?2:p[1]==="number"?3:p[1]==="button"?4:p[1]==="switch"?5:p[1]==="select"?6:p[1]=="slider"?7:-1}return~(u=d(n))&&(f=b[u]=h[u](n)),{c(){e=C("label"),t=C("div"),s=oe(n[2]),r=B(),i=C("div"),o=B(),a=C("span"),l=B(),f&&f.c(),g(i,"class","b3-label__text"),g(t,"class","fn__flex-1"),g(a,"class","fn__space"),g(e,"class","fn__flex b3-label")},m(p,m){J(p,e,m),y(e,t),y(t,s),y(t,r),y(t,i),i.innerHTML=n[3],y(e,o),y(e,a),y(e,l),~u&&b[u].m(e,null),c=!0},p(p,[m]){(!c||m&4)&&tt(s,p[2]),(!c||m&8)&&(i.innerHTML=p[3]);let S=u;u=d(p),u===S?~u&&b[u].p(p,m):(f&&(Pt(),G(b[S],1,1,()=>{b[S]=null}),vt()),~u?(f=b[u],f?f.p(p,m):(f=b[u]=h[u](p),f.c()),q(f,1),f.m(e,null)):f=null)},i(p){c||(q(f),c=!0)},o(p){G(f),c=!1},d(p){p&&W(e),~u&&b[u].d()}}}function ha(n,e,t){let{type:s}=e,{title:r}=e,{description:i}=e,{settingKey:o}=e,{settingValue:a}=e,{placeholder:l=""}=e,{options:u={}}=e,{slider:f={min:0,max:100,step:1}}=e;const c=$o();function h(){c("clicked")}function b(){c("changed",{key:o,value:a})}function d(){a=this.checked,t(0,a),t(6,u)}function p(){a=this.value,t(0,a),t(6,u)}function m(A){a=A,t(0,a)}function S(){a=Ms(this.value),t(0,a),t(6,u)}function k(A){a=A,t(0,a)}function E(){a=Uo(this),t(0,a),t(6,u)}function P(){a=Ms(this.value),t(0,a),t(6,u)}return n.$$set=A=>{"type"in A&&t(1,s=A.type),"title"in A&&t(2,r=A.title),"description"in A&&t(3,i=A.description),"settingKey"in A&&t(4,o=A.settingKey),"settingValue"in A&&t(0,a=A.settingValue),"placeholder"in A&&t(5,l=A.placeholder),"options"in A&&t(6,u=A.options),"slider"in A&&t(7,f=A.slider)},[a,s,r,i,o,l,u,f,h,b,d,p,m,S,k,E,P]}class Zs extends Ie{constructor(e){super(),xe(this,e,ha,da,Te,{type:1,title:2,description:3,settingKey:4,settingValue:0,placeholder:5,options:6,slider:7})}}var j;(function(n){n[n.PLAIN_TO_CLASS=0]="PLAIN_TO_CLASS",n[n.CLASS_TO_PLAIN=1]="CLASS_TO_PLAIN",n[n.CLASS_TO_CLASS=2]="CLASS_TO_CLASS"})(j||(j={}));var pa=function(){function n(){this._typeMetadatas=new Map,this._transformMetadatas=new Map,this._exposeMetadatas=new Map,this._excludeMetadatas=new Map,this._ancestorsMap=new Map}return n.prototype.addTypeMetadata=function(e){this._typeMetadatas.has(e.target)||this._typeMetadatas.set(e.target,new Map),this._typeMetadatas.get(e.target).set(e.propertyName,e)},n.prototype.addTransformMetadata=function(e){this._transformMetadatas.has(e.target)||this._transformMetadatas.set(e.target,new Map),this._transformMetadatas.get(e.target).has(e.propertyName)||this._transformMetadatas.get(e.target).set(e.propertyName,[]),this._transformMetadatas.get(e.target).get(e.propertyName).push(e)},n.prototype.addExposeMetadata=function(e){this._exposeMetadatas.has(e.target)||this._exposeMetadatas.set(e.target,new Map),this._exposeMetadatas.get(e.target).set(e.propertyName,e)},n.prototype.addExcludeMetadata=function(e){this._excludeMetadatas.has(e.target)||this._excludeMetadatas.set(e.target,new Map),this._excludeMetadatas.get(e.target).set(e.propertyName,e)},n.prototype.findTransformMetadatas=function(e,t,s){return this.findMetadatas(this._transformMetadatas,e,t).filter(function(r){return!r.options||r.options.toClassOnly===!0&&r.options.toPlainOnly===!0?!0:r.options.toClassOnly===!0?s===j.CLASS_TO_CLASS||s===j.PLAIN_TO_CLASS:r.options.toPlainOnly===!0?s===j.CLASS_TO_PLAIN:!0})},n.prototype.findExcludeMetadata=function(e,t){return this.findMetadata(this._excludeMetadatas,e,t)},n.prototype.findExposeMetadata=function(e,t){return this.findMetadata(this._exposeMetadatas,e,t)},n.prototype.findExposeMetadataByCustomName=function(e,t){return this.getExposedMetadatas(e).find(function(s){return s.options&&s.options.name===t})},n.prototype.findTypeMetadata=function(e,t){return this.findMetadata(this._typeMetadatas,e,t)},n.prototype.getStrategy=function(e){var t=this._excludeMetadatas.get(e),s=t&&t.get(void 0),r=this._exposeMetadatas.get(e),i=r&&r.get(void 0);return s&&i||!s&&!i?"none":s?"excludeAll":"exposeAll"},n.prototype.getExposedMetadatas=function(e){return this.getMetadata(this._exposeMetadatas,e)},n.prototype.getExcludedMetadatas=function(e){return this.getMetadata(this._excludeMetadatas,e)},n.prototype.getExposedProperties=function(e,t){return this.getExposedMetadatas(e).filter(function(s){return!s.options||s.options.toClassOnly===!0&&s.options.toPlainOnly===!0?!0:s.options.toClassOnly===!0?t===j.CLASS_TO_CLASS||t===j.PLAIN_TO_CLASS:s.options.toPlainOnly===!0?t===j.CLASS_TO_PLAIN:!0}).map(function(s){return s.propertyName})},n.prototype.getExcludedProperties=function(e,t){return this.getExcludedMetadatas(e).filter(function(s){return!s.options||s.options.toClassOnly===!0&&s.options.toPlainOnly===!0?!0:s.options.toClassOnly===!0?t===j.CLASS_TO_CLASS||t===j.PLAIN_TO_CLASS:s.options.toPlainOnly===!0?t===j.CLASS_TO_PLAIN:!0}).map(function(s){return s.propertyName})},n.prototype.clear=function(){this._typeMetadatas.clear(),this._exposeMetadatas.clear(),this._excludeMetadatas.clear(),this._ancestorsMap.clear()},n.prototype.getMetadata=function(e,t){var s=e.get(t),r;s&&(r=Array.from(s.values()).filter(function(c){return c.propertyName!==void 0}));for(var i=[],o=0,a=this.getAncestors(t);o0&&(o=o.filter(function(c){return!u.includes(c)})),this.options.version!==void 0&&(o=o.filter(function(c){var h=_e.findExposeMetadata(e,c);return!h||!h.options?!0:r.checkVersion(h.options.since,h.options.until)})),this.options.groups&&this.options.groups.length?o=o.filter(function(c){var h=_e.findExposeMetadata(e,c);return!h||!h.options?!0:r.checkGroups(h.options.groups)}):o=o.filter(function(c){var h=_e.findExposeMetadata(e,c);return!h||!h.options||!h.options.groups||!h.options.groups.length})}return this.options.excludePrefixes&&this.options.excludePrefixes.length&&(o=o.filter(function(f){return r.options.excludePrefixes.every(function(c){return f.substr(0,c.length)!==c})})),o=o.filter(function(f,c,h){return h.indexOf(f)===c}),o},n.prototype.checkVersion=function(e,t){var s=!0;return s&&e&&(s=this.options.version>=e),s&&t&&(s=this.options.version(n.click_editorcontent="click-editorcontent",n.open_menu_doctree="open-menu-doctree",n.loaded_protyle_static="loaded-protyle-static",n.loaded_protyle_dynamic="loaded-protyle-dynamic",n.switch_protyle="switch-protyle",n.destroy_protyle="destroy-protyle",n.ws_main="ws-main",n.click_flashcard_action="click-flashcard-action",n.click_blockicon="click-blockicon",n.click_pdf="click-pdf",n.click_editortitleicon="click-editortitleicon",n.open_noneditableblock="open-noneditableblock",n.open_menu_blockref="open-menu-blockref",n.open_menu_fileannotationref="open-menu-fileannotationref",n.open_menu_tag="open-menu-tag",n.open_menu_link="open-menu-link",n.open_menu_image="open-menu-image",n.open_menu_av="open-menu-av",n.open_menu_content="open-menu-content",n.open_menu_breadcrumbmore="open-menu-breadcrumbmore",n.input_search="input-search",n.paste="paste",n.open_siyuan_url_plugin="open-siyuan-url-plugin",n.open_siyuan_url_block="open-siyuan-url-block",n))(Ti||{}),M=(n=>(n.SERVICE_PROVIDER="ai-service-provider",n.TIMEOUT="ai-request-timeout",n.GENERATE_MAX_TOKEN="ai-generate-max-token",n.REQUEST_MAX_TOKEN="ai-request-max-token",n.TEMPERATURE="ai-temperature",n.MODEL="ai-model",n.API_KEY="ai-api-key",n.BASE_URL="ai-endpoint",n.hint="ai-hint",n.PROMPT_TITLE="ai-prompt-title",n.PROMPT="ai-prompt-content",n.IMG_PROMPT="ai-img-prompt",n.IMG_PROMTP_TITLE="ai-img-prompt-title",n.IMG_MODEL="ai-img-model",n.IMG_NUM="ai-img-number",n.IMG_SIZE="ai-img-size",n.IMG_QUALITY="ai-img-quality",n.STREAM="ai-stream",n))(M||{}),fe=(n=>(n.checkbox="checkbox",n.select="select",n.textinput="textinput",n.textarea="textarea",n.number="number",n.slider="slider",n.button="button",n.hint="hint",n.switch="switch",n))(fe||{});class it{}ee(it,"PLUGIN_NAME","siyuan-ai"),ee(it,"AI_SETTING_STORAGE","siyuan-ai-settings.json"),ee(it,"AI_PROMPT_STORAGE","siyuan-ai-prompts.json"),ee(it,"IS_DEVELOP","false");function xi(n,e){return function(){return n.apply(e,arguments)}}const{toString:Sa}=Object.prototype,{getPrototypeOf:er}=Object,rs=(n=>e=>{const t=Sa.call(e);return n[t]||(n[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),He=n=>(n=n.toLowerCase(),e=>rs(e)===n),is=n=>e=>typeof e===n,{isArray:Ot}=Array,Qt=is("undefined");function Aa(n){return n!==null&&!Qt(n)&&n.constructor!==null&&!Qt(n.constructor)&&Ee(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}const Ii=He("ArrayBuffer");function Ea(n){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(n):e=n&&n.buffer&&Ii(n.buffer),e}const ka=is("string"),Ee=is("function"),Li=is("number"),os=n=>n!==null&&typeof n=="object",Ca=n=>n===!0||n===!1,hn=n=>{if(rs(n)!=="object")return!1;const e=er(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},Pa=He("Date"),va=He("File"),Ra=He("Blob"),Oa=He("FileList"),Ma=n=>os(n)&&Ee(n.pipe),Ta=n=>{let e;return n&&(typeof FormData=="function"&&n instanceof FormData||Ee(n.append)&&((e=rs(n))==="formdata"||e==="object"&&Ee(n.toString)&&n.toString()==="[object FormData]"))},xa=He("URLSearchParams"),Ia=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tn(n,e,{allOwnKeys:t=!1}={}){if(n===null||typeof n>"u")return;let s,r;if(typeof n!="object"&&(n=[n]),Ot(n))for(s=0,r=n.length;s0;)if(r=t[s],e===r.toLowerCase())return r;return null}const Ni=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),Di=n=>!Qt(n)&&n!==Ni;function Is(){const{caseless:n}=Di(this)&&this||{},e={},t=(s,r)=>{const i=n&&Fi(e,r)||r;hn(e[i])&&hn(s)?e[i]=Is(e[i],s):hn(s)?e[i]=Is({},s):Ot(s)?e[i]=s.slice():e[i]=s};for(let s=0,r=arguments.length;s(tn(e,(r,i)=>{t&&Ee(r)?n[i]=xi(r,t):n[i]=r},{allOwnKeys:s}),n),Fa=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),Na=(n,e,t,s)=>{n.prototype=Object.create(e.prototype,s),n.prototype.constructor=n,Object.defineProperty(n,"super",{value:e.prototype}),t&&Object.assign(n.prototype,t)},Da=(n,e,t,s)=>{let r,i,o;const a={};if(e=e||{},n==null)return e;do{for(r=Object.getOwnPropertyNames(n),i=r.length;i-- >0;)o=r[i],(!s||s(o,n,e))&&!a[o]&&(e[o]=n[o],a[o]=!0);n=t!==!1&&er(n)}while(n&&(!t||t(n,e))&&n!==Object.prototype);return e},ja=(n,e,t)=>{n=String(n),(t===void 0||t>n.length)&&(t=n.length),t-=e.length;const s=n.indexOf(e,t);return s!==-1&&s===t},Ba=n=>{if(!n)return null;if(Ot(n))return n;let e=n.length;if(!Li(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=n[e];return t},Ua=(n=>e=>n&&e instanceof n)(typeof Uint8Array<"u"&&er(Uint8Array)),qa=(n,e)=>{const s=(n&&n[Symbol.iterator]).call(n);let r;for(;(r=s.next())&&!r.done;){const i=r.value;e.call(n,i[0],i[1])}},Ha=(n,e)=>{let t;const s=[];for(;(t=n.exec(e))!==null;)s.push(t);return s},$a=He("HTMLFormElement"),Wa=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,s,r){return s.toUpperCase()+r}),Tr=(({hasOwnProperty:n})=>(e,t)=>n.call(e,t))(Object.prototype),Ga=He("RegExp"),ji=(n,e)=>{const t=Object.getOwnPropertyDescriptors(n),s={};tn(t,(r,i)=>{let o;(o=e(r,i,n))!==!1&&(s[i]=o||r)}),Object.defineProperties(n,s)},za=n=>{ji(n,(e,t)=>{if(Ee(n)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const s=n[t];if(Ee(s)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},Ja=(n,e)=>{const t={},s=r=>{r.forEach(i=>{t[i]=!0})};return Ot(n)?s(n):s(String(n).split(e)),t},Xa=()=>{},Ka=(n,e)=>(n=+n,Number.isFinite(n)?n:e),ps="abcdefghijklmnopqrstuvwxyz",xr="0123456789",Bi={DIGIT:xr,ALPHA:ps,ALPHA_DIGIT:ps+ps.toUpperCase()+xr},Va=(n=16,e=Bi.ALPHA_DIGIT)=>{let t="";const{length:s}=e;for(;n--;)t+=e[Math.random()*s|0];return t};function Qa(n){return!!(n&&Ee(n.append)&&n[Symbol.toStringTag]==="FormData"&&n[Symbol.iterator])}const Ya=n=>{const e=new Array(10),t=(s,r)=>{if(os(s)){if(e.indexOf(s)>=0)return;if(!("toJSON"in s)){e[r]=s;const i=Ot(s)?[]:{};return tn(s,(o,a)=>{const l=t(o,r+1);!Qt(l)&&(i[a]=l)}),e[r]=void 0,i}}return s};return t(n,0)},Za=He("AsyncFunction"),el=n=>n&&(os(n)||Ee(n))&&Ee(n.then)&&Ee(n.catch),_={isArray:Ot,isArrayBuffer:Ii,isBuffer:Aa,isFormData:Ta,isArrayBufferView:Ea,isString:ka,isNumber:Li,isBoolean:Ca,isObject:os,isPlainObject:hn,isUndefined:Qt,isDate:Pa,isFile:va,isBlob:Ra,isRegExp:Ga,isFunction:Ee,isStream:Ma,isURLSearchParams:xa,isTypedArray:Ua,isFileList:Oa,forEach:tn,merge:Is,extend:La,trim:Ia,stripBOM:Fa,inherits:Na,toFlatObject:Da,kindOf:rs,kindOfTest:He,endsWith:ja,toArray:Ba,forEachEntry:qa,matchAll:Ha,isHTMLForm:$a,hasOwnProperty:Tr,hasOwnProp:Tr,reduceDescriptors:ji,freezeMethods:za,toObjectSet:Ja,toCamelCase:Wa,noop:Xa,toFiniteNumber:Ka,findKey:Fi,global:Ni,isContextDefined:Di,ALPHABET:Bi,generateString:Va,isSpecCompliantForm:Qa,toJSONObject:Ya,isAsyncFn:Za,isThenable:el};function H(n,e,t,s,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=n,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),s&&(this.request=s),r&&(this.response=r)}_.inherits(H,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const Ui=H.prototype,qi={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(n=>{qi[n]={value:n}});Object.defineProperties(H,qi);Object.defineProperty(Ui,"isAxiosError",{value:!0});H.from=(n,e,t,s,r,i)=>{const o=Object.create(Ui);return _.toFlatObject(n,o,function(l){return l!==Error.prototype},a=>a!=="isAxiosError"),H.call(o,n.message,e,t,s,r),o.cause=n,o.name=n.name,i&&Object.assign(o,i),o};const tl=null;function Ls(n){return _.isPlainObject(n)||_.isArray(n)}function Hi(n){return _.endsWith(n,"[]")?n.slice(0,-2):n}function Ir(n,e,t){return n?n.concat(e).map(function(r,i){return r=Hi(r),!t&&i?"["+r+"]":r}).join(t?".":""):e}function nl(n){return _.isArray(n)&&!n.some(Ls)}const sl=_.toFlatObject(_,{},null,function(e){return/^is[A-Z]/.test(e)});function as(n,e,t){if(!_.isObject(n))throw new TypeError("target must be an object");e=e||new FormData,t=_.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(p,m){return!_.isUndefined(m[p])});const s=t.metaTokens,r=t.visitor||f,i=t.dots,o=t.indexes,l=(t.Blob||typeof Blob<"u"&&Blob)&&_.isSpecCompliantForm(e);if(!_.isFunction(r))throw new TypeError("visitor must be a function");function u(d){if(d===null)return"";if(_.isDate(d))return d.toISOString();if(!l&&_.isBlob(d))throw new H("Blob is not supported. Use a Buffer instead.");return _.isArrayBuffer(d)||_.isTypedArray(d)?l&&typeof Blob=="function"?new Blob([d]):Buffer.from(d):d}function f(d,p,m){let S=d;if(d&&!m&&typeof d=="object"){if(_.endsWith(p,"{}"))p=s?p:p.slice(0,-2),d=JSON.stringify(d);else if(_.isArray(d)&&nl(d)||(_.isFileList(d)||_.endsWith(p,"[]"))&&(S=_.toArray(d)))return p=Hi(p),S.forEach(function(E,P){!(_.isUndefined(E)||E===null)&&e.append(o===!0?Ir([p],P,i):o===null?p:p+"[]",u(E))}),!1}return Ls(d)?!0:(e.append(Ir(m,p,i),u(d)),!1)}const c=[],h=Object.assign(sl,{defaultVisitor:f,convertValue:u,isVisitable:Ls});function b(d,p){if(!_.isUndefined(d)){if(c.indexOf(d)!==-1)throw Error("Circular reference detected in "+p.join("."));c.push(d),_.forEach(d,function(S,k){(!(_.isUndefined(S)||S===null)&&r.call(e,S,_.isString(k)?k.trim():k,p,h))===!0&&b(S,p?p.concat(k):[k])}),c.pop()}}if(!_.isObject(n))throw new TypeError("data must be an object");return b(n),e}function Lr(n){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(n).replace(/[!'()~]|%20|%00/g,function(s){return e[s]})}function tr(n,e){this._pairs=[],n&&as(n,this,e)}const $i=tr.prototype;$i.append=function(e,t){this._pairs.push([e,t])};$i.toString=function(e){const t=e?function(s){return e.call(this,s,Lr)}:Lr;return this._pairs.map(function(r){return t(r[0])+"="+t(r[1])},"").join("&")};function rl(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Wi(n,e,t){if(!e)return n;const s=t&&t.encode||rl,r=t&&t.serialize;let i;if(r?i=r(e,t):i=_.isURLSearchParams(e)?e.toString():new tr(e,t).toString(s),i){const o=n.indexOf("#");o!==-1&&(n=n.slice(0,o)),n+=(n.indexOf("?")===-1?"?":"&")+i}return n}class il{constructor(){this.handlers=[]}use(e,t,s){return this.handlers.push({fulfilled:e,rejected:t,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){_.forEach(this.handlers,function(s){s!==null&&e(s)})}}const Fr=il,Gi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ol=typeof URLSearchParams<"u"?URLSearchParams:tr,al=typeof FormData<"u"?FormData:null,ll=typeof Blob<"u"?Blob:null,cl={isBrowser:!0,classes:{URLSearchParams:ol,FormData:al,Blob:ll},protocols:["http","https","file","blob","url","data"]},zi=typeof window<"u"&&typeof document<"u",ul=(n=>zi&&["ReactNative","NativeScript","NS"].indexOf(n)<0)(typeof navigator<"u"&&navigator.product),fl=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),dl=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:zi,hasStandardBrowserEnv:ul,hasStandardBrowserWebWorkerEnv:fl},Symbol.toStringTag,{value:"Module"})),De={...dl,...cl};function hl(n,e){return as(n,new De.classes.URLSearchParams,Object.assign({visitor:function(t,s,r,i){return De.isNode&&_.isBuffer(t)?(this.append(s,t.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},e))}function pl(n){return _.matchAll(/\w+|\[(\w*)]/g,n).map(e=>e[0]==="[]"?"":e[1]||e[0])}function ml(n){const e={},t=Object.keys(n);let s;const r=t.length;let i;for(s=0;s=t.length;return o=!o&&_.isArray(r)?r.length:o,l?(_.hasOwnProp(r,o)?r[o]=[r[o],s]:r[o]=s,!a):((!r[o]||!_.isObject(r[o]))&&(r[o]=[]),e(t,s,r[o],i)&&_.isArray(r[o])&&(r[o]=ml(r[o])),!a)}if(_.isFormData(n)&&_.isFunction(n.entries)){const t={};return _.forEachEntry(n,(s,r)=>{e(pl(s),r,t,0)}),t}return null}function _l(n,e,t){if(_.isString(n))try{return(e||JSON.parse)(n),_.trim(n)}catch(s){if(s.name!=="SyntaxError")throw s}return(t||JSON.stringify)(n)}const nr={transitional:Gi,adapter:["xhr","http"],transformRequest:[function(e,t){const s=t.getContentType()||"",r=s.indexOf("application/json")>-1,i=_.isObject(e);if(i&&_.isHTMLForm(e)&&(e=new FormData(e)),_.isFormData(e))return r?JSON.stringify(Ji(e)):e;if(_.isArrayBuffer(e)||_.isBuffer(e)||_.isStream(e)||_.isFile(e)||_.isBlob(e))return e;if(_.isArrayBufferView(e))return e.buffer;if(_.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(i){if(s.indexOf("application/x-www-form-urlencoded")>-1)return hl(e,this.formSerializer).toString();if((a=_.isFileList(e))||s.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return as(a?{"files[]":e}:e,l&&new l,this.formSerializer)}}return i||r?(t.setContentType("application/json",!1),_l(e)):e}],transformResponse:[function(e){const t=this.transitional||nr.transitional,s=t&&t.forcedJSONParsing,r=this.responseType==="json";if(e&&_.isString(e)&&(s&&!this.responseType||r)){const o=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?H.from(a,H.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:De.classes.FormData,Blob:De.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_.forEach(["delete","get","head","post","put","patch"],n=>{nr.headers[n]={}});const sr=nr,gl=_.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),bl=n=>{const e={};let t,s,r;return n&&n.split(` -`).forEach(function(o){r=o.indexOf(":"),t=o.substring(0,r).trim().toLowerCase(),s=o.substring(r+1).trim(),!(!t||e[t]&&gl[t])&&(t==="set-cookie"?e[t]?e[t].push(s):e[t]=[s]:e[t]=e[t]?e[t]+", "+s:s)}),e},Nr=Symbol("internals");function Lt(n){return n&&String(n).trim().toLowerCase()}function pn(n){return n===!1||n==null?n:_.isArray(n)?n.map(pn):String(n)}function yl(n){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=t.exec(n);)e[s[1]]=s[2];return e}const wl=n=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(n.trim());function ms(n,e,t,s,r){if(_.isFunction(s))return s.call(this,e,t);if(r&&(e=t),!!_.isString(e)){if(_.isString(s))return e.indexOf(s)!==-1;if(_.isRegExp(s))return s.test(e)}}function Sl(n){return n.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,s)=>t.toUpperCase()+s)}function Al(n,e){const t=_.toCamelCase(" "+e);["get","set","has"].forEach(s=>{Object.defineProperty(n,s+t,{value:function(r,i,o){return this[s].call(this,e,r,i,o)},configurable:!0})})}class ls{constructor(e){e&&this.set(e)}set(e,t,s){const r=this;function i(a,l,u){const f=Lt(l);if(!f)throw new Error("header name must be a non-empty string");const c=_.findKey(r,f);(!c||r[c]===void 0||u===!0||u===void 0&&r[c]!==!1)&&(r[c||l]=pn(a))}const o=(a,l)=>_.forEach(a,(u,f)=>i(u,f,l));return _.isPlainObject(e)||e instanceof this.constructor?o(e,t):_.isString(e)&&(e=e.trim())&&!wl(e)?o(bl(e),t):e!=null&&i(t,e,s),this}get(e,t){if(e=Lt(e),e){const s=_.findKey(this,e);if(s){const r=this[s];if(!t)return r;if(t===!0)return yl(r);if(_.isFunction(t))return t.call(this,r,s);if(_.isRegExp(t))return t.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Lt(e),e){const s=_.findKey(this,e);return!!(s&&this[s]!==void 0&&(!t||ms(this,this[s],s,t)))}return!1}delete(e,t){const s=this;let r=!1;function i(o){if(o=Lt(o),o){const a=_.findKey(s,o);a&&(!t||ms(s,s[a],a,t))&&(delete s[a],r=!0)}}return _.isArray(e)?e.forEach(i):i(e),r}clear(e){const t=Object.keys(this);let s=t.length,r=!1;for(;s--;){const i=t[s];(!e||ms(this,this[i],i,e,!0))&&(delete this[i],r=!0)}return r}normalize(e){const t=this,s={};return _.forEach(this,(r,i)=>{const o=_.findKey(s,i);if(o){t[o]=pn(r),delete t[i];return}const a=e?Sl(i):String(i).trim();a!==i&&delete t[i],t[a]=pn(r),s[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return _.forEach(this,(s,r)=>{s!=null&&s!==!1&&(t[r]=e&&_.isArray(s)?s.join(", "):s)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(` -`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const s=new this(e);return t.forEach(r=>s.set(r)),s}static accessor(e){const s=(this[Nr]=this[Nr]={accessors:{}}).accessors,r=this.prototype;function i(o){const a=Lt(o);s[a]||(Al(r,o),s[a]=!0)}return _.isArray(e)?e.forEach(i):i(e),this}}ls.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_.reduceDescriptors(ls.prototype,({value:n},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>n,set(s){this[t]=s}}});_.freezeMethods(ls);const ze=ls;function _s(n,e){const t=this||sr,s=e||t,r=ze.from(s.headers);let i=s.data;return _.forEach(n,function(a){i=a.call(t,i,r.normalize(),e?e.status:void 0)}),r.normalize(),i}function Xi(n){return!!(n&&n.__CANCEL__)}function nn(n,e,t){H.call(this,n??"canceled",H.ERR_CANCELED,e,t),this.name="CanceledError"}_.inherits(nn,H,{__CANCEL__:!0});function El(n,e,t){const s=t.config.validateStatus;!t.status||!s||s(t.status)?n(t):e(new H("Request failed with status code "+t.status,[H.ERR_BAD_REQUEST,H.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}const kl=De.hasStandardBrowserEnv?{write(n,e,t,s,r,i){const o=[n+"="+encodeURIComponent(e)];_.isNumber(t)&&o.push("expires="+new Date(t).toGMTString()),_.isString(s)&&o.push("path="+s),_.isString(r)&&o.push("domain="+r),i===!0&&o.push("secure"),document.cookie=o.join("; ")},read(n){const e=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(n){this.write(n,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Cl(n){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}function Pl(n,e){return e?n.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):n}function Ki(n,e){return n&&!Cl(e)?Pl(n,e):e}const vl=De.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let s;function r(i){let o=i;return e&&(t.setAttribute("href",o),o=t.href),t.setAttribute("href",o),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:t.pathname.charAt(0)==="/"?t.pathname:"/"+t.pathname}}return s=r(window.location.href),function(o){const a=_.isString(o)?r(o):o;return a.protocol===s.protocol&&a.host===s.host}}():function(){return function(){return!0}}();function Rl(n){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(n);return e&&e[1]||""}function Ol(n,e){n=n||10;const t=new Array(n),s=new Array(n);let r=0,i=0,o;return e=e!==void 0?e:1e3,function(l){const u=Date.now(),f=s[i];o||(o=u),t[r]=l,s[r]=u;let c=i,h=0;for(;c!==r;)h+=t[c++],c=c%n;if(r=(r+1)%n,r===i&&(i=(i+1)%n),u-o{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-t,l=s(a),u=i<=o;t=i;const f={loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:l||void 0,estimated:l&&o&&u?(o-i)/l:void 0,event:r};f[e?"download":"upload"]=!0,n(f)}}const Ml=typeof XMLHttpRequest<"u",Tl=Ml&&function(n){return new Promise(function(t,s){let r=n.data;const i=ze.from(n.headers).normalize();let{responseType:o,withXSRFToken:a}=n,l;function u(){n.cancelToken&&n.cancelToken.unsubscribe(l),n.signal&&n.signal.removeEventListener("abort",l)}let f;if(_.isFormData(r)){if(De.hasStandardBrowserEnv||De.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((f=i.getContentType())!==!1){const[p,...m]=f?f.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([p||"multipart/form-data",...m].join("; "))}}let c=new XMLHttpRequest;if(n.auth){const p=n.auth.username||"",m=n.auth.password?unescape(encodeURIComponent(n.auth.password)):"";i.set("Authorization","Basic "+btoa(p+":"+m))}const h=Ki(n.baseURL,n.url);c.open(n.method.toUpperCase(),Wi(h,n.params,n.paramsSerializer),!0),c.timeout=n.timeout;function b(){if(!c)return;const p=ze.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),S={data:!o||o==="text"||o==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:p,config:n,request:c};El(function(E){t(E),u()},function(E){s(E),u()},S),c=null}if("onloadend"in c?c.onloadend=b:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(b)},c.onabort=function(){c&&(s(new H("Request aborted",H.ECONNABORTED,n,c)),c=null)},c.onerror=function(){s(new H("Network Error",H.ERR_NETWORK,n,c)),c=null},c.ontimeout=function(){let m=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const S=n.transitional||Gi;n.timeoutErrorMessage&&(m=n.timeoutErrorMessage),s(new H(m,S.clarifyTimeoutError?H.ETIMEDOUT:H.ECONNABORTED,n,c)),c=null},De.hasStandardBrowserEnv&&(a&&_.isFunction(a)&&(a=a(n)),a||a!==!1&&vl(h))){const p=n.xsrfHeaderName&&n.xsrfCookieName&&kl.read(n.xsrfCookieName);p&&i.set(n.xsrfHeaderName,p)}r===void 0&&i.setContentType(null),"setRequestHeader"in c&&_.forEach(i.toJSON(),function(m,S){c.setRequestHeader(S,m)}),_.isUndefined(n.withCredentials)||(c.withCredentials=!!n.withCredentials),o&&o!=="json"&&(c.responseType=n.responseType),typeof n.onDownloadProgress=="function"&&c.addEventListener("progress",Dr(n.onDownloadProgress,!0)),typeof n.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",Dr(n.onUploadProgress)),(n.cancelToken||n.signal)&&(l=p=>{c&&(s(!p||p.type?new nn(null,n,c):p),c.abort(),c=null)},n.cancelToken&&n.cancelToken.subscribe(l),n.signal&&(n.signal.aborted?l():n.signal.addEventListener("abort",l)));const d=Rl(h);if(d&&De.protocols.indexOf(d)===-1){s(new H("Unsupported protocol "+d+":",H.ERR_BAD_REQUEST,n));return}c.send(r||null)})},Fs={http:tl,xhr:Tl};_.forEach(Fs,(n,e)=>{if(n){try{Object.defineProperty(n,"name",{value:e})}catch{}Object.defineProperty(n,"adapterName",{value:e})}});const jr=n=>`- ${n}`,xl=n=>_.isFunction(n)||n===null||n===!1,Vi={getAdapter:n=>{n=_.isArray(n)?n:[n];const{length:e}=n;let t,s;const r={};for(let i=0;i`adapter ${a} `+(l===!1?"is not supported by the environment":"is not available in the build"));let o=e?i.length>1?`since : -`+i.map(jr).join(` -`):" "+jr(i[0]):"as no adapter specified";throw new H("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return s},adapters:Fs};function gs(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new nn(null,n)}function Br(n){return gs(n),n.headers=ze.from(n.headers),n.data=_s.call(n,n.transformRequest),["post","put","patch"].indexOf(n.method)!==-1&&n.headers.setContentType("application/x-www-form-urlencoded",!1),Vi.getAdapter(n.adapter||sr.adapter)(n).then(function(s){return gs(n),s.data=_s.call(n,n.transformResponse,s),s.headers=ze.from(s.headers),s},function(s){return Xi(s)||(gs(n),s&&s.response&&(s.response.data=_s.call(n,n.transformResponse,s.response),s.response.headers=ze.from(s.response.headers))),Promise.reject(s)})}const Ur=n=>n instanceof ze?{...n}:n;function Rt(n,e){e=e||{};const t={};function s(u,f,c){return _.isPlainObject(u)&&_.isPlainObject(f)?_.merge.call({caseless:c},u,f):_.isPlainObject(f)?_.merge({},f):_.isArray(f)?f.slice():f}function r(u,f,c){if(_.isUndefined(f)){if(!_.isUndefined(u))return s(void 0,u,c)}else return s(u,f,c)}function i(u,f){if(!_.isUndefined(f))return s(void 0,f)}function o(u,f){if(_.isUndefined(f)){if(!_.isUndefined(u))return s(void 0,u)}else return s(void 0,f)}function a(u,f,c){if(c in e)return s(u,f);if(c in n)return s(void 0,u)}const l={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(u,f)=>r(Ur(u),Ur(f),!0)};return _.forEach(Object.keys(Object.assign({},n,e)),function(f){const c=l[f]||r,h=c(n[f],e[f],f);_.isUndefined(h)&&c!==a||(t[f]=h)}),t}const Qi="1.6.8",rr={};["object","boolean","number","function","string","symbol"].forEach((n,e)=>{rr[n]=function(s){return typeof s===n||"a"+(e<1?"n ":" ")+n}});const qr={};rr.transitional=function(e,t,s){function r(i,o){return"[Axios v"+Qi+"] Transitional option '"+i+"'"+o+(s?". "+s:"")}return(i,o,a)=>{if(e===!1)throw new H(r(o," has been removed"+(t?" in "+t:"")),H.ERR_DEPRECATED);return t&&!qr[o]&&(qr[o]=!0,console.warn(r(o," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(i,o,a):!0}};function Il(n,e,t){if(typeof n!="object")throw new H("options must be an object",H.ERR_BAD_OPTION_VALUE);const s=Object.keys(n);let r=s.length;for(;r-- >0;){const i=s[r],o=e[i];if(o){const a=n[i],l=a===void 0||o(a,i,n);if(l!==!0)throw new H("option "+i+" must be "+l,H.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new H("Unknown option "+i,H.ERR_BAD_OPTION)}}const Ns={assertOptions:Il,validators:rr},Ke=Ns.validators;class xn{constructor(e){this.defaults=e,this.interceptors={request:new Fr,response:new Fr}}async request(e,t){try{return await this._request(e,t)}catch(s){if(s instanceof Error){let r;Error.captureStackTrace?Error.captureStackTrace(r={}):r=new Error;const i=r.stack?r.stack.replace(/^.+\n/,""):"";s.stack?i&&!String(s.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(s.stack+=` -`+i):s.stack=i}throw s}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Rt(this.defaults,t);const{transitional:s,paramsSerializer:r,headers:i}=t;s!==void 0&&Ns.assertOptions(s,{silentJSONParsing:Ke.transitional(Ke.boolean),forcedJSONParsing:Ke.transitional(Ke.boolean),clarifyTimeoutError:Ke.transitional(Ke.boolean)},!1),r!=null&&(_.isFunction(r)?t.paramsSerializer={serialize:r}:Ns.assertOptions(r,{encode:Ke.function,serialize:Ke.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=i&&_.merge(i.common,i[t.method]);i&&_.forEach(["delete","get","head","post","put","patch","common"],d=>{delete i[d]}),t.headers=ze.concat(o,i);const a=[];let l=!0;this.interceptors.request.forEach(function(p){typeof p.runWhen=="function"&&p.runWhen(t)===!1||(l=l&&p.synchronous,a.unshift(p.fulfilled,p.rejected))});const u=[];this.interceptors.response.forEach(function(p){u.push(p.fulfilled,p.rejected)});let f,c=0,h;if(!l){const d=[Br.bind(this),void 0];for(d.unshift.apply(d,a),d.push.apply(d,u),h=d.length,f=Promise.resolve(t);c{if(!s._listeners)return;let i=s._listeners.length;for(;i-- >0;)s._listeners[i](r);s._listeners=null}),this.promise.then=r=>{let i;const o=new Promise(a=>{s.subscribe(a),i=a}).then(r);return o.cancel=function(){s.unsubscribe(i)},o},e(function(i,o,a){s.reason||(s.reason=new nn(i,o,a),t(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}static source(){let e;return{token:new ir(function(r){e=r}),cancel:e}}}const Ll=ir;function Fl(n){return function(t){return n.apply(null,t)}}function Nl(n){return _.isObject(n)&&n.isAxiosError===!0}const Ds={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ds).forEach(([n,e])=>{Ds[e]=n});const Dl=Ds;function Yi(n){const e=new mn(n),t=xi(mn.prototype.request,e);return _.extend(t,mn.prototype,e,{allOwnKeys:!0}),_.extend(t,e,null,{allOwnKeys:!0}),t.create=function(r){return Yi(Rt(n,r))},t}const te=Yi(sr);te.Axios=mn;te.CanceledError=nn;te.CancelToken=Ll;te.isCancel=Xi;te.VERSION=Qi;te.toFormData=as;te.AxiosError=H;te.Cancel=te.CanceledError;te.all=function(e){return Promise.all(e)};te.spread=Fl;te.isAxiosError=Nl;te.mergeConfig=Rt;te.AxiosHeaders=ze;te.formToJSON=n=>Ji(_.isHTMLForm(n)?new FormData(n):n);te.getAdapter=Vi.getAdapter;te.HttpStatusCode=Dl;te.default=te;const jl=te;async function bs(n){var t,s,r;return n?(r=(s=(t=(await Hl("markdown","",n))[0])==null?void 0:t.doOperations)==null?void 0:s[0])==null?void 0:r.id:""}function Zi(n,e){if(n){if(n instanceof Element&&n.getAttribute("data-node-id"))if(e){if(e.reduce((s,r)=>s&&n.hasAttribute(r),!0))return n}else return n;return Zi(n.parentElement,e)}}function Bl(){const n=document.getSelection();return Zi(n==null?void 0:n.focusNode)}function Ul(n){return[/( \{:.*?\})\n/gm,/{:.*?\}/gm,/^ +(?=[\d\*])/gm].forEach(t=>{n=n.replace(t,"")}),n}async function Hr(n){let e=[];for(let t of n){if(!t||!t.className.includes("select"))continue;let s=await $l(t.dataset.nodeId);e.push(Ul(s.kramdown))}return e.join(` -`)}async function ql(n,e,t){e=e.endsWith(".png")?e:`${e}.png`;const s=`/data/assets/${t}/text2img/${e}`,r=Buffer.from(n,"base64");let i=new File([new Blob([r])],s.split("/").pop());const o=new FormData;return o.append("path",s),o.append("file",i),o.append("isDir","false"),Ge.fetchPost("/api/file/putFile",o,()=>{}),s}async function $r(n){var s;if(!n||n.length==0)return[0,0];const e={method:"POST",url:"https://fastapi.geeksphere.online/aigc/token",headers:{"content-type":"application/json"},data:{auth:"pUMsVhaMDHXiuTMs03852b8a786a491",key:n.replace("sk-",""),base_url:"https://oneapi.geeksphere.online/v1"}};let t=await jl.request(e);return!((s=t==null?void 0:t.data)!=null&&s.resultcode)||t.data.resultcode!=200?[0,0]:t.data.data}async function Mt(n,e){let t=await Ge.fetchSyncPost(n,e);return t.code===0?t.data:null}async function Hl(n,e,t){return Mt("/api/block/appendBlock",{dataType:n,data:e,parentID:t})}async function ys(n,e,t){return Mt("/api/block/updateBlock",{dataType:n,data:e,id:t})}async function $l(n){return Mt("/api/block/getBlockKramdown",{id:n})}async function Ze(n,e=7e3){return Mt("/api/notification/pushMsg",{msg:n,timeout:e})}async function Ye(n,e=7e3){return Mt("/api/notification/pushErrMsg",{msg:n,timeout:e})}async function Wr(){return Mt("/api/system/currentTime",{})}class Wl{constructor(){ee(this,"_data");this._data=new Map}set data(e){this._data=e}get data(){return this._data}set(e,t){return this._data.set(e,t),!0}get(e,t){return this._data.get(e)??t}hasKey(e){return this._data.has(e)}remove(e){return this._data.delete(e)}values(){return Array.from(this._data.values())}keys(){return Array.from(this._data.keys())}keyValues(){return Array.from(this._data.entries())}forEach(e){const t=this.keyValues();for(let s=0;s{let s=JSON.parse(t);this.set(s.key,JSON.parse(s.value))}),this._data}}class eo extends Wl{constructor(t,s){super();ee(this,"_plugin");ee(this,"_file");this._plugin=t,this._file=s.endsWith(".json")?s:`${s}.json`}load(){this._plugin.loadData(this._file).then(t=>{t?this.deserializedString(t):this.save()})}save(t){this._plugin.saveData(this._file,this.serializedToString()).then(()=>{t&&(this._file.includes("setting")&&Ze("AI插件设置已保存"),this._file.includes("prompt")&&Ze("prompt设置已保存"))})}async removeData(){await this._plugin.removeData(this._file)}}class Gl extends eo{constructor(e,t){super(e,t),this._defaultData()}onload(){this.load()}_defaultData(){this.set("小红书写手",{model:"gpt-3.5-turbo",temperature:.3,title:"小红书写手",prompt:"你的任务是以小红书博主的文章结构,以我给出的主题写一篇帖子推荐。你的回答应包括使用表情符号来增加趣味和互动,以及与每个段落相匹配的图片。请以一个引人入胜的介绍开始,为你的推荐设置基调。然后,提供至少三个与主题相关的段落,突出它们的独特特点和吸引力。在你的写作中使用表情符号,使它更加引人入胜和有趣。对于每个段落,请提供一个与描述内容相匹配的图片。这些图片应该视觉上吸引人,并帮助你的描述更加生动形象。我给出的主题是:",isStar:!1}),this.set("翻译、拼写纠正、改进",{model:"gpt-3.5-turbo",temperature:.3,title:"翻译、拼写纠正、改进",prompt:"请对以下内容进行翻译。要求:我希望你用更优美优雅的高级英语单词和句子替换我简化的 A0 级单词和句子。保持相同的意思,但使它们更文艺。你只需要翻译该内容,不必对内容中提出的问题和要求做解释,不要回答文本中的问题而是翻译它。",isStar:!1}),this.set("自动提取标题",{model:"gpt-3.5-turbo",temperature:.3,title:"自动提取标题",prompt:"请为下面这篇文章生成简洁且完整概括的标题。",isStar:!1}),this.set("自动提取摘要",{model:"gpt-3.5-turbo",temperature:.3,title:"自动提取摘要",prompt:"请为下面这篇文章生成简明扼要的摘要。",isStar:!1}),this.set("自动提取标签",{model:"gpt-3.5-turbo",temperature:.3,title:"自动提取标签",prompt:"请为下面这篇文章生成标签,单个标签不超过6个字符,多个标签用英文逗号分隔,最多返回5个标签。",isStar:!1})}async deleteStorageFile(){await super.removeData(),await Ye("删除:prompt文件...")}}class zl extends eo{constructor(e,t){super(e,t),this._defaultData()}onload(){this.load()}_defaultData(){this.set(M.SERVICE_PROVIDER,{group:"🌈 设置",key:M.SERVICE_PROVIDER,value:"OpenAI",type:fe.select,title:"AI服务提供商",description:"选择后将使用该提供商的 API 服务实现 AI 相关功能",options:{OpenAI:"OpenAI"}}),this.set(M.API_KEY,{group:"🌈 设置",key:M.API_KEY,value:"",placeholder:"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",type:fe.textinput,title:"API Key",description:"请求大模型服务的密钥."}),this.set(M.TIMEOUT,{group:"🌈 设置",key:M.TIMEOUT,value:90,type:fe.textinput,title:"AI请求超时时间",description:"发起请求的超时时间,单位:秒"}),this.set(M.BASE_URL,{group:"🌈 设置",key:M.BASE_URL,value:"https://oneapi.geeksphere.online/v1",type:fe.textinput,title:"API 基础地址",description:"发起请求的基础地址"}),this.set(M.STREAM,{group:"🌈 设置",key:M.STREAM,value:!1,type:fe.switch,title:"是否开启流式输出",description:"逐字生成回复内容"}),this.set(M.PROMPT,{group:"📃 文本生成",key:M.PROMPT,value:"",type:fe.textarea,title:"prompt",description:"prompt的内容,用于指示生成内容",placeholder:"请输入prompt,比如:请将以下文本翻译成英文"}),this.set(M.PROMPT_TITLE,{group:"📃 文本生成",key:M.PROMPT_TITLE,value:"",type:fe.textinput,title:"prompt 标题",description:"使用 prompt 时,该项可不填。保存 prompt 时,该项必填。"}),this.set(M.MODEL,{group:"📃 文本生成",key:M.MODEL,value:"gpt-3.5-turbo-0125",type:fe.select,title:"模型",description:"选择文本生成模型模型",options:{"gpt-3.5-turbo-0125":"gpt-3.5-turbo-0125","gpt-4-turbo-2024-04-09":"gpt-4-turbo-2024-04-09","gpt-4-0125-preview":"gpt-4-0125-preview","gpt-3.5-turbo":"gpt-3.5-turbo","gpt-3.5-turbo-0301":"gpt-3.5-turbo-0301","gpt-3.5-turbo-0613":"gpt-3.5-turbo-0613","gpt-3.5-turbo-16k":"gpt-3.5-turbo-16k","gpt-3.5-turbo-16k-0613":"gpt-3.5-turbo-16k-0613","gpt-4":"gpt-4","gpt-4-0314":"gpt-4-0314","gpt-4-0613":"gpt-4-0613","gpt-4-1106-preview":"gpt-4-1106-preview","gpt-4-32k":"gpt-4-32k","gpt-4-32k-0314":"gpt-4-32k-0314","gpt-4-32k-0613":"gpt-4-32k-0613","gpt-4-turbo":"gpt-4-turbo","gpt-4-turbo-preview":"gpt-4-turbo-preview"}}),this.set(M.TEMPERATURE,{group:"📃 文本生成",key:M.TEMPERATURE,value:.3,type:fe.slider,title:"温度值",description:"温度值越小,模型生成的内容越准确。温度值越高,模型生成内容越多样",slider:{min:0,max:1,step:.1}}),this.set(M.IMG_PROMPT,{group:"🏞️ 文生图",key:M.IMG_PROMPT,value:"",type:fe.textarea,title:"prompt",description:"prompt的内容,用于指示生成内容",placeholder:"请输入prompt,比如:一只白色暹罗猫"}),this.set(M.IMG_PROMTP_TITLE,{group:"🏞️ 文生图",key:M.IMG_PROMTP_TITLE,value:"",type:fe.textinput,title:"prompt 标题",description:"使用 prompt 时,该项可不填。保存 prompt 时,该项必填。"}),this.set(M.IMG_MODEL,{group:"🏞️ 文生图",key:M.IMG_MODEL,value:"dall-e-3",type:fe.select,title:"图片生成模型",description:"请选择图片生成模型",options:{"dall-e-3":"DALL·E 3","dall-e-2":"DALL·E 2"}}),this.set(M.IMG_NUM,{group:"🏞️ 文生图",key:M.IMG_NUM,value:"1",type:fe.number,title:"生成图片数量",description:"生成图片数量"}),this.set(M.IMG_QUALITY,{group:"🏞️ 文生图",key:M.IMG_QUALITY,value:"standard",type:fe.select,title:"图片质量",description:"生成的图像的质量,hd会生成更细致的图像。",options:{standard:"standard",hd:"hd"}}),this.set(M.IMG_SIZE,{group:"🏞️ 文生图",key:M.IMG_SIZE,value:"1024x1024",type:fe.select,title:"图片大小",description:"生成图片大小",options:{"1024x1024":"1024x1024","1024x1792":"1024x1792","1792x1024":"1792x1024","512x512":"512x512","256x256":"256x256"}})}async deleteStorageFile(){await super.removeData(),await Ye("删除:设置文件...")}}function Jl(n){let e,t,s;return{c(){e=C("strong"),e.textContent="注意:",t=B(),s=C("p"),s.textContent="为了修复文生图bug,请大家先主动卸载插件,再重新在插件市场安装。不然文本生成面板会出现不显示的bug。"},m(r,i){J(r,e,i),J(r,t,i),J(r,s,i)},p:z,i:z,o:z,d(r){r&&W(e),r&&W(t),r&&W(s)}}}class Xl extends Ie{constructor(e){super(),xe(this,e,null,Jl,Te,{})}}function Kl(n){let e,t,s="余额查询",r,i,o,a,l,u,f,c,h,b,d,p,m;return{c(){e=C("label"),t=C("div"),r=oe(s),i=B(),o=C("div"),a=oe("账 户 余 额 : "),l=oe(n[1]),u=oe(` ¥ - `),f=C("br"),c=oe(` - Token余额 : `),h=oe(n[2]),b=B(),d=C("button"),d.textContent="刷新",g(o,"class","b3-label__text"),g(t,"class","fn__flex-1"),g(d,"class","b3-button b3-button--outline fn__flex-center fn__size200"),g(e,"class","fn__flex b3-label")},m(S,k){J(S,e,k),y(e,t),y(t,r),y(t,i),y(t,o),y(o,a),y(o,l),y(o,u),y(o,f),y(o,c),y(o,h),y(e,b),y(e,d),p||(m=V(d,"click",n[3]),p=!0)},p(S,[k]){k&2&&tt(l,S[1]),k&4&&tt(h,S[2])},i:z,o:z,d(S){S&&W(e),p=!1,m()}}}function Vl(n,e,t){let{apiKey:s}=e,r=0,i=0;Ho(()=>{$r(s).then(a=>{t(2,i=a[0]),t(1,r=a[1])})});const o=async()=>{$r(s).then(a=>{t(2,i=a[0]),t(1,r=a[1])})};return n.$$set=a=>{"apiKey"in a&&t(0,s=a.apiKey)},[s,r,i,o]}class Ql extends Ie{constructor(e){super(),xe(this,e,Vl,Kl,Te,{apiKey:0})}}function Gr(n,e,t){const s=n.slice();return s[12]=e[t],s}function zr(n,e,t){const s=n.slice();return s[15]=e[t],s}function Jr(n){let e,t,s=n[15]+"",r,i,o,a;function l(){return n[8](n[15])}return{c(){e=C("li"),t=C("span"),r=oe(s),i=B(),g(t,"class","b3-list-item__text"),g(e,"data-name","editor"),g(e,"class","b3-list-item svelte-1fh5pey"),On(e,"b3-list-item--focus",n[15]===n[2])},m(u,f){J(u,e,f),y(e,t),y(t,r),y(e,i),o||(a=[V(e,"click",l),V(e,"keydown",ec)],o=!0)},p(u,f){n=u,f&12&&On(e,"b3-list-item--focus",n[15]===n[2])},d(u){u&&W(e),o=!1,ue(a)}}}function Yl(n){var s,r,i;let e,t;return e=new Zs({props:{type:n[12].type,title:n[12].title,description:n[12].description,settingKey:n[12].key,settingValue:n[12].value,placeholder:(s=n[12])==null?void 0:s.placeholder,options:(r=n[12])==null?void 0:r.options,slider:(i=n[12])==null?void 0:i.slider}}),e.$on("changed",n[9]),{c(){ie(e.$$.fragment)},m(o,a){se(e,o,a),t=!0},p:z,i(o){t||(q(e.$$.fragment,o),t=!0)},o(o){G(e.$$.fragment,o),t=!1},d(o){re(e,o)}}}function Xr(n,e){let t,s,r,i=e[12].group==e[3][0]&&Yl(e);return{key:n,first:null,c(){t=et(),i&&i.c(),s=et(),this.first=t},m(o,a){J(o,t,a),i&&i.m(o,a),J(o,s,a),r=!0},p(o,a){e=o,e[12].group==e[3][0]&&i.p(e,a)},i(o){r||(q(i),r=!0)},o(o){G(i),r=!1},d(o){o&&W(t),i&&i.d(o),o&&W(s)}}}function Zl(n){let e,t,s,r,i,o,a=[],l=new Map,u,f,c,h,b,d,p,m,S,k,E,P,A,F,v,L,x=n[3],X=[];for(let R=0;RR[12].key;for(let R=0;R{};function tc(n,e,t){let{$$slots:s={},$$scope:r}=e,{storageSettings:i}=e,{dialog:o=null}=e,a=["🌈 设置","💡 公告"],l=a[0],u=i.get(M.API_KEY).value,f=[];i.data.forEach(p=>{f.push(p)});const c=p=>{t(2,l=p)},h=({detail:p})=>{let m=i.get(p.key);m.value=p.value,i.set(p.key,m)},b=()=>{i.load(),o.destroy()},d=()=>{i.save(!0),o.destroy()};return n.$$set=p=>{"storageSettings"in p&&t(0,i=p.storageSettings),"dialog"in p&&t(1,o=p.dialog),"$$scope"in p&&t(6,r=p.$$scope)},[i,o,l,a,u,f,r,s,c,h,b,d]}class nc extends Ie{constructor(e){super(),xe(this,e,tc,Zl,Te,{storageSettings:0,dialog:1})}}function sc(n){let e,t,s,r,i,o,a,l=n[0].content+"",u;return{c(){e=C("div"),t=C("div"),s=C("div"),s.innerHTML='
',r=B(),i=C("div"),o=C("div"),a=C("p"),u=oe(l),g(s,"class","chat_chat-message-header__Dny_K svelte-1170n0w"),g(o,"class","markdown-body"),g(o,"dir","auto"),Vs(o,"font-size","14px"),g(i,"class","chat_chat-message-item__dKqMl svelte-1170n0w"),g(t,"class","chat_chat-message-container__O_X8_ svelte-1170n0w"),g(e,"class","chat_chat-message__dg8rL svelte-1170n0w")},m(f,c){J(f,e,c),y(e,t),y(t,s),y(t,r),y(t,i),y(i,o),y(o,a),y(a,u)},p(f,[c]){c&1&&l!==(l=f[0].content+"")&&tt(u,l)},i:z,o:z,d(f){f&&W(e)}}}function rc(n,e,t){let{message:s}=e;return n.$$set=r=>{"message"in r&&t(0,s=r.message)},[s]}class ic extends Ie{constructor(e){super(),xe(this,e,rc,sc,Te,{message:0})}}function oc(n){let e,t,s,r,i,o,a,l=n[0].content+"",u;return{c(){e=C("div"),t=C("div"),s=C("div"),s.innerHTML='
smiley
',r=B(),i=C("div"),o=C("div"),a=C("p"),u=oe(l),g(s,"class","chat_chat-message-header__Dny_K svelte-1dpaqhi"),g(o,"class","markdown-body"),g(o,"dir","auto"),Vs(o,"font-size","14px"),g(i,"class","chat_chat-message-item__dKqMl svelte-1dpaqhi"),g(t,"class","chat_chat-message-container__O_X8_ svelte-1dpaqhi"),g(e,"class","chat_chat-message-user__ZtTEj svelte-1dpaqhi")},m(f,c){J(f,e,c),y(e,t),y(t,s),y(t,r),y(t,i),y(i,o),y(o,a),y(a,u)},p(f,[c]){c&1&&l!==(l=f[0].content+"")&&tt(u,l)},i:z,o:z,d(f){f&&W(e)}}}function ac(n,e,t){let{message:s}=e;return n.$$set=r=>{"message"in r&&t(0,s=r.message)},[s]}class lc extends Ie{constructor(e){super(),xe(this,e,ac,oc,Te,{message:0})}}function Kr(n,e,t){const s=n.slice();return s[11]=e[t],s}function cc(n){let e,t;return e=new lc({props:{message:n[11]}}),{c(){ie(e.$$.fragment)},m(s,r){se(e,s,r),t=!0},p(s,r){const i={};r&2&&(i.message=s[11]),e.$set(i)},i(s){t||(q(e.$$.fragment,s),t=!0)},o(s){G(e.$$.fragment,s),t=!1},d(s){re(e,s)}}}function uc(n){let e,t;return e=new ic({props:{message:n[11]}}),{c(){ie(e.$$.fragment)},m(s,r){se(e,s,r),t=!0},p(s,r){const i={};r&2&&(i.message=s[11]),e.$set(i)},i(s){t||(q(e.$$.fragment,s),t=!0)},o(s){G(e.$$.fragment,s),t=!1},d(s){re(e,s)}}}function Vr(n,e){let t,s,r,i,o;const a=[uc,cc],l=[];function u(f,c){return f[11].role=="assistant"?0:1}return s=u(e),r=l[s]=a[s](e),{key:n,first:null,c(){t=et(),r.c(),i=et(),this.first=t},m(f,c){J(f,t,c),l[s].m(f,c),J(f,i,c),o=!0},p(f,c){e=f;let h=s;s=u(e),s===h?l[s].p(e,c):(Pt(),G(l[h],1,1,()=>{l[h]=null}),vt(),r=l[s],r?r.p(e,c):(r=l[s]=a[s](e),r.c()),q(r,1),r.m(i.parentNode,i))},i(f){o||(q(r),o=!0)},o(f){G(r),o=!1},d(f){f&&W(t),l[s].d(f),f&&W(i)}}}function fc(n){let e,t,s,r=[],i=new Map,o,a,l,u,f,c,h,b,d,p,m,S=n[1];const k=E=>E[11].id;for(let E=0;E',u=B(),f=C("label"),c=C("textarea"),h=B(),b=C("button"),b.innerHTML=`
-
发送
`,g(s,"class","chat_chat-body__QFv5x svelte-pnrkt6"),g(l,"class","chat_chat-input-actions__mwYC_ svelte-pnrkt6"),g(c,"id","chat-input"),g(c,"class","chat_chat-input__PQ_oF svelte-pnrkt6"),g(c,"placeholder","Enter 发送,Shift + Enter 换行"),g(c,"rows","3"),Vs(c,"font-size","14px"),g(b,"class","button_icon-button__VwAMf chat_chat-input-send__GFQZo clickable button_primary__dwYZ6 svelte-pnrkt6"),g(f,"class","chat_chat-input-panel-inner___IQHi svelte-pnrkt6"),g(f,"for","chat-input"),g(a,"class","chat_chat-input-panel__rO72m svelte-pnrkt6"),g(t,"class","chat_chat__ZebHg svelte-pnrkt6"),g(e,"class","home_window-content__2WGYf svelte-pnrkt6"),g(e,"id","app-body")},m(E,P){J(E,e,P),y(e,t),y(t,s);for(let A=0;A{if(s){const p=s.getBoundingClientRect().bottom;t(0,s.scrollTop+=p+160,s)}};function f(d){Vt[d?"unshift":"push"](()=>{s=d,t(0,s)})}function c(){i=this.value,t(2,i)}return[s,r,i,a,f,c,d=>d.key=="Enter"&&a(),()=>{a()}]}let hc=class extends Ie{constructor(e){super(),xe(this,e,dc,fc,Te,{})}};const _t="4.33.1";let Qr=!1,Jt,to,no,js,so,ro,io,oo,ao;function pc(n,e={auto:!1}){if(Qr)throw new Error(`you must \`import 'openai/shims/${n.kind}'\` before importing anything else from openai`);if(Jt)throw new Error(`can't \`import 'openai/shims/${n.kind}'\` after \`import 'openai/shims/${Jt}'\``);Qr=e.auto,Jt=n.kind,to=n.fetch,n.Request,n.Response,n.Headers,no=n.FormData,n.Blob,js=n.File,so=n.ReadableStream,ro=n.getMultipartRequestOptions,io=n.getDefaultAgent,oo=n.fileFromPath,ao=n.isFsReadStream}class mc{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function _c({manuallyImported:n}={}){const e=n?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let t,s,r,i;try{t=fetch,s=Request,r=Response,i=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${e}`)}return{kind:"web",fetch:t,Request:s,Response:r,Headers:i,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(o,a)=>({...a,body:new mc(o)}),getDefaultAgent:o=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:o=>!1}}Jt||pc(_c(),{auto:!0});class $ extends Error{}class ce extends ${constructor(e,t,s,r){super(`${ce.makeMessage(e,t,s)}`),this.status=e,this.headers=r;const i=t;this.error=i,this.code=i==null?void 0:i.code,this.param=i==null?void 0:i.param,this.type=i==null?void 0:i.type}static makeMessage(e,t,s){const r=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e)return new cs({cause:Us(t)});const i=t==null?void 0:t.error;return e===400?new lo(e,i,s,r):e===401?new co(e,i,s,r):e===403?new uo(e,i,s,r):e===404?new fo(e,i,s,r):e===409?new ho(e,i,s,r):e===422?new po(e,i,s,r):e===429?new mo(e,i,s,r):e>=500?new _o(e,i,s,r):new ce(e,i,s,r)}}class Se extends ce{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class cs extends ce{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class or extends cs{constructor({message:e}={}){super({message:e??"Request timed out."})}}class lo extends ce{constructor(){super(...arguments),this.status=400}}class co extends ce{constructor(){super(...arguments),this.status=401}}class uo extends ce{constructor(){super(...arguments),this.status=403}}class fo extends ce{constructor(){super(...arguments),this.status=404}}class ho extends ce{constructor(){super(...arguments),this.status=409}}class po extends ce{constructor(){super(...arguments),this.status=422}}class mo extends ce{constructor(){super(...arguments),this.status=429}}class _o extends ce{}class je{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let s=!1;async function*r(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let i=!1;try{for await(const o of gc(e,t))if(!i){if(o.data.startsWith("[DONE]")){i=!0;continue}if(o.event===null){let a;try{a=JSON.parse(o.data)}catch(l){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),l}if(a&&a.error)throw new ce(void 0,a.error,void 0,void 0);yield a}else{let a;try{a=JSON.parse(o.data)}catch(l){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),l}if(o.event=="error")throw new ce(void 0,a.error,a.message,void 0);yield{event:o.event,data:a}}}i=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{i||t.abort()}}return new je(r,t)}static fromReadableStream(e,t){let s=!1;async function*r(){const o=new at,a=go(e);for await(const l of a)for(const u of o.decode(l))yield u;for(const l of o.flush())yield l}async function*i(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const a of r())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new je(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const o=s.next();e.push(o),t.push(o)}return i.shift()}});return[new je(()=>r(e),this.controller),new je(()=>r(t),this.controller)]}toReadableStream(){const e=this;let t;const s=new TextEncoder;return new so({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:i,done:o}=await t.next();if(o)return r.close();const a=s.encode(JSON.stringify(i)+` -`);r.enqueue(a)}catch(i){r.error(i)}},async cancel(){var r;await((r=t.return)==null?void 0:r.call(t))}})}}async function*gc(n,e){if(!n.body)throw e.abort(),new $("Attempted to iterate over a response with no body");const t=new wc,s=new at,r=go(n.body);for await(const i of bc(r))for(const o of s.decode(i)){const a=t.decode(o);a&&(yield a)}for(const i of s.flush()){const o=t.decode(i);o&&(yield o)}}async function*bc(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=yc(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function yc(n){for(let s=0;s0&&(r=[this.buffer.join("")+r[0],...r.slice(1)],this.buffer=[]),s||(this.buffer=[r.pop()||""]),r)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new $(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new $(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new $("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}at.NEWLINE_CHARS=new Set([` -`,"\r"]);at.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Sc(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}function go(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const bo=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function",yo=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&wo(n),wo=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Ac=n=>yo(n)||bo(n)||ao(n);async function So(n,e,t){var r;if(n=await n,t??(t=yo(n)?{lastModified:n.lastModified,type:n.type}:{}),bo(n)){const i=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new js([i],e,t)}const s=await Ec(n);if(e||(e=Cc(n)??"unknown_file"),!t.type){const i=(r=s[0])==null?void 0:r.type;typeof i=="string"&&(t={...t,type:i})}return new js(s,e,t)}async function Ec(n){var t;let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(wo(n))e.push(await n.arrayBuffer());else if(Pc(n))for await(const s of n)e.push(s);else throw new Error(`Unexpected data type: ${typeof n}; constructor: ${(t=n==null?void 0:n.constructor)==null?void 0:t.name}; props: ${kc(n)}`);return e}function kc(n){return`[${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}function Cc(n){var e;return ws(n.name)||ws(n.filename)||((e=ws(n.path))==null?void 0:e.split(/[\\/]/).pop())}const ws=n=>{if(typeof n=="string")return n;if(typeof Buffer<"u"&&n instanceof Buffer)return String(n)},Pc=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Yr=n=>n&&typeof n=="object"&&n.body&&n[Symbol.toStringTag]==="MultipartBody",Yt=async n=>{const e=await vc(n.body);return ro(e,n)},vc=async n=>{const e=new no;return await Promise.all(Object.entries(n||{}).map(([t,s])=>Bs(e,t,s))),e},Bs=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(Ac(t)){const s=await So(t);n.append(e,s)}else if(Array.isArray(t))await Promise.all(t.map(s=>Bs(n,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,r])=>Bs(n,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Rc=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},Oc=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},cn;async function Ao(n){const{response:e}=n;if(n.options.stream)return St("response",e.status,e.url,e.headers,e.body),n.options.__streamClass?n.options.__streamClass.fromSSEResponse(e,n.controller):je.fromSSEResponse(e,n.controller);if(e.status===204)return null;if(n.options.__binaryResponse)return e;const t=e.headers.get("content-type");if((t==null?void 0:t.includes("application/json"))||(t==null?void 0:t.includes("application/vnd.api+json"))){const i=await e.json();return St("response",e.status,e.url,e.headers,i),i}const r=await e.text();return St("response",e.status,e.url,e.headers,r),r}class us extends Promise{constructor(e,t=Ao){super(s=>{s(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new us(this.responsePromise,async t=>e(await this.parseResponse(t)))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class Mc{constructor({baseURL:e,maxRetries:t=2,timeout:s=6e5,httpAgent:r,fetch:i}){this.baseURL=e,this.maxRetries=Ss("maxRetries",t),this.timeout=Ss("timeout",s),this.httpAgent=r,this.fetch=i??to}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Nc(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Uc()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:t,...r})))}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}return null}buildRequest(e){var d;const{method:t,path:s,query:r,headers:i={}}=e,o=Yr(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,a=this.calculateContentLength(o),l=this.buildURL(s,r);"timeout"in e&&Ss("timeout",e.timeout);const u=e.timeout??this.timeout,f=e.httpAgent??this.httpAgent??io(l),c=u+1e3;typeof((d=f==null?void 0:f.options)==null?void 0:d.timeout)=="number"&&c>(f.options.timeout??0)&&(f.options.timeout=c),this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const h=this.buildHeaders({options:e,headers:i,contentLength:a});return{req:{method:t,...o&&{body:o},headers:h,...f&&{agent:f},signal:e.signal??null},url:l,timeout:u}}buildHeaders({options:e,headers:t,contentLength:s}){const r={};s&&(r["content-length"]=s);const i=this.defaultHeaders(e);return ni(r,i),ni(r,t),Yr(e.body)&&Jt!=="node"&&delete r["content-type"],this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,s,r){return ce.generate(e,t,s,r)}request(e,t=null){return new us(this.makeRequest(e,t))}async makeRequest(e,t){var f,c;const s=await e;t==null&&(t=s.maxRetries??this.maxRetries),await this.prepareOptions(s);const{req:r,url:i,timeout:o}=this.buildRequest(s);if(await this.prepareRequest(r,{url:i,options:s}),St("request",i,s,r.headers),(f=s.signal)!=null&&f.aborted)throw new Se;const a=new AbortController,l=await this.fetchWithTimeout(i,r,o,a).catch(Us);if(l instanceof Error){if((c=s.signal)!=null&&c.aborted)throw new Se;if(t)return this.retryRequest(s,t);throw l.name==="AbortError"?new or:new cs({cause:l})}const u=xc(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){const S=`retrying, ${t} attempts remaining`;return St(`response (error; ${S})`,l.status,i,u),this.retryRequest(s,t,u)}const h=await l.text().catch(S=>Us(S).message),b=Dc(h),d=b?void 0:h;throw St(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,i,u,d),this.makeStatusError(l.status,b,d,u)}return{response:l,options:s,controller:a}}requestAPIList(e,t){const s=this.makeRequest(t,null);return new Tc(this,s,e)}buildURL(e,t){const s=Bc(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery();return ko(r)||(t={...r,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,s])=>typeof s<"u").map(([t,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(t)}=`;throw new $(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,s,r){const{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>r.abort());const a=setTimeout(()=>r.abort(),s);return this.getRequestClient().fetch.call(void 0,e,{signal:r.signal,...o}).finally(()=>{clearTimeout(a)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s){let r;const i=s==null?void 0:s["retry-after-ms"];if(i){const a=parseFloat(i);Number.isNaN(a)||(r=a)}const o=s==null?void 0:s["retry-after"];if(o&&!r){const a=parseFloat(o);Number.isNaN(a)?r=Date.parse(o)-Date.now():r=a*1e3}if(!(r&&0<=r&&r<60*1e3)){const a=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,a)}return await ar(r),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${_t}`}}class Eo{constructor(e,t,s,r){cn.set(this,void 0),Rc(this,cn,e,"f"),this.options=r,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new $("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){const s=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[r,i]of s)e.url.searchParams.set(r,i);t.query=void 0,t.path=e.url.toString()}return await Oc(this,cn,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(cn=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Tc extends us{constructor(e,t,s){super(t,async r=>new s(e,r.response,await Ao(r),r.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const xc=n=>new Proxy(Object.fromEntries(n.entries()),{get(e,t){const s=t.toString();return e[s.toLowerCase()]||e[s]}}),Ic={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryResponse:!0,__streamClass:!0},qe=n=>typeof n=="object"&&n!==null&&!ko(n)&&Object.keys(n).every(e=>Co(Ic,e)),Lc=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_t,"X-Stainless-OS":ei(Deno.build.os),"X-Stainless-Arch":Zr(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((e=Deno.version)==null?void 0:e.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_t,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_t,"X-Stainless-OS":ei(process.platform),"X-Stainless-Arch":Zr(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const n=Fc();return n?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_t,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${n.browser}`,"X-Stainless-Runtime-Version":n.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_t,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Fc(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,o=s[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}const Zr=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",ei=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let ti;const Nc=()=>ti??(ti=Lc()),Dc=n=>{try{return JSON.parse(n)}catch{return}},jc=new RegExp("^(?:[a-z]+:)?//","i"),Bc=n=>jc.test(n),ar=n=>new Promise(e=>setTimeout(e,n)),Ss=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new $(`${n} must be an integer`);if(e<0)throw new $(`${n} must be a positive integer`);return e},Us=n=>n instanceof Error?n:new Error(n),As=n=>{var e,t,s,r,i;if(typeof process<"u")return((t=(e=process.env)==null?void 0:e[n])==null?void 0:t.trim())??void 0;if(typeof Deno<"u")return(i=(r=(s=Deno.env)==null?void 0:s.get)==null?void 0:r.call(s,n))==null?void 0:i.trim()};function ko(n){if(!n)return!0;for(const e in n)return!1;return!0}function Co(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function ni(n,e){for(const t in e){if(!Co(e,t))continue;const s=t.toLowerCase();if(!s)continue;const r=e[t];r===null?delete n[s]:r!==void 0&&(n[s]=r)}}function St(n,...e){var t;typeof process<"u"&&((t=process==null?void 0:process.env)==null?void 0:t.DEBUG)==="true"&&console.log(`OpenAI:DEBUG:${n}`,...e)}const Uc=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)}),qc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function si(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}class lr extends Eo{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class Je extends Eo{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){var s;const e=this.getPaginatedItems();if(!e.length)return null;const t=(s=e[e.length-1])==null?void 0:s.id;return t?{params:{after:t}}:null}}class Y{constructor(e){this._client=e}}let In=class extends Y{create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}};In||(In={});let Ln=class extends Y{constructor(){super(...arguments),this.completions=new In(this._client)}};(function(n){n.Completions=In})(Ln||(Ln={}));class Fn extends Y{create(e,t){return this._client.post("/audio/speech",{body:e,...t,__binaryResponse:!0})}}Fn||(Fn={});class Nn extends Y{create(e,t){return this._client.post("/audio/transcriptions",Yt({body:e,...t}))}}Nn||(Nn={});class Dn extends Y{create(e,t){return this._client.post("/audio/translations",Yt({body:e,...t}))}}Dn||(Dn={});class jn extends Y{constructor(){super(...arguments),this.transcriptions=new Nn(this._client),this.translations=new Dn(this._client),this.speech=new Fn(this._client)}}(function(n){n.Transcriptions=Nn,n.Translations=Dn,n.Speech=Fn})(jn||(jn={}));let Bn=class extends Y{create(e,t,s){return this._client.post(`/assistants/${e}/files`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}retrieve(e,t,s){return this._client.get(`/assistants/${e}/files/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}list(e,t={},s){return qe(t)?this.list(e,{},t):this._client.getAPIList(`/assistants/${e}/files`,cr,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}del(e,t,s){return this._client.delete(`/assistants/${e}/files/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}};class cr extends Je{}(function(n){n.AssistantFilesPage=cr})(Bn||(Bn={}));class Un extends Y{constructor(){super(...arguments),this.files=new Bn(this._client)}create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}update(e,t,s){return this._client.post(`/assistants/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}list(e={},t){return qe(e)?this.list({},e):this._client.getAPIList("/assistants",ur,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}}class ur extends Je{}(function(n){n.AssistantsPage=ur,n.Files=Bn,n.AssistantFilesPage=cr})(Un||(Un={}));function ri(n){return typeof n.parse=="function"}const At=n=>(n==null?void 0:n.role)==="assistant",Po=n=>(n==null?void 0:n.role)==="function",vo=n=>(n==null?void 0:n.role)==="tool";var Pe=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},U=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},de,_n,gn,Ft,Nt,bn,Dt,$e,jt,yn,wn,gt,qs,qn,Hs,$s,Ws,Gs,Ro,zs;const ii=10;class Oo{constructor(){de.add(this),this.controller=new AbortController,_n.set(this,void 0),gn.set(this,()=>{}),Ft.set(this,()=>{}),Nt.set(this,void 0),bn.set(this,()=>{}),Dt.set(this,()=>{}),$e.set(this,{}),this._chatCompletions=[],this.messages=[],jt.set(this,!1),yn.set(this,!1),wn.set(this,!1),gt.set(this,!1),Gs.set(this,e=>{if(Pe(this,yn,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Se),e instanceof Se)return Pe(this,wn,!0,"f"),this._emit("abort",e);if(e instanceof $)return this._emit("error",e);if(e instanceof Error){const t=new $(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new $(String(e)))}),Pe(this,_n,new Promise((e,t)=>{Pe(this,gn,e,"f"),Pe(this,Ft,t,"f")}),"f"),Pe(this,Nt,new Promise((e,t)=>{Pe(this,bn,e,"f"),Pe(this,Dt,t,"f")}),"f"),U(this,_n,"f").catch(()=>{}),U(this,Nt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},U(this,Gs,"f"))},0)}_addChatCompletion(e){var s;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(s=e.choices[0])==null?void 0:s.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(Po(e)||vo(e))&&e.content)this._emit("functionCallResult",e.content);else if(At(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(At(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionCall",s.function)}}_connected(){this.ended||(U(this,gn,"f").call(this),this._emit("connect"))}get ended(){return U(this,jt,"f")}get errored(){return U(this,yn,"f")}get aborted(){return U(this,wn,"f")}abort(){this.controller.abort()}on(e,t){return(U(this,$e,"f")[e]||(U(this,$e,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=U(this,$e,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(U(this,$e,"f")[e]||(U(this,$e,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{Pe(this,gt,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){Pe(this,gt,!0,"f"),await U(this,Nt,"f")}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new $("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),U(this,de,"m",qs).call(this)}async finalMessage(){return await this.done(),U(this,de,"m",qn).call(this)}async finalFunctionCall(){return await this.done(),U(this,de,"m",Hs).call(this)}async finalFunctionCallResult(){return await this.done(),U(this,de,"m",$s).call(this)}async totalUsage(){return await this.done(),U(this,de,"m",Ws).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emit(e,...t){if(U(this,jt,"f"))return;e==="end"&&(Pe(this,jt,!0,"f"),U(this,bn,"f").call(this));const s=U(this,$e,"f")[e];if(s&&(U(this,$e,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!U(this,gt,"f")&&!(s!=null&&s.length)&&Promise.reject(r),U(this,Ft,"f").call(this,r),U(this,Dt,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!U(this,gt,"f")&&!(s!=null&&s.length)&&Promise.reject(r),U(this,Ft,"f").call(this,r),U(this,Dt,"f").call(this,r),this._emit("end")}}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=U(this,de,"m",qn).call(this);t&&this._emit("finalMessage",t);const s=U(this,de,"m",qs).call(this);s&&this._emit("finalContent",s);const r=U(this,de,"m",Hs).call(this);r&&this._emit("finalFunctionCall",r);const i=U(this,de,"m",$s).call(this);i!=null&&this._emit("finalFunctionCallResult",i),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",U(this,de,"m",Ws).call(this))}async _createChatCompletion(e,t,s){const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),U(this,de,"m",Ro).call(this,t);const i=await e.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(i)}async _runChatCompletion(e,t,s){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,s)}async _runFunctions(e,t,s){var h;const r="function",{function_call:i="auto",stream:o,...a}=t,l=typeof i!="string"&&(i==null?void 0:i.name),{maxChatCompletions:u=ii}=s||{},f={};for(const b of t.functions)f[b.name||b.function.name]=b;const c=t.functions.map(b=>({name:b.name||b.function.name,parameters:b.parameters,description:b.description}));for(const b of t.messages)this._addMessage(b,!1);for(let b=0;bJSON.stringify(v.name)).join(", ")}. Please try again`;this._addMessage({role:r,name:m,content:F});continue}let E;try{E=ri(k)?await k.parse(S):S}catch(F){this._addMessage({role:r,name:m,content:F instanceof Error?F.message:String(F)});continue}const P=await k.function(E,this),A=U(this,de,"m",zs).call(this,P);if(this._addMessage({role:r,name:m,content:A}),l)return}}async _runTools(e,t,s){var h,b;const r="tool",{tool_choice:i="auto",stream:o,...a}=t,l=typeof i!="string"&&((h=i==null?void 0:i.function)==null?void 0:h.name),{maxChatCompletions:u=ii}=s||{},f={};for(const d of t.tools)d.type==="function"&&(f[d.function.name||d.function.function.name]=d.function);const c="tools"in t?t.tools.map(d=>d.type==="function"?{type:"function",function:{name:d.function.name||d.function.function.name,parameters:d.function.parameters,description:d.function.description}}:d):void 0;for(const d of t.messages)this._addMessage(d,!1);for(let d=0;dJSON.stringify(X.function.name)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:k,content:x});continue}let F;try{F=ri(A)?await A.parse(P):P}catch(x){const X=x instanceof Error?x.message:String(x);this._addMessage({role:r,tool_call_id:k,content:X});continue}const v=await A.function(F,this),L=U(this,de,"m",zs).call(this,v);if(this._addMessage({role:r,tool_call_id:k,content:L}),l)return}}}}_n=new WeakMap,gn=new WeakMap,Ft=new WeakMap,Nt=new WeakMap,bn=new WeakMap,Dt=new WeakMap,$e=new WeakMap,jt=new WeakMap,yn=new WeakMap,wn=new WeakMap,gt=new WeakMap,Gs=new WeakMap,de=new WeakSet,qs=function(){return U(this,de,"m",qn).call(this).content??null},qn=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(At(t))return{...t,content:t.content??null}}throw new $("stream ended without producing a ChatCompletionMessage with role=assistant")},Hs=function(){var e,t;for(let s=this.messages.length-1;s>=0;s--){const r=this.messages[s];if(At(r)&&(r!=null&&r.function_call))return r.function_call;if(At(r)&&((e=r==null?void 0:r.tool_calls)!=null&&e.length))return(t=r.tool_calls.at(-1))==null?void 0:t.function}},$s=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Po(t)&&t.content!=null||vo(t)&&t.content!=null&&this.messages.some(s=>{var r;return s.role==="assistant"&&((r=s.tool_calls)==null?void 0:r.some(i=>i.type==="function"&&i.id===t.tool_call_id))}))return t.content}},Ws=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ro=function(e){if(e.n!=null&&e.n>1)throw new $("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},zs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Zt extends Oo{static runFunctions(e,t,s){const r=new Zt,i={...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"runFunctions"}};return r._run(()=>r._runFunctions(e,t,i)),r}static runTools(e,t,s){const r=new Zt,i={...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}_addMessage(e){super._addMessage(e),At(e)&&e.content&&this._emit("content",e.content)}}var ve=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},Es=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},Fe,Ve,ks,Cs,un,oi;class en extends Oo{constructor(){super(...arguments),Fe.add(this),Ve.set(this,void 0)}get currentChatCompletionSnapshot(){return ve(this,Ve,"f")}static fromReadableStream(e){const t=new en;return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const r=new en;return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,s){var o;const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),ve(this,Fe,"m",ks).call(this);const i=await e.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const a of i)ve(this,Fe,"m",Cs).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new Se;return this._addChatCompletion(ve(this,Fe,"m",un).call(this))}async _fromReadableStream(e,t){var o;const s=t==null?void 0:t.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),ve(this,Fe,"m",ks).call(this),this._connected();const r=je.fromReadableStream(e,this.controller);let i;for await(const a of r)i&&i!==a.id&&this._addChatCompletion(ve(this,Fe,"m",un).call(this)),ve(this,Fe,"m",Cs).call(this,a),i=a.id;if((o=r.controller.signal)!=null&&o.aborted)throw new Se;return this._addChatCompletion(ve(this,Fe,"m",un).call(this))}[(Ve=new WeakMap,Fe=new WeakSet,ks=function(){this.ended||Es(this,Ve,void 0,"f")},Cs=function(t){var o,a,l;if(this.ended)return;const s=ve(this,Fe,"m",oi).call(this,t);this._emit("chunk",t,s);const r=(a=(o=t.choices[0])==null?void 0:o.delta)==null?void 0:a.content,i=(l=s.choices[0])==null?void 0:l.message;r!=null&&(i==null?void 0:i.role)==="assistant"&&(i!=null&&i.content)&&this._emit("content",r,i.content)},un=function(){if(this.ended)throw new $("stream has ended, this shouldn't happen");const t=ve(this,Ve,"f");if(!t)throw new $("request ended without sending any chunks");return Es(this,Ve,void 0,"f"),Hc(t)},oi=function(t){var s,r,i;let o=ve(this,Ve,"f");const{choices:a,...l}=t;o?Object.assign(o,l):o=Es(this,Ve,{...l,choices:[]},"f");for(const{delta:u,finish_reason:f,index:c,logprobs:h=null,...b}of t.choices){let d=o.choices[c];if(d||(d=o.choices[c]={finish_reason:f,index:c,message:{},logprobs:h,...b}),h)if(!d.logprobs)d.logprobs=Object.assign({},h);else{const{content:P,...A}=h;Object.assign(d.logprobs,A),P&&((s=d.logprobs).content??(s.content=[]),d.logprobs.content.push(...P))}if(f&&(d.finish_reason=f),Object.assign(d,b),!u)continue;const{content:p,function_call:m,role:S,tool_calls:k,...E}=u;if(Object.assign(d.message,E),p&&(d.message.content=(d.message.content||"")+p),S&&(d.message.role=S),m&&(d.message.function_call?(m.name&&(d.message.function_call.name=m.name),m.arguments&&((r=d.message.function_call).arguments??(r.arguments=""),d.message.function_call.arguments+=m.arguments)):d.message.function_call=m),k){d.message.tool_calls||(d.message.tool_calls=[]);for(const{index:P,id:A,type:F,function:v,...L}of k){const x=(i=d.message.tool_calls)[P]??(i[P]={});Object.assign(x,L),A&&(x.id=A),F&&(x.type=F),v&&(x.function??(x.function={arguments:""})),v!=null&&v.name&&(x.function.name=v.name),v!=null&&v.arguments&&(x.function.arguments+=v.arguments)}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Hc(n){const{id:e,choices:t,created:s,model:r,system_fingerprint:i,...o}=n;return{...o,id:e,choices:t.map(({message:a,finish_reason:l,index:u,logprobs:f,...c})=>{if(!l)throw new $(`missing finish_reason for choice ${u}`);const{content:h=null,function_call:b,tool_calls:d,...p}=a,m=a.role;if(!m)throw new $(`missing role for choice ${u}`);if(b){const{arguments:S,name:k}=b;if(S==null)throw new $(`missing function_call.arguments for choice ${u}`);if(!k)throw new $(`missing function_call.name for choice ${u}`);return{...c,message:{content:h,function_call:{arguments:S,name:k},role:m},finish_reason:l,index:u,logprobs:f}}return d?{...c,index:u,finish_reason:l,logprobs:f,message:{...p,role:m,content:h,tool_calls:d.map((S,k)=>{const{function:E,type:P,id:A,...F}=S,{arguments:v,name:L,...x}=E||{};if(A==null)throw new $(`missing choices[${u}].tool_calls[${k}].id -${fn(n)}`);if(P==null)throw new $(`missing choices[${u}].tool_calls[${k}].type -${fn(n)}`);if(L==null)throw new $(`missing choices[${u}].tool_calls[${k}].function.name -${fn(n)}`);if(v==null)throw new $(`missing choices[${u}].tool_calls[${k}].function.arguments -${fn(n)}`);return{...F,id:A,type:P,function:{...x,name:L,arguments:v}}})}}:{...c,message:{...p,content:h,role:m},finish_reason:l,index:u,logprobs:f}}),created:s,model:r,object:"chat.completion",...i?{system_fingerprint:i}:{}}}function fn(n){return JSON.stringify(n)}class Et extends en{static fromReadableStream(e){const t=new Et;return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,s){const r=new Et,i={...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"runFunctions"}};return r._run(()=>r._runFunctions(e,t,i)),r}static runTools(e,t,s){const r=new Et,i={...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}}let Mo=class extends Y{runFunctions(e,t){return e.stream?Et.runFunctions(this._client.chat.completions,e,t):Zt.runFunctions(this._client.chat.completions,e,t)}runTools(e,t){return e.stream?Et.runTools(this._client.chat.completions,e,t):Zt.runTools(this._client.chat.completions,e,t)}stream(e,t){return en.createChatCompletion(this._client.chat.completions,e,t)}};class Hn extends Y{constructor(){super(...arguments),this.completions=new Mo(this._client)}}(function(n){n.Completions=Mo})(Hn||(Hn={}));var Re=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},Z=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},Sn,An,Bt,Ut,En,qt,We,Ht,kn,Cn,bt,Js;class $c{constructor(){this.controller=new AbortController,Sn.set(this,void 0),An.set(this,()=>{}),Bt.set(this,()=>{}),Ut.set(this,void 0),En.set(this,()=>{}),qt.set(this,()=>{}),We.set(this,{}),Ht.set(this,!1),kn.set(this,!1),Cn.set(this,!1),bt.set(this,!1),Js.set(this,e=>{if(Re(this,kn,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Se),e instanceof Se)return Re(this,Cn,!0,"f"),this._emit("abort",e);if(e instanceof $)return this._emit("error",e);if(e instanceof Error){const t=new $(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new $(String(e)))}),Re(this,Sn,new Promise((e,t)=>{Re(this,An,e,"f"),Re(this,Bt,t,"f")}),"f"),Re(this,Ut,new Promise((e,t)=>{Re(this,En,e,"f"),Re(this,qt,t,"f")}),"f"),Z(this,Sn,"f").catch(()=>{}),Z(this,Ut,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emit("end")},Z(this,Js,"f"))},0)}_addRun(e){return e}_connected(){this.ended||(Z(this,An,"f").call(this),this._emit("connect"))}get ended(){return Z(this,Ht,"f")}get errored(){return Z(this,kn,"f")}get aborted(){return Z(this,Cn,"f")}abort(){this.controller.abort()}on(e,t){return(Z(this,We,"f")[e]||(Z(this,We,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=Z(this,We,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(Z(this,We,"f")[e]||(Z(this,We,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{Re(this,bt,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){Re(this,bt,!0,"f"),await Z(this,Ut,"f")}_emit(e,...t){if(Z(this,Ht,"f"))return;e==="end"&&(Re(this,Ht,!0,"f"),Z(this,En,"f").call(this));const s=Z(this,We,"f")[e];if(s&&(Z(this,We,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!Z(this,bt,"f")&&!(s!=null&&s.length)&&Promise.reject(r),Z(this,Bt,"f").call(this,r),Z(this,qt,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!Z(this,bt,"f")&&!(s!=null&&s.length)&&Promise.reject(r),Z(this,Bt,"f").call(this,r),Z(this,qt,"f").call(this,r),this._emit("end")}}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,r){return await this._createAssistantStream(t,e,s,r)}async _runToolAssistantStream(e,t,s,r,i){return await this._createToolAssistantStream(s,e,t,r,i)}async _createThreadAssistantStream(e,t,s){const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i=await e.createAndRun({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addRun(i)}async _createToolAssistantStream(e,t,s,r,i){const o=i==null?void 0:i.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a=await e.submitToolOutputs(t,s,{...r,stream:!1},{...i,signal:this.controller.signal});return this._connected(),this._addRun(a)}async _createAssistantStream(e,t,s,r){const i=r==null?void 0:r.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const o=await e.create(t,{...s,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addRun(o)}}Sn=new WeakMap,An=new WeakMap,Bt=new WeakMap,Ut=new WeakMap,En=new WeakMap,qt=new WeakMap,We=new WeakMap,Ht=new WeakMap,kn=new WeakMap,Cn=new WeakMap,bt=new WeakMap,Js=new WeakMap;var T=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},ye=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},le,Xs,Ne,Pn,Oe,ot,yt,st,$n,we,vn,Rn,Xt,$t,Wt,ai,li,ci,ui,fi,di,hi;class Me extends $c{constructor(){super(...arguments),le.add(this),Xs.set(this,[]),Ne.set(this,{}),Pn.set(this,{}),Oe.set(this,void 0),ot.set(this,void 0),yt.set(this,void 0),st.set(this,void 0),$n.set(this,void 0),we.set(this,void 0),vn.set(this,void 0),Rn.set(this,void 0),Xt.set(this,void 0)}[(Xs=new WeakMap,Ne=new WeakMap,Pn=new WeakMap,Oe=new WeakMap,ot=new WeakMap,yt=new WeakMap,st=new WeakMap,$n=new WeakMap,we=new WeakMap,vn=new WeakMap,Rn=new WeakMap,Xt=new WeakMap,le=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Me;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var i;const s=t==null?void 0:t.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=je.fromReadableStream(e,this.controller);for await(const o of r)T(this,le,"m",$t).call(this,o);if((i=r.controller.signal)!=null&&i.aborted)throw new Se;return this._addRun(T(this,le,"m",Wt).call(this))}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,r,i){const o=new Me;return o._run(()=>o._runToolAssistantStream(e,t,s,r,{...i,headers:{...i==null?void 0:i.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,s,r,i){var u;const o=i==null?void 0:i.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},l=await e.submitToolOutputs(t,s,a,{...i,signal:this.controller.signal});this._connected();for await(const f of l)T(this,le,"m",$t).call(this,f);if((u=l.controller.signal)!=null&&u.aborted)throw new Se;return this._addRun(T(this,le,"m",Wt).call(this))}static createThreadAssistantStream(e,t,s){const r=new Me;return r._run(()=>r._threadAssistantStream(e,t,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,s,r){const i=new Me;return i._run(()=>i._runAssistantStream(e,t,s,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return T(this,vn,"f")}currentRun(){return T(this,Rn,"f")}currentMessageSnapshot(){return T(this,Oe,"f")}currentRunStepSnapshot(){return T(this,Xt,"f")}async finalRunSteps(){return await this.done(),Object.values(T(this,Ne,"f"))}async finalMessages(){return await this.done(),Object.values(T(this,Pn,"f"))}async finalRun(){if(await this.done(),!T(this,ot,"f"))throw Error("Final run was not received.");return T(this,ot,"f")}async _createThreadAssistantStream(e,t,s){var a;const r=s==null?void 0:s.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...t,stream:!0},o=await e.createAndRun(i,{...s,signal:this.controller.signal});this._connected();for await(const l of o)T(this,le,"m",$t).call(this,l);if((a=o.controller.signal)!=null&&a.aborted)throw new Se;return this._addRun(T(this,le,"m",Wt).call(this))}async _createAssistantStream(e,t,s,r){var l;const i=r==null?void 0:r.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const o={...s,stream:!0},a=await e.create(t,o,{...r,signal:this.controller.signal});this._connected();for await(const u of a)T(this,le,"m",$t).call(this,u);if((l=a.controller.signal)!=null&&l.aborted)throw new Se;return this._addRun(T(this,le,"m",Wt).call(this))}static accumulateDelta(e,t){for(const[s,r]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let i=e[s];if(i==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof i=="string"&&typeof r=="string")i+=r;else if(typeof i=="number"&&typeof r=="number")i+=r;else if(si(i)&&si(r))i=this.accumulateDelta(i,r);else if(Array.isArray(i)&&Array.isArray(r)){if(i.every(o=>typeof o=="string"||typeof o=="number")){i.push(...r);continue}}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${i}`);e[s]=i}return e}}$t=function(e){if(!this.ended)switch(ye(this,vn,e,"f"),T(this,le,"m",ci).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":T(this,le,"m",hi).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":T(this,le,"m",li).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":T(this,le,"m",ai).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Wt=function(){if(this.ended)throw new $("stream has ended, this shouldn't happen");if(!T(this,ot,"f"))throw Error("Final run has not been received");return T(this,ot,"f")},ai=function(e){const[t,s]=T(this,le,"m",fi).call(this,e,T(this,Oe,"f"));ye(this,Oe,t,"f"),T(this,Pn,"f")[t.id]=t;for(const r of s){const i=t.content[r.index];(i==null?void 0:i.type)=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let i=r.text,o=t.content[r.index];if(o&&o.type=="text")this._emit("textDelta",i,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=T(this,yt,"f")){if(T(this,st,"f"))switch(T(this,st,"f").type){case"text":this._emit("textDone",T(this,st,"f").text,T(this,Oe,"f"));break;case"image_file":this._emit("imageFileDone",T(this,st,"f").image_file,T(this,Oe,"f"));break}ye(this,yt,r.index,"f")}ye(this,st,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(T(this,yt,"f")!==void 0){const r=e.data.content[T(this,yt,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,T(this,Oe,"f"));break;case"text":this._emit("textDone",r.text,T(this,Oe,"f"));break}}T(this,Oe,"f")&&this._emit("messageDone",e.data),ye(this,Oe,void 0,"f")}},li=function(e){const t=T(this,le,"m",ui).call(this,e);switch(ye(this,Xt,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const i of s.step_details.tool_calls)i.index==T(this,$n,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(T(this,we,"f")&&this._emit("toolCallDone",T(this,we,"f")),ye(this,$n,i.index,"f"),ye(this,we,t.step_details.tool_calls[i.index],"f"),T(this,we,"f")&&this._emit("toolCallCreated",T(this,we,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":ye(this,Xt,void 0,"f"),e.data.step_details.type=="tool_calls"&&T(this,we,"f")&&(this._emit("toolCallDone",T(this,we,"f")),ye(this,we,void 0,"f")),this._emit("runStepDone",e.data,t);break}},ci=function(e){T(this,Xs,"f").push(e),this._emit("event",e)},ui=function(e){switch(e.event){case"thread.run.step.created":return T(this,Ne,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=T(this,Ne,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=Me.accumulateDelta(t,s.delta);T(this,Ne,"f")[e.data.id]=r}return T(this,Ne,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":T(this,Ne,"f")[e.data.id]=e.data;break}if(T(this,Ne,"f")[e.data.id])return T(this,Ne,"f")[e.data.id];throw new Error("No snapshot available")},fi=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const i of r.delta.content)if(i.index in t.content){let o=t.content[i.index];t.content[i.index]=T(this,le,"m",di).call(this,i,o)}else t.content[i.index]=i,s.push(i);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},di=function(e,t){return Me.accumulateDelta(t,e)},hi=function(e){switch(ye(this,Rn,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":ye(this,ot,e.data,"f"),T(this,we,"f")&&(this._emit("toolCallDone",T(this,we,"f")),ye(this,we,void 0,"f"));break}};let Wn=class extends Y{retrieve(e,t,s,r){return this._client.get(`/threads/${e}/messages/${t}/files/${s}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(e,t,s={},r){return qe(s)?this.list(e,t,{},s):this._client.getAPIList(`/threads/${e}/messages/${t}/files`,fr,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}};class fr extends Je{}(function(n){n.MessageFilesPage=fr})(Wn||(Wn={}));class Gn extends Y{constructor(){super(...arguments),this.files=new Wn(this._client)}create(e,t,s){return this._client.post(`/threads/${e}/messages`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}retrieve(e,t,s){return this._client.get(`/threads/${e}/messages/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}update(e,t,s,r){return this._client.post(`/threads/${e}/messages/${t}`,{body:s,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(e,t={},s){return qe(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,dr,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}}class dr extends Je{}(function(n){n.MessagesPage=dr,n.Files=Wn,n.MessageFilesPage=fr})(Gn||(Gn={}));class zn extends Y{retrieve(e,t,s,r){return this._client.get(`/threads/${e}/runs/${t}/steps/${s}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(e,t,s={},r){return qe(s)?this.list(e,t,{},s):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,hr,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}}class hr extends Je{}(function(n){n.RunStepsPage=hr})(zn||(zn={}));class Jn extends Y{constructor(){super(...arguments),this.steps=new zn(this._client)}create(e,t,s){return this._client.post(`/threads/${e}/runs`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers},stream:t.stream??!1})}retrieve(e,t,s){return this._client.get(`/threads/${e}/runs/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}update(e,t,s,r){return this._client.post(`/threads/${e}/runs/${t}`,{body:s,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(e,t={},s){return qe(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,pr,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}cancel(e,t,s){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(e,r.id,s)}createAndStream(e,t,s){return Me.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const r={...s==null?void 0:s.headers,"X-Stainless-Poll-Helper":"true"};for(s!=null&&s.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const{data:i,response:o}=await this.retrieve(e,t,{...s,headers:{...s==null?void 0:s.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(s!=null&&s.pollIntervalMs)a=s.pollIntervalMs;else{const l=o.headers.get("openai-poll-after-ms");if(l){const u=parseInt(l);isNaN(u)||(a=u)}}await ar(a);break;case"requires_action":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,s){return Me.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s,r){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:s,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers},stream:s.stream??!1})}async submitToolOutputsAndPoll(e,t,s,r){const i=await this.submitToolOutputs(e,t,s,r);return await this.poll(e,i.id,r)}submitToolOutputsStream(e,t,s,r){return Me.createToolAssistantStream(e,t,this._client.beta.threads.runs,s,r)}}class pr extends Je{}(function(n){n.RunsPage=pr,n.Steps=zn,n.RunStepsPage=hr})(Jn||(Jn={}));class Xn extends Y{constructor(){super(...arguments),this.runs=new Jn(this._client),this.messages=new Gn(this._client)}create(e={},t){return qe(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}update(e,t,s){return this._client.post(`/threads/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.thread_id,s.id,t)}createAndRunStream(e,t){return Me.createThreadAssistantStream(e,this._client.beta.threads,t)}}(function(n){n.Runs=Jn,n.RunsPage=pr,n.Messages=Gn,n.MessagesPage=dr})(Xn||(Xn={}));class Kn extends Y{constructor(){super(...arguments),this.chat=new Hn(this._client),this.assistants=new Un(this._client),this.threads=new Xn(this._client)}}(function(n){n.Chat=Hn,n.Assistants=Un,n.AssistantsPage=ur,n.Threads=Xn})(Kn||(Kn={}));class Vn extends Y{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}Vn||(Vn={});class Qn extends Y{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}Qn||(Qn={});class Yn extends Y{create(e,t){return this._client.post("/files",Yt({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return qe(e)?this.list({},e):this._client.getAPIList("/files",mr,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t==null?void 0:t.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=30*60*1e3}={}){const r=new Set(["processed","error","deleted"]),i=Date.now();let o=await this.retrieve(e);for(;!o.status||!r.has(o.status);)if(await ar(t),o=await this.retrieve(e),Date.now()-i>s)throw new or({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return o}}class mr extends lr{}(function(n){n.FileObjectsPage=mr})(Yn||(Yn={}));class Zn extends Y{create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return qe(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",_r,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return qe(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,gr,{query:t,...s})}}class _r extends Je{}class gr extends Je{}(function(n){n.FineTuningJobsPage=_r,n.FineTuningJobEventsPage=gr})(Zn||(Zn={}));class es extends Y{constructor(){super(...arguments),this.jobs=new Zn(this._client)}}(function(n){n.Jobs=Zn,n.FineTuningJobsPage=_r,n.FineTuningJobEventsPage=gr})(es||(es={}));class ts extends Y{createVariation(e,t){return this._client.post("/images/variations",Yt({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",Yt({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}ts||(ts={});class ns extends Y{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",br,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class br extends lr{}(function(n){n.ModelsPage=br})(ns||(ns={}));class ss extends Y{create(e,t){return this._client.post("/moderations",{body:e,...t})}}ss||(ss={});var To;class ae extends Mc{constructor({baseURL:e=As("OPENAI_BASE_URL"),apiKey:t=As("OPENAI_API_KEY"),organization:s=As("OPENAI_ORG_ID")??null,...r}={}){if(t===void 0)throw new $("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const i={apiKey:t,organization:s,...r,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&qc())throw new $(`It looks like you're running in a browser-like environment. +"use strict";var Xi=Object.defineProperty;var Ki=(n,e,t)=>e in n?Xi(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var V=(n,e,t)=>(Ki(n,typeof e!="symbol"?e+"":e,t),t);const de=require("siyuan");function G(){}function Ce(n,e){for(const t in e)n[t]=e[t];return n}function js(n){return n()}function zr(){return Object.create(null)}function ie(n){n.forEach(js)}function Bs(n){return typeof n=="function"}function Oe(n,e){return n!=n?e==e:n!==e||n&&typeof n=="object"||typeof n=="function"}function Vi(n){return Object.keys(n).length===0}function br(n,e,t,r){if(n){const s=Us(n,e,t,r);return n[0](s)}}function Us(n,e,t,r){return n[1]&&r?Ce(t.ctx.slice(),n[1](r(e))):t.ctx}function wr(n,e,t,r){if(n[2]&&r){const s=n[2](r(t));if(e.dirty===void 0)return s;if(typeof s=="object"){const i=[],o=Math.max(e.dirty.length,s.length);for(let a=0;a32){const e=[],t=n.ctx.length/32;for(let r=0;rn.removeEventListener(e,t,r)}function Yi(n){return function(e){return e.preventDefault(),n.call(this,e)}}function k(n,e,t){t==null?n.removeAttribute(e):n.getAttribute(e)!==t&&n.setAttribute(e,t)}const Zi=["width","height"];function lt(n,e){const t=Object.getOwnPropertyDescriptors(n.__proto__);for(const r in e)e[r]==null?n.removeAttribute(r):r==="style"?n.style.cssText=e[r]:r==="__value"?n.value=n[r]=e[r]:t[r]&&t[r].set&&Zi.indexOf(r)===-1?n[r]=e[r]:k(n,r,e[r])}function er(n){return n===""?null:+n}function $i(n){return Array.from(n.childNodes)}function qe(n,e){e=""+e,n.data!==e&&(n.data=e)}function eo(n,e){e=""+e,n.wholeText!==e&&(n.data=e)}function to(n,e,t){~Qi.indexOf(t)?eo(n,e):qe(n,e)}function ke(n,e){n.value=e??""}function Xr(n,e,t,r){t==null?n.style.removeProperty(e):n.style.setProperty(e,t,r?"important":"")}function Kr(n,e,t){for(let r=0;r{const s=n.$$.callbacks[e];if(s){const i=ro(e,t,{cancelable:r});return s.slice().forEach(o=>{o.call(n,i)}),!i.defaultPrevented}return!0}}function Er(n,e){const t=n.$$.callbacks[e.type];t&&t.slice().forEach(r=>r.call(this,e))}const Ye=[],nn=[];let nt=[];const tr=[],oo=Promise.resolve();let nr=!1;function ao(){nr||(nr=!0,oo.then(Gs))}function rn(n){nt.push(n)}function Ws(n){tr.push(n)}const qn=new Set;let Ke=0;function Gs(){if(Ke!==0)return;const n=kt;do{try{for(;Ken.indexOf(r)===-1?e.push(r):t.push(r)),t.forEach(r=>r()),nt=e}const Bt=new Set;let Ge;function Tt(){Ge={r:0,c:[],p:Ge}}function vt(){Ge.r||ie(Ge.c),Ge=Ge.p}function q(n,e){n&&n.i&&(Bt.delete(n),n.i(e))}function W(n,e,t,r){if(n&&n.o){if(Bt.has(n))return;Bt.add(n),Ge.c.push(()=>{Bt.delete(n),r&&(t&&n.d(1),r())}),n.o(e)}else r&&r()}function vn(n,e){W(n,1,1,()=>{e.delete(n.key)})}function In(n,e,t,r,s,i,o,a,l,u,d,c){let h=n.length,g=i.length,f=h;const p={};for(;f--;)p[n[f].key]=f;const m=[],A=new Map,P=new Map,C=[];for(f=g;f--;){const S=c(s,i,f),R=t(S);let w=o.get(R);w?r&&C.push(()=>w.p(S,e)):(w=u(R,S),w.c()),A.set(R,m[f]=w),R in p&&P.set(R,Math.abs(f-p[R]))}const E=new Set,b=new Set;function _(S){q(S,1),S.m(a,d),o.set(S.key,S),d=S.first,g--}for(;h&&g;){const S=m[g-1],R=n[h-1],w=S.key,L=R.key;S===R?(d=S.first,h--,g--):A.has(L)?!o.has(w)||E.has(w)?_(S):b.has(L)?h--:P.get(w)>P.get(L)?(b.add(w),_(S)):(E.add(L),h--):(l(R,o),h--)}for(;h--;){const S=n[h];A.has(S.key)||l(S,o)}for(;g;)_(m[g-1]);return ie(C),m}function Pr(n,e){const t={},r={},s={$$scope:1};let i=n.length;for(;i--;){const o=n[i],a=e[i];if(a){for(const l in o)l in a||(r[l]=1);for(const l in a)s[l]||(t[l]=a[l],s[l]=1);n[i]=a}else for(const l in o)s[l]=1}for(const o in r)o in t||(t[o]=void 0);return t}function Js(n,e,t){const r=n.$$.props[e];r!==void 0&&(n.$$.bound[r]=t,t(n.$$.ctx[r]))}function re(n){n&&n.c()}function $(n,e,t,r){const{fragment:s,after_update:i}=n.$$;s&&s.m(e,t),r||rn(()=>{const o=n.$$.on_mount.map(js).filter(Bs);n.$$.on_destroy?n.$$.on_destroy.push(...o):ie(o),n.$$.on_mount=[]}),i.forEach(rn)}function ee(n,e){const t=n.$$;t.fragment!==null&&(co(t.after_update),ie(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function uo(n,e){n.$$.dirty[0]===-1&&(Ye.push(n),ao(),n.$$.dirty.fill(0)),n.$$.dirty[e/31|0]|=1<{const f=g.length?g[0]:h;return u.ctx&&s(u.ctx[c],u.ctx[c]=f)&&(!u.skip_bound&&u.bound[c]&&u.bound[c](f),d&&uo(n,c)),h}):[],u.update(),d=!0,ie(u.before_update),u.fragment=r?r(u.ctx):!1,e.target){if(e.hydrate){const c=$i(e.target);u.fragment&&u.fragment.l(c),c.forEach(H)}else u.fragment&&u.fragment.c();e.intro&&q(n.$$.fragment),$(n,e.target,e.anchor,e.customElement),Gs()}Et(l)}class xe{$destroy(){ee(this,1),this.$destroy=G}$on(e,t){if(!Bs(t))return G;const r=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return r.push(t),()=>{const s=r.indexOf(t);s!==-1&&r.splice(s,1)}}$set(e){this.$$set&&!Vi(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}function fo(n){let e,t,r,s,i,o=[{type:"button"},n[4],{class:r=["b3-button",n[3],n[2]].join(" ")},{style:n[1]}],a={};for(let l=0;l{t(4,e=Ce(Ce({},e),ot(c))),"text"in c&&t(5,o=c.text),"outline"in c&&t(6,a=c.outline),"backgroundColor"in c&&t(7,l=c.backgroundColor),"label"in c&&t(0,u=c.label)},n.$$.update=()=>{n.$$.dirty&64&&t(3,r=a?"b3-button--outline":""),n.$$.dirty&32&&t(2,s=o?"b3-button--text":""),n.$$.dirty&128&&t(1,i=l?`background-color: ${l}`:"")},e=ot(e),[u,i,s,r,e,o,a,l,d]}class Le extends xe{constructor(e){super(),Me(this,e,ho,fo,Oe,{text:5,outline:6,backgroundColor:7,label:0})}}function po(n){let e,t,r,s=[n[1],{class:"b3-switch"},{type:"checkbox"}],i={};for(let o=0;o{t(1,e=Ce(Ce({},e),ot(o))),"value"in o&&t(0,r=o.value)},e=ot(e),[r,e,s,i]}class _o extends xe{constructor(e){super(),Me(this,e,mo,po,Oe,{value:0})}}function go(n){let e,t,r,s,i=[n[1],{class:t=[n[1].class,"b3-text-field"].join(" ")}],o={};for(let a=0;a{t(1,e=Ce(Ce({},e),ot(o))),"value"in o&&t(0,r=o.value)},e=ot(e),[r,e,s,i]}class bo extends xe{constructor(e){super(),Me(this,e,yo,go,Oe,{value:0})}}function Qr(n,e,t){const r=n.slice();return r[18]=e[t][0],r[19]=e[t][1],r}function wo(n){let e,t,r,s,i,o,a;return{c(){e=I("div"),t=I("input"),k(t,"class","b3-slider fn__size200"),k(t,"id","fontSize"),k(t,"min",r=n[7].min),k(t,"max",s=n[7].max),k(t,"step",i=n[7].step),k(t,"type","range"),k(e,"class","b3-tooltips b3-tooltips__n"),k(e,"aria-label",n[0])},m(l,u){J(l,e,u),O(e,t),ke(t,n[0]),o||(a=[z(t,"change",n[16]),z(t,"input",n[16]),z(t,"change",n[9])],o=!0)},p(l,u){u&128&&r!==(r=l[7].min)&&k(t,"min",r),u&128&&s!==(s=l[7].max)&&k(t,"max",s),u&128&&i!==(i=l[7].step)&&k(t,"step",i),u&65&&ke(t,l[0]),u&65&&k(e,"aria-label",l[0])},i:G,o:G,d(l){l&&H(e),o=!1,ie(a)}}}function So(n){let e,t,r,s=Object.entries(n[6]),i=[];for(let o=0;on[15].call(e))},m(o,a){J(o,e,a);for(let l=0;lJs(e,"value",s)),e.$on("change",n[9]),{c(){re(e.$$.fragment)},m(o,a){$(e,o,a),r=!0},p(o,a){const l={};a&16&&(l.id=o[4]),!t&&a&1&&(t=!0,l.value=o[0],Ws(()=>t=!1)),e.$set(l)},i(o){r||(q(e.$$.fragment,o),r=!0)},o(o){W(e.$$.fragment,o),r=!1},d(o){ee(e,o)}}}function Eo(n){let e,t,r,s;return{c(){e=I("button"),t=se(n[0]),k(e,"class","b3-button b3-button--outline fn__flex-center fn__size200"),k(e,"id",n[4])},m(i,o){J(i,e,o),O(e,t),r||(s=z(e,"click",n[8]),r=!0)},p(i,o){o&1&&qe(t,i[0]),o&16&&k(e,"id",i[4])},i:G,o:G,d(i){i&&H(e),r=!1,s()}}}function Po(n){let e,t,r;return{c(){e=I("input"),k(e,"class","b3-text-field fn__flex-center fn__size200"),k(e,"id",n[4]),k(e,"type","number")},m(s,i){J(s,e,i),ke(e,n[0]),t||(r=[z(e,"input",n[13]),z(e,"change",n[9])],t=!0)},p(s,i){i&16&&k(e,"id",s[4]),i&65&&er(e.value)!==s[0]&&ke(e,s[0])},i:G,o:G,d(s){s&&H(e),t=!1,ie(r)}}}function Co(n){let e,t,r;function s(o){n[12](o)}let i={class:"b3-text-field fn__flex-center fn__size200",rows:"6",placeholder:n[5]};return n[0]!==void 0&&(i.value=n[0]),e=new bo({props:i}),nn.push(()=>Js(e,"value",s)),e.$on("change",n[9]),{c(){re(e.$$.fragment)},m(o,a){$(e,o,a),r=!0},p(o,a){const l={};a&32&&(l.placeholder=o[5]),!t&&a&1&&(t=!0,l.value=o[0],Ws(()=>t=!1)),e.$set(l)},i(o){r||(q(e.$$.fragment,o),r=!0)},o(o){W(e.$$.fragment,o),r=!1},d(o){ee(e,o)}}}function ko(n){let e,t,r;return{c(){e=I("input"),k(e,"class","b3-text-field fn__flex-center fn__size200"),k(e,"id",n[4]),k(e,"placeholder",n[5])},m(s,i){J(s,e,i),ke(e,n[0]),t||(r=[z(e,"input",n[11]),z(e,"change",n[9])],t=!0)},p(s,i){i&16&&k(e,"id",s[4]),i&32&&k(e,"placeholder",s[5]),i&65&&e.value!==s[0]&&ke(e,s[0])},i:G,o:G,d(s){s&&H(e),t=!1,ie(r)}}}function Ro(n){let e,t,r;return{c(){e=I("input"),k(e,"class","b3-switch fn__flex-center"),k(e,"id",n[4]),k(e,"type","checkbox")},m(s,i){J(s,e,i),e.checked=n[0],t||(r=[z(e,"change",n[10]),z(e,"change",n[9])],t=!0)},p(s,i){i&16&&k(e,"id",s[4]),i&65&&(e.checked=s[0])},i:G,o:G,d(s){s&&H(e),t=!1,ie(r)}}}function Yr(n){let e,t=n[19]+"",r,s;return{c(){e=I("option"),r=se(t),e.__value=s=n[18],e.value=e.__value},m(i,o){J(i,e,o),O(e,r)},p(i,o){o&64&&t!==(t=i[19]+"")&&qe(r,t),o&64&&s!==(s=i[18])&&(e.__value=s,e.value=e.__value)},d(i){i&&H(e)}}}function Oo(n){let e,t,r,s,i,o,a,l,u;const d=[Ro,ko,Co,Po,Eo,Ao,So,wo],c=[];function h(g,f){return g[1]==="checkbox"?0:g[1]==="textinput"?1:g[1]==="textarea"?2:g[1]==="number"?3:g[1]==="button"?4:g[1]==="switch"?5:g[1]==="select"?6:g[1]=="slider"?7:-1}return~(a=h(n))&&(l=c[a]=d[a](n)),{c(){e=I("label"),t=I("div"),r=se(n[2]),s=U(),i=I("div"),o=U(),l&&l.c(),k(i,"class","b3-label__text"),k(t,"class","fn__flex-1"),k(e,"class","fn__flex b3-label")},m(g,f){J(g,e,f),O(e,t),O(t,r),O(t,s),O(t,i),i.innerHTML=n[3],O(e,o),~a&&c[a].m(e,null),u=!0},p(g,[f]){(!u||f&4)&&qe(r,g[2]),(!u||f&8)&&(i.innerHTML=g[3]);let p=a;a=h(g),a===p?~a&&c[a].p(g,f):(l&&(Tt(),W(c[p],1,1,()=>{c[p]=null}),vt()),~a?(l=c[a],l?l.p(g,f):(l=c[a]=d[a](g),l.c()),q(l,1),l.m(e,null)):l=null)},i(g){u||(q(l),u=!0)},o(g){W(l),u=!1},d(g){g&&H(e),~a&&c[a].d()}}}function Mo(n,e,t){let{type:r}=e,{title:s}=e,{description:i}=e,{settingKey:o}=e,{settingValue:a}=e,{placeholder:l=""}=e,{options:u={}}=e,{slider:d={min:0,max:100,step:1}}=e;const c=io();function h(){c("clicked")}function g(){c("changed",{key:o,value:a})}function f(){a=this.checked,t(0,a),t(6,u)}function p(){a=this.value,t(0,a),t(6,u)}function m(b){a=b,t(0,a)}function A(){a=er(this.value),t(0,a),t(6,u)}function P(b){a=b,t(0,a)}function C(){a=no(this),t(0,a),t(6,u)}function E(){a=er(this.value),t(0,a),t(6,u)}return n.$$set=b=>{"type"in b&&t(1,r=b.type),"title"in b&&t(2,s=b.title),"description"in b&&t(3,i=b.description),"settingKey"in b&&t(4,o=b.settingKey),"settingValue"in b&&t(0,a=b.settingValue),"placeholder"in b&&t(5,l=b.placeholder),"options"in b&&t(6,u=b.options),"slider"in b&&t(7,d=b.slider)},[a,r,s,i,o,l,u,d,h,g,f,p,m,A,P,C,E]}class Cr extends xe{constructor(e){super(),Me(this,e,Mo,Oo,Oe,{type:1,title:2,description:3,settingKey:4,settingValue:0,placeholder:5,options:6,slider:7})}}var N;(function(n){n[n.PLAIN_TO_CLASS=0]="PLAIN_TO_CLASS",n[n.CLASS_TO_PLAIN=1]="CLASS_TO_PLAIN",n[n.CLASS_TO_CLASS=2]="CLASS_TO_CLASS"})(N||(N={}));var xo=function(){function n(){this._typeMetadatas=new Map,this._transformMetadatas=new Map,this._exposeMetadatas=new Map,this._excludeMetadatas=new Map,this._ancestorsMap=new Map}return n.prototype.addTypeMetadata=function(e){this._typeMetadatas.has(e.target)||this._typeMetadatas.set(e.target,new Map),this._typeMetadatas.get(e.target).set(e.propertyName,e)},n.prototype.addTransformMetadata=function(e){this._transformMetadatas.has(e.target)||this._transformMetadatas.set(e.target,new Map),this._transformMetadatas.get(e.target).has(e.propertyName)||this._transformMetadatas.get(e.target).set(e.propertyName,[]),this._transformMetadatas.get(e.target).get(e.propertyName).push(e)},n.prototype.addExposeMetadata=function(e){this._exposeMetadatas.has(e.target)||this._exposeMetadatas.set(e.target,new Map),this._exposeMetadatas.get(e.target).set(e.propertyName,e)},n.prototype.addExcludeMetadata=function(e){this._excludeMetadatas.has(e.target)||this._excludeMetadatas.set(e.target,new Map),this._excludeMetadatas.get(e.target).set(e.propertyName,e)},n.prototype.findTransformMetadatas=function(e,t,r){return this.findMetadatas(this._transformMetadatas,e,t).filter(function(s){return!s.options||s.options.toClassOnly===!0&&s.options.toPlainOnly===!0?!0:s.options.toClassOnly===!0?r===N.CLASS_TO_CLASS||r===N.PLAIN_TO_CLASS:s.options.toPlainOnly===!0?r===N.CLASS_TO_PLAIN:!0})},n.prototype.findExcludeMetadata=function(e,t){return this.findMetadata(this._excludeMetadatas,e,t)},n.prototype.findExposeMetadata=function(e,t){return this.findMetadata(this._exposeMetadatas,e,t)},n.prototype.findExposeMetadataByCustomName=function(e,t){return this.getExposedMetadatas(e).find(function(r){return r.options&&r.options.name===t})},n.prototype.findTypeMetadata=function(e,t){return this.findMetadata(this._typeMetadatas,e,t)},n.prototype.getStrategy=function(e){var t=this._excludeMetadatas.get(e),r=t&&t.get(void 0),s=this._exposeMetadatas.get(e),i=s&&s.get(void 0);return r&&i||!r&&!i?"none":r?"excludeAll":"exposeAll"},n.prototype.getExposedMetadatas=function(e){return this.getMetadata(this._exposeMetadatas,e)},n.prototype.getExcludedMetadatas=function(e){return this.getMetadata(this._excludeMetadatas,e)},n.prototype.getExposedProperties=function(e,t){return this.getExposedMetadatas(e).filter(function(r){return!r.options||r.options.toClassOnly===!0&&r.options.toPlainOnly===!0?!0:r.options.toClassOnly===!0?t===N.CLASS_TO_CLASS||t===N.PLAIN_TO_CLASS:r.options.toPlainOnly===!0?t===N.CLASS_TO_PLAIN:!0}).map(function(r){return r.propertyName})},n.prototype.getExcludedProperties=function(e,t){return this.getExcludedMetadatas(e).filter(function(r){return!r.options||r.options.toClassOnly===!0&&r.options.toPlainOnly===!0?!0:r.options.toClassOnly===!0?t===N.CLASS_TO_CLASS||t===N.PLAIN_TO_CLASS:r.options.toPlainOnly===!0?t===N.CLASS_TO_PLAIN:!0}).map(function(r){return r.propertyName})},n.prototype.clear=function(){this._typeMetadatas.clear(),this._exposeMetadatas.clear(),this._excludeMetadatas.clear(),this._ancestorsMap.clear()},n.prototype.getMetadata=function(e,t){var r=e.get(t),s;r&&(s=Array.from(r.values()).filter(function(c){return c.propertyName!==void 0}));for(var i=[],o=0,a=this.getAncestors(t);o0&&(o=o.filter(function(c){return!u.includes(c)})),this.options.version!==void 0&&(o=o.filter(function(c){var h=ae.findExposeMetadata(e,c);return!h||!h.options?!0:s.checkVersion(h.options.since,h.options.until)})),this.options.groups&&this.options.groups.length?o=o.filter(function(c){var h=ae.findExposeMetadata(e,c);return!h||!h.options?!0:s.checkGroups(h.options.groups)}):o=o.filter(function(c){var h=ae.findExposeMetadata(e,c);return!h||!h.options||!h.options.groups||!h.options.groups.length})}return this.options.excludePrefixes&&this.options.excludePrefixes.length&&(o=o.filter(function(d){return s.options.excludePrefixes.every(function(c){return d.substr(0,c.length)!==c})})),o=o.filter(function(d,c,h){return h.indexOf(d)===c}),o},n.prototype.checkVersion=function(e,t){var r=!0;return r&&e&&(r=this.options.version>=e),r&&t&&(r=this.options.version(n.click_editorcontent="click-editorcontent",n.open_menu_doctree="open-menu-doctree",n.loaded_protyle_static="loaded-protyle-static",n.loaded_protyle_dynamic="loaded-protyle-dynamic",n.switch_protyle="switch-protyle",n.destroy_protyle="destroy-protyle",n.ws_main="ws-main",n.click_flashcard_action="click-flashcard-action",n.click_blockicon="click-blockicon",n.click_pdf="click-pdf",n.click_editortitleicon="click-editortitleicon",n.open_noneditableblock="open-noneditableblock",n.open_menu_blockref="open-menu-blockref",n.open_menu_fileannotationref="open-menu-fileannotationref",n.open_menu_tag="open-menu-tag",n.open_menu_link="open-menu-link",n.open_menu_image="open-menu-image",n.open_menu_av="open-menu-av",n.open_menu_content="open-menu-content",n.open_menu_breadcrumbmore="open-menu-breadcrumbmore",n.input_search="input-search",n.paste="paste",n.open_siyuan_url_plugin="open-siyuan-url-plugin",n.open_siyuan_url_block="open-siyuan-url-block",n))(zs||{}),M=(n=>(n.SERVICE_PROVIDER="ai-service-provider",n.TIMEOUT="ai-request-timeout",n.GENERATE_MAX_TOKEN="ai-generate-max-token",n.REQUEST_MAX_TOKEN="ai-request-max-token",n.TEMPERATURE="ai-temperature",n.MODEL="ai-model",n.API_KEY="ai-api-key",n.BASE_URL="ai-endpoint",n.hint="ai-hint",n.PROMPT_TITLE="ai-prompt-title",n.PROMPT="ai-prompt-content",n.IMG_PROMPT="ai-img-prompt",n.IMG_PROMTP_TITLE="ai-img-prompt-title",n.IMG_MODEL="ai-img-model",n.IMG_NUM="ai-img-number",n.IMG_SIZE="ai-img-size",n.IMG_QUALITY="ai-img-quality",n.STREAM="ai-stream",n))(M||{}),le=(n=>(n.checkbox="checkbox",n.select="select",n.textinput="textinput",n.textarea="textarea",n.number="number",n.slider="slider",n.button="button",n.hint="hint",n.switch="switch",n))(le||{});class Je{}V(Je,"PLUGIN_NAME","siyuan-ai"),V(Je,"AI_SETTING_STORAGE","siyuan-ai-settings.json"),V(Je,"AI_PROMPT_STORAGE","siyuan-ai-prompts.json"),V(Je,"IS_DEVELOP","false");function Xs(n,e){return function(){return n.apply(e,arguments)}}const{toString:Do}=Object.prototype,{getPrototypeOf:kr}=Object,Ln=(n=>e=>{const t=Do.call(e);return n[t]||(n[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Te=n=>(n=n.toLowerCase(),e=>Ln(e)===n),Nn=n=>e=>typeof e===n,{isArray:ut}=Array,Rt=Nn("undefined");function jo(n){return n!==null&&!Rt(n)&&n.constructor!==null&&!Rt(n.constructor)&&pe(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}const Ks=Te("ArrayBuffer");function Bo(n){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(n):e=n&&n.buffer&&Ks(n.buffer),e}const Uo=Nn("string"),pe=Nn("function"),Vs=Nn("number"),Fn=n=>n!==null&&typeof n=="object",qo=n=>n===!0||n===!1,Ut=n=>{if(Ln(n)!=="object")return!1;const e=kr(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},Ho=Te("Date"),Wo=Te("File"),Go=Te("Blob"),Jo=Te("FileList"),zo=n=>Fn(n)&&pe(n.pipe),Xo=n=>{let e;return n&&(typeof FormData=="function"&&n instanceof FormData||pe(n.append)&&((e=Ln(n))==="formdata"||e==="object"&&pe(n.toString)&&n.toString()==="[object FormData]"))},Ko=Te("URLSearchParams"),Vo=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function It(n,e,{allOwnKeys:t=!1}={}){if(n===null||typeof n>"u")return;let r,s;if(typeof n!="object"&&(n=[n]),ut(n))for(r=0,s=n.length;r0;)if(s=t[r],e===s.toLowerCase())return s;return null}const Ys=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),Zs=n=>!Rt(n)&&n!==Ys;function rr(){const{caseless:n}=Zs(this)&&this||{},e={},t=(r,s)=>{const i=n&&Qs(e,s)||s;Ut(e[i])&&Ut(r)?e[i]=rr(e[i],r):Ut(r)?e[i]=rr({},r):ut(r)?e[i]=r.slice():e[i]=r};for(let r=0,s=arguments.length;r(It(e,(s,i)=>{t&&pe(s)?n[i]=Xs(s,t):n[i]=s},{allOwnKeys:r}),n),Yo=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),Zo=(n,e,t,r)=>{n.prototype=Object.create(e.prototype,r),n.prototype.constructor=n,Object.defineProperty(n,"super",{value:e.prototype}),t&&Object.assign(n.prototype,t)},$o=(n,e,t,r)=>{let s,i,o;const a={};if(e=e||{},n==null)return e;do{for(s=Object.getOwnPropertyNames(n),i=s.length;i-- >0;)o=s[i],(!r||r(o,n,e))&&!a[o]&&(e[o]=n[o],a[o]=!0);n=t!==!1&&kr(n)}while(n&&(!t||t(n,e))&&n!==Object.prototype);return e},ea=(n,e,t)=>{n=String(n),(t===void 0||t>n.length)&&(t=n.length),t-=e.length;const r=n.indexOf(e,t);return r!==-1&&r===t},ta=n=>{if(!n)return null;if(ut(n))return n;let e=n.length;if(!Vs(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=n[e];return t},na=(n=>e=>n&&e instanceof n)(typeof Uint8Array<"u"&&kr(Uint8Array)),ra=(n,e)=>{const r=(n&&n[Symbol.iterator]).call(n);let s;for(;(s=r.next())&&!s.done;){const i=s.value;e.call(n,i[0],i[1])}},sa=(n,e)=>{let t;const r=[];for(;(t=n.exec(e))!==null;)r.push(t);return r},ia=Te("HTMLFormElement"),oa=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,r,s){return r.toUpperCase()+s}),$r=(({hasOwnProperty:n})=>(e,t)=>n.call(e,t))(Object.prototype),aa=Te("RegExp"),$s=(n,e)=>{const t=Object.getOwnPropertyDescriptors(n),r={};It(t,(s,i)=>{let o;(o=e(s,i,n))!==!1&&(r[i]=o||s)}),Object.defineProperties(n,r)},la=n=>{$s(n,(e,t)=>{if(pe(n)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const r=n[t];if(pe(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},ca=(n,e)=>{const t={},r=s=>{s.forEach(i=>{t[i]=!0})};return ut(n)?r(n):r(String(n).split(e)),t},ua=()=>{},fa=(n,e)=>(n=+n,Number.isFinite(n)?n:e),Hn="abcdefghijklmnopqrstuvwxyz",es="0123456789",ei={DIGIT:es,ALPHA:Hn,ALPHA_DIGIT:Hn+Hn.toUpperCase()+es},da=(n=16,e=ei.ALPHA_DIGIT)=>{let t="";const{length:r}=e;for(;n--;)t+=e[Math.random()*r|0];return t};function ha(n){return!!(n&&pe(n.append)&&n[Symbol.toStringTag]==="FormData"&&n[Symbol.iterator])}const pa=n=>{const e=new Array(10),t=(r,s)=>{if(Fn(r)){if(e.indexOf(r)>=0)return;if(!("toJSON"in r)){e[s]=r;const i=ut(r)?[]:{};return It(r,(o,a)=>{const l=t(o,s+1);!Rt(l)&&(i[a]=l)}),e[s]=void 0,i}}return r};return t(n,0)},ma=Te("AsyncFunction"),_a=n=>n&&(Fn(n)||pe(n))&&pe(n.then)&&pe(n.catch),y={isArray:ut,isArrayBuffer:Ks,isBuffer:jo,isFormData:Xo,isArrayBufferView:Bo,isString:Uo,isNumber:Vs,isBoolean:qo,isObject:Fn,isPlainObject:Ut,isUndefined:Rt,isDate:Ho,isFile:Wo,isBlob:Go,isRegExp:aa,isFunction:pe,isStream:zo,isURLSearchParams:Ko,isTypedArray:na,isFileList:Jo,forEach:It,merge:rr,extend:Qo,trim:Vo,stripBOM:Yo,inherits:Zo,toFlatObject:$o,kindOf:Ln,kindOfTest:Te,endsWith:ea,toArray:ta,forEachEntry:ra,matchAll:sa,isHTMLForm:ia,hasOwnProperty:$r,hasOwnProp:$r,reduceDescriptors:$s,freezeMethods:la,toObjectSet:ca,toCamelCase:oa,noop:ua,toFiniteNumber:fa,findKey:Qs,global:Ys,isContextDefined:Zs,ALPHABET:ei,generateString:da,isSpecCompliantForm:ha,toJSONObject:pa,isAsyncFn:ma,isThenable:_a};function j(n,e,t,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=n,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),r&&(this.request=r),s&&(this.response=s)}y.inherits(j,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:y.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const ti=j.prototype,ni={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(n=>{ni[n]={value:n}});Object.defineProperties(j,ni);Object.defineProperty(ti,"isAxiosError",{value:!0});j.from=(n,e,t,r,s,i)=>{const o=Object.create(ti);return y.toFlatObject(n,o,function(l){return l!==Error.prototype},a=>a!=="isAxiosError"),j.call(o,n.message,e,t,r,s),o.cause=n,o.name=n.name,i&&Object.assign(o,i),o};const ga=null;function sr(n){return y.isPlainObject(n)||y.isArray(n)}function ri(n){return y.endsWith(n,"[]")?n.slice(0,-2):n}function ts(n,e,t){return n?n.concat(e).map(function(s,i){return s=ri(s),!t&&i?"["+s+"]":s}).join(t?".":""):e}function ya(n){return y.isArray(n)&&!n.some(sr)}const ba=y.toFlatObject(y,{},null,function(e){return/^is[A-Z]/.test(e)});function Dn(n,e,t){if(!y.isObject(n))throw new TypeError("target must be an object");e=e||new FormData,t=y.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(p,m){return!y.isUndefined(m[p])});const r=t.metaTokens,s=t.visitor||d,i=t.dots,o=t.indexes,l=(t.Blob||typeof Blob<"u"&&Blob)&&y.isSpecCompliantForm(e);if(!y.isFunction(s))throw new TypeError("visitor must be a function");function u(f){if(f===null)return"";if(y.isDate(f))return f.toISOString();if(!l&&y.isBlob(f))throw new j("Blob is not supported. Use a Buffer instead.");return y.isArrayBuffer(f)||y.isTypedArray(f)?l&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function d(f,p,m){let A=f;if(f&&!m&&typeof f=="object"){if(y.endsWith(p,"{}"))p=r?p:p.slice(0,-2),f=JSON.stringify(f);else if(y.isArray(f)&&ya(f)||(y.isFileList(f)||y.endsWith(p,"[]"))&&(A=y.toArray(f)))return p=ri(p),A.forEach(function(C,E){!(y.isUndefined(C)||C===null)&&e.append(o===!0?ts([p],E,i):o===null?p:p+"[]",u(C))}),!1}return sr(f)?!0:(e.append(ts(m,p,i),u(f)),!1)}const c=[],h=Object.assign(ba,{defaultVisitor:d,convertValue:u,isVisitable:sr});function g(f,p){if(!y.isUndefined(f)){if(c.indexOf(f)!==-1)throw Error("Circular reference detected in "+p.join("."));c.push(f),y.forEach(f,function(A,P){(!(y.isUndefined(A)||A===null)&&s.call(e,A,y.isString(P)?P.trim():P,p,h))===!0&&g(A,p?p.concat(P):[P])}),c.pop()}}if(!y.isObject(n))throw new TypeError("data must be an object");return g(n),e}function ns(n){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(n).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Rr(n,e){this._pairs=[],n&&Dn(n,this,e)}const si=Rr.prototype;si.append=function(e,t){this._pairs.push([e,t])};si.toString=function(e){const t=e?function(r){return e.call(this,r,ns)}:ns;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function wa(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ii(n,e,t){if(!e)return n;const r=t&&t.encode||wa,s=t&&t.serialize;let i;if(s?i=s(e,t):i=y.isURLSearchParams(e)?e.toString():new Rr(e,t).toString(r),i){const o=n.indexOf("#");o!==-1&&(n=n.slice(0,o)),n+=(n.indexOf("?")===-1?"?":"&")+i}return n}class Sa{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){y.forEach(this.handlers,function(r){r!==null&&e(r)})}}const rs=Sa,oi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Aa=typeof URLSearchParams<"u"?URLSearchParams:Rr,Ea=typeof FormData<"u"?FormData:null,Pa=typeof Blob<"u"?Blob:null,Ca={isBrowser:!0,classes:{URLSearchParams:Aa,FormData:Ea,Blob:Pa},protocols:["http","https","file","blob","url","data"]},ai=typeof window<"u"&&typeof document<"u",ka=(n=>ai&&["ReactNative","NativeScript","NS"].indexOf(n)<0)(typeof navigator<"u"&&navigator.product),Ra=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),Oa=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ai,hasStandardBrowserEnv:ka,hasStandardBrowserWebWorkerEnv:Ra},Symbol.toStringTag,{value:"Module"})),Ee={...Oa,...Ca};function Ma(n,e){return Dn(n,new Ee.classes.URLSearchParams,Object.assign({visitor:function(t,r,s,i){return Ee.isNode&&y.isBuffer(t)?(this.append(r,t.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},e))}function xa(n){return y.matchAll(/\w+|\[(\w*)]/g,n).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Ta(n){const e={},t=Object.keys(n);let r;const s=t.length;let i;for(r=0;r=t.length;return o=!o&&y.isArray(s)?s.length:o,l?(y.hasOwnProp(s,o)?s[o]=[s[o],r]:s[o]=r,!a):((!s[o]||!y.isObject(s[o]))&&(s[o]=[]),e(t,r,s[o],i)&&y.isArray(s[o])&&(s[o]=Ta(s[o])),!a)}if(y.isFormData(n)&&y.isFunction(n.entries)){const t={};return y.forEachEntry(n,(r,s)=>{e(xa(r),s,t,0)}),t}return null}function va(n,e,t){if(y.isString(n))try{return(e||JSON.parse)(n),y.trim(n)}catch(r){if(r.name!=="SyntaxError")throw r}return(t||JSON.stringify)(n)}const Or={transitional:oi,adapter:["xhr","http"],transformRequest:[function(e,t){const r=t.getContentType()||"",s=r.indexOf("application/json")>-1,i=y.isObject(e);if(i&&y.isHTMLForm(e)&&(e=new FormData(e)),y.isFormData(e))return s?JSON.stringify(li(e)):e;if(y.isArrayBuffer(e)||y.isBuffer(e)||y.isStream(e)||y.isFile(e)||y.isBlob(e))return e;if(y.isArrayBufferView(e))return e.buffer;if(y.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Ma(e,this.formSerializer).toString();if((a=y.isFileList(e))||r.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return Dn(a?{"files[]":e}:e,l&&new l,this.formSerializer)}}return i||s?(t.setContentType("application/json",!1),va(e)):e}],transformResponse:[function(e){const t=this.transitional||Or.transitional,r=t&&t.forcedJSONParsing,s=this.responseType==="json";if(e&&y.isString(e)&&(r&&!this.responseType||s)){const o=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?j.from(a,j.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ee.classes.FormData,Blob:Ee.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};y.forEach(["delete","get","head","post","put","patch"],n=>{Or.headers[n]={}});const Mr=Or,Ia=y.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),La=n=>{const e={};let t,r,s;return n&&n.split(` +`).forEach(function(o){s=o.indexOf(":"),t=o.substring(0,s).trim().toLowerCase(),r=o.substring(s+1).trim(),!(!t||e[t]&&Ia[t])&&(t==="set-cookie"?e[t]?e[t].push(r):e[t]=[r]:e[t]=e[t]?e[t]+", "+r:r)}),e},ss=Symbol("internals");function dt(n){return n&&String(n).trim().toLowerCase()}function qt(n){return n===!1||n==null?n:y.isArray(n)?n.map(qt):String(n)}function Na(n){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=t.exec(n);)e[r[1]]=r[2];return e}const Fa=n=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(n.trim());function Wn(n,e,t,r,s){if(y.isFunction(r))return r.call(this,e,t);if(s&&(e=t),!!y.isString(e)){if(y.isString(r))return e.indexOf(r)!==-1;if(y.isRegExp(r))return r.test(e)}}function Da(n){return n.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}function ja(n,e){const t=y.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(n,r+t,{value:function(s,i,o){return this[r].call(this,e,s,i,o)},configurable:!0})})}class jn{constructor(e){e&&this.set(e)}set(e,t,r){const s=this;function i(a,l,u){const d=dt(l);if(!d)throw new Error("header name must be a non-empty string");const c=y.findKey(s,d);(!c||s[c]===void 0||u===!0||u===void 0&&s[c]!==!1)&&(s[c||l]=qt(a))}const o=(a,l)=>y.forEach(a,(u,d)=>i(u,d,l));return y.isPlainObject(e)||e instanceof this.constructor?o(e,t):y.isString(e)&&(e=e.trim())&&!Fa(e)?o(La(e),t):e!=null&&i(t,e,r),this}get(e,t){if(e=dt(e),e){const r=y.findKey(this,e);if(r){const s=this[r];if(!t)return s;if(t===!0)return Na(s);if(y.isFunction(t))return t.call(this,s,r);if(y.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=dt(e),e){const r=y.findKey(this,e);return!!(r&&this[r]!==void 0&&(!t||Wn(this,this[r],r,t)))}return!1}delete(e,t){const r=this;let s=!1;function i(o){if(o=dt(o),o){const a=y.findKey(r,o);a&&(!t||Wn(r,r[a],a,t))&&(delete r[a],s=!0)}}return y.isArray(e)?e.forEach(i):i(e),s}clear(e){const t=Object.keys(this);let r=t.length,s=!1;for(;r--;){const i=t[r];(!e||Wn(this,this[i],i,e,!0))&&(delete this[i],s=!0)}return s}normalize(e){const t=this,r={};return y.forEach(this,(s,i)=>{const o=y.findKey(r,i);if(o){t[o]=qt(s),delete t[i];return}const a=e?Da(i):String(i).trim();a!==i&&delete t[i],t[a]=qt(s),r[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return y.forEach(this,(r,s)=>{r!=null&&r!==!1&&(t[s]=e&&y.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(s=>r.set(s)),r}static accessor(e){const r=(this[ss]=this[ss]={accessors:{}}).accessors,s=this.prototype;function i(o){const a=dt(o);r[a]||(ja(s,o),r[a]=!0)}return y.isArray(e)?e.forEach(i):i(e),this}}jn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);y.reduceDescriptors(jn.prototype,({value:n},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>n,set(r){this[t]=r}}});y.freezeMethods(jn);const Ne=jn;function Gn(n,e){const t=this||Mr,r=e||t,s=Ne.from(r.headers);let i=r.data;return y.forEach(n,function(a){i=a.call(t,i,s.normalize(),e?e.status:void 0)}),s.normalize(),i}function ci(n){return!!(n&&n.__CANCEL__)}function Lt(n,e,t){j.call(this,n??"canceled",j.ERR_CANCELED,e,t),this.name="CanceledError"}y.inherits(Lt,j,{__CANCEL__:!0});function Ba(n,e,t){const r=t.config.validateStatus;!t.status||!r||r(t.status)?n(t):e(new j("Request failed with status code "+t.status,[j.ERR_BAD_REQUEST,j.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}const Ua=Ee.hasStandardBrowserEnv?{write(n,e,t,r,s,i){const o=[n+"="+encodeURIComponent(e)];y.isNumber(t)&&o.push("expires="+new Date(t).toGMTString()),y.isString(r)&&o.push("path="+r),y.isString(s)&&o.push("domain="+s),i===!0&&o.push("secure"),document.cookie=o.join("; ")},read(n){const e=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(n){this.write(n,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function qa(n){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}function Ha(n,e){return e?n.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):n}function ui(n,e){return n&&!qa(e)?Ha(n,e):e}const Wa=Ee.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let r;function s(i){let o=i;return e&&(t.setAttribute("href",o),o=t.href),t.setAttribute("href",o),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:t.pathname.charAt(0)==="/"?t.pathname:"/"+t.pathname}}return r=s(window.location.href),function(o){const a=y.isString(o)?s(o):o;return a.protocol===r.protocol&&a.host===r.host}}():function(){return function(){return!0}}();function Ga(n){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(n);return e&&e[1]||""}function Ja(n,e){n=n||10;const t=new Array(n),r=new Array(n);let s=0,i=0,o;return e=e!==void 0?e:1e3,function(l){const u=Date.now(),d=r[i];o||(o=u),t[s]=l,r[s]=u;let c=i,h=0;for(;c!==s;)h+=t[c++],c=c%n;if(s=(s+1)%n,s===i&&(i=(i+1)%n),u-o{const i=s.loaded,o=s.lengthComputable?s.total:void 0,a=i-t,l=r(a),u=i<=o;t=i;const d={loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:l||void 0,estimated:l&&o&&u?(o-i)/l:void 0,event:s};d[e?"download":"upload"]=!0,n(d)}}const za=typeof XMLHttpRequest<"u",Xa=za&&function(n){return new Promise(function(t,r){let s=n.data;const i=Ne.from(n.headers).normalize();let{responseType:o,withXSRFToken:a}=n,l;function u(){n.cancelToken&&n.cancelToken.unsubscribe(l),n.signal&&n.signal.removeEventListener("abort",l)}let d;if(y.isFormData(s)){if(Ee.hasStandardBrowserEnv||Ee.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((d=i.getContentType())!==!1){const[p,...m]=d?d.split(";").map(A=>A.trim()).filter(Boolean):[];i.setContentType([p||"multipart/form-data",...m].join("; "))}}let c=new XMLHttpRequest;if(n.auth){const p=n.auth.username||"",m=n.auth.password?unescape(encodeURIComponent(n.auth.password)):"";i.set("Authorization","Basic "+btoa(p+":"+m))}const h=ui(n.baseURL,n.url);c.open(n.method.toUpperCase(),ii(h,n.params,n.paramsSerializer),!0),c.timeout=n.timeout;function g(){if(!c)return;const p=Ne.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),A={data:!o||o==="text"||o==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:p,config:n,request:c};Ba(function(C){t(C),u()},function(C){r(C),u()},A),c=null}if("onloadend"in c?c.onloadend=g:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(g)},c.onabort=function(){c&&(r(new j("Request aborted",j.ECONNABORTED,n,c)),c=null)},c.onerror=function(){r(new j("Network Error",j.ERR_NETWORK,n,c)),c=null},c.ontimeout=function(){let m=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const A=n.transitional||oi;n.timeoutErrorMessage&&(m=n.timeoutErrorMessage),r(new j(m,A.clarifyTimeoutError?j.ETIMEDOUT:j.ECONNABORTED,n,c)),c=null},Ee.hasStandardBrowserEnv&&(a&&y.isFunction(a)&&(a=a(n)),a||a!==!1&&Wa(h))){const p=n.xsrfHeaderName&&n.xsrfCookieName&&Ua.read(n.xsrfCookieName);p&&i.set(n.xsrfHeaderName,p)}s===void 0&&i.setContentType(null),"setRequestHeader"in c&&y.forEach(i.toJSON(),function(m,A){c.setRequestHeader(A,m)}),y.isUndefined(n.withCredentials)||(c.withCredentials=!!n.withCredentials),o&&o!=="json"&&(c.responseType=n.responseType),typeof n.onDownloadProgress=="function"&&c.addEventListener("progress",is(n.onDownloadProgress,!0)),typeof n.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",is(n.onUploadProgress)),(n.cancelToken||n.signal)&&(l=p=>{c&&(r(!p||p.type?new Lt(null,n,c):p),c.abort(),c=null)},n.cancelToken&&n.cancelToken.subscribe(l),n.signal&&(n.signal.aborted?l():n.signal.addEventListener("abort",l)));const f=Ga(h);if(f&&Ee.protocols.indexOf(f)===-1){r(new j("Unsupported protocol "+f+":",j.ERR_BAD_REQUEST,n));return}c.send(s||null)})},ir={http:ga,xhr:Xa};y.forEach(ir,(n,e)=>{if(n){try{Object.defineProperty(n,"name",{value:e})}catch{}Object.defineProperty(n,"adapterName",{value:e})}});const os=n=>`- ${n}`,Ka=n=>y.isFunction(n)||n===null||n===!1,fi={getAdapter:n=>{n=y.isArray(n)?n:[n];const{length:e}=n;let t,r;const s={};for(let i=0;i`adapter ${a} `+(l===!1?"is not supported by the environment":"is not available in the build"));let o=e?i.length>1?`since : +`+i.map(os).join(` +`):" "+os(i[0]):"as no adapter specified";throw new j("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return r},adapters:ir};function Jn(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new Lt(null,n)}function as(n){return Jn(n),n.headers=Ne.from(n.headers),n.data=Gn.call(n,n.transformRequest),["post","put","patch"].indexOf(n.method)!==-1&&n.headers.setContentType("application/x-www-form-urlencoded",!1),fi.getAdapter(n.adapter||Mr.adapter)(n).then(function(r){return Jn(n),r.data=Gn.call(n,n.transformResponse,r),r.headers=Ne.from(r.headers),r},function(r){return ci(r)||(Jn(n),r&&r.response&&(r.response.data=Gn.call(n,n.transformResponse,r.response),r.response.headers=Ne.from(r.response.headers))),Promise.reject(r)})}const ls=n=>n instanceof Ne?{...n}:n;function ct(n,e){e=e||{};const t={};function r(u,d,c){return y.isPlainObject(u)&&y.isPlainObject(d)?y.merge.call({caseless:c},u,d):y.isPlainObject(d)?y.merge({},d):y.isArray(d)?d.slice():d}function s(u,d,c){if(y.isUndefined(d)){if(!y.isUndefined(u))return r(void 0,u,c)}else return r(u,d,c)}function i(u,d){if(!y.isUndefined(d))return r(void 0,d)}function o(u,d){if(y.isUndefined(d)){if(!y.isUndefined(u))return r(void 0,u)}else return r(void 0,d)}function a(u,d,c){if(c in e)return r(u,d);if(c in n)return r(void 0,u)}const l={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(u,d)=>s(ls(u),ls(d),!0)};return y.forEach(Object.keys(Object.assign({},n,e)),function(d){const c=l[d]||s,h=c(n[d],e[d],d);y.isUndefined(h)&&c!==a||(t[d]=h)}),t}const di="1.6.8",xr={};["object","boolean","number","function","string","symbol"].forEach((n,e)=>{xr[n]=function(r){return typeof r===n||"a"+(e<1?"n ":" ")+n}});const cs={};xr.transitional=function(e,t,r){function s(i,o){return"[Axios v"+di+"] Transitional option '"+i+"'"+o+(r?". "+r:"")}return(i,o,a)=>{if(e===!1)throw new j(s(o," has been removed"+(t?" in "+t:"")),j.ERR_DEPRECATED);return t&&!cs[o]&&(cs[o]=!0,console.warn(s(o," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(i,o,a):!0}};function Va(n,e,t){if(typeof n!="object")throw new j("options must be an object",j.ERR_BAD_OPTION_VALUE);const r=Object.keys(n);let s=r.length;for(;s-- >0;){const i=r[s],o=e[i];if(o){const a=n[i],l=a===void 0||o(a,i,n);if(l!==!0)throw new j("option "+i+" must be "+l,j.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new j("Unknown option "+i,j.ERR_BAD_OPTION)}}const or={assertOptions:Va,validators:xr},je=or.validators;class sn{constructor(e){this.defaults=e,this.interceptors={request:new rs,response:new rs}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const i=s.stack?s.stack.replace(/^.+\n/,""):"";r.stack?i&&!String(r.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+i):r.stack=i}throw r}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=ct(this.defaults,t);const{transitional:r,paramsSerializer:s,headers:i}=t;r!==void 0&&or.assertOptions(r,{silentJSONParsing:je.transitional(je.boolean),forcedJSONParsing:je.transitional(je.boolean),clarifyTimeoutError:je.transitional(je.boolean)},!1),s!=null&&(y.isFunction(s)?t.paramsSerializer={serialize:s}:or.assertOptions(s,{encode:je.function,serialize:je.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=i&&y.merge(i.common,i[t.method]);i&&y.forEach(["delete","get","head","post","put","patch","common"],f=>{delete i[f]}),t.headers=Ne.concat(o,i);const a=[];let l=!0;this.interceptors.request.forEach(function(p){typeof p.runWhen=="function"&&p.runWhen(t)===!1||(l=l&&p.synchronous,a.unshift(p.fulfilled,p.rejected))});const u=[];this.interceptors.response.forEach(function(p){u.push(p.fulfilled,p.rejected)});let d,c=0,h;if(!l){const f=[as.bind(this),void 0];for(f.unshift.apply(f,a),f.push.apply(f,u),h=f.length,d=Promise.resolve(t);c{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](s);r._listeners=null}),this.promise.then=s=>{let i;const o=new Promise(a=>{r.subscribe(a),i=a}).then(s);return o.cancel=function(){r.unsubscribe(i)},o},e(function(i,o,a){r.reason||(r.reason=new Lt(i,o,a),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}static source(){let e;return{token:new Tr(function(s){e=s}),cancel:e}}}const Qa=Tr;function Ya(n){return function(t){return n.apply(null,t)}}function Za(n){return y.isObject(n)&&n.isAxiosError===!0}const ar={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ar).forEach(([n,e])=>{ar[e]=n});const $a=ar;function hi(n){const e=new Ht(n),t=Xs(Ht.prototype.request,e);return y.extend(t,Ht.prototype,e,{allOwnKeys:!0}),y.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return hi(ct(n,s))},t}const Q=hi(Mr);Q.Axios=Ht;Q.CanceledError=Lt;Q.CancelToken=Qa;Q.isCancel=ci;Q.VERSION=di;Q.toFormData=Dn;Q.AxiosError=j;Q.Cancel=Q.CanceledError;Q.all=function(e){return Promise.all(e)};Q.spread=Ya;Q.isAxiosError=Za;Q.mergeConfig=ct;Q.AxiosHeaders=Ne;Q.formToJSON=n=>li(y.isHTMLForm(n)?new FormData(n):n);Q.getAdapter=fi.getAdapter;Q.HttpStatusCode=$a;Q.default=Q;const el=Q;async function zn(n){var t,r,s;return n?(s=(r=(t=(await sl("markdown","",n))[0])==null?void 0:t.doOperations)==null?void 0:r[0])==null?void 0:s.id:""}function tl(n){return[/( \{:.*?\})\n/gm,/{:.*?\}/gm,/^ +(?=[\d\*])/gm].forEach(t=>{n=n.replace(t,"")}),n}async function nl(n){let e=[];for(let t of n){if(!t||!t.className.includes("select"))continue;let r=await il(t.dataset.nodeId);e.push(tl(r.kramdown))}return e.join(` +`)}async function rl(n,e,t){e=e.endsWith(".png")?e:`${e}.png`;const r=`/data/assets/${t}/text2img/${e}`,s=Buffer.from(n,"base64");let i=new File([new Blob([s])],r.split("/").pop());const o=new FormData;return o.append("path",r),o.append("file",i),o.append("isDir","false"),de.fetchPost("/api/file/putFile",o,()=>{}),r}async function us(n){var r;if(!n||n.length==0)return[0,0];const e={method:"POST",url:"https://fastapi.geeksphere.online/aigc/token",headers:{"content-type":"application/json"},data:{auth:"pUMsVhaMDHXiuTMs03852b8a786a491",key:n.replace("sk-",""),base_url:"https://oneapi.geeksphere.online/v1"}};let t=await el.request(e);return!((r=t==null?void 0:t.data)!=null&&r.resultcode)||t.data.resultcode!=200?[0,0]:t.data.data}async function Nt(n,e){let t=await de.fetchSyncPost(n,e);return t.code===0?t.data:null}async function sl(n,e,t){return Nt("/api/block/appendBlock",{dataType:n,data:e,parentID:t})}async function Xn(n,e,t){return Nt("/api/block/updateBlock",{dataType:n,data:e,id:t})}async function il(n){return Nt("/api/block/getBlockKramdown",{id:n})}async function Ue(n,e=7e3){return Nt("/api/notification/pushMsg",{msg:n,timeout:e})}async function He(n,e=7e3){return Nt("/api/notification/pushErrMsg",{msg:n,timeout:e})}class ol{constructor(){V(this,"_data");this._data=new Map}set data(e){this._data=e}get data(){return this._data}set(e,t){return this._data.set(e,t),!0}get(e,t){return this._data.get(e)??t}hasKey(e){return this._data.has(e)}remove(e){return this._data.delete(e)}values(){return Array.from(this._data.values())}keys(){return Array.from(this._data.keys())}keyValues(){return Array.from(this._data.entries())}forEach(e){const t=this.keyValues();for(let r=0;r{let r=JSON.parse(t);this.set(r.key,JSON.parse(r.value))}),this._data}}class pi extends ol{constructor(t,r){super();V(this,"_plugin");V(this,"_file");this._plugin=t,this._file=r.endsWith(".json")?r:`${r}.json`}load(){this._plugin.loadData(this._file).then(t=>{t?this.deserializedString(t):this.save()})}save(t){this._plugin.saveData(this._file,this.serializedToString()).then(()=>{t&&(this._file.includes("setting")&&Ue("AI插件设置已保存"),this._file.includes("prompt")&&Ue("prompt设置已保存"))})}async removeData(){await this._plugin.removeData(this._file)}}class al extends pi{constructor(e,t){super(e,t),this._defaultData()}onload(){this.load()}_defaultData(){this.set("翻译、拼写纠正、改进",{model:"gpt-3.5-turbo",temperature:.3,title:"翻译、拼写纠正、改进",prompt:"请对以下内容进行翻译。要求:我希望你用更优美优雅的高级英语单词和句子替换我简化的 A0 级单词和句子。保持相同的意思,但使它们更文艺。你只需要翻译该内容,不必对内容中提出的问题和要求做解释,不要回答文本中的问题而是翻译它。",isStar:!1}),this.set("自动提取标题",{model:"gpt-3.5-turbo",temperature:.3,title:"自动提取标题",prompt:"请为上面这篇文章生成简洁且完整概括的标题。",isStar:!1}),this.set("自动提取摘要",{model:"gpt-3.5-turbo",temperature:.3,title:"自动提取摘要",prompt:"请为上面这篇文章生成简明扼要的摘要。",isStar:!1}),this.set("自动提取标签",{model:"gpt-3.5-turbo",temperature:.3,title:"自动提取标签",prompt:"请为上面这篇文章生成标签,单个标签不超过6个字符,多个标签用英文逗号分隔,最多返回5个标签。",isStar:!1})}async deleteStorageFile(){await super.removeData(),await He("删除:prompt文件...")}}class ll extends pi{constructor(e,t){super(e,t),this._defaultData()}onload(){this.load()}_defaultData(){this.set(M.SERVICE_PROVIDER,{group:"🌈 设置",key:M.SERVICE_PROVIDER,value:"OpenAI",type:le.select,title:"AI服务提供商",description:"选择后将使用该提供商的 API 服务实现 AI 相关功能",options:{OpenAI:"OpenAI"}}),this.set(M.API_KEY,{group:"🌈 设置",key:M.API_KEY,value:"",placeholder:"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",type:le.textinput,title:"API Key",description:"请求大模型服务的密钥."}),this.set(M.TIMEOUT,{group:"🌈 设置",key:M.TIMEOUT,value:90,type:le.textinput,title:"AI请求超时时间",description:"发起请求的超时时间,单位:秒"}),this.set(M.BASE_URL,{group:"🌈 设置",key:M.BASE_URL,value:"https://oneapi.geeksphere.online/v1",type:le.textinput,title:"API 基础地址",description:"发起请求的基础地址"}),this.set(M.STREAM,{group:"🌈 设置",key:M.STREAM,value:!1,type:le.switch,title:"是否开启流式输出",description:"逐字生成回复内容"}),this.set(M.PROMPT,{group:"📃 文本生成",key:M.PROMPT,value:"",type:le.textarea,title:"prompt",description:"prompt的内容,用于指示生成内容",placeholder:"请输入prompt,比如:请将以下文本翻译成英文"}),this.set(M.MODEL,{group:"📃 文本生成",key:M.MODEL,value:"gpt-3.5-turbo-0125",type:le.select,title:"模型",description:"选择文本生成模型模型",options:{"gpt-3.5-turbo-0125":"gpt-3.5-turbo-0125","gpt-4-turbo-2024-04-09":"gpt-4-turbo-2024-04-09","gpt-4-0125-preview":"gpt-4-0125-preview","gpt-3.5-turbo":"gpt-3.5-turbo","gpt-3.5-turbo-0301":"gpt-3.5-turbo-0301","gpt-3.5-turbo-0613":"gpt-3.5-turbo-0613","gpt-3.5-turbo-16k":"gpt-3.5-turbo-16k","gpt-3.5-turbo-16k-0613":"gpt-3.5-turbo-16k-0613","gpt-4":"gpt-4","gpt-4-0314":"gpt-4-0314","gpt-4-0613":"gpt-4-0613","gpt-4-1106-preview":"gpt-4-1106-preview","gpt-4-32k":"gpt-4-32k","gpt-4-32k-0314":"gpt-4-32k-0314","gpt-4-32k-0613":"gpt-4-32k-0613","gpt-4-turbo":"gpt-4-turbo","gpt-4-turbo-preview":"gpt-4-turbo-preview"}}),this.set(M.TEMPERATURE,{group:"📃 文本生成",key:M.TEMPERATURE,value:.3,type:le.slider,title:"温度值",description:"温度值越小,模型生成的内容越准确。温度值越高,模型生成内容越多样",slider:{min:0,max:1,step:.1}}),this.set(M.IMG_PROMPT,{group:"🏞️ 文生图",key:M.IMG_PROMPT,value:"",type:le.textarea,title:"prompt",description:"prompt的内容,用于指示生成内容",placeholder:"请输入prompt,比如:一只白色暹罗猫"}),this.set(M.IMG_MODEL,{group:"🏞️ 文生图",key:M.IMG_MODEL,value:"dall-e-3",type:le.select,title:"图片生成模型",description:"请选择图片生成模型",options:{"dall-e-3":"DALL·E 3","dall-e-2":"DALL·E 2"}}),this.set(M.IMG_NUM,{group:"🏞️ 文生图",key:M.IMG_NUM,value:"1",type:le.number,title:"生成图片数量",description:"生成图片数量"}),this.set(M.IMG_QUALITY,{group:"🏞️ 文生图",key:M.IMG_QUALITY,value:"standard",type:le.select,title:"图片质量",description:"生成的图像的质量,hd会生成更细致的图像。",options:{standard:"standard",hd:"hd"}}),this.set(M.IMG_SIZE,{group:"🏞️ 文生图",key:M.IMG_SIZE,value:"1024x1024",type:le.select,title:"图片大小",description:"生成图片大小",options:{"1024x1024":"1024x1024","1024x1792":"1024x1792","1792x1024":"1792x1024","512x512":"512x512","256x256":"256x256"}})}async deleteStorageFile(){await super.removeData(),await He("删除:设置文件...")}}function cl(n){let e,t,r;return{c(){e=I("strong"),e.textContent="注意:",t=U(),r=I("p"),r.textContent="为了修复文生图bug,请大家先主动卸载插件,再重新在插件市场安装。不然文本生成面板会出现不显示的bug。"},m(s,i){J(s,e,i),J(s,t,i),J(s,r,i)},p:G,i:G,o:G,d(s){s&&H(e),s&&H(t),s&&H(r)}}}class ul extends xe{constructor(e){super(),Me(this,e,null,cl,Oe,{})}}function fl(n){let e,t,r="余额查询",s,i,o,a,l,u,d,c,h,g,f,p,m;return{c(){e=I("label"),t=I("div"),s=se(r),i=U(),o=I("div"),a=se("账 户 余 额 : "),l=se(n[1]),u=se(` ¥ + `),d=I("br"),c=se(` + Token余额 : `),h=se(n[2]),g=U(),f=I("button"),f.textContent="刷新",k(o,"class","b3-label__text"),k(t,"class","fn__flex-1"),k(f,"class","b3-button b3-button--outline fn__flex-center fn__size200"),k(e,"class","fn__flex b3-label")},m(A,P){J(A,e,P),O(e,t),O(t,s),O(t,i),O(t,o),O(o,a),O(o,l),O(o,u),O(o,d),O(o,c),O(o,h),O(e,g),O(e,f),p||(m=z(f,"click",n[3]),p=!0)},p(A,[P]){P&2&&qe(l,A[1]),P&4&&qe(h,A[2])},i:G,o:G,d(A){A&&H(e),p=!1,m()}}}function dl(n,e,t){let{apiKey:r}=e,s=0,i=0;so(()=>{us(r).then(a=>{t(2,i=a[0]),t(1,s=a[1])})});const o=async()=>{us(r).then(a=>{t(2,i=a[0]),t(1,s=a[1])})};return n.$$set=a=>{"apiKey"in a&&t(0,r=a.apiKey)},[r,s,i,o]}class hl extends xe{constructor(e){super(),Me(this,e,dl,fl,Oe,{apiKey:0})}}function fs(n,e,t){const r=n.slice();return r[12]=e[t],r}function ds(n,e,t){const r=n.slice();return r[15]=e[t],r}function hs(n){let e,t,r=n[15]+"",s,i,o,a;function l(){return n[8](n[15])}return{c(){e=I("li"),t=I("span"),s=se(r),i=U(),k(t,"class","b3-list-item__text"),k(e,"data-name","editor"),k(e,"class","b3-list-item svelte-1fh5pey"),Vr(e,"b3-list-item--focus",n[15]===n[2])},m(u,d){J(u,e,d),O(e,t),O(t,s),O(e,i),o||(a=[z(e,"click",l),z(e,"keydown",_l)],o=!0)},p(u,d){n=u,d&12&&Vr(e,"b3-list-item--focus",n[15]===n[2])},d(u){u&&H(e),o=!1,ie(a)}}}function pl(n){var r,s,i;let e,t;return e=new Cr({props:{type:n[12].type,title:n[12].title,description:n[12].description,settingKey:n[12].key,settingValue:n[12].value,placeholder:(r=n[12])==null?void 0:r.placeholder,options:(s=n[12])==null?void 0:s.options,slider:(i=n[12])==null?void 0:i.slider}}),e.$on("changed",n[9]),{c(){re(e.$$.fragment)},m(o,a){$(e,o,a),t=!0},p:G,i(o){t||(q(e.$$.fragment,o),t=!0)},o(o){W(e.$$.fragment,o),t=!1},d(o){ee(e,o)}}}function ps(n,e){let t,r,s,i=e[12].group==e[3][0]&&pl(e);return{key:n,first:null,c(){t=at(),i&&i.c(),r=at(),this.first=t},m(o,a){J(o,t,a),i&&i.m(o,a),J(o,r,a),s=!0},p(o,a){e=o,e[12].group==e[3][0]&&i.p(e,a)},i(o){s||(q(i),s=!0)},o(o){W(i),s=!1},d(o){o&&H(t),i&&i.d(o),o&&H(r)}}}function ml(n){let e,t,r,s,i,o,a=[],l=new Map,u,d,c,h,g,f,p,m,A,P,C,E,b,_,S,R,w=n[3],L=[];for(let x=0;xx[12].key;for(let x=0;x{};function gl(n,e,t){let{$$slots:r={},$$scope:s}=e,{storageSettings:i}=e,{dialog:o=null}=e,a=["🌈 设置","💡 公告"],l=a[0],u=i.get(M.API_KEY).value,d=[];i.data.forEach(p=>{d.push(p)});const c=p=>{t(2,l=p)},h=({detail:p})=>{let m=i.get(p.key);m.value=p.value,i.set(p.key,m)},g=()=>{i.load(),o.destroy()},f=()=>{i.save(!0),o.destroy()};return n.$$set=p=>{"storageSettings"in p&&t(0,i=p.storageSettings),"dialog"in p&&t(1,o=p.dialog),"$$scope"in p&&t(6,s=p.$$scope)},[i,o,l,a,u,d,s,r,c,h,g,f]}class yl extends xe{constructor(e){super(),Me(this,e,gl,ml,Oe,{storageSettings:0,dialog:1})}}const Ze="4.33.1";let ms=!1,Pt,mi,_i,lr,gi,yi,bi,wi,Si;function bl(n,e={auto:!1}){if(ms)throw new Error(`you must \`import 'openai/shims/${n.kind}'\` before importing anything else from openai`);if(Pt)throw new Error(`can't \`import 'openai/shims/${n.kind}'\` after \`import 'openai/shims/${Pt}'\``);ms=e.auto,Pt=n.kind,mi=n.fetch,n.Request,n.Response,n.Headers,_i=n.FormData,n.Blob,lr=n.File,gi=n.ReadableStream,yi=n.getMultipartRequestOptions,bi=n.getDefaultAgent,wi=n.fileFromPath,Si=n.isFsReadStream}class wl{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function Sl({manuallyImported:n}={}){const e=n?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let t,r,s,i;try{t=fetch,r=Request,s=Response,i=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${e}`)}return{kind:"web",fetch:t,Request:r,Response:s,Headers:i,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(o,a)=>({...a,body:new wl(o)}),getDefaultAgent:o=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:o=>!1}}Pt||bl(Sl(),{auto:!0});class B extends Error{}class te extends B{constructor(e,t,r,s){super(`${te.makeMessage(e,t,r)}`),this.status=e,this.headers=s;const i=t;this.error=i,this.code=i==null?void 0:i.code,this.param=i==null?void 0:i.param,this.type=i==null?void 0:i.type}static makeMessage(e,t,r){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e)return new Bn({cause:ur(t)});const i=t==null?void 0:t.error;return e===400?new Ai(e,i,r,s):e===401?new Ei(e,i,r,s):e===403?new Pi(e,i,r,s):e===404?new Ci(e,i,r,s):e===409?new ki(e,i,r,s):e===422?new Ri(e,i,r,s):e===429?new Oi(e,i,r,s):e>=500?new Mi(e,i,r,s):new te(e,i,r,s)}}class he extends te{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class Bn extends te{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class vr extends Bn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ai extends te{constructor(){super(...arguments),this.status=400}}class Ei extends te{constructor(){super(...arguments),this.status=401}}class Pi extends te{constructor(){super(...arguments),this.status=403}}class Ci extends te{constructor(){super(...arguments),this.status=404}}class ki extends te{constructor(){super(...arguments),this.status=409}}class Ri extends te{constructor(){super(...arguments),this.status=422}}class Oi extends te{constructor(){super(...arguments),this.status=429}}class Mi extends te{}class Pe{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*s(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let i=!1;try{for await(const o of Al(e,t))if(!i){if(o.data.startsWith("[DONE]")){i=!0;continue}if(o.event===null){let a;try{a=JSON.parse(o.data)}catch(l){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),l}if(a&&a.error)throw new te(void 0,a.error,void 0,void 0);yield a}else{let a;try{a=JSON.parse(o.data)}catch(l){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),l}if(o.event=="error")throw new te(void 0,a.error,a.message,void 0);yield{event:o.event,data:a}}}i=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{i||t.abort()}}return new Pe(s,t)}static fromReadableStream(e,t){let r=!1;async function*s(){const o=new Xe,a=xi(e);for await(const l of a)for(const u of o.decode(l))yield u;for(const l of o.flush())yield l}async function*i(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const a of s())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new Pe(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),s=i=>({next:()=>{if(i.length===0){const o=r.next();e.push(o),t.push(o)}return i.shift()}});return[new Pe(()=>s(e),this.controller),new Pe(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const r=new TextEncoder;return new gi({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:i,done:o}=await t.next();if(o)return s.close();const a=r.encode(JSON.stringify(i)+` +`);s.enqueue(a)}catch(i){s.error(i)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*Al(n,e){if(!n.body)throw e.abort(),new B("Attempted to iterate over a response with no body");const t=new Cl,r=new Xe,s=xi(n.body);for await(const i of El(s))for(const o of r.decode(i)){const a=t.decode(o);a&&(yield a)}for(const i of r.flush()){const o=t.decode(i);o&&(yield o)}}async function*El(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let i;for(;(i=Pl(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Pl(n){for(let r=0;r0&&(s=[this.buffer.join("")+s[0],...s.slice(1)],this.buffer=[]),r||(this.buffer=[s.pop()||""]),s)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new B(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new B(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new B("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}Xe.NEWLINE_CHARS=new Set([` +`,"\r"]);Xe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function kl(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}function xi(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const Ti=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function",vi=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Ii(n),Ii=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Rl=n=>vi(n)||Ti(n)||Si(n);async function Li(n,e,t){var s;if(n=await n,t??(t=vi(n)?{lastModified:n.lastModified,type:n.type}:{}),Ti(n)){const i=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new lr([i],e,t)}const r=await Ol(n);if(e||(e=xl(n)??"unknown_file"),!t.type){const i=(s=r[0])==null?void 0:s.type;typeof i=="string"&&(t={...t,type:i})}return new lr(r,e,t)}async function Ol(n){var t;let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(Ii(n))e.push(await n.arrayBuffer());else if(Tl(n))for await(const r of n)e.push(r);else throw new Error(`Unexpected data type: ${typeof n}; constructor: ${(t=n==null?void 0:n.constructor)==null?void 0:t.name}; props: ${Ml(n)}`);return e}function Ml(n){return`[${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}function xl(n){var e;return Kn(n.name)||Kn(n.filename)||((e=Kn(n.path))==null?void 0:e.split(/[\\/]/).pop())}const Kn=n=>{if(typeof n=="string")return n;if(typeof Buffer<"u"&&n instanceof Buffer)return String(n)},Tl=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",_s=n=>n&&typeof n=="object"&&n.body&&n[Symbol.toStringTag]==="MultipartBody",Ot=async n=>{const e=await vl(n.body);return yi(e,n)},vl=async n=>{const e=new _i;return await Promise.all(Object.entries(n||{}).map(([t,r])=>cr(e,t,r))),e},cr=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(Rl(t)){const r=await Li(t);n.append(e,r)}else if(Array.isArray(t))await Promise.all(t.map(r=>cr(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>cr(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Il=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},Ll=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},Ft;async function Ni(n){const{response:e}=n;if(n.options.stream)return rt("response",e.status,e.url,e.headers,e.body),n.options.__streamClass?n.options.__streamClass.fromSSEResponse(e,n.controller):Pe.fromSSEResponse(e,n.controller);if(e.status===204)return null;if(n.options.__binaryResponse)return e;const t=e.headers.get("content-type");if((t==null?void 0:t.includes("application/json"))||(t==null?void 0:t.includes("application/vnd.api+json"))){const i=await e.json();return rt("response",e.status,e.url,e.headers,i),i}const s=await e.text();return rt("response",e.status,e.url,e.headers,s),s}class Un extends Promise{constructor(e,t=Ni){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new Un(this.responsePromise,async t=>e(await this.parseResponse(t)))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class Nl{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:s,fetch:i}){this.baseURL=e,this.maxRetries=Vn("maxRetries",t),this.timeout=Vn("timeout",r),this.httpAgent=s,this.fetch=i??mi}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...ql(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Jl()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}return null}buildRequest(e){var f;const{method:t,path:r,query:s,headers:i={}}=e,o=_s(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,a=this.calculateContentLength(o),l=this.buildURL(r,s);"timeout"in e&&Vn("timeout",e.timeout);const u=e.timeout??this.timeout,d=e.httpAgent??this.httpAgent??bi(l),c=u+1e3;typeof((f=d==null?void 0:d.options)==null?void 0:f.timeout)=="number"&&c>(d.options.timeout??0)&&(d.options.timeout=c),this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const h=this.buildHeaders({options:e,headers:i,contentLength:a});return{req:{method:t,...o&&{body:o},headers:h,...d&&{agent:d},signal:e.signal??null},url:l,timeout:u}}buildHeaders({options:e,headers:t,contentLength:r}){const s={};r&&(s["content-length"]=r);const i=this.defaultHeaders(e);return ws(s,i),ws(s,t),_s(e.body)&&Pt!=="node"&&delete s["content-type"],this.validateHeaders(s,t),s}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,r,s){return te.generate(e,t,r,s)}request(e,t=null){return new Un(this.makeRequest(e,t))}async makeRequest(e,t){var d,c;const r=await e;t==null&&(t=r.maxRetries??this.maxRetries),await this.prepareOptions(r);const{req:s,url:i,timeout:o}=this.buildRequest(r);if(await this.prepareRequest(s,{url:i,options:r}),rt("request",i,r,s.headers),(d=r.signal)!=null&&d.aborted)throw new he;const a=new AbortController,l=await this.fetchWithTimeout(i,s,o,a).catch(ur);if(l instanceof Error){if((c=r.signal)!=null&&c.aborted)throw new he;if(t)return this.retryRequest(r,t);throw l.name==="AbortError"?new vr:new Bn({cause:l})}const u=Dl(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){const A=`retrying, ${t} attempts remaining`;return rt(`response (error; ${A})`,l.status,i,u),this.retryRequest(r,t,u)}const h=await l.text().catch(A=>ur(A).message),g=Hl(h),f=g?void 0:h;throw rt(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,i,u,f),this.makeStatusError(l.status,g,f,u)}return{response:l,options:r,controller:a}}requestAPIList(e,t){const r=this.makeRequest(t,null);return new Fl(this,r,e)}buildURL(e,t){const r=Gl(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Di(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new B(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,r,s){const{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>s.abort());const a=setTimeout(()=>s.abort(),r);return this.getRequestClient().fetch.call(void 0,e,{signal:s.signal,...o}).finally(()=>{clearTimeout(a)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r){let s;const i=r==null?void 0:r["retry-after-ms"];if(i){const a=parseFloat(i);Number.isNaN(a)||(s=a)}const o=r==null?void 0:r["retry-after"];if(o&&!s){const a=parseFloat(o);Number.isNaN(a)?s=Date.parse(o)-Date.now():s=a*1e3}if(!(s&&0<=s&&s<60*1e3)){const a=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,a)}return await Ir(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Ze}`}}class Fi{constructor(e,t,r,s){Ft.set(this,void 0),Il(this,Ft,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new B("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){const r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[s,i]of r)e.url.searchParams.set(s,i);t.query=void 0,t.path=e.url.toString()}return await Ll(this,Ft,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ft=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Fl extends Un{constructor(e,t,r){super(t,async s=>new r(e,s.response,await Ni(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const Dl=n=>new Proxy(Object.fromEntries(n.entries()),{get(e,t){const r=t.toString();return e[r.toLowerCase()]||e[r]}}),jl={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryResponse:!0,__streamClass:!0},Re=n=>typeof n=="object"&&n!==null&&!Di(n)&&Object.keys(n).every(e=>ji(jl,e)),Bl=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ze,"X-Stainless-OS":ys(Deno.build.os),"X-Stainless-Arch":gs(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((e=Deno.version)==null?void 0:e.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ze,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ze,"X-Stainless-OS":ys(process.platform),"X-Stainless-Arch":gs(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const n=Ul();return n?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ze,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${n.browser}`,"X-Stainless-Runtime-Version":n.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ze,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ul(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const r=t.exec(navigator.userAgent);if(r){const s=r[1]||0,i=r[2]||0,o=r[3]||0;return{browser:e,version:`${s}.${i}.${o}`}}}return null}const gs=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",ys=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let bs;const ql=()=>bs??(bs=Bl()),Hl=n=>{try{return JSON.parse(n)}catch{return}},Wl=new RegExp("^(?:[a-z]+:)?//","i"),Gl=n=>Wl.test(n),Ir=n=>new Promise(e=>setTimeout(e,n)),Vn=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new B(`${n} must be an integer`);if(e<0)throw new B(`${n} must be a positive integer`);return e},ur=n=>n instanceof Error?n:new Error(n),Qn=n=>{var e,t,r,s,i;if(typeof process<"u")return((t=(e=process.env)==null?void 0:e[n])==null?void 0:t.trim())??void 0;if(typeof Deno<"u")return(i=(s=(r=Deno.env)==null?void 0:r.get)==null?void 0:s.call(r,n))==null?void 0:i.trim()};function Di(n){if(!n)return!0;for(const e in n)return!1;return!0}function ji(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function ws(n,e){for(const t in e){if(!ji(e,t))continue;const r=t.toLowerCase();if(!r)continue;const s=e[t];s===null?delete n[r]:s!==void 0&&(n[r]=s)}}function rt(n,...e){var t;typeof process<"u"&&((t=process==null?void 0:process.env)==null?void 0:t.DEBUG)==="true"&&console.log(`OpenAI:DEBUG:${n}`,...e)}const Jl=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)}),zl=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Ss(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}class Lr extends Fi{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class Fe extends Fi{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){var r;const e=this.getPaginatedItems();if(!e.length)return null;const t=(r=e[e.length-1])==null?void 0:r.id;return t?{params:{after:t}}:null}}class X{constructor(e){this._client=e}}let on=class extends X{create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}};on||(on={});let an=class extends X{constructor(){super(...arguments),this.completions=new on(this._client)}};(function(n){n.Completions=on})(an||(an={}));class ln extends X{create(e,t){return this._client.post("/audio/speech",{body:e,...t,__binaryResponse:!0})}}ln||(ln={});class cn extends X{create(e,t){return this._client.post("/audio/transcriptions",Ot({body:e,...t}))}}cn||(cn={});class un extends X{create(e,t){return this._client.post("/audio/translations",Ot({body:e,...t}))}}un||(un={});class fn extends X{constructor(){super(...arguments),this.transcriptions=new cn(this._client),this.translations=new un(this._client),this.speech=new ln(this._client)}}(function(n){n.Transcriptions=cn,n.Translations=un,n.Speech=ln})(fn||(fn={}));let dn=class extends X{create(e,t,r){return this._client.post(`/assistants/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}retrieve(e,t,r){return this._client.get(`/assistants/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(e,t={},r){return Re(t)?this.list(e,{},t):this._client.getAPIList(`/assistants/${e}/files`,Nr,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}del(e,t,r){return this._client.delete(`/assistants/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}};class Nr extends Fe{}(function(n){n.AssistantFilesPage=Nr})(dn||(dn={}));class hn extends X{constructor(){super(...arguments),this.files=new dn(this._client)}create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}update(e,t,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(e={},t){return Re(e)?this.list({},e):this._client.getAPIList("/assistants",Fr,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}}class Fr extends Fe{}(function(n){n.AssistantsPage=Fr,n.Files=dn,n.AssistantFilesPage=Nr})(hn||(hn={}));function As(n){return typeof n.parse=="function"}const st=n=>(n==null?void 0:n.role)==="assistant",Bi=n=>(n==null?void 0:n.role)==="function",Ui=n=>(n==null?void 0:n.role)==="tool";var me=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},F=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},ne,Wt,Gt,ht,pt,Jt,mt,ve,_t,zt,Xt,$e,fr,pn,dr,hr,pr,mr,qi,_r;const Es=10;class Hi{constructor(){ne.add(this),this.controller=new AbortController,Wt.set(this,void 0),Gt.set(this,()=>{}),ht.set(this,()=>{}),pt.set(this,void 0),Jt.set(this,()=>{}),mt.set(this,()=>{}),ve.set(this,{}),this._chatCompletions=[],this.messages=[],_t.set(this,!1),zt.set(this,!1),Xt.set(this,!1),$e.set(this,!1),mr.set(this,e=>{if(me(this,zt,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new he),e instanceof he)return me(this,Xt,!0,"f"),this._emit("abort",e);if(e instanceof B)return this._emit("error",e);if(e instanceof Error){const t=new B(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new B(String(e)))}),me(this,Wt,new Promise((e,t)=>{me(this,Gt,e,"f"),me(this,ht,t,"f")}),"f"),me(this,pt,new Promise((e,t)=>{me(this,Jt,e,"f"),me(this,mt,t,"f")}),"f"),F(this,Wt,"f").catch(()=>{}),F(this,pt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},F(this,mr,"f"))},0)}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(r=e.choices[0])==null?void 0:r.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(Bi(e)||Ui(e))&&e.content)this._emit("functionCallResult",e.content);else if(st(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(st(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionCall",r.function)}}_connected(){this.ended||(F(this,Gt,"f").call(this),this._emit("connect"))}get ended(){return F(this,_t,"f")}get errored(){return F(this,zt,"f")}get aborted(){return F(this,Xt,"f")}abort(){this.controller.abort()}on(e,t){return(F(this,ve,"f")[e]||(F(this,ve,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=F(this,ve,"f")[e];if(!r)return this;const s=r.findIndex(i=>i.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(F(this,ve,"f")[e]||(F(this,ve,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{me(this,$e,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){me(this,$e,!0,"f"),await F(this,pt,"f")}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new B("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),F(this,ne,"m",fr).call(this)}async finalMessage(){return await this.done(),F(this,ne,"m",pn).call(this)}async finalFunctionCall(){return await this.done(),F(this,ne,"m",dr).call(this)}async finalFunctionCallResult(){return await this.done(),F(this,ne,"m",hr).call(this)}async totalUsage(){return await this.done(),F(this,ne,"m",pr).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emit(e,...t){if(F(this,_t,"f"))return;e==="end"&&(me(this,_t,!0,"f"),F(this,Jt,"f").call(this));const r=F(this,ve,"f")[e];if(r&&(F(this,ve,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!F(this,$e,"f")&&!(r!=null&&r.length)&&Promise.reject(s),F(this,ht,"f").call(this,s),F(this,mt,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!F(this,$e,"f")&&!(r!=null&&r.length)&&Promise.reject(s),F(this,ht,"f").call(this,s),F(this,mt,"f").call(this,s),this._emit("end")}}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=F(this,ne,"m",pn).call(this);t&&this._emit("finalMessage",t);const r=F(this,ne,"m",fr).call(this);r&&this._emit("finalContent",r);const s=F(this,ne,"m",dr).call(this);s&&this._emit("finalFunctionCall",s);const i=F(this,ne,"m",hr).call(this);i!=null&&this._emit("finalFunctionCallResult",i),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",F(this,ne,"m",pr).call(this))}async _createChatCompletion(e,t,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),F(this,ne,"m",qi).call(this,t);const i=await e.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(i)}async _runChatCompletion(e,t,r){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){var h;const s="function",{function_call:i="auto",stream:o,...a}=t,l=typeof i!="string"&&(i==null?void 0:i.name),{maxChatCompletions:u=Es}=r||{},d={};for(const g of t.functions)d[g.name||g.function.name]=g;const c=t.functions.map(g=>({name:g.name||g.function.name,parameters:g.parameters,description:g.description}));for(const g of t.messages)this._addMessage(g,!1);for(let g=0;gJSON.stringify(S.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:m,content:_});continue}let C;try{C=As(P)?await P.parse(A):A}catch(_){this._addMessage({role:s,name:m,content:_ instanceof Error?_.message:String(_)});continue}const E=await P.function(C,this),b=F(this,ne,"m",_r).call(this,E);if(this._addMessage({role:s,name:m,content:b}),l)return}}async _runTools(e,t,r){var h,g;const s="tool",{tool_choice:i="auto",stream:o,...a}=t,l=typeof i!="string"&&((h=i==null?void 0:i.function)==null?void 0:h.name),{maxChatCompletions:u=Es}=r||{},d={};for(const f of t.tools)f.type==="function"&&(d[f.function.name||f.function.function.name]=f.function);const c="tools"in t?t.tools.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description}}:f):void 0;for(const f of t.messages)this._addMessage(f,!1);for(let f=0;fJSON.stringify(L.function.name)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:P,content:w});continue}let _;try{_=As(b)?await b.parse(E):E}catch(w){const L=w instanceof Error?w.message:String(w);this._addMessage({role:s,tool_call_id:P,content:L});continue}const S=await b.function(_,this),R=F(this,ne,"m",_r).call(this,S);if(this._addMessage({role:s,tool_call_id:P,content:R}),l)return}}}}Wt=new WeakMap,Gt=new WeakMap,ht=new WeakMap,pt=new WeakMap,Jt=new WeakMap,mt=new WeakMap,ve=new WeakMap,_t=new WeakMap,zt=new WeakMap,Xt=new WeakMap,$e=new WeakMap,mr=new WeakMap,ne=new WeakSet,fr=function(){return F(this,ne,"m",pn).call(this).content??null},pn=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(st(t))return{...t,content:t.content??null}}throw new B("stream ended without producing a ChatCompletionMessage with role=assistant")},dr=function(){var e,t;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(st(s)&&(s!=null&&s.function_call))return s.function_call;if(st(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},hr=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Bi(t)&&t.content!=null||Ui(t)&&t.content!=null&&this.messages.some(r=>{var s;return r.role==="assistant"&&((s=r.tool_calls)==null?void 0:s.some(i=>i.type==="function"&&i.id===t.tool_call_id))}))return t.content}},pr=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},qi=function(e){if(e.n!=null&&e.n>1)throw new B("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_r=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Mt extends Hi{static runFunctions(e,t,r){const s=new Mt,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,i)),s}static runTools(e,t,r){const s=new Mt,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,i)),s}_addMessage(e){super._addMessage(e),st(e)&&e.content&&this._emit("content",e.content)}}var _e=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},Yn=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},Se,Be,Zn,$n,Dt,Ps;class xt extends Hi{constructor(){super(...arguments),Se.add(this),Be.set(this,void 0)}get currentChatCompletionSnapshot(){return _e(this,Be,"f")}static fromReadableStream(e){const t=new xt;return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const s=new xt;return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){var o;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),_e(this,Se,"m",Zn).call(this);const i=await e.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const a of i)_e(this,Se,"m",$n).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new he;return this._addChatCompletion(_e(this,Se,"m",Dt).call(this))}async _fromReadableStream(e,t){var o;const r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),_e(this,Se,"m",Zn).call(this),this._connected();const s=Pe.fromReadableStream(e,this.controller);let i;for await(const a of s)i&&i!==a.id&&this._addChatCompletion(_e(this,Se,"m",Dt).call(this)),_e(this,Se,"m",$n).call(this,a),i=a.id;if((o=s.controller.signal)!=null&&o.aborted)throw new he;return this._addChatCompletion(_e(this,Se,"m",Dt).call(this))}[(Be=new WeakMap,Se=new WeakSet,Zn=function(){this.ended||Yn(this,Be,void 0,"f")},$n=function(t){var o,a,l;if(this.ended)return;const r=_e(this,Se,"m",Ps).call(this,t);this._emit("chunk",t,r);const s=(a=(o=t.choices[0])==null?void 0:o.delta)==null?void 0:a.content,i=(l=r.choices[0])==null?void 0:l.message;s!=null&&(i==null?void 0:i.role)==="assistant"&&(i!=null&&i.content)&&this._emit("content",s,i.content)},Dt=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");const t=_e(this,Be,"f");if(!t)throw new B("request ended without sending any chunks");return Yn(this,Be,void 0,"f"),Xl(t)},Ps=function(t){var r,s,i;let o=_e(this,Be,"f");const{choices:a,...l}=t;o?Object.assign(o,l):o=Yn(this,Be,{...l,choices:[]},"f");for(const{delta:u,finish_reason:d,index:c,logprobs:h=null,...g}of t.choices){let f=o.choices[c];if(f||(f=o.choices[c]={finish_reason:d,index:c,message:{},logprobs:h,...g}),h)if(!f.logprobs)f.logprobs=Object.assign({},h);else{const{content:E,...b}=h;Object.assign(f.logprobs,b),E&&((r=f.logprobs).content??(r.content=[]),f.logprobs.content.push(...E))}if(d&&(f.finish_reason=d),Object.assign(f,g),!u)continue;const{content:p,function_call:m,role:A,tool_calls:P,...C}=u;if(Object.assign(f.message,C),p&&(f.message.content=(f.message.content||"")+p),A&&(f.message.role=A),m&&(f.message.function_call?(m.name&&(f.message.function_call.name=m.name),m.arguments&&((s=f.message.function_call).arguments??(s.arguments=""),f.message.function_call.arguments+=m.arguments)):f.message.function_call=m),P){f.message.tool_calls||(f.message.tool_calls=[]);for(const{index:E,id:b,type:_,function:S,...R}of P){const w=(i=f.message.tool_calls)[E]??(i[E]={});Object.assign(w,R),b&&(w.id=b),_&&(w.type=_),S&&(w.function??(w.function={arguments:""})),S!=null&&S.name&&(w.function.name=S.name),S!=null&&S.arguments&&(w.function.arguments+=S.arguments)}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Pe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Xl(n){const{id:e,choices:t,created:r,model:s,system_fingerprint:i,...o}=n;return{...o,id:e,choices:t.map(({message:a,finish_reason:l,index:u,logprobs:d,...c})=>{if(!l)throw new B(`missing finish_reason for choice ${u}`);const{content:h=null,function_call:g,tool_calls:f,...p}=a,m=a.role;if(!m)throw new B(`missing role for choice ${u}`);if(g){const{arguments:A,name:P}=g;if(A==null)throw new B(`missing function_call.arguments for choice ${u}`);if(!P)throw new B(`missing function_call.name for choice ${u}`);return{...c,message:{content:h,function_call:{arguments:A,name:P},role:m},finish_reason:l,index:u,logprobs:d}}return f?{...c,index:u,finish_reason:l,logprobs:d,message:{...p,role:m,content:h,tool_calls:f.map((A,P)=>{const{function:C,type:E,id:b,..._}=A,{arguments:S,name:R,...w}=C||{};if(b==null)throw new B(`missing choices[${u}].tool_calls[${P}].id +${jt(n)}`);if(E==null)throw new B(`missing choices[${u}].tool_calls[${P}].type +${jt(n)}`);if(R==null)throw new B(`missing choices[${u}].tool_calls[${P}].function.name +${jt(n)}`);if(S==null)throw new B(`missing choices[${u}].tool_calls[${P}].function.arguments +${jt(n)}`);return{..._,id:b,type:E,function:{...w,name:R,arguments:S}}})}}:{...c,message:{...p,content:h,role:m},finish_reason:l,index:u,logprobs:d}}),created:r,model:s,object:"chat.completion",...i?{system_fingerprint:i}:{}}}function jt(n){return JSON.stringify(n)}class it extends xt{static fromReadableStream(e){const t=new it;return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,r){const s=new it,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,i)),s}static runTools(e,t,r){const s=new it,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,i)),s}}let Wi=class extends X{runFunctions(e,t){return e.stream?it.runFunctions(this._client.chat.completions,e,t):Mt.runFunctions(this._client.chat.completions,e,t)}runTools(e,t){return e.stream?it.runTools(this._client.chat.completions,e,t):Mt.runTools(this._client.chat.completions,e,t)}stream(e,t){return xt.createChatCompletion(this._client.chat.completions,e,t)}};class mn extends X{constructor(){super(...arguments),this.completions=new Wi(this._client)}}(function(n){n.Completions=Wi})(mn||(mn={}));var ge=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},K=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},Kt,Vt,gt,yt,Qt,bt,Ie,wt,Yt,Zt,et,gr;class Kl{constructor(){this.controller=new AbortController,Kt.set(this,void 0),Vt.set(this,()=>{}),gt.set(this,()=>{}),yt.set(this,void 0),Qt.set(this,()=>{}),bt.set(this,()=>{}),Ie.set(this,{}),wt.set(this,!1),Yt.set(this,!1),Zt.set(this,!1),et.set(this,!1),gr.set(this,e=>{if(ge(this,Yt,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new he),e instanceof he)return ge(this,Zt,!0,"f"),this._emit("abort",e);if(e instanceof B)return this._emit("error",e);if(e instanceof Error){const t=new B(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new B(String(e)))}),ge(this,Kt,new Promise((e,t)=>{ge(this,Vt,e,"f"),ge(this,gt,t,"f")}),"f"),ge(this,yt,new Promise((e,t)=>{ge(this,Qt,e,"f"),ge(this,bt,t,"f")}),"f"),K(this,Kt,"f").catch(()=>{}),K(this,yt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emit("end")},K(this,gr,"f"))},0)}_addRun(e){return e}_connected(){this.ended||(K(this,Vt,"f").call(this),this._emit("connect"))}get ended(){return K(this,wt,"f")}get errored(){return K(this,Yt,"f")}get aborted(){return K(this,Zt,"f")}abort(){this.controller.abort()}on(e,t){return(K(this,Ie,"f")[e]||(K(this,Ie,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=K(this,Ie,"f")[e];if(!r)return this;const s=r.findIndex(i=>i.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(K(this,Ie,"f")[e]||(K(this,Ie,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{ge(this,et,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){ge(this,et,!0,"f"),await K(this,yt,"f")}_emit(e,...t){if(K(this,wt,"f"))return;e==="end"&&(ge(this,wt,!0,"f"),K(this,Qt,"f").call(this));const r=K(this,Ie,"f")[e];if(r&&(K(this,Ie,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!K(this,et,"f")&&!(r!=null&&r.length)&&Promise.reject(s),K(this,gt,"f").call(this,s),K(this,bt,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!K(this,et,"f")&&!(r!=null&&r.length)&&Promise.reject(s),K(this,gt,"f").call(this,s),K(this,bt,"f").call(this,s),this._emit("end")}}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s,i){return await this._createToolAssistantStream(r,e,t,s,i)}async _createThreadAssistantStream(e,t,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const i=await e.createAndRun({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addRun(i)}async _createToolAssistantStream(e,t,r,s,i){const o=i==null?void 0:i.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a=await e.submitToolOutputs(t,r,{...s,stream:!1},{...i,signal:this.controller.signal});return this._connected(),this._addRun(a)}async _createAssistantStream(e,t,r,s){const i=s==null?void 0:s.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const o=await e.create(t,{...r,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addRun(o)}}Kt=new WeakMap,Vt=new WeakMap,gt=new WeakMap,yt=new WeakMap,Qt=new WeakMap,bt=new WeakMap,Ie=new WeakMap,wt=new WeakMap,Yt=new WeakMap,Zt=new WeakMap,et=new WeakMap,gr=new WeakMap;var T=globalThis&&globalThis.__classPrivateFieldGet||function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},ue=globalThis&&globalThis.__classPrivateFieldSet||function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},Z,yr,Ae,$t,ye,ze,tt,We,_n,fe,en,tn,Ct,St,At,Cs,ks,Rs,Os,Ms,xs,Ts;class be extends Kl{constructor(){super(...arguments),Z.add(this),yr.set(this,[]),Ae.set(this,{}),$t.set(this,{}),ye.set(this,void 0),ze.set(this,void 0),tt.set(this,void 0),We.set(this,void 0),_n.set(this,void 0),fe.set(this,void 0),en.set(this,void 0),tn.set(this,void 0),Ct.set(this,void 0)}[(yr=new WeakMap,Ae=new WeakMap,$t=new WeakMap,ye=new WeakMap,ze=new WeakMap,tt=new WeakMap,We=new WeakMap,_n=new WeakMap,fe=new WeakMap,en=new WeakMap,tn=new WeakMap,Ct=new WeakMap,Z=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new be;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var i;const r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Pe.fromReadableStream(e,this.controller);for await(const o of s)T(this,Z,"m",St).call(this,o);if((i=s.controller.signal)!=null&&i.aborted)throw new he;return this._addRun(T(this,Z,"m",At).call(this))}toReadableStream(){return new Pe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s,i){const o=new be;return o._run(()=>o._runToolAssistantStream(e,t,r,s,{...i,headers:{...i==null?void 0:i.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,s,i){var u;const o=i==null?void 0:i.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},l=await e.submitToolOutputs(t,r,a,{...i,signal:this.controller.signal});this._connected();for await(const d of l)T(this,Z,"m",St).call(this,d);if((u=l.controller.signal)!=null&&u.aborted)throw new he;return this._addRun(T(this,Z,"m",At).call(this))}static createThreadAssistantStream(e,t,r){const s=new be;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){const i=new be;return i._run(()=>i._runAssistantStream(e,t,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return T(this,en,"f")}currentRun(){return T(this,tn,"f")}currentMessageSnapshot(){return T(this,ye,"f")}currentRunStepSnapshot(){return T(this,Ct,"f")}async finalRunSteps(){return await this.done(),Object.values(T(this,Ae,"f"))}async finalMessages(){return await this.done(),Object.values(T(this,$t,"f"))}async finalRun(){if(await this.done(),!T(this,ze,"f"))throw Error("Final run was not received.");return T(this,ze,"f")}async _createThreadAssistantStream(e,t,r){var a;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const i={...t,stream:!0},o=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(const l of o)T(this,Z,"m",St).call(this,l);if((a=o.controller.signal)!=null&&a.aborted)throw new he;return this._addRun(T(this,Z,"m",At).call(this))}async _createAssistantStream(e,t,r,s){var l;const i=s==null?void 0:s.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(const u of a)T(this,Z,"m",St).call(this,u);if((l=a.controller.signal)!=null&&l.aborted)throw new he;return this._addRun(T(this,Z,"m",At).call(this))}static accumulateDelta(e,t){for(const[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let i=e[r];if(i==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof i=="string"&&typeof s=="string")i+=s;else if(typeof i=="number"&&typeof s=="number")i+=s;else if(Ss(i)&&Ss(s))i=this.accumulateDelta(i,s);else if(Array.isArray(i)&&Array.isArray(s)){if(i.every(o=>typeof o=="string"||typeof o=="number")){i.push(...s);continue}}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${i}`);e[r]=i}return e}}St=function(e){if(!this.ended)switch(ue(this,en,e,"f"),T(this,Z,"m",Rs).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":T(this,Z,"m",Ts).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":T(this,Z,"m",ks).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":T(this,Z,"m",Cs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},At=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");if(!T(this,ze,"f"))throw Error("Final run has not been received");return T(this,ze,"f")},Cs=function(e){const[t,r]=T(this,Z,"m",Ms).call(this,e,T(this,ye,"f"));ue(this,ye,t,"f"),T(this,$t,"f")[t.id]=t;for(const s of r){const i=t.content[s.index];(i==null?void 0:i.type)=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let i=s.text,o=t.content[s.index];if(o&&o.type=="text")this._emit("textDelta",i,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=T(this,tt,"f")){if(T(this,We,"f"))switch(T(this,We,"f").type){case"text":this._emit("textDone",T(this,We,"f").text,T(this,ye,"f"));break;case"image_file":this._emit("imageFileDone",T(this,We,"f").image_file,T(this,ye,"f"));break}ue(this,tt,s.index,"f")}ue(this,We,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(T(this,tt,"f")!==void 0){const s=e.data.content[T(this,tt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,T(this,ye,"f"));break;case"text":this._emit("textDone",s.text,T(this,ye,"f"));break}}T(this,ye,"f")&&this._emit("messageDone",e.data),ue(this,ye,void 0,"f")}},ks=function(e){const t=T(this,Z,"m",Os).call(this,e);switch(ue(this,Ct,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const i of r.step_details.tool_calls)i.index==T(this,_n,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(T(this,fe,"f")&&this._emit("toolCallDone",T(this,fe,"f")),ue(this,_n,i.index,"f"),ue(this,fe,t.step_details.tool_calls[i.index],"f"),T(this,fe,"f")&&this._emit("toolCallCreated",T(this,fe,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":ue(this,Ct,void 0,"f"),e.data.step_details.type=="tool_calls"&&T(this,fe,"f")&&(this._emit("toolCallDone",T(this,fe,"f")),ue(this,fe,void 0,"f")),this._emit("runStepDone",e.data,t);break}},Rs=function(e){T(this,yr,"f").push(e),this._emit("event",e)},Os=function(e){switch(e.event){case"thread.run.step.created":return T(this,Ae,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=T(this,Ae,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=be.accumulateDelta(t,r.delta);T(this,Ae,"f")[e.data.id]=s}return T(this,Ae,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":T(this,Ae,"f")[e.data.id]=e.data;break}if(T(this,Ae,"f")[e.data.id])return T(this,Ae,"f")[e.data.id];throw new Error("No snapshot available")},Ms=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const i of s.delta.content)if(i.index in t.content){let o=t.content[i.index];t.content[i.index]=T(this,Z,"m",xs).call(this,i,o)}else t.content[i.index]=i,r.push(i);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},xs=function(e,t){return be.accumulateDelta(t,e)},Ts=function(e){switch(ue(this,tn,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":ue(this,ze,e.data,"f"),T(this,fe,"f")&&(this._emit("toolCallDone",T(this,fe,"f")),ue(this,fe,void 0,"f"));break}};let gn=class extends X{retrieve(e,t,r,s){return this._client.get(`/threads/${e}/messages/${t}/files/${r}`,{...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}list(e,t,r={},s){return Re(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/messages/${t}/files`,Dr,{query:r,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}};class Dr extends Fe{}(function(n){n.MessageFilesPage=Dr})(gn||(gn={}));class yn extends X{constructor(){super(...arguments),this.files=new gn(this._client)}create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}update(e,t,r,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}list(e,t={},r){return Re(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,jr,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}}class jr extends Fe{}(function(n){n.MessagesPage=jr,n.Files=gn,n.MessageFilesPage=Dr})(yn||(yn={}));class bn extends X{retrieve(e,t,r,s){return this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}list(e,t,r={},s){return Re(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Br,{query:r,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}}class Br extends Fe{}(function(n){n.RunStepsPage=Br})(bn||(bn={}));class wn extends X{constructor(){super(...arguments),this.steps=new bn(this._client)}create(e,t,r){return this._client.post(`/threads/${e}/runs`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers},stream:t.stream??!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}update(e,t,r,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers}})}list(e,t={},r){return Re(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Ur,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(e,s.id,r)}createAndStream(e,t,r){return be.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const s={...r==null?void 0:r.headers,"X-Stainless-Poll-Helper":"true"};for(r!=null&&r.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const{data:i,response:o}=await this.retrieve(e,t,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r!=null&&r.pollIntervalMs)a=r.pollIntervalMs;else{const l=o.headers.get("openai-poll-after-ms");if(l){const u=parseInt(l);isNaN(u)||(a=u)}}await Ir(a);break;case"requires_action":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,r){return be.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...s,headers:{"OpenAI-Beta":"assistants=v1",...s==null?void 0:s.headers},stream:r.stream??!1})}async submitToolOutputsAndPoll(e,t,r,s){const i=await this.submitToolOutputs(e,t,r,s);return await this.poll(e,i.id,s)}submitToolOutputsStream(e,t,r,s){return be.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,s)}}class Ur extends Fe{}(function(n){n.RunsPage=Ur,n.Steps=bn,n.RunStepsPage=Br})(wn||(wn={}));class Sn extends X{constructor(){super(...arguments),this.runs=new wn(this._client),this.messages=new yn(this._client)}create(e={},t){return Re(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}update(e,t,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t==null?void 0:t.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return be.createThreadAssistantStream(e,this._client.beta.threads,t)}}(function(n){n.Runs=wn,n.RunsPage=Ur,n.Messages=yn,n.MessagesPage=jr})(Sn||(Sn={}));class An extends X{constructor(){super(...arguments),this.chat=new mn(this._client),this.assistants=new hn(this._client),this.threads=new Sn(this._client)}}(function(n){n.Chat=mn,n.Assistants=hn,n.AssistantsPage=Fr,n.Threads=Sn})(An||(An={}));class En extends X{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}En||(En={});class Pn extends X{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}Pn||(Pn={});class Cn extends X{create(e,t){return this._client.post("/files",Ot({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return Re(e)?this.list({},e):this._client.getAPIList("/files",qr,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t==null?void 0:t.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),i=Date.now();let o=await this.retrieve(e);for(;!o.status||!s.has(o.status);)if(await Ir(t),o=await this.retrieve(e),Date.now()-i>r)throw new vr({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class qr extends Lr{}(function(n){n.FileObjectsPage=qr})(Cn||(Cn={}));class kn extends X{create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return Re(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Hr,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return Re(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Wr,{query:t,...r})}}class Hr extends Fe{}class Wr extends Fe{}(function(n){n.FineTuningJobsPage=Hr,n.FineTuningJobEventsPage=Wr})(kn||(kn={}));class Rn extends X{constructor(){super(...arguments),this.jobs=new kn(this._client)}}(function(n){n.Jobs=kn,n.FineTuningJobsPage=Hr,n.FineTuningJobEventsPage=Wr})(Rn||(Rn={}));class On extends X{createVariation(e,t){return this._client.post("/images/variations",Ot({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",Ot({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}On||(On={});class Mn extends X{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Gr,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Gr extends Lr{}(function(n){n.ModelsPage=Gr})(Mn||(Mn={}));class xn extends X{create(e,t){return this._client.post("/moderations",{body:e,...t})}}xn||(xn={});var Gi;class Y extends Nl{constructor({baseURL:e=Qn("OPENAI_BASE_URL"),apiKey:t=Qn("OPENAI_API_KEY"),organization:r=Qn("OPENAI_ORG_ID")??null,...s}={}){if(t===void 0)throw new B("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const i={apiKey:t,organization:r,...s,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&zl())throw new B(`It looks like you're running in a browser-like environment. This is disabled by default, as it risks exposing your secret API credentials to attackers. If you understand the risks and have appropriate mitigations in place, @@ -23,6 +22,6 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g., new OpenAI({ apiKey, dangerouslyAllowBrowser: true }); https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety -`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new Vn(this),this.chat=new Ln(this),this.embeddings=new Qn(this),this.files=new Yn(this),this.images=new ts(this),this.audio=new jn(this),this.moderations=new ss(this),this.models=new ns(this),this.fineTuning=new es(this),this.beta=new Kn(this),this._options=i,this.apiKey=t,this.organization=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}}To=ae;ae.OpenAI=To;ae.OpenAIError=$;ae.APIError=ce;ae.APIConnectionError=cs;ae.APIConnectionTimeoutError=or;ae.APIUserAbortError=Se;ae.NotFoundError=fo;ae.ConflictError=ho;ae.RateLimitError=mo;ae.BadRequestError=lo;ae.AuthenticationError=co;ae.InternalServerError=_o;ae.PermissionDeniedError=uo;ae.UnprocessableEntityError=po;(function(n){n.toFile=So,n.fileFromPath=oo,n.Page=lr,n.CursorPage=Je,n.Completions=Vn,n.Chat=Ln,n.Embeddings=Qn,n.Files=Yn,n.FileObjectsPage=mr,n.Images=ts,n.Audio=jn,n.Moderations=ss,n.Models=ns,n.ModelsPage=br,n.FineTuning=es,n.Beta=Kn})(ae||(ae={}));const Wc=ae;class Gc{constructor(e,t,s){ee(this,"_apiKey");ee(this,"_baseUrl");ee(this,"_timeout");ee(this,"_is");this._apiKey=e,this._baseUrl=t,this._timeout=s}get baseUrl(){return this._baseUrl}}class pi extends Gc{constructor(t,s="https://api.openai.com/v1",r=90){t=t.replace("Bear ","").trim(),s=s.replace("chat/completions","").trim();super(t,s,r);ee(this,"_openai");this._openai=new Wc({apiKey:t,baseURL:s,timeout:r*1e3,dangerouslyAllowBrowser:!0})}async completion(t,s,r,i,o,a){var f,c,h,b,d;let l=await bs(a);if(!l){Ze("插入文本失败!");return}const u=await this._openai.chat.completions.create({messages:[{role:"user",content:s.concat(` -`,r)}],model:t,temperature:i,stream:o});if(o){let p="";for await(const m of u)!m||m.created===0||((f=m.choices[0])==null?void 0:f.finish_reason)==="stop"||(p=p.concat((h=(c=m.choices[0])==null?void 0:c.delta)==null?void 0:h.content),l&&await ys("markdown",p.replace(/\n\n/gm,` -`).replace(new RegExp("(?<=[\\-\\*]) |(?<=\\d\\.) ","gm"),""),l))}else await ys("markdown",(d=(b=u.choices)==null?void 0:b[0].message)==null?void 0:d.content,l),await Ze(`请求token数${u.usage.prompt_tokens},生成token数${u.usage.completion_tokens},总计token数${u.usage.total_tokens}`)}chat(t,s,r,i,o,a){throw new Error("Method not implemented.")}async imgGenerate(t,s,r,i,o,a){let l=await bs(a);if(!l){Ze("插入图片失败!");return}(await this._openai.images.generate({model:t,prompt:s,n:r,size:i,quality:o,response_format:"b64_json"})).data.forEach(async f=>{let c=await ql(f.b64_json,l,it.PLUGIN_NAME);c=c.replace("/data/",""),await ys("markdown",`![](${c})`,l),l=await bs(a),l||Ze("插入图片失败!")})}}function mi(n,e,t){const s=n.slice();return s[33]=e[t],s}function _i(n,e,t){const s=n.slice();return s[36]=e[t],s}function gi(n,e,t){const s=n.slice();return s[36]=e[t],s}function bi(n,e,t){const s=n.slice();return s[41]=e[t],s}function yi(n){let e,t,s=n[41]+"",r,i,o,a;function l(){return n[23](n[41])}return{c(){e=C("li"),t=C("span"),r=oe(s),i=B(),g(t,"class","b3-list-item__text"),g(e,"data-name","editor"),g(e,"class","b3-list-item svelte-1jo4zii"),On(e,"b3-list-item--focus",n[41]===n[17])},m(u,f){J(u,e,f),y(e,t),y(t,r),y(e,i),o||(a=[V(e,"click",l),V(e,"keydown",Kc)],o=!0)},p(u,f){n=u,f[0]&393216&&On(e,"b3-list-item--focus",n[41]===n[17])},d(u){u&&W(e),o=!1,ue(a)}}}function zc(n){var s,r,i;let e,t;return e=new Zs({props:{type:n[36].type,title:n[36].title,description:n[36].description,settingKey:n[36].key,settingValue:n[36].value,placeholder:(s=n[36])==null?void 0:s.placeholder,options:(r=n[36])==null?void 0:r.options,slider:(i=n[36])==null?void 0:i.slider}}),e.$on("changed",n[24]),{c(){ie(e.$$.fragment)},m(o,a){se(e,o,a),t=!0},p:z,i(o){t||(q(e.$$.fragment,o),t=!0)},o(o){G(e.$$.fragment,o),t=!1},d(o){re(e,o)}}}function wi(n,e){let t,s,r,i=e[36].group==e[18][0]&&zc(e);return{key:n,first:null,c(){t=et(),i&&i.c(),s=et(),this.first=t},m(o,a){J(o,t,a),i&&i.m(o,a),J(o,s,a),r=!0},p(o,a){e=o,e[36].group==e[18][0]&&i.p(e,a)},i(o){r||(q(i),r=!0)},o(o){G(i),r=!1},d(o){o&&W(t),i&&i.d(o),o&&W(s)}}}function Jc(n){var s,r,i;let e,t;return e=new Zs({props:{type:n[36].type,title:n[36].title,description:n[36].description,settingKey:n[36].key,settingValue:n[36].value,placeholder:(s=n[36])==null?void 0:s.placeholder,options:(r=n[36])==null?void 0:r.options,slider:(i=n[36])==null?void 0:i.slider}}),e.$on("changed",n[28]),{c(){ie(e.$$.fragment)},m(o,a){se(e,o,a),t=!0},p:z,i(o){t||(q(e.$$.fragment,o),t=!0)},o(o){G(e.$$.fragment,o),t=!1},d(o){re(e,o)}}}function Si(n,e){let t,s,r,i=e[36].group==e[18][1]&&Jc(e);return{key:n,first:null,c(){t=et(),i&&i.c(),s=et(),this.first=t},m(o,a){J(o,t,a),i&&i.m(o,a),J(o,s,a),r=!0},p(o,a){e=o,e[36].group==e[18][1]&&i.p(e,a)},i(o){r||(q(i),r=!0)},o(o){G(i),r=!1},d(o){o&&W(t),i&&i.d(o),o&&W(s)}}}function Ai(n,e){let t,s,r,i,o=e[33].title+"",a,l,u,f=e[33].prompt+"",c,h,b,d,p;return{key:n,first:null,c(){t=C("li"),s=C("span"),r=C("p"),i=C("strong"),a=oe(o),l=B(),u=C("p"),c=oe(f),h=B(),b=C("div"),g(r,"class","prompt_title svelte-1jo4zii"),g(u,"class","b3-label__text"),g(s,"class","b3-list-item__text"),g(t,"class","b3-list-item b3-label__text"),g(b,"class","fn__spac"),this.first=t},m(m,S){J(m,t,S),y(t,s),y(s,r),y(r,i),y(i,a),y(s,l),y(s,u),y(u,c),J(m,h,S),J(m,b,S),d||(p=[V(s,"keydown",Vc),V(s,"click",e[32])],d=!0)},p(m,S){e=m},d(m){m&&W(t),m&&W(h),m&&W(b),d=!1,ue(p)}}}function Xc(n){let e,t,s,r,i,o,a=[],l=new Map,u,f,c,h,b,d,p,m,S,k,E,P,A,F,v,L,x=[],X=new Map,be,ne,Q,he,R,I,D,Ae,sn,K,Xe,nt,rn,yr,lt,Tt,Le=[],wr=new Map,on,Sr,ct,ut,an,me,ft=n[18],pe=[];for(let w=0;ww[36].key;for(let w=0;ww[36].key;for(let w=0;ww[33].title;for(let w=0;w{},Vc=()=>{};function Qc(n,e,t){let{$$slots:s={},$$scope:r}=e,{selectedContent:i}=e,{storageSettings:o}=e,{storagePrompts:a}=e,{dialog:l}=e,{lastNodeId:u}=e,f,c,h,b,d,p,m,S,k,E,P,A,F=["📃 文本生成","🏞️ 文生图","🌈 管理prompt","🤖 聊天(开发中...)"],v=F[0],L=[],x=[];o.data.forEach(K=>{L.push(K)}),a.data.forEach(K=>{x.push(K)});const X=K=>{t(17,v=K)},be=({detail:K})=>{let Xe=o.get(K.key);Xe.value=K.value,o.set(K.key,Xe)},ne=()=>{l.destroy()},Q=()=>{t(9,d=o.get(M.MODEL).value),t(10,p=o.get(M.TEMPERATURE).value),t(11,m=o.get(M.PROMPT_TITLE).value),t(12,S=o.get(M.PROMPT).value),m.length==0?Ye("prompt标题不能为空"):(a.set(m,{model:d,temperature:p,title:m,prompt:S}),a.save(!0),l.destroy())},he=async()=>{t(9,d=o.get(M.MODEL).value),t(10,p=o.get(M.TEMPERATURE).value),t(12,S=o.get(M.PROMPT).value),t(13,k=o.get(M.STREAM).value),d.includes("gpt")&&(t(6,c=o.get(M.API_KEY).value),t(7,h=o.get(M.BASE_URL).value),t(8,b=o.get(M.TIMEOUT).value),c.length==0&&await Ye("请先填写api-key"),t(5,f=new pi(c,h,b))),f.completion(d,i,S,p,k,u),l.destroy()},R=({detail:K})=>{let Xe=o.get(K.key);Xe.value=K.value,o.set(K.key,Xe)},I=()=>{l.destroy()},D=()=>{t(9,d=o.get(M.IMG_MODEL).value),t(14,E=o.get(M.IMG_NUM).value),t(15,P=o.get(M.IMG_SIZE).value),t(16,A=o.get(M.IMG_QUALITY).value),t(11,m=o.get(M.IMG_PROMTP_TITLE).value),t(12,S=o.get(M.IMG_PROMPT).value),m.length==0?Ye("prompt标题不能为空"):(a.set(m,{model:d,imgNum:E,imgSize:P,imgQuality:A,title:m,prompt:S}),a.save(!0),l.destroy())},Ae=async()=>{t(9,d=o.get(M.IMG_MODEL).value),t(14,E=Number.parseInt(o.get(M.IMG_NUM).value)),t(15,P=o.get(M.IMG_SIZE).value),t(16,A=o.get(M.IMG_QUALITY).value),t(12,S=o.get(M.IMG_PROMPT).value),t(6,c=o.get(M.API_KEY).value),t(7,h=o.get(M.BASE_URL).value),t(8,b=o.get(M.TIMEOUT).value),c.length==0&&(Ye("请先填写api-key"),l.destroy()),t(5,f=new pi(c,h,b)),Ze("请等待1~2分钟..."),f.imgGenerate(d,S,E,P,A,u),l.destroy()},sn=()=>{Ye("prompt编辑功能开发中,敬请期待!")};return n.$$set=K=>{"selectedContent"in K&&t(0,i=K.selectedContent),"storageSettings"in K&&t(1,o=K.storageSettings),"storagePrompts"in K&&t(2,a=K.storagePrompts),"dialog"in K&&t(3,l=K.dialog),"lastNodeId"in K&&t(4,u=K.lastNodeId),"$$scope"in K&&t(21,r=K.$$scope)},[i,o,a,l,u,f,c,h,b,d,p,m,S,k,E,P,A,v,F,L,x,r,s,X,be,ne,Q,he,R,I,D,Ae,sn]}class Ei extends Ie{constructor(e){super(),xe(this,e,Qc,Xc,Te,{selectedContent:0,storageSettings:1,storagePrompts:2,dialog:3,lastNodeId:4},null,[-1,-1])}}class Yc{constructor(e,t,s){ee(this,"_storageSettings");ee(this,"_storagePrompts");ee(this,"_plugin");this._storageSettings=t,this._storagePrompts=s,this._plugin=e}async contentGenerate(){}async onload(){this._plugin.addCommand({langKey:"Prompt面板",hotkey:"⌘L",editorCallback:async e=>{var a;let t="",s="";const i=[...((a=e==null?void 0:e.wysiwyg)==null?void 0:a.element).querySelectorAll(".protyle-wysiwyg--select")];i.length>0?(t=await Hr(i),s=i.at(-1).dataset.nodeId):s=Bl().getAttribute("data-node-id");const o=new Ge.Dialog({title:"prompt面板",width:"50%",height:"60%",content:'
'});new Ei({target:o.element.querySelector("#PromptPanel"),props:{dialog:o,lastNodeId:s,selectedContent:t,storageSettings:this._storageSettings,storagePrompts:this._storagePrompts}})}})}blockIconEvent(e){e.menu.addItem({iconHTML:"✨🖍",label:"AI插件",click:async()=>{const t=new Ge.Dialog({title:"prompt面板",width:"50%",height:"60%",content:'
'});let s=await Hr(e.blockElements),r=e.blockElements.at(-1).dataset.nodeId;new Ei({target:t.element.querySelector("#PromptPanel"),props:{dialog:t,lastNodeId:r,selectedContent:s,storageSettings:this._storageSettings,storagePrompts:this._storagePrompts}})}})}}class Zc extends Ge.Plugin{constructor(t){super(t);ee(this,"blockIconEventBindThis");ee(this,"_storageSettings");ee(this,"_storagePrompts");ee(this,"_isMobile");ee(this,"_contentGenerate");this.setting=new Ge.Setting({}),this._storageSettings=new zl(this,it.AI_SETTING_STORAGE),this._storagePrompts=new Gl(this,it.AI_PROMPT_STORAGE),this._isMobile=Ge.getFrontend()==="mobile"||Ge.getFrontend()==="browser-mobile",this._contentGenerate=new Yc(this,this._storageSettings,this._storagePrompts),this.blockIconEventBindThis=this.blockIconEvent.bind(this)}async blockIconEvent({detail:t}){this._contentGenerate.blockIconEvent(t)}onload(){this._storageSettings.load(),this._storagePrompts.load(),this._contentGenerate.onload(),this.eventBus.on(Ti.click_blockicon,this.blockIconEventBindThis)}onLayoutReady(){}async uninstall(){await this._storagePrompts.deleteStorageFile(),await this._storageSettings.deleteStorageFile(),Ye("文件已删除,AI插件已卸载,bye~~")}openSetting(){if(this.setting)if(this._isMobile)Ze("手机端AI插件开发中,敬请期待!");else{let t=new Ge.Dialog({title:"思源AI",width:"50%",height:"60%",content:'
'});new nc({target:t.element.querySelector("#AISettingPanel"),props:{storageSettings:this._storageSettings,dialog:t}})}}}module.exports=Zc; +`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new En(this),this.chat=new an(this),this.embeddings=new Pn(this),this.files=new Cn(this),this.images=new On(this),this.audio=new fn(this),this.moderations=new xn(this),this.models=new Mn(this),this.fineTuning=new Rn(this),this.beta=new An(this),this._options=i,this.apiKey=t,this.organization=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}}Gi=Y;Y.OpenAI=Gi;Y.OpenAIError=B;Y.APIError=te;Y.APIConnectionError=Bn;Y.APIConnectionTimeoutError=vr;Y.APIUserAbortError=he;Y.NotFoundError=Ci;Y.ConflictError=ki;Y.RateLimitError=Oi;Y.BadRequestError=Ai;Y.AuthenticationError=Ei;Y.InternalServerError=Mi;Y.PermissionDeniedError=Pi;Y.UnprocessableEntityError=Ri;(function(n){n.toFile=Li,n.fileFromPath=wi,n.Page=Lr,n.CursorPage=Fe,n.Completions=En,n.Chat=an,n.Embeddings=Pn,n.Files=Cn,n.FileObjectsPage=qr,n.Images=On,n.Audio=fn,n.Moderations=xn,n.Models=Mn,n.ModelsPage=Gr,n.FineTuning=Rn,n.Beta=An})(Y||(Y={}));const Vl=Y;class Ql{constructor(e,t,r){V(this,"_apiKey");V(this,"_baseUrl");V(this,"_timeout");V(this,"_is");this._apiKey=e,this._baseUrl=t,this._timeout=r}get baseUrl(){return this._baseUrl}}class Tn extends Ql{constructor(t,r="https://api.openai.com/v1",s=90){t=t.replace("Bear ","").trim(),r=r.replace("chat/completions","").trim();super(t,r,s);V(this,"_openai");this._openai=new Vl({apiKey:t,baseURL:r,timeout:s*1e3,dangerouslyAllowBrowser:!0})}async completion(t,r,s,i,o,a){var d,c,h,g,f;let l=await zn(a);if(!l){Ue("插入文本失败!");return}const u=await this._openai.chat.completions.create({messages:[{role:"user",content:r.concat(` +`,s)}],model:t,temperature:i,stream:o});if(o){let p="";for await(const m of u)!m||m.created===0||((d=m.choices[0])==null?void 0:d.finish_reason)==="stop"||(p=p.concat((h=(c=m.choices[0])==null?void 0:c.delta)==null?void 0:h.content),l&&await Xn("markdown",p.replace(/\n\n/gm,` +`).replace(new RegExp("(?<=[\\-\\*]) |(?<=\\d\\.) ","gm"),""),l))}else await Xn("markdown",(f=(g=u.choices)==null?void 0:g[0].message)==null?void 0:f.content,l),await Ue(`请求token数${u.usage.prompt_tokens},生成token数${u.usage.completion_tokens},总计token数${u.usage.total_tokens}`)}chat(t,r,s,i,o,a){throw new Error("Method not implemented.")}async imgGenerate(t,r,s,i,o,a){let l=await zn(a);if(!l){Ue("插入图片失败!");return}(await this._openai.images.generate({model:t,prompt:r,n:s,size:i,quality:o,response_format:"b64_json"})).data.forEach(async d=>{let c=await rl(d.b64_json,l,Je.PLUGIN_NAME);c=c.replace("/data/",""),await Xn("markdown",`![](${c})`,l),l=await zn(a),l||Ue("插入图片失败!")})}}function vs(n,e,t){const r=n.slice();return r[22]=e[t],r}function Yl(n){var r,s,i;let e,t;return e=new Cr({props:{type:n[22].type,title:n[22].title,description:n[22].description,settingKey:n[22].key,settingValue:n[22].value,placeholder:(r=n[22])==null?void 0:r.placeholder,options:(s=n[22])==null?void 0:s.options,slider:(i=n[22])==null?void 0:i.slider}}),e.$on("changed",n[18]),{c(){re(e.$$.fragment)},m(o,a){$(e,o,a),t=!0},p:G,i(o){t||(q(e.$$.fragment,o),t=!0)},o(o){W(e.$$.fragment,o),t=!1},d(o){ee(e,o)}}}function Is(n,e){let t,r,s,i=e[22].group=="📃 文本生成"&&Yl(e);return{key:n,first:null,c(){t=at(),i&&i.c(),r=at(),this.first=t},m(o,a){J(o,t,a),i&&i.m(o,a),J(o,r,a),s=!0},p(o,a){e=o,e[22].group=="📃 文本生成"&&i.p(e,a)},i(o){s||(q(i),s=!0)},o(o){W(i),s=!1},d(o){o&&H(t),i&&i.d(o),o&&H(r)}}}function Zl(n){let e,t,r,s=[],i=new Map,o,a,l,u,d,c,h,g,f,p,m,A;const P=n[17].default,C=br(P,n,n[16],null);let E=n[15];const b=_=>_[22].key;for(let _=0;_{l.model&&l.prompt&&l.temperature&&(w.key==M.MODEL&&(w.value=l.model),w.key==M.PROMPT&&(w.value=l.prompt),w.key==M.TEMPERATURE&&(w.value=l.temperature)),E.push(w)});const b=({detail:w})=>{let L=o.get(w.key);L.value=w.value,o.set(w.key,L)},_=()=>{u.destroy()},S=()=>{t(10,p=o.get(M.MODEL).value),t(11,m=o.get(M.TEMPERATURE).value),t(13,P=o.get(M.PROMPT).value);const w=new de.Dialog({content:`
`});let L=w.element.querySelector("input");L.addEventListener("keydown",we=>{we.key==="Enter"&&(t(12,A=L.value),A||(He("prompt标题名不可为空!"),w.destroy(),u.destroy()),a.set(A,{model:p,temperature:m,title:A,prompt:P}),a.save(!0),w.destroy(),u.destroy())})},R=async()=>{t(10,p=o.get(M.MODEL).value),t(11,m=o.get(M.TEMPERATURE).value),t(13,P=o.get(M.PROMPT).value),t(14,C=o.get(M.STREAM).value),p.includes("gpt")&&(t(7,h=o.get(M.API_KEY).value),h.length==0&&await He("请先填写api-key"),t(8,g=o.get(M.BASE_URL).value),t(9,f=o.get(M.TIMEOUT).value),t(6,c=new Tn(h,g,f))),c.completion(p,i,P,m,C,d),u.destroy()};return n.$$set=w=>{"selectedContent"in w&&t(0,i=w.selectedContent),"storageSettings"in w&&t(1,o=w.storageSettings),"storagePrompts"in w&&t(2,a=w.storagePrompts),"promptItem"in w&&t(3,l=w.promptItem),"dialog"in w&&t(4,u=w.dialog),"lastNodeId"in w&&t(5,d=w.lastNodeId),"$$scope"in w&&t(16,s=w.$$scope)},[i,o,a,l,u,d,c,h,g,f,p,m,A,P,C,E,s,r,b,_,S,R]}class Ji extends xe{constructor(e){super(),Me(this,e,$l,Zl,Oe,{selectedContent:0,storageSettings:1,storagePrompts:2,promptItem:3,dialog:4,lastNodeId:5})}}function Ls(n,e,t){const r=n.slice();return r[22]=e[t],r}function ec(n){var r,s,i;let e,t;return e=new Cr({props:{type:n[22].type,title:n[22].title,description:n[22].description,settingKey:n[22].key,settingValue:n[22].value,placeholder:(r=n[22])==null?void 0:r.placeholder,options:(s=n[22])==null?void 0:s.options,slider:(i=n[22])==null?void 0:i.slider}}),e.$on("changed",n[18]),{c(){re(e.$$.fragment)},m(o,a){$(e,o,a),t=!0},p:G,i(o){t||(q(e.$$.fragment,o),t=!0)},o(o){W(e.$$.fragment,o),t=!1},d(o){ee(e,o)}}}function Ns(n,e){let t,r,s,i=e[22].group=="🏞️ 文生图"&&ec(e);return{key:n,first:null,c(){t=at(),i&&i.c(),r=at(),this.first=t},m(o,a){J(o,t,a),i&&i.m(o,a),J(o,r,a),s=!0},p(o,a){e=o,e[22].group=="🏞️ 文生图"&&i.p(e,a)},i(o){s||(q(i),s=!0)},o(o){W(i),s=!1},d(o){o&&H(t),i&&i.d(o),o&&H(r)}}}function tc(n){let e,t,r,s=[],i=new Map,o,a,l,u,d,c,h,g,f,p,m,A;const P=n[17].default,C=br(P,n,n[16],null);let E=n[15];const b=_=>_[22].key;for(let _=0;_{a.model&&a.prompt&&(w.key==M.IMG_MODEL&&(w.value=a.model),w.key==M.IMG_PROMPT&&(w.value=a.prompt),w.key==M.IMG_NUM&&(w.value=a.imgNum),w.key==M.IMG_QUALITY&&(w.value=a.imgQuality),w.key==M.IMG_SIZE&&(w.value=a.imgSize)),E.push(w)});const b=({detail:w})=>{let L=i.get(w.key);L.value=w.value,i.set(w.key,L)},_=()=>{l.destroy()},S=()=>{t(9,f=i.get(M.IMG_MODEL).value),t(12,A=i.get(M.IMG_NUM).value),t(13,P=i.get(M.IMG_SIZE).value),t(14,C=i.get(M.IMG_QUALITY).value),t(11,m=i.get(M.IMG_PROMPT).value);const w=new de.Dialog({content:`
`});let L=w.element.querySelector("input");L.addEventListener("keydown",we=>{we.key==="Enter"&&(t(10,p=L.value),p||(He("prompt标题名不可为空!"),w.destroy(),l.destroy()),o.set(p,{model:f,imgNum:A,imgSize:P,imgQuality:C,title:p,prompt:m}),o.save(!0),w.destroy(),l.destroy())})},R=async()=>{t(9,f=i.get(M.IMG_MODEL).value),t(12,A=Number.parseInt(i.get(M.IMG_NUM).value)),t(13,P=i.get(M.IMG_SIZE).value),t(14,C=i.get(M.IMG_QUALITY).value),t(11,m=i.get(M.IMG_PROMPT).value),t(6,c=i.get(M.API_KEY).value),t(7,h=i.get(M.BASE_URL).value),t(8,g=i.get(M.TIMEOUT).value),c.length==0&&(He("请先填写api-key"),l.destroy()),t(5,d=new Tn(c,h,g)),Ue("请等待1~2分钟..."),d.imgGenerate(f,m,A,P,C,u),l.destroy()};return n.$$set=w=>{"storageSettings"in w&&t(0,i=w.storageSettings),"storagePrompts"in w&&t(1,o=w.storagePrompts),"promptItem"in w&&t(2,a=w.promptItem),"dialog"in w&&t(3,l=w.dialog),"lastNodeId"in w&&t(4,u=w.lastNodeId),"$$scope"in w&&t(16,s=w.$$scope)},[i,o,a,l,u,d,c,h,g,f,p,m,A,P,C,E,s,r,b,_,S,R]}class zi extends xe{constructor(e){super(),Me(this,e,nc,tc,Oe,{storageSettings:0,storagePrompts:1,promptItem:2,dialog:3,lastNodeId:4})}}function Fs(n,e,t){const r=n.slice();return r[17]=e[t],r}function Ds(n,e){let t,r,s=e[17].title+"",i,o,a,l=e[17].prompt.slice(0,20)+"...",u,d,c,h,g,f,p,m,A;function P(){return e[14](e[17])}c=new Le({props:{label:"删除",text:!0,outline:!1}}),c.$on("click",P);function C(){return e[15](e[17])}function E(){return e[16](e[17])}return{key:n,first:null,c(){var b,_,S,R;t=I("div"),r=I("div"),i=se(s),o=U(),a=I("div"),u=se(l),d=U(),re(c.$$.fragment),g=U(),f=I("div"),k(a,"class","b3-label__text"),k(r,"class","fn__flex-1"),k(t,"class",h="b3-list-item b3-list-item--narrow fn__flex b3-label "+((_=(b=e[17])==null?void 0:b.title)!=null&&_.includes(e[11])||(R=(S=e[17])==null?void 0:S.prompt)!=null&&R.includes(e[11])?"":"fn__none")),k(f,"class","b3-menu__separator"),this.first=t},m(b,_){J(b,t,_),O(t,r),O(r,i),O(r,o),O(r,a),O(a,u),O(t,d),$(c,t,null),J(b,g,_),J(b,f,_),p=!0,m||(A=[z(t,"keydown",sc),z(t,"click",C),z(t,"contextmenu",Yi(E))],m=!0)},p(b,_){var S,R,w,L;e=b,(!p||_&1024)&&s!==(s=e[17].title+"")&&qe(i,s),(!p||_&1024)&&l!==(l=e[17].prompt.slice(0,20)+"...")&&qe(u,l),(!p||_&3072&&h!==(h="b3-list-item b3-list-item--narrow fn__flex b3-label "+((R=(S=e[17])==null?void 0:S.title)!=null&&R.includes(e[11])||(L=(w=e[17])==null?void 0:w.prompt)!=null&&L.includes(e[11])?"":"fn__none")))&&k(t,"class",h)},i(b){p||(q(c.$$.fragment,b),p=!0)},o(b){W(c.$$.fragment,b),p=!1},d(b){b&&H(t),ee(c),b&&H(g),b&&H(f),m=!1,ie(A)}}}function rc(n){let e,t,r,s,i,o,a=[],l=new Map,u,d,c,h=n[10];const g=f=>f[17].title;for(let f=0;f{};function ic(n,e,t){let{selectedContent:r}=e,{storageSettings:s}=e,{storagePrompts:i}=e,{dialog:o}=e,{lastNodeId:a}=e,l,u,d,c,h,g=[];i.data.forEach(E=>{g.push(E)});let f="";function p(E){t(10,g=g.filter(b=>b.title!==E))}function m(){f=this.value,t(11,f)}const A=E=>{i.remove(E.title),p(E.title),i.save()},P=async E=>{t(9,h=s.get(M.STREAM).value),t(6,u=s.get(M.API_KEY).value),u.length==0&&await He("请先填写api-key"),t(7,d=s.get(M.BASE_URL).value),t(8,c=s.get(M.TIMEOUT).value),E.model.includes("gpt")&&(t(5,l=new Tn(u,d,c)),l.completion(E.model,r,E.prompt,E.temperature,h,a)),(E.model.includes("dall")||E.model.includes("DALL"))&&(t(5,l=new Tn(u,d,c)),l.imgGenerate(E.model,E.prompt,E.imgNum,E.imgSize,E.imgQuality,a)),o.destroy()},C=E=>{const b=new de.Dialog({width:"35%",content:'
'});E.imgQuality?new zi({target:b.element.querySelector("#newDialog"),props:{dialog:b,lastNodeId:a,storageSettings:s,storagePrompts:i,promptItem:E}}):new Ji({target:b.element.querySelector("#newDialog"),props:{dialog:b,lastNodeId:a,selectedContent:r,storageSettings:s,storagePrompts:i,promptItem:E}}),o.destroy()};return n.$$set=E=>{"selectedContent"in E&&t(0,r=E.selectedContent),"storageSettings"in E&&t(1,s=E.storageSettings),"storagePrompts"in E&&t(2,i=E.storagePrompts),"dialog"in E&&t(3,o=E.dialog),"lastNodeId"in E&&t(4,a=E.lastNodeId)},[r,s,i,o,a,l,u,d,c,h,g,f,p,m,A,P,C]}class oc extends xe{constructor(e){super(),Me(this,e,ic,rc,Oe,{selectedContent:0,storageSettings:1,storagePrompts:2,dialog:3,lastNodeId:4})}}class ac{constructor(e,t,r){V(this,"_storageSettings");V(this,"_storagePrompts");V(this,"_plugin");this._storageSettings=t,this._storagePrompts=r,this._plugin=e}async contentGenerate(){}async onload(){}async blockIconEvent(e){let t=await nl(e.blockElements),r=e.blockElements.at(-1).dataset.nodeId;window.siyuan.menus.menu.addItem({iconHTML:"📃 ",label:"文本生成",click:async()=>{const s=new de.Dialog({width:"35%",content:'
'});new Ji({target:s.element.querySelector("#NewPrompt"),props:{dialog:s,lastNodeId:r,selectedContent:t,storageSettings:this._storageSettings,storagePrompts:this._storagePrompts,promptItem:{model:"",title:"",prompt:""}}})}}),window.siyuan.menus.menu.addItem({iconHTML:"🏞️ ",label:"文  生  图",click:async()=>{const s=new de.Dialog({width:"35%",content:'
'});new zi({target:s.element.querySelector("#ImageGenerate"),props:{dialog:s,lastNodeId:r,storageSettings:this._storageSettings,storagePrompts:this._storagePrompts,promptItem:{model:"",title:"",prompt:""}}})}}),window.siyuan.menus.menu.addItem({iconHTML:"🌈 ",label:"Prompts",click:async()=>{const s=new de.Dialog({width:"25%",content:'
'});new oc({target:s.element.querySelector("#PromptPanel"),props:{dialog:s,lastNodeId:r,selectedContent:t,storageSettings:this._storageSettings,storagePrompts:this._storagePrompts}})}}),window.siyuan.menus.menu.addSeparator()}}class lc extends de.Plugin{constructor(t){super(t);V(this,"blockIconEventBindThis");V(this,"_storageSettings");V(this,"_storagePrompts");V(this,"_isMobile");V(this,"_contentGenerate");this.setting=new de.Setting({}),this._storageSettings=new ll(this,Je.AI_SETTING_STORAGE),this._storagePrompts=new al(this,Je.AI_PROMPT_STORAGE),this._isMobile=de.getFrontend()==="mobile"||de.getFrontend()==="browser-mobile",this._contentGenerate=new ac(this,this._storageSettings,this._storagePrompts),this.blockIconEventBindThis=this.blockIconEvent.bind(this)}async blockIconEvent({detail:t}){this._contentGenerate.blockIconEvent(t)}onload(){this._storageSettings.load(),this._storagePrompts.load(),this._contentGenerate.onload(),this.eventBus.on(zs.click_blockicon,this.blockIconEventBindThis)}onLayoutReady(){}async uninstall(){await this._storagePrompts.deleteStorageFile(),await this._storageSettings.deleteStorageFile(),He("文件已删除,AI插件已卸载,bye~~")}openSetting(){if(this.setting)if(this._isMobile)Ue("手机端AI插件开发中,敬请期待!");else{let t=new de.Dialog({title:"思源AI",width:"50%",height:"60%",content:'
'});new yl({target:t.element.querySelector("#AISettingPanel"),props:{storageSettings:this._storageSettings,dialog:t}})}}}module.exports=lc; diff --git a/plugin.json b/plugin.json index 4f5b48e..357fe2e 100644 --- a/plugin.json +++ b/plugin.json @@ -2,7 +2,7 @@ "name": "siyuan-ai", "author": "lizhen", "url": "https://github.com/Lizhen0628/siyuan-ai", - "version": "0.0.25", + "version": "0.0.26", "minAppVersion": "3.0.0", "backends": [ "windows",