UNPKG

sindri

Version:

The Sindri Labs JavaScript SDK and CLI tool.

6 lines (5 loc) 28.1 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var _promises = require('fs/promises');var _path = require('path'); var _path2 = _interopRequireDefault(_path);var _gzipjs = require('gzip-js'); var _gzipjs2 = _interopRequireDefault(_gzipjs);var _ignorewalk = require('ignore-walk'); var _ignorewalk2 = _interopRequireDefault(_ignorewalk);var _tar = require('tar'); var _tar2 = _interopRequireDefault(_tar);var _tarjs = require('tar-js'); var _tarjs2 = _interopRequireDefault(_tarjs);var T=class{constructor(e){this.config=e}};var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);var _pretry = require('@fullstax/p-retry'); var _pretry2 = _interopRequireDefault(_pretry);var _buffer = require('buffer');var _formdatanode = require('formdata-node');var S=process.env.BROWSER_BUILD?window.File:_buffer.File,I=process.env.BROWSER_BUILD?window.FormData:_formdatanode.FormData;var C=class extends Error{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 D=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},E=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,_optionalChain([this, 'access', _2 => _2.#n, 'optionalCall', _3 => _3(i)]))},a=i=>{this.#t||this.#r||this.#e||(this.#r=!0,_optionalChain([this, 'access', _4 => _4.#i, 'optionalCall', _5 => _5(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,_optionalChain([this, 'access', _6 => _6.#i, 'optionalCall', _7 => _7(new D("Request aborted"))])}}get isCancelled(){return this.#e}};var M=t=>t!=null,j=t=>typeof t=="string",H=t=>j(t)&&t!=="",V=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]),se=t=>t instanceof I,ie=t=>t>=200&&t<300,ne=t=>{try{return btoa(t)}catch (e2){return Buffer.from(t).toString("base64")}},ae=t=>{let e=[],r=(s,a)=>{e.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(a))}`)},o=(s,a)=>{M(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("&")}`:""},pe=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,o=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(a,n)=>_optionalChain([e, 'access', _8 => _8.path, 'optionalAccess', _9 => _9.hasOwnProperty, 'call', _10 => _10(n)])?r(String(e.path[n])):a),s=`${t.BASE}${o}`;return e.query?`${s}${ae(e.query)}`:s},ue=t=>{if(t.formData){if(t.formData instanceof I)return t.formData;let e=new I,r=(o,s)=>{j(s)||V(s)?e.append(o,s):e.append(o,JSON.stringify(s))};return Object.entries(t.formData).filter(([o,s])=>M(s)).forEach(([o,s])=>{Array.isArray(s)?s.forEach(a=>r(o,a)):r(o,s)}),e}},L=async(t,e)=>typeof e=="function"?e(t):e,le=async(t,e,r)=>{let o=await L(e,t.TOKEN),s=await L(e,t.USERNAME),a=await L(e,t.PASSWORD),n=await L(e,t.HEADERS),i=r&&"getHeaders"in r&&typeof _optionalChain([r, 'optionalAccess', _11 => _11.getHeaders])=="function"&&_optionalChain([r, 'optionalAccess', _12 => _12.getHeaders, 'call', _13 => _13()])||{},p=Object.entries({Accept:"application/json",...n,...e.headers,...i}).filter(([l,u])=>M(u)).reduce((l,[u,m])=>({...l,[u]:String(m)}),{});if(H(o)&&(p.Authorization=`Bearer ${o}`),H(s)&&H(a)){let l=ne(`${s}:${a}`);p.Authorization=`Basic ${l}`}return e.body&&(e.mediaType?p["Content-Type"]=e.mediaType:V(e.body)?p["Content-Type"]=e.body.type||"application/octet-stream":j(e.body)?p["Content-Type"]="text/plain":se(e.body)||(p["Content-Type"]="application/json")),p},ce=t=>{if(t.body)return t.body},J=t=>!!(_axios2.default.isAxiosError(t)&&(_optionalChain([t, 'access', _14 => _14.response, 'optionalAccess', _15 => _15.status])&&[502,503,504].includes(t.response.status)||t.code&&["ECONNREFUSED","ECONNRESET","ENOTFOUND","ENETUNREACH",_axios.AxiosError.ECONNABORTED,_axios.AxiosError.ERR_NETWORK].includes(t.code))),me=async(t,e,r,o,s,a,n,i)=>{let p=_axios2.default.CancelToken.source(),l={url:r,headers:a,data:_nullishCoalesce(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 _pretry2.default.call(void 0, ()=>i.request(l),{...t.sindri.retryOptions,onFailedAttempt:u=>{J(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:J}):await i.request(l)}catch(u){let m=u;if(m.response)return m.response;throw u}},de=(t,e)=>{if(e){let r=t.headers[e];if(j(r))return r}},fe=t=>{if(t.status!==204)return t.data},he=(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 C(t,e,o);if(!e.ok){let s=_nullishCoalesce(e.status, () => ("unknown")),a=_nullishCoalesce(e.statusText, () => ("unknown")),n=(()=>{try{return JSON.stringify(e.body,null,2)}catch (e3){return}})();throw new C(t,e,`Generic Error: status: ${s}; status text: ${a}; body: ${n}`)}},Z=(t,e,r=_axios2.default)=>new E(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 f=m/60;return f<60?`${f.toFixed(2)} m`:`${(f/60).toFixed(2)} h`},p=pe(t,e),l=`${e.method} ${p}`;try{let u=ue(e),m=ce(e),f=await le(t,e,u);if(!a.isCancelled){_optionalChain([t, 'access', _16 => _16.sindri, 'optionalAccess', _17 => _17.logger, 'access', _18 => _18.debug, 'call', _19 => _19(`${l} requested`)]);let c=await me(t,e,p,m,u,f,a,r),g=fe(c),P=de(c,e.responseHeader),h={url:p,ok:ie(c.status),status:c.status,statusText:c.statusText,body:_nullishCoalesce(P, () => (g))},y=`${l} ${c.status} ${c.statusText} (${i()})`;!h.body||typeof h.body=="string"?_optionalChain([t, 'access', _20 => _20.sindri, 'optionalAccess', _21 => _21.logger, 'access', _22 => _22.debug, 'call', _23 => _23(`${y} - ${h.body||"<empty-body>"}`)]):e.responseType==="stream"?_optionalChain([t, 'access', _24 => _24.sindri, 'optionalAccess', _25 => _25.logger, 'access', _26 => _26.debug, 'call', _27 => _27(`${y} - <streaming-response>`)]):e.responseType==="blob"?_optionalChain([t, 'access', _28 => _28.sindri, 'optionalAccess', _29 => _29.logger, 'access', _30 => _30.debug, 'call', _31 => _31(`${y} - <blob-response>`)]):_optionalChain([t, 'access', _32 => _32.sindri, 'optionalAccess', _33 => _33.logger, 'access', _34 => _34.debug, 'call', _35 => _35(h.body,y)]),he(e,h),o(h.body)}}catch(u){let m=u instanceof Error?u.message:"Unknown error";_optionalChain([t, 'access', _36 => _36.sindri, 'optionalAccess', _37 => _37.logger, 'access', _38 => _38.debug, 'call', _39 => _39(`${l} ERROR (${i()}) - ${m}`)]),s(u)}});var k=class extends T{constructor(e){super(e)}request(e){return Z(this.config,e)}};var v=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 A=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 x=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 O=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 q=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 w=class{constructor(e,r=k){this.request=new r({BASE:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _40 => _40.BASE]), () => ("https://sindri.app")),VERSION:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _41 => _41.VERSION]), () => ("1.17.19")),WITH_CREDENTIALS:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _42 => _42.WITH_CREDENTIALS]), () => (!1)),CREDENTIALS:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _43 => _43.CREDENTIALS]), () => ("include")),TOKEN:_optionalChain([e, 'optionalAccess', _44 => _44.TOKEN]),USERNAME:_optionalChain([e, 'optionalAccess', _45 => _45.USERNAME]),PASSWORD:_optionalChain([e, 'optionalAccess', _46 => _46.PASSWORD]),HEADERS:_optionalChain([e, 'optionalAccess', _47 => _47.HEADERS]),ENCODE_PATH:_optionalChain([e, 'optionalAccess', _48 => _48.ENCODE_PATH])}),this.authorization=new v(this.request),this.circuits=new A(this.request),this.internal=new x(this.request),this.proofs=new O(this.request),this.token=new q(this.request)}};var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var _envpaths = require('env-paths'); var _envpaths2 = _interopRequireDefault(_envpaths);var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash);var _zod = require('zod');var Y=()=>{let t=_envpaths2.default.call(void 0, "sindri",{suffix:""});return _path2.default.join(t.config,"sindri.conf.json")},U=_zod.z.object({auth:_zod.z.nullable(_zod.z.object({apiKey:_zod.z.string(),apiKeyId:_zod.z.string(),apiKeyName:_zod.z.string(),baseUrl:_zod.z.string().url(),teamId:_zod.z.number(),teamSlug:_zod.z.string()})).default(null)}),ye=U.parse({}),ge=t=>{let e=Y();if(_fs2.default.existsSync(e)){_optionalChain([t, 'optionalAccess', _49 => _49.debug, 'call', _50 => _50(`Loading config from "${e}".`)]);try{let r=_fs2.default.readFileSync(e,{encoding:"utf-8"}),o=U.parse(JSON.parse(r));return _optionalChain([t, 'optionalAccess', _51 => _51.debug, 'call', _52 => _52("Config loaded successfully.")]),o}catch(r){_optionalChain([t, 'optionalAccess', _53 => _53.warn, 'call', _54 => _54(`The config schema in "${e}" is invalid and will not be used. To remove it and start fresh, run: rm ${e}`)]),_optionalChain([t, 'optionalAccess', _55 => _55.debug, 'call', _56 => _56(r)])}}return _optionalChain([t, 'optionalAccess', _57 => _57.debug, 'call', _58 => _58(`Config file "${e}" does not exist, initializing default config.`)]),_lodash2.default.cloneDeep(ye)},F=class{constructor(e){this.logger=e,this.reload()}get auth(){return _lodash2.default.cloneDeep(this._config.auth)}get config(){return _lodash2.default.cloneDeep(this._config)}reload(){this._config=ge(this.logger)}update(e){_optionalChain([this, 'access', _59 => _59.logger, 'optionalAccess', _60 => _60.debug, 'call', _61 => _61("Merging in config update:")]),_optionalChain([this, 'access', _62 => _62.logger, 'optionalAccess', _63 => _63.debug, 'call', _64 => _64(e)]);let r=_lodash2.default.cloneDeep(this._config);_lodash2.default.merge(r,e),this._config=U.parse(r);let o=Y(),s=_path2.default.dirname(o);_fs2.default.existsSync(s)||_fs2.default.mkdirSync(s,{recursive:!0}),_optionalChain([this, 'access', _65 => _65.logger, 'optionalAccess', _66 => _66.debug, 'call', _67 => _67(`Writing merged config to "${o}":`,this._config)]),_fs2.default.writeFileSync(o,JSON.stringify(this._config,null,2),{encoding:"utf-8"})}};var _pino = require('pino'); var _pino2 = _interopRequireDefault(_pino);var _pinopretty = require('pino-pretty'); var _pinopretty2 = _interopRequireDefault(_pinopretty);var z=t=>{let e=_pino2.default.call(void 0, process.env.BROWSER_BUILD?{browser:{asObject:!0}}:_pinopretty2.default.call(void 0, {colorize:!0,destination:2,ignore:"hostname,pid",levelFirst:!1,sync:!0}));return e.level=_nullishCoalesce(t, () => (!0))?"silent":"info",e},kt=z();var b=null;function Ce({cache:t=!0,logger:e,raiseExceptions:r=!1}={}){if(t&&b)return b;if(process.env.BROWSER_BUILD)return b={};let{SINDRI_META:o}=process.env;if(!o)return b={};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 _optionalChain([e, 'optionalAccess', _68 => _68.warn, 'call', _69 => _69({key:n,value:i,SINDRI_META:o},l+" Ignoring.")]),!1}let p=X(n,i);if(p){if(r)throw new Error(p);return _optionalChain([e, 'optionalAccess', _70 => _70.warn, 'call', _71 => _71({key:n,value:i,SINDRI_META:o},p+" Ignoring.")]),!1}return!0};if(o.startsWith("{"))try{return b=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 _optionalChain([e, 'optionalAccess', _72 => _72.warn, 'call', _73 => _73({SINDRI_META:o,error:n.toString()},i+" Using '{}' as the default.")]),b={}}let a="\0";return b=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 _optionalChain([e, 'optionalAccess', _74 => _74.warn, 'call', _75 => _75({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 K(t){let e=Ce({raiseExceptions:!0});return Object.entries(t).forEach(([r,o])=>{let s=X(r,o);if(s)throw new Error(s)}),{...e,...t}}function X(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 B= (_class =class t{__init() {this.pollingInterval=1e3}__init2() {this.retryOptions={minTimeout:1e3,retries:6}}constructor(e={},{retryOptions:r}={}){;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);this._client=new w,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=z(),process.env.BROWSER_BUILD||(this._config=new F(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||_optionalChain([this, 'access', _76 => _76._config, 'access', _77 => _77.auth, 'optionalAccess', _78 => _78.baseUrl])||this._clientConfig.BASE||"https://sindri.app",this._clientConfig.TOKEN=e.apiKey||process.env.SINDRI_API_KEY||_optionalChain([this, 'access', _79 => _79._config, 'access', _80 => _80.auth, 'optionalAccess', _81 => _81.apiKey])),!!(this._clientConfig.BASE&&this._clientConfig.TOKEN)}create(e,r){return new t(e,r)}async createCircuit(e,r=["latest"],o={}){let s=new I;r=typeof r=="string"?[r]:_nullishCoalesce(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(K(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 _promises.stat.call(void 0, e)}catch (e4){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=_path2.default.basename(e),l=await _promises.readFile.call(void 0, e);s.append("files",new S([l],p))}else if(i.isDirectory()){let p=_path2.default.join(e,"sindri.json"),l;try{l=await _promises.readFile.call(void 0, p,{encoding:"utf-8"})}catch (e5){throw new Error(`Expected Sindri manifest file at "${p}" does not exist.`)}let u;try{u=JSON.parse(l)}catch (e6){throw new Error(`Could not parse "${p}", is it valid JSON?`)}let m=_optionalChain([u, 'optionalAccess', _82 => _82.name]);if(!m)throw new Error(`No circuit "name" field was found in "${p}", the manifest is invalid.`);let f=_ignorewalk2.default.sync({follow:!0,ignoreFiles:[".sindriignore"],path:e}).filter(h=>!/(^|\/)\.git(\/|$)/.test(h)),c=_path2.default.basename(p);f.includes(c)||f.push(c);let g=`${m}.tar.gz`;f.sort((h,y)=>h.localeCompare(y));let P=_tar2.default.c({cwd:e,gzip:!0,onwarn:(h,y)=>{this.logger.warn(`While creating tarball: ${h} - ${y}`)},prefix:`${m}/`,sync:!0},f);s.append("files",new S([P.read()],g))}else throw new Error(`The "${e}" path is not a file or directory.`)}else if(Array.isArray(e)){if(!e.every(c=>c instanceof S))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 (e7){throw new Error('Could not parse "sindri.json", is it valid JSON?')}let l=_optionalChain([p, 'optionalAccess', _83 => _83.name]);if(!l)throw new Error('No circuit "name" field was found in "sindri.json", the manifest is invalid.');let u=new _tarjs2.default;e.sort((c,g)=>c.name.localeCompare(g.name));for(let c of e){let g=new Uint8Array(await c.arrayBuffer());await new Promise(P=>u.append(`${l}/${c.name}`,g,P))}let m=new Uint8Array(_gzipjs2.default.zip(u.out)),f=new S([m],`${l}.tar.gz`);process.env.BROWSER_BUILD,s.append("files",f)}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:K(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)}}, _class);var ir=new B;exports.default = ir; module.exports = exports.default; //# sourceMappingURL=index.js.map