@psalomo/jsonrpc-client 0.3.0 → 0.5.0

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.
@@ -0,0 +1 @@
1
+ function e(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function t(e){return e.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function n(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(n);const s={};for(const[o,r]of Object.entries(t)){s[e(o)]=n(r)}return s}function s(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);const n={};for(const[o,r]of Object.entries(e)){n[t(o)]=s(r)}return n}class o extends Error{code;data;constructor(e,t,n){super(e),this.code=t,this.data=n,this.name="JsonRpcClientError"}}class r extends Error{cause;constructor(e,t){super(e),this.cause=t,this.name="JsonRpcNetworkError"}}class i{endpoint;headers;timeout;retries;validation;constructor(e){this.endpoint=e.endpoint,this.headers=e.headers||{},this.timeout=e.timeout||3e4,this.retries=e.retries||3,e.validation&&(this.validation=e.validation)}async makeRequest(e,t){const i={jsonrpc:"2.0",id:"dontcare",method:e,params:t?n(t):t};this.validation&&this.validation.validateRequest(i);let a=null;for(let e=0;e<=this.retries;e++)try{const e=new AbortController,t=setTimeout(()=>e.abort(),this.timeout),n=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(i),signal:e.signal});if(clearTimeout(t),!n.ok)throw new r(`HTTP error! status: ${n.status}`);const a=await n.json();if(this.validation&&this.validation.validateResponse(a),a.error)throw new o(a.error.message,a.error.code,a.error.data);return a.result?s(a.result):a.result}catch(t){if(a=t,t instanceof o)throw t;if(e===this.retries)break;await new Promise(t=>setTimeout(t,1e3*Math.pow(2,e)))}throw a||new r("Request failed after all retries")}withConfig(e){return new i({endpoint:e.endpoint??this.endpoint,headers:e.headers??this.headers,timeout:e.timeout??this.timeout,retries:e.retries??this.retries,...void 0!==e.validation?{validation:e.validation}:void 0!==this.validation?{validation:this.validation}:{}})}}const a=new i({endpoint:"https://rpc.mainnet.near.org"});class c extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.data=n,this.name="NearRpcError"}}function u(e,t,n){function s(n,s){var o;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(o=n._zod).traits??(o.traits=new Set),n._zod.traits.add(e),t(n,s);for(const e in i.prototype)e in n||Object.defineProperty(n,e,{value:i.prototype[e].bind(n)});n._zod.constr=i,n._zod.def=s}const o=n?.Parent??Object;class r extends o{}function i(e){var t;const o=n?.Parent?new r:this;s(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const e of o._zod.deferred)e();return o}return Object.defineProperty(r,"name",{value:e}),Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class l extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const d={};function p(e){return d}function f(e,t){return"bigint"==typeof t?t.toString():t}function h(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function _(e,t,n){Object.defineProperty(e,t,{get(){{const s=n();return e[t]=s,s}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function y(e){return JSON.stringify(e)}const m=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function v(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const E=h(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function g(e,t=0){for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function w(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function b(e){return"string"==typeof e?e:e?.message}function k(e,t,n){const s={...e,path:e.path??[]};if(!e.message){const o=b(e.inst?._zod.def?.error?.(e))??b(t?.error?.(e))??b(n.customError?.(e))??b(n.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}const R=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,f,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},z=u("$ZodError",R),P=u("$ZodError",R,{Parent:Error}),I=(e=>(t,n,s,o)=>{const r=s?Object.assign(s,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new l;if(i.issues.length){const t=new(o?.Err??e)(i.issues.map(e=>k(e,r,p())));throw m(t,o?.callee),t}return i.value})(P),T=(e=>async(t,n,s,o)=>{const r=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise&&(i=await i),i.issues.length){const t=new(o?.Err??e)(i.issues.map(e=>k(e,r,p())));throw m(t,o?.callee),t}return i.value})(P),N=(e=>(t,n,s)=>{const o=s?{...s,async:!1}:{async:!1},r=t._zod.run({value:n,issues:[]},o);if(r instanceof Promise)throw new l;return r.issues.length?{success:!1,error:new(e??z)(r.issues.map(e=>k(e,o,p())))}:{success:!0,data:r.value}})(P),$=(e=>async(t,n,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let r=t._zod.run({value:n,issues:[]},o);return r instanceof Promise&&(r=await r),r.issues.length?{success:!1,error:new e(r.issues.map(e=>k(e,o,p())))}:{success:!0,data:r.value}})(P),A=/^-?\d+(?:\.\d+)?/i;class M{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),s=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of s)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const j={major:4,minor:0,patch:5},q=u("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=j;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const t of s)for(const n of t._zod.onattach)n(e);if(0===s.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let s,o=g(e);for(const r of t){if(r._zod.def.when){if(!r._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,i=r._zod.check(e);if(i instanceof Promise&&!1===n?.async)throw new l;if(s||i instanceof Promise)s=(s??Promise.resolve()).then(async()=>{await i;e.issues.length!==t&&(o||(o=g(e,t)))});else{if(e.issues.length===t)continue;o||(o=g(e,t))}}return s?s.then(()=>e):e};e._zod.run=(n,o)=>{const r=e._zod.parse(n,o);if(r instanceof Promise){if(!1===o.async)throw new l;return r.then(e=>t(e,s,o))}return t(r,s,o)}}e["~standard"]={validate:t=>{try{const n=N(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return $(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),L=u("$ZodString",(e,t)=>{var n;q.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=String(n.value)}catch(s){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),x=u("$ZodNumber",(e,t)=>{q.init(e,t),e._zod.pattern=e._zod.bag.pattern??A,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const r="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...r?{received:r}:{}}),n}}),X=u("$ZodUnknown",(e,t)=>{q.init(e,t),e._zod.parse=e=>e});function O(e,t,n){e.issues.length&&t.issues.push(...w(n,e.issues)),t.value[n]=e.value}function S(e,t,n,s){e.issues.length?void 0===s[n]?t.value[n]=n in s?void 0:e.value:t.issues.push(...w(n,e.issues)):void 0===e.value?n in s&&(t.value[n]=void 0):t.value[n]=e.value}const Z=u("$ZodObject",(e,t)=>{q.init(e,t);const n=h(()=>{const e=Object.keys(t.shape);for(const n of e)if(!(t.shape[n]instanceof q))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(s=t.shape,Object.keys(s).filter(e=>"optional"===s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});_(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const s=e[t]._zod;if(s.values){n[t]??(n[t]=new Set);for(const e of s.values)n[t].add(e)}}return n});let s;const o=v,r=!d.jitless,i=r&&E.value,a=t.catchall;let c;e._zod.parse=(u,l)=>{c??(c=n.value);const d=u.value;if(!o(d))return u.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),u;const p=[];if(r&&i&&!1===l?.async&&!0!==l.jitless)s||(s=(e=>{const t=new M(["shape","payload","ctx"]),s=n.value,o=e=>{const t=y(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const r=Object.create(null);let i=0;for(const e of s.keys)r[e]="key_"+i++;t.write("const newResult = {}");for(const e of s.keys)if(s.optionalKeys.has(e)){const n=r[e];t.write(`const ${n} = ${o(e)};`);const s=y(e);t.write(`\n if (${n}.issues.length) {\n if (input[${s}] === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${n}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}],\n }))\n );\n }\n } else if (${n}.value === undefined) {\n if (${s} in input) newResult[${s}] = undefined;\n } else {\n newResult[${s}] = ${n}.value;\n }\n `)}else{const n=r[e];t.write(`const ${n} = ${o(e)};`),t.write(`\n if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${y(e)}, ...iss.path] : [${y(e)}]\n })));`),t.write(`newResult[${y(e)}] = ${n}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),u=s(u,l);else{u.value={};const e=c.shape;for(const t of c.keys){const n=e[t],s=n._zod.run({value:d[t],issues:[]},l),o="optional"===n._zod.optin&&"optional"===n._zod.optout;s instanceof Promise?p.push(s.then(e=>o?S(e,u,t,d):O(e,u,t))):o?S(s,u,t,d):O(s,u,t)}}if(!a)return p.length?Promise.all(p).then(()=>u):u;const f=[],h=c.keySet,_=a._zod,m=_.def.type;for(const e of Object.keys(d)){if(h.has(e))continue;if("never"===m){f.push(e);continue}const t=_.run({value:d[e],issues:[]},l);t instanceof Promise?p.push(t.then(t=>O(t,u,e))):O(t,u,e)}return f.length&&u.issues.push({code:"unrecognized_keys",keys:f,input:d,inst:e}),p.length?Promise.all(p).then(()=>u):u}}),C=u("$ZodLiteral",(e,t)=>{q.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(n,s)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),K=u("$ZodOptional",(e,t)=>{q.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${function(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,n):void 0===e.value?e:t.innerType._zod.run(e,n)});const U=u("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");q.init(e,t),e.def=t,e.parse=(t,n)=>I(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>N(e,t,n),e.parseAsync=async(t,n)=>T(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>$(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,n)=>function(e,t,n){const s=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(s._zod.parent=e),s}(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e)}),J=u("ZodMiniString",(e,t)=>{L.init(e,t),U.init(e,t)});function F(e){return new J({type:"string"})}const B=u("ZodMiniNumber",(e,t)=>{x.init(e,t),U.init(e,t)});const W=u("ZodMiniUnknown",(e,t)=>{X.init(e,t),U.init(e,t)});function H(){return new W({type:"unknown"})}const V=u("ZodMiniObject",(e,t)=>{Z.init(e,t),U.init(e,t),_(e,"shape",()=>t.shape)});function D(e,t){return new V({type:"object",get shape(){var t,n,s;return t=this,n="shape",s={...e},Object.defineProperty(t,n,{value:s,writable:!0,enumerable:!0,configurable:!0}),this.shape}})}const G=u("ZodMiniLiteral",(e,t)=>{C.init(e,t),U.init(e,t)});function Q(e,t){return new G({type:"literal",values:Array.isArray(e)?e:[e]})}const Y=u("ZodMiniOptional",(e,t)=>{K.init(e,t),U.init(e,t)});function ee(e){return new Y({type:"optional",innerType:e})}var te=()=>D({jsonrpc:Q("2.0"),id:F(),method:F(),params:ee(H())}),ne=()=>D({jsonrpc:Q("2.0"),id:F(),result:ee(H()),error:ee(D({code:new B({type:"number",checks:[]}),message:F(),data:ee(H())}))}),se={"/EXPERIMENTAL_changes":"EXPERIMENTAL_changes","/EXPERIMENTAL_changes_in_block":"EXPERIMENTAL_changes_in_block","/EXPERIMENTAL_congestion_level":"EXPERIMENTAL_congestion_level","/EXPERIMENTAL_genesis_config":"EXPERIMENTAL_genesis_config","/EXPERIMENTAL_light_client_block_proof":"EXPERIMENTAL_light_client_block_proof","/EXPERIMENTAL_light_client_proof":"EXPERIMENTAL_light_client_proof","/EXPERIMENTAL_maintenance_windows":"EXPERIMENTAL_maintenance_windows","/EXPERIMENTAL_protocol_config":"EXPERIMENTAL_protocol_config","/EXPERIMENTAL_receipt":"EXPERIMENTAL_receipt","/EXPERIMENTAL_split_storage_info":"EXPERIMENTAL_split_storage_info","/EXPERIMENTAL_tx_status":"EXPERIMENTAL_tx_status","/EXPERIMENTAL_validators_ordered":"EXPERIMENTAL_validators_ordered","/block":"block","/broadcast_tx_async":"broadcast_tx_async","/broadcast_tx_commit":"broadcast_tx_commit","/changes":"changes","/chunk":"chunk","/client_config":"client_config","/gas_price":"gas_price","/health":"health","/light_client_proof":"light_client_proof","/network_info":"network_info","/next_light_client_block":"next_light_client_block","/query":"query","/send_tx":"send_tx","/status":"status","/tx":"tx","/validators":"validators"};Object.entries(se).forEach(([e,t])=>{});var oe=Object.values(se);async function re(e,t){return e.makeRequest("EXPERIMENTAL_changes",t)}async function ie(e,t){return e.makeRequest("EXPERIMENTAL_changes_in_block",t)}async function ae(e,t){return e.makeRequest("EXPERIMENTAL_congestion_level",t)}async function ce(e,t){return e.makeRequest("EXPERIMENTAL_genesis_config",t)}async function ue(e,t){return e.makeRequest("EXPERIMENTAL_light_client_block_proof",t)}async function le(e,t){return e.makeRequest("EXPERIMENTAL_light_client_proof",t)}async function de(e,t){return e.makeRequest("EXPERIMENTAL_maintenance_windows",t)}async function pe(e,t){return e.makeRequest("EXPERIMENTAL_protocol_config",t)}async function fe(e,t){return e.makeRequest("EXPERIMENTAL_receipt",t)}async function he(e,t){return e.makeRequest("EXPERIMENTAL_split_storage_info",t)}async function _e(e,t){return e.makeRequest("EXPERIMENTAL_tx_status",t)}async function ye(e,t){return e.makeRequest("EXPERIMENTAL_validators_ordered",t)}async function me(e,t){return e.makeRequest("block",t)}async function ve(e,t){return e.makeRequest("broadcast_tx_async",t)}async function Ee(e,t){return e.makeRequest("broadcast_tx_commit",t)}async function ge(e,t){return e.makeRequest("changes",t)}async function we(e,t){return e.makeRequest("chunk",t)}async function be(e,t){return e.makeRequest("client_config",t)}async function ke(e,t){return e.makeRequest("gas_price",t)}async function Re(e,t){return e.makeRequest("health",t)}async function ze(e,t){return e.makeRequest("light_client_proof",t)}async function Pe(e,t){return e.makeRequest("network_info",t)}async function Ie(e,t){return e.makeRequest("next_light_client_block",t)}async function Te(e,t){return e.makeRequest("query",t)}async function Ne(e,t){return e.makeRequest("send_tx",t)}async function $e(e,t){return e.makeRequest("status",t)}async function Ae(e,t){return e.makeRequest("tx",t)}async function Me(e,t){return e.makeRequest("validators",t)}async function je(e,t){return Te(e,t.blockId?{requestType:"view_account",accountId:t.accountId,blockId:t.blockId}:{requestType:"view_account",accountId:t.accountId,finality:t.finality||"final"})}async function qe(e,t){const n={requestType:"call_function",accountId:t.accountId,methodName:t.methodName,argsBase64:t.argsBase64??""};return Te(e,t.blockId?{...n,blockId:t.blockId}:{...n,finality:t.finality||"final"})}async function Le(e,t){return Te(e,t.blockId?{requestType:"view_access_key",accountId:t.accountId,publicKey:t.publicKey,blockId:t.blockId}:{requestType:"view_access_key",accountId:t.accountId,publicKey:t.publicKey,finality:t.finality||"final"})}function xe(){const e=te(),t=ne();return{validateRequest:t=>{try{e.parse(t)}catch(e){throw new r(`Invalid request format: ${e instanceof Error?e.message:"Unknown error"}`,e)}},validateResponse:e=>{try{t.parse(e)}catch(e){throw new o(`Invalid response format: ${e instanceof Error?e.message:"Unknown error"}`)}}}}export{o as JsonRpcClientError,r as JsonRpcNetworkError,te as JsonRpcRequestSchema,ne as JsonRpcResponseSchema,i as NearRpcClient,c as NearRpcError,oe as RPC_METHODS,me as block,ve as broadcastTxAsync,Ee as broadcastTxCommit,ge as changes,we as chunk,be as clientConfig,i as default,a as defaultClient,xe as enableValidation,re as experimentalChanges,ie as experimentalChangesInBlock,ae as experimentalCongestionLevel,ce as experimentalGenesisConfig,ue as experimentalLightClientBlockProof,le as experimentalLightClientProof,de as experimentalMaintenanceWindows,pe as experimentalProtocolConfig,fe as experimentalReceipt,he as experimentalSplitStorageInfo,_e as experimentalTxStatus,ye as experimentalValidatorsOrdered,ke as gasPrice,Re as health,ze as lightClientProof,Pe as networkInfo,Ie as nextLightClientBlock,Te as query,Ne as sendTx,$e as status,Ae as tx,Me as validators,Le as viewAccessKey,je as viewAccount,qe as viewFunction};