tenjin-cli 0.1.0-alpha.20 → 0.1.0-alpha.21
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/README.md +17 -2
- package/dist/{chunk-3BS55ANY.js → chunk-2AQO4YDI.js} +50 -4
- package/dist/{chunk-3BS55ANY.js.map → chunk-2AQO4YDI.js.map} +1 -1
- package/dist/{chunk-HH3PDYIG.js → chunk-3EUTWC2B.js} +5 -5
- package/dist/{chunk-BTX2QE2Y.js → chunk-AQRUD5GQ.js} +2 -2
- package/dist/{chunk-CXUYCDPX.js → chunk-C363JZN2.js} +4 -4
- package/dist/{chunk-PO4HAXAW.js → chunk-ETW2ASBP.js} +52 -18
- package/dist/chunk-ETW2ASBP.js.map +1 -0
- package/dist/{chunk-RPR2C2JO.js → chunk-GHTPYKDT.js} +5 -5
- package/dist/{chunk-5KD5HRAJ.js → chunk-IOB7URFH.js} +3 -2
- package/dist/chunk-IOB7URFH.js.map +1 -0
- package/dist/{chunk-5FYKPQNX.js → chunk-IOIHYOU4.js} +3 -3
- package/dist/{chunk-LN2HISWU.js → chunk-JN7TMXVF.js} +2 -2
- package/dist/{chunk-TU7XH3JJ.js → chunk-K6AXXYCG.js} +14 -2
- package/dist/chunk-K6AXXYCG.js.map +1 -0
- package/dist/{chunk-2G2WLVHB.js → chunk-LAIZ2AQA.js} +9 -4
- package/dist/chunk-LAIZ2AQA.js.map +1 -0
- package/dist/{chunk-YREKMJPP.js → chunk-N4DJEQAF.js} +65 -6
- package/dist/chunk-N4DJEQAF.js.map +1 -0
- package/dist/{chunk-NSG5TVZQ.js → chunk-OSUD6YZZ.js} +14 -10
- package/dist/chunk-OSUD6YZZ.js.map +1 -0
- package/dist/{chunk-2E6GVIRP.js → chunk-OTPEH3AH.js} +47 -9
- package/dist/chunk-OTPEH3AH.js.map +1 -0
- package/dist/{chunk-LI44XLMB.js → chunk-PJEG2JIJ.js} +5 -5
- package/dist/{chunk-4M5FBWT5.js → chunk-QF4SSCQV.js} +10 -1
- package/dist/chunk-QF4SSCQV.js.map +1 -0
- package/dist/chunk-QHILSA6G.js +82 -0
- package/dist/chunk-QHILSA6G.js.map +1 -0
- package/dist/{chunk-72UHZRG6.js → chunk-QRFONFRW.js} +2 -2
- package/dist/{chunk-P42QX3QF.js → chunk-RCJQARZF.js} +2 -2
- package/dist/{chunk-P42QX3QF.js.map → chunk-RCJQARZF.js.map} +1 -1
- package/dist/chunk-SRVDXR6B.js +337 -0
- package/dist/chunk-SRVDXR6B.js.map +1 -0
- package/dist/{chunk-7ACHDNJA.js → chunk-U2ATFMKZ.js} +13 -4
- package/dist/chunk-U2ATFMKZ.js.map +1 -0
- package/dist/{chunk-4AS52HUG.js → chunk-UY2TOI3B.js} +70 -27
- package/dist/chunk-UY2TOI3B.js.map +1 -0
- package/dist/{chunk-CCDOV45D.js → chunk-W3LVZ2EN.js} +25 -8
- package/dist/{chunk-CCDOV45D.js.map → chunk-W3LVZ2EN.js.map} +1 -1
- package/dist/{chunk-YEBNE5NW.js → chunk-YVODPFTL.js} +5 -5
- package/dist/{cli-XJQYUOHI.js → cli-7KJ4QLUU.js} +42 -29
- package/dist/{cli-XJQYUOHI.js.map → cli-7KJ4QLUU.js.map} +1 -1
- package/dist/{config-KMJLFPSI.js → config-MSN6H4MD.js} +10 -8
- package/dist/{doctor-KMN55D7U.js → doctor-ITUCKN6C.js} +25 -16
- package/dist/{doctor-KMN55D7U.js.map → doctor-ITUCKN6C.js.map} +1 -1
- package/dist/{fund-LT6ZPGEQ.js → fund-XPB4IIG5.js} +11 -11
- package/dist/{hook-command-U5XPEHAJ.js → hook-command-VVV2Q23L.js} +293 -80
- package/dist/hook-command-VVV2Q23L.js.map +1 -0
- package/dist/index.js +4 -4
- package/dist/{install-MMNXJ5LM.js → install-OSJRM2ME.js} +13 -11
- package/dist/{install-identity-B7FVIWML.js → install-identity-YIWKQOUD.js} +7 -7
- package/dist/{install-wallet-XMVUBCHS.js → install-wallet-BWJO2SUC.js} +10 -10
- package/dist/{mcp-TUPRIPSI.js → mcp-KE5YKPS2.js} +203 -29
- package/dist/{mcp-TUPRIPSI.js.map → mcp-KE5YKPS2.js.map} +1 -1
- package/dist/{paths-LRMWNTJP.js → paths-MUXHUOCM.js} +8 -2
- package/dist/{pay-XAWW3NV3.js → pay-MUV2U232.js} +18 -16
- package/dist/payments-4D27K4L2.js +48 -0
- package/dist/payments-4D27K4L2.js.map +1 -0
- package/dist/{send-HESQYRKM.js → send-BXHFKDBF.js} +10 -10
- package/dist/{status-ANZPRZJJ.js → status-3Z3YPRSE.js} +6 -6
- package/dist/{status-line-J3TUWVRQ.js → status-line-CKRMGZ3Q.js} +7 -7
- package/dist/{status-line-wiring-HSV7DXO5.js → status-line-wiring-GECLIIBT.js} +5 -5
- package/dist/tenjin-daemon.mjs +57 -6
- package/dist/{uninstall-GUU34YKP.js → uninstall-BZTVWJ7W.js} +11 -11
- package/dist/{update-KO2NZRJ5.js → update-IQQTEOI5.js} +6 -6
- package/dist/{wallet-3URC5QPK.js → wallet-UFXQ57TZ.js} +10 -10
- package/docs/agent-permissions.md +4 -2
- package/docs/safety-model.md +2 -2
- package/package.json +1 -1
- package/dist/chunk-2E6GVIRP.js.map +0 -1
- package/dist/chunk-2G2WLVHB.js.map +0 -1
- package/dist/chunk-3KKKB2AQ.js +0 -40
- package/dist/chunk-3KKKB2AQ.js.map +0 -1
- package/dist/chunk-4AS52HUG.js.map +0 -1
- package/dist/chunk-4M5FBWT5.js.map +0 -1
- package/dist/chunk-5KD5HRAJ.js.map +0 -1
- package/dist/chunk-7ACHDNJA.js.map +0 -1
- package/dist/chunk-NSG5TVZQ.js.map +0 -1
- package/dist/chunk-PO4HAXAW.js.map +0 -1
- package/dist/chunk-TU7XH3JJ.js.map +0 -1
- package/dist/chunk-YREKMJPP.js.map +0 -1
- package/dist/hook-command-U5XPEHAJ.js.map +0 -1
- /package/dist/{chunk-HH3PDYIG.js.map → chunk-3EUTWC2B.js.map} +0 -0
- /package/dist/{chunk-BTX2QE2Y.js.map → chunk-AQRUD5GQ.js.map} +0 -0
- /package/dist/{chunk-CXUYCDPX.js.map → chunk-C363JZN2.js.map} +0 -0
- /package/dist/{chunk-RPR2C2JO.js.map → chunk-GHTPYKDT.js.map} +0 -0
- /package/dist/{chunk-5FYKPQNX.js.map → chunk-IOIHYOU4.js.map} +0 -0
- /package/dist/{chunk-LN2HISWU.js.map → chunk-JN7TMXVF.js.map} +0 -0
- /package/dist/{chunk-LI44XLMB.js.map → chunk-PJEG2JIJ.js.map} +0 -0
- /package/dist/{chunk-72UHZRG6.js.map → chunk-QRFONFRW.js.map} +0 -0
- /package/dist/{chunk-YEBNE5NW.js.map → chunk-YVODPFTL.js.map} +0 -0
- /package/dist/{config-KMJLFPSI.js.map → config-MSN6H4MD.js.map} +0 -0
- /package/dist/{fund-LT6ZPGEQ.js.map → fund-XPB4IIG5.js.map} +0 -0
- /package/dist/{install-MMNXJ5LM.js.map → install-OSJRM2ME.js.map} +0 -0
- /package/dist/{install-identity-B7FVIWML.js.map → install-identity-YIWKQOUD.js.map} +0 -0
- /package/dist/{install-wallet-XMVUBCHS.js.map → install-wallet-BWJO2SUC.js.map} +0 -0
- /package/dist/{paths-LRMWNTJP.js.map → paths-MUXHUOCM.js.map} +0 -0
- /package/dist/{pay-XAWW3NV3.js.map → pay-MUV2U232.js.map} +0 -0
- /package/dist/{send-HESQYRKM.js.map → send-BXHFKDBF.js.map} +0 -0
- /package/dist/{status-ANZPRZJJ.js.map → status-3Z3YPRSE.js.map} +0 -0
- /package/dist/{status-line-J3TUWVRQ.js.map → status-line-CKRMGZ3Q.js.map} +0 -0
- /package/dist/{status-line-wiring-HSV7DXO5.js.map → status-line-wiring-GECLIIBT.js.map} +0 -0
- /package/dist/{uninstall-GUU34YKP.js.map → uninstall-BZTVWJ7W.js.map} +0 -0
- /package/dist/{update-KO2NZRJ5.js.map → update-IQQTEOI5.js.map} +0 -0
- /package/dist/{wallet-3URC5QPK.js.map → wallet-UFXQ57TZ.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/codegen/code.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/codegen/scope.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/codegen/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/util.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/names.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/errors.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/validate/boolSchema.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/rules.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/validate/applicability.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/validate/dataType.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/validate/defaults.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/code.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/validate/keyword.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/validate/subschema.ts","../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js","../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/resolve.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/validate/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/runtime/validation_error.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/ref_error.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/compile/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json","../node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/lib/utils.js","../node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/lib/schemes.js","../node_modules/.pnpm/fast-uri@3.1.8/node_modules/fast-uri/index.js","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/runtime/uri.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/core.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/core/id.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/core/ref.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/core/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/runtime/ucs2length.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/limitLength.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/pattern.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/required.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/limitItems.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/runtime/equal.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/const.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/enum.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/items.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/items2020.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/contains.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/properties.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/not.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/allOf.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/if.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/dynamic/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/validation/limitContains.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/next.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/unevaluated/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/format/format.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/format/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/metadata.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/draft2020.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/discriminator/types.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/discriminator/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/2020.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/vocabularies/draft7.ts","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json","../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/lib/ajv.ts","../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/src/formats.ts","../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/src/limit.ts","../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/src/index.ts","../src/commands/pay.ts","../src/lib/bazaar.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/http/types.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/mcp/types.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/types.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/http/resourceService.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/mcp/resourceService.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/resourceService.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/server.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/facilitator.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/v1/facilitator.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/startupValidation.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/facilitatorClient.ts","../src/lib/request-schema.ts","../src/lib/spend-gate.ts","../node_modules/.pnpm/@x402+core@2.17.0/node_modules/@x402/core/src/client/x402Client.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/constants.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/auth-capture/constants.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/auth-capture/client/scheme.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/auth-capture/nonce.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/auth-capture/utils.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/utils.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/constants.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/utils.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/errors.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/abi.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/shared/extensions/builderCode.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/extensions.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/shared/extensions/gasSponsoring.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/client/eip2612.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/client/erc20approval.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/shared/rpc.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/v1/client/scheme.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/v1/facilitator/scheme.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/facilitator/eip3009-utils.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/v1/index.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/shared/permit2.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/shared/erc20approval.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/upto/facilitator/errors.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/client/permit2.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/client/eip3009.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/client/scheme.ts","../node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/src/exact/client/register.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/builder-code/types.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/builder-code/cbor.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/builder-code/server.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/builder-code/client.ts","../node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/src/builder-code/facilitator.ts","../src/lib/x402-pay.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nexport abstract class _CodeOrName {\n abstract readonly str: string\n abstract readonly names: UsedNames\n abstract toString(): string\n abstract emptyStr(): boolean\n}\n\nexport const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i\n\nexport class Name extends _CodeOrName {\n readonly str: string\n constructor(s: string) {\n super()\n if (!IDENTIFIER.test(s)) throw new Error(\"CodeGen: name must be a valid identifier\")\n this.str = s\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n return false\n }\n\n get names(): UsedNames {\n return {[this.str]: 1}\n }\n}\n\nexport class _Code extends _CodeOrName {\n readonly _items: readonly CodeItem[]\n private _str?: string\n private _names?: UsedNames\n\n constructor(code: string | readonly CodeItem[]) {\n super()\n this._items = typeof code === \"string\" ? [code] : code\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n if (this._items.length > 1) return false\n const item = this._items[0]\n return item === \"\" || item === '\"\"'\n }\n\n get str(): string {\n return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, \"\"))\n }\n\n get names(): UsedNames {\n return (this._names ??= this._items.reduce((names: UsedNames, c) => {\n if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1\n return names\n }, {}))\n }\n}\n\nexport type CodeItem = Name | string | number | boolean | null\n\nexport type UsedNames = Record<string, number | undefined>\n\nexport type Code = _Code | Name\n\nexport type SafeExpr = Code | number | boolean | null\n\nexport const nil = new _Code(\"\")\n\ntype CodeArg = SafeExpr | string | undefined\n\nexport function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {\n const code: CodeItem[] = [strs[0]]\n let i = 0\n while (i < args.length) {\n addCodeArg(code, args[i])\n code.push(strs[++i])\n }\n return new _Code(code)\n}\n\nconst plus = new _Code(\"+\")\n\nexport function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {\n const expr: CodeItem[] = [safeStringify(strs[0])]\n let i = 0\n while (i < args.length) {\n expr.push(plus)\n addCodeArg(expr, args[i])\n expr.push(plus, safeStringify(strs[++i]))\n }\n optimize(expr)\n return new _Code(expr)\n}\n\nexport function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {\n if (arg instanceof _Code) code.push(...arg._items)\n else if (arg instanceof Name) code.push(arg)\n else code.push(interpolate(arg))\n}\n\nfunction optimize(expr: CodeItem[]): void {\n let i = 1\n while (i < expr.length - 1) {\n if (expr[i] === plus) {\n const res = mergeExprItems(expr[i - 1], expr[i + 1])\n if (res !== undefined) {\n expr.splice(i - 1, 3, res)\n continue\n }\n expr[i++] = \"+\"\n }\n i++\n }\n}\n\nfunction mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {\n if (b === '\"\"') return a\n if (a === '\"\"') return b\n if (typeof a == \"string\") {\n if (b instanceof Name || a[a.length - 1] !== '\"') return\n if (typeof b != \"string\") return `${a.slice(0, -1)}${b}\"`\n if (b[0] === '\"') return a.slice(0, -1) + b.slice(1)\n return\n }\n if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name)) return `\"${a}${b.slice(1)}`\n return\n}\n\nexport function strConcat(c1: Code, c2: Code): Code {\n return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`\n}\n\n// TODO do not allow arrays here\nfunction interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {\n return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n ? x\n : safeStringify(Array.isArray(x) ? x.join(\",\") : x)\n}\n\nexport function stringify(x: unknown): Code {\n return new _Code(safeStringify(x))\n}\n\nexport function safeStringify(x: unknown): string {\n return JSON.stringify(x)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\")\n}\n\nexport function getProperty(key: Code | string | number): Code {\n return typeof key == \"string\" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`\n}\n\n//Does best effort to format the name properly\nexport function getEsmExportName(key: Code | string | number): Code {\n if (typeof key == \"string\" && IDENTIFIER.test(key)) {\n return new _Code(`${key}`)\n }\n throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)\n}\n\nexport function regexpCode(rx: RegExp): Code {\n return new _Code(rx.toString())\n}\n","import {_, nil, Code, Name} from \"./code\"\n\ninterface NameGroup {\n prefix: string\n index: number\n}\n\nexport interface NameValue {\n ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure\n key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used\n code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)\n}\n\nexport type ValueReference = unknown // possibly make CodeGen parameterized type on this type\n\nclass ValueError extends Error {\n readonly value?: NameValue\n constructor(name: ValueScopeName) {\n super(`CodeGen: \"code\" for ${name} not defined`)\n this.value = name.value\n }\n}\n\ninterface ScopeOptions {\n prefixes?: Set<string>\n parent?: Scope\n}\n\ninterface ValueScopeOptions extends ScopeOptions {\n scope: ScopeStore\n es5?: boolean\n lines?: boolean\n}\n\nexport type ScopeStore = Record<string, ValueReference[] | undefined>\n\ntype ScopeValues = {\n [Prefix in string]?: Map<unknown, ValueScopeName>\n}\n\nexport type ScopeValueSets = {\n [Prefix in string]?: Set<ValueScopeName>\n}\n\nexport enum UsedValueState {\n Started,\n Completed,\n}\n\nexport type UsedScopeValues = {\n [Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>\n}\n\nexport const varKinds = {\n const: new Name(\"const\"),\n let: new Name(\"let\"),\n var: new Name(\"var\"),\n}\n\nexport class Scope {\n protected readonly _names: {[Prefix in string]?: NameGroup} = {}\n protected readonly _prefixes?: Set<string>\n protected readonly _parent?: Scope\n\n constructor({prefixes, parent}: ScopeOptions = {}) {\n this._prefixes = prefixes\n this._parent = parent\n }\n\n toName(nameOrPrefix: Name | string): Name {\n return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)\n }\n\n name(prefix: string): Name {\n return new Name(this._newName(prefix))\n }\n\n protected _newName(prefix: string): string {\n const ng = this._names[prefix] || this._nameGroup(prefix)\n return `${prefix}${ng.index++}`\n }\n\n private _nameGroup(prefix: string): NameGroup {\n if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {\n throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`)\n }\n return (this._names[prefix] = {prefix, index: 0})\n }\n}\n\ninterface ScopePath {\n property: string\n itemIndex: number\n}\n\nexport class ValueScopeName extends Name {\n readonly prefix: string\n value?: NameValue\n scopePath?: Code\n\n constructor(prefix: string, nameStr: string) {\n super(nameStr)\n this.prefix = prefix\n }\n\n setValue(value: NameValue, {property, itemIndex}: ScopePath): void {\n this.value = value\n this.scopePath = _`.${new Name(property)}[${itemIndex}]`\n }\n}\n\ninterface VSOptions extends ValueScopeOptions {\n _n: Code\n}\n\nconst line = _`\\n`\n\nexport class ValueScope extends Scope {\n protected readonly _values: ScopeValues = {}\n protected readonly _scope: ScopeStore\n readonly opts: VSOptions\n\n constructor(opts: ValueScopeOptions) {\n super(opts)\n this._scope = opts.scope\n this.opts = {...opts, _n: opts.lines ? line : nil}\n }\n\n get(): ScopeStore {\n return this._scope\n }\n\n name(prefix: string): ValueScopeName {\n return new ValueScopeName(prefix, this._newName(prefix))\n }\n\n value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {\n if (value.ref === undefined) throw new Error(\"CodeGen: ref must be passed in value\")\n const name = this.toName(nameOrPrefix) as ValueScopeName\n const {prefix} = name\n const valueKey = value.key ?? value.ref\n let vs = this._values[prefix]\n if (vs) {\n const _name = vs.get(valueKey)\n if (_name) return _name\n } else {\n vs = this._values[prefix] = new Map()\n }\n vs.set(valueKey, name)\n\n const s = this._scope[prefix] || (this._scope[prefix] = [])\n const itemIndex = s.length\n s[itemIndex] = value.ref\n name.setValue(value, {property: prefix, itemIndex})\n return name\n }\n\n getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n const vs = this._values[prefix]\n if (!vs) return\n return vs.get(keyOrRef)\n }\n\n scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {\n return this._reduceValues(values, (name: ValueScopeName) => {\n if (name.scopePath === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return _`${scopeName}${name.scopePath}`\n })\n }\n\n scopeCode(\n values: ScopeValues | ScopeValueSets = this._values,\n usedValues?: UsedScopeValues,\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n return this._reduceValues(\n values,\n (name: ValueScopeName) => {\n if (name.value === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return name.value.code\n },\n usedValues,\n getCode\n )\n }\n\n private _reduceValues(\n values: ScopeValues | ScopeValueSets,\n valueCode: (n: ValueScopeName) => Code | undefined,\n usedValues: UsedScopeValues = {},\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n let code: Code = nil\n for (const prefix in values) {\n const vs = values[prefix]\n if (!vs) continue\n const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())\n vs.forEach((name: ValueScopeName) => {\n if (nameSet.has(name)) return\n nameSet.set(name, UsedValueState.Started)\n let c = valueCode(name)\n if (c) {\n const def = this.opts.es5 ? varKinds.var : varKinds.const\n code = _`${code}${def} ${name} = ${c};${this.opts._n}`\n } else if ((c = getCode?.(name))) {\n code = _`${code}${c}${this.opts._n}`\n } else {\n throw new ValueError(name)\n }\n nameSet.set(name, UsedValueState.Completed)\n })\n }\n return code\n }\n}\n","import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from \"./scope\"\nimport {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from \"./code\"\nimport {Scope, varKinds} from \"./scope\"\n\nexport {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from \"./code\"\nexport {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from \"./scope\"\n\n// type for expressions that can be safely inserted in code without quotes\nexport type SafeExpr = Code | number | boolean | null\n\n// type that is either Code of function that adds code to CodeGen instance using its methods\nexport type Block = Code | (() => void)\n\nexport const operators = {\n GT: new _Code(\">\"),\n GTE: new _Code(\">=\"),\n LT: new _Code(\"<\"),\n LTE: new _Code(\"<=\"),\n EQ: new _Code(\"===\"),\n NEQ: new _Code(\"!==\"),\n NOT: new _Code(\"!\"),\n OR: new _Code(\"||\"),\n AND: new _Code(\"&&\"),\n ADD: new _Code(\"+\"),\n}\n\nabstract class Node {\n abstract readonly names: UsedNames\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n return this\n }\n\n optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {\n return this\n }\n\n // get count(): number {\n // return 1\n // }\n}\n\nclass Def extends Node {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private rhs?: SafeExpr\n ) {\n super()\n }\n\n render({es5, _n}: CGOptions): string {\n const varKind = es5 ? varKinds.var : this.varKind\n const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`\n return `${varKind} ${this.name}${rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!names[this.name.str]) return\n if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.rhs instanceof _CodeOrName ? this.rhs.names : {}\n }\n}\n\nclass Assign extends Node {\n constructor(\n readonly lhs: Code,\n public rhs: SafeExpr,\n private readonly sideEffects?: boolean\n ) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} = ${this.rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return\n this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = this.lhs instanceof Name ? {} : {...this.lhs.names}\n return addExprNames(names, this.rhs)\n }\n}\n\nclass AssignOp extends Assign {\n constructor(\n lhs: Code,\n private readonly op: Code,\n rhs: SafeExpr,\n sideEffects?: boolean\n ) {\n super(lhs, rhs, sideEffects)\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} ${this.op}= ${this.rhs};` + _n\n }\n}\n\nclass Label extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label: Name) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.label}:` + _n\n }\n}\n\nclass Break extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label?: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n const label = this.label ? ` ${this.label}` : \"\"\n return `break${label};` + _n\n }\n}\n\nclass Throw extends Node {\n constructor(readonly error: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `throw ${this.error};` + _n\n }\n\n get names(): UsedNames {\n return this.error.names\n }\n}\n\nclass AnyCode extends Node {\n constructor(private code: SafeExpr) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.code};` + _n\n }\n\n optimizeNodes(): this | undefined {\n return `${this.code}` ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n this.code = optimizeExpr(this.code, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.code instanceof _CodeOrName ? this.code.names : {}\n }\n}\n\nabstract class ParentNode extends Node {\n constructor(readonly nodes: ChildNode[] = []) {\n super()\n }\n\n render(opts: CGOptions): string {\n return this.nodes.reduce((code, n) => code + n.render(opts), \"\")\n }\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n const n = nodes[i].optimizeNodes()\n if (Array.isArray(n)) nodes.splice(i, 1, ...n)\n else if (n) nodes[i] = n\n else nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n // iterating backwards improves 1-pass optimization\n const n = nodes[i]\n if (n.optimizeNames(names, constants)) continue\n subtractNames(names, n.names)\n nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n get names(): UsedNames {\n return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})\n }\n\n // get count(): number {\n // return this.nodes.reduce((c, n) => c + n.count, 1)\n // }\n}\n\nabstract class BlockNode extends ParentNode {\n render(opts: CGOptions): string {\n return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n\n }\n}\n\nclass Root extends ParentNode {}\n\nclass Else extends BlockNode {\n static readonly kind = \"else\"\n}\n\nclass If extends BlockNode {\n static readonly kind = \"if\"\n else?: If | Else\n constructor(\n private condition: Code | boolean,\n nodes?: ChildNode[]\n ) {\n super(nodes)\n }\n\n render(opts: CGOptions): string {\n let code = `if(${this.condition})` + super.render(opts)\n if (this.else) code += \"else \" + this.else.render(opts)\n return code\n }\n\n optimizeNodes(): If | ChildNode[] | undefined {\n super.optimizeNodes()\n const cond = this.condition\n if (cond === true) return this.nodes // else is ignored here\n let e = this.else\n if (e) {\n const ns = e.optimizeNodes()\n e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)\n }\n if (e) {\n if (cond === false) return e instanceof If ? e : e.nodes\n if (this.nodes.length) return this\n return new If(not(cond), e instanceof If ? [e] : e.nodes)\n }\n if (cond === false || !this.nodes.length) return undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n this.else = this.else?.optimizeNames(names, constants)\n if (!(super.optimizeNames(names, constants) || this.else)) return\n this.condition = optimizeExpr(this.condition, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n addExprNames(names, this.condition)\n if (this.else) addNames(names, this.else.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.else?.count || 0)\n // }\n}\n\nabstract class For extends BlockNode {\n static readonly kind = \"for\"\n}\n\nclass ForLoop extends For {\n constructor(private iteration: Code) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.iteration})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iteration = optimizeExpr(this.iteration, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iteration.names)\n }\n}\n\nclass ForRange extends For {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private readonly from: SafeExpr,\n private readonly to: SafeExpr\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const varKind = opts.es5 ? varKinds.var : this.varKind\n const {name, from, to} = this\n return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)\n }\n\n get names(): UsedNames {\n const names = addExprNames(super.names, this.from)\n return addExprNames(names, this.to)\n }\n}\n\nclass ForIter extends For {\n constructor(\n private readonly loop: \"of\" | \"in\",\n private readonly varKind: Name,\n private readonly name: Name,\n private iterable: Code\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iterable = optimizeExpr(this.iterable, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iterable.names)\n }\n}\n\nclass Func extends BlockNode {\n static readonly kind = \"func\"\n constructor(\n public name: Name,\n public args: Code,\n public async?: boolean\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const _async = this.async ? \"async \" : \"\"\n return `${_async}function ${this.name}(${this.args})` + super.render(opts)\n }\n}\n\nclass Return extends ParentNode {\n static readonly kind = \"return\"\n\n render(opts: CGOptions): string {\n return \"return \" + super.render(opts)\n }\n}\n\nclass Try extends BlockNode {\n catch?: Catch\n finally?: Finally\n\n render(opts: CGOptions): string {\n let code = \"try\" + super.render(opts)\n if (this.catch) code += this.catch.render(opts)\n if (this.finally) code += this.finally.render(opts)\n return code\n }\n\n optimizeNodes(): this {\n super.optimizeNodes()\n this.catch?.optimizeNodes() as Catch | undefined\n this.finally?.optimizeNodes() as Finally | undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n super.optimizeNames(names, constants)\n this.catch?.optimizeNames(names, constants)\n this.finally?.optimizeNames(names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n if (this.catch) addNames(names, this.catch.names)\n if (this.finally) addNames(names, this.finally.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)\n // }\n}\n\nclass Catch extends BlockNode {\n static readonly kind = \"catch\"\n constructor(readonly error: Name) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `catch(${this.error})` + super.render(opts)\n }\n}\n\nclass Finally extends BlockNode {\n static readonly kind = \"finally\"\n render(opts: CGOptions): string {\n return \"finally\" + super.render(opts)\n }\n}\n\ntype StartBlockNode = If | For | Func | Return | Try\n\ntype LeafNode = Def | Assign | Label | Break | Throw | AnyCode\n\ntype ChildNode = StartBlockNode | LeafNode\n\ntype EndBlockNodeType =\n | typeof If\n | typeof Else\n | typeof For\n | typeof Func\n | typeof Return\n | typeof Catch\n | typeof Finally\n\ntype Constants = Record<string, SafeExpr | undefined>\n\nexport interface CodeGenOptions {\n es5?: boolean\n lines?: boolean\n ownProperties?: boolean\n}\n\ninterface CGOptions extends CodeGenOptions {\n _n: \"\\n\" | \"\"\n}\n\nexport class CodeGen {\n readonly _scope: Scope\n readonly _extScope: ValueScope\n readonly _values: ScopeValueSets = {}\n private readonly _nodes: ParentNode[]\n private readonly _blockStarts: number[] = []\n private readonly _constants: Constants = {}\n private readonly opts: CGOptions\n\n constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {\n this.opts = {...opts, _n: opts.lines ? \"\\n\" : \"\"}\n this._extScope = extScope\n this._scope = new Scope({parent: extScope})\n this._nodes = [new Root()]\n }\n\n toString(): string {\n return this._root.render(this.opts)\n }\n\n // returns unique name in the internal scope\n name(prefix: string): Name {\n return this._scope.name(prefix)\n }\n\n // reserves unique name in the external scope\n scopeName(prefix: string): ValueScopeName {\n return this._extScope.name(prefix)\n }\n\n // reserves unique name in the external scope and assigns value to it\n scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {\n const name = this._extScope.value(prefixOrName, value)\n const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())\n vs.add(name)\n return name\n }\n\n getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n return this._extScope.getValue(prefix, keyOrRef)\n }\n\n // return code that assigns values in the external scope to the names that are used internally\n // (same names that were returned by gen.scopeName or gen.scopeValue)\n scopeRefs(scopeName: Name): Code {\n return this._extScope.scopeRefs(scopeName, this._values)\n }\n\n scopeCode(): Code {\n return this._extScope.scopeCode(this._values)\n }\n\n private _def(\n varKind: Name,\n nameOrPrefix: Name | string,\n rhs?: SafeExpr,\n constant?: boolean\n ): Name {\n const name = this._scope.toName(nameOrPrefix)\n if (rhs !== undefined && constant) this._constants[name.str] = rhs\n this._leafNode(new Def(varKind, name, rhs))\n return name\n }\n\n // `const` declaration (`var` in es5 mode)\n const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.const, nameOrPrefix, rhs, _constant)\n }\n\n // `let` declaration with optional assignment (`var` in es5 mode)\n let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.let, nameOrPrefix, rhs, _constant)\n }\n\n // `var` declaration with optional assignment\n var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.var, nameOrPrefix, rhs, _constant)\n }\n\n // assignment code\n assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {\n return this._leafNode(new Assign(lhs, rhs, sideEffects))\n }\n\n // `+=` code\n add(lhs: Code, rhs: SafeExpr): CodeGen {\n return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))\n }\n\n // appends passed SafeExpr to code or executes Block\n code(c: Block | SafeExpr): CodeGen {\n if (typeof c == \"function\") c()\n else if (c !== nil) this._leafNode(new AnyCode(c))\n return this\n }\n\n // returns code for object literal for the passed argument list of key-value pairs\n object(...keyValues: [Name | string, SafeExpr | string][]): _Code {\n const code: CodeItem[] = [\"{\"]\n for (const [key, value] of keyValues) {\n if (code.length > 1) code.push(\",\")\n code.push(key)\n if (key !== value || this.opts.es5) {\n code.push(\":\")\n addCodeArg(code, value)\n }\n }\n code.push(\"}\")\n return new _Code(code)\n }\n\n // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {\n this._blockNode(new If(condition))\n\n if (thenBody && elseBody) {\n this.code(thenBody).else().code(elseBody).endIf()\n } else if (thenBody) {\n this.code(thenBody).endIf()\n } else if (elseBody) {\n throw new Error('CodeGen: \"else\" body without \"then\" body')\n }\n return this\n }\n\n // `else if` clause - invalid without `if` or after `else` clauses\n elseIf(condition: Code | boolean): CodeGen {\n return this._elseNode(new If(condition))\n }\n\n // `else` clause - only valid after `if` or `else if` clauses\n else(): CodeGen {\n return this._elseNode(new Else())\n }\n\n // end `if` statement (needed if gen.if was used only with condition)\n endIf(): CodeGen {\n return this._endBlockNode(If, Else)\n }\n\n private _for(node: For, forBody?: Block): CodeGen {\n this._blockNode(node)\n if (forBody) this.code(forBody).endFor()\n return this\n }\n\n // a generic `for` clause (or statement if `forBody` is passed)\n for(iteration: Code, forBody?: Block): CodeGen {\n return this._for(new ForLoop(iteration), forBody)\n }\n\n // `for` statement for a range of values\n forRange(\n nameOrPrefix: Name | string,\n from: SafeExpr,\n to: SafeExpr,\n forBody: (index: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForRange(varKind, name, from, to), () => forBody(name))\n }\n\n // `for-of` statement (in es5 mode replace with a normal for loop)\n forOf(\n nameOrPrefix: Name | string,\n iterable: Code,\n forBody: (item: Name) => void,\n varKind: Code = varKinds.const\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n if (this.opts.es5) {\n const arr = iterable instanceof Name ? iterable : this.var(\"_arr\", iterable)\n return this.forRange(\"_i\", 0, _`${arr}.length`, (i) => {\n this.var(name, _`${arr}[${i}]`)\n forBody(name)\n })\n }\n return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name))\n }\n\n // `for-in` statement.\n // With option `ownProperties` replaced with a `for-of` loop for object keys\n forIn(\n nameOrPrefix: Name | string,\n obj: Code,\n forBody: (item: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const\n ): CodeGen {\n if (this.opts.ownProperties) {\n return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)\n }\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name))\n }\n\n // end `for` loop\n endFor(): CodeGen {\n return this._endBlockNode(For)\n }\n\n // `label` statement\n label(label: Name): CodeGen {\n return this._leafNode(new Label(label))\n }\n\n // `break` statement\n break(label?: Code): CodeGen {\n return this._leafNode(new Break(label))\n }\n\n // `return` statement\n return(value: Block | SafeExpr): CodeGen {\n const node = new Return()\n this._blockNode(node)\n this.code(value)\n if (node.nodes.length !== 1) throw new Error('CodeGen: \"return\" should have one node')\n return this._endBlockNode(Return)\n }\n\n // `try` statement\n try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {\n if (!catchCode && !finallyCode) throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"')\n const node = new Try()\n this._blockNode(node)\n this.code(tryBody)\n if (catchCode) {\n const error = this.name(\"e\")\n this._currNode = node.catch = new Catch(error)\n catchCode(error)\n }\n if (finallyCode) {\n this._currNode = node.finally = new Finally()\n this.code(finallyCode)\n }\n return this._endBlockNode(Catch, Finally)\n }\n\n // `throw` statement\n throw(error: Code): CodeGen {\n return this._leafNode(new Throw(error))\n }\n\n // start self-balancing block\n block(body?: Block, nodeCount?: number): CodeGen {\n this._blockStarts.push(this._nodes.length)\n if (body) this.code(body).endBlock(nodeCount)\n return this\n }\n\n // end the current self-balancing block\n endBlock(nodeCount?: number): CodeGen {\n const len = this._blockStarts.pop()\n if (len === undefined) throw new Error(\"CodeGen: not in self-balancing block\")\n const toClose = this._nodes.length - len\n if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)\n }\n this._nodes.length = len\n return this\n }\n\n // `function` heading (or definition if funcBody is passed)\n func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {\n this._blockNode(new Func(name, args, async))\n if (funcBody) this.code(funcBody).endFunc()\n return this\n }\n\n // end function definition\n endFunc(): CodeGen {\n return this._endBlockNode(Func)\n }\n\n optimize(n = 1): void {\n while (n-- > 0) {\n this._root.optimizeNodes()\n this._root.optimizeNames(this._root.names, this._constants)\n }\n }\n\n private _leafNode(node: LeafNode): CodeGen {\n this._currNode.nodes.push(node)\n return this\n }\n\n private _blockNode(node: StartBlockNode): void {\n this._currNode.nodes.push(node)\n this._nodes.push(node)\n }\n\n private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {\n const n = this._currNode\n if (n instanceof N1 || (N2 && n instanceof N2)) {\n this._nodes.pop()\n return this\n }\n throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`)\n }\n\n private _elseNode(node: If | Else): CodeGen {\n const n = this._currNode\n if (!(n instanceof If)) {\n throw new Error('CodeGen: \"else\" without \"if\"')\n }\n this._currNode = n.else = node\n return this\n }\n\n private get _root(): Root {\n return this._nodes[0] as Root\n }\n\n private get _currNode(): ParentNode {\n const ns = this._nodes\n return ns[ns.length - 1]\n }\n\n private set _currNode(node: ParentNode) {\n const ns = this._nodes\n ns[ns.length - 1] = node\n }\n\n // get nodeCount(): number {\n // return this._root.count\n // }\n}\n\nfunction addNames(names: UsedNames, from: UsedNames): UsedNames {\n for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)\n return names\n}\n\nfunction addExprNames(names: UsedNames, from: SafeExpr): UsedNames {\n return from instanceof _CodeOrName ? addNames(names, from.names) : names\n}\n\nfunction optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T\nfunction optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {\n if (expr instanceof Name) return replaceName(expr)\n if (!canOptimize(expr)) return expr\n return new _Code(\n expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {\n if (c instanceof Name) c = replaceName(c)\n if (c instanceof _Code) items.push(...c._items)\n else items.push(c)\n return items\n }, [])\n )\n\n function replaceName(n: Name): SafeExpr {\n const c = constants[n.str]\n if (c === undefined || names[n.str] !== 1) return n\n delete names[n.str]\n return c\n }\n\n function canOptimize(e: SafeExpr): e is _Code {\n return (\n e instanceof _Code &&\n e._items.some(\n (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined\n )\n )\n }\n}\n\nfunction subtractNames(names: UsedNames, from: UsedNames): void {\n for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)\n}\n\nexport function not<T extends Code | SafeExpr>(x: T): T\nexport function not(x: Code | SafeExpr): Code | SafeExpr {\n return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : _`!${par(x)}`\n}\n\nconst andCode = mappend(operators.AND)\n\n// boolean AND (&&) expression with the passed arguments\nexport function and(...args: Code[]): Code {\n return args.reduce(andCode)\n}\n\nconst orCode = mappend(operators.OR)\n\n// boolean OR (||) expression with the passed arguments\nexport function or(...args: Code[]): Code {\n return args.reduce(orCode)\n}\n\ntype MAppend = (x: Code, y: Code) => Code\n\nfunction mappend(op: Code): MAppend {\n return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)\n}\n\nfunction par(x: Code): Code {\n return x instanceof Name ? x : _`(${x})`\n}\n","import type {AnySchema, EvaluatedProperties, EvaluatedItems} from \"../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \".\"\nimport {_, getProperty, Code, Name, CodeGen} from \"./codegen\"\nimport {_Code} from \"./codegen/code\"\nimport type {Rule, ValidationRules} from \"./rules\"\n\n// TODO refactor to use Set\nexport function toHash<T extends string = string>(arr: T[]): {[K in T]?: true} {\n const hash: {[K in T]?: true} = {}\n for (const item of arr) hash[item] = true\n return hash\n}\n\nexport function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {\n if (typeof schema == \"boolean\") return schema\n if (Object.keys(schema).length === 0) return true\n checkUnknownRules(it, schema)\n return !schemaHasRules(schema, it.self.RULES.all)\n}\n\nexport function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {\n const {opts, self} = it\n if (!opts.strictSchema) return\n if (typeof schema === \"boolean\") return\n const rules = self.RULES.keywords\n for (const key in schema) {\n if (!rules[key]) checkStrictMode(it, `unknown keyword: \"${key}\"`)\n }\n}\n\nexport function schemaHasRules(\n schema: AnySchema,\n rules: {[Key in string]?: boolean | Rule}\n): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (rules[key]) return true\n return false\n}\n\nexport function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (key !== \"$ref\" && RULES.all[key]) return true\n return false\n}\n\nexport function schemaRefOrVal(\n {topSchemaRef, schemaPath}: SchemaObjCxt,\n schema: unknown,\n keyword: string,\n $data?: string | false\n): Code | number | boolean {\n if (!$data) {\n if (typeof schema == \"number\" || typeof schema == \"boolean\") return schema\n if (typeof schema == \"string\") return _`${schema}`\n }\n return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`\n}\n\nexport function unescapeFragment(str: string): string {\n return unescapeJsonPointer(decodeURIComponent(str))\n}\n\nexport function escapeFragment(str: string | number): string {\n return encodeURIComponent(escapeJsonPointer(str))\n}\n\nexport function escapeJsonPointer(str: string | number): string {\n if (typeof str == \"number\") return `${str}`\n return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")\n}\n\nexport function unescapeJsonPointer(str: string): string {\n return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n}\n\nexport function eachItem<T>(xs: T | T[], f: (x: T) => void): void {\n if (Array.isArray(xs)) {\n for (const x of xs) f(x)\n } else {\n f(xs)\n }\n}\n\ntype SomeEvaluated = EvaluatedProperties | EvaluatedItems\n\ntype MergeEvaluatedFunc<T extends SomeEvaluated> = (\n gen: CodeGen,\n from: Name | T,\n to: Name | Exclude<T, true> | undefined,\n toName?: typeof Name\n) => Name | T\n\ninterface MakeMergeFuncArgs<T extends SomeEvaluated> {\n mergeNames: (gen: CodeGen, from: Name, to: Name) => void\n mergeToName: (gen: CodeGen, from: T, to: Name) => void\n mergeValues: (from: T, to: Exclude<T, true>) => T\n resultToName: (gen: CodeGen, res?: T) => Name\n}\n\nfunction makeMergeEvaluated<T extends SomeEvaluated>({\n mergeNames,\n mergeToName,\n mergeValues,\n resultToName,\n}: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {\n return (gen, from, to, toName) => {\n const res =\n to === undefined\n ? from\n : to instanceof Name\n ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n : from instanceof Name\n ? (mergeToName(gen, to, from), from)\n : mergeValues(from, to)\n return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res\n }\n}\n\ninterface MergeEvaluated {\n props: MergeEvaluatedFunc<EvaluatedProperties>\n items: MergeEvaluatedFunc<EvaluatedItems>\n}\n\nexport const mergeEvaluated: MergeEvaluated = {\n props: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () => {\n gen.if(\n _`${from} === true`,\n () => gen.assign(to, true),\n () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)\n )\n }),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () => {\n if (from === true) {\n gen.assign(to, true)\n } else {\n gen.assign(to, _`${to} || {}`)\n setEvaluated(gen, to, from)\n }\n }),\n mergeValues: (from, to) => (from === true ? true : {...from, ...to}),\n resultToName: evaluatedPropsToName,\n }),\n items: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () =>\n gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () =>\n gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n resultToName: (gen, items) => gen.var(\"items\", items),\n }),\n}\n\nexport function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {\n if (ps === true) return gen.var(\"props\", true)\n const props = gen.var(\"props\", _`{}`)\n if (ps !== undefined) setEvaluated(gen, props, ps)\n return props\n}\n\nexport function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {\n Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))\n}\n\nconst snippets: {[S in string]?: _Code} = {}\n\nexport function useFunc(gen: CodeGen, f: {code: string}): Name {\n return gen.scopeValue(\"func\", {\n ref: f,\n code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),\n })\n}\n\nexport enum Type {\n Num,\n Str,\n}\n\nexport function getErrorPath(\n dataProp: Name | string | number,\n dataPropType?: Type,\n jsPropertySyntax?: boolean\n): Code | string {\n // let path\n if (dataProp instanceof Name) {\n const isNumber = dataPropType === Type.Num\n return jsPropertySyntax\n ? isNumber\n ? _`\"[\" + ${dataProp} + \"]\"`\n : _`\"['\" + ${dataProp} + \"']\"`\n : isNumber\n ? _`\"/\" + ${dataProp}`\n : _`\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")` // TODO maybe use global escapePointer\n }\n return jsPropertySyntax ? getProperty(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp)\n}\n\nexport function checkStrictMode(\n it: SchemaCxt,\n msg: string,\n mode: boolean | \"log\" = it.opts.strictSchema\n): void {\n if (!mode) return\n msg = `strict mode: ${msg}`\n if (mode === true) throw new Error(msg)\n it.self.logger.warn(msg)\n}\n","import {Name} from \"./codegen\"\n\nconst names = {\n // validation function arguments\n data: new Name(\"data\"), // data passed to validation function\n // args passed from referencing schema\n valCxt: new Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n instancePath: new Name(\"instancePath\"),\n parentData: new Name(\"parentData\"),\n parentDataProperty: new Name(\"parentDataProperty\"),\n rootData: new Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n dynamicAnchors: new Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n // function scoped variables\n vErrors: new Name(\"vErrors\"), // null or array of validation errors\n errors: new Name(\"errors\"), // counter of validation errors\n this: new Name(\"this\"),\n // \"globals\"\n self: new Name(\"self\"),\n scope: new Name(\"scope\"),\n // JTD serialize/parse name for JSON string and position\n json: new Name(\"json\"),\n jsonPos: new Name(\"jsonPos\"),\n jsonLen: new Name(\"jsonLen\"),\n jsonPart: new Name(\"jsonPart\"),\n}\n\nexport default names\n","import type {KeywordErrorCxt, KeywordErrorDefinition} from \"../types\"\nimport type {SchemaCxt} from \"./index\"\nimport {CodeGen, _, str, strConcat, Code, Name} from \"./codegen\"\nimport {SafeExpr} from \"./codegen/code\"\nimport {getErrorPath, Type} from \"./util\"\nimport N from \"./names\"\n\nexport const keywordError: KeywordErrorDefinition = {\n message: ({keyword}) => str`must pass \"${keyword}\" keyword validation`,\n}\n\nexport const keyword$DataError: KeywordErrorDefinition = {\n message: ({keyword, schemaType}) =>\n schemaType\n ? str`\"${keyword}\" keyword must be ${schemaType} ($data)`\n : str`\"${keyword}\" keyword is invalid ($data)`,\n}\n\nexport interface ErrorPaths {\n instancePath?: Code\n schemaPath?: string\n parentSchema?: boolean\n}\n\nexport function reportError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths,\n overrideAllErrors?: boolean\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n if (overrideAllErrors ?? (compositeRule || allErrors)) {\n addError(gen, errObj)\n } else {\n returnErrors(it, _`[${errObj}]`)\n }\n}\n\nexport function reportExtraError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n addError(gen, errObj)\n if (!(compositeRule || allErrors)) {\n returnErrors(it, N.vErrors)\n }\n}\n\nexport function resetErrorsCount(gen: CodeGen, errsCount: Name): void {\n gen.assign(N.errors, errsCount)\n gen.if(_`${N.vErrors} !== null`, () =>\n gen.if(\n errsCount,\n () => gen.assign(_`${N.vErrors}.length`, errsCount),\n () => gen.assign(N.vErrors, null)\n )\n )\n}\n\nexport function extendErrors({\n gen,\n keyword,\n schemaValue,\n data,\n errsCount,\n it,\n}: KeywordErrorCxt): void {\n /* istanbul ignore if */\n if (errsCount === undefined) throw new Error(\"ajv implementation error\")\n const err = gen.name(\"err\")\n gen.forRange(\"i\", errsCount, N.errors, (i) => {\n gen.const(err, _`${N.vErrors}[${i}]`)\n gen.if(_`${err}.instancePath === undefined`, () =>\n gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))\n )\n gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)\n if (it.opts.verbose) {\n gen.assign(_`${err}.schema`, schemaValue)\n gen.assign(_`${err}.data`, data)\n }\n })\n}\n\nfunction addError(gen: CodeGen, errObj: Code): void {\n const err = gen.const(\"err\", errObj)\n gen.if(\n _`${N.vErrors} === null`,\n () => gen.assign(N.vErrors, _`[${err}]`),\n _`${N.vErrors}.push(${err})`\n )\n gen.code(_`${N.errors}++`)\n}\n\nfunction returnErrors(it: SchemaCxt, errs: Code): void {\n const {gen, validateName, schemaEnv} = it\n if (schemaEnv.$async) {\n gen.throw(_`new ${it.ValidationError as Name}(${errs})`)\n } else {\n gen.assign(_`${validateName}.errors`, errs)\n gen.return(false)\n }\n}\n\nconst E = {\n keyword: new Name(\"keyword\"),\n schemaPath: new Name(\"schemaPath\"), // also used in JTD errors\n params: new Name(\"params\"),\n propertyName: new Name(\"propertyName\"),\n message: new Name(\"message\"),\n schema: new Name(\"schema\"),\n parentSchema: new Name(\"parentSchema\"),\n}\n\nfunction errorObjectCode(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths?: ErrorPaths\n): Code {\n const {createErrors} = cxt.it\n if (createErrors === false) return _`{}`\n return errorObject(cxt, error, errorPaths)\n}\n\nfunction errorObject(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths: ErrorPaths = {}\n): Code {\n const {gen, it} = cxt\n const keyValues: [Name, SafeExpr | string][] = [\n errorInstancePath(it, errorPaths),\n errorSchemaPath(cxt, errorPaths),\n ]\n extraErrorProps(cxt, error, keyValues)\n return gen.object(...keyValues)\n}\n\nfunction errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {\n const instPath = instancePath\n ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`\n : errorPath\n return [N.instancePath, strConcat(N.instancePath, instPath)]\n}\n\nfunction errorSchemaPath(\n {keyword, it: {errSchemaPath}}: KeywordErrorCxt,\n {schemaPath, parentSchema}: ErrorPaths\n): [Name, string | Code] {\n let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`\n if (schemaPath) {\n schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`\n }\n return [E.schemaPath, schPath]\n}\n\nfunction extraErrorProps(\n cxt: KeywordErrorCxt,\n {params, message}: KeywordErrorDefinition,\n keyValues: [Name, SafeExpr | string][]\n): void {\n const {keyword, data, schemaValue, it} = cxt\n const {opts, propertyName, topSchemaRef, schemaPath} = it\n keyValues.push(\n [E.keyword, keyword],\n [E.params, typeof params == \"function\" ? params(cxt) : params || _`{}`]\n )\n if (opts.messages) {\n keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message])\n }\n if (opts.verbose) {\n keyValues.push(\n [E.schema, schemaValue],\n [E.parentSchema, _`${topSchemaRef}${schemaPath}`],\n [N.data, data]\n )\n }\n if (propertyName) keyValues.push([E.propertyName, propertyName])\n}\n","import type {KeywordErrorDefinition, KeywordErrorCxt} from \"../../types\"\nimport type {SchemaCxt} from \"..\"\nimport {reportError} from \"../errors\"\nimport {_, Name} from \"../codegen\"\nimport N from \"../names\"\n\nconst boolError: KeywordErrorDefinition = {\n message: \"boolean schema is false\",\n}\n\nexport function topBoolOrEmptySchema(it: SchemaCxt): void {\n const {gen, schema, validateName} = it\n if (schema === false) {\n falseSchemaError(it, false)\n } else if (typeof schema == \"object\" && schema.$async === true) {\n gen.return(N.data)\n } else {\n gen.assign(_`${validateName}.errors`, null)\n gen.return(true)\n }\n}\n\nexport function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {\n const {gen, schema} = it\n if (schema === false) {\n gen.var(valid, false) // TODO var\n falseSchemaError(it)\n } else {\n gen.var(valid, true) // TODO var\n }\n}\n\nfunction falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {\n const {gen, data} = it\n // TODO maybe some other interface should be used for non-keyword validation errors...\n const cxt: KeywordErrorCxt = {\n gen,\n keyword: \"false schema\",\n data,\n schema: false,\n schemaCode: false,\n schemaValue: false,\n params: {},\n it,\n }\n reportError(cxt, boolError, undefined, overrideAllErrors)\n}\n","import type {AddedKeywordDefinition} from \"../types\"\n\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"] as const\n\nexport type JSONType = (typeof _jsonTypes)[number]\n\nconst jsonTypes: Set<string> = new Set(_jsonTypes)\n\nexport function isJSONType(x: unknown): x is JSONType {\n return typeof x == \"string\" && jsonTypes.has(x)\n}\n\ntype ValidationTypes = {\n [K in JSONType]: boolean | RuleGroup | undefined\n}\n\nexport interface ValidationRules {\n rules: RuleGroup[]\n post: RuleGroup\n all: {[Key in string]?: boolean | Rule} // rules that have to be validated\n keywords: {[Key in string]?: boolean} // all known keywords (superset of \"all\")\n types: ValidationTypes\n}\n\nexport interface RuleGroup {\n type?: JSONType\n rules: Rule[]\n}\n\n// This interface wraps KeywordDefinition because definition can have multiple keywords\nexport interface Rule {\n keyword: string\n definition: AddedKeywordDefinition\n}\n\nexport function getRules(): ValidationRules {\n const groups: Record<\"number\" | \"string\" | \"array\" | \"object\", RuleGroup> = {\n number: {type: \"number\", rules: []},\n string: {type: \"string\", rules: []},\n array: {type: \"array\", rules: []},\n object: {type: \"object\", rules: []},\n }\n return {\n types: {...groups, integer: true, boolean: true, null: true},\n rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],\n post: {rules: []},\n all: {},\n keywords: {},\n }\n}\n","import type {AnySchemaObject} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport type {JSONType, RuleGroup, Rule} from \"../rules\"\n\nexport function schemaHasRulesForType(\n {schema, self}: SchemaObjCxt,\n type: JSONType\n): boolean | undefined {\n const group = self.RULES.types[type]\n return group && group !== true && shouldUseGroup(schema, group)\n}\n\nexport function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {\n return group.rules.some((rule) => shouldUseRule(schema, rule))\n}\n\nexport function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {\n return (\n schema[rule.keyword] !== undefined ||\n rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)\n )\n}\n","import type {\n KeywordErrorDefinition,\n KeywordErrorCxt,\n ErrorObject,\n AnySchemaObject,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {isJSONType, JSONType} from \"../rules\"\nimport {schemaHasRulesForType} from \"./applicability\"\nimport {reportError} from \"../errors\"\nimport {_, nil, and, not, operators, Code, Name} from \"../codegen\"\nimport {toHash, schemaRefOrVal} from \"../util\"\n\nexport enum DataType {\n Correct,\n Wrong,\n}\n\nexport function getSchemaTypes(schema: AnySchemaObject): JSONType[] {\n const types = getJSONTypes(schema.type)\n const hasNull = types.includes(\"null\")\n if (hasNull) {\n if (schema.nullable === false) throw new Error(\"type: null contradicts nullable: false\")\n } else {\n if (!types.length && schema.nullable !== undefined) {\n throw new Error('\"nullable\" cannot be used without \"type\"')\n }\n if (schema.nullable === true) types.push(\"null\")\n }\n return types\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\nexport function getJSONTypes(ts: unknown | unknown[]): JSONType[] {\n const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []\n if (types.every(isJSONType)) return types\n throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"))\n}\n\nexport function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {\n const {gen, data, opts} = it\n const coerceTo = coerceToTypes(types, opts.coerceTypes)\n const checkTypes =\n types.length > 0 &&\n !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))\n if (checkTypes) {\n const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)\n gen.if(wrongType, () => {\n if (coerceTo.length) coerceData(it, types, coerceTo)\n else reportTypeError(it)\n })\n }\n return checkTypes\n}\n\nconst COERCIBLE: Set<JSONType> = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"])\nfunction coerceToTypes(types: JSONType[], coerceTypes?: boolean | \"array\"): JSONType[] {\n return coerceTypes\n ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n : []\n}\n\nfunction coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {\n const {gen, data, opts} = it\n const dataType = gen.let(\"dataType\", _`typeof ${data}`)\n const coerced = gen.let(\"coerced\", _`undefined`)\n if (opts.coerceTypes === \"array\") {\n gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>\n gen\n .assign(data, _`${data}[0]`)\n .assign(dataType, _`typeof ${data}`)\n .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))\n )\n }\n gen.if(_`${coerced} !== undefined`)\n for (const t of coerceTo) {\n if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n coerceSpecificType(t)\n }\n }\n gen.else()\n reportTypeError(it)\n gen.endIf()\n\n gen.if(_`${coerced} !== undefined`, () => {\n gen.assign(data, coerced)\n assignParentData(it, coerced)\n })\n\n function coerceSpecificType(t: string): void {\n switch (t) {\n case \"string\":\n gen\n .elseIf(_`${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n .assign(coerced, _`\"\" + ${data}`)\n .elseIf(_`${data} === null`)\n .assign(coerced, _`\"\"`)\n return\n case \"number\":\n gen\n .elseIf(\n _`${dataType} == \"boolean\" || ${data} === null\n || (${dataType} == \"string\" && ${data} && ${data} == +${data})`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"integer\":\n gen\n .elseIf(\n _`${dataType} === \"boolean\" || ${data} === null\n || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"boolean\":\n gen\n .elseIf(_`${data} === \"false\" || ${data} === 0 || ${data} === null`)\n .assign(coerced, false)\n .elseIf(_`${data} === \"true\" || ${data} === 1`)\n .assign(coerced, true)\n return\n case \"null\":\n gen.elseIf(_`${data} === \"\" || ${data} === 0 || ${data} === false`)\n gen.assign(coerced, null)\n return\n\n case \"array\":\n gen\n .elseIf(\n _`${dataType} === \"string\" || ${dataType} === \"number\"\n || ${dataType} === \"boolean\" || ${data} === null`\n )\n .assign(coerced, _`[${data}]`)\n }\n }\n}\n\nfunction assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {\n // TODO use gen.property\n gen.if(_`${parentData} !== undefined`, () =>\n gen.assign(_`${parentData}[${parentDataProperty}]`, expr)\n )\n}\n\nexport function checkDataType(\n dataType: JSONType,\n data: Name,\n strictNums?: boolean | \"log\",\n correct = DataType.Correct\n): Code {\n const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ\n let cond: Code\n switch (dataType) {\n case \"null\":\n return _`${data} ${EQ} null`\n case \"array\":\n cond = _`Array.isArray(${data})`\n break\n case \"object\":\n cond = _`${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`\n break\n case \"integer\":\n cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)\n break\n case \"number\":\n cond = numCond()\n break\n default:\n return _`typeof ${data} ${EQ} ${dataType}`\n }\n return correct === DataType.Correct ? cond : not(cond)\n\n function numCond(_cond: Code = nil): Code {\n return and(_`typeof ${data} == \"number\"`, _cond, strictNums ? _`isFinite(${data})` : nil)\n }\n}\n\nexport function checkDataTypes(\n dataTypes: JSONType[],\n data: Name,\n strictNums?: boolean | \"log\",\n correct?: DataType\n): Code {\n if (dataTypes.length === 1) {\n return checkDataType(dataTypes[0], data, strictNums, correct)\n }\n let cond: Code\n const types = toHash(dataTypes)\n if (types.array && types.object) {\n const notObj = _`typeof ${data} != \"object\"`\n cond = types.null ? notObj : _`!${data} || ${notObj}`\n delete types.null\n delete types.array\n delete types.object\n } else {\n cond = nil\n }\n if (types.number) delete types.integer\n for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))\n return cond\n}\n\nexport type TypeError = ErrorObject<\"type\", {type: string}>\n\nconst typeError: KeywordErrorDefinition = {\n message: ({schema}) => `must be ${schema}`,\n params: ({schema, schemaValue}) =>\n typeof schema == \"string\" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,\n}\n\nexport function reportTypeError(it: SchemaObjCxt): void {\n const cxt = getTypeErrorContext(it)\n reportError(cxt, typeError)\n}\n\nfunction getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {\n const {gen, data, schema} = it\n const schemaCode = schemaRefOrVal(it, schema, \"type\")\n return {\n gen,\n keyword: \"type\",\n data,\n schema: schema.type,\n schemaCode,\n schemaValue: schemaCode,\n parentSchema: schema,\n params: {},\n it,\n }\n}\n","import type {SchemaObjCxt} from \"..\"\nimport {_, getProperty, stringify} from \"../codegen\"\nimport {checkStrictMode} from \"../util\"\n\nexport function assignDefaults(it: SchemaObjCxt, ty?: string): void {\n const {properties, items} = it.schema\n if (ty === \"object\" && properties) {\n for (const key in properties) {\n assignDefault(it, key, properties[key].default)\n }\n } else if (ty === \"array\" && Array.isArray(items)) {\n items.forEach((sch, i: number) => assignDefault(it, i, sch.default))\n }\n}\n\nfunction assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {\n const {gen, compositeRule, data, opts} = it\n if (defaultValue === undefined) return\n const childData = _`${data}${getProperty(prop)}`\n if (compositeRule) {\n checkStrictMode(it, `default is ignored for: ${childData}`)\n return\n }\n\n let condition = _`${childData} === undefined`\n if (opts.useDefaults === \"empty\") {\n condition = _`${condition} || ${childData} === null || ${childData} === \"\"`\n }\n // `${childData} === undefined` +\n // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)\n}\n","import type {AnySchema, SchemaMap} from \"../types\"\nimport type {SchemaCxt} from \"../compile\"\nimport type {KeywordCxt} from \"../compile/validate\"\nimport {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from \"../compile/codegen\"\nimport {alwaysValidSchema, Type} from \"../compile/util\"\nimport N from \"../compile/names\"\nimport {useFunc} from \"../compile/util\"\nexport function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {\n const {gen, data, it} = cxt\n gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n cxt.setParams({missingProperty: _`${prop}`}, true)\n cxt.error()\n })\n}\n\nexport function checkMissingProp(\n {gen, data, it: {opts}}: KeywordCxt,\n properties: string[],\n missing: Name\n): Code {\n return or(\n ...properties.map((prop) =>\n and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)\n )\n )\n}\n\nexport function reportMissingProp(cxt: KeywordCxt, missing: Name): void {\n cxt.setParams({missingProperty: missing}, true)\n cxt.error()\n}\n\nexport function hasPropFunc(gen: CodeGen): Name {\n return gen.scopeValue(\"func\", {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ref: Object.prototype.hasOwnProperty,\n code: _`Object.prototype.hasOwnProperty`,\n })\n}\n\nexport function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {\n return _`${hasPropFunc(gen)}.call(${data}, ${property})`\n}\n\nexport function propertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} !== undefined`\n return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond\n}\n\nexport function noPropertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} === undefined`\n return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond\n}\n\nexport function allSchemaProperties(schemaMap?: SchemaMap): string[] {\n return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : []\n}\n\nexport function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {\n return allSchemaProperties(schemaMap).filter(\n (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)\n )\n}\n\nexport function callValidateCode(\n {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,\n func: Code,\n context: Code,\n passSchema?: boolean\n): Code {\n const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data\n const valCxt: [Name, Code | number][] = [\n [N.instancePath, strConcat(N.instancePath, errorPath)],\n [N.parentData, it.parentData],\n [N.parentDataProperty, it.parentDataProperty],\n [N.rootData, N.rootData],\n ]\n if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])\n const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`\n return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`\n}\n\nconst newRegExp = _`new RegExp`\n\nexport function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {\n const u = opts.unicodeRegExp ? \"u\" : \"\"\n const {regExp} = opts.code\n const rx = regExp(pattern, u)\n\n return gen.scopeValue(\"pattern\", {\n key: rx.toString(),\n ref: rx,\n code: _`${regExp.code === \"new RegExp\" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,\n })\n}\n\nexport function validateArray(cxt: KeywordCxt): Name {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n if (it.allErrors) {\n const validArr = gen.let(\"valid\", true)\n validateItems(() => gen.assign(validArr, false))\n return validArr\n }\n gen.var(valid, true)\n validateItems(() => gen.break())\n return valid\n\n function validateItems(notValid: () => void): void {\n const len = gen.const(\"len\", _`${data}.length`)\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword,\n dataProp: i,\n dataPropType: Type.Num,\n },\n valid\n )\n gen.if(not(valid), notValid)\n })\n }\n}\n\nexport function validateUnion(cxt: KeywordCxt): void {\n const {gen, schema, keyword, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))\n if (alwaysValid && !it.opts.unevaluated) return\n\n const valid = gen.let(\"valid\", false)\n const schValid = gen.name(\"_valid\")\n\n gen.block(() =>\n schema.forEach((_sch: AnySchema, i: number) => {\n const schCxt = cxt.subschema(\n {\n keyword,\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n gen.assign(valid, _`${valid} || ${schValid}`)\n const merged = cxt.mergeValidEvaluated(schCxt, schValid)\n // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n // or if all properties and items were evaluated (it.props === true && it.items === true)\n if (!merged) gen.if(not(valid))\n })\n )\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n}\n","import type {KeywordCxt} from \".\"\nimport type {\n AnySchema,\n SchemaValidateFunction,\n AnyValidateFunction,\n AddedKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, nil, not, stringify, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport type {JSONType} from \"../rules\"\nimport {callValidateCode} from \"../../vocabularies/code\"\nimport {extendErrors} from \"../errors\"\n\ntype KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction\n\nexport function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, it} = cxt\n const macroSchema = def.macro.call(it.self, schema, parentSchema, it)\n const schemaRef = useKeyword(gen, keyword, macroSchema)\n if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n schema: macroSchema,\n schemaPath: nil,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n topSchemaRef: schemaRef,\n compositeRule: true,\n },\n valid\n )\n cxt.pass(valid, () => cxt.error(true))\n}\n\nexport function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, $data, it} = cxt\n checkAsyncKeyword(it, def)\n const validate =\n !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate\n const validateRef = useKeyword(gen, keyword, validate)\n const valid = gen.let(\"valid\")\n cxt.block$data(valid, validateKeyword)\n cxt.ok(def.valid ?? valid)\n\n function validateKeyword(): void {\n if (def.errors === false) {\n assignValid()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => cxt.error())\n } else {\n const ruleErrs = def.async ? validateAsync() : validateSync()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => addErrs(cxt, ruleErrs))\n }\n }\n\n function validateAsync(): Name {\n const ruleErrs = gen.let(\"ruleErrs\", null)\n gen.try(\n () => assignValid(_`await `),\n (e) =>\n gen.assign(valid, false).if(\n _`${e} instanceof ${it.ValidationError as Name}`,\n () => gen.assign(ruleErrs, _`${e}.errors`),\n () => gen.throw(e)\n )\n )\n return ruleErrs\n }\n\n function validateSync(): Code {\n const validateErrs = _`${validateRef}.errors`\n gen.assign(validateErrs, null)\n assignValid(nil)\n return validateErrs\n }\n\n function assignValid(_await: Code = def.async ? _`await ` : nil): void {\n const passCxt = it.opts.passContext ? N.this : N.self\n const passSchema = !((\"compile\" in def && !$data) || def.schema === false)\n gen.assign(\n valid,\n _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,\n def.modifying\n )\n }\n\n function reportErrs(errors: () => void): void {\n gen.if(not(def.valid ?? valid), errors)\n }\n}\n\nfunction modifyData(cxt: KeywordCxt): void {\n const {gen, data, it} = cxt\n gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))\n}\n\nfunction addErrs(cxt: KeywordCxt, errs: Code): void {\n const {gen} = cxt\n gen.if(\n _`Array.isArray(${errs})`,\n () => {\n gen\n .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)\n .assign(N.errors, _`${N.vErrors}.length`)\n extendErrors(cxt)\n },\n () => cxt.error()\n )\n}\n\nfunction checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {\n if (def.async && !schemaEnv.$async) throw new Error(\"async keyword in sync schema\")\n}\n\nfunction useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {\n if (result === undefined) throw new Error(`keyword \"${keyword}\" failed to compile`)\n return gen.scopeValue(\n \"keyword\",\n typeof result == \"function\" ? {ref: result} : {ref: result, code: stringify(result)}\n )\n}\n\nexport function validSchemaType(\n schema: unknown,\n schemaType: JSONType[],\n allowUndefined = false\n): boolean {\n // TODO add tests\n return (\n !schemaType.length ||\n schemaType.some((st) =>\n st === \"array\"\n ? Array.isArray(schema)\n : st === \"object\"\n ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")\n )\n )\n}\n\nexport function validateKeywordUsage(\n {schema, opts, self, errSchemaPath}: SchemaObjCxt,\n def: AddedKeywordDefinition,\n keyword: string\n): void {\n /* istanbul ignore if */\n if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n throw new Error(\"ajv implementation error\")\n }\n\n const deps = def.dependencies\n if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`)\n }\n\n if (def.validateSchema) {\n const valid = def.validateSchema(schema[keyword])\n if (!valid) {\n const msg =\n `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n self.errorsText(def.validateSchema.errors)\n if (opts.validateSchema === \"log\") self.logger.error(msg)\n else throw new Error(msg)\n }\n }\n}\n","import type {AnySchema} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, str, getProperty, Code, Name} from \"../codegen\"\nimport {escapeFragment, getErrorPath, Type} from \"../util\"\nimport type {JSONType} from \"../rules\"\n\nexport interface SubschemaContext {\n // TODO use Optional? align with SchemCxt property types\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef?: Code\n errorPath?: Code\n dataLevel?: number\n dataTypes?: JSONType[]\n data?: Name\n parentData?: Name\n parentDataProperty?: Code | number\n dataNames?: Name[]\n dataPathArr?: (Code | number)[]\n propertyName?: Name\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n compositeRule?: true\n createErrors?: boolean\n allErrors?: boolean\n}\n\nexport type SubschemaArgs = Partial<{\n keyword: string\n schemaProp: string | number\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef: Code\n data: Name | Code\n dataProp: Code | string | number\n dataTypes: JSONType[]\n definedProperties: Set<string>\n propertyName: Name\n dataPropType: Type\n jtdDiscriminator: string\n jtdMetadata: boolean\n compositeRule: true\n createErrors: boolean\n allErrors: boolean\n}>\n\nexport function getSubschema(\n it: SchemaObjCxt,\n {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs\n): SubschemaContext {\n if (keyword !== undefined && schema !== undefined) {\n throw new Error('both \"keyword\" and \"schema\" passed, only one allowed')\n }\n\n if (keyword !== undefined) {\n const sch = it.schema[keyword]\n return schemaProp === undefined\n ? {\n schema: sch,\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n }\n : {\n schema: sch[schemaProp],\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,\n }\n }\n\n if (schema !== undefined) {\n if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"')\n }\n return {\n schema,\n schemaPath,\n topSchemaRef,\n errSchemaPath,\n }\n }\n\n throw new Error('either \"keyword\" or \"schema\" must be passed')\n}\n\nexport function extendSubschemaData(\n subschema: SubschemaContext,\n it: SchemaObjCxt,\n {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs\n): void {\n if (data !== undefined && dataProp !== undefined) {\n throw new Error('both \"data\" and \"dataProp\" passed, only one allowed')\n }\n\n const {gen} = it\n\n if (dataProp !== undefined) {\n const {errorPath, dataPathArr, opts} = it\n const nextData = gen.let(\"data\", _`${it.data}${getProperty(dataProp)}`, true)\n dataContextProps(nextData)\n subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`\n subschema.parentDataProperty = _`${dataProp}`\n subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]\n }\n\n if (data !== undefined) {\n const nextData = data instanceof Name ? data : gen.let(\"data\", data, true) // replaceable if used once?\n dataContextProps(nextData)\n if (propertyName !== undefined) subschema.propertyName = propertyName\n // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n }\n\n if (dataTypes) subschema.dataTypes = dataTypes\n\n function dataContextProps(_nextData: Name): void {\n subschema.data = _nextData\n subschema.dataLevel = it.dataLevel + 1\n subschema.dataTypes = []\n it.definedProperties = new Set<string>()\n subschema.parentData = it.data\n subschema.dataNames = [...it.dataNames, _nextData]\n }\n}\n\nexport function extendSubschemaMode(\n subschema: SubschemaContext,\n {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs\n): void {\n if (compositeRule !== undefined) subschema.compositeRule = compositeRule\n if (createErrors !== undefined) subschema.createErrors = createErrors\n if (allErrors !== undefined) subschema.allErrors = allErrors\n subschema.jtdDiscriminator = jtdDiscriminator // not inherited\n subschema.jtdMetadata = jtdMetadata // not inherited\n}\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n // Legacy support for v0.3.1 and earlier.\n if (typeof opts == 'function') {\n cb = opts;\n opts = {};\n }\n\n cb = opts.cb || cb;\n var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n var post = cb.post || function() {};\n\n _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n additionalItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\n\ntraverse.arrayKeywords = {\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\n\ntraverse.propsKeywords = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependencies: true\n};\n\ntraverse.skipKeywords = {\n default: true,\n enum: true,\n const: true,\n required: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n for (var key in schema) {\n var sch = schema[key];\n if (Array.isArray(sch)) {\n if (key in traverse.arrayKeywords) {\n for (var i=0; i<sch.length; i++)\n _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);\n }\n } else if (key in traverse.propsKeywords) {\n if (sch && typeof sch == 'object') {\n for (var prop in sch)\n _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);\n }\n } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {\n _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);\n }\n }\n post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n }\n}\n\n\nfunction escapeJsonPtr(str) {\n return str.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n","import type {AnySchema, AnySchemaObject, UriResolver} from \"../types\"\nimport type Ajv from \"../ajv\"\nimport type {URIComponent} from \"fast-uri\"\nimport {eachItem} from \"./util\"\nimport * as equal from \"fast-deep-equal\"\nimport * as traverse from \"json-schema-traverse\"\n\n// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution\nexport type LocalRefs = {[Ref in string]?: AnySchemaObject}\n\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n \"type\",\n \"format\",\n \"pattern\",\n \"maxLength\",\n \"minLength\",\n \"maxProperties\",\n \"minProperties\",\n \"maxItems\",\n \"minItems\",\n \"maximum\",\n \"minimum\",\n \"uniqueItems\",\n \"multipleOf\",\n \"required\",\n \"enum\",\n \"const\",\n])\n\nexport function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {\n if (typeof schema == \"boolean\") return true\n if (limit === true) return !hasRef(schema)\n if (!limit) return false\n return countKeys(schema) <= limit\n}\n\nconst REF_KEYWORDS = new Set([\n \"$ref\",\n \"$recursiveRef\",\n \"$recursiveAnchor\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n])\n\nfunction hasRef(schema: AnySchemaObject): boolean {\n for (const key in schema) {\n if (REF_KEYWORDS.has(key)) return true\n const sch = schema[key]\n if (Array.isArray(sch) && sch.some(hasRef)) return true\n if (typeof sch == \"object\" && hasRef(sch)) return true\n }\n return false\n}\n\nfunction countKeys(schema: AnySchemaObject): number {\n let count = 0\n for (const key in schema) {\n if (key === \"$ref\") return Infinity\n count++\n if (SIMPLE_INLINED.has(key)) continue\n if (typeof schema[key] == \"object\") {\n eachItem(schema[key], (sch) => (count += countKeys(sch)))\n }\n if (count === Infinity) return Infinity\n }\n return count\n}\n\nexport function getFullPath(resolver: UriResolver, id = \"\", normalize?: boolean): string {\n if (normalize !== false) id = normalizeId(id)\n const p = resolver.parse(id)\n return _getFullPath(resolver, p)\n}\n\nexport function _getFullPath(resolver: UriResolver, p: URIComponent): string {\n const serialized = resolver.serialize(p)\n return serialized.split(\"#\")[0] + \"#\"\n}\n\nconst TRAILING_SLASH_HASH = /#\\/?$/\nexport function normalizeId(id: string | undefined): string {\n return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\"\n}\n\nexport function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {\n id = normalizeId(id)\n return resolver.resolve(baseId, id)\n}\n\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i\n\nexport function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {\n if (typeof schema == \"boolean\") return {}\n const {schemaId, uriResolver} = this.opts\n const schId = normalizeId(schema[schemaId] || baseId)\n const baseIds: {[JsonPtr in string]?: string} = {\"\": schId}\n const pathPrefix = getFullPath(uriResolver, schId, false)\n const localRefs: LocalRefs = {}\n const schemaRefs: Set<string> = new Set()\n\n traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {\n if (parentJsonPtr === undefined) return\n const fullPath = pathPrefix + jsonPtr\n let innerBaseId = baseIds[parentJsonPtr]\n if (typeof sch[schemaId] == \"string\") innerBaseId = addRef.call(this, sch[schemaId])\n addAnchor.call(this, sch.$anchor)\n addAnchor.call(this, sch.$dynamicAnchor)\n baseIds[jsonPtr] = innerBaseId\n\n function addRef(this: Ajv, ref: string): string {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _resolve = this.opts.uriResolver.resolve\n ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref)\n if (schemaRefs.has(ref)) throw ambiguos(ref)\n schemaRefs.add(ref)\n let schOrRef = this.refs[ref]\n if (typeof schOrRef == \"string\") schOrRef = this.refs[schOrRef]\n if (typeof schOrRef == \"object\") {\n checkAmbiguosRef(sch, schOrRef.schema, ref)\n } else if (ref !== normalizeId(fullPath)) {\n if (ref[0] === \"#\") {\n checkAmbiguosRef(sch, localRefs[ref], ref)\n localRefs[ref] = sch\n } else {\n this.refs[ref] = fullPath\n }\n }\n return ref\n }\n\n function addAnchor(this: Ajv, anchor: unknown): void {\n if (typeof anchor == \"string\") {\n if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor \"${anchor}\"`)\n addRef.call(this, `#${anchor}`)\n }\n }\n })\n\n return localRefs\n\n function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {\n if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)\n }\n\n function ambiguos(ref: string): Error {\n return new Error(`reference \"${ref}\" resolves to more than one schema`)\n }\n}\n","import type {\n AddedKeywordDefinition,\n AnySchema,\n AnySchemaObject,\n KeywordErrorCxt,\n KeywordCxtParams,\n} from \"../../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \"..\"\nimport type {InstanceOptions} from \"../../core\"\nimport {boolOrEmptySchema, topBoolOrEmptySchema} from \"./boolSchema\"\nimport {coerceAndCheckDataType, getSchemaTypes} from \"./dataType\"\nimport {shouldUseGroup, shouldUseRule} from \"./applicability\"\nimport {checkDataType, checkDataTypes, reportTypeError, DataType} from \"./dataType\"\nimport {assignDefaults} from \"./defaults\"\nimport {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from \"./keyword\"\nimport {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from \"./subschema\"\nimport {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport {resolveUrl} from \"../resolve\"\nimport {\n schemaRefOrVal,\n schemaHasRulesButRef,\n checkUnknownRules,\n checkStrictMode,\n unescapeJsonPointer,\n mergeEvaluated,\n} from \"../util\"\nimport type {JSONType, Rule, RuleGroup} from \"../rules\"\nimport {\n ErrorPaths,\n reportError,\n reportExtraError,\n resetErrorsCount,\n keyword$DataError,\n} from \"../errors\"\n\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nexport function validateFunctionCode(it: SchemaCxt): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it)\n return\n }\n }\n validateFunction(it, () => topBoolOrEmptySchema(it))\n}\n\nfunction validateFunction(\n {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,\n body: Block\n): void {\n if (opts.code.es5) {\n gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {\n gen.code(_`\"use strict\"; ${funcSourceUrl(schema, opts)}`)\n destructureValCxtES5(gen, opts)\n gen.code(body)\n })\n } else {\n gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>\n gen.code(funcSourceUrl(schema, opts)).code(body)\n )\n }\n}\n\nfunction destructureValCxt(opts: InstanceOptions): Code {\n return _`{${N.instancePath}=\"\", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${\n N.data\n }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`\n}\n\nfunction destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {\n gen.if(\n N.valCxt,\n () => {\n gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)\n gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)\n gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)\n gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)\n },\n () => {\n gen.var(N.instancePath, _`\"\"`)\n gen.var(N.parentData, _`undefined`)\n gen.var(N.parentDataProperty, _`undefined`)\n gen.var(N.rootData, N.data)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)\n }\n )\n}\n\nfunction topSchemaObjCode(it: SchemaObjCxt): void {\n const {schema, opts, gen} = it\n validateFunction(it, () => {\n if (opts.$comment && schema.$comment) commentKeyword(it)\n checkNoDefault(it)\n gen.let(N.vErrors, null)\n gen.let(N.errors, 0)\n if (opts.unevaluated) resetEvaluated(it)\n typeAndKeywords(it)\n returnResults(it)\n })\n return\n}\n\nfunction resetEvaluated(it: SchemaObjCxt): void {\n // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n const {gen, validateName} = it\n it.evaluated = gen.const(\"evaluated\", _`${validateName}.evaluated`)\n gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))\n gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))\n}\n\nfunction funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {\n const schId = typeof schema == \"object\" && schema[opts.schemaId]\n return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil\n}\n\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it: SchemaCxt, valid: Name): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid)\n return\n }\n }\n boolOrEmptySchema(it, valid)\n}\n\nfunction schemaCxtHasRules({schema, self}: SchemaCxt): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (self.RULES.all[key]) return true\n return false\n}\n\nfunction isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {\n return typeof it.schema != \"boolean\"\n}\n\nfunction subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {\n const {schema, gen, opts} = it\n if (opts.$comment && schema.$comment) commentKeyword(it)\n updateContext(it)\n checkAsyncSchema(it)\n const errsCount = gen.const(\"_errs\", N.errors)\n typeAndKeywords(it, errsCount)\n // TODO var\n gen.var(valid, _`${errsCount} === ${N.errors}`)\n}\n\nfunction checkKeywords(it: SchemaObjCxt): void {\n checkUnknownRules(it)\n checkRefsAndKeywords(it)\n}\n\nfunction typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {\n if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)\n const types = getSchemaTypes(it.schema)\n const checkedTypes = coerceAndCheckDataType(it, types)\n schemaKeywords(it, types, !checkedTypes, errsCount)\n}\n\nfunction checkRefsAndKeywords(it: SchemaObjCxt): void {\n const {schema, errSchemaPath, opts, self} = it\n if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {\n self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`)\n }\n}\n\nfunction checkNoDefault(it: SchemaObjCxt): void {\n const {schema, opts} = it\n if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n checkStrictMode(it, \"default is ignored in the schema root\")\n }\n}\n\nfunction updateContext(it: SchemaObjCxt): void {\n const schId = it.schema[it.opts.schemaId]\n if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)\n}\n\nfunction checkAsyncSchema(it: SchemaObjCxt): void {\n if (it.schema.$async && !it.schemaEnv.$async) throw new Error(\"async schema in sync schema\")\n}\n\nfunction commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {\n const msg = schema.$comment\n if (opts.$comment === true) {\n gen.code(_`${N.self}.logger.log(${msg})`)\n } else if (typeof opts.$comment == \"function\") {\n const schemaPath = str`${errSchemaPath}/$comment`\n const rootName = gen.scopeValue(\"root\", {ref: schemaEnv.root})\n gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)\n }\n}\n\nfunction returnResults(it: SchemaCxt): void {\n const {gen, schemaEnv, validateName, ValidationError, opts} = it\n if (schemaEnv.$async) {\n // TODO assign unevaluated\n gen.if(\n _`${N.errors} === 0`,\n () => gen.return(N.data),\n () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)\n )\n } else {\n gen.assign(_`${validateName}.errors`, N.vErrors)\n if (opts.unevaluated) assignEvaluated(it)\n gen.return(_`${N.errors} === 0`)\n }\n}\n\nfunction assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {\n if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)\n if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)\n}\n\nfunction schemaKeywords(\n it: SchemaObjCxt,\n types: JSONType[],\n typeErrors: boolean,\n errsCount?: Name\n): void {\n const {gen, schema, data, allErrors, opts, self} = it\n const {RULES} = self\n if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {\n gen.block(() => keywordCode(it, \"$ref\", (RULES.all.$ref as Rule).definition)) // TODO typecast\n return\n }\n if (!opts.jtd) checkStrictTypes(it, types)\n gen.block(() => {\n for (const group of RULES.rules) groupKeywords(group)\n groupKeywords(RULES.post)\n })\n\n function groupKeywords(group: RuleGroup): void {\n if (!shouldUseGroup(schema, group)) return\n if (group.type) {\n gen.if(checkDataType(group.type, data, opts.strictNumbers))\n iterateKeywords(it, group)\n if (types.length === 1 && types[0] === group.type && typeErrors) {\n gen.else()\n reportTypeError(it)\n }\n gen.endIf()\n } else {\n iterateKeywords(it, group)\n }\n // TODO make it \"ok\" call?\n if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)\n }\n}\n\nfunction iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {\n const {\n gen,\n schema,\n opts: {useDefaults},\n } = it\n if (useDefaults) assignDefaults(it, group.type)\n gen.block(() => {\n for (const rule of group.rules) {\n if (shouldUseRule(schema, rule)) {\n keywordCode(it, rule.keyword, rule.definition, group.type)\n }\n }\n })\n}\n\nfunction checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (it.schemaEnv.meta || !it.opts.strictTypes) return\n checkContextTypes(it, types)\n if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)\n checkKeywordTypes(it, it.dataTypes)\n}\n\nfunction checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (!types.length) return\n if (!it.dataTypes.length) {\n it.dataTypes = types\n return\n }\n types.forEach((t) => {\n if (!includesType(it.dataTypes, t)) {\n strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`)\n }\n })\n narrowSchemaTypes(it, types)\n}\n\nfunction checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n strictTypesError(it, \"use allowUnionTypes to allow union type keyword\")\n }\n}\n\nfunction checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n const rules = it.self.RULES.all\n for (const keyword in rules) {\n const rule = rules[keyword]\n if (typeof rule == \"object\" && shouldUseRule(it.schema, rule)) {\n const {type} = rule.definition\n if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`)\n }\n }\n }\n}\n\nfunction hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {\n return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"))\n}\n\nfunction includesType(ts: JSONType[], t: JSONType): boolean {\n return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"))\n}\n\nfunction narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {\n const ts: JSONType[] = []\n for (const t of it.dataTypes) {\n if (includesType(withTypes, t)) ts.push(t)\n else if (withTypes.includes(\"integer\") && t === \"number\") ts.push(\"integer\")\n }\n it.dataTypes = ts\n}\n\nfunction strictTypesError(it: SchemaObjCxt, msg: string): void {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n msg += ` at \"${schemaPath}\" (strictTypes)`\n checkStrictMode(it, msg, it.opts.strictTypes)\n}\n\nexport class KeywordCxt implements KeywordErrorCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean\n readonly keyword: string\n readonly data: Name // Name referencing the current level of the data instance\n readonly $data?: string | false\n schema: any // keyword value in the schema\n readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value\n readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)\n readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema\n readonly parentSchema: AnySchemaObject\n readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,\n // requires option trackErrors in keyword definition\n params: KeywordCxtParams // object to pass parameters to error messages from keyword code\n readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)\n readonly def: AddedKeywordDefinition\n\n constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {\n validateKeywordUsage(it, def, keyword)\n this.gen = it.gen\n this.allErrors = it.allErrors\n this.keyword = keyword\n this.data = it.data\n this.schema = it.schema[keyword]\n this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data\n this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)\n this.schemaType = def.schemaType\n this.parentSchema = it.schema\n this.params = {}\n this.it = it\n this.def = def\n\n if (this.$data) {\n this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it))\n } else {\n this.schemaCode = this.schemaValue\n if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {\n throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)\n }\n }\n\n if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n this.errsCount = it.gen.const(\"_errs\", N.errors)\n }\n }\n\n result(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.failResult(not(condition), successAction, failAction)\n }\n\n failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.gen.if(condition)\n if (failAction) failAction()\n else this.error()\n if (successAction) {\n this.gen.else()\n successAction()\n if (this.allErrors) this.gen.endIf()\n } else {\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n }\n\n pass(condition: Code, failAction?: () => void): void {\n this.failResult(not(condition), undefined, failAction)\n }\n\n fail(condition?: Code): void {\n if (condition === undefined) {\n this.error()\n if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize\n return\n }\n this.gen.if(condition)\n this.error()\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n\n fail$data(condition: Code): void {\n if (!this.$data) return this.fail(condition)\n const {schemaCode} = this\n this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)\n }\n\n error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {\n if (errorParams) {\n this.setParams(errorParams)\n this._error(append, errorPaths)\n this.setParams({})\n return\n }\n this._error(append, errorPaths)\n }\n\n private _error(append?: boolean, errorPaths?: ErrorPaths): void {\n ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)\n }\n\n $dataError(): void {\n reportError(this, this.def.$dataError || keyword$DataError)\n }\n\n reset(): void {\n if (this.errsCount === undefined) throw new Error('add \"trackErrors\" to keyword definition')\n resetErrorsCount(this.gen, this.errsCount)\n }\n\n ok(cond: Code | boolean): void {\n if (!this.allErrors) this.gen.if(cond)\n }\n\n setParams(obj: KeywordCxtParams, assign?: true): void {\n if (assign) Object.assign(this.params, obj)\n else this.params = obj\n }\n\n block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {\n this.gen.block(() => {\n this.check$data(valid, $dataValid)\n codeBlock()\n })\n }\n\n check$data(valid: Name = nil, $dataValid: Code = nil): void {\n if (!this.$data) return\n const {gen, schemaCode, schemaType, def} = this\n gen.if(or(_`${schemaCode} === undefined`, $dataValid))\n if (valid !== nil) gen.assign(valid, true)\n if (schemaType.length || def.validateSchema) {\n gen.elseIf(this.invalid$data())\n this.$dataError()\n if (valid !== nil) gen.assign(valid, false)\n }\n gen.else()\n }\n\n invalid$data(): Code {\n const {gen, schemaCode, schemaType, def, it} = this\n return or(wrong$DataType(), invalid$DataSchema())\n\n function wrong$DataType(): Code {\n if (schemaType.length) {\n /* istanbul ignore if */\n if (!(schemaCode instanceof Name)) throw new Error(\"ajv implementation error\")\n const st = Array.isArray(schemaType) ? schemaType : [schemaType]\n return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`\n }\n return nil\n }\n\n function invalid$DataSchema(): Code {\n if (def.validateSchema) {\n const validateSchemaRef = gen.scopeValue(\"validate$data\", {ref: def.validateSchema}) // TODO value.code for standalone\n return _`!${validateSchemaRef}(${schemaCode})`\n }\n return nil\n }\n }\n\n subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {\n const subschema = getSubschema(this.it, appl)\n extendSubschemaData(subschema, this.it, appl)\n extendSubschemaMode(subschema, appl)\n const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}\n subschemaCode(nextContext, valid)\n return nextContext\n }\n\n mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {\n const {it, gen} = this\n if (!it.opts.unevaluated) return\n if (it.props !== true && schemaCxt.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)\n }\n if (it.items !== true && schemaCxt.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)\n }\n }\n\n mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {\n const {it, gen} = this\n if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))\n return true\n }\n }\n}\n\nfunction keywordCode(\n it: SchemaObjCxt,\n keyword: string,\n def: AddedKeywordDefinition,\n ruleType?: JSONType\n): void {\n const cxt = new KeywordCxt(it, def, keyword)\n if (\"code\" in def) {\n def.code(cxt, ruleType)\n } else if (cxt.$data && def.validate) {\n funcKeywordCode(cxt, def)\n } else if (\"macro\" in def) {\n macroKeywordCode(cxt, def)\n } else if (def.compile || def.validate) {\n funcKeywordCode(cxt, def)\n }\n}\n\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/\nexport function getData(\n $data: string,\n {dataLevel, dataNames, dataPathArr}: SchemaCxt\n): Code | number {\n let jsonPointer\n let data: Code\n if ($data === \"\") return N.rootData\n if ($data[0] === \"/\") {\n if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)\n jsonPointer = $data\n data = N.rootData\n } else {\n const matches = RELATIVE_JSON_POINTER.exec($data)\n if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)\n const up: number = +matches[1]\n jsonPointer = matches[2]\n if (jsonPointer === \"#\") {\n if (up >= dataLevel) throw new Error(errorMsg(\"property/index\", up))\n return dataPathArr[dataLevel - up]\n }\n if (up > dataLevel) throw new Error(errorMsg(\"data\", up))\n data = dataNames[dataLevel - up]\n if (!jsonPointer) return data\n }\n\n let expr = data\n const segments = jsonPointer.split(\"/\")\n for (const segment of segments) {\n if (segment) {\n data = _`${data}${getProperty(unescapeJsonPointer(segment))}`\n expr = _`${expr} && ${data}`\n }\n }\n return expr\n\n function errorMsg(pointerType: string, up: number): string {\n return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`\n }\n}\n","import type {ErrorObject} from \"../types\"\n\nexport default class ValidationError extends Error {\n readonly errors: Partial<ErrorObject>[]\n readonly ajv: true\n readonly validation: true\n\n constructor(errors: Partial<ErrorObject>[]) {\n super(\"validation failed\")\n this.errors = errors\n this.ajv = this.validation = true\n }\n}\n","import {resolveUrl, normalizeId, getFullPath} from \"./resolve\"\nimport type {UriResolver} from \"../types\"\n\nexport default class MissingRefError extends Error {\n readonly missingRef: string\n readonly missingSchema: string\n\n constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {\n super(msg || `can't resolve reference ${ref} from id ${baseId}`)\n this.missingRef = resolveUrl(resolver, baseId, ref)\n this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))\n }\n}\n","import type {\n AnySchema,\n AnySchemaObject,\n AnyValidateFunction,\n AsyncValidateFunction,\n EvaluatedProperties,\n EvaluatedItems,\n} from \"../types\"\nimport type Ajv from \"../core\"\nimport type {InstanceOptions} from \"../core\"\nimport {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from \"./codegen\"\nimport ValidationError from \"../runtime/validation_error\"\nimport N from \"./names\"\nimport {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from \"./resolve\"\nimport {schemaHasRulesButRef, unescapeFragment} from \"./util\"\nimport {validateFunctionCode} from \"./validate\"\nimport {URIComponent} from \"fast-uri\"\nimport {JSONType} from \"./rules\"\n\nexport type SchemaRefs = {\n [Ref in string]?: SchemaEnv | AnySchema\n}\n\nexport interface SchemaCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error\n readonly data: Name // Name with reference to the current part of data instance\n readonly parentData: Name // should be used in keywords modifying data\n readonly parentDataProperty: Code | number // should be used in keywords modifying data\n readonly dataNames: Name[]\n readonly dataPathArr: (Code | number)[]\n readonly dataLevel: number // the level of the currently validated data,\n // it can be used to access both the property names and the data on all levels from the top.\n dataTypes: JSONType[] // data types applied to the current part of data instance\n definedProperties: Set<string> // set of properties to keep track of for required checks\n readonly topSchemaRef: Code\n readonly validateName: Name\n evaluated?: Name\n readonly ValidationError?: Name\n readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt\n readonly schemaEnv: SchemaEnv\n readonly rootId: string\n baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\\$ref)\n readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema\n readonly errSchemaPath: string // this is actual string, should not be changed to Code\n readonly errorPath: Code\n readonly propertyName?: Name\n readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,\n // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).\n // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.\n // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.\n props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function\n items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n readonly createErrors?: boolean\n readonly opts: InstanceOptions // Ajv instance option.\n readonly self: Ajv // current Ajv instance\n}\n\nexport interface SchemaObjCxt extends SchemaCxt {\n readonly schema: AnySchemaObject\n}\ninterface SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root?: SchemaEnv\n readonly baseId?: string\n readonly schemaPath?: string\n readonly localRefs?: LocalRefs\n readonly meta?: boolean\n}\n\nexport class SchemaEnv implements SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root: SchemaEnv\n baseId: string // TODO possibly, it should be readonly\n schemaPath?: string\n localRefs?: LocalRefs\n readonly meta?: boolean\n readonly $async?: boolean // true if the current schema is asynchronous.\n readonly refs: SchemaRefs = {}\n readonly dynamicAnchors: {[Ref in string]?: true} = {}\n validate?: AnyValidateFunction\n validateName?: ValueScopeName\n serialize?: (data: unknown) => string\n serializeName?: ValueScopeName\n parse?: (data: string) => unknown\n parseName?: ValueScopeName\n\n constructor(env: SchemaEnvArgs) {\n let schema: AnySchemaObject | undefined\n if (typeof env.schema == \"object\") schema = env.schema\n this.schema = env.schema\n this.schemaId = env.schemaId\n this.root = env.root || this\n this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || \"$id\"])\n this.schemaPath = env.schemaPath\n this.localRefs = env.localRefs\n this.meta = env.meta\n this.$async = schema?.$async\n this.refs = {}\n }\n}\n\n// let codeSize = 0\n// let nodeCount = 0\n\n// Compiles schema in SchemaEnv\nexport function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {\n // TODO refactor - remove compilations\n const _sch = getCompilingSchema.call(this, sch)\n if (_sch) return _sch\n const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails\n const {es5, lines} = this.opts.code\n const {ownProperties} = this.opts\n const gen = new CodeGen(this.scope, {es5, lines, ownProperties})\n let _ValidationError\n if (sch.$async) {\n _ValidationError = gen.scopeValue(\"Error\", {\n ref: ValidationError,\n code: _`require(\"ajv/dist/runtime/validation_error\").default`,\n })\n }\n\n const validateName = gen.scopeName(\"validate\")\n sch.validateName = validateName\n\n const schemaCxt: SchemaCxt = {\n gen,\n allErrors: this.opts.allErrors,\n data: N.data,\n parentData: N.parentData,\n parentDataProperty: N.parentDataProperty,\n dataNames: [N.data],\n dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?\n dataLevel: 0,\n dataTypes: [],\n definedProperties: new Set<string>(),\n topSchemaRef: gen.scopeValue(\n \"schema\",\n this.opts.code.source === true\n ? {ref: sch.schema, code: stringify(sch.schema)}\n : {ref: sch.schema}\n ),\n validateName,\n ValidationError: _ValidationError,\n schema: sch.schema,\n schemaEnv: sch,\n rootId,\n baseId: sch.baseId || rootId,\n schemaPath: nil,\n errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n errorPath: _`\"\"`,\n opts: this.opts,\n self: this,\n }\n\n let sourceCode: string | undefined\n try {\n this._compilations.add(sch)\n validateFunctionCode(schemaCxt)\n gen.optimize(this.opts.code.optimize)\n // gen.optimize(1)\n const validateCode = gen.toString()\n sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`\n // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)\n const validate: AnyValidateFunction = makeValidate(this, this.scope.get())\n this.scope.value(validateName, {ref: validate})\n\n validate.errors = null\n validate.schema = sch.schema\n validate.schemaEnv = sch\n if (sch.$async) (validate as AsyncValidateFunction).$async = true\n if (this.opts.code.source === true) {\n validate.source = {validateName, validateCode, scopeValues: gen._values}\n }\n if (this.opts.unevaluated) {\n const {props, items} = schemaCxt\n validate.evaluated = {\n props: props instanceof Name ? undefined : props,\n items: items instanceof Name ? undefined : items,\n dynamicProps: props instanceof Name,\n dynamicItems: items instanceof Name,\n }\n if (validate.source) validate.source.evaluated = stringify(validate.evaluated)\n }\n sch.validate = validate\n return sch\n } catch (e) {\n delete sch.validate\n delete sch.validateName\n if (sourceCode) this.logger.error(\"Error compiling schema, function code:\", sourceCode)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n throw e\n } finally {\n this._compilations.delete(sch)\n }\n}\n\nexport function resolveRef(\n this: Ajv,\n root: SchemaEnv,\n baseId: string,\n ref: string\n): AnySchema | SchemaEnv | undefined {\n ref = resolveUrl(this.opts.uriResolver, baseId, ref)\n const schOrFunc = root.refs[ref]\n if (schOrFunc) return schOrFunc\n\n let _sch = resolve.call(this, root, ref)\n if (_sch === undefined) {\n const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv\n const {schemaId} = this.opts\n if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})\n }\n\n if (_sch === undefined) return\n return (root.refs[ref] = inlineOrCompile.call(this, _sch))\n}\n\nfunction inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {\n if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema\n return sch.validate ? sch : compileSchema.call(this, sch)\n}\n\n// Index of schema compilation in the currently compiled list\nexport function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {\n for (const sch of this._compilations) {\n if (sameSchemaEnv(sch, schEnv)) return sch\n }\n}\n\nfunction sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {\n return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId\n}\n\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(\n this: Ajv,\n root: SchemaEnv, // information about the root schema for the current schema\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n let sch\n while (typeof (sch = this.refs[ref]) == \"string\") ref = sch\n return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)\n}\n\n// Resolve schema, its root and baseId\nexport function resolveSchema(\n this: Ajv,\n root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n const p = this.opts.uriResolver.parse(ref)\n const refPath = _getFullPath(this.opts.uriResolver, p)\n let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)\n // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n return getJsonPointer.call(this, p, root)\n }\n\n const id = normalizeId(refPath)\n const schOrRef = this.refs[id] || this.schemas[id]\n if (typeof schOrRef == \"string\") {\n const sch = resolveSchema.call(this, root, schOrRef)\n if (typeof sch?.schema !== \"object\") return\n return getJsonPointer.call(this, p, sch)\n }\n\n if (typeof schOrRef?.schema !== \"object\") return\n if (!schOrRef.validate) compileSchema.call(this, schOrRef)\n if (id === normalizeId(ref)) {\n const {schema} = schOrRef\n const {schemaId} = this.opts\n const schId = schema[schemaId]\n if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n return new SchemaEnv({schema, schemaId, root, baseId})\n }\n return getJsonPointer.call(this, p, schOrRef)\n}\n\nconst PREVENT_SCOPE_CHANGE = new Set([\n \"properties\",\n \"patternProperties\",\n \"enum\",\n \"dependencies\",\n \"definitions\",\n])\n\nfunction getJsonPointer(\n this: Ajv,\n parsedRef: URIComponent,\n {baseId, schema, root}: SchemaEnv\n): SchemaEnv | undefined {\n if (parsedRef.fragment?.[0] !== \"/\") return\n for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n if (typeof schema === \"boolean\") return\n const partSchema = schema[unescapeFragment(part)]\n if (partSchema === undefined) return\n schema = partSchema\n // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n const schId = typeof schema === \"object\" && schema[this.opts.schemaId]\n if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n }\n }\n let env: SchemaEnv | undefined\n if (typeof schema != \"boolean\" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {\n const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)\n env = resolveSchema.call(this, root, $ref)\n }\n // even though resolution failed we need to return SchemaEnv to throw exception\n // so that compileAsync loads missing schema.\n const {schemaId} = this.opts\n env = env || new SchemaEnv({schema, schemaId, root, baseId})\n if (env.schema !== env.root.schema) return env\n return undefined\n}\n","{\n \"$id\": \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n \"description\": \"Meta-schema for $data reference (JSON AnySchema extension proposal)\",\n \"type\": \"object\",\n \"required\": [\"$data\"],\n \"properties\": {\n \"$data\": {\n \"type\": \"string\",\n \"anyOf\": [{\"format\": \"relative-json-pointer\"}, {\"format\": \"json-pointer\"}]\n }\n },\n \"additionalProperties\": false\n}\n","'use strict'\n\n/** @type {(value: string) => boolean} */\nconst isUUID = RegExp.prototype.test.bind(/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)$/u)\n\n/** @type {(value: string) => boolean} */\nconst isPort = RegExp.prototype.test.bind(/^\\d*$/u)\n\n/** @type {(value: string) => boolean} */\nconst isHexPair = RegExp.prototype.test.bind(/^[\\da-f]{2}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isUnreserved = RegExp.prototype.test.bind(/^[\\da-z\\-._~]$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\\-._~!$&'()*+,;=:@/]$/u)\n\n/** @type {(value: string) => boolean} */\nconst isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\\-._~!$&'()*+,;=:@/?]$/u)\n\n/** @type {(value: string) => boolean} */\nconst isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\\-._~!$&'()*+,;=:]$/u)\n\nconst BYTE_HEX = new Array(256)\n{\n const HEX_DIGITS = '0123456789ABCDEF'\n for (let i = 0; i < 256; i++) {\n BYTE_HEX[i] = '%' + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 0xF]\n }\n}\nfunction percentEncodeNonAscii (cp) {\n if (cp < 0x800) {\n return BYTE_HEX[0xC0 | (cp >> 6)] +\n BYTE_HEX[0x80 | (cp & 0x3F)]\n }\n if (cp < 0x10000) {\n return BYTE_HEX[0xE0 | (cp >> 12)] +\n BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +\n BYTE_HEX[0x80 | (cp & 0x3F)]\n }\n return BYTE_HEX[0xF0 | (cp >> 18)] +\n BYTE_HEX[0x80 | ((cp >> 12) & 0x3F)] +\n BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +\n BYTE_HEX[0x80 | (cp & 0x3F)]\n}\n\n/**\n * @param {Array<string>} input\n * @returns {string}\n */\nfunction stringArrayToHexStripped (input) {\n let acc = ''\n let code = 0\n let i = 0\n\n for (i = 0; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (code === 48) {\n continue\n }\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n break\n }\n\n for (i += 1; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n }\n return acc\n}\n\n/** @type {(value: string) => boolean} */\nconst isHextet = RegExp.prototype.test.bind(/^[\\dA-Fa-f]{1,4}$/)\n\n/** @type {(value: string) => boolean} */\nconst isIPvFuture = RegExp.prototype.test.bind(/^[vV][\\dA-Fa-f]+\\.[A-Za-z\\d\\-._~!$&'()*+,;=:]+$/)\n\n/** @type {(value: string) => boolean} */\nconst isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\\d\\-._~]$/)\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nconst nonSimpleDomain = RegExp.prototype.test.bind(/[^!\"$&'()*+,\\-.;=_`a-z{}~]/u)\n\n/**\n * @param {string} zone\n * @returns {boolean}\n */\nfunction isZoneIdentifier (zone) {\n if (zone.length === 0) return false\n\n for (let i = 0; i < zone.length; i++) {\n if (isZoneCharacter(zone[i])) continue\n if (zone[i] === '%' && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {\n i += 2\n continue\n }\n return false\n }\n\n return true\n}\n\n/**\n * Compresses the longest run of zero hextets to \"::\" per RFC 5952. A run of a\n * single zero hextet is left uncompressed. On ties the leftmost run wins.\n *\n * @param {string[]} hextets\n * @returns {string}\n */\nfunction compressIPv6ZeroRun (hextets) {\n let bestStart = -1\n let bestLength = 0\n let runStart = -1\n let runLength = 0\n for (let i = 0; i < hextets.length; i++) {\n if (hextets[i] === '0') {\n if (runStart === -1) runStart = i\n runLength++\n if (runLength > bestLength) {\n bestLength = runLength\n bestStart = runStart\n }\n } else {\n runStart = -1\n runLength = 0\n }\n }\n\n if (bestLength < 2) return hextets.join(':')\n\n const head = hextets.slice(0, bestStart).join(':')\n const tail = hextets.slice(bestStart + bestLength).join(':')\n return head + '::' + tail\n}\n\n/**\n * Validates an IPv6 address against the alternatives in RFC 3986 section\n * 3.2.2 and returns the same address with leading hextet zeroes removed.\n * An embedded IPv4 address counts as two hextets and is only valid at the end.\n *\n * @param {string} input\n * @returns {string|undefined}\n */\nfunction normalizeIPv6Address (input) {\n const compression = input.indexOf('::')\n if (compression !== -1 && input.indexOf('::', compression + 1) !== -1) return undefined\n\n const left = compression === -1 ? input.split(':') : input.slice(0, compression).split(':')\n const right = compression === -1 ? [] : input.slice(compression + 2).split(':')\n if (compression !== -1) {\n if (left.length === 1 && left[0] === '') left.length = 0\n if (right.length === 1 && right[0] === '') right.length = 0\n }\n\n const parts = left.concat(right)\n let hextetCount = 0\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i]\n if (part === '') return undefined\n\n if (part.indexOf('.') !== -1) {\n if (i !== parts.length - 1 || (compression !== -1 && right.length === 0) || !isIPv4(part)) return undefined\n hextetCount += 2\n continue\n }\n\n if (!isHextet(part)) return undefined\n parts[i] = parseInt(part, 16).toString(16)\n hextetCount++\n }\n\n if (compression === -1) {\n if (hextetCount !== 8) return undefined\n return compressIPv6ZeroRun(parts)\n }\n if (hextetCount >= 8) return undefined\n\n // expand \"::\" then re-compress the longest run for a canonical result\n const expanded = parts.slice(0, left.length)\n for (let i = hextetCount; i < 8; i++) expanded.push('0')\n for (let i = left.length; i < parts.length; i++) expanded.push(parts[i])\n return compressIPv6ZeroRun(expanded)\n}\n\n/**\n * @typedef {Object} NormalizeIPv6Result\n * @property {string} host - The normalized host.\n * @property {string} [escapedHost] - The escaped host.\n * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.\n * @property {boolean} [isIPVFuture] - Indicates if the host is an IPvFuture literal.\n * @property {boolean} [error] - Indicates if a bracketed IP literal is malformed.\n */\n\n/**\n * Validates and normalizes a bracketed IP literal. Raw zone separators remain\n * accepted for backwards compatibility, while encoded separators and zone\n * contents follow RFC 6874.\n *\n * @param {string} host\n * @returns {NormalizeIPv6Result}\n */\nfunction normalizeIPv6 (host) {\n const bracketed = host[0] === '[' && host[host.length - 1] === ']'\n const hasBracket = host[0] === '[' || host[host.length - 1] === ']'\n if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }\n\n let input = bracketed ? host.slice(1, -1) : host\n if (bracketed && isIPvFuture(input)) {\n input = input.toLowerCase()\n return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }\n }\n\n if (findToken(input, ':') < 2) {\n return { host, isIPV6: false, error: bracketed }\n }\n\n let zoneIdentifier = ''\n const zoneSeparator = input.indexOf('%')\n if (zoneSeparator !== -1) {\n const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === '%25' ? 3 : 1\n zoneIdentifier = input.slice(zoneSeparator + separatorLength)\n if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }\n input = input.slice(0, zoneSeparator)\n }\n\n const address = normalizeIPv6Address(input)\n if (address === undefined) return { host, isIPV6: false, error: true }\n\n return {\n host: address + (zoneIdentifier ? '%' + zoneIdentifier : ''),\n escapedHost: address + (zoneIdentifier ? '%25' + zoneIdentifier : ''),\n isIPV6: true\n }\n}\n\n/**\n * @param {string} str\n * @param {string} token\n * @returns {number}\n */\nfunction findToken (str, token) {\n let ind = 0\n for (let i = 0; i < str.length; i++) {\n if (str[i] === token) ind++\n }\n return ind\n}\n\n/**\n * @param {string} path\n * @returns {string}\n *\n * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4\n */\nfunction removeDotSegments (path) {\n let input = path\n const output = []\n let nextSlash = -1\n let len = 0\n\n // eslint-disable-next-line no-cond-assign\n while (len = input.length) {\n if (len === 1) {\n if (input === '.') {\n break\n } else if (input === '/') {\n output.push('/')\n break\n } else {\n output.push(input)\n break\n }\n } else if (len === 2) {\n if (input[0] === '.') {\n if (input[1] === '.') {\n break\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.' || input[1] === '/') {\n output.push('/')\n break\n }\n }\n } else if (len === 3) {\n if (input === '/..') {\n if (output.length !== 0) {\n output.pop()\n }\n output.push('/')\n break\n }\n }\n if (input[0] === '.') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(3)\n continue\n }\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(2)\n continue\n } else if (input[2] === '.') {\n if (input[3] === '/') {\n input = input.slice(3)\n if (output.length !== 0) {\n output.pop()\n }\n continue\n }\n }\n }\n }\n\n // Rule 2E: Move normal path segment to output\n if ((nextSlash = input.indexOf('/', 1)) === -1) {\n output.push(input)\n break\n } else {\n output.push(input.slice(0, nextSlash))\n input = input.slice(nextSlash)\n }\n }\n\n return output.join('')\n}\n\n/**\n * Re-escape RFC 3986 gen-delims that must not appear literally in the host.\n * After the URI regex parses, these characters cannot be literal in the host\n * field, so any that appear after decoding came from percent-encoding and\n * must be restored to prevent authority structure changes.\n *\n * @param {string} host\n * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping)\n * @returns {string}\n */\nconst HOST_DELIMS = { '@': '%40', '/': '%2F', '?': '%3F', '#': '%23', ':': '%3A' }\nconst HOST_DELIM_RE = /[@/?#:]/g\nconst HOST_DELIM_NO_COLON_RE = /[@/?#]/g\n\nfunction reescapeHostDelimiters (host, isIP) {\n const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE\n re.lastIndex = 0\n return host.replace(re, (ch) => HOST_DELIMS[ch])\n}\n\n/**\n * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.\n * Reserved delimiters such as `%2F` stay escaped; `%2E` is unreserved.\n *\n * @param {string} input\n * @param {boolean} [decodeUnreserved=false]\n * @returns {string}\n */\nfunction normalizePercentEncoding (input, decodeUnreserved = false) {\n if (input.indexOf('%') === -1) {\n return input\n }\n\n let output = ''\n\n for (let i = 0; i < input.length; i++) {\n if (input[i] === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n const normalizedHex = hex.toUpperCase()\n const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n if (decodeUnreserved && isUnreserved(decoded)) {\n output += decoded\n } else {\n output += '%' + normalizedHex\n }\n\n i += 2\n continue\n }\n }\n\n output += input[i]\n }\n\n return output\n}\n\n/**\n * Normalizes path data without turning reserved escapes into live path syntax.\n * Valid escapes are uppercased, raw unsafe characters are escaped, and only\n * unreserved bytes that are not `.` are decoded.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction normalizePathEncoding (input) {\n let output = ''\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i]\n if (ch === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n const normalizedHex = hex.toUpperCase()\n const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n if (decoded !== '.' && isUnreserved(decoded)) {\n output += decoded\n } else {\n output += '%' + normalizedHex\n }\n\n i += 2\n continue\n }\n }\n\n if (isPathCharacter(ch)) {\n output += ch\n } else {\n const code = input.charCodeAt(i)\n if (code < 0x80) {\n output += isEscapeSafe(code) ? ch : BYTE_HEX[code]\n } else if (code < 0xD800 || code > 0xDFFF) {\n output += percentEncodeNonAscii(code)\n } else if (code <= 0xDBFF && i + 1 < input.length) {\n const low = input.charCodeAt(i + 1)\n if (low >= 0xDC00 && low <= 0xDFFF) {\n output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))\n i++\n } else {\n output += percentEncodeNonAscii(0xFFFD)\n }\n } else {\n output += percentEncodeNonAscii(0xFFFD)\n }\n }\n }\n\n return output\n}\n\n/**\n * Serializes a path without rewriting reserved data. Raw RFC 3986 path\n * characters remain literal, valid escapes are preserved and uppercased, and\n * everything else is UTF-8 percent-encoded. In a path-noscheme, a colon in the\n * first segment must be escaped so the result cannot be parsed as a scheme.\n *\n * @param {string} input\n * @param {boolean} [pathNoScheme=false]\n * @returns {string}\n */\nfunction serializePathEncoding (input, pathNoScheme = false) {\n let output = ''\n let firstSegment = pathNoScheme && input[0] !== '/'\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i]\n if (ch === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n output += '%' + hex.toUpperCase()\n i += 2\n continue\n }\n }\n\n if (ch === '/') {\n firstSegment = false\n }\n\n if (isPathCharacter(ch) && (ch !== ':' || !firstSegment)) {\n output += ch\n } else {\n const code = input.charCodeAt(i)\n if (code < 0x80) {\n output += BYTE_HEX[code]\n } else if (code < 0xD800 || code > 0xDFFF) {\n output += percentEncodeNonAscii(code)\n } else if (code <= 0xDBFF && i + 1 < input.length) {\n const low = input.charCodeAt(i + 1)\n if (low >= 0xDC00 && low <= 0xDFFF) {\n output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))\n i++\n } else {\n output += percentEncodeNonAscii(0xFFFD)\n }\n } else {\n output += percentEncodeNonAscii(0xFFFD)\n }\n }\n }\n\n return output\n}\n\n/**\n * Percent-encodes a URI component using its RFC 3986 literal character set.\n * Existing valid escapes are preserved and normalized to uppercase hex.\n *\n * @param {string} input\n * @param {(value: string) => boolean} isAllowed\n * @returns {string}\n */\nfunction encodeComponent (input, isAllowed) {\n let output = ''\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i]\n if (ch === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n output += '%' + hex.toUpperCase()\n i += 2\n continue\n }\n }\n\n if (isAllowed(ch)) {\n output += ch\n } else {\n const code = input.charCodeAt(i)\n if (code < 0x80) {\n output += BYTE_HEX[code]\n } else if (code < 0xD800 || code > 0xDFFF) {\n output += percentEncodeNonAscii(code)\n } else if (code <= 0xDBFF && i + 1 < input.length) {\n const low = input.charCodeAt(i + 1)\n if (low >= 0xDC00 && low <= 0xDFFF) {\n output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))\n i++\n } else {\n output += percentEncodeNonAscii(0xFFFD)\n }\n } else {\n output += percentEncodeNonAscii(0xFFFD)\n }\n }\n }\n\n return output\n}\n\n/**\n * Encodes userinfo while preserving its RFC 3986 §3.2.1 literal characters.\n * In particular, authority delimiters such as `@`, `/`, `?`, and `#` are data.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction encodeUserinfo (input) {\n return encodeComponent(input, isUserinfoCharacter)\n}\n\n/**\n * Encodes query data using the RFC 3986 §3.4 grammar. A literal `#` must be\n * escaped because it would otherwise begin the fragment component.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction encodeQuery (input) {\n return encodeComponent(input, isQueryFragmentCharacter)\n}\n\n/**\n * Encodes fragment data using the RFC 3986 §3.5 grammar.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction encodeFragment (input) {\n return encodeComponent(input, isQueryFragmentCharacter)\n}\n\nfunction isEscapeSafe (cp) {\n return (\n (cp >= 0x30 && cp <= 0x39) ||\n (cp >= 0x41 && cp <= 0x5A) ||\n (cp >= 0x61 && cp <= 0x7A) ||\n cp === 0x2A || cp === 0x2B || cp === 0x2D || cp === 0x2E ||\n cp === 0x2F || cp === 0x40 || cp === 0x5F\n )\n}\n\n/**\n * Normalizes the percent-encoding of a query or fragment component.\n *\n * Like `normalizePathEncoding`, but uses the query/fragment character set\n * (which additionally allows `?`) and decodes `.` since it has no dot-segment\n * meaning outside of a path.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction normalizeQueryFragmentEncoding (input) {\n let output = ''\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i]\n if (ch === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n const normalizedHex = hex.toUpperCase()\n const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n if (isUnreserved(decoded)) {\n output += decoded\n } else {\n output += '%' + normalizedHex\n }\n\n i += 2\n continue\n }\n }\n\n if (isQueryFragmentCharacter(ch)) {\n output += ch\n } else {\n const code = input.charCodeAt(i)\n if (code < 0x80) {\n output += isEscapeSafe(code) ? ch : BYTE_HEX[code]\n } else if (code < 0xD800 || code > 0xDFFF) {\n output += percentEncodeNonAscii(code)\n } else if (code <= 0xDBFF && i + 1 < input.length) {\n const low = input.charCodeAt(i + 1)\n if (low >= 0xDC00 && low <= 0xDFFF) {\n output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))\n i++\n } else {\n output += percentEncodeNonAscii(0xFFFD)\n }\n } else {\n output += percentEncodeNonAscii(0xFFFD)\n }\n }\n }\n\n return output\n}\n\n/**\n * Escapes a component while preserving existing valid percent escapes.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction escapePreservingEscapes (input) {\n let output = ''\n\n for (let i = 0; i < input.length; i++) {\n if (input[i] === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n output += '%' + hex.toUpperCase()\n i += 2\n continue\n }\n }\n\n output += escape(input[i])\n }\n\n return output\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @returns {string|undefined}\n */\nfunction recomposeAuthority (component) {\n const uriTokens = []\n\n if (component.userinfo !== undefined) {\n uriTokens.push(encodeUserinfo(component.userinfo))\n uriTokens.push('@')\n }\n\n if (component.host !== undefined) {\n let host = component.host\n if (!isIPv4(host)) {\n let ipV6res = normalizeIPv6(host)\n if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {\n // Decode only unreserved bytes, once. In particular, keep %25 encoded\n // so it cannot introduce a second escape during recomposition.\n host = normalizePercentEncoding(host, true)\n ipV6res = normalizeIPv6(host)\n }\n if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {\n host = `[${ipV6res.escapedHost}]`\n } else {\n host = reescapeHostDelimiters(host, false)\n }\n }\n uriTokens.push(host)\n }\n\n if (typeof component.port === 'number' || typeof component.port === 'string') {\n const port = String(component.port)\n if (!isPort(port)) {\n throw new TypeError('URI port is malformed.')\n }\n uriTokens.push(':')\n uriTokens.push(port)\n }\n\n return uriTokens.length ? uriTokens.join('') : undefined\n};\n\nmodule.exports = {\n nonSimpleDomain,\n recomposeAuthority,\n reescapeHostDelimiters,\n normalizePercentEncoding,\n normalizePathEncoding,\n serializePathEncoding,\n normalizeQueryFragmentEncoding,\n encodeUserinfo,\n encodeQuery,\n encodeFragment,\n escapePreservingEscapes,\n removeDotSegments,\n isIPv4,\n isUUID,\n normalizeIPv6,\n stringArrayToHexStripped\n}\n","'use strict'\n\nconst { isUUID } = require('./utils')\nconst URN_REG = /^([\\da-z][\\d\\-a-z]{0,31}):((?:[\\w!$'()*+,\\-./:;=@]|%[\\da-f]{2})+)$/iu\n\nconst supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',\n 'wss', 'urn', 'urn:uuid'])\n\n/** @typedef {supportedSchemeNames[number]} SchemeName */\n\n/**\n * @param {string} name\n * @returns {name is SchemeName}\n */\nfunction isValidSchemeName (name) {\n return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1\n}\n\n/**\n * @callback SchemeFn\n * @param {import('../types/index').URIComponent} component\n * @param {import('../types/index').Options} options\n * @returns {import('../types/index').URIComponent}\n */\n\n/**\n * @typedef {Object} SchemeHandler\n * @property {SchemeName} scheme - The scheme name.\n * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.\n * @property {SchemeFn} parse - Function to parse the URI component for this scheme.\n * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.\n * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.\n * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.\n * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.\n */\n\n/**\n * @param {import('../types/index').URIComponent} wsComponent\n * @returns {boolean}\n */\nfunction wsIsSecure (wsComponent) {\n if (wsComponent.secure === true) {\n return true\n } else if (wsComponent.secure === false) {\n return false\n } else if (wsComponent.scheme) {\n return (\n wsComponent.scheme.length === 3 &&\n (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&\n (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&\n (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')\n )\n } else {\n return false\n }\n}\n\n/** @type {SchemeFn} */\nfunction httpParse (component) {\n if (!component.host) {\n component.error = component.error || 'HTTP URIs must have a host.'\n }\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction httpSerialize (component) {\n const secure = String(component.scheme).toLowerCase() === 'https'\n\n // normalize the default port\n if (component.port === (secure ? 443 : 80) || component.port === '') {\n component.port = undefined\n }\n\n // normalize the empty path\n if (!component.path) {\n component.path = '/'\n }\n\n // NOTE: We do not parse query strings for HTTP URIs\n // as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n // and not the HTTP spec.\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction wsParse (wsComponent) {\n// indicate if the secure flag is set\n wsComponent.secure = wsIsSecure(wsComponent)\n\n // construct resouce name\n wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')\n wsComponent.path = undefined\n wsComponent.query = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction wsSerialize (wsComponent) {\n// normalize the default port\n if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {\n wsComponent.port = undefined\n }\n\n // ensure scheme matches secure flag\n if (typeof wsComponent.secure === 'boolean') {\n wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')\n wsComponent.secure = undefined\n }\n\n // reconstruct path from resource name\n if (wsComponent.resourceName) {\n const queryIndex = wsComponent.resourceName.indexOf('?')\n const path = queryIndex === -1\n ? wsComponent.resourceName\n : wsComponent.resourceName.slice(0, queryIndex)\n wsComponent.path = (path && path !== '/' ? path : undefined)\n wsComponent.query = queryIndex === -1\n ? undefined\n : wsComponent.resourceName.slice(queryIndex + 1)\n wsComponent.resourceName = undefined\n }\n\n // forbid fragment component\n wsComponent.fragment = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnParse (urnComponent, options) {\n if (!urnComponent.path) {\n urnComponent.error = 'URN can not be parsed'\n return urnComponent\n }\n const matches = urnComponent.path.match(URN_REG)\n if (matches && matches[0] === urnComponent.path) {\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n urnComponent.nid = matches[1].toLowerCase()\n urnComponent.nss = matches[2]\n const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n urnComponent.path = undefined\n\n if (schemeHandler) {\n urnComponent = schemeHandler.parse(urnComponent, options)\n }\n } else {\n urnComponent.error = urnComponent.error || 'URN can not be parsed.'\n }\n\n return urnComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnSerialize (urnComponent, options) {\n if (urnComponent.nid === undefined) {\n throw new Error('URN without nid cannot be serialized')\n }\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n const nid = urnComponent.nid.toLowerCase()\n const urnScheme = `${scheme}:${options.nid || nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n\n if (schemeHandler) {\n urnComponent = schemeHandler.serialize(urnComponent, options)\n }\n\n const uriComponent = urnComponent\n const nss = urnComponent.nss\n uriComponent.path = `${nid || options.nid}:${nss}`\n\n options.skipEscape = true\n return uriComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidParse (urnComponent, options) {\n const uuidComponent = urnComponent\n uuidComponent.uuid = uuidComponent.nss\n uuidComponent.nss = undefined\n\n if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {\n uuidComponent.error = uuidComponent.error || 'UUID is not valid.'\n }\n\n return uuidComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidSerialize (uuidComponent) {\n const urnComponent = uuidComponent\n // normalize UUID\n urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()\n return urnComponent\n}\n\nconst http = /** @type {SchemeHandler} */ ({\n scheme: 'http',\n domainHost: true,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst https = /** @type {SchemeHandler} */ ({\n scheme: 'https',\n domainHost: http.domainHost,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst ws = /** @type {SchemeHandler} */ ({\n scheme: 'ws',\n domainHost: true,\n parse: wsParse,\n serialize: wsSerialize\n})\n\nconst wss = /** @type {SchemeHandler} */ ({\n scheme: 'wss',\n domainHost: ws.domainHost,\n parse: ws.parse,\n serialize: ws.serialize\n})\n\nconst urn = /** @type {SchemeHandler} */ ({\n scheme: 'urn',\n parse: urnParse,\n serialize: urnSerialize,\n skipNormalize: true\n})\n\nconst urnuuid = /** @type {SchemeHandler} */ ({\n scheme: 'urn:uuid',\n parse: urnuuidParse,\n serialize: urnuuidSerialize,\n skipNormalize: true\n})\n\nconst SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({\n http,\n https,\n ws,\n wss,\n urn,\n 'urn:uuid': urnuuid\n})\n\nObject.setPrototypeOf(SCHEMES, null)\n\n/**\n * @param {string|undefined} scheme\n * @returns {SchemeHandler|undefined}\n */\nfunction getSchemeHandler (scheme) {\n return (\n scheme && (\n SCHEMES[/** @type {SchemeName} */ (scheme)] ||\n SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])\n ) ||\n undefined\n}\n\nmodule.exports = {\n wsIsSecure,\n SCHEMES,\n isValidSchemeName,\n getSchemeHandler,\n}\n","'use strict'\n\nconst { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require('./lib/utils')\nconst { SCHEMES, getSchemeHandler } = require('./lib/schemes')\n\nconst VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u\nconst MALFORMED_SCHEME_ERROR = 'URI scheme is malformed.'\n\n/**\n * @param {string} scheme\n * @returns {string}\n */\nfunction decodeValidScheme (scheme) {\n const decodedScheme = unescape(String(scheme))\n if (!VALID_SCHEME.test(decodedScheme)) {\n throw new TypeError(MALFORMED_SCHEME_ERROR)\n }\n return decodedScheme\n}\n\n/**\n * @template {import('./types/index').URIComponent|string} T\n * @param {T} uri\n * @param {import('./types/index').Options} [options]\n * @returns {T}\n */\nfunction normalize (uri, options) {\n if (typeof uri === 'string') {\n uri = /** @type {T} */ (normalizeString(uri, options))\n } else if (typeof uri === 'object') {\n uri = /** @type {T} */ (parse(serialize(uri, options), options))\n }\n return uri\n}\n\n/**\n * @param {string} baseURI\n * @param {string} relativeURI\n * @param {import('./types/index').Options} [options]\n * @returns {string}\n */\nfunction resolve (baseURI, relativeURI, options) {\n const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }\n const {\n parsed: baseParsed,\n malformedAuthorityOrPort: baseMalformed,\n malformedPercentEncoding: baseMalformedPercentEncoding,\n malformedSchemeSpecific: baseMalformedSchemeSpecific,\n malformedHost: baseMalformedHost,\n malformedScheme: baseMalformedScheme\n } = parseWithStatus(baseURI, schemelessOptions)\n const {\n parsed: relativeParsed,\n malformedAuthorityOrPort: relativeMalformed,\n malformedPercentEncoding: relativeMalformedPercentEncoding,\n malformedSchemeSpecific: relativeMalformedSchemeSpecific,\n malformedHost: relativeMalformedHost,\n malformedScheme: relativeMalformedScheme\n } = parseWithStatus(relativeURI, schemelessOptions)\n if (\n baseMalformed ||\n relativeMalformed ||\n baseMalformedPercentEncoding ||\n relativeMalformedPercentEncoding ||\n baseMalformedSchemeSpecific ||\n relativeMalformedSchemeSpecific ||\n baseMalformedHost ||\n relativeMalformedHost ||\n baseMalformedScheme ||\n relativeMalformedScheme\n ) {\n throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.')\n }\n const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true)\n const resolvedSchemeHandler = getSchemeHandler((options && options.scheme) || resolved.scheme)\n const resolvedHost = resolved.host\n const resolvedHostIsIP = resolvedHost !== undefined && resolvedHost !== '' &&\n (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6)\n canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)\n // Percent escapes in an ASCII reg-name are encoded data. The WHATWG hostname\n // parser can reject them even though fast-uri preserves them safely as RFC\n // 3986 data. A raw non-ASCII host must still fail closed if conversion fails.\n const encodedASCIIHost = resolvedHost && resolvedHost.indexOf('%') !== -1 &&\n !/\\P{ASCII}/u.test(resolvedHost)\n if (resolved.error && !encodedASCIIHost) {\n throw new Error(resolved.error)\n }\n schemelessOptions.skipEscape = true\n return serialize(resolved, schemelessOptions)\n}\n\n/**\n * @param {import ('./types/index').URIComponent} base\n * @param {import ('./types/index').URIComponent} relative\n * @param {import('./types/index').Options} [options]\n * @param {boolean} [skipNormalization=false]\n * @returns {import ('./types/index').URIComponent}\n */\nfunction resolveComponent (base, relative, options, skipNormalization) {\n /** @type {import('./types/index').URIComponent} */\n const target = {}\n if (!skipNormalization) {\n base = parse(serialize(base, options), options) // normalize base component\n relative = parse(serialize(relative, options), options) // normalize relative component\n }\n options = options || {}\n\n if (!options.tolerant && relative.scheme) {\n target.scheme = relative.scheme\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (!relative.path) {\n target.path = base.path\n if (relative.query !== undefined) {\n target.query = relative.query\n } else {\n target.query = base.query\n }\n } else {\n if (relative.path[0] === '/') {\n target.path = removeDotSegments(relative.path)\n } else {\n if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n target.path = '/' + relative.path\n } else if (!base.path) {\n target.path = relative.path\n } else {\n target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path\n }\n target.path = removeDotSegments(target.path)\n }\n target.query = relative.query\n }\n // target.authority = base.authority;\n target.userinfo = base.userinfo\n target.host = base.host\n target.port = base.port\n }\n target.scheme = base.scheme\n }\n\n target.fragment = relative.fragment\n\n return target\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uriA\n * @param {import ('./types/index').URIComponent|string} uriB\n * @param {import ('./types/index').Options} options\n * @returns {boolean}\n */\nfunction equal (uriA, uriB, options) {\n const normalizedA = normalizeComparableURI(uriA, options)\n const normalizedB = normalizeComparableURI(uriB, options)\n\n return normalizedA !== undefined && normalizedB !== undefined && normalizedA === normalizedB\n}\n\n/**\n * @param {Readonly<import('./types/index').URIComponent>} cmpts\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction serialize (cmpts, opts) {\n const component = {\n host: cmpts.host,\n scheme: cmpts.scheme,\n userinfo: cmpts.userinfo,\n port: cmpts.port,\n path: cmpts.path,\n query: cmpts.query,\n nid: cmpts.nid,\n nss: cmpts.nss,\n uuid: cmpts.uuid,\n fragment: cmpts.fragment,\n reference: cmpts.reference,\n resourceName: cmpts.resourceName,\n secure: cmpts.secure,\n error: ''\n }\n const options = Object.assign({}, opts)\n const uriTokens = []\n\n if (component.scheme) {\n component.scheme = decodeValidScheme(component.scheme)\n }\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || component.scheme)\n\n // perform scheme specific serialization\n if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)\n\n const hasAuthority = component.userinfo !== undefined || component.host !== undefined || component.port !== undefined\n const pathNoScheme = !options.skipEscape && component.scheme === undefined && !hasAuthority\n\n if (component.path !== undefined) {\n if (!options.skipEscape) {\n component.path = serializePathEncoding(component.path, pathNoScheme)\n } else {\n component.path = normalizePercentEncoding(component.path)\n }\n }\n\n if (options.reference !== 'suffix' && component.scheme) {\n // Scheme handlers may replace the scheme during serialization.\n component.scheme = decodeValidScheme(component.scheme)\n uriTokens.push(component.scheme, ':')\n }\n\n const authority = recomposeAuthority(component)\n if (authority !== undefined) {\n if (options.reference !== 'suffix') {\n uriTokens.push('//')\n }\n\n uriTokens.push(authority)\n\n if (component.path && component.path[0] !== '/') {\n uriTokens.push('/')\n }\n }\n if (component.path !== undefined) {\n let s = component.path\n\n if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n s = removeDotSegments(s)\n }\n\n // Dot-segment removal can expose a colon that was not originally in the\n // first segment (for example, \"./a:b\"). Reapply path-noscheme encoding so\n // the serialized relative reference cannot be reparsed as a URI scheme.\n if (pathNoScheme) {\n s = serializePathEncoding(s, true)\n }\n\n if (\n authority === undefined &&\n s[0] === '/' &&\n s[1] === '/'\n ) {\n // don't allow the path to start with \"//\"\n s = '/%2F' + s.slice(2)\n }\n\n uriTokens.push(s)\n }\n\n if (component.query !== undefined) {\n uriTokens.push('?', encodeQuery(component.query))\n }\n\n if (component.fragment !== undefined) {\n uriTokens.push('#', encodeFragment(component.fragment))\n }\n return uriTokens.join('')\n}\n\nconst URI_PARSE = /^(?:([^#/:?]+):)?(?:\\/\\/((?:([^#/?@]*)@)?(\\[[^#/?\\]]+\\]|[^#/:?]*)(?::(\\d*))?))?([^#?]*)(?:\\?([^#]*))?(?:#((?:.|[\\n\\r])*))?/u\n\n// Captures the authority component (between \"//\" and the next \"/\", \"?\" or \"#\"),\n// with or without a scheme prefix, for the literal-backslash rejection below.\nconst AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\\/\\/([^/?#]*)/\n\n// Captures the leading authority-introducer region after an optional scheme: a\n// run of forward slashes, backslashes, and the characters the WHATWG URL parser\n// removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer\n// is exactly \"//\". Node treats \"\\\" as \"/\" on special schemes and strips those\n// characters first, so forms like \"\\\\\", \"/\\\", \"\\/\", \"/<TAB>/\", or a leading\n// \"<TAB>//\" reach an authority in Node while fast-uri's URI_PARSE folds them into\n// the path group (host confusion / SSRF / redirect bypass).\nconst AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\\\\t\\n\\r]*)/\n\n/**\n * @param {import('./types/index').URIComponent} parsed\n * @param {RegExpMatchArray} matches\n * @returns {string|undefined}\n */\nfunction getParseError (parsed, matches) {\n if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {\n return 'URI path must start with \"/\" when authority is present.'\n }\n\n if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) {\n return 'URI port is malformed.'\n }\n\n return undefined\n}\n\n/**\n * Checks percent syntax without decoding the represented octets. RFC 3986\n * percent-encoding is byte-oriented, so sequences such as `%FF` are valid even\n * though they are not independently valid UTF-8.\n *\n * @param {string|undefined} component\n * @returns {boolean}\n */\nfunction hasMalformedPercentEncoding (component) {\n if (component === undefined) return false\n\n let percent = component.indexOf('%')\n while (percent !== -1) {\n if (percent + 2 >= component.length || !/^[\\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {\n return true\n }\n percent = component.indexOf('%', percent + 3)\n }\n\n return false\n}\n\n/**\n * Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`).\n * An unterminated `[` is not a literal, so it must still be validated as a\n * reg-name instead of being waved through as an IP.\n *\n * @param {string} host\n * @returns {boolean}\n */\nfunction isIPLiteral (host) {\n return host[0] === '[' && host[host.length - 1] === ']'\n}\n\n/**\n * @param {RegExpMatchArray} matches\n * @returns {boolean}\n */\nfunction hasMalformedComponentPercentEncoding (matches) {\n // Bracketed IP literals use a raw \"%\" as the zone separator for historical\n // compatibility. Their parsing is intentionally left to normalizeIPv6.\n const host = matches[4]\n return hasMalformedPercentEncoding(matches[3]) ||\n (host !== undefined && !isIPLiteral(host) && hasMalformedPercentEncoding(host)) ||\n hasMalformedPercentEncoding(matches[6]) ||\n hasMalformedPercentEncoding(matches[7]) ||\n hasMalformedPercentEncoding(matches[8])\n}\n\n/**\n * @param {import('./types/index').URIComponent} parsed\n * @param {import('./types/index').Options} options\n * @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler\n * @param {boolean} isIP\n * @returns {boolean} whether host conversion failed\n */\nfunction canonicalizeHost (parsed, options, schemeHandler, isIP) {\n if (\n !options.unicodeSupport &&\n (!schemeHandler || !schemeHandler.unicodeSupport) &&\n parsed.host &&\n !isIPLiteral(parsed.host) &&\n (options.domainHost || (schemeHandler && schemeHandler.domainHost)) &&\n isIP === false &&\n nonSimpleDomain(parsed.host)\n ) {\n try {\n parsed.host = new URL('http://' + parsed.host).hostname\n } catch (e) {\n parsed.error = parsed.error || \"Host's domain name can not be converted to ASCII: \" + e\n return true\n }\n }\n return false\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}\n */\nfunction parseWithStatus (uri, opts) {\n const options = Object.assign({}, opts)\n /** @type {import('./types/index').URIComponent} */\n const parsed = {\n scheme: undefined,\n userinfo: undefined,\n host: '',\n port: undefined,\n path: '',\n query: undefined,\n fragment: undefined\n }\n\n let malformedAuthorityOrPort = false\n let malformedPercentEncoding = false\n let malformedSchemeSpecific = false\n let malformedHost = false\n let malformedIPLiteral = false\n let malformedScheme = false\n\n let isIP = false\n if (options.reference === 'suffix') {\n if (options.scheme) {\n uri = options.scheme + ':' + uri\n } else {\n uri = '//' + uri\n }\n }\n\n // A literal backslash (U+005C) is not a valid RFC 3986 URI character and is\n // not an authority delimiter. Reject it in the authority rather than\n // rewriting it: normalizing \"\\\" -> \"/\" (WHATWG error recovery) could silently\n // change the resource identified by an otherwise-invalid input, and lets \"\\\"\n // act as a host delimiter here while Node's native URL parses a different\n // host (SSRF / redirect / origin-allowlist bypass). Percent-encoded %5C is\n // untouched and remains valid encoded data.\n const authorityMatch = uri.match(AUTHORITY_PREFIX)\n if (authorityMatch !== null && authorityMatch[1].indexOf('\\\\') !== -1) {\n parsed.error = 'URI authority must not contain a literal backslash.'\n malformedAuthorityOrPort = true\n }\n\n // Reject a malformed or whitespace-smuggled authority introducer. fast-uri\n // only recognizes a literal \"//\"; anything else in the leading separator run\n // (a backslash, or a \"//\" that appears only after removing the TAB/LF/CR that\n // Node strips) means the authority fast-uri parses differs from the one Node's\n // URL resolves. Reject rather than rewrite, mirroring the literal-backslash\n // guard above. Percent-encoded forms (%5C, %09) are untouched, valid data.\n const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION)\n if (introducerMatch !== null) {\n const region = introducerMatch[1]\n const normalizedRegion = region.replace(/[\\t\\n\\r]/g, '')\n // Two or more leading separators introduce an authority.\n if (normalizedRegion.length >= 2) {\n if (normalizedRegion.slice(0, 2) !== '//') {\n parsed.error = parsed.error || 'URI authority must not contain a literal backslash.'\n malformedAuthorityOrPort = true\n } else if (region.length !== normalizedRegion.length) {\n parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.'\n malformedAuthorityOrPort = true\n }\n }\n }\n\n const matches = uri.match(URI_PARSE)\n\n if (matches) {\n // store each component\n parsed.scheme = matches[1]\n parsed.userinfo = matches[3]\n parsed.host = matches[4]\n parsed.port = parseInt(matches[5], 10)\n parsed.path = matches[6] || ''\n parsed.query = matches[7]\n parsed.fragment = matches[8]\n\n if (parsed.scheme !== undefined) {\n const decodedScheme = unescape(parsed.scheme)\n if (VALID_SCHEME.test(decodedScheme)) {\n parsed.scheme = decodedScheme.toLowerCase()\n } else {\n parsed.error = parsed.error || MALFORMED_SCHEME_ERROR\n malformedScheme = true\n }\n }\n\n malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches)\n if (malformedPercentEncoding) {\n parsed.error = parsed.error || 'URI contains malformed percent-encoding.'\n }\n\n // fix port number\n if (isNaN(parsed.port)) {\n parsed.port = matches[5]\n }\n\n const parseError = getParseError(parsed, matches)\n if (parseError !== undefined) {\n parsed.error = parsed.error || parseError\n malformedAuthorityOrPort = true\n }\n\n if (parsed.host) {\n const ipv4result = isIPv4(parsed.host)\n if (ipv4result === false) {\n const bracketedIPLiteral = isIPLiteral(parsed.host)\n const hasIPLiteralBracket = parsed.host.indexOf('[') !== -1 || parsed.host.indexOf(']') !== -1\n const ipv6result = normalizeIPv6(parsed.host)\n isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true\n malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true)\n parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase()\n\n if (malformedIPLiteral) {\n parsed.error = parsed.error || 'URI host is malformed.'\n malformedAuthorityOrPort = true\n }\n } else {\n isIP = true\n }\n }\n if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {\n parsed.reference = 'same-document'\n } else if (parsed.scheme === undefined) {\n parsed.reference = 'relative'\n } else if (parsed.fragment === undefined) {\n parsed.reference = 'absolute'\n } else {\n parsed.reference = 'uri'\n }\n\n // check for reference errors\n if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {\n parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'\n }\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)\n\n // convert Unicode IDN -> ASCII IDN when the effective scheme uses domain hosts\n if (!malformedIPLiteral) {\n malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP)\n }\n\n if (uri.indexOf('%') !== -1 && parsed.host !== undefined && !malformedIPLiteral) {\n let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true)\n if (!isIP) {\n // Fold reg-name case after decoding unreserved octets. The second\n // pass only restores uppercase hex in escapes that remain encoded.\n host = normalizePercentEncoding(host.toLowerCase())\n }\n parsed.host = reescapeHostDelimiters(host, isIP)\n }\n\n if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {\n if (parsed.path) {\n parsed.path = normalizePathEncoding(parsed.path)\n }\n if (parsed.query) {\n parsed.query = normalizeQueryFragmentEncoding(parsed.query)\n }\n if (parsed.fragment) {\n parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment)\n }\n }\n\n // perform scheme specific parsing\n if (schemeHandler && schemeHandler.parse) {\n schemeHandler.parse(parsed, options)\n if (schemeHandler === SCHEMES.urn && parsed.nid === undefined) {\n malformedSchemeSpecific = true\n }\n }\n } else {\n parsed.error = parsed.error || 'URI can not be parsed.'\n }\n return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns\n */\nfunction parse (uri, opts) {\n return parseWithStatus(uri, opts).parsed\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction normalizeString (uri, opts) {\n return normalizeStringWithStatus(uri, opts).normalized\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}\n */\nfunction normalizeStringWithStatus (uri, opts) {\n const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts)\n return {\n normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),\n malformedAuthorityOrPort,\n malformedPercentEncoding,\n malformedSchemeSpecific,\n malformedHost,\n malformedScheme\n }\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {string|undefined}\n */\nfunction normalizeComparableURI (uri, opts) {\n if (typeof uri !== 'string' && typeof uri !== 'object') {\n return undefined\n }\n\n let value\n try {\n value = typeof uri === 'string' ? uri : serialize(uri, opts)\n } catch {\n return undefined\n }\n const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts)\n return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? undefined : normalized\n}\n\nconst fastUri = {\n SCHEMES,\n normalize,\n resolve,\n resolveComponent,\n equal,\n serialize,\n parse\n}\n\nmodule.exports = fastUri\nmodule.exports.default = fastUri\nmodule.exports.fastUri = fastUri\n","import * as uri from \"fast-uri\"\n\ntype URI = typeof uri & {code: string}\n;(uri as URI).code = 'require(\"ajv/dist/runtime/uri\").default'\n\nexport default uri as URI\n","export {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n AnyValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport interface Plugin<Opts> {\n (ajv: Ajv, options?: Opts): Ajv\n [prop: string]: any\n}\n\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\n\nimport type {\n Schema,\n AnySchema,\n AnySchemaObject,\n SchemaObject,\n AsyncSchema,\n Vocabulary,\n KeywordDefinition,\n AddedKeywordDefinition,\n AnyValidateFunction,\n ValidateFunction,\n AsyncValidateFunction,\n ErrorObject,\n Format,\n AddedFormat,\n RegExpEngine,\n UriResolver,\n} from \"./types\"\nimport type {JSONSchemaType} from \"./types/json-schema\"\nimport type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nimport ValidationError from \"./runtime/validation_error\"\nimport MissingRefError from \"./compile/ref_error\"\nimport {getRules, ValidationRules, Rule, RuleGroup, JSONType} from \"./compile/rules\"\nimport {SchemaEnv, compileSchema, resolveSchema} from \"./compile\"\nimport {Code, ValueScope} from \"./compile/codegen\"\nimport {normalizeId, getSchemaRefs} from \"./compile/resolve\"\nimport {getJSONTypes} from \"./compile/validate/dataType\"\nimport {eachItem} from \"./compile/util\"\nimport * as $dataRefSchema from \"./refs/data.json\"\n\nimport DefaultUriResolver from \"./runtime/uri\"\n\nconst defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)\ndefaultRegExp.code = \"new RegExp\"\n\nconst META_IGNORE_OPTIONS: (keyof Options)[] = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"]\nconst EXT_SCOPE_NAMES = new Set([\n \"validate\",\n \"serialize\",\n \"parse\",\n \"wrapper\",\n \"root\",\n \"schema\",\n \"keyword\",\n \"pattern\",\n \"formats\",\n \"validate$data\",\n \"func\",\n \"obj\",\n \"Error\",\n])\n\nexport type Options = CurrentOptions & DeprecatedOptions\n\nexport interface CurrentOptions {\n // strict mode options (NEW)\n strict?: boolean | \"log\"\n strictSchema?: boolean | \"log\"\n strictNumbers?: boolean | \"log\"\n strictTypes?: boolean | \"log\"\n strictTuples?: boolean | \"log\"\n strictRequired?: boolean | \"log\"\n allowMatchingProperties?: boolean // disables a strict mode restriction\n allowUnionTypes?: boolean\n validateFormats?: boolean\n // validation and reporting options:\n $data?: boolean\n allErrors?: boolean\n verbose?: boolean\n discriminator?: boolean\n unicodeRegExp?: boolean\n timestamp?: \"string\" | \"date\" // JTD only\n parseDate?: boolean // JTD only\n allowDate?: boolean // JTD only\n specialNumbers?: \"fast\" | \"null\" // JTD only\n $comment?:\n | true\n | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)\n formats?: {[Name in string]?: Format}\n keywords?: Vocabulary\n schemas?: AnySchema[] | {[Key in string]?: AnySchema}\n logger?: Logger | false\n loadSchema?: (uri: string) => Promise<AnySchemaObject>\n // options to modify validated data:\n removeAdditional?: boolean | \"all\" | \"failing\"\n useDefaults?: boolean | \"empty\"\n coerceTypes?: boolean | \"array\"\n // advanced options:\n next?: boolean // NEW\n unevaluated?: boolean // NEW\n dynamicRef?: boolean // NEW\n schemaId?: \"id\" | \"$id\"\n jtd?: boolean // NEW\n meta?: SchemaObject | boolean\n defaultMeta?: string | AnySchemaObject\n validateSchema?: boolean | \"log\"\n addUsedSchema?: boolean\n inlineRefs?: boolean | number\n passContext?: boolean\n loopRequired?: number\n loopEnum?: number // NEW\n ownProperties?: boolean\n multipleOfPrecision?: number\n int32range?: boolean // JTD only\n messages?: boolean\n code?: CodeOptions // NEW\n uriResolver?: UriResolver\n}\n\nexport interface CodeOptions {\n es5?: boolean\n esm?: boolean\n lines?: boolean\n optimize?: boolean | number\n formats?: Code // code to require (or construct) map of available formats - for standalone code\n source?: boolean\n process?: (code: string, schema?: SchemaEnv) => string\n regExp?: RegExpEngine\n}\n\ninterface InstanceCodeOptions extends CodeOptions {\n regExp: RegExpEngine\n optimize: number\n}\n\ninterface DeprecatedOptions {\n /** @deprecated */\n ignoreKeywordsWithRef?: boolean\n /** @deprecated */\n jsPropertySyntax?: boolean // added instead of jsonPointers\n /** @deprecated */\n unicode?: boolean\n}\n\ninterface RemovedOptions {\n format?: boolean\n errorDataPath?: \"object\" | \"property\"\n nullable?: boolean // \"nullable\" keyword is supported by default\n jsonPointers?: boolean\n extendRefs?: true | \"ignore\" | \"fail\"\n missingRefs?: true | \"ignore\" | \"fail\"\n processCode?: (code: string, schema?: SchemaEnv) => string\n sourceCode?: boolean\n strictDefaults?: boolean\n strictKeywords?: boolean\n uniqueItems?: boolean\n unknownFormats?: true | string[] | \"ignore\"\n cache?: any\n serialize?: (schema: AnySchema) => unknown\n ajvErrors?: boolean\n}\n\ntype OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {\n [K in keyof T]-?: string | undefined\n}\n\nconst removedOptions: OptionsInfo<RemovedOptions> = {\n errorDataPath: \"\",\n format: \"`validateFormats: false` can be used instead.\",\n nullable: '\"nullable\" keyword is supported by default.',\n jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n sourceCode: \"Use option `code: {source: true}`\",\n strictDefaults: \"It is default now, see option `strict`.\",\n strictKeywords: \"It is default now, see option `strict`.\",\n uniqueItems: '\"uniqueItems\" keyword is always validated.',\n unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n cache: \"Map is used as cache, schema object as key.\",\n serialize: \"Map is used as cache, schema object as key.\",\n ajvErrors: \"It is default now.\",\n}\n\nconst deprecatedOptions: OptionsInfo<DeprecatedOptions> = {\n ignoreKeywordsWithRef: \"\",\n jsPropertySyntax: \"\",\n unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n}\n\ntype RequiredInstanceOptions = {\n [K in\n | \"strictSchema\"\n | \"strictNumbers\"\n | \"strictTypes\"\n | \"strictTuples\"\n | \"strictRequired\"\n | \"inlineRefs\"\n | \"loopRequired\"\n | \"loopEnum\"\n | \"meta\"\n | \"messages\"\n | \"schemaId\"\n | \"addUsedSchema\"\n | \"validateSchema\"\n | \"validateFormats\"\n | \"int32range\"\n | \"unicodeRegExp\"\n | \"uriResolver\"]: NonNullable<Options[K]>\n} & {code: InstanceCodeOptions}\n\nexport type InstanceOptions = Options & RequiredInstanceOptions\n\nconst MAX_EXPRESSION = 200\n\n// eslint-disable-next-line complexity\nfunction requiredOptions(o: Options): RequiredInstanceOptions {\n const s = o.strict\n const _optz = o.code?.optimize\n const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0\n const regExp = o.code?.regExp ?? defaultRegExp\n const uriResolver = o.uriResolver ?? DefaultUriResolver\n return {\n strictSchema: o.strictSchema ?? s ?? true,\n strictNumbers: o.strictNumbers ?? s ?? true,\n strictTypes: o.strictTypes ?? s ?? \"log\",\n strictTuples: o.strictTuples ?? s ?? \"log\",\n strictRequired: o.strictRequired ?? s ?? false,\n code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},\n loopRequired: o.loopRequired ?? MAX_EXPRESSION,\n loopEnum: o.loopEnum ?? MAX_EXPRESSION,\n meta: o.meta ?? true,\n messages: o.messages ?? true,\n inlineRefs: o.inlineRefs ?? true,\n schemaId: o.schemaId ?? \"$id\",\n addUsedSchema: o.addUsedSchema ?? true,\n validateSchema: o.validateSchema ?? true,\n validateFormats: o.validateFormats ?? true,\n unicodeRegExp: o.unicodeRegExp ?? true,\n int32range: o.int32range ?? true,\n uriResolver: uriResolver,\n }\n}\n\nexport interface Logger {\n log(...args: unknown[]): unknown\n warn(...args: unknown[]): unknown\n error(...args: unknown[]): unknown\n}\n\nexport default class Ajv {\n opts: InstanceOptions\n errors?: ErrorObject[] | null // errors from the last validation\n logger: Logger\n // shared external scope values for compiled functions\n readonly scope: ValueScope\n readonly schemas: {[Key in string]?: SchemaEnv} = {}\n readonly refs: {[Ref in string]?: SchemaEnv | string} = {}\n readonly formats: {[Name in string]?: AddedFormat} = Object.create(null)\n readonly RULES: ValidationRules\n readonly _compilations: Set<SchemaEnv> = new Set()\n private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}\n private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()\n private readonly _metaOpts: InstanceOptions\n\n static ValidationError = ValidationError\n static MissingRefError = MissingRefError\n\n constructor(opts: Options = {}) {\n opts = this.opts = {...opts, ...requiredOptions(opts)}\n const {es5, lines} = this.opts.code\n\n this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})\n this.logger = getLogger(opts.logger)\n const formatOpt = opts.validateFormats\n opts.validateFormats = false\n\n this.RULES = getRules()\n checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\")\n checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\")\n this._metaOpts = getMetaSchemaOptions.call(this)\n\n if (opts.formats) addInitialFormats.call(this)\n this._addVocabularies()\n this._addDefaultMetaSchema()\n if (opts.keywords) addInitialKeywords.call(this, opts.keywords)\n if (typeof opts.meta == \"object\") this.addMetaSchema(opts.meta)\n addInitialSchemas.call(this)\n opts.validateFormats = formatOpt\n }\n\n _addVocabularies(): void {\n this.addKeyword(\"$async\")\n }\n\n _addDefaultMetaSchema(): void {\n const {$data, meta, schemaId} = this.opts\n let _dataRefSchema: SchemaObject = $dataRefSchema\n if (schemaId === \"id\") {\n _dataRefSchema = {...$dataRefSchema}\n _dataRefSchema.id = _dataRefSchema.$id\n delete _dataRefSchema.$id\n }\n if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n const {meta, schemaId} = this.opts\n return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined)\n }\n\n // Validate data using schema\n // AnySchema will be compiled and cached using schema itself as a key for Map\n validate(schema: Schema | string, data: unknown): boolean\n validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>\n validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n validate<N extends never, T extends SomeJTDSchemaType>(\n schema: T,\n data: unknown\n ): data is JTDDataType<T>\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>\n validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>\n validate<T>(\n schemaKeyRef: AnySchema | string, // key, ref or schema object\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n data: unknown | T // to be validated\n ): boolean | Promise<T> {\n let v: AnyValidateFunction | undefined\n if (typeof schemaKeyRef == \"string\") {\n v = this.getSchema<T>(schemaKeyRef)\n if (!v) throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`)\n } else {\n v = this.compile<T>(schemaKeyRef)\n }\n\n const valid = v(data)\n if (!(\"$async\" in v)) this.errors = v.errors\n return valid\n }\n\n // Create validation function for passed schema\n // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.\n compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n compile<N extends never, T extends SomeJTDSchemaType>(\n schema: T,\n _meta?: boolean\n ): ValidateFunction<JTDDataType<T>>\n compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>\n compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>\n compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {\n const sch = this._addSchema(schema, _meta)\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>\n }\n\n // Creates validating function for passed schema with asynchronous loading of missing schemas.\n // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.\n // TODO allow passing schema URI\n // meta - optional true to compile meta-schema\n compileAsync<T = unknown>(\n schema: SchemaObject | JSONSchemaType<T>,\n _meta?: boolean\n ): Promise<ValidateFunction<T>>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>\n compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync<T = unknown>(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise<AnyValidateFunction<T>>\n compileAsync<T = unknown>(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise<AnyValidateFunction<T>> {\n if (typeof this.opts.loadSchema != \"function\") {\n throw new Error(\"options.loadSchema should be a function\")\n }\n const {loadSchema} = this.opts\n return runCompileAsync.call(this, schema, meta)\n\n async function runCompileAsync(\n this: Ajv,\n _schema: AnySchemaObject,\n _meta?: boolean\n ): Promise<AnyValidateFunction> {\n await loadMetaSchema.call(this, _schema.$schema)\n const sch = this._addSchema(_schema, _meta)\n return sch.validate || _compileAsync.call(this, sch)\n }\n\n async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {\n if ($ref && !this.getSchema($ref)) {\n await runCompileAsync.call(this, {$ref}, true)\n }\n }\n\n async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {\n try {\n return this._compileSchemaEnv(sch)\n } catch (e) {\n if (!(e instanceof MissingRefError)) throw e\n checkLoaded.call(this, e)\n await loadMissingSchema.call(this, e.missingSchema)\n return _compileAsync.call(this, sch)\n }\n }\n\n function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {\n if (this.refs[ref]) {\n throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)\n }\n }\n\n async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {\n const _schema = await _loadSchema.call(this, ref)\n if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)\n if (!this.refs[ref]) this.addSchema(_schema, ref, meta)\n }\n\n async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {\n const p = this._loading[ref]\n if (p) return p\n try {\n return await (this._loading[ref] = loadSchema(ref))\n } finally {\n delete this._loading[ref]\n }\n }\n }\n\n // Adds schema to the instance\n addSchema(\n schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored\n key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n ): Ajv {\n if (Array.isArray(schema)) {\n for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)\n return this\n }\n let id: string | undefined\n if (typeof schema === \"object\") {\n const {schemaId} = this.opts\n id = schema[schemaId]\n if (id !== undefined && typeof id != \"string\") {\n throw new Error(`schema ${schemaId} must be string`)\n }\n }\n key = normalizeId(key || id)\n this._checkUnique(key)\n this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)\n return this\n }\n\n // Add schema that will be used to validate other schemas\n // options in META_IGNORE_OPTIONS are alway set to false\n addMetaSchema(\n schema: AnySchemaObject,\n key?: string, // schema key\n _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n ): Ajv {\n this.addSchema(schema, key, true, _validateSchema)\n return this\n }\n\n // Validate schema against its meta-schema\n validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {\n if (typeof schema == \"boolean\") return true\n let $schema: string | AnySchemaObject | undefined\n $schema = schema.$schema\n if ($schema !== undefined && typeof $schema != \"string\") {\n throw new Error(\"$schema must be a string\")\n }\n $schema = $schema || this.opts.defaultMeta || this.defaultMeta()\n if (!$schema) {\n this.logger.warn(\"meta-schema not available\")\n this.errors = null\n return true\n }\n const valid = this.validate($schema, schema)\n if (!valid && throwOrLogError) {\n const message = \"schema is invalid: \" + this.errorsText()\n if (this.opts.validateSchema === \"log\") this.logger.error(message)\n else throw new Error(message)\n }\n return valid\n }\n\n // Get compiled schema by `key` or `ref`.\n // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {\n let sch\n while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\") keyRef = sch\n if (sch === undefined) {\n const {schemaId} = this.opts\n const root = new SchemaEnv({schema: {}, schemaId})\n sch = resolveSchema.call(this, root, keyRef)\n if (!sch) return\n this.refs[keyRef] = sch\n }\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined\n }\n\n // Remove cached schema(s).\n // If no parameter is passed all schemas but meta-schemas are removed.\n // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {\n if (schemaKeyRef instanceof RegExp) {\n this._removeAllSchemas(this.schemas, schemaKeyRef)\n this._removeAllSchemas(this.refs, schemaKeyRef)\n return this\n }\n switch (typeof schemaKeyRef) {\n case \"undefined\":\n this._removeAllSchemas(this.schemas)\n this._removeAllSchemas(this.refs)\n this._cache.clear()\n return this\n case \"string\": {\n const sch = getSchEnv.call(this, schemaKeyRef)\n if (typeof sch == \"object\") this._cache.delete(sch.schema)\n delete this.schemas[schemaKeyRef]\n delete this.refs[schemaKeyRef]\n return this\n }\n case \"object\": {\n const cacheKey = schemaKeyRef\n this._cache.delete(cacheKey)\n let id = schemaKeyRef[this.opts.schemaId]\n if (id) {\n id = normalizeId(id)\n delete this.schemas[id]\n delete this.refs[id]\n }\n return this\n }\n default:\n throw new Error(\"ajv.removeSchema: invalid parameter\")\n }\n }\n\n // add \"vocabulary\" - a collection of keywords\n addVocabulary(definitions: Vocabulary): Ajv {\n for (const def of definitions) this.addKeyword(def)\n return this\n }\n\n addKeyword(\n kwdOrDef: string | KeywordDefinition,\n def?: KeywordDefinition // deprecated\n ): Ajv {\n let keyword: string | string[]\n if (typeof kwdOrDef == \"string\") {\n keyword = kwdOrDef\n if (typeof def == \"object\") {\n this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\")\n def.keyword = keyword\n }\n } else if (typeof kwdOrDef == \"object\" && def === undefined) {\n def = kwdOrDef\n keyword = def.keyword\n if (Array.isArray(keyword) && !keyword.length) {\n throw new Error(\"addKeywords: keyword must be string or non-empty array\")\n }\n } else {\n throw new Error(\"invalid addKeywords parameters\")\n }\n\n checkKeyword.call(this, keyword, def)\n if (!def) {\n eachItem(keyword, (kwd) => addRule.call(this, kwd))\n return this\n }\n keywordMetaschema.call(this, def)\n const definition: AddedKeywordDefinition = {\n ...def,\n type: getJSONTypes(def.type),\n schemaType: getJSONTypes(def.schemaType),\n }\n eachItem(\n keyword,\n definition.type.length === 0\n ? (k) => addRule.call(this, k, definition)\n : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))\n )\n return this\n }\n\n getKeyword(keyword: string): AddedKeywordDefinition | boolean {\n const rule = this.RULES.all[keyword]\n return typeof rule == \"object\" ? rule.definition : !!rule\n }\n\n // Remove keyword\n removeKeyword(keyword: string): Ajv {\n // TODO return type should be Ajv\n const {RULES} = this\n delete RULES.keywords[keyword]\n delete RULES.all[keyword]\n for (const group of RULES.rules) {\n const i = group.rules.findIndex((rule) => rule.keyword === keyword)\n if (i >= 0) group.rules.splice(i, 1)\n }\n return this\n }\n\n // Add format\n addFormat(name: string, format: Format): Ajv {\n if (typeof format == \"string\") format = new RegExp(format)\n this.formats[name] = format\n return this\n }\n\n errorsText(\n errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors\n {separator = \", \", dataVar = \"data\"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`\n ): string {\n if (!errors || errors.length === 0) return \"No errors\"\n return errors\n .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n .reduce((text, msg) => text + separator + msg)\n }\n\n $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {\n const rules = this.RULES.all\n metaSchema = JSON.parse(JSON.stringify(metaSchema))\n for (const jsonPointer of keywordsJsonPointers) {\n const segments = jsonPointer.split(\"/\").slice(1) // first segment is an empty string\n let keywords = metaSchema\n for (const seg of segments) keywords = keywords[seg] as AnySchemaObject\n\n for (const key in rules) {\n const rule = rules[key]\n if (typeof rule != \"object\") continue\n const {$data} = rule.definition\n const schema = keywords[key] as AnySchemaObject | undefined\n if ($data && schema) keywords[key] = schemaOrData(schema)\n }\n }\n\n return metaSchema\n }\n\n private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {\n for (const keyRef in schemas) {\n const sch = schemas[keyRef]\n if (!regex || regex.test(keyRef)) {\n if (typeof sch == \"string\") {\n delete schemas[keyRef]\n } else if (sch && !sch.meta) {\n this._cache.delete(sch.schema)\n delete schemas[keyRef]\n }\n }\n }\n }\n\n _addSchema(\n schema: AnySchema,\n meta?: boolean,\n baseId?: string,\n validateSchema = this.opts.validateSchema,\n addSchema = this.opts.addUsedSchema\n ): SchemaEnv {\n let id: string | undefined\n const {schemaId} = this.opts\n if (typeof schema == \"object\") {\n id = schema[schemaId]\n } else {\n if (this.opts.jtd) throw new Error(\"schema must be object\")\n else if (typeof schema != \"boolean\") throw new Error(\"schema must be object or boolean\")\n }\n let sch = this._cache.get(schema)\n if (sch !== undefined) return sch\n\n baseId = normalizeId(id || baseId)\n const localRefs = getSchemaRefs.call(this, schema, baseId)\n sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})\n this._cache.set(sch.schema, sch)\n if (addSchema && !baseId.startsWith(\"#\")) {\n // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n if (baseId) this._checkUnique(baseId)\n this.refs[baseId] = sch\n }\n if (validateSchema) this.validateSchema(schema, true)\n return sch\n }\n\n private _checkUnique(id: string): void {\n if (this.schemas[id] || this.refs[id]) {\n throw new Error(`schema with key or id \"${id}\" already exists`)\n }\n }\n\n private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {\n if (sch.meta) this._compileMetaSchema(sch)\n else compileSchema.call(this, sch)\n\n /* istanbul ignore if */\n if (!sch.validate) throw new Error(\"ajv implementation error\")\n return sch.validate\n }\n\n private _compileMetaSchema(sch: SchemaEnv): void {\n const currentOpts = this.opts\n this.opts = this._metaOpts\n try {\n compileSchema.call(this, sch)\n } finally {\n this.opts = currentOpts\n }\n }\n}\n\nexport interface ErrorsTextOptions {\n separator?: string\n dataVar?: string\n}\n\nfunction checkOptions(\n this: Ajv,\n checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,\n options: Options & RemovedOptions,\n msg: string,\n log: \"warn\" | \"error\" = \"error\"\n): void {\n for (const key in checkOpts) {\n const opt = key as keyof typeof checkOpts\n if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)\n }\n}\n\nfunction getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {\n keyRef = normalizeId(keyRef) // TODO tests fail without this line\n return this.schemas[keyRef] || this.refs[keyRef]\n}\n\nfunction addInitialSchemas(this: Ajv): void {\n const optsSchemas = this.opts.schemas\n if (!optsSchemas) return\n if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)\n else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)\n}\n\nfunction addInitialFormats(this: Ajv): void {\n for (const name in this.opts.formats) {\n const format = this.opts.formats[name]\n if (format) this.addFormat(name, format)\n }\n}\n\nfunction addInitialKeywords(\n this: Ajv,\n defs: Vocabulary | {[K in string]?: KeywordDefinition}\n): void {\n if (Array.isArray(defs)) {\n this.addVocabulary(defs)\n return\n }\n this.logger.warn(\"keywords option as map is deprecated, pass array\")\n for (const keyword in defs) {\n const def = defs[keyword] as KeywordDefinition\n if (!def.keyword) def.keyword = keyword\n this.addKeyword(def)\n }\n}\n\nfunction getMetaSchemaOptions(this: Ajv): InstanceOptions {\n const metaOpts = {...this.opts}\n for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]\n return metaOpts\n}\n\nconst noLogs = {log() {}, warn() {}, error() {}}\n\nfunction getLogger(logger?: Partial<Logger> | false): Logger {\n if (logger === false) return noLogs\n if (logger === undefined) return console\n if (logger.log && logger.warn && logger.error) return logger as Logger\n throw new Error(\"logger must implement log, warn and error methods\")\n}\n\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i\n\nfunction checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {\n const {RULES} = this\n eachItem(keyword, (kwd) => {\n if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)\n if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)\n })\n if (!def) return\n if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n throw new Error('$data keyword must have \"code\" or \"validate\" function')\n }\n}\n\nfunction addRule(\n this: Ajv,\n keyword: string,\n definition?: AddedKeywordDefinition,\n dataType?: JSONType\n): void {\n const post = definition?.post\n if (dataType && post) throw new Error('keyword with \"post\" flag cannot have \"type\"')\n const {RULES} = this\n let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)\n if (!ruleGroup) {\n ruleGroup = {type: dataType, rules: []}\n RULES.rules.push(ruleGroup)\n }\n RULES.keywords[keyword] = true\n if (!definition) return\n\n const rule: Rule = {\n keyword,\n definition: {\n ...definition,\n type: getJSONTypes(definition.type),\n schemaType: getJSONTypes(definition.schemaType),\n },\n }\n if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)\n else ruleGroup.rules.push(rule)\n RULES.all[keyword] = rule\n definition.implements?.forEach((kwd) => this.addKeyword(kwd))\n}\n\nfunction addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {\n const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)\n if (i >= 0) {\n ruleGroup.rules.splice(i, 0, rule)\n } else {\n ruleGroup.rules.push(rule)\n this.logger.warn(`rule ${before} is not defined`)\n }\n}\n\nfunction keywordMetaschema(this: Ajv, def: KeywordDefinition): void {\n let {metaSchema} = def\n if (metaSchema === undefined) return\n if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)\n def.validateSchema = this.compile(metaSchema, true)\n}\n\nconst $dataRef = {\n $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n}\n\nfunction schemaOrData(schema: AnySchema): AnySchemaObject {\n return {anyOf: [schema, $dataRef]}\n}\n","import type {CodeKeywordDefinition} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"id\",\n code() {\n throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID')\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {callValidateCode} from \"../code\"\nimport {_, nil, stringify, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport {SchemaEnv, resolveRef} from \"../../compile\"\nimport {mergeEvaluated} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$ref\",\n schemaType: \"string\",\n code(cxt: KeywordCxt): void {\n const {gen, schema: $ref, it} = cxt\n const {baseId, schemaEnv: env, validateName, opts, self} = it\n const {root} = env\n if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId) return callRootRef()\n const schOrEnv = resolveRef.call(self, root, baseId, $ref)\n if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref)\n if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv)\n return inlineRefSchema(schOrEnv)\n\n function callRootRef(): void {\n if (env === root) return callRef(cxt, validateName, env, env.$async)\n const rootName = gen.scopeValue(\"root\", {ref: root})\n return callRef(cxt, _`${rootName}.validate`, root, root.$async)\n }\n\n function callValidate(sch: SchemaEnv): void {\n const v = getValidate(cxt, sch)\n callRef(cxt, v, sch, sch.$async)\n }\n\n function inlineRefSchema(sch: AnySchema): void {\n const schName = gen.scopeValue(\n \"schema\",\n opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch}\n )\n const valid = gen.name(\"valid\")\n const schCxt = cxt.subschema(\n {\n schema: sch,\n dataTypes: [],\n schemaPath: nil,\n topSchemaRef: schName,\n errSchemaPath: $ref,\n },\n valid\n )\n cxt.mergeEvaluated(schCxt)\n cxt.ok(valid)\n }\n },\n}\n\nexport function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code {\n const {gen} = cxt\n return sch.validate\n ? gen.scopeValue(\"validate\", {ref: sch.validate})\n : _`${gen.scopeValue(\"wrapper\", {ref: sch})}.validate`\n}\n\nexport function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void {\n const {gen, it} = cxt\n const {allErrors, schemaEnv: env, opts} = it\n const passCxt = opts.passContext ? N.this : nil\n if ($async) callAsyncRef()\n else callSyncRef()\n\n function callAsyncRef(): void {\n if (!env.$async) throw new Error(\"async schema referenced by sync schema\")\n const valid = gen.let(\"valid\")\n gen.try(\n () => {\n gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`)\n addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result\n if (!allErrors) gen.assign(valid, true)\n },\n (e) => {\n gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e))\n addErrorsFrom(e)\n if (!allErrors) gen.assign(valid, false)\n }\n )\n cxt.ok(valid)\n }\n\n function callSyncRef(): void {\n cxt.result(\n callValidateCode(cxt, v, passCxt),\n () => addEvaluatedFrom(v),\n () => addErrorsFrom(v)\n )\n }\n\n function addErrorsFrom(source: Code): void {\n const errs = _`${source}.errors`\n gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged\n gen.assign(N.errors, _`${N.vErrors}.length`)\n }\n\n function addEvaluatedFrom(source: Code): void {\n if (!it.opts.unevaluated) return\n const schEvaluated = sch?.validate?.evaluated\n // TODO refactor\n if (it.props !== true) {\n if (schEvaluated && !schEvaluated.dynamicProps) {\n if (schEvaluated.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props)\n }\n } else {\n const props = gen.var(\"props\", _`${source}.evaluated.props`)\n it.props = mergeEvaluated.props(gen, props, it.props, Name)\n }\n }\n if (it.items !== true) {\n if (schEvaluated && !schEvaluated.dynamicItems) {\n if (schEvaluated.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items)\n }\n } else {\n const items = gen.var(\"items\", _`${source}.evaluated.items`)\n it.items = mergeEvaluated.items(gen, items, it.items, Name)\n }\n }\n }\n}\n\nexport default def\n","import type {Vocabulary} from \"../../types\"\nimport idKeyword from \"./id\"\nimport refKeyword from \"./ref\"\n\nconst core: Vocabulary = [\n \"$schema\",\n \"$id\",\n \"$defs\",\n \"$vocabulary\",\n {keyword: \"$comment\"},\n \"definitions\",\n idKeyword,\n refKeyword,\n]\n\nexport default core\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators, Code} from \"../../compile/codegen\"\n\nconst ops = operators\n\ntype Kwd = \"maximum\" | \"minimum\" | \"exclusiveMaximum\" | \"exclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n maximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n minimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n exclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n exclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitNumberError = ErrorObject<\n Kwd,\n {limit: number; comparison: Comparison},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type MultipleOfError = ErrorObject<\n \"multipleOf\",\n {multipleOf: number},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,\n params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"multipleOf\",\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schemaCode, it} = cxt\n // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)\n const prec = it.opts.multipleOfPrecision\n const res = gen.let(\"res\")\n const invalid = prec\n ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n : _`${res} !== parseInt(${res})`\n cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)\n },\n}\n\nexport default def\n","// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nexport default function ucs2length(str: string): number {\n const len = str.length\n let length = 0\n let pos = 0\n let value: number\n while (pos < len) {\n length++\n value = str.charCodeAt(pos++)\n if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos)\n if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate\n }\n }\n return length\n}\n\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default'\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport ucs2length from \"../../runtime/ucs2length\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} characters`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxLength\", \"minLength\"],\n type: \"string\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode, it} = cxt\n const op = keyword === \"maxLength\" ? operators.GT : operators.LT\n const len =\n it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`\n cxt.fail$data(_`${len} ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {usePattern} from \"../code\"\nimport {useFunc} from \"../../compile/util\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type PatternError = ErrorObject<\"pattern\", {pattern: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match pattern \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const u = it.opts.unicodeRegExp ? \"u\" : \"\"\n if ($data) {\n const {regExp} = it.opts.code\n const regExpCode = regExp.code === \"new RegExp\" ? _`new RegExp` : useFunc(gen, regExp)\n const valid = gen.let(\"valid\")\n gen.try(\n () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`),\n () => gen.assign(valid, false)\n )\n cxt.fail$data(_`!${valid}`)\n } else {\n const regExp = usePattern(cxt, schema)\n cxt.fail$data(_`!${regExp}.test(${data})`)\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} properties`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxProperties\", \"minProperties\"],\n type: \"object\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxProperties\" ? operators.GT : operators.LT\n cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {\n checkReportMissingProp,\n checkMissingProp,\n reportMissingProp,\n propertyInData,\n noPropertyInData,\n} from \"../code\"\nimport {_, str, nil, not, Name, Code} from \"../../compile/codegen\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nexport type RequiredError = ErrorObject<\n \"required\",\n {missingProperty: string},\n string[] | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`,\n params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"required\",\n type: \"object\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, schemaCode, data, $data, it} = cxt\n const {opts} = it\n if (!$data && schema.length === 0) return\n const useLoop = schema.length >= opts.loopRequired\n if (it.allErrors) allErrorsMode()\n else exitOnErrorMode()\n\n if (opts.strictRequired) {\n const props = cxt.parentSchema.properties\n const {definedProperties} = cxt.it\n for (const requiredKey of schema) {\n if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`\n checkStrictMode(it, msg, it.opts.strictRequired)\n }\n }\n }\n\n function allErrorsMode(): void {\n if (useLoop || $data) {\n cxt.block$data(nil, loopAllRequired)\n } else {\n for (const prop of schema) {\n checkReportMissingProp(cxt, prop)\n }\n }\n }\n\n function exitOnErrorMode(): void {\n const missing = gen.let(\"missing\")\n if (useLoop || $data) {\n const valid = gen.let(\"valid\", true)\n cxt.block$data(valid, () => loopUntilMissing(missing, valid))\n cxt.ok(valid)\n } else {\n gen.if(checkMissingProp(cxt, schema, missing))\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n\n function loopAllRequired(): void {\n gen.forOf(\"prop\", schemaCode as Code, (prop) => {\n cxt.setParams({missingProperty: prop})\n gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error())\n })\n }\n\n function loopUntilMissing(missing: Name, valid: Name): void {\n cxt.setParams({missingProperty: missing})\n gen.forOf(\n missing,\n schemaCode as Code,\n () => {\n gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties))\n gen.if(not(valid), () => {\n cxt.error()\n gen.break()\n })\n },\n nil\n )\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} items`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxItems\", \"minItems\"],\n type: \"array\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxItems\" ? operators.GT : operators.LT\n cxt.fail$data(_`${data}.length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n","// https://github.com/ajv-validator/ajv/issues/889\nimport * as equal from \"fast-deep-equal\"\n\ntype Equal = typeof equal & {code: string}\n;(equal as Equal).code = 'require(\"ajv/dist/runtime/equal\").default'\n\nexport default equal as Equal\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkDataTypes, getSchemaTypes, DataType} from \"../../compile/validate/dataType\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type UniqueItemsError = ErrorObject<\n \"uniqueItems\",\n {i: number; j: number},\n boolean | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {i, j}}) =>\n str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"uniqueItems\",\n type: \"array\",\n schemaType: \"boolean\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt\n if (!$data && !schema) return\n const valid = gen.let(\"valid\")\n const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []\n cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)\n cxt.ok(valid)\n\n function validateUniqueItems(): void {\n const i = gen.let(\"i\", _`${data}.length`)\n const j = gen.let(\"j\")\n cxt.setParams({i, j})\n gen.assign(valid, true)\n gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))\n }\n\n function canOptimize(): boolean {\n return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\")\n }\n\n function loopN(i: Name, j: Name): void {\n const item = gen.name(\"item\")\n const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong)\n const indices = gen.const(\"indices\", _`{}`)\n gen.for(_`;${i}--;`, () => {\n gen.let(item, _`${data}[${i}]`)\n gen.if(wrongType, _`continue`)\n if (itemTypes.length > 1) gen.if(_`typeof ${item} == \"string\"`, _`${item} += \"_\"`)\n gen\n .if(_`typeof ${indices}[${item}] == \"number\"`, () => {\n gen.assign(j, _`${indices}[${item}]`)\n cxt.error()\n gen.assign(valid, false).break()\n })\n .code(_`${indices}[${item}] = ${i}`)\n })\n }\n\n function loopN2(i: Name, j: Name): void {\n const eql = useFunc(gen, equal)\n const outer = gen.name(\"outer\")\n gen.label(outer).for(_`;${i}--;`, () =>\n gen.for(_`${j} = ${i}; ${j}--;`, () =>\n gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {\n cxt.error()\n gen.assign(valid, false).break(outer)\n })\n )\n )\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type ConstError = ErrorObject<\"const\", {allowedValue: any}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to constant\",\n params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"const\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schemaCode, schema} = cxt\n if ($data || (schema && typeof schema == \"object\")) {\n cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)\n } else {\n cxt.fail(_`${schema} !== ${data}`)\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, or, Name, Code} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type EnumError = ErrorObject<\"enum\", {allowedValues: any[]}, any[] | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to one of the allowed values\",\n params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"enum\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n if (!$data && schema.length === 0) throw new Error(\"enum must have non-empty array\")\n const useLoop = schema.length >= it.opts.loopEnum\n let eql: Name | undefined\n const getEql = (): Name => (eql ??= useFunc(gen, equal))\n\n let valid: Code\n if (useLoop || $data) {\n valid = gen.let(\"valid\")\n cxt.block$data(valid, loopEnum)\n } else {\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const vSchema = gen.const(\"vSchema\", schemaCode)\n valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))\n }\n cxt.pass(valid)\n\n function loopEnum(): void {\n gen.assign(valid, false)\n gen.forOf(\"v\", schemaCode as Code, (v) =>\n gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())\n )\n }\n\n function equalCode(vSchema: Name, i: number): Code {\n const sch = schema[i]\n return typeof sch === \"object\" && sch !== null\n ? _`${getEql()}(${data}, ${vSchema}[${i}])`\n : _`${data} === ${sch}`\n }\n },\n}\n\nexport default def\n","import type {ErrorObject, Vocabulary} from \"../../types\"\nimport limitNumber, {LimitNumberError} from \"./limitNumber\"\nimport multipleOf, {MultipleOfError} from \"./multipleOf\"\nimport limitLength from \"./limitLength\"\nimport pattern, {PatternError} from \"./pattern\"\nimport limitProperties from \"./limitProperties\"\nimport required, {RequiredError} from \"./required\"\nimport limitItems from \"./limitItems\"\nimport uniqueItems, {UniqueItemsError} from \"./uniqueItems\"\nimport constKeyword, {ConstError} from \"./const\"\nimport enumKeyword, {EnumError} from \"./enum\"\n\nconst validation: Vocabulary = [\n // number\n limitNumber,\n multipleOf,\n // string\n limitLength,\n pattern,\n // object\n limitProperties,\n required,\n // array\n limitItems,\n uniqueItems,\n // any\n {keyword: \"type\", schemaType: [\"string\", \"array\"]},\n {keyword: \"nullable\", schemaType: \"boolean\"},\n constKeyword,\n enumKeyword,\n]\n\nexport default validation\n\ntype LimitError = ErrorObject<\n \"maxItems\" | \"minItems\" | \"minProperties\" | \"maxProperties\" | \"minLength\" | \"maxLength\",\n {limit: number},\n number | {$data: string}\n>\n\nexport type ValidationKeywordError =\n | LimitError\n | LimitNumberError\n | MultipleOfError\n | PatternError\n | RequiredError\n | UniqueItemsError\n | ConstError\n | EnumError\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type AdditionalItemsError = ErrorObject<\"additionalItems\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"additionalItems\" as const,\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {parentSchema, it} = cxt\n const {items} = parentSchema\n if (!Array.isArray(items)) {\n checkStrictMode(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas')\n return\n }\n validateAdditionalItems(cxt, items)\n },\n}\n\nexport function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void {\n const {gen, schema, data, keyword, it} = cxt\n it.items = true\n const len = gen.const(\"len\", _`${data}.length`)\n if (schema === false) {\n cxt.setParams({len: items.length})\n cxt.pass(_`${len} <= ${items.length}`)\n } else if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.var(\"valid\", _`${len} <= ${items.length}`) // TODO var\n gen.if(not(valid), () => validateItems(valid))\n cxt.ok(valid)\n }\n\n function validateItems(valid: Name): void {\n gen.forRange(\"i\", items.length, len, (i) => {\n cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid)\n if (!it.allErrors) gen.if(not(valid), () => gen.break())\n })\n }\n}\n\nexport default def\n","import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {alwaysValidSchema, mergeEvaluated, checkStrictMode} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"array\", \"boolean\"],\n before: \"uniqueItems\",\n code(cxt: KeywordCxt) {\n const {schema, it} = cxt\n if (Array.isArray(schema)) return validateTuple(cxt, \"additionalItems\", schema)\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n cxt.ok(validateArray(cxt))\n },\n}\n\nexport function validateTuple(\n cxt: KeywordCxt,\n extraItems: string,\n schArr: AnySchema[] = cxt.schema\n): void {\n const {gen, parentSchema, data, keyword, it} = cxt\n checkStrictTuple(parentSchema)\n if (it.opts.unevaluated && schArr.length && it.items !== true) {\n it.items = mergeEvaluated.items(gen, schArr.length, it.items)\n }\n const valid = gen.name(\"valid\")\n const len = gen.const(\"len\", _`${data}.length`)\n schArr.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n gen.if(_`${len} > ${i}`, () =>\n cxt.subschema(\n {\n keyword,\n schemaProp: i,\n dataProp: i,\n },\n valid\n )\n )\n cxt.ok(valid)\n })\n\n function checkStrictTuple(sch: AnySchemaObject): void {\n const {opts, errSchemaPath} = it\n const l = schArr.length\n const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false)\n if (opts.strictTuples && !fullTuple) {\n const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`\n checkStrictMode(it, msg, opts.strictTuples)\n }\n }\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {validateTuple} from \"./items\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"prefixItems\",\n type: \"array\",\n schemaType: [\"array\"],\n before: \"uniqueItems\",\n code: (cxt) => validateTuple(cxt, \"items\"),\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\nimport {validateAdditionalItems} from \"./additionalItems\"\n\nexport type ItemsError = ErrorObject<\"items\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {schema, parentSchema, it} = cxt\n const {prefixItems} = parentSchema\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n if (prefixItems) validateAdditionalItems(cxt, prefixItems)\n else cxt.ok(validateArray(cxt))\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type ContainsError = ErrorObject<\n \"contains\",\n {minContains: number; maxContains?: number},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {min, max}}) =>\n max === undefined\n ? str`must contain at least ${min} valid item(s)`\n : str`must contain at least ${min} and no more than ${max} valid item(s)`,\n params: ({params: {min, max}}) =>\n max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"contains\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n let min: number\n let max: number | undefined\n const {minContains, maxContains} = parentSchema\n if (it.opts.next) {\n min = minContains === undefined ? 1 : minContains\n max = maxContains\n } else {\n min = 1\n }\n const len = gen.const(\"len\", _`${data}.length`)\n cxt.setParams({min, max})\n if (max === undefined && min === 0) {\n checkStrictMode(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`)\n return\n }\n if (max !== undefined && min > max) {\n checkStrictMode(it, `\"minContains\" > \"maxContains\" is always invalid`)\n cxt.fail()\n return\n }\n if (alwaysValidSchema(it, schema)) {\n let cond = _`${len} >= ${min}`\n if (max !== undefined) cond = _`${cond} && ${len} <= ${max}`\n cxt.pass(cond)\n return\n }\n\n it.items = true\n const valid = gen.name(\"valid\")\n if (max === undefined && min === 1) {\n validateItems(valid, () => gen.if(valid, () => gen.break()))\n } else if (min === 0) {\n gen.let(valid, true)\n if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount)\n } else {\n gen.let(valid, false)\n validateItemsWithCount()\n }\n cxt.result(valid, () => cxt.reset())\n\n function validateItemsWithCount(): void {\n const schValid = gen.name(\"_valid\")\n const count = gen.let(\"count\", 0)\n validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)))\n }\n\n function validateItems(_valid: Name, block: () => void): void {\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword: \"contains\",\n dataProp: i,\n dataPropType: Type.Num,\n compositeRule: true,\n },\n _valid\n )\n block()\n })\n }\n\n function checkLimits(count: Name): void {\n gen.code(_`${count}++`)\n if (max === undefined) {\n gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break())\n } else {\n gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break())\n if (min === 1) gen.assign(valid, true)\n else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true))\n }\n }\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n SchemaMap,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from \"../code\"\n\nexport type PropertyDependencies = {[K in string]?: string[]}\n\nexport interface DependenciesErrorParams {\n property: string\n missingProperty: string\n depsCount: number\n deps: string // TODO change to string[]\n}\n\ntype SchemaDependencies = SchemaMap\n\nexport type DependenciesError = ErrorObject<\n \"dependencies\",\n DependenciesErrorParams,\n {[K in string]?: string[] | AnySchema}\n>\n\nexport const error: KeywordErrorDefinition = {\n message: ({params: {property, depsCount, deps}}) => {\n const property_ies = depsCount === 1 ? \"property\" : \"properties\"\n return str`must have ${property_ies} ${deps} when property ${property} is present`\n },\n params: ({params: {property, depsCount, deps, missingProperty}}) =>\n _`{property: ${property},\n missingProperty: ${missingProperty},\n depsCount: ${depsCount},\n deps: ${deps}}`, // TODO change to reference\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"dependencies\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const [propDeps, schDeps] = splitDependencies(cxt)\n validatePropertyDeps(cxt, propDeps)\n validateSchemaDeps(cxt, schDeps)\n },\n}\n\nfunction splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] {\n const propertyDeps: PropertyDependencies = {}\n const schemaDeps: SchemaDependencies = {}\n for (const key in schema) {\n if (key === \"__proto__\") continue\n const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps\n deps[key] = schema[key]\n }\n return [propertyDeps, schemaDeps]\n}\n\nexport function validatePropertyDeps(\n cxt: KeywordCxt,\n propertyDeps: {[K in string]?: string[]} = cxt.schema\n): void {\n const {gen, data, it} = cxt\n if (Object.keys(propertyDeps).length === 0) return\n const missing = gen.let(\"missing\")\n for (const prop in propertyDeps) {\n const deps = propertyDeps[prop] as string[]\n if (deps.length === 0) continue\n const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties)\n cxt.setParams({\n property: prop,\n depsCount: deps.length,\n deps: deps.join(\", \"),\n })\n if (it.allErrors) {\n gen.if(hasProperty, () => {\n for (const depProp of deps) {\n checkReportMissingProp(cxt, depProp)\n }\n })\n } else {\n gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`)\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n}\n\nexport function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n for (const prop in schemaDeps) {\n if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue\n gen.if(\n propertyInData(gen, data, prop, it.opts.ownProperties),\n () => {\n const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid)\n cxt.mergeValidEvaluated(schCxt, valid)\n },\n () => gen.var(valid, true) // TODO var\n )\n cxt.ok(valid)\n }\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, not} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type PropertyNamesError = ErrorObject<\"propertyNames\", {propertyName: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: \"property name must be valid\",\n params: ({params}) => _`{propertyName: ${params.propertyName}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"propertyNames\",\n type: \"object\",\n schemaType: [\"object\", \"boolean\"],\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, data, it} = cxt\n if (alwaysValidSchema(it, schema)) return\n const valid = gen.name(\"valid\")\n\n gen.forIn(\"key\", data, (key) => {\n cxt.setParams({propertyName: key})\n cxt.subschema(\n {\n keyword: \"propertyNames\",\n data: key,\n dataTypes: [\"string\"],\n propertyName: key,\n compositeRule: true,\n },\n valid\n )\n gen.if(not(valid), () => {\n cxt.error(true)\n if (!it.allErrors) gen.break()\n })\n })\n\n cxt.ok(valid)\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n AddedKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport {allSchemaProperties, usePattern, isOwnProperty} from \"../code\"\nimport {_, nil, or, not, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport type {SubschemaArgs} from \"../../compile/validate/subschema\"\nimport {alwaysValidSchema, schemaRefOrVal, Type} from \"../../compile/util\"\n\nexport type AdditionalPropertiesError = ErrorObject<\n \"additionalProperties\",\n {additionalProperty: string},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must NOT have additional properties\",\n params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,\n}\n\nconst def: CodeKeywordDefinition & AddedKeywordDefinition = {\n keyword: \"additionalProperties\",\n type: [\"object\"],\n schemaType: [\"boolean\", \"object\"],\n allowUndefined: true,\n trackErrors: true,\n error,\n code(cxt) {\n const {gen, schema, parentSchema, data, errsCount, it} = cxt\n /* istanbul ignore if */\n if (!errsCount) throw new Error(\"ajv implementation error\")\n const {allErrors, opts} = it\n it.props = true\n if (opts.removeAdditional !== \"all\" && alwaysValidSchema(it, schema)) return\n const props = allSchemaProperties(parentSchema.properties)\n const patProps = allSchemaProperties(parentSchema.patternProperties)\n checkAdditionalProperties()\n cxt.ok(_`${errsCount} === ${N.errors}`)\n\n function checkAdditionalProperties(): void {\n gen.forIn(\"key\", data, (key: Name) => {\n if (!props.length && !patProps.length) additionalPropertyCode(key)\n else gen.if(isAdditional(key), () => additionalPropertyCode(key))\n })\n }\n\n function isAdditional(key: Name): Code {\n let definedProp: Code\n if (props.length > 8) {\n // TODO maybe an option instead of hard-coded 8?\n const propsSchema = schemaRefOrVal(it, parentSchema.properties, \"properties\")\n definedProp = isOwnProperty(gen, propsSchema as Code, key)\n } else if (props.length) {\n definedProp = or(...props.map((p) => _`${key} === ${p}`))\n } else {\n definedProp = nil\n }\n if (patProps.length) {\n definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`))\n }\n return not(definedProp)\n }\n\n function deleteAdditional(key: Name): void {\n gen.code(_`delete ${data}[${key}]`)\n }\n\n function additionalPropertyCode(key: Name): void {\n if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n deleteAdditional(key)\n return\n }\n\n if (schema === false) {\n cxt.setParams({additionalProperty: key})\n cxt.error()\n if (!allErrors) gen.break()\n return\n }\n\n if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.name(\"valid\")\n if (opts.removeAdditional === \"failing\") {\n applyAdditionalSchema(key, valid, false)\n gen.if(not(valid), () => {\n cxt.reset()\n deleteAdditional(key)\n })\n } else {\n applyAdditionalSchema(key, valid)\n if (!allErrors) gen.if(not(valid), () => gen.break())\n }\n }\n }\n\n function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void {\n const subschema: SubschemaArgs = {\n keyword: \"additionalProperties\",\n dataProp: key,\n dataPropType: Type.Str,\n }\n if (errors === false) {\n Object.assign(subschema, {\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n })\n }\n cxt.subschema(subschema, valid)\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {KeywordCxt} from \"../../compile/validate\"\nimport {propertyInData, allSchemaProperties} from \"../code\"\nimport {alwaysValidSchema, toHash, mergeEvaluated} from \"../../compile/util\"\nimport apDef from \"./additionalProperties\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"properties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n apDef.code(new KeywordCxt(it, apDef, \"additionalProperties\"))\n }\n const allProps = allSchemaProperties(schema)\n for (const prop of allProps) {\n it.definedProperties.add(prop)\n }\n if (it.opts.unevaluated && allProps.length && it.props !== true) {\n it.props = mergeEvaluated.props(gen, toHash(allProps), it.props)\n }\n const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p]))\n if (properties.length === 0) return\n const valid = gen.name(\"valid\")\n\n for (const prop of properties) {\n if (hasDefault(prop)) {\n applyPropertySchema(prop)\n } else {\n gen.if(propertyInData(gen, data, prop, it.opts.ownProperties))\n applyPropertySchema(prop)\n if (!it.allErrors) gen.else().var(valid, true)\n gen.endIf()\n }\n cxt.it.definedProperties.add(prop)\n cxt.ok(valid)\n }\n\n function hasDefault(prop: string): boolean | undefined {\n return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined\n }\n\n function applyPropertySchema(prop: string): void {\n cxt.subschema(\n {\n keyword: \"properties\",\n schemaProp: prop,\n dataProp: prop,\n },\n valid\n )\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {allSchemaProperties, usePattern} from \"../code\"\nimport {_, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\nimport {evaluatedPropsToName, Type} from \"../../compile/util\"\nimport {AnySchema} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"patternProperties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, data, parentSchema, it} = cxt\n const {opts} = it\n const patterns = allSchemaProperties(schema)\n const alwaysValidPatterns = patterns.filter((p) =>\n alwaysValidSchema(it, schema[p] as AnySchema)\n )\n\n if (\n patterns.length === 0 ||\n (alwaysValidPatterns.length === patterns.length &&\n (!it.opts.unevaluated || it.props === true))\n ) {\n return\n }\n\n const checkProperties =\n opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties\n const valid = gen.name(\"valid\")\n if (it.props !== true && !(it.props instanceof Name)) {\n it.props = evaluatedPropsToName(gen, it.props)\n }\n const {props} = it\n validatePatternProperties()\n\n function validatePatternProperties(): void {\n for (const pat of patterns) {\n if (checkProperties) checkMatchingProperties(pat)\n if (it.allErrors) {\n validateProperties(pat)\n } else {\n gen.var(valid, true) // TODO var\n validateProperties(pat)\n gen.if(valid)\n }\n }\n }\n\n function checkMatchingProperties(pat: string): void {\n for (const prop in checkProperties) {\n if (new RegExp(pat).test(prop)) {\n checkStrictMode(\n it,\n `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`\n )\n }\n }\n }\n\n function validateProperties(pat: string): void {\n gen.forIn(\"key\", data, (key) => {\n gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => {\n const alwaysValid = alwaysValidPatterns.includes(pat)\n if (!alwaysValid) {\n cxt.subschema(\n {\n keyword: \"patternProperties\",\n schemaProp: pat,\n dataProp: key,\n dataPropType: Type.Str,\n },\n valid\n )\n }\n\n if (it.opts.unevaluated && props !== true) {\n gen.assign(_`${props}[${key}]`, true)\n } else if (!alwaysValid && !it.allErrors) {\n // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n // or if all properties were evaluated (props === true)\n gen.if(not(valid), () => gen.break())\n }\n })\n })\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type NotKeywordError = ErrorNoParams<\"not\", AnySchema>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"not\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n if (alwaysValidSchema(it, schema)) {\n cxt.fail()\n return\n }\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n keyword: \"not\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n valid\n )\n\n cxt.failResult(\n valid,\n () => cxt.reset(),\n () => cxt.error()\n )\n },\n error: {message: \"must NOT be valid\"},\n}\n\nexport default def\n","import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport {validateUnion} from \"../code\"\n\nexport type AnyOfError = ErrorNoParams<\"anyOf\", AnySchema[]>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"anyOf\",\n schemaType: \"array\",\n trackErrors: true,\n code: validateUnion,\n error: {message: \"must match a schema in anyOf\"},\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {SchemaCxt} from \"../../compile\"\n\nexport type OneOfError = ErrorObject<\n \"oneOf\",\n {passingSchemas: [number, number] | null},\n AnySchema[]\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must match exactly one schema in oneOf\",\n params: ({params}) => _`{passingSchemas: ${params.passing}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"oneOf\",\n schemaType: \"array\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n if (it.opts.discriminator && parentSchema.discriminator) return\n const schArr: AnySchema[] = schema\n const valid = gen.let(\"valid\", false)\n const passing = gen.let(\"passing\", null)\n const schValid = gen.name(\"_valid\")\n cxt.setParams({passing})\n // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n\n gen.block(validateOneOf)\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n\n function validateOneOf(): void {\n schArr.forEach((sch: AnySchema, i: number) => {\n let schCxt: SchemaCxt | undefined\n if (alwaysValidSchema(it, sch)) {\n gen.var(schValid, true)\n } else {\n schCxt = cxt.subschema(\n {\n keyword: \"oneOf\",\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n }\n\n if (i > 0) {\n gen\n .if(_`${schValid} && ${valid}`)\n .assign(valid, false)\n .assign(passing, _`[${passing}, ${i}]`)\n .else()\n }\n\n gen.if(schValid, () => {\n gen.assign(valid, true)\n gen.assign(passing, i)\n if (schCxt) cxt.mergeEvaluated(schCxt, Name)\n })\n })\n }\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"allOf\",\n schemaType: \"array\",\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const valid = gen.name(\"valid\")\n schema.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n const schCxt = cxt.subschema({keyword: \"allOf\", schemaProp: i}, valid)\n cxt.ok(valid)\n cxt.mergeEvaluated(schCxt)\n })\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"../../compile\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\n\nexport type IfKeywordError = ErrorObject<\"if\", {failingKeyword: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params}) => str`must match \"${params.ifClause}\" schema`,\n params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"if\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, parentSchema, it} = cxt\n if (parentSchema.then === undefined && parentSchema.else === undefined) {\n checkStrictMode(it, '\"if\" without \"then\" and \"else\" is ignored')\n }\n const hasThen = hasSchema(it, \"then\")\n const hasElse = hasSchema(it, \"else\")\n if (!hasThen && !hasElse) return\n\n const valid = gen.let(\"valid\", true)\n const schValid = gen.name(\"_valid\")\n validateIf()\n cxt.reset()\n\n if (hasThen && hasElse) {\n const ifClause = gen.let(\"ifClause\")\n cxt.setParams({ifClause})\n gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause))\n } else if (hasThen) {\n gen.if(schValid, validateClause(\"then\"))\n } else {\n gen.if(not(schValid), validateClause(\"else\"))\n }\n\n cxt.pass(valid, () => cxt.error(true))\n\n function validateIf(): void {\n const schCxt = cxt.subschema(\n {\n keyword: \"if\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n schValid\n )\n cxt.mergeEvaluated(schCxt)\n }\n\n function validateClause(keyword: string, ifClause?: Name): () => void {\n return () => {\n const schCxt = cxt.subschema({keyword}, schValid)\n gen.assign(valid, schValid)\n cxt.mergeValidEvaluated(schCxt, valid)\n if (ifClause) gen.assign(ifClause, _`${keyword}`)\n else cxt.setParams({ifClause: keyword})\n }\n }\n },\n}\n\nfunction hasSchema(it: SchemaObjCxt, keyword: string): boolean {\n const schema = it.schema[keyword]\n return schema !== undefined && !alwaysValidSchema(it, schema)\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"then\", \"else\"],\n schemaType: [\"object\", \"boolean\"],\n code({keyword, parentSchema, it}: KeywordCxt) {\n if (parentSchema.if === undefined) checkStrictMode(it, `\"${keyword}\" without \"if\" is ignored`)\n },\n}\n\nexport default def\n","import type {ErrorNoParams, Vocabulary} from \"../../types\"\nimport additionalItems, {AdditionalItemsError} from \"./additionalItems\"\nimport prefixItems from \"./prefixItems\"\nimport items from \"./items\"\nimport items2020, {ItemsError} from \"./items2020\"\nimport contains, {ContainsError} from \"./contains\"\nimport dependencies, {DependenciesError} from \"./dependencies\"\nimport propertyNames, {PropertyNamesError} from \"./propertyNames\"\nimport additionalProperties, {AdditionalPropertiesError} from \"./additionalProperties\"\nimport properties from \"./properties\"\nimport patternProperties from \"./patternProperties\"\nimport notKeyword, {NotKeywordError} from \"./not\"\nimport anyOf, {AnyOfError} from \"./anyOf\"\nimport oneOf, {OneOfError} from \"./oneOf\"\nimport allOf from \"./allOf\"\nimport ifKeyword, {IfKeywordError} from \"./if\"\nimport thenElse from \"./thenElse\"\n\nexport default function getApplicator(draft2020 = false): Vocabulary {\n const applicator = [\n // any\n notKeyword,\n anyOf,\n oneOf,\n allOf,\n ifKeyword,\n thenElse,\n // object\n propertyNames,\n additionalProperties,\n dependencies,\n properties,\n patternProperties,\n ]\n // array\n if (draft2020) applicator.push(prefixItems, items2020)\n else applicator.push(additionalItems, items)\n applicator.push(contains)\n return applicator\n}\n\nexport type ApplicatorKeywordError =\n | ErrorNoParams<\"false schema\">\n | AdditionalItemsError\n | ItemsError\n | ContainsError\n | AdditionalPropertiesError\n | DependenciesError\n | IfKeywordError\n | AnyOfError\n | OneOfError\n | NotKeywordError\n | PropertyNamesError\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, getProperty, Code} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport {SchemaEnv, compileSchema} from \"../../compile\"\nimport {getValidate} from \"../core/ref\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$dynamicAnchor\",\n schemaType: \"string\",\n code: (cxt) => dynamicAnchor(cxt, cxt.schema),\n}\n\nexport function dynamicAnchor(cxt: KeywordCxt, anchor: string): void {\n const {gen, it} = cxt\n it.schemaEnv.root.dynamicAnchors[anchor] = true\n const v = _`${N.dynamicAnchors}${getProperty(anchor)}`\n const validate = it.errSchemaPath === \"#\" ? it.validateName : _getValidate(cxt)\n gen.if(_`!${v}`, () => gen.assign(v, validate))\n}\n\nfunction _getValidate(cxt: KeywordCxt): Code {\n const {schemaEnv, schema, self} = cxt.it\n const {root, baseId, localRefs, meta} = schemaEnv.root\n const {schemaId} = self.opts\n const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta})\n compileSchema.call(self, sch)\n return getValidate(cxt, sch)\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, getProperty, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport {callRef} from \"../core/ref\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$dynamicRef\",\n schemaType: \"string\",\n code: (cxt) => dynamicRef(cxt, cxt.schema),\n}\n\nexport function dynamicRef(cxt: KeywordCxt, ref: string): void {\n const {gen, keyword, it} = cxt\n if (ref[0] !== \"#\") throw new Error(`\"${keyword}\" only supports hash fragment reference`)\n const anchor = ref.slice(1)\n if (it.allErrors) {\n _dynamicRef()\n } else {\n const valid = gen.let(\"valid\", false)\n _dynamicRef(valid)\n cxt.ok(valid)\n }\n\n function _dynamicRef(valid?: Name): void {\n // TODO the assumption here is that `recursiveRef: #` always points to the root\n // of the schema object, which is not correct, because there may be $id that\n // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.\n // Because of that 2 tests in recursiveRef.json fail.\n // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ \"$ref\": \"#\" }`).\n // (This problem is not tested in JSON-Schema-Test-Suite)\n if (it.schemaEnv.root.dynamicAnchors[anchor]) {\n const v = gen.let(\"_v\", _`${N.dynamicAnchors}${getProperty(anchor)}`)\n gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid))\n } else {\n _callRef(it.validateName, valid)()\n }\n }\n\n function _callRef(validate: Code, valid?: Name): () => void {\n return valid\n ? () =>\n gen.block(() => {\n callRef(cxt, validate)\n gen.let(valid, true)\n })\n : () => callRef(cxt, validate)\n }\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {dynamicAnchor} from \"./dynamicAnchor\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$recursiveAnchor\",\n schemaType: \"boolean\",\n code(cxt) {\n if (cxt.schema) dynamicAnchor(cxt, \"\")\n else checkStrictMode(cxt.it, \"$recursiveAnchor: false is ignored\")\n },\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {dynamicRef} from \"./dynamicRef\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$recursiveRef\",\n schemaType: \"string\",\n code: (cxt) => dynamicRef(cxt, cxt.schema),\n}\n\nexport default def\n","import type {Vocabulary} from \"../../types\"\nimport dynamicAnchor from \"./dynamicAnchor\"\nimport dynamicRef from \"./dynamicRef\"\nimport recursiveAnchor from \"./recursiveAnchor\"\nimport recursiveRef from \"./recursiveRef\"\n\nconst dynamic: Vocabulary = [dynamicAnchor, dynamicRef, recursiveAnchor, recursiveRef]\n\nexport default dynamic\n","import type {CodeKeywordDefinition, ErrorObject} from \"../../types\"\nimport {\n validatePropertyDeps,\n error,\n DependenciesErrorParams,\n PropertyDependencies,\n} from \"../applicator/dependencies\"\n\nexport type DependentRequiredError = ErrorObject<\n \"dependentRequired\",\n DependenciesErrorParams,\n PropertyDependencies\n>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"dependentRequired\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code: (cxt) => validatePropertyDeps(cxt),\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport {validateSchemaDeps} from \"./dependencies\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"dependentSchemas\",\n type: \"object\",\n schemaType: \"object\",\n code: (cxt) => validateSchemaDeps(cxt),\n}\n\nexport default def\n","import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxContains\", \"minContains\"],\n type: \"array\",\n schemaType: \"number\",\n code({keyword, parentSchema, it}: KeywordCxt) {\n if (parentSchema.contains === undefined) {\n checkStrictMode(it, `\"${keyword}\" without \"contains\" is ignored`)\n }\n },\n}\n\nexport default def\n","import type {Vocabulary} from \"../types\"\nimport dependentRequired from \"./validation/dependentRequired\"\nimport dependentSchemas from \"./applicator/dependentSchemas\"\nimport limitContains from \"./validation/limitContains\"\n\nconst next: Vocabulary = [dependentRequired, dependentSchemas, limitContains]\n\nexport default next\n","import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport {_, not, and, Name, Code} from \"../../compile/codegen\"\nimport {alwaysValidSchema, Type} from \"../../compile/util\"\nimport N from \"../../compile/names\"\n\nexport type UnevaluatedPropertiesError = ErrorObject<\n \"unevaluatedProperties\",\n {unevaluatedProperty: string},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must NOT have unevaluated properties\",\n params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"unevaluatedProperties\",\n type: \"object\",\n schemaType: [\"boolean\", \"object\"],\n trackErrors: true,\n error,\n code(cxt) {\n const {gen, schema, data, errsCount, it} = cxt\n /* istanbul ignore if */\n if (!errsCount) throw new Error(\"ajv implementation error\")\n const {allErrors, props} = it\n if (props instanceof Name) {\n gen.if(_`${props} !== true`, () =>\n gen.forIn(\"key\", data, (key: Name) =>\n gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))\n )\n )\n } else if (props !== true) {\n gen.forIn(\"key\", data, (key: Name) =>\n props === undefined\n ? unevaluatedPropCode(key)\n : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))\n )\n }\n it.props = true\n cxt.ok(_`${errsCount} === ${N.errors}`)\n\n function unevaluatedPropCode(key: Name): void {\n if (schema === false) {\n cxt.setParams({unevaluatedProperty: key})\n cxt.error()\n if (!allErrors) gen.break()\n return\n }\n\n if (!alwaysValidSchema(it, schema)) {\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n keyword: \"unevaluatedProperties\",\n dataProp: key,\n dataPropType: Type.Str,\n },\n valid\n )\n if (!allErrors) gen.if(not(valid), () => gen.break())\n }\n }\n\n function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code {\n return _`!${evaluatedProps} || !${evaluatedProps}[${key}]`\n }\n\n function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code {\n const ps: Code[] = []\n for (const p in evaluatedProps) {\n if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`)\n }\n return and(...ps)\n }\n },\n}\n\nexport default def\n","import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, Type} from \"../../compile/util\"\n\nexport type UnevaluatedItemsError = ErrorObject<\"unevaluatedItems\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"unevaluatedItems\",\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, data, it} = cxt\n const items = it.items || 0\n if (items === true) return\n const len = gen.const(\"len\", _`${data}.length`)\n if (schema === false) {\n cxt.setParams({len: items})\n cxt.fail(_`${len} > ${items}`)\n } else if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.var(\"valid\", _`${len} <= ${items}`)\n gen.if(not(valid), () => validateItems(valid, items))\n cxt.ok(valid)\n }\n it.items = true\n\n function validateItems(valid: Name, from: Name | number): void {\n gen.forRange(\"i\", from, len, (i) => {\n cxt.subschema({keyword: \"unevaluatedItems\", dataProp: i, dataPropType: Type.Num}, valid)\n if (!it.allErrors) gen.if(not(valid), () => gen.break())\n })\n }\n },\n}\n\nexport default def\n","import type {Vocabulary} from \"../../types\"\nimport unevaluatedProperties from \"./unevaluatedProperties\"\nimport unevaluatedItems from \"./unevaluatedItems\"\n\nconst unevaluated: Vocabulary = [unevaluatedProperties, unevaluatedItems]\n\nexport default unevaluated\n","import type {\n AddedFormat,\n FormatValidator,\n AsyncFormatValidator,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, nil, or, Code, getProperty, regexpCode} from \"../../compile/codegen\"\n\ntype FormatValidate =\n | FormatValidator<string>\n | FormatValidator<number>\n | AsyncFormatValidator<string>\n | AsyncFormatValidator<number>\n | RegExp\n | string\n | true\n\nexport type FormatError = ErrorObject<\"format\", {format: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match format \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{format: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"format\",\n type: [\"number\", \"string\"],\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt, ruleType?: string) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const {opts, errSchemaPath, schemaEnv, self} = it\n if (!opts.validateFormats) return\n\n if ($data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fDef = gen.const(\"fDef\", _`${fmts}[${schemaCode}]`)\n const fType = gen.let(\"fType\")\n const format = gen.let(\"format\")\n // TODO simplify\n gen.if(\n _`typeof ${fDef} == \"object\" && !(${fDef} instanceof RegExp)`,\n () => gen.assign(fType, _`${fDef}.type || \"string\"`).assign(format, _`${fDef}.validate`),\n () => gen.assign(fType, _`\"string\"`).assign(format, fDef)\n )\n cxt.fail$data(or(unknownFmt(), invalidFmt()))\n\n function unknownFmt(): Code {\n if (opts.strictSchema === false) return nil\n return _`${schemaCode} && !${format}`\n }\n\n function invalidFmt(): Code {\n const callFormat = schemaEnv.$async\n ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n : _`${format}(${data})`\n const validData = _`(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`\n return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`\n }\n }\n\n function validateFormat(): void {\n const formatDef: AddedFormat | undefined = self.formats[schema]\n if (!formatDef) {\n unknownFormat()\n return\n }\n if (formatDef === true) return\n const [fmtType, format, fmtRef] = getFormat(formatDef)\n if (fmtType === ruleType) cxt.pass(validCondition())\n\n function unknownFormat(): void {\n if (opts.strictSchema === false) {\n self.logger.warn(unknownMsg())\n return\n }\n throw new Error(unknownMsg())\n\n function unknownMsg(): string {\n return `unknown format \"${schema as string}\" ignored in schema at path \"${errSchemaPath}\"`\n }\n }\n\n function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {\n const code =\n fmtDef instanceof RegExp\n ? regexpCode(fmtDef)\n : opts.code.formats\n ? _`${opts.code.formats}${getProperty(schema)}`\n : undefined\n const fmt = gen.scopeValue(\"formats\", {key: schema, ref: fmtDef, code})\n if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n return [fmtDef.type || \"string\", fmtDef.validate, _`${fmt}.validate`]\n }\n\n return [\"string\", fmtDef, fmt]\n }\n\n function validCondition(): Code {\n if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n if (!schemaEnv.$async) throw new Error(\"async format in sync schema\")\n return _`await ${fmtRef}(${data})`\n }\n return typeof format == \"function\" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})`\n }\n }\n },\n}\n\nexport default def\n","import type {Vocabulary} from \"../../types\"\nimport formatKeyword from \"./format\"\n\nconst format: Vocabulary = [formatKeyword]\n\nexport default format\n","import type {Vocabulary} from \"../types\"\n\nexport const metadataVocabulary: Vocabulary = [\n \"title\",\n \"description\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n \"examples\",\n]\n\nexport const contentVocabulary: Vocabulary = [\n \"contentMediaType\",\n \"contentEncoding\",\n \"contentSchema\",\n]\n","import type {Vocabulary} from \"../types\"\nimport coreVocabulary from \"./core\"\nimport validationVocabulary from \"./validation\"\nimport getApplicatorVocabulary from \"./applicator\"\nimport dynamicVocabulary from \"./dynamic\"\nimport nextVocabulary from \"./next\"\nimport unevaluatedVocabulary from \"./unevaluated\"\nimport formatVocabulary from \"./format\"\nimport {metadataVocabulary, contentVocabulary} from \"./metadata\"\n\nconst draft2020Vocabularies: Vocabulary[] = [\n dynamicVocabulary,\n coreVocabulary,\n validationVocabulary,\n getApplicatorVocabulary(true),\n formatVocabulary,\n metadataVocabulary,\n contentVocabulary,\n nextVocabulary,\n unevaluatedVocabulary,\n]\n\nexport default draft2020Vocabularies\n","import type {ErrorObject} from \"../../types\"\n\nexport enum DiscrError {\n Tag = \"tag\",\n Mapping = \"mapping\",\n}\n\nexport type DiscrErrorObj<E extends DiscrError> = ErrorObject<\n \"discriminator\",\n {error: E; tag: string; tagValue: unknown},\n string\n>\n","import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, getProperty, Name} from \"../../compile/codegen\"\nimport {DiscrError, DiscrErrorObj} from \"../discriminator/types\"\nimport {resolveRef, SchemaEnv} from \"../../compile\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {schemaHasRulesButRef} from \"../../compile/util\"\n\nexport type DiscriminatorError = DiscrErrorObj<DiscrError.Tag> | DiscrErrorObj<DiscrError.Mapping>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {discrError, tagName}}) =>\n discrError === DiscrError.Tag\n ? `tag \"${tagName}\" must be string`\n : `value of tag \"${tagName}\" must be in oneOf`,\n params: ({params: {discrError, tag, tagName}}) =>\n _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"discriminator\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schema, parentSchema, it} = cxt\n const {oneOf} = parentSchema\n if (!it.opts.discriminator) {\n throw new Error(\"discriminator: requires discriminator option\")\n }\n const tagName = schema.propertyName\n if (typeof tagName != \"string\") throw new Error(\"discriminator: requires propertyName\")\n if (schema.mapping) throw new Error(\"discriminator: mapping is not supported\")\n if (!oneOf) throw new Error(\"discriminator: requires oneOf keyword\")\n const valid = gen.let(\"valid\", false)\n const tag = gen.const(\"tag\", _`${data}${getProperty(tagName)}`)\n gen.if(\n _`typeof ${tag} == \"string\"`,\n () => validateMapping(),\n () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName})\n )\n cxt.ok(valid)\n\n function validateMapping(): void {\n const mapping = getMapping()\n gen.if(false)\n for (const tagValue in mapping) {\n gen.elseIf(_`${tag} === ${tagValue}`)\n gen.assign(valid, applyTagSchema(mapping[tagValue]))\n }\n gen.else()\n cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName})\n gen.endIf()\n }\n\n function applyTagSchema(schemaProp?: number): Name {\n const _valid = gen.name(\"valid\")\n const schCxt = cxt.subschema({keyword: \"oneOf\", schemaProp}, _valid)\n cxt.mergeEvaluated(schCxt, Name)\n return _valid\n }\n\n function getMapping(): {[T in string]?: number} {\n const oneOfMapping: {[T in string]?: number} = {}\n const topRequired = hasRequired(parentSchema)\n let tagRequired = true\n for (let i = 0; i < oneOf.length; i++) {\n let sch = oneOf[i]\n if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) {\n const ref = sch.$ref\n sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref)\n if (sch instanceof SchemaEnv) sch = sch.schema\n if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref)\n }\n const propSch = sch?.properties?.[tagName]\n if (typeof propSch != \"object\") {\n throw new Error(\n `discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`\n )\n }\n tagRequired = tagRequired && (topRequired || hasRequired(sch))\n addMappings(propSch, i)\n }\n if (!tagRequired) throw new Error(`discriminator: \"${tagName}\" must be required`)\n return oneOfMapping\n\n function hasRequired({required}: AnySchemaObject): boolean {\n return Array.isArray(required) && required.includes(tagName)\n }\n\n function addMappings(sch: AnySchemaObject, i: number): void {\n if (sch.const) {\n addMapping(sch.const, i)\n } else if (sch.enum) {\n for (const tagValue of sch.enum) {\n addMapping(tagValue, i)\n }\n } else {\n throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`)\n }\n }\n\n function addMapping(tagValue: unknown, i: number): void {\n if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n throw new Error(`discriminator: \"${tagName}\" values must be unique strings`)\n }\n oneOfMapping[tagValue] = i\n }\n }\n },\n}\n\nexport default def\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$vocabulary\": {\n \"https://json-schema.org/draft/2020-12/vocab/core\": true,\n \"https://json-schema.org/draft/2020-12/vocab/applicator\": true,\n \"https://json-schema.org/draft/2020-12/vocab/unevaluated\": true,\n \"https://json-schema.org/draft/2020-12/vocab/validation\": true,\n \"https://json-schema.org/draft/2020-12/vocab/meta-data\": true,\n \"https://json-schema.org/draft/2020-12/vocab/format-annotation\": true,\n \"https://json-schema.org/draft/2020-12/vocab/content\": true\n },\n \"$dynamicAnchor\": \"meta\",\n\n \"title\": \"Core and Validation specifications meta-schema\",\n \"allOf\": [\n {\"$ref\": \"meta/core\"},\n {\"$ref\": \"meta/applicator\"},\n {\"$ref\": \"meta/unevaluated\"},\n {\"$ref\": \"meta/validation\"},\n {\"$ref\": \"meta/meta-data\"},\n {\"$ref\": \"meta/format-annotation\"},\n {\"$ref\": \"meta/content\"}\n ],\n \"type\": [\"object\", \"boolean\"],\n \"$comment\": \"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.\",\n \"properties\": {\n \"definitions\": {\n \"$comment\": \"\\\"definitions\\\" has been replaced by \\\"$defs\\\".\",\n \"type\": \"object\",\n \"additionalProperties\": {\"$dynamicRef\": \"#meta\"},\n \"deprecated\": true,\n \"default\": {}\n },\n \"dependencies\": {\n \"$comment\": \"\\\"dependencies\\\" has been split and replaced by \\\"dependentSchemas\\\" and \\\"dependentRequired\\\" in order to serve their differing semantics.\",\n \"type\": \"object\",\n \"additionalProperties\": {\n \"anyOf\": [{\"$dynamicRef\": \"#meta\"}, {\"$ref\": \"meta/validation#/$defs/stringArray\"}]\n },\n \"deprecated\": true,\n \"default\": {}\n },\n \"$recursiveAnchor\": {\n \"$comment\": \"\\\"$recursiveAnchor\\\" has been replaced by \\\"$dynamicAnchor\\\".\",\n \"$ref\": \"meta/core#/$defs/anchorString\",\n \"deprecated\": true\n },\n \"$recursiveRef\": {\n \"$comment\": \"\\\"$recursiveRef\\\" has been replaced by \\\"$dynamicRef\\\".\",\n \"$ref\": \"meta/core#/$defs/uriReferenceString\",\n \"deprecated\": true\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://json-schema.org/draft/2020-12/meta/applicator\",\n \"$vocabulary\": {\n \"https://json-schema.org/draft/2020-12/vocab/applicator\": true\n },\n \"$dynamicAnchor\": \"meta\",\n\n \"title\": \"Applicator vocabulary meta-schema\",\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"prefixItems\": {\"$ref\": \"#/$defs/schemaArray\"},\n \"items\": {\"$dynamicRef\": \"#meta\"},\n \"contains\": {\"$dynamicRef\": \"#meta\"},\n \"additionalProperties\": {\"$dynamicRef\": \"#meta\"},\n \"properties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$dynamicRef\": \"#meta\"},\n \"default\": {}\n },\n \"patternProperties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$dynamicRef\": \"#meta\"},\n \"propertyNames\": {\"format\": \"regex\"},\n \"default\": {}\n },\n \"dependentSchemas\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$dynamicRef\": \"#meta\"},\n \"default\": {}\n },\n \"propertyNames\": {\"$dynamicRef\": \"#meta\"},\n \"if\": {\"$dynamicRef\": \"#meta\"},\n \"then\": {\"$dynamicRef\": \"#meta\"},\n \"else\": {\"$dynamicRef\": \"#meta\"},\n \"allOf\": {\"$ref\": \"#/$defs/schemaArray\"},\n \"anyOf\": {\"$ref\": \"#/$defs/schemaArray\"},\n \"oneOf\": {\"$ref\": \"#/$defs/schemaArray\"},\n \"not\": {\"$dynamicRef\": \"#meta\"}\n },\n \"$defs\": {\n \"schemaArray\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\"$dynamicRef\": \"#meta\"}\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://json-schema.org/draft/2020-12/meta/unevaluated\",\n \"$vocabulary\": {\n \"https://json-schema.org/draft/2020-12/vocab/unevaluated\": true\n },\n \"$dynamicAnchor\": \"meta\",\n\n \"title\": \"Unevaluated applicator vocabulary meta-schema\",\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"unevaluatedItems\": {\"$dynamicRef\": \"#meta\"},\n \"unevaluatedProperties\": {\"$dynamicRef\": \"#meta\"}\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://json-schema.org/draft/2020-12/meta/content\",\n \"$vocabulary\": {\n \"https://json-schema.org/draft/2020-12/vocab/content\": true\n },\n \"$dynamicAnchor\": \"meta\",\n\n \"title\": \"Content vocabulary meta-schema\",\n\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"contentEncoding\": {\"type\": \"string\"},\n \"contentMediaType\": {\"type\": \"string\"},\n \"contentSchema\": {\"$dynamicRef\": \"#meta\"}\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://json-schema.org/draft/2020-12/meta/core\",\n \"$vocabulary\": {\n \"https://json-schema.org/draft/2020-12/vocab/core\": true\n },\n \"$dynamicAnchor\": \"meta\",\n\n \"title\": \"Core vocabulary meta-schema\",\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"$id\": {\n \"$ref\": \"#/$defs/uriReferenceString\",\n \"$comment\": \"Non-empty fragments not allowed.\",\n \"pattern\": \"^[^#]*#?$\"\n },\n \"$schema\": {\"$ref\": \"#/$defs/uriString\"},\n \"$ref\": {\"$ref\": \"#/$defs/uriReferenceString\"},\n \"$anchor\": {\"$ref\": \"#/$defs/anchorString\"},\n \"$dynamicRef\": {\"$ref\": \"#/$defs/uriReferenceString\"},\n \"$dynamicAnchor\": {\"$ref\": \"#/$defs/anchorString\"},\n \"$vocabulary\": {\n \"type\": \"object\",\n \"propertyNames\": {\"$ref\": \"#/$defs/uriString\"},\n \"additionalProperties\": {\n \"type\": \"boolean\"\n }\n },\n \"$comment\": {\n \"type\": \"string\"\n },\n \"$defs\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$dynamicRef\": \"#meta\"}\n }\n },\n \"$defs\": {\n \"anchorString\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Za-z_][-A-Za-z0-9._]*$\"\n },\n \"uriString\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n },\n \"uriReferenceString\": {\n \"type\": \"string\",\n \"format\": \"uri-reference\"\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://json-schema.org/draft/2020-12/meta/format-annotation\",\n \"$vocabulary\": {\n \"https://json-schema.org/draft/2020-12/vocab/format-annotation\": true\n },\n \"$dynamicAnchor\": \"meta\",\n\n \"title\": \"Format vocabulary meta-schema for annotation results\",\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"format\": {\"type\": \"string\"}\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://json-schema.org/draft/2020-12/meta/meta-data\",\n \"$vocabulary\": {\n \"https://json-schema.org/draft/2020-12/vocab/meta-data\": true\n },\n \"$dynamicAnchor\": \"meta\",\n\n \"title\": \"Meta-data vocabulary meta-schema\",\n\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"title\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"default\": true,\n \"deprecated\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"readOnly\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"writeOnly\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"examples\": {\n \"type\": \"array\",\n \"items\": true\n }\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://json-schema.org/draft/2020-12/meta/validation\",\n \"$vocabulary\": {\n \"https://json-schema.org/draft/2020-12/vocab/validation\": true\n },\n \"$dynamicAnchor\": \"meta\",\n\n \"title\": \"Validation vocabulary meta-schema\",\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"type\": {\n \"anyOf\": [\n {\"$ref\": \"#/$defs/simpleTypes\"},\n {\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/$defs/simpleTypes\"},\n \"minItems\": 1,\n \"uniqueItems\": true\n }\n ]\n },\n \"const\": true,\n \"enum\": {\n \"type\": \"array\",\n \"items\": true\n },\n \"multipleOf\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n },\n \"maximum\": {\n \"type\": \"number\"\n },\n \"exclusiveMaximum\": {\n \"type\": \"number\"\n },\n \"minimum\": {\n \"type\": \"number\"\n },\n \"exclusiveMinimum\": {\n \"type\": \"number\"\n },\n \"maxLength\": {\"$ref\": \"#/$defs/nonNegativeInteger\"},\n \"minLength\": {\"$ref\": \"#/$defs/nonNegativeIntegerDefault0\"},\n \"pattern\": {\n \"type\": \"string\",\n \"format\": \"regex\"\n },\n \"maxItems\": {\"$ref\": \"#/$defs/nonNegativeInteger\"},\n \"minItems\": {\"$ref\": \"#/$defs/nonNegativeIntegerDefault0\"},\n \"uniqueItems\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"maxContains\": {\"$ref\": \"#/$defs/nonNegativeInteger\"},\n \"minContains\": {\n \"$ref\": \"#/$defs/nonNegativeInteger\",\n \"default\": 1\n },\n \"maxProperties\": {\"$ref\": \"#/$defs/nonNegativeInteger\"},\n \"minProperties\": {\"$ref\": \"#/$defs/nonNegativeIntegerDefault0\"},\n \"required\": {\"$ref\": \"#/$defs/stringArray\"},\n \"dependentRequired\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"$ref\": \"#/$defs/stringArray\"\n }\n }\n },\n \"$defs\": {\n \"nonNegativeInteger\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"nonNegativeIntegerDefault0\": {\n \"$ref\": \"#/$defs/nonNegativeInteger\",\n \"default\": 0\n },\n \"simpleTypes\": {\n \"enum\": [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n \"stringArray\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n \"uniqueItems\": true,\n \"default\": []\n }\n }\n}\n","import type Ajv from \"../../core\"\nimport type {AnySchemaObject} from \"../../types\"\nimport * as metaSchema from \"./schema.json\"\nimport * as applicator from \"./meta/applicator.json\"\nimport * as unevaluated from \"./meta/unevaluated.json\"\nimport * as content from \"./meta/content.json\"\nimport * as core from \"./meta/core.json\"\nimport * as format from \"./meta/format-annotation.json\"\nimport * as metadata from \"./meta/meta-data.json\"\nimport * as validation from \"./meta/validation.json\"\n\nconst META_SUPPORT_DATA = [\"/properties\"]\n\nexport default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv {\n ;[\n metaSchema,\n applicator,\n unevaluated,\n content,\n core,\n with$data(this, format),\n metadata,\n with$data(this, validation),\n ].forEach((sch) => this.addMetaSchema(sch, undefined, false))\n return this\n\n function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject {\n return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch\n }\n}\n","import type {AnySchemaObject} from \"./types\"\nimport AjvCore, {Options} from \"./core\"\n\nimport draft2020Vocabularies from \"./vocabularies/draft2020\"\nimport discriminator from \"./vocabularies/discriminator\"\nimport addMetaSchema2020 from \"./refs/json-schema-2020-12\"\n\nconst META_SCHEMA_ID = \"https://json-schema.org/draft/2020-12/schema\"\n\nexport class Ajv2020 extends AjvCore {\n constructor(opts: Options = {}) {\n super({\n ...opts,\n dynamicRef: true,\n next: true,\n unevaluated: true,\n })\n }\n\n _addVocabularies(): void {\n super._addVocabularies()\n draft2020Vocabularies.forEach((v) => this.addVocabulary(v))\n if (this.opts.discriminator) this.addKeyword(discriminator)\n }\n\n _addDefaultMetaSchema(): void {\n super._addDefaultMetaSchema()\n const {$data, meta} = this.opts\n if (!meta) return\n addMetaSchema2020.call(this, $data)\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))\n }\n}\n\nmodule.exports = exports = Ajv2020\nmodule.exports.Ajv2020 = Ajv2020\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default Ajv2020\n\nexport {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from \"./core\"\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\nexport {default as ValidationError} from \"./runtime/validation_error\"\nexport {default as MissingRefError} from \"./compile/ref_error\"\n","import type {Vocabulary} from \"../types\"\nimport coreVocabulary from \"./core\"\nimport validationVocabulary from \"./validation\"\nimport getApplicatorVocabulary from \"./applicator\"\nimport formatVocabulary from \"./format\"\nimport {metadataVocabulary, contentVocabulary} from \"./metadata\"\n\nconst draft7Vocabularies: Vocabulary[] = [\n coreVocabulary,\n validationVocabulary,\n getApplicatorVocabulary(),\n formatVocabulary,\n metadataVocabulary,\n contentVocabulary,\n]\n\nexport default draft7Vocabularies\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"http://json-schema.org/draft-07/schema#\",\n \"title\": \"Core schema meta-schema\",\n \"definitions\": {\n \"schemaArray\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\"$ref\": \"#\"}\n },\n \"nonNegativeInteger\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"nonNegativeIntegerDefault0\": {\n \"allOf\": [{\"$ref\": \"#/definitions/nonNegativeInteger\"}, {\"default\": 0}]\n },\n \"simpleTypes\": {\n \"enum\": [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n \"stringArray\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n \"uniqueItems\": true,\n \"default\": []\n }\n },\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"$id\": {\n \"type\": \"string\",\n \"format\": \"uri-reference\"\n },\n \"$schema\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n },\n \"$ref\": {\n \"type\": \"string\",\n \"format\": \"uri-reference\"\n },\n \"$comment\": {\n \"type\": \"string\"\n },\n \"title\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"default\": true,\n \"readOnly\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"examples\": {\n \"type\": \"array\",\n \"items\": true\n },\n \"multipleOf\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n },\n \"maximum\": {\n \"type\": \"number\"\n },\n \"exclusiveMaximum\": {\n \"type\": \"number\"\n },\n \"minimum\": {\n \"type\": \"number\"\n },\n \"exclusiveMinimum\": {\n \"type\": \"number\"\n },\n \"maxLength\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minLength\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"pattern\": {\n \"type\": \"string\",\n \"format\": \"regex\"\n },\n \"additionalItems\": {\"$ref\": \"#\"},\n \"items\": {\n \"anyOf\": [{\"$ref\": \"#\"}, {\"$ref\": \"#/definitions/schemaArray\"}],\n \"default\": true\n },\n \"maxItems\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minItems\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"uniqueItems\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"contains\": {\"$ref\": \"#\"},\n \"maxProperties\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minProperties\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"required\": {\"$ref\": \"#/definitions/stringArray\"},\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"definitions\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"properties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"patternProperties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"propertyNames\": {\"format\": \"regex\"},\n \"default\": {}\n },\n \"dependencies\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"anyOf\": [{\"$ref\": \"#\"}, {\"$ref\": \"#/definitions/stringArray\"}]\n }\n },\n \"propertyNames\": {\"$ref\": \"#\"},\n \"const\": true,\n \"enum\": {\n \"type\": \"array\",\n \"items\": true,\n \"minItems\": 1,\n \"uniqueItems\": true\n },\n \"type\": {\n \"anyOf\": [\n {\"$ref\": \"#/definitions/simpleTypes\"},\n {\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/definitions/simpleTypes\"},\n \"minItems\": 1,\n \"uniqueItems\": true\n }\n ]\n },\n \"format\": {\"type\": \"string\"},\n \"contentMediaType\": {\"type\": \"string\"},\n \"contentEncoding\": {\"type\": \"string\"},\n \"if\": {\"$ref\": \"#\"},\n \"then\": {\"$ref\": \"#\"},\n \"else\": {\"$ref\": \"#\"},\n \"allOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"anyOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"oneOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"not\": {\"$ref\": \"#\"}\n },\n \"default\": true\n}\n","import type {AnySchemaObject} from \"./types\"\nimport AjvCore from \"./core\"\nimport draft7Vocabularies from \"./vocabularies/draft7\"\nimport discriminator from \"./vocabularies/discriminator\"\nimport * as draft7MetaSchema from \"./refs/json-schema-draft-07.json\"\n\nconst META_SUPPORT_DATA = [\"/properties\"]\n\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\"\n\nexport class Ajv extends AjvCore {\n _addVocabularies(): void {\n super._addVocabularies()\n draft7Vocabularies.forEach((v) => this.addVocabulary(v))\n if (this.opts.discriminator) this.addKeyword(discriminator)\n }\n\n _addDefaultMetaSchema(): void {\n super._addDefaultMetaSchema()\n if (!this.opts.meta) return\n const metaSchema = this.opts.$data\n ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n : draft7MetaSchema\n this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))\n }\n}\n\nmodule.exports = exports = Ajv\nmodule.exports.Ajv = Ajv\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default Ajv\n\nexport {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n SchemaValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from \"./core\"\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\nexport {default as ValidationError} from \"./runtime/validation_error\"\nexport {default as MissingRefError} from \"./compile/ref_error\"\n","import type {Format, FormatDefinition} from \"ajv\"\nimport type {FormatValidator, FormatCompare} from \"ajv/dist/types\"\n\nexport type FormatMode = \"fast\" | \"full\"\n\nexport type FormatName =\n | \"date\"\n | \"time\"\n | \"date-time\"\n | \"iso-time\"\n | \"iso-date-time\"\n | \"duration\"\n | \"uri\"\n | \"uri-reference\"\n | \"uri-template\"\n | \"url\"\n | \"email\"\n | \"hostname\"\n | \"ipv4\"\n | \"ipv6\"\n | \"regex\"\n | \"uuid\"\n | \"json-pointer\"\n | \"json-pointer-uri-fragment\"\n | \"relative-json-pointer\"\n | \"byte\"\n | \"int32\"\n | \"int64\"\n | \"float\"\n | \"double\"\n | \"password\"\n | \"binary\"\n\nexport type DefinedFormats = {\n [key in FormatName]: Format\n}\n\nfunction fmtDef(\n validate: RegExp | FormatValidator<string>,\n compare: FormatCompare<string>\n): FormatDefinition<string> {\n return {validate, compare}\n}\n\nexport const fullFormats: DefinedFormats = {\n // date: http://tools.ietf.org/html/rfc3339#section-5.6\n date: fmtDef(date, compareDate),\n // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n time: fmtDef(getTime(true), compareTime),\n \"date-time\": fmtDef(getDateTime(true), compareDateTime),\n \"iso-time\": fmtDef(getTime(), compareIsoTime),\n \"iso-date-time\": fmtDef(getDateTime(), compareIsoDateTime),\n // duration: https://tools.ietf.org/html/rfc3339#appendix-A\n duration: /^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/,\n uri,\n \"uri-reference\":\n /^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'\"()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,\n // uri-template: https://tools.ietf.org/html/rfc6570\n \"uri-template\":\n /^(?:(?:[^\\x00-\\x20\"'<>%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i,\n // For the source: https://gist.github.com/dperini/729294\n // For test cases: https://mathiasbynens.be/demo/url-regex\n url: /^(?:https?|ftp):\\/\\/(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)(?:\\.(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu,\n email:\n /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,\n hostname:\n /^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i,\n // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n ipv4: /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/,\n ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i,\n regex,\n // uuid: http://tools.ietf.org/html/rfc4122\n uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n // JSON-pointer: https://tools.ietf.org/html/rfc6901\n // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n \"json-pointer\": /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n \"json-pointer-uri-fragment\": /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n \"relative-json-pointer\": /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n // byte: https://github.com/miguelmota/is-base64\n byte,\n // signed 32 bit integer\n int32: {type: \"number\", validate: validateInt32},\n // signed 64 bit integer\n int64: {type: \"number\", validate: validateInt64},\n // C-type float\n float: {type: \"number\", validate: validateNumber},\n // C-type double\n double: {type: \"number\", validate: validateNumber},\n // hint to the UI to hide input strings\n password: true,\n // unchecked string payload\n binary: true,\n}\n\nexport const fastFormats: DefinedFormats = {\n ...fullFormats,\n date: fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/, compareDate),\n time: fmtDef(\n /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i,\n compareTime\n ),\n \"date-time\": fmtDef(\n /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\dt(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i,\n compareDateTime\n ),\n \"iso-time\": fmtDef(\n /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,\n compareIsoTime\n ),\n \"iso-date-time\": fmtDef(\n /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d[t\\s](?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,\n compareIsoDateTime\n ),\n // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n \"uri-reference\": /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n // email (sources from jsen validator):\n // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')\n email:\n /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,\n}\n\nexport const formatNames = Object.keys(fullFormats) as FormatName[]\n\nfunction isLeapYear(year: number): boolean {\n // https://tools.ietf.org/html/rfc3339#appendix-C\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)\n}\n\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nfunction date(str: string): boolean {\n // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n const matches: string[] | null = DATE.exec(str)\n if (!matches) return false\n const year: number = +matches[1]\n const month: number = +matches[2]\n const day: number = +matches[3]\n return (\n month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])\n )\n}\n\nfunction compareDate(d1: string, d2: string): number | undefined {\n if (!(d1 && d2)) return undefined\n if (d1 > d2) return 1\n if (d1 < d2) return -1\n return 0\n}\n\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i\n\nfunction getTime(strictTimeZone?: boolean): (str: string) => boolean {\n return function time(str: string): boolean {\n const matches: string[] | null = TIME.exec(str)\n if (!matches) return false\n const hr: number = +matches[1]\n const min: number = +matches[2]\n const sec: number = +matches[3]\n const tz: string | undefined = matches[4]\n const tzSign: number = matches[5] === \"-\" ? -1 : 1\n const tzH: number = +(matches[6] || 0)\n const tzM: number = +(matches[7] || 0)\n if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false\n if (hr <= 23 && min <= 59 && sec < 60) return true\n // leap second\n const utcMin = min - tzM * tzSign\n const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0)\n return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61\n }\n}\n\nfunction compareTime(s1: string, s2: string): number | undefined {\n if (!(s1 && s2)) return undefined\n const t1 = new Date(\"2020-01-01T\" + s1).valueOf()\n const t2 = new Date(\"2020-01-01T\" + s2).valueOf()\n if (!(t1 && t2)) return undefined\n return t1 - t2\n}\n\nfunction compareIsoTime(t1: string, t2: string): number | undefined {\n if (!(t1 && t2)) return undefined\n const a1 = TIME.exec(t1)\n const a2 = TIME.exec(t2)\n if (!(a1 && a2)) return undefined\n t1 = a1[1] + a1[2] + a1[3]\n t2 = a2[1] + a2[2] + a2[3]\n if (t1 > t2) return 1\n if (t1 < t2) return -1\n return 0\n}\n\nconst DATE_TIME_SEPARATOR = /t|\\s/i\nfunction getDateTime(strictTimeZone?: boolean): (str: string) => boolean {\n const time = getTime(strictTimeZone)\n\n return function date_time(str: string): boolean {\n // http://tools.ietf.org/html/rfc3339#section-5.6\n const dateTime: string[] = str.split(DATE_TIME_SEPARATOR)\n return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1])\n }\n}\n\nfunction compareDateTime(dt1: string, dt2: string): number | undefined {\n if (!(dt1 && dt2)) return undefined\n const d1 = new Date(dt1).valueOf()\n const d2 = new Date(dt2).valueOf()\n if (!(d1 && d2)) return undefined\n return d1 - d2\n}\n\nfunction compareIsoDateTime(dt1: string, dt2: string): number | undefined {\n if (!(dt1 && dt2)) return undefined\n const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR)\n const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR)\n const res = compareDate(d1, d2)\n if (res === undefined) return undefined\n return res || compareTime(t1, t2)\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&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i\n\nfunction uri(str: string): boolean {\n // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n return NOT_URI_FRAGMENT.test(str) && URI.test(str)\n}\n\nconst BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm\n\nfunction byte(str: string): boolean {\n BYTE.lastIndex = 0\n return BYTE.test(str)\n}\n\nconst MIN_INT32 = -(2 ** 31)\nconst MAX_INT32 = 2 ** 31 - 1\n\nfunction validateInt32(value: number): boolean {\n return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32\n}\n\nfunction validateInt64(value: number): boolean {\n // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n return Number.isInteger(value)\n}\n\nfunction validateNumber(): boolean {\n return true\n}\n\nconst Z_ANCHOR = /[^\\\\]\\\\Z/\nfunction regex(str: string): boolean {\n if (Z_ANCHOR.test(str)) return false\n try {\n new RegExp(str)\n return true\n } catch (e) {\n return false\n }\n}\n","import type Ajv from \"ajv\"\nimport type {\n Plugin,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n Code,\n Name,\n ErrorObject,\n} from \"ajv\"\nimport type {AddedFormat} from \"ajv/dist/types\"\nimport type {Rule} from \"ajv/dist/compile/rules\"\nimport {KeywordCxt} from \"ajv\"\nimport {_, str, or, getProperty, operators} from \"ajv/dist/compile/codegen\"\n\ntype Kwd = \"formatMaximum\" | \"formatMinimum\" | \"formatExclusiveMaximum\" | \"formatExclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst ops = operators\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n formatMaximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n formatMinimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n formatExclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n formatExclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitFormatError = ErrorObject<Kwd, {limit: string; comparison: Comparison}>\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`should be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nexport const formatLimitDefinition: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt) {\n const {gen, data, schemaCode, keyword, it} = cxt\n const {opts, self} = it\n if (!opts.validateFormats) return\n\n const fCxt = new KeywordCxt(it, (self.RULES.all.format as Rule).definition, \"format\")\n if (fCxt.$data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fmt = gen.const(\"fmt\", _`${fmts}[${fCxt.schemaCode}]`)\n cxt.fail$data(\n or(\n _`typeof ${fmt} != \"object\"`,\n _`${fmt} instanceof RegExp`,\n _`typeof ${fmt}.compare != \"function\"`,\n compareCode(fmt)\n )\n )\n }\n\n function validateFormat(): void {\n const format = fCxt.schema as string\n const fmtDef: AddedFormat | undefined = self.formats[format]\n if (!fmtDef || fmtDef === true) return\n if (\n typeof fmtDef != \"object\" ||\n fmtDef instanceof RegExp ||\n typeof fmtDef.compare != \"function\"\n ) {\n throw new Error(`\"${keyword}\": format \"${format}\" does not define \"compare\" function`)\n }\n const fmt = gen.scopeValue(\"formats\", {\n key: format,\n ref: fmtDef,\n code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined,\n })\n\n cxt.fail$data(compareCode(fmt))\n }\n\n function compareCode(fmt: Name): Code {\n return _`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword as Kwd].fail} 0`\n }\n },\n dependencies: [\"format\"],\n}\n\nconst formatLimitPlugin: Plugin<undefined> = (ajv: Ajv): Ajv => {\n ajv.addKeyword(formatLimitDefinition)\n return ajv\n}\n\nexport default formatLimitPlugin\n","import {\n DefinedFormats,\n FormatMode,\n FormatName,\n formatNames,\n fastFormats,\n fullFormats,\n} from \"./formats\"\nimport formatLimit from \"./limit\"\nimport type Ajv from \"ajv\"\nimport type {Plugin, Format} from \"ajv\"\nimport {_, Name} from \"ajv/dist/compile/codegen\"\n\nexport {FormatMode, FormatName} from \"./formats\"\nexport {LimitFormatError} from \"./limit\"\nexport interface FormatOptions {\n mode?: FormatMode\n formats?: FormatName[]\n keywords?: boolean\n}\n\nexport type FormatsPluginOptions = FormatName[] | FormatOptions\n\nexport interface FormatsPlugin extends Plugin<FormatsPluginOptions> {\n get: (format: FormatName, mode?: FormatMode) => Format\n}\n\nconst fullName = new Name(\"fullFormats\")\nconst fastName = new Name(\"fastFormats\")\n\nconst formatsPlugin: FormatsPlugin = (\n ajv: Ajv,\n opts: FormatsPluginOptions = {keywords: true}\n): Ajv => {\n if (Array.isArray(opts)) {\n addFormats(ajv, opts, fullFormats, fullName)\n return ajv\n }\n const [formats, exportName] =\n opts.mode === \"fast\" ? [fastFormats, fastName] : [fullFormats, fullName]\n const list = opts.formats || formatNames\n addFormats(ajv, list, formats, exportName)\n if (opts.keywords) formatLimit(ajv)\n return ajv\n}\n\nformatsPlugin.get = (name: FormatName, mode: FormatMode = \"full\"): Format => {\n const formats = mode === \"fast\" ? fastFormats : fullFormats\n const f = formats[name]\n if (!f) throw new Error(`Unknown format \"${name}\"`)\n return f\n}\n\nfunction addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void {\n ajv.opts.code.formats ??= _`require(\"ajv-formats/dist/formats\").${exportName}`\n for (const f of list) ajv.addFormat(f, fs[f])\n}\n\nmodule.exports = exports = formatsPlugin\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default formatsPlugin\n","import { setTimeout as delay } from 'node:timers/promises';\nimport { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';\nimport { SIGN_IN_WITH_X } from '@x402/extensions/sign-in-with-x';\nimport type { PaymentRequired, PaymentRequirements } from '@x402/core/types';\nimport { verifyAgainstRegistries, type RegistryVerification } from '../lib/bazaar';\nimport { readUsdcBalance } from '../lib/usdc-balance';\nimport { assertPublicDestination, type DestinationOptions } from '../lib/destination';\nimport { CliError } from '../lib/errors';\nimport { validateResultBody, type ResultCheck } from '../lib/request-schema';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { HttpResponse } from '../lib/http';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { mask } from '../lib/redact';\nimport { isSameDeployment } from '../lib/production-origin';\nimport { resolveContextSettings } from '../lib/settings';\nimport { SIWX_HEADER, buildSiwxHeader } from '../lib/siwx';\nimport { gateSpend } from '../lib/spend-gate';\nimport type { ResolvedSettings } from '../lib/settings';\nimport {\n describeWallet,\n resolveSpendAuthorizer,\n resolveWalletProvider,\n type SpendAuthorizer,\n type WalletProvider,\n} from '../lib/wallet';\nimport {\n buildExactPayment,\n createPayerClient,\n noPayableRequirement,\n selectPayableRequirement,\n} from '../lib/x402-pay';\nimport type { x402Client } from '@x402/core/client';\nimport type { TenjinSigner } from '../lib/wallet/provider';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin pay <url>`: the standard x402 client verb, for ANY paid endpoint\n * rather than marketplace pieces. One probe; a 2xx delivers free; a 402 runs\n * shared payment gate (automatic limits for the router, mandatory consent for\n * manual pay, hard price/creator checks for both) and retries once with the\n * `PAYMENT-SIGNATURE`. Deliberately NOT `buy`: no library idempotence (every\n * paid call pays; manual consent and optional `--max-price` are the brakes) and no\n * search attribution. SIWX rides ONLY when the 402 advertises the standard\n * sign-in-with-x extension, and the signature is bound to the TARGET origin\n * (never the configured deployment's), so an entitled wallet re-reads free at\n * any seller that supports it while nothing origin-bound can leak elsewhere.\n *\n * Direct third-party payments require acknowledgement of registry warnings.\n * Router calls retain their advertised-price and supplied-term hard checks.\n * Every positive payment checks the actual signer's balance before signing.\n */\n\nconst PAYMENT_REQUIRED_HEADER = 'PAYMENT-REQUIRED';\nconst PAYMENT_RESPONSE_HEADER = 'PAYMENT-RESPONSE';\n\n/** Terminal preview cap; `--print-body` lifts it. The machine body is never cut. */\nconst BODY_PREVIEW_CHARS = 1200;\n\n/**\n * What a caller was told this endpoint costs, BEFORE the live 402 is seen. It\n * stands in for the registry lookup on a lane that has one from elsewhere (the\n * router's paid decision carries it), and it is a ceiling, never a licence: the\n * live requirement has to match the network and asset exactly and may not\n * exceed the amount. Direct calls without offered terms use registry warning acknowledgement.\n */\nexport interface AdvertisedTerms {\n /** Pins the deal's chain and token when the caller was told them. */\n network?: string;\n asset?: string;\n /**\n * A ceiling the caller was quoted, when there was one: a live 402 above it is\n * refused. It only ever refuses; the amount actually signed still meets\n * `maxAutoSpend` and `sessionBudget` in `gateSpend`, the payment authority.\n */\n maxAmountAtomic?: string;\n /** The advertised recipient, when the caller was given one. Checked exactly. */\n payTo?: string;\n /** Free-text provenance for the payee label, e.g. a registry name. */\n source?: string;\n}\n\nexport interface PayArgs {\n url: string;\n /** GET (default) or POST; POST is implied when --data is given. */\n method?: string;\n /** A JSON request body; content-type is always application/json. */\n data?: string;\n /** Decimal USD; the hard price cap, never bypassed by --yes. */\n maxPrice?: string;\n /** Bypass the interactive confirm only (never the price cap or a hard deny). */\n yes?: boolean;\n /** Acknowledge direct-payment registry warnings for this invocation only. */\n ignoreWarnings?: boolean;\n /** Internal router entrypoint; missing terms must never become direct pay. */\n execution?: 'router';\n /** Print the full body to the terminal instead of the capped preview. */\n printBody?: boolean;\n /** Advertised terms that replace the registry lookup on this call. */\n terms?: AdvertisedTerms;\n /**\n * Request headers a caller was handed rather than composed: the router's\n * provider leg sends the decision's own `accept` and `content-type`. Only\n * those two names are accepted, so nothing can smuggle a credential or a\n * payment header in beside the one this command signs.\n */\n headers?: Record<string, string>;\n /** A body the caller already encoded; sent byte for byte. Needs `-X POST`. */\n rawBody?: string;\n /** The same-turn duplicate guard's identity for this request. */\n requestKey?: string;\n /**\n * The caller's APPLICATION success rule for the delivered body. On a free or\n * entitled 2xx, a body that fails it is refused: nothing was paid. On the\n * PAID leg the money already moved, so the body is always delivered: one\n * that fails the rule, or that is past this client's own validation limit so\n * the rule never ran, comes back with `resultUnverified` and a\n * `resultCaveat` saying which.\n */\n resultSchema?: unknown;\n}\n\nexport interface PayDeps {\n fetchImpl?: typeof fetch;\n readBalance?: typeof readUsdcBalance;\n provider?: WalletProvider;\n authorizer?: SpendAuthorizer;\n confirm?: (prompt: string) => Promise<boolean>;\n /** Resolver seam for the destination preflight; production leaves it unset. */\n destination?: DestinationOptions;\n}\n\ntype Lane = 'tenjin' | 'bazaar';\n\ntype RegistryWarning = Exclude<RegistryVerification, { outcome: 'verified' | 'unlisted' }> & {\n acknowledged: boolean;\n quote: PaymentRequirements & { url: string };\n};\n\nexport async function runPay(\n args: PayArgs,\n ctx: CommandContext,\n deps: PayDeps = {},\n): Promise<CommandResult> {\n const warnings: RegistryWarning[] = [];\n try {\n return await executePay(args, ctx, deps, warnings);\n } catch (err) {\n if (err instanceof CliError && warnings.length > 0) {\n throw new CliError(err.code, err.message, {\n exitCode: err.exitCode,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n details: {\n ...(typeof err.details === 'object' && err.details !== null ? err.details : {}),\n warnings,\n },\n cause: err,\n });\n }\n throw err;\n }\n}\n\nasync function executePay(\n args: PayArgs,\n ctx: CommandContext,\n deps: PayDeps,\n warnings: RegistryWarning[],\n): Promise<CommandResult> {\n const router = args.execution === 'router' || args.terms !== undefined;\n if (router) {\n const terms = args.terms;\n if (\n args.ignoreWarnings === true ||\n !terms ||\n typeof terms.maxAmountAtomic !== 'string' ||\n !/^\\d+$/.test(terms.maxAmountAtomic) ||\n [terms.network, terms.asset, terms.payTo, terms.source].some(\n (v) => v !== undefined && (typeof v !== 'string' || v.trim().length === 0),\n )\n ) {\n throw new CliError(\n 'REFUSED',\n 'Router payments require valid advertised terms and cannot acknowledge registry warnings.',\n { details: { reason: 'invalid_router_terms' } },\n );\n }\n }\n const settings = await resolveContextSettings(ctx);\n const maxPriceAtomic =\n args.maxPrice !== undefined ? BigInt(parseUsdToAtomic(args.maxPrice)) : undefined;\n // Filled once the wallet is opened; the payer client closes over it so\n // selection can run first without one.\n const openedSigner: { current?: TenjinSigner } = {};\n const url = args.url.trim();\n const lane = resolveLane(url, settings);\n // BEFORE the probe, and only on the third-party lane: the configured base URL\n // is the operator's own deployment and is legitimately a local origin in\n // development, while any other host is a destination something else chose, so\n // that is the one that has to prove it is not on this network.\n if (lane === 'bazaar') await assertPublicDestination(url, deps.destination ?? {});\n const method = resolveMethod(args);\n const jsonBody = parseBody(args.data);\n const headers = callerHeaders(args.headers);\n\n const fetchOpts = {\n timeoutMs: ctx.flags.timeout,\n // Both legs: the probe's 402 is money-path input, and the paid retry\n // carries a signed header (which pins redirects on its own; this pins the\n // probe too, so the challenge always comes from the URL that was gated).\n blockRedirects: true as const,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n ...(jsonBody !== undefined ? { jsonBody } : {}),\n ...(jsonBody === undefined && args.rawBody !== undefined ? { rawBody: args.rawBody } : {}),\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n method,\n };\n\n const probe = await httpRequest(url, fetchOpts);\n // The unpaid leg says so itself: the transport is shared with the paid retry\n // and asserts nothing about money either way.\n if (!probe.ok) {\n throw fetchFailureToCliError(probe, {\n fix: `Nothing was sent and nothing was paid. ${legFix(probe)}`,\n });\n }\n if (probe.status >= 200 && probe.status < 300) {\n const caveat = assertUsableResult(args.resultSchema, probe.text, probe.status, 'free');\n return deliver(url, lane, probe, {\n paid: false,\n ...(caveat !== undefined ? { caveat } : {}),\n printBody: args.printBody === true,\n });\n }\n if (probe.status !== 402) {\n // THE PROVIDER'S OWN WORDS, when it sent `{error: {message}}`: a free docs\n // lookup's 404 says no library matched and to use your own tools, which a\n // bare status line turned into \"retry\". A 404 is the endpoint's answer, not\n // a transient failure, so it is never told to retry either.\n const said = providerMessage(probe.json);\n throw new CliError(\n 'API_UNREACHABLE',\n `${url} answered ${probe.status}${said === null ? '.' : `: ${said}`}`,\n {\n fix:\n probe.status === 404\n ? 'Nothing was paid. The same request will answer 404 again.'\n : 'Check the URL and the endpoint status, then retry.',\n details: { status: probe.status, body: probe.json, ...providerError(probe.text) },\n },\n );\n }\n\n const paymentRequired = decodeChallenge(probe, url);\n // The client is built BEFORE the wallet is opened on purpose: selection needs\n // only the registered networks and the policies, never a key, so an\n // unpayable or unverifiable deal is refused before a signer exists.\n const payer = createPayerClient(() => signerOrThrow(openedSigner));\n const requirement = selectRequirement(payer.core, paymentRequired, args.terms);\n if (requirement === undefined) {\n throw noMatchingEntry(paymentRequired, args.terms);\n }\n // The FIRST-SEEN amount: a later challenge may never cost more than this.\n const firstSeenAmount = BigInt(requirement.amount);\n const host = new URL(url).host;\n\n // Both checks run BEFORE the wallet is even opened: an unverifiable deal must\n // not reach a signer. Terms a caller was given bind on EVERY lane, since a\n // routing decision can name a contract on the configured origin too; the\n // registry check is the Bazaar lane's own.\n let registry: string | undefined;\n let termsLabel: string | undefined;\n if (args.terms !== undefined) termsLabel = assertWithinTerms(args.terms, requirement);\n else if (lane === 'bazaar' && paymentRequired.extensions?.[SIGN_IN_WITH_X] === undefined) {\n registry = await checkRegistry(\n settings,\n url,\n requirement,\n ctx,\n args.ignoreWarnings === true,\n warnings,\n );\n }\n\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n await describeWallet(provider); // WALLET_MISSING with its own fix if none exists\n const signer = await provider.getSigner();\n openedSigner.current = signer;\n\n // The standard sign-in-with-x extension, same sequence as `buy`: when the 402\n // advertises it, an entitled wallet re-reads FREE before any payment exists,\n // and the re-check doubles as the fresh-challenge refetch the payment is\n // built against. The signature binds to the TARGET origin (host-with-port),\n // so a foreign seller gets a credential worth nothing anywhere else.\n let effectiveChallenge = paymentRequired;\n let effectiveRequirement = requirement;\n if (paymentRequired.extensions?.[SIGN_IN_WITH_X] !== undefined) {\n const siwxHeader = await buildSiwxHeader(signer, {\n baseUrl: new URL(url).origin,\n chainId: requirement.network,\n });\n const recheck = await httpRequest(url, {\n ...fetchOpts,\n headers: { ...headers, [SIWX_HEADER]: siwxHeader },\n });\n if (!recheck.ok) throw fetchFailureToCliError(recheck);\n if (recheck.status >= 200 && recheck.status < 300) {\n const caveat = assertUsableResult(\n args.resultSchema,\n recheck.text,\n recheck.status,\n 'entitled',\n );\n return deliver(url, lane, recheck, {\n paid: false,\n entitled: true,\n ...(caveat !== undefined ? { caveat } : {}),\n printBody: args.printBody === true,\n });\n }\n if (recheck.status !== 402) {\n throw new CliError(\n 'API_UNREACHABLE',\n `${url} answered ${recheck.status} on the entitlement re-check.`,\n {\n fix: 'Retry; if it persists the endpoint looks misconfigured.',\n details: { status: recheck.status, body: recheck.json, ...providerError(recheck.text) },\n },\n );\n }\n effectiveChallenge = decodeChallenge(recheck, url);\n const fresh = selectRequirement(payer.core, effectiveChallenge, args.terms);\n if (fresh === undefined) {\n throw noMatchingEntry(effectiveChallenge, args.terms);\n }\n // Refuse a price bump between the first look and signing, exactly as `buy`.\n if (BigInt(fresh.amount) > firstSeenAmount) {\n throw new CliError('PAYMENT_FAILED', 'The price increased before signing; refusing to pay.', {\n fix: 'Re-run `tenjin pay` to review the new price, and set --max-price to cap it.',\n details: {\n firstSeenAtomic: firstSeenAmount.toString(),\n currentAtomic: fresh.amount,\n },\n });\n }\n if (\n fresh.scheme !== requirement.scheme ||\n fresh.network !== requirement.network ||\n fresh.asset.toLowerCase() !== requirement.asset.toLowerCase() ||\n fresh.payTo.toLowerCase() !== requirement.payTo.toLowerCase() ||\n JSON.stringify(fresh.extra) !== JSON.stringify(requirement.extra)\n ) {\n throw new CliError(\n 'PAYMENT_FAILED',\n 'The payment terms changed before signing; refusing to pay.',\n { fix: 'Review a fresh challenge before paying again.' },\n );\n }\n effectiveRequirement = fresh;\n // The challenge it will actually SIGN is checked again: the store answers\n // the registry question without a network round trip in the common case.\n if (args.terms !== undefined) termsLabel = assertWithinTerms(args.terms, fresh);\n else if (lane === 'bazaar') {\n registry = await checkRegistry(\n settings,\n url,\n fresh,\n ctx,\n args.ignoreWarnings === true,\n warnings,\n );\n }\n }\n const amountAtomic = BigInt(effectiveRequirement.amount);\n\n const authorizer = resolveSpendAuthorizer(\n ctx,\n settings.policy,\n deps.authorizer !== undefined ? { authorizer: deps.authorizer } : {},\n );\n // The host is the creator identity here (`allowlistCreators` users pin\n // hosts); the gate itself is shared with `buy` so the two verbs cannot drift.\n const verifiedVia = registry ?? termsLabel;\n const via = verifiedVia !== undefined ? ` (${sanitizeForTerminal(verifiedVia)})` : '';\n const mode = router ? 'automatic' : 'manual';\n const reservationId = await gateSpend({\n mode,\n ctx,\n authorizer,\n amountAtomic,\n creator: host,\n ...(maxPriceAtomic !== undefined ? { maxPriceAtomic } : {}),\n ...(args.requestKey !== undefined ? { requestKey: args.requestKey } : {}),\n yes: args.yes === true,\n ...(deps.confirm !== undefined ? { confirm: deps.confirm } : {}),\n payeeLabel: `${sanitizeForTerminal(url)}${via}; recipient ${sanitizeForTerminal(effectiveRequirement.payTo)}, ${sanitizeForTerminal(effectiveRequirement.network)} / ${sanitizeForTerminal(effectiveRequirement.asset)}`,\n allowlistSubject: 'this host',\n notConfirmedMessage: 'Payment not confirmed.',\n });\n\n // A failure BEFORE transmission (the build) releases: no signature exists,\n // nothing can move. That is the last point where releasing is honest.\n let payment: Awaited<ReturnType<typeof buildExactPayment>>;\n try {\n // The SIGNED entry is the CHECKED entry, by construction: the challenge is\n // narrowed to the one selection everything above ran against, so a seller\n // advertising several chains cannot have one entry priced and another\n // signed. Without this the builder re-picked `accepts[0]`.\n if (amountAtomic > 0n) {\n // One retry across a rate-limit interval, within the original read deadline.\n const deadline = Date.now() + ctx.flags.timeout;\n const readBalance = deps.readBalance ?? readUsdcBalance;\n let balance = await readBalance(signer.address, settings.rpcUrl, {\n timeoutMs: Math.max(1, Math.floor(ctx.flags.timeout / 2)),\n });\n if (balance === null && Date.now() < deadline) {\n await delay(Math.min(1100, Math.floor((deadline - Date.now()) / 2)));\n const remaining = deadline - Date.now();\n if (remaining > 0)\n balance = await readBalance(signer.address, settings.rpcUrl, { timeoutMs: remaining });\n }\n if (balance === null) {\n throw new CliError(\n 'REFUSED',\n 'The wallet balance could not be read; no payment was signed.',\n {\n fix: 'Check the configured Base rpcUrl and retry when it is available.',\n details: { reason: 'balance_unavailable', address: signer.address },\n },\n );\n }\n if (balance < amountAtomic) {\n throw new CliError('REFUSED', 'The wallet has insufficient USDC; no payment was signed.', {\n fix: 'Fund this wallet on Base with `tenjin wallet fund` before paying.',\n details: {\n reason: 'insufficient_funds',\n address: signer.address,\n balanceAtomic: balance.toString(),\n requiredAtomic: amountAtomic.toString(),\n },\n });\n }\n }\n payment = await buildExactPayment(effectiveChallenge, signer, effectiveRequirement);\n } catch (err) {\n await authorizer.release(reservationId);\n throw err;\n }\n\n // From here the signed EIP-3009 authorization leaves the process, and it is a\n // bearer instrument: the counterparty can settle it whatever it answers, or\n // if it answers nothing. So EVERY post-transmission outcome commits the\n // reservation; money that may move is money accounted. Releasing here let a\n // hostile registry-listed seller answer 402 after each signature while\n // sessionBudget counted zero of the authorizations it was stacking up.\n // (httpRequest never throws on transport failure; it returns ok:false.)\n const paid = await httpRequest(url, {\n ...fetchOpts,\n timeoutMs: paidLegTimeoutMs(effectiveRequirement, ctx.flags.timeout),\n headers: { ...headers, ...payment.headers },\n });\n await authorizer.commit(reservationId, payment.amountAtomic, { mode });\n // A TRANSPORT failure on this leg is a post-transmission outcome like any\n // other: the authorization has left, the reservation is committed above, and\n // a receipt that said nothing was paid would report a provider cost of zero\n // for money the ledger has already counted. The transport's own reason and\n // code survive; only the fix and the amounts are this leg's to state.\n if (!paid.ok) {\n throw fetchFailureToCliError(paid, {\n fix:\n 'The authorization was transmitted and settlement is unknown; it is recorded as transmitted exposure. ' +\n `Do not simply retry: each attempt signs a fresh authorization. ${legFix(paid)}`,\n details: { amountAtomic: payment.amountAtomic.toString(), settlement: 'unknown' },\n });\n }\n if (paid.status >= 200 && paid.status < 300) {\n let caveat: string | undefined;\n if (args.resultSchema !== undefined) {\n const check = validateResultBody(args.resultSchema, paid.text);\n // A PAID BODY IS ALWAYS DELIVERED. The authorization has already left and\n // the money moved, so the success rule is a check on the body, never a\n // reason to withhold it: withholding charged the caller and threw the\n // product away. A body past this client's validation limit (never\n // checked) and one that fails the rule (checked, and missed) both come\n // back whole, flagged unverified, with a caveat that says which.\n if (check.unvalidated === true) caveat = unvalidatedCaveat(check);\n else if (!check.valid) caveat = failedRuleCaveat(check);\n }\n return deliver(url, lane, paid, {\n paid: true,\n warnings,\n amountAtomic: payment.amountAtomic,\n requirement: effectiveRequirement,\n ...(registry !== undefined ? { registry } : {}),\n ...(caveat !== undefined ? { caveat } : {}),\n printBody: args.printBody === true,\n });\n }\n // Still 402 (payment rejected) or anything else: nothing was delivered, but\n // the seller holds a live authorization, so the amount stays counted and the\n // fix must NOT coach a retry loop, since each retry signs a fresh authorization.\n throw new CliError(\n 'PAYMENT_FAILED',\n paid.status === 402\n ? 'Payment was not accepted by the endpoint.'\n : `The endpoint answered ${paid.status} on the paid request; whether it settled is unknown.`,\n {\n fix: 'The signed payment already left and is recorded as transmitted exposure; the endpoint may still settle it. Do not simply retry: each attempt signs a fresh authorization. Verify the endpoint (and this listing, if Bazaar) before paying again.',\n // The amount rides on the failure so a caller can report what is at risk\n // rather than a zero. Settlement is unknown by construction here.\n details: {\n status: paid.status,\n body: paid.json,\n ...providerError(paid.text),\n amountAtomic: payment.amountAtomic.toString(),\n settlement: 'unknown',\n },\n },\n );\n}\n\n/**\n * THE PAID LEG WAITS AS LONG AS THE SELLER SAID IT WOULD TAKE, within reason.\n * A signed authorization is already out when this leg starts, so a client\n * timeout here abandons money the seller can still settle: a 10 s default cut\n * off a provider advertising 360 s of work and threw its answer away. The\n * requirement's `maxTimeoutSeconds` is that promise; it is clamped to\n * {@link MAX_PAID_LEG_TIMEOUT_MS} so a hostile seller cannot hang the caller,\n * and it never shortens what the user asked for with `--timeout`. The probe\n * leg keeps the CLI timeout: nothing is at stake there.\n */\nexport const MAX_PAID_LEG_TIMEOUT_MS = 120_000;\n\nexport function paidLegTimeoutMs(requirement: PaymentRequirements, cliTimeoutMs: number): number {\n const advertised = requirement.maxTimeoutSeconds;\n if (typeof advertised !== 'number' || !Number.isFinite(advertised) || advertised <= 0) {\n return cliTimeoutMs;\n }\n return Math.max(cliTimeoutMs, Math.min(advertised * 1000, MAX_PAID_LEG_TIMEOUT_MS));\n}\n\n/** Which lane may pay this URL, or the exact refusal. */\nfunction resolveLane(url: string, settings: ResolvedSettings): Lane {\n let target: URL;\n try {\n target = new URL(url);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute http(s) URL.',\n });\n }\n if (target.protocol !== 'http:' && target.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute http(s) URL.',\n });\n }\n // Same deployment, not merely the same spelling: without this a URL on the\n // deployment's other origin falls through to the Bazaar lane, which then\n // refuses it as a third-party endpoint or pays it under registry rules meant\n // for one. The SIWX signature below binds to the TARGET origin either way.\n if (isSameDeployment(target.origin, new URL(settings.baseUrl).origin)) return 'tenjin';\n if (target.protocol !== 'https:') {\n throw new CliError('USAGE', 'The Bazaar lane pays https endpoints only.', {\n fix: 'Use a public HTTPS endpoint.',\n });\n }\n return 'bazaar';\n}\n\nfunction resolveMethod(args: PayArgs): 'GET' | 'POST' {\n const method = args.method?.toUpperCase() ?? (args.data !== undefined ? 'POST' : 'GET');\n if (method !== 'GET' && method !== 'POST') {\n throw new CliError('USAGE', `Unsupported method ${JSON.stringify(args.method)}`, {\n fix: 'Use -X GET or -X POST.',\n });\n }\n if (method === 'GET' && (args.data !== undefined || args.rawBody !== undefined)) {\n throw new CliError('USAGE', 'A request body needs -X POST.', {\n fix: 'Drop --data, or pass -X POST.',\n });\n }\n return method;\n}\n\n/**\n * The caller's headers, or a refusal. Two names only: everything else on this\n * request is either this command's to set (the payment signature, the user\n * agent, the shelf bypass) or nobody's.\n */\nfunction callerHeaders(headers: Record<string, string> | undefined): Record<string, string> {\n if (headers === undefined) return {};\n const allowed = new Set(['accept', 'content-type']);\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n const lowered = name.toLowerCase();\n if (!allowed.has(lowered) || value.length > 1_024 || /[\\r\\n]/.test(value)) {\n throw new CliError(\n 'USAGE',\n `This command will not send the header ${JSON.stringify(name)}.`,\n {\n fix: 'Only bounded accept and content-type headers ride on a paid request.',\n },\n );\n }\n out[lowered] = value;\n }\n return out;\n}\n\nfunction parseBody(data: string | undefined): unknown {\n if (data === undefined) return undefined;\n try {\n return JSON.parse(data);\n } catch {\n throw new CliError('USAGE', 'The --data value is not valid JSON.', {\n fix: 'Pass a JSON object/array/string, e.g. --data \\'{\"question\":\"...\"}\\'.',\n });\n }\n}\n\nfunction decodeChallenge(res: HttpResponse, url: string): PaymentRequired {\n const encoded = res.header(PAYMENT_REQUIRED_HEADER);\n if (encoded === undefined) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The 402 from ${url} carried no PAYMENT-REQUIRED header.`,\n {\n fix: 'The endpoint does not speak x402 v2; nothing was paid.',\n },\n );\n }\n try {\n return decodePaymentRequiredHeader(encoded);\n } catch (err) {\n throw new CliError('CONTRACT_MISMATCH', 'Could not decode the PAYMENT-REQUIRED header.', {\n cause: err,\n });\n }\n}\n\n/**\n * The caller's success rule, on EVERY delivery this command makes: a body that\n * fails it is not a result, whether it arrived free, by entitlement or paid.\n * Applying it only to the paid branch let a `{success:false}` body come back as\n * `fulfilled` the moment the wallet was already entitled.\n *\n * Returns the caveat for a body the rule could not be RUN against, so the three\n * branches treat an over-limit body the same way; `undefined` when the rule\n * passed or there was none.\n */\nfunction assertUsableResult(\n schema: unknown,\n body: string,\n status: number,\n how: 'free' | 'entitled',\n): string | undefined {\n if (schema === undefined) return undefined;\n const check = validateResultBody(schema, body);\n if (check.valid) return undefined;\n if (check.unvalidated === true) return unvalidatedCaveat(check);\n throw new CliError('CONTRACT_MISMATCH', 'The response is not a usable result.', {\n fix: `Nothing was paid on this ${how} delivery. The endpoint answered ${status} with a body that fails the success rule it was asked under.`,\n details: {\n status,\n reason: check.reason,\n ...(check.diagnosis !== undefined ? { diagnosis: check.diagnosis } : {}),\n paid: false,\n },\n });\n}\n\n/**\n * What the caller is told INSTEAD of a refusal when the success rule could not\n * run: the byte count, that the check was skipped, and that the body in hand is\n * unverified. It rides in the result rather than only in a log, because the\n * agent reading the envelope is the one that has to discount it.\n */\nfunction unvalidatedCaveat(check: ResultCheck): string {\n return `${check.reason ?? 'The result could not be validated.'} The body is delivered unverified: its shape was never checked against the success rule.`;\n}\n\n/** What the caller is told when a PAID body was checked and missed its success\n * rule: the rule that failed, and that the body is handed back unverified. */\nfunction failedRuleCaveat(check: ResultCheck): string {\n return `${check.reason ?? 'The result does not satisfy its success schema.'} The payment settled, so the body is delivered as received, unverified: treat it as possibly not the answer that was paid for.`;\n}\n\n/** The transport's own remedy, when it has one, appended after the leg's\n * payment sentence so the two never contradict each other. */\nfunction legFix(failure: { kind: string }): string {\n return failure.kind === 'oversized-header'\n ? 'Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes.'\n : '';\n}\n\n/** `{error: {message}}` from the provider, as one bounded plain line, or null.\n * It reaches a model's context, so control characters do not survive. */\nfunction providerMessage(body: unknown): string | null {\n const error = (body as { error?: unknown } | null | undefined)?.error;\n const message = (error as { message?: unknown } | null | undefined)?.message;\n if (typeof message !== 'string') return null;\n const line = message\n .replace(/[\\p{Cc}\\p{Cf}]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 300);\n return line.length > 0 ? line : null;\n}\n\n/** Cap on {@link providerError}: enough for a provider's reason, never its page. */\nconst PROVIDER_ERROR_CHARS = 500;\n\n/**\n * WHY THE PROVIDER REFUSED, in its own words: the first\n * {@link PROVIDER_ERROR_CHARS} characters of a non-2xx body, redacted and on\n * one plain line, whatever its type. `body` above is the parse, which an HTML\n * error page has none of, and without this a 403 reached the agent as a bare\n * status. Other people's content, never instructions.\n */\nfunction providerError(text: string): { providerError?: string } {\n // Masked in a window well past the cap, so a large page costs nothing and a\n // secret that starts inside the snippet is seen whole.\n const flat = sanitizeForTerminal(\n mask(text.slice(0, PROVIDER_ERROR_CHARS * 8)).replace(/\\s+/g, ' '),\n ).trim();\n if (flat.length === 0) return {};\n const chars = Array.from(flat);\n return {\n providerError:\n chars.length <= PROVIDER_ERROR_CHARS\n ? flat\n : `${chars.slice(0, PROVIDER_ERROR_CHARS).join('')}…`,\n };\n}\n\n/** Nothing this caller may pay: no entry at all, or none on the advertised\n * scheme, network and asset. Refused before a signer is even opened. */\nfunction noMatchingEntry(challenge: PaymentRequired, terms: AdvertisedTerms | undefined): CliError {\n // No terms, or terms that pinned no chain and no token: the 402 simply\n // advertises nothing this wallet can pay, which the shared refusal already\n // names in the SDK's own vocabulary.\n if (terms === undefined || (terms.network === undefined && terms.asset === undefined)) {\n return noPayableRequirement(challenge.accepts);\n }\n const advertised = challenge.accepts.map((a) => `${a.scheme}/${a.network}/${a.asset}`);\n return new CliError(\n 'REGISTRY_MISMATCH',\n `The 402 advertises nothing on ${terms.network ?? 'any supported chain'} in ${terms.asset ?? 'any supported token'}, which is what this call was authorized against.`,\n {\n fix: 'Nothing was signed. The endpoint changed the deal since those terms were issued; ask for a fresh decision.',\n details: { advertised, terms },\n },\n );\n}\n\n/**\n * WHICH advertised entry this call is about, from the SDK's own selection\n * (`src/lib/x402-pay.ts`): the registered networks, the `exact` scheme and the\n * canonical-USDC policy, narrowed further by advertised terms when the caller\n * has them. Every paying path asks this one question, so a 402 that lists\n * seven entries cannot have one priced and another signed.\n */\nfunction selectRequirement(\n core: x402Client,\n challenge: PaymentRequired,\n terms: AdvertisedTerms | undefined,\n): PaymentRequirements | undefined {\n return selectPayableRequirement(\n core,\n challenge,\n terms === undefined ? undefined : { network: terms.network, asset: terms.asset },\n );\n}\n\n/**\n * The advertised-terms gate. Same shape of answer as the registry gate and the\n * same failure code, because it answers the same question: is the live 402 the\n * deal this call was authorized against? Exact on scheme, network and asset, at\n * most on the amount. Returns the label the payee line names.\n */\nfunction assertWithinTerms(terms: AdvertisedTerms, requirement: PaymentRequirements): string {\n // Scheme, network and asset already matched: `selectRequirement` chose this\n // entry BY them. What is left is the deal's price and its destination.\n const overQuote =\n terms.maxAmountAtomic !== undefined &&\n BigInt(requirement.amount) > BigInt(terms.maxAmountAtomic);\n const mismatch = overQuote\n ? `amount ${requirement.amount} over the advertised ${terms.maxAmountAtomic ?? '0'}`\n : terms.payTo !== undefined && requirement.payTo.toLowerCase() !== terms.payTo.toLowerCase()\n ? `payTo ${requirement.payTo}`\n : undefined;\n if (mismatch !== undefined) {\n throw new CliError(\n 'REGISTRY_MISMATCH',\n `The live 402 exceeds the terms this call was authorized against (${mismatch}).`,\n {\n fix: 'Nothing was signed. The endpoint changed its deal since those terms were issued; ask for a fresh decision.',\n details: { advertised: terms, live: requirement },\n },\n );\n }\n return terms.source ?? 'the advertised terms';\n}\n\n/** Registry evidence informs direct payments; only this invocation can acknowledge a warning. */\nasync function checkRegistry(\n settings: ResolvedSettings,\n url: string,\n requirement: PaymentRequirements,\n ctx: CommandContext,\n acknowledged: boolean,\n warnings: RegistryWarning[],\n): Promise<string | undefined> {\n const verification = await verifyAgainstRegistries(\n settings.bazaarRegistries,\n url,\n requirement,\n ctx.flags.timeout,\n { dataDir: ctx.dataDir },\n );\n if (verification.outcome === 'verified') return verification.registry;\n if (verification.outcome === 'unlisted') return undefined;\n const warning: RegistryWarning = {\n ...verification,\n acknowledged,\n quote: { url, ...requirement },\n };\n warnings.push(warning);\n const message = warningMessage(warning);\n if (!ctx.flags.json) {\n ctx.io.stderr.write(\n `Live quote: ${sanitizeForTerminal(url)}; recipient ${sanitizeForTerminal(requirement.payTo)}; ${sanitizeForTerminal(requirement.network)} / ${sanitizeForTerminal(requirement.asset)}; ${toMoney(requirement.amount).usd} USD\\n`,\n );\n ctx.io.stderr.write(\n `${sanitizeForTerminal(message)}${acknowledged ? ' (acknowledged for this invocation)' : ''}\\n`,\n );\n }\n if (!acknowledged) {\n throw new CliError('REFUSED', message, {\n fix: 'Review the live quote and use --ignore-warnings to acknowledge this registry warning for this invocation. --yes only confirms payment; normal payment checks still apply.',\n details: { reason: 'registry_acknowledgement_required', quote: { url, ...requirement } },\n });\n }\n return undefined;\n}\n\nfunction warningMessage(warning: RegistryWarning): string {\n switch (warning.outcome) {\n case 'unavailable':\n return 'Registry warning: verification is unavailable or incomplete.';\n case 'mismatch':\n return `Registry warning: the live terms differ from ${warning.registry} (${warning.detail}).`;\n }\n}\n\n/** Discriminated on `paid`: a paid delivery always carries what it paid and to\n * whom, so no branch ever reaches for an amount that might not be there. */\ntype DeliverOpts = {\n /** Set when the body is delivered UNVERIFIED: the success rule could not run. */\n caveat?: string;\n warnings?: RegistryWarning[];\n} & (\n | {\n paid: false;\n /** Free because the wallet was already entitled (SIWX), not free-of-price. */\n entitled?: boolean;\n printBody: boolean;\n }\n | {\n paid: true;\n amountAtomic: bigint;\n requirement: PaymentRequirements;\n registry?: string;\n printBody: boolean;\n }\n);\n\nfunction deliver(url: string, lane: Lane, res: HttpResponse, opts: DeliverOpts): CommandResult {\n const settlementTxHash = opts.paid ? settlementTx(res) : undefined;\n const data = {\n url,\n lane,\n status: res.status,\n paid: opts.paid,\n ...(opts.warnings !== undefined ? { warnings: opts.warnings } : {}),\n ...(opts.paid\n ? {\n amountPaid: toMoney(opts.amountAtomic.toString()),\n payTo: opts.requirement.payTo,\n network: opts.requirement.network,\n asset: opts.requirement.asset,\n ...(opts.registry !== undefined ? { registry: opts.registry } : {}),\n }\n : opts.entitled === true\n ? { entitled: true }\n : {}),\n ...(settlementTxHash !== undefined ? { settlementTxHash } : {}),\n // Beside the body, never instead of it: the caller gets the product AND the\n // fact that its shape was never checked. The flag is what a machine reads:\n // a caller branching on a delivery must not have to match on prose, which\n // is how an unchecked body passed for a checked one one layer up.\n ...(opts.caveat !== undefined ? { resultUnverified: true, resultCaveat: opts.caveat } : {}),\n // The body is the product: JSON when the endpoint spoke it, raw text always.\n ...(res.json !== undefined ? { body: res.json } : {}),\n bodyText: res.text,\n };\n const headline = opts.paid\n ? `paid ${toMoney(opts.amountAtomic.toString()).usd} USD to ${sanitizeForTerminal(new URL(url).host)}` +\n (settlementTxHash !== undefined ? ` (tx ${settlementTxHash})` : '')\n : opts.entitled === true\n ? `free (entitled, no charge)`\n : `free (${res.status}, no charge)`;\n const body = sanitizeForTerminal(res.text);\n const preview =\n opts.printBody || body.length <= BODY_PREVIEW_CHARS\n ? body\n : `${body.slice(0, BODY_PREVIEW_CHARS)}\\n… truncated; run with --print-body or --json for the full body`;\n return {\n data,\n humanLines: [\n headline,\n ...(opts.warnings ?? []).map(\n (w) => `${sanitizeForTerminal(warningMessage(w))} (acknowledged)`,\n ),\n ...(opts.caveat !== undefined ? [sanitizeForTerminal(opts.caveat)] : []),\n ...(preview.length > 0 ? [preview] : []),\n ],\n };\n}\n\nfunction settlementTx(res: HttpResponse): string | undefined {\n const header = res.header(PAYMENT_RESPONSE_HEADER);\n if (header === undefined) return undefined;\n try {\n const settle = decodePaymentResponseHeader(header);\n const tx = (settle as { transaction?: unknown }).transaction;\n return typeof tx === 'string' ? tx : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The signer, once the wallet has been opened. Selection never reaches it. */\nfunction signerOrThrow(held: { current?: TenjinSigner }): TenjinSigner {\n if (held.current === undefined) {\n throw new CliError('INTERNAL', 'The payment was built before the wallet was opened.');\n }\n return held.current;\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { HTTPFacilitatorClient } from '@x402/core/http';\nimport { withBazaar } from '@x402/extensions/bazaar';\nimport type { DiscoveryResource } from '@x402/extensions/bazaar';\nimport type { PaymentRequirements } from '@x402/core/types';\nimport { getAddress } from 'viem';\nimport { PaymentRequirementsV2Schema } from '@x402/core/schemas';\nimport { z } from 'zod';\nimport { writeFileAtomic } from './atomic-json';\n\n/**\n * Discovery is evidence, never payment authority. Standard registries use the\n * SDK; Ultravioleta has an explicit adapter for its different discovery shape.\n * Every payment candidate is matched locally against the live requirement.\n */\n\nexport interface RegistryResource {\n /** The payable resource URL, exactly as the registry lists it. */\n url: string;\n registry: string;\n description?: string;\n accepts: PaymentRequirements[];\n lastUpdated?: string;\n}\n\nexport interface RegistryError {\n registry: string;\n message: string;\n}\n\nexport interface RegistrySweep {\n resources: RegistryResource[];\n /** Registries that did not answer; a sweep with errors is PARTIAL, never silently complete. */\n errors: RegistryError[];\n /** Listings skipped because they are not plain HTTP resources (e.g. MCP servers). */\n skippedNonHttp: number;\n}\n\n/** One page is the sweep unit; a payTo filter narrows far below this. */\nconst PAGE_LIMIT = 100;\n/** CDP's search endpoint rejects limits above 20 (verified live 2026-08-14). */\nconst SEARCH_LIMIT = 20;\n\nconst MAX_PAGES = 5;\nconst MAX_RESPONSE_BYTES = 2 * 1024 * 1024;\nconst ULTRAVIOLETA_ORIGIN = 'https://facilitator.ultravioletadao.xyz';\n\nfunction isUltravioleta(registry: string): boolean {\n return new URL(registry).origin === ULTRAVIOLETA_ORIGIN;\n}\n\nconst paymentTerms = z.custom<PaymentRequirements>((value: unknown) => {\n const parsed = PaymentRequirementsV2Schema.safeParse(value);\n return parsed.success && /^\\d+$/.test(parsed.data.amount);\n});\nconst ultravioletResource = z.object({\n url: z.string().url(),\n type: z.string(),\n x402Version: z.number().int(),\n description: z.string().optional(),\n accepts: z.array(paymentTerms).max(100),\n lastUpdated: z.number().int().nonnegative().max(8_640_000_000_000),\n});\nconst paginationSchema = z.object({\n limit: z.number().int().positive().max(PAGE_LIMIT),\n offset: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n});\ninterface Listings {\n items: DiscoveryResource[];\n incomplete?: string;\n}\n\n/** A registry controls its response size as well as its latency. */\nasync function boundedJson(res: Response): Promise<unknown> {\n const reader = res.body?.getReader();\n if (!reader) throw new Error('Registry response has no body');\n const chunks: Uint8Array[] = [];\n let bytes = 0;\n try {\n for (;;) {\n const next = await reader.read();\n if (next.done) break;\n bytes += next.value.byteLength;\n if (bytes > MAX_RESPONSE_BYTES) throw new Error('Registry response exceeds size limit');\n chunks.push(next.value);\n }\n } finally {\n await reader.cancel();\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;\n}\n\n/** Ultravioleta's documented resources API uses q, url and Unix seconds. */\nasync function ultravioletListings(\n registry: string,\n timeoutMs: number,\n query?: string,\n): Promise<Listings> {\n const deadline = Date.now() + timeoutMs;\n const items: DiscoveryResource[] = [];\n let offset = 0;\n let incomplete: string | undefined;\n for (let page = 0; page < MAX_PAGES; page++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new Error('Registry lookup deadline exceeded');\n const params = new URLSearchParams({\n limit: String(PAGE_LIMIT),\n offset: String(offset),\n ...(query !== undefined ? { q: query } : {}),\n });\n const res = await fetch(`${new URL(registry).origin}/discovery/resources?${params}`, {\n headers: { accept: 'application/json' },\n signal: AbortSignal.timeout(remaining),\n redirect: 'error',\n });\n if (!res.ok) throw new Error(`listing ${registry} answered ${res.status}`);\n const response = z\n .object({ items: z.array(z.unknown()).max(PAGE_LIMIT), pagination: paginationSchema })\n .parse(await boundedJson(res));\n const pagination = response.pagination;\n if (pagination.offset !== offset || response.items.length > pagination.limit)\n throw new Error('Invalid registry pagination');\n for (const record of response.items) {\n const parsed = ultravioletResource.safeParse(record);\n if (!parsed.success) {\n incomplete = 'Registry search skipped malformed records';\n continue;\n }\n const item = parsed.data;\n items.push({\n resource: item.url,\n type: item.type,\n x402Version: item.x402Version,\n accepts: item.accepts as PaymentRequirements[],\n lastUpdated: new Date(item.lastUpdated * 1000).toISOString(),\n ...(item.description !== undefined ? { description: item.description } : {}),\n });\n }\n const next = pagination.offset + response.items.length;\n if (next >= pagination.total) return { items, ...(incomplete ? { incomplete } : {}) };\n if (response.items.length === 0) break;\n offset = next;\n }\n return { items, incomplete: 'Registry search truncated at the pagination limit' };\n}\n\nfunction client(registry: string) {\n return withBazaar(new HTTPFacilitatorClient({ url: registry }));\n}\n\n/** The SDK fetch carries no deadline; a registry that stalls loses its slot. */\nasync function withTimeout<T>(work: Promise<T>, timeoutMs: number, what: string): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`${what} timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction toResource(item: DiscoveryResource, registry: string): RegistryResource {\n return {\n url: item.resource,\n registry,\n ...(item.description !== undefined ? { description: item.description } : {}),\n accepts: item.accepts,\n ...(item.lastUpdated !== undefined ? { lastUpdated: item.lastUpdated } : {}),\n };\n}\n\n/** List HTTP-type resources across every configured registry. */\nexport async function sweepRegistries(\n registries: readonly string[],\n opts: { timeoutMs: number; query?: string },\n): Promise<RegistrySweep> {\n const resources: RegistryResource[] = [];\n const errors: RegistryError[] = [];\n let skippedNonHttp = 0;\n const deadline = Date.now() + opts.timeoutMs;\n for (const registry of registries) {\n try {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new Error('Registry lookup deadline exceeded');\n const bazaar = client(registry).extensions.bazaar;\n const ultraviolet = isUltravioleta(registry)\n ? await withTimeout(\n ultravioletListings(registry, remaining, opts.query),\n remaining,\n registry,\n )\n : undefined;\n if (ultraviolet?.incomplete) errors.push({ registry, message: ultraviolet.incomplete });\n const items =\n ultraviolet?.items ??\n (opts.query !== undefined\n ? (\n await withTimeout(\n bazaar.search({ query: opts.query, limit: SEARCH_LIMIT }),\n remaining,\n `search on ${registry}`,\n )\n ).resources\n : (\n await withTimeout(\n bazaar.listResources({ type: 'http', limit: PAGE_LIMIT }),\n remaining,\n `listing ${registry}`,\n )\n ).items);\n for (const item of items) {\n if (item.type !== 'http') {\n // An MCP-type listing is a seller this CLI cannot speak x402-over-HTTP\n // to; counted so the sweep never silently narrows what it covered.\n skippedNonHttp += 1;\n continue;\n }\n resources.push(toResource(item, registry));\n }\n } catch (err) {\n errors.push({ registry, message: err instanceof Error ? err.message : String(err) });\n }\n }\n return { resources, errors, skippedNonHttp };\n}\n\n// ---------------------------------------------------------------------------\n// The local listing store: what a `discover` sweep returned, kept as pay-time\n// evidence (bounded, TTL'd). The pay lane checks a fresh stored listing first,\n// then asks each registry live (`listingsFor`), so the store is a shortcut and\n// never the only way a listed resource can be paid.\n// ---------------------------------------------------------------------------\n\nconst LISTING_STORE_FILE = 'bazaar-listings.json';\n/** A listing older than this is not pay-time evidence; the live lookup decides. */\nconst LISTING_TTL_MS = 24 * 60 * 60 * 1000;\n/** Newest-first cap so the store cannot grow without bound. */\nconst LISTING_STORE_CAP = 1000;\n\nexport interface StoredListing {\n url: string;\n registry: string;\n accepts: PaymentRequirements[];\n fetchedAt: string;\n}\n\ninterface ListingStore {\n listings: StoredListing[];\n}\n\nfunction listingStorePath(dataDir: string): string {\n return join(dataDir, LISTING_STORE_FILE);\n}\n\n/**\n * Shape-checked PER ENTRY, not just per array. `acceptsMismatch` iterates\n * `accepts`, so one malformed row from a truncated write or a hand-edit throws a\n * raw TypeError out of the check that decides whether a payment may be signed.\n * A row that is not the shape this module writes is dropped, which costs at\n * worst a live lookup.\n */\nfunction isStoredListing(value: unknown): value is StoredListing {\n if (typeof value !== 'object' || value === null) return false;\n const listing = value as Partial<StoredListing>;\n return (\n typeof listing.url === 'string' &&\n typeof listing.registry === 'string' &&\n typeof listing.fetchedAt === 'string' &&\n Array.isArray(listing.accepts)\n );\n}\n\nasync function loadListingStore(dataDir: string): Promise<ListingStore> {\n try {\n const raw: unknown = JSON.parse(await readFile(listingStorePath(dataDir), 'utf8'));\n const listings = (raw as { listings?: unknown } | null)?.listings;\n return { listings: Array.isArray(listings) ? listings.filter(isStoredListing) : [] };\n } catch {\n return { listings: [] };\n }\n}\n\n/** Persist a sweep's listings, newest first, deduplicated on (identity, registry). */\nexport async function saveSweepListings(\n dataDir: string,\n resources: readonly RegistryResource[],\n now: () => number = Date.now,\n): Promise<void> {\n const store = await loadListingStore(dataDir);\n const fetchedAt = new Date(now()).toISOString();\n const fresh: StoredListing[] = resources.map((r) => ({\n url: r.url,\n registry: r.registry,\n accepts: r.accepts,\n fetchedAt,\n }));\n const seen = new Set(fresh.map((l) => `${l.registry} ${l.url}`));\n const kept = store.listings.filter((l) => !seen.has(`${l.registry} ${l.url}`));\n await writeFileAtomic(\n listingStorePath(dataDir),\n JSON.stringify({ listings: [...fresh, ...kept].slice(0, LISTING_STORE_CAP) }, null, 2),\n );\n}\n\n/** Fresh stored listings for this resource identity, newest first. */\nasync function storedListingsFor(\n dataDir: string,\n url: string,\n now: () => number,\n): Promise<StoredListing[]> {\n const store = await loadListingStore(dataDir);\n return store.listings.filter((l) => {\n if (!sameResourceUrl(l.url, url)) return false;\n const age = now() - Date.parse(l.fetchedAt);\n // BOUNDED AT BOTH ENDS. A negative age is not extra-fresh evidence, it is a\n // stamp the clock disagrees with (skew, a restored or copied data dir), and\n // an unbounded `age < TTL` made such a listing permanent pay-time evidence\n // that no 24h re-sweep could ever expire. NaN (an unparseable stamp) fails\n // the same comparison.\n return age >= 0 && age < LISTING_TTL_MS;\n });\n}\n\nexport type RegistryVerification =\n | { outcome: 'verified'; registry: string }\n /** Listed somewhere, but no listing matches the live 402's terms. */\n | { outcome: 'mismatch'; registry: string; detail: string }\n | { outcome: 'unlisted' }\n /** Some required evidence could not be checked; absence is not established. */\n | { outcome: 'unavailable'; errors: RegistryError[] };\n\n/**\n * Resource identity is origin + path (trailing slash normalized): a registry\n * lists the ENDPOINT, and the query string is the per-call request riding it\n * (verified live: the Bazaar lists `/search`, callers pay `/search?query=...`).\n * An unparseable listing matches nothing.\n */\nfunction sameResourceUrl(listed: string, requested: string): boolean {\n const a = resourceIdentity(listed);\n return a !== null && a === resourceIdentity(requested);\n}\n\nfunction resourceIdentity(u: string): string | null {\n try {\n const parsed = new URL(u);\n const path = parsed.pathname.endsWith('/') ? parsed.pathname.slice(0, -1) : parsed.pathname;\n return `${parsed.origin}${path}`;\n } catch {\n return null;\n }\n}\n\n/** Search by endpoint identity so differing recipients remain visible. Registries\n * without search retain the SDK's recipient-filtered listing fallback. */\nasync function listingsFor(\n registry: string,\n url: string,\n payTo: string,\n timeoutMs: number,\n): Promise<Listings> {\n if (isUltravioleta(registry))\n return ultravioletListings(registry, timeoutMs, resourceIdentity(url) ?? url);\n const deadline = Date.now() + timeoutMs;\n const params = new URLSearchParams({\n urlSubstring: resourceIdentity(url) ?? url,\n limit: String(SEARCH_LIMIT),\n });\n const res = await fetch(`${registry.replace(/\\/+$/, '')}/discovery/search?${params.toString()}`, {\n headers: { accept: 'application/json' },\n signal: AbortSignal.timeout(timeoutMs),\n redirect: 'error',\n });\n if (res.ok) {\n const answer = (await boundedJson(res)) as {\n resources?: unknown;\n partialResults?: boolean;\n pagination?: { cursor?: unknown };\n } | null;\n if (Array.isArray(answer?.resources)) {\n return {\n items: answer.resources.slice(0, PAGE_LIMIT) as DiscoveryResource[],\n ...(answer.resources.length > PAGE_LIMIT ||\n answer.partialResults === true ||\n answer.pagination?.cursor != null\n ? { incomplete: 'Registry search results are truncated' }\n : {}),\n };\n }\n } else if (res.status !== 400 && res.status !== 404) {\n throw new Error(`search on ${registry} answered ${res.status}`);\n }\n const bazaar = client(registry).extensions.bazaar;\n const items: DiscoveryResource[] = [];\n let offset = 0;\n for (let page = 0; page < MAX_PAGES; page++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new Error('Registry lookup deadline exceeded');\n const response = await withTimeout(\n bazaar.listResources({ type: 'http', payTo, limit: PAGE_LIMIT, offset }),\n remaining,\n registry,\n );\n const pagination = paginationSchema.parse(response.pagination);\n if (\n !Array.isArray(response.items) ||\n response.items.length > PAGE_LIMIT ||\n pagination.offset !== offset\n )\n throw new Error('Invalid registry page');\n items.push(...response.items);\n offset = pagination.offset + response.items.length;\n if (offset >= pagination.total) return { items };\n if (response.items.length === 0) break;\n }\n return { items, incomplete: 'Registry listing truncated at the pagination limit' };\n}\n\n/** An exact resource match must cover the live scheme, network, asset, recipient\n * and price. Missing or incomplete evidence is never a verified listing. */\nexport async function verifyAgainstRegistries(\n registries: readonly string[],\n url: string,\n live: PaymentRequirements,\n timeoutMs: number,\n opts: { dataDir?: string; now?: () => number } = {},\n): Promise<RegistryVerification> {\n const errors: RegistryError[] = [];\n let mismatch: { registry: string; detail: string } | undefined;\n\n // A fresh listing a `discover` sweep stored IS the registry's word for this\n // resource, and it answers without a round trip.\n if (opts.dataDir !== undefined) {\n for (const listing of await storedListingsFor(opts.dataDir, url, opts.now ?? Date.now)) {\n if (!registries.includes(listing.registry)) continue; // no longer configured\n const detail = acceptsMismatch(listing.accepts, live);\n if (detail === null) return { outcome: 'verified', registry: listing.registry };\n mismatch ??= { registry: listing.registry, detail };\n }\n }\n\n const deadline = Date.now() + timeoutMs;\n for (const registry of registries) {\n try {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new Error('Registry lookup deadline exceeded');\n const listed = await withTimeout(\n listingsFor(registry, url, live.payTo, remaining),\n remaining,\n `looking up this resource on ${registry}`,\n );\n if (listed.incomplete) errors.push({ registry, message: listed.incomplete });\n const matches = listed.items.filter(\n (item) =>\n item != null &&\n item.type === 'http' &&\n typeof item.resource === 'string' &&\n Array.isArray(item.accepts) &&\n sameResourceUrl(item.resource, url),\n );\n if (matches.length === 0) continue;\n for (const item of matches) {\n const detail = acceptsMismatch(item.accepts, live);\n if (detail === null) return { outcome: 'verified', registry };\n mismatch ??= { registry, detail };\n }\n } catch (err) {\n errors.push({ registry, message: err instanceof Error ? err.message : String(err) });\n }\n }\n if (mismatch !== undefined) return { outcome: 'mismatch', ...mismatch };\n if (errors.length > 0) {\n return { outcome: 'unavailable', errors };\n }\n return { outcome: 'unlisted' };\n}\n\n/** Null when some advertised accept covers the live requirement; else why not. */\nfunction acceptsMismatch(\n advertised: PaymentRequirements[],\n live: PaymentRequirements,\n): string | null {\n let closest = 'the listing advertises no payment terms';\n for (const raw of advertised) {\n const parsed = paymentTerms.safeParse(raw);\n if (!parsed.success) {\n closest = 'malformed advertised payment terms';\n continue;\n }\n const adv = parsed.data;\n if (adv.scheme !== live.scheme) {\n closest = `advertised scheme ${adv.scheme}, live ${live.scheme}`;\n continue;\n }\n if (adv.network !== live.network) {\n closest = `advertised network ${adv.network}, live ${live.network}`;\n continue;\n }\n if (!sameAddress(adv.asset, live.asset)) {\n closest = `advertised asset ${adv.asset}, live ${live.asset}`;\n continue;\n }\n if (!sameAddress(adv.payTo, live.payTo)) {\n closest = `advertised payTo ${adv.payTo}, live ${live.payTo}`;\n continue;\n }\n let advertisedAmount: bigint;\n let liveAmount: bigint;\n try {\n advertisedAmount = BigInt(adv.amount);\n liveAmount = BigInt(live.amount);\n } catch {\n closest = 'a non-integer amount in the listing or the live 402';\n continue;\n }\n if (liveAmount > advertisedAmount) {\n closest = `live amount ${live.amount} exceeds the advertised ${adv.amount}`;\n continue;\n }\n return null;\n }\n return closest;\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n try {\n return getAddress(a) === getAddress(b);\n } catch {\n return false;\n }\n}\n","/**\n * HTTP-specific type definitions for the Bazaar Discovery Extension\n */\n\nimport type { BodyMethods, QueryParamMethods } from \"@x402/core/http\";\nimport type { DiscoveryInfo } from \"../types\";\n\n/** Shared schema definition for an object-typed parameter map (queryParams, pathParams, etc.) */\ninterface ParamMapSchemaProperty {\n type: \"object\";\n properties?: Record<string, unknown>;\n additionalProperties?: boolean;\n}\n\n/**\n * Discovery info for query parameter methods (GET, HEAD, DELETE)\n */\nexport interface QueryDiscoveryInfo {\n input: {\n type: \"http\";\n /** Absent at declaration time; set by bazaarResourceServerExtension.enrichDeclaration */\n method?: QueryParamMethods;\n queryParams?: Record<string, unknown>;\n pathParams?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Discovery info for body methods (POST, PUT, PATCH)\n */\nexport interface BodyDiscoveryInfo {\n input: {\n type: \"http\";\n /** Absent at declaration time; set by bazaarResourceServerExtension.enrichDeclaration */\n method?: BodyMethods;\n bodyType: \"json\" | \"form-data\" | \"text\";\n body: Record<string, unknown>;\n queryParams?: Record<string, unknown>;\n pathParams?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Discovery extension for query parameter methods (GET, HEAD, DELETE)\n */\nexport interface QueryDiscoveryExtension {\n info: QueryDiscoveryInfo;\n routeTemplate?: string;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"http\";\n };\n method: {\n type: \"string\";\n enum: QueryParamMethods[];\n };\n queryParams?: ParamMapSchemaProperty & { required?: string[] };\n pathParams?: ParamMapSchemaProperty;\n headers?: {\n type: \"object\";\n additionalProperties: {\n type: \"string\";\n };\n };\n };\n required: (\"type\" | \"method\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\n/**\n * Discovery extension for body methods (POST, PUT, PATCH)\n */\nexport interface BodyDiscoveryExtension {\n info: BodyDiscoveryInfo;\n routeTemplate?: string;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"http\";\n };\n method: {\n type: \"string\";\n enum: BodyMethods[];\n };\n bodyType: {\n type: \"string\";\n enum: [\"json\", \"form-data\", \"text\"];\n };\n body: Record<string, unknown>;\n queryParams?: ParamMapSchemaProperty & { required?: string[] };\n pathParams?: ParamMapSchemaProperty;\n headers?: {\n type: \"object\";\n additionalProperties: {\n type: \"string\";\n };\n };\n };\n required: (\"type\" | \"method\" | \"bodyType\" | \"body\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\nexport interface DeclareQueryDiscoveryExtensionConfig {\n method?: QueryParamMethods;\n input?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n pathParams?: Record<string, unknown>;\n pathParamsSchema?: Record<string, unknown>;\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport interface DeclareBodyDiscoveryExtensionConfig {\n method?: BodyMethods;\n input?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n pathParams?: Record<string, unknown>;\n pathParamsSchema?: Record<string, unknown>;\n bodyType: \"json\" | \"form-data\" | \"text\";\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport interface DiscoveredHTTPResource {\n resourceUrl: string;\n description?: string;\n mimeType?: string;\n /** Sanitized service metadata. See `sanitizeResourceServiceMetadata` for rules. */\n serviceName?: string;\n tags?: string[];\n iconUrl?: string;\n /** Present after server extension enrichment; may be absent for pre-enrichment data */\n method?: string;\n routeTemplate?: string;\n x402Version: number;\n discoveryInfo: DiscoveryInfo;\n /** Extension payloads for catalog echo (v2: payload.extensions; v1: synthesized extensions.bazaar) */\n extensions?: Record<string, unknown>;\n}\n\nexport const isQueryExtensionConfig = (\n config: DeclareQueryDiscoveryExtensionConfig | DeclareBodyDiscoveryExtensionConfig,\n): config is DeclareQueryDiscoveryExtensionConfig => {\n return !(\"bodyType\" in config) && !(\"toolName\" in config);\n};\n\nexport const isBodyExtensionConfig = (\n config: DeclareQueryDiscoveryExtensionConfig | DeclareBodyDiscoveryExtensionConfig,\n): config is DeclareBodyDiscoveryExtensionConfig => {\n return \"bodyType\" in config;\n};\n","/**\n * MCP-specific type definitions for the Bazaar Discovery Extension\n */\n\nimport type { DiscoveryInfo } from \"../types\";\n\n/**\n * Discovery info for MCP tools\n */\nexport interface McpDiscoveryInfo {\n input: {\n type: \"mcp\";\n toolName: string;\n description?: string;\n transport?: string;\n inputSchema: Record<string, unknown>;\n example?: Record<string, unknown>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Discovery extension for MCP tools\n */\nexport interface McpDiscoveryExtension {\n info: McpDiscoveryInfo;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"mcp\";\n };\n toolName: {\n type: \"string\";\n };\n description?: {\n type: \"string\";\n };\n transport?: {\n type: \"string\";\n enum?: string[];\n };\n inputSchema: Record<string, unknown>;\n example?: Record<string, unknown>;\n };\n required: (\"type\" | \"toolName\" | \"inputSchema\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\nexport interface DeclareMcpDiscoveryExtensionConfig {\n toolName: string;\n description?: string;\n transport?: string;\n inputSchema: Record<string, unknown>;\n example?: Record<string, unknown>;\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport interface DiscoveredMCPResource {\n resourceUrl: string;\n description?: string;\n mimeType?: string;\n /** Sanitized service metadata. See `sanitizeResourceServiceMetadata` for rules. */\n serviceName?: string;\n tags?: string[];\n iconUrl?: string;\n toolName: string;\n x402Version: number;\n discoveryInfo: DiscoveryInfo;\n /** Extension payloads for catalog echo (v2: payload.extensions; v1: synthesized extensions.bazaar) */\n extensions?: Record<string, unknown>;\n}\n\nexport const isMcpExtensionConfig = (\n config: DeclareMcpDiscoveryExtensionConfig | Record<string, unknown>,\n): config is DeclareMcpDiscoveryExtensionConfig => {\n return \"toolName\" in config;\n};\n","/**\n * Shared type definitions for the Bazaar Discovery Extension\n *\n * Protocol-specific types live in their own directories (http/, mcp/).\n * This file defines the shared unions, constants, and utility types,\n * and re-exports all protocol-specific types for backwards compatibility.\n */\n\nimport type { FacilitatorExtension } from \"@x402/core/types\";\n\n// --- Shared union types ---\n\nimport type { QueryDiscoveryInfo, BodyDiscoveryInfo } from \"./http/types\";\nimport type { McpDiscoveryInfo } from \"./mcp/types\";\nimport type { QueryDiscoveryExtension, BodyDiscoveryExtension } from \"./http/types\";\nimport type { McpDiscoveryExtension } from \"./mcp/types\";\nimport type {\n DeclareQueryDiscoveryExtensionConfig,\n DeclareBodyDiscoveryExtensionConfig,\n} from \"./http/types\";\nimport type { DeclareMcpDiscoveryExtensionConfig } from \"./mcp/types\";\n\n// Re-export protocol-specific types\nexport type {\n QueryDiscoveryInfo,\n BodyDiscoveryInfo,\n QueryDiscoveryExtension,\n BodyDiscoveryExtension,\n DeclareQueryDiscoveryExtensionConfig,\n DeclareBodyDiscoveryExtensionConfig,\n DiscoveredHTTPResource,\n} from \"./http/types\";\n\nexport { isQueryExtensionConfig, isBodyExtensionConfig } from \"./http/types\";\n\nexport type {\n McpDiscoveryInfo,\n McpDiscoveryExtension,\n DeclareMcpDiscoveryExtensionConfig,\n DiscoveredMCPResource,\n} from \"./mcp/types\";\n\nexport { isMcpExtensionConfig } from \"./mcp/types\";\n\n// --- Shared constants ---\n\n/**\n * Extension identifier for the Bazaar discovery extension.\n */\nexport const BAZAAR: FacilitatorExtension = { key: \"bazaar\" };\n\n/**\n * Combined discovery info type\n */\nexport type DiscoveryInfo = QueryDiscoveryInfo | BodyDiscoveryInfo | McpDiscoveryInfo;\n\n/**\n * Combined discovery extension type\n */\nexport type DiscoveryExtension =\n | QueryDiscoveryExtension\n | BodyDiscoveryExtension\n | McpDiscoveryExtension;\n\nexport type DeclareDiscoveryExtensionConfig =\n | DeclareQueryDiscoveryExtensionConfig\n | DeclareBodyDiscoveryExtensionConfig\n | DeclareMcpDiscoveryExtensionConfig;\n\n/**\n * Distributive Omit - properly distributes Omit over union types.\n *\n * Standard `Omit<A | B, K>` collapses to common properties only,\n * losing discriminant properties like `bodyType`.\n *\n * This type uses conditional type distribution to preserve the union:\n * `DistributiveOmit<A | B, K>` = `Omit<A, K> | Omit<B, K>`\n */\nexport type DistributiveOmit<T, K extends keyof T> = T extends T ? Omit<T, K> : never;\n\n/**\n * Config type for declareDiscoveryExtension function.\n * Uses DistributiveOmit to preserve bodyType discriminant in the union for HTTP configs.\n * MCP config has no `method` field so it's included directly.\n */\nexport type DeclareDiscoveryExtensionInput =\n | DistributiveOmit<DeclareQueryDiscoveryExtensionConfig, \"method\">\n | DistributiveOmit<DeclareBodyDiscoveryExtensionConfig, \"method\">\n | DeclareMcpDiscoveryExtensionConfig;\n","/**\n * HTTP resource service functions for creating Bazaar discovery extensions\n */\n\nimport type {\n QueryDiscoveryExtension,\n BodyDiscoveryExtension,\n DeclareQueryDiscoveryExtensionConfig,\n DeclareBodyDiscoveryExtensionConfig,\n} from \"./types\";\n\n/**\n * Create a query discovery extension (GET, HEAD, DELETE)\n *\n * @param root0 - Configuration object for query discovery extension\n * @param root0.method - HTTP method (GET, HEAD, DELETE)\n * @param root0.input - Query parameters\n * @param root0.inputSchema - JSON schema for query parameters\n * @param root0.output - Output specification with example\n * @param root0.pathParams - Concrete path parameter values extracted from the request\n * @param root0.pathParamsSchema - JSON schema for path parameters\n * @returns QueryDiscoveryExtension with info and schema\n */\nexport function createQueryDiscoveryExtension({\n method,\n input = {},\n inputSchema = { properties: {} },\n pathParams,\n pathParamsSchema,\n output,\n}: DeclareQueryDiscoveryExtensionConfig): QueryDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"http\" as const,\n ...(method ? { method } : {}),\n ...(input ? { queryParams: input } : {}),\n ...(pathParams ? { pathParams } : {}),\n },\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"http\",\n },\n method: {\n type: \"string\",\n enum: [\"GET\", \"HEAD\", \"DELETE\"],\n },\n ...(inputSchema\n ? {\n queryParams: {\n type: \"object\" as const,\n ...(typeof inputSchema === \"object\" ? inputSchema : {}),\n },\n }\n : {}),\n ...(pathParamsSchema\n ? {\n pathParams: {\n type: \"object\" as const,\n ...(typeof pathParamsSchema === \"object\" ? pathParamsSchema : {}),\n },\n }\n : {}),\n },\n required: [\"type\", \"method\"] as (\"type\" | \"method\")[],\n // pathParams are not declared here at schema build time --\n // the server extension's enrichDeclaration adds them to both info and schema\n // atomically at request time, keeping data and schema consistent.\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n\n/**\n * Create a body discovery extension (POST, PUT, PATCH)\n *\n * @param root0 - Configuration object for body discovery extension\n * @param root0.method - HTTP method (POST, PUT, PATCH)\n * @param root0.input - Request body specification\n * @param root0.inputSchema - JSON schema for request body\n * @param root0.bodyType - Content type of body (json, form-data, text)\n * @param root0.output - Output specification with example\n * @param root0.pathParams - Concrete path parameter values extracted from the request\n * @param root0.pathParamsSchema - JSON schema for path parameters\n * @returns BodyDiscoveryExtension with info and schema\n */\nexport function createBodyDiscoveryExtension({\n method,\n input = {},\n inputSchema = { properties: {} },\n pathParams,\n pathParamsSchema,\n bodyType,\n output,\n}: DeclareBodyDiscoveryExtensionConfig): BodyDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"http\" as const,\n ...(method ? { method } : {}),\n bodyType,\n body: input,\n ...(pathParams ? { pathParams } : {}),\n },\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"http\",\n },\n method: {\n type: \"string\",\n enum: [\"POST\", \"PUT\", \"PATCH\"],\n },\n bodyType: {\n type: \"string\",\n enum: [\"json\", \"form-data\", \"text\"],\n },\n body: inputSchema,\n ...(pathParamsSchema\n ? {\n pathParams: {\n type: \"object\" as const,\n ...(typeof pathParamsSchema === \"object\" ? pathParamsSchema : {}),\n },\n }\n : {}),\n },\n required: [\"type\", \"method\", \"bodyType\", \"body\"] as (\n | \"type\"\n | \"method\"\n | \"bodyType\"\n | \"body\"\n )[],\n // pathParams are not declared here at schema build time --\n // the server extension's enrichDeclaration adds them to both info and schema\n // atomically at request time, keeping data and schema consistent.\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n","/**\n * MCP resource service functions for creating Bazaar discovery extensions\n */\n\nimport type { McpDiscoveryExtension, DeclareMcpDiscoveryExtensionConfig } from \"./types\";\n\n/**\n * Create an MCP tool discovery extension\n *\n * @param root0 - Configuration object for MCP discovery extension\n * @param root0.toolName - MCP tool name\n * @param root0.description - Tool description\n * @param root0.inputSchema - JSON Schema for tool arguments\n * @param root0.example - Example tool arguments\n * @param root0.output - Output specification with example\n * @param root0.transport - MCP transport type (streamable-http or sse)\n * @returns McpDiscoveryExtension with info and schema\n */\nexport function createMcpDiscoveryExtension({\n toolName,\n description,\n transport,\n inputSchema,\n example,\n output,\n}: DeclareMcpDiscoveryExtensionConfig): McpDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"mcp\",\n toolName,\n ...(description !== undefined ? { description } : {}),\n ...(transport !== undefined ? { transport } : {}),\n inputSchema,\n ...(example !== undefined ? { example } : {}),\n },\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"mcp\",\n },\n toolName: {\n type: \"string\",\n },\n ...(description !== undefined\n ? {\n description: {\n type: \"string\" as const,\n },\n }\n : {}),\n ...(transport !== undefined\n ? {\n transport: {\n type: \"string\" as const,\n ...(transport === \"streamable-http\" || transport === \"sse\"\n ? { enum: [transport] }\n : {}),\n },\n }\n : {}),\n inputSchema: {\n type: \"object\" as const,\n },\n ...(example !== undefined\n ? {\n example: {\n type: \"object\" as const,\n },\n }\n : {}),\n },\n required: [\"type\", \"toolName\", \"inputSchema\"] as (\"type\" | \"toolName\" | \"inputSchema\")[],\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n","/**\n * Resource Service entry point for creating Bazaar discovery extensions\n *\n * This module provides the unified `declareDiscoveryExtension` function that\n * routes to protocol-specific builders in http/ and mcp/.\n */\n\nimport type { DiscoveryExtension, DeclareDiscoveryExtensionInput } from \"./types\";\nimport type {\n DeclareQueryDiscoveryExtensionConfig,\n DeclareBodyDiscoveryExtensionConfig,\n} from \"./http/types\";\nimport type { DeclareMcpDiscoveryExtensionConfig } from \"./mcp/types\";\nimport {\n createQueryDiscoveryExtension,\n createBodyDiscoveryExtension,\n} from \"./http/resourceService\";\nimport { createMcpDiscoveryExtension } from \"./mcp/resourceService\";\n\n/**\n * Create a discovery extension for any HTTP method or MCP tool\n *\n * This function helps servers declare how their endpoint should be called,\n * including the expected input parameters/body and output format.\n *\n * @param config - Configuration object for the discovery extension\n * @returns A discovery extension object with both info and schema\n *\n * @example\n * ```typescript\n * // For a GET endpoint with no input\n * const getExtension = declareDiscoveryExtension({\n * method: \"GET\",\n * output: {\n * example: { message: \"Success\", timestamp: \"2024-01-01T00:00:00Z\" }\n * }\n * });\n *\n * // For a GET endpoint with query params\n * const getWithParams = declareDiscoveryExtension({\n * method: \"GET\",\n * input: { query: \"example\" },\n * inputSchema: {\n * properties: {\n * query: { type: \"string\" }\n * },\n * required: [\"query\"]\n * }\n * });\n *\n * // For a POST endpoint with JSON body\n * const postExtension = declareDiscoveryExtension({\n * method: \"POST\",\n * input: { name: \"John\", age: 30 },\n * inputSchema: {\n * properties: {\n * name: { type: \"string\" },\n * age: { type: \"number\" }\n * },\n * required: [\"name\"]\n * },\n * bodyType: \"json\",\n * output: {\n * example: { success: true, id: \"123\" }\n * }\n * });\n *\n * // For an MCP tool\n * const mcpExtension = declareDiscoveryExtension({\n * toolName: \"financial_analysis\",\n * description: \"Analyze financial data for a given ticker\",\n * inputSchema: {\n * type: \"object\",\n * properties: {\n * ticker: { type: \"string\" },\n * },\n * required: [\"ticker\"],\n * },\n * output: {\n * example: { pe_ratio: 28.5, recommendation: \"hold\" }\n * }\n * });\n * ```\n */\nexport function declareDiscoveryExtension(\n config: DeclareDiscoveryExtensionInput,\n): Record<string, DiscoveryExtension> {\n if (\"toolName\" in config) {\n const extension = createMcpDiscoveryExtension(config as DeclareMcpDiscoveryExtensionConfig);\n return { bazaar: extension as DiscoveryExtension };\n }\n\n const bodyType = (config as DeclareBodyDiscoveryExtensionConfig).bodyType;\n const isBodyMethod = bodyType !== undefined;\n\n const extension = isBodyMethod\n ? createBodyDiscoveryExtension(config as DeclareBodyDiscoveryExtensionConfig)\n : createQueryDiscoveryExtension(config as DeclareQueryDiscoveryExtensionConfig);\n\n return { bazaar: extension as DiscoveryExtension };\n}\n","import type { ResourceServerExtension } from \"@x402/core/types\";\nimport type { HTTPRequestContext } from \"@x402/core/http\";\nimport { BAZAAR } from \"./types\";\n\n// Non-global: safe for test/split (no stateful lastIndex side-effects).\nconst BRACKET_PARAM_REGEX = /\\[([^\\]]+)\\]/;\n// Global variant required for String.replace to substitute ALL occurrences.\n// JS String.replace with a non-global regex replaces only the first match.\n// (String.replaceAll with a non-global regex would work in ES2021+, but the\n// target lib is ES2020 — keep this separate constant to avoid that constraint.)\nconst BRACKET_PARAM_REGEX_ALL = /\\[([^\\]]+)\\]/g;\n\nconst COLON_PARAM_REGEX = /:([a-zA-Z_][a-zA-Z0-9_]*)/;\n\n/**\n * Type guard to check if context is an HTTP request context.\n *\n * @param ctx - The context to check\n * @returns True if context is an HTTPRequestContext\n */\nfunction isHTTPRequestContext(ctx: unknown): ctx is HTTPRequestContext {\n return ctx !== null && typeof ctx === \"object\" && \"method\" in ctx && \"adapter\" in ctx;\n}\n\n/**\n * Converts wildcard segments in a route pattern to named :varN parameters\n * so they can be treated as dynamic routes for discovery catalog normalization.\n *\n * @param pattern - Route pattern that may contain wildcard segments\n * @returns The pattern with wildcard segments replaced by :var1, :var2, etc.\n */\nfunction normalizeWildcardPattern(pattern: string): string {\n if (!pattern.includes(\"*\")) {\n return pattern;\n }\n let counter = 0;\n return pattern\n .split(\"/\")\n .map(seg => {\n if (seg === \"*\") {\n counter++;\n return `:var${counter}`;\n }\n return seg;\n })\n .join(\"/\");\n}\n\n/**\n * Converts a parameterized route pattern into a :param template and extracts concrete\n * param values from the URL path in a single call.\n *\n * Supports both [param] (Next.js) and :param (Express) syntax. The output routeTemplate\n * always uses :param syntax regardless of input format.\n *\n * @param routePattern - Route pattern (e.g. \"/users/[userId]\" or \"/users/:userId\")\n * @param urlPath - Concrete URL path (e.g. \"/users/123\")\n * @returns Object with routeTemplate and pathParams, or null if no params detected\n */\nfunction extractDynamicRouteInfo(\n routePattern: string,\n urlPath: string,\n): { routeTemplate: string; pathParams: Record<string, string> } | null {\n const hasBracket = BRACKET_PARAM_REGEX.test(routePattern);\n const hasColon = COLON_PARAM_REGEX.test(routePattern);\n if (!hasBracket && !hasColon) {\n return null;\n }\n // When both [param] and :param are present, normalize brackets to colons first\n // so all params are extracted uniformly.\n const normalizedPattern = hasBracket\n ? routePattern.replace(BRACKET_PARAM_REGEX_ALL, \":$1\")\n : routePattern;\n const pathParams = extractPathParams(normalizedPattern, urlPath, false);\n return { routeTemplate: normalizedPattern, pathParams };\n}\n\n/**\n * Extracts concrete path parameter values by matching a URL path against a route pattern.\n *\n * @param routePattern - Route pattern with [paramName] or :paramName segments\n * @param urlPath - Concrete URL path (e.g. \"/users/123\")\n * @param isBracket - True if pattern uses [param] syntax, false for :param\n * @returns Record mapping param names to their values\n */\nfunction extractPathParams(\n routePattern: string,\n urlPath: string,\n isBracket: boolean,\n): Record<string, string> {\n const paramNames: string[] = [];\n const splitRegex = isBracket ? BRACKET_PARAM_REGEX : COLON_PARAM_REGEX;\n // Split on param markers so literal segments can be regex-escaped independently.\n // Without escaping, a route like /api/v1.0/[id] would produce a regex where '.' matches\n // any character (e.g. /api/v1X0/123 would incorrectly match).\n const parts = routePattern.split(splitRegex);\n const regexParts: string[] = [];\n parts.forEach((part, i) => {\n if (i % 2 === 0) {\n // Literal segment – escape all regex metacharacters\n regexParts.push(part.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"));\n } else {\n // Param name\n paramNames.push(part);\n regexParts.push(\"([^/]+)\");\n }\n });\n\n const regex = new RegExp(`^${regexParts.join(\"\")}$`);\n const match = urlPath.match(regex);\n\n if (!match) return {};\n\n const result: Record<string, string> = {};\n paramNames.forEach((name, idx) => {\n result[name] = match[idx + 1];\n });\n return result;\n}\n\ninterface ExtensionDeclaration {\n [key: string]: unknown;\n info?: {\n [key: string]: unknown;\n input?: Record<string, unknown>;\n };\n schema?: {\n [key: string]: unknown;\n properties?: {\n [key: string]: unknown;\n input?: {\n [key: string]: unknown;\n properties?: {\n [key: string]: unknown;\n method?: Record<string, unknown>;\n };\n required?: string[];\n };\n };\n };\n}\n\nexport const bazaarResourceServerExtension: ResourceServerExtension = {\n key: BAZAAR.key,\n\n enrichDeclaration: (declaration, transportContext) => {\n if (!isHTTPRequestContext(transportContext)) {\n return declaration;\n }\n\n const extension = declaration as ExtensionDeclaration;\n\n // MCP extensions don't need HTTP method enrichment\n if (extension.info?.input?.type === \"mcp\") {\n return declaration;\n }\n\n const method = transportContext.method;\n\n // At declaration time, the schema uses a broad enum ([\"GET\", \"HEAD\", \"DELETE\"] or [\"POST\", \"PUT\", \"PATCH\"])\n // because the method isn't known until the HTTP context is available.\n // Here we narrow it to the actual method for precise schema validation.\n const existingInputProps = extension.schema?.properties?.input?.properties || {};\n const updatedInputProps = {\n ...existingInputProps,\n method: {\n type: \"string\",\n enum: [method],\n },\n };\n\n const enrichedResult = {\n ...extension,\n info: {\n ...(extension.info || {}),\n input: {\n ...(extension.info?.input || {}),\n method,\n },\n },\n schema: {\n ...(extension.schema || {}),\n properties: {\n ...(extension.schema?.properties || {}),\n input: {\n ...(extension.schema?.properties?.input || {}),\n properties: updatedInputProps,\n required: [\n ...(extension.schema?.properties?.input?.required || []),\n ...(!(extension.schema?.properties?.input?.required || []).includes(\"method\")\n ? [\"method\"]\n : []),\n ],\n },\n },\n },\n };\n\n // Dynamic routes: translate [param]/:param → :param for the routeTemplate catalog key;\n // pathParams carries runtime values (distinct from pathParamsSchema in the declaration).\n // Wildcard * segments are auto-converted to :var1, :var2, etc. for catalog normalization.\n const rawRoutePattern = (transportContext as HTTPRequestContext).routePattern;\n const routePattern = rawRoutePattern ? normalizeWildcardPattern(rawRoutePattern) : undefined;\n const dynamicRoute = routePattern\n ? extractDynamicRouteInfo(routePattern, transportContext.adapter.getPath())\n : null;\n if (dynamicRoute) {\n const inputSchemaProps = enrichedResult.schema?.properties?.input?.properties || {};\n const hasPathParamsInSchema = \"pathParams\" in inputSchemaProps;\n return {\n ...enrichedResult,\n routeTemplate: dynamicRoute.routeTemplate,\n info: {\n ...enrichedResult.info,\n input: { ...enrichedResult.info.input, pathParams: dynamicRoute.pathParams },\n },\n ...(!hasPathParamsInSchema\n ? {\n schema: {\n ...enrichedResult.schema,\n properties: {\n ...enrichedResult.schema?.properties,\n input: {\n ...enrichedResult.schema?.properties?.input,\n properties: {\n ...inputSchemaProps,\n pathParams: { type: \"object\" },\n },\n },\n },\n },\n }\n : {}),\n };\n }\n\n return enrichedResult;\n },\n};\n","/**\n * Facilitator functions for validating and extracting Bazaar discovery extensions\n *\n * These functions help facilitators validate extension data against schemas\n * and extract the discovery information for cataloging in the Bazaar.\n *\n * Supports both v2 (extensions in PaymentRequired) and v1 (outputSchema in PaymentRequirements).\n */\n\nimport { domainToASCII } from \"node:url\";\nimport Ajv from \"ajv/dist/2020.js\";\nimport type {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequirementsV1,\n ResourceInfo,\n} from \"@x402/core/types\";\nimport type { DiscoveryExtension, DiscoveryInfo } from \"./types\";\nimport type { McpDiscoveryInfo } from \"./mcp/types\";\nimport type { DiscoveredHTTPResource } from \"./http/types\";\nimport type { DiscoveredMCPResource } from \"./mcp/types\";\nimport { BAZAAR } from \"./types\";\nimport { buildV1CatalogExtensions, extractDiscoveryInfoV1 } from \"./v1/facilitator\";\n\n/**\n * Valid routeTemplate pattern: must start with \"/\", contain only safe URL path characters\n * and :param identifiers, and not include traversal sequences or scheme markers.\n *\n * Allowed: /users/:userId, /weather/:country/:city, /api/v1/items\n */\nconst ROUTE_TEMPLATE_REGEX = /^\\/[a-zA-Z0-9_/:.\\-~%]+$/;\n\n/**\n * Checks whether a routeTemplate value is structurally valid.\n *\n * Expected format: \"/:param\" segments using colon-prefixed identifiers\n * (e.g. \"/users/:userId\", \"/weather/:country/:city\").\n *\n * The facilitator is a trust boundary: clients control the payment payload and\n * can modify routeTemplate before submission. A malicious value could cause the\n * facilitator to catalog the payment under an arbitrary URL (catalog poisoning).\n * This function enforces minimal structural requirements:\n * - Must be a non-empty string starting with \"/\"\n * - Must match the safe URL path character set (alphanumeric, _, :, /, ., -, ~, %)\n * - Must not contain \"..\" (path traversal)\n * - Must not contain \"://\" (URL injection)\n *\n * @param value - The raw routeTemplate string from the client payload\n * @returns true if the value is a valid routeTemplate, false otherwise\n *\n * @internal Exported for facilitator use.\n */\nexport function isValidRouteTemplate(value: string | undefined): value is string {\n if (!value) return false;\n if (!ROUTE_TEMPLATE_REGEX.test(value)) return false;\n // Decode percent-encoding before traversal checks so that %2e%2e is caught.\n let decoded: string;\n try {\n decoded = decodeURIComponent(value);\n } catch {\n return false;\n }\n if (decoded.includes(\"..\")) return false;\n if (decoded.includes(\"://\")) return false;\n return true;\n}\n\n/**\n * Validates a routeTemplate and returns it if valid, undefined otherwise.\n *\n * @param value - The raw routeTemplate string to validate\n * @returns The validated value, or undefined if invalid\n * @deprecated Use `isValidRouteTemplate` instead.\n */\nexport function validateRouteTemplate(value: string | undefined): string | undefined {\n return isValidRouteTemplate(value) ? value : undefined;\n}\n\n/**\n * Maximum lengths for resource service metadata fields. Spec: see\n * `specs/extensions/bazaar.md` \"Service Metadata on `resource`\".\n */\nconst MAX_SERVICE_NAME_LEN = 32;\nconst MAX_TAG_LEN = 32;\nconst MAX_TAGS = 5;\nconst MAX_ICON_URL_LEN = 2048;\n// Matches ASCII control characters (C0 + DEL).\nconst CONTROL_CHAR_REGEX = /[\\x00-\\x1f\\x7f]/;\n// Printable ASCII range (U+0020–U+007E). `serviceName` and `tags` are\n// constrained to this range so that String.length (UTF-16 code units),\n// len() in Python (code points), and len() in Go (UTF-8 bytes) all agree\n// on the character count. Same convention as paymentidentifier.id.\nconst PRINTABLE_ASCII_REGEX = /^[\\x20-\\x7e]+$/;\n// Unicode control characters (category Cc). Defense-in-depth: the printable\n// ASCII regex already rejects every control character, but this explicit\n// check documents intent and would survive any future relaxation of the\n// ASCII restriction. Mirrors `unicode.IsControl` (Go).\nconst UNICODE_CONTROL_REGEX = /\\p{Cc}/u;\n\n// Loopback hostnames that must be rejected for SSRF defense. Includes the\n// common /etc/hosts aliases on Linux/macOS (`localhost.localdomain`,\n// `ip6-localhost`, `ip6-loopback`) — without these, a hostile provider could\n// route the facilitator's image fetcher to its own loopback interface.\nconst LOOPBACK_HOSTNAMES = new Set([\n \"localhost\",\n \"localhost.localdomain\",\n \"ip6-localhost\",\n \"ip6-loopback\",\n]);\n// Matches a bare IPv4 dotted-quad. IPv6 literals are detected via hostname brackets.\nconst IPV4_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\n// SSRF defense: any all-digit hostname is suspect because no legitimate DNS name\n// is purely numeric. Catches decimal-encoded IPs (`http://2130706433/` → 127.0.0.1)\n// and short-form IPs (`http://0/` → 0.0.0.0, treated as loopback on Linux).\nconst ALL_DIGITS_REGEX = /^\\d+$/;\n// SSRF defense: hex-encoded IPs (`http://0x7f000001/` → 127.0.0.1) — same family\n// of bypasses as the decimal form above.\nconst HEX_LITERAL_REGEX = /^0x[0-9a-f]+$/i;\n\n/**\n * Checks whether a serviceName value is structurally valid for the bazaar\n * `resource.serviceName` field. Non-empty string of printable ASCII\n * (U+0020–U+007E), length ≤ 32.\n *\n * The ASCII restriction matches the `paymentidentifier.id` convention and\n * keeps `len()` semantics identical across TS / Python / Go.\n *\n * Mirrors `_is_valid_service_name` (Python) and `isValidServiceName` (Go).\n * All three implementations must stay in sync.\n *\n * @param value - The raw serviceName string from the resource object\n * @returns true if the value is a valid serviceName, false otherwise\n *\n * @internal Exported for facilitator use.\n */\nexport function isValidServiceName(value: string | undefined): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length === 0 || value.length > MAX_SERVICE_NAME_LEN) return false;\n if (UNICODE_CONTROL_REGEX.test(value)) return false;\n if (!PRINTABLE_ASCII_REGEX.test(value)) return false;\n return true;\n}\n\n/**\n * Sanitizes a tags array for the bazaar `resource.tags` field. Drops entries\n * that are not non-empty printable-ASCII strings of at most 32 characters,\n * then truncates to the first 5 valid entries. Returns undefined when no\n * entries survive (so the field can be omitted from the catalog).\n *\n * The ASCII restriction matches the `paymentidentifier.id` convention and\n * keeps `len()` semantics identical across TS / Python / Go.\n *\n * Mirrors `_sanitize_tags` (Python) and `sanitizeTags` (Go).\n * All three implementations must stay in sync.\n *\n * @param value - The raw tags value from the resource object (typed as unknown\n * because callers pass it directly from a parsed JSON payload)\n * @returns The sanitized tags array, or undefined if no entries survive\n *\n * @internal Exported for facilitator use.\n */\nexport function sanitizeTags(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const out: string[] = [];\n // Case-insensitive dedup: keeps the first occurrence's casing.\n // Prevents catalog noise like [\"Weather\", \"weather\", \"WEATHER\"].\n const seen = new Set<string>();\n for (const entry of value) {\n if (typeof entry !== \"string\") continue;\n if (entry.length === 0 || entry.length > MAX_TAG_LEN) continue;\n if (UNICODE_CONTROL_REGEX.test(entry)) continue;\n if (!PRINTABLE_ASCII_REGEX.test(entry)) continue;\n const key = entry.toLowerCase();\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(entry);\n if (out.length === MAX_TAGS) break;\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Checks whether an iconUrl value is structurally safe for the bazaar\n * `resource.iconUrl` field.\n *\n * Rules (see `specs/extensions/bazaar.md` \"Service Metadata on `resource`\"):\n * - String of length ≤ 2048\n * - No ASCII control characters\n * - Parses as an absolute http:// or https:// URL\n * - No userinfo (user@host)\n * - Host is IDN-normalized (UTS #46) before checks, so confusable\n * full-width / Unicode forms (e.g. `localhost`) collapse to their\n * ASCII canonical and get caught by the loopback check\n * - Host is not an IP literal (v4 or v6), not in the loopback set\n * (`localhost`, `localhost.localdomain`, `ip6-localhost`, `ip6-loopback`)\n * - Host is not a decimal IP encoding (e.g. `2130706433` → 127.0.0.1) or\n * hex literal (e.g. `0x7f000001`) — common SSRF bypass forms\n *\n * Percent-decoding is applied to the hostname before IDN normalization, and\n * IDN normalization runs before the IP / loopback checks (parallel to the\n * routeTemplate decoder).\n *\n * Mirrors `_is_valid_icon_url` (Python) and `isValidIconUrl` (Go).\n * All three implementations must stay in sync.\n *\n * @param value - The raw iconUrl string from the resource object\n * @returns true if the value is a structurally safe iconUrl, false otherwise\n *\n * @internal Exported for facilitator use.\n */\nexport function isValidIconUrl(value: string | undefined): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length === 0 || value.length > MAX_ICON_URL_LEN) return false;\n if (CONTROL_CHAR_REGEX.test(value)) return false;\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return false;\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n if (parsed.username !== \"\" || parsed.password !== \"\") return false;\n // URL.hostname strips IPv6 brackets, so detect IPv6 from the bracketed host instead.\n if (parsed.host.startsWith(\"[\")) return false;\n let hostname: string;\n try {\n hostname = decodeURIComponent(parsed.hostname);\n } catch {\n return false;\n }\n // IDN/full-width normalization: e.g. \"localhost\" (full-width Latin)\n // → \"localhost\". Without this the loopback alias check would miss\n // confusable Unicode hostnames. domainToASCII applies the same WHATWG /\n // UTS #46 mapping that idna.Lookup.ToASCII (Go) and idna.encode (Python)\n // use; returns \"\" on failure.\n const asciiHost = domainToASCII(hostname);\n if (asciiHost === \"\") return false;\n hostname = asciiHost.toLowerCase();\n if (hostname === \"\") return false;\n if (LOOPBACK_HOSTNAMES.has(hostname)) return false;\n if (IPV4_REGEX.test(hostname)) return false;\n if (ALL_DIGITS_REGEX.test(hostname)) return false;\n if (HEX_LITERAL_REGEX.test(hostname)) return false;\n return true;\n}\n\n/**\n * Sanitized service metadata extracted from a `resource` object.\n */\nexport interface SanitizedResourceServiceMetadata {\n serviceName?: string;\n tags?: string[];\n iconUrl?: string;\n}\n\n/**\n * Applies the bazaar service-metadata validation rules to a `resource` object\n * and returns only the fields that survive. Missing or invalid fields are\n * dropped silently (soft-drop semantics — see spec).\n *\n * @param resource - The raw `resource` object from a PaymentRequired or\n * PaymentPayload, or undefined.\n * @returns An object containing only the valid serviceName / tags / iconUrl.\n *\n * @internal Exported for facilitator use.\n */\nexport function sanitizeResourceServiceMetadata(\n resource: ResourceInfo | undefined | null,\n): SanitizedResourceServiceMetadata {\n if (!resource) return {};\n const out: SanitizedResourceServiceMetadata = {};\n if (isValidServiceName(resource.serviceName)) {\n out.serviceName = resource.serviceName;\n }\n const tags = sanitizeTags(resource.tags);\n if (tags) {\n out.tags = tags;\n }\n if (isValidIconUrl(resource.iconUrl)) {\n out.iconUrl = resource.iconUrl;\n }\n return out;\n}\n\n/**\n * Validation result for discovery extensions\n */\nexport interface ValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/**\n * Validates a discovery extension's info against its schema\n *\n * @param extension - The discovery extension containing info and schema\n * @returns Validation result indicating if the info matches the schema\n *\n * @example\n * ```typescript\n * const extension = declareDiscoveryExtension(...);\n * const result = validateDiscoveryExtension(extension);\n *\n * if (result.valid) {\n * console.log(\"Extension is valid\");\n * } else {\n * console.error(\"Validation errors:\", result.errors);\n * }\n * ```\n */\nexport function validateDiscoveryExtension(extension: DiscoveryExtension): ValidationResult {\n try {\n const ajv = new Ajv({ strict: false, allErrors: true });\n const validate = ajv.compile(extension.schema);\n\n // The schema describes the structure of info directly\n // Schema has properties: { input: {...}, output: {...} }\n // So we validate extension.info which has { input: {...}, output: {...} }\n const valid = validate(extension.info);\n\n if (valid) {\n return { valid: true };\n }\n\n const errors = validate.errors?.map(err => {\n const path = err.instancePath || \"(root)\";\n return `${path}: ${err.message}`;\n }) || [\"Unknown validation error\"];\n\n return { valid: false, errors };\n } catch (error) {\n return {\n valid: false,\n errors: [\n `Schema validation failed: ${error instanceof Error ? error.message : String(error)}`,\n ],\n };\n }\n}\n\nconst VALID_QUERY_METHODS = new Set([\"GET\", \"HEAD\", \"DELETE\"]);\nconst VALID_BODY_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\"]);\nconst VALID_METHODS = new Set([...VALID_QUERY_METHODS, ...VALID_BODY_METHODS]);\nconst VALID_BODY_TYPES = new Set([\"json\", \"form-data\", \"text\"]);\nconst VALID_MCP_TRANSPORTS = new Set([\"streamable-http\", \"sse\"]);\n\n/**\n * Validates a discovery extension against the Bazaar protocol specification.\n *\n * Unlike `validateDiscoveryExtension` which checks internal consistency (info vs schema),\n * this function enforces protocol-level invariants:\n * - `info.input.type` must be \"http\" or \"mcp\"\n * - HTTP: if `method` is present it must be GET/POST/PUT/PATCH/DELETE/HEAD\n * - HTTP body methods: `bodyType` must be \"json\" | \"form-data\" | \"text\"\n * - MCP: `toolName` (string) and `inputSchema` (object) are required\n * - MCP: if `transport` is present it must be \"streamable-http\" | \"sse\"\n *\n * Designed to be safe for pre-enrichment HTTP extensions where `method` may be absent.\n *\n * @param extension - The discovery extension to validate\n * @returns Validation result with spec-level errors\n */\nexport function validateDiscoveryExtensionSpec(\n extension: Record<string, unknown>,\n): ValidationResult {\n const errors: string[] = [];\n\n const info = extension.info;\n if (!info || typeof info !== \"object\") {\n return { valid: false, errors: [\"Missing or invalid 'info' field\"] };\n }\n\n const input = (info as Record<string, unknown>).input;\n if (!input || typeof input !== \"object\") {\n return { valid: false, errors: [\"Missing or invalid 'info.input' field\"] };\n }\n\n const inputObj = input as Record<string, unknown>;\n const inputType = inputObj.type;\n\n if (inputType !== \"http\" && inputType !== \"mcp\") {\n errors.push(`info.input.type must be \"http\" or \"mcp\", got \"${String(inputType)}\"`);\n return { valid: false, errors };\n }\n\n if (inputType === \"http\") {\n const method = inputObj.method;\n if (method !== undefined && !VALID_METHODS.has(method as string)) {\n errors.push(\n `info.input.method must be one of ${[...VALID_METHODS].join(\", \")}, got \"${String(method)}\"`,\n );\n }\n\n const bodyType = inputObj.bodyType;\n if (bodyType !== undefined) {\n if (!VALID_BODY_TYPES.has(bodyType as string)) {\n errors.push(\n `info.input.bodyType must be one of ${[...VALID_BODY_TYPES].join(\", \")}, got \"${String(bodyType)}\"`,\n );\n }\n if (method !== undefined && !VALID_BODY_METHODS.has(method as string)) {\n errors.push(\n `info.input.bodyType is set but method \"${String(method)}\" is not a body method (POST, PUT, PATCH)`,\n );\n }\n }\n }\n\n if (inputType === \"mcp\") {\n if (typeof inputObj.toolName !== \"string\" || inputObj.toolName.length === 0) {\n errors.push(\n \"info.input.toolName is required and must be a non-empty string for MCP extensions\",\n );\n }\n if (!inputObj.inputSchema || typeof inputObj.inputSchema !== \"object\") {\n errors.push(\"info.input.inputSchema is required and must be an object for MCP extensions\");\n }\n const transport = inputObj.transport;\n if (transport !== undefined && !VALID_MCP_TRANSPORTS.has(transport as string)) {\n errors.push(\n `info.input.transport must be one of ${[...VALID_MCP_TRANSPORTS].join(\", \")}, got \"${String(transport)}\"`,\n );\n }\n }\n\n return errors.length === 0 ? { valid: true } : { valid: false, errors };\n}\n\n/**\n * Extracts the discovery info from payment payload and requirements\n *\n * This function handles both v2 (extensions) and v1 (outputSchema) formats.\n *\n * For v2: Discovery info is in PaymentPayload.extensions (client copied it from PaymentRequired)\n * For v1: Discovery info is in PaymentRequirements.outputSchema\n *\n * V1 data is automatically transformed to v2 DiscoveryInfo format, making smart\n * assumptions about field names (queryParams/query/params for GET, bodyFields/body/data for POST, etc.)\n *\n * @param paymentPayload - The payment payload containing extensions (v2) and version info\n * @param paymentRequirements - The payment requirements (contains outputSchema for v1)\n * @param validate - Whether to validate v2 extensions before extracting (default: true)\n * @returns The discovery info in v2 format if present, or null if not discoverable\n *\n * @example\n * ```typescript\n * // V2 - extensions are in PaymentPayload\n * const info = extractDiscoveryInfo(paymentPayload, paymentRequirements);\n *\n * // V1 - discovery info is in PaymentRequirements.outputSchema\n * const info = extractDiscoveryInfo(paymentPayloadV1, paymentRequirementsV1);\n *\n * if (info) {\n * // Both v1 and v2 return the same DiscoveryInfo structure\n * console.log(\"Method:\", info.input.method);\n * }\n * ```\n */\nexport type { DiscoveredHTTPResource } from \"./http/types\";\nexport type { DiscoveredMCPResource } from \"./mcp/types\";\n\nexport type DiscoveredResource = DiscoveredHTTPResource | DiscoveredMCPResource;\n\n/**\n * Extracts discovery information from payment payload and requirements.\n * Combines resource URL, HTTP method, version, and discovery info into a single object.\n *\n * @param paymentPayload - The payment payload containing extensions and resource info\n * @param paymentRequirements - The payment requirements to validate against\n * @param validate - Whether to validate the discovery info against the schema (default: true)\n * @returns Discovered resource info with URL, method, version, discovery data, and catalog\n * extensions echo (v2: `paymentPayload.extensions`; v1: synthesized `extensions.bazaar`\n * from requirements outputSchema), or null if not found\n */\nexport function extractDiscoveryInfo(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements | PaymentRequirementsV1,\n validate: boolean = true,\n): DiscoveredResource | null {\n let discoveryInfo: DiscoveryInfo | null = null;\n let resourceUrl: string;\n\n let routeTemplate: string | undefined;\n\n if (paymentPayload.x402Version === 2) {\n resourceUrl = paymentPayload.resource?.url ?? \"\";\n\n if (paymentPayload.extensions) {\n const bazaarExtension = paymentPayload.extensions[BAZAAR.key];\n\n if (bazaarExtension && typeof bazaarExtension === \"object\") {\n try {\n // routeTemplate uses :param syntax (e.g. \"/users/:userId\", \"/weather/:country/:city\").\n // Must start with \"/\", must not contain \"..\" or \"://\".\n // Validate before use: the client controls this field in the payment payload.\n const rawExt = bazaarExtension as Record<string, unknown>;\n const rawTemplate =\n typeof rawExt.routeTemplate === \"string\" ? rawExt.routeTemplate : undefined;\n if (isValidRouteTemplate(rawTemplate)) {\n routeTemplate = rawTemplate;\n }\n const extension = bazaarExtension as DiscoveryExtension;\n\n if (validate) {\n const result = validateDiscoveryExtension(extension);\n if (!result.valid) {\n console.warn(\n `V2 discovery extension validation failed: ${result.errors?.join(\", \")}`,\n );\n } else {\n discoveryInfo = extension.info;\n }\n } else {\n discoveryInfo = extension.info;\n }\n } catch (error) {\n console.warn(`V2 discovery extension extraction failed: ${error}`);\n }\n }\n }\n } else if (paymentPayload.x402Version === 1) {\n const requirementsV1 = paymentRequirements as PaymentRequirementsV1;\n resourceUrl = requirementsV1.resource;\n discoveryInfo = extractDiscoveryInfoV1(requirementsV1);\n } else {\n return null;\n }\n\n if (!discoveryInfo) {\n return null;\n }\n\n // Strip query params (?) and hash sections (#) for discovery cataloging\n const url = new URL(resourceUrl);\n // If a routeTemplate is present (dynamic route), use it as the canonical path\n const canonicalUrl = routeTemplate\n ? `${url.origin}${routeTemplate}`\n : `${url.origin}${url.pathname}`;\n\n // Extract description and mimeType from resource info (v2) or requirements (v1)\n let description: string | undefined;\n let mimeType: string | undefined;\n let serviceMetadata: SanitizedResourceServiceMetadata = {};\n\n if (paymentPayload.x402Version === 2) {\n description = paymentPayload.resource?.description;\n mimeType = paymentPayload.resource?.mimeType;\n // Service metadata only exists in v2; v1 had no equivalent.\n serviceMetadata = sanitizeResourceServiceMetadata(paymentPayload.resource);\n } else if (paymentPayload.x402Version === 1) {\n const requirementsV1 = paymentRequirements as PaymentRequirementsV1;\n description = requirementsV1.description;\n mimeType = requirementsV1.mimeType;\n }\n\n let extensions: Record<string, unknown> | undefined;\n if (paymentPayload.x402Version === 2) {\n extensions = paymentPayload.extensions;\n } else if (paymentPayload.x402Version === 1) {\n extensions = buildV1CatalogExtensions(paymentPayload.extensions, discoveryInfo);\n }\n\n const base = {\n resourceUrl: canonicalUrl,\n description,\n mimeType,\n ...serviceMetadata,\n x402Version: paymentPayload.x402Version,\n discoveryInfo,\n extensions,\n };\n\n if (discoveryInfo.input.type === \"mcp\") {\n // MCP routes are not parameterized; routeTemplate is not applicable.\n return { ...base, toolName: (discoveryInfo as McpDiscoveryInfo).input.toolName };\n }\n\n return { ...base, routeTemplate, method: discoveryInfo.input.method };\n}\n\n/**\n * Extracts discovery info from a v2 extension directly\n *\n * This is a lower-level function for when you already have the extension object.\n * For general use, prefer the main extractDiscoveryInfo function.\n *\n * @param extension - The discovery extension to extract info from\n * @param validate - Whether to validate before extracting (default: true)\n * @returns The discovery info if valid\n * @throws Error if validation fails and validate is true\n */\nexport function extractDiscoveryInfoFromExtension(\n extension: DiscoveryExtension,\n validate: boolean = true,\n): DiscoveryInfo {\n if (validate) {\n const result = validateDiscoveryExtension(extension);\n if (!result.valid) {\n throw new Error(\n `Invalid discovery extension: ${result.errors?.join(\", \") || \"Unknown error\"}`,\n );\n }\n }\n\n return extension.info;\n}\n\n/**\n * Validates and extracts discovery info in one step\n *\n * This is a convenience function that combines validation and extraction,\n * returning both the validation result and the info if valid.\n *\n * @param extension - The discovery extension to validate and extract\n * @returns Object containing validation result and info (if valid)\n *\n * @example\n * ```typescript\n * const extension = declareDiscoveryExtension(...);\n * const { valid, info, errors } = validateAndExtract(extension);\n *\n * if (valid && info) {\n * // Store info in Bazaar catalog\n * } else {\n * console.error(\"Validation errors:\", errors);\n * }\n * ```\n */\nexport function validateAndExtract(extension: DiscoveryExtension): {\n valid: boolean;\n info?: DiscoveryInfo;\n errors?: string[];\n} {\n const result = validateDiscoveryExtension(extension);\n\n if (result.valid) {\n return {\n valid: true,\n info: extension.info,\n };\n }\n\n return {\n valid: false,\n errors: result.errors,\n };\n}\n","/**\n * V1 Facilitator functions for extracting Bazaar discovery information\n *\n * In v1, discovery information is stored in the `outputSchema` field\n * of PaymentRequirements, which has a different structure than v2.\n *\n * This module transforms v1 data into v2 DiscoveryInfo format.\n */\n\nimport type { PaymentRequirementsV1 } from \"@x402/core/types\";\nimport type { BodyMethods, QueryParamMethods } from \"@x402/core/http\";\nimport type {\n DiscoveryExtension,\n DiscoveryInfo,\n QueryDiscoveryInfo,\n BodyDiscoveryInfo,\n} from \"../types\";\nimport { BAZAAR } from \"../types\";\n\n/**\n * Type guard to check if an object has the v1 outputSchema structure\n *\n * @param obj - The object to check\n * @returns True if object has v1 outputSchema structure\n */\nfunction hasV1OutputSchema(\n obj: unknown,\n): obj is { input: Record<string, unknown>; output?: Record<string, unknown> } {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"input\" in obj &&\n obj.input !== null &&\n typeof obj.input === \"object\" &&\n \"type\" in obj.input &&\n obj.input.type === \"http\" &&\n \"method\" in obj.input\n );\n}\n\n/**\n * Checks if a method is a query parameter method\n *\n * @param method - HTTP method string to check\n * @returns True if method is GET, HEAD, or DELETE\n */\nfunction isQueryMethod(method: string): method is QueryParamMethods {\n const upperMethod = method.toUpperCase();\n return upperMethod === \"GET\" || upperMethod === \"HEAD\" || upperMethod === \"DELETE\";\n}\n\n/**\n * Checks if a method is a body method\n *\n * @param method - HTTP method string to check\n * @returns True if method is POST, PUT, or PATCH\n */\nfunction isBodyMethod(method: string): method is BodyMethods {\n const upperMethod = method.toUpperCase();\n return upperMethod === \"POST\" || upperMethod === \"PUT\" || upperMethod === \"PATCH\";\n}\n\n/**\n * Extracts query parameters from v1 input, making smart assumptions\n * about common field names used in v1\n *\n * @param v1Input - V1 input object from payment requirements\n * @returns Extracted query parameters or undefined\n */\nfunction extractQueryParams(v1Input: Record<string, unknown>): Record<string, unknown> | undefined {\n // Check various common field names used in v1 (both camelCase and snake_case)\n if (v1Input.queryParams && typeof v1Input.queryParams === \"object\") {\n return v1Input.queryParams as Record<string, unknown>;\n }\n if (v1Input.query_params && typeof v1Input.query_params === \"object\") {\n return v1Input.query_params as Record<string, unknown>;\n }\n if (v1Input.query && typeof v1Input.query === \"object\") {\n return v1Input.query as Record<string, unknown>;\n }\n if (v1Input.params && typeof v1Input.params === \"object\") {\n return v1Input.params as Record<string, unknown>;\n }\n return undefined;\n}\n\n/**\n * Extracts body information from v1 input, making smart assumptions\n *\n * @param v1Input - V1 input object from payment requirements\n * @returns Object containing body content and bodyType\n */\nfunction extractBodyInfo(v1Input: Record<string, unknown>): {\n body: Record<string, unknown>;\n bodyType: \"json\" | \"form-data\" | \"text\";\n} {\n // Determine body type (check both camelCase and snake_case)\n let bodyType: \"json\" | \"form-data\" | \"text\" = \"json\";\n const bodyTypeField = v1Input.bodyType || v1Input.body_type;\n\n if (bodyTypeField && typeof bodyTypeField === \"string\") {\n const type = bodyTypeField.toLowerCase();\n if (type.includes(\"form\") || type.includes(\"multipart\")) {\n bodyType = \"form-data\";\n } else if (type.includes(\"text\") || type.includes(\"plain\")) {\n bodyType = \"text\";\n } else {\n bodyType = \"json\";\n }\n }\n\n // Extract body content from various possible fields\n // Priority order based on observed patterns in real data\n let body: Record<string, unknown> = {};\n\n if (v1Input.bodyFields && typeof v1Input.bodyFields === \"object\") {\n body = v1Input.bodyFields as Record<string, unknown>;\n } else if (\n v1Input.body_fields &&\n v1Input.body_fields !== null &&\n typeof v1Input.body_fields === \"object\"\n ) {\n body = v1Input.body_fields as Record<string, unknown>;\n } else if (v1Input.bodyParams && typeof v1Input.bodyParams === \"object\") {\n body = v1Input.bodyParams as Record<string, unknown>;\n } else if (v1Input.body && typeof v1Input.body === \"object\") {\n body = v1Input.body as Record<string, unknown>;\n } else if (v1Input.data && typeof v1Input.data === \"object\") {\n body = v1Input.data as Record<string, unknown>;\n } else if (v1Input.properties && typeof v1Input.properties === \"object\") {\n // Some endpoints have properties directly at the input level\n body = v1Input.properties as Record<string, unknown>;\n }\n\n return { body, bodyType };\n}\n\n/**\n * Extracts discovery info from v1 PaymentRequirements and transforms to v2 format\n *\n * In v1, the discovery information is stored in the `outputSchema` field,\n * which contains both input (endpoint shape) and output (response schema) information.\n *\n * This function makes smart assumptions to normalize v1 data into v2 DiscoveryInfo format:\n * - For GET/HEAD/DELETE: Looks for queryParams, query, or params fields\n * - For POST/PUT/PATCH: Looks for bodyFields, body, or data fields and normalizes bodyType\n * - Extracts optional headers if present\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns Discovery info in v2 format if present and valid, or null if not discoverable\n *\n * @example\n * ```typescript\n * const requirements: PaymentRequirementsV1 = {\n * scheme: \"exact\",\n * network: \"eip155:8453\",\n * maxAmountRequired: \"100000\",\n * resource: \"https://api.example.com/data\",\n * description: \"Get data\",\n * mimeType: \"application/json\",\n * outputSchema: {\n * input: {\n * type: \"http\",\n * method: \"GET\",\n * discoverable: true,\n * queryParams: { query: \"string\" }\n * },\n * output: { type: \"object\" }\n * },\n * payTo: \"0x...\",\n * maxTimeoutSeconds: 300,\n * asset: \"0x...\",\n * extra: {}\n * };\n *\n * const info = extractDiscoveryInfoV1(requirements);\n * if (info) {\n * console.log(\"Endpoint method:\", info.input.method);\n * }\n * ```\n */\nexport function extractDiscoveryInfoV1(\n paymentRequirements: PaymentRequirementsV1,\n): DiscoveryInfo | null {\n const { outputSchema } = paymentRequirements;\n\n // Check if outputSchema exists and has the expected structure\n if (!outputSchema || !hasV1OutputSchema(outputSchema)) {\n return null;\n }\n\n const v1Input = outputSchema.input;\n\n // Check if the endpoint is marked as discoverable\n // Default to true if not specified (for backwards compatibility)\n const isDiscoverable = v1Input.discoverable ?? true;\n\n if (!isDiscoverable) {\n return null;\n }\n\n const method = typeof v1Input.method === \"string\" ? v1Input.method.toUpperCase() : \"\";\n\n // Extract headers if present (check both camelCase and snake_case)\n const headersRaw = v1Input.headerFields || v1Input.header_fields || v1Input.headers;\n const headers =\n headersRaw && typeof headersRaw === \"object\"\n ? (headersRaw as Record<string, string>)\n : undefined;\n\n // Extract output example/schema if present\n const output = outputSchema.output\n ? {\n type: \"json\" as const,\n example: outputSchema.output,\n }\n : undefined;\n\n // Transform based on method type\n if (isQueryMethod(method)) {\n // Query parameter method (GET, HEAD, DELETE)\n const queryParams = extractQueryParams(v1Input);\n\n const discoveryInfo: QueryDiscoveryInfo = {\n input: {\n type: \"http\",\n method: method as QueryParamMethods,\n ...(queryParams ? { queryParams } : {}),\n ...(headers ? { headers } : {}),\n },\n ...(output ? { output } : {}),\n };\n\n return discoveryInfo;\n } else if (isBodyMethod(method)) {\n // Body method (POST, PUT, PATCH)\n const { body, bodyType } = extractBodyInfo(v1Input);\n const queryParams = extractQueryParams(v1Input); // Some POST requests also have query params\n\n const discoveryInfo: BodyDiscoveryInfo = {\n input: {\n type: \"http\",\n method: method as BodyMethods,\n bodyType,\n body,\n ...(queryParams ? { queryParams } : {}),\n ...(headers ? { headers } : {}),\n },\n ...(output ? { output } : {}),\n };\n\n return discoveryInfo;\n }\n\n // Unsupported method, return null\n return null;\n}\n\n/**\n * Checks if v1 PaymentRequirements contains discoverable information\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns True if the requirements contain valid discovery info\n *\n * @example\n * ```typescript\n * if (isDiscoverableV1(requirements)) {\n * const info = extractDiscoveryInfoV1(requirements);\n * // Catalog info in Bazaar\n * }\n * ```\n */\nexport function isDiscoverableV1(paymentRequirements: PaymentRequirementsV1): boolean {\n return extractDiscoveryInfoV1(paymentRequirements) !== null;\n}\n\n/**\n * Extracts resource metadata from v1 PaymentRequirements\n *\n * In v1, resource information is embedded directly in the payment requirements\n * rather than in a separate resource object.\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns Resource metadata\n *\n * @example\n * ```typescript\n * const metadata = extractResourceMetadataV1(requirements);\n * console.log(\"Resource URL:\", metadata.url);\n * console.log(\"Description:\", metadata.description);\n * ```\n */\nexport function extractResourceMetadataV1(paymentRequirements: PaymentRequirementsV1): {\n url: string;\n description: string;\n mimeType: string;\n} {\n return {\n url: paymentRequirements.resource,\n description: paymentRequirements.description,\n mimeType: paymentRequirements.mimeType,\n };\n}\n\n/**\n * Builds a v2 bazaar extension from extracted v1 discovery info.\n *\n * V1 had no formal schema validation, so the synthesized schema is permissive.\n *\n * @param discoveryInfo - Discovery info extracted from v1 payment requirements\n * @returns A bazaar extension suitable for catalog echo\n */\nexport function buildBazaarExtensionFromDiscoveryInfo(\n discoveryInfo: DiscoveryInfo,\n): DiscoveryExtension {\n // V1 had no formal schema; use a permissive envelope for catalog echo only.\n return {\n info: discoveryInfo,\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: { type: \"object\" },\n output: { type: \"object\" },\n },\n required: [\"input\"],\n },\n } as DiscoveryExtension;\n}\n\n/**\n * Normalizes v1 catalog extension payloads to v2 bazaar format.\n *\n * Preserves non-bazaar extensions from the payment payload. Replaces legacy\n * `outputSchema` entries with a synthesized `bazaar` extension.\n *\n * @param existingExtensions - Extension payloads from the v1 payment payload, if any\n * @param discoveryInfo - Discovery info extracted from v1 payment requirements\n * @returns Normalized extension payloads with a `bazaar` entry\n */\nexport function buildV1CatalogExtensions(\n existingExtensions: Record<string, unknown> | undefined,\n discoveryInfo: DiscoveryInfo,\n): Record<string, unknown> {\n if (existingExtensions?.[BAZAAR.key]) {\n return existingExtensions;\n }\n\n const extensions: Record<string, unknown> = existingExtensions ? { ...existingExtensions } : {};\n delete extensions.outputSchema;\n extensions[BAZAAR.key] = buildBazaarExtensionFromDiscoveryInfo(discoveryInfo);\n return extensions;\n}\n","/**\n * Shared startup-time validation utilities for bazaar extensions in route configs.\n *\n * Used by middleware packages (Express, Hono, Next) to validate bazaar extensions\n * at server startup without duplicating the iteration and warning logic.\n */\n\nimport type { RoutesConfig } from \"@x402/core/server\";\nimport type { DiscoveryExtension } from \"./types\";\nimport { validateDiscoveryExtension, validateDiscoveryExtensionSpec } from \"./facilitator\";\n\nexport { checkIfBazaarNeeded } from \"@x402/core/server\";\n\nconst HTTP_VERB_RE = /^(GET|POST|PUT|PATCH|DELETE|HEAD)\\b/i;\n\n/**\n * Inject a synthetic method into a pre-enrichment extension so the schema's\n * required:[\"method\"] check doesn't produce a false-positive warning at startup.\n * Priority: (1) route pattern verb (e.g. \"GET /api\"), (2) body vs query inference.\n * Returns the same object unchanged if method is already present.\n *\n * @param ext - The raw bazaar extension object\n * @param pattern - The route pattern key (e.g. \"GET /api\" or \"*\")\n * @returns The extension with a synthetic method injected into info.input if needed\n */\nfunction withSyntheticMethod(\n ext: Record<string, unknown>,\n pattern: string,\n): Record<string, unknown> {\n const info = ext.info as Record<string, unknown> | undefined;\n const input = info?.input as Record<string, unknown> | undefined;\n if (!input || (typeof input.method === \"string\" && input.method)) {\n return ext;\n }\n const verbMatch = pattern.match(HTTP_VERB_RE);\n const method = verbMatch\n ? verbMatch[1].toUpperCase()\n : input.body !== undefined || input.bodyType !== undefined\n ? \"POST\"\n : \"GET\";\n return { ...ext, info: { ...info, input: { ...input, method } } };\n}\n\n/**\n * Validate bazaar extensions on all routes using JSON-schema validation.\n * Emits console warnings for invalid extensions but does not throw.\n *\n * @param routes - Route configuration to scan for bazaar extensions\n */\nexport function validateBazaarRouteExtensions(routes: RoutesConfig): void {\n const entries: [string, { extensions?: Record<string, unknown> }][] =\n \"accepts\" in routes ? [[\"*\", routes]] : Object.entries(routes);\n\n for (const [pattern, config] of entries) {\n const bazaarExt = config.extensions?.[\"bazaar\"];\n if (!bazaarExt) continue;\n if (\n typeof bazaarExt === \"object\" &&\n bazaarExt !== null &&\n \"info\" in (bazaarExt as Record<string, unknown>) &&\n \"schema\" in (bazaarExt as Record<string, unknown>)\n ) {\n const specResult = validateDiscoveryExtensionSpec(bazaarExt as Record<string, unknown>);\n if (!specResult.valid) {\n console.warn(\n `x402: Route \"${pattern}\" has an invalid bazaar extension: ${specResult.errors?.join(\", \")}`,\n );\n continue;\n }\n const extForSchema = withSyntheticMethod(bazaarExt as Record<string, unknown>, pattern);\n const schemaResult = validateDiscoveryExtension(\n extForSchema as unknown as DiscoveryExtension,\n );\n if (!schemaResult.valid) {\n console.warn(\n `x402: Route \"${pattern}\" has an invalid bazaar extension: ${schemaResult.errors?.join(\", \")}`,\n );\n }\n } else {\n console.warn(\n `x402: Route \"${pattern}\" declares a bazaar extension but it is malformed ` +\n `(expected an object with \"info\" and \"schema\" fields)`,\n );\n }\n }\n}\n","/**\n * Client extensions for querying Bazaar discovery resources\n */\n\nimport { HTTPFacilitatorClient } from \"@x402/core/http\";\nimport type { PaymentRequirements } from \"@x402/core/types\";\nimport { WithExtensions } from \"../types\";\n\n/**\n * Parameters for listing discovery resources.\n * All parameters are optional and used for filtering/pagination.\n */\nexport interface ListDiscoveryResourcesParams {\n /**\n * Filter by protocol type (e.g., \"http\", \"mcp\").\n */\n type?: string;\n\n /**\n * Filter by payment recipient address.\n */\n payTo?: string;\n\n /**\n * Filter by payment scheme (e.g., \"exact\").\n */\n scheme?: string;\n\n /**\n * Filter by payment network (e.g., \"eip155:8453\").\n */\n network?: string;\n\n /**\n * Filter by extension key present on the discovered resource.\n */\n extensions?: string;\n\n /**\n * The number of discovered x402 resources to return per page.\n */\n limit?: number;\n\n /**\n * The offset of the first discovered x402 resource to return.\n */\n offset?: number;\n}\n\n/**\n * Parameters for searching discovery resources.\n */\nexport interface SearchDiscoveryResourcesParams {\n /**\n * Natural-language search query.\n */\n query: string;\n\n /**\n * Filter by protocol type (e.g., \"http\", \"mcp\").\n */\n type?: string;\n\n /**\n * Filter by payment recipient address.\n */\n payTo?: string;\n\n /**\n * Filter by payment scheme (e.g., \"exact\").\n */\n scheme?: string;\n\n /**\n * Filter by payment network (e.g., \"eip155:8453\").\n */\n network?: string;\n\n /**\n * Filter by extension key present on the discovered resource.\n */\n extensions?: string;\n\n /**\n * Advisory maximum number of results. The server may return fewer or ignore this.\n */\n limit?: number;\n\n /**\n * Advisory continuation cursor from a previous response. The server may ignore this.\n */\n cursor?: string;\n}\n\n/**\n * A discovered x402 resource from the bazaar.\n */\nexport interface DiscoveryResource {\n /** The URL or identifier of the discovered resource */\n resource: string;\n /** The protocol type of the resource (e.g., \"http\") */\n type: string;\n /** The x402 protocol version supported by this resource */\n x402Version: number;\n /** Array of accepted payment methods for this resource */\n accepts: PaymentRequirements[];\n /** ISO 8601 timestamp of when the resource was last updated */\n lastUpdated: string;\n /** Human-readable description of the resource */\n description?: string;\n /** MIME type of the resource response */\n mimeType?: string;\n /** Human-readable name for the service hosting the resource */\n serviceName?: string;\n /** Short topical tags for discovery search */\n tags?: string[];\n /** Absolute http(s) URL to a service icon */\n iconUrl?: string;\n /** Extension payloads echoed from discovery (e.g. bazaar info/schema) */\n extensions?: Record<string, unknown>;\n}\n\n/**\n * Response from listing discovery resources.\n */\nexport interface DiscoveryResourcesResponse {\n /** The x402 protocol version of this response */\n x402Version: number;\n /** The list of discovered resources */\n items: DiscoveryResource[];\n /** Pagination information for the response */\n pagination: {\n /** Maximum number of results returned */\n limit: number;\n /** Number of results skipped */\n offset: number;\n /** Total count of resources matching the query */\n total: number;\n };\n}\n\n/**\n * Response from searching discovery resources.\n */\nexport interface SearchDiscoveryResourcesResponse {\n /** The x402 protocol version of this response */\n x402Version: number;\n /** The list of matching discovered resources */\n resources: DiscoveryResource[];\n /** Whether additional matches were truncated by facilitator */\n partialResults?: boolean;\n /** Optional pagination details when a paginated response is returned */\n pagination?: {\n /** Number of results in this page */\n limit: number;\n /** Continuation cursor for the next page; may be null */\n cursor: string | null;\n } | null;\n}\n\n/**\n * Bazaar client extension interface providing discovery query functionality.\n */\nexport interface BazaarClientExtension {\n bazaar: {\n /**\n * List x402 discovery resources from the bazaar.\n *\n * @param params - Optional filtering and pagination parameters\n * @returns A promise resolving to the discovery resources response\n */\n listResources(params?: ListDiscoveryResourcesParams): Promise<DiscoveryResourcesResponse>;\n\n /**\n * Search x402 discovery resources from the bazaar using a natural-language query.\n *\n * Pagination is optional: facilitators may ignore `limit` and `cursor`, or include\n * `response.pagination` when pagination is used.\n *\n * @param params - Search parameters including the required query string\n * @returns A promise resolving to the search response\n */\n search(params: SearchDiscoveryResourcesParams): Promise<SearchDiscoveryResourcesResponse>;\n };\n}\n\n/**\n * Extends a facilitator client with Bazaar discovery query functionality.\n * Preserves and merges with any existing extensions from prior chaining.\n *\n * @param client - The facilitator client to extend\n * @returns The client extended with bazaar discovery capabilities\n *\n * @example\n * ```ts\n * // Basic usage\n * const client = withBazaar(new HTTPFacilitatorClient());\n * const resources = await client.extensions.bazaar.listResources({ type: \"http\" });\n *\n * // Search\n * const results = await client.extensions.bazaar.search({ query: \"weather APIs\" });\n *\n * // Chaining with other extensions\n * const client = withBazaar(withOtherExtension(new HTTPFacilitatorClient()));\n * await client.extensions.other.someMethod();\n * await client.extensions.bazaar.listResources();\n * ```\n */\nexport function withBazaar<T extends HTTPFacilitatorClient>(\n client: T,\n): WithExtensions<T, BazaarClientExtension> {\n // Preserve any existing extensions from prior chaining\n const existingExtensions =\n (client as T & { extensions?: Record<string, unknown> }).extensions ?? {};\n\n const extended = client as WithExtensions<T, BazaarClientExtension>;\n\n extended.extensions = {\n ...existingExtensions,\n bazaar: {\n async listResources(\n params?: ListDiscoveryResourcesParams,\n ): Promise<DiscoveryResourcesResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const authHeaders = await client.createAuthHeaders(\"bazaar\");\n headers = { ...headers, ...authHeaders.headers };\n\n const queryParams = new URLSearchParams();\n if (params?.type !== undefined) {\n queryParams.set(\"type\", params.type);\n }\n if (params?.payTo !== undefined) {\n queryParams.set(\"payTo\", params.payTo);\n }\n if (params?.scheme !== undefined) {\n queryParams.set(\"scheme\", params.scheme);\n }\n if (params?.network !== undefined) {\n queryParams.set(\"network\", params.network);\n }\n if (params?.extensions !== undefined) {\n queryParams.set(\"extensions\", params.extensions);\n }\n if (params?.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n if (params?.offset !== undefined) {\n queryParams.set(\"offset\", params.offset.toString());\n }\n\n const queryString = queryParams.toString();\n const endpoint = `${client.url}/discovery/resources${queryString ? `?${queryString}` : \"\"}`;\n\n const response = await fetch(endpoint, {\n method: \"GET\",\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n throw new Error(\n `Facilitator listDiscoveryResources failed (${response.status}): ${errorText}`,\n );\n }\n\n return (await response.json()) as DiscoveryResourcesResponse;\n },\n\n async search(\n params: SearchDiscoveryResourcesParams,\n ): Promise<SearchDiscoveryResourcesResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const authHeaders = await client.createAuthHeaders(\"bazaar\");\n headers = { ...headers, ...authHeaders.headers };\n\n const queryParams = new URLSearchParams();\n queryParams.set(\"query\", params.query);\n if (params.type !== undefined) {\n queryParams.set(\"type\", params.type);\n }\n if (params.payTo !== undefined) {\n queryParams.set(\"payTo\", params.payTo);\n }\n if (params.scheme !== undefined) {\n queryParams.set(\"scheme\", params.scheme);\n }\n if (params.network !== undefined) {\n queryParams.set(\"network\", params.network);\n }\n if (params.extensions !== undefined) {\n queryParams.set(\"extensions\", params.extensions);\n }\n if (params.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n if (params.cursor !== undefined) {\n queryParams.set(\"cursor\", params.cursor);\n }\n\n const endpoint = `${client.url}/discovery/search?${queryParams.toString()}`;\n\n const response = await fetch(endpoint, {\n method: \"GET\",\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n throw new Error(\n `Facilitator searchDiscoveryResources failed (${response.status}): ${errorText}`,\n );\n }\n\n return (await response.json()) as SearchDiscoveryResourcesResponse;\n },\n },\n } as WithExtensions<T, BazaarClientExtension>[\"extensions\"];\n\n return extended;\n}\n","import { createHash } from 'node:crypto';\nimport Ajv from 'ajv';\nimport Ajv2020 from 'ajv/dist/2020.js';\nimport addFormats from 'ajv-formats';\nimport type { ValidateFunction } from 'ajv';\nimport { mask } from './redact';\n\n/**\n * JSON Schema validation for anything a remote party asks this CLI to send or\n * accepts back: the router's decision arguments, and a result body a caller\n * declared a success condition for. Ported from the draft auto-mode experiment\n * (PR #369 `contracts.ts`) into a shared path so `tenjin pay` gets it too.\n *\n * SCHEMAS ARE UNTRUSTED INPUT. Ajv compiles keywords, never merchant code, but a\n * schema still reaches a compiler, so the checks below run BEFORE compilation:\n * bounded size and nesting, no prototype-poisoning keys, no remote `$ref`, and\n * no regular-expression keyword until a bounded regexp runtime exists. A schema\n * that fails any of them is refused rather than compiled.\n */\n\nexport type JsonRecord = Record<string, unknown>;\n\nconst MAX_SCHEMA_BYTES = 96 * 1024;\nconst MAX_VALUE_BYTES = 64 * 1024;\nconst MAX_BODY_BYTES = 128 * 1024;\nconst MAX_DEPTH = 24;\nconst VALIDATOR_CACHE_LIMIT = 128;\n\nconst DRAFT_07 = 'http://json-schema.org/draft-07/schema#';\n\n/** Key-order-independent serialization, so one schema has one cache identity. */\nfunction stable(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const object = value as JsonRecord;\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stable(object[key])}`)\n .join(',')}}`;\n }\n return JSON.stringify(value) ?? 'null';\n}\n\n/** The stable SHA-256 of a value; the identity a decision row and a duplicate\n * guard key are built from. */\nexport function canonicalHash(value: unknown): string {\n return createHash('sha256').update(stable(value)).digest('hex');\n}\n\nfunction walk(value: unknown, schemaMode: boolean, depth = 0): void {\n if (depth > MAX_DEPTH) throw new Error('Schema or value exceeds the nesting limit.');\n if (Array.isArray(value)) {\n for (const entry of value) walk(entry, schemaMode, depth + 1);\n return;\n }\n if (value === null || typeof value !== 'object') return;\n for (const [key, entry] of Object.entries(value)) {\n if (['__proto__', 'constructor', 'prototype'].includes(key)) {\n throw new Error(`Forbidden object key: ${key}`);\n }\n if (schemaMode && key === '$ref' && typeof entry === 'string' && !entry.startsWith('#/')) {\n throw new Error('Remote or recursive schema references are unsupported.');\n }\n if (schemaMode && (key === 'pattern' || key === 'patternProperties')) {\n throw new Error('Regular-expression schema constraints are unsupported.');\n }\n walk(entry, schemaMode, depth + 1);\n }\n}\n\nconst validators = new Map<string, ValidateFunction>();\n\nfunction compile(schema: JsonRecord): ValidateFunction {\n if (Buffer.byteLength(stable(schema)) > MAX_SCHEMA_BYTES) {\n throw new Error('Schema exceeds its size limit.');\n }\n const key = canonicalHash(schema);\n const cached = validators.get(key);\n if (cached !== undefined) return cached;\n walk(schema, true);\n const options = {\n strict: true,\n strictTypes: false,\n strictTuples: false,\n strictRequired: false,\n allErrors: false,\n validateFormats: true,\n coerceTypes: false,\n useDefaults: false,\n removeAdditional: false,\n allowUnionTypes: true,\n };\n const ajv = schema.$schema === DRAFT_07 ? new Ajv(options) : new Ajv2020(options);\n // A nested body schema can declare draft-07 under a 2020 parent. Registering\n // the meta-schema keeps the dialect's keywords checked and loads nothing\n // remote; Ajv's own remote loading stays off.\n if (!ajv.getSchema(DRAFT_07)) ajv.addMetaSchema({ $id: DRAFT_07 });\n addFormats(ajv);\n const compiled = ajv.compile(schema);\n if (validators.size >= VALIDATOR_CACHE_LIMIT) {\n validators.delete(validators.keys().next().value!);\n }\n validators.set(key, compiled);\n return compiled;\n}\n\nexport interface SchemaCheck {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Check a value against its own schema. Both are untrusted: the value is\n * round-tripped through JSON first so an exotic JS object can never reach the\n * validator, and its size is bounded before anything is compiled.\n */\nexport function validateAgainstSchema(schema: unknown, value: unknown): SchemaCheck {\n try {\n if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {\n throw new Error('A schema must be a JSON Schema object.');\n }\n const json = JSON.stringify(value);\n if (json === undefined || Buffer.byteLength(json) > MAX_VALUE_BYTES) {\n throw new Error('The value is not JSON, or exceeds its size limit.');\n }\n walk(value, false);\n const validate = compile(schema as JsonRecord);\n if (validate(value)) return { valid: true, errors: [] };\n return {\n valid: false,\n errors: (validate.errors ?? []).map(\n (e) => `${e.instancePath || '/'} ${e.message ?? 'invalid'}`,\n ),\n };\n } catch (err) {\n return { valid: false, errors: [err instanceof Error ? err.message : String(err)] };\n }\n}\n\n/** Compile a success schema before a payment is signed, so a broken rule refuses\n * at the cheap end rather than after money moved. */\nexport function assertResultSchema(schema: unknown): void {\n if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {\n throw new Error('A result success schema must be a JSON Schema object.');\n }\n compile(schema as JsonRecord);\n}\n\nexport interface ResultCheck {\n valid: boolean;\n /**\n * The check could not RUN, as against running and rejecting the body. The\n * size limit is this client's constant and the caller's success rule knows\n * nothing about it, so an over-limit body is not evidence the endpoint broke\n * its contract, and on a paid delivery the money has already moved by the\n * time it is measured. Callers deliver these with a caveat rather than\n * refusing them; a `valid: false` without it is a real contract failure.\n */\n unvalidated?: boolean;\n reason?: string;\n /**\n * WHAT A CATALOG OWNER NEEDS to tell one failure from another: a provider\n * whose parse missed looks exactly like one that answered HTML, and the\n * reason alone could not separate them during the live smoke.\n */\n diagnosis?: {\n /** `not-json`, `too-large`, or the schema rule that rejected it. */\n failed: string;\n json: boolean;\n bytes: number;\n maxBytes: number;\n /** First 300 characters, redacted. Other people's content, never instructions. */\n preview: string;\n };\n}\n\n/** A bounded, redacted look at the body, for a refusal a human has to act on. */\nfunction preview(body: string): string {\n const flat = mask(body).replace(/\\s+/g, ' ').trim();\n return flat.length <= 300 ? flat : `${flat.slice(0, 300)}…`;\n}\n\n/**\n * HTTP success and APPLICATION success are separate facts. A 200 whose body\n * fails the caller's declared success schema is a failure, and no success field\n * is ever inferred from the body itself.\n */\nexport function validateResultBody(schema: unknown, body: string): ResultCheck {\n const bytes = Buffer.byteLength(body);\n const base = { json: false, bytes, maxBytes: MAX_BODY_BYTES, preview: preview(body) };\n if (bytes > MAX_BODY_BYTES) {\n // NOT a contract failure: nothing was checked. See {@link ResultCheck.unvalidated}.\n return {\n valid: false,\n unvalidated: true,\n reason: `The result is ${bytes} bytes, over the ${MAX_BODY_BYTES} byte validation limit, so its success schema was not checked.`,\n diagnosis: { ...base, failed: 'too-large' },\n };\n }\n let value: unknown;\n try {\n value = JSON.parse(body);\n walk(value, false);\n } catch (err) {\n return {\n valid: false,\n reason: `The result is not a supported bounded JSON document (${err instanceof Error ? err.message : String(err)}).`,\n diagnosis: { ...base, failed: 'not-json' },\n };\n }\n const check = validateAgainstSchema(schema, value);\n if (check.valid) return { valid: true };\n const failed = check.errors[0] ?? 'the success rule';\n return {\n valid: false,\n reason: `The result does not satisfy its success schema: ${failed}`,\n diagnosis: { ...base, json: true, failed },\n };\n}\n","import type { PaymentMode } from './policy';\nimport { CliError } from './errors';\nimport { toMoney } from './money';\nimport { promptYesNo } from './prompt';\nimport type { SpendAuthorizer } from './wallet';\nimport type { CommandContext } from '../context';\n\n/**\n * The one money gate `buy` and `pay` share: policy authorization, the confirm\n * ceremony, and the refusal shapes. Both verbs run EXACTLY this sequence\n * between seeing a price and building a signature, so the two cannot drift on\n * what `--yes` clears (the confirm only), what a deny looks like, or when a\n * reservation is released. The caller still owns everything around it: the\n * challenge it priced, the payment build, and settling the reservation after a\n * failure: releasing only while no signature has left the process, committing\n * once one has (pay.ts), because a transmitted authorization can still settle.\n */\n\nexport interface SpendGateInput {\n ctx: CommandContext;\n mode: PaymentMode;\n authorizer: SpendAuthorizer;\n amountAtomic: bigint;\n /** The policy's creator identity (a handle for buy, the target host for pay). */\n creator: string;\n maxPriceAtomic?: bigint;\n /** The same-turn duplicate guard's identity for this request; see SpendRequest. */\n requestKey?: string;\n /** --yes: bypasses the interactive confirm only, never a cap or a deny. */\n yes: boolean;\n /** Interactive-confirm seam; defaults to a TTY y/n prompt. */\n confirm?: (prompt: string) => Promise<boolean>;\n /**\n * Who the human is told they are paying, PRE-SANITIZED by the caller (it\n * knows which parts are external input). Rendered before the price so escape\n * sequences could never repaint the amount being approved.\n */\n payeeLabel: string;\n /** \"Add the creator\" (buy) vs \"Add this host\" (pay) in the allowlist fix. */\n allowlistSubject: string;\n /** \"Purchase not confirmed.\" (buy) vs \"Payment not confirmed.\" (pay). */\n notConfirmedMessage: string;\n}\n\n/** Runs the gate; returns the reservation to commit or release (undefined\n * mirrors the authorizer's own optionality, same as before the extraction).\n * Throws POLICY_REFUSED (deny, or confirm declined), releasing first. */\nexport async function gateSpend(input: SpendGateInput): Promise<string | undefined> {\n const { authorizer, amountAtomic } = input;\n const authorization = await authorizer.authorize({\n mode: input.mode,\n amountAtomic,\n creator: input.creator,\n ...(input.maxPriceAtomic !== undefined ? { maxPriceAtomic: input.maxPriceAtomic } : {}),\n ...(input.requestKey !== undefined ? { requestKey: input.requestKey } : {}),\n });\n if (authorization.decision === 'deny') {\n throw new CliError('POLICY_REFUSED', authorization.message, {\n fix: policyFix(authorization.reason, input.allowlistSubject),\n details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() },\n });\n }\n const reservationId = authorization.reservationId;\n if (authorization.decision === 'confirm') {\n let approved: boolean;\n try {\n approved = await confirmSpend(input);\n } catch (err) {\n await authorizer.release(reservationId);\n throw err;\n }\n if (!approved) {\n await authorizer.release(reservationId);\n throw new CliError('POLICY_REFUSED', input.notConfirmedMessage, {\n fix: 'Obtain explicit user consent for this quoted payment, then re-run with --yes or confirm interactively. Manual pay is never an autonomous workaround for a router refusal.',\n details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() },\n });\n }\n }\n return reservationId;\n}\n\nfunction policyFix(reason: string, allowlistSubject: string): string {\n switch (reason) {\n case 'price_cap_exceeded':\n return 'Raise --max-price if this price is acceptable.';\n case 'not_allowlisted':\n return `Add ${allowlistSubject} to allowlistCreators, or clear the allowlist.`;\n case 'session_budget_exceeded':\n return 'Raise sessionBudget with `tenjin config set sessionBudget <usd>`, or wait for the window to roll over.';\n case 'duplicate_in_flight':\n return 'Let the in-flight request finish and read its result; retrying the same request does not renew authorization.';\n default:\n return 'Adjust your spend policy with `tenjin config set`.';\n }\n}\n\nasync function confirmSpend(input: SpendGateInput): Promise<boolean> {\n if (input.yes) return true;\n const prompt = `Pay ${toMoney(input.amountAtomic.toString()).usd} USD to ${input.payeeLabel}? [y/N] `;\n if (input.confirm !== undefined) return input.confirm(prompt);\n if (!input.ctx.io.isTTY) return false; // non-interactive without --yes: refuse (exit 3)\n // The real prompt reads stdin, so stdin must be interactive too: at EOF the\n // question could never be answered and the process would exit with no answer.\n if (!process.stdin.isTTY) return false;\n return promptYesNo(prompt); // default-no: only an explicit y/yes approves\n}\n","import { x402Version } from \"..\";\nimport { SchemeNetworkClient } from \"../types/mechanisms\";\nimport { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport { Network, PaymentRequired, SettleResponse } from \"../types\";\nimport { findByNetworkAndScheme, findSchemesByNetwork } from \"../utils\";\n\n/**\n * Client Hook Context Interfaces\n */\n\nexport interface PaymentCreationContext {\n paymentRequired: PaymentRequired;\n selectedRequirements: PaymentRequirements;\n}\n\nexport interface PaymentCreatedContext extends PaymentCreationContext {\n paymentPayload: PaymentPayload;\n}\n\nexport interface PaymentCreationFailureContext extends PaymentCreationContext {\n error: Error;\n}\n\n/**\n * Client Hook Type Definitions\n */\n\nexport type BeforePaymentCreationHook = (\n context: PaymentCreationContext,\n) => Promise<void | { abort: true; reason: string }>;\n\nexport type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise<void>;\n\nexport type OnPaymentCreationFailureHook = (\n context: PaymentCreationFailureContext,\n) => Promise<void | { recovered: true; payload: PaymentPayload }>;\n\n/**\n * Context provided to payment response hooks after the paid request completes.\n *\n * Discriminate by what's present:\n * - `settleResponse` with `success: true` → settle succeeded\n * - `settleResponse` with `success: false` → settle failed\n * - `paymentRequired` (no `settleResponse`) → verify failed\n * - `error` → transport or parse error\n */\nexport interface PaymentResponseContext {\n paymentPayload: PaymentPayload;\n requirements: PaymentRequirements;\n settleResponse?: SettleResponse;\n paymentRequired?: PaymentRequired;\n error?: Error;\n}\n\n/**\n * Hook fired after a paid request completes.\n * Return `{ recovered: true }` to signal the transport should retry with a fresh payload.\n */\nexport type OnPaymentResponseHook = (\n ctx: PaymentResponseContext,\n) => Promise<void | { recovered: true }>;\n\nexport type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;\n\ntype ClientHookAdapterHandles = {\n beforePaymentCreation?: BeforePaymentCreationHook;\n afterPaymentCreation?: AfterPaymentCreationHook;\n onPaymentCreationFailure?: OnPaymentCreationFailureHook;\n onPaymentResponse?: OnPaymentResponseHook;\n};\n\ntype ClientHookPhase = keyof ClientHookAdapterHandles;\n\nexport interface ClientExtensionHooks {\n onBeforePaymentCreation?: (\n declaration: unknown,\n context: PaymentCreationContext,\n ) => Promise<void | { abort: true; reason: string }>;\n onAfterPaymentCreation?: (\n declaration: unknown,\n context: PaymentCreatedContext,\n ) => Promise<void>;\n onPaymentCreationFailure?: (\n declaration: unknown,\n context: PaymentCreationFailureContext,\n ) => Promise<void | { recovered: true; payload: PaymentPayload }>;\n onPaymentResponse?: (\n declaration: unknown,\n context: PaymentResponseContext,\n ) => Promise<void | { recovered: true }>;\n}\n\nexport interface ClientTransportExtensionHooks {\n [transport: string]: unknown;\n}\n\n/**\n * Extension that can enrich payment payloads on the client side.\n *\n * Client extensions are invoked after the scheme creates the base payment payload\n * but before it is returned. This allows mechanism-specific logic (e.g., EVM EIP-2612\n * permit signing) to enrich the payload's extensions data.\n */\nexport interface ClientExtension {\n /**\n * Unique key identifying this extension (e.g., \"eip2612GasSponsoring\").\n * Must match the extension key used in PaymentRequired.extensions.\n */\n key: string;\n\n /**\n * Called after payload creation when the extension key is present in\n * paymentRequired.extensions. Allows the extension to enrich the payload\n * with extension-specific data (e.g., signing an EIP-2612 permit).\n *\n * @param paymentPayload - The payment payload to enrich\n * @param paymentRequired - The original PaymentRequired response\n * @returns The enriched payment payload\n */\n enrichPaymentPayload?: (\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ) => Promise<PaymentPayload>;\n\n hooks?: ClientExtensionHooks;\n transportHooks?: ClientTransportExtensionHooks;\n}\n\n/**\n * A policy function that filters or transforms payment requirements.\n * Policies are applied in order before the selector chooses the final option.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of payment requirements to filter/transform\n * @returns Filtered array of payment requirements\n */\nexport type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];\n\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:8453', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme client implementation for this network\n */\n client: SchemeNetworkClient;\n\n /**\n * The x402 protocol version to use for this scheme\n *\n * @default 2\n */\n x402Version?: number;\n}\n\n/**\n * Configuration options for the fetch wrapper\n */\nexport interface x402ClientConfig {\n /**\n * Array of scheme registrations defining which payment methods are supported\n */\n schemes: SchemeRegistration[];\n\n /**\n * Policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Custom payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n}\n\n/**\n * Core client for managing x402 payment schemes and creating payment payloads.\n *\n * Handles registration of payment schemes, policy-based filtering of payment requirements,\n * and creation of payment payloads based on server requirements.\n */\nexport class x402Client {\n private readonly paymentRequirementsSelector: SelectPaymentRequirements;\n private readonly registeredClientSchemes: Map<number, Map<string, Map<string, SchemeNetworkClient>>> = new Map();\n private readonly schemeClientHookAdapters: Map<number, Map<string, Map<string, ClientHookAdapterHandles>>> = new Map();\n private readonly policies: PaymentPolicy[] = [];\n private readonly registeredExtensions: Map<string, ClientExtension> = new Map();\n\n private beforePaymentCreationHooks: BeforePaymentCreationHook[] = [];\n private afterPaymentCreationHooks: AfterPaymentCreationHook[] = [];\n private onPaymentCreationFailureHooks: OnPaymentCreationFailureHook[] = [];\n private paymentResponseHooks: OnPaymentResponseHook[] = [];\n\n /**\n * Creates a new x402Client instance.\n *\n * @param paymentRequirementsSelector - Function to select payment requirements from available options\n */\n constructor(paymentRequirementsSelector?: SelectPaymentRequirements) {\n this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version, accepts) => accepts[0]);\n }\n\n /**\n * Creates a new x402Client instance from a configuration object.\n *\n * @param config - The client configuration including schemes, policies, and payment requirements selector\n * @returns A configured x402Client instance\n */\n static fromConfig(config: x402ClientConfig): x402Client {\n const client = new x402Client(config.paymentRequirementsSelector);\n config.schemes.forEach(scheme => {\n if (scheme.x402Version === 1) {\n client.registerV1(scheme.network, scheme.client);\n } else {\n client.register(scheme.network, scheme.client);\n }\n });\n config.policies?.forEach(policy => {\n client.registerPolicy(policy);\n });\n return client;\n }\n\n /**\n * Registers a scheme client for the current x402 version.\n *\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n register(network: Network, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(x402Version, network, client);\n }\n\n /**\n * Registers a scheme client for x402 version 1.\n *\n * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n registerV1(network: string, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(1, network as Network, client);\n }\n\n /**\n * Registers a policy to filter or transform payment requirements.\n *\n * Policies are applied in order after filtering by registered schemes\n * and before the selector chooses the final payment requirement.\n *\n * @param policy - Function to filter/transform payment requirements\n * @returns The x402Client instance for chaining\n *\n * @example\n * ```typescript\n * // Prefer cheaper options\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))\n * );\n *\n * // Prefer specific networks\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => r.network.startsWith('eip155:'))\n * );\n * ```\n */\n registerPolicy(policy: PaymentPolicy): x402Client {\n this.policies.push(policy);\n return this;\n }\n\n /**\n * Registers a client extension that can enrich payment payloads.\n *\n * Extensions are invoked after the scheme creates the base payload and the\n * payload is wrapped with extensions/resource/accepted data. If the extension's\n * key is present in `paymentRequired.extensions`, the extension's\n * `enrichPaymentPayload` hook is called to modify the payload.\n *\n * @param extension - The client extension to register\n * @returns The x402Client instance for chaining\n */\n registerExtension(extension: ClientExtension): x402Client {\n this.registeredExtensions.set(extension.key, extension);\n return this;\n }\n\n /**\n * Get all registered client extensions.\n *\n * @returns Array of registered extensions\n */\n getExtensions(): ClientExtension[] {\n return Array.from(this.registeredExtensions.values());\n }\n\n /**\n * Register a hook to execute before payment payload creation.\n * Can abort creation by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client {\n this.beforePaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment payload creation.\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client {\n this.afterPaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment payload creation fails.\n * Can recover from failure by returning { recovered: true, payload: PaymentPayload }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client {\n this.onPaymentCreationFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after a paid request completes.\n * Can signal recovery by returning { recovered: true }, causing the transport to retry.\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onPaymentResponse(hook: OnPaymentResponseHook): x402Client {\n this.paymentResponseHooks.push(hook);\n return this;\n }\n\n /**\n * Fires all registered payment response hooks in order.\n * Returns `{ recovered: true }` if any hook signals recovery (first wins).\n *\n * @param ctx - The payment response context\n * @returns Recovery signal or undefined\n */\n async handlePaymentResponse(\n ctx: PaymentResponseContext,\n ): Promise<{ recovered: true } | undefined> {\n for (const hook of this.getLabeledHooks(\n \"onPaymentResponse\",\n ctx.paymentPayload.x402Version,\n ctx.requirements,\n ctx.paymentRequired?.extensions ?? ctx.paymentPayload.extensions,\n )) {\n const result = await hook(ctx);\n if (result && \"recovered\" in result && result.recovered) {\n return { recovered: true };\n }\n }\n return undefined;\n }\n\n /**\n * Creates a payment payload based on a PaymentRequired response.\n *\n * Automatically extracts x402Version, resource, and extensions from the PaymentRequired\n * response and constructs a complete PaymentPayload with the accepted requirements.\n *\n * @param paymentRequired - The PaymentRequired response from the server\n * @returns Promise resolving to the complete payment payload\n */\n async createPaymentPayload(\n paymentRequired: PaymentRequired,\n ): Promise<PaymentPayload> {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);\n }\n\n const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);\n\n const context: PaymentCreationContext = {\n paymentRequired,\n selectedRequirements: requirements,\n };\n\n for (const hook of this.getLabeledHooks(\n \"beforePaymentCreation\",\n paymentRequired.x402Version,\n requirements,\n paymentRequired.extensions,\n )) {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new Error(`Payment creation aborted: ${result.reason}`);\n }\n }\n\n try {\n const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);\n if (!schemeNetworkClient) {\n throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);\n }\n\n const partialPayload = await schemeNetworkClient.createPaymentPayload(\n paymentRequired.x402Version,\n requirements,\n { extensions: paymentRequired.extensions },\n );\n\n let paymentPayload: PaymentPayload;\n if (partialPayload.x402Version == 1) {\n paymentPayload = partialPayload as PaymentPayload;\n } else {\n // Merge server-declared extensions with any scheme-provided extensions.\n // Scheme extensions overlay on top (e.g., EIP-2612 info enriches server declaration).\n const mergedExtensions = this.mergeExtensions(\n paymentRequired.extensions,\n partialPayload.extensions,\n );\n\n paymentPayload = {\n x402Version: partialPayload.x402Version,\n payload: partialPayload.payload,\n extensions: mergedExtensions,\n resource: paymentRequired.resource,\n accepted: requirements,\n };\n }\n\n // Enrich payload via registered client extensions (for non-scheme extensions)\n paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);\n\n const createdContext: PaymentCreatedContext = {\n ...context,\n paymentPayload,\n };\n\n for (const hook of this.getLabeledHooks(\n \"afterPaymentCreation\",\n paymentRequired.x402Version,\n requirements,\n paymentRequired.extensions,\n )) {\n await hook(createdContext);\n }\n\n return paymentPayload;\n } catch (error) {\n const failureContext: PaymentCreationFailureContext = {\n ...context,\n error: error as Error,\n };\n\n for (const hook of this.getLabeledHooks(\n \"onPaymentCreationFailure\",\n paymentRequired.x402Version,\n requirements,\n paymentRequired.extensions,\n )) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.payload;\n }\n }\n\n throw error;\n }\n }\n\n\n\n /**\n * Merges server-declared extensions with client extension echoes.\n * Client extension data may add fields, but server-declared fields remain intact.\n *\n * @param serverExtensions - Extensions declared by the server in the 402 response\n * @param clientExtensions - Extensions provided by the client or scheme\n * @returns The merged extensions object, or undefined if both inputs are undefined\n */\n private mergeExtensions(\n serverExtensions?: Record<string, unknown>,\n clientExtensions?: Record<string, unknown>,\n ): Record<string, unknown> | undefined {\n if (!clientExtensions) return serverExtensions;\n if (!serverExtensions) return clientExtensions;\n\n const merged = { ...serverExtensions };\n for (const [key, clientValue] of Object.entries(clientExtensions)) {\n const serverValue = merged[key];\n if (\n serverValue === null ||\n typeof serverValue !== \"object\" ||\n Array.isArray(serverValue) ||\n clientValue === null ||\n typeof clientValue !== \"object\" ||\n Array.isArray(clientValue)\n ) {\n merged[key] = clientValue;\n continue;\n }\n\n const serverRecord = serverValue as Record<string, unknown>;\n const clientRecord = clientValue as Record<string, unknown>;\n const extensionValue = { ...serverRecord };\n const pending = [{ target: extensionValue, source: clientRecord }];\n for (const item of pending) {\n for (const [fieldKey, clientFieldValue] of Object.entries(item.source)) {\n const serverFieldValue = item.target[fieldKey];\n if (\n serverFieldValue !== null &&\n typeof serverFieldValue === \"object\" &&\n !Array.isArray(serverFieldValue) &&\n clientFieldValue !== null &&\n typeof clientFieldValue === \"object\" &&\n !Array.isArray(clientFieldValue)\n ) {\n const nestedValue = { ...(serverFieldValue as Record<string, unknown>) };\n item.target[fieldKey] = nestedValue;\n pending.push({\n target: nestedValue,\n source: clientFieldValue as Record<string, unknown>,\n });\n continue;\n }\n\n if (!Object.prototype.hasOwnProperty.call(item.target, fieldKey)) {\n item.target[fieldKey] = clientFieldValue;\n }\n }\n }\n\n merged[key] = extensionValue;\n }\n return merged;\n }\n\n /**\n * Enriches a payment payload by calling registered extension hooks.\n * For each extension key present in the PaymentRequired response,\n * invokes the corresponding extension's enrichPaymentPayload callback.\n *\n * @param paymentPayload - The payment payload to enrich with extension data\n * @param paymentRequired - The PaymentRequired response containing extension declarations\n * @returns The enriched payment payload with extension data applied\n */\n private async enrichPaymentPayloadWithExtensions(\n paymentPayload: PaymentPayload,\n paymentRequired: PaymentRequired,\n ): Promise<PaymentPayload> {\n if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {\n return paymentPayload;\n }\n\n let enriched = paymentPayload;\n for (const [key, extension] of this.registeredExtensions) {\n if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {\n enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);\n }\n }\n\n return {\n ...enriched,\n extensions: this.mergeExtensions(paymentRequired.extensions, enriched.extensions),\n };\n }\n\n /**\n * Selects appropriate payment requirements based on registered clients and policies.\n *\n * Selection process:\n * 1. Filter by registered schemes (network + scheme support)\n * 2. Apply all registered policies in order\n * 3. Use selector to choose final requirement\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of available payment requirements\n * @returns The selected payment requirements\n */\n private selectPaymentRequirements(x402Version: number, paymentRequirements: PaymentRequirements[]): PaymentRequirements {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${x402Version}`);\n }\n\n // Step 1: Filter by registered schemes\n const supportedPaymentRequirements = paymentRequirements.filter(requirement => {\n let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);\n if (!clientSchemes) {\n return false;\n }\n\n return clientSchemes.has(requirement.scheme);\n })\n\n if (supportedPaymentRequirements.length === 0) {\n throw new Error(`No network/scheme registered for x402 version: ${x402Version} which comply with the payment requirements. ${JSON.stringify({\n x402Version,\n paymentRequirements,\n x402Versions: Array.from(this.registeredClientSchemes.keys()),\n networks: Array.from(clientSchemesByNetwork.keys()),\n schemes: Array.from(clientSchemesByNetwork.values()).map(schemes => Array.from(schemes.keys())).flat(),\n })}`);\n }\n\n // Step 2: Apply all policies in order\n let filteredRequirements = supportedPaymentRequirements;\n for (const policy of this.policies) {\n filteredRequirements = policy(x402Version, filteredRequirements);\n\n if (filteredRequirements.length === 0) {\n throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version}`);\n }\n }\n\n // Step 3: Use selector to choose final requirement\n return this.paymentRequirementsSelector(x402Version, filteredRequirements);\n }\n\n /**\n * Internal method to register a scheme client.\n *\n * @param x402Version - The x402 protocol version\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n private _registerScheme(x402Version: number, network: Network, client: SchemeNetworkClient): x402Client {\n if (!this.registeredClientSchemes.has(x402Version)) {\n this.registeredClientSchemes.set(x402Version, new Map());\n }\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version)!;\n if (!clientSchemesByNetwork.has(network)) {\n clientSchemesByNetwork.set(network, new Map());\n }\n\n const clientByScheme = clientSchemesByNetwork.get(network)!;\n clientByScheme.set(client.scheme, client);\n\n if (!this.schemeClientHookAdapters.has(x402Version)) {\n this.schemeClientHookAdapters.set(x402Version, new Map());\n }\n const adaptersByNetwork = this.schemeClientHookAdapters.get(x402Version)!;\n if (!adaptersByNetwork.has(network)) {\n adaptersByNetwork.set(network, new Map());\n }\n\n const adaptersByScheme = adaptersByNetwork.get(network)!;\n const hooks = client.schemeHooks;\n if (!hooks) {\n adaptersByScheme.delete(client.scheme);\n return this;\n }\n\n const handles: ClientHookAdapterHandles = {};\n if (hooks.onBeforePaymentCreation) {\n handles.beforePaymentCreation = hooks.onBeforePaymentCreation;\n }\n if (hooks.onAfterPaymentCreation) {\n handles.afterPaymentCreation = hooks.onAfterPaymentCreation;\n }\n if (hooks.onPaymentCreationFailure) {\n handles.onPaymentCreationFailure = hooks.onPaymentCreationFailure;\n }\n if (hooks.onPaymentResponse) {\n handles.onPaymentResponse = hooks.onPaymentResponse;\n }\n\n if (Object.keys(handles).length > 0) {\n adaptersByScheme.set(client.scheme, handles);\n } else {\n adaptersByScheme.delete(client.scheme);\n }\n\n return this;\n }\n\n /**\n * Returns manual hooks followed by the selected scheme hook and declared extension hooks.\n *\n * @param phase - Hook slot to collect\n * @param x402Version - Protocol version for the selected requirement\n * @param requirements - Selected payment requirement\n * @param declaredExtensions - Extension declarations that scope extension hooks\n * @returns Hooks in invocation order\n */\n private getLabeledHooks<P extends ClientHookPhase>(\n phase: P,\n x402Version: number,\n requirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n ): Array<NonNullable<ClientHookAdapterHandles[P]>> {\n let manual: Array<NonNullable<ClientHookAdapterHandles[P]>>;\n switch (phase) {\n case \"beforePaymentCreation\":\n manual = this.beforePaymentCreationHooks as Array<\n NonNullable<ClientHookAdapterHandles[P]>\n >;\n break;\n case \"afterPaymentCreation\":\n manual = this.afterPaymentCreationHooks as Array<\n NonNullable<ClientHookAdapterHandles[P]>\n >;\n break;\n case \"onPaymentCreationFailure\":\n manual = this.onPaymentCreationFailureHooks as Array<\n NonNullable<ClientHookAdapterHandles[P]>\n >;\n break;\n case \"onPaymentResponse\":\n manual = this.paymentResponseHooks as Array<NonNullable<ClientHookAdapterHandles[P]>>;\n break;\n }\n\n const out: Array<NonNullable<ClientHookAdapterHandles[P]>> = [...manual];\n const adaptersByNetwork = this.schemeClientHookAdapters.get(x402Version);\n const schemeAdapter = adaptersByNetwork\n ? findByNetworkAndScheme(adaptersByNetwork, requirements.scheme, requirements.network)\n : undefined;\n const hook = schemeAdapter?.[phase];\n if (hook !== undefined) {\n out.push(hook);\n }\n if (!declaredExtensions) {\n return out;\n }\n\n const extensionHookKey = this.getClientExtensionHookKey(phase);\n for (const [extensionKey, extension] of this.registeredExtensions) {\n if (!(extensionKey in declaredExtensions)) continue;\n\n const extensionHook = extension.hooks?.[extensionHookKey];\n if (!extensionHook) continue;\n\n type HookFn = NonNullable<ClientHookAdapterHandles[P]>;\n type HookContext = Parameters<HookFn>[0];\n out.push((async (ctx: HookContext) => {\n return (\n extensionHook as (\n declaration: unknown,\n context: HookContext,\n ) => ReturnType<HookFn>\n )(declaredExtensions[extensionKey], ctx);\n }) as HookFn);\n }\n return out;\n }\n\n /**\n * Maps internal hook phases to extension hook names.\n *\n * @param phase - Internal hook phase\n * @returns Extension hook key for the phase\n */\n private getClientExtensionHookKey<P extends ClientHookPhase>(\n phase: P,\n ): keyof ClientExtensionHooks {\n switch (phase) {\n case \"beforePaymentCreation\":\n return \"onBeforePaymentCreation\";\n case \"afterPaymentCreation\":\n return \"onAfterPaymentCreation\";\n case \"onPaymentCreationFailure\":\n return \"onPaymentCreationFailure\";\n case \"onPaymentResponse\":\n return \"onPaymentResponse\";\n }\n }\n}\n","// EIP-3009 TransferWithAuthorization types for EIP-712 signing\nexport const authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/**\n * Permit2 EIP-712 types for signing PermitWitnessTransferFrom (exact scheme).\n * Must match the exact format expected by the Permit2 contract.\n * Note: Types must be in ALPHABETICAL order after the primary type (TokenPermissions < Witness).\n */\nexport const permit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"Witness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n Witness: [\n { name: \"to\", type: \"address\" },\n { name: \"validAfter\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * Permit2 EIP-712 types for signing PermitWitnessTransferFrom (upto scheme).\n * The upto witness includes a `facilitator` field that the exact witness does not.\n * This ensures only the authorized facilitator can settle the payment.\n * Must match: Witness(address to,address facilitator,uint256 validAfter)\n */\nexport const uptoPermit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"Witness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n Witness: [\n { name: \"to\", type: \"address\" },\n { name: \"facilitator\", type: \"address\" },\n { name: \"validAfter\", type: \"uint256\" },\n ],\n} as const;\n\n// EIP3009 ABI for transferWithAuthorization function\nexport const eip3009ABI = [\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"version\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"name\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"authorizer\", type: \"address\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n name: \"authorizationState\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n/**\n * EIP-2612 Permit EIP-712 types for signing token.permit().\n */\nexport const eip2612PermitTypes = {\n Permit: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * EIP-2612 nonces ABI for querying current nonce.\n */\nexport const eip2612NoncesAbi = [\n {\n type: \"function\",\n name: \"nonces\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** ERC-20 approve(address,uint256) ABI for encoding/decoding approval calldata. */\nexport const erc20ApproveAbi = [\n {\n type: \"function\",\n name: \"approve\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ type: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n] as const;\n\n/** ERC-20 allowance(address,address) ABI for checking spender approval. */\nexport const erc20AllowanceAbi = [\n {\n type: \"function\",\n name: \"allowance\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n outputs: [{ type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n\n/** Gas limit for a standard ERC-20 approve() transaction. */\nexport const ERC20_APPROVE_GAS_LIMIT = 70_000n;\n\n/** Fallback max fee per gas (1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_FEE_PER_GAS = 1_000_000_000n;\n\n/** Fallback max priority fee per gas (0.1 gwei) when fee estimation fails. */\nexport const DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100_000_000n;\n\n/**\n * Canonical Permit2 contract address.\n * Same address on all EVM chains via CREATE2 deployment.\n *\n * @see https://github.com/Uniswap/permit2\n */\nexport const PERMIT2_ADDRESS = \"0x000000000022D473030F116dDEE9F6B43aC78BA3\" as const;\n\n/**\n * x402ExactPermit2Proxy contract address.\n * Vanity address: 0x4020...0001 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0001\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402ExactPermit2ProxyAddress = \"0x402085c248EeA27D92E8b30b2C58ed07f9E20001\" as const;\n\n/**\n * x402UptoPermit2Proxy contract address.\n * Vanity address: 0x4020...0002 for easy recognition.\n * This address is deterministic based on:\n * - Arachnid's deterministic deployer (0x4e59b44847b379578588920cA78FbF26c0B4956C)\n * - Vanity-mined salt for prefix 0x4020 and suffix 0002\n * - Contract bytecode + constructor args (PERMIT2_ADDRESS)\n */\nexport const x402UptoPermit2ProxyAddress = \"0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002\" as const;\n\n/**\n * ABI components for the exact Permit2 witness tuple: Witness(address to, uint256 validAfter).\n */\nconst permit2WitnessABIComponents = [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"validAfter\", type: \"uint256\", internalType: \"uint256\" },\n] as const;\n\n/**\n * ABI components for the upto Permit2 witness tuple:\n * Witness(address to, address facilitator, uint256 validAfter).\n */\nconst uptoPermit2WitnessABIComponents = [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"facilitator\", type: \"address\", internalType: \"address\" },\n { name: \"validAfter\", type: \"uint256\", internalType: \"uint256\" },\n] as const;\n\n/**\n * x402UptoPermit2Proxy ABI — settle/settleWithPermit for the upto payment scheme.\n * Key differences from exact: settle() takes a `uint256 amount` parameter, and the\n * Witness struct includes an `address facilitator` field.\n */\nexport const x402UptoPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: uptoPermit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402UptoPermit2Proxy.Witness\",\n components: uptoPermit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"AmountExceedsPermitted\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n { type: \"error\", name: \"UnauthorizedFacilitator\", inputs: [] },\n] as const;\n\n/**\n * x402ExactPermit2Proxy ABI - settle function for exact payment scheme.\n */\nexport const x402ExactPermit2ProxyABI = [\n {\n type: \"function\",\n name: \"PERMIT2\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\", internalType: \"contract ISignatureTransfer\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\", internalType: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"WITNESS_TYPE_STRING\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\", internalType: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settleWithPermit\",\n inputs: [\n {\n name: \"permit2612\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.EIP2612Permit\",\n components: [\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"r\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"s\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"v\", type: \"uint8\", internalType: \"uint8\" },\n ],\n },\n {\n name: \"permit\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.PermitTransferFrom\",\n components: [\n {\n name: \"permitted\",\n type: \"tuple\",\n internalType: \"struct ISignatureTransfer.TokenPermissions\",\n components: [\n { name: \"token\", type: \"address\", internalType: \"address\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"nonce\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"deadline\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n {\n name: \"witness\",\n type: \"tuple\",\n internalType: \"struct x402ExactPermit2Proxy.Witness\",\n components: permit2WitnessABIComponents,\n },\n { name: \"signature\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n { type: \"event\", name: \"Settled\", inputs: [], anonymous: false },\n { type: \"event\", name: \"SettledWithPermit\", inputs: [], anonymous: false },\n { type: \"error\", name: \"InvalidAmount\", inputs: [] },\n { type: \"error\", name: \"InvalidDestination\", inputs: [] },\n { type: \"error\", name: \"InvalidOwner\", inputs: [] },\n { type: \"error\", name: \"InvalidPermit2Address\", inputs: [] },\n { type: \"error\", name: \"PaymentTooEarly\", inputs: [] },\n { type: \"error\", name: \"Permit2612AmountMismatch\", inputs: [] },\n { type: \"error\", name: \"ReentrancyGuardReentrantCall\", inputs: [] },\n] as const;\n","// Scheme identifier for the auth-capture payment scheme.\nexport const AUTH_CAPTURE_SCHEME = \"auth-capture\" as const;\n\n// Canonical AuthCaptureEscrow + token collector deployments from\n// base/commerce-payments (https://github.com/base/commerce-payments). These are\n// the audited, live addresses listed in the upstream README and are the source\n// of truth for this scheme. They are universal constants, not configurable per\n// merchant.\nexport const AUTH_CAPTURE_ESCROW_ADDRESS =\n \"0xBdEA0D1bcC5966192B070Fdf62aB4EF5b4420cff\" as const satisfies `0x${string}`;\nexport const EIP3009_TOKEN_COLLECTOR_ADDRESS =\n \"0x0E3dF9510de65469C4518D7843919c0b8C7A7757\" as const satisfies `0x${string}`;\nexport const PERMIT2_TOKEN_COLLECTOR_ADDRESS =\n \"0x992476B9Ee81d52a5BdA0622C333938D0Af0aB26\" as const satisfies `0x${string}`;\n\n// ERC-3009 ReceiveWithAuthorization EIP-712 types\nexport const RECEIVE_AUTHORIZATION_TYPES = {\n ReceiveWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n// Uniswap Permit2 PermitTransferFrom EIP-712 types\nexport const PERMIT2_TRANSFER_FROM_TYPES = {\n PermitTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n} as const;\n","/**\n * AuthCapture Scheme - Client\n * Builds payment payloads for auth-capture payments.\n *\n * Implements x402's SchemeNetworkClient interface so it can be registered\n * on an x402Client via client.register('eip155:84532', new AuthCaptureEvmScheme(signer)).\n */\n\nimport type {\n PaymentPayloadContext,\n PaymentPayloadResult,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport type { ClientEvmSigner } from \"../../signer\";\nimport { hexToBigInt } from \"viem\";\nimport {\n AUTH_CAPTURE_SCHEME,\n EIP3009_TOKEN_COLLECTOR_ADDRESS,\n PERMIT2_TOKEN_COLLECTOR_ADDRESS,\n} from \"../constants\";\nimport {\n computePayerAgnosticPaymentInfoHash,\n generateSalt,\n signERC3009,\n signPermit2,\n} from \"../nonce\";\nimport type { AuthCaptureExtra, Eip3009Payload, PaymentInfoStruct, Permit2Payload } from \"../types\";\nimport { parseChainId } from \"../utils\";\n\n/**\n * Client-side implementation of the auth-capture scheme: derives the canonical\n * payer-agnostic PaymentInfo hash, signs an ERC-3009 ReceiveWithAuthorization\n * (default) or a Permit2 PermitTransferFrom against it, and returns a wire\n * payload the facilitator can settle. Implements `SchemeNetworkClient`.\n */\nexport class AuthCaptureEvmScheme implements SchemeNetworkClient {\n readonly scheme = AUTH_CAPTURE_SCHEME;\n\n /**\n * Construct a client-side auth-capture scheme bound to a specific signer.\n *\n * @param signer - Client-side signer that exposes `address` and `signTypedData`.\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Build and sign an auth-capture payment payload for the given requirements.\n * Validates all spec-mandated `extra` fields and the asset-transfer method\n * (default `eip3009`, alternative `permit2`), reconstructs the on-chain\n * PaymentInfo struct, computes its payer-agnostic hash, and returns the\n * signed wire payload.\n *\n * @param x402Version - Wire protocol version; only `2` is supported.\n * @param requirements - Resource server's payment requirements (includes scheme `extra`).\n * @param _ - Unused FacilitatorContext (interface compatibility).\n * @returns The signed wire payload tagged with the x402 protocol version.\n * @throws If `x402Version !== 2` or any required `extra` field is missing.\n */\n async createPaymentPayload(\n x402Version: number,\n requirements: PaymentRequirements,\n _?: PaymentPayloadContext,\n ): Promise<PaymentPayloadResult> {\n if (x402Version !== 2) {\n throw new Error(`Unsupported x402Version: ${x402Version}. Only version 2 is supported.`);\n }\n\n const extra = requirements.extra as unknown as AuthCaptureExtra;\n\n // Validate required EIP-712 token-domain parameters\n if (!extra.name) {\n throw new Error(\n `EIP-712 domain parameter 'name' is required in payment requirements for asset ${requirements.asset}`,\n );\n }\n if (!extra.version) {\n throw new Error(\n `EIP-712 domain parameter 'version' is required in payment requirements for asset ${requirements.asset}`,\n );\n }\n if (!extra.captureAuthorizer) {\n throw new Error(`'captureAuthorizer' is required in payment requirements extra`);\n }\n if (!extra.feeRecipient) {\n throw new Error(`'feeRecipient' is required in payment requirements extra`);\n }\n if (typeof extra.captureDeadline !== \"number\") {\n throw new Error(`'captureDeadline' is required in payment requirements extra`);\n }\n if (typeof extra.refundDeadline !== \"number\") {\n throw new Error(`'refundDeadline' is required in payment requirements extra`);\n }\n if (typeof extra.minFeeBps !== \"number\") {\n throw new Error(`'minFeeBps' is required in payment requirements extra`);\n }\n if (typeof extra.maxFeeBps !== \"number\") {\n throw new Error(`'maxFeeBps' is required in payment requirements extra`);\n }\n if (typeof requirements.maxTimeoutSeconds !== \"number\") {\n throw new Error(\n `'maxTimeoutSeconds' is required in PaymentRequirements (used to derive preApprovalExpiry)`,\n );\n }\n\n const chainId = parseChainId(requirements.network);\n const maxAmount = requirements.amount;\n const nowSeconds = Math.floor(Date.now() / 1000);\n const preApprovalExpiry = nowSeconds + requirements.maxTimeoutSeconds;\n const salt = generateSalt();\n const assetTransferMethod = extra.assetTransferMethod ?? \"eip3009\";\n\n // Build the canonical PaymentInfo struct (Solidity field names — do not rename).\n const paymentInfo: PaymentInfoStruct = {\n operator: extra.captureAuthorizer,\n payer: this.signer.address,\n receiver: requirements.payTo as `0x${string}`,\n token: requirements.asset as `0x${string}`,\n maxAmount,\n preApprovalExpiry,\n authorizationExpiry: extra.captureDeadline,\n refundExpiry: extra.refundDeadline,\n minFeeBps: extra.minFeeBps,\n maxFeeBps: extra.maxFeeBps,\n feeReceiver: extra.feeRecipient,\n salt,\n };\n\n // Payer-agnostic PaymentInfo hash — used as ERC-3009 nonce or Permit2 nonce.\n const nonce = computePayerAgnosticPaymentInfoHash(chainId, paymentInfo);\n\n if (assetTransferMethod === \"permit2\") {\n const permit2Authorization: Permit2Payload[\"permit2Authorization\"] = {\n from: this.signer.address,\n permitted: {\n token: requirements.asset as `0x${string}`,\n amount: maxAmount,\n },\n spender: PERMIT2_TOKEN_COLLECTOR_ADDRESS,\n nonce: hexToBigInt(nonce).toString(),\n deadline: String(preApprovalExpiry),\n };\n const signature = await signPermit2(this.signer, permit2Authorization, chainId);\n const payload: Permit2Payload = { permit2Authorization, signature, salt };\n return { x402Version, payload: payload as unknown as Record<string, unknown> };\n }\n\n // Default: EIP-3009 ReceiveWithAuthorization to the canonical EIP-3009 token collector.\n const authorization: Eip3009Payload[\"authorization\"] = {\n from: this.signer.address,\n to: EIP3009_TOKEN_COLLECTOR_ADDRESS,\n value: maxAmount,\n validAfter: \"0\",\n validBefore: String(preApprovalExpiry),\n nonce,\n };\n const signature = await signERC3009(\n this.signer,\n authorization,\n extra,\n requirements.asset as `0x${string}`,\n chainId,\n );\n const payload: Eip3009Payload = { authorization, signature, salt };\n return { x402Version, payload: payload as unknown as Record<string, unknown> };\n }\n}\n","/**\n * Nonce computation, salt generation, and signing helpers.\n */\n\nimport { encodeAbiParameters, getAddress, keccak256, toHex, zeroAddress } from \"viem\";\nimport type { ClientEvmSigner } from \"../signer\";\nimport { PERMIT2_ADDRESS } from \"../constants\";\nimport {\n AUTH_CAPTURE_ESCROW_ADDRESS,\n PERMIT2_TRANSFER_FROM_TYPES,\n RECEIVE_AUTHORIZATION_TYPES,\n} from \"./constants\";\nimport type { AuthCaptureExtra, Eip3009Payload, PaymentInfoStruct, Permit2Payload } from \"./types\";\n\n/**\n * PaymentInfo typehash — must match AuthCaptureEscrow.PAYMENT_INFO_TYPEHASH.\n */\nconst PAYMENT_INFO_TYPEHASH = keccak256(\n new TextEncoder().encode(\n \"PaymentInfo(address operator,address payer,address receiver,address token,uint120 maxAmount,uint48 preApprovalExpiry,uint48 authorizationExpiry,uint48 refundExpiry,uint16 minFeeBps,uint16 maxFeeBps,address feeReceiver,uint256 salt)\",\n ),\n);\n\n/**\n * Compute the payer-agnostic PaymentInfo hash that auth-capture uses as both\n * the ERC-3009 nonce (`bytes32`) and the Permit2 nonce (`uint256`, via the\n * same 32 bytes interpreted as an integer). The payer field is zeroed before\n * hashing so the facilitator can reconstruct the same hash on the verify side\n * without knowing payer identity in advance.\n *\n * Freshness comes from `paymentInfo.salt`; generate a new salt per signing\n * call via `generateSalt`. Identical extras + same salt would collide across\n * payers.\n *\n * @param chainId - EVM chain id; binds the hash to a specific chain.\n * @param paymentInfo - The reconstructed PaymentInfo struct (canonical Solidity field names).\n * @returns The 32-byte hash to use as the nonce on the wire.\n */\nexport function computePayerAgnosticPaymentInfoHash(\n chainId: number,\n paymentInfo: PaymentInfoStruct,\n): `0x${string}` {\n const paymentInfoEncoded = encodeAbiParameters(\n [\n { name: \"typehash\", type: \"bytes32\" },\n { name: \"operator\", type: \"address\" },\n { name: \"payer\", type: \"address\" },\n { name: \"receiver\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"maxAmount\", type: \"uint120\" },\n { name: \"preApprovalExpiry\", type: \"uint48\" },\n { name: \"authorizationExpiry\", type: \"uint48\" },\n { name: \"refundExpiry\", type: \"uint48\" },\n { name: \"minFeeBps\", type: \"uint16\" },\n { name: \"maxFeeBps\", type: \"uint16\" },\n { name: \"feeReceiver\", type: \"address\" },\n { name: \"salt\", type: \"uint256\" },\n ],\n [\n PAYMENT_INFO_TYPEHASH,\n paymentInfo.operator,\n zeroAddress,\n paymentInfo.receiver,\n paymentInfo.token,\n BigInt(paymentInfo.maxAmount),\n paymentInfo.preApprovalExpiry,\n paymentInfo.authorizationExpiry,\n paymentInfo.refundExpiry,\n paymentInfo.minFeeBps,\n paymentInfo.maxFeeBps,\n paymentInfo.feeReceiver,\n BigInt(paymentInfo.salt),\n ],\n );\n const paymentInfoHash = keccak256(paymentInfoEncoded);\n\n const outerEncoded = encodeAbiParameters(\n [\n { name: \"chainId\", type: \"uint256\" },\n { name: \"escrow\", type: \"address\" },\n { name: \"paymentInfoHash\", type: \"bytes32\" },\n ],\n [BigInt(chainId), AUTH_CAPTURE_ESCROW_ADDRESS, paymentInfoHash],\n );\n\n return keccak256(outerEncoded);\n}\n\n/**\n * Sign an ERC-3009 `ReceiveWithAuthorization` over the supplied authorization\n * fields. The EIP-712 domain is bound to the **token contract** (not the\n * escrow), so the token's `name` and `version` come from `extra` because they\n * vary per asset (e.g. `\"USDC\"` on Sepolia vs `\"USD Coin\"` on mainnet).\n *\n * @param signer - Client signer with `signTypedData`.\n * @param authorization - The ERC-3009 authorization to sign.\n * @param extra - Carries the token EIP-712 domain `name` + `version`.\n * @param tokenAddress - Address of the token contract (verifyingContract in the domain).\n * @param chainId - EVM chain id (chainId in the domain).\n * @returns The 65-byte ECDSA signature (or EIP-1271 / EIP-6492 envelope, depending on the signer).\n */\nexport async function signERC3009(\n signer: ClientEvmSigner,\n authorization: Eip3009Payload[\"authorization\"],\n extra: AuthCaptureExtra,\n tokenAddress: `0x${string}`,\n chainId: number,\n): Promise<`0x${string}`> {\n const domain = {\n name: extra.name,\n version: extra.version,\n chainId,\n verifyingContract: getAddress(tokenAddress),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return signer.signTypedData({\n domain,\n types: RECEIVE_AUTHORIZATION_TYPES,\n primaryType: \"ReceiveWithAuthorization\",\n message,\n });\n}\n\n/**\n * Sign a Permit2 `PermitTransferFrom` over the supplied permit fields. Domain\n * is bound to the canonical Permit2 contract. No witness struct is needed —\n * the deterministic nonce (the payer-agnostic PaymentInfo hash, packed into\n * uint256) cryptographically binds all payment parameters including receiver,\n * amount, and deadlines.\n *\n * @param signer - Client signer with `signTypedData`.\n * @param permit - The Permit2 PermitTransferFrom message to sign.\n * @param chainId - EVM chain id (chainId in the Permit2 domain).\n * @returns The 65-byte ECDSA signature (or EIP-1271 / EIP-6492 envelope, depending on the signer).\n */\nexport async function signPermit2(\n signer: ClientEvmSigner,\n permit: Permit2Payload[\"permit2Authorization\"],\n chainId: number,\n): Promise<`0x${string}`> {\n const domain = {\n name: \"Permit2\",\n chainId,\n verifyingContract: PERMIT2_ADDRESS,\n };\n\n const message = {\n permitted: {\n token: getAddress(permit.permitted.token),\n amount: BigInt(permit.permitted.amount),\n },\n spender: getAddress(permit.spender),\n nonce: BigInt(permit.nonce),\n deadline: BigInt(permit.deadline),\n };\n\n return signer.signTypedData({\n domain,\n types: PERMIT2_TRANSFER_FROM_TYPES,\n primaryType: \"PermitTransferFrom\",\n message,\n });\n}\n\n/**\n * Generate a fresh cryptographically-random 32-byte salt. MUST be called once\n * per signing request — never reuse across requests. Freshness is required\n * because the nonce derivation zeroes the payer field; identical extras with\n * the same salt would collide across payers.\n *\n * @returns A new 32-byte salt as a `0x`-prefixed hex string.\n */\nexport function generateSalt(): `0x${string}` {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return toHex(bytes);\n}\n","/**\n * Parse chainId from CAIP-2 network identifier\n *\n * @param network - CAIP-2 network identifier (e.g., 'eip155:84532')\n * @returns The chain ID as a number\n */\nexport function parseChainId(network: string): number {\n const parts = network.split(\":\");\n if (parts.length !== 2 || parts[0] !== \"eip155\") {\n throw new Error(`Invalid network format: ${network}. Expected 'eip155:<chainId>'`);\n }\n const chainId = parseInt(parts[1], 10);\n if (isNaN(chainId)) {\n throw new Error(`Invalid chainId in network: ${network}`);\n }\n return chainId;\n}\n","import { toHex } from \"viem\";\n\n/**\n * Extract chain ID from a CAIP-2 network identifier (eip155:CHAIN_ID).\n *\n * @param network - The network identifier in CAIP-2 format (e.g., \"eip155:8453\")\n * @returns The numeric chain ID\n * @throws Error if the network format is invalid\n */\nexport function getEvmChainId(network: string): number {\n if (network.startsWith(\"eip155:\")) {\n const idStr = network.split(\":\")[1];\n const chainId = parseInt(idStr, 10);\n if (isNaN(chainId)) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n return chainId;\n }\n\n throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);\n}\n\n/**\n * Get the crypto object from the global scope.\n *\n * @returns The crypto object\n * @throws Error if crypto API is not available\n */\nfunction getCrypto(): Crypto {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n return cryptoObj;\n}\n\n/**\n * Create a random 32-byte nonce for EIP-3009 authorization.\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n return toHex(getCrypto().getRandomValues(new Uint8Array(32)));\n}\n\n/**\n * Creates a random 256-bit nonce for Permit2.\n * Permit2 uses uint256 nonces (not bytes32 like EIP-3009).\n *\n * @returns A string representation of the random nonce\n */\nexport function createPermit2Nonce(): string {\n const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));\n return BigInt(toHex(randomBytes)).toString();\n}\n","import { keccak256, toBytes } from \"viem\";\n\n/** Scheme identifier for the batch-settlement payment scheme. */\nexport const BATCH_SETTLEMENT_SCHEME = \"batch-settlement\" as const;\n\n/** Deployed address of the x402BatchSettlement contract. */\nexport const BATCH_SETTLEMENT_ADDRESS = \"0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003\" as const;\n\n/** Deployed address of the ERC3009DepositCollector contract. */\nexport const ERC3009_DEPOSIT_COLLECTOR_ADDRESS =\n \"0x4020806089470a89826cB9fB1f4059150b550004\" as const;\n\n/** Deployed address of the Permit2DepositCollector contract. */\nexport const PERMIT2_DEPOSIT_COLLECTOR_ADDRESS =\n \"0x4020425FAf3B746C082C2f942b4E5159887B0005\" as const;\n\n/** Minimum withdraw delay in seconds (15 minutes), matching the onchain constant. */\nexport const MIN_WITHDRAW_DELAY = 900;\n\n/** Maximum withdraw delay in seconds (30 days), matching the onchain constant. */\nexport const MAX_WITHDRAW_DELAY = 2_592_000;\n\n/** EIP-712 domain fields shared across all batch-settlement typed-data signatures. */\nexport const BATCH_SETTLEMENT_DOMAIN = {\n name: \"x402 Batch Settlement\",\n version: \"1\",\n} as const;\n\n/** EIP-712 type hash for channel identity. */\nexport const CHANNEL_CONFIG_TYPEHASH = keccak256(\n toBytes(\n \"ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)\",\n ),\n);\n\n/** EIP-712 type definition for a channel configuration. */\nexport const channelConfigTypes = {\n ChannelConfig: [\n { name: \"payer\", type: \"address\" },\n { name: \"payerAuthorizer\", type: \"address\" },\n { name: \"receiver\", type: \"address\" },\n { name: \"receiverAuthorizer\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"withdrawDelay\", type: \"uint40\" },\n { name: \"salt\", type: \"bytes32\" },\n ],\n} as const;\n\n/** EIP-712 type definition for a cumulative voucher: `Voucher(bytes32 channelId, uint128 maxClaimableAmount)`. */\nexport const voucherTypes = {\n Voucher: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"maxClaimableAmount\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definition for cooperative refund: `Refund(bytes32 channelId, uint256 nonce, uint128 amount)`. */\nexport const refundTypes = {\n Refund: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"amount\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definitions for a receiver-authorizer claim batch (nested ClaimEntry). */\nexport const claimBatchTypes = {\n ClaimBatch: [{ name: \"claims\", type: \"ClaimEntry[]\" }],\n ClaimEntry: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"maxClaimableAmount\", type: \"uint128\" },\n { name: \"totalClaimed\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definition for ERC-3009 `ReceiveWithAuthorization` (used for gasless deposits). */\nexport const receiveAuthorizationTypes = {\n ReceiveWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/** Permit2 typed data for channel-bound batch deposits. */\nexport const batchPermit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"DepositWitness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n DepositWitness: [{ name: \"channelId\", type: \"bytes32\" }],\n} as const;\n","import { getAddress, hashTypedData } from \"viem\";\nimport { BATCH_SETTLEMENT_ADDRESS, BATCH_SETTLEMENT_DOMAIN, channelConfigTypes } from \"./constants\";\nimport type { ChannelConfig } from \"./types\";\nimport { getEvmChainId } from \"../utils\";\n\n/**\n * Computes the chain-bound channel id from a {@link ChannelConfig} struct.\n *\n * @param config - The immutable channel configuration.\n * @param networkOrChainId - CAIP-2 network identifier or numeric EVM chain id.\n * @returns The `bytes32` channel id as a hex string.\n */\nexport function computeChannelId(\n config: ChannelConfig,\n networkOrChainId: string | number,\n): `0x${string}` {\n const chainId =\n typeof networkOrChainId === \"number\" ? networkOrChainId : getEvmChainId(networkOrChainId);\n return hashTypedData({\n domain: getBatchSettlementEip712Domain(chainId),\n types: channelConfigTypes,\n primaryType: \"ChannelConfig\",\n message: {\n payer: config.payer,\n payerAuthorizer: config.payerAuthorizer,\n receiver: config.receiver,\n receiverAuthorizer: config.receiverAuthorizer,\n token: config.token,\n withdrawDelay: config.withdrawDelay,\n salt: config.salt,\n },\n });\n}\n\n/**\n * Returns the full EIP-712 domain for the batch-settlement contract on the given chain.\n *\n * @param chainId - Numeric EVM chain id.\n * @returns EIP-712 domain with `name`, `version`, `chainId`, and checksummed `verifyingContract`.\n */\nexport function getBatchSettlementEip712Domain(chainId: number) {\n return {\n ...BATCH_SETTLEMENT_DOMAIN,\n chainId,\n verifyingContract: getAddress(BATCH_SETTLEMENT_ADDRESS),\n } as const;\n}\n","/** Error codes for the batch-settlement EVM scheme (see scheme_batch_settlement_evm2.md). */\n\nexport const ErrChannelNotFound = \"invalid_batch_settlement_evm_channel_not_found\";\nexport const ErrTokenMismatch = \"invalid_batch_settlement_evm_token_mismatch\";\nexport const ErrInvalidVoucherSignature = \"invalid_batch_settlement_evm_voucher_signature\";\nexport const ErrCumulativeExceedsBalance =\n \"invalid_batch_settlement_evm_cumulative_exceeds_balance\";\nexport const ErrCumulativeAmountBelowClaimed =\n \"invalid_batch_settlement_evm_cumulative_below_claimed\";\nexport const ErrInsufficientBalance = \"invalid_batch_settlement_evm_insufficient_balance\";\nexport const ErrDepositTransactionFailed =\n \"invalid_batch_settlement_evm_deposit_transaction_failed\";\nexport const ErrClaimTransactionFailed = \"invalid_batch_settlement_evm_claim_transaction_failed\";\nexport const ErrSettleTransactionFailed = \"invalid_batch_settlement_evm_settle_transaction_failed\";\nexport const ErrInvalidScheme = \"invalid_batch_settlement_evm_scheme\";\nexport const ErrNetworkMismatch = \"invalid_batch_settlement_evm_network_mismatch\";\nexport const ErrMissingEip712Domain = \"invalid_batch_settlement_evm_missing_eip712_domain\";\nexport const ErrValidBeforeExpired =\n \"invalid_batch_settlement_evm_payload_authorization_valid_before\";\nexport const ErrValidAfterInFuture =\n \"invalid_batch_settlement_evm_payload_authorization_valid_after\";\nexport const ErrInvalidReceiveAuthorizationSignature =\n \"invalid_batch_settlement_evm_receive_authorization_signature\";\nexport const ErrErc3009AuthorizationRequired =\n \"invalid_batch_settlement_evm_erc3009_authorization_required\";\nexport const ErrRefundTransactionFailed = \"invalid_batch_settlement_evm_refund_transaction_failed\";\nexport const ErrInvalidPayloadType = \"invalid_batch_settlement_evm_payload_type\";\nexport const ErrWithdrawDelayOutOfRange =\n \"invalid_batch_settlement_evm_withdraw_delay_out_of_range\";\nexport const ErrChannelIdMismatch = \"invalid_batch_settlement_evm_channel_id_mismatch\";\nexport const ErrReceiverMismatch = \"invalid_batch_settlement_evm_receiver_mismatch\";\nexport const ErrReceiverAuthorizerMismatch =\n \"invalid_batch_settlement_evm_receiver_authorizer_mismatch\";\nexport const ErrWithdrawDelayMismatch = \"invalid_batch_settlement_evm_withdraw_delay_mismatch\";\nexport const ErrAuthorizerAddressMismatch =\n \"invalid_batch_settlement_evm_authorizer_address_mismatch\";\nexport const ErrAuthorizerNotConfigured = \"invalid_batch_settlement_evm_authorizer_not_configured\";\nexport const ErrDepositSimulationFailed = \"invalid_batch_settlement_evm_deposit_simulation_failed\";\n\n// ERC-6492 counterfactual deployment errors (ERC-3009 deposit path). Wire values keep the\n// scheme prefix to match the rest of this module's contract.\nexport const ErrFactoryNotAllowed = \"invalid_batch_settlement_evm_eip6492_factory_not_allowed\";\nexport const ErrSmartWalletDeploymentFailed =\n \"invalid_batch_settlement_evm_smart_wallet_deployment_failed\";\nexport const ErrClaimSimulationFailed = \"invalid_batch_settlement_evm_claim_simulation_failed\";\nexport const ErrSettleSimulationFailed = \"invalid_batch_settlement_evm_settle_simulation_failed\";\nexport const ErrNothingToSettle = \"invalid_batch_settlement_evm_nothing_to_settle\";\nexport const ErrRefundPayload = \"invalid_batch_settlement_evm_refund_payload\";\nexport const ErrRefundSimulationFailed = \"invalid_batch_settlement_evm_refund_simulation_failed\";\nexport const ErrRpcReadFailed = \"invalid_batch_settlement_evm_rpc_read_failed\";\nexport const ErrPermit2AuthorizationRequired =\n \"invalid_batch_settlement_evm_permit2_authorization_required\";\nexport const ErrPermit2InvalidSpender = \"invalid_batch_settlement_evm_permit2_invalid_spender\";\nexport const ErrPermit2AmountMismatch = \"invalid_batch_settlement_evm_permit2_amount_mismatch\";\nexport const ErrPermit2DeadlineExpired = \"invalid_batch_settlement_evm_permit2_deadline_expired\";\nexport const ErrPermit2InvalidSignature = \"invalid_batch_settlement_evm_permit2_invalid_signature\";\nexport const ErrPermit2AllowanceRequired =\n \"invalid_batch_settlement_evm_permit2_allowance_required\";\nexport const ErrEip2612AmountMismatch = \"invalid_batch_settlement_evm_eip2612_amount_mismatch\";\nexport const ErrEip2612OwnerMismatch = \"invalid_batch_settlement_evm_eip2612_owner_mismatch\";\nexport const ErrEip2612AssetMismatch = \"invalid_batch_settlement_evm_eip2612_asset_mismatch\";\nexport const ErrEip2612SpenderMismatch = \"invalid_batch_settlement_evm_eip2612_spender_mismatch\";\nexport const ErrEip2612DeadlineExpired = \"invalid_batch_settlement_evm_eip2612_deadline_expired\";\nexport const ErrErc20ApprovalUnavailable =\n \"invalid_batch_settlement_evm_erc20_approval_unavailable\";\n\n/** Resource server: 402 `error` and lifecycle `reason` (same strings as the spec). */\nexport const ErrCumulativeAmountMismatch =\n \"invalid_batch_settlement_evm_cumulative_amount_mismatch\";\nexport const ErrChannelBusy = \"invalid_batch_settlement_evm_channel_busy\";\nexport const ErrChargeExceedsSignedCumulative =\n \"invalid_batch_settlement_evm_charge_exceeds_signed_cumulative\";\nexport const ErrMissingChannel = \"invalid_batch_settlement_evm_missing_channel\";\nexport const ErrRefundNoBalance = \"invalid_batch_settlement_evm_refund_no_balance\";\nexport const ErrRefundAmountInvalid = \"invalid_batch_settlement_evm_refund_amount_invalid\";\n","export const channelConfigComponents = [\n { name: \"payer\", type: \"address\" },\n { name: \"payerAuthorizer\", type: \"address\" },\n { name: \"receiver\", type: \"address\" },\n { name: \"receiverAuthorizer\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"withdrawDelay\", type: \"uint40\" },\n { name: \"salt\", type: \"bytes32\" },\n] as const;\n\nconst voucherClaimComponents = [\n {\n name: \"voucher\",\n type: \"tuple\",\n components: [\n {\n name: \"channel\",\n type: \"tuple\",\n components: channelConfigComponents,\n },\n { name: \"maxClaimableAmount\", type: \"uint128\" },\n ],\n },\n { name: \"signature\", type: \"bytes\" },\n { name: \"totalClaimed\", type: \"uint128\" },\n] as const;\n\nexport const batchSettlementABI = [\n {\n type: \"function\",\n name: \"multicall\",\n inputs: [{ name: \"data\", type: \"bytes[]\" }],\n outputs: [{ name: \"results\", type: \"bytes[]\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"deposit\",\n inputs: [\n { name: \"config\", type: \"tuple\", components: channelConfigComponents },\n { name: \"amount\", type: \"uint128\" },\n { name: \"collector\", type: \"address\" },\n { name: \"collectorData\", type: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"claim\",\n inputs: [{ name: \"voucherClaims\", type: \"tuple[]\", components: voucherClaimComponents }],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"claimWithSignature\",\n inputs: [\n { name: \"voucherClaims\", type: \"tuple[]\", components: voucherClaimComponents },\n { name: \"authorizerSignature\", type: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"settle\",\n inputs: [\n { name: \"receiver\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"initiateWithdraw\",\n inputs: [\n { name: \"config\", type: \"tuple\", components: channelConfigComponents },\n { name: \"amount\", type: \"uint128\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"finalizeWithdraw\",\n inputs: [{ name: \"config\", type: \"tuple\", components: channelConfigComponents }],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"refund\",\n inputs: [\n { name: \"config\", type: \"tuple\", components: channelConfigComponents },\n { name: \"amount\", type: \"uint128\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"refundWithSignature\",\n inputs: [\n { name: \"config\", type: \"tuple\", components: channelConfigComponents },\n { name: \"amount\", type: \"uint128\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"receiverAuthorizerSignature\", type: \"bytes\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getChannelId\",\n inputs: [{ name: \"config\", type: \"tuple\", components: channelConfigComponents }],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"CHANNEL_CONFIG_TYPEHASH\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"channels\",\n inputs: [{ name: \"channelId\", type: \"bytes32\" }],\n outputs: [\n { name: \"balance\", type: \"uint128\" },\n { name: \"totalClaimed\", type: \"uint128\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"pendingWithdrawals\",\n inputs: [{ name: \"channelId\", type: \"bytes32\" }],\n outputs: [\n { name: \"amount\", type: \"uint128\" },\n { name: \"initiatedAt\", type: \"uint40\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"receivers\",\n inputs: [\n { name: \"receiver\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n ],\n outputs: [\n { name: \"totalClaimed\", type: \"uint128\" },\n { name: \"totalSettled\", type: \"uint128\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getVoucherDigest\",\n inputs: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"maxClaimableAmount\", type: \"uint128\" },\n ],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getRefundDigest\",\n inputs: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"amount\", type: \"uint128\" },\n ],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"refundNonce\",\n inputs: [{ name: \"channelId\", type: \"bytes32\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getClaimBatchDigest\",\n inputs: [{ name: \"voucherClaims\", type: \"tuple[]\", components: voucherClaimComponents }],\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"event\",\n name: \"Settled\",\n inputs: [\n { name: \"receiver\", type: \"address\", indexed: true },\n { name: \"token\", type: \"address\", indexed: true },\n { name: \"sender\", type: \"address\", indexed: true },\n { name: \"amount\", type: \"uint128\", indexed: false },\n ],\n anonymous: false,\n },\n] as const;\n\nexport const erc20BalanceOfABI = [\n {\n type: \"function\",\n name: \"balanceOf\",\n inputs: [{ name: \"account\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n },\n] as const;\n","import type {\n FacilitatorContext,\n FacilitatorExtension,\n PaymentPayload,\n PaymentRequirements,\n} from \"@x402/core/types\";\nimport type { Hex } from \"viem\";\n\nexport const BUILDER_CODE_KEY = \"builder-code\" as const;\n\nexport interface DataSuffixContext {\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n}\n\nexport interface BuilderCodeFacilitatorExtension extends FacilitatorExtension {\n key: typeof BUILDER_CODE_KEY;\n buildDataSuffix?(ctx: DataSuffixContext): Hex | undefined | Promise<Hex | undefined>;\n}\n\ntype DataSuffixResolver = (\n context: FacilitatorContext,\n ctx: DataSuffixContext,\n) => Promise<Hex | undefined>;\n\nconst BUILDER_CODE_RESOLVER: DataSuffixResolver = async (context, ctx) => {\n const ext = context.getExtension<BuilderCodeFacilitatorExtension>(BUILDER_CODE_KEY);\n if (!ext?.buildDataSuffix) {\n return undefined;\n }\n\n return ext.buildDataSuffix(ctx);\n};\n\nconst DATA_SUFFIX_RESOLVERS: DataSuffixResolver[] = [BUILDER_CODE_RESOLVER];\n\n/**\n * Resolves and concatenates data suffixes from registered extensions.\n *\n * @param context - Facilitator context with registered extensions\n * @param ctx - Data suffix context passed to extension resolvers\n * @returns Hex-encoded suffix to append to settlement calldata, or undefined if none\n */\nexport async function resolveDataSuffix(\n context: FacilitatorContext | undefined,\n ctx: DataSuffixContext,\n): Promise<Hex | undefined> {\n if (!context) {\n return undefined;\n }\n\n const parts: Hex[] = [];\n for (const resolver of DATA_SUFFIX_RESOLVERS) {\n const suffix = await resolver(context, ctx);\n if (suffix && suffix !== \"0x\" && suffix.length > 2) {\n parts.push(suffix);\n }\n }\n\n if (parts.length === 0) {\n return undefined;\n }\n\n if (parts.length === 1) {\n return parts[0];\n }\n\n return parts.reduce((acc, part, index) => {\n if (index === 0) {\n return part;\n }\n const stripped = part.startsWith(\"0x\") ? part.slice(2) : part;\n return `${acc}${stripped}` as Hex;\n });\n}\n\n/**\n * Appends a hex data suffix to encoded contract calldata.\n *\n * @param calldata - Base encoded function calldata\n * @param suffix - Optional hex suffix (with or without 0x prefix)\n * @returns Calldata with suffix appended, or the original calldata when suffix is empty\n */\nexport function appendDataSuffix(calldata: Hex, suffix?: Hex): Hex {\n if (!suffix || suffix === \"0x\" || suffix.length <= 2) {\n return calldata;\n }\n const suffixHex = suffix.startsWith(\"0x\") ? suffix.slice(2) : suffix;\n return `${calldata}${suffixHex}` as Hex;\n}\n","import type { PaymentPayload } from \"@x402/core/types\";\nimport type { FacilitatorEvmSigner } from \"../signer\";\n\nexport const EIP2612_GAS_SPONSORING_KEY = \"eip2612GasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_KEY = \"erc20ApprovalGasSponsoring\" as const;\nexport const ERC20_APPROVAL_GAS_SPONSORING_VERSION = \"1\" as const;\n\nexport interface Eip2612GasSponsoringInfo {\n [key: string]: unknown;\n from: string;\n asset: string;\n spender: string;\n amount: string;\n nonce: string;\n deadline: string;\n signature: string;\n version: string;\n}\n\nexport interface Erc20ApprovalGasSponsoringInfo {\n [key: string]: unknown;\n from: `0x${string}`;\n asset: `0x${string}`;\n spender: `0x${string}`;\n amount: string;\n signedTransaction: `0x${string}`;\n version: string;\n}\n\n/**\n * A single transaction to be executed by the signer.\n * - `0x${string}`: a pre-signed serialized transaction (broadcast as-is via sendRawTransaction)\n * - `{ to, data, gas? }`: an unsigned call intent (signer signs and broadcasts)\n */\nexport type TransactionRequest =\n | `0x${string}`\n | { to: `0x${string}`; data: `0x${string}`; gas?: bigint };\n\nexport type Erc20ApprovalGasSponsoringSigner = FacilitatorEvmSigner & {\n sendTransactions(transactions: TransactionRequest[]): Promise<`0x${string}`[]>;\n simulateTransactions?(transactions: TransactionRequest[]): Promise<boolean>;\n};\n\nexport interface Erc20ApprovalGasSponsoringFacilitatorExtension {\n key: typeof ERC20_APPROVAL_GAS_SPONSORING_KEY;\n signer?: Erc20ApprovalGasSponsoringSigner;\n signerForNetwork?: (network: string) => Erc20ApprovalGasSponsoringSigner | undefined;\n}\n\n/**\n * Extracts a typed `info` payload from an extension entry.\n *\n * @param payload - Payment payload containing optional extensions.\n * @param extensionKey - Extension key to extract.\n * @returns The extension `info` object when present; otherwise null.\n */\nfunction _extractInfo(\n payload: PaymentPayload,\n extensionKey: string,\n): Record<string, unknown> | null {\n const extensions = payload.extensions;\n if (!extensions) return null;\n const extension = extensions[extensionKey] as { info?: Record<string, unknown> } | undefined;\n if (!extension?.info) return null;\n return extension.info;\n}\n\n/**\n * Extracts and validates required EIP-2612 gas sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed EIP-2612 gas sponsoring info when available and complete.\n */\nexport function extractEip2612GasSponsoringInfo(\n payload: PaymentPayload,\n): Eip2612GasSponsoringInfo | null {\n const info = _extractInfo(payload, EIP2612_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.nonce ||\n !info.deadline ||\n !info.signature ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Eip2612GasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of EIP-2612 sponsoring info.\n *\n * @param info - EIP-2612 extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateEip2612GasSponsoringInfo(info: Eip2612GasSponsoringInfo): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n numericPattern.test(info.nonce) &&\n numericPattern.test(info.deadline) &&\n hexPattern.test(info.signature) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Extracts and validates required ERC-20 approval sponsoring fields.\n *\n * @param payload - Payment payload returned by the client scheme.\n * @returns Parsed ERC-20 approval sponsoring info when available and complete.\n */\nexport function extractErc20ApprovalGasSponsoringInfo(\n payload: PaymentPayload,\n): Erc20ApprovalGasSponsoringInfo | null {\n const info = _extractInfo(payload, ERC20_APPROVAL_GAS_SPONSORING_KEY);\n if (!info) return null;\n if (\n !info.from ||\n !info.asset ||\n !info.spender ||\n !info.amount ||\n !info.signedTransaction ||\n !info.version\n ) {\n return null;\n }\n return info as unknown as Erc20ApprovalGasSponsoringInfo;\n}\n\n/**\n * Validates the structure and formatting of ERC-20 approval sponsoring info.\n *\n * @param info - ERC-20 approval extension info to validate.\n * @returns True when all required fields match expected patterns.\n */\nexport function validateErc20ApprovalGasSponsoringInfo(\n info: Erc20ApprovalGasSponsoringInfo,\n): boolean {\n const addressPattern = /^0x[a-fA-F0-9]{40}$/;\n const numericPattern = /^[0-9]+$/;\n const hexPattern = /^0x[a-fA-F0-9]+$/;\n const versionPattern = /^[0-9]+(\\.[0-9]+)*$/;\n return (\n addressPattern.test(info.from) &&\n addressPattern.test(info.asset) &&\n addressPattern.test(info.spender) &&\n numericPattern.test(info.amount) &&\n hexPattern.test(info.signedTransaction) &&\n versionPattern.test(info.version)\n );\n}\n\n/**\n * Resolves the ERC-20 approval extension signer for a specific network.\n *\n * @param extension - Optional facilitator extension config.\n * @param network - CAIP-2 network identifier.\n * @returns A network-specific signer when available, else the default signer.\n */\nexport function resolveErc20ApprovalExtensionSigner(\n extension: Erc20ApprovalGasSponsoringFacilitatorExtension | undefined,\n network: string,\n): Erc20ApprovalGasSponsoringSigner | undefined {\n if (!extension) return undefined;\n return extension.signerForNetwork?.(network) ?? extension.signer;\n}\n","import type {\n PaymentRequirements,\n PaymentPayloadResult,\n PaymentPayloadContext,\n} from \"@x402/core/types\";\nimport {\n EIP2612_GAS_SPONSORING_KEY,\n ERC20_APPROVAL_GAS_SPONSORING_KEY,\n} from \"../../exact/extensions\";\nimport { getAddress } from \"viem\";\nimport { PERMIT2_ADDRESS, erc20AllowanceAbi } from \"../../constants\";\nimport { getEvmChainId } from \"../../utils\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { signEip2612Permit } from \"../../exact/client/eip2612\";\nimport { signErc20ApprovalTransaction } from \"../../exact/client/erc20approval\";\nimport { resolveExtensionRpcCapabilities, type ExactEvmSchemeOptions } from \"../rpc\";\n\n/**\n * Attempts to sign an EIP-2612 permit for gasless Permit2 approval.\n *\n * @param signer - The EVM client signer\n * @param options - Optional RPC configuration for backfilling capabilities\n * @param requirements - The payment requirements from the server\n * @param result - The payment payload result from the scheme\n * @param context - Optional context containing server extensions and metadata\n * @param approvalAmount - Optional amount to approve instead of `requirements.amount`\n * @returns Extension data for EIP-2612 gas sponsoring, or undefined if not applicable\n */\nexport async function trySignEip2612PermitExtension(\n signer: ClientEvmSigner,\n options: ExactEvmSchemeOptions | undefined,\n requirements: PaymentRequirements,\n result: PaymentPayloadResult,\n context?: PaymentPayloadContext,\n approvalAmount?: string,\n): Promise<Record<string, unknown> | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n const tokenName = requirements.extra?.name as string | undefined;\n const tokenVersion = requirements.extra?.version as string | undefined;\n if (!tokenName || !tokenVersion) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n const requiredAllowance = approvalAmount ?? requirements.amount;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requiredAllowance)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const permit2Auth = result.payload?.permit2Authorization as Record<string, unknown> | undefined;\n const deadline =\n (permit2Auth?.deadline as string) ??\n Math.floor(Date.now() / 1000 + requirements.maxTimeoutSeconds).toString();\n\n const info = await signEip2612Permit(\n {\n address: signer.address,\n signTypedData: msg => signer.signTypedData(msg),\n readContract: capabilities.readContract,\n },\n tokenAddress,\n tokenName,\n tokenVersion,\n chainId,\n deadline,\n requiredAllowance,\n );\n\n return {\n [EIP2612_GAS_SPONSORING_KEY]: { info },\n };\n}\n\n/**\n * Attempts to sign an ERC-20 approval transaction for gasless Permit2 approval.\n *\n * @param signer - The EVM client signer\n * @param options - Optional RPC configuration for backfilling capabilities\n * @param requirements - The payment requirements from the server\n * @param context - Optional context containing server extensions and metadata\n * @param approvalAmount - Optional amount to check for Permit2 allowance\n * @returns Extension data for ERC-20 approval gas sponsoring, or undefined if not applicable\n */\nexport async function trySignErc20ApprovalExtension(\n signer: ClientEvmSigner,\n options: ExactEvmSchemeOptions | undefined,\n requirements: PaymentRequirements,\n context?: PaymentPayloadContext,\n approvalAmount?: string,\n): Promise<Record<string, unknown> | undefined> {\n const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);\n\n if (!capabilities.readContract) {\n return undefined;\n }\n\n if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {\n return undefined;\n }\n\n if (!capabilities.signTransaction || !capabilities.getTransactionCount) {\n return undefined;\n }\n\n const chainId = getEvmChainId(requirements.network);\n const tokenAddress = getAddress(requirements.asset) as `0x${string}`;\n const requiredAllowance = approvalAmount ?? requirements.amount;\n\n try {\n const allowance = (await capabilities.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [signer.address, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requiredAllowance)) {\n return undefined;\n }\n } catch {\n // Allowance check failed, proceed with signing\n }\n\n const info = await signErc20ApprovalTransaction(\n {\n address: signer.address,\n signTransaction: capabilities.signTransaction,\n getTransactionCount: capabilities.getTransactionCount,\n estimateFeesPerGas: capabilities.estimateFeesPerGas,\n },\n tokenAddress,\n chainId,\n );\n\n return {\n [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info },\n };\n}\n","import { getAddress } from \"viem\";\nimport { eip2612PermitTypes, eip2612NoncesAbi, PERMIT2_ADDRESS } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport type { Eip2612GasSponsoringInfo } from \"../extensions\";\n\nexport type Eip2612PermitSigner = Pick<ClientEvmSigner, \"address\" | \"signTypedData\"> & {\n readContract: NonNullable<ClientEvmSigner[\"readContract\"]>;\n};\n\n/**\n * Signs an EIP-2612 permit authorizing the Permit2 contract to spend tokens.\n *\n * This creates a gasless off-chain signature that the facilitator can submit\n * on-chain via `x402Permit2Proxy.settleWithPermit()`.\n *\n * The `permittedAmount` must match the Permit2 `permitted.amount` exactly, as the\n * proxy contract enforces `permit2612.value == permittedAmount`.\n *\n * @param signer - The client EVM signer (must support readContract for nonce query)\n * @param tokenAddress - The ERC-20 token contract address\n * @param tokenName - The token name (from paymentRequirements.extra.name)\n * @param tokenVersion - The token version (from paymentRequirements.extra.version)\n * @param chainId - The chain ID\n * @param deadline - The deadline for the permit (unix timestamp as string)\n * @param permittedAmount - The Permit2 permitted amount (must match exactly)\n * @returns The EIP-2612 gas sponsoring info object\n */\nexport async function signEip2612Permit(\n signer: Eip2612PermitSigner,\n tokenAddress: `0x${string}`,\n tokenName: string,\n tokenVersion: string,\n chainId: number,\n deadline: string,\n permittedAmount: string,\n): Promise<Eip2612GasSponsoringInfo> {\n const owner = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Query the current EIP-2612 nonce from the token contract\n const nonce = (await signer.readContract({\n address: tokenAddress,\n abi: eip2612NoncesAbi,\n functionName: \"nonces\",\n args: [owner],\n })) as bigint;\n\n // Construct EIP-712 domain for the token's permit function\n const domain = {\n name: tokenName,\n version: tokenVersion,\n chainId,\n verifyingContract: tokenAddress,\n };\n\n const approvalAmount = BigInt(permittedAmount);\n\n const message = {\n owner,\n spender,\n value: approvalAmount,\n nonce,\n deadline: BigInt(deadline),\n };\n\n // Sign the EIP-2612 permit\n const signature = await signer.signTypedData({\n domain,\n types: eip2612PermitTypes,\n primaryType: \"Permit\",\n message,\n });\n\n return {\n from: owner,\n asset: tokenAddress,\n spender,\n amount: approvalAmount.toString(),\n nonce: nonce.toString(),\n deadline,\n signature,\n version: \"1\",\n };\n}\n","import { encodeFunctionData, getAddress, maxUint256 } from \"viem\";\nimport {\n PERMIT2_ADDRESS,\n erc20ApproveAbi,\n ERC20_APPROVE_GAS_LIMIT,\n DEFAULT_MAX_FEE_PER_GAS,\n DEFAULT_MAX_PRIORITY_FEE_PER_GAS,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport {\n ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n type Erc20ApprovalGasSponsoringInfo,\n} from \"../extensions\";\n\nexport type Erc20ApprovalTxSigner = Pick<ClientEvmSigner, \"address\"> & {\n signTransaction: NonNullable<ClientEvmSigner[\"signTransaction\"]>;\n getTransactionCount: NonNullable<ClientEvmSigner[\"getTransactionCount\"]>;\n estimateFeesPerGas?: NonNullable<ClientEvmSigner[\"estimateFeesPerGas\"]>;\n};\n\n/**\n * Signs an EIP-1559 `approve(Permit2, MaxUint256)` transaction for the given token.\n *\n * The signed transaction is NOT broadcast here — the facilitator broadcasts it\n * atomically before settling the Permit2 payment. This enables Permit2 payments\n * for generic ERC-20 tokens that do NOT implement EIP-2612.\n *\n * Always approves MaxUint256 regardless of the payment amount.\n *\n * @param signer - The client EVM signer (must support signTransaction, getTransactionCount)\n * @param tokenAddress - The ERC-20 token contract address\n * @param chainId - The chain ID\n * @returns The ERC-20 approval gas sponsoring info object\n */\nexport async function signErc20ApprovalTransaction(\n signer: Erc20ApprovalTxSigner,\n tokenAddress: `0x${string}`,\n chainId: number,\n): Promise<Erc20ApprovalGasSponsoringInfo> {\n const from = signer.address;\n const spender = getAddress(PERMIT2_ADDRESS);\n\n // Encode approve(PERMIT2_ADDRESS, MaxUint256) calldata\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [spender, maxUint256],\n });\n\n // Get current nonce for the sender\n const nonce = await signer.getTransactionCount({ address: from });\n\n // Get current fee estimates, with fallback values\n let maxFeePerGas: bigint;\n let maxPriorityFeePerGas: bigint;\n try {\n const fees = await signer.estimateFeesPerGas?.();\n if (!fees) {\n throw new Error(\"no fee estimates available\");\n }\n maxFeePerGas = fees.maxFeePerGas;\n maxPriorityFeePerGas = fees.maxPriorityFeePerGas;\n } catch {\n maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;\n maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;\n }\n\n // Sign the EIP-1559 transaction (not broadcast)\n const signedTransaction = await signer.signTransaction({\n to: tokenAddress,\n data,\n nonce,\n gas: ERC20_APPROVE_GAS_LIMIT,\n maxFeePerGas,\n maxPriorityFeePerGas,\n chainId,\n });\n\n return {\n from,\n asset: tokenAddress,\n spender,\n amount: maxUint256.toString(),\n signedTransaction,\n version: ERC20_APPROVAL_GAS_SPONSORING_VERSION,\n };\n}\n","import { createPublicClient, http } from \"viem\";\nimport type { ClientEvmSigner } from \"../signer\";\nimport { getEvmChainId } from \"../utils\";\n\nexport type EvmSchemeConfig = {\n rpcUrl?: string;\n};\n\nexport type EvmSchemeConfigByChainId = Record<number, EvmSchemeConfig>;\n\nexport type EvmSchemeOptions = EvmSchemeConfig | EvmSchemeConfigByChainId;\n\n/** @deprecated Use EvmSchemeConfig */\nexport type ExactEvmSchemeConfig = EvmSchemeConfig;\n/** @deprecated Use EvmSchemeConfigByChainId */\nexport type ExactEvmSchemeConfigByChainId = EvmSchemeConfigByChainId;\n/** @deprecated Use EvmSchemeOptions */\nexport type ExactEvmSchemeOptions = EvmSchemeOptions;\n\ntype ExtensionRpcCapabilities = Pick<\n ClientEvmSigner,\n \"readContract\" | \"signTransaction\" | \"getTransactionCount\" | \"estimateFeesPerGas\"\n>;\n\nconst rpcClientCache = new Map<string, ReturnType<typeof createPublicClient>>();\n\n/**\n * Check if options is a per-chain-id configuration map.\n *\n * @param options - The EVM scheme options to check\n * @returns True if the options are keyed by chain ID\n */\nfunction isConfigByChainId(options: EvmSchemeOptions): options is EvmSchemeConfigByChainId {\n const keys = Object.keys(options);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n\n/**\n * Get or create a cached viem public client for the given RPC URL.\n *\n * @param rpcUrl - The JSON-RPC endpoint URL\n * @returns A viem PublicClient instance\n */\nfunction getRpcClient(rpcUrl: string): ReturnType<typeof createPublicClient> {\n const existing = rpcClientCache.get(rpcUrl);\n if (existing) {\n return existing;\n }\n\n const client = createPublicClient({\n transport: http(rpcUrl),\n });\n rpcClientCache.set(rpcUrl, client);\n return client;\n}\n\n/**\n * Resolve an RPC URL from scheme options for the given network.\n *\n * @param network - The CAIP-2 network identifier\n * @param options - Optional EVM scheme options (flat or per-chain-id)\n * @returns The resolved RPC URL, or undefined if not configured\n */\nexport function resolveRpcUrl(network: string, options?: EvmSchemeOptions): string | undefined {\n if (!options) {\n return undefined;\n }\n\n if (isConfigByChainId(options)) {\n const chainId = getEvmChainId(network);\n const optionsByChainId = options as EvmSchemeConfigByChainId;\n return optionsByChainId[chainId]?.rpcUrl;\n }\n\n return (options as EvmSchemeConfig).rpcUrl;\n}\n\n/**\n * Resolve RPC capabilities for extensions, backfilling from a public RPC client when the signer lacks them.\n *\n * @param network - The CAIP-2 network identifier\n * @param signer - The client EVM signer\n * @param options - Optional EVM scheme options for RPC URL resolution\n * @returns Extension RPC capabilities (readContract, signTransaction, etc.)\n */\nexport function resolveExtensionRpcCapabilities(\n network: string,\n signer: ClientEvmSigner,\n options?: EvmSchemeOptions,\n): ExtensionRpcCapabilities {\n const capabilities: ExtensionRpcCapabilities = {\n signTransaction: signer.signTransaction,\n readContract: signer.readContract,\n getTransactionCount: signer.getTransactionCount,\n estimateFeesPerGas: signer.estimateFeesPerGas,\n };\n\n const needsRpcBackfill =\n !capabilities.readContract ||\n !capabilities.getTransactionCount ||\n !capabilities.estimateFeesPerGas;\n if (!needsRpcBackfill) {\n return capabilities;\n }\n\n const rpcUrl = resolveRpcUrl(network, options);\n if (!rpcUrl) {\n return capabilities;\n }\n const rpcClient = getRpcClient(rpcUrl);\n if (!capabilities.readContract) {\n capabilities.readContract = args => rpcClient.readContract(args as never) as Promise<unknown>;\n }\n if (!capabilities.getTransactionCount) {\n capabilities.getTransactionCount = async args =>\n rpcClient.getTransactionCount({ address: args.address });\n }\n if (!capabilities.estimateFeesPerGas) {\n capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();\n }\n\n return capabilities;\n}\n","import {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { ClientEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { createNonce } from \"../../../utils\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\n\n/**\n * EVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClientV1 instance.\n *\n * @param signer - The EVM signer for client operations\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick<PaymentPayload, \"x402Version\" | \"payload\"> & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEvmPayloadV1[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(selectedV1.payTo),\n value: selectedV1.maxAmountRequired,\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Sign the authorization\n const signature = await this.signAuthorization(authorization, selectedV1);\n\n const payload: ExactEvmPayloadV1 = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV1[\"authorization\"],\n requirements: PaymentRequirementsV1,\n ): Promise<`0x${string}`> {\n const chainId = getEvmChainIdV1(requirements.network as EvmNetworkV1);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n","import {\n PaymentPayload,\n PaymentPayloadV1,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n FacilitatorContext,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport { resolveDataSuffix } from \"../../../shared/extensions\";\nimport { verifyTypedDataSignature, classifyErc6492Payer } from \"../../../shared/verifySignature\";\nimport { PaymentRequirementsV1 } from \"@x402/core/types/v1\";\nimport { getAddress, Hex, isAddressEqual, parseErc6492Signature } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { FacilitatorEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { EvmNetworkV1, getEvmChainIdV1 } from \"../../../v1\";\nimport * as Errors from \"../../facilitator/errors\";\nimport {\n diagnoseEip3009SimulationFailure,\n executeTransferWithAuthorization,\n simulateEip3009Transfer,\n} from \"../../facilitator/eip3009-utils\";\n\nexport interface VerifyV1Options {\n /** Run onchain simulation. Defaults to true. */\n simulate?: boolean;\n}\n\nexport interface ExactEvmSchemeV1Config {\n /**\n * Allowlist of factory contract addresses (hex strings, case-insensitive) that the facilitator\n * will call when deploying an undeployed smart wallet via ERC-6492.\n *\n * A non-empty list enables ERC-4337 smart wallet deployment via EIP-6492. Facilitators must\n * explicitly list every factory they trust to prevent arbitrary transaction injection via\n * attacker-controlled ERC-6492 signature wrappers. An empty or omitted list denies all factory\n * deployment calls.\n *\n * @default []\n */\n eip6492AllowedFactories?: string[];\n /**\n * If enabled, simulates transaction before settling. Defaults to false, ie only simulate during verify.\n *\n * @default false\n */\n simulateInSettle?: boolean;\n}\n\n/**\n * EVM facilitator implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required<ExactEvmSchemeV1Config>;\n\n /**\n * Creates a new ExactEvmFacilitatorV1 instance.\n *\n * @param signer - The EVM signer for facilitator operations\n * @param config - Optional configuration for the facilitator\n */\n constructor(\n private readonly signer: FacilitatorEvmSigner,\n config?: ExactEvmSchemeV1Config,\n ) {\n this.config = {\n eip6492AllowedFactories: config?.eip6492AllowedFactories ?? [],\n simulateInSettle: config?.simulateInSettle ?? false,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * For EVM, no extra data is needed.\n *\n * @param _ - The network identifier (unused for EVM)\n * @returns undefined (EVM has no extra data)\n */\n getExtra(_: string): Record<string, unknown> | undefined {\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * Returns all addresses this facilitator can use for signing/settling transactions.\n *\n * @param _ - The network identifier (unused for EVM, addresses are network-agnostic)\n * @returns Array of facilitator wallet addresses\n */\n getSigners(_: string): string[] {\n return [...this.signer.getAddresses()];\n }\n\n /**\n * Verifies a payment payload (V1).\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n return this._verify(payload, requirements);\n }\n\n /**\n * Settles a payment by executing the transfer (V1).\n *\n * @param payload - The payment payload to settle\n * @param requirements - The payment requirements\n * @param context - Optional facilitator context for extension capabilities\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n context?: FacilitatorContext,\n ): Promise<SettleResponse> {\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Re-verify before settling\n const valid = await this._verify(payload, requirements, {\n simulate: this.config.simulateInSettle ?? false,\n });\n if (!valid.isValid) {\n return {\n success: false,\n network: payloadV1.network,\n transaction: \"\",\n errorReason: valid.invalidReason ?? Errors.ErrInvalidScheme,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n try {\n // Parse ERC-6492 signature if applicable (for optional deployment)\n const { address: factoryAddress, data: factoryCalldata } = parseErc6492Signature(\n exactEvmPayload.signature!,\n );\n\n // Deploy ERC-4337 smart wallet via EIP-6492 if factory is in the allowlist\n if (\n factoryAddress &&\n factoryCalldata &&\n !isAddressEqual(factoryAddress, \"0x0000000000000000000000000000000000000000\")\n ) {\n // Check if smart wallet is already deployed\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n const normalizedFactory = factoryAddress.toLowerCase();\n const isAllowed = (this.config.eip6492AllowedFactories ?? []).some(\n allowed => allowed.toLowerCase() === normalizedFactory,\n );\n if (!isAllowed) {\n return {\n success: false,\n errorReason: Errors.ErrFactoryNotAllowed,\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Send the factory calldata directly as a transaction\n // The factoryCalldata already contains the complete encoded function call\n const deployTx = await this.signer.sendTransaction({\n to: factoryAddress as Hex,\n data: factoryCalldata as Hex,\n });\n\n // Wait for deployment and verify it actually succeeded.\n const deployReceipt = await this.signer.waitForTransactionReceipt({ hash: deployTx });\n if (deployReceipt.status !== \"success\") {\n return {\n success: false,\n errorReason: Errors.ErrSmartWalletDeploymentFailed,\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Do NOT re-simulate the transfer here. The authoritative pre-check is the atomic\n // deploy+transfer simulation in verify; a second standalone eth_call after the real\n // deploy tx races the deploy's state propagation across load-balanced RPC nodes and\n // false-rejected valid wallets. The on-chain transferWithAuthorization below is the\n // definitive signature check; a genuinely unsupported inner signature reverts there\n // and is classified by parseEip3009TransferError.\n }\n }\n\n // V1 payloads carry no extensions, so the builder-code suffix can only contain the\n // facilitator's own wallet code (`w`); client app (`a`) and service (`s`) codes are\n // always absent.\n const dataSuffix = await resolveDataSuffix(context, {\n paymentPayload: payload,\n paymentRequirements: requirements,\n });\n\n const tx = await executeTransferWithAuthorization(\n this.signer,\n getAddress(requirements.asset),\n exactEvmPayload,\n dataSuffix,\n );\n\n // Wait for transaction confirmation\n const receipt = await this.signer.waitForTransactionReceipt({ hash: tx });\n\n if (receipt.status !== \"success\") {\n return {\n success: false,\n errorReason: Errors.ErrTransactionFailed,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n success: true,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n } catch (error) {\n return {\n success: false,\n errorReason: error instanceof Error ? error.message : Errors.ErrTransactionFailed,\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n\n /**\n * Internal verify with optional simulation control.\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @param options - Verification options (e.g. simulate)\n * @returns Promise resolving to verification response\n */\n private async _verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n options?: VerifyV1Options,\n ): Promise<VerifyResponse> {\n const requirementsV1 = requirements as unknown as PaymentRequirementsV1;\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n const payer = exactEvmPayload.authorization.from;\n let eip6492Deployment:\n | { factoryAddress: `0x${string}`; factoryCalldata: `0x${string}` }\n | undefined;\n\n // Verify scheme matches\n if (payloadV1.scheme !== \"exact\" || requirements.scheme !== \"exact\") {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidScheme,\n payer,\n };\n }\n\n // Get chain configuration\n let chainId: number;\n try {\n chainId = getEvmChainIdV1(payloadV1.network as EvmNetworkV1);\n } catch {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n return {\n isValid: false,\n invalidReason: Errors.ErrMissingEip712Domain,\n payer,\n };\n }\n\n const { name, version } = requirements.extra as { name: string; version: string };\n const erc20Address = getAddress(requirements.asset);\n\n // Verify network matches\n if (payloadV1.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: Errors.ErrNetworkMismatch,\n payer,\n };\n }\n\n // Build typed data for signature verification\n const permitTypedData = {\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\" as const,\n domain: {\n name,\n version,\n chainId,\n verifyingContract: erc20Address,\n },\n message: {\n from: exactEvmPayload.authorization.from,\n to: exactEvmPayload.authorization.to,\n value: BigInt(exactEvmPayload.authorization.value),\n validAfter: BigInt(exactEvmPayload.authorization.validAfter),\n validBefore: BigInt(exactEvmPayload.authorization.validBefore),\n nonce: exactEvmPayload.authorization.nonce,\n },\n };\n\n const signature = exactEvmPayload.signature!;\n\n // Classify the payer (counterfactual vs deployed) and extract inner sig in one shot.\n const {\n isCounterfactual,\n innerSignature,\n eip6492Deployment: classification6492,\n } = await classifyErc6492Payer(this.signer, signature, payer);\n\n if (classification6492) {\n eip6492Deployment = classification6492;\n }\n\n if (isCounterfactual) {\n // Mirror settle's allowlist gate so verify predicts settle: a counterfactual payment whose\n // factory is not allowlisted is rejected at settle, so reject it here too.\n const factory = classification6492?.factoryAddress;\n const factoryAllowed =\n !!factory &&\n this.config.eip6492AllowedFactories.some(\n a => a.trim().toLowerCase() === factory.toLowerCase(),\n );\n if (!factoryAllowed) {\n return {\n isValid: false,\n invalidReason: Errors.ErrFactoryNotAllowed,\n payer,\n };\n }\n }\n\n if (!isCounterfactual) {\n // Non-counterfactual path: verify using the strict primitive that mirrors\n // on-chain SignatureChecker semantics (ecrecover for EOAs, strict EIP-1271\n // for any address with code). No ECDSA fallback for code addresses.\n const isValid = await verifyTypedDataSignature(this.signer, {\n address: payer,\n ...permitTypedData,\n signature: innerSignature,\n });\n if (!isValid) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidSignature,\n payer,\n };\n }\n }\n // Counterfactual path: defer to on-chain simulation which deploys + verifies atomically.\n\n // Verify payment recipient matches\n if (getAddress(exactEvmPayload.authorization.to) !== getAddress(requirements.payTo)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrRecipientMismatch,\n payer,\n };\n }\n\n // Verify validBefore is in the future (with 6 second buffer for block time)\n const now = Math.floor(Date.now() / 1000);\n if (BigInt(exactEvmPayload.authorization.validBefore) < BigInt(now + 6)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidBeforeExpired,\n payer,\n };\n }\n\n // Verify validAfter is not in the future\n if (BigInt(exactEvmPayload.authorization.validAfter) > BigInt(now)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrValidAfterInFuture,\n payer,\n };\n }\n\n // Verify amount exactly matches requirements\n if (BigInt(exactEvmPayload.authorization.value) !== BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrInvalidAuthorizationValue,\n payer,\n };\n }\n\n // Transaction simulation\n if (options?.simulate !== false) {\n const simulationSucceeded = await simulateEip3009Transfer(\n this.signer,\n erc20Address,\n exactEvmPayload,\n eip6492Deployment,\n );\n if (!simulationSucceeded) {\n return diagnoseEip3009SimulationFailure(\n this.signer,\n erc20Address,\n exactEvmPayload,\n requirements,\n requirementsV1.maxAmountRequired,\n );\n }\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer,\n };\n }\n}\n","import { PaymentRequirements, VerifyResponse } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress, Hex, parseErc6492Signature, parseSignature } from \"viem\";\nimport { eip3009ABI } from \"../../constants\";\nimport { multicall, ContractCall, RawContractCall } from \"../../multicall\";\nimport { FacilitatorEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport * as Errors from \"./errors\";\n\nexport interface Eip6492Deployment {\n factoryAddress: `0x${string}`;\n factoryCalldata: `0x${string}`;\n}\n\n/**\n * Outcome of a transfer simulation. `error` is populated only when the underlying `eth_call`\n * threw (revert or transport), letting callers distinguish a contract revert from an RPC failure.\n */\nexport interface SimulateEip3009Result {\n ok: boolean;\n error?: unknown;\n}\n\n/**\n * Simulates transferWithAuthorization via eth_call.\n * Returns true if simulation succeeded, false if it failed.\n *\n * @param signer - EVM signer for contract reads\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n * @param eip6492Deployment - Optional EIP-6492 factory info for undeployed smart wallets\n *\n * @returns true if simulation succeeded, false if it failed\n */\nexport async function simulateEip3009Transfer(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n eip6492Deployment?: Eip6492Deployment,\n): Promise<boolean> {\n return (await simulateEip3009TransferResult(signer, erc20Address, payload, eip6492Deployment)).ok;\n}\n\n/**\n * Like {@link simulateEip3009Transfer} but returns the thrown error (if any) alongside the\n * boolean outcome, so callers can tell a contract revert apart from a transport/RPC failure.\n *\n * @param signer - EVM signer for contract reads\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n * @param eip6492Deployment - Optional EIP-6492 factory info for undeployed smart wallets\n * @returns The simulation outcome and, on failure via a thrown error, that error.\n */\nexport async function simulateEip3009TransferResult(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n eip6492Deployment?: Eip6492Deployment,\n): Promise<SimulateEip3009Result> {\n const auth = payload.authorization;\n const transferArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n if (eip6492Deployment) {\n const { signature: innerSignature } = parseErc6492Signature(payload.signature!);\n const transferCalldata = encodeFunctionData({\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, innerSignature],\n });\n\n try {\n const results = await multicall(signer.readContract.bind(signer), [\n {\n address: getAddress(eip6492Deployment.factoryAddress),\n callData: eip6492Deployment.factoryCalldata,\n } satisfies RawContractCall,\n {\n address: erc20Address,\n callData: transferCalldata,\n } satisfies RawContractCall,\n ]);\n\n return { ok: results[1]?.status === \"success\" };\n } catch (error) {\n return { ok: false, error };\n }\n }\n\n const sig = payload.signature!;\n const sigLength = sig.startsWith(\"0x\") ? sig.length - 2 : sig.length;\n const isECDSA = sigLength === 130;\n\n try {\n if (isECDSA) {\n const parsedSig = parseSignature(sig);\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n ...transferArgs,\n (parsedSig.v as number | undefined) ?? parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n } else {\n await signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...transferArgs, sig],\n });\n }\n return { ok: true };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n/**\n * After simulation fails, runs a single diagnostic multicall to determine the most specific error reason.\n * Checks balanceOf, name, version and authorizationState in one RPC round-trip.\n *\n * @param signer - EVM signer used for the payment\n * @param erc20Address - Address of the ERC-20 token contract\n * @param payload - The EIP-3009 transfer authorization payload\n * @param requirements - Payment requirements to validate against\n * @param amountRequired - Required amount for the payment (balance check)\n *\n * @returns Promise resolving to the verification result with validity and optional invalid reason\n */\nexport async function diagnoseEip3009SimulationFailure(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n requirements: PaymentRequirements,\n amountRequired: string,\n): Promise<VerifyResponse> {\n const payer = payload.authorization.from;\n\n const diagnosticCalls: ContractCall[] = [\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [payload.authorization.from],\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"name\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"version\",\n },\n {\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"authorizationState\",\n args: [payload.authorization.from, payload.authorization.nonce],\n },\n ];\n\n try {\n const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);\n\n const [balanceResult, nameResult, versionResult, authStateResult] = results;\n\n if (authStateResult.status === \"failure\") {\n return { isValid: false, invalidReason: Errors.ErrEip3009NotSupported, payer };\n }\n\n if (authStateResult.status === \"success\" && authStateResult.result === true) {\n return { isValid: false, invalidReason: Errors.ErrEip3009NonceAlreadyUsed, payer };\n }\n\n if (\n nameResult.status === \"success\" &&\n requirements.extra?.name &&\n nameResult.result !== requirements.extra.name\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenNameMismatch, payer };\n }\n\n if (\n versionResult.status === \"success\" &&\n requirements.extra?.version &&\n versionResult.result !== requirements.extra.version\n ) {\n return { isValid: false, invalidReason: Errors.ErrEip3009TokenVersionMismatch, payer };\n }\n\n if (balanceResult.status === \"success\") {\n const balance = balanceResult.result as bigint;\n if (balance < BigInt(amountRequired)) {\n return {\n isValid: false,\n invalidReason: Errors.ErrEip3009InsufficientBalance,\n payer,\n };\n }\n }\n } catch {\n // Diagnostic multicall failed — fall through to generic error\n }\n\n return { isValid: false, invalidReason: Errors.ErrEip3009SimulationFailed, payer };\n}\n\n/**\n * Maps an EIP-3009 contract revert error to a specific error code.\n * Falls back to ErrTransactionFailed when the revert reason is unknown.\n *\n * @param error - The error thrown during transfer execution\n * @returns A specific error reason string\n */\nexport function parseEip3009TransferError(error: unknown): string {\n const msg = error instanceof Error ? error.message : String(error);\n if (/authorization.*(expired|valid before)/i.test(msg) || /AuthorizationExpired/i.test(msg)) {\n return Errors.ErrValidBeforeExpired;\n }\n if (/authorization.*not.*valid|AuthorizationNotYetValid/i.test(msg)) {\n return Errors.ErrValidAfterInFuture;\n }\n if (/authorization.*used|AuthorizationAlreadyUsed|AuthorizationUsedOrCanceled/i.test(msg)) {\n return Errors.ErrEip3009NonceAlreadyUsed;\n }\n if (/transfer.*exceeds.*balance|insufficient.*balance|ERC20InsufficientBalance/i.test(msg)) {\n return Errors.ErrEip3009InsufficientBalance;\n }\n if (/invalid.*signature|SignerMismatch|InvalidSignatureV|InvalidSignatureS/i.test(msg)) {\n return Errors.ErrInvalidSignature;\n }\n return Errors.ErrTransactionFailed;\n}\n\n/**\n * Executes transferWithAuthorization onchain.\n *\n * @param signer - EVM signer for contract writes\n * @param erc20Address - ERC-20 token contract address\n * @param payload - EIP-3009 transfer authorization payload\n * @param dataSuffix - Optional hex bytes to append after the ABI-encoded calldata\n *\n * @returns Transaction hash\n */\nexport async function executeTransferWithAuthorization(\n signer: FacilitatorEvmSigner,\n erc20Address: `0x${string}`,\n payload: ExactEIP3009Payload,\n dataSuffix?: Hex,\n): Promise<Hex> {\n const { signature } = parseErc6492Signature(payload.signature!);\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isECDSA = signatureLength === 130;\n\n const auth = payload.authorization;\n const baseArgs = [\n getAddress(auth.from),\n getAddress(auth.to),\n BigInt(auth.value),\n BigInt(auth.validAfter),\n BigInt(auth.validBefore),\n auth.nonce,\n ] as const;\n\n let signatureArgs: readonly unknown[];\n if (isECDSA) {\n const parsedSig = parseSignature(signature);\n signatureArgs = [\n (parsedSig.v as number | undefined) || parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ];\n } else {\n signatureArgs = [signature];\n }\n\n return signer.writeContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [...baseArgs, ...signatureArgs],\n dataSuffix,\n });\n}\n","export { ExactEvmSchemeV1 } from \"../exact/v1\";\n\nexport const EVM_NETWORK_CHAIN_ID_MAP = {\n ethereum: 1,\n sepolia: 11155111,\n abstract: 2741,\n \"abstract-testnet\": 11124,\n \"base-sepolia\": 84532,\n base: 8453,\n \"avalanche-fuji\": 43113,\n avalanche: 43114,\n iotex: 4689,\n sei: 1329,\n \"sei-testnet\": 1328,\n polygon: 137,\n \"polygon-amoy\": 80002,\n peaq: 3338,\n story: 1514,\n educhain: 41923,\n \"skale-base-sepolia\": 324705682,\n megaeth: 4326,\n monad: 143,\n stable: 988,\n \"stable-testnet\": 2201,\n} as const;\n\nexport type EvmNetworkV1 = keyof typeof EVM_NETWORK_CHAIN_ID_MAP;\n\nexport const NETWORKS: string[] = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);\n\n/**\n * Extract chain ID from a v1 legacy network name.\n *\n * @param network - The v1 network name (e.g., \"base-sepolia\", \"polygon\")\n * @returns The numeric chain ID\n * @throws Error if the network name is not a known v1 network\n */\nexport function getEvmChainIdV1(network: string): number {\n const chainId = EVM_NETWORK_CHAIN_ID_MAP[network as EvmNetworkV1];\n if (!chainId) {\n throw new Error(`Unsupported v1 network: ${network}`);\n }\n return chainId;\n}\n","import {\n PaymentPayload,\n PaymentPayloadResult,\n PaymentRequirements,\n FacilitatorContext,\n SettleResponse,\n VerifyResponse,\n} from \"@x402/core/types\";\nimport {\n extractEip2612GasSponsoringInfo,\n validateEip2612GasSponsoringInfo,\n extractErc20ApprovalGasSponsoringInfo,\n ERC20_APPROVAL_GAS_SPONSORING_KEY,\n type Eip2612GasSponsoringInfo,\n type Erc20ApprovalGasSponsoringFacilitatorExtension,\n type Erc20ApprovalGasSponsoringSigner,\n} from \"../exact/extensions\";\nimport { getAddress, encodeFunctionData, parseErc6492Signature } from \"viem\";\nimport { PERMIT2_ADDRESS, eip3009ABI, erc20AllowanceAbi, permit2WitnessTypes } from \"../constants\";\nimport { multicall, ContractCall } from \"../multicall\";\nimport { createPermit2Nonce, getEvmChainId } from \"../utils\";\nimport {\n ErrPermit2612AmountMismatch,\n ErrPermit2InvalidAmount,\n ErrPermit2InvalidDestination,\n ErrPermit2InvalidNonce,\n ErrPermit2InvalidOwner,\n ErrPermit2InvalidSignature,\n ErrPermit2PaymentTooEarly,\n ErrPermit2AllowanceRequired,\n ErrPermit2SimulationFailed,\n ErrPermit2InsufficientBalance,\n ErrPermit2ProxyNotDeployed,\n ErrInvalidTransactionState,\n ErrTransactionFailed,\n ErrInvalidEip2612ExtensionFormat,\n ErrEip2612FromMismatch,\n ErrEip2612AssetMismatch,\n ErrEip2612SpenderNotPermit2,\n ErrEip2612DeadlineExpired,\n ErrErc20ApprovalTxFailed,\n} from \"../exact/facilitator/errors\";\nimport { ClientEvmSigner, FacilitatorEvmSigner } from \"../signer\";\nimport { ExactPermit2Payload, Permit2Authorization, UptoPermit2Payload } from \"../types\";\nimport { validateErc20ApprovalForPayment } from \"./erc20approval\";\nimport {\n ErrUptoAmountExceedsPermitted,\n ErrUptoUnauthorizedFacilitator,\n} from \"../upto/facilitator/errors\";\n\n/**\n * Base type for Permit2 payloads shared between exact and upto schemes.\n * Both {@link ExactPermit2Payload} and {@link UptoPermit2Payload} satisfy this type.\n */\nexport type Permit2PayloadBase = ExactPermit2Payload | UptoPermit2Payload;\n\n/**\n * Configuration for the Permit2 proxy contract used during settlement.\n * The exact and upto schemes use different proxy addresses and ABIs.\n */\nexport type Permit2ProxyConfig = {\n /** The deployed proxy contract address. */\n proxyAddress: `0x${string}`;\n /** The proxy contract ABI (must include settle and settleWithPermit functions). */\n proxyABI: readonly Record<string, unknown>[];\n};\n\n/**\n * Checks Permit2 allowance and validates gas sponsoring extensions if allowance is insufficient.\n *\n * When the on-chain ERC-20 allowance to the Permit2 contract is below the required amount,\n * this function falls back to validating EIP-2612 or ERC-20 approval gas sponsoring extensions\n * attached to the payment payload.\n *\n * @param signer - The facilitator signer for on-chain reads\n * @param payload - The payment payload\n * @param requirements - The payment requirements\n * @param payer - The payer address\n * @param tokenAddress - The token contract address\n * @param context - Optional facilitator context for extension lookup\n * @returns A VerifyResponse if verification should stop (failure), or null to continue\n */\nexport async function verifyPermit2Allowance(\n signer: FacilitatorEvmSigner,\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n payer: `0x${string}`,\n tokenAddress: `0x${string}`,\n context?: FacilitatorContext,\n): Promise<VerifyResponse | null> {\n try {\n const allowance = (await signer.readContract({\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [payer, PERMIT2_ADDRESS],\n })) as bigint;\n\n if (allowance >= BigInt(requirements.amount)) {\n return null; // Sufficient allowance, continue verification\n }\n\n // Allowance insufficient — try EIP-2612 gas sponsoring first\n const eip2612Info = extractEip2612GasSponsoringInfo(payload);\n if (eip2612Info) {\n const result = validateEip2612PermitForPayment(eip2612Info, payer, tokenAddress);\n if (!result.isValid) {\n return { isValid: false, invalidReason: result.invalidReason!, payer };\n }\n return null; // EIP-2612 is valid, allowance will be set atomically during settlement\n }\n\n // Try ERC-20 approval gas sponsoring as fallback\n const erc20GasSponsorshipExtension =\n context?.getExtension<Erc20ApprovalGasSponsoringFacilitatorExtension>(\n ERC20_APPROVAL_GAS_SPONSORING_KEY,\n );\n if (erc20GasSponsorshipExtension) {\n const erc20Info = extractErc20ApprovalGasSponsoringInfo(payload);\n if (erc20Info) {\n const result = await validateErc20ApprovalForPayment(erc20Info, payer, tokenAddress);\n if (!result.isValid) {\n return { isValid: false, invalidReason: result.invalidReason!, payer };\n }\n return null; // ERC-20 approval is valid, will be broadcast before settlement\n }\n }\n\n return { isValid: false, invalidReason: \"permit2_allowance_required\", payer };\n } catch {\n // Allowance check failed — validate extensions if present; fail closed if none valid\n const eip2612Info = extractEip2612GasSponsoringInfo(payload);\n if (eip2612Info) {\n const result = validateEip2612PermitForPayment(eip2612Info, payer, tokenAddress);\n if (!result.isValid) {\n return { isValid: false, invalidReason: result.invalidReason!, payer };\n }\n return null;\n }\n\n const erc20GasSponsorshipExtension =\n context?.getExtension<Erc20ApprovalGasSponsoringFacilitatorExtension>(\n ERC20_APPROVAL_GAS_SPONSORING_KEY,\n );\n if (erc20GasSponsorshipExtension) {\n const erc20Info = extractErc20ApprovalGasSponsoringInfo(payload);\n if (erc20Info) {\n const result = await validateErc20ApprovalForPayment(erc20Info, payer, tokenAddress);\n if (!result.isValid) {\n return { isValid: false, invalidReason: result.invalidReason!, payer };\n }\n return null;\n }\n }\n\n return { isValid: false, invalidReason: \"permit2_allowance_required\", payer };\n }\n}\n\n/**\n * Waits for a transaction receipt and returns the appropriate SettleResponse.\n *\n * @param signer - Signer with waitForTransactionReceipt capability\n * @param tx - The transaction hash to wait for\n * @param payload - The payment payload (for network info)\n * @param payer - The payer address\n * @returns Promise resolving to a settlement response indicating success or failure\n */\nexport async function waitAndReturnSettleResponse(\n signer: Pick<FacilitatorEvmSigner, \"waitForTransactionReceipt\">,\n tx: `0x${string}`,\n payload: PaymentPayload,\n payer: `0x${string}`,\n): Promise<SettleResponse> {\n const receipt = await signer.waitForTransactionReceipt({ hash: tx });\n\n if (receipt.status !== \"success\") {\n return {\n success: false,\n errorReason: ErrInvalidTransactionState,\n transaction: tx,\n network: payload.accepted.network,\n payer,\n };\n }\n\n return {\n success: true,\n transaction: tx,\n network: payload.accepted.network,\n payer,\n };\n}\n\n/**\n * Maps contract revert errors to structured SettleResponse error reasons.\n *\n * Inspects the error message for known contract revert strings and maps them\n * to the corresponding error reason constants. Falls back to a generic\n * \"transaction_failed\" reason with truncated message for unrecognized errors.\n *\n * @param error - The caught error (typically from a contract write)\n * @param payload - The payment payload (for network info)\n * @param payer - The payer address\n * @returns A failed SettleResponse with the mapped error reason\n */\nexport function mapSettleError(\n error: unknown,\n payload: PaymentPayload,\n payer: `0x${string}`,\n): SettleResponse {\n let errorReason: string = ErrTransactionFailed;\n if (error instanceof Error) {\n const message = error.message;\n if (message.includes(\"Permit2612AmountMismatch\")) {\n errorReason = ErrPermit2612AmountMismatch;\n } else if (message.includes(\"InvalidAmount\")) {\n errorReason = ErrPermit2InvalidAmount;\n } else if (message.includes(\"InvalidDestination\")) {\n errorReason = ErrPermit2InvalidDestination;\n } else if (message.includes(\"InvalidOwner\")) {\n errorReason = ErrPermit2InvalidOwner;\n } else if (message.includes(\"PaymentTooEarly\")) {\n errorReason = ErrPermit2PaymentTooEarly;\n } else if (message.includes(\"InvalidSignature\") || message.includes(\"SignatureExpired\")) {\n errorReason = ErrPermit2InvalidSignature;\n } else if (message.includes(\"InvalidNonce\")) {\n errorReason = ErrPermit2InvalidNonce;\n } else if (message.includes(\"erc20_approval_tx_failed\")) {\n errorReason = ErrErc20ApprovalTxFailed;\n } else if (message.includes(\"AmountExceedsPermitted\")) {\n errorReason = ErrUptoAmountExceedsPermitted;\n } else if (message.includes(\"UnauthorizedFacilitator\")) {\n errorReason = ErrUptoUnauthorizedFacilitator;\n } else {\n errorReason = `${ErrTransactionFailed}: ${message.slice(0, 500)}`;\n }\n }\n return {\n success: false,\n errorReason,\n transaction: \"\",\n network: payload.accepted.network,\n payer,\n };\n}\n\n/**\n * Validates EIP-2612 permit extension data for a Permit2 payment.\n *\n * Checks that the permit extension has a valid format and that the from address,\n * asset address, spender address, and deadline all match expectations.\n *\n * @param info - The EIP-2612 gas sponsoring info extracted from the payment payload\n * @param payer - The expected payer address\n * @param tokenAddress - The expected token address\n * @returns Validation result with isValid flag and optional invalidReason string\n */\nexport function validateEip2612PermitForPayment(\n info: Eip2612GasSponsoringInfo,\n payer: `0x${string}`,\n tokenAddress: `0x${string}`,\n): { isValid: boolean; invalidReason?: string } {\n if (!validateEip2612GasSponsoringInfo(info)) {\n return { isValid: false, invalidReason: ErrInvalidEip2612ExtensionFormat };\n }\n\n if (getAddress(info.from as `0x${string}`) !== getAddress(payer)) {\n return { isValid: false, invalidReason: ErrEip2612FromMismatch };\n }\n\n if (getAddress(info.asset as `0x${string}`) !== tokenAddress) {\n return { isValid: false, invalidReason: ErrEip2612AssetMismatch };\n }\n\n if (getAddress(info.spender as `0x${string}`) !== getAddress(PERMIT2_ADDRESS)) {\n return { isValid: false, invalidReason: ErrEip2612SpenderNotPermit2 };\n }\n\n const now = Math.floor(Date.now() / 1000);\n if (BigInt(info.deadline) < BigInt(now + 6)) {\n return { isValid: false, invalidReason: ErrEip2612DeadlineExpired };\n }\n\n return { isValid: true };\n}\n\n// ---------------------------------------------------------------------------\n// Simulation helpers (shared across exact and upto)\n// ---------------------------------------------------------------------------\n\n/**\n * Simulates settle() via eth_call (readContract).\n * Returns true if simulation succeeded, false if it failed.\n *\n * @param config - The proxy contract configuration (address and ABI)\n * @param signer - EVM signer for contract reads\n * @param settleArgs - Pre-built settle function arguments (scheme-specific)\n * @returns true if simulation succeeded, false if it failed\n */\nexport async function simulatePermit2Settle(\n config: Permit2ProxyConfig,\n signer: FacilitatorEvmSigner,\n settleArgs: readonly unknown[],\n): Promise<boolean> {\n try {\n await signer.readContract({\n address: config.proxyAddress,\n abi: config.proxyABI,\n functionName: \"settle\",\n args: settleArgs,\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Simulates settleWithPermit() via eth_call (readContract).\n * The contract atomically calls token.permit() then PERMIT2.permitTransferFrom(),\n * so simulation covers allowance + balance + nonces.\n *\n * @param config - The proxy contract configuration (address and ABI)\n * @param signer - EVM signer for contract reads\n * @param settleArgs - Pre-built settle function arguments (scheme-specific)\n * @param eip2612Info - EIP-2612 gas sponsoring info from the payload extension\n * @returns true if simulation succeeded, false if it failed\n */\nexport async function simulatePermit2SettleWithPermit(\n config: Permit2ProxyConfig,\n signer: FacilitatorEvmSigner,\n settleArgs: readonly unknown[],\n eip2612Info: Eip2612GasSponsoringInfo,\n): Promise<boolean> {\n try {\n const { v, r, s } = splitEip2612Signature(eip2612Info.signature);\n\n await signer.readContract({\n address: config.proxyAddress,\n abi: config.proxyABI,\n functionName: \"settleWithPermit\",\n args: [\n {\n value: BigInt(eip2612Info.amount),\n deadline: BigInt(eip2612Info.deadline),\n r,\n s,\n v,\n },\n ...settleArgs,\n ],\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Delegates the full approve+settle simulation flow to the extension signer via simulateTransactions.\n * The signer owns execution strategy.\n *\n * @param config - The proxy contract configuration (address and ABI)\n * @param extensionSigner - The extension signer with simulateTransactions capability\n * @param settleArgs - Pre-built settle function arguments (scheme-specific)\n * @param erc20Info - Object containing the signed approval transaction\n * @param erc20Info.signedTransaction - The RLP-encoded signed ERC-20 approve transaction hex string\n * @returns true if the bundle simulation succeeded, false otherwise\n */\nexport async function simulatePermit2SettleWithErc20Approval(\n config: Permit2ProxyConfig,\n extensionSigner: Erc20ApprovalGasSponsoringSigner,\n settleArgs: readonly unknown[],\n erc20Info: { signedTransaction: string },\n): Promise<boolean> {\n if (!extensionSigner.simulateTransactions) {\n return false;\n }\n\n try {\n const settleData = encodeFunctionData({\n abi: config.proxyABI,\n functionName: \"settle\",\n args: settleArgs,\n });\n\n return await extensionSigner.simulateTransactions([\n erc20Info.signedTransaction as `0x${string}`,\n { to: config.proxyAddress, data: settleData, gas: BigInt(300_000) },\n ]);\n } catch {\n return false;\n }\n}\n\n/**\n * Diagnoses a Permit2 simulation failure by performing a multicall to check the proxy deployment, balance and allowance.\n *\n * @param config - The proxy contract configuration (address and ABI)\n * @param signer - EVM signer for contract reads\n * @param tokenAddress - ERC-20 token contract address\n * @param permit2Payload - The Permit2 authorization payload\n * @param amountRequired - Required payment amount (as string)\n * @returns VerifyResponse with the most specific failure reason\n */\nexport async function diagnosePermit2SimulationFailure(\n config: Permit2ProxyConfig,\n signer: FacilitatorEvmSigner,\n tokenAddress: `0x${string}`,\n permit2Payload: Permit2PayloadBase,\n amountRequired: string,\n): Promise<VerifyResponse> {\n const payer = permit2Payload.permit2Authorization.from;\n\n const diagnosticCalls: ContractCall[] = [\n {\n address: config.proxyAddress,\n abi: config.proxyABI,\n functionName: \"PERMIT2\",\n },\n {\n address: tokenAddress,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [payer],\n },\n {\n address: tokenAddress,\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [payer, PERMIT2_ADDRESS],\n },\n ];\n\n try {\n const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);\n\n const [proxyResult, balanceResult, allowanceResult] = results;\n\n if (proxyResult.status === \"failure\") {\n return { isValid: false, invalidReason: ErrPermit2ProxyNotDeployed, payer };\n }\n\n if (balanceResult.status === \"success\") {\n const balance = balanceResult.result as bigint;\n if (balance < BigInt(amountRequired)) {\n return { isValid: false, invalidReason: ErrPermit2InsufficientBalance, payer };\n }\n }\n\n if (allowanceResult.status === \"success\") {\n const allowance = allowanceResult.result as bigint;\n if (allowance < BigInt(amountRequired)) {\n return { isValid: false, invalidReason: ErrPermit2AllowanceRequired, payer };\n }\n }\n } catch {\n // Diagnostic multicall itself failed — fall through to generic error\n }\n\n return { isValid: false, invalidReason: ErrPermit2SimulationFailed, payer };\n}\n\n/**\n * Targeted multicall for the ERC-20 approval path where simulation cannot be used\n * (the approval hasn't been broadcast yet, so settle() would fail for expected reasons).\n * Checks proxy deployment, payer token balance and payer ETH balance for gas.\n *\n * @param config - The proxy contract configuration (address and ABI)\n * @param signer - EVM signer for contract reads\n * @param tokenAddress - ERC-20 token contract address\n * @param payer - The payer address\n * @param amountRequired - Required payment amount (as string)\n * @returns VerifyResponse — valid if checks pass, otherwise the most specific failure\n */\nexport async function checkPermit2Prerequisites(\n config: Permit2ProxyConfig,\n signer: FacilitatorEvmSigner,\n tokenAddress: `0x${string}`,\n payer: `0x${string}`,\n amountRequired: string,\n): Promise<VerifyResponse> {\n const diagnosticCalls: ContractCall[] = [\n {\n address: config.proxyAddress,\n abi: config.proxyABI,\n functionName: \"PERMIT2\",\n },\n {\n address: tokenAddress,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [payer],\n },\n ];\n\n try {\n const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);\n\n const [proxyResult, balanceResult] = results;\n\n if (proxyResult.status === \"failure\") {\n return { isValid: false, invalidReason: ErrPermit2ProxyNotDeployed, payer };\n }\n\n if (balanceResult.status === \"success\") {\n const balance = balanceResult.result as bigint;\n if (balance < BigInt(amountRequired)) {\n return { isValid: false, invalidReason: ErrPermit2InsufficientBalance, payer };\n }\n }\n } catch {\n // Multicall failed — fall through to valid (fail open for prerequisites-only check)\n }\n\n return { isValid: true, invalidReason: undefined, payer };\n}\n\n/**\n * Builds args for exact settle(permit, owner, witness, signature).\n *\n * @param permit2Payload - The Permit2 payload containing authorization and signature data\n * @returns Tuple of contract call arguments for the exact settle function\n */\nexport function buildExactPermit2SettleArgs(permit2Payload: Permit2PayloadBase) {\n const { signature } = parseErc6492Signature(permit2Payload.signature);\n\n return [\n {\n permitted: {\n token: getAddress(permit2Payload.permit2Authorization.permitted.token),\n amount: BigInt(permit2Payload.permit2Authorization.permitted.amount),\n },\n nonce: BigInt(permit2Payload.permit2Authorization.nonce),\n deadline: BigInt(permit2Payload.permit2Authorization.deadline),\n },\n getAddress(permit2Payload.permit2Authorization.from),\n {\n to: getAddress(permit2Payload.permit2Authorization.witness.to),\n validAfter: BigInt(permit2Payload.permit2Authorization.witness.validAfter),\n },\n signature,\n ] as const;\n}\n\n/**\n * Builds args for upto settle(permit, amount, owner, witness, signature).\n * The upto contract's settle() takes an additional `amount` parameter and the witness\n * includes a `facilitator` field.\n *\n * @param permit2Payload - The upto Permit2 payload containing authorization and signature data\n * @param settlementAmount - The amount to settle on-chain\n * @param facilitatorAddress - The facilitator address authorized in the witness\n * @returns Tuple of contract call arguments for the upto settle function\n */\nexport function buildUptoPermit2SettleArgs(\n permit2Payload: UptoPermit2Payload,\n settlementAmount: bigint,\n facilitatorAddress: `0x${string}`,\n) {\n const { signature } = parseErc6492Signature(permit2Payload.signature);\n\n return [\n {\n permitted: {\n token: getAddress(permit2Payload.permit2Authorization.permitted.token),\n amount: BigInt(permit2Payload.permit2Authorization.permitted.amount),\n },\n nonce: BigInt(permit2Payload.permit2Authorization.nonce),\n deadline: BigInt(permit2Payload.permit2Authorization.deadline),\n },\n settlementAmount,\n getAddress(permit2Payload.permit2Authorization.from),\n {\n to: getAddress(permit2Payload.permit2Authorization.witness.to),\n facilitator: getAddress(facilitatorAddress),\n validAfter: BigInt(permit2Payload.permit2Authorization.witness.validAfter),\n },\n signature,\n ] as const;\n}\n\n/**\n * Splits a 65-byte EIP-2612 signature into v, r, s components.\n *\n * @param signature - The hex-encoded 65-byte signature (with or without 0x prefix)\n * @returns Object with v (uint8), r (bytes32 hex), s (bytes32 hex)\n * @throws Error if the signature is not exactly 65 bytes (130 hex chars)\n */\nexport function splitEip2612Signature(signature: string): {\n v: number;\n r: `0x${string}`;\n s: `0x${string}`;\n} {\n const sig = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n\n if (sig.length !== 130) {\n throw new Error(\n `invalid EIP-2612 signature length: expected 65 bytes (130 hex chars), got ${sig.length / 2} bytes`,\n );\n }\n\n const r = `0x${sig.slice(0, 64)}` as `0x${string}`;\n const s = `0x${sig.slice(64, 128)}` as `0x${string}`;\n const v = parseInt(sig.slice(128, 130), 16);\n\n return { v, r, s };\n}\n\n// ---------------------------------------------------------------------------\n// Client-side helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a Permit2 payload for any scheme (exact or upto).\n * The only scheme-specific input is the proxy address used as the spender.\n *\n * @param proxyAddress - The x402 proxy contract address to set as spender\n * @param signer - The EVM client signer\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createPermit2PayloadForProxy(\n proxyAddress: `0x${string}`,\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise<PaymentPayloadResult> {\n const now = Math.floor(Date.now() / 1000);\n const nonce = createPermit2Nonce();\n\n // Lower time bound - allow some clock skew\n const validAfter = \"0\";\n // Upper time bound is enforced by Permit2's deadline field\n const deadline = (now + paymentRequirements.maxTimeoutSeconds).toString();\n\n const permit2Authorization: Permit2Authorization & { from: `0x${string}` } = {\n from: signer.address,\n permitted: {\n token: getAddress(paymentRequirements.asset),\n amount: paymentRequirements.amount,\n },\n spender: proxyAddress,\n nonce,\n deadline,\n witness: {\n to: getAddress(paymentRequirements.payTo),\n validAfter,\n },\n };\n\n const signature = await signPermit2Authorization(\n signer,\n permit2Authorization,\n paymentRequirements,\n );\n\n return {\n x402Version,\n payload: { signature, permit2Authorization },\n };\n}\n\n/**\n * Signs a Permit2 authorization using EIP-712 with witness data.\n * The signature authorizes the proxy contract to transfer tokens on behalf of the signer.\n *\n * @param signer - The EVM client signer\n * @param permit2Authorization - The Permit2 authorization parameters\n * @param requirements - The payment requirements\n * @returns Promise resolving to the hex-encoded signature\n */\nasync function signPermit2Authorization(\n signer: ClientEvmSigner,\n permit2Authorization: Permit2Authorization & { from: `0x${string}` },\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n return await signer.signTypedData({\n domain: { name: \"Permit2\", chainId, verifyingContract: PERMIT2_ADDRESS },\n types: permit2WitnessTypes,\n primaryType: \"PermitWitnessTransferFrom\",\n message: {\n permitted: {\n token: getAddress(permit2Authorization.permitted.token),\n amount: BigInt(permit2Authorization.permitted.amount),\n },\n spender: getAddress(permit2Authorization.spender),\n nonce: BigInt(permit2Authorization.nonce),\n deadline: BigInt(permit2Authorization.deadline),\n witness: {\n to: getAddress(permit2Authorization.witness.to),\n validAfter: BigInt(permit2Authorization.witness.validAfter),\n },\n },\n });\n}\n","import {\n getAddress,\n parseTransaction,\n decodeFunctionData,\n recoverTransactionAddress,\n type TransactionSerialized,\n} from \"viem\";\nimport type { VerifyResponse } from \"@x402/core/types\";\nimport {\n validateErc20ApprovalGasSponsoringInfo,\n type Erc20ApprovalGasSponsoringInfo,\n} from \"../exact/extensions\";\nimport { PERMIT2_ADDRESS, erc20ApproveAbi } from \"../constants\";\nimport {\n ErrErc20ApprovalInvalidFormat,\n ErrErc20ApprovalFromMismatch,\n ErrErc20ApprovalAssetMismatch,\n ErrErc20ApprovalSpenderNotPermit2,\n ErrErc20ApprovalTxWrongTarget,\n ErrErc20ApprovalTxWrongSelector,\n ErrErc20ApprovalTxWrongSpender,\n ErrErc20ApprovalTxInvalidCalldata,\n ErrErc20ApprovalTxSignerMismatch,\n ErrErc20ApprovalTxInvalidSignature,\n ErrErc20ApprovalTxParseFailed,\n} from \"../exact/facilitator/errors\";\n\n/** The approve(address,uint256) function selector */\nconst APPROVE_SELECTOR = \"0x095ea7b3\";\n\n/**\n * Validates ERC-20 approval extension data for a Permit2 payment.\n *\n * Performs comprehensive validation:\n * - Format validation via validateErc20ApprovalGasSponsoringInfo (JSON Schema)\n * - `from` matches payer\n * - `asset` matches token\n * - `spender` is PERMIT2_ADDRESS\n * - Transaction `to` matches token address\n * - Transaction calldata is a valid approve(PERMIT2_ADDRESS, ...) call\n * - Recovered transaction signer matches `from`\n *\n * @param info - The ERC-20 approval gas sponsoring info\n * @param payer - The expected payer address\n * @param tokenAddress - The expected token address\n * @returns Validation result with invalidReason and invalidMessage on failure\n */\nexport async function validateErc20ApprovalForPayment(\n info: Erc20ApprovalGasSponsoringInfo,\n payer: `0x${string}`,\n tokenAddress: `0x${string}`,\n): Promise<Pick<VerifyResponse, \"isValid\" | \"invalidReason\" | \"invalidMessage\">> {\n if (!validateErc20ApprovalGasSponsoringInfo(info)) {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalInvalidFormat,\n invalidMessage: \"ERC-20 approval extension info failed schema validation\",\n };\n }\n\n if (getAddress(info.from) !== getAddress(payer)) {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalFromMismatch,\n invalidMessage: `Expected from=${payer}, got ${info.from}`,\n };\n }\n\n if (getAddress(info.asset) !== tokenAddress) {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalAssetMismatch,\n invalidMessage: `Expected asset=${tokenAddress}, got ${info.asset}`,\n };\n }\n\n if (getAddress(info.spender) !== getAddress(PERMIT2_ADDRESS)) {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalSpenderNotPermit2,\n invalidMessage: `Expected spender=${PERMIT2_ADDRESS}, got ${info.spender}`,\n };\n }\n\n try {\n const serializedTx = info.signedTransaction as TransactionSerialized;\n const tx = parseTransaction(serializedTx);\n\n if (!tx.to || getAddress(tx.to) !== tokenAddress) {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalTxWrongTarget,\n invalidMessage: `Transaction targets ${tx.to ?? \"null\"}, expected ${tokenAddress}`,\n };\n }\n\n const data = tx.data ?? \"0x\";\n if (!data.startsWith(APPROVE_SELECTOR)) {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalTxWrongSelector,\n invalidMessage: `Transaction calldata does not start with approve() selector ${APPROVE_SELECTOR}`,\n };\n }\n\n try {\n const decoded = decodeFunctionData({\n abi: erc20ApproveAbi,\n data: data as `0x${string}`,\n });\n const calldataSpender = getAddress(decoded.args[0] as `0x${string}`);\n if (calldataSpender !== getAddress(PERMIT2_ADDRESS)) {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalTxWrongSpender,\n invalidMessage: `approve() spender is ${calldataSpender}, expected Permit2 ${PERMIT2_ADDRESS}`,\n };\n }\n } catch {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalTxInvalidCalldata,\n invalidMessage: \"Failed to decode approve() calldata from the signed transaction\",\n };\n }\n\n try {\n const recoveredAddress = await recoverTransactionAddress({\n serializedTransaction: serializedTx,\n });\n if (getAddress(recoveredAddress) !== getAddress(payer)) {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalTxSignerMismatch,\n invalidMessage: `Transaction signed by ${recoveredAddress}, expected payer ${payer}`,\n };\n }\n } catch {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalTxInvalidSignature,\n invalidMessage: \"Failed to recover signer from the signed transaction\",\n };\n }\n } catch {\n return {\n isValid: false,\n invalidReason: ErrErc20ApprovalTxParseFailed,\n invalidMessage: \"Failed to parse the signed transaction\",\n };\n }\n\n return { isValid: true };\n}\n","/**\n * Named error reason constants for the upto EVM facilitator.\n *\n * Shared Permit2 errors are re-exported from exact/facilitator/errors.ts.\n * Upto-specific errors are defined here.\n *\n * These strings must be character-for-character identical to the Go constants\n * to maintain cross-SDK parity.\n */\n\n// Re-export shared EVM errors\nexport { ErrAssetNotDeployedContract } from \"../../exact/facilitator/errors\";\n\n// Re-export shared Permit2 errors\nexport {\n ErrPermit2InvalidSpender,\n ErrPermit2RecipientMismatch,\n ErrPermit2DeadlineExpired,\n ErrPermit2NotYetValid,\n ErrPermit2AmountMismatch,\n ErrPermit2TokenMismatch,\n ErrPermit2InvalidSignature,\n ErrPermit2AllowanceRequired,\n ErrPermit2InvalidAmount,\n ErrPermit2InvalidDestination,\n ErrPermit2InvalidOwner,\n ErrPermit2PaymentTooEarly,\n ErrPermit2InvalidNonce,\n ErrPermit2612AmountMismatch,\n ErrErc20ApprovalInvalidFormat,\n ErrErc20ApprovalFromMismatch,\n ErrErc20ApprovalAssetMismatch,\n ErrErc20ApprovalSpenderNotPermit2,\n ErrErc20ApprovalTxWrongTarget,\n ErrErc20ApprovalTxWrongSelector,\n ErrErc20ApprovalTxWrongSpender,\n ErrErc20ApprovalTxInvalidCalldata,\n ErrErc20ApprovalTxSignerMismatch,\n ErrErc20ApprovalTxInvalidSignature,\n ErrErc20ApprovalTxParseFailed,\n} from \"../../exact/facilitator/errors\";\n\n// Upto-specific errors\nexport const ErrUptoInvalidScheme = \"invalid_upto_evm_scheme\";\nexport const ErrUptoNetworkMismatch = \"invalid_upto_evm_network_mismatch\";\nexport const ErrUptoSettlementExceedsAmount = \"invalid_upto_evm_payload_settlement_exceeds_amount\";\nexport const ErrUptoAmountExceedsPermitted = \"upto_amount_exceeds_permitted\";\nexport const ErrUptoUnauthorizedFacilitator = \"upto_unauthorized_facilitator\";\nexport const ErrUptoFacilitatorMismatch = \"upto_facilitator_mismatch\";\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { encodeFunctionData, getAddress } from \"viem\";\nimport {\n PERMIT2_ADDRESS,\n x402ExactPermit2ProxyAddress,\n erc20ApproveAbi,\n erc20AllowanceAbi,\n} from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { createPermit2PayloadForProxy } from \"../../shared/permit2\";\n\n/** Maximum uint256 value for unlimited approval. */\nconst MAX_UINT256 = BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n\n/**\n * Creates a Permit2 payload using the x402Permit2Proxy witness pattern.\n * The spender is set to x402Permit2Proxy, which enforces that funds\n * can only be sent to the witness.to address.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createPermit2Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise<PaymentPayloadResult> {\n return createPermit2PayloadForProxy(\n x402ExactPermit2ProxyAddress,\n signer,\n x402Version,\n paymentRequirements,\n );\n}\n\n/**\n * Creates transaction data to approve Permit2 to spend tokens.\n * The user sends this transaction (paying gas) before using Permit2 flow.\n *\n * @param tokenAddress - The ERC20 token contract address\n * @returns Transaction data to send for approval\n *\n * @example\n * ```typescript\n * const tx = createPermit2ApprovalTx(\"0x...\");\n * await walletClient.sendTransaction({\n * to: tx.to,\n * data: tx.data,\n * });\n * ```\n */\nexport function createPermit2ApprovalTx(tokenAddress: `0x${string}`): {\n to: `0x${string}`;\n data: `0x${string}`;\n} {\n const data = encodeFunctionData({\n abi: erc20ApproveAbi,\n functionName: \"approve\",\n args: [PERMIT2_ADDRESS, MAX_UINT256],\n });\n\n return {\n to: getAddress(tokenAddress),\n data,\n };\n}\n\n/**\n * Parameters for checking Permit2 allowance.\n * Application provides these to check if approval is needed.\n */\nexport interface Permit2AllowanceParams {\n tokenAddress: `0x${string}`;\n ownerAddress: `0x${string}`;\n}\n\n/**\n * Returns contract read parameters for checking Permit2 allowance.\n * Use with a public client to check if the user has approved Permit2.\n *\n * @param params - The allowance check parameters\n * @returns Contract read parameters for checking allowance\n *\n * @example\n * ```typescript\n * const readParams = getPermit2AllowanceReadParams({\n * tokenAddress: \"0x...\",\n * ownerAddress: \"0x...\",\n * });\n *\n * const allowance = await publicClient.readContract(readParams);\n * const needsApproval = allowance < requiredAmount;\n * ```\n */\nexport function getPermit2AllowanceReadParams(params: Permit2AllowanceParams): {\n address: `0x${string}`;\n abi: typeof erc20AllowanceAbi;\n functionName: \"allowance\";\n args: [`0x${string}`, `0x${string}`];\n} {\n return {\n address: getAddress(params.tokenAddress),\n abi: erc20AllowanceAbi,\n functionName: \"allowance\",\n args: [getAddress(params.ownerAddress), PERMIT2_ADDRESS],\n };\n}\n","import { PaymentRequirements, PaymentPayloadResult } from \"@x402/core/types\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEIP3009Payload } from \"../../types\";\nimport { createNonce, getEvmChainId } from \"../../utils\";\n\n/**\n * Creates an EIP-3009 (transferWithAuthorization) payload.\n *\n * @param signer - The EVM signer for client operations\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload result\n */\nexport async function createEIP3009Payload(\n signer: ClientEvmSigner,\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n): Promise<PaymentPayloadResult> {\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEIP3009Payload[\"authorization\"] = {\n from: signer.address,\n to: getAddress(paymentRequirements.payTo),\n value: paymentRequirements.amount,\n validAfter: \"0\",\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n const signature = await signEIP3009Authorization(signer, authorization, paymentRequirements);\n\n const payload: ExactEIP3009Payload = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n payload,\n };\n}\n\n/**\n * Sign the EIP-3009 authorization using EIP-712.\n *\n * @param signer - The EVM signer\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\nasync function signEIP3009Authorization(\n signer: ClientEvmSigner,\n authorization: ExactEIP3009Payload[\"authorization\"],\n requirements: PaymentRequirements,\n): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n}\n","import {\n SchemeNetworkClient,\n PaymentRequirements,\n PaymentPayloadResult,\n PaymentPayloadContext,\n} from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { AssetTransferMethod } from \"../../types\";\nimport { createEIP3009Payload } from \"./eip3009\";\nimport { createPermit2Payload } from \"./permit2\";\nimport {\n trySignEip2612PermitExtension,\n trySignErc20ApprovalExtension,\n} from \"../../shared/extensions\";\nimport { ExactEvmSchemeOptions } from \"./rpc\";\n\n/**\n * EVM client implementation for the Exact payment scheme.\n * Supports both EIP-3009 (transferWithAuthorization) and Permit2 flows.\n *\n * Routes to the appropriate authorization method based on\n * `requirements.extra.assetTransferMethod`. Defaults to EIP-3009\n * for backward compatibility with older facilitators.\n *\n * When the server advertises `eip2612GasSponsoring` and the asset transfer\n * method is `permit2`, the scheme automatically signs an EIP-2612 permit\n * if the user lacks Permit2 approval. This requires `readContract` on the signer.\n */\nexport class ExactEvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClient instance.\n *\n * @param signer - The EVM signer for client operations.\n * Base flow only requires `address` + `signTypedData`.\n * Extension enrichment (EIP-2612 / ERC-20 approval sponsoring) additionally\n * requires optional capabilities like `readContract` and tx signing helpers.\n * @param options - Optional RPC configuration used to backfill extension capabilities.\n */\n constructor(\n private readonly signer: ClientEvmSigner,\n private readonly options?: ExactEvmSchemeOptions,\n ) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n * Routes to EIP-3009 or Permit2 based on requirements.extra.assetTransferMethod.\n *\n * For Permit2 flows, if the server advertises `eip2612GasSponsoring` and the\n * signer supports `readContract`, automatically signs an EIP-2612 permit\n * when Permit2 allowance is insufficient.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @param context - Optional context with server-declared extensions\n * @returns Promise resolving to a payment payload result (with optional extensions)\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n context?: PaymentPayloadContext,\n ): Promise<PaymentPayloadResult> {\n const assetTransferMethod =\n (paymentRequirements.extra?.assetTransferMethod as AssetTransferMethod) ?? \"eip3009\";\n\n if (assetTransferMethod === \"permit2\") {\n const result = await createPermit2Payload(this.signer, x402Version, paymentRequirements);\n\n const eip2612Extensions = await trySignEip2612PermitExtension(\n this.signer,\n this.options,\n paymentRequirements,\n result,\n context,\n );\n\n if (eip2612Extensions) {\n return {\n ...result,\n extensions: eip2612Extensions,\n };\n }\n\n const erc20Extensions = await trySignErc20ApprovalExtension(\n this.signer,\n this.options,\n paymentRequirements,\n context,\n );\n if (erc20Extensions) {\n return {\n ...result,\n extensions: erc20Extensions,\n };\n }\n\n return result;\n }\n\n return createEIP3009Payload(this.signer, x402Version, paymentRequirements);\n }\n}\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\nimport { Network } from \"@x402/core/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEvmScheme } from \"./scheme\";\nimport { ExactEvmSchemeOptions } from \"./rpc\";\nimport { ExactEvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering EVM schemes to an x402Client\n */\nexport interface EvmClientConfig {\n /**\n * The EVM signer to use for creating payment payloads\n */\n signer: ClientEvmSigner;\n\n /**\n * Optional payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional Exact EVM client scheme options.\n * Supports either a single config ({ rpcUrl }) or per-chain configs\n * keyed by EVM chain ID ({ 8453: { rpcUrl: \"...\" } }).\n */\n schemeOptions?: ExactEvmSchemeOptions;\n\n /**\n * Optional specific networks to register.\n * If not provided, registers wildcard support (eip155:*).\n */\n networks?: Network[];\n}\n\n/**\n * Registers EVM exact payment schemes to an x402Client instance.\n *\n * This function registers:\n * - V2: eip155:* wildcard scheme with ExactEvmScheme (or specific networks if provided)\n * - V1: All supported EVM networks with ExactEvmSchemeV1\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for EVM client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactEvmScheme } from \"@x402/evm/exact/client/register\";\n * import { x402Client } from \"@x402/core/client\";\n * import { privateKeyToAccount } from \"viem/accounts\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const client = new x402Client();\n * registerExactEvmScheme(client, { signer: account });\n * ```\n */\nexport function registerExactEvmScheme(client: x402Client, config: EvmClientConfig): x402Client {\n const evmScheme = new ExactEvmScheme(config.signer, config.schemeOptions);\n\n // Register V2 scheme\n // EIP-2612 gas sponsoring is handled internally by the scheme when the\n // server advertises support - no separate extension registration needed.\n if (config.networks && config.networks.length > 0) {\n // Register specific networks\n config.networks.forEach(network => {\n client.register(network, evmScheme);\n });\n } else {\n // Register wildcard for all EVM chains\n client.register(\"eip155:*\", evmScheme);\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactEvmSchemeV1(config.signer));\n });\n\n // Apply policies if provided\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n","/**\n * Type definitions for the Builder Code Extension (ERC-8021)\n *\n * Enables attribution tracking for x402 payments by appending\n * ERC-8021 Schema 2 builder codes to settlement transaction calldata.\n */\n\nimport type { PaymentPayload, PaymentRequirements } from \"@x402/core/types\";\n\n/**\n * Extension identifier constant\n */\nexport const BUILDER_CODE = \"builder-code\";\n\n/**\n * ERC-8021 marker bytes (16 bytes) appended at the end of every suffix\n */\nexport const ERC_8021_MARKER = \"80218021802180218021802180218021\";\n\n/**\n * Schema 2 identifier byte\n */\nexport const SCHEMA_2_ID = 0x02;\n\n/**\n * Pattern for valid builder codes (lowercase alphanumeric + underscore, 1-32 chars)\n */\nexport const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;\n\n/**\n * Builder code extension data as it appears in PaymentRequired/PaymentPayload extensions.\n *\n * Maps to ERC-8021 Schema 2 fields:\n * - a: app code (the x402 service that exposed the endpoint)\n * - w: wallet code (the facilitator that settled the payment on-chain)\n * - s: service codes array (related on-chain services the app depends on)\n */\nexport interface BuilderCodeExtensionData {\n /**\n * App builder code — the x402 service that exposed the paid endpoint.\n * Maps to the \"a\" field in ERC-8021 Schema 2.\n * Set by the service in the 402 response.\n */\n a?: string;\n\n /**\n * Wallet builder code — the facilitator that settled the payment on-chain.\n * Maps to the \"w\" field in ERC-8021 Schema 2.\n * Set by the facilitator at settlement time.\n */\n w?: string;\n\n /**\n * Service builder codes — client-provided attribution codes.\n * Maps to the \"s\" field in ERC-8021 Schema 2 (encoded as an array on wire).\n * Accepts a single string or an array of strings; normalized to an array internally.\n */\n s?: string | string[];\n}\n\n/**\n * Configuration for the builder code facilitator extension.\n */\nexport interface BuilderCodeFacilitatorConfig {\n /**\n * The facilitator's own builder code, set as the \"w\" field at settlement when provided.\n */\n builderCode?: string;\n}\n\nexport interface DataSuffixContext {\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n}\n","/**\n * ERC-8021 Schema 2 CBOR encoding for builder code suffixes.\n *\n * Schema 2 suffix format:\n * [cbor_data (variable)] [suffix_data_length (2 bytes)] [schema_id = 0x02 (1 byte)] [ERC-8021 marker (16 bytes)]\n *\n * CBOR payload uses single-letter keys:\n * \"a\" — app builder code (string)\n * \"w\" — wallet/facilitator builder code (string)\n * \"s\" — service codes (string array)\n */\n\nimport { type Hex } from \"viem\";\nimport { ERC_8021_MARKER, SCHEMA_2_ID, type BuilderCodeExtensionData } from \"./types\";\n\n/**\n * Normalizes the `s` field (string or array of strings) into an array of strings.\n *\n * @param s - Service code value as a string, array of strings, or undefined\n * @returns Array of service code strings (empty when absent)\n */\nfunction normalizeServiceCodes(s: BuilderCodeExtensionData[\"s\"]): string[] {\n if (typeof s === \"string\") return [s];\n if (Array.isArray(s)) return s;\n return [];\n}\n\n/**\n * Encodes a CBOR map from builder code extension data.\n *\n * Produces a minimal CBOR map with:\n * - \"a\" key (major type 3, length 1) → string value (app/service code)\n * - \"w\" key (major type 3, length 1) → string value (facilitator code)\n * - \"s\" key (major type 3, length 1) → array of strings (related services)\n *\n * Uses hand-rolled CBOR to avoid adding a dependency.\n *\n * @param data - Builder code extension fields to encode\n * @returns CBOR-encoded map bytes\n */\nfunction encodeCborMap(data: BuilderCodeExtensionData): Uint8Array {\n const entries: Uint8Array[] = [];\n let mapSize = 0;\n\n if (data.a) {\n mapSize++;\n entries.push(encodeCborString(\"a\"));\n entries.push(encodeCborString(data.a));\n }\n\n if (data.w) {\n mapSize++;\n entries.push(encodeCborString(\"w\"));\n entries.push(encodeCborString(data.w));\n }\n\n const serviceCodes = normalizeServiceCodes(data.s);\n if (serviceCodes.length > 0) {\n mapSize++;\n entries.push(encodeCborString(\"s\"));\n entries.push(encodeCborArray(serviceCodes));\n }\n\n // CBOR map header\n const header = encodeCborMajorType(5, mapSize); // major type 5 = map\n\n const totalLength = header.length + entries.reduce((sum, e) => sum + e.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n\n result.set(header, offset);\n offset += header.length;\n\n for (const entry of entries) {\n result.set(entry, offset);\n offset += entry.length;\n }\n\n return result;\n}\n\n/**\n * Encodes a CBOR text string (major type 3).\n *\n * @param value - UTF-8 text to encode\n * @returns CBOR-encoded text string bytes\n */\nfunction encodeCborString(value: string): Uint8Array {\n const encoded = new TextEncoder().encode(value);\n const header = encodeCborMajorType(3, encoded.length); // major type 3 = text string\n const result = new Uint8Array(header.length + encoded.length);\n result.set(header, 0);\n result.set(encoded, header.length);\n return result;\n}\n\n/**\n * Encodes a CBOR array of strings (major type 4).\n *\n * @param values - UTF-8 strings to encode as array elements\n * @returns CBOR-encoded array bytes\n */\nfunction encodeCborArray(values: string[]): Uint8Array {\n const header = encodeCborMajorType(4, values.length); // major type 4 = array\n const encodedValues = values.map(encodeCborString);\n\n const totalLength = header.length + encodedValues.reduce((sum, e) => sum + e.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n\n result.set(header, offset);\n offset += header.length;\n\n for (const encoded of encodedValues) {\n result.set(encoded, offset);\n offset += encoded.length;\n }\n\n return result;\n}\n\n/**\n * Encodes a CBOR major type with an argument value.\n *\n * CBOR encoding rules:\n * - 0-23: single byte (major type << 5 | value)\n * - 24-255: two bytes (major type << 5 | 24, value)\n * - 256-65535: three bytes (major type << 5 | 25, value high, value low)\n *\n * @param majorType - CBOR major type (0–7)\n * @param value - Argument length or inline value for the header\n * @returns CBOR header bytes\n */\nfunction encodeCborMajorType(majorType: number, value: number): Uint8Array {\n const mt = majorType << 5;\n\n if (value <= 23) {\n return new Uint8Array([mt | value]);\n }\n if (value <= 0xff) {\n return new Uint8Array([mt | 24, value]);\n }\n if (value <= 0xffff) {\n return new Uint8Array([mt | 25, (value >> 8) & 0xff, value & 0xff]);\n }\n\n throw new Error(`CBOR value too large: ${value}`);\n}\n\n/**\n * Builds a complete ERC-8021 Schema 2 data suffix from builder code data.\n *\n * Format: [cbor_data][suffix_data_length (2 bytes)][schema_id (1 byte)][marker (16 bytes)]\n *\n * The suffix_data_length covers the cbor_data only (not itself, schema_id, or marker).\n *\n * @param data - Builder code extension data with \"a\" and/or \"s\" fields\n * @returns Hex-encoded suffix bytes (without 0x prefix) ready to append to calldata\n */\nexport function encodeBuilderCodeSuffix(data: BuilderCodeExtensionData): Hex {\n const cborBytes = encodeCborMap(data);\n const cborLength = cborBytes.length;\n\n // suffix_data_length is 2 bytes, big-endian\n const lengthHigh = (cborLength >> 8) & 0xff;\n const lengthLow = cborLength & 0xff;\n\n // Build the full suffix: [cbor][length 2B][schema_id 1B][marker 16B]\n const suffixBytes = new Uint8Array(cborLength + 2 + 1 + 16);\n let offset = 0;\n\n // CBOR data\n suffixBytes.set(cborBytes, offset);\n offset += cborLength;\n\n // Suffix data length (2 bytes, big-endian)\n suffixBytes[offset++] = lengthHigh;\n suffixBytes[offset++] = lengthLow;\n\n // Schema ID\n suffixBytes[offset++] = SCHEMA_2_ID;\n\n // ERC-8021 marker (16 bytes)\n const markerBytes = hexToBytes(ERC_8021_MARKER);\n suffixBytes.set(markerBytes, offset);\n\n return `0x${bytesToHex(suffixBytes)}`;\n}\n\n/**\n * Converts a hex string (without 0x prefix) to bytes.\n *\n * @param hex - Hex-encoded string (two characters per byte)\n * @returns Decoded byte array\n */\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Converts bytes to a lowercase hex string (without 0x prefix).\n *\n * @param bytes - Raw bytes to encode\n * @returns Lowercase hex string\n */\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map(b => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Parses ERC-8021 Schema 2 builder code attribution from settlement calldata.\n *\n * @param calldata - Full transaction input data\n * @returns Decoded builder code fields, or undefined if no valid suffix is present\n */\nexport function parseBuilderCodeSuffixFromCalldata(\n calldata: Hex,\n): BuilderCodeExtensionData | undefined {\n const hex = calldata.startsWith(\"0x\") ? calldata.slice(2) : calldata;\n const markerPos = hex.lastIndexOf(ERC_8021_MARKER.toLowerCase());\n if (markerPos < 6) {\n return undefined;\n }\n\n if (parseInt(hex.slice(markerPos - 2, markerPos), 16) !== SCHEMA_2_ID) {\n return undefined;\n }\n\n const cborLength = parseInt(hex.slice(markerPos - 6, markerPos - 2), 16);\n const suffixStart = markerPos - 6 - cborLength * 2;\n if (suffixStart < 0 || suffixStart + (cborLength + 19) * 2 !== hex.length) {\n return undefined;\n }\n\n const bytes = hexToBytes(hex.slice(suffixStart, markerPos - 6));\n let o = 0;\n\n if (bytes[o] >> 5 !== 5) {\n return undefined;\n }\n\n const mapInfo = bytes[o++] & 0x1f;\n const mapSize = mapInfo <= 23 ? mapInfo : mapInfo === 24 ? bytes[o++] : undefined;\n if (mapSize === undefined) {\n return undefined;\n }\n\n const result: BuilderCodeExtensionData = {};\n for (let entry = 0; entry < mapSize; entry++) {\n if (bytes[o] >> 5 !== 3) {\n return undefined;\n }\n\n const keyInfo = bytes[o++] & 0x1f;\n const keyLen = keyInfo <= 23 ? keyInfo : keyInfo === 24 ? bytes[o++] : undefined;\n if (keyLen === undefined) {\n return undefined;\n }\n\n const key = new TextDecoder().decode(bytes.subarray(o, o + keyLen));\n o += keyLen;\n\n if (key === \"a\" || key === \"w\") {\n if (bytes[o] >> 5 !== 3) {\n return undefined;\n }\n\n const valueInfo = bytes[o++] & 0x1f;\n const valueLen = valueInfo <= 23 ? valueInfo : valueInfo === 24 ? bytes[o++] : undefined;\n if (valueLen === undefined) {\n return undefined;\n }\n\n result[key] = new TextDecoder().decode(bytes.subarray(o, o + valueLen));\n o += valueLen;\n continue;\n }\n\n if (key === \"s\") {\n if (bytes[o] >> 5 !== 4) {\n return undefined;\n }\n\n const arrayInfo = bytes[o++] & 0x1f;\n const arraySize = arrayInfo <= 23 ? arrayInfo : arrayInfo === 24 ? bytes[o++] : undefined;\n if (arraySize === undefined) {\n return undefined;\n }\n\n const codes: string[] = [];\n for (let i = 0; i < arraySize; i++) {\n if (bytes[o] >> 5 !== 3) {\n return undefined;\n }\n\n const itemInfo = bytes[o++] & 0x1f;\n const itemLen = itemInfo <= 23 ? itemInfo : itemInfo === 24 ? bytes[o++] : undefined;\n if (itemLen === undefined) {\n return undefined;\n }\n\n codes.push(new TextDecoder().decode(bytes.subarray(o, o + itemLen)));\n o += itemLen;\n }\n\n if (codes.length > 0) {\n result.s = codes;\n }\n continue;\n }\n\n return undefined;\n }\n\n return result;\n}\n","/**\n * Resource Server utilities for the Builder Code Extension.\n */\n\nimport type { ResourceServerExtension } from \"@x402/core/types\";\nimport { BUILDER_CODE, BUILDER_CODE_PATTERN, type BuilderCodeExtensionData } from \"./types\";\n\nexport const BUILDER_CODE_SCHEMA = {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n a: {\n type: \"string\",\n pattern: \"^[a-z0-9_]{1,32}$\",\n description: \"App builder code\",\n },\n w: {\n type: \"string\",\n pattern: \"^[a-z0-9_]{1,32}$\",\n description: \"Wallet builder code\",\n },\n s: {\n type: \"array\",\n items: {\n type: \"string\",\n pattern: \"^[a-z0-9_]{1,32}$\",\n },\n description: \"Service builder codes\",\n },\n },\n additionalProperties: false,\n} as const;\n\nexport interface BuilderCodeRequiredExtension {\n info: BuilderCodeExtensionData;\n schema: typeof BUILDER_CODE_SCHEMA;\n}\n\n/**\n * Declares the builder-code extension for inclusion in PaymentRequired.extensions.\n *\n * @param appCode - The service's builder code (e.g., \"bc_weather_svc\")\n * @returns Extension declaration with info and schema for PaymentRequired.extensions\n */\nexport function declareBuilderCodeExtension(appCode: string): BuilderCodeRequiredExtension {\n if (!BUILDER_CODE_PATTERN.test(appCode)) {\n throw new Error(\n `Invalid builder code: \"${appCode}\". ` +\n `Must be 1-32 characters, lowercase alphanumeric and underscores only.`,\n );\n }\n\n return {\n info: { a: appCode },\n schema: BUILDER_CODE_SCHEMA,\n };\n}\n\nexport const builderCodeResourceServerExtension: ResourceServerExtension = {\n key: BUILDER_CODE,\n};\n","/**\n * Client-side extension for the Builder Code Extension.\n *\n * Attaches the client's service code (`s`) to the payment payload.\n */\n\nimport type { ClientExtension } from \"@x402/core/client\";\nimport type { PaymentPayload, PaymentRequired } from \"@x402/core/types\";\nimport { BUILDER_CODE, BUILDER_CODE_PATTERN } from \"./types\";\n\n/**\n * Client extension that adds builder-code attribution to payment payloads.\n *\n * @example\n * ```typescript\n * import { BuilderCodeClientExtension } from '@x402/extensions/builder-code';\n *\n * const client = new x402Client();\n * client.registerExtension(new BuilderCodeClientExtension(\"bc_my_client\"));\n * ```\n */\nexport class BuilderCodeClientExtension implements ClientExtension {\n readonly key = BUILDER_CODE;\n private readonly serviceCodes: string[];\n\n /**\n * Creates a client extension that attaches the given service code(s) to payments.\n *\n * Accepts a single code or an array of codes so layered clients (e.g. an MCP\n * middleware) can attribute multiple participants. Codes are normalized to an\n * array and sent as the `s` field.\n *\n * @param serviceCodes - Client service code(s) (`s`), each 1-32 lowercase alphanumeric/underscore characters\n */\n constructor(serviceCodes: string | string[]) {\n const codes = Array.isArray(serviceCodes) ? serviceCodes : [serviceCodes];\n for (const code of codes) {\n if (!BUILDER_CODE_PATTERN.test(code)) {\n throw new Error(\n `Invalid builder code: \"${code}\". ` +\n `Must be 1-32 characters, lowercase alphanumeric and underscores only.`,\n );\n }\n }\n this.serviceCodes = codes;\n }\n\n /**\n * Attaches this client's service code(s) (`s`).\n *\n * @param payload - Payment payload to enrich\n * @param _ - Server payment requirements; core merges server extension data\n * @returns Payment payload with builder-code extension data\n */\n async enrichPaymentPayload(payload: PaymentPayload, _: PaymentRequired): Promise<PaymentPayload> {\n return {\n ...payload,\n extensions: {\n ...payload.extensions,\n [BUILDER_CODE]: { info: { s: this.serviceCodes } },\n },\n };\n }\n}\n","/**\n * Facilitator-side extension for the Builder Code Extension.\n *\n * At settlement time, the facilitator encodes its wallet code into the ERC-8021\n * suffix when configured. App code (`a`) and service code (`s`) are read from\n * the client payment payload extensions.\n */\n\nimport type { FacilitatorExtension } from \"@x402/core/types\";\nimport type { Hex } from \"viem\";\nimport { encodeBuilderCodeSuffix } from \"./cbor\";\nimport {\n BUILDER_CODE,\n BUILDER_CODE_PATTERN,\n type BuilderCodeExtensionData,\n type BuilderCodeFacilitatorConfig,\n type DataSuffixContext,\n} from \"./types\";\n\n/**\n * Reads the client builder-code extension object from payment-payload extensions.\n *\n * @param extensions - Extensions map from PaymentPayload\n * @returns Raw builder-code extension object, or undefined if absent\n */\nfunction extractClientExtension(\n extensions?: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const info = (extensions?.[BUILDER_CODE] as { info?: unknown } | undefined)?.info;\n if (typeof info !== \"object\" || info === null || Array.isArray(info)) return undefined;\n return info as Record<string, unknown>;\n}\n\n/**\n * Normalizes `s` from the client payload — accepts a string or an array and keeps\n * every valid entry.\n *\n * @param raw - Client-provided service code value (string or array of strings)\n * @returns Array of valid service codes (empty when missing or all invalid)\n */\nfunction resolveServiceCodes(raw: unknown): string[] {\n const candidates = typeof raw === \"string\" ? [raw] : Array.isArray(raw) ? raw : [];\n return candidates.filter(\n (v): v is string => typeof v === \"string\" && BUILDER_CODE_PATTERN.test(v),\n );\n}\n\n/**\n * Facilitator extension that manages builder code attribution at settlement time.\n *\n * @example\n * ```typescript\n * import { BuilderCodeFacilitatorExtension } from '@x402/extensions/builder-code';\n *\n * const facilitator = new x402Facilitator();\n * facilitator.registerExtension(new BuilderCodeFacilitatorExtension({\n * builderCode: \"bc_my_facilitator\", // optional\n * }));\n * ```\n */\nexport class BuilderCodeFacilitatorExtension implements FacilitatorExtension {\n readonly key = BUILDER_CODE;\n private readonly config: BuilderCodeFacilitatorConfig;\n\n /**\n * Creates a facilitator extension that encodes builder-code attribution at settlement.\n *\n * @param config - Optional facilitator builder-code configuration (wallet code `w`)\n */\n constructor(config: BuilderCodeFacilitatorConfig = {}) {\n if (config.builderCode && !BUILDER_CODE_PATTERN.test(config.builderCode)) {\n throw new Error(\n `Invalid builder code: \"${config.builderCode}\". ` +\n `Must be 1-32 characters, lowercase alphanumeric and underscores only.`,\n );\n }\n this.config = config;\n }\n\n /**\n * Builds the ERC-8021 Schema 2 calldata suffix for a settlement transaction.\n *\n * - `a` and `s` are read from the client's payment payload extensions.\n * - `w` is the facilitator's own code when configured.\n *\n * @param ctx - Settlement context with payment-payload extensions\n * @returns Hex-encoded ERC-8021 builder-code calldata suffix, or undefined when no attribution is present\n */\n buildDataSuffix(ctx: DataSuffixContext): Hex | undefined {\n const clientExt = extractClientExtension(ctx.paymentPayload.extensions);\n\n const a =\n typeof clientExt?.a === \"string\" && BUILDER_CODE_PATTERN.test(clientExt.a)\n ? clientExt.a\n : undefined;\n const s = resolveServiceCodes(clientExt?.s);\n\n const data: BuilderCodeExtensionData = {\n ...(this.config.builderCode && { w: this.config.builderCode }),\n ...(a && { a }),\n ...(s.length > 0 && { s }),\n };\n\n if (!data.a && !data.w && (!data.s || (Array.isArray(data.s) && data.s.length === 0))) {\n return undefined;\n }\n\n return encodeBuilderCodeSuffix(data);\n }\n}\n","import { x402Client, x402HTTPClient } from '@x402/core/client';\nimport type { PaymentPolicy } from '@x402/core/client';\nimport { ExactEvmScheme } from '@x402/evm';\nimport { BuilderCodeClientExtension } from '@x402/extensions/builder-code';\nimport type { ClientEvmSigner } from '@x402/evm';\nimport type { PaymentRequired, PaymentRequirements } from '@x402/core/types';\nimport type { TypedDataDefinition } from 'viem';\nimport { getAddress } from 'viem';\nimport { CliError } from './errors';\nimport { USDC_ADDRESS } from './usdc';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * x402 exact-scheme payment construction (spec 10 sanctioned deps: @x402/* +\n * viem). Given the server's decoded PAYMENT-REQUIRED and a structural signer, it\n * produces the `PAYMENT-SIGNATURE` header the paid re-request carries. The base\n * exact flow needs only `address` + `signTypedData` (no RPC), so this never\n * touches the network, the signature is an offline EIP-712/EIP-3009 authorization\n * the facilitator settles.\n */\n\nexport interface BuiltPayment {\n /** The `PAYMENT-SIGNATURE` header(s) to attach to the paid re-request. */\n headers: Record<string, string>;\n /** The exact amount authorized, atomic USDC (from accepts[0]). */\n amountAtomic: bigint;\n}\n\n/**\n * Build the payment header for the first advertised requirement. The read route\n * advertises exactly one `exact` requirement; if the scheme isn't the exact-EVM\n * this CLI supports, it fails PAYMENT_FAILED rather than signing something the\n * facilitator will reject.\n */\n/**\n * The only asset/chain pairs this CLI will EVER sign for: canonical USDC on\n * Base, and on Base Sepolia for previews. Both are 6-decimal, so every USD\n * display and cap in the CLI stays truthful. Without this pin, a hostile or\n * misconfigured 402 (reachable via --base-url or a candidate URL) could name\n * any eip155 chain, any token, and its own payTo: the signed EIP-3009\n * authorization is a bearer instrument valid on that chain's contract directly,\n * no Tenjin facilitator required. Asset compare is checksummed via getAddress.\n */\nconst ALLOWED_USDC_BY_NETWORK: Record<string, string> = {\n 'eip155:8453': USDC_ADDRESS,\n 'eip155:84532': '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n};\n\n/**\n * Tenjin's registered ERC-8021 builder code, claimed here as the client service\n * code (`s`). One value, not a CLI-specific second code: Base registers one code\n * per account, and Schema 2 already separates the roles structurally, so a\n * payment this CLI brokers to Tenjin carries the code in BOTH `a` (seller) and\n * `s` (client) while a payment to any other seller carries it only in `s`. It\n * names the client, never the user, and is public by construction. Attribution\n * only, never proof: the ERC-8021 suffix is emitted by the FACILITATOR at\n * settlement, so a facilitator without the extension registered puts nothing on\n * chain, and `s` is unauthenticated and seller-writable, so an occurrence of the\n * code proves nothing about who brokered the payment. Constant, not\n * configurable: a per-install override would make the code meaningless as a\n * client identity.\n */\nexport const TENJIN_CLI_BUILDER_CODE = 'bc_kc0altv3';\n\n/**\n * Drop any `builder-code.info.s` the SELLER declared, leaving its `a` and schema\n * untouched. Without this a 402 that names its own `s` silently wins: the SDK\n * merges the enriched payload onto the server's extensions as the base and\n * copies a client field only where the server left it unset, so the client\n * extension's `{info: {s}}` is discarded and Tenjin's code never reaches the\n * payload, with no error. Narrowing the top-level `extensions` key set does not\n * help, the override lives inside the entry. Per ERC-8021 Schema 2 `a` is the\n * seller's to declare and `s` is the client's, so removing it here restores the\n * roles rather than suppressing seller data, and this is client-side composition\n * of what we send: nothing off-spec goes on the wire.\n */\nfunction withoutSellerServiceCodes(\n extensions: PaymentRequired['extensions'],\n key: string,\n): PaymentRequired['extensions'] {\n const entry = extensions?.[key];\n if (!isPlainObject(entry) || !isPlainObject(entry.info)) return extensions;\n const info = { ...entry.info };\n delete info.s;\n return { ...extensions, [key]: { ...entry, info } };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * THE SDK OWNS SELECTION AND PAYLOAD; THIS FILE OWNS WHAT THIS WALLET HOLDS.\n *\n * `x402Client.selectPaymentRequirements` filters a 402's `accepts` to the\n * (network, scheme) pairs registered on the client, runs the registered\n * policies, and picks from what survives. Registering the exact EVM scheme for\n * the Base networks therefore IS the selection rule, and the canonical-USDC pin\n * below is a policy, which the SDK applies as a veto and never as a licence.\n *\n * It replaces a hand-rolled `accepts[0]`, which registered the scheme for\n * whatever network the FIRST entry named and then agreed that entry was\n * supported. Against CoinMarketCap, whose live 402 lists seven entries with BNB\n * chain first and Base USDC third, every quote was priced against an\n * 18-decimal BNB entry and refused before anything was signed.\n */\nexport function createPayerClient(getSigner: () => TenjinSigner): {\n core: x402Client;\n http: x402HTTPClient;\n builderCodeKey: string;\n} {\n // LAZY, so selection can run before the wallet is opened: the price check and\n // the advertised-terms check both happen before a signer exists on purpose,\n // and neither reads an address.\n const lazy: ClientEvmSigner = {\n get address() {\n return getSigner().address;\n },\n signTypedData: (message) =>\n getSigner().signTypedData(message as unknown as TypedDataDefinition),\n };\n const core = new x402Client();\n for (const network of Object.keys(ALLOWED_USDC_BY_NETWORK)) {\n core.register(network as `${string}:${string}`, new ExactEvmScheme(lazy));\n }\n core.registerPolicy(canonicalUsdcOnly);\n // The SDK fires this hook only for sellers whose 402 advertises\n // `builder-code`, so a seller that never declared it still gets an\n // extension-free payload. That gating is why attribution stays spec-clean.\n const builderCode = new BuilderCodeClientExtension(TENJIN_CLI_BUILDER_CODE);\n core.registerExtension(builderCode);\n return { core, http: new x402HTTPClient(core), builderCodeKey: builderCode.key };\n}\n\n/**\n * A VETO, in the SDK's own vocabulary: the scheme registration already limits\n * the networks, and this drops any entry on one of them whose asset is not that\n * network's canonical USDC. Without it a seller could advertise `exact` on Base\n * in a token of its choosing, and the signed EIP-3009 authorization is valid\n * against that token's contract directly, no facilitator required.\n */\nconst canonicalUsdcOnly: PaymentPolicy = (_version, requirements) =>\n requirements.filter((requirement) => {\n const allowed = ALLOWED_USDC_BY_NETWORK[requirement.network];\n if (allowed === undefined) return false;\n try {\n return getAddress(requirement.asset) === getAddress(allowed);\n } catch {\n return false;\n }\n });\n\n/**\n * The entry the SDK would pay, or undefined when it would pay none. The SDK\n * throws on an empty selection; callers here have their own named refusals, so\n * the throw becomes an absence. `want` narrows it to a caller's advertised\n * terms, which is a further veto and never a widening.\n */\nexport function selectPayableRequirement(\n core: x402Client,\n paymentRequired: PaymentRequired,\n want?: { network?: string; asset?: string },\n): PaymentRequirements | undefined {\n const approved = supportedEntries(paymentRequired);\n if (want === undefined) return sdkSelect(core, paymentRequired) ?? approved[0];\n // A caller holding terms wants the supported entry that matches THEM, so the\n // search runs over the same policy-approved set the SDK would choose from\n // rather than over the raw list.\n return approved.find(\n (r) =>\n (want.network === undefined || r.network === want.network) &&\n (want.asset === undefined || sameAsset(r.asset, want.asset)),\n );\n}\n\n/**\n * The entries the SDK's selection would consider: the registered networks, the\n * `exact` scheme, and the canonical-USDC policy. Spelled here because the\n * SDK's own `selectPaymentRequirements` is typed private at 2.17.0, so this is\n * the set the adapter below falls back to and the set a terms-narrowed search\n * runs over; the SIGNATURE always goes through the SDK either way.\n */\nfunction supportedEntries(paymentRequired: PaymentRequired): PaymentRequirements[] {\n return canonicalUsdcOnly(paymentRequired.x402Version, paymentRequired.accepts).filter(\n (r) => r.scheme === 'exact' && ALLOWED_USDC_BY_NETWORK[r.network] !== undefined,\n );\n}\n\n/**\n * The SDK's own selector when it is reachable. `selectPaymentRequirements` is\n * public at runtime and carries the registered schemes, the policies and the\n * configured selector, which is exactly the decision wanted here; it is only\n * typed private, so the call is adapted rather than reimplemented, and an SDK\n * that ever removes it degrades to {@link supportedEntries} rather than\n * breaking. A test pins the two agreeing on a multi-network challenge.\n */\nfunction sdkSelect(\n core: x402Client,\n paymentRequired: PaymentRequired,\n): PaymentRequirements | undefined {\n const select = (\n core as unknown as {\n selectPaymentRequirements?: (\n version: number,\n accepts: readonly PaymentRequirements[],\n ) => PaymentRequirements;\n }\n ).selectPaymentRequirements;\n if (typeof select !== 'function') return undefined;\n try {\n return select.call(core, paymentRequired.x402Version, paymentRequired.accepts);\n } catch {\n return undefined;\n }\n}\n\nfunction sameAsset(a: string, b: string): boolean {\n try {\n return getAddress(a) === getAddress(b);\n } catch {\n return a.toLowerCase() === b.toLowerCase();\n }\n}\n\n/** The named refusal when a 402 advertises nothing this wallet can pay. */\nexport function noPayableRequirement(accepts: readonly PaymentRequirements[]): CliError {\n const advertised = accepts.map((a) => `${a.scheme}/${a.network}/${a.asset}`);\n return new CliError(\n 'PAYMENT_FAILED',\n accepts.length === 0\n ? 'The 402 advertised no payment requirements.'\n : 'The 402 advertises nothing this CLI can pay: it lists no exact-scheme entry in canonical USDC on Base.',\n {\n fix: 'Only USDC on Base (eip155:8453), or Base Sepolia for previews, is supported. Nothing was signed.',\n ...(accepts.length > 0 ? { details: { advertised } } : {}),\n },\n );\n}\n\n/**\n * Build the `PAYMENT-SIGNATURE` header for the entry the SDK selects, or for\n * `only` when the caller has already selected one and wants that exact deal\n * signed. Selection, payload construction and header encoding are all the\n * SDK's; what stays here is which networks and assets this wallet holds.\n */\nexport async function buildExactPayment(\n paymentRequired: PaymentRequired,\n signer: TenjinSigner,\n only?: PaymentRequirements,\n): Promise<BuiltPayment> {\n const { core, http, builderCodeKey } = createPayerClient(() => signer);\n const requirement = only ?? selectPayableRequirement(core, paymentRequired);\n if (requirement === undefined) throw noPayableRequirement(paymentRequired.accepts);\n\n // A single-accept challenge, so nothing can re-select a different or costlier\n // entry between the check and the signature. Narrow `accepts` only, or the\n // builder-code hook never fires.\n const bound: PaymentRequired = {\n ...paymentRequired,\n accepts: [requirement],\n extensions: withoutSellerServiceCodes(paymentRequired.extensions, builderCodeKey),\n };\n\n let headers: Record<string, string>;\n try {\n const payload = await http.createPaymentPayload(bound);\n headers = http.encodePaymentSignatureHeader(payload);\n } catch (err) {\n throw new CliError('PAYMENT_FAILED', 'Could not build the x402 payment authorization.', {\n fix: 'Confirm the wallet is a supported EVM account on the advertised network.',\n cause: err,\n });\n }\n\n return { headers, amountAtomic: BigInt(requirement.amount) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,QAAsB,cAAtB,MAAiC;;AAAjC,YAAA,cAAA;AAOa,YAAA,aAAa;AAE1B,QAAa,OAAb,cAA0B,YAAW;MAEnC,YAAY,GAAS;AACnB,cAAK;AACL,YAAI,CAAC,QAAA,WAAW,KAAK,CAAC;AAAG,gBAAM,IAAI,MAAM,0CAA0C;AACnF,aAAK,MAAM;MACb;MAEA,WAAQ;AACN,eAAO,KAAK;MACd;MAEA,WAAQ;AACN,eAAO;MACT;MAEA,IAAI,QAAK;AACP,eAAO,EAAC,CAAC,KAAK,GAAG,GAAG,EAAC;MACvB;;AAlBF,YAAA,OAAA;AAqBA,QAAa,QAAb,cA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AA,IACxC;AAAA,EACF;AACF;AAEA,SAAS,aAAa,KAAuC;AAC3D,QAAM,SAAS,IAAI,OAAO,uBAAuB;AACjD,MAAI,WAAW,OAAW,QAAO;AACjC,MAAI;AACF,UAAM,SAAS,4BAA4B,MAAM;AACjD,UAAM,KAAM,OAAqC;AACjD,WAAO,OAAO,OAAO,WAAW,KAAK;AAAA,EACvC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,cAAc,MAAgD;AACrE,MAAI,KAAK,YAAY,QAAW;AAC9B,UAAM,IAAI,SAAS,YAAY,qDAAqD;AAAA,EACtF;AACA,SAAO,KAAK;AACd;","names":["UsedValueState","Type","DataType","_a","http","Ajv","DiscrError","require_applicator","require_unevaluated","require_core","require_validation","Ajv2020","Ajv","addFormats","client","Ajv","Ajv2020","addFormats","x402Version","client","getAddress","client","x402Version","getAddress","x402Version","x402Version","getAddress","http","preview"]}
|