@dhzh/foundry 6.3.0 → 6.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/dist/web/assets/{BottomSheet-BFGTK8Fb.js → BottomSheet-Bs6VGQRD.js} +1 -1
- package/dist/web/assets/{ItemSwipeLayer-C8uG5Wte.js → ItemSwipeLayer-N9jsy2FE.js} +1 -1
- package/dist/web/assets/{MenuBottomSheet-CIOl4-qj.js → MenuBottomSheet-B4cYS_67.js} +1 -1
- package/dist/web/assets/{index-D2I6J0FK.js → index-DgKRKmzj.js} +15 -15
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{defineCommand as e,runMain as t,showUsage as n}from"citty";import{setTimeout as r}from"node:timers/promises";import{chmod as i,copyFile as a,cp as o,link as s,mkdir as c,open as l,readFile as u,readdir as d,rename as f,rm as p,stat as m,writeFile as h}from"node:fs/promises";import g from"node:process";import{createCipheriv as _,createDecipheriv as v,createHash as ee,randomBytes as te,randomUUID as y,scrypt as ne}from"node:crypto";import{FirecrawlClient as re}from"firecrawl";import{parse as ie}from"tldts";import{chmodSync as ae,closeSync as oe,createReadStream as b,createWriteStream as se,existsSync as x,fsyncSync as ce,mkdirSync as S,openSync as le,readFileSync as C,readdirSync as ue,renameSync as de,rmSync as w,rmdirSync as fe,statSync as T,writeFileSync as pe}from"node:fs";import E from"node:path";import{pipeline as D}from"node:stream/promises";import me from"yauzl";import he from"yazl";import{Buffer as O}from"node:buffer";import{Readable as ge,Transform as _e}from"node:stream";import{matchedRoutes as ve}from"hono/route";import{spawn as ye}from"node:child_process";import be,{homedir as xe}from"node:os";import{fileURLToPath as Se}from"node:url";import{StringDecoder as Ce}from"node:string_decoder";import{createZstdDecompress as we}from"node:zlib";import{serve as Te}from"@hono/node-server";import{serveStatic as Ee}from"@hono/node-server/serve-static";import{Hono as k}from"hono";import{streamSSE as De}from"hono/streaming";import{createServer as Oe}from"node:net";var ke=`6.3.0`;function Ae(e){if(!Pe(e)||typeof e.url!=`string`)throw new Ne(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function je(e){return e===`no-successful`?`no-successful`:`all`}function Me(e){if(!Pe(e)||typeof e.userNote!=`string`)throw new Ne(`userNote must be a string`);return e.userNote}var Ne=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function Pe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var A=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}},Fe=class{storage;constructor(e){this.storage=e}findCapture(e){let t=this.storage.get(`captures`,e);return t&&!t.deletedAt?t:null}newJob(e,t){let n=(/* @__PURE__ */ new Date()).toISOString();return{id:y(),captureId:e,fetcher:t.fetcher,configSnapshot:t,rawResponse:null,creditsUsed:null,status:`pending`,errorCode:null,errorMessage:null,createdAt:n,updatedAt:n,deletedAt:null}}list(e){return this.storage.all(`captures`).filter(t=>!t.deletedAt&&(e!==`no-successful`||!t.latestSuccessfulJobId)).toSorted((e,t)=>t.createdAt.localeCompare(e.createdAt)).map(e=>Ie(e))}counts(){let e=this.storage.all(`captures`).filter(e=>!e.deletedAt);return{all:e.length,noSuccessful:e.filter(e=>!e.latestSuccessfulJobId).length}}get(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return null;let n=t.latestSuccessfulJobId?this.storage.get(`fetchJobs`,t.latestSuccessfulJobId):void 0;return{capture:Ie(t),rawResponse:n?.captureId===e&&!n.deletedAt?n.rawResponse:null}})}findActiveByURL(e){return this.storage.all(`captures`).find(t=>t.url===e&&!t.deletedAt)??null}createWithJob(e,t,n){return this.storage.transaction(()=>{if(this.findActiveByURL(e))throw new A(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:y(),url:e,title:null,userNote:t,latestSuccessfulJobId:null,createdAt:r,updatedAt:r,deletedAt:null},a=this.newJob(i.id,n);return this.storage.put(`captures`,i),this.storage.put(`fetchJobs`,a),{capture:Ie(i),jobId:a.id}})}hasActiveJob(e){return this.storage.all(`fetchJobs`).some(t=>t.captureId===e&&!t.deletedAt&&[`pending`,`running`].includes(t.status))}createJob(e,t){return this.storage.transaction(()=>{if(!this.findCapture(e))throw new A(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new A(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:Le(n),jobId:n.id}})}delete(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return!1;if(this.hasActiveJob(e))throw new A(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=(/* @__PURE__ */ new Date()).toISOString();this.storage.put(`captures`,{...t,deletedAt:n,updatedAt:n});for(let t of this.storage.all(`fetchJobs`))t.captureId===e&&!t.deletedAt&&this.storage.put(`fetchJobs`,{...t,deletedAt:n,updatedAt:n});return!0})}updateNote(e,t){return this.storage.transaction(()=>{let n=this.findCapture(e);if(!n)return null;let r={...n,userNote:t.trim()||null,updatedAt:(/* @__PURE__ */ new Date()).toISOString()};return this.storage.put(`captures`,r),Ie(r)})}listJobs(e){return this.storage.all(`fetchJobs`).filter(t=>t.captureId===e&&!t.deletedAt).toSorted((e,t)=>t.createdAt.localeCompare(e.createdAt)).map(e=>Le(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?Le(n.job):null}getJobContext(e){return this.storage.transaction(()=>{let t=this.storage.get(`fetchJobs`,e);if(!t||t.deletedAt)return null;let n=this.findCapture(t.captureId);return n?{job:t,capture:n}:null})}markRunning(e){this.storage.transaction(()=>{let t=this.storage.get(`fetchJobs`,e);t?.status===`pending`&&this.storage.put(`fetchJobs`,{...t,status:`running`,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})})}markSucceeded(e,t,n,r,i){this.storage.transaction(()=>{let a=this.storage.get(`fetchJobs`,e),o=this.findCapture(t);if(!a||!o||a.captureId!==t)throw Error(`Invalid capture job`);let s=(/* @__PURE__ */ new Date()).toISOString();this.storage.put(`fetchJobs`,{...a,status:`succeeded`,rawResponse:r,creditsUsed:i,errorCode:null,errorMessage:null,updatedAt:s}),this.storage.put(`captures`,{...o,...n&&{title:n},latestSuccessfulJobId:e,updatedAt:s})})}markFailed(e,t,n){this.storage.transaction(()=>{let r=this.storage.get(`fetchJobs`,e);r&&this.storage.put(`fetchJobs`,{...r,status:`failed`,creditsUsed:null,errorCode:t,errorMessage:n,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})})}recoverRunningJobs(){return this.storage.transaction(()=>{let e=this.storage.all(`fetchJobs`).filter(e=>e.status===`running`&&!e.deletedAt);for(let t of e)this.storage.put(`fetchJobs`,{...t,status:`pending`});return e.length})}pendingJobIDs(){return this.storage.all(`fetchJobs`).filter(e=>e.status===`pending`&&!e.deletedAt).toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt)).map(e=>e.id)}};function Ie(e){let{deletedAt:t,...n}=e;return n}function Le(e){return{id:e.id,captureId:e.captureId,status:e.status,fetcher:e.fetcher,creditsUsed:e.creditsUsed,errorCode:e.errorCode,errorMessage:e.errorMessage,createdAt:e.createdAt,updatedAt:e.updatedAt}}const Re=[`system`,`light`,`dark`],ze=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Be=[`YYYY-MM-DD HH:mm:ss`,`YYYY-MM-DD`,`YYYY/MM/DD HH:mm:ss`,`DD/MM/YYYY HH:mm:ss`,`MM/DD/YYYY hh:mm:ss A`,`HH:mm:ss`],Ve=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],He=[`firecrawl`],j={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}},features:{library:{captures:{fetcher:null,maxAttempts:1,fetchConcurrency:2,firecrawl:{apiKey:``}}}}};function Ue(e){let t=P(e)?e:{},n=P(t.workspace)?t.workspace:{},r=P(n.appearance)?n.appearance:{},i=P(n[`language-region`])?n[`language-region`]:{},a=P(t.features)?t.features:{},o=P(a.library)?a.library:{},s=P(o.captures)?o.captures:{},c=P(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":Xe(r[`color-theme`],Re,j.workspace.appearance[`color-theme`])},"language-region":{language:Xe(i.language,ze,j.workspace[`language-region`].language),"time-format":Xe(i[`time-format`],Be,j.workspace[`language-region`][`time-format`]),"time-zone":Xe(i[`time-zone`],Ve,j.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:Je(s.fetcher),maxAttempts:Ze(s.maxAttempts,10,1),fetchConcurrency:Ze(s.fetchConcurrency,5,2),firecrawl:{apiKey:et(c.apiKey)}}}}}}function We(e){if(!P(e))throw new M(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=N(e.theme,Re,`theme`)),`language`in e&&(t.language=N(e.language,ze,`language`)),`timeFormat`in e&&(t.timeFormat=N(e.timeFormat,Be,`timeFormat`)),`timezone`in e&&(t.timezone=N(e.timezone,Ve,`timezone`)),`captures`in e&&(t.captures=qe(e.captures)),t}function Ge(e,t){let n=e.features.library.captures,r=t.captures;return{workspace:{appearance:{"color-theme":t.theme??e.workspace.appearance[`color-theme`]},"language-region":{language:t.language??e.workspace[`language-region`].language,"time-format":t.timeFormat??e.workspace[`language-region`][`time-format`],"time-zone":t.timezone??e.workspace[`language-region`][`time-zone`]}},features:{...e.features,library:{...e.features.library,captures:{...n,fetcher:r?.fetcher===void 0?n.fetcher:r.fetcher,maxAttempts:r?.maxAttempts??n.maxAttempts,fetchConcurrency:r?.fetchConcurrency??n.fetchConcurrency,firecrawl:{apiKey:r?.firecrawlApiKey??n.firecrawl.apiKey}}}}}}function Ke(e){let t=e.features.library.captures;return{workspace:e.workspace,features:{...e.features,library:{...e.features.library,captures:{fetcher:t.fetcher,maxAttempts:t.maxAttempts,fetchConcurrency:t.fetchConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey}}}}}}var M=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function qe(e){if(!P(e))throw new M(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:N(e.fetcher,He,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=Qe(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=Qe(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=$e(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function Je(e){return Ye(e,He)}function Ye(e,t){return typeof e==`string`&&t.includes(e)?e:null}function Xe(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function N(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new M(`Invalid ${n}`);return e}function Ze(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function Qe(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new M(`${n} must be an integer from 1 to ${t}`);return e}function $e(e,t){if(typeof e!=`string`)throw new M(`${t} must be a string`);return e.trim()}function et(e){return typeof e==`string`?e:``}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return e.readSettings()}function tt(e){return Ke(F(e))}function nt(e,t){return t.transaction(()=>{let n=Ge(F(t),e);return t.setSettings(n),Ke(n)})}var I=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function rt(e){if(e instanceof I)return e;let t=it(e);return t===null?st(e)?new I(`timeout`,`The configured fetcher timed out`):ct(e)?new I(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new I(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new I(`http_${t}`,at(e)??`The configured fetcher returned ${t}`,t)}function it(e){if(!L(e))return null;let t=lt(e.status);return t===null?L(e.response)?lt(e.response.status):null:t}function at(e){if(!L(e))return null;if(L(e.response)){let t=ot(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:ot(e.details)}function ot(e){return L(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function st(e){if(!(e instanceof Error))return!1;let t=ut(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function ct(e){if(e instanceof TypeError)return!0;if(!L(e))return!1;let t=ut(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!L(e.response)}function lt(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function ut(e){let t=e.code;return typeof t==`string`?t:null}function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var dt=class extends re{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function ft(e,t,n={}){let r=new dt({apiKey:e,maxRetries:Math.max(1,Math.trunc(t)),...n.apiUrl&&{apiUrl:n.apiUrl},...n.backoffFactor!==void 0&&{backoffFactor:n.backoffFactor}});return{search:e=>r.searchEnvelope(e)}}async function pt(e,t,n=1,r=ft(t,n)){try{let t=mt(e),n=await r.search(ht(t));if(!R(n))throw new I(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new I(`fetcher_error`,jt(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new I(`invalid_response`,`The configured fetcher returned an invalid response`);let i=At(n);if(i===null)throw new I(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=Ct(e,St(n));return{title:a?Ot(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw rt(e)}}function mt(e){return{query:gt(e),limit:5,sources:[`web`],highlights:!1,ignoreInvalidURLs:!0,timeout:12e4,pageOptions:{formats:[`summary`],onlyMainContent:!0,onlyCleanContent:!1,maxAge:1728e5,timeout:6e4,removeBase64Images:!0,blockAds:!0,proxy:`auto`,storeInCache:!0}}}function ht(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function gt(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=_t(t.pathname),i=xt(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function _t(e){let t=e.split(`/`).map(e=>vt(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||bt(n))continue;let r=yt(n);if(r)return r}return null}function vt(e){try{return decodeURIComponent(e)}catch{return e}}function yt(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function bt(e){return/^(?:index|home|latest)$/i.test(e)||/^\d+$/.test(e)||/^v?\d+(?:\.\d+)+$/i.test(e)||/^[a-z]{2}(?:[-_][a-z]{2})?$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(e)||/^[0-9a-f]{20,}$/i.test(e)}function xt(e){return ie(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function St(e){return!R(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!R(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:R(e.metadata)?e.metadata:{}}])}function Ct(e,t){let n=Tt(e);if(n){let e=t.find(e=>wt(e).some(e=>Tt(e)===n));if(e)return e}let r=Et(e),i=r===null?[]:t.filter(e=>wt(e).some(e=>Et(e)===r));return i.find(e=>Dt(e))??(i.length>0?i[0]:null)}function wt(e){return[e.url,kt(e,`sourceURL`),kt(e,`url`)].filter(e=>!!e)}function Tt(e){try{let t=new URL(e);return t.hash=``,t.searchParams.sort(),t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)),t.href}catch{return null}}function Et(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function Dt(e){return wt(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function Ot(e){return e.title?.trim()||kt(e,`ogTitle`)?.trim()||kt(e,`title`)?.trim()||null}function kt(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function At(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function jt(e){return R(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function R(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mt(e,t){return pt(e,t.apiKey,t.maxAttempts)}var Nt=class{repository;storage;onChanged;fetchCaptureImplementation;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;paused=!1;constructor(e,t,n=()=>{},r=Mt){this.repository=e,this.storage=t,this.onChanged=n,this.fetchCaptureImplementation=r}schedule(){if(this.paused)return;let e=F(this.storage).features.library.captures.fetchConcurrency;for(;this.runningCount<e&&this.queue.length>0;){let e=this.queue.shift();if(!e)return;this.runningCount+=1,this.runJob(e).finally(()=>{--this.runningCount,this.knownJobIDs.delete(e),this.schedule()})}}async runJob(e){let t=this.repository.getJobContext(e);if(!t||t.job.status!==`pending`&&t.job.status!==`running`)return;let n;try{n=Pt(t.job.configSnapshot)}catch(n){let r=n instanceof Error?n.message:`Invalid fetch job configuration`;this.failJob(e,t.job.captureId,`invalid_config`,r);return}this.repository.markRunning(e),this.onChanged({captureId:t.capture.id,jobId:e,status:`running`});try{let r=await this.fetchCaptureImplementation(t.capture.url,n);this.repository.markSucceeded(e,t.capture.id,r.title,r.rawResponse,r.creditsUsed),this.onChanged({captureId:t.capture.id,jobId:e,status:`succeeded`})}catch(n){let r=rt(n);this.failJob(e,t.capture.id,r.code,r.message)}}failJob(e,t,n,r){this.repository.markFailed(e,n,r),this.onChanged({captureId:t,jobId:e,status:`failed`,errorMessage:r})}start(){this.repository.recoverRunningJobs();for(let e of this.repository.pendingJobIDs())this.enqueue(e)}enqueue(e){if(this.knownJobIDs.has(e))return;let t=this.repository.getJobContext(e);t&&(this.knownJobIDs.add(e),this.queue.push(e),this.onChanged({captureId:t.capture.id,jobId:e,status:`pending`}),this.schedule())}notifySettingsChanged(){this.schedule()}pause(){this.paused=!0}resume(){this.paused=!1,this.schedule()}};function Pt(e){let t=e;if(!Ft(t)||t.fetcher!==`firecrawl`||typeof t.apiKey!=`string`||!t.apiKey||typeof t.maxAttempts!=`number`)throw Error(`Invalid fetch job configuration`);return{fetcher:t.fetcher,apiKey:t.apiKey,maxAttempts:Math.min(10,Math.max(1,Math.trunc(t.maxAttempts)))}}function Ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var It=class{repository;storage;runner;constructor(e,t,n){this.repository=e,this.storage=t,this.runner=n}executionConfig(){let e=F(this.storage).features.library.captures;if(!e.fetcher)return null;let t=e[e.fetcher].apiKey.trim();return t?{fetcher:e.fetcher,apiKey:t,maxAttempts:e.maxAttempts}:null}list(e){return this.repository.list(e)}counts(){return this.repository.counts()}get(e){let t=this.repository.get(e);if(!t)throw new A(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=Lt(e.url);if(!t)throw new A(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new A(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new A(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before adding a capture`);try{let r=this.repository.createWithJob(t,e.userNote?.trim()||null,n);return this.runner.enqueue(r.jobId),r.capture}catch(e){throw this.repository.findActiveByURL(t)?new A(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new A(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new A(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before re-capturing`);let n=this.repository.createJob(e,t);return this.runner.enqueue(n.jobId),n.job}delete(e){if(this.get(e),this.repository.hasActiveJob(e))throw new A(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new A(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new A(`CAPTURE_NOT_FOUND`,`Capture not found`);return n}listJobs(e){return this.get(e),this.repository.listJobs(e)}getJob(e,t){return this.get(e),this.repository.getJob(e,t)}};function Lt(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function Rt(e,t,n){let r=new Fe(e),i=new Nt(r,e,e=>t?.publish(`capture.job.changed`,e),n);return{service:new It(r,e,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}const zt=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Bt=[`active`,`disabled`,`deleted`];var z=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},Vt=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function B(e){if(!Jt(e))throw new z(`Provider input must be an object`);let t=V(e.name,`name`),n=Kt(e.protocol),r=qt(e.baseURL),i=e.apiKey===void 0?``:V(e.apiKey,`apiKey`,{allowEmpty:!0}),a=Gt(e.customModels);return{...e.avatar!==void 0&&{avatar:Ht(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Ht(e){if(e===null)return null;if(typeof e==`string`&&e.length<=2796236){let t=/^data:image\/(?:png|jpeg|gif|webp|svg\+xml);base64,/u.exec(e);if(t){let n=e.slice(t[0].length),r=n.endsWith(`==`)?2:+!!n.endsWith(`=`);if(n.length>0&&n.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/u.test(n)&&n.length/4*3-r<=2097152)return e}}throw new z(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Ut(e){if(!Jt(e))throw new z(`Provider connection must be an object`);return{protocol:Kt(e.protocol),baseURL:qt(e.baseURL),apiKey:e.apiKey===void 0?``:V(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Wt(e){if(typeof e!=`string`||!Bt.includes(e))throw new z(`Invalid provider status`);return e}function Gt(e){if(e===void 0)return[];if(!Array.isArray(e))throw new z(`customModels must be an array`);return e.map(e=>{if(!Jt(e))throw new z(`Each custom model must be an object`);return{id:V(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:V(e.displayName,`customModels.displayName`)}})}function Kt(e){if(typeof e!=`string`||!zt.includes(e))throw new z(`Invalid provider protocol`);return e}function qt(e){let t=V(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new z(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function V(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new z(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new z(`${t} is required`);return r}function Jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function H(e,t){if(!e)throw Error(t)}function Xt(e){return e===null||typeof e==`string`}function Zt(e){H(Yt(e)&&e.formatVersion===1,`Unsupported Foundry JSON data format`),H(Yt(e.settings),`Invalid settings`),Ue(e.settings);for(let t of[`providers`,`captures`,`fetchJobs`]){let n=e[t];H(Array.isArray(n),`Invalid storage collection`);let r=/* @__PURE__ */ new Set;for(let e of n)H(Yt(e)&&typeof e.id==`string`&&e.id.length>0&&e.id.length<=200&&!r.has(e.id),`Invalid or duplicate record ID`),r.add(e.id),H(typeof e.createdAt==`string`&&Number.isFinite(Date.parse(e.createdAt))&&typeof e.updatedAt==`string`&&Number.isFinite(Date.parse(e.updatedAt)),`Invalid record timestamp`),H(e.deletedAt===null||typeof e.deletedAt==`string`&&Number.isFinite(Date.parse(e.deletedAt)),`Invalid deletion timestamp`)}let t=e;for(let e of t.providers)try{H([`active`,`disabled`,`deleted`].includes(e.status),`Invalid status`),H(typeof e.apiKey==`string`,`Invalid API key`),B(e)}catch{throw Error(`A provider record is invalid`)}let n=/* @__PURE__ */ new Set,r=new Map(t.captures.map(e=>[e.id,e])),i=new Map(t.fetchJobs.map(e=>[e.id,e]));for(let e of t.captures){try{H([`http:`,`https:`].includes(new URL(e.url).protocol),`Invalid protocol`)}catch{throw Error(`A capture URL is invalid`)}if(H(Xt(e.title)&&Xt(e.userNote)&&Xt(e.latestSuccessfulJobId),`A capture record is invalid`),e.deletedAt||(H(!n.has(e.url),`Duplicate active capture URL`),n.add(e.url),!e.latestSuccessfulJobId))continue;let t=i.get(e.latestSuccessfulJobId);H(t?.captureId===e.id&&t.status===`succeeded`&&!t.deletedAt,`A capture points to an invalid successful fetch job`)}let a=/* @__PURE__ */ new Set;for(let e of t.fetchJobs)H(r.has(e.captureId)&&[`pending`,`running`,`succeeded`,`failed`].includes(e.status)&&e.fetcher===`firecrawl`,`A fetch job record is invalid`),H(Yt(e.configSnapshot),`A fetch job configuration is invalid`),H(e.creditsUsed===null||typeof e.creditsUsed==`number`&&Number.isFinite(e.creditsUsed),`A fetch job credit value is invalid`),H(Xt(e.errorCode)&&Xt(e.errorMessage),`A fetch job record is invalid`),!e.deletedAt&&[`pending`,`running`].includes(e.status)&&(H(!a.has(e.captureId),`Duplicate active fetch jobs`),a.add(e.captureId))}var U=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`DataTransferError`}};function Qt(e){return e instanceof U?e:new U(`IO_ERROR`,e instanceof Error?e.message:`The data transfer failed`,{cause:e})}const W=`data/foundry.json`,$t=`manifest.json`;function en(e){if(!on(e)||e.format!==`foundry.snapshot`)throw new U(`INVALID_ARCHIVE`,`The file is not a Foundry export`);let t=an(e.archiveVersion,`archiveVersion`);if(t!==3)throw new U(`UNSUPPORTED_ARCHIVE`,`The archive version is not supported`);let n=rn(e.createdAt,`createdAt`);if(Number.isNaN(Date.parse(n)))throw new U(`INVALID_ARCHIVE`,`createdAt is invalid`);if(!on(e.data)||e.database!==void 0||e.settings!==void 0)throw new U(`INVALID_ARCHIVE`,`JSON data metadata is invalid`);return{format:`foundry.snapshot`,archiveVersion:t,appVersion:rn(e.appVersion,`appVersion`),createdAt:n,data:{...nn(e.data,W),formatVersion:an(e.data.formatVersion,`data.formatVersion`)}}}function tn(e){return e.toLowerCase().endsWith(`.foundry-backup`)?e:`${e}.foundry-backup`}function nn(e,t){if(!on(e)||e.path!==t)throw new U(`INVALID_ARCHIVE`,`File metadata path is invalid`);let n=rn(e.sha256,`sha256`);if(!/^[a-f0-9]{64}$/u.test(n))throw new U(`INVALID_ARCHIVE`,`File checksum is invalid`);return{path:t,bytes:an(e.bytes,`bytes`),sha256:n}}function rn(e,t){if(typeof e!=`string`||e.length===0)throw new U(`INVALID_ARCHIVE`,`${t} must be a non-empty string`);return e}function an(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new U(`INVALID_ARCHIVE`,`${t} must be a non-negative integer`);return e}function on(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const sn=/* @__PURE__ */ new Set([$t,W]);async function cn(e,t){let n=new he.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await D(n.outputStream,se(t,{mode:384}))}async function ln(e,t){let n=await un(e),r=/* @__PURE__ */ new Map,i=0;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!sn.has(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);if(e.fileName.endsWith(`/`)||r.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let a=e.fileName===`manifest.json`?1048576:4294967296;if(i+=e.uncompressedSize,e.uncompressedSize>a||i>4294967296)throw Error(`The Foundry archive is too large`);let o=E.join(t,e.fileName);await c(E.dirname(o),{recursive:!0}),await D(await dn(n,e),se(o,{mode:384})),r.set(e.fileName,o),n.readEntry()};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await p(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!r.has(`manifest.json`)||!r.has(`data/foundry.json`))throw await p(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function un(e){return new Promise((t,n)=>{me.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function dn(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}const G=O.from(`FOUNDRYX`,`ascii`),fn=`aes-256-gcm`,pn=`scrypt`,mn={N:131072,r:8,p:1};async function hn(e,t,n){let r=te(16),a=te(12),o={version:1,cipher:fn,kdf:{name:pn,salt:r.toString(`base64`),...mn,keyLength:32},nonce:a.toString(`base64`)},s=O.from(JSON.stringify(o),`utf8`),c=_n(s.byteLength),u=O.concat([c,s]),d=await vn(n,r,mn);try{let n=await l(t,`w`,384);try{await n.write(u)}finally{await n.close()}await D(b(e),yn(d,a,u),se(t,{flags:`r+`,mode:384,start:u.byteLength})),await i(t,384)}catch(e){throw await p(t,{force:!0}),new U(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function gn(e,t,n){let r;try{let a=(await m(e)).size;if(a<=29)throw Error(`The export file is incomplete`);let o=await l(e,`r`),s,c,u;try{if(s=await Sn(o,13,0),!s.subarray(0,G.byteLength).equals(G))throw Error(`The export file signature is invalid`);if(s.readUInt8(G.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=s.readUInt32BE(G.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(a<=13+e+16)throw Error(`The export file is incomplete`);c=await Sn(o,e,13),u=await Sn(o,16,a-16)}finally{await o.close()}let d=xn(JSON.parse(c.toString(`utf8`)));r=await vn(n,d.salt,d.header.kdf);let f=O.concat([s,c]);await D(b(e,{start:13+c.byteLength,end:a-16-1}),bn(r,d.nonce,f,u),se(t,{mode:384})),await i(t,384)}catch(e){throw await p(t,{force:!0}),e instanceof U?e:new U(`INVALID_PASSPHRASE`,`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function _n(e){let t=O.alloc(13);return G.copy(t,0),t.writeUInt8(1,G.byteLength),t.writeUInt32BE(e,G.byteLength+1),t}function vn(e,t,n){return new Promise((r,i)=>{ne(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function yn(e,t,n){let r=_(fn,e,t,{authTagLength:16});return r.setAAD(n),new _e({transform(e,t,n){try{n(null,r.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{e(null,O.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function bn(e,t,n,r){let i=v(fn,e,t,{authTagLength:16});return i.setAAD(n),new _e({transform(e,t,n){try{n(null,i.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{i.setAuthTag(r),e(null,i.final())}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function xn(e){if(!Cn(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==fn||!Cn(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==pn||typeof t.salt!=`string`||t.N!==mn.N||t.r!==mn.r||t.p!==mn.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=O.from(t.salt,`base64`),r=O.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:fn,kdf:{name:pn,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Sn(e,t,n){let r=O.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Cn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var wn=class{storage;runner;temporaryRoot;appVersion;workspaceMutationGate;onStatusChanged;busy=!1;stagedImports=/* @__PURE__ */ new Map;constructor(e,t,n,r,i,a=()=>{}){this.storage=e,this.runner=t,this.temporaryRoot=n,this.appVersion=r,this.workspaceMutationGate=i,this.onStatusChanged=a}async runExclusive(e){if(this.busy||!this.workspaceMutationGate.tryBeginTransfer())throw new U(`BUSY`,`Another data transfer is in progress`);this.busy=!0;try{return this.onStatusChanged(this.getStatus()),await e()}finally{this.busy=!1,this.workspaceMutationGate.endTransfer(),this.onStatusChanged(this.getStatus())}}async createWorkDirectory(e){await c(this.temporaryRoot,{recursive:!0,mode:448}),await jn(this.temporaryRoot);let t=E.join(this.temporaryRoot,`${e}-${y()}`);return await c(t,{mode:448}),await jn(t),t}async removeQuietly(e){try{await p(e,{recursive:!0,force:!0})}catch{}}async createUploadTarget(){let e=await this.createWorkDirectory(`upload`);return{filePath:E.join(e,`archive.foundry-backup`),cleanup:()=>this.removeQuietly(e)}}cleanupStaleTransfers(){w(this.temporaryRoot,{recursive:!0,force:!0}),S(this.temporaryRoot,{recursive:!0,mode:448}),this.stagedImports.clear()}getStatus(){return{activeJobCount:this.storage.all(`fetchJobs`).filter(e=>En(e)).length,isBusy:this.busy}}async createExport(e){return Tn(e),this.runExclusive(async()=>{let t=await this.createWorkDirectory(`export`),n=E.join(t,`foundry.json`),r=E.join(t,$t),i=E.join(t,`foundry.zip`),a=E.join(this.temporaryRoot,`foundry-${y()}.foundry-backup`);this.runner.pause();try{let t=this.storage.snapshot();Dn(t),Zt(t),await h(n,JSON.stringify(t),{mode:384});let o={format:`foundry.snapshot`,archiveVersion:3,appVersion:this.appVersion,createdAt:(/* @__PURE__ */ new Date()).toISOString(),data:{...await kn(n,W),formatVersion:1}};return await h(r,JSON.stringify(o,null,2),{mode:384}),await cn([{entryPath:$t,filePath:r},{entryPath:W,filePath:n}],i),await hn(i,a,e),{filePath:a,...On(t)}}finally{this.runner.resume(),await this.removeQuietly(t)}})}async inspectImport(e,t,n=E.basename(e)){return Tn(t),this.runExclusive(async()=>{Dn(this.storage.snapshot());let r=this.stagedImports.values().toArray();this.stagedImports.clear(),await Promise.all(r.map(e=>this.removeQuietly(e.directory)));let i=y(),a=await this.createWorkDirectory(`import-${i}`),o=E.join(a,`archive.zip`);try{await gn(e,o,t);let r=await ln(o,E.join(a,`extracted`)),s=en(JSON.parse(await u(r[$t],`utf8`)));if(s.data.formatVersion>1)throw new U(`NEWER_SCHEMA`,`The archive was created by a newer Foundry version`);let c=/* @__PURE__ */ new Set([$t,W]);await An(r[W],s.data);let l=JSON.parse(await u(r[W],`utf8`));if(Zt(l),l.formatVersion!==s.data.formatVersion)throw new U(`INVALID_ARCHIVE`,`The JSON data format does not match its manifest`);if(Object.keys(r).some(e=>!c.has(e)))throw new U(`INVALID_ARCHIVE`,`Unexpected archive file`);Dn(l);let d=E.join(a,`staged.json`);await h(d,JSON.stringify(l),{mode:384});let f={importId:i,fileName:E.basename(n),exportedAt:s.createdAt,appVersion:s.appVersion,dataFormatVersion:l.formatVersion,settingsVersion:1,...On(l)};return this.stagedImports.set(i,{snapshotPath:d,directory:a,preview:f}),await p(o,{force:!0}),f}catch(e){throw await this.removeQuietly(a),e instanceof U?e:new U(`INVALID_ARCHIVE`,e instanceof Error?e.message:`The Foundry export could not be inspected`,{cause:e})}})}async cancelImport(e){let t=this.stagedImports.get(e);t&&(this.stagedImports.delete(e),await this.removeQuietly(t.directory))}async commitImport(e){let t=this.stagedImports.get(e);if(!t)throw new U(`IMPORT_NOT_FOUND`,`The import session has expired`);return this.runExclusive(async()=>{this.runner.pause();try{let n=JSON.parse(await u(t.snapshotPath,`utf8`));Zt(n),Dn(n),this.storage.transaction(()=>{Dn(this.storage.snapshot()),this.storage.replace(n)}),this.stagedImports.delete(e),await this.removeQuietly(t.directory)}finally{this.runner.resume(),this.runner.notifySettingsChanged()}})}async removeExportFile(e){E.dirname(e)===this.temporaryRoot&&await p(e,{force:!0})}};function Tn(e){if(!e)throw new U(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}function En(e){return!e.deletedAt&&[`pending`,`running`].includes(e.status)}function Dn(e){if(e.fetchJobs.some(e=>En(e)))throw new U(`ACTIVE_JOBS`,`Finish active fetch jobs before transferring data`)}function On(e){return{providerCount:e.providers.length,captureCount:e.captures.length,jobCount:e.fetchJobs.length}}async function kn(e,t){let n=ee(`sha256`);for await(let t of b(e))n.update(t);return{path:t,bytes:(await m(e)).size,sha256:n.digest(`hex`)}}async function An(e,t){let n=await kn(e,t.path);if(n.bytes!==t.bytes||n.sha256!==t.sha256)throw new U(`INVALID_ARCHIVE`,`An archived file failed its integrity validation`)}function jn(e){return g.platform===`win32`?Promise.resolve():i(e,448)}const Mn=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var Nn=class{transferActive=!1;get isTransferActive(){return this.transferActive}tryBeginTransfer(){return!this.transferActive&&(this.transferActive=!0,!0)}endTransfer(){this.transferActive=!1}};function Pn(e){return async(t,n)=>{if(e.isTransferActive&&Mn.has(t.req.method)&&!t.req.path.startsWith(`/api/data-transfer/`)&&Fn(t))return t.json({error:{code:`DATA_TRANSFER_BUSY`,message:`Another data transfer is in progress`}},409);await n()}}function Fn(e){return ve(e).some(e=>e.path.startsWith(`/api/`)&&e.path!==`/api/*`)}var K=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function In(e,t=fetch){let n={accept:`application/json`};e.protocol===`anthropic-messages`?(n[`anthropic-version`]=`2023-06-01`,e.apiKey&&(n[`x-api-key`]=e.apiKey)):n.authorization=`Bearer ${e.apiKey||`local-provider`}`;let r;try{r=await t(Ln(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new K(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new K(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new K(`Provider returned invalid JSON`)}return Rn(i)}function Ln(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function Rn(e){if(!Bn(e)||!Array.isArray(e.data))throw new K(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Bn(e)||typeof e.id!=`string`||e.id.length===0)throw new K(`Provider returned an invalid model entry`);let t=zn(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function zn(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Bn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Vn=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Hn=class{storage;constructor(e){this.storage=e}list(e=/* @__PURE__ */ new Set){return this.storage.all(`providers`).filter(e=>e.status!==`deleted`).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(t=>({...Un(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?Un(t):null}getConnection(e){let t=this.storage.get(`providers`,e);return t&&t.status!==`deleted`?{protocol:t.protocol,baseURL:t.baseURL,apiKey:t.apiKey}:null}save(e,t){return this.storage.transaction(()=>{let n=t?this.storage.get(`providers`,t):void 0;if(t&&!n)throw new Vn;let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:t??y(),status:`active`,createdAt:r,deletedAt:null,...n,...e,avatar:e.avatar===void 0?n?.avatar??null:e.avatar,updatedAt:r};return this.storage.put(`providers`,i),Un(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new Vt;let r=this.storage.get(`providers`,e);if(!r)throw new Vn;let i=(/* @__PURE__ */ new Date()).toISOString(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),Un(a)})}};function Un(e){return{...e,avatar:e.avatar??null,status:e.status}}function Wn(e){let t=F(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))Gn(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function Gn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Kn=class{storage;repository;constructor(e){this.storage=e,this.repository=new Hn(e)}list(){return this.repository.list(Wn(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new Vn;return In(t)}fetchModelsForConnection(e){return In(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,Wn(this.storage)))}};function qn(e){let t=g.platform===`darwin`?`open`:g.platform===`win32`?`explorer`:`xdg-open`,n=ye(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function Jn(){return E.join(be.homedir(),`.foundry`)}function Yn(){let e=Jn();return S(e,{recursive:!0,mode:448}),g.platform!==`win32`&&ae(e,448),e}function Xn(){return E.join(Jn(),`.data-transfer`)}var Zn=class{storage;configFolder;openFolder;constructor(e,t=Jn(),n=qn){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...tt(this.storage),configFolder:this.configFolder}}update(e){return{...nt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const Qn=E.dirname(Se(import.meta.url)),q=`foundry`;var $n=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=xe()}={}){this.configuredSkillRoot=e,this.homeDirectory=E.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??tr();if(!x(E.join(t,`SKILL.md`)))throw new er(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=E.join(n,q),i=E.join(n,`.${q}-${y()}.tmp`),a=E.join(n,`.${q}-${y()}.backup`);try{return await c(n,{recursive:!0}),await o(t,i,{recursive:!0,errorOnExist:!0}),await nr(i,r,a),{target:e,destination:r}}catch(e){throw await p(i,{recursive:!0,force:!0}),e instanceof er?e:new er(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return E.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:E.join(this.getTargetParent(e),q)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},er=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function tr(){let e=[E.resolve(Qn,`skills`,q),E.resolve(Qn,`..`,`..`,`..`,`skills`,q),E.resolve(g.cwd(),`skills`,q)].find(e=>x(E.join(e,`SKILL.md`)));if(!e)throw new er(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function nr(e,t,n){let r=x(t);r&&await f(t,n);try{await f(e,t),r&&await p(n,{recursive:!0,force:!0})}catch(e){throw r&&!x(t)&&x(n)&&await f(n,t),e}}function rr(){let e=g.env.CLAUDE_CONFIG_DIR?.trim();return e?E.resolve(e):E.join(be.homedir(),`.claude`)}var ir=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};const ar=1048576;async function or(e){let t;try{t=await d(e,{withFileTypes:!0})}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`ENOENT`;return{files:[],unreadable:+!t,found:!t}}let n={files:[],unreadable:0,found:!0};for(let r of t){let t=E.join(e,r.name);if(r.isDirectory()){let e=await or(t);n.files.push(...e.files),n.unreadable+=e.unreadable}else r.isFile()&&/\.jsonl(?:\.zst)?$/u.test(r.name)&&n.files.push(t)}let r=new Set(n.files);return n.files=n.files.filter(e=>!e.endsWith(`.zst`)||!r.has(e.slice(0,-4))).toSorted((e,t)=>e.localeCompare(t)),n}async function sr(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}J(r)?t(r):n=!0},i=async e=>{let t=new Ce(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
|
|
2
|
+
import{defineCommand as e,runMain as t,showUsage as n}from"citty";import{setTimeout as r}from"node:timers/promises";import{chmod as i,copyFile as a,cp as o,link as s,mkdir as c,open as l,readFile as u,readdir as d,rename as f,rm as p,stat as m,writeFile as h}from"node:fs/promises";import g from"node:process";import{createCipheriv as _,createDecipheriv as v,createHash as ee,randomBytes as te,randomUUID as y,scrypt as ne}from"node:crypto";import{FirecrawlClient as re}from"firecrawl";import{parse as ie}from"tldts";import{chmodSync as ae,closeSync as oe,createReadStream as b,createWriteStream as se,existsSync as x,fsyncSync as ce,mkdirSync as S,openSync as le,readFileSync as C,readdirSync as ue,renameSync as de,rmSync as w,rmdirSync as fe,statSync as T,writeFileSync as pe}from"node:fs";import E from"node:path";import{pipeline as D}from"node:stream/promises";import me from"yauzl";import he from"yazl";import{Buffer as O}from"node:buffer";import{Readable as ge,Transform as _e}from"node:stream";import{matchedRoutes as ve}from"hono/route";import{spawn as ye}from"node:child_process";import be,{homedir as xe}from"node:os";import{fileURLToPath as Se}from"node:url";import{StringDecoder as Ce}from"node:string_decoder";import{createZstdDecompress as we}from"node:zlib";import{serve as Te}from"@hono/node-server";import{serveStatic as Ee}from"@hono/node-server/serve-static";import{Hono as k}from"hono";import{streamSSE as De}from"hono/streaming";import{createServer as Oe}from"node:net";var ke=`6.3.1`;function Ae(e){if(!Pe(e)||typeof e.url!=`string`)throw new Ne(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function je(e){return e===`no-successful`?`no-successful`:`all`}function Me(e){if(!Pe(e)||typeof e.userNote!=`string`)throw new Ne(`userNote must be a string`);return e.userNote}var Ne=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function Pe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var A=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}},Fe=class{storage;constructor(e){this.storage=e}findCapture(e){let t=this.storage.get(`captures`,e);return t&&!t.deletedAt?t:null}newJob(e,t){let n=(/* @__PURE__ */ new Date()).toISOString();return{id:y(),captureId:e,fetcher:t.fetcher,configSnapshot:t,rawResponse:null,creditsUsed:null,status:`pending`,errorCode:null,errorMessage:null,createdAt:n,updatedAt:n,deletedAt:null}}list(e){return this.storage.all(`captures`).filter(t=>!t.deletedAt&&(e!==`no-successful`||!t.latestSuccessfulJobId)).toSorted((e,t)=>t.createdAt.localeCompare(e.createdAt)).map(e=>Ie(e))}counts(){let e=this.storage.all(`captures`).filter(e=>!e.deletedAt);return{all:e.length,noSuccessful:e.filter(e=>!e.latestSuccessfulJobId).length}}get(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return null;let n=t.latestSuccessfulJobId?this.storage.get(`fetchJobs`,t.latestSuccessfulJobId):void 0;return{capture:Ie(t),rawResponse:n?.captureId===e&&!n.deletedAt?n.rawResponse:null}})}findActiveByURL(e){return this.storage.all(`captures`).find(t=>t.url===e&&!t.deletedAt)??null}createWithJob(e,t,n){return this.storage.transaction(()=>{if(this.findActiveByURL(e))throw new A(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:y(),url:e,title:null,userNote:t,latestSuccessfulJobId:null,createdAt:r,updatedAt:r,deletedAt:null},a=this.newJob(i.id,n);return this.storage.put(`captures`,i),this.storage.put(`fetchJobs`,a),{capture:Ie(i),jobId:a.id}})}hasActiveJob(e){return this.storage.all(`fetchJobs`).some(t=>t.captureId===e&&!t.deletedAt&&[`pending`,`running`].includes(t.status))}createJob(e,t){return this.storage.transaction(()=>{if(!this.findCapture(e))throw new A(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new A(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:Le(n),jobId:n.id}})}delete(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return!1;if(this.hasActiveJob(e))throw new A(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=(/* @__PURE__ */ new Date()).toISOString();this.storage.put(`captures`,{...t,deletedAt:n,updatedAt:n});for(let t of this.storage.all(`fetchJobs`))t.captureId===e&&!t.deletedAt&&this.storage.put(`fetchJobs`,{...t,deletedAt:n,updatedAt:n});return!0})}updateNote(e,t){return this.storage.transaction(()=>{let n=this.findCapture(e);if(!n)return null;let r={...n,userNote:t.trim()||null,updatedAt:(/* @__PURE__ */ new Date()).toISOString()};return this.storage.put(`captures`,r),Ie(r)})}listJobs(e){return this.storage.all(`fetchJobs`).filter(t=>t.captureId===e&&!t.deletedAt).toSorted((e,t)=>t.createdAt.localeCompare(e.createdAt)).map(e=>Le(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?Le(n.job):null}getJobContext(e){return this.storage.transaction(()=>{let t=this.storage.get(`fetchJobs`,e);if(!t||t.deletedAt)return null;let n=this.findCapture(t.captureId);return n?{job:t,capture:n}:null})}markRunning(e){this.storage.transaction(()=>{let t=this.storage.get(`fetchJobs`,e);t?.status===`pending`&&this.storage.put(`fetchJobs`,{...t,status:`running`,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})})}markSucceeded(e,t,n,r,i){this.storage.transaction(()=>{let a=this.storage.get(`fetchJobs`,e),o=this.findCapture(t);if(!a||!o||a.captureId!==t)throw Error(`Invalid capture job`);let s=(/* @__PURE__ */ new Date()).toISOString();this.storage.put(`fetchJobs`,{...a,status:`succeeded`,rawResponse:r,creditsUsed:i,errorCode:null,errorMessage:null,updatedAt:s}),this.storage.put(`captures`,{...o,...n&&{title:n},latestSuccessfulJobId:e,updatedAt:s})})}markFailed(e,t,n){this.storage.transaction(()=>{let r=this.storage.get(`fetchJobs`,e);r&&this.storage.put(`fetchJobs`,{...r,status:`failed`,creditsUsed:null,errorCode:t,errorMessage:n,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})})}recoverRunningJobs(){return this.storage.transaction(()=>{let e=this.storage.all(`fetchJobs`).filter(e=>e.status===`running`&&!e.deletedAt);for(let t of e)this.storage.put(`fetchJobs`,{...t,status:`pending`});return e.length})}pendingJobIDs(){return this.storage.all(`fetchJobs`).filter(e=>e.status===`pending`&&!e.deletedAt).toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt)).map(e=>e.id)}};function Ie(e){let{deletedAt:t,...n}=e;return n}function Le(e){return{id:e.id,captureId:e.captureId,status:e.status,fetcher:e.fetcher,creditsUsed:e.creditsUsed,errorCode:e.errorCode,errorMessage:e.errorMessage,createdAt:e.createdAt,updatedAt:e.updatedAt}}const Re=[`system`,`light`,`dark`],ze=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Be=[`YYYY-MM-DD HH:mm:ss`,`YYYY-MM-DD`,`YYYY/MM/DD HH:mm:ss`,`DD/MM/YYYY HH:mm:ss`,`MM/DD/YYYY hh:mm:ss A`,`HH:mm:ss`],Ve=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],He=[`firecrawl`],j={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}},features:{library:{captures:{fetcher:null,maxAttempts:1,fetchConcurrency:2,firecrawl:{apiKey:``}}}}};function Ue(e){let t=P(e)?e:{},n=P(t.workspace)?t.workspace:{},r=P(n.appearance)?n.appearance:{},i=P(n[`language-region`])?n[`language-region`]:{},a=P(t.features)?t.features:{},o=P(a.library)?a.library:{},s=P(o.captures)?o.captures:{},c=P(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":Xe(r[`color-theme`],Re,j.workspace.appearance[`color-theme`])},"language-region":{language:Xe(i.language,ze,j.workspace[`language-region`].language),"time-format":Xe(i[`time-format`],Be,j.workspace[`language-region`][`time-format`]),"time-zone":Xe(i[`time-zone`],Ve,j.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:Je(s.fetcher),maxAttempts:Ze(s.maxAttempts,10,1),fetchConcurrency:Ze(s.fetchConcurrency,5,2),firecrawl:{apiKey:et(c.apiKey)}}}}}}function We(e){if(!P(e))throw new M(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=N(e.theme,Re,`theme`)),`language`in e&&(t.language=N(e.language,ze,`language`)),`timeFormat`in e&&(t.timeFormat=N(e.timeFormat,Be,`timeFormat`)),`timezone`in e&&(t.timezone=N(e.timezone,Ve,`timezone`)),`captures`in e&&(t.captures=qe(e.captures)),t}function Ge(e,t){let n=e.features.library.captures,r=t.captures;return{workspace:{appearance:{"color-theme":t.theme??e.workspace.appearance[`color-theme`]},"language-region":{language:t.language??e.workspace[`language-region`].language,"time-format":t.timeFormat??e.workspace[`language-region`][`time-format`],"time-zone":t.timezone??e.workspace[`language-region`][`time-zone`]}},features:{...e.features,library:{...e.features.library,captures:{...n,fetcher:r?.fetcher===void 0?n.fetcher:r.fetcher,maxAttempts:r?.maxAttempts??n.maxAttempts,fetchConcurrency:r?.fetchConcurrency??n.fetchConcurrency,firecrawl:{apiKey:r?.firecrawlApiKey??n.firecrawl.apiKey}}}}}}function Ke(e){let t=e.features.library.captures;return{workspace:e.workspace,features:{...e.features,library:{...e.features.library,captures:{fetcher:t.fetcher,maxAttempts:t.maxAttempts,fetchConcurrency:t.fetchConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey}}}}}}var M=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function qe(e){if(!P(e))throw new M(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:N(e.fetcher,He,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=Qe(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=Qe(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=$e(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function Je(e){return Ye(e,He)}function Ye(e,t){return typeof e==`string`&&t.includes(e)?e:null}function Xe(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function N(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new M(`Invalid ${n}`);return e}function Ze(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function Qe(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new M(`${n} must be an integer from 1 to ${t}`);return e}function $e(e,t){if(typeof e!=`string`)throw new M(`${t} must be a string`);return e.trim()}function et(e){return typeof e==`string`?e:``}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return e.readSettings()}function tt(e){return Ke(F(e))}function nt(e,t){return t.transaction(()=>{let n=Ge(F(t),e);return t.setSettings(n),Ke(n)})}var I=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function rt(e){if(e instanceof I)return e;let t=it(e);return t===null?st(e)?new I(`timeout`,`The configured fetcher timed out`):ct(e)?new I(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new I(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new I(`http_${t}`,at(e)??`The configured fetcher returned ${t}`,t)}function it(e){if(!L(e))return null;let t=lt(e.status);return t===null?L(e.response)?lt(e.response.status):null:t}function at(e){if(!L(e))return null;if(L(e.response)){let t=ot(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:ot(e.details)}function ot(e){return L(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function st(e){if(!(e instanceof Error))return!1;let t=ut(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function ct(e){if(e instanceof TypeError)return!0;if(!L(e))return!1;let t=ut(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!L(e.response)}function lt(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function ut(e){let t=e.code;return typeof t==`string`?t:null}function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var dt=class extends re{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function ft(e,t,n={}){let r=new dt({apiKey:e,maxRetries:Math.max(1,Math.trunc(t)),...n.apiUrl&&{apiUrl:n.apiUrl},...n.backoffFactor!==void 0&&{backoffFactor:n.backoffFactor}});return{search:e=>r.searchEnvelope(e)}}async function pt(e,t,n=1,r=ft(t,n)){try{let t=mt(e),n=await r.search(ht(t));if(!R(n))throw new I(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new I(`fetcher_error`,jt(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new I(`invalid_response`,`The configured fetcher returned an invalid response`);let i=At(n);if(i===null)throw new I(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=Ct(e,St(n));return{title:a?Ot(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw rt(e)}}function mt(e){return{query:gt(e),limit:5,sources:[`web`],highlights:!1,ignoreInvalidURLs:!0,timeout:12e4,pageOptions:{formats:[`summary`],onlyMainContent:!0,onlyCleanContent:!1,maxAge:1728e5,timeout:6e4,removeBase64Images:!0,blockAds:!0,proxy:`auto`,storeInCache:!0}}}function ht(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function gt(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=_t(t.pathname),i=xt(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function _t(e){let t=e.split(`/`).map(e=>vt(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||bt(n))continue;let r=yt(n);if(r)return r}return null}function vt(e){try{return decodeURIComponent(e)}catch{return e}}function yt(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function bt(e){return/^(?:index|home|latest)$/i.test(e)||/^\d+$/.test(e)||/^v?\d+(?:\.\d+)+$/i.test(e)||/^[a-z]{2}(?:[-_][a-z]{2})?$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(e)||/^[0-9a-f]{20,}$/i.test(e)}function xt(e){return ie(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function St(e){return!R(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!R(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:R(e.metadata)?e.metadata:{}}])}function Ct(e,t){let n=Tt(e);if(n){let e=t.find(e=>wt(e).some(e=>Tt(e)===n));if(e)return e}let r=Et(e),i=r===null?[]:t.filter(e=>wt(e).some(e=>Et(e)===r));return i.find(e=>Dt(e))??(i.length>0?i[0]:null)}function wt(e){return[e.url,kt(e,`sourceURL`),kt(e,`url`)].filter(e=>!!e)}function Tt(e){try{let t=new URL(e);return t.hash=``,t.searchParams.sort(),t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)),t.href}catch{return null}}function Et(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function Dt(e){return wt(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function Ot(e){return e.title?.trim()||kt(e,`ogTitle`)?.trim()||kt(e,`title`)?.trim()||null}function kt(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function At(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function jt(e){return R(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function R(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mt(e,t){return pt(e,t.apiKey,t.maxAttempts)}var Nt=class{repository;storage;onChanged;fetchCaptureImplementation;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;paused=!1;constructor(e,t,n=()=>{},r=Mt){this.repository=e,this.storage=t,this.onChanged=n,this.fetchCaptureImplementation=r}schedule(){if(this.paused)return;let e=F(this.storage).features.library.captures.fetchConcurrency;for(;this.runningCount<e&&this.queue.length>0;){let e=this.queue.shift();if(!e)return;this.runningCount+=1,this.runJob(e).finally(()=>{--this.runningCount,this.knownJobIDs.delete(e),this.schedule()})}}async runJob(e){let t=this.repository.getJobContext(e);if(!t||t.job.status!==`pending`&&t.job.status!==`running`)return;let n;try{n=Pt(t.job.configSnapshot)}catch(n){let r=n instanceof Error?n.message:`Invalid fetch job configuration`;this.failJob(e,t.job.captureId,`invalid_config`,r);return}this.repository.markRunning(e),this.onChanged({captureId:t.capture.id,jobId:e,status:`running`});try{let r=await this.fetchCaptureImplementation(t.capture.url,n);this.repository.markSucceeded(e,t.capture.id,r.title,r.rawResponse,r.creditsUsed),this.onChanged({captureId:t.capture.id,jobId:e,status:`succeeded`})}catch(n){let r=rt(n);this.failJob(e,t.capture.id,r.code,r.message)}}failJob(e,t,n,r){this.repository.markFailed(e,n,r),this.onChanged({captureId:t,jobId:e,status:`failed`,errorMessage:r})}start(){this.repository.recoverRunningJobs();for(let e of this.repository.pendingJobIDs())this.enqueue(e)}enqueue(e){if(this.knownJobIDs.has(e))return;let t=this.repository.getJobContext(e);t&&(this.knownJobIDs.add(e),this.queue.push(e),this.onChanged({captureId:t.capture.id,jobId:e,status:`pending`}),this.schedule())}notifySettingsChanged(){this.schedule()}pause(){this.paused=!0}resume(){this.paused=!1,this.schedule()}};function Pt(e){let t=e;if(!Ft(t)||t.fetcher!==`firecrawl`||typeof t.apiKey!=`string`||!t.apiKey||typeof t.maxAttempts!=`number`)throw Error(`Invalid fetch job configuration`);return{fetcher:t.fetcher,apiKey:t.apiKey,maxAttempts:Math.min(10,Math.max(1,Math.trunc(t.maxAttempts)))}}function Ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var It=class{repository;storage;runner;constructor(e,t,n){this.repository=e,this.storage=t,this.runner=n}executionConfig(){let e=F(this.storage).features.library.captures;if(!e.fetcher)return null;let t=e[e.fetcher].apiKey.trim();return t?{fetcher:e.fetcher,apiKey:t,maxAttempts:e.maxAttempts}:null}list(e){return this.repository.list(e)}counts(){return this.repository.counts()}get(e){let t=this.repository.get(e);if(!t)throw new A(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=Lt(e.url);if(!t)throw new A(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new A(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new A(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before adding a capture`);try{let r=this.repository.createWithJob(t,e.userNote?.trim()||null,n);return this.runner.enqueue(r.jobId),r.capture}catch(e){throw this.repository.findActiveByURL(t)?new A(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new A(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new A(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before re-capturing`);let n=this.repository.createJob(e,t);return this.runner.enqueue(n.jobId),n.job}delete(e){if(this.get(e),this.repository.hasActiveJob(e))throw new A(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new A(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new A(`CAPTURE_NOT_FOUND`,`Capture not found`);return n}listJobs(e){return this.get(e),this.repository.listJobs(e)}getJob(e,t){return this.get(e),this.repository.getJob(e,t)}};function Lt(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function Rt(e,t,n){let r=new Fe(e),i=new Nt(r,e,e=>t?.publish(`capture.job.changed`,e),n);return{service:new It(r,e,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}const zt=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Bt=[`active`,`disabled`,`deleted`];var z=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},Vt=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function B(e){if(!Jt(e))throw new z(`Provider input must be an object`);let t=V(e.name,`name`),n=Kt(e.protocol),r=qt(e.baseURL),i=e.apiKey===void 0?``:V(e.apiKey,`apiKey`,{allowEmpty:!0}),a=Gt(e.customModels);return{...e.avatar!==void 0&&{avatar:Ht(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Ht(e){if(e===null)return null;if(typeof e==`string`&&e.length<=2796236){let t=/^data:image\/(?:png|jpeg|gif|webp|svg\+xml);base64,/u.exec(e);if(t){let n=e.slice(t[0].length),r=n.endsWith(`==`)?2:+!!n.endsWith(`=`);if(n.length>0&&n.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/u.test(n)&&n.length/4*3-r<=2097152)return e}}throw new z(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Ut(e){if(!Jt(e))throw new z(`Provider connection must be an object`);return{protocol:Kt(e.protocol),baseURL:qt(e.baseURL),apiKey:e.apiKey===void 0?``:V(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Wt(e){if(typeof e!=`string`||!Bt.includes(e))throw new z(`Invalid provider status`);return e}function Gt(e){if(e===void 0)return[];if(!Array.isArray(e))throw new z(`customModels must be an array`);return e.map(e=>{if(!Jt(e))throw new z(`Each custom model must be an object`);return{id:V(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:V(e.displayName,`customModels.displayName`)}})}function Kt(e){if(typeof e!=`string`||!zt.includes(e))throw new z(`Invalid provider protocol`);return e}function qt(e){let t=V(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new z(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function V(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new z(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new z(`${t} is required`);return r}function Jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function H(e,t){if(!e)throw Error(t)}function Xt(e){return e===null||typeof e==`string`}function Zt(e){H(Yt(e)&&e.formatVersion===1,`Unsupported Foundry JSON data format`),H(Yt(e.settings),`Invalid settings`),Ue(e.settings);for(let t of[`providers`,`captures`,`fetchJobs`]){let n=e[t];H(Array.isArray(n),`Invalid storage collection`);let r=/* @__PURE__ */ new Set;for(let e of n)H(Yt(e)&&typeof e.id==`string`&&e.id.length>0&&e.id.length<=200&&!r.has(e.id),`Invalid or duplicate record ID`),r.add(e.id),H(typeof e.createdAt==`string`&&Number.isFinite(Date.parse(e.createdAt))&&typeof e.updatedAt==`string`&&Number.isFinite(Date.parse(e.updatedAt)),`Invalid record timestamp`),H(e.deletedAt===null||typeof e.deletedAt==`string`&&Number.isFinite(Date.parse(e.deletedAt)),`Invalid deletion timestamp`)}let t=e;for(let e of t.providers)try{H([`active`,`disabled`,`deleted`].includes(e.status),`Invalid status`),H(typeof e.apiKey==`string`,`Invalid API key`),B(e)}catch{throw Error(`A provider record is invalid`)}let n=/* @__PURE__ */ new Set,r=new Map(t.captures.map(e=>[e.id,e])),i=new Map(t.fetchJobs.map(e=>[e.id,e]));for(let e of t.captures){try{H([`http:`,`https:`].includes(new URL(e.url).protocol),`Invalid protocol`)}catch{throw Error(`A capture URL is invalid`)}if(H(Xt(e.title)&&Xt(e.userNote)&&Xt(e.latestSuccessfulJobId),`A capture record is invalid`),e.deletedAt||(H(!n.has(e.url),`Duplicate active capture URL`),n.add(e.url),!e.latestSuccessfulJobId))continue;let t=i.get(e.latestSuccessfulJobId);H(t?.captureId===e.id&&t.status===`succeeded`&&!t.deletedAt,`A capture points to an invalid successful fetch job`)}let a=/* @__PURE__ */ new Set;for(let e of t.fetchJobs)H(r.has(e.captureId)&&[`pending`,`running`,`succeeded`,`failed`].includes(e.status)&&e.fetcher===`firecrawl`,`A fetch job record is invalid`),H(Yt(e.configSnapshot),`A fetch job configuration is invalid`),H(e.creditsUsed===null||typeof e.creditsUsed==`number`&&Number.isFinite(e.creditsUsed),`A fetch job credit value is invalid`),H(Xt(e.errorCode)&&Xt(e.errorMessage),`A fetch job record is invalid`),!e.deletedAt&&[`pending`,`running`].includes(e.status)&&(H(!a.has(e.captureId),`Duplicate active fetch jobs`),a.add(e.captureId))}var U=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`DataTransferError`}};function Qt(e){return e instanceof U?e:new U(`IO_ERROR`,e instanceof Error?e.message:`The data transfer failed`,{cause:e})}const W=`data/foundry.json`,$t=`manifest.json`;function en(e){if(!on(e)||e.format!==`foundry.snapshot`)throw new U(`INVALID_ARCHIVE`,`The file is not a Foundry export`);let t=an(e.archiveVersion,`archiveVersion`);if(t!==3)throw new U(`UNSUPPORTED_ARCHIVE`,`The archive version is not supported`);let n=rn(e.createdAt,`createdAt`);if(Number.isNaN(Date.parse(n)))throw new U(`INVALID_ARCHIVE`,`createdAt is invalid`);if(!on(e.data)||e.database!==void 0||e.settings!==void 0)throw new U(`INVALID_ARCHIVE`,`JSON data metadata is invalid`);return{format:`foundry.snapshot`,archiveVersion:t,appVersion:rn(e.appVersion,`appVersion`),createdAt:n,data:{...nn(e.data,W),formatVersion:an(e.data.formatVersion,`data.formatVersion`)}}}function tn(e){return e.toLowerCase().endsWith(`.foundry-backup`)?e:`${e}.foundry-backup`}function nn(e,t){if(!on(e)||e.path!==t)throw new U(`INVALID_ARCHIVE`,`File metadata path is invalid`);let n=rn(e.sha256,`sha256`);if(!/^[a-f0-9]{64}$/u.test(n))throw new U(`INVALID_ARCHIVE`,`File checksum is invalid`);return{path:t,bytes:an(e.bytes,`bytes`),sha256:n}}function rn(e,t){if(typeof e!=`string`||e.length===0)throw new U(`INVALID_ARCHIVE`,`${t} must be a non-empty string`);return e}function an(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new U(`INVALID_ARCHIVE`,`${t} must be a non-negative integer`);return e}function on(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const sn=/* @__PURE__ */ new Set([$t,W]);async function cn(e,t){let n=new he.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await D(n.outputStream,se(t,{mode:384}))}async function ln(e,t){let n=await un(e),r=/* @__PURE__ */ new Map,i=0;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!sn.has(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);if(e.fileName.endsWith(`/`)||r.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let a=e.fileName===`manifest.json`?1048576:4294967296;if(i+=e.uncompressedSize,e.uncompressedSize>a||i>4294967296)throw Error(`The Foundry archive is too large`);let o=E.join(t,e.fileName);await c(E.dirname(o),{recursive:!0}),await D(await dn(n,e),se(o,{mode:384})),r.set(e.fileName,o),n.readEntry()};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await p(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!r.has(`manifest.json`)||!r.has(`data/foundry.json`))throw await p(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function un(e){return new Promise((t,n)=>{me.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function dn(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}const G=O.from(`FOUNDRYX`,`ascii`),fn=`aes-256-gcm`,pn=`scrypt`,mn={N:131072,r:8,p:1};async function hn(e,t,n){let r=te(16),a=te(12),o={version:1,cipher:fn,kdf:{name:pn,salt:r.toString(`base64`),...mn,keyLength:32},nonce:a.toString(`base64`)},s=O.from(JSON.stringify(o),`utf8`),c=_n(s.byteLength),u=O.concat([c,s]),d=await vn(n,r,mn);try{let n=await l(t,`w`,384);try{await n.write(u)}finally{await n.close()}await D(b(e),yn(d,a,u),se(t,{flags:`r+`,mode:384,start:u.byteLength})),await i(t,384)}catch(e){throw await p(t,{force:!0}),new U(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function gn(e,t,n){let r;try{let a=(await m(e)).size;if(a<=29)throw Error(`The export file is incomplete`);let o=await l(e,`r`),s,c,u;try{if(s=await Sn(o,13,0),!s.subarray(0,G.byteLength).equals(G))throw Error(`The export file signature is invalid`);if(s.readUInt8(G.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=s.readUInt32BE(G.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(a<=13+e+16)throw Error(`The export file is incomplete`);c=await Sn(o,e,13),u=await Sn(o,16,a-16)}finally{await o.close()}let d=xn(JSON.parse(c.toString(`utf8`)));r=await vn(n,d.salt,d.header.kdf);let f=O.concat([s,c]);await D(b(e,{start:13+c.byteLength,end:a-16-1}),bn(r,d.nonce,f,u),se(t,{mode:384})),await i(t,384)}catch(e){throw await p(t,{force:!0}),e instanceof U?e:new U(`INVALID_PASSPHRASE`,`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function _n(e){let t=O.alloc(13);return G.copy(t,0),t.writeUInt8(1,G.byteLength),t.writeUInt32BE(e,G.byteLength+1),t}function vn(e,t,n){return new Promise((r,i)=>{ne(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function yn(e,t,n){let r=_(fn,e,t,{authTagLength:16});return r.setAAD(n),new _e({transform(e,t,n){try{n(null,r.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{e(null,O.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function bn(e,t,n,r){let i=v(fn,e,t,{authTagLength:16});return i.setAAD(n),new _e({transform(e,t,n){try{n(null,i.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{i.setAuthTag(r),e(null,i.final())}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function xn(e){if(!Cn(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==fn||!Cn(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==pn||typeof t.salt!=`string`||t.N!==mn.N||t.r!==mn.r||t.p!==mn.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=O.from(t.salt,`base64`),r=O.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:fn,kdf:{name:pn,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Sn(e,t,n){let r=O.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Cn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var wn=class{storage;runner;temporaryRoot;appVersion;workspaceMutationGate;onStatusChanged;busy=!1;stagedImports=/* @__PURE__ */ new Map;constructor(e,t,n,r,i,a=()=>{}){this.storage=e,this.runner=t,this.temporaryRoot=n,this.appVersion=r,this.workspaceMutationGate=i,this.onStatusChanged=a}async runExclusive(e){if(this.busy||!this.workspaceMutationGate.tryBeginTransfer())throw new U(`BUSY`,`Another data transfer is in progress`);this.busy=!0;try{return this.onStatusChanged(this.getStatus()),await e()}finally{this.busy=!1,this.workspaceMutationGate.endTransfer(),this.onStatusChanged(this.getStatus())}}async createWorkDirectory(e){await c(this.temporaryRoot,{recursive:!0,mode:448}),await jn(this.temporaryRoot);let t=E.join(this.temporaryRoot,`${e}-${y()}`);return await c(t,{mode:448}),await jn(t),t}async removeQuietly(e){try{await p(e,{recursive:!0,force:!0})}catch{}}async createUploadTarget(){let e=await this.createWorkDirectory(`upload`);return{filePath:E.join(e,`archive.foundry-backup`),cleanup:()=>this.removeQuietly(e)}}cleanupStaleTransfers(){w(this.temporaryRoot,{recursive:!0,force:!0}),S(this.temporaryRoot,{recursive:!0,mode:448}),this.stagedImports.clear()}getStatus(){return{activeJobCount:this.storage.all(`fetchJobs`).filter(e=>En(e)).length,isBusy:this.busy}}async createExport(e){return Tn(e),this.runExclusive(async()=>{let t=await this.createWorkDirectory(`export`),n=E.join(t,`foundry.json`),r=E.join(t,$t),i=E.join(t,`foundry.zip`),a=E.join(this.temporaryRoot,`foundry-${y()}.foundry-backup`);this.runner.pause();try{let t=this.storage.snapshot();Dn(t),Zt(t),await h(n,JSON.stringify(t),{mode:384});let o={format:`foundry.snapshot`,archiveVersion:3,appVersion:this.appVersion,createdAt:(/* @__PURE__ */ new Date()).toISOString(),data:{...await kn(n,W),formatVersion:1}};return await h(r,JSON.stringify(o,null,2),{mode:384}),await cn([{entryPath:$t,filePath:r},{entryPath:W,filePath:n}],i),await hn(i,a,e),{filePath:a,...On(t)}}finally{this.runner.resume(),await this.removeQuietly(t)}})}async inspectImport(e,t,n=E.basename(e)){return Tn(t),this.runExclusive(async()=>{Dn(this.storage.snapshot());let r=this.stagedImports.values().toArray();this.stagedImports.clear(),await Promise.all(r.map(e=>this.removeQuietly(e.directory)));let i=y(),a=await this.createWorkDirectory(`import-${i}`),o=E.join(a,`archive.zip`);try{await gn(e,o,t);let r=await ln(o,E.join(a,`extracted`)),s=en(JSON.parse(await u(r[$t],`utf8`)));if(s.data.formatVersion>1)throw new U(`NEWER_SCHEMA`,`The archive was created by a newer Foundry version`);let c=/* @__PURE__ */ new Set([$t,W]);await An(r[W],s.data);let l=JSON.parse(await u(r[W],`utf8`));if(Zt(l),l.formatVersion!==s.data.formatVersion)throw new U(`INVALID_ARCHIVE`,`The JSON data format does not match its manifest`);if(Object.keys(r).some(e=>!c.has(e)))throw new U(`INVALID_ARCHIVE`,`Unexpected archive file`);Dn(l);let d=E.join(a,`staged.json`);await h(d,JSON.stringify(l),{mode:384});let f={importId:i,fileName:E.basename(n),exportedAt:s.createdAt,appVersion:s.appVersion,dataFormatVersion:l.formatVersion,settingsVersion:1,...On(l)};return this.stagedImports.set(i,{snapshotPath:d,directory:a,preview:f}),await p(o,{force:!0}),f}catch(e){throw await this.removeQuietly(a),e instanceof U?e:new U(`INVALID_ARCHIVE`,e instanceof Error?e.message:`The Foundry export could not be inspected`,{cause:e})}})}async cancelImport(e){let t=this.stagedImports.get(e);t&&(this.stagedImports.delete(e),await this.removeQuietly(t.directory))}async commitImport(e){let t=this.stagedImports.get(e);if(!t)throw new U(`IMPORT_NOT_FOUND`,`The import session has expired`);return this.runExclusive(async()=>{this.runner.pause();try{let n=JSON.parse(await u(t.snapshotPath,`utf8`));Zt(n),Dn(n),this.storage.transaction(()=>{Dn(this.storage.snapshot()),this.storage.replace(n)}),this.stagedImports.delete(e),await this.removeQuietly(t.directory)}finally{this.runner.resume(),this.runner.notifySettingsChanged()}})}async removeExportFile(e){E.dirname(e)===this.temporaryRoot&&await p(e,{force:!0})}};function Tn(e){if(!e)throw new U(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}function En(e){return!e.deletedAt&&[`pending`,`running`].includes(e.status)}function Dn(e){if(e.fetchJobs.some(e=>En(e)))throw new U(`ACTIVE_JOBS`,`Finish active fetch jobs before transferring data`)}function On(e){return{providerCount:e.providers.length,captureCount:e.captures.length,jobCount:e.fetchJobs.length}}async function kn(e,t){let n=ee(`sha256`);for await(let t of b(e))n.update(t);return{path:t,bytes:(await m(e)).size,sha256:n.digest(`hex`)}}async function An(e,t){let n=await kn(e,t.path);if(n.bytes!==t.bytes||n.sha256!==t.sha256)throw new U(`INVALID_ARCHIVE`,`An archived file failed its integrity validation`)}function jn(e){return g.platform===`win32`?Promise.resolve():i(e,448)}const Mn=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var Nn=class{transferActive=!1;get isTransferActive(){return this.transferActive}tryBeginTransfer(){return!this.transferActive&&(this.transferActive=!0,!0)}endTransfer(){this.transferActive=!1}};function Pn(e){return async(t,n)=>{if(e.isTransferActive&&Mn.has(t.req.method)&&!t.req.path.startsWith(`/api/data-transfer/`)&&Fn(t))return t.json({error:{code:`DATA_TRANSFER_BUSY`,message:`Another data transfer is in progress`}},409);await n()}}function Fn(e){return ve(e).some(e=>e.path.startsWith(`/api/`)&&e.path!==`/api/*`)}var K=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function In(e,t=fetch){let n={accept:`application/json`};e.protocol===`anthropic-messages`?(n[`anthropic-version`]=`2023-06-01`,e.apiKey&&(n[`x-api-key`]=e.apiKey)):n.authorization=`Bearer ${e.apiKey||`local-provider`}`;let r;try{r=await t(Ln(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new K(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new K(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new K(`Provider returned invalid JSON`)}return Rn(i)}function Ln(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function Rn(e){if(!Bn(e)||!Array.isArray(e.data))throw new K(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Bn(e)||typeof e.id!=`string`||e.id.length===0)throw new K(`Provider returned an invalid model entry`);let t=zn(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function zn(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Bn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Vn=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Hn=class{storage;constructor(e){this.storage=e}list(e=/* @__PURE__ */ new Set){return this.storage.all(`providers`).filter(e=>e.status!==`deleted`).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(t=>({...Un(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?Un(t):null}getConnection(e){let t=this.storage.get(`providers`,e);return t&&t.status!==`deleted`?{protocol:t.protocol,baseURL:t.baseURL,apiKey:t.apiKey}:null}save(e,t){return this.storage.transaction(()=>{let n=t?this.storage.get(`providers`,t):void 0;if(t&&!n)throw new Vn;let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:t??y(),status:`active`,createdAt:r,deletedAt:null,...n,...e,avatar:e.avatar===void 0?n?.avatar??null:e.avatar,updatedAt:r};return this.storage.put(`providers`,i),Un(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new Vt;let r=this.storage.get(`providers`,e);if(!r)throw new Vn;let i=(/* @__PURE__ */ new Date()).toISOString(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),Un(a)})}};function Un(e){return{...e,avatar:e.avatar??null,status:e.status}}function Wn(e){let t=F(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))Gn(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function Gn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Kn=class{storage;repository;constructor(e){this.storage=e,this.repository=new Hn(e)}list(){return this.repository.list(Wn(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new Vn;return In(t)}fetchModelsForConnection(e){return In(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,Wn(this.storage)))}};function qn(e){let t=g.platform===`darwin`?`open`:g.platform===`win32`?`explorer`:`xdg-open`,n=ye(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function Jn(){return E.join(be.homedir(),`.foundry`)}function Yn(){let e=Jn();return S(e,{recursive:!0,mode:448}),g.platform!==`win32`&&ae(e,448),e}function Xn(){return E.join(Jn(),`.data-transfer`)}var Zn=class{storage;configFolder;openFolder;constructor(e,t=Jn(),n=qn){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...tt(this.storage),configFolder:this.configFolder}}update(e){return{...nt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const Qn=E.dirname(Se(import.meta.url)),q=`foundry`;var $n=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=xe()}={}){this.configuredSkillRoot=e,this.homeDirectory=E.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??tr();if(!x(E.join(t,`SKILL.md`)))throw new er(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=E.join(n,q),i=E.join(n,`.${q}-${y()}.tmp`),a=E.join(n,`.${q}-${y()}.backup`);try{return await c(n,{recursive:!0}),await o(t,i,{recursive:!0,errorOnExist:!0}),await nr(i,r,a),{target:e,destination:r}}catch(e){throw await p(i,{recursive:!0,force:!0}),e instanceof er?e:new er(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return E.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:E.join(this.getTargetParent(e),q)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},er=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function tr(){let e=[E.resolve(Qn,`skills`,q),E.resolve(Qn,`..`,`..`,`..`,`skills`,q),E.resolve(g.cwd(),`skills`,q)].find(e=>x(E.join(e,`SKILL.md`)));if(!e)throw new er(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function nr(e,t,n){let r=x(t);r&&await f(t,n);try{await f(e,t),r&&await p(n,{recursive:!0,force:!0})}catch(e){throw r&&!x(t)&&x(n)&&await f(n,t),e}}function rr(){let e=g.env.CLAUDE_CONFIG_DIR?.trim();return e?E.resolve(e):E.join(be.homedir(),`.claude`)}var ir=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};const ar=1048576;async function or(e){let t;try{t=await d(e,{withFileTypes:!0})}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`ENOENT`;return{files:[],unreadable:+!t,found:!t}}let n={files:[],unreadable:0,found:!0};for(let r of t){let t=E.join(e,r.name);if(r.isDirectory()){let e=await or(t);n.files.push(...e.files),n.unreadable+=e.unreadable}else r.isFile()&&/\.jsonl(?:\.zst)?$/u.test(r.name)&&n.files.push(t)}let r=new Set(n.files);return n.files=n.files.filter(e=>!e.endsWith(`.zst`)||!r.has(e.slice(0,-4))).toSorted((e,t)=>e.localeCompare(t)),n}async function sr(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}J(r)?t(r):n=!0},i=async e=>{let t=new Ce(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
|
|
3
3
|
`,e);for(;a!==-1;)r(n.slice(e,a)),e=a+1,a=n.indexOf(`
|
|
4
4
|
`,e);n=n.slice(e)}n+=t.end(),r(n)};return e.endsWith(`.zst`)?await D(b(e,{highWaterMark:ar}),we({chunkSize:ar}),i):await D(b(e,{highWaterMark:ar}),i),{hasMalformedLines:n}}function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y(e){return typeof e==`string`?e:``}function cr(e){let t=Date.parse(Y(e));return Number.isFinite(t)?t:null}function lr(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):0}function ur(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(J).filter(e=>[`text`,`input_text`,`output_text`].includes(Y(e.type))).map(e=>Y(e.text)).join(`
|
|
5
5
|
`):``}function dr(e,t){return e.replaceAll(/\s+/gu,` `).trim().slice(0,240)||t.slice(0,8)}async function fr(e){let t=await or(E.join(e,`projects`));if(!t.found)throw new ir(`CLAUDE_DATA_NOT_FOUND`,`Claude Code sessions directory was not found`);let n=t.unreadable,r=/* @__PURE__ */ new Map;for(let e of t.files)try{let t=await pr(e);if((t.hasMalformedLines||!t.thread)&&(n+=1),t.thread){let e=r.get(t.thread.id);(!e||e.updatedAt<t.thread.updatedAt)&&r.set(t.thread.id,t.thread)}}catch{n+=1}return{threads:r.values().toArray(),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function pr(e){let t=await m(e),n=``,r=``,i=null,a=``,o=``,s=``,c=null,l=1/0,u=0,d=e.split(E.sep).includes(`subagents`),f=d?E.basename(E.dirname(E.dirname(e))):null,p=d,h=/* @__PURE__ */ new Map,g=0,{hasMalformedLines:_}=await sr(e,e=>{d?f=Y(e.sessionId)||f:n||=Y(e.sessionId),r=Y(e.cwd)||r,i=Y(e.gitBranch)||i,p||=e.isSidechain===!0;let t=cr(e.timestamp);t!==null&&(l=Math.min(l,t),u=Math.max(u,t)),e.type===`custom-title`?o=Y(e.customTitle)||o:e.type===`last-prompt`&&(s=Y(e.lastPrompt)||s);let m=J(e.message)?e.message:{};if(e.type===`user`&&e.isMeta!==!0&&m.role===`user`&&(a||=ur(m.content).trim()),e.type!==`assistant`||m.role!==`assistant`)return;let _=Y(m.model);_&&_!==`<synthetic>`&&(c=_);let v=J(m.usage)?m.usage:{},ee=[v.input_tokens,v.output_tokens,v.cache_creation_input_tokens,v.cache_read_input_tokens].reduce((e,t)=>e+lr(t),0),te=Y(m.id)||Y(e.uuid);te?h.set(te,Math.max(h.get(te)??0,ee)):g+=ee});return n||=E.basename(e).replace(/\.jsonl(?:\.zst)?$/u,``),Number.isFinite(l)?{thread:{id:n,title:dr(o||a||s,n),cwd:r,gitBranch:i,model:c,archived:!1,subagent:p,parentThreadId:f,createdAt:new Date(l).toISOString(),updatedAt:new Date(u).toISOString(),sizeBytes:t.size,segmentCount:1,tokensUsed:h.values().reduce((e,t)=>e+t,g)},hasMalformedLines:_}:{thread:null,hasMalformedLines:!0}}function mr(){let e=g.env.CODEX_HOME?.trim();return e?E.resolve(e):E.join(be.homedir(),`.codex`)}async function hr(e){let t=await Promise.all([or(E.join(e,`sessions`)),or(E.join(e,`archived_sessions`))]);if(t.every(e=>!e.found))throw new ir(`CODEX_DATA_NOT_FOUND`,`Codex session directories were not found`);let n=t.reduce((e,t)=>e+t.unreadable,0),r=/* @__PURE__ */ new Map;for(let[e,i]of t.entries())for(let t of i.files)try{let i=await gr(t,e===1);if((i.hasMalformedLines||!i.segment)&&(n+=1),i.segment){let e=r.get(i.segment.id)??[];e.push(i.segment),r.set(i.segment.id,e)}}catch{n+=1}return{threads:Array.from(r.values(),_r),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function gr(e,t){let n={id:``,title:``,cwd:``,model:null,gitBranch:null,subagent:!1,parentThreadId:null,archived:t,createdAt:1/0,updatedAt:0,sizeBytes:(await m(e)).size,tokensUsed:0},r=``,{hasMalformedLines:i}=await sr(e,e=>{let t=cr(e.timestamp);t!==null&&(n.createdAt=Math.min(n.createdAt,t),n.updatedAt=Math.max(n.updatedAt,t));let i=J(e.payload)?e.payload:{};if(e.type===`session_meta`){n.id||=Y(i.id),n.cwd||=Y(i.cwd),n.model??=Y(i.model_provider)||null;let e=J(i.git)?i.git:{};n.gitBranch??=Y(e.branch)||null;let t=J(i.source)?i.source:{},r=J(i.thread_source)?i.thread_source:{},a=J(t.subagent)?t.subagent:{},o=J(r.subagent)?r.subagent:{};n.parentThreadId??=Y(i.parent_thread_id)||Y(a.parent_thread_id)||Y(o.parent_thread_id)||null,n.subagent||=!!i.parent_thread_id||J(i.source)&&`subagent`in i.source||J(i.thread_source)&&`subagent`in i.thread_source}else if(e.type===`turn_context`)n.cwd=Y(i.cwd)||n.cwd,n.model=Y(i.model)||n.model;else if(e.type===`response_item`&&i.type===`message`&&i.role===`user`){let e=ur(i.content).trim();e&&!e.startsWith(`<environment_context>`)&&!e.startsWith(`# AGENTS.md instructions`)&&(r||=e)}else if(e.type===`token_usage_record`){let e=J(i.thread_token_usage)?i.thread_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,lr(e.total_tokens))}else if(e.type===`event_msg`&&i.type===`token_count`){let e=J(i.info)?i.info:{},t=J(e.total_token_usage)?e.total_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,lr(t.total_tokens))}});return n.title=r,n.id||=/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/u.exec(E.basename(e))?.[1]??``,Number.isFinite(n.createdAt)?{segment:n.id?n:null,hasMalformedLines:i}:{segment:null,hasMalformedLines:!0}}function _r(e){e.sort((e,t)=>e.updatedAt-t.updatedAt);let t=e[0];return{id:t.id,title:dr(e.find(e=>e.title)?.title??``,t.id),cwd:e.findLast(e=>e.cwd)?.cwd??``,model:e.findLast(e=>e.model)?.model??null,gitBranch:e.findLast(e=>e.gitBranch)?.gitBranch??null,archived:e.every(e=>e.archived),subagent:e.some(e=>e.subagent),parentThreadId:e.findLast(e=>e.parentThreadId)?.parentThreadId??null,createdAt:new Date(Math.min(...e.map(e=>e.createdAt))).toISOString(),updatedAt:new Date(Math.max(...e.map(e=>e.updatedAt))).toISOString(),sizeBytes:e.reduce((e,t)=>e+t.sizeBytes,0),segmentCount:e.length,tokensUsed:Math.max(...e.map(e=>e.tokensUsed))}}var vr=class{codexHome;claudeHome;constructor(e=mr(),t=rr()){this.codexHome=e,this.claudeHome=t}async getCodexSnapshot(){return yr(`codex`,await hr(this.codexHome))}async getClaudeSnapshot(){return yr(`claude`,await fr(this.claudeHome))}};function yr(e,t){return{source:e,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),threads:t.threads.toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt)),warnings:t.warnings}}var br=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:y(),type:e,occurredAt:(/* @__PURE__ */ new Date()).toISOString(),data:t};for(let e of this.listeners)e(n);return n}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function xr(e){let t=new br,n=new Nn,r=Rt(e,t),i=new wn(e,r.runner,Xn(),ke,n,e=>t.publish(`data-transfer.status.changed`,e)),a=new Kn(e),o=new Zn(e),s=new $n,c=new vr;return{services:{captureRuntime:r,dataTransferService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c},apiOptions:{captureService:r.service,dataTransferService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c,workspaceMutationGate:n,eventHub:t,onSettingsChanged:r.notifySettingsChanged},start(){i.cleanupStaleTransfers(),r.start()}}}function Sr(e){S(e,{recursive:!0,mode:448}),g.platform!==`win32`&&ae(e,448)}function Cr(e){if(g.platform===`win32`)return;let t=le(e,`r`);try{ce(t)}finally{oe(t)}}function wr(e,t){Sr(E.dirname(e));let n=`${e}.${y()}.tmp`;try{let r=le(n,`wx`,384);try{pe(r,`${JSON.stringify(t,null,2)}\n`),ce(r)}finally{oe(r)}de(n,e),Cr(E.dirname(e))}finally{w(n,{force:!0})}}const Tr=[`providers`,`captures`,`fetchJobs`];function Er(e){try{let t=JSON.parse(C(E.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return g.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-T(e).mtimeMs>3e4}}var Dr=class{path;changes=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,Sr(e);for(let e of Tr)e!==`providers`&&Sr(this.collectionPath(e))}collectionPath(e){return E.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return E.relative(this.path,E.join(this.collectionPath(e),`${ee(`sha256`).update(t).digest(`hex`)}.json`))}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=E.join(this.path,`.lock`),n=Date.now();for(;;)try{S(t,{mode:448});try{pe(E.join(t,`owner.json`),JSON.stringify({pid:g.pid}),{mode:384})}catch(e){throw w(t,{recursive:!0,force:!0}),e}break}catch(e){if(e.code!==`EEXIST`)throw e;if(this.recoverLock(t),Date.now()-n>1e4)throw Error(`Foundry storage is busy in another process`,{cause:e});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}try{return this.recover(),this.lockDepth=1,this.initializeProviders(),e()}finally{this.lockDepth=0,w(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=T(e);if(!Er(e))return;let n=E.join(e,`recovering`);try{S(n)}catch(e){if(e.code===`EEXIST`){let e=T(n);Er(n)&&T(n).ino===e.ino&&w(n,{recursive:!0,force:!0})}return}if(pe(E.join(n,`owner.json`),JSON.stringify({pid:g.pid}),{mode:384,flag:`wx`}),T(e).ino!==t.ino||!Er(e)){w(n,{recursive:!0,force:!0});return}w(e,{recursive:!0,force:!0})}catch{}}recover(){let e=E.join(this.path,`.transaction.json`);if(!x(e))return;let t=JSON.parse(C(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=E.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!x(e)){let e=x(t)?ue(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,E.join(`providers`,e)))},...e.map(e=>({file:E.join(`providers`,e),value:null}))]};wr(E.join(this.path,`.transaction.json`),n),this.applyJournal(n)}x(t)&&ue(t).length===0&&(fe(t),Cr(this.path))}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(C(E.join(this.path,`providers.json`),`utf8`));if(!Array.isArray(e))throw TypeError(`Invalid Foundry providers collection`);let t=/* @__PURE__ */ new Set;for(let n of e){if(!n||typeof n.id!=`string`||t.has(n.id))throw Error(`Invalid or duplicate provider ID`);this.recordPath(`providers`,n.id),t.add(n.id)}return structuredClone(e)}applyJournal(e){for(let t of e.changes){let e=E.resolve(this.path,t.file),n=E.relative(this.path,e);if(n.startsWith(`..`)||E.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|(?:providers|captures|fetch-jobs)[/\\][^/\\]+\.json)$/u.test(n))throw Error(`Invalid storage recovery journal`);t.value===null?(w(e,{force:!0}),Cr(E.dirname(e))):wr(e,t.value)}w(E.join(this.path,`.transaction.json`),{force:!0}),Cr(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=E.join(this.path,t);if(!x(e))return;n=JSON.parse(C(e,`utf8`))}let r=n;if(this.recordPath(e,r.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(r)}all(e){return this.locked(()=>{if(e===`providers`)return this.readProviders();let t=this.collectionPath(e),n=new Set(ue(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>E.relative(this.path,E.join(t,e.name))));if(this.changes){let e=E.relative(this.path,t);for(let t of this.changes.keys())E.dirname(t)===e&&n.add(t)}let r=[];for(let t of n){let n=this.readRecord(e,t);n&&r.push(n)}return r})}get(e,t){return this.locked(()=>{let n=this.recordPath(e,t);return e===`providers`?this.all(e).find(e=>e.id===t):this.readRecord(e,n)})}readSettings(){return this.locked(()=>{if(this.changes?.has(`settings.json`))return structuredClone(this.changes.get(`settings.json`));let e=E.join(this.path,`settings.json`);return x(e)?Ue(JSON.parse(C(e,`utf8`))):structuredClone(j)})}put(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);let n=this.recordPath(e,t.id);if(e===`providers`){let n=this.all(e),r=n.findIndex(e=>e.id===t.id);r===-1?n.push(t):n[r]=t,this.changes.set(`providers.json`,structuredClone(n))}else this.changes.set(n,structuredClone(t))}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,Ue(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map;let t=!1;try{let n=e(this);if(n instanceof Promise)throw TypeError(`Storage transactions must be synchronous`);if(this.changes.size>0){let e={changes:[...this.changes].map(([e,t])=>({file:e,value:t}))};wr(E.join(this.path,`.transaction.json`),e),t=!0,this.applyJournal(e)}return n}catch(e){throw t&&this.recover(),e}finally{this.changes=null}})}snapshot(){return this.locked(()=>({formatVersion:1,settings:this.readSettings(),providers:this.all(`providers`),captures:this.all(`captures`),fetchJobs:this.all(`fetchJobs`)}))}replace(e){this.transaction(()=>{for(let t of Tr){if(t===`providers`){this.changes?.set(`providers.json`,structuredClone(e.providers));continue}let n=this.all(t);for(let e of n)this.changes?.set(this.recordPath(t,e.id),null);let r=e[t];for(let e of r)this.put(t,e)}this.setSettings(e.settings)})}close(){this.closed=!0}};function Or(e=Jn()){let t=new Dr(e);try{return t.transaction(()=>{let n=t.readSettings();x(E.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function kr(){return Yn(),Or()}const Ar={input:{type:`string`,description:`JSON payload; use "-" to read it from stdin`,valueHint:`json`},"input-file":{type:`string`,description:`Path to a JSON payload file`,valueHint:`path`}};async function X(e){let t;try{let n=kr();t={storage:n,runtime:xr(n)},Pr(await e(t))}catch(e){let t=Fr(e);console.error(JSON.stringify({error:t},null,2)),g.exitCode=1}finally{t?.storage.close()}}async function jr(e){if(e.input!==void 0&&e.inputFile!==void 0)throw new Z(`CONFLICTING_INPUT`,`Use either --input or --input-file, not both`);if(e.input===void 0&&e.inputFile===void 0)throw new Z(`INPUT_REQUIRED`,`Provide a JSON payload with --input or --input-file`);let t;try{t=e.inputFile===void 0?e.input===`-`?await Mr():e.input??``:e.inputFile===`-`?await Mr():await u(e.inputFile,`utf8`)}catch(e){throw new Z(`INPUT_READ_FAILED`,e instanceof Error?e.message:`Unable to read JSON input`)}try{return JSON.parse(t)}catch{throw new Z(`INVALID_JSON`,`Input must be valid JSON`)}}async function Mr(){let e=[];for await(let t of g.stdin)e.push(typeof t==`string`?t:t.toString(`utf8`));return e.join(``)}function Nr(e){let t=e??g.env.FOUNDRY_PASSPHRASE;if(!t)throw new Z(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var Z=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Pr(e){console.log(JSON.stringify(e,null,2))}function Fr(e){return e instanceof Error?{code:Ir(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Ir(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}function Lr(e,t){return e.listJobs(t.id)[0]}async function Rr(e,t,n){let r=await zr(e,t.id,n.id),i=e.get(t.id);return{capture:i.capture,rawResponse:i.rawResponse,job:r}}async function zr(e,t,n){let i=Br(e,t,n);for(;i.status!==`succeeded`&&i.status!==`failed`;)await r(250),i=Br(e,t,n);return i}function Br(e,t,n){let r=e.getJob(t,n);if(!r)throw new Z(`JOB_NOT_FOUND`,`Fetch job not found`);return r}const Vr=e({meta:{name:`list`,description:`List fetch jobs for a capture`,alias:[`ls`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return X(({runtime:t})=>t.services.captureRuntime.service.listJobs(e[`capture-id`]))}}),Hr=e({meta:{name:`get`,description:`Read one fetch job owned by a capture`,alias:[`show`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0},"job-id":{type:`positional`,description:`Fetch job ID`,required:!0}},run({args:e}){return X(({runtime:t})=>{let n=t.services.captureRuntime.service.getJob(e[`capture-id`],e[`job-id`]);if(!n)throw new Z(`JOB_NOT_FOUND`,`Fetch job not found`);return n})}}),Ur=e({meta:{name:`recapture`,description:`Run a new fetch job for a capture and wait for completion`},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return X(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.recapture(e[`capture-id`]);return zr(n,e[`capture-id`],r.id)})}}),Wr=e({meta:{name:`jobs`,description:`Inspect and run jobs for a capture`},subCommands:{list:Vr,get:Hr,recapture:Ur}}),Gr=e({meta:{name:`list`,description:`List captures`,alias:[`ls`]},args:{filter:{type:`enum`,description:`Capture filter`,options:[`all`,`no-successful`],default:`all`}},run({args:e}){return X(({runtime:t})=>t.services.captureRuntime.service.list(je(e.filter)))}}),Kr=e({meta:{name:`counts`,description:`Read capture counts`},run(){return X(({runtime:e})=>e.services.captureRuntime.service.counts())}}),qr=e({meta:{name:`get`,description:`Read a capture and its latest successful fetcher response`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return X(({runtime:t})=>t.services.captureRuntime.service.get(e.id))}}),Jr=e({meta:{name:`create`,description:`Capture a URL`,alias:[`add`]},args:{url:{type:`positional`,description:`HTTP or HTTPS URL`,required:!0},note:{type:`string`,description:`User note`,valueHint:`text`}},run({args:e}){return X(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.create(Ae({url:e.url,userNote:e.note}));return Rr(n,r,Lr(n,r))})}}),Yr=e({meta:{name:`recapture`,description:`Create a new fetch job for an existing capture`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return X(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.recapture(e.id),i=n.get(e.id).capture;return Rr(n,i,r)})}}),Xr=e({meta:{name:`note`,description:`Replace a capture user note`},args:{id:{type:`positional`,description:`Capture ID`,required:!0},note:{type:`positional`,description:`New note; use an empty string to clear it`,required:!0}},run({args:e}){return X(({runtime:t})=>t.services.captureRuntime.service.updateNote(e.id,e.note))}}),Zr=e({meta:{name:`delete`,description:`Delete a capture and its fetch jobs`,alias:[`remove`,`rm`]},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return X(({runtime:t})=>(t.services.captureRuntime.service.delete(e.id),{deleted:!0,id:e.id}))}}),Qr=e({meta:{name:`captures`,description:`Manage captured pages`,alias:[`capture`]},subCommands:{list:Gr,counts:Kr,get:qr,create:Jr,recapture:Yr,note:Xr,delete:Zr,jobs:Wr}}),$r=e({meta:{name:`status`,description:`Read data-transfer and fetch-job status`},run(){return X(({runtime:e})=>e.services.dataTransferService.getStatus())}}),ei=e({meta:{name:`export`,description:`Write an encrypted Foundry backup`},args:{passphrase:{type:`string`,description:`Encryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`},output:{type:`string`,description:`Destination .foundry-backup path`,valueHint:`path`,alias:[`o`]},force:{type:`boolean`,description:`Overwrite an existing destination file`,default:!1}},run({args:e}){return X(async({runtime:t})=>{let n=t.services.dataTransferService,r=Nr(e.passphrase);n.cleanupStaleTransfers();let i=await n.createExport(r),a=ii(e.output);try{await ai(i,a,e.force)}finally{await n.removeExportFile(i.filePath)}return{...i,filePath:a}})}}),ti=e({meta:{name:`inspect`,description:`Validate a Foundry backup without importing it`},args:{file:{type:`positional`,description:`Path to a .foundry-backup file`,required:!0},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return X(async({runtime:t})=>{let n=t.services.dataTransferService;n.cleanupStaleTransfers();let r=await n.inspectImport(E.resolve(e.file),Nr(e.passphrase));try{return r}finally{await n.cancelImport(r.importId)}})}}),ni=e({meta:{name:`import`,description:`Validate and replace local Foundry data from a backup`,alias:[`restore`]},args:{file:{type:`positional`,description:`Path to a .foundry-backup file`,required:!0},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return X(async({runtime:t})=>{let n=t.services.dataTransferService;n.cleanupStaleTransfers();let r=await n.inspectImport(E.resolve(e.file),Nr(e.passphrase));return await n.commitImport(r.importId),{status:`imported`,preview:r}})}}),ri=e({meta:{name:`data-transfer`,description:`Export or import encrypted Foundry backups`,alias:[`data`]},subCommands:{status:$r,export:ei,inspect:ti,import:ni}});function ii(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`;return tn(E.resolve(n))}async function ai(e,t,n){await c(E.dirname(t),{recursive:!0,mode:448});let r=E.join(E.dirname(t),`.${E.basename(t)}.${y()}.tmp`);try{if(await a(e.filePath,r),g.platform!==`win32`&&await i(r,384),n){await f(r,t);return}if(x(t))throw oi(t);try{await s(r,t)}catch(e){throw si(e)?oi(t):e}}finally{await p(r,{force:!0})}}function oi(e){return new Z(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function si(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const ci=e({meta:{name:`list`,description:`List providers and model credentials`,alias:[`ls`]},run(){return X(({runtime:e})=>e.services.providerService.list())}}),li=e({meta:{name:`get`,description:`Read one provider`},args:{id:{type:`positional`,description:`Provider ID`,required:!0}},run({args:e}){return X(({runtime:t})=>{let n=t.services.providerService.get(e.id);if(!n)throw new Vn;return n})}}),ui=e({meta:{name:`create`,description:`Create a provider from a JSON payload`,alias:[`add`]},args:Ar,run({args:e}){return X(async({runtime:t})=>{let n=B(await jr(e));return t.services.providerService.save(n)})}}),di=e({meta:{name:`update`,description:`Replace a provider using a JSON payload`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},...Ar},run({args:e}){return X(async({runtime:t})=>{let n=B(await jr(e));return t.services.providerService.save(n,e.id)})}}),fi=e({meta:{name:`set-status`,description:`Change a provider status`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},status:{type:`enum`,description:`New provider status`,options:[...Bt],required:!0}},run({args:e}){return X(({runtime:t})=>t.services.providerService.setStatus(e.id,Wt(e.status)))}}),pi=e({meta:{name:`models`,description:`Discover models for a saved provider`},args:{id:{type:`positional`,description:`Provider ID`,required:!0}},run({args:e}){return X(({runtime:t})=>t.services.providerService.fetchModels(e.id))}}),mi=e({meta:{name:`models-for-connection`,description:`Discover models before saving a provider`},args:Ar,run({args:e}){return X(async({runtime:t})=>{let n=Ut(await jr(e));return t.services.providerService.fetchModelsForConnection(n)})}}),hi=e({meta:{name:`providers`,description:`Manage model providers`,alias:[`provider`]},subCommands:{list:ci,get:li,create:ui,update:di,"set-status":fi,models:pi,"models-for-connection":mi}}),gi=[`agents`,`claude`];function _i(e){if(!yi(e)||!Array.isArray(e.targets))throw new vi(`targets must be an array`);if(e.targets.length===0)throw new vi(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!gi.includes(e))throw new vi(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var vi=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function yi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const bi=e({meta:{name:`get`,description:`Read Foundry settings as JSON`,alias:[`show`]},run(){return X(({runtime:e})=>e.services.settingsService.read())}}),xi=e({meta:{name:`update`,description:`Apply a settings patch`},args:Ar,run({args:e}){return X(async({runtime:t})=>{let n=We(await jr(e));return t.services.settingsService.update(n)})}}),Si=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return X(({runtime:e})=>e.services.settingsService.openConfigFolder())}}),Ci=e({meta:{name:`download-skill`,description:`Copy the bundled Foundry skill into user-level skill targets`},args:{target:{type:`string`,description:`Comma-separated targets: .agents, .claude`,valueHint:`.agents,.claude`,required:!0}},run({args:e}){return X(({runtime:t})=>{let n=_i({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.services.settingsSkillCopyService.copyToTargets(n.targets)})}}),wi=e({meta:{name:`settings`,description:`Read or update Foundry settings`},subCommands:{get:bi,update:xi,open:Si,"download-skill":Ci}});function Ti(e,t=()=>{}){let n=new k;return n.get(`/`,t=>{let n=je(t.req.query(`filter`));return t.json(e.list(n))}),n.get(`/counts`,t=>t.json(e.counts())),n.post(`/`,async n=>{try{let r=Ae(await Ei(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return Q(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return Q(t,e)}}),n.post(`/:id/recapture`,n=>{try{let r=n.req.param(`id`),i=e.recapture(r);return t({captureId:r,action:`recaptured`}),n.json(i,202)}catch(e){return Q(n,e)}}),n.delete(`/:id`,n=>{try{let r=n.req.param(`id`);return e.delete(r),t({captureId:r,action:`deleted`}),n.body(null,204)}catch(e){return Q(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=Me(await Ei(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return Q(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return Q(t,e)}}),n}async function Ei(e){try{return await e.req.json()}catch{throw new Ne(`Request body must be valid JSON`)}}function Q(e,t){if(t instanceof Ne)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof A)return e.json({error:{code:t.code,message:t.message}},Di(t.code));throw t}function Di(e){switch(e){case`CAPTURE_NOT_FOUND`:return 404;case`CAPTURE_ALREADY_EXISTS`:case`ACTIVE_JOB_EXISTS`:return 409;case`FETCHER_NOT_CONFIGURED`:return 503;default:return 400}}function Oi(e,t=()=>{},{maximumUploadBytes:n=4296015872}={}){let r=new k;return r.get(`/status`,t=>t.json(e.getStatus())),r.post(`/export`,async t=>{try{let n=await Mi(t),r=await e.createExport(n),i=b(r.filePath);return i.on(`close`,()=>{e.removeExportFile(r.filePath)}),t.body(ge.toWeb(i),200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${E.basename(r.filePath)}"`,"x-foundry-provider-count":String(r.providerCount),"x-foundry-capture-count":String(r.captureCount),"x-foundry-job-count":String(r.jobCount)})}catch(e){return Ni(t,e)}}),r.post(`/inspect`,async t=>{let r;try{if(t.req.header(`content-type`)?.split(`;`,1)[0]?.trim().toLowerCase()!==`application/octet-stream`)throw new U(`INVALID_ARCHIVE`,`The Foundry backup must be uploaded as application/octet-stream`);Ai(t,n);let i=ji(t,`x-foundry-passphrase`);if(!i)throw new U(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);let a=ji(t,`x-foundry-filename`)?.trim()||`foundry.foundry-backup`;return r=await e.createUploadTarget(),await ki(t,r.filePath,n),t.json(await e.inspectImport(r.filePath,i,a))}catch(e){return Ni(t,e)}finally{await r?.cleanup()}}),r.post(`/imports/:id/commit`,async n=>{try{return await e.commitImport(n.req.param(`id`)),t(),n.json({status:`imported`})}catch(e){return Ni(n,e)}}),r.delete(`/imports/:id`,async t=>{try{return await e.cancelImport(t.req.param(`id`)),t.body(null,204)}catch(e){return Ni(t,e)}}),r}async function ki(e,t,n){let r=e.req.raw.body;if(!r)throw new U(`INVALID_ARCHIVE`,`A Foundry backup file is required`);let i=0,a=new _e({transform(e,t,r){i+=e.byteLength,i>n?r(new U(`INVALID_ARCHIVE`,`The Foundry archive is too large`)):r(null,e)}});try{await D(ge.fromWeb(r),a,se(t,{mode:384}))}catch(e){throw e instanceof U?e:new U(`IO_ERROR`,`Unable to receive the Foundry archive`,{cause:e})}if(i===0)throw new U(`INVALID_ARCHIVE`,`A Foundry backup file is required`)}function Ai(e,t){let n=e.req.header(`content-length`);if(n===void 0)return;let r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new U(`INVALID_ARCHIVE`,`The upload length is invalid`);if(r>t)throw new U(`INVALID_ARCHIVE`,`The Foundry archive is too large`)}function ji(e,t){let n=e.req.header(t);if(n!==void 0)try{return decodeURIComponent(n)}catch{throw new U(`INVALID_ARCHIVE`,`The ${t} header is invalid`)}}async function Mi(e){try{let t=await e.req.json();if(typeof t!=`object`||!t||!(`passphrase`in t)||typeof t.passphrase!=`string`)throw new U(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);return t.passphrase}catch(e){throw e instanceof U?e:new U(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}}function Ni(e,t){let n=Qt(t);return e.json({error:{code:n.code,message:n.message}},Pi(n.code))}function Pi(e){switch(e){case`IMPORT_NOT_FOUND`:return 404;case`ACTIVE_JOBS`:case`BUSY`:return 409;case`IO_ERROR`:return 500;default:return 400}}function Fi(e,t=()=>{}){let n=new k;return n.get(`/`,t=>t.json(e.list())),n.get(`/:id`,t=>{let n=e.get(t.req.param(`id`));return n?t.json(n):t.json({error:{code:`PROVIDER_NOT_FOUND`,message:`Provider not found`}},404)}),n.get(`/:id/models`,async t=>{try{return t.json(await e.fetchModels(t.req.param(`id`)))}catch(e){return $(t,e)}}),n.post(`/models`,async t=>{try{let n=Ut(await Ii(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return $(t,e)}}),n.post(`/`,async n=>{try{let r=B(await Ii(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return $(n,e)}}),n.put(`/:id`,async n=>{try{let r=B(await Ii(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return $(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Ii(n),i=Wt(typeof r==`object`&&r&&`status`in r?r.status:void 0),a=e.setStatus(n.req.param(`id`),i);return t(),n.json(a)}catch(e){return $(n,e)}}),n}async function Ii(e){try{return await e.req.json()}catch{throw new z(`Request body must be valid JSON`)}}function $(e,t){if(t instanceof z)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Vn)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Vt)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof K)return e.json({error:{code:t.code,message:t.message}},502);throw t}function Li(e,t=()=>{},n=new $n){let r=new k;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=We(await Ri(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return zi(n,e)}}),r.post(`/config-folder/open`,t=>{let n=e.openConfigFolder();return t.json({configFolder:n.configFolder},202)}),r.post(`/skill-copy`,async e=>{try{let t=_i(await Ri(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return zi(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function Ri(e){try{return await e.req.json()}catch{throw new M(`Request body must be valid JSON`)}}function zi(e,t){if(t instanceof M||t instanceof vi)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof er)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function Bi(e){let t=new k;return t.get(`/codex`,async t=>{try{return t.json(await e.getCodexSnapshot())}catch(e){return Vi(t,e)}}),t.get(`/claude`,async t=>{try{return t.json(await e.getClaudeSnapshot())}catch(e){return Vi(t,e)}}),t}function Vi(e,t){if(t instanceof ir)switch(t.code){case`CODEX_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CODEX_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500);case`CLAUDE_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CLAUDE_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500)}throw t}function Hi(e){let t=new k;return t.get(`/`,t=>De(t,async n=>{await Ui(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Wi(n,e)}),c=setInterval(()=>{r||Gi(n)},15e3),l=()=>{o()};t.req.raw.signal.addEventListener(`abort`,l,{once:!0}),n.onAbort(o),t.req.raw.signal.aborted&&o(),await i,clearInterval(c),s(),t.req.raw.signal.removeEventListener(`abort`,l)})),t}function Ui(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Wi(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Gi(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}function Ki(e){return e===`/api`||e.startsWith(`/api/`)}function qi(e,t={}){let n=new k,r=t.workspaceMutationGate??t.dataTransferService?.workspaceMutationGate??new Nn,i=t.providerService??new Kn(e),a=t.settingsService??new Zn(e),o=t.settingsSkillCopyService??new $n,s=t.sessionService??new vr;return n.use(`/api/*`,Pn(r)),n.get(`/api/health`,t=>t.json({status:`ok`,version:ke,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,Hi(t.eventHub)),n.route(`/api/providers`,Fi(i,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,Li(a,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(`settings.changed`,e)},o)),n.route(`/api/sessions`,Bi(s)),t.captureService&&n.route(`/api/captures`,Ti(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),t.dataTransferService&&n.route(`/api/data-transfer`,Oi(t.dataTransferService,()=>{t.eventHub?.publish(`data-transfer.imported`,{})})),n.notFound(e=>Ki(e.req.path)?e.json({error:{code:`NOT_FOUND`,message:`API route not found`}},404):e.text(`Not Found`,404)),n.onError((e,t)=>(console.error(e),Ki(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function Ji(e,t,n){let r=qi(t,n),i=Ee({root:e});r.use(`*`,(e,t)=>Ki(e.req.path)?t():i(e,t));let a=Ee({root:e,path:`/index.html`});return r.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!Ki(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&E.posix.extname(e.req.path)===``?a(e,t):t()),r}const{dirname:Yi,join:Xi,resolve:Zi}=E,Qi=Yi(Se(import.meta.url));function $i(){let e=[Zi(Qi,`web`),Zi(g.cwd(),`dist/web`)].find(e=>x(Xi(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function ea({storage:e,webRoot:t=$i(),onListening:n}){let r=xr(e),i=Ji(t,e,r.apiOptions);r.start();let a=Te({fetch:i.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return a.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),g.exitCode=1}),a}function ta(e,t){return new Promise((n,r)=>{let i=Oe();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function na(e){let t=`xdg-open`,n=[e];g.platform===`darwin`?t=`open`:g.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=ye(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const ra=e({meta:{name:`web`,description:`Start the Foundry local Web UI`},args:{open:{type:`boolean`,description:`Open the Web UI in the default browser`,negativeDescription:`Do not open the browser`,default:!0}},async run({args:e}){try{await ta(`127.0.0.1`,11111)}catch(e){ia(e);return}ea({storage:kr(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&na(t)}})}});function ia(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),g.exitCode=1}function aa(){let t,r=e({meta:{name:`help`,description:`Show Foundry CLI help`,hidden:!0},async run(){await n(t)}});return t=e({meta:{name:`foundry`,version:ke,description:`Manage local Foundry data or start the Web UI`},default:`help`,subCommands:{help:r,web:ra,settings:wi,providers:hi,captures:Qr,"data-transfer":ri}}),t}t(aa());export{};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as n,u as Mt,a as Ne,b as It,j as K,L as jt,p as Je,c as Bt,d as At,e as Dt,g as Nt,h as qt,m as mt,k as Ht,o as Yt,l as _t,n as Ft,t as $t,s as Vt,q as Kt,v as Gt,w as Ut}from"./index-D2I6J0FK.js";const Wt=48,Xt=.25,Jt=/^(\d+(?:\.\d+)?|\.\d+)(px|%)$/i;function St(e,o){if(typeof e=="number")return Number.isFinite(e)&&e>0&&e<=1?e*o:null;const s=Jt.exec(e.trim());if(s===null)return null;const c=Number.parseFloat(s[1]);return c>0?s[2].toLowerCase()==="%"?c/100*o:c:null}function Qt(e){return St(e,1)!==null}function Zt(e,o){const s=[];for(const c of e){const h=St(c,o);h!==null&&s.push(h)}return s}function en(e,o,s=Wt){const h=[0,...o.filter(f=>f>0&&f<e).map(f=>e-f)].sort((f,u)=>f-u),p=[];for(const f of h){const u=p[p.length-1];(u===void 0||f-u>=s)&&p.push(f)}return p}function tn(e,o){return o.reduce((s,c)=>Math.abs(c-e)<Math.abs(s-e)?c:s,o[0])}const nn=.3;function rn(e,o){if(e.length<2||o<=0)return null;const s=e[e.length-1];return o-s<=Xt*o?s:null}function Ye(e,o,s,c){const h=c!==null,p=h?o[o.length-2]:o[o.length-1],f=h?c:s,u=h?nn:0;return e<=p?1:e>=f?u:1-(1-u)*((e-p)/(f-p))}function on(e,o,s,c){let h=o;if(s>0){const p=o.filter(f=>f>=c);p.length>0&&(h=p)}else if(s<0){const p=o.filter(f=>f<=c);p.length>0&&(h=p)}return tn(e,h)}const _e="--_sheet-keyboard-inset",sn=new Set(["button","checkbox","color","file","hidden","image","radio","range","reset","submit"]);function Ve(){return window.visualViewport?.height??window.innerHeight}function cn(){return Ve()>=window.innerHeight-.5}function an(){const e=window.navigator.userAgent;return/iPad|iPhone|iPod/.test(e)||e.includes("Macintosh")&&window.navigator.maxTouchPoints>1}function Ke(e){return e instanceof HTMLTextAreaElement?!e.disabled&&!e.readOnly:e instanceof HTMLInputElement?!e.disabled&&!e.readOnly&&!sn.has((e.getAttribute("type")??"text").toLowerCase()):e instanceof HTMLElement&&e.matches('[contenteditable]:not([contenteditable="false"])')}function gt(e,o){if(!(e instanceof Element))return null;const s=e.closest('input, textarea, [contenteditable]:not([contenteditable="false"])');if(o.contains(s)&&Ke(s))return s;const c=e.closest("label"),h=c instanceof HTMLLabelElement?c.control:null;return o.contains(h)&&Ke(h)?h:null}function ln({bodyRef:e,bottomClearance:o,isEnabled:s,isFullyExpanded:c,isPageScrollLocked:h,isSheetTraveling:p,isOpen:f,isPresented:u,sheetRef:j}){const E=n.useRef(!1),B=n.useRef(!1),A=n.useRef(c),M=n.useRef(f);A.current=c,M.current=f,n.useEffect(()=>{if(!s||!p)return;const i=j.current,b=document.activeElement;i&&b instanceof HTMLElement&&b!==i&&i.contains(b)&&(B.current=E.current,i.focus({preventScroll:!0}))},[s,p,j]),n.useEffect(()=>{if(!s||!u||f)return;const i=j.current,b=document.activeElement;i&&b instanceof HTMLElement&&b!==i&&i.contains(b)&&(B.current=E.current,b.blur())},[s,f,u,j]),n.useEffect(()=>{const i=e.current,b=j.current;if(!s||!u||!i)return;let P=null,D=null;const N=an(),ee=()=>{i.style.setProperty(_e,"0px"),P=null,D=null,E.current=!1,B.current=!1},F=(d,x)=>{if(typeof i.scrollBy!="function"){i.scrollTop+=d;return}const S=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;i.scrollBy({top:d,behavior:x&&!S?"smooth":"instant"})},Q=(d,x)=>{const S=i.getBoundingClientRect(),I=d.getBoundingClientRect(),q=Ve(),se=Math.max(0,S.bottom-q)>0?o:0,re=S.top,C=Math.min(S.bottom,q-se);C<=re||(I.bottom>C?F(I.bottom-C,x):I.top<re&&F(I.top-re,x))},R=d=>{const x=Ve();if(cn()){ee();return}if(Math.max(0,d.bodyBottom-x)===0){ee();return}const I=Math.max(0,d.bodyBottom-(x-o));i.style.setProperty(_e,`${I}px`)},w=d=>{if(!A.current)return;const x=gt(d.relatedTarget,i);if(x){x!==document.activeElement&&x.focus({preventScroll:!0});return}const S=gt(d.target,i);M.current&&S&&!d.relatedTarget&&b?.focus({preventScroll:!0})},te=()=>{const d=document.activeElement;if(!A.current||!(d instanceof HTMLElement)||!i.contains(d)||!Ke(d)){if(B.current&&P){R(P);return}ee();return}B.current=!1;const x=i.getBoundingClientRect(),S=Ve(),I=Math.max(0,x.bottom-S),q=I>0?o:0;P=I>0?{bodyBottom:x.bottom}:null,h&&I>0&&!E.current&&(D={x:window.scrollX,y:window.scrollY}),E.current=I>0;const me=I>0?Math.max(0,x.bottom-(S-q)):0;i.style.setProperty(_e,`${me}px`),Q(d,I>0)};let H=0;const k=()=>{cancelAnimationFrame(H),H=requestAnimationFrame(te)},X=()=>{const d=D;if(d==null||window.scrollX===d.x&&window.scrollY===d.y)return;window.scrollTo(d.x,d.y);const x=document.activeElement;x instanceof HTMLElement&&i.contains(x)&&Ke(x)&&Q(x,!1)},y=typeof ResizeObserver>"u"?null:new ResizeObserver(k),$=()=>{if(!y)return;y.disconnect();const d=new Set([i]);b&&d.add(b);for(const S of i.children)d.add(S);const x=document.activeElement;if(x instanceof HTMLElement&&i.contains(x))for(let S=x;S&&S!==i;S=S.parentElement)d.add(S);for(const S of d)y.observe(S)},G=typeof MutationObserver>"u"?null:new MutationObserver(d=>{d.every(x=>x.type==="attributes"&&x.target===i)||($(),k())}),U=()=>{$(),k()},Y=()=>{B.current=E.current,k()},_=d=>{d.target===b&&d.propertyName==="transform"&&k()},ne=window.visualViewport;return N&&document.addEventListener("blur",w,!0),i.addEventListener("focusin",U),i.addEventListener("focusout",Y),b?.addEventListener("transitionend",_),ne?.addEventListener("resize",k),ne?.addEventListener("scroll",k),window.addEventListener("scroll",X),window.addEventListener("resize",k),G?.observe(i,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),$(),k(),()=>{cancelAnimationFrame(H),N&&document.removeEventListener("blur",w,!0),i.removeEventListener("focusin",U),i.removeEventListener("focusout",Y),b?.removeEventListener("transitionend",_),ne?.removeEventListener("resize",k),ne?.removeEventListener("scroll",k),window.removeEventListener("scroll",X),window.removeEventListener("resize",k),y?.disconnect(),G?.disconnect(),i.style.removeProperty(_e),E.current=!1,B.current=!1}},[e,o,s,h,u,j])}const pt=.998,un=pt/(1-pt),fn=48,Qe=100,Fe=.4,yt=40;function Ze(e){return e.syntheticTouch===!0}const dn=.35,xn=4,et=8;function hn(){typeof navigator>"u"||typeof navigator.vibrate!="function"||Rt()||navigator.vibrate(8)}function mn(e,o){let s=o[0],c=Math.abs(e-s);for(const f of o){const u=Math.abs(e-f);u<c&&(c=u,s=f)}if(c>=yt)return e;const h=c/yt,p=1-h*h;return e+(s-e)*p}function tt(e,o,s){return Math.max(0,e-o-s)}function Tt(e){const o=Number.parseFloat(getComputedStyle(e).paddingBlockEnd);return Number.isFinite(o)?o:0}function bt(e){if(!e)return 0;const o=Tt(e);return Math.max(0,e.scrollHeight-e.clientHeight-o)-e.scrollTop}function gn(e){if(e.scrollHeight-e.clientHeight<=1)return!1;const{overflowY:o}=getComputedStyle(e);return o==="auto"||o==="scroll"}function kt(e,o){const s=[];for(let c=e instanceof Element?e:null;c!=null&&c!==o;c=c.parentElement)c instanceof HTMLElement&&gn(c)&&s.push(c);return s.push(o),s}function pn(e){return e.scrollTop<=0}function yn(e){return e.scrollTop+e.clientHeight>=e.scrollHeight-1}function $e(e){return e.every(pn)}function nt(e){return e.every(yn)}function Le(e,o,s){return Math.max(0,e-s-o)}function Rt(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function bn({isOpen:e,canDismiss:o=!0,offscreenBlockEndInset:s=0,onDismiss:c,snapHeights:h,onSnap:p,onScrimOpacity:f}){const[u,j]=n.useState(0),[E,B]=n.useState(0),[A,M]=n.useState(!1),[i,b]=n.useState(!1),[P,D]=n.useState(0),[N,ee]=n.useState(0),[F,Q]=n.useState(0),R=n.useRef(0),w=n.useRef(0),[te,H]=n.useState(null),[k,X]=n.useState(!1),y=n.useRef(0),$=n.useRef(null),G=n.useRef(null),U=n.useRef(s);U.current=Math.max(0,s);const Y=n.useCallback(t=>{const r=Math.max(0,t);R.current=r,Q(r)},[]),_=n.useCallback(t=>{const r=Math.max(0,t);Math.abs(r-y.current)>.5&&(y.current=r,ee(r))},[]),ne=n.useCallback(()=>{X(!0),$.current=null,H(null);const t=G.current;G.current=null,t!=null&&_(t)},[_]),d=n.useCallback((t,r,m,T,g,L,a)=>{const v=tt(t,m,L);if(a&&Math.abs(T-r)>.5&&!Rt()){G.current=v,$.current=g,H(g);return}G.current=null,$.current=null,H(null),X(Math.abs(g-m)>.5),_(v)},[_]),x=n.useRef(0);A||(x.current=E);const S=n.useRef(e);S.current=e;const I=n.useRef(h);I.current=h;const q=n.useRef(c),me=n.useRef(o),se=n.useRef(p),re=n.useRef(f);n.useEffect(()=>{q.current=c,me.current=o,se.current=p,re.current=f});const C=n.useRef(null),ge=n.useRef(0),pe=n.useRef(null),ye=n.useRef(null),be=n.useRef(null);n.useLayoutEffect(()=>{if(!k)return;pe.current?.offsetHeight;const t=requestAnimationFrame(()=>{X(!1)});return()=>cancelAnimationFrame(t)},[k]);const le=n.useCallback(t=>{t<=0||!S.current||x.current>0||(ge.current=t,D(r=>r===t?r:t))},[]),Ge=n.useCallback(t=>{if(be.current?.disconnect(),be.current=null,pe.current=t,!t||typeof ResizeObserver>"u"){t&&le(t.getBoundingClientRect().height);return}le(t.getBoundingClientRect().height);const r=new ResizeObserver(m=>{const T=m[0];if(T){const g=T.borderBoxSize?.[0]?.blockSize;le(g??T.target.getBoundingClientRect().height)}});r.observe(t),be.current=r},[le]);n.useEffect(()=>()=>be.current?.disconnect(),[]),n.useEffect(()=>{e&&(j(0),B(0),M(!1),b(!1),X(!1),Y(0),w.current=0,y.current=0,$.current=null,G.current=null,ee(0),H(null))},[e,Y]);const ue=n.useCallback(()=>ge.current>0?ge.current:pe.current?.getBoundingClientRect().height??0,[]),oe=n.useCallback(t=>{const r=Le(t,0,U.current),m=en(r,I.current?.()??[]);return{offsets:m,peekOffset:rn(m,r)}},[]),Re=n.useCallback(()=>{const t=pe.current;if(!t)return ge.current;const r=t.style.height;if(r==="")return t.getBoundingClientRect().height;t.style.height="";const m=t.getBoundingClientRect().height;return t.style.height=r,m},[]),ce=n.useCallback(()=>{if(!S.current||C.current!=null||$.current!=null)return;const t=Re();if(t<=0)return;const{offsets:r,peekOffset:m}=oe(t),T=Math.min(w.current,r.length-1),g=r[T],L=g===m?0:g,a=R.current;if(t===ge.current&&Math.abs(g-x.current)<=.5&&Math.abs(L-a)<=.5)return;ge.current=t,D(t),w.current=T,d(a,g,L,g,a,bt(ye.current),!1),Y(L),B(g),se.current?.(Le(t,g,U.current));const v=r[r.length-1],l=Le(t,v,U.current);re.current?.(Ye(g,r,v+l*Fe,m))},[Re,d,Y,oe]);n.useEffect(()=>{if(!(!e||typeof window>"u"))return window.addEventListener("resize",ce),window.addEventListener("orientationchange",ce),()=>{window.removeEventListener("resize",ce),window.removeEventListener("orientationchange",ce)}},[e,ce]);const Be=n.useRef(!1);n.useLayoutEffect(()=>{if(!Be.current){Be.current=!0;return}ce()},[ce,h]);const qe=n.useCallback((t,r)=>{const m=pe.current;if(m==null)return;const T=t-r;m.style.transform=T!==0?`translateY(${T}px)`:""},[]),J=n.useCallback(t=>{const r=C.current;if(r==null)return;C.current=null,t?.hasPointerCapture?.(r.pointerId)&&t.releasePointerCapture(r.pointerId),j(r.baseOffset),M(!1),b(!1),d(r.baseLayoutOffset,r.baseOffset,r.baseLayoutOffset,r.renderedOffset,r.layoutOffset,r.naturalEndGap,!0);const{offsets:m,peekOffset:T}=oe(r.height),g=m[m.length-1],L=Le(r.height,g,U.current),a=g+L*Fe;re.current?.(Ye(r.baseOffset,m,a,T))},[d,oe]);n.useEffect(()=>{const t=()=>J(),r=()=>{document.visibilityState==="hidden"&&J()};return window.addEventListener("blur",t),document.addEventListener("visibilitychange",r),()=>{window.removeEventListener("blur",t),document.removeEventListener("visibilitychange",r)}},[J]);const He=n.useCallback((t,r,m,T,g,L,a,v,l,z)=>{const{offsets:W,peekOffset:xe}=oe(m),Se=W[W.length-1],ae=Le(m,Se,U.current),Oe=Se+ae*Fe,De=g>fn?t+r*un:t,xt=Te=>{const ht=Te===xe?0:Te;d(a,Te,ht,v,l,z,!0),Y(ht),w.current=Math.max(0,W.indexOf(Te)),B(Te),se.current?.(Le(m,Te,U.current)),re.current?.(Ye(Te,W,Oe,xe)),Te!==L&&hn()};if(T>0&&De>Oe){me.current?(d(a,L,a,a,a,z,!1),q.current()):xt(Se);return}const zt=on(Math.min(Math.max(De,0),Se),W,T,L);xt(zt)},[d,Y,oe]),O=n.useCallback((t,r,m)=>{const T=t.currentTarget,g=Ze(t);g||T.setPointerCapture?.(t.pointerId);const L=m??t.clientY,a=bt(ye.current),v=R.current;C.current={syntheticTouch:g,pointerId:t.pointerId,startCoord:L,lastCoord:t.clientY,lastTime:t.timeStamp,samples:[{t:t.timeStamp,y:t.clientY}],velocity:0,height:r,baseOffset:E,baseLayoutOffset:v,renderedOffset:E,layoutOffset:v,naturalEndGap:a,hasTraveled:!1},_(tt(v,v,a)),j(E),M(!0)},[E,_]),ke=n.useCallback(t=>{t.button!==0||!t.isPrimary||(t.preventDefault(),O(t,ue()))},[O,ue]),Z=n.useCallback(t=>{C.current!=null&&(t.preventDefault(),J(t.currentTarget))},[J]),fe=n.useCallback(t=>{C.current?.syntheticTouch||C.current?.pointerId===t.pointerId&&J()},[J]),ve=n.useCallback(t=>{const r=C.current;if(!r||r.pointerId!==t.pointerId||r.syntheticTouch&&!Ze(t))return;const m=t.clientY-r.startCoord;if(t.timeStamp-r.lastTime>0){for(r.lastCoord=t.clientY,r.lastTime=t.timeStamp,r.samples.push({t:t.timeStamp,y:t.clientY});r.samples.length>2&&t.timeStamp-r.samples[0].t>Qe;)r.samples.shift();const Oe=r.samples[0],De=Math.min(t.timeStamp-Oe.t,Qe);r.velocity=De>0?(t.clientY-Oe.y)/De:0}const{offsets:g,peekOffset:L}=oe(r.height),a=r.baseOffset+m,v=g[g.length-1];let l;a<0?l=Math.max(-48,a*dn):a>v?l=a:l=mn(a,g);const z=l<r.baseOffset?0:r.baseLayoutOffset,W=z!==r.layoutOffset;r.renderedOffset=l,r.layoutOffset=z,x.current=l,qe(l,z),W&&j(l),!r.hasTraveled&&l!==r.baseOffset&&(r.hasTraveled=!0,b(!0)),_(tt(r.baseLayoutOffset,z,r.naturalEndGap));const xe=g[g.length-1],Se=Le(r.height,xe,U.current),ae=xe+Se*Fe;re.current?.(Ye(l,g,ae,L))},[oe,_,qe]),Ee=n.useCallback(t=>{const r=C.current;if(!r||r.pointerId!==t.pointerId||r.syntheticTouch&&!Ze(t))return;const m=t.currentTarget,T=t.clientY-r.startCoord,g=Math.max(0,r.baseOffset+T),L=T===0?0:T>0?1:-1,a=t.timeStamp-r.lastTime<Qe?r.velocity:0;C.current=null,r.syntheticTouch||m.releasePointerCapture?.(t.pointerId),M(!1),b(!1),He(g,a,r.height||1,L,Math.abs(T),r.baseOffset,r.baseLayoutOffset,r.renderedOffset,r.layoutOffset,r.naturalEndGap)},[He]),de=n.useRef(null),Ce=n.useCallback(t=>{if(t.button!==0||!t.isPrimary)return;const r=kt(t.target,t.currentTarget);if(!$e(r)){de.current=null;return}de.current={pointerId:t.pointerId,startCoord:t.clientY,scrollers:r}},[]),ze=n.useCallback(t=>{if(C.current){ve(t);return}const r=de.current;if(!r||r.pointerId!==t.pointerId)return;const m=t.clientY-r.startCoord;m>et&&$e(r.scrollers)?(de.current=null,O(t,ue(),r.startCoord),ve(t)):m<0&&(de.current=null)},[O,ve,ue]),Ae=n.useCallback(t=>{de.current=null,!C.current?.syntheticTouch&&C.current&&Ee(t)},[Ee]),we=n.useRef(null),Me=n.useRef(null),ie=n.useCallback(t=>{we.current=null,de.current=null,J(t)},[J]),V=n.useRef(O),Ie=n.useRef(J),je=n.useRef(ie),Pe=n.useRef(ve),st=n.useRef(Ee),Ue=n.useRef(ue);n.useEffect(()=>{V.current=O,Ie.current=J,je.current=ie,Pe.current=ve,st.current=Ee,Ue.current=ue});const ct=n.useCallback(t=>{const r=(a,v)=>({syntheticTouch:!0,pointerId:a.identifier,clientY:a.clientY,timeStamp:Date.now(),currentTarget:v,setPointerCapture:()=>{},releasePointerCapture:()=>{}}),m=a=>{const v=a.currentTarget;if(a.touches.length>1){je.current(v);return}const l=a.changedTouches[0];if(!l){we.current=null;return}const z=kt(a.target,v),W=$e(z),xe=nt(z)&&x.current>0;we.current={id:l.identifier,startY:l.clientY,scrollers:z,top:W,bottom:xe,contentEndY:null,promotedAtContentEnd:!1}},T=a=>{const v=a.currentTarget;if(a.touches.length>1){je.current(v);return}const l=we.current;if(C.current){const ae=[...a.changedTouches].find(Oe=>Oe.identifier===C.current?.pointerId);if(!ae)return;if(l?.promotedAtContentEnd&&l.contentEndY!=null){if(ae.clientY>=l.contentEndY){l.contentEndY=null,l.promotedAtContentEnd=!1,Ie.current(v);return}Pe.current(r(ae,v));return}a.preventDefault(),Pe.current(r(ae,v));return}if(!l)return;const z=[...a.changedTouches].find(ae=>ae.identifier===l.id);if(!z)return;const W=z.clientY-l.startY,xe=l.top&&W>et&&$e(l.scrollers),Se=l.bottom&&W<-et&&nt(l.scrollers);if(xe||Se){a.preventDefault(),we.current=null,V.current(r(z,v),Ue.current(),l.startY),Pe.current(r(z,v));return}(l.top&&W<0||l.bottom&&W>0)&&(l.top=!1,l.bottom=!1),x.current>0&&nt(l.scrollers)?l.contentEndY==null?l.contentEndY=z.clientY:l.contentEndY-z.clientY>=xn&&(l.promotedAtContentEnd=!0,V.current(r(z,v),Ue.current(),l.contentEndY),Pe.current(r(z,v))):l.contentEndY=null},g=a=>{we.current=null;const v=C.current?.pointerId;if(v==null)return;const l=[...a.changedTouches].find(W=>W.identifier===v),z=a.currentTarget;l?st.current(r(l,z)):a.touches.length===0&&Ie.current(z)},L=ye.current;if(L&&Me.current){const a=Me.current;L.removeEventListener("touchstart",a.start),L.removeEventListener("touchmove",a.move),L.removeEventListener("touchend",a.end),L.removeEventListener("touchcancel",a.end)}ye.current=t,t?(t.addEventListener("touchstart",m,{passive:!0}),t.addEventListener("touchmove",T,{passive:!1}),t.addEventListener("touchend",g,{passive:!0}),t.addEventListener("touchcancel",g,{passive:!0}),Me.current={start:m,move:T,end:g}):Me.current=null},[]),it=Mt("(prefers-reduced-motion: reduce)"),at=n.useCallback(t=>{if(y.current<=0)return;const r=Tt(t),m=Math.max(0,t.scrollHeight-t.clientHeight-r),T=Math.max(0,t.scrollTop-m);T<y.current-.5&&_(T)},[_]),lt=n.useCallback(t=>{C.current!=null||$.current!=null||at(t.currentTarget)},[at]),ut=n.useCallback(t=>{if(!t.isPrimary){ie(t.currentTarget);return}ke(t)},[ke,ie]),ft=n.useCallback(t=>{if(!t.isPrimary){ie(t.currentTarget);return}Ce(t)},[Ce,ie]),We=n.useCallback(t=>{t.touches.length>1&&ie(t.currentTarget)},[ie]),dt=n.useCallback(t=>{const r=C.current;r?.pointerId!==t.pointerId||r.syntheticTouch||J(t.currentTarget)},[J]),Xe=A?u:E,Pt=n.useMemo(()=>({style:{transform:Xe!==0?`translateY(${Xe}px)`:void 0,transition:e&&(A||k||it)?"none":void 0,touchAction:"pinch-zoom",overscrollBehavior:"contain"}}),[Xe,A,e,k,it]),Ot=n.useMemo(()=>({style:{touchAction:"pinch-zoom",cursor:"grab"},onContextMenu:Z,onLostPointerCapture:fe,onPointerDown:ut,onPointerMove:ve,onPointerUp:Ee,onPointerCancel:dt,onTouchStart:We,onTouchMove:We}),[Ee,Z,dt,ut,We,fe,ve]),Lt=n.useMemo(()=>({ref:ct,onContextMenu:Z,onLostPointerCapture:fe,onPointerDown:ft,onPointerMove:ze,onPointerUp:Ae,onPointerCancel:Ae,onScroll:lt}),[ct,Ae,ft,ze,lt,Z,fe]);return{sheetRef:Ge,contentProps:Pt,handleProps:Ot,bodyProps:Lt,bodyElementRef:ye,dragOffset:u,settledOffset:E,isDragging:A,isTraveling:i,activeOffsetRef:x,sheetHeight:P,scrollPreservationInset:N,settlingLayoutOffset:te,settledLayoutOffset:F,completeScrollAreaSettle:ne}}const vt={hug:"92dvh",capped:"62dvh",tall:"92dvh"},kn=48,vn=48,En=50;function wn(){return typeof window>"u"?0:window.innerHeight}function Sn(e){let o="";for(const s of e??[])o+=`${typeof s}:${s}|`;return o}const he={sheet:{kfzvcC:"x67bb7w",kB7OPa:"x9f619",kVAEAm:"x1n2onr6",k1xSpc:"x78zum5",kXwgrk:"xdt5ytf",kAzted:"x2lwn1j",kzqmXN:"xh8yej3",ks0D6T:"x11gisft",kWkggS:"x10xzikg",kEafiO:"x11xkdxz",kPef9Z:"x13fuv20",kLZC3w:"x1pc3f07",k2ei4v:"xgbv0en",kVhnKS:"x1t7ytsu",kGJrpR:"x1j92z86",ke9TFa:"xw8tdv1",k8ry5P:"x18b5jzi",kBCPoo:"x1gejf6u",krdFHd:"x81l70g",kfmiAY:"x7hs6f1",kGVxlE:"x1kcpxr7",kI3sdo:"x1a2a7pz",kVQacm:"xb3r6kr",kGO01o:"x1wkw6tp",k1K539:"x1if0o47",k3aq6I:"xnn1q72 xhbqy3z",kSiTet:"x1hc1fzr",k1ekBW:"xwcsmn1",kIyJzY:"x80gvsz",kAMwcw:"xlr8y92",k6sLGO:"x1q1rmc8",k6CgDc:"xzg1mie",$$css:!0},sheetClosing:{k3aq6I:"x1weeur4",kAMwcw:"xv2sgk5",$$css:!0},sheetFading:{kSiTet:"xg01cxk",$$css:!0},sheetInactive:{kfzvcC:"x47corl",$$css:!0},body:{kzQI83:"x1iyjqo2",kAzted:"x2lwn1j",kB7OPa:"x9f619",kFalU9:"xge0x1e",kInvED:"x1wfwxd8 x1nw7mhf",kWkggS:"x10xzikg",kGO01o:"x18d9i69",$$css:!0},content:{k1xSpc:"xufnvkl",kB7OPa:"x9f619",kZKoxP:"x5yr21d",kAzted:"x121v3j4",$$css:!0},tallKeyboardBody:{kFlMNQ:"xrw9175",k5JduY:"x1s928wv",kc3QkE:"xhkezso",k4zj60:"xu6fald",kloYau:"x2q1x1w",$$css:!0},budget:{kZKoxP:"x1tpcejd",$$css:!0},hugHeight:{kZKoxP:"xg7h5cd",kskxy:"x14bu9tk",$$css:!0}};function Tn(e){return e.kind==="open"?e.entering?"entering":null:e.kind==="retained"?e.motion==="covered"?null:e.motion:e.kind==="exiting"?"exiting":null}function Et(e,o,s){if(e==null)return s(),()=>{};let c=!1,h=null;const p=()=>{c||(c=!0,h!=null&&clearTimeout(h),e.removeEventListener("transitionend",f),e.removeEventListener("transitioncancel",f),s())},f=i=>{i.target===e&&i.propertyName===o&&p()};e.addEventListener("transitionend",f),e.addEventListener("transitioncancel",f);const u=getComputedStyle(e);if(e.style.transition.trim()==="none"||u.transition.trim()==="none")return p(),()=>{};const j=u.transitionProperty.split(",").map(i=>i.trim()),E=u.transitionDuration.split(",").map(wt),B=u.transitionDelay.split(",").map(wt);let A=!1;const M=j.reduce((i,b,P)=>{if(b!==o&&b!=="all")return i;const D=E[P%E.length],N=B[P%B.length];return D==null||N==null?(A=!0,i):Math.max(i,D+N)},0);return A?()=>{e.removeEventListener("transitionend",f),e.removeEventListener("transitioncancel",f)}:M<=0?(p(),()=>{}):(h=setTimeout(p,M+En),()=>{h!=null&&clearTimeout(h),e.removeEventListener("transitionend",f),e.removeEventListener("transitioncancel",f)})}function wt(e){const o=e.trim();if(!/^-?(?:\d+|\d*\.\d+)(?:ms|s)$/.test(o))return null;const s=Number.parseFloat(e);return o.endsWith("ms")?s:s*1e3}function rt({ref:e,state:o,height:s,label:c,children:h,padding:p,snapPoints:f,className:u,style:j,tabIndex:E,xstyle:B,isSwipeDismissAllowed:A=!0,isPageScrollLocked:M=!1,onDismiss:i,onScrimOpacity:b,onElementChange:P,onMotionStart:D,onMotionComplete:N,...ee}){const F=n.useRef(null),Q=n.useRef(o),R=n.useRef(!1),w=n.useRef(D),te=n.useRef(N),H=n.useRef(null),k=n.useRef(null),X=o.kind==="open"&&o.entering,y=Q.current,$=y.kind==="open"&&y.entering;X&&!$?R.current=y.kind==="retained":X||(R.current=!1),n.useLayoutEffect(()=>{Q.current=o,w.current=D,te.current=N},[N,D,o]);const G=o.kind==="open",U=o.kind!=="hidden",Y=o.kind==="retained",_=Y||o.kind==="exiting",ne=o.kind==="exiting",d=Y&&o.motion==="fading",x=Y?o.alignmentOffset:0,S=Sn(f),I=n.useRef(f);I.current=f;const{snapHeights:q,ignoredSnapPointsMessage:me}=n.useMemo(()=>{if(S==="")return{snapHeights:void 0,ignoredSnapPointsMessage:""};const V=(I.current??[]).filter(Ie=>!Qt(Ie));return{snapHeights:()=>Zt(I.current??[],wn()),ignoredSnapPointsMessage:V.length===0?"":`snapPoints ignored ${JSON.stringify(V)}. A snap point is a viewport fraction above 0 and up to 1 (0.5 is half the screen), a px length ('320px'), or a percentage ('50%').`}},[S]);Ne("BottomSheet",me,me!=="");const{contentProps:se,handleProps:re,bodyProps:C,bodyElementRef:ge,sheetRef:pe,dragOffset:ye,settledOffset:be,isDragging:le,isTraveling:Ge,sheetHeight:ue,scrollPreservationInset:oe,settlingLayoutOffset:Re,settledLayoutOffset:ce,completeScrollAreaSettle:Be}=bn({isOpen:G,canDismiss:A,offscreenBlockEndInset:kn,onDismiss:i,snapHeights:q,onScrimOpacity:b}),{getViewportProps:qe,getContentProps:J}=It({axis:"both",keyboardAccess:{owner:"contentOrViewport",label:c},overscroll:"contain",stickyContainment:"always"}),He=n.useCallback(V=>{pe(V),F.current=V,P?.(V)},[P,pe]);ln({bodyRef:ge,bottomClearance:vn,isEnabled:s==="tall",isFullyExpanded:be===0,isPageScrollLocked:M,isSheetTraveling:Ge,isOpen:G,isPresented:U,sheetRef:F}),n.useImperativeHandle(e,()=>F.current,[]);const O=Tn(o);n.useLayoutEffect(()=>{if(O!=null){if(H.current=null,k.current=null,O==="entering"&&R.current){k.current=O;return}return Et(F.current,O==="fading"?"opacity":"transform",()=>{H.current===O?te.current?.(O):k.current=O})}},[O]),n.useLayoutEffect(()=>{if(Re!=null)return Et(F.current,"transform",Be)},[Be,Re]),n.useEffect(()=>{if(O!=null)return w.current?.(O),H.current=O,k.current===O&&(k.current=null,te.current?.(O)),()=>{H.current===O&&(H.current=null),k.current===O&&(k.current=null)}},[O]);const ke=p==null,Z=p??4,fe=Vt[Z],Ee=typeof s=="string"&&s in vt?vt[s]:typeof s=="number"?`${s}px`:s,de=ue>0;let Ce=se.style.transform,ze;if(de){const V=le?ye<be?0:ce:Re??ce,je=(le?ye:be)-V,Pe=le||Re!=null;ze=V>0||Pe?`${Math.max(0,ue-Math.max(0,V))}px`:void 0,Ce=je!==0?`translateY(${je}px)`:void 0}const Ae=x>0?[Ce,`translateY(${x}px)`].filter(Boolean).join(" "):Ce,we=G?Ce:Y?Ae:void 0,Me=j?.transform;n.useLayoutEffect(()=>{if(le||Me!=null)return;const V=F.current;V!=null&&(V.style.transform=we??"")});const ie={transition:se.style.transition,touchAction:se.style.touchAction,overscrollBehavior:se.style.overscrollBehavior,height:ze};return K.jsxs("div",{...ee,ref:He,tabIndex:E??-1,...mt($t("bottom-sheet"),Je(Ft.reset,_t.reset,he.sheet,Yt.reset,s==="hug"?he.hugHeight:he.budget,ne&&he.sheetClosing,d&&he.sheetFading,_&&he.sheetInactive,B),u,{"--_sheet-budget":Ee,...G?ie:Y||ne?{height:ze}:{},...j}),children:[K.jsx("div",{className:"x10l6tqk x13vifvy x1o0tod xtijo5x x1vjfegm x78zum5 x6s0dn4 xl56j7k xvpftlf xafqdz2 x1j4r261 x1jm3nie x16khyan",...re,"aria-hidden":"true",children:K.jsx("div",{className:"x1m747yf x11c6zpc xjspbzw x1m4xfpy"})}),K.jsx("div",{...qe({...C,...mt(Je(Ht.focusVisible,he.body,s==="tall"&&he.tallKeyboardBody),oe>0?{style:{paddingBlockEnd:`${oe}px`}}:{})}),children:K.jsx("div",{...J(Je(he.content,...Bt(ke?{useThemeDefault:"bottom-sheet"}:{paddingInnerX:fe,paddingInnerY:fe,paddingOuterX:fe,paddingOuterY:fe}),!ke&&Z!==4&&At[Z],!ke&&Z!==4&&Dt[Z],!ke&&Z!==4&&Nt[Z],!ke&&Z!==4&&qt[Z])),children:K.jsx(jt,{children:h})})})]})}rt.displayName="BottomSheetPanel";function Rn(){return K.jsx("div",{className:"xixxii4 x17y0mx6 x1ey2m1c x1kpxq89 x10xzikg xhtitgo x47corl x1cb67k9 xt2iwb0","data-sheet-edge-tint":"","aria-hidden":"true"})}const ot=n.createContext(null);ot.displayName="BottomSheetSwitcherContext";function Cn(e,o){switch(e){case"active":return{kind:"open",entering:!1};case"entering":return{kind:"open",entering:!0};case"covered":case"aligning":case"fading":return{kind:"retained",motion:e,alignmentOffset:o};case"exiting":return{kind:"exiting"};case"hidden":return{kind:"hidden"}}}function Ct(e,o){const s=document.activeElement;if(s!=null&&e?.contains(s))return;const c=e?.querySelector("[data-autofocus]");c!=null?c.focus({preventScroll:!0}):o&&e?.focus({preventScroll:!0})}function Pn({ref:e,isOpen:o,onOpenChange:s,label:c,children:h,height:p="capped",snapPoints:f,hasScrim:u=!0,finalFocusRef:j,purpose:E="info",xstyle:B,...A}){const M=n.useRef(null),i=n.useRef(null),b=n.useRef(null),[P,D]=n.useState(o),N=o||P,ee=o?{kind:"open",entering:!1}:P?{kind:"exiting"}:{kind:"hidden"},F=n.useCallback(()=>{o&&E!=="required"&&s(!1)},[o,s,E]),Q=n.useCallback(()=>{E==="info"&&s(!1)},[s,E]),R=n.useCallback(y=>{i.current=y},[]),w=n.useCallback(y=>{M.current?.style.setProperty("--_sheet-scrim-opacity",String(y))},[]);n.useEffect(()=>{const y=M.current;if(y==null||!o)return;D(!0),y.style.setProperty("--_sheet-scrim-opacity","1"),y.open||(u?(b.current=document.activeElement,y.showModal()):y.show(),Ct(i.current,u))},[u,o]),n.useEffect(()=>{!o&&P&&u&&w(0)},[w,u,o,P]);const te=n.useCallback(y=>{if(y!=="exiting"||o)return;const $=M.current;$?.open&&$.close(),D(!1),(j?.current??b.current)?.focus(),b.current=null},[j,o]);Kt(N&&u),Ne("BottomSheet","requires a non-empty `label` for an accessible name; the open sheet has no built-in heading to derive one from.",o&&!c);const{shouldDismissOnCloseRequest:H}=Gt({isActive:N,escapeBehavior:o&&E!=="required"?"close":"block",onDismiss:F,getContainer:()=>M.current,isPresent:()=>M.current?.open??!1}),k=n.useCallback(y=>{y.preventDefault(),H()&&F()},[F,H]),X=n.useCallback(y=>{u&&y.target===y.currentTarget&&Q()},[Q,u]);return K.jsxs("dialog",{...{0:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz"},8:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq"},4:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x15h3t91 x142juwg x1viac0w"},12:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x15h3t91 x142juwg x1viac0w"},2:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz x1cz9k3x"},10:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq x1cz9k3x"},6:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x142juwg x1viac0w x1cz9k3x"},14:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x142juwg x1viac0w x1cz9k3x"},1:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz x47corl xfo81ep xh8yej3 x5yr21d"},9:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq x47corl xfo81ep xh8yej3 x5yr21d"},5:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x15h3t91 x142juwg x1viac0w x47corl xfo81ep xh8yej3 x5yr21d"},13:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x15h3t91 x142juwg x1viac0w x47corl xfo81ep xh8yej3 x5yr21d"},3:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz x1cz9k3x x47corl xfo81ep xh8yej3 x5yr21d"},11:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq x1cz9k3x x47corl xfo81ep xh8yej3 x5yr21d"},7:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x142juwg x1viac0w x1cz9k3x x47corl xfo81ep xh8yej3 x5yr21d"},15:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x142juwg x1viac0w x1cz9k3x x47corl xfo81ep xh8yej3 x5yr21d"}}[!!N<<3|!!u<<2|!!(u&&!o&&P)<<1|!u<<0],ref:M,"aria-label":c,"aria-hidden":!o&&P?"true":void 0,"aria-modal":u&&o?"true":void 0,role:E==="required"?"alertdialog":void 0,inert:!o&&P?!0:void 0,onCancel:k,onClick:X,children:[K.jsx("div",{className:"x10l6tqk x17y0mx6 x1ey2m1c x78zum5 xl56j7k x47corl",children:K.jsx(rt,{...A,ref:e,state:ee,height:p,label:c,snapPoints:f,isSwipeDismissAllowed:E==="info",isPageScrollLocked:N&&u,xstyle:B,onDismiss:Q,onScrimOpacity:w,onElementChange:R,onMotionComplete:te,children:K.jsx(Ut,{children:h})})}),K.jsx(Rn,{})]})}function On({switcher:e,ref:o,sheetId:s,label:c,children:h,height:p="capped",snapPoints:f,purpose:u="info",xstyle:j,...E}){const{activeSheet:B,hasScrim:A,onActiveSheetChange:M,getSheetPhase:i,getSheetAlignmentOffset:b,registerSheetElement:P,registerSheetLabel:D,registerSheetPurpose:N,onSheetEnterStart:ee,onSheetTransitionComplete:F,onSheetScrimOpacityChange:Q}=e,R=typeof s=="string"&&s.length>0,w=R?i(s):"hidden",te=R?b(s):0,H=Cn(w,te),k=w==="active"||w==="entering",X=w==="covered"||w==="aligning"||w==="fading"||w==="exiting",y=w!=="hidden",$=w==="active"||w==="entering",G=n.useRef(null),U=n.useRef(w),Y=U.current,_=n.useRef(!1);n.useLayoutEffect(()=>{U.current=w},[w]);const ne=n.useCallback(()=>{u==="info"&&R&&B===s&&M(null)},[B,R,M,u,s]),d=n.useCallback(q=>{G.current=q,R&&P(s,q)},[R,P,s]),x=n.useCallback(q=>{q==="entering"&&R&&ee(s)},[R,ee,s]),S=n.useCallback(q=>{R&&F({sheetId:s,phase:q})},[R,F,s]),I=n.useCallback(q=>{R&&Q(s,q)},[R,Q,s]);return n.useLayoutEffect(()=>{if(R)return D(s,c),()=>D(s,null)},[R,c,D,s]),n.useLayoutEffect(()=>{if(R)return N(s,u),()=>N(s,null)},[R,u,N,s]),n.useEffect(()=>{if(k){const q=Y==="active"||Y==="entering";(!_.current||!q)&&Ct(G.current,A),_.current=!0}else w==="hidden"&&(_.current=!1)},[A,k,w,Y]),Ne("BottomSheet","requires a non-empty `label` for an accessible name; the open sheet has no built-in heading to derive one from.",k&&!c),K.jsx("div",{...{0:{className:"x10l6tqk x17y0mx6 x1ey2m1c x78zum5 xl56j7k x47corl"},2:{className:"x10l6tqk x17y0mx6 x1ey2m1c xl56j7k x47corl x1s85apg"},1:{className:"x10l6tqk x17y0mx6 x1ey2m1c x78zum5 xl56j7k x47corl x1vjfegm"},3:{className:"x10l6tqk x17y0mx6 x1ey2m1c xl56j7k x47corl x1s85apg x1vjfegm"}}[!y<<1|!!$<<0],hidden:!y,"aria-hidden":X?"true":void 0,inert:X?!0:void 0,children:K.jsx(rt,{...E,ref:o,state:H,height:p,label:c,snapPoints:f,isSwipeDismissAllowed:u==="info",isPageScrollLocked:A,xstyle:j,onDismiss:ne,onScrimOpacity:I,onElementChange:d,onMotionStart:x,onMotionComplete:S,children:K.jsx(ot,{value:null,children:h})})})}function Ln(e){const o=n.use(ot),s=e.sheetId,c=typeof s=="string"&&s.length>0;return Ne("BottomSheet","requires a non-empty `sheetId` when nested in BottomSheetSwitcher; standalone `isOpen` / `onOpenChange` props are ignored there.",o!=null&&!c),Ne("BottomSheet","`sheetId` only works inside BottomSheetSwitcher. Use `isOpen` and `onOpenChange` for a standalone sheet.",o==null&&s!=null),o!=null?K.jsx(On,{...e,switcher:o}):K.jsx(Pn,{...e})}Ln.displayName="BottomSheet";export{Ln as BottomSheet};
|
|
1
|
+
import{r as n,u as Mt,a as Ne,b as It,j as K,L as jt,p as Je,c as Bt,d as At,e as Dt,g as Nt,h as qt,m as mt,k as Ht,o as Yt,l as _t,n as Ft,t as $t,s as Vt,q as Kt,v as Gt,w as Ut}from"./index-DgKRKmzj.js";const Wt=48,Xt=.25,Jt=/^(\d+(?:\.\d+)?|\.\d+)(px|%)$/i;function St(e,o){if(typeof e=="number")return Number.isFinite(e)&&e>0&&e<=1?e*o:null;const s=Jt.exec(e.trim());if(s===null)return null;const c=Number.parseFloat(s[1]);return c>0?s[2].toLowerCase()==="%"?c/100*o:c:null}function Qt(e){return St(e,1)!==null}function Zt(e,o){const s=[];for(const c of e){const h=St(c,o);h!==null&&s.push(h)}return s}function en(e,o,s=Wt){const h=[0,...o.filter(f=>f>0&&f<e).map(f=>e-f)].sort((f,u)=>f-u),p=[];for(const f of h){const u=p[p.length-1];(u===void 0||f-u>=s)&&p.push(f)}return p}function tn(e,o){return o.reduce((s,c)=>Math.abs(c-e)<Math.abs(s-e)?c:s,o[0])}const nn=.3;function rn(e,o){if(e.length<2||o<=0)return null;const s=e[e.length-1];return o-s<=Xt*o?s:null}function Ye(e,o,s,c){const h=c!==null,p=h?o[o.length-2]:o[o.length-1],f=h?c:s,u=h?nn:0;return e<=p?1:e>=f?u:1-(1-u)*((e-p)/(f-p))}function on(e,o,s,c){let h=o;if(s>0){const p=o.filter(f=>f>=c);p.length>0&&(h=p)}else if(s<0){const p=o.filter(f=>f<=c);p.length>0&&(h=p)}return tn(e,h)}const _e="--_sheet-keyboard-inset",sn=new Set(["button","checkbox","color","file","hidden","image","radio","range","reset","submit"]);function Ve(){return window.visualViewport?.height??window.innerHeight}function cn(){return Ve()>=window.innerHeight-.5}function an(){const e=window.navigator.userAgent;return/iPad|iPhone|iPod/.test(e)||e.includes("Macintosh")&&window.navigator.maxTouchPoints>1}function Ke(e){return e instanceof HTMLTextAreaElement?!e.disabled&&!e.readOnly:e instanceof HTMLInputElement?!e.disabled&&!e.readOnly&&!sn.has((e.getAttribute("type")??"text").toLowerCase()):e instanceof HTMLElement&&e.matches('[contenteditable]:not([contenteditable="false"])')}function gt(e,o){if(!(e instanceof Element))return null;const s=e.closest('input, textarea, [contenteditable]:not([contenteditable="false"])');if(o.contains(s)&&Ke(s))return s;const c=e.closest("label"),h=c instanceof HTMLLabelElement?c.control:null;return o.contains(h)&&Ke(h)?h:null}function ln({bodyRef:e,bottomClearance:o,isEnabled:s,isFullyExpanded:c,isPageScrollLocked:h,isSheetTraveling:p,isOpen:f,isPresented:u,sheetRef:j}){const E=n.useRef(!1),B=n.useRef(!1),A=n.useRef(c),M=n.useRef(f);A.current=c,M.current=f,n.useEffect(()=>{if(!s||!p)return;const i=j.current,b=document.activeElement;i&&b instanceof HTMLElement&&b!==i&&i.contains(b)&&(B.current=E.current,i.focus({preventScroll:!0}))},[s,p,j]),n.useEffect(()=>{if(!s||!u||f)return;const i=j.current,b=document.activeElement;i&&b instanceof HTMLElement&&b!==i&&i.contains(b)&&(B.current=E.current,b.blur())},[s,f,u,j]),n.useEffect(()=>{const i=e.current,b=j.current;if(!s||!u||!i)return;let P=null,D=null;const N=an(),ee=()=>{i.style.setProperty(_e,"0px"),P=null,D=null,E.current=!1,B.current=!1},F=(d,x)=>{if(typeof i.scrollBy!="function"){i.scrollTop+=d;return}const S=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;i.scrollBy({top:d,behavior:x&&!S?"smooth":"instant"})},Q=(d,x)=>{const S=i.getBoundingClientRect(),I=d.getBoundingClientRect(),q=Ve(),se=Math.max(0,S.bottom-q)>0?o:0,re=S.top,C=Math.min(S.bottom,q-se);C<=re||(I.bottom>C?F(I.bottom-C,x):I.top<re&&F(I.top-re,x))},R=d=>{const x=Ve();if(cn()){ee();return}if(Math.max(0,d.bodyBottom-x)===0){ee();return}const I=Math.max(0,d.bodyBottom-(x-o));i.style.setProperty(_e,`${I}px`)},w=d=>{if(!A.current)return;const x=gt(d.relatedTarget,i);if(x){x!==document.activeElement&&x.focus({preventScroll:!0});return}const S=gt(d.target,i);M.current&&S&&!d.relatedTarget&&b?.focus({preventScroll:!0})},te=()=>{const d=document.activeElement;if(!A.current||!(d instanceof HTMLElement)||!i.contains(d)||!Ke(d)){if(B.current&&P){R(P);return}ee();return}B.current=!1;const x=i.getBoundingClientRect(),S=Ve(),I=Math.max(0,x.bottom-S),q=I>0?o:0;P=I>0?{bodyBottom:x.bottom}:null,h&&I>0&&!E.current&&(D={x:window.scrollX,y:window.scrollY}),E.current=I>0;const me=I>0?Math.max(0,x.bottom-(S-q)):0;i.style.setProperty(_e,`${me}px`),Q(d,I>0)};let H=0;const k=()=>{cancelAnimationFrame(H),H=requestAnimationFrame(te)},X=()=>{const d=D;if(d==null||window.scrollX===d.x&&window.scrollY===d.y)return;window.scrollTo(d.x,d.y);const x=document.activeElement;x instanceof HTMLElement&&i.contains(x)&&Ke(x)&&Q(x,!1)},y=typeof ResizeObserver>"u"?null:new ResizeObserver(k),$=()=>{if(!y)return;y.disconnect();const d=new Set([i]);b&&d.add(b);for(const S of i.children)d.add(S);const x=document.activeElement;if(x instanceof HTMLElement&&i.contains(x))for(let S=x;S&&S!==i;S=S.parentElement)d.add(S);for(const S of d)y.observe(S)},G=typeof MutationObserver>"u"?null:new MutationObserver(d=>{d.every(x=>x.type==="attributes"&&x.target===i)||($(),k())}),U=()=>{$(),k()},Y=()=>{B.current=E.current,k()},_=d=>{d.target===b&&d.propertyName==="transform"&&k()},ne=window.visualViewport;return N&&document.addEventListener("blur",w,!0),i.addEventListener("focusin",U),i.addEventListener("focusout",Y),b?.addEventListener("transitionend",_),ne?.addEventListener("resize",k),ne?.addEventListener("scroll",k),window.addEventListener("scroll",X),window.addEventListener("resize",k),G?.observe(i,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),$(),k(),()=>{cancelAnimationFrame(H),N&&document.removeEventListener("blur",w,!0),i.removeEventListener("focusin",U),i.removeEventListener("focusout",Y),b?.removeEventListener("transitionend",_),ne?.removeEventListener("resize",k),ne?.removeEventListener("scroll",k),window.removeEventListener("scroll",X),window.removeEventListener("resize",k),y?.disconnect(),G?.disconnect(),i.style.removeProperty(_e),E.current=!1,B.current=!1}},[e,o,s,h,u,j])}const pt=.998,un=pt/(1-pt),fn=48,Qe=100,Fe=.4,yt=40;function Ze(e){return e.syntheticTouch===!0}const dn=.35,xn=4,et=8;function hn(){typeof navigator>"u"||typeof navigator.vibrate!="function"||Rt()||navigator.vibrate(8)}function mn(e,o){let s=o[0],c=Math.abs(e-s);for(const f of o){const u=Math.abs(e-f);u<c&&(c=u,s=f)}if(c>=yt)return e;const h=c/yt,p=1-h*h;return e+(s-e)*p}function tt(e,o,s){return Math.max(0,e-o-s)}function Tt(e){const o=Number.parseFloat(getComputedStyle(e).paddingBlockEnd);return Number.isFinite(o)?o:0}function bt(e){if(!e)return 0;const o=Tt(e);return Math.max(0,e.scrollHeight-e.clientHeight-o)-e.scrollTop}function gn(e){if(e.scrollHeight-e.clientHeight<=1)return!1;const{overflowY:o}=getComputedStyle(e);return o==="auto"||o==="scroll"}function kt(e,o){const s=[];for(let c=e instanceof Element?e:null;c!=null&&c!==o;c=c.parentElement)c instanceof HTMLElement&&gn(c)&&s.push(c);return s.push(o),s}function pn(e){return e.scrollTop<=0}function yn(e){return e.scrollTop+e.clientHeight>=e.scrollHeight-1}function $e(e){return e.every(pn)}function nt(e){return e.every(yn)}function Le(e,o,s){return Math.max(0,e-s-o)}function Rt(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function bn({isOpen:e,canDismiss:o=!0,offscreenBlockEndInset:s=0,onDismiss:c,snapHeights:h,onSnap:p,onScrimOpacity:f}){const[u,j]=n.useState(0),[E,B]=n.useState(0),[A,M]=n.useState(!1),[i,b]=n.useState(!1),[P,D]=n.useState(0),[N,ee]=n.useState(0),[F,Q]=n.useState(0),R=n.useRef(0),w=n.useRef(0),[te,H]=n.useState(null),[k,X]=n.useState(!1),y=n.useRef(0),$=n.useRef(null),G=n.useRef(null),U=n.useRef(s);U.current=Math.max(0,s);const Y=n.useCallback(t=>{const r=Math.max(0,t);R.current=r,Q(r)},[]),_=n.useCallback(t=>{const r=Math.max(0,t);Math.abs(r-y.current)>.5&&(y.current=r,ee(r))},[]),ne=n.useCallback(()=>{X(!0),$.current=null,H(null);const t=G.current;G.current=null,t!=null&&_(t)},[_]),d=n.useCallback((t,r,m,T,g,L,a)=>{const v=tt(t,m,L);if(a&&Math.abs(T-r)>.5&&!Rt()){G.current=v,$.current=g,H(g);return}G.current=null,$.current=null,H(null),X(Math.abs(g-m)>.5),_(v)},[_]),x=n.useRef(0);A||(x.current=E);const S=n.useRef(e);S.current=e;const I=n.useRef(h);I.current=h;const q=n.useRef(c),me=n.useRef(o),se=n.useRef(p),re=n.useRef(f);n.useEffect(()=>{q.current=c,me.current=o,se.current=p,re.current=f});const C=n.useRef(null),ge=n.useRef(0),pe=n.useRef(null),ye=n.useRef(null),be=n.useRef(null);n.useLayoutEffect(()=>{if(!k)return;pe.current?.offsetHeight;const t=requestAnimationFrame(()=>{X(!1)});return()=>cancelAnimationFrame(t)},[k]);const le=n.useCallback(t=>{t<=0||!S.current||x.current>0||(ge.current=t,D(r=>r===t?r:t))},[]),Ge=n.useCallback(t=>{if(be.current?.disconnect(),be.current=null,pe.current=t,!t||typeof ResizeObserver>"u"){t&&le(t.getBoundingClientRect().height);return}le(t.getBoundingClientRect().height);const r=new ResizeObserver(m=>{const T=m[0];if(T){const g=T.borderBoxSize?.[0]?.blockSize;le(g??T.target.getBoundingClientRect().height)}});r.observe(t),be.current=r},[le]);n.useEffect(()=>()=>be.current?.disconnect(),[]),n.useEffect(()=>{e&&(j(0),B(0),M(!1),b(!1),X(!1),Y(0),w.current=0,y.current=0,$.current=null,G.current=null,ee(0),H(null))},[e,Y]);const ue=n.useCallback(()=>ge.current>0?ge.current:pe.current?.getBoundingClientRect().height??0,[]),oe=n.useCallback(t=>{const r=Le(t,0,U.current),m=en(r,I.current?.()??[]);return{offsets:m,peekOffset:rn(m,r)}},[]),Re=n.useCallback(()=>{const t=pe.current;if(!t)return ge.current;const r=t.style.height;if(r==="")return t.getBoundingClientRect().height;t.style.height="";const m=t.getBoundingClientRect().height;return t.style.height=r,m},[]),ce=n.useCallback(()=>{if(!S.current||C.current!=null||$.current!=null)return;const t=Re();if(t<=0)return;const{offsets:r,peekOffset:m}=oe(t),T=Math.min(w.current,r.length-1),g=r[T],L=g===m?0:g,a=R.current;if(t===ge.current&&Math.abs(g-x.current)<=.5&&Math.abs(L-a)<=.5)return;ge.current=t,D(t),w.current=T,d(a,g,L,g,a,bt(ye.current),!1),Y(L),B(g),se.current?.(Le(t,g,U.current));const v=r[r.length-1],l=Le(t,v,U.current);re.current?.(Ye(g,r,v+l*Fe,m))},[Re,d,Y,oe]);n.useEffect(()=>{if(!(!e||typeof window>"u"))return window.addEventListener("resize",ce),window.addEventListener("orientationchange",ce),()=>{window.removeEventListener("resize",ce),window.removeEventListener("orientationchange",ce)}},[e,ce]);const Be=n.useRef(!1);n.useLayoutEffect(()=>{if(!Be.current){Be.current=!0;return}ce()},[ce,h]);const qe=n.useCallback((t,r)=>{const m=pe.current;if(m==null)return;const T=t-r;m.style.transform=T!==0?`translateY(${T}px)`:""},[]),J=n.useCallback(t=>{const r=C.current;if(r==null)return;C.current=null,t?.hasPointerCapture?.(r.pointerId)&&t.releasePointerCapture(r.pointerId),j(r.baseOffset),M(!1),b(!1),d(r.baseLayoutOffset,r.baseOffset,r.baseLayoutOffset,r.renderedOffset,r.layoutOffset,r.naturalEndGap,!0);const{offsets:m,peekOffset:T}=oe(r.height),g=m[m.length-1],L=Le(r.height,g,U.current),a=g+L*Fe;re.current?.(Ye(r.baseOffset,m,a,T))},[d,oe]);n.useEffect(()=>{const t=()=>J(),r=()=>{document.visibilityState==="hidden"&&J()};return window.addEventListener("blur",t),document.addEventListener("visibilitychange",r),()=>{window.removeEventListener("blur",t),document.removeEventListener("visibilitychange",r)}},[J]);const He=n.useCallback((t,r,m,T,g,L,a,v,l,z)=>{const{offsets:W,peekOffset:xe}=oe(m),Se=W[W.length-1],ae=Le(m,Se,U.current),Oe=Se+ae*Fe,De=g>fn?t+r*un:t,xt=Te=>{const ht=Te===xe?0:Te;d(a,Te,ht,v,l,z,!0),Y(ht),w.current=Math.max(0,W.indexOf(Te)),B(Te),se.current?.(Le(m,Te,U.current)),re.current?.(Ye(Te,W,Oe,xe)),Te!==L&&hn()};if(T>0&&De>Oe){me.current?(d(a,L,a,a,a,z,!1),q.current()):xt(Se);return}const zt=on(Math.min(Math.max(De,0),Se),W,T,L);xt(zt)},[d,Y,oe]),O=n.useCallback((t,r,m)=>{const T=t.currentTarget,g=Ze(t);g||T.setPointerCapture?.(t.pointerId);const L=m??t.clientY,a=bt(ye.current),v=R.current;C.current={syntheticTouch:g,pointerId:t.pointerId,startCoord:L,lastCoord:t.clientY,lastTime:t.timeStamp,samples:[{t:t.timeStamp,y:t.clientY}],velocity:0,height:r,baseOffset:E,baseLayoutOffset:v,renderedOffset:E,layoutOffset:v,naturalEndGap:a,hasTraveled:!1},_(tt(v,v,a)),j(E),M(!0)},[E,_]),ke=n.useCallback(t=>{t.button!==0||!t.isPrimary||(t.preventDefault(),O(t,ue()))},[O,ue]),Z=n.useCallback(t=>{C.current!=null&&(t.preventDefault(),J(t.currentTarget))},[J]),fe=n.useCallback(t=>{C.current?.syntheticTouch||C.current?.pointerId===t.pointerId&&J()},[J]),ve=n.useCallback(t=>{const r=C.current;if(!r||r.pointerId!==t.pointerId||r.syntheticTouch&&!Ze(t))return;const m=t.clientY-r.startCoord;if(t.timeStamp-r.lastTime>0){for(r.lastCoord=t.clientY,r.lastTime=t.timeStamp,r.samples.push({t:t.timeStamp,y:t.clientY});r.samples.length>2&&t.timeStamp-r.samples[0].t>Qe;)r.samples.shift();const Oe=r.samples[0],De=Math.min(t.timeStamp-Oe.t,Qe);r.velocity=De>0?(t.clientY-Oe.y)/De:0}const{offsets:g,peekOffset:L}=oe(r.height),a=r.baseOffset+m,v=g[g.length-1];let l;a<0?l=Math.max(-48,a*dn):a>v?l=a:l=mn(a,g);const z=l<r.baseOffset?0:r.baseLayoutOffset,W=z!==r.layoutOffset;r.renderedOffset=l,r.layoutOffset=z,x.current=l,qe(l,z),W&&j(l),!r.hasTraveled&&l!==r.baseOffset&&(r.hasTraveled=!0,b(!0)),_(tt(r.baseLayoutOffset,z,r.naturalEndGap));const xe=g[g.length-1],Se=Le(r.height,xe,U.current),ae=xe+Se*Fe;re.current?.(Ye(l,g,ae,L))},[oe,_,qe]),Ee=n.useCallback(t=>{const r=C.current;if(!r||r.pointerId!==t.pointerId||r.syntheticTouch&&!Ze(t))return;const m=t.currentTarget,T=t.clientY-r.startCoord,g=Math.max(0,r.baseOffset+T),L=T===0?0:T>0?1:-1,a=t.timeStamp-r.lastTime<Qe?r.velocity:0;C.current=null,r.syntheticTouch||m.releasePointerCapture?.(t.pointerId),M(!1),b(!1),He(g,a,r.height||1,L,Math.abs(T),r.baseOffset,r.baseLayoutOffset,r.renderedOffset,r.layoutOffset,r.naturalEndGap)},[He]),de=n.useRef(null),Ce=n.useCallback(t=>{if(t.button!==0||!t.isPrimary)return;const r=kt(t.target,t.currentTarget);if(!$e(r)){de.current=null;return}de.current={pointerId:t.pointerId,startCoord:t.clientY,scrollers:r}},[]),ze=n.useCallback(t=>{if(C.current){ve(t);return}const r=de.current;if(!r||r.pointerId!==t.pointerId)return;const m=t.clientY-r.startCoord;m>et&&$e(r.scrollers)?(de.current=null,O(t,ue(),r.startCoord),ve(t)):m<0&&(de.current=null)},[O,ve,ue]),Ae=n.useCallback(t=>{de.current=null,!C.current?.syntheticTouch&&C.current&&Ee(t)},[Ee]),we=n.useRef(null),Me=n.useRef(null),ie=n.useCallback(t=>{we.current=null,de.current=null,J(t)},[J]),V=n.useRef(O),Ie=n.useRef(J),je=n.useRef(ie),Pe=n.useRef(ve),st=n.useRef(Ee),Ue=n.useRef(ue);n.useEffect(()=>{V.current=O,Ie.current=J,je.current=ie,Pe.current=ve,st.current=Ee,Ue.current=ue});const ct=n.useCallback(t=>{const r=(a,v)=>({syntheticTouch:!0,pointerId:a.identifier,clientY:a.clientY,timeStamp:Date.now(),currentTarget:v,setPointerCapture:()=>{},releasePointerCapture:()=>{}}),m=a=>{const v=a.currentTarget;if(a.touches.length>1){je.current(v);return}const l=a.changedTouches[0];if(!l){we.current=null;return}const z=kt(a.target,v),W=$e(z),xe=nt(z)&&x.current>0;we.current={id:l.identifier,startY:l.clientY,scrollers:z,top:W,bottom:xe,contentEndY:null,promotedAtContentEnd:!1}},T=a=>{const v=a.currentTarget;if(a.touches.length>1){je.current(v);return}const l=we.current;if(C.current){const ae=[...a.changedTouches].find(Oe=>Oe.identifier===C.current?.pointerId);if(!ae)return;if(l?.promotedAtContentEnd&&l.contentEndY!=null){if(ae.clientY>=l.contentEndY){l.contentEndY=null,l.promotedAtContentEnd=!1,Ie.current(v);return}Pe.current(r(ae,v));return}a.preventDefault(),Pe.current(r(ae,v));return}if(!l)return;const z=[...a.changedTouches].find(ae=>ae.identifier===l.id);if(!z)return;const W=z.clientY-l.startY,xe=l.top&&W>et&&$e(l.scrollers),Se=l.bottom&&W<-et&&nt(l.scrollers);if(xe||Se){a.preventDefault(),we.current=null,V.current(r(z,v),Ue.current(),l.startY),Pe.current(r(z,v));return}(l.top&&W<0||l.bottom&&W>0)&&(l.top=!1,l.bottom=!1),x.current>0&&nt(l.scrollers)?l.contentEndY==null?l.contentEndY=z.clientY:l.contentEndY-z.clientY>=xn&&(l.promotedAtContentEnd=!0,V.current(r(z,v),Ue.current(),l.contentEndY),Pe.current(r(z,v))):l.contentEndY=null},g=a=>{we.current=null;const v=C.current?.pointerId;if(v==null)return;const l=[...a.changedTouches].find(W=>W.identifier===v),z=a.currentTarget;l?st.current(r(l,z)):a.touches.length===0&&Ie.current(z)},L=ye.current;if(L&&Me.current){const a=Me.current;L.removeEventListener("touchstart",a.start),L.removeEventListener("touchmove",a.move),L.removeEventListener("touchend",a.end),L.removeEventListener("touchcancel",a.end)}ye.current=t,t?(t.addEventListener("touchstart",m,{passive:!0}),t.addEventListener("touchmove",T,{passive:!1}),t.addEventListener("touchend",g,{passive:!0}),t.addEventListener("touchcancel",g,{passive:!0}),Me.current={start:m,move:T,end:g}):Me.current=null},[]),it=Mt("(prefers-reduced-motion: reduce)"),at=n.useCallback(t=>{if(y.current<=0)return;const r=Tt(t),m=Math.max(0,t.scrollHeight-t.clientHeight-r),T=Math.max(0,t.scrollTop-m);T<y.current-.5&&_(T)},[_]),lt=n.useCallback(t=>{C.current!=null||$.current!=null||at(t.currentTarget)},[at]),ut=n.useCallback(t=>{if(!t.isPrimary){ie(t.currentTarget);return}ke(t)},[ke,ie]),ft=n.useCallback(t=>{if(!t.isPrimary){ie(t.currentTarget);return}Ce(t)},[Ce,ie]),We=n.useCallback(t=>{t.touches.length>1&&ie(t.currentTarget)},[ie]),dt=n.useCallback(t=>{const r=C.current;r?.pointerId!==t.pointerId||r.syntheticTouch||J(t.currentTarget)},[J]),Xe=A?u:E,Pt=n.useMemo(()=>({style:{transform:Xe!==0?`translateY(${Xe}px)`:void 0,transition:e&&(A||k||it)?"none":void 0,touchAction:"pinch-zoom",overscrollBehavior:"contain"}}),[Xe,A,e,k,it]),Ot=n.useMemo(()=>({style:{touchAction:"pinch-zoom",cursor:"grab"},onContextMenu:Z,onLostPointerCapture:fe,onPointerDown:ut,onPointerMove:ve,onPointerUp:Ee,onPointerCancel:dt,onTouchStart:We,onTouchMove:We}),[Ee,Z,dt,ut,We,fe,ve]),Lt=n.useMemo(()=>({ref:ct,onContextMenu:Z,onLostPointerCapture:fe,onPointerDown:ft,onPointerMove:ze,onPointerUp:Ae,onPointerCancel:Ae,onScroll:lt}),[ct,Ae,ft,ze,lt,Z,fe]);return{sheetRef:Ge,contentProps:Pt,handleProps:Ot,bodyProps:Lt,bodyElementRef:ye,dragOffset:u,settledOffset:E,isDragging:A,isTraveling:i,activeOffsetRef:x,sheetHeight:P,scrollPreservationInset:N,settlingLayoutOffset:te,settledLayoutOffset:F,completeScrollAreaSettle:ne}}const vt={hug:"92dvh",capped:"62dvh",tall:"92dvh"},kn=48,vn=48,En=50;function wn(){return typeof window>"u"?0:window.innerHeight}function Sn(e){let o="";for(const s of e??[])o+=`${typeof s}:${s}|`;return o}const he={sheet:{kfzvcC:"x67bb7w",kB7OPa:"x9f619",kVAEAm:"x1n2onr6",k1xSpc:"x78zum5",kXwgrk:"xdt5ytf",kAzted:"x2lwn1j",kzqmXN:"xh8yej3",ks0D6T:"x11gisft",kWkggS:"x10xzikg",kEafiO:"x11xkdxz",kPef9Z:"x13fuv20",kLZC3w:"x1pc3f07",k2ei4v:"xgbv0en",kVhnKS:"x1t7ytsu",kGJrpR:"x1j92z86",ke9TFa:"xw8tdv1",k8ry5P:"x18b5jzi",kBCPoo:"x1gejf6u",krdFHd:"x81l70g",kfmiAY:"x7hs6f1",kGVxlE:"x1kcpxr7",kI3sdo:"x1a2a7pz",kVQacm:"xb3r6kr",kGO01o:"x1wkw6tp",k1K539:"x1if0o47",k3aq6I:"xnn1q72 xhbqy3z",kSiTet:"x1hc1fzr",k1ekBW:"xwcsmn1",kIyJzY:"x80gvsz",kAMwcw:"xlr8y92",k6sLGO:"x1q1rmc8",k6CgDc:"xzg1mie",$$css:!0},sheetClosing:{k3aq6I:"x1weeur4",kAMwcw:"xv2sgk5",$$css:!0},sheetFading:{kSiTet:"xg01cxk",$$css:!0},sheetInactive:{kfzvcC:"x47corl",$$css:!0},body:{kzQI83:"x1iyjqo2",kAzted:"x2lwn1j",kB7OPa:"x9f619",kFalU9:"xge0x1e",kInvED:"x1wfwxd8 x1nw7mhf",kWkggS:"x10xzikg",kGO01o:"x18d9i69",$$css:!0},content:{k1xSpc:"xufnvkl",kB7OPa:"x9f619",kZKoxP:"x5yr21d",kAzted:"x121v3j4",$$css:!0},tallKeyboardBody:{kFlMNQ:"xrw9175",k5JduY:"x1s928wv",kc3QkE:"xhkezso",k4zj60:"xu6fald",kloYau:"x2q1x1w",$$css:!0},budget:{kZKoxP:"x1tpcejd",$$css:!0},hugHeight:{kZKoxP:"xg7h5cd",kskxy:"x14bu9tk",$$css:!0}};function Tn(e){return e.kind==="open"?e.entering?"entering":null:e.kind==="retained"?e.motion==="covered"?null:e.motion:e.kind==="exiting"?"exiting":null}function Et(e,o,s){if(e==null)return s(),()=>{};let c=!1,h=null;const p=()=>{c||(c=!0,h!=null&&clearTimeout(h),e.removeEventListener("transitionend",f),e.removeEventListener("transitioncancel",f),s())},f=i=>{i.target===e&&i.propertyName===o&&p()};e.addEventListener("transitionend",f),e.addEventListener("transitioncancel",f);const u=getComputedStyle(e);if(e.style.transition.trim()==="none"||u.transition.trim()==="none")return p(),()=>{};const j=u.transitionProperty.split(",").map(i=>i.trim()),E=u.transitionDuration.split(",").map(wt),B=u.transitionDelay.split(",").map(wt);let A=!1;const M=j.reduce((i,b,P)=>{if(b!==o&&b!=="all")return i;const D=E[P%E.length],N=B[P%B.length];return D==null||N==null?(A=!0,i):Math.max(i,D+N)},0);return A?()=>{e.removeEventListener("transitionend",f),e.removeEventListener("transitioncancel",f)}:M<=0?(p(),()=>{}):(h=setTimeout(p,M+En),()=>{h!=null&&clearTimeout(h),e.removeEventListener("transitionend",f),e.removeEventListener("transitioncancel",f)})}function wt(e){const o=e.trim();if(!/^-?(?:\d+|\d*\.\d+)(?:ms|s)$/.test(o))return null;const s=Number.parseFloat(e);return o.endsWith("ms")?s:s*1e3}function rt({ref:e,state:o,height:s,label:c,children:h,padding:p,snapPoints:f,className:u,style:j,tabIndex:E,xstyle:B,isSwipeDismissAllowed:A=!0,isPageScrollLocked:M=!1,onDismiss:i,onScrimOpacity:b,onElementChange:P,onMotionStart:D,onMotionComplete:N,...ee}){const F=n.useRef(null),Q=n.useRef(o),R=n.useRef(!1),w=n.useRef(D),te=n.useRef(N),H=n.useRef(null),k=n.useRef(null),X=o.kind==="open"&&o.entering,y=Q.current,$=y.kind==="open"&&y.entering;X&&!$?R.current=y.kind==="retained":X||(R.current=!1),n.useLayoutEffect(()=>{Q.current=o,w.current=D,te.current=N},[N,D,o]);const G=o.kind==="open",U=o.kind!=="hidden",Y=o.kind==="retained",_=Y||o.kind==="exiting",ne=o.kind==="exiting",d=Y&&o.motion==="fading",x=Y?o.alignmentOffset:0,S=Sn(f),I=n.useRef(f);I.current=f;const{snapHeights:q,ignoredSnapPointsMessage:me}=n.useMemo(()=>{if(S==="")return{snapHeights:void 0,ignoredSnapPointsMessage:""};const V=(I.current??[]).filter(Ie=>!Qt(Ie));return{snapHeights:()=>Zt(I.current??[],wn()),ignoredSnapPointsMessage:V.length===0?"":`snapPoints ignored ${JSON.stringify(V)}. A snap point is a viewport fraction above 0 and up to 1 (0.5 is half the screen), a px length ('320px'), or a percentage ('50%').`}},[S]);Ne("BottomSheet",me,me!=="");const{contentProps:se,handleProps:re,bodyProps:C,bodyElementRef:ge,sheetRef:pe,dragOffset:ye,settledOffset:be,isDragging:le,isTraveling:Ge,sheetHeight:ue,scrollPreservationInset:oe,settlingLayoutOffset:Re,settledLayoutOffset:ce,completeScrollAreaSettle:Be}=bn({isOpen:G,canDismiss:A,offscreenBlockEndInset:kn,onDismiss:i,snapHeights:q,onScrimOpacity:b}),{getViewportProps:qe,getContentProps:J}=It({axis:"both",keyboardAccess:{owner:"contentOrViewport",label:c},overscroll:"contain",stickyContainment:"always"}),He=n.useCallback(V=>{pe(V),F.current=V,P?.(V)},[P,pe]);ln({bodyRef:ge,bottomClearance:vn,isEnabled:s==="tall",isFullyExpanded:be===0,isPageScrollLocked:M,isSheetTraveling:Ge,isOpen:G,isPresented:U,sheetRef:F}),n.useImperativeHandle(e,()=>F.current,[]);const O=Tn(o);n.useLayoutEffect(()=>{if(O!=null){if(H.current=null,k.current=null,O==="entering"&&R.current){k.current=O;return}return Et(F.current,O==="fading"?"opacity":"transform",()=>{H.current===O?te.current?.(O):k.current=O})}},[O]),n.useLayoutEffect(()=>{if(Re!=null)return Et(F.current,"transform",Be)},[Be,Re]),n.useEffect(()=>{if(O!=null)return w.current?.(O),H.current=O,k.current===O&&(k.current=null,te.current?.(O)),()=>{H.current===O&&(H.current=null),k.current===O&&(k.current=null)}},[O]);const ke=p==null,Z=p??4,fe=Vt[Z],Ee=typeof s=="string"&&s in vt?vt[s]:typeof s=="number"?`${s}px`:s,de=ue>0;let Ce=se.style.transform,ze;if(de){const V=le?ye<be?0:ce:Re??ce,je=(le?ye:be)-V,Pe=le||Re!=null;ze=V>0||Pe?`${Math.max(0,ue-Math.max(0,V))}px`:void 0,Ce=je!==0?`translateY(${je}px)`:void 0}const Ae=x>0?[Ce,`translateY(${x}px)`].filter(Boolean).join(" "):Ce,we=G?Ce:Y?Ae:void 0,Me=j?.transform;n.useLayoutEffect(()=>{if(le||Me!=null)return;const V=F.current;V!=null&&(V.style.transform=we??"")});const ie={transition:se.style.transition,touchAction:se.style.touchAction,overscrollBehavior:se.style.overscrollBehavior,height:ze};return K.jsxs("div",{...ee,ref:He,tabIndex:E??-1,...mt($t("bottom-sheet"),Je(Ft.reset,_t.reset,he.sheet,Yt.reset,s==="hug"?he.hugHeight:he.budget,ne&&he.sheetClosing,d&&he.sheetFading,_&&he.sheetInactive,B),u,{"--_sheet-budget":Ee,...G?ie:Y||ne?{height:ze}:{},...j}),children:[K.jsx("div",{className:"x10l6tqk x13vifvy x1o0tod xtijo5x x1vjfegm x78zum5 x6s0dn4 xl56j7k xvpftlf xafqdz2 x1j4r261 x1jm3nie x16khyan",...re,"aria-hidden":"true",children:K.jsx("div",{className:"x1m747yf x11c6zpc xjspbzw x1m4xfpy"})}),K.jsx("div",{...qe({...C,...mt(Je(Ht.focusVisible,he.body,s==="tall"&&he.tallKeyboardBody),oe>0?{style:{paddingBlockEnd:`${oe}px`}}:{})}),children:K.jsx("div",{...J(Je(he.content,...Bt(ke?{useThemeDefault:"bottom-sheet"}:{paddingInnerX:fe,paddingInnerY:fe,paddingOuterX:fe,paddingOuterY:fe}),!ke&&Z!==4&&At[Z],!ke&&Z!==4&&Dt[Z],!ke&&Z!==4&&Nt[Z],!ke&&Z!==4&&qt[Z])),children:K.jsx(jt,{children:h})})})]})}rt.displayName="BottomSheetPanel";function Rn(){return K.jsx("div",{className:"xixxii4 x17y0mx6 x1ey2m1c x1kpxq89 x10xzikg xhtitgo x47corl x1cb67k9 xt2iwb0","data-sheet-edge-tint":"","aria-hidden":"true"})}const ot=n.createContext(null);ot.displayName="BottomSheetSwitcherContext";function Cn(e,o){switch(e){case"active":return{kind:"open",entering:!1};case"entering":return{kind:"open",entering:!0};case"covered":case"aligning":case"fading":return{kind:"retained",motion:e,alignmentOffset:o};case"exiting":return{kind:"exiting"};case"hidden":return{kind:"hidden"}}}function Ct(e,o){const s=document.activeElement;if(s!=null&&e?.contains(s))return;const c=e?.querySelector("[data-autofocus]");c!=null?c.focus({preventScroll:!0}):o&&e?.focus({preventScroll:!0})}function Pn({ref:e,isOpen:o,onOpenChange:s,label:c,children:h,height:p="capped",snapPoints:f,hasScrim:u=!0,finalFocusRef:j,purpose:E="info",xstyle:B,...A}){const M=n.useRef(null),i=n.useRef(null),b=n.useRef(null),[P,D]=n.useState(o),N=o||P,ee=o?{kind:"open",entering:!1}:P?{kind:"exiting"}:{kind:"hidden"},F=n.useCallback(()=>{o&&E!=="required"&&s(!1)},[o,s,E]),Q=n.useCallback(()=>{E==="info"&&s(!1)},[s,E]),R=n.useCallback(y=>{i.current=y},[]),w=n.useCallback(y=>{M.current?.style.setProperty("--_sheet-scrim-opacity",String(y))},[]);n.useEffect(()=>{const y=M.current;if(y==null||!o)return;D(!0),y.style.setProperty("--_sheet-scrim-opacity","1"),y.open||(u?(b.current=document.activeElement,y.showModal()):y.show(),Ct(i.current,u))},[u,o]),n.useEffect(()=>{!o&&P&&u&&w(0)},[w,u,o,P]);const te=n.useCallback(y=>{if(y!=="exiting"||o)return;const $=M.current;$?.open&&$.close(),D(!1),(j?.current??b.current)?.focus(),b.current=null},[j,o]);Kt(N&&u),Ne("BottomSheet","requires a non-empty `label` for an accessible name; the open sheet has no built-in heading to derive one from.",o&&!c);const{shouldDismissOnCloseRequest:H}=Gt({isActive:N,escapeBehavior:o&&E!=="required"?"close":"block",onDismiss:F,getContainer:()=>M.current,isPresent:()=>M.current?.open??!1}),k=n.useCallback(y=>{y.preventDefault(),H()&&F()},[F,H]),X=n.useCallback(y=>{u&&y.target===y.currentTarget&&Q()},[Q,u]);return K.jsxs("dialog",{...{0:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz"},8:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq"},4:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x15h3t91 x142juwg x1viac0w"},12:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x15h3t91 x142juwg x1viac0w"},2:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz x1cz9k3x"},10:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq x1cz9k3x"},6:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x142juwg x1viac0w x1cz9k3x"},14:{className:"xixxii4 x10a8y8t x1o6l61p xtdtrs8 x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x142juwg x1viac0w x1cz9k3x"},1:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz x47corl xfo81ep xh8yej3 x5yr21d"},9:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq x47corl xfo81ep xh8yej3 x5yr21d"},5:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x15h3t91 x142juwg x1viac0w x47corl xfo81ep xh8yej3 x5yr21d"},13:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x15h3t91 x142juwg x1viac0w x47corl xfo81ep xh8yej3 x5yr21d"},3:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz x1cz9k3x x47corl xfo81ep xh8yej3 x5yr21d"},11:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq x1cz9k3x x47corl xfo81ep xh8yej3 x5yr21d"},7:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1s85apg x1a2a7pz xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x142juwg x1viac0w x1cz9k3x x47corl xfo81ep xh8yej3 x5yr21d"},15:{className:"xixxii4 x10a8y8t x1x1rfll x7ab17h x1ghz6dp x1717udv xc342km xng3xce xjbqb8w x1rea2x4 x1a2a7pz x1lliihq xnixb3f xni466t xxiuuzi xc0dz0a xft5bk6 x142juwg x1viac0w x1cz9k3x x47corl xfo81ep xh8yej3 x5yr21d"}}[!!N<<3|!!u<<2|!!(u&&!o&&P)<<1|!u<<0],ref:M,"aria-label":c,"aria-hidden":!o&&P?"true":void 0,"aria-modal":u&&o?"true":void 0,role:E==="required"?"alertdialog":void 0,inert:!o&&P?!0:void 0,onCancel:k,onClick:X,children:[K.jsx("div",{className:"x10l6tqk x17y0mx6 x1ey2m1c x78zum5 xl56j7k x47corl",children:K.jsx(rt,{...A,ref:e,state:ee,height:p,label:c,snapPoints:f,isSwipeDismissAllowed:E==="info",isPageScrollLocked:N&&u,xstyle:B,onDismiss:Q,onScrimOpacity:w,onElementChange:R,onMotionComplete:te,children:K.jsx(Ut,{children:h})})}),K.jsx(Rn,{})]})}function On({switcher:e,ref:o,sheetId:s,label:c,children:h,height:p="capped",snapPoints:f,purpose:u="info",xstyle:j,...E}){const{activeSheet:B,hasScrim:A,onActiveSheetChange:M,getSheetPhase:i,getSheetAlignmentOffset:b,registerSheetElement:P,registerSheetLabel:D,registerSheetPurpose:N,onSheetEnterStart:ee,onSheetTransitionComplete:F,onSheetScrimOpacityChange:Q}=e,R=typeof s=="string"&&s.length>0,w=R?i(s):"hidden",te=R?b(s):0,H=Cn(w,te),k=w==="active"||w==="entering",X=w==="covered"||w==="aligning"||w==="fading"||w==="exiting",y=w!=="hidden",$=w==="active"||w==="entering",G=n.useRef(null),U=n.useRef(w),Y=U.current,_=n.useRef(!1);n.useLayoutEffect(()=>{U.current=w},[w]);const ne=n.useCallback(()=>{u==="info"&&R&&B===s&&M(null)},[B,R,M,u,s]),d=n.useCallback(q=>{G.current=q,R&&P(s,q)},[R,P,s]),x=n.useCallback(q=>{q==="entering"&&R&&ee(s)},[R,ee,s]),S=n.useCallback(q=>{R&&F({sheetId:s,phase:q})},[R,F,s]),I=n.useCallback(q=>{R&&Q(s,q)},[R,Q,s]);return n.useLayoutEffect(()=>{if(R)return D(s,c),()=>D(s,null)},[R,c,D,s]),n.useLayoutEffect(()=>{if(R)return N(s,u),()=>N(s,null)},[R,u,N,s]),n.useEffect(()=>{if(k){const q=Y==="active"||Y==="entering";(!_.current||!q)&&Ct(G.current,A),_.current=!0}else w==="hidden"&&(_.current=!1)},[A,k,w,Y]),Ne("BottomSheet","requires a non-empty `label` for an accessible name; the open sheet has no built-in heading to derive one from.",k&&!c),K.jsx("div",{...{0:{className:"x10l6tqk x17y0mx6 x1ey2m1c x78zum5 xl56j7k x47corl"},2:{className:"x10l6tqk x17y0mx6 x1ey2m1c xl56j7k x47corl x1s85apg"},1:{className:"x10l6tqk x17y0mx6 x1ey2m1c x78zum5 xl56j7k x47corl x1vjfegm"},3:{className:"x10l6tqk x17y0mx6 x1ey2m1c xl56j7k x47corl x1s85apg x1vjfegm"}}[!y<<1|!!$<<0],hidden:!y,"aria-hidden":X?"true":void 0,inert:X?!0:void 0,children:K.jsx(rt,{...E,ref:o,state:H,height:p,label:c,snapPoints:f,isSwipeDismissAllowed:u==="info",isPageScrollLocked:A,xstyle:j,onDismiss:ne,onScrimOpacity:I,onElementChange:d,onMotionStart:x,onMotionComplete:S,children:K.jsx(ot,{value:null,children:h})})})}function Ln(e){const o=n.use(ot),s=e.sheetId,c=typeof s=="string"&&s.length>0;return Ne("BottomSheet","requires a non-empty `sheetId` when nested in BottomSheetSwitcher; standalone `isOpen` / `onOpenChange` props are ignored there.",o!=null&&!c),Ne("BottomSheet","`sheetId` only works inside BottomSheetSwitcher. Use `isOpen` and `onOpenChange` for a standalone sheet.",o==null&&s!=null),o!=null?K.jsx(On,{...e,switcher:o}):K.jsx(Pn,{...e})}Ln.displayName="BottomSheet";export{Ln as BottomSheet};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as n,i as de,u as pe,j as x,p as J,m as $,t as q,f as me}from"./index-
|
|
1
|
+
import{r as n,i as de,u as pe,j as x,p as J,m as $,t as q,f as me}from"./index-DgKRKmzj.js";const Q="--_item-swipe-travel",Z="--_item-swipe-dir",F="--_item-swipe-duration",fe=10,xe=48,ke=.5,ge=.5,he=.35,Pe=.6,we=44,ee=24,Ee=200,ye=400,te={isArmed:!1,phase:"idle",side:"leading"};function M(p){return p==="trailing"?-1:1}function L(){return typeof performance>"u"?Date.now():performance.now()}function ne(p){const P=p.querySelectorAll('button, a[href], input, [tabindex]:not([tabindex="-1"])');for(const m of P)if(m.closest("[data-swipe-panel]")==null){m.focus();return}document.activeElement instanceof HTMLElement&&document.activeElement.blur()}function Se({isEnabled:p,behavior:P,sides:m,measurePanel:T,fireOutermost:v,isReducedMotion:b=!1,rootRef:s}){const k=n.useRef(null),C=n.useRef(0),w=n.useRef(1),I=n.useRef(0),f=n.useRef(null),i=n.useRef(null),l=n.useRef(null),[E,g]=n.useState(te),h=n.useRef(E);h.current=E;const u=n.useRef(T),y=n.useRef(v),O=n.useRef(m),R=n.useRef(P),Y=n.useRef(b);n.useEffect(()=>{u.current=T,y.current=v,O.current=m,R.current=P,Y.current=b}),n.useEffect(()=>()=>{f.current!=null&&clearTimeout(f.current),i.current!=null&&cancelAnimationFrame(i.current)},[]);const A=n.useCallback(t=>{const e=s.current;e&&(C.current=t,e.style.setProperty(Q,`${t}px`))},[s]),_=n.useCallback(t=>{const e=s.current;e&&(t>0?e.style.setProperty(F,`${t}ms`):e.style.setProperty(F,"0s"))},[s]),G=n.useCallback(()=>{const t=s.current;t&&(t.style.removeProperty(Q),t.style.removeProperty(Z),t.style.removeProperty(F),C.current=0)},[s]),U=n.useCallback(()=>{i.current!=null&&cancelAnimationFrame(i.current),i.current=null,l.current=null},[]),H=n.useCallback(t=>{l.current=t,i.current==null&&(i.current=requestAnimationFrame(()=>{i.current=null;const e=l.current;l.current=null,e!=null&&A(e)}))},[A]),o=n.useCallback((t,e,r,c)=>{U();const a=Y.current?0:Ee;g({isArmed:!1,phase:"settling",side:t}),_(a),A(e),f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{f.current=null,_(0),c?.()!==!0&&(r==="idle"&&G(),g(r==="idle"?te:{isArmed:!1,phase:r,side:t}))},a)},[U,G,_,A]),K=n.useCallback((t,e)=>{const c=s.current?.clientWidth??0,a=M(t)*e*(c+ee);o(t,a,"held",()=>y.current(t)?!1:(o(t,0,"idle"),!0))},[s,o]),j=n.useCallback(()=>{const t=h.current;if(t.phase!=="resting")return;const e=s.current;e!=null&&e.contains(document.activeElement)&&ne(e),o(t.side,0,"idle")},[s,o]);n.useEffect(()=>{if(E.phase!=="resting")return;const t=e=>{const r=s.current;r!=null&&e.target instanceof Node&&!r.contains(e.target)&&j()};return document.addEventListener("pointerdown",t,!0),()=>{document.removeEventListener("pointerdown",t,!0)}},[j,s,E.phase]),n.useEffect(()=>{const t=s.current;if(t==null||!p)return;const e=r=>{k.current?.claimed===!0&&r.cancelable&&r.preventDefault()};return t.addEventListener("touchmove",e,{passive:!1}),()=>{t.removeEventListener("touchmove",e)}},[p,s]);const re=n.useCallback(t=>{const e=h.current;if(e.phase!=="resting")return;const r=s.current;if(r!=null&&r.contains(document.activeElement)&&ne(r),t()){const a=r?.clientWidth??0,d=M(e.side)*w.current*(a+ee);o(e.side,d,"held")}else o(e.side,0,"idle")},[s,o]),se=n.useCallback(t=>{const e=h.current;if(t.pointerType!=="touch"||k.current!=null||e.phase==="settling"||e.phase==="held")return;const r=s.current,c=de(r)?-1:1;w.current=c;const a=L();k.current={baseTravel:C.current*c,claimed:null,commitPx:0,inlineSign:c,lastTime:a,lastX:t.clientX,panelWidth:0,pointerId:t.pointerId,prevTime:a,prevX:t.clientX,side:e.phase==="resting"?e.side:"leading",startX:t.clientX,startY:t.clientY,travel:0}},[p,s]),ie=n.useCallback(t=>{const e=k.current;if(e==null||e.pointerId!==t.pointerId||e.claimed===!1)return;const r=(t.clientX-e.startX)*e.inlineSign,c=t.clientY-e.startY;if(e.claimed===null){if(Math.max(Math.abs(r),Math.abs(c))<fe)return;if(Math.abs(r)<=Math.abs(c)){e.claimed=!1;return}const N=h.current.phase==="resting"?e.side:r>0?"leading":"trailing";if(!O.current[N]){e.claimed=!1;return}e.claimed=!0,e.side=N,e.panelWidth=u.current(N);const oe=s.current?.clientWidth??0;e.commitPx=Math.max(e.panelWidth+xe,oe*ke),s.current!=null&&s.current.style.setProperty(Z,String(e.inlineSign)),_(0),g({isArmed:!1,phase:"dragging",side:N});try{s.current?.setPointerCapture(t.pointerId)}catch{}}const a=M(e.side),d=Math.max(0,r*a+e.baseTravel*a),W=d<=e.commitPx?d:e.commitPx+(d-e.commitPx)*he,z=d>=e.commitPx;z!==e.travel>=e.commitPx&&g({isArmed:z,phase:"dragging",side:e.side}),e.travel=d,e.prevX=e.lastX,e.prevTime=e.lastTime,e.lastX=t.clientX,e.lastTime=L(),H(a*e.inlineSign*W)},[H,s,_]),X=n.useCallback((t,e)=>{const r=k.current;if(r==null||r.pointerId!==t.pointerId||(k.current=null,r.claimed!==!0))return;I.current=L()+ye;try{s.current?.releasePointerCapture(t.pointerId)}catch{}const{side:c,inlineSign:a}=r,d=M(c)*a*r.panelWidth;if(e){o(c,0,"idle");return}const W=Math.max(1,r.lastTime-r.prevTime),B=M(c)*a*(r.lastX-r.prevX)/W>=Pe&&r.travel>=we;if(r.travel>=r.commitPx||B){K(c,a);return}if(R.current==="reveal"&&r.travel>=r.panelWidth*ge){o(c,d,"resting");return}o(c,0,"idle")},[s,o,K]),ce=n.useCallback(t=>X(t,!1),[X]),le=n.useCallback(t=>X(t,!0),[X]),D=n.useCallback(()=>L()<I.current,[]),ae=n.useCallback(t=>{!D()||t.target instanceof Element&&t.target.closest("[data-swipe-panel]")!=null||(I.current=0,t.preventDefault(),t.stopPropagation())},[D]),ue=n.useCallback(t=>{t.key==="Escape"&&h.current.phase==="resting"&&(t.stopPropagation(),j())},[j]);return{activateEntry:re,close:j,handlers:{onClickCapture:ae,onKeyDown:ue,onPointerCancel:le,onPointerDown:se,onPointerMove:ie,onPointerUp:ce},shouldSuppressClick:D,state:E}}const S={swipePanel:{kVAEAm:"x10l6tqk",k87sOh:"x13vifvy",krVfgx:"x1ey2m1c",kzqmXN:"xnalus7",k1xSpc:"x78zum5",kGNEyG:"x1qjc9v5",kB7OPa:"x9f619",kVQacm:"xb3r6kr",kaIpWk:"x1pjcqnp",k3aq6I:"x145au52",k1ekBW:"x13zkoj4",kIyJzY:"xxfakuu",kAMwcw:"xn34ekc",$$css:!0},swipePanelLeading:{kLqNvP:"x1o0tod",kjj79g:"x1nhvcw1",kzqmXN:"x96shys",$$css:!0},swipePanelTrailing:{kt4wiu:"xtijo5x",kjj79g:"x13a6bvl",kzqmXN:"x1qwjaml",$$css:!0},swipeEntry:{k1xSpc:"x78zum5",kXwgrk:"xdt5ytf",kGNEyG:"x6s0dn4",kjj79g:"xl56j7k",kOIVth:"xzye2dw",k7Eaqz:"x187xtus",kZKoxP:"x5yr21d",kg3NbH:"xrrkdod",kB7OPa:"x9f619",kogj98:"x1ghz6dp",kMzoRj:"xc342km",ksu8eU:"xng3xce",kysU6D:"xjyslct",kkrTdU:"x1ypdohk x16khyan",kMv6JI:"x9ynric",kGuDYH:"x141an7d",k63SB2:"x1e4wzip",kLWn49:"x1ltkj2j",khDVqt:"xuxw1ft",$$css:!0},swipeEntryDisabled:{kSiTet:"xbyyjgo",$$css:!0}},V={neutral:{kWkggS:"x17x4s8c",kMwMTN:"x1tgivj0",$$css:!0},accent:{kWkggS:"x1ewilqj",kMwMTN:"x17wrial",$$css:!0},destructive:{kWkggS:"x1pjz0fi",kMwMTN:"x1m024r3",$$css:!0}};function Te({rootRef:p,onBridge:P,leading:m,trailing:T,behavior:v}){const b=n.useRef(null),s=n.useRef(null),k=pe("(prefers-reduced-motion: reduce)"),C=i=>{const l=i==="leading"?m:T;return l[l.length-1]},w=Se({isEnabled:!0,behavior:v,sides:{leading:m.length>0,trailing:T.length>0},measurePanel:i=>(i==="leading"?b:s).current?.offsetWidth??0,fireOutermost:i=>{const l=C(i);return l==null||l.isDisabled===!0?!1:(l.onActivate(),l.hasRemoval===!0)},isReducedMotion:k,rootRef:p});n.useEffect(()=>(P({handlers:w.handlers,shouldSuppressClick:w.shouldSuppressClick}),()=>{P(null)}));const I=w.state.phase==="resting",f=(i,l)=>{if(l.length===0)return null;const E=l[l.length-1],g=v==="commit",h=I&&!g;return x.jsx("div",{"data-swipe-panel":i,inert:h?void 0:!0,"aria-hidden":g?!0:void 0,...$(q("item-swipe-panel",{side:i}),J(S.swipePanel,i==="leading"?S.swipePanelLeading:S.swipePanelTrailing,V[E.variant??"accent"])),children:x.jsx("div",{ref:i==="leading"?b:s,...{0:{className:"x78zum5 x2lah0s x5yr21d x10xzikg"},1:{className:"x78zum5 x2lah0s x5yr21d x10xzikg x15zctf7"}}[(i==="leading")<<0],children:l.map(u=>{const y=u.variant??"accent",O=x.jsxs(x.Fragment,{children:[u.icon,x.jsx("span",{children:u.label})]}),R=J(S.swipeEntry,V[y],u.isDisabled===!0&&S.swipeEntryDisabled);return g?x.jsx("span",{...$(q("item-swipe-action",{variant:y}),R),children:O},u.id??u.label):x.jsx("button",{type:"button",disabled:u.isDisabled===!0,onClick:()=>w.activateEntry(()=>(u.onActivate(),u.hasRemoval===!0)),...$(q("item-swipe-action",{variant:y}),me.focusVisible(S.swipeEntry,V[y],u.isDisabled===!0&&S.swipeEntryDisabled)),children:O},u.id??u.label)})})},i)};return x.jsxs(x.Fragment,{children:[f("leading",m),f("trailing",T)]})}Te.displayName="ItemSwipeLayer";export{Te as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BottomSheet as r}from"./BottomSheet-
|
|
1
|
+
import{BottomSheet as r}from"./BottomSheet-Bs6VGQRD.js";import{j as e,S as a}from"./index-DgKRKmzj.js";function d({finalFocusRef:n,isOpen:o,onOpenChange:t,label:i,children:p}){return e.jsx(r,{finalFocusRef:n,isOpen:o,onOpenChange:t,label:i,height:"hug",purpose:"info",children:e.jsx(a,{paddingBlockStart:4,paddingBlockEnd:0,paddingInline:1,children:p})})}d.displayName="MenuBottomSheet";export{d as MenuBottomSheet};
|