@zk-email/sdk 0.0.86-1 → 0.0.86-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -394,6 +394,20 @@ type ValidationErrors = {
394
394
  [K in keyof z.infer<typeof blueprintFormSchema>]?: string;
395
395
  };
396
396
 
397
+ type SdkOptions = {
398
+ auth?: Auth;
399
+ baseUrl?: string;
400
+ };
401
+
402
+ type ParsedEmail = {
403
+ canonicalizedHeader: string;
404
+ canonicalizedBody: string;
405
+ signature: number[];
406
+ publicKey: any[];
407
+ cleanedBody: string;
408
+ headers: Map<string, string[]>;
409
+ };
410
+
397
411
  /**
398
412
  * Represents a Regex Blueprint including the decomposed regex access to the circuit.
399
413
  */
@@ -480,7 +494,7 @@ declare class Blueprint {
480
494
  * Creates an instance of Prover with which you can create proofs.
481
495
  * @returns An instance of Prover.
482
496
  */
483
- createProver(): Prover;
497
+ createProver(options?: ProverOptions): Prover;
484
498
  /**
485
499
  * Verifies a proof on chain.
486
500
  * @param proof - The generated proof you want to verify.
@@ -517,20 +531,6 @@ declare class Blueprint {
517
531
  getWasmUrl(): Promise<string>;
518
532
  }
519
533
 
520
- type SdkOptions = {
521
- auth?: Auth;
522
- baseUrl?: string;
523
- };
524
-
525
- type ParsedEmail = {
526
- canonicalizedHeader: string;
527
- canonicalizedBody: string;
528
- signature: number[];
529
- publicKey: any[];
530
- cleanedBody: string;
531
- headers: Map<string, string[]>;
532
- };
533
-
534
534
  declare function startJsonFileDownload(json: string, name?: string): void;
535
535
  declare function getDKIMSelector(emlContent: string): string | null;
536
536
 
package/dist/index.d.ts CHANGED
@@ -394,6 +394,20 @@ type ValidationErrors = {
394
394
  [K in keyof z.infer<typeof blueprintFormSchema>]?: string;
395
395
  };
396
396
 
397
+ type SdkOptions = {
398
+ auth?: Auth;
399
+ baseUrl?: string;
400
+ };
401
+
402
+ type ParsedEmail = {
403
+ canonicalizedHeader: string;
404
+ canonicalizedBody: string;
405
+ signature: number[];
406
+ publicKey: any[];
407
+ cleanedBody: string;
408
+ headers: Map<string, string[]>;
409
+ };
410
+
397
411
  /**
398
412
  * Represents a Regex Blueprint including the decomposed regex access to the circuit.
399
413
  */
@@ -480,7 +494,7 @@ declare class Blueprint {
480
494
  * Creates an instance of Prover with which you can create proofs.
481
495
  * @returns An instance of Prover.
482
496
  */
483
- createProver(): Prover;
497
+ createProver(options?: ProverOptions): Prover;
484
498
  /**
485
499
  * Verifies a proof on chain.
486
500
  * @param proof - The generated proof you want to verify.
@@ -517,20 +531,6 @@ declare class Blueprint {
517
531
  getWasmUrl(): Promise<string>;
518
532
  }
519
533
 
520
- type SdkOptions = {
521
- auth?: Auth;
522
- baseUrl?: string;
523
- };
524
-
525
- type ParsedEmail = {
526
- canonicalizedHeader: string;
527
- canonicalizedBody: string;
528
- signature: number[];
529
- publicKey: any[];
530
- cleanedBody: string;
531
- headers: Map<string, string[]>;
532
- };
533
-
534
534
  declare function startJsonFileDownload(json: string, name?: string): void;
535
535
  declare function getDKIMSelector(emlContent: string): string | null;
536
536
 
package/dist/index.js CHANGED
@@ -1,4 +1,84 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains'),relayerUtils=require('@zk-email/relayer-utils'),zod=require('zod');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function N(n){return [{type:"function",name:"verify",inputs:[{name:"a",type:"uint256[2]",internalType:"uint256[2]"},{name:"b",type:"uint256[2][2]",internalType:"uint256[2][2]"},{name:"c",type:"uint256[2]",internalType:"uint256[2]"},{name:"signals",type:`uint256[${n}]`,internalType:`uint256[${n}]`}],outputs:[],stateMutability:"view"}]}async function f(n){if(!n.blueprint.props.verifierContract?.chain||!n.blueprint.props.verifierContract?.address)throw new Error("No verifier contract deployed for the blueprint of this proof");if(!n.props.proofData||!n.props.publicOutputs)throw new Error("No proof data generated yet");let e=viem.createPublicClient({chain:chains.base,transport:viem.http("https://sepolia.base.org")}),t=n.props.proofData,o=[[BigInt(t.pi_a[0]),BigInt(t.pi_a[1])],[[BigInt(t.pi_b[0][1]),BigInt(t.pi_b[0][0])],[BigInt(t.pi_b[1][1]),BigInt(t.pi_b[1][0])]],[BigInt(t.pi_c[0]),BigInt(t.pi_c[1])],n.props.publicOutputs.map(r=>BigInt(r))];console.log("Call data to verify: ",o),console.log("contract address: ",n.blueprint.props.verifierContract.address);try{await e.readContract({address:n.blueprint.props.verifierContract.address,abi:N(n.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var x=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(x||{});var j="Ov23li0KABFCUsxBEQkn";function z(n,e=j){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(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";async function h(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":b,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),i=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${i}`);return i}catch(r){throw console.error("POST Error:",r),r}}async function E(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":b,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),i=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${i}`);return i}catch(r){throw console.error("PATCH Error:",r),r}}async function p(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=n;if(e){let i=new URLSearchParams;Object.entries(e).forEach(([a,c])=>{c&&i.append(a,String(c));}),i.size>0&&(r+=`?${i.toString()}`);}let s=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":b,...o?{Authorization:o}:{}}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return await s.json()}catch(r){throw console.error("GET Error:",r),r}}async function y(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"DELETE",headers:{"Content-Type":"application/json","x-api-key":b,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),i=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${i}`);return i}catch(r){throw console.error("DELETE Error:",r),r}}function Z(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");r.href=o,r.download=`${e}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o);}function G(n){let e=[],t=n.split(`
2
- `);for(let o of t){if(o.trim()==="")break;o.startsWith(" ")||o.startsWith(" ")?e[e.length-1]+=o.trim():e.push(o);}for(let o of e)if(o.includes("DKIM-Signature")){let r=o.match(/s=([^;]+)/);if(r&&r[1])return r[1].trim()}return null}var m=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof d))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(o){throw console.error("Failed to start download of ZKeys: ",o),o}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 o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}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}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await n.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){await f(this);}async createCallData(){if(!this.props.proofData||!this.props.publicOutputs)throw new Error("No proof data generated yet");let e=this.props.proofData;return [[BigInt(e.pi_a[0]),BigInt(e.pi_a[1])],[[BigInt(e.pi_b[0][1]),BigInt(e.pi_b[0][0])],[BigInt(e.pi_b[1][1]),BigInt(e.pi_b[1][0])]],[BigInt(e.pi_c[0]),BigInt(e.pi_c[1])],this.props.publicOutputs.map(t=>BigInt(t))]}static async getProofById(e,t){let o;try{o=await p(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let r=this.responseToProofProps(o),s=await d.getBlueprintById(o.blueprint_id,t);return new n(s,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,publicOutputs:e.public_outputs,externalInputs:e.external_inputs,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData,publicOutputs:this.props.publicOutputs,externalInputs:this.props.externalInputs}}};var R,w=new Promise(n=>{R=n;});relayerUtils.init().then(()=>{R(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function L(n){try{return await w,await relayerUtils.parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function W(n,e,t=!1){let o=await L(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.cleanedBody;if(e.shaPrecomputeSelector){let a=r.split(e.shaPrecomputeSelector)[1];if(!a)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=a;}let s=o.canonicalizedHeader;return await Q(s,r,e),await Promise.all(e.decomposedRegexes.map(a=>T(r,s,a,t)))}async function Q(n,e,t){await w;let o=new TextEncoder,r=o.encode(n);if((await relayerUtils.sha256Pad(r,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let i=o.encode(e),a=(e.length+63+65)/64*64,c=Math.max(a,t.emailBodyMaxLength);if((await relayerUtils.sha256Pad(i,c)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function T(n,e,t,o=!1){let r={parts:t.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(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);let i="maxLength"in t?t.maxLength:t.max_length;console.log("maxLength: ",i),await w;let a=relayerUtils.extractSubstr(s,r,!1);if(console.log("privateResult : ",a),a[0].length>i)throw new Error(`Max length of ${i} of extracted result was exceeded for decomposed regex ${t.name}`);return o?relayerUtils.extractSubstr(s,r,o):a}async function _(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await w;let s=e.map(a=>({...a,parts:a.parts.map(c=>({is_public:c.isPublic||!!c.is_public,regex_def:c.regexDef||!!c.regex_def}))})),i=await relayerUtils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,s,t,r);return JSON.stringify(Object.fromEntries(i))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}var P=class{options;blueprint;constructor(e,t){if(!(e instanceof d))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={...t||{isLocal:!1}};}async generateProof(e,t=[]){if(this.options.isLocal)return await this.generateLocalProof(e,t);{let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}}async generateLocalProof(e,t=[]){let o=await this.generateProofInputs(e,t);console.log("got inputs");let r=await this.blueprint.getChunkedZkeyUrls(),s=await this.blueprint.getWasmUrl();console.log("got urls, wasmUrl: ",s);let i=await new Promise((a,c)=>{console.log("meta url: ",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)));let u=new URL("../dist/localProverWorker.js",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))),B=new Worker(u,{type:"module"});B.onmessage=U=>{let{type:A,message:F,progress:M,result:k,error:D}=U.data;switch(A){case"progress":console.log(`Download progress: ${M}`);break;case"message":console.log(F);break;case"result":console.log("Proof result:",k),a(k);break;case"error":console.error("Error in worker:",D),c(D);break}},B.postMessage({chunkedZkeyUrls:r,inputs:o,wasmUrl:s});});return console.log("result: ",i),i}async generateProofInputs(e,t=[]){if(!this.blueprint.getId())throw new Error("Blueprint of Proover must be initialized in order to create a Proof");if(this.blueprint.props.externalInputs?.length&&!t.length)throw new Error(`The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`);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 _(e,this.blueprint.props.decomposedRegexes,t,s);}catch(s){throw console.error("Failed to generate inputs for proof"),s}return r}async generateProofRequest(e,t=[]){let o=this.blueprint.getId();if(!o)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r=await this.generateProofInputs(e,t);console.log("got proof input");let s;try{let a={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((c,u)=>({...c,[u.name]:u.value}),{})};s=await h(`${this.blueprint.baseUrl}/proof`,a);}catch(a){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",a),a}let i=m.responseToProofProps(s);return new m(this.blueprint,i)}};var Y=(e=>(e.Circom="circom",e))(Y||{}),S=(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))(S||{});var C=zod.z.object({title:zod.z.string().min(1,{message:"Title must be at least 1 characters."}),circuitName:zod.z.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/,"Invalid name, must start with a letter, digit, or underscore, and can only contain letters, digits or underscores."),description:zod.z.string().min(1),emailQuery:zod.z.string(),ignoreBodyHashCheck:zod.z.boolean(),shaPrecomputeSelector:zod.z.string().transform(n=>n.replace(/(?<!\\)"/g,'\\"')).optional(),senderDomain:zod.z.string().refine(n=>!n.includes("@"),{message:"Sender domain should not contain '@' symbol, only the domain"}),emailBodyMaxLength:zod.z.coerce.number().transform((n,e)=>(n%64!==0&&e.addIssue({code:"custom",message:"Must be a multiple of 64"}),n>1e4&&e.addIssue({code:"custom",message:"Must be less than or equal to 10000"}),n)),emailHeaderMaxLength:zod.z.coerce.number().transform((n,e)=>(n%64!==0&&e.addIssue({code:"custom",message:"Must be a multiple of 64"}),n)).default(1024),decomposedRegexes:zod.z.array(zod.z.object({name:zod.z.string().min(1).transform((n,e)=>n.includes(" ")?(e.addIssue({code:"custom",message:"Warning: Name contains spaces or dashes. They will be replaced with underscores."}),n.replace(/[ -]/g,"_")):n),maxLength:zod.z.coerce.number().positive().default(64),location:zod.z.string().regex(/(body)|(header)/),parts:zod.z.string().transform((n,e)=>{if(!n.includes("isPublic"))return e.addIssue({code:"custom",message:'Each parts config must include at least one "isPublic" field, and at least one thats true and one thats false. Please add it for now until we fix this requirement.'}),zod.z.NEVER;let t;try{t=JSON.parse(n);}catch{return e.addIssue({code:"custom",message:"Invalid JSON"}),zod.z.NEVER}if(!Array.isArray(t))return e.addIssue({code:"custom",message:"Parts must be an array"}),zod.z.NEVER;for(let o=0;o<t.length;o++){let r=t[o];if(typeof r!="object"||r===null)return e.addIssue({code:"custom",message:`Part ${o} must be an object`}),zod.z.NEVER;if(!("isPublic"in r)||typeof r.isPublic!="boolean")return e.addIssue({code:"custom",message:`Part ${o} must have a boolean 'isPublic' field`}),zod.z.NEVER;if(!("regexDef"in r)||typeof r.regexDef!="string")return e.addIssue({code:"custom",message:`Part ${o} must have a string 'regexDef' field`}),zod.z.NEVER}try{return X(t),t}catch(o){return e.addIssue({code:"custom",message:o.message}),zod.z.NEVER}}).optional().or(zod.z.array(zod.z.any()))})),externalInputs:zod.z.array(zod.z.object({name:zod.z.string().min(1),maxLength:zod.z.coerce.number().positive().default(64)})).optional()});function X(n){let e="";for(let t of n){if(t.isPublic||(e=e+t.regexDef),!t.isPublic&&!t.regexDef)throw new Error("Part has to have a nonempty regex with isPublic = false");break}if(!e)throw new Error("Part has to have a regex with isPublic = false in order to find it later");return JSON.stringify(e)}var d=class n{props;auth;baseUrl;stars=0;static formSchema=C;lastCheckedStatus=null;constructor(e,t,o){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=o;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,o){let r;try{r=await p(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let s=this.responseToBlueprintProps(r);return new n(s,t,o)}static async getBlueprintBySlug(e,t,o){let r=e.split("@");if(!r||!(r.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let s=r.pop().replace("v","");if(e=encodeURIComponent(r.join("")),!s)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let i;try{let u=`${t}/blueprint/by-slug/${e}/${s}`;i=await p(u);}catch(u){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",u),u}let a=this.responseToBlueprintProps(i);return new n(a,t,o)}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(o=>({name:o.name,maxLength:o.max_length})),decomposedRegexes:e.decomposed_regexes?.map(o=>({parts:o.parts.map(r=>({isPublic:r.is_public,regexDef:r.regex_def})),name:o.name,maxLength:o.max_length,location:o.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version,stars:e.stars}}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(o=>({name:o.name,max_length:o.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(o=>({parts:o.parts.map(r=>({is_public:r.isPublic||r.is_public,regex_def:r.regexDef||r.regex_def})),name:o.name,max_length:o.maxLength,location:o.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 h(`${this.baseUrl}/blueprint`,e,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}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),o;try{o=await h(`${this.baseUrl}/blueprint`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitNewVersionDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await h(`${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,o){t?.sortBy&&(t.sortBy=t.sortBy==="updatedAt"?"updated_at":t.sortBy);let r;try{r=await p(`${e}/blueprint`,t,o);}catch(i){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",i),i}return r.blueprints?r.blueprints.map(i=>{let a=n.responseToBlueprintProps(i);return new n(a,e,o)}):[]}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 h(`${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 o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}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.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,o]of Object.entries(e)){let r=document.createElement("a");r.href=o,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r);}}createProver(){return new P(this)}async verifyProofOnChain(e){try{await f(e);}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),o;try{o=await E(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}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 o=n.responseToBlueprintProps(t);return new n(o,this.baseUrl,this.auth)})}async addStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await h(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling POST on /blueprint/${slug}/stars in addStar: ",e),e}}async removeStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await y(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id}/stars in addStar: ",e),e}}async getStars(){try{let{stars:e}=await p(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.props.stars=e||0,e||0}catch(e){throw console.error("Failed calling POST on /blueprint/${id}/stars in addStar: ",e),e}}async cancelCompilation(){if(this.props.status!==2)throw new Error("Can only cancel compilation of a blueprint that is in progress");try{await y(`${this.baseUrl}/blueprint/cancel/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: ",e),e}}async delete(){try{await y(`${this.baseUrl}/blueprint/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id} in cancelCompilation: ",e),e}}async getChunkedZkeyUrls(){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/chunked-zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/chunked-zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async getWasmUrl(){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/wasm/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/wasm/:id in getWasmUrl: ",t),t}return e.url}};async function $(n,e){let{slugs:t}=await p(`${n}/blueprint/starred`,null,e);return t}var et=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new d(t,e,n.auth)},async getBlueprint(t){return d.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return d.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return d.listBlueprints(e,t,n?.auth)},async getProof(t){return m.getProofById(t,e)},async getStarredBlueprints(){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return $(e,n.auth)}}};
3
- Object.defineProperty(exports,"ZodError",{enumerable:true,get:function(){return zod.ZodError}});exports.Blueprint=d;exports.Proof=m;exports.ProofStatus=x;exports.Status=S;exports.ZkFramework=Y;exports.default=et;exports.generateProofInputs=_;exports.getDKIMSelector=G;exports.getLoginWithGithubUrl=z;exports.parseEmail=L;exports.startJsonFileDownload=Z;exports.testBlueprint=W;exports.testDecomposedRegex=T;//# sourceMappingURL=index.js.map
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains'),relayerUtils=require('@zk-email/relayer-utils'),zod=require('zod');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function z(s){return [{type:"function",name:"verify",inputs:[{name:"a",type:"uint256[2]",internalType:"uint256[2]"},{name:"b",type:"uint256[2][2]",internalType:"uint256[2][2]"},{name:"c",type:"uint256[2]",internalType:"uint256[2]"},{name:"signals",type:`uint256[${s}]`,internalType:`uint256[${s}]`}],outputs:[],stateMutability:"view"}]}async function f(s){if(!s.blueprint.props.verifierContract?.chain||!s.blueprint.props.verifierContract?.address)throw new Error("No verifier contract deployed for the blueprint of this proof");if(!s.props.proofData||!s.props.publicOutputs)throw new Error("No proof data generated yet");let e=viem.createPublicClient({chain:chains.base,transport:viem.http("https://sepolia.base.org")}),t=s.props.proofData,o=[[BigInt(t.pi_a[0]),BigInt(t.pi_a[1])],[[BigInt(t.pi_b[0][1]),BigInt(t.pi_b[0][0])],[BigInt(t.pi_b[1][1]),BigInt(t.pi_b[1][0])]],[BigInt(t.pi_c[0]),BigInt(t.pi_c[1])],s.props.publicOutputs.map(r=>BigInt(r))];console.log("Call data to verify: ",o),console.log("contract address: ",s.blueprint.props.verifierContract.address);try{await e.readContract({address:s.blueprint.props.verifierContract.address,abi:z(s.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var x=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(x||{});var G="Ov23li0KABFCUsxBEQkn";function Z(s,e=G){let t=encodeURIComponent(s);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(s){try{let e=await s.getToken();if(e||(await s.onTokenExpired(),e=await s.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";async function h(s,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":b,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let n=await fetch(s,r),i=await n.json();if(!n.ok)throw new Error(`HTTP error! status: ${n.status}, message: ${i}`);return i}catch(r){throw console.error("POST Error:",r),r}}async function E(s,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":b,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let n=await fetch(s,r),i=await n.json();if(!n.ok)throw new Error(`HTTP error! status: ${n.status}, message: ${i}`);return i}catch(r){throw console.error("PATCH Error:",r),r}}async function p(s,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=s;if(e){let i=new URLSearchParams;Object.entries(e).forEach(([a,c])=>{c&&i.append(a,String(c));}),i.size>0&&(r+=`?${i.toString()}`);}let n=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":b,...o?{Authorization:o}:{}}});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return await n.json()}catch(r){throw console.error("GET Error:",r),r}}async function w(s,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"DELETE",headers:{"Content-Type":"application/json","x-api-key":b,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let n=await fetch(s,r),i=await n.json();if(!n.ok)throw new Error(`HTTP error! status: ${n.status}, message: ${i}`);return i}catch(r){throw console.error("DELETE Error:",r),r}}function J(s,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([s],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");r.href=o,r.download=`${e}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o);}function V(s){let e=[],t=s.split(`
2
+ `);for(let o of t){if(o.trim()==="")break;o.startsWith(" ")||o.startsWith(" ")?e[e.length-1]+=o.trim():e.push(o);}for(let o of e)if(o.includes("DKIM-Signature")){let r=o.match(/s=([^;]+)/);if(r&&r[1])return r[1].trim()}return null}var m=class s{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof d))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(o){throw console.error("Failed to start download of ZKeys: ",o),o}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 o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}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}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await s.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){await f(this);}async createCallData(){if(!this.props.proofData||!this.props.publicOutputs)throw new Error("No proof data generated yet");let e=this.props.proofData;return [[BigInt(e.pi_a[0]),BigInt(e.pi_a[1])],[[BigInt(e.pi_b[0][1]),BigInt(e.pi_b[0][0])],[BigInt(e.pi_b[1][1]),BigInt(e.pi_b[1][0])]],[BigInt(e.pi_c[0]),BigInt(e.pi_c[1])],this.props.publicOutputs.map(t=>BigInt(t))]}static async getProofById(e,t){let o;try{o=await p(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let r=this.responseToProofProps(o),n=await d.getBlueprintById(o.blueprint_id,t);return new s(n,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,publicOutputs:e.public_outputs,externalInputs:e.external_inputs,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData,publicOutputs:this.props.publicOutputs,externalInputs:this.props.externalInputs}}};var R,y=new Promise(s=>{R=s;});relayerUtils.init().then(()=>{R(null);}).catch(s=>{console.log("Failed to initialize wasm for relayer-utils: ",s);});async function S(s){try{return await y,await relayerUtils.parseEmail(s)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function Y(s,e,t=!1){let o=await S(s);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.cleanedBody;if(e.shaPrecomputeSelector){let a=r.split(e.shaPrecomputeSelector)[1];if(!a)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=a;}let n=o.canonicalizedHeader;return await X(n,r,e),await Promise.all(e.decomposedRegexes.map(a=>T(r,n,a,t)))}async function X(s,e,t){await y;let o=new TextEncoder,r=o.encode(s);if((await relayerUtils.sha256Pad(r,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let i=o.encode(e),a=(e.length+63+65)/64*64,c=Math.max(a,t.emailBodyMaxLength);if((await relayerUtils.sha256Pad(i,c)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function T(s,e,t,o=!1){let r={parts:t.parts.map(u=>({is_public:"isPublic"in u?u.isPublic:u.is_public,regex_def:"regexDef"in u?u.regexDef:u.regex_def}))},n;if(t.location==="body")n=s;else if(t.location==="header")n=e;else throw Error(`Unsupported location ${t.location}`);let i="maxLength"in t?t.maxLength:t.max_length;console.log("maxLength: ",i),await y;let a=relayerUtils.extractSubstr(n,r,!1);if(console.log("privateResult : ",a),a[0].length>i)throw new Error(`Max length of ${i} of extracted result was exceeded for decomposed regex ${t.name}`);return o?relayerUtils.extractSubstr(n,r,o):a}async function B(s,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await y;let n=e.map(a=>({...a,parts:a.parts.map(c=>({is_public:c.isPublic||!!c.is_public,regex_def:c.regexDef||!!c.regex_def}))})),i=await relayerUtils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(s,n,t,r);return JSON.stringify(Object.fromEntries(i))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}var P=class{options;blueprint;constructor(e,t){if(!(e instanceof d))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={...t||{isLocal:!1}};}async generateProof(e,t=[]){if(this.options.isLocal)return await this.generateLocalProof(e,t);{let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}}async generateLocalProof(e,t=[]){let o=await this.generateProofInputs(e,t);console.log("got inputs");let r=await this.blueprint.getChunkedZkeyUrls(),n=await this.blueprint.getWasmUrl(),i=`
3
+ import localforage from "localforage";
4
+ import * as snarkjs from "snarkjs";
5
+ import pako from "pako";
6
+
7
+ const circuitName = "circuit";
8
+
9
+ async function downloadWithRetries(link, downloadAttempts) {
10
+ for (let i = 1; i <= downloadAttempts; i++) {
11
+ console.log(\`download attempt \${i} for \${link}\`);
12
+ const response = await fetch(link, { method: "GET" });
13
+ if (response.status === 200) {
14
+ return response;
15
+ }
16
+ }
17
+ throw new Error(\`Error downloading \${link} after \${downloadAttempts} retries\`);
18
+ }
19
+
20
+ // uncompresses single .gz file.
21
+ // returns the contents as an ArrayBuffer
22
+ export const uncompressGz = async (arrayBuffer) => {
23
+ const output = pako.ungzip(arrayBuffer);
24
+ const buff = output.buffer;
25
+ return buff;
26
+ };
27
+
28
+ // GET the compressed file from the remote server, then store it with localforage
29
+ // Note that it must be stored as an uncompressed ArrayBuffer
30
+ // and named such that filename===\`\${name}.zkey\${a}\` in order for it to be found by snarkjs.
31
+ export async function downloadFromUrl(fileUrl, targetFileName, compressed = false) {
32
+ const fileResp = await downloadWithRetries(fileUrl, 3);
33
+
34
+ const buff = await fileResp.arrayBuffer();
35
+ if (!compressed) {
36
+ await localforage.setItem(targetFileName, buff);
37
+ } else {
38
+ // uncompress the data
39
+ const fileUncompressed = await uncompressGz(buff);
40
+ await localforage.setItem(targetFileName, fileUncompressed);
41
+ console.log("stored file in localforage", targetFileName);
42
+ }
43
+ console.log(\`Storage of \${targetFileName} successful!\`);
44
+ }
45
+
46
+ self.onmessage = async function (event) {
47
+ const { chunkedZkeyUrls, inputs, wasmUrl } = event.data;
48
+
49
+ self.postMessage({ type: "message", message: "Worker started" });
50
+
51
+ // const circuitName = "circuit";
52
+ // const filesUrl = "http://localhost:4000/download/";
53
+
54
+ await Promise.all(
55
+ chunkedZkeyUrls.map(async ({ suffix, url }) => {
56
+ await downloadFromUrl(url, \`\${circuitName}.zkey\${suffix}\`, true);
57
+ })
58
+ );
59
+ self.postMessage({ type: "message", message: "Download complete" });
60
+
61
+ try {
62
+ // const { proof, publicSignals } = await generateProof(input, filesUrl, circuitName);
63
+ const { proof, publicSignals } = await snarkjs.groth16.fullProve(
64
+ JSON.parse(inputs),
65
+ wasmUrl,
66
+ \`\${circuitName}.zkey\`
67
+ );
68
+
69
+ await localforage.clear();
70
+ self.postMessage({ type: "result", message: proof });
71
+
72
+ // const result = await verifyProof(proof, publicSignals, filesUrl, circuitName);
73
+
74
+ // self.postMessage({ type: "result", result });
75
+
76
+ self.close(); // Shut down the worker
77
+ } catch (error) {
78
+ self.postMessage({ type: "error", error: error.message });
79
+ self.close(); // Shut down on error
80
+ }
81
+ };
82
+ `;console.log("got urls, wasmUrl: ",n);let a=new Blob([i],{type:"application/javascript"}),c=URL.createObjectURL(a),u=await new Promise((U,A)=>{let _=new Worker(c,{type:"module"});console.log("meta url: ",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))),_.onmessage=F=>{let{type:M,message:N,progress:O,result:k,error:D}=F.data;switch(M){case"progress":console.log(`Download progress: ${O}`);break;case"message":console.log(N);break;case"result":console.log("Proof result:",k),U(k);break;case"error":console.error("Error in worker:",D),A(D);break}},_.postMessage({chunkedZkeyUrls:r,inputs:o,wasmUrl:n});});return console.log("result: ",u),u}async generateProofInputs(e,t=[]){if(!this.blueprint.getId())throw new Error("Blueprint of Proover must be initialized in order to create a Proof");if(this.blueprint.props.externalInputs?.length&&!t.length)throw new Error(`The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`);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 B(e,this.blueprint.props.decomposedRegexes,t,n);}catch(n){throw console.error("Failed to generate inputs for proof"),n}return r}async generateProofRequest(e,t=[]){let o=this.blueprint.getId();if(!o)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r=await this.generateProofInputs(e,t);console.log("got proof input");let n;try{let a={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((c,u)=>({...c,[u.name]:u.value}),{})};n=await h(`${this.blueprint.baseUrl}/proof`,a);}catch(a){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",a),a}let i=m.responseToProofProps(n);return new m(this.blueprint,i)}};var ee=(e=>(e.Circom="circom",e))(ee||{}),L=(n=>(n[n.None=0]="None",n[n.Draft=1]="Draft",n[n.InProgress=2]="InProgress",n[n.Done=3]="Done",n[n.Failed=4]="Failed",n))(L||{});var $=zod.z.object({title:zod.z.string().min(1,{message:"Title must be at least 1 characters."}),circuitName:zod.z.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/,"Invalid name, must start with a letter, digit, or underscore, and can only contain letters, digits or underscores."),description:zod.z.string().min(1),emailQuery:zod.z.string(),ignoreBodyHashCheck:zod.z.boolean(),shaPrecomputeSelector:zod.z.string().transform(s=>s.replace(/(?<!\\)"/g,'\\"')).optional(),senderDomain:zod.z.string().refine(s=>!s.includes("@"),{message:"Sender domain should not contain '@' symbol, only the domain"}),emailBodyMaxLength:zod.z.coerce.number().transform((s,e)=>(s%64!==0&&e.addIssue({code:"custom",message:"Must be a multiple of 64"}),s>1e4&&e.addIssue({code:"custom",message:"Must be less than or equal to 10000"}),s)),emailHeaderMaxLength:zod.z.coerce.number().transform((s,e)=>(s%64!==0&&e.addIssue({code:"custom",message:"Must be a multiple of 64"}),s)).default(1024),decomposedRegexes:zod.z.array(zod.z.object({name:zod.z.string().min(1).transform((s,e)=>s.includes(" ")?(e.addIssue({code:"custom",message:"Warning: Name contains spaces or dashes. They will be replaced with underscores."}),s.replace(/[ -]/g,"_")):s),maxLength:zod.z.coerce.number().positive().default(64),location:zod.z.string().regex(/(body)|(header)/),parts:zod.z.string().transform((s,e)=>{if(!s.includes("isPublic"))return e.addIssue({code:"custom",message:'Each parts config must include at least one "isPublic" field, and at least one thats true and one thats false. Please add it for now until we fix this requirement.'}),zod.z.NEVER;let t;try{t=JSON.parse(s);}catch{return e.addIssue({code:"custom",message:"Invalid JSON"}),zod.z.NEVER}if(!Array.isArray(t))return e.addIssue({code:"custom",message:"Parts must be an array"}),zod.z.NEVER;for(let o=0;o<t.length;o++){let r=t[o];if(typeof r!="object"||r===null)return e.addIssue({code:"custom",message:`Part ${o} must be an object`}),zod.z.NEVER;if(!("isPublic"in r)||typeof r.isPublic!="boolean")return e.addIssue({code:"custom",message:`Part ${o} must have a boolean 'isPublic' field`}),zod.z.NEVER;if(!("regexDef"in r)||typeof r.regexDef!="string")return e.addIssue({code:"custom",message:`Part ${o} must have a string 'regexDef' field`}),zod.z.NEVER}try{return te(t),t}catch(o){return e.addIssue({code:"custom",message:o.message}),zod.z.NEVER}}).optional().or(zod.z.array(zod.z.any()))})),externalInputs:zod.z.array(zod.z.object({name:zod.z.string().min(1),maxLength:zod.z.coerce.number().positive().default(64)})).optional()});function te(s){let e="";for(let t of s){if(t.isPublic||(e=e+t.regexDef),!t.isPublic&&!t.regexDef)throw new Error("Part has to have a nonempty regex with isPublic = false");break}if(!e)throw new Error("Part has to have a regex with isPublic = false in order to find it later");return JSON.stringify(e)}var d=class s{props;auth;baseUrl;stars=0;static formSchema=$;lastCheckedStatus=null;constructor(e,t,o){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=o;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,o){let r;try{r=await p(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let n=this.responseToBlueprintProps(r);return new s(n,t,o)}static async getBlueprintBySlug(e,t,o){let r=e.split("@");if(!r||!(r.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let n=r.pop().replace("v","");if(e=encodeURIComponent(r.join("")),!n)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let i;try{let u=`${t}/blueprint/by-slug/${e}/${n}`;i=await p(u);}catch(u){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",u),u}let a=this.responseToBlueprintProps(i);return new s(a,t,o)}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(o=>({name:o.name,maxLength:o.max_length})),decomposedRegexes:e.decomposed_regexes?.map(o=>({parts:o.parts.map(r=>({isPublic:r.is_public,regexDef:r.regex_def})),name:o.name,maxLength:o.max_length,location:o.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version,stars:e.stars}}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(o=>({name:o.name,max_length:o.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(o=>({parts:o.parts.map(r=>({is_public:r.isPublic||r.is_public,regex_def:r.regexDef||r.regex_def})),name:o.name,max_length:o.maxLength,location:o.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=s.blueprintPropsToRequest(this.props),t;try{t=await h(`${this.baseUrl}/blueprint`,e,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=s.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=s.blueprintPropsToRequest(e),o;try{o=await h(`${this.baseUrl}/blueprint`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitNewVersionDraft: ",r),r}this.props=s.responseToBlueprintProps(o);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await h(`${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,o){t?.sortBy&&(t.sortBy=t.sortBy==="updatedAt"?"updated_at":t.sortBy);let r;try{r=await p(`${e}/blueprint`,t,o);}catch(i){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",i),i}return r.blueprints?r.blueprints.map(i=>{let a=s.responseToBlueprintProps(i);return new s(a,e,o)}):[]}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 h(`${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 o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}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.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,o]of Object.entries(e)){let r=document.createElement("a");r.href=o,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r);}}createProver(e){return new P(this,e)}async verifyProofOnChain(e){try{await f(e);}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=s.blueprintPropsToRequest(e),o;try{o=await E(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=s.responseToBlueprintProps(o);}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 o=s.responseToBlueprintProps(t);return new s(o,this.baseUrl,this.auth)})}async addStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await h(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling POST on /blueprint/${slug}/stars in addStar: ",e),e}}async removeStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await w(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id}/stars in addStar: ",e),e}}async getStars(){try{let{stars:e}=await p(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.props.stars=e||0,e||0}catch(e){throw console.error("Failed calling POST on /blueprint/${id}/stars in addStar: ",e),e}}async cancelCompilation(){if(this.props.status!==2)throw new Error("Can only cancel compilation of a blueprint that is in progress");try{await w(`${this.baseUrl}/blueprint/cancel/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: ",e),e}}async delete(){try{await w(`${this.baseUrl}/blueprint/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id} in cancelCompilation: ",e),e}}async getChunkedZkeyUrls(){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/chunked-zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/chunked-zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async getWasmUrl(){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/wasm/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/wasm/:id in getWasmUrl: ",t),t}return e.url}};async function C(s,e){let{slugs:t}=await p(`${s}/blueprint/starred`,null,e);return t}var rt=s=>{let e=s?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!s&&!s.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new d(t,e,s.auth)},async getBlueprint(t){return d.getBlueprintBySlug(t,e,s?.auth)},async getBlueprintById(t){return d.getBlueprintById(t,e,s?.auth)},async listBlueprints(t){return d.listBlueprints(e,t,s?.auth)},async getProof(t){return m.getProofById(t,e)},async getStarredBlueprints(){if(!s&&!s.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return C(e,s.auth)}}};
83
+ Object.defineProperty(exports,"ZodError",{enumerable:true,get:function(){return zod.ZodError}});exports.Blueprint=d;exports.Proof=m;exports.ProofStatus=x;exports.Status=L;exports.ZkFramework=ee;exports.default=rt;exports.generateProofInputs=B;exports.getDKIMSelector=V;exports.getLoginWithGithubUrl=Z;exports.parseEmail=S;exports.startJsonFileDownload=J;exports.testBlueprint=Y;exports.testDecomposedRegex=T;//# sourceMappingURL=index.js.map
4
84
  //# sourceMappingURL=index.js.map