sindri
Version:
The Sindri Labs JavaScript SDK and CLI tool.
4 lines • 23.1 kB
JavaScript
import{readFile as te,stat as Te}from"fs/promises";import G from"path";import Se from"gzip-js";import Ee from"ignore-walk";import ve from"tar";import Ae from"tar-js";var S=class{constructor(e){this.config=e}};import M from"axios";import{AxiosError as J}from"axios";import se from"@fullstax/p-retry";import{File as re}from"buffer";import{FormData as oe}from"formdata-node";var E=process.env.BROWSER_BUILD?window.File:re,C=process.env.BROWSER_BUILD?window.FormData:oe;var P=class extends Error{url;status;statusText;body;request;constructor(e,r,o){super(o),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=e}};var L=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},v=class{#t;#r;#e;#o;#s;#n;#i;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#o=[],this.#s=new Promise((r,o)=>{this.#n=r,this.#i=o;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#n?.(i))},a=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#i?.(i))},n=i=>{this.#t||this.#r||this.#e||this.#o.push(i)};return Object.defineProperty(n,"isResolved",{get:()=>this.#t}),Object.defineProperty(n,"isRejected",{get:()=>this.#r}),Object.defineProperty(n,"isCancelled",{get:()=>this.#e}),e(s,a,n)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,r){return this.#s.then(e,r)}catch(e){return this.#s.catch(e)}finally(e){return this.#s.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#o.length)try{for(let e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#i?.(new L("Request aborted"))}}get isCancelled(){return this.#e}};var U=t=>t!=null,k=t=>typeof t=="string",$=t=>k(t)&&t!=="",Z=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),ie=t=>t instanceof C,ne=t=>t>=200&&t<300,ae=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},pe=t=>{let e=[],r=(s,a)=>{e.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(a))}`)},o=(s,a)=>{U(a)&&(Array.isArray(a)?a.forEach(n=>{o(s,n)}):typeof a=="object"?Object.entries(a).forEach(([n,i])=>{o(`${s}[${n}]`,i)}):r(s,a))};return Object.entries(t).forEach(([s,a])=>{o(s,a)}),e.length>0?`?${e.join("&")}`:""},ue=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,o=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(a,n)=>e.path?.hasOwnProperty(n)?r(String(e.path[n])):a),s=`${t.BASE}${o}`;return e.query?`${s}${pe(e.query)}`:s},le=t=>{if(t.formData){if(t.formData instanceof C)return t.formData;let e=new C,r=(o,s)=>{k(s)||Z(s)?e.append(o,s):e.append(o,JSON.stringify(s))};return Object.entries(t.formData).filter(([o,s])=>U(s)).forEach(([o,s])=>{Array.isArray(s)?s.forEach(a=>r(o,a)):r(o,s)}),e}},j=async(t,e)=>typeof e=="function"?e(t):e,ce=async(t,e,r)=>{let o=await j(e,t.TOKEN),s=await j(e,t.USERNAME),a=await j(e,t.PASSWORD),n=await j(e,t.HEADERS),i=r&&"getHeaders"in r&&typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...n,...e.headers,...i}).filter(([l,u])=>U(u)).reduce((l,[u,m])=>({...l,[u]:String(m)}),{});if($(o)&&(p.Authorization=`Bearer ${o}`),$(s)&&$(a)){let l=ae(`${s}:${a}`);p.Authorization=`Basic ${l}`}return e.body&&(e.mediaType?p["Content-Type"]=e.mediaType:Z(e.body)?p["Content-Type"]=e.body.type||"application/octet-stream":k(e.body)?p["Content-Type"]="text/plain":ie(e.body)||(p["Content-Type"]="application/json")),p},me=t=>{if(t.body)return t.body},V=t=>!!(M.isAxiosError(t)&&(t.response?.status&&[502,503,504].includes(t.response.status)||t.code&&["ECONNREFUSED","ECONNRESET","ENOTFOUND","ENETUNREACH",J.ECONNABORTED,J.ERR_NETWORK].includes(t.code))),de=async(t,e,r,o,s,a,n,i)=>{let p=M.CancelToken.source(),l={url:r,headers:a,data:o??s,method:e.method,withCredentials:t.WITH_CREDENTIALS,cancelToken:p.token,responseType:e.responseType};n(()=>p.cancel("The user aborted a request."));try{return t.sindri?await se(()=>i.request(l),{...t.sindri.retryOptions,onFailedAttempt:u=>{V(u)&&t.sindri.logger.debug({attemptNumber:u.attemptNumber,error:u.message,retriesLeft:u.retriesLeft},`${e.method} ${r} - Request failed, ${u.retriesLeft>0?"retrying":"aborting..."}...`)},shouldRetry:V}):await i.request(l)}catch(u){let m=u;if(m.response)return m.response;throw u}},fe=(t,e)=>{if(e){let r=t.headers[e];if(k(r))return r}},he=t=>{if(t.status!==204)return t.data},Re=(t,e)=>{let o={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(o)throw new P(t,e,o);if(!e.ok){let s=e.status??"unknown",a=e.statusText??"unknown",n=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new P(t,e,`Generic Error: status: ${s}; status text: ${a}; body: ${n}`)}},Q=(t,e,r=M)=>new v(async(o,s,a)=>{let n=Date.now(),i=()=>{let u=Date.now()-n;if(u<1e3)return`${u} ms`;let m=u/1e3;if(m<60)return`${m.toFixed(2)} s`;let h=m/60;return h<60?`${h.toFixed(2)} m`:`${(h/60).toFixed(2)} h`},p=ue(t,e),l=`${e.method} ${p}`;try{let u=le(e),m=me(e),h=await ce(t,e,u);if(!a.isCancelled){t.sindri?.logger.debug(`${l} requested`);let c=await de(t,e,p,m,u,h,a,r),b=he(c),T=fe(c,e.responseHeader),R={url:p,ok:ne(c.status),status:c.status,statusText:c.statusText,body:T??b},g=`${l} ${c.status} ${c.statusText} (${i()})`;!R.body||typeof R.body=="string"?t.sindri?.logger.debug(`${g} - ${R.body||"<empty-body>"}`):e.responseType==="stream"?t.sindri?.logger.debug(`${g} - <streaming-response>`):e.responseType==="blob"?t.sindri?.logger.debug(`${g} - <blob-response>`):t.sindri?.logger.debug(R.body,g),Re(e,R),o(R.body)}}catch(u){let m=u instanceof Error?u.message:"Unknown error";t.sindri?.logger.debug(`${l} ERROR (${i()}) - ${m}`),s(u)}});var F=class extends S{constructor(e){super(e)}request(e){return Q(this.config,e)}};var A=class{constructor(e){this.httpRequest=e}apikeyGenerate(e,r){return this.httpRequest.request({method:"POST",url:"/api/apikey/generate",headers:{"Sindri-Team-Id":r},body:e,mediaType:"application/json",errors:{400:"Bad Request",401:"Unauthorized",403:"Forbidden"}})}apikeyGenerateWithAuth(e){return this.httpRequest.request({method:"POST",url:"/api/v1/apikey/generate",query:{name:e},errors:{400:"Bad Request"}})}apikeyList(){return this.httpRequest.request({method:"GET",url:"/api/v1/apikey/list",errors:{500:"Internal Server Error"}})}apikeyDelete(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/apikey/{apikey_id}/delete",path:{apikey_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}};var x=class{constructor(e){this.httpRequest=e}circuitCreate(e){return this.httpRequest.request({method:"POST",url:"/api/v1/circuit/create",formData:e,mediaType:"multipart/form-data",errors:{400:"Bad Request",422:"Unprocessable Entity",500:"Internal Server Error",501:"Not Implemented"}})}circuitList(){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/list",errors:{500:"Internal Server Error"}})}circuitDetail(e,r=!0){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/detail",path:{circuit_id:e},query:{include_verification_key:r},errors:{404:"Not Found",500:"Internal Server Error"}})}circuitDelete(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/circuit/{circuit_id}/delete",path:{circuit_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}circuitProofs(e){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/proofs",path:{circuit_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}proofCreate(e,r){return this.httpRequest.request({method:"POST",url:"/api/v1/circuit/{circuit_id}/prove",path:{circuit_id:e},body:r,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",501:"Not Implemented"}})}};var O=class{constructor(e){this.httpRequest=e}circuitDownload(e,r){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/download",path:{circuit_id:e},query:{path:r},errors:{404:"Not Found",500:"Internal Server Error"},responseType:process.env.BROWSER_BUILD?"blob":"stream"})}circuitProofsPaginated(e,r=100,o){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/proofs/paginated",path:{circuit_id:e},query:{limit:r,offset:o},errors:{404:"Not Found",500:"Internal Server Error"}})}projectCircuits(e){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/circuits",path:{project_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectCircuitsPaginated(e,r=100,o){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/circuits/paginated",path:{project_id:e},query:{limit:r,offset:o},errors:{404:"Not Found",500:"Internal Server Error"}})}projectDelete(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/project/{project_id}/delete",path:{project_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectDetail(e){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/detail",path:{project_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectList(e){return this.httpRequest.request({method:"POST",url:"/api/v1/project/list",body:e,mediaType:"application/json",errors:{404:"Not Found",500:"Internal Server Error"}})}projectListPaginated(e,r=100,o){return this.httpRequest.request({method:"POST",url:"/api/v1/project/list/paginated",query:{limit:r,offset:o},body:e,mediaType:"application/json",errors:{404:"Not Found",500:"Internal Server Error"}})}projectProofs(e){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/proofs",path:{project_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectProofsPaginated(e,r=100,o){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/proofs/paginated",path:{project_id:e},query:{limit:r,offset:o},errors:{404:"Not Found",500:"Internal Server Error"}})}projectSettings(e,r){return this.httpRequest.request({method:"POST",url:"/api/v1/project/{project_name}/settings",path:{project_name:e},body:r,mediaType:"application/json",errors:{404:"Not Found",422:"Unprocessable Entity",500:"Internal Server Error"}})}circuitSmartContractVerifier(e){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/smart_contract_verifier",path:{circuit_id:e},errors:{404:"Not Found",409:"Conflict",500:"Internal Server Error",501:"Not Implemented"}})}circuitStatus(e){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/status",path:{circuit_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}passwordChangeWithJwtAuth(e){return this.httpRequest.request({method:"POST",url:"/api/v1/password/change",body:e,mediaType:"application/json",errors:{422:"Unprocessable Entity"}})}proofHistogram(e){return this.httpRequest.request({method:"POST",url:"/api/v1/proof/histogram",body:e,mediaType:"application/json",errors:{500:"Internal Server Error"}})}proofList(e){return this.httpRequest.request({method:"POST",url:"/api/v1/proof/list",body:e,mediaType:"application/json",errors:{500:"Internal Server Error"}})}proofListPaginated(e,r=100,o){return this.httpRequest.request({method:"POST",url:"/api/v1/proof/list/paginated",query:{limit:r,offset:o},body:e,mediaType:"application/json",errors:{500:"Internal Server Error"}})}proofStatus(e){return this.httpRequest.request({method:"GET",url:"/api/v1/proof/{proof_id}/status",path:{proof_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}sindriManifestSchema(){return this.httpRequest.request({method:"GET",url:"/api/v1/sindri-manifest-schema.json"})}teamAvatarUpload(e){return this.httpRequest.request({method:"POST",url:"/api/v1/team/avatar/upload",formData:e,mediaType:"multipart/form-data",errors:{400:"Bad Request",500:"Internal Server Error"}})}teamCreate(e,r){return this.httpRequest.request({method:"POST",url:"/api/v1/team/create",headers:{"Sindri-Team-Id":r},body:e,mediaType:"application/json",errors:{400:"Bad Request",409:"Conflict",500:"Internal Server Error"}})}teamDetail(e){return this.httpRequest.request({method:"GET",url:"/api/v1/team/{team_slug}/detail",path:{team_slug:e},errors:{404:"Not Found"}})}teamInvite(e,r){return this.httpRequest.request({method:"POST",url:"/api/v1/team/invite",headers:{"Sindri-Team-Id":r},body:e,mediaType:"application/json"})}teamMe(){return this.httpRequest.request({method:"GET",url:"/api/v1/team/me"})}teamMembers(e,r){return this.httpRequest.request({method:"GET",url:"/api/v1/team/{team_slug}/members",path:{team_slug:e},headers:{"Sindri-Team-Id":r},errors:{404:"Not Found"}})}teamRemoveMember(e,r){return this.httpRequest.request({method:"POST",url:"/api/v1/team/remove-member",headers:{"Sindri-Team-Id":r},body:e,mediaType:"application/json",errors:{403:"Forbidden",404:"Not Found"}})}teamSettings(e){return this.httpRequest.request({method:"POST",url:"/api/v1/team/settings",body:e,mediaType:"application/json",errors:{404:"Not Found",422:"Unprocessable Entity",500:"Internal Server Error"}})}userLogin(e){return this.httpRequest.request({method:"POST",url:"/api/v1/user/login",body:e,mediaType:"application/json",errors:{401:"Unauthorized",403:"Forbidden"}})}userLogout(){return this.httpRequest.request({method:"POST",url:"/api/v1/user/logout"})}userMe(){return this.httpRequest.request({method:"GET",url:"/api/v1/user/me"})}};var q=class{constructor(e){this.httpRequest=e}proofDetail(e,r=!0,o=!0,s=!0,a=!0){return this.httpRequest.request({method:"GET",url:"/api/v1/proof/{proof_id}/detail",path:{proof_id:e},query:{include_proof:r,include_public:o,include_smart_contract_calldata:s,include_verification_key:a},errors:{404:"Not Found",500:"Internal Server Error",501:"Not Implemented"}})}proofDelete(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/proof/{proof_id}/delete",path:{proof_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}};var w=class{constructor(e){this.httpRequest=e}jwtTokenVerify(e){return this.httpRequest.request({method:"POST",url:"/api/token/verify",body:e,mediaType:"application/json"})}jwtTokenGenerate(e){return this.httpRequest.request({method:"POST",url:"/api/token/pair",body:e,mediaType:"application/json",errors:{403:"Forbidden"}})}jwtTokenRefresh(e){return this.httpRequest.request({method:"POST",url:"/api/token/refresh",body:e,mediaType:"application/json"})}};var N=class{authorization;circuits;internal;proofs;token;request;constructor(e,r=F){this.request=new r({BASE:e?.BASE??"https://sindri.app",VERSION:e?.VERSION??"1.17.19",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.authorization=new A(this.request),this.circuits=new x(this.request),this.internal=new O(this.request),this.proofs=new q(this.request),this.token=new w(this.request)}};import D from"fs";import Y from"path";import ye from"env-paths";import _ from"lodash";import{z as y}from"zod";var X=()=>{let t=ye("sindri",{suffix:""});return Y.join(t.config,"sindri.conf.json")},z=y.object({auth:y.nullable(y.object({apiKey:y.string(),apiKeyId:y.string(),apiKeyName:y.string(),baseUrl:y.string().url(),teamId:y.number(),teamSlug:y.string()})).default(null)}),ge=z.parse({}),be=t=>{let e=X();if(D.existsSync(e)){t?.debug(`Loading config from "${e}".`);try{let r=D.readFileSync(e,{encoding:"utf-8"}),o=z.parse(JSON.parse(r));return t?.debug("Config loaded successfully."),o}catch(r){t?.warn(`The config schema in "${e}" is invalid and will not be used.
To remove it and start fresh, run:
rm ${e}`),t?.debug(r)}}return t?.debug(`Config file "${e}" does not exist, initializing default config.`),_.cloneDeep(ge)},B=class{_config;logger;constructor(e){this.logger=e,this.reload()}get auth(){return _.cloneDeep(this._config.auth)}get config(){return _.cloneDeep(this._config)}reload(){this._config=be(this.logger)}update(e){this.logger?.debug("Merging in config update:"),this.logger?.debug(e);let r=_.cloneDeep(this._config);_.merge(r,e),this._config=z.parse(r);let o=X(),s=Y.dirname(o);D.existsSync(s)||D.mkdirSync(s,{recursive:!0}),this.logger?.debug(`Writing merged config to "${o}":`,this._config),D.writeFileSync(o,JSON.stringify(this._config,null,2),{encoding:"utf-8"})}};import Ie from"pino";import Ce from"pino-pretty";var K=t=>{let e=Ie(process.env.BROWSER_BUILD?{browser:{asObject:!0}}:Ce({colorize:!0,destination:2,ignore:"hostname,pid",levelFirst:!1,sync:!0}));return e.level=t??!0?"silent":"info",e},Ft=K();var I=null;function Pe({cache:t=!0,logger:e,raiseExceptions:r=!1}={}){if(t&&I)return I;if(process.env.BROWSER_BUILD)return I={};let{SINDRI_META:o}=process.env;if(!o)return I={};let s=([n,i])=>{if(typeof i!="string"){let l=`Invalid metadata entry for '${n}' (value must be a string).`;if(r)throw new Error(l);return e?.warn({key:n,value:i,SINDRI_META:o},l+" Ignoring."),!1}let p=ee(n,i);if(p){if(r)throw new Error(p);return e?.warn({key:n,value:i,SINDRI_META:o},p+" Ignoring."),!1}return!0};if(o.startsWith("{"))try{return I=Object.fromEntries(Object.entries(JSON.parse(o)).filter(s))}catch(n){let i="Failed to parse 'SINDRI_META' as JSON.";if(r)throw new Error(i);return e?.warn({SINDRI_META:o,error:n.toString()},i+" Using '{}' as the default."),I={}}let a="\0";return I=Object.fromEntries(o.replace(/::/g,a).split(":").map(n=>n.replace(new RegExp(a,"g"),":")).filter(n=>{if(!n.includes("=")){let i=`Invalid 'SINDRI_META' metadata segment '${n}' (missing '=', try 'key=value').`;if(r)throw new Error(i);return e?.warn({segment:n,SINDRI_META:o},i+" Ignoring."),!1}return!0}).map(n=>{let i=n.indexOf("=");return[n.slice(0,i),n.slice(i+1)]}).filter(s))}function W(t){let e=Pe({raiseExceptions:!0});return Object.entries(t).forEach(([r,o])=>{let s=ee(r,o);if(s)throw new Error(s)}),{...e,...t}}function ee(t,e){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;return t.length<1||t.length>64?`Invalid metadata key length for '${t}' (must be 1-64 characters).`:n.test(t)?e.length<0||e.length>4096?`Invalid metadata value length for '${t}' (must be 0-4096 characters).`:null:`Invalid metadata key for '${t}' (must start with an alphabet character and only include alphanumeric characters, underscores, and hyphens).`}var H=class t{_client;_clientConfig;_config;logger;pollingInterval=1e3;retryOptions={minTimeout:1e3,retries:6};constructor(e={},{retryOptions:r}={}){this._client=new N,this._clientConfig=this._client.request.config;let o="v0.0.1-alpha.71";this._clientConfig.HEADERS={...this._clientConfig.HEADERS,"Sindri-Client":`sindri-js-sdk/${o}`},this.logger=K(),process.env.BROWSER_BUILD||(this._config=new B(this.logger)),this._clientConfig.sindri=this,this.authorize(e),r&&(this.retryOptions=structuredClone(r))}get apiKey(){return this._clientConfig.TOKEN&&typeof this._clientConfig.TOKEN!="string"?null:this._clientConfig.TOKEN||null}get baseUrl(){return this._clientConfig.BASE}get logLevel(){return this.logger.level}set logLevel(e){this.logger.level=e,this.logger.debug(`Set log level to "${this.logger.level}".`)}authorize(e){return process.env.BROWSER_BUILD?(this._clientConfig.BASE=e.baseUrl||"https://sindri.app",this._clientConfig.TOKEN=e.apiKey):(this._config.reload(),this._clientConfig.BASE=e.baseUrl||process.env.SINDRI_BASE_URL||this._config.auth?.baseUrl||this._clientConfig.BASE||"https://sindri.app",this._clientConfig.TOKEN=e.apiKey||process.env.SINDRI_API_KEY||this._config.auth?.apiKey),!!(this._clientConfig.BASE&&this._clientConfig.TOKEN)}create(e,r){return new t(e,r)}async createCircuit(e,r=["latest"],o={}){let s=new C;r=typeof r=="string"?[r]:r??[];for(let i of r){if(!/^[-a-zA-Z0-9_.]+$/.test(i))throw new Error(`"${i}" is not a valid tag. Tags may only contain alphanumeric characters, underscores, hyphens, and periods.`);s.append("tags",i)}if(r.length===0&&s.append("tags",""),s.append("meta",JSON.stringify(W(o))),typeof e=="string"){if(process.env.BROWSER_BUILD)throw new Error("Specifying `project` as a path is not allowed in the browser build.");let i;try{i=await Te(e)}catch{throw new Error(`The "${e}" path does not exist or you do not have permission to access it.`)}if(i.isFile()){if(!/\.(zip|tar|tar\.gz|tgz)$/i.test(e))throw new Error("Only gzipped tarballs or zip files are supported.");let p=G.basename(e),l=await te(e);s.append("files",new E([l],p))}else if(i.isDirectory()){let p=G.join(e,"sindri.json"),l;try{l=await te(p,{encoding:"utf-8"})}catch{throw new Error(`Expected Sindri manifest file at "${p}" does not exist.`)}let u;try{u=JSON.parse(l)}catch{throw new Error(`Could not parse "${p}", is it valid JSON?`)}let m=u?.name;if(!m)throw new Error(`No circuit "name" field was found in "${p}", the manifest is invalid.`);let h=Ee.sync({follow:!0,ignoreFiles:[".sindriignore"],path:e}).filter(R=>!/(^|\/)\.git(\/|$)/.test(R)),c=G.basename(p);h.includes(c)||h.push(c);let b=`${m}.tar.gz`;h.sort((R,g)=>R.localeCompare(g));let T=ve.c({cwd:e,gzip:!0,onwarn:(R,g)=>{this.logger.warn(`While creating tarball: ${R} - ${g}`)},prefix:`${m}/`,sync:!0},h);s.append("files",new E([T.read()],b))}else throw new Error(`The "${e}" path is not a file or directory.`)}else if(Array.isArray(e)){if(!e.every(c=>c instanceof E))throw new Error("All entries in `project` must be `File` instances.");let i=e.find(c=>c.name==="sindri.json");if(!i)throw new Error("The `project` array must include a `sindri.json` file.");let p;try{p=JSON.parse(await i.text())}catch{throw new Error('Could not parse "sindri.json", is it valid JSON?')}let l=p?.name;if(!l)throw new Error('No circuit "name" field was found in "sindri.json", the manifest is invalid.');let u=new Ae;e.sort((c,b)=>c.name.localeCompare(b.name));for(let c of e){let b=new Uint8Array(await c.arrayBuffer());await new Promise(T=>u.append(`${l}/${c.name}`,b,T))}let m=new Uint8Array(Se.zip(u.out)),h=new E([m],`${l}.tar.gz`);process.env.BROWSER_BUILD,s.append("files",h)}let n=(await this._client.circuits.circuitCreate(s)).circuit_id;for(;;){let i=await this._client.internal.circuitStatus(n);if(i.status==="Ready"||i.status==="Failed")break;await new Promise(p=>setTimeout(p,this.pollingInterval))}return this._client.circuits.circuitDetail(n,!1)}async getAllCircuitProofs(e){return await this._client.circuits.circuitProofs(e)}async getAllCircuits(){return await this._client.circuits.circuitList()}async getCircuit(e){return await this._client.circuits.circuitDetail(e)}async getProof(e){return await this._client.proofs.proofDetail(e)}async proveCircuit(e,r,o=!1,s=!1,a={}){let i=(await this._client.circuits.proofCreate(e,{meta:W(a),perform_verify:o,proof_input:r})).proof_id;for(;;){let p=await this._client.internal.proofStatus(i);if(p.status==="Ready"||p.status==="Failed")break;await new Promise(l=>setTimeout(l,this.pollingInterval))}return this._client.proofs.proofDetail(i,!0,!0,s,!0)}};var nr=new H;export{nr as default};
//# sourceMappingURL=index.mjs.map