@superglue/cli 1.1.47 → 1.1.48
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/.claude-plugin/plugin.json +1 -1
- package/dist/cli.js +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "superglue",
|
|
3
3
|
"description": "Build, test, and manage superglue tools via the sg CLI. Use when working with superglue tools, systems, APIs, SDKs, or the sg command.",
|
|
4
|
-
"version": "1.1.
|
|
4
|
+
"version": "1.1.48",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "superglue",
|
|
7
7
|
"email": "hello@superglue.cloud"
|
package/dist/cli.js
CHANGED
|
@@ -1396,9 +1396,9 @@ ${e.format(t)}`.trim())}};vB.exports=EA});var CA=y((jge,EB)=>{"use strict";var{I
|
|
|
1396
1396
|
${s}`;break;case"retry":c5(s)&&(t[i]=s);break;case"id":m5(s)&&(t[i]=s);break;case"event":s.length>0&&(t[i]=s);break}}processEvent(e){e.retry&&c5(e.retry)&&(this.state.reconnectionTime=parseInt(e.retry,10)),e.id!==void 0&&m5(e.id)&&(this.state.lastEventId=e.id),e.data!==void 0&&this.push({type:e.event||"message",options:{data:e.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event={data:void 0,event:void 0,id:void 0,retry:void 0}}};l5.exports={EventSourceStream:Gw}});var k5=y((xpe,y5)=>{"use strict";var{pipeline:Fne}=require("stream"),{fetching:Lne}=Um(),{makeRequest:Pne}=gn(),{webidl:ko}=eo(),{EventSourceStream:Hne}=u5(),{parseMIMEType:Yne}=dt(),{createFastMessageEvent:Gne}=zg(),{isNetworkError:d5}=Rm(),{kEnumerableProperty:Zs}=K(),{environmentSettingsObject:g5}=Ho(),p5=!1,h5=3e3,Hm=0,f5=1,Ym=2,Vne="anonymous",Wne="use-credentials",xn=class o extends EventTarget{#e={open:null,error:null,message:null};#o;#a=!1;#i=Hm;#s=null;#t=null;#c;#r;constructor(e,t={}){super(),ko.util.markAsUncloneable(this);let a="EventSource constructor";ko.argumentLengthCheck(arguments,1,a),p5||(p5=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),e=ko.converters.USVString(e),t=ko.converters.EventSourceInitDict(t,a,"eventSourceInitDict"),this.#c=t.node.dispatcher||t.dispatcher,this.#r={lastEventId:"",reconnectionTime:t.node.reconnectionTime};let i=g5,s;try{s=new URL(e,i.settingsObject.baseUrl),this.#r.origin=s.origin}catch(c){throw new DOMException(c,"SyntaxError")}this.#o=s.href;let r=Vne;t.withCredentials===!0&&(r=Wne,this.#a=!0);let n={redirect:"follow",keepalive:!0,mode:"cors",credentials:r==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};n.client=g5.settingsObject,n.headersList=[["accept",{name:"accept",value:"text/event-stream"}]],n.cache="no-store",n.initiator="other",n.urlList=[new URL(this.#o)],this.#s=Pne(n),this.#n()}get readyState(){return this.#i}get url(){return this.#o}get withCredentials(){return this.#a}#n(){if(this.#i===Ym)return;this.#i=Hm;let e={request:this.#s,dispatcher:this.#c},t=a=>{if(!d5(a))return this.#m()};e.processResponseEndOfBody=t,e.processResponse=a=>{if(d5(a))if(a.aborted){this.close(),this.dispatchEvent(new Event("error"));return}else{this.#m();return}let i=a.headersList.get("content-type",!0),s=i!==null?Yne(i):"failure",r=s!=="failure"&&s.essence==="text/event-stream";if(a.status!==200||r===!1){this.close(),this.dispatchEvent(new Event("error"));return}this.#i=f5,this.dispatchEvent(new Event("open")),this.#r.origin=a.urlList[a.urlList.length-1].origin;let n=new Hne({eventSourceSettings:this.#r,push:c=>{this.dispatchEvent(Gne(c.type,c.options))}});Fne(a.body.stream,n,c=>{c?.aborted===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},this.#t=Lne(e)}#m(){this.#i!==Ym&&(this.#i=Hm,this.dispatchEvent(new Event("error")),setTimeout(()=>{this.#i===Hm&&(this.#r.lastEventId.length&&this.#s.headersList.set("last-event-id",this.#r.lastEventId,!0),this.#n())},this.#r.reconnectionTime)?.unref())}close(){ko.brandCheck(this,o),this.#i!==Ym&&(this.#i=Ym,this.#t.abort(),this.#s=null)}get onopen(){return this.#e.open}set onopen(e){this.#e.open&&this.removeEventListener("open",this.#e.open);let t=ko.converters.EventHandlerNonNull(e);t!==null?(this.addEventListener("open",t),this.#e.open=e):this.#e.open=null}get onmessage(){return this.#e.message}set onmessage(e){this.#e.message&&this.removeEventListener("message",this.#e.message);let t=ko.converters.EventHandlerNonNull(e);t!==null?(this.addEventListener("message",t),this.#e.message=e):this.#e.message=null}get onerror(){return this.#e.error}set onerror(e){this.#e.error&&this.removeEventListener("error",this.#e.error);let t=ko.converters.EventHandlerNonNull(e);t!==null?(this.addEventListener("error",t),this.#e.error=e):this.#e.error=null}},b5={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:Hm,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:f5,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:Ym,writable:!1}};Object.defineProperties(xn,b5);Object.defineProperties(xn.prototype,b5);Object.defineProperties(xn.prototype,{close:Zs,onerror:Zs,onmessage:Zs,onopen:Zs,readyState:Zs,url:Zs,withCredentials:Zs});ko.converters.EventSourceInitDict=ko.dictionaryConverter([{key:"withCredentials",converter:ko.converters.boolean,defaultValue:()=>!1},{key:"dispatcher",converter:ko.converters.any},{key:"node",converter:ko.dictionaryConverter([{key:"reconnectionTime",converter:ko.converters["unsigned long"],defaultValue:()=>h5},{key:"dispatcher",converter:ko.converters.any}]),defaultValue:()=>({})}]);y5.exports={EventSource:xn,defaultReconnectionTime:h5}});var q5=y((zpe,B)=>{"use strict";var $ne=xi(),w5=Pc(),Jne=Cs(),Kne=s8(),Zne=m8(),Xne=Bs(),ece=Qk(),oce=Ek(),tce=W8(),ace=oQ(),ice=iQ(),v5=V(),Ug=K(),{InvalidArgumentError:Ng}=v5,zn=OQ(),sce=bs(),rce=hA(),{MockCallHistory:nce,MockCallHistoryLog:cce}=yA(),mce=IA(),lce=vA(),uce=MB(),dce=Zk(),gce=Sd(),{getGlobalDispatcher:x5,setGlobalDispatcher:pce}=Vd(),hce=nn(),fce=TA();Object.assign(w5.prototype,zn);B.exports.Dispatcher=w5;B.exports.Client=$ne;B.exports.Pool=Jne;B.exports.BalancedPool=Kne;B.exports.RoundRobinPool=Zne;B.exports.Agent=Xne;B.exports.ProxyAgent=ece;B.exports.Socks5ProxyAgent=oce;B.exports.EnvHttpProxyAgent=tce;B.exports.RetryAgent=ace;B.exports.H2CClient=ice;B.exports.RetryHandler=gce;B.exports.DecoratorHandler=hce;B.exports.RedirectHandler=fce;B.exports.interceptors={redirect:$B(),responseError:KB(),retry:XB(),dump:o4(),dns:s4(),cache:U4(),decompress:L4(),deduplicate:V4()};B.exports.cacheStores={MemoryCacheStore:JA()};var bce=J4();B.exports.cacheStores.SqliteCacheStore=bce;B.exports.buildConnector=sce;B.exports.errors=v5;B.exports.util={parseHeaders:Ug.parseHeaders,headerNameToString:Ug.headerNameToString};function Gm(o){return(e,t,a)=>{if(typeof t=="function"&&(a=t,t=null),!e||typeof e!="string"&&typeof e!="object"&&!(e instanceof URL))throw new Ng("invalid url");if(t!=null&&typeof t!="object")throw new Ng("invalid opts");if(t&&t.path!=null){if(typeof t.path!="string")throw new Ng("invalid opts.path");let r=t.path;t.path.startsWith("/")||(r=`/${r}`),e=new URL(Ug.parseOrigin(e).origin+r)}else t||(t=typeof e=="object"?e:{}),e=Ug.parseURL(e);let{agent:i,dispatcher:s=x5()}=t;if(i)throw new Ng("unsupported opts.agent. Did you mean opts.client?");return o.call(s,{...t,origin:e.origin,path:e.search?`${e.pathname}${e.search}`:e.pathname,method:t.method||(t.body?"PUT":"GET")},a)}}B.exports.setGlobalDispatcher=pce;B.exports.getGlobalDispatcher=x5;var yce=Um().fetch,A5=typeof __filename<"u"?__filename:void 0;function z5(o,e){if(!o||typeof o!="object")return;let t=typeof o.stack=="string"?o.stack:"",a=e.replace(/\\/g,"/");if(t&&(t.includes(e)||t.includes(a)))return;let i={};if(Error.captureStackTrace(i,z5),!i.stack)return;let s=i.stack.split(`
|
|
1397
1397
|
`).slice(1).join(`
|
|
1398
1398
|
`);o.stack=t?`${t}
|
|
1399
|
-
${s}`:i.stack}B.exports.fetch=function(e,t=void 0){return yce(e,t).catch(a=>{throw A5?z5(a,A5):a&&typeof a=="object"&&Error.captureStackTrace(a,B.exports.fetch),a})};B.exports.Headers=Hs().Headers;B.exports.Response=Rm().Response;B.exports.Request=gn().Request;B.exports.FormData=sd().FormData;var{setGlobalOrigin:kce,getGlobalOrigin:Ace}=uy();B.exports.setGlobalOrigin=kce;B.exports.getGlobalOrigin=Ace;var{CacheStorage:wce}=r9(),{kConstruct:vce}=de();B.exports.caches=new wce(vce);var{deleteCookie:xce,getCookies:zce,getSetCookies:qce,setCookie:Ece,parseCookie:Ice}=y9();B.exports.deleteCookie=xce;B.exports.getCookies=zce;B.exports.getSetCookies=qce;B.exports.setCookie=Ece;B.exports.parseCookie=Ice;var{parseMIMEType:Cce,serializeAMimeType:jce}=dt();B.exports.parseMIMEType=Cce;B.exports.serializeAMimeType=jce;var{CloseEvent:Qce,ErrorEvent:Bce,MessageEvent:Sce}=zg(),{WebSocket:Dce,ping:Rce}=K9();B.exports.WebSocket=Dce;B.exports.CloseEvent=Qce;B.exports.ErrorEvent=Bce;B.exports.MessageEvent=Sce;B.exports.ping=Rce;B.exports.WebSocketStream=s5().WebSocketStream;B.exports.WebSocketError=Fw().WebSocketError;B.exports.request=Gm(zn.request);B.exports.stream=Gm(zn.stream);B.exports.pipeline=Gm(zn.pipeline);B.exports.connect=Gm(zn.connect);B.exports.upgrade=Gm(zn.upgrade);B.exports.MockClient=rce;B.exports.MockCallHistory=nce;B.exports.MockCallHistoryLog=cce;B.exports.MockPool=lce;B.exports.MockAgent=mce;B.exports.SnapshotAgent=uce;B.exports.mockErrors=dce;var{EventSource:Tce}=k5();B.exports.EventSource=Tce;function Nce(){globalThis.fetch=B.exports.fetch,globalThis.Headers=B.exports.Headers,globalThis.Response=B.exports.Response,globalThis.Request=B.exports.Request,globalThis.FormData=B.exports.FormData,globalThis.WebSocket=B.exports.WebSocket,globalThis.CloseEvent=B.exports.CloseEvent,globalThis.ErrorEvent=B.exports.ErrorEvent,globalThis.MessageEvent=B.exports.MessageEvent,globalThis.EventSource=B.exports.EventSource}B.exports.install=Nce});var E5=y(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.SuperglueClient=En.SuperglueHttpError=void 0;var qn=zt(),Uce=nb(),Mce=M2(),Oce=Vt(),La=xr(),_ce=du(),Mg=14400*1e3,Vm;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:o}=q5();Vm=new o({headersTimeout:Mg,bodyTimeout:Mg})}catch{}var Og=class extends Error{constructor(e,t,a,i){super(e),this.status=t,this.code=a,this.details=i,this.name="SuperglueHttpError"}};En.SuperglueHttpError=Og;var Vw=class{constructor({apiKey:e,apiEndpoint:t,onInfrastructureError:a,sseTokenProvider:i,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=t??"https://api.superglue.cloud",this.sseManager=new Uce.SSELogSubscriptionManager(this.apiEndpoint,i??this.tokenProvider),this.onInfrastructureError=a}async getApiKey(){return this.tokenProvider()}isInfrastructureError(e){return(0,Oce.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,t,a,i,s){let n=await(await this.restResponse({method:e,path:t,body:a,extraHeaders:i,requestInit:s})).text();if(n)return JSON.parse(n)}async restResponse({method:e,path:t,body:a,extraHeaders:i,requestInit:s}){let r=`${this.apiEndpoint.replace(/\/$/,"")}${t}`,c={Authorization:`Bearer ${await this.getApiKey()}`,...i};a&&e!=="GET"&&(c["Content-Type"]="application/json");let m;try{m=await fetch(r,{...s,method:e,headers:c,body:a?JSON.stringify(a):void 0,signal:s?.signal??AbortSignal.timeout(Mg),...Vm?{dispatcher:Vm}:{}})}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}if(!m.ok)throw await this.buildHttpError(m);return m}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let t=await e.text(),a=`HTTP ${e.status}: ${t}`,i,s;try{let r=JSON.parse(t);r&&typeof r=="object"&&!Array.isArray(r)&&(s=r),typeof r?.code=="string"&&(i=r.code);let n=r.error;typeof n=="string"?a=n:n&&typeof n=="object"&&(a=n.message||JSON.stringify(n))}catch{}return new Og(a,e.status,i,s)}async streamRequest(e,t,a){let i=e.includes("?")?"&":"?",s=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,n={Authorization:`Bearer ${await this.getApiKey()}`,Accept:"text/event-stream","Content-Type":"application/json"},c;try{c=await fetch(s,{method:"POST",headers:n,body:JSON.stringify(t),signal:a??AbortSignal.timeout(Mg),...Vm?{dispatcher:Vm}:{}})}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}if(!c.ok)throw await this.buildHttpError(c);if(!(c.headers.get("content-type")||"").includes("text/event-stream")){let l=await c.text();return l?JSON.parse(l):void 0}try{return await(0,Mce.consumeEventStreamResult)(c)}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async getMe(){return this.restRequest("GET","/v1/me")}async runTool(e){let t=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:t.status==="success",data:t.data,error:t.error,tool:t.tool,stepResults:t.stepResults?.map(a=>({...a}))||[],...t.fileArtifacts&&t.fileArtifacts.length>0?{fileArtifacts:t.fileArtifacts}:{},...t.metadata?.warnings?.length?{warnings:t.metadata.warnings}:{}}}async runToolConfig(e){let t=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",a=await this.restRequest("POST",t,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:a.status?a.status==="success":a.success??!1,data:a.data,error:a.error,tool:a.tool||e.tool,stepResults:a.stepResults?.map(s=>({...s}))||[],...a.fileArtifacts&&a.fileArtifacts.length>0?{fileArtifacts:a.fileArtifacts}:{},...a.metadata?.warnings?.length?{warnings:a.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:t,files:a,previousResults:i,credentials:s,options:r,runId:n,systemIds:c,createRun:m,parentToolId:l,stepIndex:u,stepId:d,signal:g,stream:p}){let b={step:e,payload:t,files:a,previousResults:i,credentials:s,options:r,runId:n,systemIds:c,createRun:m,parentToolId:l,stepIndex:u,stepId:d};return p?this.streamRequest("/v1/tools/step/run",b,g):this.restRequest("POST","/v1/tools/step/run",b,void 0,g?{signal:g}:void 0)}async abortStep(e){return this.restRequest("POST","/v1/tools/step/abort",{runId:e})}async executeTransformOnly({outputTransform:e,outputSchema:t,inputSchema:a,payload:i,files:s,stepResults:r,options:n,runId:c,createRun:m,parentToolId:l,stepId:u,signal:d,stream:g}){let p={outputTransform:e,outputSchema:t,inputSchema:a,payload:i,files:s,stepResults:r,options:n,runId:c,createRun:m,parentToolId:l,stepId:u};return g?this.streamRequest("/v1/tools/transform/run",p,d):this.restRequest("POST","/v1/tools/transform/run",p,void 0,d?{signal:d}:void 0)}async createRun({toolId:e,toolConfig:t,toolResult:a,stepResults:i,toolPayload:s,status:r,error:n,startedAt:c,completedAt:m,executionKind:l,parentToolId:u,draftId:d}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:t,toolResult:a,stepResults:i,toolPayload:s,status:r,error:n,startedAt:(0,La.toUTCISOString)(c,"run.startedAt"),completedAt:(0,La.toUTCISOString)(m,"run.completedAt"),executionKind:l,parentToolId:u,draftId:d})}async checkRunLimit(){return(await this.restRequest("POST","/v1/runs/check-limit")).data}async extract({file:e,envelope:t}){if(!e)throw new Error("File must be provided for extract.");let a=new FormData;a.append("file",e);let i=new URL(`${this.apiEndpoint.replace(/\/$/,"")}/v1/extract`);t&&i.searchParams.set("envelope","true");let s=i.toString(),r=await this.getApiKey(),n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:a});if(!n.ok){let c=await n.text(),m=`HTTP ${n.status}: ${c}`;try{let l=JSON.parse(c);l.error&&(m=l.error)}catch{}throw new Error(m)}return n.json()}mapOpenAPIRunToRun(e){let t={running:qn.RunStatus.RUNNING,success:qn.RunStatus.SUCCESS,failed:qn.RunStatus.FAILED,aborted:qn.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:t[e.status]??qn.RunStatus.FAILED,toolPayload:e.toolPayload,data:e.data,toolResult:e.data,error:e.error,stepResults:e.stepResults,options:e.options,requestSource:e.requestSource,traceId:e.traceId,resultStorageUri:e.resultStorageUri,userId:e.userId,userEmail:e.userEmail,userName:e.userName,metadata:{...e.metadata,executionKind:e.metadata?.executionKind??qn.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,La.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,La.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,La.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,La.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e){let{limit:t=100,page:a=1,toolId:i,search:s,searchUserIds:r,includeTotal:n=!0,startedAfter:c,status:m,requestSources:l,executionKinds:u,userId:d,systemId:g,signal:p}=e??{},b=new URLSearchParams({limit:String(t),page:String(a)});i&&b.set("toolId",i),s?.trim()&&b.set("search",s.trim()),r&&r.length>0&&b.set("searchUserIds",r.join(",")),n||b.set("includeTotal","false"),c&&b.set("startedAfter",c instanceof Date?(0,La.toUTCISOString)(c,"run.startedAfter"):c),m&&b.set("status",m),l&&l.length>0&&b.set("requestSources",l.join(",")),u&&u.length>0&&b.set("executionKinds",u.join(",")),d&&b.set("userId",d),g&&b.set("systemId",g);let w=await this.restRequest("GET",`/v1/runs?${b.toString()}`,void 0,void 0,{signal:p});return{items:w.data.map(k=>this.mapOpenAPIRunToRun(k)),total:w.total,page:w.page,limit:w.limit,hasMore:w.hasMore}}async getActivityCounts(e){let t=new URLSearchParams;e?.from&&t.set("from",e.from instanceof Date?(0,La.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&t.set("to",e.to instanceof Date?(0,La.toUTCISOString)(e.to,"activity.to"):e.to);let a=t.toString();return(await this.restRequest("GET",`/v1/activity/counts${a?`?${a}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let t=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(t)}catch(t){if(t.message?.includes("404")||t.message?.includes("not found"))return null;throw t}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(t){if(t.message?.includes("404")||t.message?.includes("not found")||t.message?.includes("403")||t.message?.includes("not allowed"))return null;throw t}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,t){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:t})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,t=!0){return this.updateTool(e,{archived:t})}async bulkArchiveTools(e,t=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:t})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e=10,t=0,a=!1){let i=Math.floor(t/e)+1,s=a?"&includeArchived=true":"",r=await this.restRequest("GET",`/v1/tools?limit=${e}&page=${i}${s}`);return{items:r.data,total:r.total}}async createTool(e,t){return this.restRequest("POST","/v1/tools",{...t,id:e})}async updateTool(e,t){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,t)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(t){if(t.message?.includes("404"))return!1;throw t}}async renameTool(e,t){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:t})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,t=!0){return this.upsertWorkflow(e,{archived:t})}async listWorkflows(e=10,t=0,a=!1){return this.listTools(e,t,a)}async createWorkflow(e,t){return this.createTool(e,t)}async updateWorkflow(e,t){return this.updateTool(e,t)}async upsertWorkflow(e,t){return await this.getTool(e)?this.updateTool(e,t):this.createTool(e,t)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,t){return this.renameTool(e,t)}async listToolSchedules(e){if(e&&typeof e=="object")return this.listToolSchedulesPage(e);let t=[],a=typeof e=="string"?e:void 0,i=1;for(;;){let s=await this.listToolSchedulesPage({toolId:a,limit:1e3,page:i});if(t.push(...s.items),!s.hasMore||s.items.length===0)break;i+=1}return t}async listToolSchedulesPage(e){let{toolId:t,limit:a=100,page:i=1}=e??{},s=new URLSearchParams({limit:String(a),page:String(i)}),r=t?`/v1/tools/${encodeURIComponent(t)}/schedules?${s.toString()}`:`/v1/schedules?${s.toString()}`,n=await this.restRequest("GET",r);return{items:n.data.map(c=>this.mapOpenAPIScheduleToToolSchedule(c)),total:n.total,page:n.page,limit:n.limit,hasMore:n.hasMore}}async getToolSchedule(e,t){try{let a=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`);return this.mapOpenAPIScheduleToToolSchedule(a)}catch(a){if(a.message?.includes("404")||a.message?.includes("not found"))return null;throw a}}async createToolSchedule(e,t){let a=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...t,timezone:t.timezone||(0,_ce.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(a)}async updateToolSchedule(e,t,a){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`,a);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,t){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`),!0}async bulkSetSchedulesEnabled(e,t){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:t})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listCredentials(e){let t=new URLSearchParams;e?.systemId&&t.set("systemId",e.systemId);let a=t.toString();return(await this.restRequest("GET",`/v1/credentials${a?`?${a}`:""}`)).data.items}async createCredentials(e){return(await this.restRequest("POST","/v1/credentials",e)).data}async replaceCredentials(e,t){return(await this.restRequest("PUT",`/v1/credentials/${encodeURIComponent(e)}`,{credentials:t})).data}async updateCredentials(e,t){return(await this.restRequest("PATCH",`/v1/credentials/${encodeURIComponent(e)}`,t)).data}async deleteCredentials(e){await this.restRequest("DELETE",`/v1/credentials/${encodeURIComponent(e)}`)}async setDefaultCredentials(e){await this.restRequest("POST",`/v1/credentials/${encodeURIComponent(e)}/default`)}async listSystems(e=10,t=1){let a=new URLSearchParams({limit:String(e),page:String(t)}),i=await this.restRequest("GET",`/v1/systems?${a.toString()}`);return{items:i.data,total:i.total}}async getSystem(e){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}`)).data}async createSystem(e){return(await this.restRequest("POST","/v1/systems",e)).data}async updateSystem(e,t){return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(e)}`,t)).data}async deleteSystem(e){return await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}`),!0}async bulkDeleteSystems(e){return this.restRequest("POST","/v1/systems/bulk/delete",{ids:e})}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,t){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,t)).data}async searchSystemDocumentation(e,t){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/search`,{keywords:t})).data}async triggerSystemDocumentationScrapeJob(e,t){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/scrape`,t)).data}async fetchOpenApiSpec(e,t,a){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/openapi`,{url:t,link:a?.link})).data}async createSystemFileUploadUrls(e,t,a){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/file-references`,{files:t.map(s=>({fileName:s.fileName,metadata:{contentType:s.contentType,contentLength:s.contentLength}})),link:a?.link})).data.files}async uploadSystemFileReferences(e,t,a){if(t.length===0)return[];let i=await this.createSystemFileUploadUrls(e,t.map(n=>({fileName:n.fileName,contentType:n.contentType,contentLength:n.contentLength})),{link:a?.link}),r=(await Promise.allSettled(i.map(async(n,c)=>{let m=t[c],l=await fetch(n.uploadUrl,{method:"PUT",body:m.content,headers:m.contentType?{"Content-Type":m.contentType}:void 0});if(!l.ok)throw new Error(`Upload failed for ${m.fileName}: ${l.status} ${l.statusText}`);return this.processFileReference(n.id).catch(()=>{}),n.id}))).map((n,c)=>{let m=t[c],l=i[c].id;return n.status==="fulfilled"?{id:l,fileName:m.fileName,contentLength:m.contentLength,status:"uploaded"}:(this.deleteSystemFileReference(e,l).catch(()=>{}),{id:l,fileName:m.fileName,contentLength:m.contentLength,status:"failed",error:n.reason instanceof Error?n.reason.message:"Upload failed"})});if(!a?.settle){let n=r.filter(c=>c.status==="failed");if(n.length>0)throw new Error(n.map(c=>c.error).join("; "))}return r}async processFileReference(e){return this.restRequest("POST",`/v1/file-references/${encodeURIComponent(e)}/process`)}async listSystemFileReferences(e){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/file-references`)).data}async listFileReferences(e){if(e.length===0)return{files:[],total:0};let t=new URLSearchParams;t.set("fileIds",e.join(",")),t.set("limit",String(e.length));let a=await this.restRequest("GET",`/v1/file-references?${t.toString()}`);return{files:a.items,total:a.total}}async deleteSystemFileReference(e,t){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}/file-references/${encodeURIComponent(t)}`)}async getFileReferenceContent(e){return(await this.restRequest("GET",`/v1/file-references/${encodeURIComponent(e)}?includeContent=true`)).data.content??null}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(t){return{success:!1,error:t.message}}}};En.SuperglueClient=Vw});var C5=y(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.UnquotedKeyStrategy=Ce.TripleQuoteStrategy=Ce.TrailingCommaStrategy=Ce.SingleQuoteStrategy=Ce.PythonLiteralStrategy=Ce.CommentStrategy=Ce.ResilientJsonParser=Ce.RepairStrategy=void 0;Ce.parseJsonResilient=Fce;Ce.parseJSON=Lce;Ce.isValidJson=Pce;Ce.prettyPrintJson=Hce;Ce.minifyJson=Yce;var _t=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};Ce.RepairStrategy=_t;var _g=class extends _t{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(t,a)=>{let i=a.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let r=JSON.parse(i);return JSON.stringify(r)}catch{return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};Ce.TripleQuoteStrategy=_g;var Fg=class extends _t{constructor(){super(...arguments),this.name="PythonLiteralRepair",this.description="Converts Python literals to JavaScript equivalents"}canApply(e){return/\b(None|True|False)\b/.test(e)}apply(e){return e.replace(/\bNone\b/g,"null").replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false")}};Ce.PythonLiteralStrategy=Fg;var Lg=class extends _t{constructor(){super(...arguments),this.name="TrailingCommaRepair",this.description="Removes trailing commas from objects and arrays"}canApply(e){return/,\s*[}\]]/.test(e)}apply(e){return e.replace(/,(\s*[}\]])/g,"$1")}};Ce.TrailingCommaStrategy=Lg;var Pg=class extends _t{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let t=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return t=t.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),t}};Ce.SingleQuoteStrategy=Pg;var Hg=class extends _t{constructor(){super(...arguments),this.name="UnquotedKeyRepair",this.description="Adds quotes to unquoted object keys"}canApply(e){return/[{,]\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*:/.test(e)}apply(e){return e.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g,'$1"$2"$3')}};Ce.UnquotedKeyStrategy=Hg;var Yg=class extends _t{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),t}};Ce.CommentStrategy=Yg;var Ww=class extends _t{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(t){let a=t.message||"";return a.includes("control character")||a.includes("Bad control")||a.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let t="",a=!1,i=!1;for(let s=0;s<e.length;s++){let r=e[s],n=s>0?e[s-1]:"";if(i){t+=r,i=!1;continue}if(r==="\\"&&a){t+=r,i=!0;continue}if(r==='"'&&n!=="\\"){a=!a,t+=r;continue}if(a)switch(r){case`
|
|
1399
|
+
${s}`:i.stack}B.exports.fetch=function(e,t=void 0){return yce(e,t).catch(a=>{throw A5?z5(a,A5):a&&typeof a=="object"&&Error.captureStackTrace(a,B.exports.fetch),a})};B.exports.Headers=Hs().Headers;B.exports.Response=Rm().Response;B.exports.Request=gn().Request;B.exports.FormData=sd().FormData;var{setGlobalOrigin:kce,getGlobalOrigin:Ace}=uy();B.exports.setGlobalOrigin=kce;B.exports.getGlobalOrigin=Ace;var{CacheStorage:wce}=r9(),{kConstruct:vce}=de();B.exports.caches=new wce(vce);var{deleteCookie:xce,getCookies:zce,getSetCookies:qce,setCookie:Ece,parseCookie:Ice}=y9();B.exports.deleteCookie=xce;B.exports.getCookies=zce;B.exports.getSetCookies=qce;B.exports.setCookie=Ece;B.exports.parseCookie=Ice;var{parseMIMEType:Cce,serializeAMimeType:jce}=dt();B.exports.parseMIMEType=Cce;B.exports.serializeAMimeType=jce;var{CloseEvent:Qce,ErrorEvent:Bce,MessageEvent:Sce}=zg(),{WebSocket:Dce,ping:Rce}=K9();B.exports.WebSocket=Dce;B.exports.CloseEvent=Qce;B.exports.ErrorEvent=Bce;B.exports.MessageEvent=Sce;B.exports.ping=Rce;B.exports.WebSocketStream=s5().WebSocketStream;B.exports.WebSocketError=Fw().WebSocketError;B.exports.request=Gm(zn.request);B.exports.stream=Gm(zn.stream);B.exports.pipeline=Gm(zn.pipeline);B.exports.connect=Gm(zn.connect);B.exports.upgrade=Gm(zn.upgrade);B.exports.MockClient=rce;B.exports.MockCallHistory=nce;B.exports.MockCallHistoryLog=cce;B.exports.MockPool=lce;B.exports.MockAgent=mce;B.exports.SnapshotAgent=uce;B.exports.mockErrors=dce;var{EventSource:Tce}=k5();B.exports.EventSource=Tce;function Nce(){globalThis.fetch=B.exports.fetch,globalThis.Headers=B.exports.Headers,globalThis.Response=B.exports.Response,globalThis.Request=B.exports.Request,globalThis.FormData=B.exports.FormData,globalThis.WebSocket=B.exports.WebSocket,globalThis.CloseEvent=B.exports.CloseEvent,globalThis.ErrorEvent=B.exports.ErrorEvent,globalThis.MessageEvent=B.exports.MessageEvent,globalThis.EventSource=B.exports.EventSource}B.exports.install=Nce});var E5=y(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.SuperglueClient=En.SuperglueHttpError=void 0;var qn=zt(),Uce=nb(),Mce=M2(),Oce=Vt(),La=xr(),_ce=du(),Mg=14400*1e3,Vm;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:o}=q5();Vm=new o({headersTimeout:Mg,bodyTimeout:Mg})}catch{}var Og=class extends Error{constructor(e,t,a,i){super(e),this.status=t,this.code=a,this.details=i,this.name="SuperglueHttpError"}};En.SuperglueHttpError=Og;var Vw=class{constructor({apiKey:e,apiEndpoint:t,onInfrastructureError:a,sseTokenProvider:i,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=t??"https://api.superglue.cloud",this.sseManager=new Uce.SSELogSubscriptionManager(this.apiEndpoint,i??this.tokenProvider),this.onInfrastructureError=a}async getApiKey(){return this.tokenProvider()}isInfrastructureError(e){return(0,Oce.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,t,a,i,s){let n=await(await this.restResponse({method:e,path:t,body:a,extraHeaders:i,requestInit:s})).text();if(n)return JSON.parse(n)}async restResponse({method:e,path:t,body:a,extraHeaders:i,requestInit:s}){let r=`${this.apiEndpoint.replace(/\/$/,"")}${t}`,c={Authorization:`Bearer ${await this.getApiKey()}`,...i};a&&e!=="GET"&&(c["Content-Type"]="application/json");let m;try{m=await fetch(r,{...s,method:e,headers:c,body:a?JSON.stringify(a):void 0,signal:s?.signal??AbortSignal.timeout(Mg),...Vm?{dispatcher:Vm}:{}})}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}if(!m.ok)throw await this.buildHttpError(m);return m}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let t=await e.text(),a=`HTTP ${e.status}: ${t}`,i,s;try{let r=JSON.parse(t);r&&typeof r=="object"&&!Array.isArray(r)&&(s=r),typeof r?.code=="string"&&(i=r.code);let n=r.error;typeof n=="string"?a=n:n&&typeof n=="object"&&(a=n.message||JSON.stringify(n))}catch{}return new Og(a,e.status,i,s)}async streamRequest(e,t,a){let i=e.includes("?")?"&":"?",s=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,n={Authorization:`Bearer ${await this.getApiKey()}`,Accept:"text/event-stream","Content-Type":"application/json"},c;try{c=await fetch(s,{method:"POST",headers:n,body:JSON.stringify(t),signal:a??AbortSignal.timeout(Mg),...Vm?{dispatcher:Vm}:{}})}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}if(!c.ok)throw await this.buildHttpError(c);if(!(c.headers.get("content-type")||"").includes("text/event-stream")){let l=await c.text();return l?JSON.parse(l):void 0}try{return await(0,Mce.consumeEventStreamResult)(c)}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async getMe(){return this.restRequest("GET","/v1/me")}async runTool(e){let t=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:t.status==="success",data:t.data,error:t.error,tool:t.tool,stepResults:t.stepResults?.map(a=>({...a}))||[],...t.fileArtifacts&&t.fileArtifacts.length>0?{fileArtifacts:t.fileArtifacts}:{},...t.metadata?.warnings?.length?{warnings:t.metadata.warnings}:{}}}async runToolConfig(e){let t=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",a=await this.restRequest("POST",t,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:a.status?a.status==="success":a.success??!1,data:a.data,error:a.error,tool:a.tool||e.tool,stepResults:a.stepResults?.map(s=>({...s}))||[],...a.fileArtifacts&&a.fileArtifacts.length>0?{fileArtifacts:a.fileArtifacts}:{},...a.metadata?.warnings?.length?{warnings:a.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:t,files:a,previousResults:i,credentials:s,options:r,runId:n,systemIds:c,createRun:m,parentToolId:l,stepIndex:u,stepId:d,signal:g,stream:p}){let b={step:e,payload:t,files:a,previousResults:i,credentials:s,options:r,runId:n,systemIds:c,createRun:m,parentToolId:l,stepIndex:u,stepId:d};return p?this.streamRequest("/v1/tools/step/run",b,g):this.restRequest("POST","/v1/tools/step/run",b,void 0,g?{signal:g}:void 0)}async abortStep(e){return this.restRequest("POST","/v1/tools/step/abort",{runId:e})}async executeTransformOnly({outputTransform:e,outputSchema:t,inputSchema:a,payload:i,files:s,stepResults:r,options:n,runId:c,createRun:m,parentToolId:l,stepId:u,signal:d,stream:g}){let p={outputTransform:e,outputSchema:t,inputSchema:a,payload:i,files:s,stepResults:r,options:n,runId:c,createRun:m,parentToolId:l,stepId:u};return g?this.streamRequest("/v1/tools/transform/run",p,d):this.restRequest("POST","/v1/tools/transform/run",p,void 0,d?{signal:d}:void 0)}async createRun({toolId:e,toolConfig:t,toolResult:a,stepResults:i,toolPayload:s,status:r,error:n,startedAt:c,completedAt:m,executionKind:l,parentToolId:u,draftId:d}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:t,toolResult:a,stepResults:i,toolPayload:s,status:r,error:n,startedAt:(0,La.toUTCISOString)(c,"run.startedAt"),completedAt:(0,La.toUTCISOString)(m,"run.completedAt"),executionKind:l,parentToolId:u,draftId:d})}async checkRunLimit(){return(await this.restRequest("POST","/v1/runs/check-limit")).data}async extract({file:e,envelope:t}){if(!e)throw new Error("File must be provided for extract.");let a=new FormData;a.append("file",e);let i=new URL(`${this.apiEndpoint.replace(/\/$/,"")}/v1/extract`);t&&i.searchParams.set("envelope","true");let s=i.toString(),r=await this.getApiKey(),n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:a});if(!n.ok){let c=await n.text(),m=`HTTP ${n.status}: ${c}`;try{let l=JSON.parse(c);l.error&&(m=l.error)}catch{}throw new Error(m)}return n.json()}mapOpenAPIRunToRun(e){let t={running:qn.RunStatus.RUNNING,success:qn.RunStatus.SUCCESS,failed:qn.RunStatus.FAILED,aborted:qn.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:t[e.status]??qn.RunStatus.FAILED,toolPayload:e.toolPayload,data:e.data,toolResult:e.data,error:e.error,stepResults:e.stepResults,options:e.options,requestSource:e.requestSource,traceId:e.traceId,resultStorageUri:e.resultStorageUri,userId:e.userId,userEmail:e.userEmail,userName:e.userName,metadata:{...e.metadata,executionKind:e.metadata?.executionKind??qn.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,La.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,La.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,La.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,La.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e){let{limit:t=100,page:a=1,toolId:i,search:s,searchUserIds:r,includeTotal:n=!0,startedAfter:c,status:m,requestSources:l,executionKinds:u,userId:d,systemId:g,signal:p}=e??{},b=new URLSearchParams({limit:String(t),page:String(a)});i&&b.set("toolId",i),s?.trim()&&b.set("search",s.trim()),r&&r.length>0&&b.set("searchUserIds",r.join(",")),n||b.set("includeTotal","false"),c&&b.set("startedAfter",c instanceof Date?(0,La.toUTCISOString)(c,"run.startedAfter"):c),m&&b.set("status",m),l&&l.length>0&&b.set("requestSources",l.join(",")),u&&u.length>0&&b.set("executionKinds",u.join(",")),d&&b.set("userId",d),g&&b.set("systemId",g);let w=await this.restRequest("GET",`/v1/runs?${b.toString()}`,void 0,void 0,{signal:p});return{items:w.data.map(k=>this.mapOpenAPIRunToRun(k)),total:w.total,page:w.page,limit:w.limit,hasMore:w.hasMore}}async getActivityCounts(e){let t=new URLSearchParams;e?.from&&t.set("from",e.from instanceof Date?(0,La.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&t.set("to",e.to instanceof Date?(0,La.toUTCISOString)(e.to,"activity.to"):e.to);let a=t.toString();return(await this.restRequest("GET",`/v1/activity/counts${a?`?${a}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let t=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(t)}catch(t){if(t.message?.includes("404")||t.message?.includes("not found"))return null;throw t}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(t){if(t.message?.includes("404")||t.message?.includes("not found")||t.message?.includes("403")||t.message?.includes("not allowed"))return null;throw t}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,t){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:t})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,t=!0){return this.updateTool(e,{archived:t})}async bulkArchiveTools(e,t=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:t})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e=10,t=0,a=!1){let i=Math.floor(t/e)+1,s=a?"&includeArchived=true":"",r=await this.restRequest("GET",`/v1/tools?limit=${e}&page=${i}${s}`);return{items:r.data,total:r.total}}async createTool(e,t){return this.restRequest("POST","/v1/tools",{...t,id:e})}async updateTool(e,t){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,t)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(t){if(t.message?.includes("404"))return!1;throw t}}async renameTool(e,t){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:t})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,t=!0){return this.upsertWorkflow(e,{archived:t})}async listWorkflows(e=10,t=0,a=!1){return this.listTools(e,t,a)}async createWorkflow(e,t){return this.createTool(e,t)}async updateWorkflow(e,t){return this.updateTool(e,t)}async upsertWorkflow(e,t){return await this.getTool(e)?this.updateTool(e,t):this.createTool(e,t)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,t){return this.renameTool(e,t)}async listToolSchedules(e){if(e&&typeof e=="object")return this.listToolSchedulesPage(e);let t=[],a=typeof e=="string"?e:void 0,i=1;for(;;){let s=await this.listToolSchedulesPage({toolId:a,limit:1e3,page:i});if(t.push(...s.items),!s.hasMore||s.items.length===0)break;i+=1}return t}async listToolSchedulesPage(e){let{toolId:t,limit:a=100,page:i=1}=e??{},s=new URLSearchParams({limit:String(a),page:String(i)}),r=t?`/v1/tools/${encodeURIComponent(t)}/schedules?${s.toString()}`:`/v1/schedules?${s.toString()}`,n=await this.restRequest("GET",r);return{items:n.data.map(c=>this.mapOpenAPIScheduleToToolSchedule(c)),total:n.total,page:n.page,limit:n.limit,hasMore:n.hasMore}}async getToolSchedule(e,t){try{let a=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`);return this.mapOpenAPIScheduleToToolSchedule(a)}catch(a){if(a.message?.includes("404")||a.message?.includes("not found"))return null;throw a}}async createToolSchedule(e,t){let a=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...t,timezone:t.timezone||(0,_ce.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(a)}async updateToolSchedule(e,t,a){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`,a);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,t){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`),!0}async bulkSetSchedulesEnabled(e,t){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:t})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listCredentials(e){let t=new URLSearchParams;e?.systemId&&t.set("systemId",e.systemId);let a=t.toString();return(await this.restRequest("GET",`/v1/credentials${a?`?${a}`:""}`)).data.items}async createCredentials(e){return(await this.restRequest("POST","/v1/credentials",e)).data}async replaceCredentials(e,t){return(await this.restRequest("PUT",`/v1/credentials/${encodeURIComponent(e)}`,{credentials:t})).data}async updateCredentials(e,t){return(await this.restRequest("PATCH",`/v1/credentials/${encodeURIComponent(e)}`,t)).data}async deleteCredentials(e){await this.restRequest("DELETE",`/v1/credentials/${encodeURIComponent(e)}`)}async setDefaultCredentials(e){await this.restRequest("POST",`/v1/credentials/${encodeURIComponent(e)}/default`)}async listSystems(e=10,t=1){let a=new URLSearchParams({limit:String(e),page:String(t)}),i=await this.restRequest("GET",`/v1/systems?${a.toString()}`);return{items:i.data,total:i.total}}async getSystem(e){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}`)).data}async createSystem(e){return(await this.restRequest("POST","/v1/systems",e)).data}async updateSystem(e,t){return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(e)}`,t)).data}async deleteSystem(e){return await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}`),!0}async bulkDeleteSystems(e){return this.restRequest("POST","/v1/systems/bulk/delete",{ids:e})}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,t){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,t)).data}async searchSystemDocumentation(e,t){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/search`,{keywords:t})).data}async triggerSystemDocumentationScrapeJob(e,t){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/scrape`,t)).data}async fetchOpenApiSpec(e,t,a){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/openapi`,{url:t,link:a?.link})).data}async createSystemDocumentationFileUploadUrls(e,t,a){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/files`,{files:t.map(s=>({fileName:s.fileName,metadata:{contentType:s.contentType,contentLength:s.contentLength}})),link:a?.link})).data.files}async uploadSystemDocumentationFiles(e,t,a){if(t.length===0)return[];let i=await this.createSystemDocumentationFileUploadUrls(e,t.map(n=>({fileName:n.fileName,contentType:n.contentType,contentLength:n.contentLength})),{link:a?.link}),r=(await Promise.allSettled(i.map(async(n,c)=>{let m=t[c],l=await fetch(n.uploadUrl,{method:"PUT",body:m.content,headers:m.contentType?{"Content-Type":m.contentType}:void 0});if(!l.ok)throw new Error(`Upload failed for ${m.fileName}: ${l.status} ${l.statusText}`);return this.completeSystemDocumentationFileUpload(e,n.id).catch(()=>{}),n.id}))).map((n,c)=>{let m=t[c],l=i[c].id;return n.status==="fulfilled"?{id:l,fileName:m.fileName,contentLength:m.contentLength,status:"uploaded"}:(this.deleteSystemDocumentationFile(e,l).catch(()=>{}),{id:l,fileName:m.fileName,contentLength:m.contentLength,status:"failed",error:n.reason instanceof Error?n.reason.message:"Upload failed"})});if(!a?.settle){let n=r.filter(c=>c.status==="failed");if(n.length>0)throw new Error(n.map(c=>c.error).join("; "))}return r}async completeSystemDocumentationFileUpload(e,t){return this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(t)}/complete`)}async listSystemDocumentationFiles(e,t){let a=new URLSearchParams;t?.length&&a.set("fileIds",t.join(","));let i=a.size>0?`?${a.toString()}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files${i}`)).data}async getSystemDocumentationFileContent(e,t){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(t)}/content`)).data}async deleteSystemDocumentationFile(e,t){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(t)}`)}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(t){return{success:!1,error:t.message}}}};En.SuperglueClient=Vw});var C5=y(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.UnquotedKeyStrategy=Ce.TripleQuoteStrategy=Ce.TrailingCommaStrategy=Ce.SingleQuoteStrategy=Ce.PythonLiteralStrategy=Ce.CommentStrategy=Ce.ResilientJsonParser=Ce.RepairStrategy=void 0;Ce.parseJsonResilient=Fce;Ce.parseJSON=Lce;Ce.isValidJson=Pce;Ce.prettyPrintJson=Hce;Ce.minifyJson=Yce;var _t=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};Ce.RepairStrategy=_t;var _g=class extends _t{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(t,a)=>{let i=a.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let r=JSON.parse(i);return JSON.stringify(r)}catch{return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};Ce.TripleQuoteStrategy=_g;var Fg=class extends _t{constructor(){super(...arguments),this.name="PythonLiteralRepair",this.description="Converts Python literals to JavaScript equivalents"}canApply(e){return/\b(None|True|False)\b/.test(e)}apply(e){return e.replace(/\bNone\b/g,"null").replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false")}};Ce.PythonLiteralStrategy=Fg;var Lg=class extends _t{constructor(){super(...arguments),this.name="TrailingCommaRepair",this.description="Removes trailing commas from objects and arrays"}canApply(e){return/,\s*[}\]]/.test(e)}apply(e){return e.replace(/,(\s*[}\]])/g,"$1")}};Ce.TrailingCommaStrategy=Lg;var Pg=class extends _t{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let t=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return t=t.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),t}};Ce.SingleQuoteStrategy=Pg;var Hg=class extends _t{constructor(){super(...arguments),this.name="UnquotedKeyRepair",this.description="Adds quotes to unquoted object keys"}canApply(e){return/[{,]\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*:/.test(e)}apply(e){return e.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g,'$1"$2"$3')}};Ce.UnquotedKeyStrategy=Hg;var Yg=class extends _t{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),t}};Ce.CommentStrategy=Yg;var Ww=class extends _t{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(t){let a=t.message||"";return a.includes("control character")||a.includes("Bad control")||a.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let t="",a=!1,i=!1;for(let s=0;s<e.length;s++){let r=e[s],n=s>0?e[s-1]:"";if(i){t+=r,i=!1;continue}if(r==="\\"&&a){t+=r,i=!0;continue}if(r==='"'&&n!=="\\"){a=!a,t+=r;continue}if(a)switch(r){case`
|
|
1400
1400
|
`:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;case"\b":t+="\\b";break;case"\f":t+="\\f";break;default:let c=r.charCodeAt(0);c<32?t+="\\u"+("0000"+c.toString(16)).slice(-4):t+=r}else t+=r}return t}},$w=class extends _t{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return!1;let a=0,i=0,s=!1,r=!1;for(let n=0;n<t.length;n++){let c=t[n];if(s)r?r=!1:c==="\\"?r=!0:c==='"'&&(s=!1);else if(c==='"')s=!0;else if(c==="{")a++;else if(c==="}"){if(a--,a===0&&i===0&&n>0&&n<t.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&a===0&&n>0&&n<t.length-1))return!0}return!1}apply(e){let t=e.trim(),a=0,i=0,s=!1,r=!1,n=-1;for(let c=0;c<t.length;c++){let m=t[c];if(s)r?r=!1:m==="\\"?r=!0:m==='"'&&(s=!1);else if(m==='"')s=!0;else if(m==="{")a++;else if(m==="}"){if(a--,a===0&&i===0&&c>0){n=c;break}}else if(m==="[")i++;else if(m==="]"&&(i--,i===0&&a===0&&c>0)){n=c;break}}return n>0&&n<t.length-1?t.substring(0,n+1):e}},In=class{constructor(e={}){this.strategies=[],this.repairLog=[],this.options={attemptRepair:!0,maxDepth:10,preserveStringsOnFailure:!1,logRepairs:!1,...e},this.initializeDefaultStrategies(),e.customStrategies&&this.strategies.push(...e.customStrategies)}initializeDefaultStrategies(){this.strategies=[new _g,new Pg,new Ww,new $w,new Fg,new Lg,new Hg,new Yg]}parse(e){let t=Date.now();this.repairLog=[];let a=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(a),metadata:{parseTime:Date.now()-t,strategiesApplied:[]}}}catch(r){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${r}`,metadata:{parseTime:Date.now()-t}}}let i=a,s=[];for(let r of this.strategies)if(r.canApply(i)){let n=i;if(i=r.apply(i),n!==i){s.push(r.name),this.repairLog.push(r.description),this.options.logRepairs&&console.log(`Applied ${r.name}: ${r.description}`);try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:s}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:s}}}catch(r){let n=this.aggressiveFallback(i);return n.success?{...n,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-t,strategiesApplied:[...s,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${s.length} strategies: ${r}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:s}}}}aggressiveFallback(e){try{let t=e.indexOf("{"),a=e.indexOf("[");if(t===-1&&a===-1)return{success:!1,error:"No JSON-like structure found"};let i=t===-1?a:a===-1?t:Math.min(t,a),s=e.substring(i);for(let n of this.strategies)n.canApply(s)&&(s=n.apply(s));return{success:!0,data:JSON.parse(s)}}catch(t){return{success:!1,error:`Aggressive fallback failed: ${t}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(t=>t.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};Ce.ResilientJsonParser=In;var I5=new In;function Fce(o,e){return(e?new In(e):I5).parse(o)}function Lce(o){let e=I5.parse(o);if(e.success)return e.repairs&&e.repairs.length>0&&console.log("JSON parsed with repairs:",e.repairs),e.data;throw new Error(`Failed to parse JSON: ${e.error}`)}function Pce(o){try{return JSON.parse(o),!0}catch{return!1}}function Hce(o,e=2){return JSON.stringify(o,null,e)}function Yce(o){let t=new In().parse(o);if(t.success)return JSON.stringify(t.data);throw new Error("Cannot minify invalid JSON")}});var wt=y(H=>{"use strict";var Gce=H&&H.__createBinding||(Object.create?(function(o,e,t,a){a===void 0&&(a=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(o,a,i)}):(function(o,e,t,a){a===void 0&&(a=t),o[a]=e[t]})),ee=H&&H.__exportStar||function(o,e){for(var t in o)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Gce(e,o,t)};Object.defineProperty(H,"__esModule",{value:!0});H.SSELogSubscriptionManager=H.SuperglueHttpError=H.SuperglueClient=void 0;ee(Y1(),H);ee(X1(),H);ee(iE(),H);ee(cE(),H);ee(Sc(),H);ee(zE(),H);ee(qE(),H);ee(EE(),H);ee(IE(),H);ee(CE(),H);ee(jE(),H);ee(QE(),H);ee(SE(),H);ee(DE(),H);ee(TE(),H);ee(ul(),H);ee(UE(),H);ee(ME(),H);ee(_E(),H);ee(PE(),H);ee(YE(),H);ee(KE(),H);ee(XE(),H);ee(o2(),H);ee(g2(),H);ee(h2(),H);ee(Kf(),H);ee(q2(),H);ee(ib(),H);ee(j2(),H);ee(D2(),H);ee(T2(),H);ee(zt(),H);ee(Vt(),H);ee(N2(),H);ee(U2(),H);ee(Eu(),H);ee(xr(),H);ee(du(),H);var j5=E5();Object.defineProperty(H,"SuperglueClient",{enumerable:!0,get:function(){return j5.SuperglueClient}});Object.defineProperty(H,"SuperglueHttpError",{enumerable:!0,get:function(){return j5.SuperglueHttpError}});var Vce=nb();Object.defineProperty(H,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return Vce.SSELogSubscriptionManager}});ee(C5(),H)});var xp=require("commander");var So=$(require("fs")),S5=$(require("os")),Pa=$(require("path")),Wm=$(wt()),Q5=new Set(["runner","builder","admin"]),B5={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function Ha(o){let e=Pa.join(process.cwd(),".superglue"),t=S5.homedir();if(!t)return e;let a=Pa.join(t,".superglue");return o===!0?e:o===!1?a:So.existsSync(Pa.join(e,"config.json"))?e:a}function Jw(o){return Pa.join(Ha(o),"config.json")}function Gg(o){let e=Jw(o);if(!So.existsSync(e))return{};try{return JSON.parse(So.readFileSync(e,"utf-8"))}catch{return{}}}function Cn(o){let e=Gg(),t=o.apiKey||(0,Wm.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",a=o.endpoint||(0,Wm.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,Wm.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||a.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),s=(0,Wm.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),r=s&&Q5.has(s)?s:e.preset&&Q5.has(e.preset)?e.preset:"admin";return{...B5,...e,apiKey:t,endpoint:a,webEndpoint:i,preset:r,output:{...B5.output,...e.output}}}function Vg(o,e){let t=Ha(e);So.existsSync(t)||So.mkdirSync(t,{recursive:!0}),So.writeFileSync(Pa.join(t,"config.json"),JSON.stringify(o,null,2)+`
|
|
1401
|
-
`,{mode:384})}function Wg(o,e){let t=Pa.join(Ha(e),"drafts");if(So.existsSync(t)||So.mkdirSync(t,{recursive:!0}),o.output.mode==="stdout+file"){let a=Pa.resolve(o.output.directory);So.existsSync(a)||So.mkdirSync(a,{recursive:!0})}}var av=$(wt());var Kw=$(require("readline"));var T5=require("child_process"),N5=require("util");var D5={name:"@superglue/cli",version:"1.1.
|
|
1401
|
+
`,{mode:384})}function Wg(o,e){let t=Pa.join(Ha(e),"drafts");if(So.existsSync(t)||So.mkdirSync(t,{recursive:!0}),o.output.mode==="stdout+file"){let a=Pa.resolve(o.output.directory);So.existsSync(a)||So.mkdirSync(a,{recursive:!0})}}var av=$(wt());var Kw=$(require("readline"));var T5=require("child_process"),N5=require("util");var D5={name:"@superglue/cli",version:"1.1.48",bin:{sg:"./dist/cli.js"},files:[".claude-plugin/","dist/","skills/","LICENSE"],dependencies:{commander:"15.0.0-0","fast-json-patch":"3.1.1"},devDependencies:{"@superglue/shared":"file:../shared","@types/node":"25.5.0",tsup:"8.5.1",typescript:"5.8.3"},scripts:{build:"tsup && (cp -r skills dist/ 2>/dev/null || true)",dev:"tsup --watch","type-check":"tsc --noEmit",prepublishOnly:"npm run build"},publishConfig:{access:"public"}};var $ce=(0,N5.promisify)(T5.exec),Ao=D5.version;function R5(o){let e=o.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:o}}function Jg(o,e){let t=o.split("."),a=e.split("."),i=Math.max(t.length,a.length);for(let s=0;s<i;s++){let r=R5(t[s]||"0"),n=R5(a[s]||"0");if(r.numeric<n.numeric)return-1;if(r.numeric>n.numeric||r.prerelease===null&&n.prerelease!==null)return 1;if(r.prerelease!==null&&n.prerelease===null)return-1;if(r.prerelease!==null&&n.prerelease!==null){if(r.prerelease<n.prerelease)return-1;if(r.prerelease>n.prerelease)return 1}}return 0}async function Kg(){try{let o=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return o.ok&&(await o.json()).version||null}catch{return null}}var $g=null;function U5(){Y()&&($g=Kg())}async function M5(){if(!(!Y()||!$g)){try{let o=new Promise(t=>{setTimeout(()=>t(null),2e3).unref()}),e=await Promise.race([$g,o]);e&&Jg(Ao,e)<0&&(console.error(""),console.error(`${h.cyan}${h.bold} Update available: ${Ao} \u2192 ${e}${h.reset}`),console.error(`${h.cyan} Run ${h.bold}sg update${h.reset}${h.cyan} to upgrade${h.reset}`),console.error(""))}catch{}$g=null}}async function O5(){let o=await Kg();if(!o)return{success:!1,message:"Could not fetch latest version from npm"};if(Jg(Ao,o)>=0)return{success:!0,message:`Already on latest version (${Ao})`};try{return await $ce("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${Ao} to ${o}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var Y=()=>process.argv.includes("--table")&&process.stdout.isTTY,vt=()=>process.argv.includes("--full"),h={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m"};function _5(o,e){let t=e||o;return`\x1B]8;;${o}\x07${h.underline}${h.cyan}${t}${h.reset}\x1B]8;;\x07`}function F5(){if(!Y())return;let o=h.reset,e=h.dim,t="\x1B[47;30m",a=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),a.forEach(i=>{let s=i.search(/\S/),r=i.length-[...i].reverse().join("").search(/\S/)-1;if(s===-1)return console.log(" "+i);let n=i.slice(0,s),c=i.slice(s,r+1).split("").map(l=>l===" "?" ":"\u2588").join(""),m=i.slice(r+1);console.log(` ${n}${t}${c}${o}${m}`)}),console.log(` ${e} CLI v${Ao}${o}`),console.log("")}function Ee(o){if(!Y())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],t=0,a=o,i=()=>process.stdout.write("\r\x1B[2K"),s=()=>{process.stdout.write(`\r ${h.cyan}${e[t++%e.length]}${h.reset} ${a}`)},r=setInterval(s,80);return{update:n=>{a=n},log:n=>{i(),console.log(` ${h.dim}\u2502${h.reset} ${n}`),s()},stop:n=>{clearInterval(r),i(),n&&console.log(` ${n}`)}}}function U(o){Y()?Zg(o):console.log(JSON.stringify(o,null,2))}function ie(o,e){Y()?(console.log(` ${h.green}\u2713${h.reset} ${o}`),e&&Zg(e,4)):console.log(JSON.stringify({success:!0,message:o,...e&&typeof e=="object"?e:{data:e}}))}function z(o,e){Y()?(console.error(` ${h.red}\u2717${h.reset} ${o}`),e&&Zg(e,4)):console.error(JSON.stringify({success:!1,error:o,details:e}))}function L5(o){Y()&&console.log(` ${h.yellow}\u26A0${h.reset} ${o}`)}function mo(o){Y()&&console.log(` ${h.dim}${o}${h.reset}`)}function Ya(o){Y()&&(console.log(`
|
|
1402
1402
|
${h.bold}${h.cyan}${o}${h.reset}`),console.log(` ${h.dim}${"\u2500".repeat(o.length)}${h.reset}`))}function ma(o,e,t){if(!Y()){console.log(JSON.stringify({success:!0,total:t?.total??o.length,items:o}));return}if(o.length===0){console.log(`
|
|
1403
1403
|
${h.dim}0 results${h.reset}
|
|
1404
1404
|
`);return}let a=e||Object.keys(o[0]),i=vt()?1/0:60,s=a.map(l=>Math.min(i,Math.max(l.length,...o.map(u=>String(u[l]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let r=a.map((l,u)=>`${h.bold}${h.cyan}${l.toUpperCase().padEnd(s[u])}${h.reset}`).join(" ");console.log(` ${r}`);let n=s.map(l=>`${h.dim}${"\u2500".repeat(l)}${h.reset}`).join(`${h.dim}\u2500\u2500${h.reset}`);console.log(` ${n}`);for(let l of o){let u=a.map((d,g)=>{let p=String(l[d]??"").replace(/[\n\r]+/g," ").trim();if(p.length>i){let w=`\u2026 (${p.length})`;p=p.slice(0,Math.max(0,i-w.length))+`${h.dim}${w}${h.reset}`}return d==="status"?`${{success:h.green,running:h.yellow,failed:h.red,aborted:h.red,error:h.red,pending:h.dim}[p.toLowerCase()]||""}${p.padEnd(s[g])}${h.reset}`:p.padEnd(s[g])}).join(" ");console.log(` ${u}`)}let c=t?.total??o.length,m=c===o.length?`${o.length} result${o.length===1?"":"s"}`:`${o.length} of ${c} result${c===1?"":"s"}`;console.log(`
|