UNPKG

sindri

Version:

The Sindri Labs JavaScript SDK and CLI tool.

22 lines (17 loc) 19.5 kB
'use strict'; var me = require('gzip-js'); var he = require('tar-js'); var k = require('axios'); var V = require('@fullstax/p-retry'); var zod = require('zod'); var ue = require('pino'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } var me__default = /*#__PURE__*/_interopDefault(me); var he__default = /*#__PURE__*/_interopDefault(he); var k__default = /*#__PURE__*/_interopDefault(k); var V__default = /*#__PURE__*/_interopDefault(V); var ue__default = /*#__PURE__*/_interopDefault(ue); var T=class{constructor(e){this.config=e;}};var S=window.File,I=window.FormData;var C=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 N=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,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 N("Request aborted"));}}get isCancelled(){return this.#e}};var B=t=>t!=null,D=t=>typeof t=="string",F=t=>D(t)&&t!=="",K=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]),Z=t=>t instanceof I,Q=t=>t>=200&&t<300,Y=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},X=t=>{let e=[],r=(s,a)=>{e.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(a))}`);},o=(s,a)=>{B(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("&")}`:""},ee=(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}${X(e.query)}`:s},te=t=>{if(t.formData){if(t.formData instanceof I)return t.formData;let e=new I,r=(o,s)=>{D(s)||K(s)?e.append(o,s):e.append(o,JSON.stringify(s));};return Object.entries(t.formData).filter(([o,s])=>B(s)).forEach(([o,s])=>{Array.isArray(s)?s.forEach(a=>r(o,a)):r(o,s);}),e}},_=async(t,e)=>typeof e=="function"?e(t):e,re=async(t,e,r)=>{let o=await _(e,t.TOKEN),s=await _(e,t.USERNAME),a=await _(e,t.PASSWORD),n=await _(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])=>B(u)).reduce((l,[u,m])=>({...l,[u]:String(m)}),{});if(F(o)&&(p.Authorization=`Bearer ${o}`),F(s)&&F(a)){let l=Y(`${s}:${a}`);p.Authorization=`Basic ${l}`;}return e.body&&(e.mediaType?p["Content-Type"]=e.mediaType:K(e.body)?p["Content-Type"]=e.body.type||"application/octet-stream":D(e.body)?p["Content-Type"]="text/plain":Z(e.body)||(p["Content-Type"]="application/json")),p},oe=t=>{if(t.body)return t.body},z=t=>!!(k__default.default.isAxiosError(t)&&(t.response?.status&&[502,503,504].includes(t.response.status)||t.code&&["ECONNREFUSED","ECONNRESET","ENOTFOUND","ENETUNREACH",k.AxiosError.ECONNABORTED,k.AxiosError.ERR_NETWORK].includes(t.code))),se=async(t,e,r,o,s,a,n,i)=>{let p=k__default.default.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 V__default.default(()=>i.request(l),{...t.sindri.retryOptions,onFailedAttempt:u=>{z(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:z}):await i.request(l)}catch(u){let m=u;if(m.response)return m.response;throw u}},ie=(t,e)=>{if(e){let r=t.headers[e];if(D(r))return r}},ne=t=>{if(t.status!==204)return t.data},ae=(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=e.status??"unknown",a=e.statusText??"unknown",n=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new C(t,e,`Generic Error: status: ${s}; status text: ${a}; body: ${n}`)}},W=(t,e,r=k__default.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=ee(t,e),l=`${e.method} ${p}`;try{let u=te(e),m=oe(e),f=await re(t,e,u);if(!a.isCancelled){t.sindri?.logger.debug(`${l} requested`);let c=await se(t,e,p,m,u,f,a,r),g=ne(c),P=ie(c,e.responseHeader),h={url:p,ok:Q(c.status),status:c.status,statusText:c.statusText,body:P??g},y=`${l} ${c.status} ${c.statusText} (${i()})`;!h.body||typeof h.body=="string"?t.sindri?.logger.debug(`${y} - ${h.body||"<empty-body>"}`):e.responseType==="stream"?t.sindri?.logger.debug(`${y} - <streaming-response>`):e.responseType==="blob"?t.sindri?.logger.debug(`${y} - <blob-response>`):t.sindri?.logger.debug(h.body,y),ae(e,h),o(h.body);}}catch(u){let m=u instanceof Error?u.message:"Unknown error";t.sindri?.logger.debug(`${l} ERROR (${i()}) - ${m}`),s(u);}});var L=class extends T{constructor(e){super(e);}request(e){return W(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:"blob"})}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{authorization;circuits;internal;proofs;token;request;constructor(e,r=L){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 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 pe=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)});pe.parse({});var H=t=>{let e=ue__default.default({browser:{asObject:!0}});return e.level=t??!0?"silent":"info",e};H();var b=null;function le({cache:t=!0,logger:e,raiseExceptions:r=!1}={}){if(t&&b)return b;return b={};}function $(t){let e=le({raiseExceptions:!0});return Object.entries(t).forEach(([r,o])=>{let s=G(r,o);if(s)throw new Error(s)}),{...e,...t}}function G(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 j=class t{_client;_clientConfig;_config;logger;pollingInterval=1e3;retryOptions={minTimeout:1e3,retries:6};constructor(e={},{retryOptions:r}={}){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=H(),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 this._clientConfig.BASE=e.baseUrl||"https://sindri.app",this._clientConfig.TOKEN=e.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]: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($(o))),typeof e=="string"){throw new Error("Specifying `project` as a path is not allowed in the browser build.");}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{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 he__default.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(me__default.default.zip(u.out)),f=new S([m],`${l}.tar.gz`);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:$(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 Qt=new j; module.exports = Qt; //# sourceMappingURL=out.js.map //# sourceMappingURL=index.js.map