@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,1245 @@
1
+ // Case conversion utilities (identical to regular client)
2
+ function camelToSnake(str) {
3
+ return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
4
+ }
5
+ function snakeToCamel(str) {
6
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
7
+ }
8
+ function convertKeysToSnakeCase(obj) {
9
+ if (obj === null || typeof obj !== 'object') {
10
+ return obj;
11
+ }
12
+ if (Array.isArray(obj)) {
13
+ return obj.map(convertKeysToSnakeCase);
14
+ }
15
+ const converted = {};
16
+ for (const [key, value] of Object.entries(obj)) {
17
+ const snakeKey = camelToSnake(key);
18
+ converted[snakeKey] = convertKeysToSnakeCase(value);
19
+ }
20
+ return converted;
21
+ }
22
+ function convertKeysToCamelCase(obj) {
23
+ if (obj === null || typeof obj !== 'object') {
24
+ return obj;
25
+ }
26
+ if (Array.isArray(obj)) {
27
+ return obj.map(convertKeysToCamelCase);
28
+ }
29
+ const converted = {};
30
+ for (const [key, value] of Object.entries(obj)) {
31
+ const camelKey = snakeToCamel(key);
32
+ converted[camelKey] = convertKeysToCamelCase(value);
33
+ }
34
+ return converted;
35
+ }
36
+ // Use static ID matching NEAR RPC documentation examples
37
+ const REQUEST_ID = 'dontcare';
38
+ // Custom error classes
39
+ class JsonRpcClientError extends Error {
40
+ code;
41
+ data;
42
+ constructor(message, code, data) {
43
+ super(message);
44
+ this.code = code;
45
+ this.data = data;
46
+ this.name = 'JsonRpcClientError';
47
+ }
48
+ }
49
+ class JsonRpcNetworkError extends Error {
50
+ cause;
51
+ constructor(message, cause) {
52
+ super(message);
53
+ this.cause = cause;
54
+ this.name = 'JsonRpcNetworkError';
55
+ }
56
+ }
57
+ /**
58
+ * Simplified NEAR RPC Client for mini version
59
+ * This client only holds configuration and provides a makeRequest method
60
+ * Individual RPC methods are provided as standalone functions that take this client as a parameter
61
+ */
62
+ class NearRpcClient {
63
+ endpoint;
64
+ headers;
65
+ timeout;
66
+ retries;
67
+ validation;
68
+ constructor(config) {
69
+ this.endpoint = config.endpoint;
70
+ this.headers = config.headers || {};
71
+ this.timeout = config.timeout || 30000;
72
+ this.retries = config.retries || 3;
73
+ if (config.validation) {
74
+ this.validation = config.validation;
75
+ }
76
+ }
77
+ /**
78
+ * Make a raw JSON-RPC request
79
+ * This is used internally by the standalone RPC functions
80
+ */
81
+ async makeRequest(method, params) {
82
+ // Convert camelCase params to snake_case for the RPC call
83
+ const snakeCaseParams = params ? convertKeysToSnakeCase(params) : params;
84
+ const request = {
85
+ jsonrpc: '2.0',
86
+ id: REQUEST_ID,
87
+ method,
88
+ params: snakeCaseParams,
89
+ };
90
+ // Validate request if validation is enabled
91
+ if (this.validation) {
92
+ this.validation.validateRequest(request);
93
+ }
94
+ let lastError = null;
95
+ for (let attempt = 0; attempt <= this.retries; attempt++) {
96
+ try {
97
+ const controller = new AbortController();
98
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
99
+ const response = await fetch(this.endpoint, {
100
+ method: 'POST',
101
+ headers: {
102
+ 'Content-Type': 'application/json',
103
+ ...this.headers,
104
+ },
105
+ body: JSON.stringify(request),
106
+ signal: controller.signal,
107
+ });
108
+ clearTimeout(timeoutId);
109
+ if (!response.ok) {
110
+ throw new JsonRpcNetworkError(`HTTP error! status: ${response.status}`);
111
+ }
112
+ const jsonResponse = await response.json();
113
+ // Validate response if validation is enabled
114
+ if (this.validation) {
115
+ this.validation.validateResponse(jsonResponse);
116
+ }
117
+ if (jsonResponse.error) {
118
+ throw new JsonRpcClientError(jsonResponse.error.message, jsonResponse.error.code, jsonResponse.error.data);
119
+ }
120
+ // Convert snake_case response back to camelCase
121
+ const camelCaseResult = jsonResponse.result
122
+ ? convertKeysToCamelCase(jsonResponse.result)
123
+ : jsonResponse.result;
124
+ return camelCaseResult;
125
+ }
126
+ catch (error) {
127
+ lastError = error;
128
+ // Don't retry on client errors or validation errors
129
+ if (error instanceof JsonRpcClientError) {
130
+ throw error;
131
+ }
132
+ // Don't retry if this is the last attempt
133
+ if (attempt === this.retries) {
134
+ break;
135
+ }
136
+ // Wait before retrying (exponential backoff)
137
+ await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
138
+ }
139
+ }
140
+ throw (lastError || new JsonRpcNetworkError('Request failed after all retries'));
141
+ }
142
+ /**
143
+ * Create a new client with modified configuration
144
+ */
145
+ withConfig(config) {
146
+ return new NearRpcClient({
147
+ endpoint: config.endpoint ?? this.endpoint,
148
+ headers: config.headers ?? this.headers,
149
+ timeout: config.timeout ?? this.timeout,
150
+ retries: config.retries ?? this.retries,
151
+ ...(config.validation !== undefined
152
+ ? { validation: config.validation }
153
+ : this.validation !== undefined
154
+ ? { validation: this.validation }
155
+ : {}),
156
+ });
157
+ }
158
+ }
159
+ // Default client instance for convenience
160
+ const defaultClient = new NearRpcClient({
161
+ endpoint: 'https://rpc.mainnet.near.org',
162
+ });
163
+
164
+ // Client-specific types
165
+ class NearRpcError extends Error {
166
+ code;
167
+ data;
168
+ constructor(code, message, data) {
169
+ super(message);
170
+ this.code = code;
171
+ this.data = data;
172
+ this.name = 'NearRpcError';
173
+ }
174
+ }
175
+
176
+ /** A special constant with type `never` */
177
+ function $constructor(name, initializer, params) {
178
+ function init(inst, def) {
179
+ var _a;
180
+ Object.defineProperty(inst, "_zod", {
181
+ value: inst._zod ?? {},
182
+ enumerable: false,
183
+ });
184
+ (_a = inst._zod).traits ?? (_a.traits = new Set());
185
+ inst._zod.traits.add(name);
186
+ initializer(inst, def);
187
+ // support prototype modifications
188
+ for (const k in _.prototype) {
189
+ if (!(k in inst))
190
+ Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
191
+ }
192
+ inst._zod.constr = _;
193
+ inst._zod.def = def;
194
+ }
195
+ // doesn't work if Parent has a constructor with arguments
196
+ const Parent = params?.Parent ?? Object;
197
+ class Definition extends Parent {
198
+ }
199
+ Object.defineProperty(Definition, "name", { value: name });
200
+ function _(def) {
201
+ var _a;
202
+ const inst = params?.Parent ? new Definition() : this;
203
+ init(inst, def);
204
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
205
+ for (const fn of inst._zod.deferred) {
206
+ fn();
207
+ }
208
+ return inst;
209
+ }
210
+ Object.defineProperty(_, "init", { value: init });
211
+ Object.defineProperty(_, Symbol.hasInstance, {
212
+ value: (inst) => {
213
+ if (params?.Parent && inst instanceof params.Parent)
214
+ return true;
215
+ return inst?._zod?.traits?.has(name);
216
+ },
217
+ });
218
+ Object.defineProperty(_, "name", { value: name });
219
+ return _;
220
+ }
221
+ class $ZodAsyncError extends Error {
222
+ constructor() {
223
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
224
+ }
225
+ }
226
+ const globalConfig = {};
227
+ function config(newConfig) {
228
+ return globalConfig;
229
+ }
230
+
231
+ // functions
232
+ function jsonStringifyReplacer(_, value) {
233
+ if (typeof value === "bigint")
234
+ return value.toString();
235
+ return value;
236
+ }
237
+ function cached(getter) {
238
+ return {
239
+ get value() {
240
+ {
241
+ const value = getter();
242
+ Object.defineProperty(this, "value", { value });
243
+ return value;
244
+ }
245
+ },
246
+ };
247
+ }
248
+ function cleanRegex(source) {
249
+ const start = source.startsWith("^") ? 1 : 0;
250
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
251
+ return source.slice(start, end);
252
+ }
253
+ function defineLazy(object, key, getter) {
254
+ Object.defineProperty(object, key, {
255
+ get() {
256
+ {
257
+ const value = getter();
258
+ object[key] = value;
259
+ return value;
260
+ }
261
+ },
262
+ set(v) {
263
+ Object.defineProperty(object, key, {
264
+ value: v,
265
+ // configurable: true,
266
+ });
267
+ // object[key] = v;
268
+ },
269
+ configurable: true,
270
+ });
271
+ }
272
+ function assignProp(target, prop, value) {
273
+ Object.defineProperty(target, prop, {
274
+ value,
275
+ writable: true,
276
+ enumerable: true,
277
+ configurable: true,
278
+ });
279
+ }
280
+ function esc(str) {
281
+ return JSON.stringify(str);
282
+ }
283
+ const captureStackTrace = Error.captureStackTrace
284
+ ? Error.captureStackTrace
285
+ : (..._args) => { };
286
+ function isObject(data) {
287
+ return typeof data === "object" && data !== null && !Array.isArray(data);
288
+ }
289
+ const allowsEval = cached(() => {
290
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
291
+ return false;
292
+ }
293
+ try {
294
+ const F = Function;
295
+ new F("");
296
+ return true;
297
+ }
298
+ catch (_) {
299
+ return false;
300
+ }
301
+ });
302
+ function escapeRegex(str) {
303
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
304
+ }
305
+ // zod-specific utils
306
+ function clone(inst, def, params) {
307
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
308
+ if (!def || params?.parent)
309
+ cl._zod.parent = inst;
310
+ return cl;
311
+ }
312
+ function normalizeParams(_params) {
313
+ return {};
314
+ }
315
+ function optionalKeys(shape) {
316
+ return Object.keys(shape).filter((k) => {
317
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
318
+ });
319
+ }
320
+ function aborted(x, startIndex = 0) {
321
+ for (let i = startIndex; i < x.issues.length; i++) {
322
+ if (x.issues[i]?.continue !== true)
323
+ return true;
324
+ }
325
+ return false;
326
+ }
327
+ function prefixIssues(path, issues) {
328
+ return issues.map((iss) => {
329
+ var _a;
330
+ (_a = iss).path ?? (_a.path = []);
331
+ iss.path.unshift(path);
332
+ return iss;
333
+ });
334
+ }
335
+ function unwrapMessage(message) {
336
+ return typeof message === "string" ? message : message?.message;
337
+ }
338
+ function finalizeIssue(iss, ctx, config) {
339
+ const full = { ...iss, path: iss.path ?? [] };
340
+ // for backwards compatibility
341
+ if (!iss.message) {
342
+ const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
343
+ unwrapMessage(ctx?.error?.(iss)) ??
344
+ unwrapMessage(config.customError?.(iss)) ??
345
+ unwrapMessage(config.localeError?.(iss)) ??
346
+ "Invalid input";
347
+ full.message = message;
348
+ }
349
+ // delete (full as any).def;
350
+ delete full.inst;
351
+ delete full.continue;
352
+ if (!ctx?.reportInput) {
353
+ delete full.input;
354
+ }
355
+ return full;
356
+ }
357
+
358
+ const initializer = (inst, def) => {
359
+ inst.name = "$ZodError";
360
+ Object.defineProperty(inst, "_zod", {
361
+ value: inst._zod,
362
+ enumerable: false,
363
+ });
364
+ Object.defineProperty(inst, "issues", {
365
+ value: def,
366
+ enumerable: false,
367
+ });
368
+ Object.defineProperty(inst, "message", {
369
+ get() {
370
+ return JSON.stringify(def, jsonStringifyReplacer, 2);
371
+ },
372
+ enumerable: true,
373
+ // configurable: false,
374
+ });
375
+ Object.defineProperty(inst, "toString", {
376
+ value: () => inst.message,
377
+ enumerable: false,
378
+ });
379
+ };
380
+ const $ZodError = $constructor("$ZodError", initializer);
381
+ const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
382
+
383
+ const _parse = (_Err) => (schema, value, _ctx, _params) => {
384
+ const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
385
+ const result = schema._zod.run({ value, issues: [] }, ctx);
386
+ if (result instanceof Promise) {
387
+ throw new $ZodAsyncError();
388
+ }
389
+ if (result.issues.length) {
390
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
391
+ captureStackTrace(e, _params?.callee);
392
+ throw e;
393
+ }
394
+ return result.value;
395
+ };
396
+ const parse = /* @__PURE__*/ _parse($ZodRealError);
397
+ const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
398
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
399
+ let result = schema._zod.run({ value, issues: [] }, ctx);
400
+ if (result instanceof Promise)
401
+ result = await result;
402
+ if (result.issues.length) {
403
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
404
+ captureStackTrace(e, params?.callee);
405
+ throw e;
406
+ }
407
+ return result.value;
408
+ };
409
+ const parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError);
410
+ const _safeParse = (_Err) => (schema, value, _ctx) => {
411
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
412
+ const result = schema._zod.run({ value, issues: [] }, ctx);
413
+ if (result instanceof Promise) {
414
+ throw new $ZodAsyncError();
415
+ }
416
+ return result.issues.length
417
+ ? {
418
+ success: false,
419
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
420
+ }
421
+ : { success: true, data: result.value };
422
+ };
423
+ const safeParse = /* @__PURE__*/ _safeParse($ZodRealError);
424
+ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
425
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
426
+ let result = schema._zod.run({ value, issues: [] }, ctx);
427
+ if (result instanceof Promise)
428
+ result = await result;
429
+ return result.issues.length
430
+ ? {
431
+ success: false,
432
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
433
+ }
434
+ : { success: true, data: result.value };
435
+ };
436
+ const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError);
437
+
438
+ const string$1 = (params) => {
439
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
440
+ return new RegExp(`^${regex}$`);
441
+ };
442
+ const number$1 = /^-?\d+(?:\.\d+)?/i;
443
+
444
+ class Doc {
445
+ constructor(args = []) {
446
+ this.content = [];
447
+ this.indent = 0;
448
+ if (this)
449
+ this.args = args;
450
+ }
451
+ indented(fn) {
452
+ this.indent += 1;
453
+ fn(this);
454
+ this.indent -= 1;
455
+ }
456
+ write(arg) {
457
+ if (typeof arg === "function") {
458
+ arg(this, { execution: "sync" });
459
+ arg(this, { execution: "async" });
460
+ return;
461
+ }
462
+ const content = arg;
463
+ const lines = content.split("\n").filter((x) => x);
464
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
465
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
466
+ for (const line of dedented) {
467
+ this.content.push(line);
468
+ }
469
+ }
470
+ compile() {
471
+ const F = Function;
472
+ const args = this?.args;
473
+ const content = this?.content ?? [``];
474
+ const lines = [...content.map((x) => ` ${x}`)];
475
+ // console.log(lines.join("\n"));
476
+ return new F(...args, lines.join("\n"));
477
+ }
478
+ }
479
+
480
+ const version = {
481
+ major: 4,
482
+ minor: 0,
483
+ patch: 5,
484
+ };
485
+
486
+ const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
487
+ var _a;
488
+ inst ?? (inst = {});
489
+ inst._zod.def = def; // set _def property
490
+ inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
491
+ inst._zod.version = version;
492
+ const checks = [...(inst._zod.def.checks ?? [])];
493
+ // if inst is itself a checks.$ZodCheck, run it as a check
494
+ if (inst._zod.traits.has("$ZodCheck")) {
495
+ checks.unshift(inst);
496
+ }
497
+ //
498
+ for (const ch of checks) {
499
+ for (const fn of ch._zod.onattach) {
500
+ fn(inst);
501
+ }
502
+ }
503
+ if (checks.length === 0) {
504
+ // deferred initializer
505
+ // inst._zod.parse is not yet defined
506
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
507
+ inst._zod.deferred?.push(() => {
508
+ inst._zod.run = inst._zod.parse;
509
+ });
510
+ }
511
+ else {
512
+ const runChecks = (payload, checks, ctx) => {
513
+ let isAborted = aborted(payload);
514
+ let asyncResult;
515
+ for (const ch of checks) {
516
+ if (ch._zod.def.when) {
517
+ const shouldRun = ch._zod.def.when(payload);
518
+ if (!shouldRun)
519
+ continue;
520
+ }
521
+ else if (isAborted) {
522
+ continue;
523
+ }
524
+ const currLen = payload.issues.length;
525
+ const _ = ch._zod.check(payload);
526
+ if (_ instanceof Promise && ctx?.async === false) {
527
+ throw new $ZodAsyncError();
528
+ }
529
+ if (asyncResult || _ instanceof Promise) {
530
+ asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
531
+ await _;
532
+ const nextLen = payload.issues.length;
533
+ if (nextLen === currLen)
534
+ return;
535
+ if (!isAborted)
536
+ isAborted = aborted(payload, currLen);
537
+ });
538
+ }
539
+ else {
540
+ const nextLen = payload.issues.length;
541
+ if (nextLen === currLen)
542
+ continue;
543
+ if (!isAborted)
544
+ isAborted = aborted(payload, currLen);
545
+ }
546
+ }
547
+ if (asyncResult) {
548
+ return asyncResult.then(() => {
549
+ return payload;
550
+ });
551
+ }
552
+ return payload;
553
+ };
554
+ inst._zod.run = (payload, ctx) => {
555
+ const result = inst._zod.parse(payload, ctx);
556
+ if (result instanceof Promise) {
557
+ if (ctx.async === false)
558
+ throw new $ZodAsyncError();
559
+ return result.then((result) => runChecks(result, checks, ctx));
560
+ }
561
+ return runChecks(result, checks, ctx);
562
+ };
563
+ }
564
+ inst["~standard"] = {
565
+ validate: (value) => {
566
+ try {
567
+ const r = safeParse(inst, value);
568
+ return r.success ? { value: r.data } : { issues: r.error?.issues };
569
+ }
570
+ catch (_) {
571
+ return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
572
+ }
573
+ },
574
+ vendor: "zod",
575
+ version: 1,
576
+ };
577
+ });
578
+ const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
579
+ $ZodType.init(inst, def);
580
+ inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$1(inst._zod.bag);
581
+ inst._zod.parse = (payload, _) => {
582
+ if (def.coerce)
583
+ try {
584
+ payload.value = String(payload.value);
585
+ }
586
+ catch (_) { }
587
+ if (typeof payload.value === "string")
588
+ return payload;
589
+ payload.issues.push({
590
+ expected: "string",
591
+ code: "invalid_type",
592
+ input: payload.value,
593
+ inst,
594
+ });
595
+ return payload;
596
+ };
597
+ });
598
+ const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
599
+ $ZodType.init(inst, def);
600
+ inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
601
+ inst._zod.parse = (payload, _ctx) => {
602
+ if (def.coerce)
603
+ try {
604
+ payload.value = Number(payload.value);
605
+ }
606
+ catch (_) { }
607
+ const input = payload.value;
608
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
609
+ return payload;
610
+ }
611
+ const received = typeof input === "number"
612
+ ? Number.isNaN(input)
613
+ ? "NaN"
614
+ : !Number.isFinite(input)
615
+ ? "Infinity"
616
+ : undefined
617
+ : undefined;
618
+ payload.issues.push({
619
+ expected: "number",
620
+ code: "invalid_type",
621
+ input,
622
+ inst,
623
+ ...(received ? { received } : {}),
624
+ });
625
+ return payload;
626
+ };
627
+ });
628
+ const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
629
+ $ZodType.init(inst, def);
630
+ inst._zod.parse = (payload) => payload;
631
+ });
632
+ function handleObjectResult(result, final, key) {
633
+ // if(isOptional)
634
+ if (result.issues.length) {
635
+ final.issues.push(...prefixIssues(key, result.issues));
636
+ }
637
+ final.value[key] = result.value;
638
+ }
639
+ function handleOptionalObjectResult(result, final, key, input) {
640
+ if (result.issues.length) {
641
+ // validation failed against value schema
642
+ if (input[key] === undefined) {
643
+ // if input was undefined, ignore the error
644
+ if (key in input) {
645
+ final.value[key] = undefined;
646
+ }
647
+ else {
648
+ final.value[key] = result.value;
649
+ }
650
+ }
651
+ else {
652
+ final.issues.push(...prefixIssues(key, result.issues));
653
+ }
654
+ }
655
+ else if (result.value === undefined) {
656
+ // validation returned `undefined`
657
+ if (key in input)
658
+ final.value[key] = undefined;
659
+ }
660
+ else {
661
+ // non-undefined value
662
+ final.value[key] = result.value;
663
+ }
664
+ }
665
+ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
666
+ // requires cast because technically $ZodObject doesn't extend
667
+ $ZodType.init(inst, def);
668
+ const _normalized = cached(() => {
669
+ const keys = Object.keys(def.shape);
670
+ for (const k of keys) {
671
+ if (!(def.shape[k] instanceof $ZodType)) {
672
+ throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
673
+ }
674
+ }
675
+ const okeys = optionalKeys(def.shape);
676
+ return {
677
+ shape: def.shape,
678
+ keys,
679
+ keySet: new Set(keys),
680
+ numKeys: keys.length,
681
+ optionalKeys: new Set(okeys),
682
+ };
683
+ });
684
+ defineLazy(inst._zod, "propValues", () => {
685
+ const shape = def.shape;
686
+ const propValues = {};
687
+ for (const key in shape) {
688
+ const field = shape[key]._zod;
689
+ if (field.values) {
690
+ propValues[key] ?? (propValues[key] = new Set());
691
+ for (const v of field.values)
692
+ propValues[key].add(v);
693
+ }
694
+ }
695
+ return propValues;
696
+ });
697
+ const generateFastpass = (shape) => {
698
+ const doc = new Doc(["shape", "payload", "ctx"]);
699
+ const normalized = _normalized.value;
700
+ const parseStr = (key) => {
701
+ const k = esc(key);
702
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
703
+ };
704
+ doc.write(`const input = payload.value;`);
705
+ const ids = Object.create(null);
706
+ let counter = 0;
707
+ for (const key of normalized.keys) {
708
+ ids[key] = `key_${counter++}`;
709
+ }
710
+ // A: preserve key order {
711
+ doc.write(`const newResult = {}`);
712
+ for (const key of normalized.keys) {
713
+ if (normalized.optionalKeys.has(key)) {
714
+ const id = ids[key];
715
+ doc.write(`const ${id} = ${parseStr(key)};`);
716
+ const k = esc(key);
717
+ doc.write(`
718
+ if (${id}.issues.length) {
719
+ if (input[${k}] === undefined) {
720
+ if (${k} in input) {
721
+ newResult[${k}] = undefined;
722
+ }
723
+ } else {
724
+ payload.issues = payload.issues.concat(
725
+ ${id}.issues.map((iss) => ({
726
+ ...iss,
727
+ path: iss.path ? [${k}, ...iss.path] : [${k}],
728
+ }))
729
+ );
730
+ }
731
+ } else if (${id}.value === undefined) {
732
+ if (${k} in input) newResult[${k}] = undefined;
733
+ } else {
734
+ newResult[${k}] = ${id}.value;
735
+ }
736
+ `);
737
+ }
738
+ else {
739
+ const id = ids[key];
740
+ // const id = ids[key];
741
+ doc.write(`const ${id} = ${parseStr(key)};`);
742
+ doc.write(`
743
+ if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
744
+ ...iss,
745
+ path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
746
+ })));`);
747
+ doc.write(`newResult[${esc(key)}] = ${id}.value`);
748
+ }
749
+ }
750
+ doc.write(`payload.value = newResult;`);
751
+ doc.write(`return payload;`);
752
+ const fn = doc.compile();
753
+ return (payload, ctx) => fn(shape, payload, ctx);
754
+ };
755
+ let fastpass;
756
+ const isObject$1 = isObject;
757
+ const jit = !globalConfig.jitless;
758
+ const allowsEval$1 = allowsEval;
759
+ const fastEnabled = jit && allowsEval$1.value; // && !def.catchall;
760
+ const catchall = def.catchall;
761
+ let value;
762
+ inst._zod.parse = (payload, ctx) => {
763
+ value ?? (value = _normalized.value);
764
+ const input = payload.value;
765
+ if (!isObject$1(input)) {
766
+ payload.issues.push({
767
+ expected: "object",
768
+ code: "invalid_type",
769
+ input,
770
+ inst,
771
+ });
772
+ return payload;
773
+ }
774
+ const proms = [];
775
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
776
+ // always synchronous
777
+ if (!fastpass)
778
+ fastpass = generateFastpass(def.shape);
779
+ payload = fastpass(payload, ctx);
780
+ }
781
+ else {
782
+ payload.value = {};
783
+ const shape = value.shape;
784
+ for (const key of value.keys) {
785
+ const el = shape[key];
786
+ // do not add omitted optional keys
787
+ // if (!(key in input)) {
788
+ // if (optionalKeys.has(key)) continue;
789
+ // payload.issues.push({
790
+ // code: "invalid_type",
791
+ // path: [key],
792
+ // expected: "nonoptional",
793
+ // note: `Missing required key: "${key}"`,
794
+ // input,
795
+ // inst,
796
+ // });
797
+ // }
798
+ const r = el._zod.run({ value: input[key], issues: [] }, ctx);
799
+ const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
800
+ if (r instanceof Promise) {
801
+ proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key)));
802
+ }
803
+ else if (isOptional) {
804
+ handleOptionalObjectResult(r, payload, key, input);
805
+ }
806
+ else {
807
+ handleObjectResult(r, payload, key);
808
+ }
809
+ }
810
+ }
811
+ if (!catchall) {
812
+ // return payload;
813
+ return proms.length ? Promise.all(proms).then(() => payload) : payload;
814
+ }
815
+ const unrecognized = [];
816
+ // iterate over input keys
817
+ const keySet = value.keySet;
818
+ const _catchall = catchall._zod;
819
+ const t = _catchall.def.type;
820
+ for (const key of Object.keys(input)) {
821
+ if (keySet.has(key))
822
+ continue;
823
+ if (t === "never") {
824
+ unrecognized.push(key);
825
+ continue;
826
+ }
827
+ const r = _catchall.run({ value: input[key], issues: [] }, ctx);
828
+ if (r instanceof Promise) {
829
+ proms.push(r.then((r) => handleObjectResult(r, payload, key)));
830
+ }
831
+ else {
832
+ handleObjectResult(r, payload, key);
833
+ }
834
+ }
835
+ if (unrecognized.length) {
836
+ payload.issues.push({
837
+ code: "unrecognized_keys",
838
+ keys: unrecognized,
839
+ input,
840
+ inst,
841
+ });
842
+ }
843
+ if (!proms.length)
844
+ return payload;
845
+ return Promise.all(proms).then(() => {
846
+ return payload;
847
+ });
848
+ };
849
+ });
850
+ const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => {
851
+ $ZodType.init(inst, def);
852
+ inst._zod.values = new Set(def.values);
853
+ inst._zod.pattern = new RegExp(`^(${def.values
854
+ .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)))
855
+ .join("|")})$`);
856
+ inst._zod.parse = (payload, _ctx) => {
857
+ const input = payload.value;
858
+ if (inst._zod.values.has(input)) {
859
+ return payload;
860
+ }
861
+ payload.issues.push({
862
+ code: "invalid_value",
863
+ values: def.values,
864
+ input,
865
+ inst,
866
+ });
867
+ return payload;
868
+ };
869
+ });
870
+ const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
871
+ $ZodType.init(inst, def);
872
+ inst._zod.optin = "optional";
873
+ inst._zod.optout = "optional";
874
+ defineLazy(inst._zod, "values", () => {
875
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
876
+ });
877
+ defineLazy(inst._zod, "pattern", () => {
878
+ const pattern = def.innerType._zod.pattern;
879
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
880
+ });
881
+ inst._zod.parse = (payload, ctx) => {
882
+ if (def.innerType._zod.optin === "optional") {
883
+ return def.innerType._zod.run(payload, ctx);
884
+ }
885
+ if (payload.value === undefined) {
886
+ return payload;
887
+ }
888
+ return def.innerType._zod.run(payload, ctx);
889
+ };
890
+ });
891
+
892
+ function _string(Class, params) {
893
+ return new Class({
894
+ type: "string",
895
+ ...normalizeParams(),
896
+ });
897
+ }
898
+ function _number(Class, params) {
899
+ return new Class({
900
+ type: "number",
901
+ checks: [],
902
+ ...normalizeParams(),
903
+ });
904
+ }
905
+ function _unknown(Class) {
906
+ return new Class({
907
+ type: "unknown",
908
+ });
909
+ }
910
+
911
+ const ZodMiniType = /*@__PURE__*/ $constructor("ZodMiniType", (inst, def) => {
912
+ if (!inst._zod)
913
+ throw new Error("Uninitialized schema in ZodMiniType.");
914
+ $ZodType.init(inst, def);
915
+ inst.def = def;
916
+ inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
917
+ inst.safeParse = (data, params) => safeParse(inst, data, params);
918
+ inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
919
+ inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
920
+ inst.check = (...checks) => {
921
+ return inst.clone({
922
+ ...def,
923
+ checks: [
924
+ ...(def.checks ?? []),
925
+ ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
926
+ ],
927
+ }
928
+ // { parent: true }
929
+ );
930
+ };
931
+ inst.clone = (_def, params) => clone(inst, _def, params);
932
+ inst.brand = () => inst;
933
+ inst.register = ((reg, meta) => {
934
+ reg.add(inst, meta);
935
+ return inst;
936
+ });
937
+ });
938
+ const ZodMiniString = /*@__PURE__*/ $constructor("ZodMiniString", (inst, def) => {
939
+ $ZodString.init(inst, def);
940
+ ZodMiniType.init(inst, def);
941
+ });
942
+ function string(params) {
943
+ return _string(ZodMiniString);
944
+ }
945
+ const ZodMiniNumber = /*@__PURE__*/ $constructor("ZodMiniNumber", (inst, def) => {
946
+ $ZodNumber.init(inst, def);
947
+ ZodMiniType.init(inst, def);
948
+ });
949
+ function number(params) {
950
+ return _number(ZodMiniNumber);
951
+ }
952
+ const ZodMiniUnknown = /*@__PURE__*/ $constructor("ZodMiniUnknown", (inst, def) => {
953
+ $ZodUnknown.init(inst, def);
954
+ ZodMiniType.init(inst, def);
955
+ });
956
+ function unknown() {
957
+ return _unknown(ZodMiniUnknown);
958
+ }
959
+ const ZodMiniObject = /*@__PURE__*/ $constructor("ZodMiniObject", (inst, def) => {
960
+ $ZodObject.init(inst, def);
961
+ ZodMiniType.init(inst, def);
962
+ defineLazy(inst, "shape", () => def.shape);
963
+ });
964
+ function object(shape, params) {
965
+ const def = {
966
+ type: "object",
967
+ get shape() {
968
+ assignProp(this, "shape", { ...shape });
969
+ return this.shape;
970
+ },
971
+ ...normalizeParams(),
972
+ };
973
+ return new ZodMiniObject(def);
974
+ }
975
+ const ZodMiniLiteral = /*@__PURE__*/ $constructor("ZodMiniLiteral", (inst, def) => {
976
+ $ZodLiteral.init(inst, def);
977
+ ZodMiniType.init(inst, def);
978
+ });
979
+ function literal(value, params) {
980
+ return new ZodMiniLiteral({
981
+ type: "literal",
982
+ values: Array.isArray(value) ? value : [value],
983
+ ...normalizeParams(),
984
+ });
985
+ }
986
+ const ZodMiniOptional = /*@__PURE__*/ $constructor("ZodMiniOptional", (inst, def) => {
987
+ $ZodOptional.init(inst, def);
988
+ ZodMiniType.init(inst, def);
989
+ });
990
+ function optional(innerType) {
991
+ return new ZodMiniOptional({
992
+ type: "optional",
993
+ innerType: innerType,
994
+ });
995
+ }
996
+
997
+ // src/schemas.mini.ts
998
+ var JsonRpcRequestSchema = () => object({
999
+ jsonrpc: literal("2.0"),
1000
+ id: string(),
1001
+ method: string(),
1002
+ params: optional(unknown())
1003
+ });
1004
+ var JsonRpcErrorSchema = () => object({
1005
+ code: number(),
1006
+ message: string(),
1007
+ data: optional(unknown())
1008
+ });
1009
+ var JsonRpcResponseSchema = () => object({
1010
+ jsonrpc: literal("2.0"),
1011
+ id: string(),
1012
+ result: optional(unknown()),
1013
+ error: optional(JsonRpcErrorSchema())
1014
+ });
1015
+
1016
+ // src/methods.ts
1017
+ var PATH_TO_METHOD_MAP = {
1018
+ "/EXPERIMENTAL_changes": "EXPERIMENTAL_changes",
1019
+ "/EXPERIMENTAL_changes_in_block": "EXPERIMENTAL_changes_in_block",
1020
+ "/EXPERIMENTAL_congestion_level": "EXPERIMENTAL_congestion_level",
1021
+ "/EXPERIMENTAL_genesis_config": "EXPERIMENTAL_genesis_config",
1022
+ "/EXPERIMENTAL_light_client_block_proof": "EXPERIMENTAL_light_client_block_proof",
1023
+ "/EXPERIMENTAL_light_client_proof": "EXPERIMENTAL_light_client_proof",
1024
+ "/EXPERIMENTAL_maintenance_windows": "EXPERIMENTAL_maintenance_windows",
1025
+ "/EXPERIMENTAL_protocol_config": "EXPERIMENTAL_protocol_config",
1026
+ "/EXPERIMENTAL_receipt": "EXPERIMENTAL_receipt",
1027
+ "/EXPERIMENTAL_split_storage_info": "EXPERIMENTAL_split_storage_info",
1028
+ "/EXPERIMENTAL_tx_status": "EXPERIMENTAL_tx_status",
1029
+ "/EXPERIMENTAL_validators_ordered": "EXPERIMENTAL_validators_ordered",
1030
+ "/block": "block",
1031
+ "/broadcast_tx_async": "broadcast_tx_async",
1032
+ "/broadcast_tx_commit": "broadcast_tx_commit",
1033
+ "/changes": "changes",
1034
+ "/chunk": "chunk",
1035
+ "/client_config": "client_config",
1036
+ "/gas_price": "gas_price",
1037
+ "/health": "health",
1038
+ "/light_client_proof": "light_client_proof",
1039
+ "/network_info": "network_info",
1040
+ "/next_light_client_block": "next_light_client_block",
1041
+ "/query": "query",
1042
+ "/send_tx": "send_tx",
1043
+ "/status": "status",
1044
+ "/tx": "tx",
1045
+ "/validators": "validators"
1046
+ };
1047
+ Object.entries(PATH_TO_METHOD_MAP).forEach(([path, method]) => {
1048
+ });
1049
+ var RPC_METHODS = Object.values(PATH_TO_METHOD_MAP);
1050
+
1051
+ // Auto-generated static RPC functions for tree-shaking
1052
+ // Generated at: 2025-07-25T05:44:53.307Z
1053
+ // Total functions: 28
1054
+ //
1055
+ // This file is automatically generated by tools/codegen/generate-client-interface.ts
1056
+ // Do not edit manually - changes will be overwritten
1057
+ // EXPERIMENTAL_changes static function
1058
+ async function experimentalChanges(client, params) {
1059
+ return client.makeRequest('EXPERIMENTAL_changes', params);
1060
+ }
1061
+ // EXPERIMENTAL_changes_in_block static function
1062
+ async function experimentalChangesInBlock(client, params) {
1063
+ return client.makeRequest('EXPERIMENTAL_changes_in_block', params);
1064
+ }
1065
+ // EXPERIMENTAL_congestion_level static function
1066
+ async function experimentalCongestionLevel(client, params) {
1067
+ return client.makeRequest('EXPERIMENTAL_congestion_level', params);
1068
+ }
1069
+ // EXPERIMENTAL_genesis_config static function
1070
+ async function experimentalGenesisConfig(client, params) {
1071
+ return client.makeRequest('EXPERIMENTAL_genesis_config', params);
1072
+ }
1073
+ // EXPERIMENTAL_light_client_block_proof static function
1074
+ async function experimentalLightClientBlockProof(client, params) {
1075
+ return client.makeRequest('EXPERIMENTAL_light_client_block_proof', params);
1076
+ }
1077
+ // EXPERIMENTAL_light_client_proof static function
1078
+ async function experimentalLightClientProof(client, params) {
1079
+ return client.makeRequest('EXPERIMENTAL_light_client_proof', params);
1080
+ }
1081
+ // EXPERIMENTAL_maintenance_windows static function
1082
+ async function experimentalMaintenanceWindows(client, params) {
1083
+ return client.makeRequest('EXPERIMENTAL_maintenance_windows', params);
1084
+ }
1085
+ // EXPERIMENTAL_protocol_config static function
1086
+ async function experimentalProtocolConfig(client, params) {
1087
+ return client.makeRequest('EXPERIMENTAL_protocol_config', params);
1088
+ }
1089
+ // EXPERIMENTAL_receipt static function
1090
+ async function experimentalReceipt(client, params) {
1091
+ return client.makeRequest('EXPERIMENTAL_receipt', params);
1092
+ }
1093
+ // EXPERIMENTAL_split_storage_info static function
1094
+ async function experimentalSplitStorageInfo(client, params) {
1095
+ return client.makeRequest('EXPERIMENTAL_split_storage_info', params);
1096
+ }
1097
+ // EXPERIMENTAL_tx_status static function
1098
+ async function experimentalTxStatus(client, params) {
1099
+ return client.makeRequest('EXPERIMENTAL_tx_status', params);
1100
+ }
1101
+ // EXPERIMENTAL_validators_ordered static function
1102
+ async function experimentalValidatorsOrdered(client, params) {
1103
+ return client.makeRequest('EXPERIMENTAL_validators_ordered', params);
1104
+ }
1105
+ // block static function
1106
+ async function block(client, params) {
1107
+ return client.makeRequest('block', params);
1108
+ }
1109
+ // broadcast_tx_async static function
1110
+ async function broadcastTxAsync(client, params) {
1111
+ return client.makeRequest('broadcast_tx_async', params);
1112
+ }
1113
+ // broadcast_tx_commit static function
1114
+ async function broadcastTxCommit(client, params) {
1115
+ return client.makeRequest('broadcast_tx_commit', params);
1116
+ }
1117
+ // changes static function
1118
+ async function changes(client, params) {
1119
+ return client.makeRequest('changes', params);
1120
+ }
1121
+ // chunk static function
1122
+ async function chunk(client, params) {
1123
+ return client.makeRequest('chunk', params);
1124
+ }
1125
+ // client_config static function
1126
+ async function clientConfig(client, params) {
1127
+ return client.makeRequest('client_config', params);
1128
+ }
1129
+ // gas_price static function
1130
+ async function gasPrice(client, params) {
1131
+ return client.makeRequest('gas_price', params);
1132
+ }
1133
+ // health static function
1134
+ async function health(client, params) {
1135
+ return client.makeRequest('health', params);
1136
+ }
1137
+ // light_client_proof static function
1138
+ async function lightClientProof(client, params) {
1139
+ return client.makeRequest('light_client_proof', params);
1140
+ }
1141
+ // network_info static function
1142
+ async function networkInfo(client, params) {
1143
+ return client.makeRequest('network_info', params);
1144
+ }
1145
+ // next_light_client_block static function
1146
+ async function nextLightClientBlock(client, params) {
1147
+ return client.makeRequest('next_light_client_block', params);
1148
+ }
1149
+ // query static function
1150
+ async function query(client, params) {
1151
+ return client.makeRequest('query', params);
1152
+ }
1153
+ // send_tx static function
1154
+ async function sendTx(client, params) {
1155
+ return client.makeRequest('send_tx', params);
1156
+ }
1157
+ // status static function
1158
+ async function status(client, params) {
1159
+ return client.makeRequest('status', params);
1160
+ }
1161
+ // tx static function
1162
+ async function tx(client, params) {
1163
+ return client.makeRequest('tx', params);
1164
+ }
1165
+ // validators static function
1166
+ async function validators(client, params) {
1167
+ return client.makeRequest('validators', params);
1168
+ }
1169
+
1170
+ async function viewAccount(client, params) {
1171
+ // Construct query parameters: use blockId if provided, otherwise use finality (default 'final')
1172
+ const queryParams = params.blockId
1173
+ ? {
1174
+ requestType: 'view_account',
1175
+ accountId: params.accountId,
1176
+ blockId: params.blockId,
1177
+ }
1178
+ : {
1179
+ requestType: 'view_account',
1180
+ accountId: params.accountId,
1181
+ finality: params.finality || 'final',
1182
+ };
1183
+ return query(client, queryParams);
1184
+ }
1185
+ async function viewFunction(client, params) {
1186
+ // Construct query parameters: use blockId if provided, otherwise use finality (default 'final')
1187
+ const baseParams = {
1188
+ requestType: 'call_function',
1189
+ accountId: params.accountId,
1190
+ methodName: params.methodName,
1191
+ argsBase64: params.argsBase64 ?? '', // Default to empty string if no arguments
1192
+ };
1193
+ const queryParams = params.blockId
1194
+ ? { ...baseParams, blockId: params.blockId }
1195
+ : { ...baseParams, finality: params.finality || 'final' };
1196
+ return query(client, queryParams);
1197
+ }
1198
+ async function viewAccessKey(client, params) {
1199
+ // Construct query parameters: use blockId if provided, otherwise use finality (default 'final')
1200
+ const queryParams = params.blockId
1201
+ ? {
1202
+ requestType: 'view_access_key',
1203
+ accountId: params.accountId,
1204
+ publicKey: params.publicKey,
1205
+ blockId: params.blockId,
1206
+ }
1207
+ : {
1208
+ requestType: 'view_access_key',
1209
+ accountId: params.accountId,
1210
+ publicKey: params.publicKey,
1211
+ finality: params.finality || 'final',
1212
+ };
1213
+ return query(client, queryParams);
1214
+ }
1215
+
1216
+ // Optional validation for mini client - only imported when explicitly enabled
1217
+ /**
1218
+ * Enable validation for the mini client
1219
+ * This function should only be called if you want to include schema validation
1220
+ * Calling this function will include Zod schemas in your bundle
1221
+ */
1222
+ function enableValidation() {
1223
+ const requestSchema = JsonRpcRequestSchema();
1224
+ const responseSchema = JsonRpcResponseSchema();
1225
+ return {
1226
+ validateRequest: (request) => {
1227
+ try {
1228
+ requestSchema.parse(request);
1229
+ }
1230
+ catch (error) {
1231
+ throw new JsonRpcNetworkError(`Invalid request format: ${error instanceof Error ? error.message : 'Unknown error'}`, error);
1232
+ }
1233
+ },
1234
+ validateResponse: (response) => {
1235
+ try {
1236
+ responseSchema.parse(response);
1237
+ }
1238
+ catch (error) {
1239
+ throw new JsonRpcClientError(`Invalid response format: ${error instanceof Error ? error.message : 'Unknown error'}`);
1240
+ }
1241
+ },
1242
+ };
1243
+ }
1244
+
1245
+ export { JsonRpcClientError, JsonRpcNetworkError, JsonRpcRequestSchema, JsonRpcResponseSchema, NearRpcClient, NearRpcError, RPC_METHODS, block, broadcastTxAsync, broadcastTxCommit, changes, chunk, clientConfig, NearRpcClient as default, defaultClient, enableValidation, experimentalChanges, experimentalChangesInBlock, experimentalCongestionLevel, experimentalGenesisConfig, experimentalLightClientBlockProof, experimentalLightClientProof, experimentalMaintenanceWindows, experimentalProtocolConfig, experimentalReceipt, experimentalSplitStorageInfo, experimentalTxStatus, experimentalValidatorsOrdered, gasPrice, health, lightClientProof, networkInfo, nextLightClientBlock, query, sendTx, status, tx, validators, viewAccessKey, viewAccount, viewFunction };