tenjin-cli 0.1.0-alpha.3 → 0.1.0-alpha.30
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/NOTICE.md +54 -7
- package/README.md +149 -264
- package/dist/{_esm-FEASBWRP.js → _esm-CE7KNONL.js} +9 -10
- package/dist/alive-3J3CHOQP.js +21 -0
- package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
- package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
- package/dist/chunk-2SNUOHAT.js +75 -0
- package/dist/chunk-2SNUOHAT.js.map +1 -0
- package/dist/chunk-3O2BQIF6.js +2227 -0
- package/dist/chunk-3O2BQIF6.js.map +1 -0
- package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
- package/dist/chunk-5LJCEMFD.js +12700 -0
- package/dist/chunk-5LJCEMFD.js.map +1 -0
- package/dist/chunk-6W5GYG3W.js +128 -0
- package/dist/chunk-6W5GYG3W.js.map +1 -0
- package/dist/chunk-7EKYXMUO.js +7536 -0
- package/dist/chunk-7EKYXMUO.js.map +1 -0
- package/dist/chunk-7QKHZQKW.js +1680 -0
- package/dist/chunk-7QKHZQKW.js.map +1 -0
- package/dist/chunk-A36LQPHV.js +29 -0
- package/dist/chunk-A36LQPHV.js.map +1 -0
- package/dist/chunk-AEG2PXBP.js +192 -0
- package/dist/chunk-AEG2PXBP.js.map +1 -0
- package/dist/chunk-AKWGE6JQ.js +49 -0
- package/dist/chunk-AKWGE6JQ.js.map +1 -0
- package/dist/chunk-AWFUPKTM.js +238 -0
- package/dist/chunk-AWFUPKTM.js.map +1 -0
- package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
- package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
- package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
- package/dist/chunk-EBVIKMCH.js +108 -0
- package/dist/chunk-EBVIKMCH.js.map +1 -0
- package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
- package/dist/{chunk-S3IGX57D.js → chunk-EL56RW2J.js} +166 -7237
- package/dist/chunk-EL56RW2J.js.map +1 -0
- package/dist/chunk-HE2MS4QO.js +256 -0
- package/dist/chunk-HE2MS4QO.js.map +1 -0
- package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
- package/dist/chunk-IOODYAXL.js +324 -0
- package/dist/chunk-IOODYAXL.js.map +1 -0
- package/dist/chunk-JMM6YE7J.js +2174 -0
- package/dist/chunk-JMM6YE7J.js.map +1 -0
- package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
- package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
- package/dist/chunk-KHE6L6TD.js +416 -0
- package/dist/chunk-KHE6L6TD.js.map +1 -0
- package/dist/chunk-KOGZDMHO.js +21 -0
- package/dist/chunk-KOGZDMHO.js.map +1 -0
- package/dist/chunk-KYFZTGMC.js +237 -0
- package/dist/chunk-KYFZTGMC.js.map +1 -0
- package/dist/chunk-LFZJM56J.js +159 -0
- package/dist/chunk-LFZJM56J.js.map +1 -0
- package/dist/chunk-LHHMV4GU.js +27 -0
- package/dist/chunk-LHHMV4GU.js.map +1 -0
- package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
- package/dist/chunk-MEFB5KHA.js.map +1 -0
- package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
- package/dist/chunk-N35E6CM2.js.map +1 -0
- package/dist/chunk-NZIP4PA2.js +114 -0
- package/dist/chunk-NZIP4PA2.js.map +1 -0
- package/dist/chunk-O2FRQ2L2.js +168 -0
- package/dist/chunk-O2FRQ2L2.js.map +1 -0
- package/dist/chunk-OK2TDZQU.js +404 -0
- package/dist/chunk-OK2TDZQU.js.map +1 -0
- package/dist/chunk-ORWL5BSN.js +269 -0
- package/dist/chunk-ORWL5BSN.js.map +1 -0
- package/dist/{chunk-Z6MFJV5Z.js → chunk-OSYTBCUC.js} +850 -499
- package/dist/chunk-OSYTBCUC.js.map +1 -0
- package/dist/chunk-P7LABKCW.js +90 -0
- package/dist/chunk-P7LABKCW.js.map +1 -0
- package/dist/chunk-PAYV4XUA.js +151 -0
- package/dist/chunk-PAYV4XUA.js.map +1 -0
- package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
- package/dist/chunk-QUVVWYJW.js +112 -0
- package/dist/chunk-QUVVWYJW.js.map +1 -0
- package/dist/chunk-RAULEAZ6.js +228 -0
- package/dist/chunk-RAULEAZ6.js.map +1 -0
- package/dist/chunk-S4SAZ7OD.js +30 -0
- package/dist/chunk-S4SAZ7OD.js.map +1 -0
- package/dist/chunk-SJLTEINJ.js +117 -0
- package/dist/chunk-SJLTEINJ.js.map +1 -0
- package/dist/chunk-SPAVAYSW.js +125 -0
- package/dist/chunk-SPAVAYSW.js.map +1 -0
- package/dist/chunk-TTBKWWTV.js +1605 -0
- package/dist/chunk-TTBKWWTV.js.map +1 -0
- package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
- package/dist/chunk-U6YQ6FRI.js +378 -0
- package/dist/chunk-U6YQ6FRI.js.map +1 -0
- package/dist/chunk-VFMQTSXG.js +29 -0
- package/dist/chunk-VFMQTSXG.js.map +1 -0
- package/dist/chunk-VUFAK2LW.js +115 -0
- package/dist/chunk-VUFAK2LW.js.map +1 -0
- package/dist/chunk-VZGAONSJ.js +194 -0
- package/dist/chunk-VZGAONSJ.js.map +1 -0
- package/dist/{chunk-OYMYCW7J.js → chunk-WO5BJNIB.js} +682 -53
- package/dist/chunk-WO5BJNIB.js.map +1 -0
- package/dist/chunk-WVUSXNIE.js +39 -0
- package/dist/chunk-WVUSXNIE.js.map +1 -0
- package/dist/chunk-XKESD27X.js +10 -0
- package/dist/chunk-XKESD27X.js.map +1 -0
- package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
- package/dist/{chunk-XJIW7USF.js → chunk-YFQOA5AU.js} +118 -9
- package/dist/chunk-YFQOA5AU.js.map +1 -0
- package/dist/chunk-YHKXNYTB.js +105 -0
- package/dist/chunk-YHKXNYTB.js.map +1 -0
- package/dist/{cli-SBXI5AMS.js → cli-O5SN7ZJ4.js} +382 -214
- package/dist/cli-O5SN7ZJ4.js.map +1 -0
- package/dist/config-OJQI27LT.js +45 -0
- package/dist/dist-3LOO6M4U.js +2842 -0
- package/dist/dist-3LOO6M4U.js.map +1 -0
- package/dist/doctor-IQQJHGGM.js +590 -0
- package/dist/doctor-IQQJHGGM.js.map +1 -0
- package/dist/env-proxy-XL4P73MZ.js +15 -0
- package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
- package/dist/fund-WEV6DMTD.js +365 -0
- package/dist/fund-WEV6DMTD.js.map +1 -0
- package/dist/hook-command-D2P3ILRV.js +32 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
- package/dist/hosts/claude/tenjin/.mcp.json +12 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
- package/dist/index.js +21 -2
- package/dist/index.js.map +1 -1
- package/dist/install-TUCRF32I.js +60 -0
- package/dist/install-identity-WHPNMNMQ.js +26 -0
- package/dist/install-wallet-MA27FTQ5.js +113 -0
- package/dist/install-wallet-MA27FTQ5.js.map +1 -0
- package/dist/mcp-QML7ZMPH.js +13427 -0
- package/dist/mcp-QML7ZMPH.js.map +1 -0
- package/dist/package-LGKYOEPV.js +37 -0
- package/dist/package-LGKYOEPV.js.map +1 -0
- package/dist/paths-POPTXJO6.js +61 -0
- package/dist/paths-POPTXJO6.js.map +1 -0
- package/dist/pay-2C2UBBXJ.js +51 -0
- package/dist/pay-2C2UBBXJ.js.map +1 -0
- package/dist/payments-C44QUFXU.js +106 -0
- package/dist/payments-C44QUFXU.js.map +1 -0
- package/dist/redact-6W23GGJC.js +15 -0
- package/dist/redact-6W23GGJC.js.map +1 -0
- package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
- package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
- package/dist/send-KVJX4XIR.js +222 -0
- package/dist/send-KVJX4XIR.js.map +1 -0
- package/dist/status-S7C3WMSH.js +115 -0
- package/dist/status-S7C3WMSH.js.map +1 -0
- package/dist/status-line-YR2T5HC4.js +86 -0
- package/dist/status-line-YR2T5HC4.js.map +1 -0
- package/dist/uninstall-HY6LKIIT.js +149 -0
- package/dist/uninstall-HY6LKIIT.js.map +1 -0
- package/dist/update-OJV22LR3.js +36 -0
- package/dist/update-OJV22LR3.js.map +1 -0
- package/dist/usdc-JK4RRFFQ.js +39 -0
- package/dist/usdc-JK4RRFFQ.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
- package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
- package/dist/wallet-PD2IMZDU.js +39 -0
- package/dist/wallet-PD2IMZDU.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +980 -0
- package/docs/agent-permissions.md +180 -0
- package/docs/safety-model.md +59 -0
- package/docs/troubleshooting.md +13 -0
- package/package.json +28 -19
- package/LICENSE +0 -21
- package/dist/buy-EE6SEXP6.js +0 -1598
- package/dist/buy-EE6SEXP6.js.map +0 -1
- package/dist/candidate-ERMSYYQZ.js +0 -127
- package/dist/candidate-ERMSYYQZ.js.map +0 -1
- package/dist/chunk-3OV7E5G5.js +0 -18
- package/dist/chunk-3OV7E5G5.js.map +0 -1
- package/dist/chunk-4ONXEEQL.js +0 -152
- package/dist/chunk-4ONXEEQL.js.map +0 -1
- package/dist/chunk-662MSGZB.js +0 -286
- package/dist/chunk-662MSGZB.js.map +0 -1
- package/dist/chunk-7KUW4MJD.js +0 -59
- package/dist/chunk-7KUW4MJD.js.map +0 -1
- package/dist/chunk-AWPAWHNX.js +0 -333
- package/dist/chunk-AWPAWHNX.js.map +0 -1
- package/dist/chunk-DXTQ3CSI.js +0 -171
- package/dist/chunk-DXTQ3CSI.js.map +0 -1
- package/dist/chunk-ESPNTPQ2.js +0 -207
- package/dist/chunk-ESPNTPQ2.js.map +0 -1
- package/dist/chunk-FJPLRISB.js +0 -79
- package/dist/chunk-FJPLRISB.js.map +0 -1
- package/dist/chunk-GO75V3NZ.js +0 -160
- package/dist/chunk-GO75V3NZ.js.map +0 -1
- package/dist/chunk-JPHG2JW3.js +0 -96
- package/dist/chunk-JPHG2JW3.js.map +0 -1
- package/dist/chunk-MUBUQVC3.js +0 -67
- package/dist/chunk-MUBUQVC3.js.map +0 -1
- package/dist/chunk-NCE5NSN6.js.map +0 -1
- package/dist/chunk-OYMYCW7J.js.map +0 -1
- package/dist/chunk-RY4XKNV3.js +0 -140
- package/dist/chunk-RY4XKNV3.js.map +0 -1
- package/dist/chunk-S3IGX57D.js.map +0 -1
- package/dist/chunk-TLCMMYLY.js +0 -126
- package/dist/chunk-TLCMMYLY.js.map +0 -1
- package/dist/chunk-UO22YNY4.js +0 -69
- package/dist/chunk-UO22YNY4.js.map +0 -1
- package/dist/chunk-XHC6FCGZ.js +0 -261
- package/dist/chunk-XHC6FCGZ.js.map +0 -1
- package/dist/chunk-XJIW7USF.js.map +0 -1
- package/dist/chunk-YBMMV4Y4.js.map +0 -1
- package/dist/chunk-YN5SHIXQ.js +0 -126
- package/dist/chunk-YN5SHIXQ.js.map +0 -1
- package/dist/chunk-Z52RA3NC.js +0 -137
- package/dist/chunk-Z52RA3NC.js.map +0 -1
- package/dist/chunk-Z6MFJV5Z.js.map +0 -1
- package/dist/cli-SBXI5AMS.js.map +0 -1
- package/dist/config-VELDKLHY.js +0 -21
- package/dist/doctor-T3KWNNP2.js +0 -20
- package/dist/inspect-LMKOXE4Y.js +0 -96
- package/dist/inspect-LMKOXE4Y.js.map +0 -1
- package/dist/install-LEX3ENQ6.js +0 -387
- package/dist/install-LEX3ENQ6.js.map +0 -1
- package/dist/lookup-ZPN2Q67N.js +0 -129
- package/dist/lookup-ZPN2Q67N.js.map +0 -1
- package/dist/outcome-N7TAK6WR.js +0 -66
- package/dist/outcome-N7TAK6WR.js.map +0 -1
- package/dist/publish-BKBQQAW4.js +0 -1478
- package/dist/publish-BKBQQAW4.js.map +0 -1
- package/dist/usdc-JIAJW4SV.js +0 -22
- package/dist/wallet-CWEMYVIH.js +0 -179
- package/dist/wallet-CWEMYVIH.js.map +0 -1
- package/dist/wallet-PA54CRBL.js +0 -30
- package/skills/tenjin/SKILL.md +0 -199
- package/skills/tenjin-publish/SKILL.md +0 -111
- package/skills/tenjin-search/SKILL.md +0 -133
- /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
- /package/dist/{ccip-NQXCEK2U.js.map → alive-3J3CHOQP.js.map} +0 -0
- /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
- /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
- /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
- /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
- /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
- /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
- /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
- /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
- /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
- /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
- /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
- /package/dist/{doctor-T3KWNNP2.js.map → config-OJQI27LT.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
- /package/dist/{secp256k1-N3ZHU7LB.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
- /package/dist/{usdc-JIAJW4SV.js.map → hook-command-D2P3ILRV.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → install-TUCRF32I.js.map} +0 -0
- /package/dist/{wallet-PA54CRBL.js.map → install-identity-WHPNMNMQ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/spend-ledger.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { hasCode } from './errno';\nimport { spendLedgerPath } from './paths';\n\n/**\n * The spend ledger's READ side: its shape, the two expiries, and a read-only\n * summary. It lives outside `lib/wallet` so the router hooks can measure an\n * offer against the same session total an authorization would, without the\n * wallet entering their chunk graph (`src/router/dist-chunks.test.ts`). The\n * write side, with its lock and reservations, stays in `lib/wallet/spend.ts`.\n */\n\nexport const DEFAULT_WINDOW_MS = 86_400_000; // 24h rolling day\nexport const RESERVATION_TTL_MS = 600_000; // 10 min: a dangling reservation self-expires\n\nconst ReservationSchema = z.object({\n id: z.string(),\n amountAtomic: z.string().regex(/^\\d+$/),\n atMs: z.number(),\n /** Optional so a ledger written by an older build still parses. */\n requestKey: z.string().optional(),\n mode: z.enum(['automatic', 'manual']).optional(),\n});\nexport type Reservation = z.infer<typeof ReservationSchema>;\n\n/**\n * ONE TRANSMITTED AUTHORIZATION, by its EIP-3009 nonce: what it exposed and\n * when, so a payment the chain later proves was never charged can give back\n * exactly its own amount inside the window it was counted in.\n */\nconst ExposureSchema = z.object({\n nonce: z.string(),\n amountAtomic: z.string().regex(/^\\d+$/),\n atMs: z.number(),\n mode: z.enum(['automatic', 'manual']).optional(),\n});\nexport type Exposure = z.infer<typeof ExposureSchema>;\n\nconst LedgerSchema = z.object({\n schemaVersion: z.literal(2),\n windowStartMs: z.number(),\n /**\n * EXPOSURE: every authorization this window transmitted. A signed EIP-3009\n * authorization is a bearer instrument, so total exposure stays recorded,\n * whatever any counterparty later says it took.\n */\n committedAtomic: z.string().regex(/^\\d+$/),\n automaticCommittedAtomic: z.string().regex(/^\\d+$/).optional(),\n /**\n * SETTLED: what counterparties reported actually taking, which the router's\n * waived outcomes made a different number from the line above (2026-09-23\n * lookup contract). Optional so a ledger an older build wrote still parses;\n * absent means \"everything committed was settled\", which is what that build\n * assumed. Reporting only, never a budget input: under-counting exposure\n * because a server said \"no charge\" is exactly the hole this avoids.\n */\n settledAtomic: z.string().regex(/^\\d+$/).optional(),\n reservations: z.array(ReservationSchema),\n /** Optional so a ledger an older build wrote still parses; such a ledger\n * simply has nothing a reconcile can release. */\n exposures: z.array(ExposureSchema).optional(),\n});\nexport type Ledger = z.infer<typeof LedgerSchema>;\n\nexport function emptyLedger(nowMs: number): Ledger {\n return {\n schemaVersion: 2,\n windowStartMs: nowMs,\n committedAtomic: '0',\n automaticCommittedAtomic: '0',\n settledAtomic: '0',\n reservations: [],\n };\n}\n\n/** Automatic exposure plus automatic pending reservations: the budget's input.\n * Legacy records with no mode/counter conservatively count as automatic. */\nexport function spentOf(ledger: {\n committedAtomic: string;\n automaticCommittedAtomic?: string;\n reservations: { amountAtomic: string; mode?: 'automatic' | 'manual' }[];\n}): bigint {\n return ledger.reservations.reduce(\n (sum, r) => sum + (r.mode === 'manual' ? 0n : BigInt(r.amountAtomic)),\n BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic),\n );\n}\n\n/**\n * ABSENT and CORRUPT both reset the window, but they are not the same fact: the\n * first is a first run, the second is spend that existed and is now gone. Only\n * the second is worth telling anyone about, so the two stay distinguishable here\n * rather than collapsing into one null.\n */\ninterface LedgerRead {\n ledger: Ledger | null;\n /** Set only when the file EXISTS and could not be turned back into a ledger. */\n corrupt?: string;\n}\n\nexport async function readLedger(path: string): Promise<LedgerRead> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n // A missing file is the ordinary first run. Any other read failure means a\n // file is there and unusable, which is the corrupt case by another name.\n if (hasCode(err, 'ENOENT')) return { ledger: null };\n return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { ledger: null, corrupt: 'not valid JSON' };\n }\n const parsed = LedgerSchema.safeParse(json);\n if (parsed.success) return { ledger: parsed.data };\n const issue = parsed.error.issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // Field-qualified: \"expected number, received undefined\" names nothing on its\n // own. zod never echoes the received VALUE, so no spend figure rides along.\n return {\n ledger: null,\n corrupt: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n}\n\nexport interface SpendSummary {\n windowStartMs: number;\n committedAtomic: string;\n automaticCommittedAtomic?: string;\n /** The window's transmitted authorizations by key; a routing deposit's is\n * `routing-deposit:<id>`. */\n exposures?: Exposure[];\n reservations: {\n amountAtomic: string;\n atMs: number;\n requestKey?: string;\n mode?: 'automatic' | 'manual';\n }[];\n}\n\n/**\n * The ledger AS AN AUTHORIZATION WOULD SEE IT, for `tenjin status`. Read-only,\n * and it applies the same two expiries the authorizer applies before it\n * evaluates a spend: a rolling window that has run out reads as a fresh one,\n * and reservations past their TTL are gone. Summing the raw file instead\n * reported spend as current, and crashed reservations as open, until the next\n * payment happened to rewrite it.\n *\n * `null` for absent or unreadable, which is the same thing to a report.\n */\nexport async function readSpendSummary(\n dir: string,\n opts: { now?: () => number; windowMs?: number } = {},\n): Promise<SpendSummary | null> {\n const { ledger } = await readLedger(spendLedgerPath(dir));\n if (ledger === null) return null;\n const nowMs = (opts.now ?? Date.now)();\n const windowMs = opts.windowMs ?? DEFAULT_WINDOW_MS;\n if (nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);\n return {\n ...ledger,\n reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAalB,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAElC,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,IAAI,iBAAE,OAAO;AAAA,EACb,cAAc,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACtC,MAAM,iBAAE,OAAO;AAAA;AAAA,EAEf,YAAY,iBAAE,OAAO,EAAE,SAAS;AAAA,EAChC,MAAM,iBAAE,KAAK,CAAC,aAAa,QAAQ,CAAC,EAAE,SAAS;AACjD,CAAC;AAQD,IAAM,iBAAiB,iBAAE,OAAO;AAAA,EAC9B,OAAO,iBAAE,OAAO;AAAA,EAChB,cAAc,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACtC,MAAM,iBAAE,OAAO;AAAA,EACf,MAAM,iBAAE,KAAK,CAAC,aAAa,QAAQ,CAAC,EAAE,SAAS;AACjD,CAAC;AAGD,IAAM,eAAe,iBAAE,OAAO;AAAA,EAC5B,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,eAAe,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMxB,iBAAiB,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACzC,0BAA0B,iBAAE,OAAO,EAAE,MAAM,OAAO,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS7D,eAAe,iBAAE,OAAO,EAAE,MAAM,OAAO,EAAE,SAAS;AAAA,EAClD,cAAc,iBAAE,MAAM,iBAAiB;AAAA;AAAA;AAAA,EAGvC,WAAW,iBAAE,MAAM,cAAc,EAAE,SAAS;AAC9C,CAAC;AAGM,SAAS,YAAY,OAAuB;AACjD,SAAO;AAAA,IACL,eAAe;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,KAAK,YAAY;AAClC,MAAI,QAAQ,OAAO,iBAAiB,SAAU,QAAO,YAAY,KAAK;AACtE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,cAAc,OAAO,aAAa,OAAO,CAAC,MAAM,QAAQ,EAAE,OAAO,kBAAkB;AAAA,EACrF;AACF;","names":[]}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
balanceCachePath
|
|
4
|
+
} from "./chunk-SJLTEINJ.js";
|
|
5
|
+
|
|
6
|
+
// src/lib/atomic-json.ts
|
|
7
|
+
import { chmod, link, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { basename, dirname, join } from "node:path";
|
|
10
|
+
var isWindows = process.platform === "win32";
|
|
11
|
+
async function writeFileAtomic(targetPath, data, opts = {}) {
|
|
12
|
+
const dir = dirname(targetPath);
|
|
13
|
+
const fileMode = opts.mode ?? 420;
|
|
14
|
+
const dirMode = opts.dirMode ?? 493;
|
|
15
|
+
await mkdir(dir, { recursive: true, ...isWindows ? {} : { mode: dirMode } });
|
|
16
|
+
const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
|
|
17
|
+
try {
|
|
18
|
+
await writeFile(tmpPath, data, isWindows ? void 0 : { mode: fileMode });
|
|
19
|
+
if (!isWindows) await chmod(tmpPath, fileMode);
|
|
20
|
+
await rename(tmpPath, targetPath);
|
|
21
|
+
} catch (err) {
|
|
22
|
+
await rm(tmpPath, { force: true }).catch(() => void 0);
|
|
23
|
+
throw err;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
async function writeFileAtomicExclusive(targetPath, data, opts = {}) {
|
|
27
|
+
const dir = dirname(targetPath);
|
|
28
|
+
const fileMode = opts.mode ?? 420;
|
|
29
|
+
const dirMode = opts.dirMode ?? 493;
|
|
30
|
+
await mkdir(dir, { recursive: true, ...isWindows ? {} : { mode: dirMode } });
|
|
31
|
+
if (isWindows) {
|
|
32
|
+
const handle = await open(targetPath, "wx");
|
|
33
|
+
try {
|
|
34
|
+
await handle.writeFile(data);
|
|
35
|
+
await handle.sync();
|
|
36
|
+
} finally {
|
|
37
|
+
await handle.close();
|
|
38
|
+
}
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
|
|
42
|
+
try {
|
|
43
|
+
const handle = await open(tmpPath, "wx", fileMode);
|
|
44
|
+
try {
|
|
45
|
+
await handle.writeFile(data);
|
|
46
|
+
await handle.chmod(fileMode);
|
|
47
|
+
await handle.sync();
|
|
48
|
+
} finally {
|
|
49
|
+
await handle.close();
|
|
50
|
+
}
|
|
51
|
+
await link(tmpPath, targetPath);
|
|
52
|
+
await fsyncDir(dir);
|
|
53
|
+
} finally {
|
|
54
|
+
await rm(tmpPath, { force: true }).catch(() => void 0);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async function fsyncDir(dir) {
|
|
58
|
+
const handle = await open(dir, "r");
|
|
59
|
+
try {
|
|
60
|
+
await handle.sync();
|
|
61
|
+
} finally {
|
|
62
|
+
await handle.close();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/lib/usdc-balance.ts
|
|
67
|
+
import { readFile } from "node:fs/promises";
|
|
68
|
+
var USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
|
|
69
|
+
var BALANCE_OF_SELECTOR = "0x70a08231";
|
|
70
|
+
var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
71
|
+
var WORD_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
72
|
+
async function readUsdcBalance(address, rpcUrl, opts) {
|
|
73
|
+
if (!ADDRESS_RE.test(address) || opts.timeoutMs <= 0) return null;
|
|
74
|
+
try {
|
|
75
|
+
const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {
|
|
76
|
+
method: "POST",
|
|
77
|
+
headers: { "content-type": "application/json" },
|
|
78
|
+
body: JSON.stringify({
|
|
79
|
+
jsonrpc: "2.0",
|
|
80
|
+
id: 1,
|
|
81
|
+
method: "eth_call",
|
|
82
|
+
params: [
|
|
83
|
+
{
|
|
84
|
+
to: USDC_ADDRESS,
|
|
85
|
+
data: `${BALANCE_OF_SELECTOR}${address.slice(2).toLowerCase().padStart(64, "0")}`
|
|
86
|
+
},
|
|
87
|
+
"latest"
|
|
88
|
+
]
|
|
89
|
+
}),
|
|
90
|
+
signal: AbortSignal.timeout(opts.timeoutMs)
|
|
91
|
+
});
|
|
92
|
+
if (!res.ok) return null;
|
|
93
|
+
const result = (await res.json())?.result;
|
|
94
|
+
return typeof result === "string" && WORD_RE.test(result) ? BigInt(result) : null;
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
var DEFAULT_RPC_URL = "https://mainnet.base.org";
|
|
100
|
+
var FALLBACK_RPC_URLS = [
|
|
101
|
+
"https://base-rpc.publicnode.com",
|
|
102
|
+
"https://base.drpc.org"
|
|
103
|
+
];
|
|
104
|
+
async function readUsdcBalanceWithFallback(address, rpcUrl, opts) {
|
|
105
|
+
const urls = sameUrl(rpcUrl, DEFAULT_RPC_URL) ? [rpcUrl, ...FALLBACK_RPC_URLS] : [rpcUrl];
|
|
106
|
+
const deadline = Date.now() + opts.timeoutMs;
|
|
107
|
+
for (const [index, url] of urls.entries()) {
|
|
108
|
+
const left = deadline - Date.now();
|
|
109
|
+
if (left <= 0) return null;
|
|
110
|
+
const timeoutMs = index === urls.length - 1 ? left : Math.ceil(left / 2);
|
|
111
|
+
const balance = await readUsdcBalance(address, url, { ...opts, timeoutMs });
|
|
112
|
+
if (balance !== null) return balance;
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
function sameUrl(a, b) {
|
|
117
|
+
try {
|
|
118
|
+
return new URL(a).href === new URL(b).href;
|
|
119
|
+
} catch {
|
|
120
|
+
return a === b;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
var LAST_KNOWN_BALANCE_MS = 6e4;
|
|
124
|
+
function rememberingBalanceReader(dataDir, opts = {}) {
|
|
125
|
+
const read = opts.read ?? readUsdcBalanceWithFallback;
|
|
126
|
+
const now = opts.now ?? Date.now;
|
|
127
|
+
const path = balanceCachePath(dataDir);
|
|
128
|
+
return async (address, rpcUrl, readOpts) => {
|
|
129
|
+
const remembered = await recallBalance(path, address, now());
|
|
130
|
+
if (remembered !== null) return remembered;
|
|
131
|
+
const live = await read(address, rpcUrl, readOpts);
|
|
132
|
+
if (live === null) return null;
|
|
133
|
+
const record = {
|
|
134
|
+
version: 1,
|
|
135
|
+
address: address.toLowerCase(),
|
|
136
|
+
atomic: live.toString(),
|
|
137
|
+
at: now()
|
|
138
|
+
};
|
|
139
|
+
try {
|
|
140
|
+
await writeFileAtomic(path, JSON.stringify(record), { mode: 384, dirMode: 448 });
|
|
141
|
+
} catch {
|
|
142
|
+
}
|
|
143
|
+
return live;
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
async function recallBalance(path, address, now) {
|
|
147
|
+
try {
|
|
148
|
+
const row = JSON.parse(await readFile(path, "utf8"));
|
|
149
|
+
if (row?.version !== 1 || row.address !== address.toLowerCase() || typeof row.atomic !== "string" || !/^\d{1,40}$/.test(row.atomic) || typeof row.at !== "number" || now - row.at < 0 || now - row.at > LAST_KNOWN_BALANCE_MS) {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
return BigInt(row.atomic);
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export {
|
|
159
|
+
writeFileAtomic,
|
|
160
|
+
writeFileAtomicExclusive,
|
|
161
|
+
fsyncDir,
|
|
162
|
+
USDC_ADDRESS,
|
|
163
|
+
readUsdcBalance,
|
|
164
|
+
DEFAULT_RPC_URL,
|
|
165
|
+
readUsdcBalanceWithFallback,
|
|
166
|
+
rememberingBalanceReader
|
|
167
|
+
};
|
|
168
|
+
//# sourceMappingURL=chunk-O2FRQ2L2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/atomic-json.ts","../src/lib/usdc-balance.ts"],"sourcesContent":["import { chmod, link, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { basename, dirname, join } from 'node:path';\n\n/** fs modes are no-ops on Windows; the 0600/0700 custody story does not apply. */\nconst isWindows = process.platform === 'win32';\n\nexport interface AtomicWriteOptions {\n /** Mode for the written file (ignored on win32). Default 0o644. */\n mode?: number;\n /** Mode for the parent dir when this call creates it (ignored on win32). Default 0o755. */\n dirMode?: number;\n}\n\n/**\n * Write `data` to `targetPath` atomically: a uniquely-named temp file is created\n * in the SAME directory (so the rename is atomic — a cross-filesystem rename is\n * not), given the final mode at open time, then renamed over the target. A\n * reader therefore sees either the old file or the fully-written new one, never\n * a partial write.\n *\n * The temp file is born with the caller's `mode` (0o600 for a wallet key) so the\n * bytes are never written through a world-readable descriptor; the follow-up\n * chmod only makes the mode exact under an unusual umask and only ever touches\n * the temp path, so the live target still appears atomically at its final mode.\n */\nexport async function writeFileAtomic(\n targetPath: string,\n data: string | Buffer,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n await writeFile(tmpPath, data, isWindows ? undefined : { mode: fileMode });\n if (!isWindows) await chmod(tmpPath, fileMode);\n await rename(tmpPath, targetPath);\n } catch (err) {\n await rm(tmpPath, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * Like {@link writeFileAtomic} but NO-CLOBBER and crash-durable: the commit fails\n * with `EEXIST` when `targetPath` already exists instead of replacing it, and the\n * new entry is fsynced before returning. This is what a wallet key needs — two\n * concurrent `create`/`import` runs must not both \"succeed\" and silently lose one\n * key; the loser gets a distinguishable EEXIST the wallet layer maps to\n * WALLET_EXISTS.\n *\n * The temp file is fsynced, then `link()` commits it — link is atomic and throws\n * EEXIST if the target already exists, so the check-then-write race is closed at\n * the filesystem, not by an earlier stat. The parent dir is then fsynced so the\n * new entry survives a crash. On win32, link semantics differ and a directory\n * cannot be fsynced, so we fall back to an exclusive `wx` open (still atomic\n * create-or-EEXIST, just not crash-durable — win32 has no 0600 custody story to\n * protect anyway).\n */\nexport async function writeFileAtomicExclusive(\n targetPath: string,\n data: string,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n if (isWindows) {\n const handle = await open(targetPath, 'wx');\n try {\n await handle.writeFile(data);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return;\n }\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const handle = await open(tmpPath, 'wx', fileMode);\n try {\n await handle.writeFile(data);\n await handle.chmod(fileMode); // exact mode even under an unusual umask\n await handle.sync();\n } finally {\n await handle.close();\n }\n await link(tmpPath, targetPath); // atomic; throws EEXIST when the target exists\n await fsyncDir(dir);\n } finally {\n // On success the temp is now a redundant link to the target; on EEXIST it is\n // the orphaned write. Either way remove it before returning/throwing.\n await rm(tmpPath, { force: true }).catch(() => undefined);\n }\n}\n\n/** fsync a directory so a freshly linked entry is durable. Never call on win32. */\nexport async function fsyncDir(dir: string): Promise<void> {\n const handle = await open(dir, 'r');\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\n","/**\n * Base USDC's address and one `balanceOf` over plain JSON-RPC. No viem on\n * purpose: the router hooks read a balance before they redirect a call, and\n * their chunk graph must stay free of it (`src/router/dist-chunks.test.ts`).\n * One `eth_call` needs nothing viem adds. `usdc.ts` keeps the viem client for\n * the send path and re-exports the address from here.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { writeFileAtomic } from './atomic-json';\nimport { balanceCachePath } from './paths';\n\n// Values mirror the app's lib/chain.ts Base mainnet entry (chain 8453).\nexport const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';\n\n/** `balanceOf(address)`: the first four bytes of its keccak-256. */\nconst BALANCE_OF_SELECTOR = '0x70a08231';\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n/** One ABI word: what `balanceOf` returns. */\nconst WORD_RE = /^0x[0-9a-fA-F]{64}$/;\n\n/**\n * The address's USDC balance in atomic units, or null when it could not be\n * read inside `timeoutMs`: a transport failure, a non-2xx, an RPC error, or an\n * answer that is not one word. Never throws, so the caller picks which way an\n * unreadable balance falls.\n */\nexport async function readUsdcBalance(\n address: string,\n rpcUrl: string,\n opts: { timeoutMs: number; fetchImpl?: typeof fetch },\n): Promise<bigint | null> {\n if (!ADDRESS_RE.test(address) || opts.timeoutMs <= 0) return null;\n try {\n const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'eth_call',\n params: [\n {\n to: USDC_ADDRESS,\n data: `${BALANCE_OF_SELECTOR}${address.slice(2).toLowerCase().padStart(64, '0')}`,\n },\n 'latest',\n ],\n }),\n signal: AbortSignal.timeout(opts.timeoutMs),\n });\n if (!res.ok) return null;\n const result = ((await res.json()) as { result?: unknown } | null)?.result;\n return typeof result === 'string' && WORD_RE.test(result) ? BigInt(result) : null;\n } catch {\n return null;\n }\n}\n\n/** Base's public RPC: the shipped `rpcUrl` default (`CONFIG_DEFAULTS`). */\nexport const DEFAULT_RPC_URL = 'https://mainnet.base.org';\n\n/**\n * Public Base RPCs a balance read on the DEFAULT `rpcUrl` falls back to, in\n * order, only after it fails. mainnet.base.org rate-limits a busy IP\n * (`-32016 over rate limit`): four paid lookups across two research runs were\n * refused with `balance_unavailable` before signing, while these two answered\n * every read. They see the wallet's address only when the default did not\n * answer, as the default sees it on every read.\n */\nexport const FALLBACK_RPC_URLS: readonly string[] = [\n 'https://base-rpc.publicnode.com',\n 'https://base.drpc.org',\n];\n\n/**\n * {@link readUsdcBalance} from `rpcUrl` first and, when that is the default,\n * then from each of {@link FALLBACK_RPC_URLS} until one answers, all inside the\n * one `timeoutMs`. Every RPC but the last gets half of what is left, so one\n * that hangs still leaves the others time to answer.\n *\n * AN RPC THE USER CONFIGURED IS THE ONLY ONE ASKED. Choosing one can be about\n * privacy, and the public RPCs would see the wallet's address; a read that\n * fails there fails, as it did before the fallbacks.\n */\nexport async function readUsdcBalanceWithFallback(\n address: string,\n rpcUrl: string,\n opts: { timeoutMs: number; fetchImpl?: typeof fetch },\n): Promise<bigint | null> {\n const urls = sameUrl(rpcUrl, DEFAULT_RPC_URL) ? [rpcUrl, ...FALLBACK_RPC_URLS] : [rpcUrl];\n const deadline = Date.now() + opts.timeoutMs;\n for (const [index, url] of urls.entries()) {\n const left = deadline - Date.now();\n if (left <= 0) return null;\n const timeoutMs = index === urls.length - 1 ? left : Math.ceil(left / 2);\n const balance = await readUsdcBalance(address, url, { ...opts, timeoutMs });\n if (balance !== null) return balance;\n }\n return null;\n}\n\nfunction sameUrl(a: string, b: string): boolean {\n try {\n return new URL(a).href === new URL(b).href;\n } catch {\n return a === b;\n }\n}\n\n/**\n * How long the hooks remember a balance read. Base's public RPC refuses the\n * sixth `eth_call` in a second, which a burst of parallel lookups reaches, and\n * each hook then waited on a failed read. A minute carries a burst past that;\n * the hooks' read only decides whether to offer.\n */\nexport const LAST_KNOWN_BALANCE_MS = 60_000;\n\n/**\n * {@link readUsdcBalanceWithFallback} for the router hooks, which returns the\n * last read it made for this address while it is under\n * {@link LAST_KNOWN_BALANCE_MS} old, without asking an RPC, and reads the chain\n * otherwise. A read that fails on every RPC is null, never the remembered\n * balance. The RPC URL is never stored, since it can embed a key.\n *\n * NEVER FOR A PAYMENT. `tenjin pay` reads the signer's balance live\n * immediately before signing (docs/agent-permissions.md): a minute-old balance\n * can be one the wallet has since spent.\n */\nexport function rememberingBalanceReader(\n dataDir: string,\n opts: { now?: () => number; read?: typeof readUsdcBalance } = {},\n): typeof readUsdcBalance {\n const read = opts.read ?? readUsdcBalanceWithFallback;\n const now = opts.now ?? Date.now;\n const path = balanceCachePath(dataDir);\n return async (address, rpcUrl, readOpts) => {\n const remembered = await recallBalance(path, address, now());\n if (remembered !== null) return remembered;\n const live = await read(address, rpcUrl, readOpts);\n if (live === null) return null;\n const record = {\n version: 1,\n address: address.toLowerCase(),\n atomic: live.toString(),\n at: now(),\n };\n try {\n await writeFileAtomic(path, JSON.stringify(record), { mode: 0o600, dirMode: 0o700 });\n } catch {\n // A cache that cannot be written is a cache that is not used.\n }\n return live;\n };\n}\n\n/** The remembered balance for this address while it is fresh, else null. */\nasync function recallBalance(path: string, address: string, now: number): Promise<bigint | null> {\n try {\n const row = JSON.parse(await readFile(path, 'utf8')) as Record<string, unknown> | null;\n if (\n row?.version !== 1 ||\n row.address !== address.toLowerCase() ||\n typeof row.atomic !== 'string' ||\n !/^\\d{1,40}$/.test(row.atomic) ||\n typeof row.at !== 'number' ||\n now - row.at < 0 ||\n now - row.at > LAST_KNOWN_BALANCE_MS\n ) {\n return null;\n }\n return BigInt(row.atomic);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,OAAO,MAAM,OAAO,MAAM,QAAQ,IAAI,iBAAiB;AAChE,SAAS,mBAAmB;AAC5B,SAAS,UAAU,SAAS,YAAY;AAGxC,IAAM,YAAY,QAAQ,aAAa;AAq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A,MACb,SAAS;AAAA,MACT,SAAS,QAAQ,YAAY;AAAA,MAC7B,QAAQ,KAAK,SAAS;AAAA,MACtB,IAAI,IAAI;AAAA,IACV;AACA,QAAI;AACF,YAAM,gBAAgB,MAAM,KAAK,UAAU,MAAM,GAAG,EAAE,MAAM,KAAO,SAAS,IAAM,CAAC;AAAA,IACrF,QAAQ;AAAA,IAER;AACA,WAAO;AAAA,EACT;AACF;AAGA,eAAe,cAAc,MAAc,SAAiB,KAAqC;AAC/F,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;AACnD,QACE,KAAK,YAAY,KACjB,IAAI,YAAY,QAAQ,YAAY,KACpC,OAAO,IAAI,WAAW,YACtB,CAAC,aAAa,KAAK,IAAI,MAAM,KAC7B,OAAO,IAAI,OAAO,YAClB,MAAM,IAAI,KAAK,KACf,MAAM,IAAI,KAAK,uBACf;AACA,aAAO;AAAA,IACT;AACA,WAAO,OAAO,IAAI,MAAM;AAAA,EAC1B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
resolvePublicDestination
|
|
4
|
+
} from "./chunk-EBVIKMCH.js";
|
|
5
|
+
import {
|
|
6
|
+
releaseUnchargedExposure
|
|
7
|
+
} from "./chunk-AEG2PXBP.js";
|
|
8
|
+
import {
|
|
9
|
+
withFileLock
|
|
10
|
+
} from "./chunk-MEFB5KHA.js";
|
|
11
|
+
import {
|
|
12
|
+
mask
|
|
13
|
+
} from "./chunk-7QKHZQKW.js";
|
|
14
|
+
import {
|
|
15
|
+
hasCode
|
|
16
|
+
} from "./chunk-2I4QTOLB.js";
|
|
17
|
+
import {
|
|
18
|
+
USDC_ADDRESS,
|
|
19
|
+
writeFileAtomic
|
|
20
|
+
} from "./chunk-O2FRQ2L2.js";
|
|
21
|
+
import {
|
|
22
|
+
downloadsDir,
|
|
23
|
+
paidLedgerPath
|
|
24
|
+
} from "./chunk-SJLTEINJ.js";
|
|
25
|
+
|
|
26
|
+
// src/router/paid.ts
|
|
27
|
+
import { randomBytes } from "node:crypto";
|
|
28
|
+
import { appendFile, mkdir, open, readFile, rm } from "node:fs/promises";
|
|
29
|
+
import { request as httpsRequest } from "node:https";
|
|
30
|
+
import { dirname, join } from "node:path";
|
|
31
|
+
var MAX_SENT_CHARS = 4096;
|
|
32
|
+
function maskDeep(value) {
|
|
33
|
+
if (typeof value === "string") return mask(value);
|
|
34
|
+
if (Array.isArray(value)) return value.map(maskDeep);
|
|
35
|
+
if (value !== null && typeof value === "object") {
|
|
36
|
+
return Object.fromEntries(
|
|
37
|
+
Object.entries(value).map(([key, entry]) => [
|
|
38
|
+
mask(key),
|
|
39
|
+
maskDeep(entry)
|
|
40
|
+
])
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
function recordedSent(sent) {
|
|
46
|
+
return mask(sent).slice(0, MAX_SENT_CHARS);
|
|
47
|
+
}
|
|
48
|
+
async function appendPaidRecord(dataDir, record) {
|
|
49
|
+
try {
|
|
50
|
+
const path = paidLedgerPath(dataDir);
|
|
51
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
52
|
+
await withFileLock(
|
|
53
|
+
`${path}.lock`,
|
|
54
|
+
() => appendFile(path, `${JSON.stringify(record)}
|
|
55
|
+
`, { mode: 384 })
|
|
56
|
+
);
|
|
57
|
+
} catch {
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function updatePaidRecord(dataDir, nonce, patch) {
|
|
61
|
+
try {
|
|
62
|
+
const path = paidLedgerPath(dataDir);
|
|
63
|
+
const key = nonce.toLowerCase();
|
|
64
|
+
await withFileLock(`${path}.lock`, async () => {
|
|
65
|
+
const current = parseLedger(await readFile(path, "utf8").catch(() => ""));
|
|
66
|
+
let found = false;
|
|
67
|
+
const lines = current.map(({ line, record }) => {
|
|
68
|
+
if (record?.authorization?.nonce.toLowerCase() !== key) return line;
|
|
69
|
+
found = true;
|
|
70
|
+
return JSON.stringify({
|
|
71
|
+
...record,
|
|
72
|
+
...patch.savedFiles !== void 0 ? { savedFiles: patch.savedFiles } : {},
|
|
73
|
+
...patch.txHash !== void 0 && record.settlement === "unknown" ? { txHash: patch.txHash, settlement: "settled" } : {}
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
if (found) {
|
|
77
|
+
await writeFileAtomic(path, lines.map((line) => `${line}
|
|
78
|
+
`).join(""), { mode: 384 });
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
} catch {
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
var AUTHORIZATION_STATE_SELECTOR = "0xe94a0102";
|
|
85
|
+
var WORD_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
86
|
+
var MAX_RECONCILE_CHECKS = 3;
|
|
87
|
+
var RECHECK_MS = 10 * 6e4;
|
|
88
|
+
var RECONCILE_TIMEOUT_MS = 1500;
|
|
89
|
+
async function authorizationUsed(authorization, rpcUrl, opts = {}) {
|
|
90
|
+
const result = await rpcCall(
|
|
91
|
+
rpcUrl,
|
|
92
|
+
"eth_call",
|
|
93
|
+
[
|
|
94
|
+
{
|
|
95
|
+
to: USDC_ADDRESS,
|
|
96
|
+
data: `${AUTHORIZATION_STATE_SELECTOR}${authorization.from.slice(2).toLowerCase().padStart(64, "0")}${authorization.nonce.slice(2).toLowerCase()}`
|
|
97
|
+
},
|
|
98
|
+
opts.blockTag ?? "latest"
|
|
99
|
+
],
|
|
100
|
+
opts
|
|
101
|
+
);
|
|
102
|
+
if (typeof result !== "string" || !WORD_RE.test(result)) return null;
|
|
103
|
+
return BigInt(result) !== 0n;
|
|
104
|
+
}
|
|
105
|
+
async function latestBlock(rpcUrl, opts = {}) {
|
|
106
|
+
const result = await rpcCall(rpcUrl, "eth_getBlockByNumber", ["latest", false], opts);
|
|
107
|
+
if (result === null || typeof result !== "object") return null;
|
|
108
|
+
const { number, timestamp } = result;
|
|
109
|
+
if (typeof number !== "string" || !/^0x[0-9a-fA-F]+$/.test(number)) return null;
|
|
110
|
+
if (typeof timestamp !== "string" || !/^0x[0-9a-fA-F]+$/.test(timestamp)) return null;
|
|
111
|
+
return { tag: number, timestamp: Number(BigInt(timestamp)) };
|
|
112
|
+
}
|
|
113
|
+
async function rpcCall(rpcUrl, method, params, opts) {
|
|
114
|
+
try {
|
|
115
|
+
const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {
|
|
116
|
+
method: "POST",
|
|
117
|
+
headers: { "content-type": "application/json" },
|
|
118
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
119
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? RECONCILE_TIMEOUT_MS)
|
|
120
|
+
});
|
|
121
|
+
if (!res.ok) return null;
|
|
122
|
+
return (await res.json())?.result ?? null;
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function reconcilePayments(dataDir, opts) {
|
|
128
|
+
const path = paidLedgerPath(dataDir);
|
|
129
|
+
const now = (opts.now ?? Date.now)();
|
|
130
|
+
const records = parseLedger(await readFile(path, "utf8").catch(() => ""));
|
|
131
|
+
const open2 = records.filter(
|
|
132
|
+
(entry) => entry.record !== null && entry.record.settlement === "unknown"
|
|
133
|
+
);
|
|
134
|
+
const recheckMs = opts.recheckMs ?? RECHECK_MS;
|
|
135
|
+
const due = open2.filter(
|
|
136
|
+
({ record }) => record.authorization !== void 0 && Number(record.authorization.validBefore) * 1e3 < now && (record.lastCheckedAt === void 0 || now - Date.parse(record.lastCheckedAt) >= recheckMs)
|
|
137
|
+
);
|
|
138
|
+
const answers = /* @__PURE__ */ new Map();
|
|
139
|
+
const asked = /* @__PURE__ */ new Set();
|
|
140
|
+
let checked = 0;
|
|
141
|
+
const rpc = {
|
|
142
|
+
...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {},
|
|
143
|
+
...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {}
|
|
144
|
+
};
|
|
145
|
+
const block = due.length > 0 ? await latestBlock(opts.rpcUrl, rpc) : null;
|
|
146
|
+
for (const { record } of due.slice(0, opts.max ?? MAX_RECONCILE_CHECKS)) {
|
|
147
|
+
if (block !== null && Number(record.authorization.validBefore) >= block.timestamp) continue;
|
|
148
|
+
checked += 1;
|
|
149
|
+
asked.add(record.authorization.nonce);
|
|
150
|
+
if (block === null) continue;
|
|
151
|
+
const used = await authorizationUsed(record.authorization, opts.rpcUrl, {
|
|
152
|
+
...rpc,
|
|
153
|
+
blockTag: block.tag
|
|
154
|
+
});
|
|
155
|
+
if (used !== null) answers.set(record.authorization.nonce, used ? "settled" : "not_charged");
|
|
156
|
+
}
|
|
157
|
+
let releasedAtomic = 0n;
|
|
158
|
+
for (const [nonce, answer] of [...answers]) {
|
|
159
|
+
if (answer !== "not_charged") continue;
|
|
160
|
+
const released = await releaseUnchargedExposure(dataDir, nonce, {
|
|
161
|
+
...opts.now !== void 0 ? { now: opts.now } : {}
|
|
162
|
+
});
|
|
163
|
+
if (released === null) answers.delete(nonce);
|
|
164
|
+
else releasedAtomic += released;
|
|
165
|
+
}
|
|
166
|
+
if (asked.size > 0) {
|
|
167
|
+
await withFileLock(`${path}.lock`, async () => {
|
|
168
|
+
const current = parseLedger(await readFile(path, "utf8").catch(() => ""));
|
|
169
|
+
const lines = current.map(({ line, record }) => {
|
|
170
|
+
const nonce = record?.settlement === "unknown" && record.authorization !== void 0 ? record.authorization.nonce : void 0;
|
|
171
|
+
if (nonce === void 0 || !asked.has(nonce)) return line;
|
|
172
|
+
const answer = answers.get(nonce);
|
|
173
|
+
const stamp = new Date(now).toISOString();
|
|
174
|
+
return JSON.stringify(
|
|
175
|
+
answer === void 0 ? { ...record, lastCheckedAt: stamp } : { ...record, settlement: answer, lastCheckedAt: stamp, reconciledAt: stamp }
|
|
176
|
+
);
|
|
177
|
+
});
|
|
178
|
+
await writeFileAtomic(path, lines.map((line) => `${line}
|
|
179
|
+
`).join(""), { mode: 384 });
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
const settled = [...answers.values()].filter((value) => value === "settled").length;
|
|
183
|
+
return {
|
|
184
|
+
checked,
|
|
185
|
+
settled,
|
|
186
|
+
notCharged: answers.size - settled,
|
|
187
|
+
unknown: open2.length - answers.size,
|
|
188
|
+
releasedAtomic: releasedAtomic.toString()
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
async function readPaidRecords(dataDir) {
|
|
192
|
+
const raw = await readFile(paidLedgerPath(dataDir), "utf8").catch(() => "");
|
|
193
|
+
return parseLedger(raw).flatMap(({ record }) => record === null ? [] : [record]);
|
|
194
|
+
}
|
|
195
|
+
function parseLedger(raw) {
|
|
196
|
+
return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => {
|
|
197
|
+
try {
|
|
198
|
+
const value = JSON.parse(line);
|
|
199
|
+
return { line, record: value !== null && value.version === 1 ? value : null };
|
|
200
|
+
} catch {
|
|
201
|
+
return { line, record: null };
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
206
|
+
"png",
|
|
207
|
+
"jpg",
|
|
208
|
+
"jpeg",
|
|
209
|
+
"webp",
|
|
210
|
+
"gif",
|
|
211
|
+
"svg",
|
|
212
|
+
"mp3",
|
|
213
|
+
"wav",
|
|
214
|
+
"m4a",
|
|
215
|
+
"ogg",
|
|
216
|
+
"mp4",
|
|
217
|
+
"webm",
|
|
218
|
+
"mov"
|
|
219
|
+
]);
|
|
220
|
+
var MAX_MEDIA_FILES = 5;
|
|
221
|
+
var MAX_MEDIA_BYTES = 200 * 1024 * 1024;
|
|
222
|
+
var MEDIA_TIMEOUT_MS = 6e4;
|
|
223
|
+
var MAX_REDIRECTS = 3;
|
|
224
|
+
var URL_RE = /https:\/\/[^\s"'<>\\]+/g;
|
|
225
|
+
function mediaUrlsIn(result, limit = MAX_MEDIA_FILES) {
|
|
226
|
+
const found = [];
|
|
227
|
+
for (const match of result.matchAll(URL_RE)) {
|
|
228
|
+
if (found.length >= limit) break;
|
|
229
|
+
let url;
|
|
230
|
+
try {
|
|
231
|
+
url = new URL(match[0]);
|
|
232
|
+
} catch {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
const ext = url.pathname.split(".").pop()?.toLowerCase() ?? "";
|
|
236
|
+
if (!url.pathname.includes(".") || !MEDIA_EXTENSIONS.has(ext)) continue;
|
|
237
|
+
if (!found.includes(url.toString())) found.push(url.toString());
|
|
238
|
+
}
|
|
239
|
+
return found;
|
|
240
|
+
}
|
|
241
|
+
var pinnedGet = (target, signal) => new Promise((resolve, reject) => {
|
|
242
|
+
const req = httpsRequest(
|
|
243
|
+
target.url,
|
|
244
|
+
{
|
|
245
|
+
method: "GET",
|
|
246
|
+
signal,
|
|
247
|
+
lookup: pinnedLookup(target)
|
|
248
|
+
},
|
|
249
|
+
(res) => {
|
|
250
|
+
const length = Number(res.headers["content-length"]);
|
|
251
|
+
const location = res.headers.location;
|
|
252
|
+
resolve({
|
|
253
|
+
status: res.statusCode ?? 0,
|
|
254
|
+
...typeof location === "string" ? { location } : {},
|
|
255
|
+
...Number.isFinite(length) ? { contentLength: length } : {},
|
|
256
|
+
body: res,
|
|
257
|
+
discard: () => res.destroy()
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
);
|
|
261
|
+
req.on("error", reject);
|
|
262
|
+
req.end();
|
|
263
|
+
});
|
|
264
|
+
function pinnedLookup(target) {
|
|
265
|
+
return ((_host, options, callback) => {
|
|
266
|
+
if (options.all === true) {
|
|
267
|
+
callback(null, [{ address: target.address, family: target.family }]);
|
|
268
|
+
} else {
|
|
269
|
+
callback(null, target.address, target.family);
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
var CAPPED = /* @__PURE__ */ Symbol("capped");
|
|
274
|
+
var FAILED = /* @__PURE__ */ Symbol("failed");
|
|
275
|
+
async function saveMedia(dataDir, stem, urls, deps = {}) {
|
|
276
|
+
const saved = [];
|
|
277
|
+
let capped = false;
|
|
278
|
+
let failed = false;
|
|
279
|
+
for (const [index, url] of urls.entries()) {
|
|
280
|
+
const path = await saveOne(dataDir, `${stem}-${index + 1}`, url, deps);
|
|
281
|
+
if (path === CAPPED) capped = true;
|
|
282
|
+
else if (path === FAILED) failed = true;
|
|
283
|
+
else if (path !== null) saved.push(path);
|
|
284
|
+
}
|
|
285
|
+
return { saved, capped, failed };
|
|
286
|
+
}
|
|
287
|
+
var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 429]);
|
|
288
|
+
async function saveOne(dataDir, stem, raw, deps) {
|
|
289
|
+
const transport = deps.transport ?? pinnedGet;
|
|
290
|
+
const cap = deps.maxBytes ?? MAX_MEDIA_BYTES;
|
|
291
|
+
const { budget } = deps;
|
|
292
|
+
if (budget !== void 0 && budget.leftBytes <= 0) return CAPPED;
|
|
293
|
+
let charged = 0;
|
|
294
|
+
let kept = false;
|
|
295
|
+
let capped = false;
|
|
296
|
+
let refused = false;
|
|
297
|
+
const signal = AbortSignal.timeout(deps.timeoutMs ?? MEDIA_TIMEOUT_MS);
|
|
298
|
+
let target = raw;
|
|
299
|
+
let path = null;
|
|
300
|
+
try {
|
|
301
|
+
let res = null;
|
|
302
|
+
for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
|
|
303
|
+
const pinned = await resolvePublicDestination(target, deps.destination ?? {}).catch(
|
|
304
|
+
(err) => {
|
|
305
|
+
refused = true;
|
|
306
|
+
throw err;
|
|
307
|
+
}
|
|
308
|
+
);
|
|
309
|
+
res = await transport(pinned, signal);
|
|
310
|
+
if (res.status < 300 || res.status >= 400 || res.location === void 0) break;
|
|
311
|
+
res.discard();
|
|
312
|
+
target = new URL(res.location, target).toString();
|
|
313
|
+
res = null;
|
|
314
|
+
}
|
|
315
|
+
if (res === null || res.status < 200 || res.status >= 300) {
|
|
316
|
+
res?.discard();
|
|
317
|
+
const status = res?.status ?? 0;
|
|
318
|
+
return status >= 500 || RETRYABLE_STATUS.has(status) ? FAILED : null;
|
|
319
|
+
}
|
|
320
|
+
const declared = res.contentLength ?? 0;
|
|
321
|
+
if (declared > cap) {
|
|
322
|
+
res.discard();
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
if (budget !== void 0 && declared > budget.leftBytes) {
|
|
326
|
+
res.discard();
|
|
327
|
+
return CAPPED;
|
|
328
|
+
}
|
|
329
|
+
const ext = new URL(target).pathname.split(".").pop()?.toLowerCase() ?? "bin";
|
|
330
|
+
const file = await createUniqueFile(
|
|
331
|
+
downloadsDir(dataDir),
|
|
332
|
+
`${stem}-${(deps.now ?? Date.now)()}`,
|
|
333
|
+
MEDIA_EXTENSIONS.has(ext) ? ext : "bin"
|
|
334
|
+
);
|
|
335
|
+
path = file.path;
|
|
336
|
+
let size = 0;
|
|
337
|
+
try {
|
|
338
|
+
for await (const chunk of res.body) {
|
|
339
|
+
size += chunk.byteLength;
|
|
340
|
+
if (size > cap) {
|
|
341
|
+
res.discard();
|
|
342
|
+
refused = true;
|
|
343
|
+
throw new Error("media over the size cap");
|
|
344
|
+
}
|
|
345
|
+
if (budget !== void 0) {
|
|
346
|
+
if (chunk.byteLength > budget.leftBytes) {
|
|
347
|
+
res.discard();
|
|
348
|
+
capped = true;
|
|
349
|
+
throw new Error("media over the call's download cap");
|
|
350
|
+
}
|
|
351
|
+
budget.leftBytes -= chunk.byteLength;
|
|
352
|
+
charged += chunk.byteLength;
|
|
353
|
+
}
|
|
354
|
+
await writeAll(file.handle, chunk);
|
|
355
|
+
}
|
|
356
|
+
} finally {
|
|
357
|
+
await file.handle.close();
|
|
358
|
+
}
|
|
359
|
+
kept = true;
|
|
360
|
+
return path;
|
|
361
|
+
} catch {
|
|
362
|
+
if (path !== null) await rm(path, { force: true }).catch(() => void 0);
|
|
363
|
+
return capped ? CAPPED : refused ? null : FAILED;
|
|
364
|
+
} finally {
|
|
365
|
+
if (budget !== void 0 && !kept) budget.leftBytes += charged;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
async function writeAll(handle, bytes) {
|
|
369
|
+
let offset = 0;
|
|
370
|
+
while (offset < bytes.byteLength) {
|
|
371
|
+
const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset);
|
|
372
|
+
if (bytesWritten <= 0) throw new Error("the file write made no progress");
|
|
373
|
+
offset += bytesWritten;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async function createUniqueFile(directory, stem, ext) {
|
|
377
|
+
await mkdir(directory, { recursive: true });
|
|
378
|
+
const safe = stem.replace(/[^A-Za-z0-9_-]+/g, "-").slice(0, 100) || "lookup";
|
|
379
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
380
|
+
const path = join(directory, `${safe}-${randomBytes(4).toString("hex")}.${ext}`);
|
|
381
|
+
try {
|
|
382
|
+
return { path, handle: await open(path, "wx", 384) };
|
|
383
|
+
} catch (err) {
|
|
384
|
+
if (attempt >= 4 || !hasCode(err, "EEXIST")) throw err;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export {
|
|
390
|
+
maskDeep,
|
|
391
|
+
recordedSent,
|
|
392
|
+
appendPaidRecord,
|
|
393
|
+
updatePaidRecord,
|
|
394
|
+
reconcilePayments,
|
|
395
|
+
readPaidRecords,
|
|
396
|
+
MAX_MEDIA_FILES,
|
|
397
|
+
MAX_MEDIA_BYTES,
|
|
398
|
+
mediaUrlsIn,
|
|
399
|
+
pinnedLookup,
|
|
400
|
+
saveMedia,
|
|
401
|
+
writeAll,
|
|
402
|
+
createUniqueFile
|
|
403
|
+
};
|
|
404
|
+
//# sourceMappingURL=chunk-OK2TDZQU.js.map
|