@x402scan/mcp 0.0.7-beta.2 → 0.0.7-beta.4

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,970 @@
1
+ // src/shared/neverthrow/fs/index.ts
2
+ import * as fs from "fs/promises";
3
+ import { existsSync } from "fs";
4
+
5
+ // ../../../node_modules/.pnpm/neverthrow@8.2.0/node_modules/neverthrow/dist/index.es.js
6
+ var defaultErrorConfig = {
7
+ withStackTrace: false
8
+ };
9
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
10
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
11
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
12
+ return {
13
+ data,
14
+ message,
15
+ stack: maybeStack
16
+ };
17
+ };
18
+ function __awaiter(thisArg, _arguments, P, generator) {
19
+ function adopt(value) {
20
+ return value instanceof P ? value : new P(function(resolve) {
21
+ resolve(value);
22
+ });
23
+ }
24
+ return new (P || (P = Promise))(function(resolve, reject) {
25
+ function fulfilled(value) {
26
+ try {
27
+ step(generator.next(value));
28
+ } catch (e) {
29
+ reject(e);
30
+ }
31
+ }
32
+ function rejected(value) {
33
+ try {
34
+ step(generator["throw"](value));
35
+ } catch (e) {
36
+ reject(e);
37
+ }
38
+ }
39
+ function step(result) {
40
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
41
+ }
42
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
43
+ });
44
+ }
45
+ function __values(o) {
46
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
47
+ if (m) return m.call(o);
48
+ if (o && typeof o.length === "number") return {
49
+ next: function() {
50
+ if (o && i >= o.length) o = void 0;
51
+ return { value: o && o[i++], done: !o };
52
+ }
53
+ };
54
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
55
+ }
56
+ function __await(v) {
57
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
58
+ }
59
+ function __asyncGenerator(thisArg, _arguments, generator) {
60
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
61
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
62
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
63
+ return this;
64
+ }, i;
65
+ function awaitReturn(f) {
66
+ return function(v) {
67
+ return Promise.resolve(v).then(f, reject);
68
+ };
69
+ }
70
+ function verb(n, f) {
71
+ if (g[n]) {
72
+ i[n] = function(v) {
73
+ return new Promise(function(a, b) {
74
+ q.push([n, v, a, b]) > 1 || resume(n, v);
75
+ });
76
+ };
77
+ if (f) i[n] = f(i[n]);
78
+ }
79
+ }
80
+ function resume(n, v) {
81
+ try {
82
+ step(g[n](v));
83
+ } catch (e) {
84
+ settle(q[0][3], e);
85
+ }
86
+ }
87
+ function step(r) {
88
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
89
+ }
90
+ function fulfill(value) {
91
+ resume("next", value);
92
+ }
93
+ function reject(value) {
94
+ resume("throw", value);
95
+ }
96
+ function settle(f, v) {
97
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
98
+ }
99
+ }
100
+ function __asyncDelegator(o) {
101
+ var i, p;
102
+ return i = {}, verb("next"), verb("throw", function(e) {
103
+ throw e;
104
+ }), verb("return"), i[Symbol.iterator] = function() {
105
+ return this;
106
+ }, i;
107
+ function verb(n, f) {
108
+ i[n] = o[n] ? function(v) {
109
+ return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
110
+ } : f;
111
+ }
112
+ }
113
+ function __asyncValues(o) {
114
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
115
+ var m = o[Symbol.asyncIterator], i;
116
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
117
+ return this;
118
+ }, i);
119
+ function verb(n) {
120
+ i[n] = o[n] && function(v) {
121
+ return new Promise(function(resolve, reject) {
122
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
123
+ });
124
+ };
125
+ }
126
+ function settle(resolve, reject, d, v) {
127
+ Promise.resolve(v).then(function(v2) {
128
+ resolve({ value: v2, done: d });
129
+ }, reject);
130
+ }
131
+ }
132
+ var ResultAsync = class _ResultAsync {
133
+ constructor(res) {
134
+ this._promise = res;
135
+ }
136
+ static fromSafePromise(promise) {
137
+ const newPromise = promise.then((value) => new Ok(value));
138
+ return new _ResultAsync(newPromise);
139
+ }
140
+ static fromPromise(promise, errorFn) {
141
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
142
+ return new _ResultAsync(newPromise);
143
+ }
144
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
145
+ static fromThrowable(fn, errorFn) {
146
+ return (...args) => {
147
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
148
+ try {
149
+ return new Ok(yield fn(...args));
150
+ } catch (error) {
151
+ return new Err(errorFn ? errorFn(error) : error);
152
+ }
153
+ }))());
154
+ };
155
+ }
156
+ static combine(asyncResultList) {
157
+ return combineResultAsyncList(asyncResultList);
158
+ }
159
+ static combineWithAllErrors(asyncResultList) {
160
+ return combineResultAsyncListWithAllErrors(asyncResultList);
161
+ }
162
+ map(f) {
163
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
164
+ if (res.isErr()) {
165
+ return new Err(res.error);
166
+ }
167
+ return new Ok(yield f(res.value));
168
+ })));
169
+ }
170
+ andThrough(f) {
171
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
172
+ if (res.isErr()) {
173
+ return new Err(res.error);
174
+ }
175
+ const newRes = yield f(res.value);
176
+ if (newRes.isErr()) {
177
+ return new Err(newRes.error);
178
+ }
179
+ return new Ok(res.value);
180
+ })));
181
+ }
182
+ andTee(f) {
183
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
184
+ if (res.isErr()) {
185
+ return new Err(res.error);
186
+ }
187
+ try {
188
+ yield f(res.value);
189
+ } catch (e) {
190
+ }
191
+ return new Ok(res.value);
192
+ })));
193
+ }
194
+ orTee(f) {
195
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
196
+ if (res.isOk()) {
197
+ return new Ok(res.value);
198
+ }
199
+ try {
200
+ yield f(res.error);
201
+ } catch (e) {
202
+ }
203
+ return new Err(res.error);
204
+ })));
205
+ }
206
+ mapErr(f) {
207
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
208
+ if (res.isOk()) {
209
+ return new Ok(res.value);
210
+ }
211
+ return new Err(yield f(res.error));
212
+ })));
213
+ }
214
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
215
+ andThen(f) {
216
+ return new _ResultAsync(this._promise.then((res) => {
217
+ if (res.isErr()) {
218
+ return new Err(res.error);
219
+ }
220
+ const newValue = f(res.value);
221
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
222
+ }));
223
+ }
224
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
225
+ orElse(f) {
226
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
227
+ if (res.isErr()) {
228
+ return f(res.error);
229
+ }
230
+ return new Ok(res.value);
231
+ })));
232
+ }
233
+ match(ok3, _err) {
234
+ return this._promise.then((res) => res.match(ok3, _err));
235
+ }
236
+ unwrapOr(t) {
237
+ return this._promise.then((res) => res.unwrapOr(t));
238
+ }
239
+ /**
240
+ * @deprecated will be removed in 9.0.0.
241
+ *
242
+ * You can use `safeTry` without this method.
243
+ * @example
244
+ * ```typescript
245
+ * safeTry(async function* () {
246
+ * const okValue = yield* yourResult
247
+ * })
248
+ * ```
249
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
250
+ */
251
+ safeUnwrap() {
252
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
253
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
254
+ });
255
+ }
256
+ // Makes ResultAsync implement PromiseLike<Result>
257
+ then(successCallback, failureCallback) {
258
+ return this._promise.then(successCallback, failureCallback);
259
+ }
260
+ [Symbol.asyncIterator]() {
261
+ return __asyncGenerator(this, arguments, function* _a() {
262
+ const result = yield __await(this._promise);
263
+ if (result.isErr()) {
264
+ yield yield __await(errAsync(result.error));
265
+ }
266
+ return yield __await(result.value);
267
+ });
268
+ }
269
+ };
270
+ function errAsync(err3) {
271
+ return new ResultAsync(Promise.resolve(new Err(err3)));
272
+ }
273
+ var fromPromise = ResultAsync.fromPromise;
274
+ var fromSafePromise = ResultAsync.fromSafePromise;
275
+ var fromAsyncThrowable = ResultAsync.fromThrowable;
276
+ var combineResultList = (resultList) => {
277
+ let acc = ok([]);
278
+ for (const result of resultList) {
279
+ if (result.isErr()) {
280
+ acc = err(result.error);
281
+ break;
282
+ } else {
283
+ acc.map((list) => list.push(result.value));
284
+ }
285
+ }
286
+ return acc;
287
+ };
288
+ var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
289
+ var combineResultListWithAllErrors = (resultList) => {
290
+ let acc = ok([]);
291
+ for (const result of resultList) {
292
+ if (result.isErr() && acc.isErr()) {
293
+ acc.error.push(result.error);
294
+ } else if (result.isErr() && acc.isOk()) {
295
+ acc = err([result.error]);
296
+ } else if (result.isOk() && acc.isOk()) {
297
+ acc.value.push(result.value);
298
+ }
299
+ }
300
+ return acc;
301
+ };
302
+ var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
303
+ var Result;
304
+ (function(Result2) {
305
+ function fromThrowable2(fn, errorFn) {
306
+ return (...args) => {
307
+ try {
308
+ const result = fn(...args);
309
+ return ok(result);
310
+ } catch (e) {
311
+ return err(errorFn ? errorFn(e) : e);
312
+ }
313
+ };
314
+ }
315
+ Result2.fromThrowable = fromThrowable2;
316
+ function combine(resultList) {
317
+ return combineResultList(resultList);
318
+ }
319
+ Result2.combine = combine;
320
+ function combineWithAllErrors(resultList) {
321
+ return combineResultListWithAllErrors(resultList);
322
+ }
323
+ Result2.combineWithAllErrors = combineWithAllErrors;
324
+ })(Result || (Result = {}));
325
+ function ok(value) {
326
+ return new Ok(value);
327
+ }
328
+ function err(err3) {
329
+ return new Err(err3);
330
+ }
331
+ var Ok = class {
332
+ constructor(value) {
333
+ this.value = value;
334
+ }
335
+ isOk() {
336
+ return true;
337
+ }
338
+ isErr() {
339
+ return !this.isOk();
340
+ }
341
+ map(f) {
342
+ return ok(f(this.value));
343
+ }
344
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
345
+ mapErr(_f) {
346
+ return ok(this.value);
347
+ }
348
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
349
+ andThen(f) {
350
+ return f(this.value);
351
+ }
352
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
353
+ andThrough(f) {
354
+ return f(this.value).map((_value) => this.value);
355
+ }
356
+ andTee(f) {
357
+ try {
358
+ f(this.value);
359
+ } catch (e) {
360
+ }
361
+ return ok(this.value);
362
+ }
363
+ orTee(_f) {
364
+ return ok(this.value);
365
+ }
366
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
367
+ orElse(_f) {
368
+ return ok(this.value);
369
+ }
370
+ asyncAndThen(f) {
371
+ return f(this.value);
372
+ }
373
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
374
+ asyncAndThrough(f) {
375
+ return f(this.value).map(() => this.value);
376
+ }
377
+ asyncMap(f) {
378
+ return ResultAsync.fromSafePromise(f(this.value));
379
+ }
380
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
381
+ unwrapOr(_v) {
382
+ return this.value;
383
+ }
384
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
385
+ match(ok3, _err) {
386
+ return ok3(this.value);
387
+ }
388
+ safeUnwrap() {
389
+ const value = this.value;
390
+ return (function* () {
391
+ return value;
392
+ })();
393
+ }
394
+ _unsafeUnwrap(_) {
395
+ return this.value;
396
+ }
397
+ _unsafeUnwrapErr(config) {
398
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
399
+ }
400
+ // eslint-disable-next-line @typescript-eslint/no-this-alias, require-yield
401
+ *[Symbol.iterator]() {
402
+ return this.value;
403
+ }
404
+ };
405
+ var Err = class {
406
+ constructor(error) {
407
+ this.error = error;
408
+ }
409
+ isOk() {
410
+ return false;
411
+ }
412
+ isErr() {
413
+ return !this.isOk();
414
+ }
415
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
416
+ map(_f) {
417
+ return err(this.error);
418
+ }
419
+ mapErr(f) {
420
+ return err(f(this.error));
421
+ }
422
+ andThrough(_f) {
423
+ return err(this.error);
424
+ }
425
+ andTee(_f) {
426
+ return err(this.error);
427
+ }
428
+ orTee(f) {
429
+ try {
430
+ f(this.error);
431
+ } catch (e) {
432
+ }
433
+ return err(this.error);
434
+ }
435
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
436
+ andThen(_f) {
437
+ return err(this.error);
438
+ }
439
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
440
+ orElse(f) {
441
+ return f(this.error);
442
+ }
443
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
444
+ asyncAndThen(_f) {
445
+ return errAsync(this.error);
446
+ }
447
+ asyncAndThrough(_f) {
448
+ return errAsync(this.error);
449
+ }
450
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
451
+ asyncMap(_f) {
452
+ return errAsync(this.error);
453
+ }
454
+ unwrapOr(v) {
455
+ return v;
456
+ }
457
+ match(_ok, err3) {
458
+ return err3(this.error);
459
+ }
460
+ safeUnwrap() {
461
+ const error = this.error;
462
+ return (function* () {
463
+ yield err(error);
464
+ throw new Error("Do not use this generator out of `safeTry`");
465
+ })();
466
+ }
467
+ _unsafeUnwrap(config) {
468
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
469
+ }
470
+ _unsafeUnwrapErr(_) {
471
+ return this.error;
472
+ }
473
+ *[Symbol.iterator]() {
474
+ const self = this;
475
+ yield self;
476
+ return self;
477
+ }
478
+ };
479
+ var fromThrowable = Result.fromThrowable;
480
+
481
+ // ../../internal/neverthrow/dist/index.js
482
+ function resultFromPromise(type3, surface, promise, error) {
483
+ return ResultAsync.fromPromise(promise, (e) => ({
484
+ ...error(e),
485
+ type: type3,
486
+ surface
487
+ }));
488
+ }
489
+ function resultFromThrowable(type3, surface, fn, error) {
490
+ return Result.fromThrowable(fn, (e) => ({
491
+ ...error(e),
492
+ type: type3,
493
+ surface
494
+ }))();
495
+ }
496
+ function ok2(data) {
497
+ return ok(data);
498
+ }
499
+ function err2(type3, surface, error) {
500
+ return err({
501
+ ...error,
502
+ type: type3,
503
+ surface
504
+ });
505
+ }
506
+
507
+ // src/shared/neverthrow/fs/index.ts
508
+ var errorType = "fs";
509
+ var fsErr = (surface, error) => err2(errorType, surface, error);
510
+ var fsResultFromPromise = (surface, promise, error) => resultFromPromise(errorType, surface, promise, error);
511
+ var safeReadFile = (surface, path) => fsResultFromPromise(surface, fs.readFile(path, "utf-8"), () => ({
512
+ cause: "file_not_readable",
513
+ message: "Failed to read file"
514
+ }));
515
+ var safeWriteFile = (surface, path, data) => fsResultFromPromise(surface, fs.writeFile(path, data), () => ({
516
+ cause: "file_not_writable",
517
+ message: "Failed to write file"
518
+ }));
519
+ var safeAppendFile = (surface, path, data) => fsResultFromPromise(surface, fs.appendFile(path, data), () => ({
520
+ cause: "file_not_writable",
521
+ message: "Failed to append file"
522
+ }));
523
+ var safeChmod = (surface, path, mode) => fsResultFromPromise(surface, fs.chmod(path, mode), () => ({
524
+ cause: "file_not_chmodable",
525
+ message: "Failed to chmod file"
526
+ }));
527
+ var safeFileExists = (surface, path) => {
528
+ const fileExists = existsSync(path);
529
+ if (fileExists) {
530
+ return ok2(true);
531
+ }
532
+ return err2(errorType, surface, {
533
+ cause: "file_not_found",
534
+ message: "File not found"
535
+ });
536
+ };
537
+
538
+ // src/shared/fs.ts
539
+ import { join } from "path";
540
+ import { homedir } from "os";
541
+ import * as fs2 from "fs";
542
+ var BASE_DIRECTORY = join(homedir(), ".x402scan-mcp");
543
+ if (!fs2.existsSync(BASE_DIRECTORY)) {
544
+ fs2.mkdirSync(BASE_DIRECTORY, { recursive: true });
545
+ }
546
+ var configFile = (name, defaultValue) => {
547
+ if (!fs2.existsSync(BASE_DIRECTORY)) {
548
+ fs2.mkdirSync(BASE_DIRECTORY, { recursive: true });
549
+ }
550
+ const filePath = join(BASE_DIRECTORY, name);
551
+ if (!fs2.existsSync(filePath)) {
552
+ fs2.writeFileSync(filePath, defaultValue);
553
+ }
554
+ return filePath;
555
+ };
556
+
557
+ // src/shared/log.ts
558
+ var LOG_FILE = configFile("mcp.log", "");
559
+ var DEBUG = process.env.X402_DEBUG === "true";
560
+ function format(args) {
561
+ return args.map(
562
+ (a) => typeof a === "object" && a !== null ? JSON.stringify(a) : String(a)
563
+ ).join(" ");
564
+ }
565
+ function write(level, msg, args) {
566
+ const formatted = args.length ? `${msg} ${format(args)}` : msg;
567
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] [${level}] ${formatted}
568
+ `;
569
+ safeAppendFile("log", LOG_FILE, line);
570
+ if (process.env.X402_DEBUG === "true") {
571
+ console.error(`[x402scan] ${formatted}`);
572
+ }
573
+ }
574
+ var log = {
575
+ info: (msg, ...args) => write("INFO", msg, args),
576
+ error: (msg, ...args) => write("ERROR", msg, args),
577
+ debug: (msg, ...args) => DEBUG && write("DEBUG", msg, args),
578
+ path: LOG_FILE
579
+ };
580
+
581
+ // src/shared/neverthrow/fetch/index.ts
582
+ var errorType2 = "fetch";
583
+ var fetchErr = (surface, error) => err2(errorType2, surface, error);
584
+ var fetchHttpErr = (surface, response) => fetchErr(surface, {
585
+ cause: "http",
586
+ statusCode: response.status,
587
+ message: response.statusText,
588
+ response
589
+ });
590
+ var safeFetch = (surface, request) => {
591
+ return resultFromPromise(
592
+ errorType2,
593
+ surface,
594
+ fetch(request),
595
+ (error) => ({
596
+ cause: "network",
597
+ message: error instanceof Error ? error.message : "Network error"
598
+ })
599
+ );
600
+ };
601
+ var safeFetchJson = (surface, request) => {
602
+ return safeFetch(surface, request).andThen((response) => {
603
+ if (!response.ok) {
604
+ return fetchHttpErr(surface, response);
605
+ }
606
+ return resultFromPromise(
607
+ errorType2,
608
+ surface,
609
+ response.json(),
610
+ () => ({
611
+ cause: "parse",
612
+ message: "Could not parse JSON from response",
613
+ statusCode: response.status,
614
+ contentType: response.headers.get("content-type") ?? "Not specified"
615
+ })
616
+ );
617
+ });
618
+ };
619
+ var safeParseResponse = (surface, response) => {
620
+ return resultFromPromise(
621
+ errorType2,
622
+ surface,
623
+ (async () => {
624
+ const contentType = response.headers.get("content-type") ?? "";
625
+ switch (contentType) {
626
+ case "application/json":
627
+ return {
628
+ type: "json",
629
+ data: await response.json()
630
+ };
631
+ case "image/png":
632
+ case "image/jpeg":
633
+ case "image/gif":
634
+ case "image/webp":
635
+ case "image/svg+xml":
636
+ case "image/tiff":
637
+ case "image/bmp":
638
+ case "image/ico":
639
+ return {
640
+ type: "image",
641
+ mimeType: contentType,
642
+ data: await response.arrayBuffer()
643
+ };
644
+ case "audio/":
645
+ return {
646
+ type: "audio",
647
+ mimeType: contentType,
648
+ data: await response.arrayBuffer()
649
+ };
650
+ case "video/":
651
+ return {
652
+ type: "video",
653
+ mimeType: contentType,
654
+ data: await response.arrayBuffer()
655
+ };
656
+ case "application/pdf":
657
+ return {
658
+ type: "pdf",
659
+ mimeType: contentType,
660
+ data: await response.arrayBuffer()
661
+ };
662
+ case "application/octet-stream":
663
+ return {
664
+ type: "octet-stream",
665
+ mimeType: contentType,
666
+ data: await response.arrayBuffer()
667
+ };
668
+ case "multipart/form-data":
669
+ return { type: "formData", data: await response.formData() };
670
+ case "text/":
671
+ return { type: "text", data: await response.text() };
672
+ default:
673
+ throw new Error(`Unsupported content type: ${contentType}`);
674
+ }
675
+ })(),
676
+ (e) => ({
677
+ cause: "parse",
678
+ message: e instanceof Error ? e.message : "Could not parse response",
679
+ statusCode: response.status,
680
+ contentType: response.headers.get("content-type") ?? "Not specified"
681
+ })
682
+ );
683
+ };
684
+ var isFetchError = (error) => {
685
+ return error.type === errorType2;
686
+ };
687
+
688
+ // src/shared/utils.ts
689
+ import open from "open";
690
+ var getBaseUrl = (dev) => {
691
+ return dev ? "http://localhost:3000" : "https://x402scan.com";
692
+ };
693
+ var getDepositLink = (address, flags) => {
694
+ return `${getBaseUrl(flags.dev)}/mcp/deposit/${address}`;
695
+ };
696
+ var openDepositLink = async (address, flags) => {
697
+ const depositLink = getDepositLink(address, flags);
698
+ await open(depositLink);
699
+ };
700
+
701
+ // src/shared/state.ts
702
+ import z from "zod";
703
+ import fs3 from "fs";
704
+ var STATE_FILE = configFile("state.json", "{}");
705
+ var stateSchema = z.looseObject({
706
+ redeemedCodes: z.array(z.string())
707
+ }).partial();
708
+ var getState = () => {
709
+ const result = stateSchema.safeParse(
710
+ JSON.parse(fs3.readFileSync(STATE_FILE, "utf-8"))
711
+ );
712
+ if (!result.success) {
713
+ log.error("Failed to parse state", { error: result.error });
714
+ return {};
715
+ }
716
+ return result.data;
717
+ };
718
+ var setState = (state) => {
719
+ const existing = getState();
720
+ const newState = stateSchema.parse({ ...existing, ...state });
721
+ fs3.writeFileSync(STATE_FILE, JSON.stringify(newState, null, 2));
722
+ };
723
+
724
+ // src/shared/redeem-invite.ts
725
+ var redeemInviteCode = async ({
726
+ code,
727
+ dev,
728
+ address,
729
+ surface
730
+ }) => {
731
+ const state = getState();
732
+ if (state.redeemedCodes?.includes(code)) {
733
+ return err2("user", surface, {
734
+ cause: "conflict",
735
+ message: "This invite code has already been redeemed"
736
+ });
737
+ }
738
+ const result = await safeFetchJson(
739
+ surface,
740
+ new Request(`${getBaseUrl(dev)}/api/invite/redeem`, {
741
+ method: "POST",
742
+ headers: {
743
+ "Content-Type": "application/json"
744
+ },
745
+ body: JSON.stringify({
746
+ code,
747
+ recipientAddr: address
748
+ })
749
+ })
750
+ );
751
+ if (result.isOk()) {
752
+ setState({
753
+ redeemedCodes: [...state.redeemedCodes ?? [], code]
754
+ });
755
+ }
756
+ return result;
757
+ };
758
+
759
+ // src/shared/wallet.ts
760
+ import { getAddress } from "viem";
761
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
762
+ import z3 from "zod";
763
+
764
+ // src/shared/neverthrow/json/index.ts
765
+ var type = "json";
766
+ var jsonErr = (surface, error) => {
767
+ return err2(type, surface, error);
768
+ };
769
+ var safeStringifyJson = (surface, value) => {
770
+ return resultFromThrowable(
771
+ type,
772
+ surface,
773
+ () => JSON.stringify(value),
774
+ () => ({
775
+ cause: "stringify",
776
+ message: "Could not stringify JSON"
777
+ })
778
+ );
779
+ };
780
+ var safeParseJson = (surface, value) => {
781
+ return resultFromThrowable(
782
+ type,
783
+ surface,
784
+ () => JSON.parse(value),
785
+ (e) => ({
786
+ cause: "parse",
787
+ message: e instanceof Error ? e.message : "Could not parse JSON"
788
+ })
789
+ );
790
+ };
791
+
792
+ // src/shared/neverthrow/parse/index.ts
793
+ import z2 from "zod";
794
+ var type2 = "json";
795
+ var parseErr = (surface, error) => err2(type2, surface, error);
796
+ var safeParse = (surface, schema, value) => {
797
+ const parseResult = schema.safeParse(value);
798
+ if (!parseResult.success) {
799
+ return parseErr(surface, {
800
+ cause: "invalid_data",
801
+ message: JSON.stringify(z2.treeifyError(parseResult.error), null, 2),
802
+ error: parseResult.error
803
+ });
804
+ }
805
+ return ok2(parseResult.data);
806
+ };
807
+
808
+ // src/shared/wallet.ts
809
+ var WALLET_FILE = configFile("wallet.json", "");
810
+ var storedWalletSchema = z3.object({
811
+ privateKey: z3.string().regex(/^0x[a-fA-F0-9]{64}$/, "Invalid Ethereum private key").transform((privateKey) => privateKey),
812
+ address: z3.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid Ethereum address").transform((address) => getAddress(address)),
813
+ createdAt: z3.string()
814
+ });
815
+ var walletSurface = "wallet";
816
+ async function getWallet() {
817
+ if (process.env.X402_PRIVATE_KEY) {
818
+ const account2 = privateKeyToAccount(process.env.X402_PRIVATE_KEY);
819
+ log.info(`Using wallet from env: ${account2.address}`);
820
+ return ok2({ account: account2, isNew: false });
821
+ }
822
+ const readFileResult = await safeReadFile(walletSurface, WALLET_FILE);
823
+ if (!readFileResult.isOk()) {
824
+ const fileExistsResult = safeFileExists(walletSurface, WALLET_FILE);
825
+ if (fileExistsResult.isOk()) {
826
+ return fsErr(walletSurface, {
827
+ cause: "file_not_readable",
828
+ message: `The file exists but is not readable. Fix corrupted state file: ${WALLET_FILE}`
829
+ });
830
+ }
831
+ }
832
+ if (readFileResult.isOk()) {
833
+ const data = readFileResult.value;
834
+ const jsonParseResult = safeParseJson(walletSurface, data);
835
+ if (jsonParseResult.isErr()) {
836
+ return jsonErr(walletSurface, {
837
+ cause: "parse",
838
+ message: `The data in ${WALLET_FILE} is not valid JSON`
839
+ });
840
+ }
841
+ const parseResult = safeParse(
842
+ walletSurface,
843
+ storedWalletSchema,
844
+ jsonParseResult.value
845
+ );
846
+ if (parseResult.isErr()) {
847
+ return parseResult;
848
+ }
849
+ const account2 = privateKeyToAccount(parseResult.value.privateKey);
850
+ log.info(`Loaded wallet: ${account2.address}`);
851
+ return ok2({ account: account2, isNew: false });
852
+ }
853
+ const privateKey = generatePrivateKey();
854
+ const account = privateKeyToAccount(privateKey);
855
+ const stored = {
856
+ privateKey,
857
+ address: account.address,
858
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
859
+ };
860
+ const saveResult = await safeWriteFile(
861
+ walletSurface,
862
+ WALLET_FILE,
863
+ JSON.stringify(stored, null, 2)
864
+ ).andThen(() => safeChmod(walletSurface, WALLET_FILE, 384));
865
+ if (saveResult.isErr()) {
866
+ return saveResult;
867
+ }
868
+ log.info(`Created wallet: ${account.address}`);
869
+ log.info(`Saved to: ${WALLET_FILE}`);
870
+ return ok2({ account, isNew: true });
871
+ }
872
+
873
+ // src/shared/networks.ts
874
+ import {
875
+ base,
876
+ baseSepolia,
877
+ mainnet,
878
+ sepolia,
879
+ optimism,
880
+ arbitrum,
881
+ polygon
882
+ } from "viem/chains";
883
+ var CHAIN_CONFIGS = {
884
+ "eip155:8453": {
885
+ chain: base,
886
+ caip2: "eip155:8453",
887
+ v1Name: "base",
888
+ usdcAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
889
+ },
890
+ "eip155:84532": {
891
+ chain: baseSepolia,
892
+ caip2: "eip155:84532",
893
+ v1Name: "base-sepolia",
894
+ usdcAddress: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
895
+ },
896
+ "eip155:1": {
897
+ chain: mainnet,
898
+ caip2: "eip155:1",
899
+ v1Name: "ethereum",
900
+ usdcAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
901
+ },
902
+ "eip155:11155111": {
903
+ chain: sepolia,
904
+ caip2: "eip155:11155111",
905
+ v1Name: "ethereum-sepolia",
906
+ usdcAddress: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
907
+ },
908
+ "eip155:10": {
909
+ chain: optimism,
910
+ caip2: "eip155:10",
911
+ v1Name: "optimism",
912
+ usdcAddress: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"
913
+ },
914
+ "eip155:42161": {
915
+ chain: arbitrum,
916
+ caip2: "eip155:42161",
917
+ v1Name: "arbitrum",
918
+ usdcAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"
919
+ },
920
+ "eip155:137": {
921
+ chain: polygon,
922
+ caip2: "eip155:137",
923
+ v1Name: "polygon",
924
+ usdcAddress: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"
925
+ }
926
+ };
927
+ var V1_TO_CAIP2 = {
928
+ base: "eip155:8453",
929
+ "base-sepolia": "eip155:84532",
930
+ ethereum: "eip155:1",
931
+ "ethereum-sepolia": "eip155:11155111",
932
+ optimism: "eip155:10",
933
+ arbitrum: "eip155:42161",
934
+ polygon: "eip155:137"
935
+ };
936
+ var DEFAULT_NETWORK = "eip155:8453";
937
+ function toCaip2(network) {
938
+ if (network.startsWith("eip155:")) return network;
939
+ return V1_TO_CAIP2[network.toLowerCase()] ?? network;
940
+ }
941
+ function getChainConfig(network) {
942
+ return CHAIN_CONFIGS[toCaip2(network)];
943
+ }
944
+ function getChainName(network) {
945
+ return getChainConfig(network)?.chain.name ?? network;
946
+ }
947
+
948
+ export {
949
+ resultFromPromise,
950
+ resultFromThrowable,
951
+ ok2 as ok,
952
+ err2 as err,
953
+ fetchHttpErr,
954
+ safeFetch,
955
+ safeFetchJson,
956
+ safeParseResponse,
957
+ isFetchError,
958
+ safeStringifyJson,
959
+ getBaseUrl,
960
+ getDepositLink,
961
+ openDepositLink,
962
+ safeReadFile,
963
+ safeWriteFile,
964
+ log,
965
+ DEFAULT_NETWORK,
966
+ getChainName,
967
+ redeemInviteCode,
968
+ getWallet
969
+ };
970
+ //# sourceMappingURL=chunk-JXXC6FYE.js.map