quirl-cli 0.1.0 → 0.1.2
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/quirl.mjs +10 -8
- package/package.json +1 -1
package/dist/quirl.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import{parseArgs as t,promisify as n}from"node:util";import r from"node:process";import{execFile as i,execFileSync as a,spawn as o}from"node:child_process";import{chmod as s,lstat as c,mkdir as l,readFile as u,readdir as d,rm as f,stat as p,writeFile as m}from"node:fs/promises";import{homedir as h,hostname as g}from"node:os";import _,{basename as v,dirname as y,isAbsolute as b,join as x,relative as S}from"node:path";import{createHash as C,randomUUID as w}from"node:crypto";import{existsSync as T}from"node:fs";import{createInterface as E}from"node:readline/promises";var ee=Object.create,te=Object.defineProperty,ne=Object.getOwnPropertyDescriptor,re=Object.getOwnPropertyNames,ie=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty,oe=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},D=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),se=(e,t)=>{let n={};for(var r in e)te(n,r,{get:e[r],enumerable:!0});return t||te(n,Symbol.toStringTag,{value:`Module`}),n},ce=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=re(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ae.call(e,s)&&s!==n&&te(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ne(t,s))||r.enumerable});return e},le=(e,t,n)=>(n=e==null?{}:ee(ie(e)),ce(t||!e||!e.__esModule||!ae.call(e,`default`)?te(n,`default`,{value:e,enumerable:!0}):n,e)),ue=e=>ae.call(e,`module.exports`)?e[`module.exports`]:ce(te({},`__esModule`,{value:!0}),e),de=/* @__PURE__ */ e(import.meta.url);const fe=Symbol.for(`@supabase/supabase-js.traceContextExtractor`);function pe(){return globalThis[fe]}var me=/* @__PURE__ */ se({__addDisposableResource:()=>He,__assign:()=>Ke,__asyncDelegator:()=>Pe,__asyncGenerator:()=>Ne,__asyncValues:()=>Fe,__await:()=>Me,__awaiter:()=>we,__classPrivateFieldGet:()=>ze,__classPrivateFieldIn:()=>Ve,__classPrivateFieldSet:()=>Be,__createBinding:()=>qe,__decorate:()=>_e,__disposeResources:()=>Ue,__esDecorate:()=>ye,__exportStar:()=>Ee,__extends:()=>he,__generator:()=>Te,__importDefault:()=>Re,__importStar:()=>Le,__makeTemplateObject:()=>Ie,__metadata:()=>Ce,__param:()=>ve,__propKey:()=>xe,__read:()=>Oe,__rest:()=>ge,__rewriteRelativeImportExtension:()=>We,__runInitializers:()=>be,__setFunctionName:()=>Se,__spread:()=>ke,__spreadArray:()=>je,__spreadArrays:()=>Ae,__values:()=>De,default:()=>Ze});function he(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);Ge(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function ge(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function _e(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function ve(e,t){return function(n,r){t(n,r,e)}}function ye(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function be(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function xe(e){return typeof e==`symbol`?e:`${e}`}function Se(e,t,n){return typeof t==`symbol`&&(t=t.description?`[${t.description}]`:``),Object.defineProperty(e,"name",{configurable:!0,value:n?`${n} ${t}`:t})}function Ce(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function we(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Te(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function Ee(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&qe(t,e,n)}function De(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Oe(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function ke(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Oe(arguments[t]));return e}function Ae(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}function je(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function Me(e){return this instanceof Me?(this.v=e,this):new Me(e)}function Ne(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Me?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Pe(e){var t={},n;return r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:Me(e[r](t)),done:!1}:i?i(t):t}:i}}function Fe(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof De==`function`?De(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function Ie(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function Le(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=Ye(e),r=0;r<n.length;r++)n[r]!=="default"&&qe(t,e,n[r]);return Je(t,e),t}function Re(e){return e&&e.__esModule?e:{default:e}}function ze(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function Be(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Ve(e,t){if(t===null||typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Cannot use 'in' operator on non-object`);return typeof e==`function`?t===e:e.has(t)}function He(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}function Ue(e){function t(t){e.error=e.hasError?new Xe(t,e.error,`An error was suppressed during disposal.`):t,e.hasError=!0}var n,r=0;function i(){for(;n=e.stack.pop();)try{if(!n.async&&r===1)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(a).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(r===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return i()}function We(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e}var Ge,Ke,qe,Je,Ye,Xe,Ze,Qe=oe((()=>{Ge=function(e,t){return Ge=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},Ge(e,t)},Ke=function(){return Ke=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Ke.apply(this,arguments)},qe=Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Je=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},Ye=function(e){return Ye=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},Ye(e)},Xe=typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},Ze={__extends:he,__assign:Ke,__rest:ge,__decorate:_e,__param:ve,__esDecorate:ye,__runInitializers:be,__propKey:xe,__setFunctionName:Se,__metadata:Ce,__awaiter:we,__generator:Te,__createBinding:qe,__exportStar:Ee,__values:De,__read:Oe,__spread:ke,__spreadArrays:Ae,__spreadArray:je,__await:Me,__asyncGenerator:Ne,__asyncDelegator:Pe,__asyncValues:Fe,__makeTemplateObject:Ie,__importStar:Le,__importDefault:Re,__classPrivateFieldGet:ze,__classPrivateFieldSet:Be,__classPrivateFieldIn:Ve,__addDisposableResource:He,__disposeResources:Ue,__rewriteRelativeImportExtension:We}})),$e=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveFetch=void 0,e.resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e)})),et=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionRegion=e.FunctionsHttpError=e.FunctionsRelayError=e.FunctionsFetchError=e.FunctionsError=void 0;var t=class extends Error{constructor(e,t=`FunctionsError`,n){super(e),this.name=t,this.context=n}toJSON(){return{name:this.name,message:this.message,context:this.context}}};e.FunctionsError=t,e.FunctionsFetchError=class extends t{constructor(e){super(`Failed to send a request to the Edge Function`,`FunctionsFetchError`,e)}},e.FunctionsRelayError=class extends t{constructor(e){super(`Relay Error invoking the Edge Function`,`FunctionsRelayError`,e)}},e.FunctionsHttpError=class extends t{constructor(e){super(`Edge Function returned a non-2xx status code`,`FunctionsHttpError`,e)}};var n;(function(e){e.Any=`any`,e.ApNortheast1=`ap-northeast-1`,e.ApNortheast2=`ap-northeast-2`,e.ApSouth1=`ap-south-1`,e.ApSoutheast1=`ap-southeast-1`,e.ApSoutheast2=`ap-southeast-2`,e.CaCentral1=`ca-central-1`,e.EuCentral1=`eu-central-1`,e.EuWest1=`eu-west-1`,e.EuWest2=`eu-west-2`,e.EuWest3=`eu-west-3`,e.SaEast1=`sa-east-1`,e.UsEast1=`us-east-1`,e.UsWest1=`us-west-1`,e.UsWest2=`us-west-2`})(n||(e.FunctionRegion=n={}))})),tt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionsClient=void 0;let t=(Qe(),ue(me)),n=$e(),r=et();e.FunctionsClient=class{constructor(e,{headers:t={},customFetch:i,region:a=r.FunctionRegion.Any}={}){this.url=e,this.headers=t,this.region=a,this.fetch=(0,n.resolveFetch)(i)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return t.__awaiter(this,arguments,void 0,function*(e,t={}){var n;let i,a,o;try{let{headers:n,method:s,body:c,signal:l,timeout:u}=t,d={},{region:f}=t;f||=this.region;let p=new URL(`${this.url}/${e}`);f&&f!==`any`&&(d[`x-region`]=f,p.searchParams.set(`forceFunctionRegion`,f));let m,h=!!n&&Object.keys(n).some(e=>e.toLowerCase()===`content-type`);c&&!h?typeof Blob<`u`&&c instanceof Blob||c instanceof ArrayBuffer?(d[`Content-Type`]=c.type||`application/octet-stream`,m=c):typeof c==`string`?(d[`Content-Type`]=`text/plain`,m=c):typeof FormData<`u`&&c instanceof FormData?m=c:(d[`Content-Type`]=`application/json`,m=JSON.stringify(c)):m=c&&typeof c!=`string`&&!(typeof Blob<`u`&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<`u`&&c instanceof FormData)?JSON.stringify(c):c;let g=l;u&&(a=new AbortController,i=setTimeout(()=>a.abort(),u),l?(g=a.signal,o=()=>a.abort(),l.addEventListener(`abort`,o)):g=a.signal);let _=yield this.fetch(p.toString(),{method:s||`POST`,headers:Object.assign(Object.assign(Object.assign({},d),this.headers),n),body:m,signal:g}).catch(e=>{throw new r.FunctionsFetchError(e)}),v=_.headers.get(`x-relay-error`);if(v&&v===`true`)throw new r.FunctionsRelayError(_);if(!_.ok)throw new r.FunctionsHttpError(_);let y=(_.headers.get(`Content-Type`)??`text/plain`).split(`;`)[0].trim().toLowerCase(),b;return b=y===`application/json`?yield _.json():y===`application/octet-stream`||y===`application/pdf`?yield _.blob():y===`text/event-stream`?_:y===`multipart/form-data`?yield _.formData():yield _.text(),{data:b,error:null,response:_}}catch(e){return{data:null,error:e,response:e instanceof r.FunctionsHttpError||e instanceof r.FunctionsRelayError?e.context:void 0}}finally{i&&clearTimeout(i),o&&((n=t.signal)==null||n.removeEventListener(`abort`,o))}})}}})),nt=(/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionRegion=e.FunctionsRelayError=e.FunctionsHttpError=e.FunctionsFetchError=e.FunctionsError=e.FunctionsClient=void 0;var t=tt();Object.defineProperty(e,"FunctionsClient",{enumerable:!0,get:function(){return t.FunctionsClient}});var n=et();Object.defineProperty(e,"FunctionsError",{enumerable:!0,get:function(){return n.FunctionsError}}),Object.defineProperty(e,"FunctionsFetchError",{enumerable:!0,get:function(){return n.FunctionsFetchError}}),Object.defineProperty(e,"FunctionsHttpError",{enumerable:!0,get:function(){return n.FunctionsHttpError}}),Object.defineProperty(e,"FunctionsRelayError",{enumerable:!0,get:function(){return n.FunctionsRelayError}}),Object.defineProperty(e,"FunctionRegion",{enumerable:!0,get:function(){return n.FunctionRegion}})})))(),rt=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};const it=e=>Math.min(1e3*2**e,3e4),at=[520,503],ot=[`GET`,`HEAD`,`OPTIONS`];function st(e){"@babel/helpers - typeof";return st=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},st(e)}function ct(e,t){if(st(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(st(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function lt(e){var t=ct(e,`string`);return st(t)==`symbol`?t:t+``}function ut(e,t,n){return(t=lt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function dt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function ft(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?dt(Object(n),!0).forEach(function(t){ut(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function pt(e,t){return new Promise(n=>{if(t?.aborted){n();return}let r=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);function i(){clearTimeout(r),n()}t?.addEventListener(`abort`,i)})}function mt(e,t,n,r){return!(!r||n>=3||!ot.includes(e)||!at.includes(t))}async function ht(e,t,n,r){let i=0;for(;;){let a=ft({},n.headers);i>0&&(a[`X-Retry-Count`]=String(i));let o;try{o=await e(t,{method:n.method,headers:a,body:n.body,signal:n.signal})}catch(e){if(e?.name===`AbortError`||e?.code===`ABORT_ERR`||e?.name===`TimeoutError`&&n.signal?.aborted||!ot.includes(n.method))throw e;if(r&&i<3){let e=it(i);i++,await pt(e,n.signal);continue}throw e}if(mt(n.method,o.status,i,r)){let e=o.headers?.get(`Retry-After`)??null,t=e===null?it(i):Math.max(0,parseInt(e,10)||0)*1e3;await o.text(),i++,await pt(t,n.signal)}else return o}}var gt=class{constructor(e){this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.shouldStripNulls=e.shouldStripNulls??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,this.retryEnabled=e.retry??!0,this.fetch=e.fetch?e.fetch:fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get(`Accept`)===`text/csv`)throw Error(`stripNulls() cannot be used with csv()`);return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var n=this;if(this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`),this.shouldStripNulls){let e=this.headers.get(`Accept`);e===`application/vnd.pgrst.object+json`?this.headers.set(`Accept`,`application/vnd.pgrst.object+json;nulls=stripped`):e&&e!==`application/json`||this.headers.set(`Accept`,`application/vnd.pgrst.array+json;nulls=stripped`)}let r=this.fetch,i=(async()=>{let e={};n.headers.forEach((t,n)=>{e[n]=t});let t=await ht(r,n.url.toString(),{method:n.method,headers:e,body:JSON.stringify(n.body,(e,t)=>typeof t==`bigint`?t.toString():t),signal:n.signal},n.retryEnabled);return await n.processResponse(t)})();return this.shouldThrowOnError||(i=i.catch(e=>{let t=``,n=``,r=``,i=e?.cause;if(i){let n=i?.message??``,r=i?.code??``;t=`${e?.name??`FetchError`}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??`Error`}: ${n}`,r&&(t+=` (${r})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??``;let a=this.url.toString().length;return e?.name===`AbortError`||e?.code===`ABORT_ERR`?(r=``,n=`Request was aborted (timeout or manual cancellation)`,a>this.urlLengthLimit&&(n+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(i?.name===`HeadersOverflowError`||i?.code===`UND_ERR_HEADERS_OVERFLOW`)&&(r=``,n=`HTTP headers exceeded server limits (typically 16KB)`,a>this.urlLengthLimit&&(n+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:t,hint:n,code:r},data:null,count:null,status:0,statusText:``}})),i.then(e,t)}async processResponse(e){var t=this;let n=null,r=null,i=null,a=e.status,o=e.statusText;if(e.ok){if(t.method!==`HEAD`){let i=await e.text();if(i!==``){if(t.headers.get(`Accept`)===`text/csv`)r=i;else if(t.headers.get(`Accept`)&&t.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`))r=i;else try{r=JSON.parse(i)}catch{if(n={message:i},r=null,t.shouldThrowOnError)throw new rt({message:i,details:``,hint:``,code:``})}}}let s=t.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),c=e.headers.get(`content-range`)?.split(`/`);if(s&&c&&c.length>1&&(i=parseInt(c[1])),t.isMaybeSingle&&Array.isArray(r)){if(r.length>1){if(n={code:`PGRST116`,details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:`JSON object requested, multiple (or no) rows returned`},r=null,i=null,a=406,o=`Not Acceptable`,t.shouldThrowOnError)throw new rt(ft(ft({},n),{},{hint:n.hint??``}))}else r=r.length===1?r[0]:null}}else{let i=await e.text();try{n=JSON.parse(i),Array.isArray(n)&&e.status===404&&(r=[],n=null,a=200,o=`OK`)}catch{e.status===404&&i===``?(a=204,o=`No Content`):n={message:i}}if(n&&t.shouldThrowOnError)throw new rt(n)}return{success:n===null,error:n,data:r,count:i,status:a,statusText:o}}returns(){
|
|
2
|
+
import{createRequire as e}from"node:module";import{parseArgs as t,promisify as n}from"node:util";import r from"node:process";import{execFile as i,execFileSync as a,spawn as o}from"node:child_process";import{chmod as s,lstat as c,mkdir as l,readFile as u,readdir as d,rm as f,stat as p,writeFile as m}from"node:fs/promises";import{homedir as h,hostname as g}from"node:os";import _,{basename as v,dirname as y,isAbsolute as b,join as x,relative as S}from"node:path";import{existsSync as C}from"node:fs";import{createHash as w,randomUUID as T}from"node:crypto";import{createInterface as E}from"node:readline/promises";var ee=Object.create,te=Object.defineProperty,ne=Object.getOwnPropertyDescriptor,re=Object.getOwnPropertyNames,ie=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty,oe=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},D=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),se=(e,t)=>{let n={};for(var r in e)te(n,r,{get:e[r],enumerable:!0});return t||te(n,Symbol.toStringTag,{value:`Module`}),n},ce=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=re(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ae.call(e,s)&&s!==n&&te(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ne(t,s))||r.enumerable});return e},le=(e,t,n)=>(n=e==null?{}:ee(ie(e)),ce(t||!e||!e.__esModule||!ae.call(e,`default`)?te(n,`default`,{value:e,enumerable:!0}):n,e)),ue=e=>ae.call(e,`module.exports`)?e[`module.exports`]:ce(te({},`__esModule`,{value:!0}),e),de=/* @__PURE__ */ e(import.meta.url);const fe=Symbol.for(`@supabase/supabase-js.traceContextExtractor`);function pe(){return globalThis[fe]}var me=/* @__PURE__ */ se({__addDisposableResource:()=>He,__assign:()=>Ke,__asyncDelegator:()=>Pe,__asyncGenerator:()=>Ne,__asyncValues:()=>Fe,__await:()=>Me,__awaiter:()=>we,__classPrivateFieldGet:()=>ze,__classPrivateFieldIn:()=>Ve,__classPrivateFieldSet:()=>Be,__createBinding:()=>qe,__decorate:()=>_e,__disposeResources:()=>Ue,__esDecorate:()=>ye,__exportStar:()=>Ee,__extends:()=>he,__generator:()=>Te,__importDefault:()=>Re,__importStar:()=>Le,__makeTemplateObject:()=>Ie,__metadata:()=>Ce,__param:()=>ve,__propKey:()=>xe,__read:()=>Oe,__rest:()=>ge,__rewriteRelativeImportExtension:()=>We,__runInitializers:()=>be,__setFunctionName:()=>Se,__spread:()=>ke,__spreadArray:()=>je,__spreadArrays:()=>Ae,__values:()=>De,default:()=>Ze});function he(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);Ge(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function ge(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function _e(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function ve(e,t){return function(n,r){t(n,r,e)}}function ye(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function be(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function xe(e){return typeof e==`symbol`?e:`${e}`}function Se(e,t,n){return typeof t==`symbol`&&(t=t.description?`[${t.description}]`:``),Object.defineProperty(e,"name",{configurable:!0,value:n?`${n} ${t}`:t})}function Ce(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function we(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Te(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function Ee(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&qe(t,e,n)}function De(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Oe(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function ke(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Oe(arguments[t]));return e}function Ae(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}function je(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function Me(e){return this instanceof Me?(this.v=e,this):new Me(e)}function Ne(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Me?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Pe(e){var t={},n;return r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:Me(e[r](t)),done:!1}:i?i(t):t}:i}}function Fe(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof De==`function`?De(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function Ie(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function Le(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=Ye(e),r=0;r<n.length;r++)n[r]!=="default"&&qe(t,e,n[r]);return Je(t,e),t}function Re(e){return e&&e.__esModule?e:{default:e}}function ze(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function Be(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Ve(e,t){if(t===null||typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Cannot use 'in' operator on non-object`);return typeof e==`function`?t===e:e.has(t)}function He(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}function Ue(e){function t(t){e.error=e.hasError?new Xe(t,e.error,`An error was suppressed during disposal.`):t,e.hasError=!0}var n,r=0;function i(){for(;n=e.stack.pop();)try{if(!n.async&&r===1)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(a).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(r===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return i()}function We(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e}var Ge,Ke,qe,Je,Ye,Xe,Ze,Qe=oe((()=>{Ge=function(e,t){return Ge=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},Ge(e,t)},Ke=function(){return Ke=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Ke.apply(this,arguments)},qe=Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Je=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},Ye=function(e){return Ye=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},Ye(e)},Xe=typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},Ze={__extends:he,__assign:Ke,__rest:ge,__decorate:_e,__param:ve,__esDecorate:ye,__runInitializers:be,__propKey:xe,__setFunctionName:Se,__metadata:Ce,__awaiter:we,__generator:Te,__createBinding:qe,__exportStar:Ee,__values:De,__read:Oe,__spread:ke,__spreadArrays:Ae,__spreadArray:je,__await:Me,__asyncGenerator:Ne,__asyncDelegator:Pe,__asyncValues:Fe,__makeTemplateObject:Ie,__importStar:Le,__importDefault:Re,__classPrivateFieldGet:ze,__classPrivateFieldSet:Be,__classPrivateFieldIn:Ve,__addDisposableResource:He,__disposeResources:Ue,__rewriteRelativeImportExtension:We}})),$e=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveFetch=void 0,e.resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e)})),et=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionRegion=e.FunctionsHttpError=e.FunctionsRelayError=e.FunctionsFetchError=e.FunctionsError=void 0;var t=class extends Error{constructor(e,t=`FunctionsError`,n){super(e),this.name=t,this.context=n}toJSON(){return{name:this.name,message:this.message,context:this.context}}};e.FunctionsError=t,e.FunctionsFetchError=class extends t{constructor(e){super(`Failed to send a request to the Edge Function`,`FunctionsFetchError`,e)}},e.FunctionsRelayError=class extends t{constructor(e){super(`Relay Error invoking the Edge Function`,`FunctionsRelayError`,e)}},e.FunctionsHttpError=class extends t{constructor(e){super(`Edge Function returned a non-2xx status code`,`FunctionsHttpError`,e)}};var n;(function(e){e.Any=`any`,e.ApNortheast1=`ap-northeast-1`,e.ApNortheast2=`ap-northeast-2`,e.ApSouth1=`ap-south-1`,e.ApSoutheast1=`ap-southeast-1`,e.ApSoutheast2=`ap-southeast-2`,e.CaCentral1=`ca-central-1`,e.EuCentral1=`eu-central-1`,e.EuWest1=`eu-west-1`,e.EuWest2=`eu-west-2`,e.EuWest3=`eu-west-3`,e.SaEast1=`sa-east-1`,e.UsEast1=`us-east-1`,e.UsWest1=`us-west-1`,e.UsWest2=`us-west-2`})(n||(e.FunctionRegion=n={}))})),tt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionsClient=void 0;let t=(Qe(),ue(me)),n=$e(),r=et();e.FunctionsClient=class{constructor(e,{headers:t={},customFetch:i,region:a=r.FunctionRegion.Any}={}){this.url=e,this.headers=t,this.region=a,this.fetch=(0,n.resolveFetch)(i)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return t.__awaiter(this,arguments,void 0,function*(e,t={}){var n;let i,a,o;try{let{headers:n,method:s,body:c,signal:l,timeout:u}=t,d={},{region:f}=t;f||=this.region;let p=new URL(`${this.url}/${e}`);f&&f!==`any`&&(d[`x-region`]=f,p.searchParams.set(`forceFunctionRegion`,f));let m,h=!!n&&Object.keys(n).some(e=>e.toLowerCase()===`content-type`);c&&!h?typeof Blob<`u`&&c instanceof Blob||c instanceof ArrayBuffer?(d[`Content-Type`]=c.type||`application/octet-stream`,m=c):typeof c==`string`?(d[`Content-Type`]=`text/plain`,m=c):typeof FormData<`u`&&c instanceof FormData?m=c:(d[`Content-Type`]=`application/json`,m=JSON.stringify(c)):m=c&&typeof c!=`string`&&!(typeof Blob<`u`&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<`u`&&c instanceof FormData)?JSON.stringify(c):c;let g=l;u&&(a=new AbortController,i=setTimeout(()=>a.abort(),u),l?(g=a.signal,o=()=>a.abort(),l.addEventListener(`abort`,o)):g=a.signal);let _=yield this.fetch(p.toString(),{method:s||`POST`,headers:Object.assign(Object.assign(Object.assign({},d),this.headers),n),body:m,signal:g}).catch(e=>{throw new r.FunctionsFetchError(e)}),v=_.headers.get(`x-relay-error`);if(v&&v===`true`)throw new r.FunctionsRelayError(_);if(!_.ok)throw new r.FunctionsHttpError(_);let y=(_.headers.get(`Content-Type`)??`text/plain`).split(`;`)[0].trim().toLowerCase(),b;return b=y===`application/json`?yield _.json():y===`application/octet-stream`||y===`application/pdf`?yield _.blob():y===`text/event-stream`?_:y===`multipart/form-data`?yield _.formData():yield _.text(),{data:b,error:null,response:_}}catch(e){return{data:null,error:e,response:e instanceof r.FunctionsHttpError||e instanceof r.FunctionsRelayError?e.context:void 0}}finally{i&&clearTimeout(i),o&&((n=t.signal)==null||n.removeEventListener(`abort`,o))}})}}})),nt=(/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionRegion=e.FunctionsRelayError=e.FunctionsHttpError=e.FunctionsFetchError=e.FunctionsError=e.FunctionsClient=void 0;var t=tt();Object.defineProperty(e,"FunctionsClient",{enumerable:!0,get:function(){return t.FunctionsClient}});var n=et();Object.defineProperty(e,"FunctionsError",{enumerable:!0,get:function(){return n.FunctionsError}}),Object.defineProperty(e,"FunctionsFetchError",{enumerable:!0,get:function(){return n.FunctionsFetchError}}),Object.defineProperty(e,"FunctionsHttpError",{enumerable:!0,get:function(){return n.FunctionsHttpError}}),Object.defineProperty(e,"FunctionsRelayError",{enumerable:!0,get:function(){return n.FunctionsRelayError}}),Object.defineProperty(e,"FunctionRegion",{enumerable:!0,get:function(){return n.FunctionRegion}})})))(),rt=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};const it=e=>Math.min(1e3*2**e,3e4),at=[520,503],ot=[`GET`,`HEAD`,`OPTIONS`];function st(e){"@babel/helpers - typeof";return st=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},st(e)}function ct(e,t){if(st(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(st(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function lt(e){var t=ct(e,`string`);return st(t)==`symbol`?t:t+``}function ut(e,t,n){return(t=lt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function dt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function ft(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?dt(Object(n),!0).forEach(function(t){ut(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function pt(e,t){return new Promise(n=>{if(t?.aborted){n();return}let r=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);function i(){clearTimeout(r),n()}t?.addEventListener(`abort`,i)})}function mt(e,t,n,r){return!(!r||n>=3||!ot.includes(e)||!at.includes(t))}async function ht(e,t,n,r){let i=0;for(;;){let a=ft({},n.headers);i>0&&(a[`X-Retry-Count`]=String(i));let o;try{o=await e(t,{method:n.method,headers:a,body:n.body,signal:n.signal})}catch(e){if(e?.name===`AbortError`||e?.code===`ABORT_ERR`||e?.name===`TimeoutError`&&n.signal?.aborted||!ot.includes(n.method))throw e;if(r&&i<3){let e=it(i);i++,await pt(e,n.signal);continue}throw e}if(mt(n.method,o.status,i,r)){let e=o.headers?.get(`Retry-After`)??null,t=e===null?it(i):Math.max(0,parseInt(e,10)||0)*1e3;await o.text(),i++,await pt(t,n.signal)}else return o}}var gt=class{constructor(e){this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.shouldStripNulls=e.shouldStripNulls??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,this.retryEnabled=e.retry??!0,this.fetch=e.fetch?e.fetch:fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get(`Accept`)===`text/csv`)throw Error(`stripNulls() cannot be used with csv()`);return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var n=this;if(this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`),this.shouldStripNulls){let e=this.headers.get(`Accept`);e===`application/vnd.pgrst.object+json`?this.headers.set(`Accept`,`application/vnd.pgrst.object+json;nulls=stripped`):e&&e!==`application/json`||this.headers.set(`Accept`,`application/vnd.pgrst.array+json;nulls=stripped`)}let r=this.fetch,i=(async()=>{let e={};n.headers.forEach((t,n)=>{e[n]=t});let t=await ht(r,n.url.toString(),{method:n.method,headers:e,body:JSON.stringify(n.body,(e,t)=>typeof t==`bigint`?t.toString():t),signal:n.signal},n.retryEnabled);return await n.processResponse(t)})();return this.shouldThrowOnError||(i=i.catch(e=>{let t=``,n=``,r=``,i=e?.cause;if(i){let n=i?.message??``,r=i?.code??``;t=`${e?.name??`FetchError`}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??`Error`}: ${n}`,r&&(t+=` (${r})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??``;let a=this.url.toString().length;return e?.name===`AbortError`||e?.code===`ABORT_ERR`?(r=``,n=`Request was aborted (timeout or manual cancellation)`,a>this.urlLengthLimit&&(n+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(i?.name===`HeadersOverflowError`||i?.code===`UND_ERR_HEADERS_OVERFLOW`)&&(r=``,n=`HTTP headers exceeded server limits (typically 16KB)`,a>this.urlLengthLimit&&(n+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:t,hint:n,code:r},data:null,count:null,status:0,statusText:``}})),i.then(e,t)}async processResponse(e){var t=this;let n=null,r=null,i=null,a=e.status,o=e.statusText;if(e.ok){if(t.method!==`HEAD`){let i=await e.text();if(i!==``){if(t.headers.get(`Accept`)===`text/csv`)r=i;else if(t.headers.get(`Accept`)&&t.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`))r=i;else try{r=JSON.parse(i)}catch{if(n={message:i},r=null,t.shouldThrowOnError)throw new rt({message:i,details:``,hint:``,code:``})}}}let s=t.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),c=e.headers.get(`content-range`)?.split(`/`);if(s&&c&&c.length>1&&(i=parseInt(c[1])),t.isMaybeSingle&&Array.isArray(r)){if(r.length>1){if(n={code:`PGRST116`,details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:`JSON object requested, multiple (or no) rows returned`},r=null,i=null,a=406,o=`Not Acceptable`,t.shouldThrowOnError)throw new rt(ft(ft({},n),{},{hint:n.hint??``}))}else r=r.length===1?r[0]:null}}else{let i=await e.text();try{n=JSON.parse(i),Array.isArray(n)&&e.status===404&&(r=[],n=null,a=200,o=`OK`)}catch{e.status===404&&i===``?(a=204,o=`No Content`):n={message:i}}if(n&&t.shouldThrowOnError)throw new rt(n)}return{success:n===null,error:n,data:r,count:i,status:a,statusText:o}}returns(){
|
|
3
3
|
/* istanbul ignore next */
|
|
4
4
|
return this}overrideTypes(){return this}},_t=class extends gt{throwOnError(){return super.throwOnError()}select(e){let t=!1,n=(e??`*`).split(``).map(e=>/\s/.test(e)&&!t?``:(e===`"`&&(t=!t),e)).join(``);return this.url.searchParams.set(`select`,n),this.headers.append(`Prefer`,`return=representation`),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){let a=i?`${i}.order`:`order`,o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:``}${e}.${t?`asc`:`desc`}${n===void 0?``:n?`.nullsfirst`:`.nullslast`}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let r=n===void 0?`limit`:`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){let i=r===void 0?`offset`:`${r}.offset`,a=r===void 0?`limit`:`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set(`Accept`,`text/csv`),this}geojson(){return this.headers.set(`Accept`,`application/geo+json`),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:a=`text`}={}){let o=[e?`analyze`:null,t?`verbose`:null,n?`settings`:null,r?`buffers`:null,i?`wal`:null].filter(Boolean).join(`|`),s=this.headers.get(`Accept`)??`application/json`;return this.headers.set(`Accept`,`application/vnd.pgrst.plan+${a}; for="${s}"; options=${o};`),this}rollback(){return this.headers.append(`Prefer`,`tx=rollback`),this}returns(){return this}maxAffected(e){return this.headers.append(`Prefer`,`handling=strict`),this.headers.append(`Prefer`,`max-affected=${e}`),this}};const vt=/* @__PURE__ */ RegExp(`[,()]`);var yt=class extends _t{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(`,`)}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(`,`)}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(`,`)}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(`,`)}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&vt.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&vt.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t==`string`?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t==`string`?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t==`string`?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(`,`)}}`),this}textSearch(e,t,{config:n,type:r}={}){let i=``;r===`plain`?i=`pl`:r===`phrase`?i=`ph`:r===`websearch`&&(i=`w`);let a=n===void 0?``:`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>t!==void 0).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let r=n?`${n}.or`:`or`;return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},bt=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:i=8e3,retry:a}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=i,this.retry=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:n=!1,count:r}=t??{},i=n?`HEAD`:`GET`,a=!1,o=(e??`*`).split(``).map(e=>/\s/.test(e)&&!a?``:(e===`"`&&(a=!a),e)).join(``),{url:s,headers:c}=this.cloneRequestState();return s.searchParams.set(`select`,o),r&&c.append(`Prefer`,`count=${r}`),new yt({method:i,url:s,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:n=!0}={}){let{url:r,headers:i}=this.cloneRequestState();if(t&&i.append(`Prefer`,`count=${t}`),n||i.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);r.searchParams.set(`columns`,e.join(`,`))}}return new yt({method:`POST`,url:r,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:i=!0}={}){let{url:a,headers:o}=this.cloneRequestState();if(o.append(`Prefer`,`resolution=${n?`ignore`:`merge`}-duplicates`),t!==void 0&&a.searchParams.set(`on_conflict`,t),r&&o.append(`Prefer`,`count=${r}`),i||o.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set(`columns`,e.join(`,`))}}return new yt({method:`POST`,url:a,headers:o,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){let{url:n,headers:r}=this.cloneRequestState();return t&&r.append(`Prefer`,`count=${t}`),new yt({method:`PATCH`,url:n,headers:r,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){let{url:t,headers:n}=this.cloneRequestState();return e&&n.append(`Prefer`,`count=${e}`),new yt({method:`DELETE`,url:t,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function xt(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return new rt({message:String(t.message??e),details:t.details??``,hint:t.hint??``,code:t.code??``})}catch{}return new rt({message:e||t,details:``,hint:``,code:``})}function St(e,t,n){let r=e;return{success:!1,error:new rt({message:`${r?.name??`FetchError`}: ${r?.message}`,details:``,hint:``,code:``}),data:null,count:null,status:t,statusText:n}}var Ct=class e{constructor(e,{headers:t={},schema:n,fetch:r,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.urlLengthLimit=a;let s=r??globalThis.fetch;this.fetch=i!==void 0&&i>0?(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(r),s(e,t);let i=()=>{clearTimeout(r),n.abort()};return a.addEventListener(`abort`,i,{once:!0}),s(e,ft(ft({},t),{},{signal:n.signal})).finally(()=>{clearTimeout(r),a.removeEventListener(`abort`,i)})}return s(e,ft(ft({},t),{},{signal:n.signal})).finally(()=>clearTimeout(r))}:s,this.retry=o}from(e){if(!e||typeof e!=`string`||e.trim()===``)throw Error(`Invalid relation name: relation must be a non-empty string.`);return new bt(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}async getOpenApiSpec(){var e=this;let t=new Headers(e.headers);t.set(`Accept`,`application/openapi+json`),e.schemaName&&t.set(`Accept-Profile`,e.schemaName);let n={};t.forEach((e,t)=>{n[t]=e});let r=e.fetch??globalThis.fetch,i;try{i=await ht(r,`${e.url}/`,{method:`GET`,headers:n},e.retry??!0)}catch(e){return St(e,0,``)}let a;try{a=await i.text()}catch(e){return St(e,i.status,i.statusText)}if(i.ok)try{return{success:!0,error:null,data:JSON.parse(a),count:null,status:i.status,statusText:i.statusText}}catch{}return{success:!1,error:xt(a,i.statusText),data:null,count:null,status:i.status,statusText:i.statusText}}rpc(e,t={},{head:n=!1,get:r=!1,count:i}={}){let a,o=new URL(`${this.url}/rpc/${e}`),s,c=e=>typeof e==`object`&&!!e&&(!Array.isArray(e)||e.some(c)),l=n&&Object.values(t).some(c);l?(a=`POST`,s=t):n||r?(a=n?`HEAD`:`GET`,Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(`,`)}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a=`POST`,s=t);let u=new Headers(this.headers);return l?u.set(`Prefer`,i?`count=${i},return=minimal`:`return=minimal`):i&&u.set(`Prefer`,`count=${i}`),new yt({method:a,url:o,headers:u,schema:this.schemaName,body:s,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},wt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebSocketFactory=void 0;var t=class{constructor(){}static detectEnvironment(){if(typeof WebSocket<`u`)return{type:`native`,wsConstructor:WebSocket};let e=globalThis;if(typeof globalThis<`u`&&e.WebSocket!==void 0)return{type:`native`,wsConstructor:e.WebSocket};let t=typeof global<`u`?global:void 0;if(t&&t.WebSocket!==void 0)return{type:`native`,wsConstructor:t.WebSocket};if(typeof globalThis<`u`&&e.WebSocketPair!==void 0&&globalThis.WebSocket===void 0)return{type:`cloudflare`,error:`Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.`,workaround:`Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.`};if(typeof globalThis<`u`&&e.EdgeRuntime||typeof navigator<`u`&&navigator.userAgent?.includes(`Vercel-Edge`))return{type:`unsupported`,error:`Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.`,workaround:`Use serverless functions or a different deployment target for WebSocket functionality.`};let n=globalThis.process;if(n){let e=n.versions;if(e&&e.node)return{type:`unsupported`,error:`Node.js detected but native WebSocket not found.`,workaround:`Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option.`}}return{type:`unsupported`,error:`Unknown JavaScript runtime without WebSocket support.`,workaround:`Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.`}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let t=e.error||`WebSocket not supported in this environment.`;throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),Error(t)}static isWebSocketSupported(){try{return this.detectEnvironment().type===`native`}catch{return!1}}};e.WebSocketFactory=t,e.default=t})),Tt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.version=void 0,e.version=`2.118.0`})),Et=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CONNECTION_STATE=e.TRANSPORTS=e.CHANNEL_EVENTS=e.CHANNEL_STATES=e.SOCKET_STATES=e.MAX_PUSH_BUFFER_SIZE=e.WS_CLOSE_NORMAL=e.POSTGRES_CHANGES_WAIT_ERROR_GRACE=e.DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT=e.DEFAULT_TIMEOUT=e.VERSION=e.DEFAULT_VSN=e.VSN_2_0_0=e.VSN_1_0_0=e.DEFAULT_VERSION=void 0;let t=Tt();e.DEFAULT_VERSION=`realtime-js/${t.version}`,e.VSN_1_0_0=`1.0.0`,e.VSN_2_0_0=`2.0.0`,e.DEFAULT_VSN=e.VSN_2_0_0,e.VERSION=t.version,e.DEFAULT_TIMEOUT=1e4,e.DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT=15e3,e.POSTGRES_CHANGES_WAIT_ERROR_GRACE=1e4,e.WS_CLOSE_NORMAL=1e3,e.MAX_PUSH_BUFFER_SIZE=100,e.SOCKET_STATES={connecting:0,open:1,closing:2,closed:3},e.CHANNEL_STATES={closed:`closed`,errored:`errored`,joined:`joined`,joining:`joining`,leaving:`leaving`},e.CHANNEL_EVENTS={close:`phx_close`,error:`phx_error`,join:`phx_join`,reply:`phx_reply`,leave:`phx_leave`,access_token:`access_token`},e.TRANSPORTS={websocket:`websocket`},e.CONNECTION_STATE={connecting:`connecting`,open:`open`,closing:`closing`,closed:`closed`}})),Dt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT=`broadcast`,this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event==`string`)return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){return this._isArrayBuffer(e.payload?.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){let t=e.payload?.payload??/* @__PURE__ */ new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,t)}_encodeJsonUserBroadcastPush(e){let t=e.payload?.payload??{},n=new TextEncoder().encode(JSON.stringify(t)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,n){let r=new TextEncoder,i=r.encode(e.topic),a=r.encode(e.ref??``),o=r.encode(e.join_ref??``),s=r.encode(e.payload.event),c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=r.encode(Object.keys(c).length===0?``:JSON.stringify(c));if(o.length>255)throw Error(`joinRef length ${o.length} exceeds maximum of 255`);if(a.length>255)throw Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw Error(`topic length ${i.length} exceeds maximum of 255`);if(s.length>255)throw Error(`userEvent length ${s.length} exceeds maximum of 255`);if(l.length>255)throw Error(`metadata length ${l.length} exceeds maximum of 255`);let u=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+a.length+i.length+s.length+l.length,d=new ArrayBuffer(this.HEADER_LENGTH+u),f=new DataView(d),p=new Uint8Array(d),m=0;f.setUint8(m++,this.KINDS.userBroadcastPush),f.setUint8(m++,o.length),f.setUint8(m++,a.length),f.setUint8(m++,i.length),f.setUint8(m++,s.length),f.setUint8(m++,l.length),f.setUint8(m++,t),p.set(o,m),m+=o.length,p.set(a,m),m+=a.length,p.set(i,m),m+=i.length,p.set(s,m),m+=s.length,p.set(l,m),m+=l.length;var h=new Uint8Array(d.byteLength+n.byteLength);return h.set(new Uint8Array(d),0),h.set(new Uint8Array(n),d.byteLength),h.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if(typeof e==`string`){let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}return t({})}_binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,r)}}_decodeUserBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+4,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=e.slice(s,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(n.decode(d)):d,p={type:this.BROADCAST_EVENT,event:l,payload:f};return a>0&&(p.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){return e instanceof ArrayBuffer||e?.constructor?.name===`ArrayBuffer`}_pick(e,t){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}}})),Ot=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.httpEndpointURL=e.toTimestampString=e.toArray=e.toJson=e.toNumber=e.toBoolean=e.convertCell=e.convertColumn=e.convertChangeData=e.PostgresTypes=void 0;var t;(function(e){e.abstime=`abstime`,e.bool=`bool`,e.date=`date`,e.daterange=`daterange`,e.float4=`float4`,e.float8=`float8`,e.int2=`int2`,e.int4=`int4`,e.int4range=`int4range`,e.int8=`int8`,e.int8range=`int8range`,e.json=`json`,e.jsonb=`jsonb`,e.money=`money`,e.numeric=`numeric`,e.oid=`oid`,e.reltime=`reltime`,e.text=`text`,e.time=`time`,e.timestamp=`timestamp`,e.timestamptz=`timestamptz`,e.timetz=`timetz`,e.tsrange=`tsrange`,e.tstzrange=`tstzrange`})(t||(e.PostgresTypes=t={})),e.convertChangeData=(t,n,r={})=>{let i=r.skipTypes??[];return n?Object.keys(n).reduce((r,a)=>(r[a]=(0,e.convertColumn)(a,t,n,i),r),{}):{}},e.convertColumn=(t,r,i,a)=>{let o=r.find(e=>e.name===t)?.type,s=i[t];return o&&!a.includes(o)?(0,e.convertCell)(o,s):n(s)},e.convertCell=(r,i)=>{if(r.charAt(0)===`_`){let t=r.slice(1,r.length);return(0,e.toArray)(i,t)}switch(r){case t.bool:return(0,e.toBoolean)(i);case t.float4:case t.float8:case t.int2:case t.int4:case t.int8:case t.numeric:case t.oid:return(0,e.toNumber)(i);case t.json:case t.jsonb:return(0,e.toJson)(i);case t.timestamp:return(0,e.toTimestampString)(i);case t.abstime:case t.date:case t.daterange:case t.int4range:case t.int8range:case t.money:case t.reltime:case t.text:case t.time:case t.timestamptz:case t.timetz:case t.tsrange:case t.tstzrange:return n(i);default:return n(i)}};let n=e=>e;e.toBoolean=e=>{switch(e){case`t`:return!0;case`f`:return!1;default:return e}},e.toNumber=e=>{if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},e.toJson=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e},e.toArray=(t,n)=>{if(typeof t!=`string`)return t;let r=t.length-1,i=t[r];if(t[0]===`{`&&i===`}`){let i,a=t.slice(1,r);try{i=JSON.parse(`[`+a+`]`)}catch{i=a?a.split(`,`):[]}return i.map(t=>(0,e.convertCell)(n,t))}return t},e.toTimestampString=e=>typeof e==`string`?e.replace(` `,`T`):e,e.httpEndpointURL=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,`http`),t.pathname=t.pathname.replace(/\/+$/,``).replace(/\/socket\/websocket$/i,``).replace(/\/socket$/i,``).replace(/\/websocket$/i,``),t.pathname===``||t.pathname===`/`?t.pathname=`/api/broadcast`:t.pathname+=`/api/broadcast`,t.href}})),kt=/* @__PURE__ */ D(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{Channel:()=>E,LongPoll:()=>ne,Presence:()=>re,Push:()=>w,Serializer:()=>ie,Socket:()=>ae,Timer:()=>T}),t.exports=c(l);var u=e=>typeof e==`function`?e:function(){return e},d=typeof self<`u`?self:null,f=typeof window<`u`?window:null,p=d||f||globalThis,m=`2.0.0`,h=1e4,g=1e3,_=100,v={connecting:0,open:1,closing:2,closed:3},y={closed:`closed`,errored:`errored`,joined:`joined`,joining:`joining`,leaving:`leaving`},b={close:`phx_close`,error:`phx_error`,join:`phx_join`,reply:`phx_reply`,leave:`phx_leave`},x={longpoll:`longpoll`,websocket:`websocket`},S={complete:4},C=`base64url.bearer.phx.`,w=class{constructor(e,t,n,r){this.channel=e,this.event=t,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived(`timeout`)||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:n}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger(`timeout`,{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},T=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries+=1,this.callback()},this.timerCalc(this.tries+1))}},E=class{constructor(e,t,n){this.state=y.closed,this.topic=e,this.params=u(t||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new w(this,b.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new T(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive(`ok`,()=>{this.state=y.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this.joinPush.receive(`error`,e=>{this.state=y.errored,this.socket.hasLogger()&&this.socket.log(`channel`,`error ${this.topic}`,e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log(`channel`,`close ${this.topic}`),this.state=y.closed,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log(`channel`,`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=y.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive(`timeout`,()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`timeout ${this.topic}`,this.joinPush.timeout),new w(this,b.leave,u({}),this.timeout).send(),this.state=y.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(b.reply,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(this.joinedOnce)throw Error(`tried to join multiple times. 'join' can only be called a single time per channel instance`);return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=y.closed,this.bindings=[]}onClose(e){this.on(b.close,e)}onError(e){return this.on(b.error,t=>e(t))}on(e,t){let n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}off(e,t){this.bindings=this.bindings.filter(n=>n.event!==e||t!==void 0&&t!==n.ref)}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,n=this.timeout){if(t||={},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new w(this,e,function(){return t},n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=y.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`leave ${this.topic}`),this.trigger(b.close,`leave`)},n=new w(this,b.leave,u({}),e);return n.receive(`ok`,()=>t()).receive(`timeout`,()=>t()),n.send(),this.canPush()||n.trigger(`ok`,{}),n}onMessage(e,t,n){return t}filterBindings(e,t,n){return!0}isMember(e,t,n,r){return this.topic===e?r&&r!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log(`channel`,`dropping outdated message`,{topic:e,event:t,payload:n,joinRef:r}),!1):!0:!1}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=y.joining,this.joinPush.resend(e))}trigger(e,t,n,r){let i=this.onMessage(e,t,n,r);if(t&&!i)throw Error(`channel onMessage callbacks must return the payload, modified or unmodified`);let a=this.bindings.filter(r=>r.event===e&&this.filterBindings(r,t,n));for(let e=0;e<a.length;e++)a[e].callback(i,n,r||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===y.closed}isErrored(){return this.state===y.errored}isJoined(){return this.state===y.joined}isJoining(){return this.state===y.joining}isLeaving(){return this.state===y.leaving}},ee=class{static request(e,t,n,r,i,a,o){if(p.XDomainRequest){let n=new p.XDomainRequest;return this.xdomainRequest(n,e,t,r,i,a,o)}if(p.XMLHttpRequest){let s=new p.XMLHttpRequest;return this.xhrRequest(s,e,t,n,r,i,a,o)}if(p.fetch&&p.AbortController)return this.fetchRequest(e,t,n,r,i,a,o);throw Error(`No suitable XMLHttpRequest implementation found`)}static fetchRequest(e,t,n,r,i,a,o){let s={method:e,headers:n,body:r},c=null;return i&&(c=new AbortController,setTimeout(()=>c.abort(),i),s.signal=c.signal),p.fetch(t,s).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>o&&o(e)).catch(e=>{e.name===`AbortError`&&a?a():o&&o(null)}),c}static xdomainRequest(e,t,n,r,i,a,o){return e.timeout=i,e.open(t,n),e.onload=()=>{let t=this.parseJSON(e.responseText);o&&o(t)},a&&(e.ontimeout=a),e.onprogress=()=>{},e.send(r),e}static xhrRequest(e,t,n,r,i,a,o,s){e.open(t,n,!0),e.timeout=a;for(let[t,n]of Object.entries(r))e.setRequestHeader(t,n);return e.onerror=()=>s&&s(null),e.onreadystatechange=()=>{e.readyState===S.complete&&s&&s(this.parseJSON(e.responseText))},o&&(e.ontimeout=o),e.send(i),e}static parseJSON(e){if(!e||e===``)return null;try{return JSON.parse(e)}catch{return console&&console.log(`failed to parse JSON response`,e),null}}static serialize(e,t){let n=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=t?`${t}[${r}]`:r,a=e[r];typeof a==`object`?n.push(this.serialize(a,i)):n.push(encodeURIComponent(i)+`=`+encodeURIComponent(a))}return n.join(`&`)}static appendParams(e,t){return Object.keys(t).length===0?e:`${e}${e.match(/\?/)?`&`:`?`}${this.serialize(t)}`}},te=e=>{let t=``,n=new Uint8Array(e),r=n.byteLength;for(let e=0;e<r;e++)t+=String.fromCharCode(n[e]);return btoa(t)},ne=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(C)&&(this.authToken=atob(t[1].slice(C.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=/* @__PURE__ */ new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=v.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace(`ws://`,`http://`).replace(`wss://`,`https://`).replace(RegExp(`(.*)/`+x.websocket),`$1/`+x.longpoll)}endpointURL(){return ee.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,n){this.close(e,t,n),this.readyState=v.connecting}ontimeout(){this.onerror(`timeout`),this.closeAndRetry(1005,`timeout`,!1)}isActive(){return this.readyState===v.open||this.readyState===v.connecting}poll(){let e={Accept:`application/json`};this.authToken&&(e[`X-Phoenix-AuthToken`]=this.authToken),this.ajax(`GET`,e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:n,messages:r}=e;if(t===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,`session_gone`,!1);return}this.token=n}else t=0;switch(t){case 200:r.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=v.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,`forbidden`,!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,`internal server error`,500);break;default:throw Error(`unhandled poll status ${t}`)}})}send(e){typeof e!=`string`&&(e=te(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e,t=0){this.awaitingBatchAck=!0;let n=t+_,r=e.slice(t,n);this.ajax(`POST`,{"Content-Type":`application/x-ndjson`},r.join(`
|
|
5
5
|
`),()=>this.onerror(`timeout`),t=>{!t||t.status!==200?(this.awaitingBatchAck=!1,this.onerror(t&&t.status),this.closeAndRetry(1011,`internal server error`,!1)):n<e.length?this.batchSend(e,n):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(e,t,n){for(let e of this.reqs)e.abort();this.readyState=v.closed;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<`u`?this.onclose(new CloseEvent(`close`,r)):this.onclose(r)}ajax(e,t,n,r,i){let a;a=ee.request(e,this.endpointURL(),t,n,this.timeout,()=>{this.reqs.delete(a),r()},e=>{this.reqs.delete(a),this.isActive()&&i(e)}),this.reqs.add(a)}},re=class e{constructor(t,n={}){let r=n.events||{state:`presence_state`,diff:`presence_diff`};this.state=/* @__PURE__ */ Object.create(null),this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(r.state,t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.joinRef=this.channel.joinRef(),this.state=e.syncState(this.state,t,n,r),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,n,r)}),this.pendingDiffs=[],i()}),this.channel.on(r.diff,t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,n,r),i())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,n,r){let i=this.toNullProtoObj(this.clone(e));t=this.toNullProtoObj(t);let a=/* @__PURE__ */ Object.create(null),o=/* @__PURE__ */ Object.create(null);return this.map(i,(e,n)=>{t[e]||(o[e]=n)}),this.map(t,(e,t)=>{let n=i[e];if(n){let r=t.metas.map(e=>e.phx_ref),i=n.metas.map(e=>e.phx_ref),s=t.metas.filter(e=>i.indexOf(e.phx_ref)<0),c=n.metas.filter(e=>r.indexOf(e.phx_ref)<0);s.length>0&&(a[e]=t,a[e].metas=s),c.length>0&&(o[e]=this.clone(n),o[e].metas=c)}else a[e]=t}),this.syncDiff(i,{joins:a,leaves:o},n,r)}static syncDiff(e,t,n,r){e=this.toNullProtoObj(e);let{joins:i,leaves:a}=this.clone(t);return n||=function(){},r||=function(){},this.map(i,(t,r)=>{let i=e[t];if(e[t]=this.clone(r),i){let n=e[t].metas.map(e=>e.phx_ref),r=i.metas.filter(e=>n.indexOf(e.phx_ref)<0);e[t].metas.unshift(...r)}n(t,i,r)}),this.map(a,(t,n)=>{let i=e[t];if(!i)return;let a=n.metas.map(e=>e.phx_ref);i.metas=i.metas.filter(e=>a.indexOf(e.phx_ref)<0),r(t,i,n),i.metas.length===0&&delete e[t]}),e}static list(e,t){return t||=function(e,t){return t},this.map(e,(e,n)=>t(e,n))}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let t=/* @__PURE__ */ Object.create(null);return Object.getOwnPropertyNames(e).forEach(n=>{t[n]=e[n]}),t}static clone(e){return JSON.parse(JSON.stringify(e))}},ie={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}},binaryEncode(e){let{join_ref:t,ref:n,event:r,topic:i,payload:a}=e,o=new TextEncoder,s=o.encode(t),c=o.encode(n),l=o.encode(i),u=o.encode(r);this.assertFieldSize(s.byteLength,`join_ref`),this.assertFieldSize(c.byteLength,`ref`),this.assertFieldSize(l.byteLength,`topic`),this.assertFieldSize(u.byteLength,`event`);let d=this.META_LENGTH+s.byteLength+c.byteLength+l.byteLength+u.byteLength,f=new ArrayBuffer(this.HEADER_LENGTH+d),p=new Uint8Array(f),m=new DataView(f),h=0;m.setUint8(h++,this.KINDS.push),m.setUint8(h++,s.byteLength),m.setUint8(h++,c.byteLength),m.setUint8(h++,l.byteLength),m.setUint8(h++,u.byteLength),p.set(s,h),h+=s.byteLength,p.set(c,h),h+=c.byteLength,p.set(l,h),h+=l.byteLength,p.set(u,h),h+=u.byteLength;var g=new Uint8Array(f.byteLength+a.byteLength);return g.set(p,0),g.set(new Uint8Array(a),f.byteLength),g.buffer},assertFieldSize(e,t){if(e>255)throw Error(`unable to convert ${t} to binary: must be less than or equal to 255 bytes, but is ${e} bytes`)},binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,s=n.decode(e.slice(o,o+r));o+=r;let c=n.decode(e.slice(o,o+i));o+=i;let l=n.decode(e.slice(o,o+a));return o+=a,{join_ref:s,ref:null,topic:c,event:l,payload:e.slice(o,e.byteLength)}},decodeReply(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+this.META_LENGTH,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=n.decode(e.slice(s,s+o));s+=o;let f={status:d,response:e.slice(s,e.byteLength)};return{join_ref:c,ref:l,topic:u,event:b.reply,payload:f}},decodeBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,o=n.decode(e.slice(a,a+r));a+=r;let s=n.decode(e.slice(a,a+i));return a+=i,{join_ref:null,ref:null,topic:o,event:s,payload:e.slice(a,e.byteLength)}}},ae=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||h,this.transport=t.transport||p.WebSocket||ne,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let n=null;try{n=p&&p.sessionStorage}catch{}this.sessionStore=t.sessionStorage||n,this.establishedConnections=0,this.defaultEncoder=ie.encode.bind(ie),this.defaultDecoder=ie.decode.bind(ie),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||`arraybuffer`,this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport===ne?(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder):(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder);let r=null;f&&f.addEventListener&&(f.addEventListener(`pagehide`,e=>{this.conn&&(this.disconnect(),r=this.connectClock)}),f.addEventListener(`pageshow`,e=>{r===this.connectClock&&(r=null,this.connect())}),f.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,n)=>{console.log(`${e}: ${t}`,n)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=u(t.params||{}),this.endPoint=`${e}/${x.websocket}`,this.vsn=t.vsn||m,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new T(()=>{this.pageHidden?(this.log(`Not reconnecting as page is hidden!`),this.teardown()):this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken&&u(t.authToken)}getLongPollTransport(){return ne}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&=(this.conn.close(),null),this.transport=e}protocol(){return location.protocol.match(/^https/)?`wss`:`ws`}endPointURL(){let e=ee.appendParams(ee.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)===`/`?e.charAt(1)===`/`?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`:e}disconnect(e,t,n){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,n)}connect(e){e&&(console&&console.log(`passing params to connect is deprecated. Instead pass :params to the Socket constructor`),this.params=u(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==ne?this.connectWithFallback(ne,this.longPollFallbackMs):this.transportConnect())}log(e,t,n){this.logger&&this.logger(e,t,n)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),n=Date.now();this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:t});let r=this.onMessage(i=>{i.ref===t&&(this.off([r]),e(Date.now()-n))});return!0}transportName(e){switch(e){case ne:return`LongPoll`;default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=[`phoenix`,`${C}${btoa(this.authToken()).replace(/=/g,``)}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let n=!1,r=!0,i,a,o=this.transportName(e),s=t=>{this.log(`transport`,`falling back to ${o}...`,t),this.off([i,a]),r=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return s(`memorized`);this.fallbackTimer=setTimeout(s,t),a=this.onError(e=>{this.log(`transport`,`error`,e),r&&!n&&(clearTimeout(this.fallbackTimer),s(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!r){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,`true`),this.log(`transport`,`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(s,t),this.ping(e=>{this.log(`transport`,`connected to primary after`,e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log(`transport`,`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks(`open`)}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log(`transport`,`heartbeat timeout. Attempting to re-establish connection`);try{this.heartbeatCallback(`timeout`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.triggerChanError(/* @__PURE__ */ Error(`heartbeat timeout`)),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),g,`heartbeat timeout`)}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,n){if(!this.conn)return e&&e();let r=this.conn;this.waitForBufferDone(r,()=>{t?r.close(t,n||``):r.close(),this.waitForSocketClosed(r,()=>{this.conn===r&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,n=1){n===5||!e.bufferedAmount?t():setTimeout(()=>{this.waitForBufferDone(e,t,n+1)},150*n)}waitForSocketClosed(e,t,n=1){n===5||e.readyState===v.closed?t():setTimeout(()=>{this.waitForSocketClosed(e,t,n+1)},150*n)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log(`transport`,`close`,e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks(`close`,e)}onConnError(e){this.hasLogger()&&this.log(`transport`,`error`,e);let t=this.transport,n=this.establishedConnections;this.triggerStateCallbacks(`error`,e,t,n),(t===this.transport||n>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(b.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case v.connecting:return`connecting`;case v.open:return`open`;case v.closing:return`closing`;default:return`closed`}}isConnected(){return this.connectionState()===`open`}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>e.indexOf(t)===-1)}channel(e,t={}){let n=new E(e,t,this);return this.channels.push(n),n}push(e){if(this.hasLogger()){let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;this.log(`push`,`${t} ${n} (${a}, ${i})`,r)}this.isConnected()?this.encode(e,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(e,e=>this.conn.send(e)))}makeRef(){let e=this.ref+1;return this.ref=e===this.ref?0:e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected())try{this.heartbeatCallback(`disconnected`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}else if(this.pendingHeartbeatRef)this.heartbeatTimeout();else{this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback(`sent`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){let e=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(r.status===`ok`?`ok`:`error`,e)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log(`receive`,`${r.status||``} ${t} ${n} ${i&&`(`+i+`)`||``}`.trim(),r);for(let e=0;e<this.channels.length;e++){let o=this.channels[e];o.isMember(t,n,r,a)&&o.trigger(n,r,i,a)}this.triggerStateCallbacks(`message`,e)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([n,r])=>{try{r(...t)}catch(t){this.log(`error`,`error in ${e} callback`,t)}})}catch(t){this.log(`error`,`error triggering ${e} callbacks`,t)}}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log(`transport`,`leaving duplicate topic "${e}"`),t.leave())}}})),At=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kt();e.default=class e{constructor(n,r){let a=i(r);this.presence=new t.Presence(n.getChannel(),a),this.presence.onJoin((t,r,i)=>{let a=e.onJoinPayload(t,r,i);n.getChannel().trigger(`presence`,a)}),this.presence.onLeave((t,r,i)=>{let a=e.onLeavePayload(t,r,i);n.getChannel().trigger(`presence`,a)}),this.presence.onSync(()=>{n.getChannel().trigger(`presence`,{event:`sync`})})}get state(){return e.transformState(this.presence.state)}static transformState(e){return e=r(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return t[r]=n(i),t},{})}static onJoinPayload(e,t,r){return{event:`join`,key:e,currentPresences:a(t),newPresences:n(r)}}static onLeavePayload(e,t,r){return{event:`leave`,key:e,currentPresences:a(t),leftPresences:n(r)}}};function n(e){return e.metas.map(e=>{let t=Object.getOwnPropertyDescriptors(e),n=Object.defineProperties({},t);return n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n})}function r(e){return JSON.parse(JSON.stringify(e))}function i(e){return e?.events&&{events:e.events}}function a(e){return e?.metas?n(e):[]}})),jt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.REALTIME_PRESENCE_LISTEN_EVENTS=void 0;let t=(Qe(),ue(me)).__importDefault(At());var n;(function(e){e.SYNC=`sync`,e.JOIN=`join`,e.LEAVE=`leave`})(n||(e.REALTIME_PRESENCE_LISTEN_EVENTS=n={})),e.default=class{get state(){return this.presenceAdapter.state}constructor(e,n){this.channel=e,this.presenceAdapter=new t.default(this.channel.channelAdapter,n)}}})),Mt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.normalizeChannelError=t;function t(e){if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);if(e&&typeof e==`object`){let t=e;if(typeof t.code==`number`){let n=typeof t.reason==`string`&&t.reason?` (${t.reason})`:``;return Error(`socket closed: ${t.code}${n}`,{cause:e})}return Error(`channel error: transport failure`,{cause:e})}return/* @__PURE__ */ Error(`channel error: connection lost`)}})),Nt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Et();e.default=class{constructor(e,t,r){let i=n(r);this.channel=e.getSocket().channel(t,i),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,n,r){let i;try{i=this.channel.push(e,n,r)}catch{throw Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>t.MAX_PUSH_BUFFER_SIZE){let e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log(`channel`,`discarded push due to buffer overflow: ${e.event}`,e.payload())}return i}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===t.CHANNEL_STATES.joined}isJoined(){return this.state===t.CHANNEL_STATES.joined}isJoining(){return this.state===t.CHANNEL_STATES.joining}isClosed(){return this.state===t.CHANNEL_STATES.closed}isLeaving(){return this.state===t.CHANNEL_STATES.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function n(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:``,enabled:!1},private:!1},e.config)}}})),Pt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.postgresChangesFilter=e.RealtimePostgresFilterBuilder=void 0;let t=/[,()"\\]/,n=e=>t.test(e)||e!==e.trim(),r=e=>`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`,i=e=>{let t=e===null?`null`:String(e);return n(t)?r(t):t},a=e=>e===null?`null`:String(e),o=(e,t)=>{if(e===`in`){let e=Array.isArray(t)?t:[t];if(e.length===0)throw Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(e)).map(e=>i(e)).join(`,`)})`}return e===`is`?`is.${a(t)}`:`${e}.${i(t)}`};var s=class{constructor(){this.filters=[]}add(e,t,n,r=!1){let i=r?`not.`:``;return this.filters.push(`${e}=${i}${o(t,n)}`),this}eq(e,t){return this.add(e,`eq`,t)}neq(e,t){return this.add(e,`neq`,t)}gt(e,t){return this.add(e,`gt`,t)}gte(e,t){return this.add(e,`gte`,t)}lt(e,t){return this.add(e,`lt`,t)}lte(e,t){return this.add(e,`lte`,t)}in(e,t){return this.add(e,`in`,t)}like(e,t){return this.add(e,`like`,t)}ilike(e,t){return this.add(e,`ilike`,t)}match(e,t){return this.add(e,`match`,t)}imatch(e,t){return this.add(e,`imatch`,t)}is(e,t){return this.add(e,`is`,t)}isDistinct(e,t){return this.add(e,`isdistinct`,t)}not(e,t,n){return this.add(e,t,n,!0)}build(){return this.filters.join(`,`)}toString(){return this.build()}};e.RealtimePostgresFilterBuilder=s,e.postgresChangesFilter=()=>new s})),Ft=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.REALTIME_CHANNEL_STATES=e.REALTIME_SUBSCRIBE_STATES=e.REALTIME_LISTEN_TYPES=e.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=e.postgresChangesFilter=e.RealtimePostgresFilterBuilder=void 0;let t=(Qe(),ue(me)),n=Et(),r=t.__importDefault(jt()),i=t.__importStar(Ot()),a=Ot(),o=Mt(),s=t.__importDefault(Nt()),c=Pt();var l=Pt();Object.defineProperty(e,"RealtimePostgresFilterBuilder",{enumerable:!0,get:function(){return l.RealtimePostgresFilterBuilder}}),Object.defineProperty(e,"postgresChangesFilter",{enumerable:!0,get:function(){return l.postgresChangesFilter}});var u;(function(e){e.ALL=`*`,e.INSERT=`INSERT`,e.UPDATE=`UPDATE`,e.DELETE=`DELETE`})(u||(e.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=u={}));var d;(function(e){e.BROADCAST=`broadcast`,e.PRESENCE=`presence`,e.POSTGRES_CHANGES=`postgres_changes`,e.SYSTEM=`system`})(d||(e.REALTIME_LISTEN_TYPES=d={}));var f;(function(e){e.SUBSCRIBED=`SUBSCRIBED`,e.TIMED_OUT=`TIMED_OUT`,e.CLOSED=`CLOSED`,e.CHANNEL_ERROR=`CHANNEL_ERROR`})(f||(e.REALTIME_SUBSCRIBE_STATES=f={})),e.REALTIME_CHANNEL_STATES=n.CHANNEL_STATES,e.default=class e{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,t={config:{}},n){if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,``),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:``,enabled:!1},private:!1},t.config),this.channelAdapter=new s.default(this.socket.socketAdapter,e,this.params),this.presence=new r.default(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=(0,a.httpEndpointURL)(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&this.params.config?.broadcast?.replay)throw Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,t=this.timeout){if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:r,presence:i,private:a,postgres_changes_options:s}}=this.params,c=this.bindings.postgres_changes?.map(e=>e.filter)??[],l=!!this.bindings[d.PRESENCE]&&this.bindings[d.PRESENCE].length>0||this.params.config.presence?.enabled===!0,u={},p=Object.assign({broadcast:r,presence:Object.assign(Object.assign({},i),{enabled:l}),postgres_changes:c,private:a},s?{postgres_changes_options:s}:{});this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(t=>{e?.(f.CHANNEL_ERROR,(0,o.normalizeChannelError)(t))}),this._onClose(()=>e?.(f.CLOSED)),this.updateJoinPayload(Object.assign({config:p},u)),this._updateFilterMessage();let m=s?.wait&&c.length>0?Math.max(t,(s.timeout??n.DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT)+n.POSTGRES_CHANGES_WAIT_ERROR_GRACE):t;this.channelAdapter.subscribe(m).receive(`ok`,async({postgres_changes:t})=>{this.socket._isManualToken()||this.socket.setAuth(),t===void 0?e?.(f.SUBSCRIBED):this._updatePostgresBindings(t,e)}).receive(`error`,t=>{this.state=n.CHANNEL_STATES.errored;let r=Object.values(t).join(`, `)||`error`;e?.(f.CHANNEL_ERROR,Error(r,{cause:t}))}).receive(`timeout`,()=>{e?.(f.TIMED_OUT)})}return this}_updatePostgresBindings(t,r){let i=this.bindings.postgres_changes,a=i?.length??0,o=[];for(let s=0;s<a;s++){let a=i[s],{filter:{event:c,schema:l,table:u,filter:d}}=a,p=t&&t[s];if(p&&p.event===c&&e.isFilterValueEqual(p.schema,l)&&e.isFilterValueEqual(p.table,u)&&e.isFilterValueEqual(p.filter,d))o.push(Object.assign(Object.assign({},a),{id:p.id}));else{this.unsubscribe(),this.state=n.CHANNEL_STATES.errored,r?.(f.CHANNEL_ERROR,/* @__PURE__ */ Error(`mismatch between server and client bindings for postgres changes`));return}}this.bindings.postgres_changes=o,this.state!=n.CHANNEL_STATES.errored&&r&&r(f.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:`presence`,event:`track`,payload:e},t)}async untrack(e={}){return await this.send({type:`presence`,event:`untrack`},e)}on(e,t,n){let r=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===d.PRESENCE||e===d.POSTGRES_CHANGES;if(r&&i)throw this.socket.log(`channel`,`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,t,n)}async httpSend(e,t,n={}){if(t==null)return Promise.reject(/* @__PURE__ */ Error(`Payload is required for httpSend()`));let r=t instanceof ArrayBuffer||ArrayBuffer.isView(t),i={apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":r?`application/octet-stream`:`application/json`};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a=new URL(this.broadcastEndpointURL);a.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&a.searchParams.set(`private`,`true`);let o={method:`POST`,headers:i,body:r?t:JSON.stringify(t)},s=await this._fetchWithTimeout(a.toString(),o,n.timeout??this.timeout);if(s.status===202)return{success:!0};if(s.status===404)return Promise.reject(/* @__PURE__ */ Error(`httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md`));let c=s.statusText;try{let e=await s.json();c=e.error||e.message||c}catch{}return Promise.reject(Error(c))}async send(e,t={}){if(!this.channelAdapter.canPush()&&e.type===`broadcast`){let n=`Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.`;this.socket.hasLogger()?this.socket.log(`channel`,n):console.warn(n);let{event:r,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":`application/json`};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:`POST`,headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:r,payload:i,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,t.timeout??this.timeout);return await e.body?.cancel(),e.ok?`ok`:`error`}catch(e){return e instanceof Error&&e.name===`AbortError`?`timed out`:`error`}}return new Promise(n=>{let r=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);e.type===`broadcast`&&!this.params?.config?.broadcast?.ack&&n(`ok`),r.receive(`ok`,()=>n(`ok`)),r.receive(`error`,()=>n(`error`)),r.receive(`timeout`,()=>n(`timed out`))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(t=>{this.channelAdapter.unsubscribe(e).receive(`ok`,()=>t(`ok`)).receive(`timeout`,()=>t(`timed out`)).receive(`error`,()=>t(`error`))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),a}_on(t,n,r){let i=t.toLocaleLowerCase(),a=n?.filter;if((a instanceof c.RealtimePostgresFilterBuilder||typeof a==`object`&&a&&typeof a.build==`function`)&&(n=Object.assign(Object.assign({},n),{filter:a.build()})),i===d.POSTGRES_CHANGES&&this.bindings[i]?.find(t=>e.isSamePostgresFilter(t.filter,n)))return this.socket.log(`error`,`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,n),this;let o=this.channelAdapter.on(t,r),s={type:i,filter:n,callback:r,ref:o};return this.bindings[i]?this.bindings[i].push(s):this.bindings[i]=[s],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,n)=>{let r=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(r,n))return!1;let i=this.bindings[r]?.find(t=>t.ref===e.ref);if(!i)return!0;if([`broadcast`,`presence`,`postgres_changes`].includes(r)){if(`id`in i){let e=i.id,n=i.filter?.event;return e&&t.ids?.includes(e)&&(n===`*`||n?.toLocaleLowerCase()===t.data?.type.toLocaleLowerCase())}{let e=(i?.filter?.event)?.toLocaleLowerCase();return e===`*`||e===(t?.event)?.toLocaleLowerCase()}}return i.type.toLocaleLowerCase()===r})}_notThisChannelEvent(e,t){let{close:r,error:i,leave:a,join:o}=n.CHANNEL_EVENTS;return t&&[r,i,a,o].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,n)=>{if(typeof t==`object`&&`ids`in t){let e=t.data,{schema:n,table:r,commit_timestamp:i,type:a,errors:o}=e;return Object.assign(Object.assign({},{schema:n,table:r,commit_timestamp:i,eventType:a,new:{},old:{},errors:o}),this._getPayloadRecords(e))}return t})}copyBindings(e){if(this.joinedOnce)throw Error(`cannot copy bindings into joined channel`);for(let t in e.bindings)for(let n of e.bindings[t])this._on(n.type,n.filter,n.callback)}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}static isSamePostgresFilter(t,n){let r=(t?.select)?.join()??void 0,i=(n?.select)?.join()??void 0;return t?.event===n?.event&&e.isFilterValueEqual(t?.schema,n?.schema)&&e.isFilterValueEqual(t?.table,n?.table)&&e.isFilterValueEqual(t?.filter,n?.filter)&&r===i}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type===`INSERT`||e.type===`UPDATE`)&&(t.new=i.convertChangeData(e.columns,e.record)),(e.type===`UPDATE`||e.type===`DELETE`)&&(t.old=i.convertChangeData(e.columns,e.old_record)),t}}})),It=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kt(),n=Et();e.default=class{constructor(e,n){this.socket=new t.Socket(e,n)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,n,r=1e4){return new Promise(i=>{setTimeout(()=>i(`timeout`),r),this.socket.disconnect(()=>{e(),i(`ok`)},t,n)})}push(e){this.socket.push(e)}log(e,t,n){this.socket.log(e,t,n)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==n.CONNECTION_STATE.connecting}isDisconnecting(){return this.socket.connectionState()==n.CONNECTION_STATE.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}})),Lt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=(Qe(),ue(me)),n=t.__importDefault(wt()),r=Et(),i=t.__importDefault(Dt()),a=Ot(),o=t.__importDefault(Ft()),s=t.__importDefault(It()),c={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},l=[1e3,2e3,5e3,1e4];function u(){let e=/* @__PURE__ */ new Map;return{get length(){return e.size},clear(){e.clear()},getItem(t){return e.has(t)?e.get(t):null},key(t){return Array.from(e.keys())[t]??null},removeItem(t){e.delete(t)},setItem(t,n){e.set(t,String(n))}}}function d(){try{if(typeof globalThis<`u`&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return u()}e.default=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,t){if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint=``,this.headers={},this.params={},this.ref=0,this.serializer=new i.default,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!t?.params?.apikey)throw Error(`API key is required to connect to Realtime`);this.apiKey=t.params.apikey;let n=this._initializeOptions(t);this.socketAdapter=new s.default(e,n),this.httpEndpoint=(0,a.httpEndpointURL)(e),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely(`connect`),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let t=e.message;throw Error(`WebSocket not available: ${t}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return this._cancelPendingDisconnect(),this.isDisconnecting()?`ok`:await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return t===`ok`&&e.teardown(),t}async removeAllChannels(){let e=this.channels.map(async e=>{let t=await e.unsubscribe();return e.teardown(),t}),t=await Promise.all(e);return await this.disconnect(),t}log(e,t,n){this.socketAdapter.log(e,t,n)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||r.CONNECTION_STATE.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let n=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===n);if(r)return r;{let n=new o.default(`realtime:${e}`,t,this);return this._cancelPendingDisconnect(),this.channels.push(n),n}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){let t=++this._authGeneration,n=this._performAuth(e,t);t===this._authGeneration&&(this._authPromise=n);try{await n}finally{this._authPromise===n&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic),this.channels.length===0&&(this.log(`transport`,`no channels remaining, scheduling disconnect`),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0?(this.log(`transport`,`disconnecting immediately - no channels`),this.disconnect()):(this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log(`transport`,`deferred disconnect fired - no channels, disconnecting`),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log(`transport`,`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`))}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log(`transport`,`pending disconnect cancelled - channel activity detected`),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e,t){let n,i=!1;if(e)n=e,i=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(e){this.log(`error`,`Error fetching access token from callback`,e),n=this.accessTokenValue}else n=this.accessTokenValue;t===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:i&&(this._manuallySetToken=!0),this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(e=>{let t={access_token:n,version:r.DEFAULT_VERSION};e.updateJoinPayload(t),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(r.CHANNEL_EVENTS.access_token,{access_token:n})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e=`general`){this._isManualToken()||this.setAuth().catch(t=>{this.log(`error`,`Error setting auth in ${e}`,t)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(e=>{this.log(`error`,`error waiting for auth on connect`,e)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,n)=>{t!==`disconnected`&&(t==`sent`&&this._setAuthSafely(),e&&e(t,n))}}_startWorkerHeartbeat(){this.workerUrl?this.log(`worker`,`starting worker for from ${this.workerUrl}`):this.log(`worker`,`starting default worker`);let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log(`worker`,`worker error`,e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{e.data.event===`keepAlive`&&this.sendHeartbeat()},this.workerRef.postMessage({event:`start`,interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&=(this.log(`worker`,`terminating worker`),this.workerRef.terminate(),void 0)}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([`
|
|
@@ -177,8 +177,10 @@ if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid
|
|
|
177
177
|
- Tag items only from their tag sets (listed under Tags in the briefing): capabilities by who they're for and their kind, features by kind of change, tasks by kind of work. Product areas aren't tags; group capabilities under a parent capability instead.
|
|
178
178
|
- Flags are messages people send about a section (a capability, feature, task, doc or term). Approved ones are listed first in the briefing: act on them, then mark each done with resolve_flag. Only admins approve or remove flags (decide_flag); list_flags shows them.
|
|
179
179
|
- Home shows everyone the product as a map built from Quirl: each top-level capability with its icon, arrows from what it relies on, and its parts listed under it. Give features and capabilities an icon (request_feature's icon, set_feature_icon, set_capability_icon), and propose what each capability relies on and which capability it's part of (propose_capability_details) once it's approved.
|
|
180
|
+
- Resources (databases, hosted services, external APIs) come from quirl sync. If the project runs on something sync can't see from the code, add it with add_resource, without secret values.
|
|
180
181
|
- If the project has no capabilities yet, offer to read the codebase and draft them with propose_capability.
|
|
181
|
-
- If the project briefing isn't already in your context, call quirl_context first.`}),r={p_project:e.project},i=()=>({tool:n.server.getClientVersion()?.name??`mcp`,model:process.env.QUIRL_AGENT_MODEL}),a=e=>async t=>{try{return Pb(await e(t))}catch(e){if(e instanceof Hr)return{...Pb(e.message),isError:!0};throw e}};n.registerTool(`quirl_context`,{title:`Project briefing`,description:`The project briefing: always-loaded docs in full, glossary, capabilities, your open tasks and the list of other docs. Usually already loaded at session start.`,inputSchema:{}},a(async()=>Nb(await t.context(e.project)))),n.registerTool(`search_docs`,{title:`Search docs`,description:`Full-text search across the project's docs (README, ADRs, guides, runbooks). Returns matching sections with their content. Use for anything not in the briefing.`,inputSchema:{query:V().describe(`Words to search for, e.g. 'refund approval limits'`),limit:H().int().min(1).max(20).optional()}},a(({query:e,limit:n})=>t.call(`search_docs`,{...r,p_query:e,p_limit:n??6}))),n.registerTool(`read_doc`,{title:`Read a doc`,description:`Read one doc in full, by id, title or source path.`,inputSchema:{doc:V().describe(`Doc id, title or path, e.g. 'docs/adr/004-queues.md'`)}},a(({doc:e})=>t.call(`read_doc`,{...r,p_doc:e}))),n.registerTool(`lookup`,{title:`Look up a term, capability or contract`,description:`Find glossary terms, capabilities, features and API/table contracts matching a name. Use it to check what a word means here, or the request/response shape of an endpoint or table.`,inputSchema:{query:V().describe(`A term, capability, endpoint or table name, e.g. 'Visit' or 'POST /login'`)}},a(({query:e})=>t.call(`lookup`,{...r,p_query:e})));let o=(e,t,r,i)=>{n.registerTool(e,r,i),n.registerTool(t,{...r,description:`Old name for ${e}; use ${e}. ${r.description}`},i)};o(`list_tasks`,`list_cards`,{title:`List tasks`,description:`List tasks on the board. Defaults to your own tasks that aren't done.`,inputSchema:{onlyMine:Qp().optional(),includeDone:Qp().optional()}},a(({onlyMine:e,includeDone:n})=>t.call(`list_cards`,{...r,p_only_mine:e??!0,p_include_done:n??!1})));let s=`Markdown: short paragraphs, and lists for steps or parts, not one long block.`,c=`Kind of work: e.g. Frontend, Backend, Database, Design, DevOps, Testing, Docs, Research. Only tags from the task set are accepted (see tagSets in quirl_context); propose a new value with propose_term (kind tag, tagSet task_work).`,l=V().describe(`Task number, e.g. 'K-104' or '104'`);return o(`get_task`,`get_card`,{title:`Get a task`,description:`A task with its feature, docs, dependencies and evidence.`,inputSchema:{task:l.optional(),card:l.optional()}},a(({task:e,card:n})=>t.call(`get_card`,{...r,p_card:e??n}))),o(`create_task`,`create_card`,{title:`Create a task`,description:`Add a task to the board (status: todo). Use it for work you discover that should be tracked. Put it under the feature it serves.`,inputSchema:{title:V(),description:V().optional().describe(`What to do and why. ${s}`),type:_m([`feature_work`,`bug`,`chore`,`research`]).optional(),feature:V().optional().describe(`Feature name or id (e.g. F-4) this task belongs to`),tags:U(V()).optional().describe(c)}},a(async({title:e,description:n,type:a,feature:o,tags:s})=>{let c=await t.call(`create_card`,{...r,p_title:e,p_description:n??``,p_type:a??`feature_work`,p_feature:o??null,p_agent:i()});return s?.length&&await t.call(`update_card`,{...r,p_card:c,p_patch:{tags:s},p_agent:i()}),c})),o(`update_task`,`update_card`,{title:`Update a task`,description:`Move a task, mark it blocked (with a reason) or unblocked, put it under a feature, set its tags, rewrite its title or description, and attach evidence: a branch, commit or pull request. Repos are referenced by name.`,inputSchema:{task:l.optional(),card:l.optional(),status:_m([`backlog`,`todo`,`in_progress`,`review`,`done`]).optional(),feature:V().optional().describe(`Feature name or id (e.g. F-4) to put the task under; an empty string takes it off its feature`),title:V().optional(),description:V().optional().describe(`Replaces the description. ${s}`),tags:U(V()).optional().describe(`${c} Replaces the current tags.`),blocked:Qp().optional(),blockedReason:V().optional(),addBranch:W({repo:V(),name:V()}).optional(),addCommit:W({repo:V(),sha:V(),message:V().optional()}).optional(),addPullRequest:W({repo:V(),number:H().int(),url:V(),state:_m([`open`,`merged`,`closed`]).optional()}).optional()}},a(({task:e,card:n,...a})=>t.call(`update_card`,{...r,p_card:e??n,p_patch:a,p_agent:i()}))),n.registerTool(`propose_term`,{title:`Propose a glossary term`,description:`Suggest a new glossary term. It shows up for approval; it isn't used until a person approves it.`,inputSchema:{term:V(),plain:V().describe(`What it means, for someone non-technical`),technical:V().describe(`What it means in the code`),kind:_m([`concept`,`tag`,`name`]).optional(),tagSet:V().optional().describe(`Required for kind 'tag': the set the value belongs to, e.g. feature_change, task_work, capability_audience, capability_kind (see tagSets in quirl_context)`),reason:V().optional()}},a(({term:e,plain:n,technical:a,kind:o,tagSet:s,reason:c})=>t.call(`propose_term`,{...r,p_term:e,p_plain:n,p_technical:a,p_kind:o??`concept`,p_tag_set:s??null,p_reason:c??null,p_agent:i()}))),n.registerTool(`propose_term_retire`,{title:`Retire a glossary term`,description:`Propose retiring a glossary term or tag that's no longer used or was a mistake. With replaceWith, the term stays as one not to say (agents are told the replacement); without it, it's removed. Either way it comes off every capability, task and feature that used it. A person approves it. Built-in tag values can't be retired.`,inputSchema:{term:V().describe(`The term or tag to retire`),replaceWith:V().optional().describe(`An approved term to say instead, if there is one`),reason:V().optional()}},a(({term:e,replaceWith:n,reason:a})=>t.call(`propose_term_retire`,{...r,p_term:e,p_replace_with:n??null,p_reason:a??null,p_agent:i()}))),n.registerTool(`list_flags`,{title:`List flags`,description:`Flags are messages people send about a section of the project: a capability, feature, task, doc or glossary term. Lists open (waiting for an admin) and approved (to act on) flags, or only those with the given status.`,inputSchema:{status:_m([`open`,`approved`,`removed`,`done`]).optional()}},a(({status:e})=>t.call(`list_flags`,{...r,p_status:e??null}))),n.registerTool(`decide_flag`,{title:`Approve or remove a flag`,description:`Admins only. Approve a flag so agents act on it at the start of their sessions, or remove it. An approved flag can still be removed. Only do this when the person you work for asks you to.`,inputSchema:{flag:V().describe(`The flag's id, from the briefing or list_flags`),decision:_m([`approve`,`remove`])}},a(({flag:e,decision:n})=>t.call(`decide_flag`,{...r,p_flag:e,p_approve:n===`approve`,p_agent:i()}))),n.registerTool(`resolve_flag`,{title:`Mark a flag done`,description:`Mark an approved flag done once you've handled it, so it leaves the briefing. Say briefly what you did.`,inputSchema:{flag:V().describe(`The flag's id, from the briefing or list_flags`),note:V().optional().describe(`What was done, e.g. 'Updated C-12 to mention SMS'`)}},a(({flag:e,note:n})=>t.call(`resolve_flag`,{...r,p_flag:e,p_note:n??null,p_agent:i()}))),n.registerTool(`set_capability_icon`,{title:`Set a capability's icon`,description:`Give a capability an icon that fits what it does; it's shown on the capability's card. Use the same icon a related feature has when one fits both.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),icon:_m(jb)}},a(({capability:e,icon:n})=>t.call(`set_capability_icon`,{...r,p_capability:e,p_icon:n,p_agent:i()}))),n.registerTool(`list_features`,{title:`List features`,description:`List the project's features with their status, the capability each changes (or createsCapability when it has none), and task counts. Shipped ones are left out unless includeShipped. Check here before requesting a feature.`,inputSchema:{includeShipped:Qp().optional()}},a(({includeShipped:e})=>t.call(`list_features`,{...r,p_include_shipped:e??!1}))),n.registerTool(`get_feature`,{title:`Get a feature`,description:`A feature with its description, status, the capability it changes (and what that capability does) and its tasks.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`)}},a(({feature:e})=>t.call(`get_feature`,{...r,p_feature:e}))),n.registerTool(`request_feature`,{title:`Request a feature`,description:`Request a feature: a change to the product that stakeholders follow on the Features page, usually made of several tasks. Check list_features first so you don't request one twice. It shows as requested straight away and a person accepts or declines it. Put tasks under it with create_task or update_task.`,inputSchema:{name:V().describe(`Short name, e.g. 'Repeat appointments'`),description:V().describe(`What changes for the user, in plain words. Markdown: short paragraphs, and lists for parts`),capability:V().optional().describe(`Capability name or id (e.g. C-12) it changes. Leave it out when the feature creates a new capability`),tags:U(V()).optional().describe(`Kind of change: e.g. New, Improvement, Visual, Fix, Performance, Security, Removal, Internal (the feature_change set in quirl_context)`),reason:V().optional().describe(`Why it's worth doing`),icon:_m(jb).optional().describe(`An icon that fits the feature, shown on its card`)}},a(async({name:e,description:n,capability:a,tags:o,reason:s,icon:c})=>{let l=await t.call(`request_feature`,{...r,p_name:e,p_description:n,p_capability:a??null,p_tags:o??null,p_reason:s??null,p_agent:i()});return c&&l===`requested`&&await t.call(`set_feature_icon`,{...r,p_feature:e,p_icon:c,p_agent:i()}),l})),n.registerTool(`set_feature_icon`,{title:`Set a feature's icon`,description:`Give a feature an icon that fits what it does; it's shown on the feature's card. list_features shows which features have none.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`),icon:_m(jb)}},a(({feature:e,icon:n})=>t.call(`set_feature_icon`,{...r,p_feature:e,p_icon:n,p_agent:i()}))),n.registerTool(`tag_feature`,{title:`Tag a feature`,description:`Set a feature's kind-of-change tags (replaces the current ones). Only values from the feature_change tag set are accepted.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`),tags:U(V()).describe(`Kind of change: e.g. New, Improvement, Visual, Fix, Performance, Security, Removal, Internal`)}},a(({feature:e,tags:n})=>t.call(`tag_feature`,{...r,p_feature:e,p_tags:n,p_agent:i()}))),n.registerTool(`propose_capability`,{title:`Propose a capability`,description:"Draft a capability: one thing the product does today, described for a non-technical reader. Use it when the project has none yet (for example right after `quirl init`), when you find one that's missing, or when a feature that creates a new capability ships (pass it in features). Never for something not built yet: request a feature instead. A person approves it before it shows up.",inputSchema:{name:V().describe(`Short name, e.g. 'Online booking'`),whatItDoes:V().describe(`One or two plain sentences, no jargon`),technical:V().optional().describe(`Where it lives in the code and how it works. Markdown: short paragraphs, and lists for parts, not one long block`),features:U(V()).optional().describe(`Feature names or ids (e.g. F-4) that create or change this capability; they're linked to it once it's approved`),reason:V().optional()}},a(({name:e,whatItDoes:n,technical:a,features:o,reason:s})=>t.call(`propose_capability`,{...r,p_name:e,p_what_it_does:n,p_technical:a??``,p_features:o??null,p_reason:s??null,p_agent:i()}))),n.registerTool(`propose_capability_archive`,{title:`Propose archiving a capability`,description:`Suggest retiring a capability that no longer describes what the product does, or that was drafted for something not built yet. Unshipped features linked to it will create a new capability when they ship. A person approves it.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),reason:V().describe(`Why it should go`)}},a(({capability:e,reason:n})=>t.call(`propose_capability_archive`,{...r,p_capability:e,p_reason:n,p_agent:i()}))),n.registerTool(`propose_capability_update`,{title:`Propose a capability correction`,description:`Suggest a corrected description for a capability when the code no longer matches it. A person approves it.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),field:_m([`what_it_does`,`technical_description`]),after:V().describe(`The corrected text. Markdown: short paragraphs, and lists for parts, not one long block`),reason:V().optional()}},a(({capability:e,field:n,after:a,reason:o})=>t.call(`propose_capability_update`,{...r,p_capability:e,p_field:n,p_after:a,p_reason:o??null,p_agent:i()}))),n.registerTool(`propose_capability_details`,{title:`Propose how a capability works and its connections`,description:`Suggest a capability's 'How it works' steps, its tags (glossary terms of kind 'tag'), the capability it's part of, and its connections: capabilities it relies on, repos, resources it runs on, glossary terms and docs. Each part you pass replaces that part when a person approves it; parts you leave out are kept. Names are matched to existing, approved items. What it relies on draws the arrows on the Home map, so link the steps a user goes through (e.g. invoicing relies on booking).`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),howItWorks:U(V()).optional().describe(`3 to 5 plain-language steps, as the user experiences it`),reliesOn:U(W({capability:V().describe(`Capability name or id (e.g. C-12)`),label:V().describe(`How it relies on it, read before the name, e.g. 'extends'`)})).optional(),parent:V().optional().describe(`The capability this one is part of (name or id, e.g. C-2), or 'none' to make it top-level. Parts are listed under their parent instead of on their own`),repos:U(V()).optional().describe(`Repo names`),resources:U(V()).optional().describe(`Resource names it runs on`),terms:U(V()).optional().describe(`Glossary terms`),docs:U(V()).optional().describe(`Doc titles, or <repo>/<path> (e.g. quirl/AGENTS.md) when titles repeat`),tags:U(V()).optional().describe(`Who it's for (Customer, Admin, Developer, Agent) and its kind (Interface, Integration, Data, Automation, Infrastructure, Access and security, AI): the capability tag sets in quirl_context`),reason:V().optional()}},a(({capability:e,howItWorks:n,reliesOn:a,parent:o,repos:s,resources:c,terms:l,docs:u,tags:d,reason:f})=>t.call(`propose_capability_details`,{...r,p_capability:e,p_how_it_works:n??null,p_relies_on:a??null,p_parent:o??null,p_repos:s??null,p_resources:c??null,p_terms:l??null,p_docs:u??null,p_tags:d??null,p_reason:f??null,p_agent:i()}))),n}async function Ib(e){await Fb(e).connect(new Ab)}const Lb=`0.1.0`,Rb=process.env.QUIRL_SERVER===`local`?{apiUrl:`http://127.0.0.1:54321`,publishableKey:`sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH`,appUrl:`http://localhost:5173`}:{apiUrl:`https://dugevhzlzrdtasuibdzr.supabase.co`,publishableKey:`sb_publishable_45P7GyyZoJsN0AO3wfmqNA_CXbx1iCW`,appUrl:`https://app.quirl.io`};function zb(){return{apiUrl:process.env.QUIRL_API_URL??Rb.apiUrl,publishableKey:process.env.QUIRL_PUBLISHABLE_KEY??Rb.publishableKey,appUrl:process.env.QUIRL_APP_URL??Rb.appUrl}}const Bb=()=>x(process.env.XDG_CONFIG_HOME??x(h(),`.config`),`quirl`),Vb=()=>x(Bb(),`credentials.json`);async function Hb(){try{return JSON.parse(await u(Vb(),`utf8`))}catch{return{}}}async function Ub(){return process.env.QUIRL_KEY?{apiUrl:zb().apiUrl,key:process.env.QUIRL_KEY,email:``}:(await Hb())[zb().apiUrl]??null}async function Wb(e){let t=await Hb();t[e.apiUrl]=e,await l(Bb(),{recursive:!0,mode:448}),await m(Vb(),`${JSON.stringify(t,null,` `)}\n`,{mode:384}),await s(Vb(),384)}async function Gb(){let e=await Hb();delete e[zb().apiUrl],Object.keys(e).length?await m(Vb(),`${JSON.stringify(e,null,` `)}\n`,{mode:384}):await f(Vb(),{force:!0})}async function Kb(){let e=zb();return{apiUrl:e.apiUrl,publishableKey:e.publishableKey,key:(await Ub())?.key??``}}function qb(e=process.cwd()){try{return a(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim()}catch{return e}}const Jb=e=>x(e,`.quirl`,`project.json`);async function Yb(e=process.cwd()){let t=e;for(;;)try{return{root:t,link:JSON.parse(await u(Jb(t),`utf8`))}}catch{let e=y(t);if(e===t)return null;t=e}}async function Xb(e,t){await l(x(e,`.quirl`),{recursive:!0}),await m(Jb(e),`${JSON.stringify(t,null,` `)}\n`)}async function Zb({hook:e=!1}={}){let t=await Yb();if(!t){if(e)return;throw Error("This folder isn't linked to a Quirl project. Run `quirl init`.")}try{let n=await new Ur(await Kb()).context(t.link.projectId);process.stdout.write(`${Nb(n,e?9500:void 0)}\n`)}catch(n){if(!e)throw n;process.stdout.write(`Quirl project "${t.link.name}": couldn't load the briefing (${n.message}). The quirl MCP tools may still work.\n`)}}const Qb=/* @__PURE__ */ new Set([`.git`,`node_modules`,`dist`,`build`,`.next`,`vendor`,`.venv`,`venv`,`__pycache__`,`coverage`,`.turbo`,`.svelte-kit`,`.nuxt`,`.output`,`.cache`,`.vercel`,`.pnpm-store`,`fixtures`,`test-fixtures`,`__fixtures__`,`testdata`]),$b=2e5;async function ex(e){let t=[],n=await tx(e,t),r=new Map(n.map(e=>[e.path,e]));return{root:e,files:n,warnings:t,file:e=>r.get(e),async readText(e,n=1048576){if(e.size>n)return t.push(`${e.path}: skipped, ${cx(e.size)} is over the ${cx(n)} limit`),null;try{return await u(e.absolutePath,`utf8`)}catch(n){return t.push(`${e.path}: could not be read (${ox(n)})`),null}}}}async function tx(e,t){let n=[],r=[``];for(;r.length>0;){let i=r.pop(),a;try{a=await d(_.join(e,i),{withFileTypes:!0})}catch(e){t.push(`${i||`.`}: folder could not be read (${ox(e)})`);continue}for(let o of a){let a=i?`${i}/${o.name}`:o.name;if(o.isSymbolicLink())continue;if(o.isDirectory()){!Qb.has(o.name)&&!T(_.join(e,a,`.git`))&&r.push(a);continue}if(!o.isFile())continue;if(n.length>=$b)return t.push(`Stopped after ${$b} files; the rest of the tree was not scanned`),nx(n);let s=_.join(e,a);try{let e=await c(s);n.push({path:a,absolutePath:s,size:e.size})}catch(e){t.push(`${a}: could not be read (${ox(e)})`)}}}return nx(n)}function nx(e){return e.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function rx(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function ix(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function ax(e,t){return e?`${e}/${t}`:t}function ox(e){return e instanceof Error?e.message:String(e)}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sx(e){return typeof e==`string`?e:void 0}function cx(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}async function lx(e,t=3){let n=[],r=async(e,i)=>{if(T(_.join(e,`.git`))&&n.push(e),i>=t)return;let a;try{a=await d(e,{withFileTypes:!0})}catch{return}for(let t of a)!t.isDirectory()||t.name.startsWith(`.`)||Qb.has(t.name)||await r(_.join(e,t.name),i+1)};return await r(_.resolve(e),0),n.sort((e,t)=>e.localeCompare(t))}const ux=process.stdout.isTTY&&!process.env.NO_COLOR,dx=e=>t=>ux?`\x1b[${e}m${t}\x1b[0m`:t,fx=dx(1),px=dx(2),mx=dx(32),hx=dx(31),gx=dx(36),_x=e=>console.log(`${mx(`✓`)} ${e}`),vx=e=>console.log(` ${e}`),yx=(e,t)=>console.log(`\n${e} ${t}`),bx=e=>console.log(` ${e}`);function xx(e){if(!ux)return bx(px(e)),{stop:()=>{}};let t=0,n=setInterval(()=>{process.stdout.write(`\r ${gx(`⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏`[t++%10]??``)} ${px(e)}`)},80);return{stop:()=>{clearInterval(n),process.stdout.write(`\r\x1B[2K`)}}}var Sx=class extends Error{};async function Cx(e,t=``){if(!process.stdin.isTTY)return t;let n=E({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()||t}finally{n.close()}}async function wx(e,t){let n=await Cx(`${e} ${px(t?`[Y/n]`:`[y/N]`)} `,t?`y`:`n`);return/^y/i.test(n)}function Tx(e){if(process.env.QUIRL_NO_BROWSER)return;let t=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,n=process.platform===`win32`?[`/c`,`start`,``,e]:[e];try{o(t,n,{stdio:`ignore`,detached:!0}).on(`error`,()=>{}).unref()}catch{}}const Ex=`<!-- quirl:start -->`,Dx=`<!-- quirl:end -->`,Ox=`# quirl: keep the project in sync`;function kx(){try{let e=a(process.platform===`win32`?`where`:`which`,[`quirl`],{stdio:[`ignore`,`pipe`,`ignore`]}).toString();if(!/[\\/]_npx[\\/]/.test(e))return{command:`quirl`,args:[],shell:`quirl`,portable:!0}}catch{}return{command:`npx`,args:[`-y`,`quirl-cli`],shell:`npx -y quirl-cli`,portable:!0}}const Ax=[`QUIRL_SERVER`,`QUIRL_API_URL`,`QUIRL_PUBLISHABLE_KEY`,`QUIRL_APP_URL`];function jx(){return Object.fromEntries(Ax.flatMap(e=>process.env[e]?[[e,process.env[e]]]:[]))}function Mx(){return`${Object.entries(jx()).map(([e,t])=>`${e}="${t}" `).join(``)}${kx().shell}`}async function Nx(e){try{return JSON.parse(await u(e,`utf8`))}catch(t){if(t.code===`ENOENT`)return{};throw Error(`${e} isn't valid JSON; fix it and run \`quirl init\` again.`)}}const Px=async(e,t)=>{await l(y(e),{recursive:!0}),await m(e,`${JSON.stringify(t,null,2)}\n`)};async function Fx(e){let t=x(e,`.mcp.json`),n=await Nx(t),r=kx();n.mcpServers={...n.mcpServers,quirl:{command:r.command,args:[...r.args,`mcp`],...Object.keys(jx()).length?{env:jx()}:{}}},await Px(t,n)}async function Ix(e){let t=x(e,`.claude`,`settings.json`),n=await Nx(t),r=n.hooks??{},i=`${Mx()} context --hook`;r.SessionStart=[...(r.SessionStart??[]).map(e=>({...e,hooks:e.hooks.filter(e=>!/\bcontext --hook$/.test(e.command))})).filter(e=>e.hooks.length),{hooks:[{type:`command`,command:i,timeout:15}]}],n.hooks=r,await Px(t,n)}async function Lx(e,t,n=[]){let r=x(e,`CLAUDE.md`),i=``;try{i=await u(r,`utf8`)}catch{}let a=`${Ex}
|
|
182
|
+
- If the project briefing isn't already in your context, call quirl_context first.`}),r={p_project:e.project},i=()=>({tool:n.server.getClientVersion()?.name??`mcp`,model:process.env.QUIRL_AGENT_MODEL}),a=e=>async t=>{try{return Pb(await e(t))}catch(e){if(e instanceof Hr)return{...Pb(e.message),isError:!0};throw e}};n.registerTool(`quirl_context`,{title:`Project briefing`,description:`The project briefing: always-loaded docs in full, glossary, capabilities, your open tasks and the list of other docs. Usually already loaded at session start.`,inputSchema:{}},a(async()=>Nb(await t.context(e.project)))),n.registerTool(`search_docs`,{title:`Search docs`,description:`Full-text search across the project's docs (README, ADRs, guides, runbooks). Returns matching sections with their content. Use for anything not in the briefing.`,inputSchema:{query:V().describe(`Words to search for, e.g. 'refund approval limits'`),limit:H().int().min(1).max(20).optional()}},a(({query:e,limit:n})=>t.call(`search_docs`,{...r,p_query:e,p_limit:n??6}))),n.registerTool(`read_doc`,{title:`Read a doc`,description:`Read one doc in full, by id, title or source path.`,inputSchema:{doc:V().describe(`Doc id, title or path, e.g. 'docs/adr/004-queues.md'`)}},a(({doc:e})=>t.call(`read_doc`,{...r,p_doc:e}))),n.registerTool(`lookup`,{title:`Look up a term, capability or contract`,description:`Find glossary terms, capabilities, features and API/table contracts matching a name. Use it to check what a word means here, or the request/response shape of an endpoint or table.`,inputSchema:{query:V().describe(`A term, capability, endpoint or table name, e.g. 'Visit' or 'POST /login'`)}},a(({query:e})=>t.call(`lookup`,{...r,p_query:e})));let o=(e,t,r,i)=>{n.registerTool(e,r,i),n.registerTool(t,{...r,description:`Old name for ${e}; use ${e}. ${r.description}`},i)};o(`list_tasks`,`list_cards`,{title:`List tasks`,description:`List tasks on the board. Defaults to your own tasks that aren't done.`,inputSchema:{onlyMine:Qp().optional(),includeDone:Qp().optional()}},a(({onlyMine:e,includeDone:n})=>t.call(`list_cards`,{...r,p_only_mine:e??!0,p_include_done:n??!1})));let s=`Markdown: short paragraphs, and lists for steps or parts, not one long block.`,c=`Kind of work: e.g. Frontend, Backend, Database, Design, DevOps, Testing, Docs, Research. Only tags from the task set are accepted (see tagSets in quirl_context); propose a new value with propose_term (kind tag, tagSet task_work).`,l=V().describe(`Task number, e.g. 'K-104' or '104'`);return o(`get_task`,`get_card`,{title:`Get a task`,description:`A task with its feature, docs, dependencies and evidence.`,inputSchema:{task:l.optional(),card:l.optional()}},a(({task:e,card:n})=>t.call(`get_card`,{...r,p_card:e??n}))),o(`create_task`,`create_card`,{title:`Create a task`,description:`Add a task to the board (status: todo). Use it for work you discover that should be tracked. Put it under the feature it serves.`,inputSchema:{title:V(),description:V().optional().describe(`What to do and why. ${s}`),type:_m([`feature_work`,`bug`,`chore`,`research`]).optional(),feature:V().optional().describe(`Feature name or id (e.g. F-4) this task belongs to`),tags:U(V()).optional().describe(c)}},a(async({title:e,description:n,type:a,feature:o,tags:s})=>{let c=await t.call(`create_card`,{...r,p_title:e,p_description:n??``,p_type:a??`feature_work`,p_feature:o??null,p_agent:i()});return s?.length&&await t.call(`update_card`,{...r,p_card:c,p_patch:{tags:s},p_agent:i()}),c})),o(`update_task`,`update_card`,{title:`Update a task`,description:`Move a task, mark it blocked (with a reason) or unblocked, put it under a feature, set its tags, rewrite its title or description, and attach evidence: a branch, commit or pull request. Repos are referenced by name.`,inputSchema:{task:l.optional(),card:l.optional(),status:_m([`backlog`,`todo`,`in_progress`,`review`,`done`]).optional(),feature:V().optional().describe(`Feature name or id (e.g. F-4) to put the task under; an empty string takes it off its feature`),title:V().optional(),description:V().optional().describe(`Replaces the description. ${s}`),tags:U(V()).optional().describe(`${c} Replaces the current tags.`),blocked:Qp().optional(),blockedReason:V().optional(),addBranch:W({repo:V(),name:V()}).optional(),addCommit:W({repo:V(),sha:V(),message:V().optional()}).optional(),addPullRequest:W({repo:V(),number:H().int(),url:V(),state:_m([`open`,`merged`,`closed`]).optional()}).optional()}},a(({task:e,card:n,...a})=>t.call(`update_card`,{...r,p_card:e??n,p_patch:a,p_agent:i()}))),n.registerTool(`propose_term`,{title:`Propose a glossary term`,description:`Suggest a new glossary term. It shows up for approval; it isn't used until a person approves it.`,inputSchema:{term:V(),plain:V().describe(`What it means, for someone non-technical`),technical:V().describe(`What it means in the code`),kind:_m([`concept`,`tag`,`name`]).optional(),tagSet:V().optional().describe(`Required for kind 'tag': the set the value belongs to, e.g. feature_change, task_work, capability_audience, capability_kind (see tagSets in quirl_context)`),reason:V().optional()}},a(({term:e,plain:n,technical:a,kind:o,tagSet:s,reason:c})=>t.call(`propose_term`,{...r,p_term:e,p_plain:n,p_technical:a,p_kind:o??`concept`,p_tag_set:s??null,p_reason:c??null,p_agent:i()}))),n.registerTool(`propose_term_retire`,{title:`Retire a glossary term`,description:`Propose retiring a glossary term or tag that's no longer used or was a mistake. With replaceWith, the term stays as one not to say (agents are told the replacement); without it, it's removed. Either way it comes off every capability, task and feature that used it. A person approves it. Built-in tag values can't be retired.`,inputSchema:{term:V().describe(`The term or tag to retire`),replaceWith:V().optional().describe(`An approved term to say instead, if there is one`),reason:V().optional()}},a(({term:e,replaceWith:n,reason:a})=>t.call(`propose_term_retire`,{...r,p_term:e,p_replace_with:n??null,p_reason:a??null,p_agent:i()}))),n.registerTool(`list_flags`,{title:`List flags`,description:`Flags are messages people send about a section of the project: a capability, feature, task, doc or glossary term. Lists open (waiting for an admin) and approved (to act on) flags, or only those with the given status.`,inputSchema:{status:_m([`open`,`approved`,`removed`,`done`]).optional()}},a(({status:e})=>t.call(`list_flags`,{...r,p_status:e??null}))),n.registerTool(`decide_flag`,{title:`Approve or remove a flag`,description:`Admins only. Approve a flag so agents act on it at the start of their sessions, or remove it. An approved flag can still be removed. Only do this when the person you work for asks you to.`,inputSchema:{flag:V().describe(`The flag's id, from the briefing or list_flags`),decision:_m([`approve`,`remove`])}},a(({flag:e,decision:n})=>t.call(`decide_flag`,{...r,p_flag:e,p_approve:n===`approve`,p_agent:i()}))),n.registerTool(`resolve_flag`,{title:`Mark a flag done`,description:`Mark an approved flag done once you've handled it, so it leaves the briefing. Say briefly what you did.`,inputSchema:{flag:V().describe(`The flag's id, from the briefing or list_flags`),note:V().optional().describe(`What was done, e.g. 'Updated C-12 to mention SMS'`)}},a(({flag:e,note:n})=>t.call(`resolve_flag`,{...r,p_flag:e,p_note:n??null,p_agent:i()}))),n.registerTool(`set_capability_icon`,{title:`Set a capability's icon`,description:`Give a capability an icon that fits what it does; it's shown on the capability's card. Use the same icon a related feature has when one fits both.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),icon:_m(jb)}},a(({capability:e,icon:n})=>t.call(`set_capability_icon`,{...r,p_capability:e,p_icon:n,p_agent:i()}))),n.registerTool(`add_resource`,{title:`Add or fill in a resource`,description:"Record a service the project runs on that `quirl sync` can't see from the code: a hosted database another team runs, a SaaS named only in docs or the console, a staging copy. Sync already finds most things from env templates, docker-compose and client packages, so check Stack first (lookup) and don't add what it found. A resource with the same provider and environment is filled in rather than duplicated: the fields you give are set, and repos and capabilities are added to its links. Never pass URLs with credentials, keys or other secret values.",inputSchema:{name:V().describe(`What the team calls it, e.g. "Postgres", "Stripe"`),type:_m([`database`,`storage`,`service`,`queue`,`auth`,`external_api`]),provider:V().optional().describe(`Who runs it, e.g. "Google Cloud SQL", "Stripe". Resources are matched on this. Defaults to the name.`),description:V().optional().describe(`One plain sentence on what the project uses it for`),technical:V().optional().describe(`Technical notes for developers: setup, access, limits`),environment:V().optional().describe(`Defaults to "production"; e.g. "staging"`),repos:U(V()).optional().describe(`Repos that use it, by name`),capabilities:U(V()).optional().describe(`Capabilities that run on it, by name or id (e.g. C-12)`)}},a(e=>t.call(`add_resource`,{...r,p_name:e.name,p_type:e.type,p_provider:e.provider??null,p_description:e.description??null,p_technical:e.technical??null,p_environment:e.environment??null,p_repos:e.repos??null,p_capabilities:e.capabilities??null,p_agent:i()}))),n.registerTool(`list_features`,{title:`List features`,description:`List the project's features with their status, the capability each changes (or createsCapability when it has none), and task counts. Shipped ones are left out unless includeShipped. Check here before requesting a feature.`,inputSchema:{includeShipped:Qp().optional()}},a(({includeShipped:e})=>t.call(`list_features`,{...r,p_include_shipped:e??!1}))),n.registerTool(`get_feature`,{title:`Get a feature`,description:`A feature with its description, status, the capability it changes (and what that capability does) and its tasks.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`)}},a(({feature:e})=>t.call(`get_feature`,{...r,p_feature:e}))),n.registerTool(`request_feature`,{title:`Request a feature`,description:`Request a feature: a change to the product that stakeholders follow on the Features page, usually made of several tasks. Check list_features first so you don't request one twice. It shows as requested straight away and a person accepts or declines it. Put tasks under it with create_task or update_task.`,inputSchema:{name:V().describe(`Short name, e.g. 'Repeat appointments'`),description:V().describe(`What changes for the user, in plain words. Markdown: short paragraphs, and lists for parts`),capability:V().optional().describe(`Capability name or id (e.g. C-12) it changes. Leave it out when the feature creates a new capability`),tags:U(V()).optional().describe(`Kind of change: e.g. New, Improvement, Visual, Fix, Performance, Security, Removal, Internal (the feature_change set in quirl_context)`),reason:V().optional().describe(`Why it's worth doing`),icon:_m(jb).optional().describe(`An icon that fits the feature, shown on its card`)}},a(async({name:e,description:n,capability:a,tags:o,reason:s,icon:c})=>{let l=await t.call(`request_feature`,{...r,p_name:e,p_description:n,p_capability:a??null,p_tags:o??null,p_reason:s??null,p_agent:i()});return c&&l===`requested`&&await t.call(`set_feature_icon`,{...r,p_feature:e,p_icon:c,p_agent:i()}),l})),n.registerTool(`set_feature_icon`,{title:`Set a feature's icon`,description:`Give a feature an icon that fits what it does; it's shown on the feature's card. list_features shows which features have none.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`),icon:_m(jb)}},a(({feature:e,icon:n})=>t.call(`set_feature_icon`,{...r,p_feature:e,p_icon:n,p_agent:i()}))),n.registerTool(`tag_feature`,{title:`Tag a feature`,description:`Set a feature's kind-of-change tags (replaces the current ones). Only values from the feature_change tag set are accepted.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`),tags:U(V()).describe(`Kind of change: e.g. New, Improvement, Visual, Fix, Performance, Security, Removal, Internal`)}},a(({feature:e,tags:n})=>t.call(`tag_feature`,{...r,p_feature:e,p_tags:n,p_agent:i()}))),n.registerTool(`propose_capability`,{title:`Propose a capability`,description:"Draft a capability: one thing the product does today, described for a non-technical reader. Use it when the project has none yet (for example right after `quirl init`), when you find one that's missing, or when a feature that creates a new capability ships (pass it in features). Never for something not built yet: request a feature instead. A person approves it before it shows up.",inputSchema:{name:V().describe(`Short name, e.g. 'Online booking'`),whatItDoes:V().describe(`One or two plain sentences, no jargon`),technical:V().optional().describe(`Where it lives in the code and how it works. Markdown: short paragraphs, and lists for parts, not one long block`),features:U(V()).optional().describe(`Feature names or ids (e.g. F-4) that create or change this capability; they're linked to it once it's approved`),reason:V().optional()}},a(({name:e,whatItDoes:n,technical:a,features:o,reason:s})=>t.call(`propose_capability`,{...r,p_name:e,p_what_it_does:n,p_technical:a??``,p_features:o??null,p_reason:s??null,p_agent:i()}))),n.registerTool(`propose_capability_archive`,{title:`Propose archiving a capability`,description:`Suggest retiring a capability that no longer describes what the product does, or that was drafted for something not built yet. Unshipped features linked to it will create a new capability when they ship. A person approves it.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),reason:V().describe(`Why it should go`)}},a(({capability:e,reason:n})=>t.call(`propose_capability_archive`,{...r,p_capability:e,p_reason:n,p_agent:i()}))),n.registerTool(`propose_capability_update`,{title:`Propose a capability correction`,description:`Suggest a corrected description for a capability when the code no longer matches it. A person approves it.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),field:_m([`what_it_does`,`technical_description`]),after:V().describe(`The corrected text. Markdown: short paragraphs, and lists for parts, not one long block`),reason:V().optional()}},a(({capability:e,field:n,after:a,reason:o})=>t.call(`propose_capability_update`,{...r,p_capability:e,p_field:n,p_after:a,p_reason:o??null,p_agent:i()}))),n.registerTool(`propose_capability_details`,{title:`Propose how a capability works and its connections`,description:`Suggest a capability's 'How it works' steps, its tags (glossary terms of kind 'tag'), the capability it's part of, and its connections: capabilities it relies on, repos, resources it runs on, glossary terms and docs. Each part you pass replaces that part when a person approves it; parts you leave out are kept. Names are matched to existing, approved items. What it relies on draws the arrows on the Home map, so link the steps a user goes through (e.g. invoicing relies on booking).`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),howItWorks:U(V()).optional().describe(`3 to 5 plain-language steps, as the user experiences it`),reliesOn:U(W({capability:V().describe(`Capability name or id (e.g. C-12)`),label:V().describe(`How it relies on it, read before the name, e.g. 'extends'`)})).optional(),parent:V().optional().describe(`The capability this one is part of (name or id, e.g. C-2), or 'none' to make it top-level. Parts are listed under their parent instead of on their own`),repos:U(V()).optional().describe(`Repo names`),resources:U(V()).optional().describe(`Resource names it runs on`),terms:U(V()).optional().describe(`Glossary terms`),docs:U(V()).optional().describe(`Doc titles, or <repo>/<path> (e.g. quirl/AGENTS.md) when titles repeat`),tags:U(V()).optional().describe(`Who it's for (Customer, Admin, Developer, Agent) and its kind (Interface, Integration, Data, Automation, Infrastructure, Access and security, AI): the capability tag sets in quirl_context`),reason:V().optional()}},a(({capability:e,howItWorks:n,reliesOn:a,parent:o,repos:s,resources:c,terms:l,docs:u,tags:d,reason:f})=>t.call(`propose_capability_details`,{...r,p_capability:e,p_how_it_works:n??null,p_relies_on:a??null,p_parent:o??null,p_repos:s??null,p_resources:c??null,p_terms:l??null,p_docs:u??null,p_tags:d??null,p_reason:f??null,p_agent:i()}))),n}async function Ib(e){await Fb(e).connect(new Ab)}const Lb=`0.1.2`,Rb=process.env.QUIRL_SERVER===`local`?{apiUrl:`http://127.0.0.1:54321`,publishableKey:`sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH`,appUrl:`http://localhost:5173`}:{apiUrl:`https://dugevhzlzrdtasuibdzr.supabase.co`,publishableKey:`sb_publishable_45P7GyyZoJsN0AO3wfmqNA_CXbx1iCW`,appUrl:`https://app.quirl.io`};function zb(){return{apiUrl:process.env.QUIRL_API_URL??Rb.apiUrl,publishableKey:process.env.QUIRL_PUBLISHABLE_KEY??Rb.publishableKey,appUrl:process.env.QUIRL_APP_URL??Rb.appUrl}}const Bb=()=>x(process.env.XDG_CONFIG_HOME??x(h(),`.config`),`quirl`),Vb=()=>x(Bb(),`credentials.json`);async function Hb(){try{return JSON.parse(await u(Vb(),`utf8`))}catch{return{}}}async function Ub(){return process.env.QUIRL_KEY?{apiUrl:zb().apiUrl,key:process.env.QUIRL_KEY,email:``}:(await Hb())[zb().apiUrl]??null}async function Wb(e){let t=await Hb();t[e.apiUrl]=e,await l(Bb(),{recursive:!0,mode:448}),await m(Vb(),`${JSON.stringify(t,null,` `)}\n`,{mode:384}),await s(Vb(),384)}async function Gb(){let e=await Hb();delete e[zb().apiUrl],Object.keys(e).length?await m(Vb(),`${JSON.stringify(e,null,` `)}\n`,{mode:384}):await f(Vb(),{force:!0})}async function Kb(){let e=zb();return{apiUrl:e.apiUrl,publishableKey:e.publishableKey,key:(await Ub())?.key??``}}function qb(e=process.cwd()){try{return a(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim()}catch{return e}}const Jb=e=>x(e,`.quirl`,`project.json`);async function Yb(e=process.cwd()){let t=e;for(;;)try{return{root:t,link:JSON.parse(await u(Jb(t),`utf8`))}}catch{let e=y(t);if(e===t)return null;t=e}}async function Xb(e,t){await l(x(e,`.quirl`),{recursive:!0}),await m(Jb(e),`${JSON.stringify(t,null,` `)}\n`)}const Zb=/* @__PURE__ */ new Set([`.git`,`node_modules`,`dist`,`build`,`.next`,`vendor`,`.venv`,`venv`,`__pycache__`,`coverage`,`.turbo`,`.svelte-kit`,`.nuxt`,`.output`,`.cache`,`.vercel`,`.pnpm-store`,`fixtures`,`test-fixtures`,`__fixtures__`,`testdata`]),Qb=2e5;async function $b(e){let t=[],n=await ex(e,t),r=new Map(n.map(e=>[e.path,e]));return{root:e,files:n,warnings:t,file:e=>r.get(e),async readText(e,n=1048576){if(e.size>n)return t.push(`${e.path}: skipped, ${sx(e.size)} is over the ${sx(n)} limit`),null;try{return await u(e.absolutePath,`utf8`)}catch(n){return t.push(`${e.path}: could not be read (${ax(n)})`),null}}}}async function ex(e,t){let n=[],r=[``];for(;r.length>0;){let i=r.pop(),a;try{a=await d(_.join(e,i),{withFileTypes:!0})}catch(e){t.push(`${i||`.`}: folder could not be read (${ax(e)})`);continue}for(let o of a){let a=i?`${i}/${o.name}`:o.name;if(o.isSymbolicLink())continue;if(o.isDirectory()){!Zb.has(o.name)&&!C(_.join(e,a,`.git`))&&r.push(a);continue}if(!o.isFile())continue;if(n.length>=Qb)return t.push(`Stopped after ${Qb} files; the rest of the tree was not scanned`),tx(n);let s=_.join(e,a);try{let e=await c(s);n.push({path:a,absolutePath:s,size:e.size})}catch(e){t.push(`${a}: could not be read (${ax(e)})`)}}}return tx(n)}function tx(e){return e.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function nx(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function rx(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function ix(e,t){return e?`${e}/${t}`:t}function ax(e){return(e instanceof Error?e.message:String(e)).split(`
|
|
183
|
+
`,1)[0]?.trim()??``}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ox(e){return typeof e==`string`?e:void 0}function sx(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}async function cx({hook:e=!1}={}){let t=await Yb();if(!t){if(e)return;throw Error("This folder isn't linked to a Quirl project. Run `quirl init`.")}try{let n=await new Ur(await Kb()).context(t.link.projectId);process.stdout.write(`${Nb(n,e?9500:void 0)}\n`)}catch(n){if(!e)throw n;process.stdout.write(`Quirl project "${t.link.name}": couldn't load the briefing (${ax(n)}). The quirl MCP tools may still work.\n`)}}async function lx(e,t=3){let n=[],r=async(e,i)=>{if(C(_.join(e,`.git`))&&n.push(e),i>=t)return;let a;try{a=await d(e,{withFileTypes:!0})}catch{return}for(let t of a)!t.isDirectory()||t.name.startsWith(`.`)||Zb.has(t.name)||await r(_.join(e,t.name),i+1)};return await r(_.resolve(e),0),n.sort((e,t)=>e.localeCompare(t))}const ux=process.stdout.isTTY&&!process.env.NO_COLOR,dx=e=>t=>ux?`\x1b[${e}m${t}\x1b[0m`:t,fx=dx(1),px=dx(2),mx=dx(32),hx=dx(31),gx=dx(36),_x=e=>console.log(`${mx(`✓`)} ${e}`),vx=e=>console.log(` ${e}`),yx=(e,t)=>console.log(`\n${e} ${t}`),bx=e=>console.log(` ${e}`);function xx(e){if(!ux)return bx(px(e)),{stop:()=>{}};let t=0,n=setInterval(()=>{process.stdout.write(`\r ${gx(`⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏`[t++%10]??``)} ${px(e)}`)},80);return{stop:()=>{clearInterval(n),process.stdout.write(`\r\x1B[2K`)}}}var Sx=class extends Error{};async function Cx(e,t=``){if(!process.stdin.isTTY)return t;let n=E({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()||t}finally{n.close()}}async function wx(e,t){let n=await Cx(`${e} ${px(t?`[Y/n]`:`[y/N]`)} `,t?`y`:`n`);return/^y/i.test(n)}function Tx(e){if(process.env.QUIRL_NO_BROWSER)return;let t=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,n=process.platform===`win32`?[`/c`,`start`,``,e]:[e];try{o(t,n,{stdio:`ignore`,detached:!0}).on(`error`,()=>{}).unref()}catch{}}const Ex=`<!-- quirl:start -->`,Dx=`<!-- quirl:end -->`,Ox=`# quirl: keep the project in sync`;function kx(){try{let e=a(process.platform===`win32`?`where`:`which`,[`quirl`],{stdio:[`ignore`,`pipe`,`ignore`]}).toString();if(!/[\\/]_npx[\\/]/.test(e))return{command:`quirl`,args:[],shell:`quirl`,portable:!0}}catch{}return{command:`npx`,args:[`-y`,`quirl-cli`],shell:`npx -y quirl-cli`,portable:!0}}const Ax=[`QUIRL_SERVER`,`QUIRL_API_URL`,`QUIRL_PUBLISHABLE_KEY`,`QUIRL_APP_URL`];function jx(){return Object.fromEntries(Ax.flatMap(e=>process.env[e]?[[e,process.env[e]]]:[]))}function Mx(){return`${Object.entries(jx()).map(([e,t])=>`${e}="${t}" `).join(``)}${kx().shell}`}async function Nx(e){try{return JSON.parse(await u(e,`utf8`))}catch(t){if(t.code===`ENOENT`)return{};throw Error(`${e} isn't valid JSON; fix it and run \`quirl init\` again.`)}}const Px=async(e,t)=>{await l(y(e),{recursive:!0}),await m(e,`${JSON.stringify(t,null,2)}\n`)};async function Fx(e){let t=x(e,`.mcp.json`),n=await Nx(t),r=kx();n.mcpServers={...n.mcpServers,quirl:{command:r.command,args:[...r.args,`mcp`],...Object.keys(jx()).length?{env:jx()}:{}}},await Px(t,n)}async function Ix(e){let t=x(e,`.claude`,`settings.json`),n=await Nx(t),r=n.hooks??{},i=`${Mx()} context --hook`;r.SessionStart=[...(r.SessionStart??[]).map(e=>({...e,hooks:e.hooks.filter(e=>!/\bcontext --hook$/.test(e.command))})).filter(e=>e.hooks.length),{hooks:[{type:`command`,command:i,timeout:15}]}],n.hooks=r,await Px(t,n)}async function Lx(e,t,n=[]){let r=x(e,`CLAUDE.md`),i=``;try{i=await u(r,`utf8`)}catch{}let a=`${Ex}
|
|
182
184
|
## Quirl
|
|
183
185
|
|
|
184
186
|
${n.length?`This folder holds the repos of the Quirl project **${t}** (${n.join(`, `)}). Quirl is`:`This repo is part of the Quirl project **${t}**,`} the team's source of truth for what the product does. The project briefing (always-loaded docs, glossary, capabilities, your tasks) is loaded at the start of each session. Use the \`quirl\` MCP tools:
|
|
@@ -195,8 +197,8 @@ ${Dx}`,o=RegExp(`${Ex}[\\s\\S]*?${Dx}`);i=o.test(i)?i.replace(o,a):`${i.trimEnd(
|
|
|
195
197
|
|
|
196
198
|
`:``}${a}\n`,await m(r,i)}async function Rx(e){let t;try{t=a(`git`,[`rev-parse`,`--git-path`,`hooks`],{cwd:e}).toString().trim()}catch{return null}b(t)||(t=x(e,t));let n=x(t,`pre-push`),r=``;try{r=await u(n,`utf8`)}catch{}let i=`${Ox}\n${Mx()} sync --quiet --source=git_hook || echo "quirl: sync skipped"\n`,o=r.indexOf(Ox);if(o>=0){let e=r.indexOf(`
|
|
197
199
|
`,r.indexOf(`
|
|
198
|
-
`,o)+1);r=`${r.slice(0,o)}${i}${e>=0?r.slice(e+1):``}`}else r=r?`${r.trimEnd()}\n\n${i}`:`#!/bin/sh\n${i}`;return await l(t,{recursive:!0}),await m(n,r),await s(n,493),n}async function zx({quiet:e=!1}={}){let t=zb(),n=await Ub();yx(`🔑`,fx(`Sign in to Quirl`)),n&&!e&&bx(px(`Already signed in as ${n.email}. Signing in again replaces this machine's key.`));let r=Wr(t.apiUrl,t.publishableKey),i=await r.start(`quirl CLI on ${g()}`),a=`${t.appUrl}/cli/authorize?code=${i.user_code}`;bx(`Approve this computer in your browser:`),bx(gx(a)),bx(`Check the code matches ${fx(Bx(i.user_code))}`),Tx(a);let o=xx(`Waiting for you to approve…`),s=Date.now()+6e5;for(;Date.now()<s;){await new Promise(e=>setTimeout(e,2e3));let e=await r.poll(i.request_id,i.poll_secret);if(e.status===`approved`&&e.key){let n=await new Ur({...t,key:e.key}).whoami();return o.stop(),await Wb({apiUrl:t.apiUrl,key:e.key,email:n.email}),bx(`${mx(`✓`)} Signed in as ${fx(n.email)}`),n}if(e.status!==`pending`)throw o.stop(),new Sx(`Sign-in ${e.status}. Run \`quirl login\` again.`)}throw o.stop(),new Sx("Sign-in timed out. Run `quirl login` again.")}const Bx=e=>`${e.slice(0,4)}-${e.slice(4)}`,Vx=/* @__PURE__ */ new Set([`docs`,`doc`,`adr`,`adrs`,`architecture`]),Hx=/* @__PURE__ */ new Set([`readme.md`,`contributing.md`,`architecture.md`]),Ux=/^(changelog|changes|history|license|licence|copying|notice|code_of_conduct|claude|agents)(\.|$)/i,Wx=/\.(md|mdx|markdown)$/i;async function Gx(e){let t=[];for(let n of e.files){if(!Kx(n.path))continue;let r=await e.readText(n);if(r===null)continue;let i=qx(r)??
|
|
199
|
-
`),n=/^---\n([\s\S]*?)\n---\n/.exec(t),r=n?.[1]?/^title:\s*["']?(.+?)["']?\s*$/m.exec(n[1]):null;if(r?.[1])return r[1];let i=t.replace(/^(```|~~~)[\s\S]*?^\1.*$/gm,``),a=/^#\s+(.+?)\s*#*\s*$/m.exec(i),o=/^(?!\s*$)([^\n#>].*)\n=+\s*$/m.exec(i),s=a&&o?a.index<o.index?a[1]:o[1]:a?.[1]??o?.[1];return s?Jx(s):null}function Jx(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,``).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/[`*_]/g,``).trim()}function Yx(e,t){let n=`${e} ${t}`.toLowerCase();return/(^|\/)adrs?\//.test(n)||/\bdecision|\badr[-_ ]?\d/.test(n)?`decision`:/guideline|convention|contributing|style ?guide|styleguide|code[-_ ]?style|coding[-_ ]standard/.test(n)?`guideline`:/guide|how[-_ ]?to|setup|set[-_ ]up|getting[-_ ]started|install|tutorial|runbook|playbook/.test(n)?`how_to`:/architecture|design|overview/.test(n)?`architecture`:`reference`}function Xx(e,t){if(t===`guideline`)return!0;let n=
|
|
200
|
+
`,o)+1);r=`${r.slice(0,o)}${i}${e>=0?r.slice(e+1):``}`}else r=r?`${r.trimEnd()}\n\n${i}`:`#!/bin/sh\n${i}`;return await l(t,{recursive:!0}),await m(n,r),await s(n,493),n}async function zx({quiet:e=!1}={}){let t=zb(),n=await Ub();yx(`🔑`,fx(`Sign in to Quirl`)),n&&!e&&bx(px(`Already signed in as ${n.email}. Signing in again replaces this machine's key.`));let r=Wr(t.apiUrl,t.publishableKey),i=await r.start(`quirl CLI on ${g()}`),a=`${t.appUrl}/cli/authorize?code=${i.user_code}`;bx(`Approve this computer in your browser:`),bx(gx(a)),bx(`Check the code matches ${fx(Bx(i.user_code))}`),Tx(a);let o=xx(`Waiting for you to approve…`),s=Date.now()+6e5;for(;Date.now()<s;){await new Promise(e=>setTimeout(e,2e3));let e=await r.poll(i.request_id,i.poll_secret);if(e.status===`approved`&&e.key){let n=await new Ur({...t,key:e.key}).whoami();return o.stop(),await Wb({apiUrl:t.apiUrl,key:e.key,email:n.email}),bx(`${mx(`✓`)} Signed in as ${fx(n.email)}`),n}if(e.status!==`pending`)throw o.stop(),new Sx(`Sign-in ${e.status}. Run \`quirl login\` again.`)}throw o.stop(),new Sx("Sign-in timed out. Run `quirl login` again.")}const Bx=e=>`${e.slice(0,4)}-${e.slice(4)}`,Vx=/* @__PURE__ */ new Set([`docs`,`doc`,`adr`,`adrs`,`architecture`]),Hx=/* @__PURE__ */ new Set([`readme.md`,`contributing.md`,`architecture.md`]),Ux=/^(changelog|changes|history|license|licence|copying|notice|code_of_conduct|claude|agents)(\.|$)/i,Wx=/\.(md|mdx|markdown)$/i;async function Gx(e){let t=[];for(let n of e.files){if(!Kx(n.path))continue;let r=await e.readText(n);if(r===null)continue;let i=qx(r)??nx(n.path).replace(Wx,``),a=Yx(n.path,i);t.push({path:n.path,title:i,type:a,body:r,alwaysLoadCandidate:Xx(n.path,a),contentHash:w(`sha256`).update(r).digest(`hex`)})}return t}function Kx(e){let t=nx(e);if(!Wx.test(t)||Ux.test(t))return!1;let n=e.toLowerCase().split(`/`);return n.length===1?Hx.has(n[0]??``):e.toLowerCase()===`.github/contributing.md`||n.slice(0,-1).some(e=>Vx.has(e))}function qx(e){let t=e.replace(/\r\n/g,`
|
|
201
|
+
`),n=/^---\n([\s\S]*?)\n---\n/.exec(t),r=n?.[1]?/^title:\s*["']?(.+?)["']?\s*$/m.exec(n[1]):null;if(r?.[1])return r[1];let i=t.replace(/^(```|~~~)[\s\S]*?^\1.*$/gm,``),a=/^#\s+(.+?)\s*#*\s*$/m.exec(i),o=/^(?!\s*$)([^\n#>].*)\n=+\s*$/m.exec(i),s=a&&o?a.index<o.index?a[1]:o[1]:a?.[1]??o?.[1];return s?Jx(s):null}function Jx(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,``).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/[`*_]/g,``).trim()}function Yx(e,t){let n=`${e} ${t}`.toLowerCase();return/(^|\/)adrs?\//.test(n)||/\bdecision|\badr[-_ ]?\d/.test(n)?`decision`:/guideline|convention|contributing|style ?guide|styleguide|code[-_ ]?style|coding[-_ ]standard/.test(n)?`guideline`:/guide|how[-_ ]?to|setup|set[-_ ]up|getting[-_ ]started|install|tutorial|runbook|playbook/.test(n)?`how_to`:/architecture|design|overview/.test(n)?`architecture`:`reference`}function Xx(e,t){if(t===`guideline`)return!0;let n=nx(e).toLowerCase();return/architecture|conventions?|guidelines?|contributing|style-?guide/.test(n)||t===`architecture`&&/overview/.test(n)}const Zx=/* @__PURE__ */ new Set([`claude.md`,`agents.md`,`.cursorrules`]);async function Qx(e){let t=[];for(let n of e.files){if(!(Zx.has(nx(n.path).toLowerCase())||n.path===`.github/copilot-instructions.md`))continue;let r=(await e.readText(n))?.replace(/<!-- quirl:start -->[\s\S]*?<!-- quirl:end -->\n?/,``).trim();r&&t.push({path:n.path,body:r})}return t}const $x=/\.(md|mdx|markdown|txt)$/i,eS=/\.(pdf|docx?|odt|rtf|pages|pptx?|key|xlsx?|numbers)$/i;async function tS(e){let t=[],n=[];for(let r of e.files){if(r.path.split(`/`).some(e=>e.startsWith(`.`)))continue;let i=nx(r.path);if(eS.test(i)){n.push(r.path);continue}if(!$x.test(i)||/^(claude|agents)\.md$/i.test(i))continue;let a=await e.readText(r);if(!a?.trim())continue;let o=i.replace($x,``),s=(Wx.test(i)?qx(a):null)??o,c=Yx(r.path,s);t.push({path:r.path,title:s,type:c,body:a,alwaysLoadCandidate:!1,contentHash:w(`sha256`).update(a).digest(`hex`)})}return{docs:t,unsupported:n}}var nS=class{#e=/* @__PURE__ */ new Map;#t;#n;constructor(e,t){this.#t=e,this.#n=t}add(e,t,n){if(!e||!t)return;let r=this.#e.get(e);r&&(r.direct&&!n||r.direct===n&&rS(r.version,t)>=0)||this.#e.set(e,{ecosystem:this.#t,package:e,version:t,direct:n,sourceLockfile:this.#n})}has(e){return this.#e.has(e)}rows(){return[...this.#e.values()].sort((e,t)=>e.package.localeCompare(t.package))}};function rS(e,t){let n=e=>e.replace(/^v/,``).split(/[.+-]/),r=n(e),i=n(t);for(let e=0;e<Math.max(r.length,i.length);e++){let t=r[e]??``,n=i[e]??``,a=Number(t),o=Number(n),s=t!==``&&n!==``&&!Number.isNaN(a)&&!Number.isNaN(o)?a-o:t.localeCompare(n);if(s!==0)return s}return 0}function iS(e){let t=/* @__PURE__ */ new Set;if(!Q(e))return t;for(let n of[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`]){let r=e[n];if(Q(r))for(let e of Object.keys(r))t.add(e)}return t}function aS(e){return JSON.parse(e)}function oS(e,t,n){let r=aS(e);if(!Q(r))throw Error(`not a JSON object`);let i=/* @__PURE__ */ new Set;if(n!==null){let e=aS(n);if(Q(e))for(let t of[`require`,`require-dev`]){let n=e[t];if(Q(n))for(let e of Object.keys(n))i.add(e.toLowerCase())}}let a=new nS(`composer`,t);for(let e of[`packages`,`packages-dev`]){let t=r[e];if(Array.isArray(t))for(let e of t){if(!Q(e))continue;let{name:t,version:n}=e;typeof t==`string`&&typeof n==`string`&&a.add(t,n,i.has(t.toLowerCase()))}}return a.rows()}function sS(e,t,n){let r=new nS(`other`,n),i=/* @__PURE__ */ new Set;if(e!==null){let t=!1;for(let n of e.split(/\r?\n/)){let e=n.trim();if(t){if(e.startsWith(`)`)){t=!1;continue}a(e);continue}if(/^require\s*\($/.test(e)){t=!0;continue}let r=/^require\s+(.+)$/.exec(e);r?.[1]&&a(r[1])}}function a(e){let t=/^(\S+)\s+(\S+)(.*)$/.exec(e);if(!t?.[1]||!t[2]||t[1].startsWith(`//`))return;let n=/\/\/\s*indirect\b/.test(t[3]??``);r.add(t[1],t[2],!n),i.add(t[1])}if(t!==null)for(let e of t.split(/\r?\n/)){let[t,n]=e.trim().split(/\s+/);if(!t||!n)continue;let a=n.replace(/\/go\.mod$/,``);i.has(t)||r.add(t,a,!1)}return r.rows()}var $=/* @__PURE__ */ D((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),cS=/* @__PURE__ */ D((e=>{var t=$();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),lS=/* @__PURE__ */ D((e=>{var t=$(),n=cS();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||e&&!a.some(e=>e.startsWith(n))||r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
200
202
|
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),uS=/* @__PURE__ */ D((e=>{var t=$(),n=cS();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=/* @__PURE__ */ new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=/* @__PURE__ */ new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=/* @__PURE__ */ Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),dS=/* @__PURE__ */ D((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),fS=/* @__PURE__ */ D((e=>{var t=$();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),pS=/* @__PURE__ */ D((e=>{var t=dS(),n=$(),r=fS();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:/* @__PURE__ */ new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),mS=/* @__PURE__ */ D((e=>{var t=uS(),n=cS(),r=$(),i=pS(),a=fS(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);
|
|
201
203
|
/* istanbul ignore if */
|
|
202
204
|
if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(r>=0&&(i.count+=1,i.aliasCount===0&&(i.aliasCount=s(n,o,e)),i.count*i.aliasCount>r))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return o}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),hS=/* @__PURE__ */ D((e=>{var t=$(),n=pS(),r=fS();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),gS=/* @__PURE__ */ D((e=>{var t=mS(),n=$(),r=hS();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??(f.anchor=c(e)),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),_S=/* @__PURE__ */ D((e=>{var t=gS(),n=$(),r=pS();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=/* @__PURE__ */ new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:/* @__PURE__ */ new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),vS=/* @__PURE__ */ D((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
@@ -334,10 +336,10 @@ default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.l
|
|
|
334
336
|
/* istanbul ignore else should not happen */
|
|
335
337
|
n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));u(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
336
338
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
337
|
-
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),CC=/* @__PURE__ */ D((e=>{var t=hC(),n=QS(),r=$S(),i=CS(),a=$(),o=xC(),s=SC();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),wC=(/* @__PURE__ */ D((e=>{var t=hC(),n=QS(),r=XS(),i=$S(),a=mS(),o=$(),s=ES(),c=hS(),l=OS(),u=AS();yC();var d=bC(),f=xC(),p=SC(),m=CC(),h=cS();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})))();function TC(e,t){let n=(0,wC.parse)(e,{uniqueKeys:!1});if(!Q(n))throw Error(`not a YAML mapping`);let r=new nS(`npm`,t),i=Q(n.importers)?n.importers:{".":n};for(let e of Object.values(i))if(Q(e))for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let n=e[t];if(Q(n))for(let[e,t]of Object.entries(n)){let n=Q(t)?t.version:t;if(typeof n!=`string`||EC(n))continue;let i=OC(n);i?r.add(i.name,i.version,!0):r.add(e,DC(n),!0)}}for(let e of[`packages`,`snapshots`]){let t=n[e];if(Q(t))for(let e of Object.keys(t)){let t=OC(e);t&&!EC(t.version)&&r.add(t.name,t.version,!1)}}return r.rows()}function EC(e){return/^(link|file|workspace):/.test(e)}function DC(e){return e.replace(/\(.*$/,``).replace(/_(?=[^/]*@).*$/,``)}function OC(e){let t=e.replace(/^\//,``).replace(/\(.*$/,``),n=t.indexOf(`@`,1);if(n>0)return{name:t.slice(0,n),version:DC(t.slice(n+1))};if(!e.startsWith(`/`))return null;let r=t.lastIndexOf(`/`);return r<=0?null:{name:t.slice(0,r),version:DC(t.slice(r+1))}}function kC(e,t){let n=aS(e);if(!Q(n))throw Error(`not a JSON object`);let r=new nS(`npm`,t);if(Q(n.packages)){let e=/* @__PURE__ */ new Set;for(let[t,r]of Object.entries(n.packages))if(!t.includes(`node_modules/`))for(let t of iS(r))e.add(t);for(let[t,i]of Object.entries(n.packages)){let n=t.lastIndexOf(`node_modules/`);if(n===-1||!Q(i)||i.link===!0)continue;let a=t.slice(n+13),o=typeof i.name==`string`?i.name:a;if(typeof i.version!=`string`)continue;let s=t===`node_modules/${a}`;r.add(o,i.version,s&&e.has(a))}return r.rows()}if(Q(n.dependencies)){let e=(t,n)=>{for(let[i,a]of Object.entries(t)){if(!Q(a))continue;let t=a.version;typeof t==`string`&&!EC(t)&&r.add(i,t,n===0&&a.dev!==!0),Q(a.dependencies)&&e(a.dependencies,n+1)}};e(n.dependencies,0)}return r.rows()}function AC(e,t,n){let r=new nS(`npm`,t),i=[],a=!1;for(let t of e.split(/\r?\n/)){if(t===``||t.startsWith(`#`))continue;if(!/^\s/.test(t)&&t.endsWith(`:`)){let e=t.slice(0,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``));a=e.some(e=>/@(workspace|link|file|portal):/.test(e)),i=[...new Set(e.map(jC).filter(e=>e!==null))];continue}let e=/^\s+version:?\s+"?([^"\s]+)"?/.exec(t)?.[1];if(e&&!a){for(let t of i)r.add(t,e,n.has(t));i=[]}}return r.rows()}function jC(e){if(e===`__metadata`)return null;let t=e.indexOf(`@`,1);return t>0?e.slice(0,t):null}async function MC(e,t){let n=ix(t),r=/* @__PURE__ */ new Set,i=await NC(e,ax(n,`package.json`));for(let e of iS(i))r.add(e);if(!Q(i))return r;let a=i.workspaces,o=(Array.isArray(a)?a:Q(a)&&Array.isArray(a.packages)?a.packages:[]).filter(e=>typeof e==`string`).map(e=>PC(ax(n,e.replace(/^\.\//,``).replace(/\/$/,``))));if(o.length===0)return r;for(let t of e.files){if(!t.path.endsWith(`package.json`))continue;let n=ix(t.path);if(o.some(e=>e.test(n)))for(let n of iS(await NC(e,t.path)))r.add(n)}return r}async function NC(e,t){let n=e.file(t);if(!n)return null;let r=await e.readText(n);if(r===null)return null;try{return aS(r)}catch{return e.warnings.push(`${t}: not valid JSON, skipped`),null}}function PC(e){let t=e.split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${t}$`)}function FC(e){return e.toLowerCase().replace(/[-_.]+/g,`-`)}function IC(e,t,n){let r=new nS(`pip`,t),i=!1,a=null,o=null,s=!1,c=()=>{a&&o&&!s&&r.add(a,o,n.has(FC(a))),a=null,o=null,s=!1};for(let t of e.split(/\r?\n/)){if(/^\s*\[{1,2}([^\]]+)\]{1,2}\s*$/.exec(t)){t.trim()===`[[package]]`?(c(),i=!0):i=!1;continue}if(!i)continue;let e=/^\s*(name|version|source)\s*=\s*(.+)$/.exec(t);if(!e)continue;let n=e[2]?.trim()??``;if(e[1]===`source`)s=/\b(editable|virtual)\s*=/.test(n);else{let t=/^"([^"]*)"/.exec(n)?.[1];e[1]===`name`&&t&&(a=t),e[1]===`version`&&t&&(o=t)}}return c(),r.rows()}function LC(e){let t=/* @__PURE__ */ new Set,n=``,r=null,i=``,a=e=>{let n=/^\s*([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(e)?.[1];n&&t.add(FC(n))},o=()=>{for(let e of i.matchAll(/"([^"]*)"|'([^']*)'/g))a(e[1]??e[2]??``);r=null,i=``};for(let a of e.split(/\r?\n/)){let e=a.replace(/\s+#.*$/,``);if(r!==null){i+=` ${e}`,e.includes(`]`)&&o();continue}let s=/^\s*\[([^\]]+)\]\s*$/.exec(e);if(s){n=(s[1]??``).trim();continue}let c=/^\s*"?([A-Za-z0-9_.-]+)"?\s*=\s*(.*)$/.exec(e);if(!c)continue;let l=c[1]??``,u=c[2]??``;n===`tool.poetry.dependencies`||n===`tool.poetry.dev-dependencies`||/^tool\.poetry\.group\.[^.]+\.dependencies$/.test(n)?FC(l)!==`python`&&t.add(FC(l)):(n===`project`&&l===`dependencies`||n===`project.optional-dependencies`||n===`dependency-groups`)&&u.trimStart().startsWith(`[`)&&(r=l,i=u,u.includes(`]`)&&o())}return t}function RC(e,t){let n=new nS(`pip`,t),r=0;for(let t of e.split(/\r?\n/)){let e=t.replace(/(^|\s)#.*$/,``).trim();if(e===``||e.startsWith(`-`))continue;let i=/^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*===?\s*([^\s;,\\]+)/.exec(e);i?.[1]&&i[2]?n.add(i[1],i[2],!0):r++}return{rows:n.rows(),unpinned:r}}async function zC(e){let t=[];for(let n of e.files)try{let r=await BC(e,n);r&&t.push(...r)}catch(t){e.warnings.push(`${n.path}: could not be parsed (${ox(t)})`)}return t}async function BC(e,t){let n=rx(t.path),r=ix(t.path),i=t=>t?e.readText(t,52428800):Promise.resolve(null),a=t=>e.file(ax(r,t));switch(n){case`pnpm-lock.yaml`:{let e=await i(t);return e===null?null:TC(e,t.path)}case`package-lock.json`:case`npm-shrinkwrap.json`:{let e=await i(t);return e===null?null:kC(e,t.path)}case`yarn.lock`:{let n=await i(t);return n===null?null:AC(n,t.path,await MC(e,t.path))}case`composer.lock`:{let e=await i(t);return e===null?null:oS(e,t.path,await i(a(`composer.json`)))}case`poetry.lock`:case`uv.lock`:{let e=await i(t);if(e===null)return null;let n=await i(a(`pyproject.toml`)),r=n?LC(n):/* @__PURE__ */ new Set;return IC(e,t.path,r)}case`go.sum`:case`go.mod`:return n===`go.mod`&&a(`go.sum`)?null:sS(await i(a(`go.mod`)),n===`go.sum`?await i(t):null,t.path)}if(/^requirements[\w.-]*\.txt$/i.test(n)||/(^|\/)requirements\/[^/]+\.txt$/.test(t.path)){let n=await i(t);if(n===null)return null;let{rows:r,unpinned:a}=RC(n,t.path);return a>0&&e.warnings.push(`${t.path}: ${a} requirement${a===1?``:`s`} without an exact == pin skipped`),r}return null}const VC=n(i);async function HC(e,t){try{let{stdout:n}=await VC(`git`,t,{cwd:e,timeout:1e4}),r=n.trim();return r===``?null:r}catch{return null}}async function UC(e,t){let n=_.basename(e);if(await HC(e,[`rev-parse`,`--is-inside-work-tree`])!==`true`)return t.push(`Not a git repository (or git is not installed): repo details are empty`),{name:n,provider:null,url:null,defaultBranch:null,headSha:null,lastCommitAt:null};let[r,i,a,o,s]=await Promise.all([HC(e,[`remote`,`get-url`,`origin`]),HC(e,[`rev-parse`,`--verify`,`--quiet`,`HEAD`]),HC(e,[`log`,`-1`,`--format=%cI`]),HC(e,[`symbolic-ref`,`--quiet`,`refs/remotes/origin/HEAD`]),HC(e,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`])]);i===null&&t.push(`Git repository has no commits yet`),r===null&&t.push(`Git repository has no 'origin' remote`);let c=r?WC(r):null;return r&&!c&&t.push(`Could not read the 'origin' remote URL`),{name:c?.name??n,provider:c?.provider??null,url:c?.url??null,defaultBranch:o?.replace(/^refs\/remotes\/origin\//,``)??s,headSha:i,lastCommitAt:a?new Date(a).toISOString():null}}function WC(e){let t,n,r=/^(?:[^@/]+@)?([^:/]+):(?!\/)(.+)$/.exec(e);if(/^[a-z+]+:\/\//i.test(e)){let r;try{r=new URL(e)}catch{return null}if(r.protocol===`file:`)return null;t=r.hostname,n=r.pathname}else if(r?.[1]&&r[2])t=r[1],n=r[2];else return null;if(n=n.replace(/^\/+/,``).replace(/\/+$/,``).replace(/\.git$/,``),!t||!n)return null;let i=t.toLowerCase(),a=i.includes(`github`)?`github`:i.includes(`gitlab`)?`gitlab`:null;return{name:n.slice(n.lastIndexOf(`/`)+1),provider:a,url:`https://${i}/${n}`}}const GC={ts:`TypeScript`,tsx:`TypeScript`,mts:`TypeScript`,cts:`TypeScript`,js:`JavaScript`,jsx:`JavaScript`,mjs:`JavaScript`,cjs:`JavaScript`,py:`Python`,go:`Go`,rb:`Ruby`,php:`PHP`,java:`Java`,kt:`Kotlin`,kts:`Kotlin`,swift:`Swift`,rs:`Rust`,cs:`C#`,fs:`F#`,c:`C`,h:`C`,cc:`C++`,cpp:`C++`,cxx:`C++`,hpp:`C++`,m:`Objective-C`,mm:`Objective-C++`,scala:`Scala`,dart:`Dart`,ex:`Elixir`,exs:`Elixir`,erl:`Erlang`,clj:`Clojure`,hs:`Haskell`,ml:`OCaml`,lua:`Lua`,r:`R`,pl:`Perl`,groovy:`Groovy`,zig:`Zig`,sol:`Solidity`,sql:`SQL`,sh:`Shell`,bash:`Shell`,zsh:`Shell`,ps1:`PowerShell`,tf:`HCL`,vue:`Vue`,svelte:`Svelte`,astro:`Astro`,html:`HTML`,css:`CSS`,scss:`SCSS`,sass:`SCSS`,less:`Less`};function KC(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=n.path.lastIndexOf(`.`);if(e===-1||e<n.path.lastIndexOf(`/`))continue;let r=GC[n.path.slice(e+1).toLowerCase()];r&&t.set(r,(t.get(r)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,5).map(([e])=>e)}const qC=/* @__PURE__ */ new Set([`auth`,`storage`,`realtime`,`_realtime`,`extensions`,`graphql`,`graphql_public`,`supabase_functions`,`supabase_migrations`,`pgsodium`,`pgsodium_masks`,`vault`,`net`,`cron`,`pgbouncer`,`pg_catalog`,`information_schema`]),JC=/^(not|null|default|primary|unique|references|check|constraint|generated|collate|deferrable|initially|identity)$/i;function YC(e){if(!/\.sql$/i.test(e))return!1;let t=e.toLowerCase();return/(^|\/)migrations\//.test(t)||/(^|\/)db\/migrate\//.test(t)}async function XC(e){let t=/* @__PURE__ */ new Map,n=e.files.filter(e=>YC(e.path));n.sort((e,t)=>{let n=e.path.slice(e.path.lastIndexOf(`/`)+1),r=t.path.slice(t.path.lastIndexOf(`/`)+1);return n<r?-1:n>r?1:e.path<t.path?-1:1});for(let r of n){let n=await e.readText(r);if(n!==null)for(let i of ZC(n))try{aw(i,r.path,t,e.warnings)}catch(t){e.warnings.push(`${r.path}: could not read statement "${hw(i)}" (${t instanceof Error?t.message:String(t)})`)}}return[...t.values()].filter(e=>!qC.has(e.schema)).map(e=>{let t=e.schema===`public`?e.table:`${e.schema}.${e.table}`;return{kind:`table`,name:t,sourcePath:e.sourcePath,table:t,columns:e.columns}})}function ZC(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r],a=e[r+1];if(i===`-`&&a===`-`){let t=e.indexOf(`
|
|
338
|
-
`,r);r=t===-1?e.length:t,n+=` `}else if(i===`/`&&a===`*`){let t=1;for(r+=2;r<e.length&&t>0;)e.startsWith(`/*`,r)?(t++,r+=2):e.startsWith(`*/`,r)?(t--,r+=2):r++;n+=` `}else if(i===`'`||i===`"`){let t=r+1;for(;t<e.length;)if(e[t]===i){if(e[t+1]===i)t+=2;else break}else t++;n+=e.slice(r,t+1),r=t+1}else{if(i===`$`){let t=/^\$[A-Za-z_]?[A-Za-z0-9_]*\$/.exec(e.slice(r,r+64))?.[0];if(t){let i=e.indexOf(t,r+t.length),a=i===-1?e.length:i+t.length;n+=e.slice(r,a),r=a;continue}}i===`;`?(n.trim()&&t.push(n.trim()),n=``,r++):(n+=i,r++)}}return n.trim()&&t.push(n.trim()),t.map(e=>e.replace(/\s+/g,` `))}function QC(e){let t=[],n=0,r=null,i=0;for(let a=0;a<e.length;a++){let o=e[a];r?o===r&&(r=null):o===`'`||o===`"`?r=o:o===`(`?n++:o===`)`?n--:o===`,`&&n===0&&(t.push(e.slice(i,a).trim()),i=a+1)}return t.push(e.slice(i).trim()),t.filter(Boolean)}function $C(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(/\s/.test(r)){n++;continue}if(r===`(`){let r=0,i=n,a=null;for(;i<e.length;i++){let t=e[i];if(a)t===a&&(a=null);else if(t===`'`||t===`"`)a=t;else if(t===`(`)r++;else if(t===`)`&&--r===0)break}t.push(e.slice(n,i+1)),n=i+1;continue}let i=n,a=null;for(;i<e.length;i++){let t=e[i];if(a)t===a&&(a=null);else if(t===`'`||t===`"`)a=t;else if(/\s/.test(t)||t===`(`)break}t.push(e.slice(n,i)),n=i}return t}const ew=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`,tw=String.raw`(${ew}(?:\s*\.\s*${ew})?)`;function nw(e){let t=e.trim();return t.startsWith(`"`)?t.slice(1,-1).replace(/""/g,`"`):t.toLowerCase()}function rw(e){let t=e.match(new RegExp(ew,`g`))??[e];return t.length>=2?{schema:nw(t[0]??``),table:nw(t[1]??``)}:{schema:`public`,table:nw(t[0]??e)}}function iw(e,t){return`${e}.${t}`}function aw(e,t,n,r){if(/^create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\b/i.test(e)){ow(e,t,n,r);return}let i=new RegExp(String.raw`^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${tw}\s+(.+)$`,`i`).exec(e);if(i?.[1]&&i[2]){pw(rw(i[1]),i[2],t,n,r);return}let a=/^drop\s+table\s+(?:if\s+exists\s+)?(.+?)(?:\s+(?:cascade|restrict))?$/i.exec(e);if(a?.[1])for(let e of QC(a[1])){let{schema:t,table:r}=rw(e);n.delete(iw(t,r))}}function ow(e,t,n,r){let i=new RegExp(String.raw`^create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?${tw}\s*\(`,`i`).exec(e);if(!i?.[1]){r.push(`${t}: skipped a create table statement it couldn't read: "${hw(e)}"`);return}let{schema:a,table:o}=rw(i[1]),s=i[0].length-1,c=sw(e,s);if(c===-1){r.push(`${t}: unbalanced parentheses in create table ${o}`);return}let l=iw(a,o);if(n.has(l)&&/\bif\s+not\s+exists\b/i.test(e.slice(0,s)))return;let u={schema:a,table:o,sourcePath:t,columns:[]};for(let i of QC(e.slice(s+1,c))){if(/^(constraint|primary\s+key|unique|foreign\s+key|check|exclude|like)\b/i.test(i)){fw(u,i,n);continue}let e=cw(i,n);e?u.columns.push(e):r.push(`${t}: skipped column definition "${hw(i)}" in ${o}`)}n.set(l,u)}function sw(e,t){let n=0,r=null;for(let i=t;i<e.length;i++){let t=e[i];if(r)t===r&&(r=null);else if(t===`'`||t===`"`)r=t;else if(t===`(`)n++;else if(t===`)`&&--n===0)return i}return-1}function cw(e,t){let n=$C(e),r=n[0];if(!r||n.length<2)return null;let i=1,a=[];for(;i<n.length&&!JC.test(n[i]??``);)a.push(n[i]),i++;if(a.length===0)return null;let o={name:nw(r),type:a.join(` `).replace(/\s+\(/g,`(`).toLowerCase(),required:!1};return lw(o,n.slice(i),t),o}function lw(e,t,n){for(let r=0;r<t.length;r++){let i=t[r]?.toLowerCase(),a=t[r+1]?.toLowerCase();if(i===`not`&&a===`null`)e.required=!0,r++;else if(i===`primary`&&a===`key`)e.primaryKey=!0,e.required=!0,r++;else if(i===`unique`)e.unique=!0;else if(i==="default"){let n=[];for(;r+1<t.length&&!JC.test(t[r+1]??``);)n.push(t[r+1]),r++;n.length>0&&(e.default=uw(n))}else if(i===`references`){let i=t[r+1];if(!i)continue;let a=t[r+2]?.startsWith(`(`)?t[r+2]:void 0;e.references=dw(i,a,n),r+=a?2:1}}}function uw(e){return e.join(` `).replace(/\s+\(/g,`(`)}function dw(e,t,n){let{schema:r,table:i}=rw(e),a=r===`public`?i:`${r}.${i}`,o=t?nw(t.slice(1,-1).split(`,`)[0]??``):null;return o||=n.get(iw(r,i))?.columns.find(e=>e.primaryKey)?.name??`id`,`${a}.${o}`}function fw(e,t,n){let r=t.replace(new RegExp(String.raw`^constraint\s+${ew}\s+`,`i`),``),i=e=>(e??``).split(`,`).map(e=>nw(e)).filter(Boolean),a=/^primary\s+key\s*\(([^)]*)\)/i.exec(r);if(a){for(let t of i(a[1])){let n=e.columns.find(e=>e.name===t);n&&(n.primaryKey=!0,n.required=!0)}return}let o=/^unique\s*(?:nulls\s+(?:not\s+)?distinct\s*)?\(([^)]*)\)/i.exec(r);if(o){let t=i(o[1]),n=t.length===1?e.columns.find(e=>e.name===t[0]):void 0;n&&(n.unique=!0);return}let s=new RegExp(String.raw`^foreign\s+key\s*\(([^)]*)\)\s*references\s+${tw}\s*(\([^)]*\))?`,`i`).exec(r);if(s?.[2]){let t=i(s[1]),r=s[3]?i(s[3].slice(1,-1)):[];t.forEach((t,i)=>{let a=e.columns.find(e=>e.name===t);if(!a)return;let o=r[i];a.references=dw(s[2],o?`(${o})`:void 0,n)})}}function pw(e,t,n,r,i){let a=r.get(iw(e.schema,e.table));if(!a){!qC.has(e.schema)&&/\b(add|drop|alter|rename)\s+column\b/i.test(t)&&i.push(`${n}: alter table ${e.table} before any create table for it, skipped`);return}let o=new RegExp(String.raw`^rename\s+to\s+(${ew})$`,`i`).exec(t);if(o?.[1]){r.delete(iw(a.schema,a.table)),a.table=nw(o[1]),r.set(iw(a.schema,a.table),a);return}let s=new RegExp(String.raw`^rename\s+(?:column\s+)?(${ew})\s+to\s+(${ew})$`,`i`).exec(t);if(s?.[1]&&s[2]){let e=a.columns.find(e=>e.name===nw(s[1]));e&&(e.name=nw(s[2]))}else for(let e of QC(t)){let t=/^add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?(.+)$/i.exec(e);if(t?.[1]&&!/^add\s+(constraint|primary|unique|foreign|check|exclude)\b/i.test(e)){let o=cw(t[1],r);if(!o){i.push(`${n}: skipped "${hw(e)}" on ${a.table}`);continue}a.columns.some(e=>e.name===o.name)||a.columns.push(o);continue}let o=/^add\s+(.+)$/i.exec(e);if(o?.[1]){fw(a,o[1],r);continue}let s=new RegExp(String.raw`^drop\s+(?:column\s+)?(?:if\s+exists\s+)?(${ew})`,`i`).exec(e);if(s?.[1]&&!/^drop\s+constraint\b/i.test(e)){let e=nw(s[1]);a.columns=a.columns.filter(t=>t.name!==e);continue}let c=new RegExp(String.raw`^alter\s+(?:column\s+)?(${ew})\s+(.+)$`,`i`).exec(e);if(c?.[1]&&c[2]){let e=a.columns.find(e=>e.name===nw(c[1]));e&&mw(e,c[2])}}}function mw(e,t){if(/^set\s+not\s+null$/i.test(t))e.required=!0;else if(/^drop\s+not\s+null$/i.test(t))e.required=!!e.primaryKey;else if(/^drop\s+default$/i.test(t))delete e.default;else{let n=/^set\s+default\s+(.+)$/i.exec(t);if(n?.[1]){e.default=uw($C(n[1]));return}let r=/^(?:set\s+data\s+)?type\s+(.+?)(?:\s+(?:using|collate)\s+.*)?$/i.exec(t);r?.[1]&&(e.type=r[1].replace(/\s+\(/g,`(`).toLowerCase())}}function hw(e){return e.length>60?`${e.slice(0,57)}...`:e}const gw=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],_w=/^(openapi|swagger)([.-][\w.-]*)?\.(json|ya?ml)$/i,vw=/\.(json|ya?ml)$/i;async function yw(e){let t=[];for(let n of e.files){let r=_w.test(rx(n.path));if(!r&&!vw.test(n.path)||!r&&(n.size>1048576||/(^|\/)[^/]*lock[^/]*$/i.test(n.path)))continue;let i=await e.readText(n,r?10485760:void 0);if(i===null||!r&&!/^\s*["']?(openapi|swagger)["']?\s*:/m.test(i))continue;let a;try{a=/\.json$/i.test(n.path)?JSON.parse(i):(0,wC.parse)(i)}catch(t){e.warnings.push(`${n.path}: OpenAPI file could not be parsed (${ox(t)})`);continue}!Q(a)||typeof a.openapi!=`string`&&typeof a.swagger!=`string`?r&&e.warnings.push(`${n.path}: no top-level openapi or swagger version, skipped`):t.push(...bw(a,n.path,e.warnings))}return t}function bw(e,t,n){let r=typeof e.swagger==`string`,i=new xw(e,t,n),a=r?e.securityDefinitions:Cw(e.components)?.securitySchemes,o=Q(a)?a:{},s=Q(e.paths)?e.paths:{},c=[];for(let[n,a]of Object.entries(s)){let s=i.resolve(a);if(s)for(let a of gw){let l=Cw(s[a.toLowerCase()]);if(!l)continue;let u=[...Array.isArray(s.parameters)?s.parameters:[],...Array.isArray(l.parameters)?l.parameters:[]],d=l.security??e.security;c.push({kind:`endpoint`,name:sx(l.summary)?.trim()||sx(l.operationId)||`${a} ${n}`,sourcePath:t,method:a,path:n,auth:Lw(d,o,i),request:r?Ow(u,l,e,i):Tw(l.requestBody,i),responses:kw(l,e,r,i)})}}return c}var xw=class{#e;#t;#n;#r=/* @__PURE__ */ new Set;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}resolve(e){let t=e;for(let e=0;e<8;e++){if(!Q(t))return null;let e=t.$ref;if(typeof e!=`string`)return t;t=this.#i(e)}return null}refName(e){if(!Q(e)||typeof e.$ref!=`string`)return null;let t=e.$ref.slice(e.$ref.lastIndexOf(`/`)+1);return t?Sw(t):null}#i(e){if(!e.startsWith(`#/`))return this.#r.has(e)||(this.#r.add(e),this.#n.push(`${this.#t}: external $ref "${e}" not followed`)),null;let t=this.#e;for(let n of e.slice(2).split(`/`)){if(!Q(t))break;t=t[Sw(n)]}return t===void 0&&!this.#r.has(e)&&(this.#r.add(e),this.#n.push(`${this.#t}: $ref "${e}" points at nothing`)),t}};function Sw(e){return decodeURIComponent(e).replace(/~1/g,`/`).replace(/~0/g,`~`)}function Cw(e){return Q(e)?e:null}function ww(e){if(!Q(e))return null;let t=Object.entries(e).filter(e=>Q(e[1]));return t.find(([e])=>e===`application/json`)??t.find(([e])=>/json/.test(e))??t[0]??null}function Tw(e,t){let n=t.resolve(e),r=n?ww(n.content):null;return r?Ew(r[0],r[1],t):null}function Ew(e,t,n){let r=t.schema;return{contentType:e,fields:Nw(r,n),example:Dw(t,n)??Iw(r,n,0)}}function Dw(e,t){if(e.example!==void 0)return e.example;if(Q(e.examples)){let n=t.resolve(Object.values(e.examples)[0]);if(n&&n.value!==void 0)return n.value}}function Ow(e,t,n,r){let i=e.map(e=>r.resolve(e)).filter(e=>e!==null),a=jw(t.consumes)??jw(n.consumes),o=i.find(e=>e.in===`body`);if(o)return{contentType:a??`application/json`,fields:Nw(o.schema,r),example:Iw(o.schema,r,0)};let s=i.filter(e=>e.in===`formData`);if(s.length===0)return null;let c=s.map(e=>({name:sx(e.name)??``,type:Fw(e,r),required:e.required===!0,...Pw(e)}));return{contentType:a??`application/x-www-form-urlencoded`,fields:c,example:Object.fromEntries(s.map(e=>[sx(e.name)??``,Iw(e,r,1)]))}}function kw(e,t,n,r){if(!Q(e.responses))return[];let i=jw(e.produces)??jw(t.produces)??`application/json`,a=[];for(let[t,o]of Object.entries(e.responses)){let e=r.resolve(o);if(!e)continue;let s=null;if(n){if(e.schema!==void 0){let t=Cw(e.examples);s={contentType:i,fields:Nw(e.schema,r),example:t?.[i]??Iw(e.schema,r,0)}}}else{let t=ww(e.content);t&&(s=Ew(t[0],t[1],r))}a.push({status:Aw(t),description:sx(e.description)??``,body:s})}return a}function Aw(e){let t=e.replace(/x/gi,`0`),n=Number.parseInt(t,10);return Number.isNaN(n)?0:n}function jw(e){return Array.isArray(e)&&typeof e[0]==`string`?e[0]:void 0}function Mw(e,t,n=0){let r=t.resolve(e);if(!r||n>8)return r;if(Array.isArray(r.allOf)){let e={},i=[];for(let a of r.allOf){let r=Mw(a,t,n+1);r&&(Q(r.properties)&&Object.assign(e,r.properties),Array.isArray(r.required)&&i.push(...r.required.filter(e=>typeof e==`string`)))}return Q(r.properties)&&Object.assign(e,r.properties),Array.isArray(r.required)&&i.push(...r.required.filter(e=>typeof e==`string`)),{...r,type:`object`,properties:e,required:i}}let i=Array.isArray(r.oneOf)?r.oneOf:Array.isArray(r.anyOf)?r.anyOf:null;return i&&i.length>0&&!r.properties?Mw(i[0],t,n+1):r}function Nw(e,t){let n=Mw(e,t);if(n?.type===`array`&&(n=Mw(n.items,t)),!n||!Q(n.properties))return[];let r=new Set(Array.isArray(n.required)?n.required:[]);return Object.entries(n.properties).map(([e,n])=>{let i=Mw(n,t)??{};return{name:e,type:Fw(n,t),required:r.has(e),...Pw(i)}})}function Pw(e){let t={},n=sx(e.description)?.trim();return n&&(t.description=n),Array.isArray(e.enum)&&(t.values=e.enum.map(e=>String(e))),t}function Fw(e,t,n=0){let r=t.refName(e),i=Mw(e,t);if(!i)return r??`unknown`;let a=Array.isArray(i.type)?i.type.filter(e=>e!==`null`).join(` | `):sx(i.type);return a===`array`?n>8?`array`:`${Fw(i.items,t,n+1)}[]`:r&&(a===`object`||a===void 0)?r:sx(i.format)??a??(i.properties?`object`:`unknown`)}function Iw(e,t,n){let r=Mw(e,t);if(!r||n>8)return null;if(r.example!==void 0)return r.example;if(Array.isArray(r.enum)&&r.enum.length>0)return r.enum[0];let i=Array.isArray(r.type)?r.type.find(e=>e!==`null`):r.type;if(i===`object`||i===void 0&&Q(r.properties)){let e=Q(r.properties)?r.properties:{};return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Iw(r,t,n+1)]))}switch(i){case`array`:return[Iw(r.items,t,n+1)];case`string`:return`string`;case`integer`:case`number`:return 0;case`boolean`:return!1;default:return null}}function Lw(e,t,n){if(!Array.isArray(e)||e.length===0)return null;let r=[];for(let i of e){if(!Q(i))continue;let e=Object.keys(i);e.length===0?r.push(`none`):r.push(e.map(e=>Rw(e,n.resolve(t[e]))).join(` + `))}let i=[...new Set(r)];return i.length===0||i.length===1&&i[0]===`none`?null:i.map(e=>e===`none`?`no auth`:e).join(` or `)}function Rw(e,t){if(!t)return e;switch(sx(t.type)?.toLowerCase()){case`http`:{let e=sx(t.scheme)?.toLowerCase();if(e===`bearer`){let e=sx(t.bearerFormat);return e?`Bearer token (${e})`:`Bearer token`}return e===`basic`?`Basic auth`:`HTTP ${e??`auth`}`}case`basic`:return`Basic auth`;case`apikey`:return`apikey ${sx(t.in)??`header`} ${sx(t.name)??e}`;case`oauth2`:return`OAuth2`;case`openidconnect`:return`OpenID Connect`;case`mutualtls`:return`Mutual TLS`;default:return e}}const zw=[`readme.md`,`readme.mdx`,`readme.markdown`,`readme.txt`,`readme`];async function Bw(e){let t=e.files.find(e=>!e.path.includes(`/`)&&zw.includes(e.path.toLowerCase()));if(!t)return null;let n=await e.readText(t);return{path:t.path,oneLiner:n===null?null:Vw(n)}}function Vw(e){let t=e.replace(/\r\n/g,`
|
|
339
|
+
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),CC=/* @__PURE__ */ D((e=>{var t=hC(),n=QS(),r=$S(),i=CS(),a=$(),o=xC(),s=SC();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),wC=(/* @__PURE__ */ D((e=>{var t=hC(),n=QS(),r=XS(),i=$S(),a=mS(),o=$(),s=ES(),c=hS(),l=OS(),u=AS();yC();var d=bC(),f=xC(),p=SC(),m=CC(),h=cS();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})))();function TC(e,t){let n=(0,wC.parse)(e,{uniqueKeys:!1});if(!Q(n))throw Error(`not a YAML mapping`);let r=new nS(`npm`,t),i=Q(n.importers)?n.importers:{".":n};for(let e of Object.values(i))if(Q(e))for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let n=e[t];if(Q(n))for(let[e,t]of Object.entries(n)){let n=Q(t)?t.version:t;if(typeof n!=`string`||EC(n))continue;let i=OC(n);i?r.add(i.name,i.version,!0):r.add(e,DC(n),!0)}}for(let e of[`packages`,`snapshots`]){let t=n[e];if(Q(t))for(let e of Object.keys(t)){let t=OC(e);t&&!EC(t.version)&&r.add(t.name,t.version,!1)}}return r.rows()}function EC(e){return/^(link|file|workspace):/.test(e)}function DC(e){return e.replace(/\(.*$/,``).replace(/_(?=[^/]*@).*$/,``)}function OC(e){let t=e.replace(/^\//,``).replace(/\(.*$/,``),n=t.indexOf(`@`,1);if(n>0)return{name:t.slice(0,n),version:DC(t.slice(n+1))};if(!e.startsWith(`/`))return null;let r=t.lastIndexOf(`/`);return r<=0?null:{name:t.slice(0,r),version:DC(t.slice(r+1))}}function kC(e,t){let n=aS(e);if(!Q(n))throw Error(`not a JSON object`);let r=new nS(`npm`,t);if(Q(n.packages)){let e=/* @__PURE__ */ new Set;for(let[t,r]of Object.entries(n.packages))if(!t.includes(`node_modules/`))for(let t of iS(r))e.add(t);for(let[t,i]of Object.entries(n.packages)){let n=t.lastIndexOf(`node_modules/`);if(n===-1||!Q(i)||i.link===!0)continue;let a=t.slice(n+13),o=typeof i.name==`string`?i.name:a;if(typeof i.version!=`string`)continue;let s=t===`node_modules/${a}`;r.add(o,i.version,s&&e.has(a))}return r.rows()}if(Q(n.dependencies)){let e=(t,n)=>{for(let[i,a]of Object.entries(t)){if(!Q(a))continue;let t=a.version;typeof t==`string`&&!EC(t)&&r.add(i,t,n===0&&a.dev!==!0),Q(a.dependencies)&&e(a.dependencies,n+1)}};e(n.dependencies,0)}return r.rows()}function AC(e,t,n){let r=new nS(`npm`,t),i=[],a=!1;for(let t of e.split(/\r?\n/)){if(t===``||t.startsWith(`#`))continue;if(!/^\s/.test(t)&&t.endsWith(`:`)){let e=t.slice(0,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``));a=e.some(e=>/@(workspace|link|file|portal):/.test(e)),i=[...new Set(e.map(jC).filter(e=>e!==null))];continue}let e=/^\s+version:?\s+"?([^"\s]+)"?/.exec(t)?.[1];if(e&&!a){for(let t of i)r.add(t,e,n.has(t));i=[]}}return r.rows()}function jC(e){if(e===`__metadata`)return null;let t=e.indexOf(`@`,1);return t>0?e.slice(0,t):null}async function MC(e,t){let n=rx(t),r=/* @__PURE__ */ new Set,i=await NC(e,ix(n,`package.json`));for(let e of iS(i))r.add(e);if(!Q(i))return r;let a=i.workspaces,o=(Array.isArray(a)?a:Q(a)&&Array.isArray(a.packages)?a.packages:[]).filter(e=>typeof e==`string`).map(e=>PC(ix(n,e.replace(/^\.\//,``).replace(/\/$/,``))));if(o.length===0)return r;for(let t of e.files){if(!t.path.endsWith(`package.json`))continue;let n=rx(t.path);if(o.some(e=>e.test(n)))for(let n of iS(await NC(e,t.path)))r.add(n)}return r}async function NC(e,t){let n=e.file(t);if(!n)return null;let r=await e.readText(n);if(r===null)return null;try{return aS(r)}catch{return e.warnings.push(`${t}: not valid JSON, skipped`),null}}function PC(e){let t=e.split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${t}$`)}function FC(e){return e.toLowerCase().replace(/[-_.]+/g,`-`)}function IC(e,t,n){let r=new nS(`pip`,t),i=!1,a=null,o=null,s=!1,c=()=>{a&&o&&!s&&r.add(a,o,n.has(FC(a))),a=null,o=null,s=!1};for(let t of e.split(/\r?\n/)){if(/^\s*\[{1,2}([^\]]+)\]{1,2}\s*$/.exec(t)){t.trim()===`[[package]]`?(c(),i=!0):i=!1;continue}if(!i)continue;let e=/^\s*(name|version|source)\s*=\s*(.+)$/.exec(t);if(!e)continue;let n=e[2]?.trim()??``;if(e[1]===`source`)s=/\b(editable|virtual)\s*=/.test(n);else{let t=/^"([^"]*)"/.exec(n)?.[1];e[1]===`name`&&t&&(a=t),e[1]===`version`&&t&&(o=t)}}return c(),r.rows()}function LC(e){let t=/* @__PURE__ */ new Set,n=``,r=null,i=``,a=e=>{let n=/^\s*([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(e)?.[1];n&&t.add(FC(n))},o=()=>{for(let e of i.matchAll(/"([^"]*)"|'([^']*)'/g))a(e[1]??e[2]??``);r=null,i=``},s=e=>e.replace(/"[^"]*"|'[^']*'/g,``).includes(`]`);for(let a of e.split(/\r?\n/)){let e=a.replace(/\s+#.*$/,``);if(r!==null){i+=` ${e}`,s(e)&&o();continue}let c=/^\s*\[([^\]]+)\]\s*$/.exec(e);if(c){n=(c[1]??``).trim();continue}let l=/^\s*"?([A-Za-z0-9_.-]+)"?\s*=\s*(.*)$/.exec(e);if(!l)continue;let u=l[1]??``,d=l[2]??``;n===`tool.poetry.dependencies`||n===`tool.poetry.dev-dependencies`||/^tool\.poetry\.group\.[^.]+\.dependencies$/.test(n)?FC(u)!==`python`&&t.add(FC(u)):(n===`project`&&u===`dependencies`||n===`project.optional-dependencies`||n===`dependency-groups`)&&d.trimStart().startsWith(`[`)&&(r=u,i=d,s(d.trimStart().slice(1))&&o())}return t}function RC(e,t){let n=new nS(`pip`,t),r=0;for(let t of e.split(/\r?\n/)){let e=t.replace(/(^|\s)#.*$/,``).trim();if(e===``||e.startsWith(`-`))continue;let i=/^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*===?\s*([^\s;,\\]+)/.exec(e);i?.[1]&&i[2]?n.add(i[1],i[2],!0):r++}return{rows:n.rows(),unpinned:r}}async function zC(e){let t=[];for(let n of e.files)try{let r=await BC(e,n);r&&t.push(...r)}catch(t){e.warnings.push(`${n.path}: could not be parsed (${ax(t)})`)}return t}async function BC(e,t){let n=nx(t.path),r=rx(t.path),i=t=>t?e.readText(t,52428800):Promise.resolve(null),a=t=>e.file(ix(r,t));switch(n){case`pnpm-lock.yaml`:{let e=await i(t);return e===null?null:TC(e,t.path)}case`package-lock.json`:case`npm-shrinkwrap.json`:{let e=await i(t);return e===null?null:kC(e,t.path)}case`yarn.lock`:{let n=await i(t);return n===null?null:AC(n,t.path,await MC(e,t.path))}case`composer.lock`:{let e=await i(t);return e===null?null:oS(e,t.path,await i(a(`composer.json`)))}case`poetry.lock`:case`uv.lock`:{let e=await i(t);if(e===null)return null;let n=await i(a(`pyproject.toml`)),r=n?LC(n):/* @__PURE__ */ new Set;return IC(e,t.path,r)}case`go.sum`:case`go.mod`:return n===`go.mod`&&a(`go.sum`)?null:sS(await i(a(`go.mod`)),n===`go.sum`?await i(t):null,t.path)}if(/^requirements[\w.-]*\.txt$/i.test(n)||/(^|\/)requirements\/[^/]+\.txt$/.test(t.path)){let n=await i(t);if(n===null)return null;let{rows:r,unpinned:a}=RC(n,t.path);return a>0&&e.warnings.push(`${t.path}: ${a} requirement${a===1?``:`s`} without an exact == pin skipped`),r}return null}const VC=n(i);async function HC(e,t){try{let{stdout:n}=await VC(`git`,t,{cwd:e,timeout:1e4}),r=n.trim();return r===``?null:r}catch{return null}}async function UC(e,t){let n=_.basename(e);if(await HC(e,[`rev-parse`,`--is-inside-work-tree`])!==`true`)return t.push(`Not a git repository (or git is not installed): repo details are empty`),{name:n,provider:null,url:null,defaultBranch:null,headSha:null,lastCommitAt:null};let[r,i,a,o,s]=await Promise.all([HC(e,[`remote`,`get-url`,`origin`]),HC(e,[`rev-parse`,`--verify`,`--quiet`,`HEAD`]),HC(e,[`log`,`-1`,`--format=%cI`]),HC(e,[`symbolic-ref`,`--quiet`,`refs/remotes/origin/HEAD`]),HC(e,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`])]);i===null&&t.push(`Git repository has no commits yet`),r===null&&t.push(`Git repository has no 'origin' remote`);let c=r?WC(r):null;return r&&!c&&t.push(`Could not read the 'origin' remote URL`),{name:c?.name??n,provider:c?.provider??null,url:c?.url??null,defaultBranch:o?.replace(/^refs\/remotes\/origin\//,``)??s,headSha:i,lastCommitAt:a?new Date(a).toISOString():null}}function WC(e){let t,n,r=/^(?:[^@/]+@)?([^:/]+):(?!\/)(.+)$/.exec(e);if(/^[a-z+]+:\/\//i.test(e)){let r;try{r=new URL(e)}catch{return null}if(r.protocol===`file:`)return null;t=r.hostname,n=r.pathname}else if(r?.[1]&&r[2])t=r[1],n=r[2];else return null;if(n=n.replace(/^\/+/,``).replace(/\/+$/,``).replace(/\.git$/,``),!t||!n)return null;let i=t.toLowerCase(),a=i.includes(`github`)?`github`:i.includes(`gitlab`)?`gitlab`:null;return{name:n.slice(n.lastIndexOf(`/`)+1),provider:a,url:`https://${i}/${n}`}}const GC={ts:`TypeScript`,tsx:`TypeScript`,mts:`TypeScript`,cts:`TypeScript`,js:`JavaScript`,jsx:`JavaScript`,mjs:`JavaScript`,cjs:`JavaScript`,py:`Python`,go:`Go`,rb:`Ruby`,php:`PHP`,java:`Java`,kt:`Kotlin`,kts:`Kotlin`,swift:`Swift`,rs:`Rust`,cs:`C#`,fs:`F#`,c:`C`,h:`C`,cc:`C++`,cpp:`C++`,cxx:`C++`,hpp:`C++`,m:`Objective-C`,mm:`Objective-C++`,scala:`Scala`,dart:`Dart`,ex:`Elixir`,exs:`Elixir`,erl:`Erlang`,clj:`Clojure`,hs:`Haskell`,ml:`OCaml`,lua:`Lua`,r:`R`,pl:`Perl`,groovy:`Groovy`,zig:`Zig`,sol:`Solidity`,sql:`SQL`,sh:`Shell`,bash:`Shell`,zsh:`Shell`,ps1:`PowerShell`,tf:`HCL`,vue:`Vue`,svelte:`Svelte`,astro:`Astro`,html:`HTML`,css:`CSS`,scss:`SCSS`,sass:`SCSS`,less:`Less`};function KC(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=n.path.lastIndexOf(`.`);if(e===-1||e<n.path.lastIndexOf(`/`))continue;let r=GC[n.path.slice(e+1).toLowerCase()];r&&t.set(r,(t.get(r)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,5).map(([e])=>e)}const qC=/* @__PURE__ */ new Set([`auth`,`storage`,`realtime`,`_realtime`,`extensions`,`graphql`,`graphql_public`,`supabase_functions`,`supabase_migrations`,`pgsodium`,`pgsodium_masks`,`vault`,`net`,`cron`,`pgbouncer`,`pg_catalog`,`information_schema`]),JC=/^(not|null|default|primary|unique|references|check|constraint|generated|collate|deferrable|initially|identity)$/i;function YC(e){if(!/\.sql$/i.test(e))return!1;let t=e.toLowerCase();return/(^|\/)migrations\//.test(t)||/(^|\/)db\/migrate\//.test(t)}const XC=e=>e.slice(0,e.lastIndexOf(`/`)+1);function ZC(e,t){let n=e.toLowerCase();if(!n.endsWith(`.sql`)||YC(e))return!1;let r=n.slice(n.lastIndexOf(`/`)+1);return/seed|fixture|sample|test|demo/.test(r)?!1:/schema|structure/.test(r)||t.has(XC(n))||/(^|\/)docker-entrypoint-initdb\.d\//.test(n)}async function QC(e){let t=/* @__PURE__ */ new Map,n=e.files.filter(e=>YC(e.path)),r=new Set(n.flatMap(e=>{let t=/^(.*\/)?(migrations|db\/migrate)\//.exec(e.path.toLowerCase());return t?[t[1]??``]:[]})),i=e.files.filter(e=>ZC(e.path,r)).sort((e,t)=>e.path<t.path?-1:1);n.sort((e,t)=>{let n=e.path.slice(e.path.lastIndexOf(`/`)+1),r=t.path.slice(t.path.lastIndexOf(`/`)+1);return n<r?-1:n>r?1:e.path<t.path?-1:1});for(let r of[...i,...n]){let n=await e.readText(r);if(n!==null)for(let i of $C(n))try{sw(i,r.path,t,e.warnings)}catch(t){e.warnings.push(`${r.path}: could not read statement "${_w(i)}" (${ax(t)})`)}}return[...t.values()].filter(e=>!qC.has(e.schema)).map(e=>{let t=e.schema===`public`?e.table:`${e.schema}.${e.table}`;return{kind:`table`,name:t,sourcePath:e.sourcePath,table:t,columns:e.columns}})}function $C(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r],a=e[r+1];if(i===`-`&&a===`-`){let t=e.indexOf(`
|
|
340
|
+
`,r);r=t===-1?e.length:t,n+=` `}else if(i===`/`&&a===`*`){let t=1;for(r+=2;r<e.length&&t>0;)e.startsWith(`/*`,r)?(t++,r+=2):e.startsWith(`*/`,r)?(t--,r+=2):r++;n+=` `}else if(i===`'`||i===`"`){let t=r+1;for(;t<e.length;)if(e[t]===i){if(e[t+1]===i)t+=2;else break}else t++;n+=e.slice(r,t+1),r=t+1}else{if(i===`$`){let t=/^\$[A-Za-z_]?[A-Za-z0-9_]*\$/.exec(e.slice(r,r+64))?.[0];if(t){let i=e.indexOf(t,r+t.length),a=i===-1?e.length:i+t.length;n+=e.slice(r,a),r=a;continue}}i===`;`?(n.trim()&&t.push(n.trim()),n=``,r++):(n+=i,r++)}}return n.trim()&&t.push(n.trim()),t.map(e=>e.replace(/\s+/g,` `))}function ew(e){let t=[],n=0,r=null,i=0;for(let a=0;a<e.length;a++){let o=e[a];r?o===r&&(r=null):o===`'`||o===`"`?r=o:o===`(`?n++:o===`)`?n--:o===`,`&&n===0&&(t.push(e.slice(i,a).trim()),i=a+1)}return t.push(e.slice(i).trim()),t.filter(Boolean)}function tw(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(/\s/.test(r)){n++;continue}if(r===`(`){let r=0,i=n,a=null;for(;i<e.length;i++){let t=e[i];if(a)t===a&&(a=null);else if(t===`'`||t===`"`)a=t;else if(t===`(`)r++;else if(t===`)`&&--r===0)break}t.push(e.slice(n,i+1)),n=i+1;continue}let i=n,a=null;for(;i<e.length;i++){let t=e[i];if(a)t===a&&(a=null);else if(t===`'`||t===`"`)a=t;else if(/\s/.test(t)||t===`(`)break}t.push(e.slice(n,i)),n=i}return t}const nw=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`,rw=String.raw`(${nw}(?:\s*\.\s*${nw})?)`;function iw(e){let t=e.trim();return t.startsWith(`"`)?t.slice(1,-1).replace(/""/g,`"`):t.toLowerCase()}function aw(e){let t=e.match(new RegExp(nw,`g`))??[e];return t.length>=2?{schema:iw(t[0]??``),table:iw(t[1]??``)}:{schema:`public`,table:iw(t[0]??e)}}function ow(e,t){return`${e}.${t}`}function sw(e,t,n,r){if(/^create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\b/i.test(e)){cw(e,t,n,r);return}let i=new RegExp(String.raw`^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${rw}\s+(.+)$`,`i`).exec(e);if(i?.[1]&&i[2]){hw(aw(i[1]),i[2],t,n,r);return}let a=/^drop\s+table\s+(?:if\s+exists\s+)?(.+?)(?:\s+(?:cascade|restrict))?$/i.exec(e);if(a?.[1])for(let e of ew(a[1])){let{schema:t,table:r}=aw(e);n.delete(ow(t,r))}}function cw(e,t,n,r){let i=new RegExp(String.raw`^create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?${rw}\s*\(`,`i`).exec(e);if(!i?.[1]){r.push(`${t}: skipped a create table statement it couldn't read: "${_w(e)}"`);return}let{schema:a,table:o}=aw(i[1]),s=i[0].length-1,c=lw(e,s);if(c===-1){r.push(`${t}: unbalanced parentheses in create table ${o}`);return}let l=ow(a,o);if(n.has(l)&&/\bif\s+not\s+exists\b/i.test(e.slice(0,s)))return;let u={schema:a,table:o,sourcePath:t,columns:[]};for(let i of ew(e.slice(s+1,c))){if(/^(constraint|primary\s+key|unique|foreign\s+key|check|exclude|like)\b/i.test(i)){mw(u,i,n);continue}let e=uw(i,n);e?u.columns.push(e):r.push(`${t}: skipped column definition "${_w(i)}" in ${o}`)}n.set(l,u)}function lw(e,t){let n=0,r=null;for(let i=t;i<e.length;i++){let t=e[i];if(r)t===r&&(r=null);else if(t===`'`||t===`"`)r=t;else if(t===`(`)n++;else if(t===`)`&&--n===0)return i}return-1}function uw(e,t){let n=tw(e),r=n[0];if(!r||n.length<2)return null;let i=1,a=[];for(;i<n.length&&!JC.test(n[i]??``);)a.push(n[i]),i++;if(a.length===0)return null;let o={name:iw(r),type:a.join(` `).replace(/\s+\(/g,`(`).toLowerCase(),required:!1};return dw(o,n.slice(i),t),o}function dw(e,t,n){for(let r=0;r<t.length;r++){let i=t[r]?.toLowerCase(),a=t[r+1]?.toLowerCase();if(i===`not`&&a===`null`)e.required=!0,r++;else if(i===`primary`&&a===`key`)e.primaryKey=!0,e.required=!0,r++;else if(i===`unique`)e.unique=!0;else if(i==="default"){let n=[];for(;r+1<t.length&&!JC.test(t[r+1]??``);)n.push(t[r+1]),r++;n.length>0&&(e.default=fw(n))}else if(i===`references`){let i=t[r+1];if(!i)continue;let a=t[r+2]?.startsWith(`(`)?t[r+2]:void 0;e.references=pw(i,a,n),r+=a?2:1}}}function fw(e){return e.join(` `).replace(/\s+\(/g,`(`)}function pw(e,t,n){let{schema:r,table:i}=aw(e),a=r===`public`?i:`${r}.${i}`,o=t?iw(t.slice(1,-1).split(`,`)[0]??``):null;return o||=n.get(ow(r,i))?.columns.find(e=>e.primaryKey)?.name??`id`,`${a}.${o}`}function mw(e,t,n){let r=t.replace(new RegExp(String.raw`^constraint\s+${nw}\s+`,`i`),``),i=e=>(e??``).split(`,`).map(e=>iw(e)).filter(Boolean),a=/^primary\s+key\s*\(([^)]*)\)/i.exec(r);if(a){for(let t of i(a[1])){let n=e.columns.find(e=>e.name===t);n&&(n.primaryKey=!0,n.required=!0)}return}let o=/^unique\s*(?:nulls\s+(?:not\s+)?distinct\s*)?\(([^)]*)\)/i.exec(r);if(o){let t=i(o[1]),n=t.length===1?e.columns.find(e=>e.name===t[0]):void 0;n&&(n.unique=!0);return}let s=new RegExp(String.raw`^foreign\s+key\s*\(([^)]*)\)\s*references\s+${rw}\s*(\([^)]*\))?`,`i`).exec(r);if(s?.[2]){let t=i(s[1]),r=s[3]?i(s[3].slice(1,-1)):[];t.forEach((t,i)=>{let a=e.columns.find(e=>e.name===t);if(!a)return;let o=r[i];a.references=pw(s[2],o?`(${o})`:void 0,n)})}}function hw(e,t,n,r,i){let a=r.get(ow(e.schema,e.table));if(!a){!qC.has(e.schema)&&/\b(add|drop|alter|rename)\s+column\b/i.test(t)&&i.push(`${n}: alter table ${e.table} before any create table for it, skipped`);return}let o=new RegExp(String.raw`^rename\s+to\s+(${nw})$`,`i`).exec(t);if(o?.[1]){r.delete(ow(a.schema,a.table)),a.table=iw(o[1]),r.set(ow(a.schema,a.table),a);return}let s=new RegExp(String.raw`^rename\s+(?:column\s+)?(${nw})\s+to\s+(${nw})$`,`i`).exec(t);if(s?.[1]&&s[2]){let e=a.columns.find(e=>e.name===iw(s[1]));e&&(e.name=iw(s[2]))}else for(let e of ew(t)){let t=/^add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?(.+)$/i.exec(e);if(t?.[1]&&!/^add\s+(constraint|primary|unique|foreign|check|exclude)\b/i.test(e)){let o=uw(t[1],r);if(!o){i.push(`${n}: skipped "${_w(e)}" on ${a.table}`);continue}a.columns.some(e=>e.name===o.name)||a.columns.push(o);continue}let o=/^add\s+(.+)$/i.exec(e);if(o?.[1]){mw(a,o[1],r);continue}let s=new RegExp(String.raw`^drop\s+(?:column\s+)?(?:if\s+exists\s+)?(${nw})`,`i`).exec(e);if(s?.[1]&&!/^drop\s+constraint\b/i.test(e)){let e=iw(s[1]);a.columns=a.columns.filter(t=>t.name!==e);continue}let c=new RegExp(String.raw`^alter\s+(?:column\s+)?(${nw})\s+(.+)$`,`i`).exec(e);if(c?.[1]&&c[2]){let e=a.columns.find(e=>e.name===iw(c[1]));e&&gw(e,c[2])}}}function gw(e,t){if(/^set\s+not\s+null$/i.test(t))e.required=!0;else if(/^drop\s+not\s+null$/i.test(t))e.required=!!e.primaryKey;else if(/^drop\s+default$/i.test(t))delete e.default;else{let n=/^set\s+default\s+(.+)$/i.exec(t);if(n?.[1]){e.default=fw(tw(n[1]));return}let r=/^(?:set\s+data\s+)?type\s+(.+?)(?:\s+(?:using|collate)\s+.*)?$/i.exec(t);r?.[1]&&(e.type=r[1].replace(/\s+\(/g,`(`).toLowerCase())}}function _w(e){return e.length>60?`${e.slice(0,57)}...`:e}const vw=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],yw=/^(openapi|swagger)([.-][\w.-]*)?\.(json|ya?ml)$/i,bw=/\.(json|ya?ml)$/i;async function xw(e){let t=[];for(let n of e.files){let r=yw.test(nx(n.path));if(!r&&!bw.test(n.path)||!r&&(n.size>1048576||/(^|\/)[^/]*lock[^/]*$/i.test(n.path)))continue;let i=await e.readText(n,r?10485760:void 0);if(i===null||!r&&!/^\s*["']?(openapi|swagger)["']?\s*:/m.test(i))continue;let a;try{a=/\.json$/i.test(n.path)?JSON.parse(i):(0,wC.parse)(i)}catch(t){e.warnings.push(`${n.path}: OpenAPI file could not be parsed (${ax(t)})`);continue}!Q(a)||typeof a.openapi!=`string`&&typeof a.swagger!=`string`?r&&e.warnings.push(`${n.path}: no top-level openapi or swagger version, skipped`):t.push(...Sw(a,n.path,e.warnings))}return t}function Sw(e,t,n){let r=typeof e.swagger==`string`,i=new Cw(e,t,n),a=r?e.securityDefinitions:Tw(e.components)?.securitySchemes,o=Q(a)?a:{},s=Q(e.paths)?e.paths:{},c=[];for(let[n,a]of Object.entries(s)){let s=i.resolve(a);if(s)for(let a of vw){let l=Tw(s[a.toLowerCase()]);if(!l)continue;let u=[...Array.isArray(s.parameters)?s.parameters:[],...Array.isArray(l.parameters)?l.parameters:[]],d=l.security??e.security;c.push({kind:`endpoint`,name:ox(l.summary)?.trim()||ox(l.operationId)||`${a} ${n}`,sourcePath:t,method:a,path:n,auth:zw(d,o,i),request:r?Aw(u,l,e,i):Dw(l.requestBody,i),responses:jw(l,e,r,i)})}}return c}var Cw=class{#e;#t;#n;#r=/* @__PURE__ */ new Set;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}resolve(e){let t=e;for(let e=0;e<8;e++){if(!Q(t))return null;let e=t.$ref;if(typeof e!=`string`)return t;t=this.#i(e)}return null}refName(e){if(!Q(e)||typeof e.$ref!=`string`)return null;let t=e.$ref.slice(e.$ref.lastIndexOf(`/`)+1);return t?ww(t):null}#i(e){if(!e.startsWith(`#/`))return this.#r.has(e)||(this.#r.add(e),this.#n.push(`${this.#t}: external $ref "${e}" not followed`)),null;let t=this.#e;for(let n of e.slice(2).split(`/`)){if(!Q(t))break;t=t[ww(n)]}return t===void 0&&!this.#r.has(e)&&(this.#r.add(e),this.#n.push(`${this.#t}: $ref "${e}" points at nothing`)),t}};function ww(e){return decodeURIComponent(e).replace(/~1/g,`/`).replace(/~0/g,`~`)}function Tw(e){return Q(e)?e:null}function Ew(e){if(!Q(e))return null;let t=Object.entries(e).filter(e=>Q(e[1]));return t.find(([e])=>e===`application/json`)??t.find(([e])=>/json/.test(e))??t[0]??null}function Dw(e,t){let n=t.resolve(e),r=n?Ew(n.content):null;return r?Ow(r[0],r[1],t):null}function Ow(e,t,n){let r=t.schema;return{contentType:e,fields:Fw(r,n),example:kw(t,n)??Rw(r,n,0)}}function kw(e,t){if(e.example!==void 0)return e.example;if(Q(e.examples)){let n=t.resolve(Object.values(e.examples)[0]);if(n&&n.value!==void 0)return n.value}}function Aw(e,t,n,r){let i=e.map(e=>r.resolve(e)).filter(e=>e!==null),a=Nw(t.consumes)??Nw(n.consumes),o=i.find(e=>e.in===`body`);if(o)return{contentType:a??`application/json`,fields:Fw(o.schema,r),example:Rw(o.schema,r,0)};let s=i.filter(e=>e.in===`formData`);if(s.length===0)return null;let c=s.map(e=>({name:ox(e.name)??``,type:Lw(e,r),required:e.required===!0,...Iw(e)}));return{contentType:a??`application/x-www-form-urlencoded`,fields:c,example:Object.fromEntries(s.map(e=>[ox(e.name)??``,Rw(e,r,1)]))}}function jw(e,t,n,r){if(!Q(e.responses))return[];let i=Nw(e.produces)??Nw(t.produces)??`application/json`,a=[];for(let[t,o]of Object.entries(e.responses)){let e=r.resolve(o);if(!e)continue;let s=null;if(n){if(e.schema!==void 0){let t=Tw(e.examples);s={contentType:i,fields:Fw(e.schema,r),example:t?.[i]??Rw(e.schema,r,0)}}}else{let t=Ew(e.content);t&&(s=Ow(t[0],t[1],r))}a.push({status:Mw(t),description:ox(e.description)??``,body:s})}return a}function Mw(e){let t=e.replace(/x/gi,`0`),n=Number.parseInt(t,10);return Number.isNaN(n)?0:n}function Nw(e){return Array.isArray(e)&&typeof e[0]==`string`?e[0]:void 0}function Pw(e,t,n=0){let r=t.resolve(e);if(!r||n>8)return r;if(Array.isArray(r.allOf)){let e={},i=[];for(let a of r.allOf){let r=Pw(a,t,n+1);r&&(Q(r.properties)&&Object.assign(e,r.properties),Array.isArray(r.required)&&i.push(...r.required.filter(e=>typeof e==`string`)))}return Q(r.properties)&&Object.assign(e,r.properties),Array.isArray(r.required)&&i.push(...r.required.filter(e=>typeof e==`string`)),{...r,type:`object`,properties:e,required:i}}let i=Array.isArray(r.oneOf)?r.oneOf:Array.isArray(r.anyOf)?r.anyOf:null;return i&&i.length>0&&!r.properties?Pw(i[0],t,n+1):r}function Fw(e,t){let n=Pw(e,t);if(n?.type===`array`&&(n=Pw(n.items,t)),!n||!Q(n.properties))return[];let r=new Set(Array.isArray(n.required)?n.required:[]);return Object.entries(n.properties).map(([e,n])=>{let i=Pw(n,t)??{};return{name:e,type:Lw(n,t),required:r.has(e),...Iw(i)}})}function Iw(e){let t={},n=ox(e.description)?.trim();return n&&(t.description=n),Array.isArray(e.enum)&&(t.values=e.enum.map(e=>String(e))),t}function Lw(e,t,n=0){let r=t.refName(e),i=Pw(e,t);if(!i)return r??`unknown`;let a=Array.isArray(i.type)?i.type.filter(e=>e!==`null`).join(` | `):ox(i.type);return a===`array`?n>8?`array`:`${Lw(i.items,t,n+1)}[]`:r&&(a===`object`||a===void 0)?r:ox(i.format)??a??(i.properties?`object`:`unknown`)}function Rw(e,t,n){let r=Pw(e,t);if(!r||n>8)return null;if(r.example!==void 0)return r.example;if(Array.isArray(r.enum)&&r.enum.length>0)return r.enum[0];let i=Array.isArray(r.type)?r.type.find(e=>e!==`null`):r.type;if(i===`object`||i===void 0&&Q(r.properties)){let e=Q(r.properties)?r.properties:{};return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Rw(r,t,n+1)]))}switch(i){case`array`:return[Rw(r.items,t,n+1)];case`string`:return`string`;case`integer`:case`number`:return 0;case`boolean`:return!1;default:return null}}function zw(e,t,n){if(!Array.isArray(e)||e.length===0)return null;let r=[];for(let i of e){if(!Q(i))continue;let e=Object.keys(i);e.length===0?r.push(`none`):r.push(e.map(e=>Bw(e,n.resolve(t[e]))).join(` + `))}let i=[...new Set(r)];return i.length===0||i.length===1&&i[0]===`none`?null:i.map(e=>e===`none`?`no auth`:e).join(` or `)}function Bw(e,t){if(!t)return e;switch(ox(t.type)?.toLowerCase()){case`http`:{let e=ox(t.scheme)?.toLowerCase();if(e===`bearer`){let e=ox(t.bearerFormat);return e?`Bearer token (${e})`:`Bearer token`}return e===`basic`?`Basic auth`:`HTTP ${e??`auth`}`}case`basic`:return`Basic auth`;case`apikey`:return`apikey ${ox(t.in)??`header`} ${ox(t.name)??e}`;case`oauth2`:return`OAuth2`;case`openidconnect`:return`OpenID Connect`;case`mutualtls`:return`Mutual TLS`;default:return e}}const Vw=[`readme.md`,`readme.mdx`,`readme.markdown`,`readme.txt`,`readme`];async function Hw(e){let t=e.files.find(e=>!e.path.includes(`/`)&&Vw.includes(e.path.toLowerCase()));if(!t)return null;let n=await e.readText(t);return{path:t.path,oneLiner:n===null?null:Uw(n)}}function Uw(e){let t=e.replace(/\r\n/g,`
|
|
339
341
|
`).replace(/^---\n[\s\S]*?\n---\n/,``).replace(/<!--[\s\S]*?-->/g,``).replace(/^(```|~~~)[\s\S]*?^\1.*$/gm,``);for(let e of t.split(/\n\s*\n/)){let t=e.split(`
|
|
340
|
-
`).map(e=>e.trim()).filter(Boolean),n=t[0];if(!n||/^(#|=+$|-+$|\||[-*+] |\d+\. |>|<|\[!\[|!\[)/.test(n)||/^ {4}|^\t/.test(e))continue;let r=Hw(t.join(` `));if(!(r.length<15||!/[a-z]/i.test(r)))return Uw(/^.+?[.!?](?=\s+["'([]?[A-Z]|\s*$)/.exec(r)?.[0]??r,200)}return null}function Hw(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,``).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]*)\]\[[^\]]*\]/g,`$1`).replace(/<[^>]+>/g,``).replace(/`([^`]*)`/g,`$1`).replace(/(\*\*|__)(.*?)\1/g,`$2`).replace(/(^|\W)[*_](\S(?:.*?\S)?)[*_](?=\W|$)/g,`$1$2`).replace(/\s+/g,` `).trim()}function Uw(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(` `);return`${(r>t/2?n.slice(0,r):n).trimEnd()}…`}const Ww={name:`Supabase`,type:`database`,provider:`Supabase Postgres`},Gw={name:`Postgres`,type:`database`,provider:`Postgres`},Kw={name:`MySQL`,type:`database`,provider:`MySQL`},qw={name:`MongoDB`,type:`database`,provider:`MongoDB`},Jw={name:`Redis`,type:`database`,provider:`Redis`},Yw={name:`Elasticsearch`,type:`database`,provider:`Elasticsearch`},Xw={name:`AWS S3`,type:`storage`,provider:`AWS S3`},Zw={name:`AWS SQS`,type:`queue`,provider:`AWS SQS`},Qw={name:`AWS`,type:`service`,provider:`AWS`},$w={name:`MinIO`,type:`storage`,provider:`MinIO`},eT={name:`Cloudinary`,type:`storage`,provider:`Cloudinary`},tT={name:`RabbitMQ`,type:`queue`,provider:`RabbitMQ`},nT={name:`Kafka`,type:`queue`,provider:`Kafka`},rT={name:`Stripe`,type:`external_api`,provider:`Stripe`},iT={name:`Twilio`,type:`external_api`,provider:`Twilio`},aT={name:`SendGrid`,type:`service`,provider:`SendGrid`},oT={name:`Postmark`,type:`service`,provider:`Postmark`},sT={name:`Resend`,type:`service`,provider:`Resend`},cT={name:`Mailgun`,type:`service`,provider:`Mailgun`},lT={name:`Email (SMTP)`,type:`service`,provider:`SMTP`},uT={name:`Firebase`,type:`service`,provider:`Firebase`},dT={name:`OpenAI`,type:`external_api`,provider:`OpenAI`},fT={name:`Anthropic`,type:`external_api`,provider:`Anthropic`},pT={name:`Sentry`,type:`service`,provider:`Sentry`},mT={name:`Auth0`,type:`auth`,provider:`Auth0`},hT={name:`Clerk`,type:`auth`,provider:`Clerk`},gT={name:`Auth.js`,type:`auth`,provider:`Auth.js`},_T={name:`Algolia`,type:`external_api`,provider:`Algolia`},vT=[[/^SUPABASE_/,Ww],[/^(DATABASE_URL|POSTGRES_|PG(HOST|USER|PASSWORD|DATABASE|PORT)$)/,Gw],[/^MYSQL_/,Kw],[/^MONGO(DB)?_/,qw],[/^(REDIS_|UPSTASH_REDIS_)/,Jw],[/^(ELASTIC(SEARCH)?_)/,Yw],[/^(AWS_)?S3_|_S3_BUCKET$|^AWS_BUCKET/,Xw],[/^(AWS_)?SQS_/,Zw],[/^AWS_(ACCESS_KEY_ID|SECRET_ACCESS_KEY|REGION|DEFAULT_REGION)$/,Qw],[/^MINIO_/,$w],[/^CLOUDINARY_/,eT],[/^(RABBITMQ_|AMQP_URL)/,tT],[/^KAFKA_/,nT],[/^STRIPE_/,rT],[/^TWILIO_/,iT],[/^SENDGRID_/,aT],[/^POSTMARK_/,oT],[/^RESEND_/,sT],[/^MAILGUN_/,cT],[/^SMTP_/,lT],[/^FIREBASE_/,uT],[/^OPENAI_/,dT],[/^ANTHROPIC_/,fT],[/^SENTRY_/,pT],[/^AUTH0_/,mT],[/^CLERK_/,hT],[/^(NEXTAUTH_|AUTH_SECRET$)/,gT],[/^ALGOLIA_/,_T]],yT=[[[`@supabase/supabase-js`,`@supabase/ssr`,`supabase`,`github.com/supabase-community/*`,`supabase/supabase-php`],Ww],[[`pg`,`postgres`,`pg-promise`,`@neondatabase/serverless`,`@vercel/postgres`,`psycopg2`,`psycopg2-binary`,`psycopg`,`asyncpg`,`github.com/jackc/pgx*`,`github.com/lib/pq`],Gw],[[`mysql`,`mysql2`,`pymysql`,`mysqlclient`,`github.com/go-sql-driver/mysql`],Kw],[[`mongodb`,`mongoose`,`pymongo`,`motor`,`go.mongodb.org/mongo-driver*`,`mongodb/mongodb`],qw],[[`redis`,`ioredis`,`@upstash/redis`,`predis/predis`,`github.com/redis/go-redis*`,`github.com/go-redis/redis*`],Jw],[[`@elastic/elasticsearch`,`elasticsearch`,`elasticsearch/elasticsearch`],Yw],[[`@aws-sdk/client-s3`,`github.com/aws/aws-sdk-go-v2/service/s3`,`league/flysystem-aws-s3-v3`],Xw],[[`@aws-sdk/client-sqs`,`github.com/aws/aws-sdk-go-v2/service/sqs`],Zw],[[`aws-sdk`,`boto3`,`aws/aws-sdk-php`,`github.com/aws/aws-sdk-go`],Qw],[[`minio`],$w],[[`cloudinary`,`cloudinary/cloudinary_php`],eT],[[`amqplib`,`pika`,`php-amqplib/php-amqplib`,`github.com/rabbitmq/amqp091-go`],tT],[[`kafkajs`,`kafka-python`,`confluent-kafka`,`github.com/segmentio/kafka-go`],nT],[[`stripe`,`@stripe/stripe-js`,`@stripe/react-stripe-js`,`stripe/stripe-php`,`github.com/stripe/stripe-go*`],rT],[[`twilio`,`twilio/sdk`,`github.com/twilio/twilio-go`],iT],[[`@sendgrid/`,`sendgrid`,`sendgrid/sendgrid`],aT],[[`postmark`,`wildbit/postmark-php`],oT],[[`resend`,`resend/resend-php`],sT],[[`mailgun.js`,`mailgun/mailgun-php`],cT],[[`nodemailer`],lT],[[`firebase`,`firebase-admin`,`kreait/firebase-php`,`firebase.google.com/go*`],uT],[[`openai`,`openai-php/client`,`github.com/sashabaranov/go-openai`],dT],[[`@anthropic-ai/sdk`,`anthropic`,`github.com/anthropics/anthropic-sdk-go`],fT],[[`@sentry/`,`sentry-sdk`,`sentry/sentry`,`sentry/sentry-laravel`,`github.com/getsentry/sentry-go`],pT],[[`@auth0/`,`auth0`,`auth0/auth0-php`],mT],[[`@clerk/`],hT],[[`next-auth`,`@auth/`],gT],[[`algoliasearch`,`algolia/algoliasearch-client-php`],_T]],bT=[[/^supabase\//,Ww],[/(^|\/)(postgres|postgis|timescaledb)$/,Gw],[/(^|\/)(mysql|mariadb)$/,Kw],[/(^|\/)mongo(db)?$/,qw],[/(^|\/)(redis|redis-stack|valkey)$/,Jw],[/(^|\/)(elasticsearch|opensearch)$/,Yw],[/(^|\/)minio$/,$w],[/(^|\/)rabbitmq$/,tT],[/(^|\/)(kafka|cp-kafka)$/,nT],[/(^|\/)localstack$/,Qw]];function xT(e){return/^\.env(\.[\w-]+)*\.(example|sample|template|dist)$/i.test(e)||/^(example|sample)\.env$/i.test(e)}function ST(e){return/^(docker-)?compose([.-][\w.-]+)?\.ya?ml$/i.test(e)}var CT=class{#e=/* @__PURE__ */ new Map;add(e,t){let n=this.#e.get(e.provider);n?n.evidence.includes(t)||n.evidence.push(t):this.#e.set(e.provider,{...e,evidence:[t]})}list(){return[...this.#e.values()].sort((e,t)=>e.name.localeCompare(t.name))}};async function wT(e,t){let n=new CT;for(let t of e.files){let r=rx(t.path);if(xT(r)){let r=await e.readText(t);if(r===null)continue;for(let e of TT(r)){let r=e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|NUXT_)/,``),i=vT.find(([e])=>e.test(r));i&&n.add(i[1],`env: ${e} (${t.path})`)}}else if(ST(r)){let r=await e.readText(t);if(r===null)continue;let i;try{i=(0,wC.parse)(r)}catch(n){e.warnings.push(`${t.path}: could not be parsed (${ox(n)})`);continue}let a=Q(i)&&Q(i.services)?i.services:{};for(let[e,r]of Object.entries(a)){if(!Q(r)||typeof r.image!=`string`)continue;let i=ET(r.image),a=bT.find(([e])=>e.test(i));a&&n.add(a[1],`docker-compose: service ${e} (${r.image}) in ${t.path}`)}}else(t.path===`supabase/config.toml`||t.path.endsWith(`/supabase/config.toml`))&&n.add(Ww,`file: ${t.path}`)}for(let e of t){if(!e.direct)continue;let t=yT.find(([t])=>t.some(t=>DT(t,e.package)));t&&n.add(t[1],`dependency: ${e.package} (${e.sourceLockfile})`)}return n.list()}function TT(e){let t=[];for(let n of e.split(/\r?\n/)){let e=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(n);e?.[1]&&t.push(e[1])}return t}function ET(e){let t=e.toLowerCase().replace(/@.*$/,``),n=t.lastIndexOf(`/`),r=t.indexOf(`:`,n+1);r!==-1&&(t=t.slice(0,r));let i=t.split(`/`);return i.length>1&&/[.:]|^localhost$/.test(i[0]??``)&&i.shift(),i[0]===`library`&&i.shift(),i.join(`/`)}function DT(e,t){return e.endsWith(`*`)?t.startsWith(e.slice(0,-1)):e.endsWith(`/`)?t.startsWith(e):t===e}async function OT(e){let t=_.resolve(e);if(!(await p(t)).isDirectory())throw Error(`${t} is not a folder`);let n=(/* @__PURE__ */ new Date()).toISOString(),r=await ex(t),i=[],[a,o,s,c,l,u,d]=await Promise.all([UC(t,i),Bw(r),zC(r),Gx(r),Qx(r),yw(r),XC(r)]),f=await wT(r,s);return{scannedAt:n,root:t,repo:{...a,languages:KC(r.files),readme:o},dependencies:s,docs:c,agentInstructions:l,contracts:[...u,...d],resources:f,warnings:[...i,...r.warnings]}}function kT(e){let t=(e,t,n=`${t}s`)=>e?`${e} ${e===1?t:n}`:``;return[t(e.docs,`doc`)+(e.docsChanged&&e.docsChanged<e.docs?` (${e.docsChanged} changed)`:``),t(e.dependencies,`dependency`,`dependencies`),t(e.contracts,`contract`),t(e.resources,`service`)].filter(Boolean).join(` · `)||`nothing to import yet`}async function AT(e,t,{quiet:n=!1,source:r=`connector`}={}){let i=await OT(e),a=await new Ur(await Kb()).call(`sync_repo`,{p_project:t.projectId,p_snapshot:i,p_source:r});if(!n){_x(`Synced ${fx(i.repo.name)} to ${fx(t.name)}`),vx(px(kT(a)));for(let e of i.warnings)vx(px(`! ${e}`))}return{snapshot:i,result:a}}async function jT(e){return tS(await ex(e))}async function MT(e,t,{quiet:n=!1}={}){if(!t.folder)return;let{docs:r,unsupported:i}=await jT(e),a=await new Ur(await Kb()).call(`sync_folder`,{p_project:t.projectId,p_folder:t.folder,p_folder_name:v(e),p_docs:r});return n||(_x(`Synced the documents in ${fx(`${v(e)}/`)} outside the repos`),vx(px(`${a.docs} docs (${a.docsChanged} changed${a.archived?`, ${a.archived} removed`:``})`)),i.length&&vx(px(`! ${i.length} PDF/Office files skipped: only markdown and text are read for now`))),a}async function NT(e={}){let t=await Yb();if(!t)throw new Sx("This folder isn't linked to a Quirl project. Run `quirl init`.");let n=t.link.repos?.length?t.link.repos.map(e=>x(t.root,e)):[t.root],r=n.length+ +!!t.link.folder,i=0;for(let a of n)try{await AT(a,t.link,e)}catch(e){if(i++,r===1)throw e;let n=S(t.root,a)||`.`;console.error(`${hx(`✗`)} ${n}: ${e.message}`)}if(t.link.folder)try{await MT(t.root,t.link,e)}catch(e){i++,console.error(`${hx(`✗`)} documents in ${v(t.root)}/: ${e.message}`)}if(i)throw new Sx(`${i} of ${r} parts didn't sync.`)}async function PT(e){let t=qb(),n=await lx(t),r=n.length?n:[t],i=r.length>1||r[0]!==t,a=e=>S(t,e)||v(t),o=h(),s=t.startsWith(o)?`~${t.slice(o.length)}`:t;if(console.log(`\n🌀 ${fx(`Quirl`)} ${px(`·`)} connecting ${fx(s)}`),i&&(yx(`📁`,`Found ${r.length} ${r.length===1?`repo`:`repos`}`),bx(px(r.map(a).join(` · `))),!await wx(` Import all of them into one project?`,!0)))throw new Sx("Nothing imported. Run `quirl init` inside the repo you want instead.");let c=!1;if(i&&!n.includes(t)){let{docs:e,unsupported:n}=await jT(t);if(e.length){yx(`📄`,`Also found ${e.length} ${e.length===1?`document`:`documents`} outside the repos`);for(let t of e.slice(0,8))bx(px(t.path));e.length>8&&bx(px(`…and ${e.length-8} more`)),n.length&&bx(px(`(${n.length} PDF/Office files can't be read yet and are skipped)`)),c=await wx(` Import them too? Everyone on the project will be able to read them.`,!0)}}await Ub()||await zx({quiet:!0});let l=await IT((await new Ur(await Kb()).whoami()).projects,e.project??(await Yb(t))?.link.project);if(l.role===`stakeholder`)throw new Sx(`You're a stakeholder on ${l.name}; ask an admin or dev to run \`quirl init\`.`);let u={project:l.slug,projectId:l.id,name:l.name};yx(`🔗`,`Linked to ${fx(l.name)} ${px(`· ${l.organization}`)}`);let d=e.claude!==!1,f=e.hooks??await wx(` Sync with Quirl on every git push?`,!0);yx(`📦`,`Importing docs, dependencies and schemas`);let p=[];for(let e of r){let t=xx(`Reading ${a(e)}…`);try{await Xb(e,u);let{snapshot:n,result:r}=await AT(e,u,{quiet:!0});d&&await FT(e,l.name),f&&await Rx(e),t.stop(),bx(`${mx(`✓`)} ${fx(a(e))} ${px(kT(r))}`);for(let e of n.warnings)bx(px(` ! ${e}`));p.push(e)}catch(n){t.stop(),bx(`${hx(`✗`)} ${fx(a(e))} ${n.message}`)}}if(!p.length)throw new Sx(`No repo was imported.`);if(i){let e=p.map(a),n=await Yb(t),r={...u,repos:e,folder:c?n?.root===t&&n.link.folder||w():void 0};if(await Xb(t,r),c)try{let e=await MT(t,r,{quiet:!0});bx(`${mx(`✓`)} ${fx(`documents outside the repos`)} ${px(`${e?.docs??0} docs`)}`)}catch(e){bx(`${hx(`✗`)} ${fx(`documents outside the repos`)} ${e.message}`)}d&&!p.includes(t)&&await FT(t,l.name,e)}let m=kx().portable;d&&(yx(`🤖`,`Connected Claude Code`),bx(px(`.mcp.json the quirl tools`)),bx(px(`.claude/settings.json the briefing, loaded as each session starts`)),bx(px(`CLAUDE.md when to use Quirl`))),f&&yx(`🪝`,`Quirl syncs on every ${fx(`git push`)}`);let g=r.length-p.length,_=`.quirl .mcp.json .claude/settings.json CLAUDE.md`;yx(g?`⚠️ `:`🎉`,g?`Done, but ${g} of ${r.length} repos failed. Fix them and run ${fx(`quirl init`)} again.`:fx(`All set!`)),bx(d&&!m?px(`Don't commit ${_} yet: they point at this checkout until the CLI is installed.`):`${px(`1.`)} Commit what was added${i?` in each repo`:``}: ${gx(`git add ${_}`)}`),bx(`${px(d&&!m?`→`:`2.`)} Start Claude Code here and approve the ${fx(`quirl`)} server when it asks.`),i&&!p.includes(t)&&bx(px("Run `quirl sync` here to sync every repo at once.")),console.log(``)}async function FT(e,t,n=[]){await Fx(e),await Ix(e),await Lx(e,t,n)}async function IT(e,t){if(!e.length)throw new Sx(`You aren't on any Quirl project yet. Ask an admin to invite you.`);if(t){let n=e.find(e=>e.slug===t||e.id===t);if(!n)throw new Sx(`No project "${t}" among yours: ${e.map(e=>e.slug).join(`, `)}.`);return n}if(e.length===1)return e[0];yx(`🗂️ `,`Which project is this part of?`);for(let[t,n]of e.entries())bx(`${gx(String(t+1))} ${n.name} ${px(`· ${n.organization} · ${n.role}`)}`);let n=e[Number(await Cx(` Project [1-${e.length}]: `))-1];if(!n)throw new Sx("No project picked. Run `quirl init --project <slug>`.");return n}const LT=`${fx(`quirl`)} ${px(Lb)}: connect a repo to Quirl
|
|
342
|
+
`).map(e=>e.trim()).filter(Boolean),n=t[0];if(!n||/^(#|=+$|-+$|\||[-*+] |\d+\. |>|<|\[!\[|!\[)/.test(n)||/^ {4}|^\t/.test(e))continue;let r=Ww(t.join(` `));if(!(r.length<15||!/[a-z]/i.test(r)))return Gw(/^.+?[.!?](?=\s+["'([]?[A-Z]|\s*$)/.exec(r)?.[0]??r,200)}return null}function Ww(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,``).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]*)\]\[[^\]]*\]/g,`$1`).replace(/<[^>]+>/g,``).replace(/`([^`]*)`/g,`$1`).replace(/(\*\*|__)(.*?)\1/g,`$2`).replace(/(^|\W)[*_](\S(?:.*?\S)?)[*_](?=\W|$)/g,`$1$2`).replace(/\s+/g,` `).trim()}function Gw(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(` `);return`${(r>t/2?n.slice(0,r):n).trimEnd()}…`}const Kw={name:`Supabase`,type:`database`,provider:`Supabase Postgres`},qw={name:`Postgres`,type:`database`,provider:`Postgres`},Jw={name:`MySQL`,type:`database`,provider:`MySQL`},Yw={name:`MongoDB`,type:`database`,provider:`MongoDB`},Xw={name:`Redis`,type:`database`,provider:`Redis`},Zw={name:`Elasticsearch`,type:`database`,provider:`Elasticsearch`},Qw={name:`AWS S3`,type:`storage`,provider:`AWS S3`},$w={name:`AWS SQS`,type:`queue`,provider:`AWS SQS`},eT={name:`AWS`,type:`service`,provider:`AWS`},tT={name:`MinIO`,type:`storage`,provider:`MinIO`},nT={name:`Cloudinary`,type:`storage`,provider:`Cloudinary`},rT={name:`RabbitMQ`,type:`queue`,provider:`RabbitMQ`},iT={name:`Kafka`,type:`queue`,provider:`Kafka`},aT={name:`Stripe`,type:`external_api`,provider:`Stripe`},oT={name:`Twilio`,type:`external_api`,provider:`Twilio`},sT={name:`SendGrid`,type:`service`,provider:`SendGrid`},cT={name:`Postmark`,type:`service`,provider:`Postmark`},lT={name:`Resend`,type:`service`,provider:`Resend`},uT={name:`Mailgun`,type:`service`,provider:`Mailgun`},dT={name:`Email (SMTP)`,type:`service`,provider:`SMTP`},fT={name:`Firebase`,type:`service`,provider:`Firebase`},pT={name:`OpenAI`,type:`external_api`,provider:`OpenAI`},mT={name:`Anthropic`,type:`external_api`,provider:`Anthropic`},hT={name:`Sentry`,type:`service`,provider:`Sentry`},gT={name:`Auth0`,type:`auth`,provider:`Auth0`},_T={name:`Clerk`,type:`auth`,provider:`Clerk`},vT={name:`Auth.js`,type:`auth`,provider:`Auth.js`},yT={name:`Algolia`,type:`external_api`,provider:`Algolia`},bT={name:`Google Cloud`,type:`service`,provider:`Google Cloud`},xT={name:`Cloud Storage`,type:`storage`,provider:`Google Cloud Storage`},ST={name:`Pub/Sub`,type:`queue`,provider:`Google Cloud Pub/Sub`},CT={name:`BigQuery`,type:`database`,provider:`Google BigQuery`},wT={name:`Firestore`,type:`database`,provider:`Google Firestore`},TT={name:`Secret Manager`,type:`service`,provider:`Google Secret Manager`},ET={name:`Gemini`,type:`external_api`,provider:`Google Gemini`},DT={name:`Vertex AI`,type:`external_api`,provider:`Google Vertex AI`},OT={name:`SerpApi`,type:`external_api`,provider:`SerpApi`},kT={name:`Zyte`,type:`external_api`,provider:`Zyte`},AT={name:`Open Exchange Rates`,type:`external_api`,provider:`Open Exchange Rates`},jT={name:`reCAPTCHA`,type:`external_api`,provider:`Google reCAPTCHA`},MT={name:`DuckDB`,type:`database`,provider:`DuckDB`},NT=[[/^SUPABASE_/,Kw],[/^(DATABASE_URL|POSTGRES_|PG(HOST|USER|PASSWORD|DATABASE|PORT)$)/,qw],[/^MYSQL_/,Jw],[/^MONGO(DB)?_/,Yw],[/^(REDIS_|UPSTASH_REDIS_)/,Xw],[/^(ELASTIC(SEARCH)?_)/,Zw],[/^(AWS_)?S3_|_S3_BUCKET$|^AWS_BUCKET/,Qw],[/^(AWS_)?SQS_/,$w],[/^AWS_(ACCESS_KEY_ID|SECRET_ACCESS_KEY|REGION|DEFAULT_REGION)$/,eT],[/^MINIO_/,tT],[/^CLOUDINARY_/,nT],[/^(RABBITMQ_|AMQP_URL)/,rT],[/^KAFKA_/,iT],[/^STRIPE_/,aT],[/^TWILIO_/,oT],[/^SENDGRID_/,sT],[/^POSTMARK_/,cT],[/^RESEND_/,lT],[/^MAILGUN_/,uT],[/^SMTP_/,dT],[/^FIREBASE_/,fT],[/^OPENAI_/,pT],[/^ANTHROPIC_/,mT],[/^SENTRY_/,hT],[/^AUTH0_/,gT],[/^CLERK_/,_T],[/^(NEXTAUTH_|AUTH_SECRET$)/,vT],[/^ALGOLIA_/,yT],[/^(GCS_BUCKET|GOOGLE_CLOUD_STORAGE_|GCS_)/,xT],[/^(PUBSUB_|GOOGLE_PUBSUB_)/,ST],[/^BIGQUERY_/,CT],[/^FIRESTORE_/,wT],[/^(GEMINI_|GOOGLE_GENAI_)/,ET],[/^VERTEX(_AI)?_/,DT],[/^(SERPAPI_|SERP_API_)/,OT],[/^ZYTE_/,kT],[/^(OPEN_EXCHANGE_RATES_|OPENEXCHANGERATES_|OXR_)/,AT],[/^RECAPTCHA_/,jT],[/^(GOOGLE_CLOUD_PROJECT|GCP_PROJECT(_ID)?|GCLOUD_PROJECT|GOOGLE_APPLICATION_CREDENTIALS)$/,bT]],PT=[[[`@supabase/supabase-js`,`@supabase/ssr`,`supabase`,`github.com/supabase-community/*`,`supabase/supabase-php`],Kw],[[`pg`,`postgres`,`pg-promise`,`@neondatabase/serverless`,`@vercel/postgres`,`psycopg2`,`psycopg2-binary`,`psycopg`,`asyncpg`,`github.com/jackc/pgx*`,`github.com/lib/pq`],qw],[[`mysql`,`mysql2`,`pymysql`,`mysqlclient`,`github.com/go-sql-driver/mysql`],Jw],[[`mongodb`,`mongoose`,`pymongo`,`motor`,`go.mongodb.org/mongo-driver*`,`mongodb/mongodb`],Yw],[[`redis`,`ioredis`,`@upstash/redis`,`predis/predis`,`github.com/redis/go-redis*`,`github.com/go-redis/redis*`],Xw],[[`@elastic/elasticsearch`,`elasticsearch`,`elasticsearch/elasticsearch`],Zw],[[`@aws-sdk/client-s3`,`github.com/aws/aws-sdk-go-v2/service/s3`,`league/flysystem-aws-s3-v3`],Qw],[[`@aws-sdk/client-sqs`,`github.com/aws/aws-sdk-go-v2/service/sqs`],$w],[[`aws-sdk`,`boto3`,`aws/aws-sdk-php`,`github.com/aws/aws-sdk-go`],eT],[[`minio`],tT],[[`cloudinary`,`cloudinary/cloudinary_php`],nT],[[`amqplib`,`pika`,`php-amqplib/php-amqplib`,`github.com/rabbitmq/amqp091-go`],rT],[[`kafkajs`,`kafka-python`,`confluent-kafka`,`github.com/segmentio/kafka-go`],iT],[[`stripe`,`@stripe/stripe-js`,`@stripe/react-stripe-js`,`stripe/stripe-php`,`github.com/stripe/stripe-go*`],aT],[[`twilio`,`twilio/sdk`,`github.com/twilio/twilio-go`],oT],[[`@sendgrid/`,`sendgrid`,`sendgrid/sendgrid`],sT],[[`postmark`,`wildbit/postmark-php`],cT],[[`resend`,`resend/resend-php`],lT],[[`mailgun.js`,`mailgun/mailgun-php`],uT],[[`nodemailer`],dT],[[`firebase`,`firebase-admin`,`firebase-functions`,`kreait/firebase-php`,`firebase.google.com/go*`],fT],[[`openai`,`openai-php/client`,`github.com/sashabaranov/go-openai`],pT],[[`@anthropic-ai/sdk`,`anthropic`,`github.com/anthropics/anthropic-sdk-go`],mT],[[`@sentry/`,`sentry-sdk`,`sentry/sentry`,`sentry/sentry-laravel`,`github.com/getsentry/sentry-go`],hT],[[`@auth0/`,`auth0`,`auth0/auth0-php`],gT],[[`@clerk/`],_T],[[`next-auth`,`@auth/`],vT],[[`algoliasearch`,`algolia/algoliasearch-client-php`],yT],[[`@google-cloud/storage`,`google-cloud-storage`,`cloud.google.com/go/storage`],xT],[[`@google-cloud/pubsub`,`google-cloud-pubsub`,`cloud.google.com/go/pubsub*`],ST],[[`@google-cloud/bigquery`,`google-cloud-bigquery`,`cloud.google.com/go/bigquery`],CT],[[`@google-cloud/firestore`,`google-cloud-firestore`,`cloud.google.com/go/firestore`],wT],[[`@google-cloud/secret-manager`,`google-cloud-secret-manager`,`cloud.google.com/go/secretmanager`],TT],[[`@google/genai`,`@google/generative-ai`,`google-genai`,`google-generativeai`],ET],[[`@google-cloud/vertexai`,`google-cloud-aiplatform`,`vertexai`],DT],[[`serpapi`,`google-search-results`],OT],[[`zyte-api`,`scrapy-zyte-api`],kT],[[`open-exchange-rates`],AT],[[`react-google-recaptcha`,`react-google-recaptcha-v3`,`vue-recaptcha`,`vue-recaptcha-v3`,`@google-cloud/recaptcha-enterprise`,`google-cloud-recaptcha-enterprise`,`django-recaptcha`],jT],[[`@google-cloud/`,`google-cloud-*`,`google-auth-library`,`google-auth`,`cloud.google.com/go*`],bT],[[`duckdb`,`@duckdb/`],MT]],FT=[[/^supabase\//,Kw],[/(^|\/)(postgres|postgis|timescaledb)$/,qw],[/(^|\/)(mysql|mariadb)$/,Jw],[/(^|\/)mongo(db)?$/,Yw],[/(^|\/)(redis|redis-stack|valkey)$/,Xw],[/(^|\/)(elasticsearch|opensearch)$/,Zw],[/(^|\/)minio$/,tT],[/(^|\/)rabbitmq$/,rT],[/(^|\/)(kafka|cp-kafka)$/,iT],[/(^|\/)localstack$/,eT],[/(^|\/)(cloud-sdk|google-cloud-cli)$/,bT],[/(^|\/)(gcloud-pubsub-emulator|pubsub-emulator)$/,ST],[/(^|\/)fake-gcs-server$/,xT]];function IT(e){return/^\.env(\.[\w-]+)*\.(example|sample|template|dist)$/i.test(e)||/^(example|sample)\.env$/i.test(e)}function LT(e){let t=nx(e);return/^\.gitlab-ci\.ya?ml$/.test(t)||/^cloudbuild\.ya?ml$/.test(t)||t===`bitbucket-pipelines.yml`||/(^|\/)\.github\/workflows\/[^/]+\.ya?ml$/.test(e)}function RT(e){return[...new Set(e.match(/\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b/g)??[])]}function zT(e){return/^(docker-)?compose([.-][\w.-]+)?\.ya?ml$/i.test(e)}var BT=class{#e=/* @__PURE__ */ new Map;add(e,t){let n=this.#e.get(e.provider);n?n.evidence.includes(t)||n.evidence.push(t):this.#e.set(e.provider,{...e,evidence:[t]})}list(){return[...this.#e.values()].sort((e,t)=>e.name.localeCompare(t.name))}};async function VT(e,t){let n=new BT,r=(e,t)=>{let r=e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|NUXT_)/,``),i=NT.find(([e])=>e.test(r));i&&n.add(i[1],t)};for(let t of e.files){let i=nx(t.path);if(IT(i)){let n=await e.readText(t);if(n===null)continue;for(let e of HT(n))r(e,`env: ${e} (${t.path})`)}else if(LT(t.path)){let n=await e.readText(t);if(n===null)continue;for(let e of RT(n))r(e,`pipeline: ${e} (${t.path})`)}else if(zT(i)){let i=await e.readText(t);if(i===null)continue;let a;try{a=(0,wC.parse)(i)}catch(n){e.warnings.push(`${t.path}: could not be parsed (${ax(n)})`);continue}let o=Q(a)&&Q(a.services)?a.services:{};for(let[e,i]of Object.entries(o)){if(!Q(i))continue;let a=i.environment,o=Array.isArray(a)?a.map(e=>String(e).split(`=`,1)[0]??``):Q(a)?Object.keys(a):[];for(let n of o)r(n,`docker-compose: ${e} env ${n} in ${t.path}`);if(typeof i.image!=`string`)continue;let s=UT(i.image),c=FT.find(([e])=>e.test(s));c&&n.add(c[1],`docker-compose: service ${e} (${i.image}) in ${t.path}`)}}else t.path===`supabase/config.toml`||t.path.endsWith(`/supabase/config.toml`)?n.add(Kw,`file: ${t.path}`):i===`firebase.json`?n.add(fT,`file: ${t.path}`):/^cloudbuild\.ya?ml$/.test(i)&&n.add(bT,`file: ${t.path}`)}for(let e of t){if(!e.direct)continue;let t=PT.find(([t])=>t.some(t=>WT(t,e.package)));t&&n.add(t[1],`dependency: ${e.package} (${e.sourceLockfile})`)}return n.list()}function HT(e){let t=[];for(let n of e.split(/\r?\n/)){let e=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(n);e?.[1]&&t.push(e[1])}return t}function UT(e){let t=e.toLowerCase().replace(/@.*$/,``),n=t.lastIndexOf(`/`),r=t.indexOf(`:`,n+1);r!==-1&&(t=t.slice(0,r));let i=t.split(`/`);return i.length>1&&/[.:]|^localhost$/.test(i[0]??``)&&i.shift(),i[0]===`library`&&i.shift(),i.join(`/`)}function WT(e,t){return e.endsWith(`*`)?t.startsWith(e.slice(0,-1)):e.endsWith(`/`)?t.startsWith(e):t===e}async function GT(e){let t=_.resolve(e);if(!(await p(t)).isDirectory())throw Error(`${t} is not a folder`);let n=(/* @__PURE__ */ new Date()).toISOString(),r=await $b(t),i=[],[a,o,s,c,l,u,d]=await Promise.all([UC(t,i),Hw(r),zC(r),Gx(r),Qx(r),xw(r),QC(r)]),f=await VT(r,s);return{scannedAt:n,root:t,repo:{...a,languages:KC(r.files),readme:o},dependencies:s,docs:c,agentInstructions:l,contracts:[...u,...d],resources:f,warnings:[...i,...r.warnings]}}function KT(e){let t=(e,t,n=`${t}s`)=>e?`${e} ${e===1?t:n}`:``;return[t(e.docs,`doc`)+(e.docsChanged&&e.docsChanged<e.docs?` (${e.docsChanged} changed)`:``),t(e.dependencies,`dependency`,`dependencies`),t(e.contracts,`contract`),t(e.resources,`service`)].filter(Boolean).join(` · `)||`nothing to import yet`}async function qT(e,t,{quiet:n=!1,source:r=`connector`}={}){let i=await GT(e),a=await new Ur(await Kb()).call(`sync_repo`,{p_project:t.projectId,p_snapshot:i,p_source:r});if(!n){_x(`Synced ${fx(i.repo.name)} to ${fx(t.name)}`),vx(px(KT(a)));for(let e of i.warnings)vx(px(`! ${e}`))}return{snapshot:i,result:a}}async function JT(e){return tS(await $b(e))}async function YT(e,t,{quiet:n=!1}={}){if(!t.folder)return;let{docs:r,unsupported:i}=await JT(e),a=await new Ur(await Kb()).call(`sync_folder`,{p_project:t.projectId,p_folder:t.folder,p_folder_name:v(e),p_docs:r});return n||(_x(`Synced the documents in ${fx(`${v(e)}/`)} outside the repos`),vx(px(`${a.docs} docs (${a.docsChanged} changed${a.archived?`, ${a.archived} removed`:``})`)),i.length&&vx(px(`! ${i.length} PDF/Office files skipped: only markdown and text are read for now`))),a}async function XT(e={}){let t=await Yb();if(!t)throw new Sx("This folder isn't linked to a Quirl project. Run `quirl init`.");let n=t.link.repos?.length?t.link.repos.map(e=>x(t.root,e)):[t.root],r=n.length+ +!!t.link.folder,i=0;for(let a of n)try{await qT(a,t.link,e)}catch(e){if(i++,r===1)throw e;let n=S(t.root,a)||`.`;console.error(`${hx(`✗`)} ${n}: ${ax(e)}`)}if(t.link.folder)try{await YT(t.root,t.link,e)}catch(e){i++,console.error(`${hx(`✗`)} documents in ${v(t.root)}/: ${ax(e)}`)}if(i)throw new Sx(`${i} of ${r} parts didn't sync.`)}async function ZT(e){let t=qb(),n=await lx(t),r=n.length?n:[t],i=r.length>1||r[0]!==t,a=e=>S(t,e)||v(t),o=h(),s=t.startsWith(o)?`~${t.slice(o.length)}`:t;if(console.log(`\n🌀 ${fx(`Quirl`)} ${px(`·`)} connecting ${fx(s)}`),i&&(yx(`📁`,`Found ${r.length} ${r.length===1?`repo`:`repos`}`),bx(px(r.map(a).join(` · `))),!await wx(` Import all of them into one project?`,!0)))throw new Sx("Nothing imported. Run `quirl init` inside the repo you want instead.");let c=!1;if(i&&!n.includes(t)){let{docs:e,unsupported:n}=await JT(t);if(e.length){yx(`📄`,`Also found ${e.length} ${e.length===1?`document`:`documents`} outside the repos`);for(let t of e.slice(0,8))bx(px(t.path));e.length>8&&bx(px(`…and ${e.length-8} more`)),n.length&&bx(px(`(${n.length} PDF/Office files can't be read yet and are skipped)`)),c=await wx(` Import them too? Everyone on the project will be able to read them.`,!0)}}await Ub()||await zx({quiet:!0});let l=await $T((await new Ur(await Kb()).whoami()).projects,e.project??(await Yb(t))?.link.project);if(l.role===`stakeholder`)throw new Sx(`You're a stakeholder on ${l.name}; ask an admin or dev to run \`quirl init\`.`);let u={project:l.slug,projectId:l.id,name:l.name};yx(`🔗`,`Linked to ${fx(l.name)} ${px(`· ${l.organization}`)}`);let d=e.claude!==!1,f=e.hooks??await wx(` Sync with Quirl on every git push?`,!0);yx(`📦`,`Importing docs, dependencies and schemas`);let p=[];for(let e of r){let t=xx(`Reading ${a(e)}…`);try{await Xb(e,u);let{snapshot:n,result:r}=await qT(e,u,{quiet:!0});d&&await QT(e,l.name),f&&await Rx(e),t.stop(),bx(`${mx(`✓`)} ${fx(a(e))} ${px(KT(r))}`);for(let e of n.warnings)bx(px(` ! ${e}`));p.push(e)}catch(n){t.stop(),bx(`${hx(`✗`)} ${fx(a(e))} ${ax(n)}`)}}if(!p.length)throw new Sx(`No repo was imported.`);if(i){let e=p.map(a),n=await Yb(t),r={...u,repos:e,folder:c?n?.root===t&&n.link.folder||T():void 0};if(await Xb(t,r),c)try{let e=await YT(t,r,{quiet:!0});bx(`${mx(`✓`)} ${fx(`documents outside the repos`)} ${px(`${e?.docs??0} docs`)}`)}catch(e){bx(`${hx(`✗`)} ${fx(`documents outside the repos`)} ${ax(e)}`)}d&&!p.includes(t)&&await QT(t,l.name,e)}let m=kx().portable;d&&(yx(`🤖`,`Connected Claude Code`),bx(px(`.mcp.json the quirl tools`)),bx(px(`.claude/settings.json the briefing, loaded as each session starts`)),bx(px(`CLAUDE.md when to use Quirl`))),f&&yx(`🪝`,`Quirl syncs on every ${fx(`git push`)}`);let g=r.length-p.length,_=`.quirl .mcp.json .claude/settings.json CLAUDE.md`;yx(g?`⚠️ `:`🎉`,g?`Done, but ${g} of ${r.length} repos failed. Fix them and run ${fx(`quirl init`)} again.`:fx(`All set!`)),bx(d&&!m?px(`Don't commit ${_} yet: they point at this checkout until the CLI is installed.`):`${px(`1.`)} Commit what was added${i?` in each repo`:``}: ${gx(`git add ${_}`)}`),bx(`${px(d&&!m?`→`:`2.`)} Start Claude Code here and approve the ${fx(`quirl`)} server when it asks.`),i&&!p.includes(t)&&bx(px("Run `quirl sync` here to sync every repo at once.")),console.log(``)}async function QT(e,t,n=[]){await Fx(e),await Ix(e),await Lx(e,t,n)}async function $T(e,t){if(!e.length)throw new Sx(`You aren't on any Quirl project yet. Ask an admin to invite you.`);if(t){let n=e.find(e=>e.slug===t||e.id===t);if(!n)throw new Sx(`No project "${t}" among yours: ${e.map(e=>e.slug).join(`, `)}.`);return n}if(e.length===1)return e[0];yx(`🗂️ `,`Which project is this part of?`);for(let[t,n]of e.entries())bx(`${gx(String(t+1))} ${n.name} ${px(`· ${n.organization} · ${n.role}`)}`);let n=e[Number(await Cx(` Project [1-${e.length}]: `))-1];if(!n)throw new Sx("No project picked. Run `quirl init --project <slug>`.");return n}const eE=`${fx(`quirl`)} ${px(Lb)}: connect a repo to Quirl
|
|
341
343
|
|
|
342
344
|
quirl init [--project <slug>] [--hooks|--no-hooks] [--no-claude]
|
|
343
345
|
Link this repo, import it, and connect Claude Code
|
|
@@ -347,4 +349,4 @@ n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2
|
|
|
347
349
|
quirl logout Forget this machine's key
|
|
348
350
|
quirl whoami Show who you're signed in as
|
|
349
351
|
quirl mcp Run the MCP server (used by Claude Code)
|
|
350
|
-
`;async function
|
|
352
|
+
`;async function tE(){let[e,...n]=process.argv.slice(2),{values:r}=t({args:n,allowNegative:!0,options:{project:{type:`string`},hooks:{type:`boolean`},claude:{type:`boolean`},quiet:{type:`boolean`},hook:{type:`boolean`},source:{type:`string`}}});switch(e){case`init`:return ZT({project:r.project,hooks:r.hooks,claude:r.claude});case`sync`:return XT({quiet:r.quiet,source:r.source});case`context`:return cx({hook:r.hook});case`login`:await zx();return;case`logout`:return await Gb(),_x(`Signed out on this machine.`),vx(px(`The key still exists until you revoke it under Organization > Access keys in Quirl (${zb().appUrl}).`));case`whoami`:{if(!await Ub())throw new Sx("Not signed in. Run `quirl login`.");let e=await new Ur(await Kb()).whoami();console.log(fx(e.email));for(let t of e.projects)vx(`${t.name} ${px(`${t.slug} · ${t.organization} · ${t.role}`)}`);let t=await Yb();t&&vx(px(`This folder: ${t.link.name}`));return}case`mcp`:{let e=await Yb();if(!e)throw new Sx("This folder isn't linked to a Quirl project. Run `quirl init`.");return Ib({...await Kb(),project:e.link.projectId,version:Lb})}case void 0:case`help`:case`--help`:case`-h`:process.stdout.write(eE);return;case`--version`:case`-v`:return console.log(Lb);default:throw new Sx(`Unknown command "${e}".\n\n${eE}`)}}tE().catch(e=>{let t=e instanceof Sx?e.message:ax(e);console.error(`${hx(`✗`)} ${t}`),process.exit(1)});export{};
|