@zk-email/sdk 0.0.12 → 0.0.13

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.d.mts CHANGED
@@ -227,7 +227,7 @@ declare class Proof {
227
227
  * @param id - Id of the Proof.
228
228
  * @returns A promise that resolves to a new instance of Proof.
229
229
  */
230
- static getPoofById(id: string): Promise<Proof>;
230
+ static getPoofById(id: string, baseUrl: string): Promise<Proof>;
231
231
  static responseToProofProps(response: ProofResponse): ProofProps;
232
232
  }
233
233
 
@@ -281,15 +281,16 @@ type Auth = {
281
281
  declare class Blueprint {
282
282
  props: BlueprintProps;
283
283
  auth?: Auth;
284
+ baseUrl: string;
284
285
  private lastCheckedStatus;
285
- constructor(props: BlueprintProps, auth?: Auth);
286
+ constructor(props: BlueprintProps, baseUrl: string, auth?: Auth);
286
287
  addAuth(auth: Auth): void;
287
288
  /**
288
289
  * Fetches an existing RegexBlueprint from the database.
289
290
  * @param {string} id - Id of the RegexBlueprint.
290
291
  * @returns A promise that resolves to a new instance of RegexBlueprint.
291
292
  */
292
- static getBlueprintById(id: string, auth?: Auth): Promise<Blueprint>;
293
+ static getBlueprintById(id: string, baseUrl: string, auth?: Auth): Promise<Blueprint>;
293
294
  private static responseToBlueprintProps;
294
295
  private static blueprintPropsToRequest;
295
296
  /**
@@ -318,7 +319,7 @@ declare class Blueprint {
318
319
  * @param options - Options to filter the blueprints by.
319
320
  * @returns A promise. Once it resolves, `getId` can be called.
320
321
  */
321
- static listBlueprints(options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
322
+ static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
322
323
  /**
323
324
  * Submits a blueprint. This will save the blueprint if it didn't exist before
324
325
  * and start the compilation.
@@ -383,6 +384,7 @@ declare class Blueprint {
383
384
 
384
385
  type SdkOptions = {
385
386
  auth?: Auth;
387
+ baseUrl?: string;
386
388
  };
387
389
 
388
390
  type ParsedEmail = {
package/dist/index.d.ts CHANGED
@@ -227,7 +227,7 @@ declare class Proof {
227
227
  * @param id - Id of the Proof.
228
228
  * @returns A promise that resolves to a new instance of Proof.
229
229
  */
230
- static getPoofById(id: string): Promise<Proof>;
230
+ static getPoofById(id: string, baseUrl: string): Promise<Proof>;
231
231
  static responseToProofProps(response: ProofResponse): ProofProps;
232
232
  }
233
233
 
@@ -281,15 +281,16 @@ type Auth = {
281
281
  declare class Blueprint {
282
282
  props: BlueprintProps;
283
283
  auth?: Auth;
284
+ baseUrl: string;
284
285
  private lastCheckedStatus;
285
- constructor(props: BlueprintProps, auth?: Auth);
286
+ constructor(props: BlueprintProps, baseUrl: string, auth?: Auth);
286
287
  addAuth(auth: Auth): void;
287
288
  /**
288
289
  * Fetches an existing RegexBlueprint from the database.
289
290
  * @param {string} id - Id of the RegexBlueprint.
290
291
  * @returns A promise that resolves to a new instance of RegexBlueprint.
291
292
  */
292
- static getBlueprintById(id: string, auth?: Auth): Promise<Blueprint>;
293
+ static getBlueprintById(id: string, baseUrl: string, auth?: Auth): Promise<Blueprint>;
293
294
  private static responseToBlueprintProps;
294
295
  private static blueprintPropsToRequest;
295
296
  /**
@@ -318,7 +319,7 @@ declare class Blueprint {
318
319
  * @param options - Options to filter the blueprints by.
319
320
  * @returns A promise. Once it resolves, `getId` can be called.
320
321
  */
321
- static listBlueprints(options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
322
+ static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
322
323
  /**
323
324
  * Submits a blueprint. This will save the blueprint if it didn't exist before
324
325
  * and start the compilation.
@@ -383,6 +384,7 @@ declare class Blueprint {
383
384
 
384
385
  type SdkOptions = {
385
386
  auth?: Auth;
387
+ baseUrl?: string;
386
388
  };
387
389
 
388
390
  type ParsedEmail = {
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains');var f=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(f||{});var R="Ov23li0KABFCUsxBEQkn";function T(n){let e=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${R}&scope=user:email&state=${e}`}async function h(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var b="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",P,y=new Promise(n=>{P=n;});console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async n=>{await n.default(),P(n);}).catch(n=>{console.log("Failed to init WASM: ",n);});}catch{}async function d(n,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),i=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${i}`);return i}catch(r){throw console.error("POST Error:",r),r}}async function _(n,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),i=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${i}`);return i}catch(r){throw console.error("PATCH Error:",r),r}}async function l(n,e,t){try{let r=n;if(e){let i=new URLSearchParams;Object.entries(e).forEach(([s,m])=>{m&&i.append(s,String(m));}),i.size>0&&(r+=`?${i.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function x(n){try{return await(await y).parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function v(n,e,t=!1){let r=await x(n),o={parts:e.parts.map(u=>({is_public:"isPublic"in u?u.isPublic:u.is_public,regex_def:"regexDef"in u?u.regexDef:u.regex_def}))},i;if(e.location==="body")i=r.canonicalized_body;else if(e.location==="header")i=r.canonicalized_header;else throw Error(`Unsupported location ${e.location}`);return (await y).extractSubstr(i,o,t)}async function B(n,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},i=await y;console.log("got relayer utils"),console.log("actually creating proof inputs with params: ",o);let s=await i.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,e.map(m=>({...m,parts:m.parts.map(u=>({is_public:u.isPublic,regex_def:u.regexDef}))})),t,o);return JSON.stringify(Object.fromEntries(s))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function S(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var w="https://conductor.zk.email",c=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof a))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await l(`${w}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await l(`${w}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async verifyOnChain(){}static async getPoofById(e){let t;try{t=await l(`${w}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let r=this.responseToProofProps(t),o=await a.getBlueprintById(t.blueprint_id);return new n(o,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proof:e.proof,public:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}};var E="https://conductor.zk.email",g=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof a))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){console.log("starting generate proof");let t=await this.generateProofRequest(e);for(console.log("got proof: ",t);![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let s={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await B(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],s);}catch(s){throw console.error("Failed to generate inputs for proof"),s}console.log("got proof input");let o;try{let s={blueprint_id:t,input:r};o=await d(`${E}/proof`,s);}catch(s){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",s),s}let i=c.responseToProofProps(o);return new c(this.blueprint,i)}};var L=(e=>(e.Circom="circom",e))(L||{}),k=(i=>(i[i.None=0]="None",i[i.Draft=1]="Draft",i[i.InProgress=2]="InProgress",i[i.Done=3]="Done",i[i.Failed=4]="Failed",i))(k||{});var F="0x4200000000000000000000000000000000000006",$=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],q=viem.createPublicClient({chain:chains.baseSepolia,transport:viem.http()});async function D(){try{return await q.readContract({address:F,abi:$,functionName:"totalSupply"})}catch(n){throw console.error("Error fetching WETH total supply:",n),n}}var p="https://conductor.zk.email",a=class n{props;auth;lastCheckedStatus=null;constructor(e,t){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.auth=t;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t){let r;try{r=await l(`${p}/blueprint/${e}`);}catch(s){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",s),s}let o=this.responseToBlueprintProps(r);return new n(o,t)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await d(`${p}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),r;try{r=await d(`${p}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await d(`${p}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t){let r={skip:e?.skip,limit:e?.limit,sort:e?.sort,status:e?.status,is_public:e?.isPublic,search:e?.search},o;try{o=await l(`${p}/blueprint`,r);}catch(i){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",i),i}return o.blueprints?o.blueprints.map(i=>{let s=n.responseToBlueprintProps(i);return new n(s,t)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await d(`${p}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await l(`${p}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await l(`${p}/blueprint/zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.url}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="ZKeys.txt",document.body.appendChild(t),t.click(),document.body.removeChild(t);}createProver(){return new g(this)}async verifyProofOnChain(e){try{let t=await D();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),r;try{r=await _(`${p}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await l(`${p}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=n.responseToBlueprintProps(t);return new n(r)})}};var ke=n=>({createBlueprint(e){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new a(e,n.auth)},async getBlueprint(e){return a.getBlueprintById(e,n?.auth)},async listBlueprints(e){return a.listBlueprints(e,n?.auth)},async getProof(e){return c.getPoofById(e)}});
2
- exports.Blueprint=a;exports.Proof=c;exports.ProofStatus=f;exports.Status=k;exports.ZkFramework=L;exports.default=ke;exports.getLoginWithGithubUrl=T;exports.parseEmail=x;exports.startJsonFileDownload=S;exports.testDecomposedRegex=v;//# sourceMappingURL=index.js.map
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains');var g=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(g||{});var k="Ov23li0KABFCUsxBEQkn";function D(i){let e=encodeURIComponent(i);return `https://github.com/login/oauth/authorize?client_id=${k}&scope=user:email&state=${e}`}async function h(i){try{let e=await i.getToken();if(e||(await i.onTokenExpired(),e=await i.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var b="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",y,f=new Promise(i=>{y=i;});console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async i=>{await i.default(),y(i);}).catch(i=>{console.log("Failed to init WASM: ",i);});}catch{}async function d(i,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(i,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("POST Error:",r),r}}async function w(i,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(i,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("PATCH Error:",r),r}}async function p(i,e,t){try{let r=i;if(e){let s=new URLSearchParams;Object.entries(e).forEach(([n,l])=>{l&&s.append(n,String(l));}),s.size>0&&(r+=`?${s.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function P(i){try{return await(await f).parseEmail(i)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function R(i,e,t=!1){let r=await P(i),o={parts:e.parts.map(u=>({is_public:"isPublic"in u?u.isPublic:u.is_public,regex_def:"regexDef"in u?u.regexDef:u.regex_def}))},s;if(e.location==="body")s=r.canonicalized_body;else if(e.location==="header")s=r.canonicalized_header;else throw Error(`Unsupported location ${e.location}`);return (await f).extractSubstr(s,o,t)}async function _(i,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},s=await f;console.log("got relayer utils"),console.log("actually creating proof inputs with params: ",o);let n=await s.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(i,e.map(l=>({...l,parts:l.parts.map(u=>({is_public:u.isPublic,regex_def:u.regexDef}))})),t,o);return JSON.stringify(Object.fromEntries(n))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function T(i,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([i],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var c=class i{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof a))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await p(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await p(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async verifyOnChain(){}static async getPoofById(e,t){let r;try{r=await p(`${t}/proof/${e}`);}catch(n){throw console.error("Failed calling /proof/:id in getProofById: ",n),n}let o=this.responseToProofProps(r),s=await a.getBlueprintById(r.blueprint_id,t);return new i(s,o)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proof:e.proof,public:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}};var m=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof a))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){console.log("starting generate proof");let t=await this.generateProofRequest(e);for(console.log("got proof: ",t);![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let n={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await _(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],n);}catch(n){throw console.error("Failed to generate inputs for proof"),n}console.log("got proof input");let o;try{let n={blueprint_id:t,input:r};o=await d(`${this.blueprint.baseUrl}/proof`,n);}catch(n){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",n),n}let s=c.responseToProofProps(o);return new c(this.blueprint,s)}};var v=(e=>(e.Circom="circom",e))(v||{}),x=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(x||{});var I="0x4200000000000000000000000000000000000006",C=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],A=viem.createPublicClient({chain:chains.baseSepolia,transport:viem.http()});async function B(){try{return await A.readContract({address:I,abi:C,functionName:"totalSupply"})}catch(i){throw console.error("Error fetching WETH total supply:",i),i}}var a=class i{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,r){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=r;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,r){let o;try{o=await p(`${t}/blueprint/${e}`);}catch(l){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",l),l}let s=this.responseToBlueprintProps(o);return new i(s,t,r)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=i.blueprintPropsToRequest(this.props),t;try{t=await d(`${this.baseUrl}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=i.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=i.blueprintPropsToRequest(e),r;try{r=await d(`${this.baseUrl}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=i.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await d(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,r){let o={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await p(`${e}/blueprint`,o);}catch(n){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",n),n}return s.blueprints?s.blueprints.map(n=>{let l=i.responseToBlueprintProps(n);return new i(l,e,r)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await d(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await p(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await p(`${this.baseUrl}/blueprint/zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.url}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="ZKeys.txt",document.body.appendChild(t),t.click(),document.body.removeChild(t);}createProver(){return new m(this)}async verifyProofOnChain(e){try{let t=await B();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=i.blueprintPropsToRequest(e),r;try{r=await w(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=i.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await p(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=i.responseToBlueprintProps(t);return new i(r,this.baseUrl,this.auth)})}};var _e=i=>{let e=i?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!i&&!i.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new a(t,e,i.auth)},async getBlueprint(t){return a.getBlueprintById(t,e,i?.auth)},async listBlueprints(t){return a.listBlueprints(e,t,i?.auth)},async getProof(t){return c.getPoofById(t,e)}}};
2
+ exports.Blueprint=a;exports.Proof=c;exports.ProofStatus=g;exports.Status=x;exports.ZkFramework=v;exports.default=_e;exports.getLoginWithGithubUrl=D;exports.parseEmail=P;exports.startJsonFileDownload=T;exports.testDecomposedRegex=R;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testDecomposedRegex","decomposedRegex","revealPrivate","parsedEmail","inputDecomposedRegex","p","inputStr","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","utils","inputs","dcr","startJsonFileDownload","json","name","blob","link","BASE_URL","Proof","_Proof","blueprint","props","Blueprint","sinceLastChecked","r","id","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","regex","part","newProps","requestOptions","status","result","cloned","src_default","sdkOptions"],"mappings":"6HAGO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAAA,CAAAA,CAAA,IACAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,2BACAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,QAAA,CAJUA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,ECDZ,IAAMC,CAAAA,CAAmB,uBAElB,SAASC,CAAAA,CAAsBC,CAA6B,CAAA,CACjE,IAAMC,CAAAA,CAAQ,kBAAmBD,CAAAA,CAAW,EAC5C,OAAO,CAAA,mDAAA,EAAsDF,CAAgB,CAAA,wBAAA,EAA2BG,CAAK,CAC/G,CAAA,CAEA,eAAsBC,CAAAA,CAAiBC,EAA6B,CAClE,GAAI,CACF,IAAIC,CAAQ,CAAA,MAAMD,CAAK,CAAA,QAAA,GAOvB,GALKC,CAAAA,GACH,MAAMD,CAAAA,CAAK,cAAe,EAAA,CAC1BC,CAAQ,CAAA,MAAMD,EAAK,QAAS,EAAA,CAAA,CAG1B,CAACC,CAAAA,CACH,MAAM,IAAI,KAAM,CAAA,yBAAyB,EAG3C,OAAO,CAAA,OAAA,EAAUA,CAAK,CAAA,CACxB,OAASC,CAAK,CAAA,CACZ,MAAQ,OAAA,CAAA,KAAA,CAAM,+BAA+B,CACvCA,CAAAA,CACR,CACF,CC3BA,IAAMC,CAAAA,CAAiB,0CAoBnBC,CAAAA,CAAAA,CACEC,EAA0C,IAAI,OAAA,CAASC,CAAY,EAAA,CACv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A,MAAM,QAAS7B,CAAAA,CAAAA,CAA4B,CACzC,OAAOP,CAAAA,CAAM,WAAYO,CAAAA,CAAE,CAC7B,CACF,CAAA","file":"index.js","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proof?: string;\n public?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\nexport function getLoginWithGithubUrl(callbackUrl: string): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n} from \"./types\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// @ts-ignore\n// if (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\nif (false) {\n console.warn(\"Relayer utils won't work when used server side\");\n // console.log(\"Initializing for node\");\n // import(\"@dimidumo/relayer-utils/node\")\n // .then((rl) => {\n // relayerUtilsResolver(rl);\n // })\n // .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\n// Provisional type, delete once libary types\ntype ParsedEmail = {\n canonicalized_header: string;\n canonicalized_body: string;\n signature: number[];\n public_key: any[];\n cleaned_body: string;\n headers: Map<string, string[]>;\n};\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\nexport async function testDecomposedRegex(\n eml: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const parsedEmail = await parseEmail(eml);\n\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = parsedEmail.canonicalized_body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = parsedEmail.canonicalized_header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n // const maxLength =\n // \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n // if (inputStr.length > maxLength) {\n // throw new Error(`Max length of ${maxLength} was exceeded`);\n // }\n\n const utils = await relayerUtils;\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n console.log(\"got relayer utils\");\n console.log(\"actually creating proof inputs with params: \", internalParams);\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n // TODO: add consistent casing in relayer_utils\n decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({ is_public: p.isPublic, regex_def: p.regexDef })),\n };\n }),\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n// TODO: replace with prod version\nconst BASE_URL = \"https://conductor.zk.email\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(`${BASE_URL}/proof/files/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(`${BASE_URL}/proof/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getPoofById(id: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${BASE_URL}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proof: response.proof,\n public: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n// TODO: replace with prod version\nconst BASE_URL = \"https://conductor.zk.email\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n console.log(\"starting generate proof\");\n const proof = await this.generateProofRequest(eml);\n console.log(\"got proof: \", proof);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${BASE_URL}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n is_public?: boolean;\n search?: string;\n};\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n// TODO: replace with prod version\nconst BASE_URL = \"https://conductor.zk.email\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(id: string, auth?: Auth): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${BASE_URL}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${BASE_URL}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${BASE_URL}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${BASE_URL}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${BASE_URL}/blueprint`,\n requestOptions\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${BASE_URL}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${BASE_URL}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<string> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(`${BASE_URL}/blueprint/zkey/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"ZKeys.txt\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${BASE_URL}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${BASE_URL}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\n\n// Exports that don't need initialization or options\nexport { testDecomposedRegex, parseEmail, startJsonFileDownload } from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getPoofById(id);\n },\n };\n};\n"]}
1
+ {"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testDecomposedRegex","decomposedRegex","revealPrivate","parsedEmail","inputDecomposedRegex","p","inputStr","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","utils","inputs","dcr","startJsonFileDownload","json","name","blob","link","Proof","_Proof","blueprint","props","Blueprint","sinceLastChecked","r","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","regex","part","newProps","requestOptions","status","result","cloned","src_default","sdkOptions"],"mappings":"6HAGO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAAA,CAAAA,CAAA,IACAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,2BACAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,QAAA,CAJUA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,ECDZ,IAAMC,CAAAA,CAAmB,uBAElB,SAASC,CAAAA,CAAsBC,CAA6B,CAAA,CACjE,IAAMC,CAAAA,CAAQ,kBAAmBD,CAAAA,CAAW,EAC5C,OAAO,CAAA,mDAAA,EAAsDF,CAAgB,CAAA,wBAAA,EAA2BG,CAAK,CAC/G,CAAA,CAEA,eAAsBC,CAAAA,CAAiBC,EAA6B,CAClE,GAAI,CACF,IAAIC,CAAQ,CAAA,MAAMD,CAAK,CAAA,QAAA,GAOvB,GALKC,CAAAA,GACH,MAAMD,CAAAA,CAAK,gBACXC,CAAAA,CAAAA,CAAQ,MAAMD,CAAAA,CAAK,UAGjB,CAAA,CAAA,CAACC,CACH,CAAA,MAAM,IAAI,KAAA,CAAM,yBAAyB,CAAA,CAG3C,OAAO,CAAUA,OAAAA,EAAAA,CAAK,CACxB,CAAA,CAAA,MAASC,EAAK,CACZ,MAAA,OAAA,CAAQ,KAAM,CAAA,+BAA+B,EACvCA,CACR,CACF,CC3BA,IAAMC,CAAiB,CAAA,0CAAA,CAoBnBC,CACEC,CAAAA,CAAAA,CAA0C,IAAI,OAASC,CAAAA,CAAAA,EAAY,CACvEF,CAAAA,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,MAAM,QAAS9B,CAAAA,CAAAA,CAA4B,CACzC,OAAOP,EAAM,WAAYO,CAAAA,CAAAA,CAAIC,CAAO,CACtC,CACF,CACF","file":"index.js","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proof?: string;\n public?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\nexport function getLoginWithGithubUrl(callbackUrl: string): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n} from \"./types\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// @ts-ignore\n// if (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\nif (false) {\n console.warn(\"Relayer utils won't work when used server side\");\n // console.log(\"Initializing for node\");\n // import(\"@dimidumo/relayer-utils/node\")\n // .then((rl) => {\n // relayerUtilsResolver(rl);\n // })\n // .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\n// Provisional type, delete once libary types\ntype ParsedEmail = {\n canonicalized_header: string;\n canonicalized_body: string;\n signature: number[];\n public_key: any[];\n cleaned_body: string;\n headers: Map<string, string[]>;\n};\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\nexport async function testDecomposedRegex(\n eml: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const parsedEmail = await parseEmail(eml);\n\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = parsedEmail.canonicalized_body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = parsedEmail.canonicalized_header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n // const maxLength =\n // \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n // if (inputStr.length > maxLength) {\n // throw new Error(`Max length of ${maxLength} was exceeded`);\n // }\n\n const utils = await relayerUtils;\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n console.log(\"got relayer utils\");\n console.log(\"actually creating proof inputs with params: \", internalParams);\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n // TODO: add consistent casing in relayer_utils\n decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({ is_public: p.isPublic, regex_def: p.regexDef })),\n };\n }),\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getPoofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proof: response.proof,\n public: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n console.log(\"starting generate proof\");\n const proof = await this.generateProofRequest(eml);\n console.log(\"got proof: \", proof);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n is_public?: boolean;\n search?: string;\n};\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<string> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(`${this.baseUrl}/blueprint/zkey/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"ZKeys.txt\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\n\n// Exports that don't need initialization or options\nexport { testDecomposedRegex, parseEmail, startJsonFileDownload } from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getPoofById(id, baseUrl);\n },\n };\n};\n"]}
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import {createPublicClient,http}from'viem';import {baseSepolia}from'viem/chains';var f=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(f||{});var R="Ov23li0KABFCUsxBEQkn";function T(n){let e=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${R}&scope=user:email&state=${e}`}async function h(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var b="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",P,y=new Promise(n=>{P=n;});console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async n=>{await n.default(),P(n);}).catch(n=>{console.log("Failed to init WASM: ",n);});}catch{}async function d(n,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),i=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${i}`);return i}catch(r){throw console.error("POST Error:",r),r}}async function _(n,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),i=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${i}`);return i}catch(r){throw console.error("PATCH Error:",r),r}}async function l(n,e,t){try{let r=n;if(e){let i=new URLSearchParams;Object.entries(e).forEach(([s,m])=>{m&&i.append(s,String(m));}),i.size>0&&(r+=`?${i.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function x(n){try{return await(await y).parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function v(n,e,t=!1){let r=await x(n),o={parts:e.parts.map(u=>({is_public:"isPublic"in u?u.isPublic:u.is_public,regex_def:"regexDef"in u?u.regexDef:u.regex_def}))},i;if(e.location==="body")i=r.canonicalized_body;else if(e.location==="header")i=r.canonicalized_header;else throw Error(`Unsupported location ${e.location}`);return (await y).extractSubstr(i,o,t)}async function B(n,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},i=await y;console.log("got relayer utils"),console.log("actually creating proof inputs with params: ",o);let s=await i.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,e.map(m=>({...m,parts:m.parts.map(u=>({is_public:u.isPublic,regex_def:u.regexDef}))})),t,o);return JSON.stringify(Object.fromEntries(s))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function S(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var w="https://conductor.zk.email",c=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof a))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await l(`${w}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await l(`${w}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async verifyOnChain(){}static async getPoofById(e){let t;try{t=await l(`${w}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let r=this.responseToProofProps(t),o=await a.getBlueprintById(t.blueprint_id);return new n(o,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proof:e.proof,public:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}};var E="https://conductor.zk.email",g=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof a))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){console.log("starting generate proof");let t=await this.generateProofRequest(e);for(console.log("got proof: ",t);![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let s={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await B(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],s);}catch(s){throw console.error("Failed to generate inputs for proof"),s}console.log("got proof input");let o;try{let s={blueprint_id:t,input:r};o=await d(`${E}/proof`,s);}catch(s){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",s),s}let i=c.responseToProofProps(o);return new c(this.blueprint,i)}};var L=(e=>(e.Circom="circom",e))(L||{}),k=(i=>(i[i.None=0]="None",i[i.Draft=1]="Draft",i[i.InProgress=2]="InProgress",i[i.Done=3]="Done",i[i.Failed=4]="Failed",i))(k||{});var F="0x4200000000000000000000000000000000000006",$=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],q=createPublicClient({chain:baseSepolia,transport:http()});async function D(){try{return await q.readContract({address:F,abi:$,functionName:"totalSupply"})}catch(n){throw console.error("Error fetching WETH total supply:",n),n}}var p="https://conductor.zk.email",a=class n{props;auth;lastCheckedStatus=null;constructor(e,t){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.auth=t;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t){let r;try{r=await l(`${p}/blueprint/${e}`);}catch(s){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",s),s}let o=this.responseToBlueprintProps(r);return new n(o,t)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await d(`${p}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),r;try{r=await d(`${p}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await d(`${p}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t){let r={skip:e?.skip,limit:e?.limit,sort:e?.sort,status:e?.status,is_public:e?.isPublic,search:e?.search},o;try{o=await l(`${p}/blueprint`,r);}catch(i){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",i),i}return o.blueprints?o.blueprints.map(i=>{let s=n.responseToBlueprintProps(i);return new n(s,t)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await d(`${p}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await l(`${p}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await l(`${p}/blueprint/zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.url}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="ZKeys.txt",document.body.appendChild(t),t.click(),document.body.removeChild(t);}createProver(){return new g(this)}async verifyProofOnChain(e){try{let t=await D();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),r;try{r=await _(`${p}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await l(`${p}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=n.responseToBlueprintProps(t);return new n(r)})}};var ke=n=>({createBlueprint(e){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new a(e,n.auth)},async getBlueprint(e){return a.getBlueprintById(e,n?.auth)},async listBlueprints(e){return a.listBlueprints(e,n?.auth)},async getProof(e){return c.getPoofById(e)}});
2
- export{a as Blueprint,c as Proof,f as ProofStatus,k as Status,L as ZkFramework,ke as default,T as getLoginWithGithubUrl,x as parseEmail,S as startJsonFileDownload,v as testDecomposedRegex};//# sourceMappingURL=index.mjs.map
1
+ import {createPublicClient,http}from'viem';import {baseSepolia}from'viem/chains';var g=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(g||{});var k="Ov23li0KABFCUsxBEQkn";function D(i){let e=encodeURIComponent(i);return `https://github.com/login/oauth/authorize?client_id=${k}&scope=user:email&state=${e}`}async function h(i){try{let e=await i.getToken();if(e||(await i.onTokenExpired(),e=await i.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var b="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",y,f=new Promise(i=>{y=i;});console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async i=>{await i.default(),y(i);}).catch(i=>{console.log("Failed to init WASM: ",i);});}catch{}async function d(i,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(i,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("POST Error:",r),r}}async function w(i,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(i,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("PATCH Error:",r),r}}async function p(i,e,t){try{let r=i;if(e){let s=new URLSearchParams;Object.entries(e).forEach(([n,l])=>{l&&s.append(n,String(l));}),s.size>0&&(r+=`?${s.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":b,...t?{Authorization:await h(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function P(i){try{return await(await f).parseEmail(i)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function R(i,e,t=!1){let r=await P(i),o={parts:e.parts.map(u=>({is_public:"isPublic"in u?u.isPublic:u.is_public,regex_def:"regexDef"in u?u.regexDef:u.regex_def}))},s;if(e.location==="body")s=r.canonicalized_body;else if(e.location==="header")s=r.canonicalized_header;else throw Error(`Unsupported location ${e.location}`);return (await f).extractSubstr(s,o,t)}async function _(i,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},s=await f;console.log("got relayer utils"),console.log("actually creating proof inputs with params: ",o);let n=await s.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(i,e.map(l=>({...l,parts:l.parts.map(u=>({is_public:u.isPublic,regex_def:u.regexDef}))})),t,o);return JSON.stringify(Object.fromEntries(n))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function T(i,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([i],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var c=class i{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof a))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await p(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await p(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async verifyOnChain(){}static async getPoofById(e,t){let r;try{r=await p(`${t}/proof/${e}`);}catch(n){throw console.error("Failed calling /proof/:id in getProofById: ",n),n}let o=this.responseToProofProps(r),s=await a.getBlueprintById(r.blueprint_id,t);return new i(s,o)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proof:e.proof,public:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}};var m=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof a))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){console.log("starting generate proof");let t=await this.generateProofRequest(e);for(console.log("got proof: ",t);![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let n={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await _(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],n);}catch(n){throw console.error("Failed to generate inputs for proof"),n}console.log("got proof input");let o;try{let n={blueprint_id:t,input:r};o=await d(`${this.blueprint.baseUrl}/proof`,n);}catch(n){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",n),n}let s=c.responseToProofProps(o);return new c(this.blueprint,s)}};var v=(e=>(e.Circom="circom",e))(v||{}),x=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(x||{});var I="0x4200000000000000000000000000000000000006",C=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],A=createPublicClient({chain:baseSepolia,transport:http()});async function B(){try{return await A.readContract({address:I,abi:C,functionName:"totalSupply"})}catch(i){throw console.error("Error fetching WETH total supply:",i),i}}var a=class i{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,r){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=r;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,r){let o;try{o=await p(`${t}/blueprint/${e}`);}catch(l){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",l),l}let s=this.responseToBlueprintProps(o);return new i(s,t,r)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=i.blueprintPropsToRequest(this.props),t;try{t=await d(`${this.baseUrl}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=i.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=i.blueprintPropsToRequest(e),r;try{r=await d(`${this.baseUrl}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=i.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await d(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,r){let o={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await p(`${e}/blueprint`,o);}catch(n){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",n),n}return s.blueprints?s.blueprints.map(n=>{let l=i.responseToBlueprintProps(n);return new i(l,e,r)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await d(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await p(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await p(`${this.baseUrl}/blueprint/zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.url}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="ZKeys.txt",document.body.appendChild(t),t.click(),document.body.removeChild(t);}createProver(){return new m(this)}async verifyProofOnChain(e){try{let t=await B();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=i.blueprintPropsToRequest(e),r;try{r=await w(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=i.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await p(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=i.responseToBlueprintProps(t);return new i(r,this.baseUrl,this.auth)})}};var _e=i=>{let e=i?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!i&&!i.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new a(t,e,i.auth)},async getBlueprint(t){return a.getBlueprintById(t,e,i?.auth)},async listBlueprints(t){return a.listBlueprints(e,t,i?.auth)},async getProof(t){return c.getPoofById(t,e)}}};
2
+ export{a as Blueprint,c as Proof,g as ProofStatus,x as Status,v as ZkFramework,_e as default,D as getLoginWithGithubUrl,P as parseEmail,T as startJsonFileDownload,R as testDecomposedRegex};//# sourceMappingURL=index.mjs.map
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testDecomposedRegex","decomposedRegex","revealPrivate","parsedEmail","inputDecomposedRegex","p","inputStr","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","utils","inputs","dcr","startJsonFileDownload","json","name","blob","link","BASE_URL","Proof","_Proof","blueprint","props","Blueprint","sinceLastChecked","r","id","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","regex","part","newProps","requestOptions","status","result","cloned","src_default","sdkOptions"],"mappings":"iFAGO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAAA,CAAAA,CAAA,IACAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,2BACAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,CAAA,CA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CAAC,CACxE,CAAA,EACF,CAAS1C,MAAAA,CAAAA,CAAK,CACZ,MAAA,OAAA,CAAQ,MAAM,sEAAwEA,CAAAA,CAAG,CACnFA,CAAAA,CACR,CAEA,OAAOU,CAAAA,CAAS,UAAW,CAAA,GAAA,CAAK2D,GAAsB,CACpD,IAAMC,CAAiBF,CAAAA,CAAAA,CAAU,wBAAyBC,CAAAA,CAAiB,CAC3E,CAAA,OAAO,IAAID,CAAUE,CAAAA,CAAc,CACrC,CAAC,CACH,CACF,EC9fA,IAAOQ,GAASC,CACP,GAAA,CACL,eAAgBjC,CAAAA,CAAAA,CAAuB,CACrC,GAAI,CAACiC,CAAAA,EAAc,CAACA,CAAY,CAAA,IAAA,CAC9B,MAAM,IAAI,MAAM,yDAAyD,CAAA,CAG3E,OADkB,IAAIhC,EAAUD,CAAOiC,CAAAA,CAAAA,CAAY,IAAI,CAEzD,CACA,CAAA,MAAM,YAAa7B,CAAAA,CAAAA,CAAgC,CACjD,OAAOH,CAAAA,CAAU,gBAAiBG,CAAAA,CAAAA,CAAI6B,GAAY,IAAI,CACxD,CACA,CAAA,MAAM,eAAezB,CAAuD,CAAA,CAC1E,OAAOP,CAAAA,CAAU,cAAeO,CAAAA,CAAAA,CAASyB,CAAY,EAAA,IAAI,CAC3D,CACA,CAAA,MAAM,QAAS7B,CAAAA,CAAAA,CAA4B,CACzC,OAAOP,CAAAA,CAAM,WAAYO,CAAAA,CAAE,CAC7B,CACF,CAAA","file":"index.mjs","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proof?: string;\n public?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\nexport function getLoginWithGithubUrl(callbackUrl: string): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n} from \"./types\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// @ts-ignore\n// if (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\nif (false) {\n console.warn(\"Relayer utils won't work when used server side\");\n // console.log(\"Initializing for node\");\n // import(\"@dimidumo/relayer-utils/node\")\n // .then((rl) => {\n // relayerUtilsResolver(rl);\n // })\n // .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\n// Provisional type, delete once libary types\ntype ParsedEmail = {\n canonicalized_header: string;\n canonicalized_body: string;\n signature: number[];\n public_key: any[];\n cleaned_body: string;\n headers: Map<string, string[]>;\n};\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\nexport async function testDecomposedRegex(\n eml: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const parsedEmail = await parseEmail(eml);\n\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = parsedEmail.canonicalized_body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = parsedEmail.canonicalized_header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n // const maxLength =\n // \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n // if (inputStr.length > maxLength) {\n // throw new Error(`Max length of ${maxLength} was exceeded`);\n // }\n\n const utils = await relayerUtils;\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n console.log(\"got relayer utils\");\n console.log(\"actually creating proof inputs with params: \", internalParams);\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n // TODO: add consistent casing in relayer_utils\n decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({ is_public: p.isPublic, regex_def: p.regexDef })),\n };\n }),\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n// TODO: replace with prod version\nconst BASE_URL = \"https://conductor.zk.email\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(`${BASE_URL}/proof/files/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(`${BASE_URL}/proof/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getPoofById(id: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${BASE_URL}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proof: response.proof,\n public: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n// TODO: replace with prod version\nconst BASE_URL = \"https://conductor.zk.email\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n console.log(\"starting generate proof\");\n const proof = await this.generateProofRequest(eml);\n console.log(\"got proof: \", proof);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${BASE_URL}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n is_public?: boolean;\n search?: string;\n};\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n// TODO: replace with prod version\nconst BASE_URL = \"https://conductor.zk.email\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(id: string, auth?: Auth): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${BASE_URL}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${BASE_URL}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${BASE_URL}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${BASE_URL}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${BASE_URL}/blueprint`,\n requestOptions\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${BASE_URL}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${BASE_URL}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<string> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(`${BASE_URL}/blueprint/zkey/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"ZKeys.txt\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${BASE_URL}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${BASE_URL}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\n\n// Exports that don't need initialization or options\nexport { testDecomposedRegex, parseEmail, startJsonFileDownload } from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getPoofById(id);\n },\n };\n};\n"]}
1
+ {"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testDecomposedRegex","decomposedRegex","revealPrivate","parsedEmail","inputDecomposedRegex","p","inputStr","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","utils","inputs","dcr","startJsonFileDownload","json","name","blob","link","Proof","_Proof","blueprint","props","Blueprint","sinceLastChecked","r","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","regex","part","newProps","requestOptions","status","result","cloned","src_default","sdkOptions"],"mappings":"iFAGO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAAA,CAAAA,CAAA,IACAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,2BACAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,CAAA,CAAA,CAAA,CAA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,CAAW,GAAK2D,CAAAA,CAAAA,EAAsB,CACpD,IAAMC,CAAiBF,CAAAA,CAAAA,CAAU,yBAAyBC,CAAiB,CAAA,CAC3E,OAAO,IAAID,EAAUE,CAAgB,CAAA,IAAA,CAAK,OAAS,CAAA,IAAA,CAAK,IAAI,CAC9D,CAAC,CACH,CACF,EClgBA,IAAOQ,EAASC,CAAAA,CAAAA,EAA4B,CAC1C,IAAM7B,CAAAA,CAAU6B,CAAY,EAAA,OAAA,EAAW,6BACvC,OAAO,CACL,eAAgBlC,CAAAA,CAAAA,CAAuB,CACrC,GAAI,CAACkC,CAAc,EAAA,CAACA,CAAY,CAAA,IAAA,CAC9B,MAAM,IAAI,MAAM,yDAAyD,CAAA,CAG3E,OADkB,IAAIjC,EAAUD,CAAOK,CAAAA,CAAAA,CAAS6B,CAAY,CAAA,IAAI,CAElE,CACA,CAAA,MAAM,YAAa9B,CAAAA,CAAAA,CAAgC,CACjD,OAAOH,CAAU,CAAA,gBAAA,CAAiBG,EAAIC,CAAS6B,CAAAA,CAAAA,EAAY,IAAI,CACjE,EACA,MAAM,cAAA,CAAezB,CAAuD,CAAA,CAC1E,OAAOR,CAAU,CAAA,cAAA,CAAeI,CAASI,CAAAA,CAAAA,CAASyB,CAAY,EAAA,IAAI,CACpE,CAAA,CACA,MAAM,QAAS9B,CAAAA,CAAAA,CAA4B,CACzC,OAAOP,EAAM,WAAYO,CAAAA,CAAAA,CAAIC,CAAO,CACtC,CACF,CACF","file":"index.mjs","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proof?: string;\n public?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\nexport function getLoginWithGithubUrl(callbackUrl: string): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n} from \"./types\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// @ts-ignore\n// if (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\nif (false) {\n console.warn(\"Relayer utils won't work when used server side\");\n // console.log(\"Initializing for node\");\n // import(\"@dimidumo/relayer-utils/node\")\n // .then((rl) => {\n // relayerUtilsResolver(rl);\n // })\n // .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\n// Provisional type, delete once libary types\ntype ParsedEmail = {\n canonicalized_header: string;\n canonicalized_body: string;\n signature: number[];\n public_key: any[];\n cleaned_body: string;\n headers: Map<string, string[]>;\n};\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\nexport async function testDecomposedRegex(\n eml: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const parsedEmail = await parseEmail(eml);\n\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = parsedEmail.canonicalized_body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = parsedEmail.canonicalized_header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n // const maxLength =\n // \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n // if (inputStr.length > maxLength) {\n // throw new Error(`Max length of ${maxLength} was exceeded`);\n // }\n\n const utils = await relayerUtils;\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n console.log(\"got relayer utils\");\n console.log(\"actually creating proof inputs with params: \", internalParams);\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n // TODO: add consistent casing in relayer_utils\n decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({ is_public: p.isPublic, regex_def: p.regexDef })),\n };\n }),\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getPoofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proof: response.proof,\n public: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n console.log(\"starting generate proof\");\n const proof = await this.generateProofRequest(eml);\n console.log(\"got proof: \", proof);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n is_public?: boolean;\n search?: string;\n};\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<string> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(`${this.baseUrl}/blueprint/zkey/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"ZKeys.txt\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\n\n// Exports that don't need initialization or options\nexport { testDecomposedRegex, parseEmail, startJsonFileDownload } from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getPoofById(id, baseUrl);\n },\n };\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zk-email/sdk",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "ZK Email SDK for TypeScript",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",