@xtandard/kit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +71 -2
- package/bin/xtandard-kit.mjs +3 -0
- package/dist/base-path-BJugWLNO.cjs +42 -0
- package/dist/base-path-BJugWLNO.cjs.map +1 -0
- package/dist/base-path-CDb4In5E.mjs +31 -0
- package/dist/base-path-CDb4In5E.mjs.map +1 -0
- package/dist/basic-Qtriv0xS.mjs +176 -0
- package/dist/basic-Qtriv0xS.mjs.map +1 -0
- package/dist/basic-ZaO92-lB.cjs +199 -0
- package/dist/basic-ZaO92-lB.cjs.map +1 -0
- package/dist/bin.cjs +126 -0
- package/dist/bin.cjs.map +1 -0
- package/dist/bin.d.cts +20 -0
- package/dist/bin.d.mts +20 -0
- package/dist/bin.mjs +125 -0
- package/dist/bin.mjs.map +1 -0
- package/dist/cas-CuPSaXBV.cjs +23 -0
- package/dist/cas-CuPSaXBV.cjs.map +1 -0
- package/dist/cas-CzA-yECx.mjs +18 -0
- package/dist/cas-CzA-yECx.mjs.map +1 -0
- package/dist/chunk-DakpK96I.cjs +43 -0
- package/dist/contract-B3UPXXLx.d.cts +30 -0
- package/dist/contract-B3UPXXLx.d.mts +30 -0
- package/dist/contract-BDPNvjtp.d.mts +64 -0
- package/dist/contract-BEdfGTPs.mjs +85 -0
- package/dist/contract-BEdfGTPs.mjs.map +1 -0
- package/dist/contract-BIVzAn4f.d.cts +64 -0
- package/dist/contract-BvgtswLX.d.cts +75 -0
- package/dist/contract-BvgtswLX.d.mts +75 -0
- package/dist/contract-DUj9P3Vt.d.cts +72 -0
- package/dist/contract-DUj9P3Vt.d.mts +72 -0
- package/dist/contract-wAEMDmYG.cjs +132 -0
- package/dist/contract-wAEMDmYG.cjs.map +1 -0
- package/dist/drizzle-BElCHWri.d.mts +115 -0
- package/dist/drizzle-BXaQXCr0.cjs +232 -0
- package/dist/drizzle-BXaQXCr0.cjs.map +1 -0
- package/dist/drizzle-CEpahWQB.d.cts +115 -0
- package/dist/drizzle-DxnelsPT.mjs +197 -0
- package/dist/drizzle-DxnelsPT.mjs.map +1 -0
- package/dist/duration-7WpAK-xe.mjs +52 -0
- package/dist/duration-7WpAK-xe.mjs.map +1 -0
- package/dist/duration-DVA0Fzkx.cjs +63 -0
- package/dist/duration-DVA0Fzkx.cjs.map +1 -0
- package/dist/duration-FPwbmWIU.d.cts +35 -0
- package/dist/duration-FPwbmWIU.d.mts +35 -0
- package/dist/entry-adapters-bun.cjs +10 -0
- package/dist/entry-adapters-bun.cjs.map +1 -0
- package/dist/entry-adapters-bun.d.cts +10 -0
- package/dist/entry-adapters-bun.d.mts +10 -0
- package/dist/entry-adapters-bun.mjs +9 -0
- package/dist/entry-adapters-bun.mjs.map +1 -0
- package/dist/entry-adapters-elysia.cjs +54 -0
- package/dist/entry-adapters-elysia.cjs.map +1 -0
- package/dist/entry-adapters-elysia.d.cts +38 -0
- package/dist/entry-adapters-elysia.d.mts +38 -0
- package/dist/entry-adapters-elysia.mjs +53 -0
- package/dist/entry-adapters-elysia.mjs.map +1 -0
- package/dist/entry-adapters-express.cjs +27 -0
- package/dist/entry-adapters-express.cjs.map +1 -0
- package/dist/entry-adapters-express.d.cts +24 -0
- package/dist/entry-adapters-express.d.mts +24 -0
- package/dist/entry-adapters-express.mjs +26 -0
- package/dist/entry-adapters-express.mjs.map +1 -0
- package/dist/entry-adapters-hono.cjs +33 -0
- package/dist/entry-adapters-hono.cjs.map +1 -0
- package/dist/entry-adapters-hono.d.cts +36 -0
- package/dist/entry-adapters-hono.d.mts +36 -0
- package/dist/entry-adapters-hono.mjs +30 -0
- package/dist/entry-adapters-hono.mjs.map +1 -0
- package/dist/entry-adapters-next.cjs +19 -0
- package/dist/entry-adapters-next.cjs.map +1 -0
- package/dist/entry-adapters-next.d.cts +35 -0
- package/dist/entry-adapters-next.d.mts +35 -0
- package/dist/entry-adapters-next.mjs +18 -0
- package/dist/entry-adapters-next.mjs.map +1 -0
- package/dist/entry-adapters-node.cjs +7 -0
- package/dist/entry-adapters-node.d.cts +2 -0
- package/dist/entry-adapters-node.d.mts +2 -0
- package/dist/entry-adapters-node.mjs +2 -0
- package/dist/entry-auth-basic.cjs +5 -0
- package/dist/entry-auth-basic.d.cts +83 -0
- package/dist/entry-auth-basic.d.mts +83 -0
- package/dist/entry-auth-basic.mjs +2 -0
- package/dist/entry-auth-delegated.cjs +28 -0
- package/dist/entry-auth-delegated.cjs.map +1 -0
- package/dist/entry-auth-delegated.d.cts +36 -0
- package/dist/entry-auth-delegated.d.mts +36 -0
- package/dist/entry-auth-delegated.mjs +27 -0
- package/dist/entry-auth-delegated.mjs.map +1 -0
- package/dist/entry-auth-none.cjs +4 -0
- package/dist/entry-auth-none.d.cts +25 -0
- package/dist/entry-auth-none.d.mts +25 -0
- package/dist/entry-auth-none.mjs +2 -0
- package/dist/entry-auth.cjs +0 -0
- package/dist/entry-auth.d.cts +2 -0
- package/dist/entry-auth.d.mts +2 -0
- package/dist/entry-auth.mjs +1 -0
- package/dist/entry-authorization-delegated.cjs +27 -0
- package/dist/entry-authorization-delegated.cjs.map +1 -0
- package/dist/entry-authorization-delegated.d.cts +31 -0
- package/dist/entry-authorization-delegated.d.mts +31 -0
- package/dist/entry-authorization-delegated.mjs +26 -0
- package/dist/entry-authorization-delegated.mjs.map +1 -0
- package/dist/entry-authorization-none.cjs +3 -0
- package/dist/entry-authorization-none.d.cts +18 -0
- package/dist/entry-authorization-none.d.mts +18 -0
- package/dist/entry-authorization-none.mjs +2 -0
- package/dist/entry-authorization-roles.cjs +3 -0
- package/dist/entry-authorization-roles.d.cts +2 -0
- package/dist/entry-authorization-roles.d.mts +2 -0
- package/dist/entry-authorization-roles.mjs +2 -0
- package/dist/entry-authorization.cjs +35 -0
- package/dist/entry-authorization.cjs.map +1 -0
- package/dist/entry-authorization.d.cts +2 -0
- package/dist/entry-authorization.d.mts +2 -0
- package/dist/entry-authorization.mjs +34 -0
- package/dist/entry-authorization.mjs.map +1 -0
- package/dist/entry-build.cjs +481 -0
- package/dist/entry-build.cjs.map +1 -0
- package/dist/entry-build.d.cts +355 -0
- package/dist/entry-build.d.mts +355 -0
- package/dist/entry-build.mjs +460 -0
- package/dist/entry-build.mjs.map +1 -0
- package/dist/entry-cli.cjs +368 -0
- package/dist/entry-cli.cjs.map +1 -0
- package/dist/entry-cli.d.cts +275 -0
- package/dist/entry-cli.d.mts +275 -0
- package/dist/entry-cli.mjs +355 -0
- package/dist/entry-cli.mjs.map +1 -0
- package/dist/entry-drizzle-mysql.cjs +36 -0
- package/dist/entry-drizzle-mysql.cjs.map +1 -0
- package/dist/entry-drizzle-mysql.d.cts +55 -0
- package/dist/entry-drizzle-mysql.d.mts +55 -0
- package/dist/entry-drizzle-mysql.mjs +34 -0
- package/dist/entry-drizzle-mysql.mjs.map +1 -0
- package/dist/entry-drizzle-pg.cjs +38 -0
- package/dist/entry-drizzle-pg.cjs.map +1 -0
- package/dist/entry-drizzle-pg.d.cts +78 -0
- package/dist/entry-drizzle-pg.d.mts +78 -0
- package/dist/entry-drizzle-pg.mjs +36 -0
- package/dist/entry-drizzle-pg.mjs.map +1 -0
- package/dist/entry-drizzle-sqlite.cjs +20 -0
- package/dist/entry-drizzle-sqlite.cjs.map +1 -0
- package/dist/entry-drizzle-sqlite.d.cts +22 -0
- package/dist/entry-drizzle-sqlite.d.mts +22 -0
- package/dist/entry-drizzle-sqlite.mjs +19 -0
- package/dist/entry-drizzle-sqlite.mjs.map +1 -0
- package/dist/entry-hooks-log.cjs +32 -0
- package/dist/entry-hooks-log.cjs.map +1 -0
- package/dist/entry-hooks-log.d.cts +36 -0
- package/dist/entry-hooks-log.d.mts +36 -0
- package/dist/entry-hooks-log.mjs +31 -0
- package/dist/entry-hooks-log.mjs.map +1 -0
- package/dist/entry-hooks.cjs +10 -0
- package/dist/entry-hooks.d.cts +2 -0
- package/dist/entry-hooks.d.mts +2 -0
- package/dist/entry-hooks.mjs +2 -0
- package/dist/entry-server-router.cjs +235 -0
- package/dist/entry-server-router.cjs.map +1 -0
- package/dist/entry-server-router.d.cts +193 -0
- package/dist/entry-server-router.d.mts +193 -0
- package/dist/entry-server-router.mjs +228 -0
- package/dist/entry-server-router.mjs.map +1 -0
- package/dist/entry-server.cjs +344 -0
- package/dist/entry-server.cjs.map +1 -0
- package/dist/entry-server.d.cts +230 -0
- package/dist/entry-server.d.mts +230 -0
- package/dist/entry-server.mjs +322 -0
- package/dist/entry-server.mjs.map +1 -0
- package/dist/entry-site.cjs +1083 -0
- package/dist/entry-site.cjs.map +1 -0
- package/dist/entry-site.d.cts +336 -0
- package/dist/entry-site.d.mts +336 -0
- package/dist/entry-site.mjs +1060 -0
- package/dist/entry-site.mjs.map +1 -0
- package/dist/entry-storage-cloudflare-kv.cjs +51 -0
- package/dist/entry-storage-cloudflare-kv.cjs.map +1 -0
- package/dist/entry-storage-cloudflare-kv.d.cts +52 -0
- package/dist/entry-storage-cloudflare-kv.d.mts +52 -0
- package/dist/entry-storage-cloudflare-kv.mjs +50 -0
- package/dist/entry-storage-cloudflare-kv.mjs.map +1 -0
- package/dist/entry-storage-drizzle-internals.cjs +6 -0
- package/dist/entry-storage-drizzle-internals.d.cts +2 -0
- package/dist/entry-storage-drizzle-internals.d.mts +2 -0
- package/dist/entry-storage-drizzle-internals.mjs +2 -0
- package/dist/entry-storage-drizzle.cjs +4 -0
- package/dist/entry-storage-drizzle.d.cts +3 -0
- package/dist/entry-storage-drizzle.d.mts +3 -0
- package/dist/entry-storage-drizzle.mjs +2 -0
- package/dist/entry-storage-file.cjs +306 -0
- package/dist/entry-storage-file.cjs.map +1 -0
- package/dist/entry-storage-file.d.cts +76 -0
- package/dist/entry-storage-file.d.mts +76 -0
- package/dist/entry-storage-file.mjs +301 -0
- package/dist/entry-storage-file.mjs.map +1 -0
- package/dist/entry-storage-libsql-internals.cjs +7 -0
- package/dist/entry-storage-libsql-internals.d.cts +3 -0
- package/dist/entry-storage-libsql-internals.d.mts +3 -0
- package/dist/entry-storage-libsql-internals.mjs +3 -0
- package/dist/entry-storage-libsql.cjs +3 -0
- package/dist/entry-storage-libsql.d.cts +2 -0
- package/dist/entry-storage-libsql.d.mts +2 -0
- package/dist/entry-storage-libsql.mjs +2 -0
- package/dist/entry-storage-memory.cjs +78 -0
- package/dist/entry-storage-memory.cjs.map +1 -0
- package/dist/entry-storage-memory.d.cts +35 -0
- package/dist/entry-storage-memory.d.mts +35 -0
- package/dist/entry-storage-memory.mjs +77 -0
- package/dist/entry-storage-memory.mjs.map +1 -0
- package/dist/entry-storage-mongodb-internals.cjs +5 -0
- package/dist/entry-storage-mongodb-internals.d.cts +2 -0
- package/dist/entry-storage-mongodb-internals.d.mts +2 -0
- package/dist/entry-storage-mongodb-internals.mjs +2 -0
- package/dist/entry-storage-mongodb.cjs +3 -0
- package/dist/entry-storage-mongodb.d.cts +2 -0
- package/dist/entry-storage-mongodb.d.mts +2 -0
- package/dist/entry-storage-mongodb.mjs +2 -0
- package/dist/entry-storage-postgres-internals.cjs +6 -0
- package/dist/entry-storage-postgres-internals.d.cts +2 -0
- package/dist/entry-storage-postgres-internals.d.mts +2 -0
- package/dist/entry-storage-postgres-internals.mjs +2 -0
- package/dist/entry-storage-postgres.cjs +4 -0
- package/dist/entry-storage-postgres.d.cts +2 -0
- package/dist/entry-storage-postgres.d.mts +2 -0
- package/dist/entry-storage-postgres.mjs +2 -0
- package/dist/entry-storage-redis-internals.cjs +7 -0
- package/dist/entry-storage-redis-internals.d.cts +2 -0
- package/dist/entry-storage-redis-internals.d.mts +2 -0
- package/dist/entry-storage-redis-internals.mjs +2 -0
- package/dist/entry-storage-redis.cjs +4 -0
- package/dist/entry-storage-redis.d.cts +2 -0
- package/dist/entry-storage-redis.d.mts +2 -0
- package/dist/entry-storage-redis.mjs +2 -0
- package/dist/entry-storage-sqlite-internals.cjs +7 -0
- package/dist/entry-storage-sqlite-internals.d.cts +3 -0
- package/dist/entry-storage-sqlite-internals.d.mts +3 -0
- package/dist/entry-storage-sqlite-internals.mjs +3 -0
- package/dist/entry-storage-sqlite.cjs +3 -0
- package/dist/entry-storage-sqlite.d.cts +2 -0
- package/dist/entry-storage-sqlite.d.mts +2 -0
- package/dist/entry-storage-sqlite.mjs +2 -0
- package/dist/entry-storage-testing.cjs +801 -0
- package/dist/entry-storage-testing.cjs.map +1 -0
- package/dist/entry-storage-testing.d.cts +150 -0
- package/dist/entry-storage-testing.d.mts +150 -0
- package/dist/entry-storage-testing.mjs +790 -0
- package/dist/entry-storage-testing.mjs.map +1 -0
- package/dist/entry-storage-unstorage.cjs +78 -0
- package/dist/entry-storage-unstorage.cjs.map +1 -0
- package/dist/entry-storage-unstorage.d.cts +30 -0
- package/dist/entry-storage-unstorage.d.mts +30 -0
- package/dist/entry-storage-unstorage.mjs +77 -0
- package/dist/entry-storage-unstorage.mjs.map +1 -0
- package/dist/entry-storage.cjs +114 -0
- package/dist/entry-storage.cjs.map +1 -0
- package/dist/entry-storage.d.cts +152 -0
- package/dist/entry-storage.d.mts +152 -0
- package/dist/entry-storage.mjs +91 -0
- package/dist/entry-storage.mjs.map +1 -0
- package/dist/entry-testing.cjs +79 -0
- package/dist/entry-testing.cjs.map +1 -0
- package/dist/entry-testing.d.cts +55 -0
- package/dist/entry-testing.d.mts +55 -0
- package/dist/entry-testing.mjs +77 -0
- package/dist/entry-testing.mjs.map +1 -0
- package/dist/entry-tokens.cjs +4 -0
- package/dist/entry-tokens.d.cts +85 -0
- package/dist/entry-tokens.d.mts +85 -0
- package/dist/entry-tokens.mjs +2 -0
- package/dist/entry-ui-embed.cjs +131 -0
- package/dist/entry-ui-embed.cjs.map +1 -0
- package/dist/entry-ui-embed.d.cts +87 -0
- package/dist/entry-ui-embed.d.mts +87 -0
- package/dist/entry-ui-embed.mjs +127 -0
- package/dist/entry-ui-embed.mjs.map +1 -0
- package/dist/entry-ui.cjs +795 -0
- package/dist/entry-ui.cjs.map +1 -0
- package/dist/entry-ui.d.cts +574 -0
- package/dist/entry-ui.d.mts +574 -0
- package/dist/entry-ui.mjs +731 -0
- package/dist/entry-ui.mjs.map +1 -0
- package/dist/entry-util.cjs +145 -0
- package/dist/entry-util.cjs.map +1 -0
- package/dist/entry-util.d.cts +85 -0
- package/dist/entry-util.d.mts +85 -0
- package/dist/entry-util.mjs +130 -0
- package/dist/entry-util.mjs.map +1 -0
- package/dist/http-B_rTnLW9.cjs +235 -0
- package/dist/http-B_rTnLW9.cjs.map +1 -0
- package/dist/http-CxYM7kPT.d.mts +133 -0
- package/dist/http-DVdVI6kJ.mjs +164 -0
- package/dist/http-DVdVI6kJ.mjs.map +1 -0
- package/dist/http-XBVRk8uo.d.cts +133 -0
- package/dist/index.cjs +8 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +6 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.mjs +7 -0
- package/dist/index.mjs.map +1 -0
- package/dist/json-CCyzstIm.d.cts +44 -0
- package/dist/json-CCyzstIm.d.mts +44 -0
- package/dist/json-CM7TwYQ7.cjs +92 -0
- package/dist/json-CM7TwYQ7.cjs.map +1 -0
- package/dist/json-CmM1M5Kz.mjs +63 -0
- package/dist/json-CmM1M5Kz.mjs.map +1 -0
- package/dist/keys-Bwubabk0.mjs +73 -0
- package/dist/keys-Bwubabk0.mjs.map +1 -0
- package/dist/keys-DQrwxDKI.cjs +126 -0
- package/dist/keys-DQrwxDKI.cjs.map +1 -0
- package/dist/kv-sqlite-B6iTLOx2.d.cts +20 -0
- package/dist/kv-sqlite-CHOdIMJ-.cjs +77 -0
- package/dist/kv-sqlite-CHOdIMJ-.cjs.map +1 -0
- package/dist/kv-sqlite-DIIPfflJ.mjs +66 -0
- package/dist/kv-sqlite-DIIPfflJ.mjs.map +1 -0
- package/dist/kv-sqlite-Tx4UedJs.d.mts +20 -0
- package/dist/libsql-0160BubR.d.mts +65 -0
- package/dist/libsql-BZmRZIqt.d.cts +65 -0
- package/dist/libsql-CiBfVtbS.cjs +103 -0
- package/dist/libsql-CiBfVtbS.cjs.map +1 -0
- package/dist/libsql-CkOjQINi.mjs +86 -0
- package/dist/libsql-CkOjQINi.mjs.map +1 -0
- package/dist/mongodb--Cuj7V_9.cjs +150 -0
- package/dist/mongodb--Cuj7V_9.cjs.map +1 -0
- package/dist/mongodb-DGtsolQ2.d.cts +61 -0
- package/dist/mongodb-JMizy4Wg.mjs +127 -0
- package/dist/mongodb-JMizy4Wg.mjs.map +1 -0
- package/dist/mongodb-xGEU5Gwz.d.mts +61 -0
- package/dist/node-B1Djcwfi.d.cts +57 -0
- package/dist/node-B1Djcwfi.d.mts +57 -0
- package/dist/node-BYjocCbU.mjs +167 -0
- package/dist/node-BYjocCbU.mjs.map +1 -0
- package/dist/node-DFFqYRk-.cjs +201 -0
- package/dist/node-DFFqYRk-.cjs.map +1 -0
- package/dist/none-BEY7Kc_-.mjs +33 -0
- package/dist/none-BEY7Kc_-.mjs.map +1 -0
- package/dist/none-BoQ6-30P.cjs +33 -0
- package/dist/none-BoQ6-30P.cjs.map +1 -0
- package/dist/none-CHwVkQL-.cjs +49 -0
- package/dist/none-CHwVkQL-.cjs.map +1 -0
- package/dist/none-yu3qC47E.mjs +23 -0
- package/dist/none-yu3qC47E.mjs.map +1 -0
- package/dist/peer-BIjBFzwQ.cjs +56 -0
- package/dist/peer-BIjBFzwQ.cjs.map +1 -0
- package/dist/peer-CTHMzOdn.mjs +40 -0
- package/dist/peer-CTHMzOdn.mjs.map +1 -0
- package/dist/portal-container-CJIcau3B.mjs +610 -0
- package/dist/portal-container-CJIcau3B.mjs.map +1 -0
- package/dist/portal-container-Ca1NxrLE.cjs +774 -0
- package/dist/portal-container-Ca1NxrLE.cjs.map +1 -0
- package/dist/postgres-BJzxKBk0.d.cts +72 -0
- package/dist/postgres-CA8_XcAE.cjs +164 -0
- package/dist/postgres-CA8_XcAE.cjs.map +1 -0
- package/dist/postgres-RfQMgAsj.d.mts +72 -0
- package/dist/postgres-aDiBmNzr.mjs +135 -0
- package/dist/postgres-aDiBmNzr.mjs.map +1 -0
- package/dist/redis-B2AS4xAQ.cjs +259 -0
- package/dist/redis-B2AS4xAQ.cjs.map +1 -0
- package/dist/redis-B362ofBw.d.cts +159 -0
- package/dist/redis-CahNAVTW.d.mts +159 -0
- package/dist/redis-hdoKymfG.mjs +218 -0
- package/dist/redis-hdoKymfG.mjs.map +1 -0
- package/dist/roles-7JPrQXZa.mjs +46 -0
- package/dist/roles-7JPrQXZa.mjs.map +1 -0
- package/dist/roles-B_8QqJ3j.cjs +56 -0
- package/dist/roles-B_8QqJ3j.cjs.map +1 -0
- package/dist/roles-DLISB4T3.d.mts +41 -0
- package/dist/roles-DQbbtUPW.d.cts +41 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/dist/scope-css-BN3jf0ly.cjs +315 -0
- package/dist/scope-css-BN3jf0ly.cjs.map +1 -0
- package/dist/scope-css-BuJfRCsE.mjs +256 -0
- package/dist/scope-css-BuJfRCsE.mjs.map +1 -0
- package/dist/scoped-BRoE1W1x.cjs +175 -0
- package/dist/scoped-BRoE1W1x.cjs.map +1 -0
- package/dist/scoped-cFBbotCh.mjs +164 -0
- package/dist/scoped-cFBbotCh.mjs.map +1 -0
- package/dist/sqlite-B2g1JJz1.d.cts +47 -0
- package/dist/sqlite-BIPIlxfj.d.mts +47 -0
- package/dist/sqlite-BntoYaXZ.cjs +79 -0
- package/dist/sqlite-BntoYaXZ.cjs.map +1 -0
- package/dist/sqlite-DYJDcu7p.mjs +62 -0
- package/dist/sqlite-DYJDcu7p.mjs.map +1 -0
- package/dist/table-BrioFSra.d.cts +11 -0
- package/dist/table-BrioFSra.d.mts +11 -0
- package/dist/theme-context-DzZ1otaD.d.cts +270 -0
- package/dist/theme-context-J65pythD.d.mts +270 -0
- package/dist/ui/styles.css +239 -0
- package/dist/util-Dnj5T-yw.mjs +39 -0
- package/dist/util-Dnj5T-yw.mjs.map +1 -0
- package/dist/util-dAnTK9x-.cjs +74 -0
- package/dist/util-dAnTK9x-.cjs.map +1 -0
- package/dist/validation-B-atP968.mjs +191 -0
- package/dist/validation-B-atP968.mjs.map +1 -0
- package/dist/validation-BJifGoB2.d.mts +122 -0
- package/dist/validation-DLnzBVJr.cjs +258 -0
- package/dist/validation-DLnzBVJr.cjs.map +1 -0
- package/dist/validation-tfV2qhbD.d.cts +122 -0
- package/package.json +715 -4
- package/tsconfig/assets.d.ts +21 -0
- package/tsconfig/base.json +21 -0
- package/tsconfig/react.json +9 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-css-BuJfRCsE.mjs","names":[],"sources":["../src/build/api-surface.ts","../src/build/fix-elysia2-types.ts","../src/build/scope-css.ts"],"sourcesContent":["/**\n * API-surface snapshots (ADR 0003). For every `exports` subpath of a built package,\n * {@link apiSurface} records the runtime export names (by importing the ESM entry) and the exported\n * declaration names (from its `.d.mts`, through the TypeScript compiler API). {@link diffApiSurface}\n * compares two snapshots; a migration PR, or a kit patch, must show no removals.\n *\n * Needs the optional peer `typescript` for the declaration names.\n *\n * @module\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { importPeer } from \"../internal/peer.ts\";\n\n/** The surface of one subpath. */\nexport interface SubpathSurface {\n /** Runtime export names (sorted), from importing the ESM entry. */\n runtime: string[];\n /** Every exported name in the `.d.mts` (types and values, sorted). */\n types: string[];\n /** Why the entry could not be imported or read, when it couldn't. */\n error?: string;\n}\n\n/** A package's API surface, as written by `xtandard-kit api-surface`. */\nexport interface ApiSurface {\n package: string;\n version: string;\n /** Keyed by subpath (`\".\"`, `\"./storage/redis\"`…), in `exports` order. */\n subpaths: Record<string, SubpathSurface>;\n}\n\n/** The ESM runtime file and declaration file an `exports` entry points at. */\nexport interface ExportTarget {\n runtime?: string;\n types?: string;\n}\n\ntype Conditions = string | null | { [condition: string]: Conditions } | Conditions[];\n\nfunction pick(value: Conditions | undefined, keys: readonly string[]): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) {\n for (const v of value) {\n const hit = pick(v, keys);\n if (hit) return hit;\n }\n return undefined;\n }\n for (const key of keys) {\n const hit = pick(value[key], keys);\n if (hit) return hit;\n }\n return undefined;\n}\n\n/**\n * Resolve an `exports` value to its ESM runtime file and declaration file (paths as written in\n * `package.json`). `.d.mts` is derived from an `.mjs` target when no `types` condition is given.\n */\nexport function exportTarget(value: Conditions): ExportTarget {\n const importSide =\n value && typeof value === \"object\" && !Array.isArray(value) && \"import\" in value\n ? value.import\n : value;\n const runtime = pick(importSide ?? null, [\"node\", \"default\"]);\n // `types` only ever comes from a condition; a bare string target is the runtime file.\n const conditionTypes = (v: Conditions | undefined) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? pick(v.types ?? null, [\"default\"])\n : undefined;\n let types = conditionTypes(importSide) ?? conditionTypes(value);\n if (!types && runtime)\n types = runtime.replace(/\\.m?js$/, (ext) => (ext === \".mjs\" ? \".d.mts\" : \".d.ts\"));\n const isCode = (p?: string) => (p && /\\.[cm]?[jt]s$/.test(p) ? p : undefined);\n return {\n runtime: isCode(runtime),\n types: types && /\\.d\\.[cm]?ts$/.test(types) ? types : undefined,\n };\n}\n\n/** Locate the package root: `dir` itself, or its parent when `dir` is the `dist/` folder. */\nexport function packageRoot(dir: string): string {\n const abs = resolve(dir);\n if (existsSync(join(abs, \"package.json\"))) return abs;\n if (existsSync(join(dirname(abs), \"package.json\"))) return dirname(abs);\n throw new Error(`api-surface: no package.json in ${abs} or its parent`);\n}\n\nasync function declarationNames(files: string[]): Promise<Map<string, string[]>> {\n const out = new Map<string, string[]>();\n if (files.length === 0) return out;\n // `typescript` is CommonJS: its API is the default export under Node ESM.\n const ts = await importPeer(\"typescript\", \"@xtandard/kit/build\", async () => {\n const mod = await import(\"typescript\");\n return mod.default ?? mod;\n });\n const program = ts.createProgram(files, {\n noEmit: true,\n skipLibCheck: true,\n allowJs: false,\n types: [],\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n target: ts.ScriptTarget.ESNext,\n });\n const checker = program.getTypeChecker();\n for (const file of files) {\n const source = program.getSourceFile(file);\n const symbol = source && checker.getSymbolAtLocation(source);\n out.set(\n file,\n symbol\n ? checker\n .getExportsOfModule(symbol)\n .map((s) => s.getName())\n .sort()\n : [],\n );\n }\n return out;\n}\n\n/**\n * Snapshot the API surface of the built package at `dir` (the package root, or its `dist/`).\n * Wildcard, CSS, JSON and `./package.json` exports are skipped.\n */\nexport async function apiSurface(dir: string): Promise<ApiSurface> {\n const root = packageRoot(dir);\n const pkg = JSON.parse(await readFile(join(root, \"package.json\"), \"utf8\")) as {\n name?: string;\n version?: string;\n exports?: Record<string, Conditions> | Conditions;\n };\n const exportsField: Record<string, Conditions> =\n pkg.exports && typeof pkg.exports === \"object\" && !Array.isArray(pkg.exports)\n ? Object.keys(pkg.exports).every((k) => k.startsWith(\".\"))\n ? (pkg.exports as Record<string, Conditions>)\n : { \".\": pkg.exports as Conditions }\n : pkg.exports\n ? { \".\": pkg.exports as Conditions }\n : {};\n\n const targets: [string, ExportTarget][] = [];\n for (const [subpath, value] of Object.entries(exportsField)) {\n if (subpath.includes(\"*\") || subpath === \"./package.json\") continue;\n const target = exportTarget(value);\n if (target.runtime || target.types) targets.push([subpath, target]);\n }\n\n const typeFiles = targets\n .map(([, t]) => t.types && join(root, t.types))\n .filter((f): f is string => Boolean(f && existsSync(f)));\n const names = await declarationNames(typeFiles);\n\n const subpaths: Record<string, SubpathSurface> = {};\n for (const [subpath, target] of targets) {\n const surface: SubpathSurface = { runtime: [], types: [] };\n const errors: string[] = [];\n if (target.runtime) {\n try {\n // A fresh module instance per snapshot: Node caches ESM by URL, so a second snapshot\n // in the same process (before/after a rebuild) would otherwise see the old exports.\n const url = `${pathToFileURL(join(root, target.runtime)).href}?surface=${Date.now()}`;\n const mod = (await import(url)) as object;\n surface.runtime = Object.keys(mod).sort();\n } catch (error) {\n errors.push(`import ${target.runtime}: ${(error as Error).message}`);\n }\n }\n if (target.types) {\n const file = join(root, target.types);\n if (names.has(file)) surface.types = names.get(file)!;\n else errors.push(`missing ${target.types}`);\n }\n if (errors.length) surface.error = errors.join(\"; \");\n subpaths[subpath] = surface;\n }\n return { package: pkg.name ?? basename(root), version: pkg.version ?? \"0.0.0\", subpaths };\n}\n\n/** The result of {@link diffApiSurface}: one line per change, e.g. `\"./storage: runtime foo\"`. */\nexport interface ApiSurfaceDiff {\n removed: string[];\n added: string[];\n}\n\n/** Compare two snapshots. Anything in `before` but not in `after` is a removal. */\nexport function diffApiSurface(before: ApiSurface, after: ApiSurface): ApiSurfaceDiff {\n const removed: string[] = [];\n const added: string[] = [];\n const keys = new Set([...Object.keys(before.subpaths), ...Object.keys(after.subpaths)]);\n for (const subpath of keys) {\n const a = before.subpaths[subpath];\n const b = after.subpaths[subpath];\n if (!b) {\n removed.push(`${subpath}: subpath`);\n continue;\n }\n if (!a) {\n added.push(`${subpath}: subpath`);\n continue;\n }\n for (const kind of [\"runtime\", \"types\"] as const) {\n const was = new Set(a[kind]);\n const now = new Set(b[kind]);\n for (const name of was) if (!now.has(name)) removed.push(`${subpath}: ${kind} ${name}`);\n for (const name of now) if (!was.has(name)) added.push(`${subpath}: ${kind} ${name}`);\n }\n if (b.error && !a.error) removed.push(`${subpath}: now fails (${b.error})`);\n }\n return { removed, added };\n}\n","/**\n * Post-build step for a product's `/elysia2` declarations.\n *\n * `tsc -p tsconfig.elysia2.build.json` type-checks against the `elysia-v2` devDep alias (the repos\n * develop on Elysia 1), and where tsc has to name an inferred type it may spell the alias:\n * `import(\"elysia-v2/types\")`. Consumers install Elysia 2 as plain `elysia`, so the specifier is\n * rewritten.\n *\n * @module\n */\n\nimport { readdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/** Options for {@link fixElysia2Types}. */\nexport interface FixElysia2TypesOptions {\n /** The declarations directory; `\"dist/types-elysia2\"` by default. */\n dir?: string;\n /** The alias to rewrite; `\"elysia-v2\"` by default. */\n from?: string;\n /** What it becomes; `\"elysia\"` by default. */\n to?: string;\n}\n\n/** Rewrite `\"<from>\"` / `\"<from>/…\"` module specifiers to `<to>` in a string. */\nexport function rewriteSpecifiers(source: string, from = \"elysia-v2\", to = \"elysia\"): string {\n const name = from.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return source.replace(new RegExp(`([\"'])${name}(\\\\/[^\"']*)?\\\\1`, \"g\"), `$1${to}$2$1`);\n}\n\n/**\n * Rewrite the alias in every `.d.ts`/`.d.mts`/`.d.cts` under `dir` (recursively). Resolves to the\n * number of files changed.\n */\nexport async function fixElysia2Types(options: FixElysia2TypesOptions = {}): Promise<number> {\n const dir = options.dir ?? \"dist/types-elysia2\";\n let rewritten = 0;\n for (const rel of await readdir(dir, { recursive: true })) {\n if (!/\\.d\\.[mc]?ts$/.test(rel)) continue;\n const path = join(dir, rel);\n const src = await readFile(path, \"utf8\");\n const out = rewriteSpecifiers(src, options.from, options.to);\n if (out !== src) {\n await writeFile(path, out);\n rewritten++;\n }\n }\n return rewritten;\n}\n","/**\n * Scoping for a product's React-embed stylesheet.\n *\n * The embed build emits `dist/react.css` as a full, unscoped Tailwind build: global preflight\n * resets (`*`, `button`, `h1`, `a`, …) plus generic utilities (`.flex`, `.border`, …). A host app\n * importing it (`@xtandard/<product>/react/styles.css`) would get its whole page restyled.\n *\n * {@link scopeCss} prefixes every rule with the embed's wrapper class. The design-token\n * `:root`/`html` blocks (including `:root[data-theme=\"dark\"]` and `:root.dark`) and the `body`\n * surface rule are re-homed onto the wrapper itself, and keyframe steps are left alone. The\n * standalone SPA build (`dist/ui`) is not processed: it legitimately owns the whole document.\n *\n * Needs the optional peers `postcss` and `postcss-prefix-selector`.\n *\n * @module\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { importPeer } from \"../internal/peer.ts\";\n\nconst SUBPATH = \"@xtandard/kit/build\";\n\n/** `\".xtandard-flags\"` → `\".xtandard-flags\"`; a bare `\"xtandard-flags\"` gets its dot. */\nexport function normalizeScope(scope: string): string {\n const s = scope.trim();\n const withDot = s.startsWith(\".\") ? s : `.${s}`;\n if (!/^\\.[A-Za-z_-][\\w-]*$/.test(withDot)) {\n throw new Error(`scope must be a single class name such as \".xtandard-flags\", got \"${scope}\"`);\n }\n return withDot;\n}\n\n/**\n * Prefix every rule in `css` with `scope` (a class, e.g. `\".xtandard-flags\"`), re-homing\n * `:root`/`html`/`:host`/`body` onto the wrapper and leaving keyframe steps alone. Pure.\n */\nexport async function scopeCss(css: string, scope: string): Promise<string> {\n const prefix = normalizeScope(scope);\n const [{ default: postcss }, { default: prefixSelector }] = await Promise.all([\n importPeer(\"postcss\", SUBPATH, () => import(\"postcss\")),\n importPeer(\"postcss-prefix-selector\", SUBPATH, () => import(\"postcss-prefix-selector\")),\n ]);\n const result = await postcss([\n prefixSelector({\n prefix,\n transform(prefix: string, selector: string, prefixedSelector: string): string {\n const s = selector.trim();\n // Keyframe steps (`from`, `to`, `47%`, `0%,50%`) are not element selectors.\n if (/^(\\d+(\\.\\d+)?%|from|to)$/.test(s)) return selector;\n // Design tokens live on :root/html — re-home them onto the wrapper so the embed's own\n // scope carries them (the host <html> is untouched). `body` carries the page surface\n // (background, text colour, font): the wrapper is the embed's \"page\", so it gets them too,\n // otherwise its text inherits the host's colour over the dashboard's own surfaces.\n if (/^(:root|html|:host|body)$/.test(s)) return prefix;\n // Compound root selectors — the dark tokens on `:root[data-theme=\"dark\"]`, `:root.dark`,\n // `:root:not(…)` — become the wrapper with the same qualifier\n // (`.xtandard-flags[data-theme=\"dark\"]`), matching the `data-theme` the embed sets on its\n // own wrapper.\n const compound = /^(?::root|html)([[:.].*)$/.exec(s);\n if (compound) return `${prefix}${compound[1]}`;\n return prefixedSelector;\n },\n }),\n ]).process(css, { from: undefined });\n return result.css;\n}\n\n/**\n * Rules that would restyle the host document if they escaped the scope: preflight resets, the\n * universal custom-property rule, and token blocks left on `:root`/`html`/`body`. Returns the\n * offending rule fragments (empty when fully scoped).\n */\nexport function findUnscopedLeaks(css: string, scope: string): string[] {\n const prefix = normalizeScope(scope);\n // A fragment is scoped when the class appears as a whole class token (not `.x-flags-other`).\n const scoped = new RegExp(`${prefix.replace(/[.*+?^${}()|[\\]\\\\-]/g, \"\\\\$&\")}(?![\\\\w-])`);\n return css\n .split(\"}\")\n .filter((rule) =>\n /text-size-adjust|^\\s*\\*[,{]|^\\s*(button|a|h1|table)[,{]|^\\s*(:root|html|body)[[,{:.\\s]/.test(\n rule,\n ),\n )\n .filter((rule) => !scoped.test(rule));\n}\n\n/** What {@link scopeCssFile} did. */\nexport interface ScopeCssFileResult {\n /** The file that was rewritten. */\n path: string;\n /** Unscoped fragments left after scoping (the command fails when non-empty). */\n leaks: string[];\n}\n\n/**\n * Scope a stylesheet on disk in place (`xtandard-kit scope-embed-css --scope … --css …`), then\n * check it for leaks.\n */\nexport async function scopeCssFile(path: string, scope: string): Promise<ScopeCssFileResult> {\n const scoped = await scopeCss(await readFile(path, \"utf8\"), scope);\n await writeFile(path, scoped);\n return { path, leaks: findUnscopedLeaks(scoped, scope) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,SAAS,KAAK,OAA+B,MAA6C;CACxF,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,KAAK,MAAM,KAAK,OAAO;GACrB,MAAM,MAAM,KAAK,GAAG,IAAI;GACxB,IAAI,KAAK,OAAO;EAClB;EACA;CACF;CACA,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,MAAM,KAAK,MAAM,MAAM,IAAI;EACjC,IAAI,KAAK,OAAO;CAClB;AAEF;;;;;AAMA,SAAgB,aAAa,OAAiC;CAC5D,MAAM,aACJ,SAAS,OAAO,UAAU,Y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C-signed grants that scope their bearer to a
|
|
5
|
+
* subset of a panel (one tenant, one customer, a few actions) for a limited
|
|
6
|
+
* time. The products call them portal tokens (`whpt_`, `audpt_`, `entpt_`) or
|
|
7
|
+
* viewer tokens (`lvt_`); the mechanics are the same, the claims differ.
|
|
8
|
+
*
|
|
9
|
+
* Wire format:
|
|
10
|
+
*
|
|
11
|
+
* ```txt
|
|
12
|
+
* <prefix><base64url(JSON { ...claims, exp })>.<base64url(HMAC-SHA256(secret, payloadPart))>
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* - The secret is an **arbitrary string**, fed to the HMAC as raw UTF-8 bytes.
|
|
16
|
+
* An empty secret is rejected (it would let anyone mint tokens).
|
|
17
|
+
* - The signature is checked first, in constant time; claims are never
|
|
18
|
+
* interpreted before it passes.
|
|
19
|
+
* - `exp` is unix epoch milliseconds.
|
|
20
|
+
* - **Rotation:** `verify` accepts a list of secrets. Mint with the new secret
|
|
21
|
+
* first in the list and keep the old one until its tokens have expired. The
|
|
22
|
+
* wire format has no key id, so tokens minted by older releases keep
|
|
23
|
+
* verifying.
|
|
24
|
+
*
|
|
25
|
+
* Zero dependencies (Web Crypto only), so it runs on Workers and in browsers.
|
|
26
|
+
*
|
|
27
|
+
* @module
|
|
28
|
+
*/
|
|
29
|
+
/** Base class of every scoped-token error. Maps to HTTP 401 at the API layer. */
|
|
30
|
+
var TokenError = class extends Error {
|
|
31
|
+
constructor(message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "TokenError";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
const encoder = new TextEncoder();
|
|
37
|
+
const base64urlEncode = (bytes) => {
|
|
38
|
+
let binary = "";
|
|
39
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
40
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
41
|
+
};
|
|
42
|
+
const base64urlDecode = (value) => {
|
|
43
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new TypeError("not base64url");
|
|
44
|
+
const padded = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
45
|
+
const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
46
|
+
const bytes = new Uint8Array(binary.length);
|
|
47
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
48
|
+
return bytes;
|
|
49
|
+
};
|
|
50
|
+
/** HMAC-SHA256 keyed by the raw UTF-8 bytes of the (arbitrary-string) secret. */
|
|
51
|
+
async function hmac(secret, content) {
|
|
52
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
53
|
+
name: "HMAC",
|
|
54
|
+
hash: "SHA-256"
|
|
55
|
+
}, false, ["sign"]);
|
|
56
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(content)));
|
|
57
|
+
}
|
|
58
|
+
/** Constant-time byte comparison (XOR accumulate — no early exit on content). */
|
|
59
|
+
function timingSafeEqual(a, b) {
|
|
60
|
+
if (a.length !== b.length) return false;
|
|
61
|
+
let diff = 0;
|
|
62
|
+
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
|
63
|
+
return diff === 0;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Create a product's scoped-token codec.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* import { createScopedTokens } from "@xtandard/kit/tokens";
|
|
71
|
+
*
|
|
72
|
+
* const portal = createScopedTokens({
|
|
73
|
+
* prefix: "whpt_",
|
|
74
|
+
* ttl: "7d",
|
|
75
|
+
* label: "portal token",
|
|
76
|
+
* errorName: "PortalTokenError",
|
|
77
|
+
* validateClaims: (p) => {
|
|
78
|
+
* if (typeof p.app !== "string" || !p.app) throw new Error("missing application");
|
|
79
|
+
* return { app: p.app };
|
|
80
|
+
* },
|
|
81
|
+
* });
|
|
82
|
+
* const token = await portal.create(secret, { app: "acme" });
|
|
83
|
+
* const { claims } = await portal.verify(secret, token); // { app: "acme" }
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
function createScopedTokens(options) {
|
|
87
|
+
const { prefix } = options;
|
|
88
|
+
if (!prefix) throw new TypeError("createScopedTokens: a prefix is required");
|
|
89
|
+
const label = options.label ?? "token";
|
|
90
|
+
const errorName = options.errorName ?? "TokenError";
|
|
91
|
+
const clock = options.now ?? Date.now;
|
|
92
|
+
const defaultTtl = require_duration.durationToMs(options.ttl);
|
|
93
|
+
class ScopedTokenError extends TokenError {
|
|
94
|
+
constructor(message) {
|
|
95
|
+
super(message);
|
|
96
|
+
this.name = errorName;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const secretsOf = (secret) => {
|
|
100
|
+
const list = typeof secret === "string" ? [secret] : [...secret];
|
|
101
|
+
if (list.length === 0 || list.some((s) => typeof s !== "string" || s.length === 0)) throw new ScopedTokenError(`A ${label} secret is required`);
|
|
102
|
+
return list;
|
|
103
|
+
};
|
|
104
|
+
const validate = (payload) => {
|
|
105
|
+
try {
|
|
106
|
+
return options.validateClaims(payload);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (error instanceof TokenError) throw error;
|
|
109
|
+
throw new ScopedTokenError(`Invalid ${label}: ${error instanceof Error ? error.message : String(error)}`);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
prefix,
|
|
114
|
+
TokenError: ScopedTokenError,
|
|
115
|
+
matches: (value) => value.startsWith(prefix),
|
|
116
|
+
async create(secret, claims, createOptions = {}) {
|
|
117
|
+
const [signing] = secretsOf(secret);
|
|
118
|
+
const { exp: _ignored, ...rest } = claims;
|
|
119
|
+
validate(rest);
|
|
120
|
+
const ttl = createOptions.expiresIn === void 0 ? defaultTtl : require_duration.durationToMs(createOptions.expiresIn);
|
|
121
|
+
const payload = {
|
|
122
|
+
...rest,
|
|
123
|
+
exp: (createOptions.now ?? clock()) + ttl
|
|
124
|
+
};
|
|
125
|
+
const payloadPart = base64urlEncode(encoder.encode(JSON.stringify(payload)));
|
|
126
|
+
return `${prefix}${payloadPart}.${base64urlEncode(await hmac(signing, payloadPart))}`;
|
|
127
|
+
},
|
|
128
|
+
async verify(secret, token, verifyOptions = {}) {
|
|
129
|
+
const secrets = secretsOf(secret);
|
|
130
|
+
if (typeof token !== "string" || !token.startsWith(prefix)) throw new ScopedTokenError(`Invalid ${label}: missing ${prefix} prefix`);
|
|
131
|
+
const parts = token.slice(prefix.length).split(".");
|
|
132
|
+
if (parts.length !== 2 || !parts[0] || !parts[1]) throw new ScopedTokenError(`Invalid ${label}: malformed`);
|
|
133
|
+
const [payloadPart, signaturePart] = parts;
|
|
134
|
+
let candidate;
|
|
135
|
+
try {
|
|
136
|
+
candidate = base64urlDecode(signaturePart);
|
|
137
|
+
} catch {
|
|
138
|
+
throw new ScopedTokenError(`Invalid ${label}: malformed signature`);
|
|
139
|
+
}
|
|
140
|
+
let signed = false;
|
|
141
|
+
for (const s of secrets) if (timingSafeEqual(await hmac(s, payloadPart), candidate)) signed = true;
|
|
142
|
+
if (!signed) throw new ScopedTokenError(`Invalid ${label}: signature mismatch`);
|
|
143
|
+
let payload;
|
|
144
|
+
try {
|
|
145
|
+
payload = JSON.parse(new TextDecoder().decode(base64urlDecode(payloadPart)));
|
|
146
|
+
} catch {
|
|
147
|
+
throw new ScopedTokenError(`Invalid ${label}: malformed payload`);
|
|
148
|
+
}
|
|
149
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) throw new ScopedTokenError(`Invalid ${label}: malformed payload`);
|
|
150
|
+
const { exp, ...rest } = payload;
|
|
151
|
+
if (typeof exp !== "number" || !Number.isFinite(exp)) throw new ScopedTokenError(`Invalid ${label}: missing expiry`);
|
|
152
|
+
const claims = validate(rest);
|
|
153
|
+
if ((verifyOptions.now ?? clock()) >= exp) throw new ScopedTokenError(`${label[0]?.toUpperCase()}${label.slice(1)} has expired`);
|
|
154
|
+
return {
|
|
155
|
+
claims,
|
|
156
|
+
expiresAt: exp
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
Object.defineProperty(exports, "TokenError", {
|
|
163
|
+
enumerable: true,
|
|
164
|
+
get: function() {
|
|
165
|
+
return TokenError;
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
Object.defineProperty(exports, "createScopedTokens", {
|
|
169
|
+
enumerable: true,
|
|
170
|
+
get: function() {
|
|
171
|
+
return createScopedTokens;
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
//# sourceMappingURL=scoped-BRoE1W1x.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scoped-BRoE1W1x.cjs","names":["durationToMs"],"sources":["../src/tokens/scoped.ts"],"sourcesContent":["/**\n * Scoped tokens: compact HMAC-signed grants that scope their bearer to a\n * subset of a panel (one tenant, one customer, a few actions) for a limited\n * time. The products call them portal tokens (`whpt_`, `audpt_`, `entpt_`) or\n * viewer tokens (`lvt_`); the mechanics are the same, the claims differ.\n *\n * Wire format:\n *\n * ```txt\n * <prefix><base64url(JSON { ...claims, exp })>.<base64url(HMAC-SHA256(secret, payloadPart))>\n * ```\n *\n * - The secret is an **arbitrary string**, fed to the HMAC as raw UTF-8 bytes.\n * An empty secret is rejected (it would let anyone mint tokens).\n * - The signature is checked first, in constant time; claims are never\n * interpreted before it passes.\n * - `exp` is unix epoch milliseconds.\n * - **Rotation:** `verify` accepts a list of secrets. Mint with the new secret\n * first in the list and keep the old one until its tokens have expired. The\n * wire format has no key id, so tokens minted by older releases keep\n * verifying.\n *\n * Zero dependencies (Web Crypto only), so it runs on Workers and in browsers.\n *\n * @module\n */\n\nimport { durationToMs, type Duration } from \"../util/duration.ts\";\n\n/** Base class of every scoped-token error. Maps to HTTP 401 at the API layer. */\nexport class TokenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TokenError\";\n }\n}\n\n/** One secret, or a rotation list (the first one signs, all of them verify). */\nexport type TokenSecret = string | readonly string[];\n\n/** Options for {@link createScopedTokens}. */\nexport interface ScopedTokensOptions<Claims extends object> {\n /** Token prefix, e.g. `\"whpt_\"`. A product's tokens depend on it, so it never changes. */\n prefix: string;\n /** Default lifetime when `create` gets no `expiresIn`. */\n ttl: Duration;\n /**\n * Check the decoded payload and return the typed claims (without `exp`), or\n * throw. Runs on `create` too, so a bad grant can't be minted. A thrown\n * non-{@link TokenError} becomes `Invalid <label>: <message>`.\n */\n validateClaims: (payload: Record<string, unknown>) => Claims;\n /** Clock (unix ms). Default `Date.now`. */\n now?: () => number;\n /** How errors name the token: `\"portal token\"`, `\"viewer token\"`. Default `\"token\"`. */\n label?: string;\n /**\n * The `name` of the errors this instance throws (the products map\n * `PortalTokenError` / `ViewerTokenError` to 401 by name). Default\n * `\"TokenError\"`.\n */\n errorName?: string;\n}\n\n/** Per-call options for {@link ScopedTokens.create}. */\nexport interface CreateTokenOptions {\n /** Lifetime. Default: the instance `ttl`. */\n expiresIn?: Duration;\n /** Clock override (unix ms) for this call. */\n now?: number;\n}\n\n/** A verified token: its claims and expiry. */\nexport interface VerifiedToken<Claims> {\n claims: Claims;\n /** Expiry, unix epoch milliseconds. */\n expiresAt: number;\n}\n\n/** What {@link createScopedTokens} returns. */\nexport interface ScopedTokens<Claims extends object> {\n /** The token prefix. */\n readonly prefix: string;\n /** Mint a token for `claims`. Call it server-side, after your own authentication. */\n create(secret: TokenSecret, claims: Claims, options?: CreateTokenOptions): Promise<string>;\n /** Verify format, signature, claims and expiry; throws {@link ScopedTokens.TokenError}. */\n verify(\n secret: TokenSecret,\n token: string,\n options?: { now?: number },\n ): Promise<VerifiedToken<Claims>>;\n /** True when `value` looks like one of these tokens (prefix only, no verification). */\n matches(value: string): boolean;\n /** The error class this instance throws (a {@link TokenError} subclass named `errorName`). */\n readonly TokenError: new (message: string) => TokenError;\n}\n\nconst encoder = new TextEncoder();\n\nconst base64urlEncode = (bytes: Uint8Array): string => {\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\n\nconst base64urlDecode = (value: string): Uint8Array => {\n if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new TypeError(\"not base64url\");\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const binary = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n};\n\n/** HMAC-SHA256 keyed by the raw UTF-8 bytes of the (arbitrary-string) secret. */\nasync function hmac(secret: string, content: string): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret) as BufferSource,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(content)));\n}\n\n/** Constant-time byte comparison (XOR accumulate — no early exit on content). */\nfunction timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number);\n return diff === 0;\n}\n\n/**\n * Create a product's scoped-token codec.\n *\n * @example\n * ```ts\n * import { createScopedTokens } from \"@xtandard/kit/tokens\";\n *\n * const portal = createScopedTokens({\n * prefix: \"whpt_\",\n * ttl: \"7d\",\n * label: \"portal token\",\n * errorName: \"PortalTokenError\",\n * validateClaims: (p) => {\n * if (typeof p.app !== \"string\" || !p.app) throw new Error(\"missing application\");\n * return { app: p.app };\n * },\n * });\n * const token = await portal.create(secret, { app: \"acme\" });\n * const { claims } = await portal.verify(secret, token); // { app: \"acme\" }\n * ```\n */\nexport function createScopedTokens<Claims extends object>(\n options: ScopedTokensOptions<Claims>,\n): ScopedTokens<Claims> {\n const { prefix } = options;\n if (!prefix) throw new TypeError(\"createScopedTokens: a prefix is required\");\n const label = options.label ?? \"token\";\n const errorName = options.errorName ?? \"TokenError\";\n const clock = options.now ?? Date.now;\n const defaultTtl = durationToMs(options.ttl);\n\n class ScopedTokenError extends TokenError {\n constructor(message: string) {\n super(message);\n this.name = errorName;\n }\n }\n\n const secretsOf = (secret: TokenSecret): string[] => {\n const list = typeof secret === \"string\" ? [secret] : [...secret];\n if (list.length === 0 || list.some((s) => typeof s !== \"string\" || s.length === 0)) {\n throw new ScopedTokenError(`A ${label} secret is required`);\n }\n return list;\n };\n\n const validate = (payload: Record<string, unknown>): Claims => {\n try {\n return options.validateClaims(payload);\n } catch (error) {\n if (error instanceof TokenError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n throw new ScopedTokenError(`Invalid ${label}: ${message}`);\n }\n };\n\n return {\n prefix,\n TokenError: ScopedTokenError,\n matches: (value) => value.startsWith(prefix),\n\n async create(secret, claims, createOptions = {}) {\n const [signing] = secretsOf(secret) as [string];\n const { exp: _ignored, ...rest } = claims as Record<string, unknown>;\n validate(rest);\n const ttl =\n createOptions.expiresIn === undefined ? defaultTtl : durationToMs(createOptions.expiresIn);\n const payload = { ...rest, exp: (createOptions.now ?? clock()) + ttl };\n const payloadPart = base64urlEncode(encoder.encode(JSON.stringify(payload)));\n const signature = base64urlEncode(await hmac(signing, payloadPart));\n return `${prefix}${payloadPart}.${signature}`;\n },\n\n async verify(secret, token, verifyOptions = {}) {\n const secrets = secretsOf(secret);\n if (typeof token !== \"string\" || !token.startsWith(prefix)) {\n throw new ScopedTokenError(`Invalid ${label}: missing ${prefix} prefix`);\n }\n const parts = token.slice(prefix.length).split(\".\");\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new ScopedTokenError(`Invalid ${label}: malformed`);\n }\n const [payloadPart, signaturePart] = parts as [string, string];\n\n // Signature first: never interpret unauthenticated claims.\n let candidate: Uint8Array;\n try {\n candidate = base64urlDecode(signaturePart);\n } catch {\n throw new ScopedTokenError(`Invalid ${label}: malformed signature`);\n }\n let signed = false;\n for (const s of secrets) {\n // Check every secret (no early exit), so timing doesn't reveal which one matched.\n if (timingSafeEqual(await hmac(s, payloadPart), candidate)) signed = true;\n }\n if (!signed) throw new ScopedTokenError(`Invalid ${label}: signature mismatch`);\n\n let payload: unknown;\n try {\n payload = JSON.parse(new TextDecoder().decode(base64urlDecode(payloadPart)));\n } catch {\n throw new ScopedTokenError(`Invalid ${label}: malformed payload`);\n }\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n throw new ScopedTokenError(`Invalid ${label}: malformed payload`);\n }\n const { exp, ...rest } = payload as Record<string, unknown>;\n if (typeof exp !== \"number\" || !Number.isFinite(exp)) {\n throw new ScopedTokenError(`Invalid ${label}: missing expiry`);\n }\n const claims = validate(rest);\n if ((verifyOptions.now ?? clock()) >= exp) {\n throw new ScopedTokenError(`${label[0]?.toUpperCase()}${label.slice(1)} has expired`);\n }\n return { claims, expiresAt: exp };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AA8DA,MAAM,UAAU,IAAI,YAAY;AAEhC,MAAM,mBAAmB,UAA8B;CACrD,IAAI,SAAS;CACb,KAAK,MAAM,KAAK,OAAO,UAAU,OAAO,aAAa,CAAC;CACtD,OAAO,KAAK,MAAM,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE;AAC/E;AAEA,MAAM,mBAAmB,UAA8B;CACrD,IAAI,CAAC,mBAAmB,KAAK,KAAK,GAAG,MAAM,IAAI,UAAU,eAAe;CACxE,MAAM,SAAS,MAAM,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG;CACzD,MAAM,SAAS,KAAK,SAAS,IAAI,QAAQ,IAAK,OAAO,SAAS,KAAM,CAA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,WAAW,MAAM,sBAAsB;GACpE;GACA,IAAI,SAAS;GACb,KAAK,MAAM,KAAK,SAEd,IAAI,gBAAgB,MAAM,KAAK,GAAG,WAAW,GAAG,SAAS,GAAG,SAAS;GAEvE,IAAI,CAAC,QAAQ,MAAM,IAAI,iBAAiB,WAAW,MAAM,qBAAqB;GAE9E,IAAI;GACJ,IAAI;IACF,UAAU,KAAK,MAAM,IAAI,YAAY,EAAE,OAAO,gBAAgB,WAAW,CAAC,CAAC;GAC7E,QAAQ;IACN,MAAM,IAAI,iBAAiB,WAAW,MAAM,oBAAoB;GAClE;GACA,IAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,MAAM,QAAQ,OAAO,GAC1E,MAAM,IAAI,iBAAiB,WAAW,MAAM,oBAAoB;GAElE,MAAM,EAAE,KAAK,GAAG,SAAS;GACzB,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,SAAS,GAAG,GACjD,MAAM,IAAI,iBAAiB,WAAW,MAAM,iBAAiB;GAE/D,MAAM,SAAS,SAAS,IAAI;GAC5B,KAAK,cAAc,OAAO,MAAM,MAAM,KACpC,MAAM,IAAI,iBAAiB,GAAG,MAAM,IAAI,YAAY,IAAI,MAAM,MAAM,CAAC,EAAE,aAAa;GAEtF,OAAO;IAAE;IAAQ,WAAW;GAAI;EAClC;CACF;AACF"}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { t as durationToMs } from "./duration-7WpAK-xe.mjs";
|
|
2
|
+
//#region src/tokens/scoped.ts
|
|
3
|
+
/**
|
|
4
|
+
* Scoped tokens: compact HMAC-signed grants that scope their bearer to a
|
|
5
|
+
* subset of a panel (one tenant, one customer, a few actions) for a limited
|
|
6
|
+
* time. The products call them portal tokens (`whpt_`, `audpt_`, `entpt_`) or
|
|
7
|
+
* viewer tokens (`lvt_`); the mechanics are the same, the claims differ.
|
|
8
|
+
*
|
|
9
|
+
* Wire format:
|
|
10
|
+
*
|
|
11
|
+
* ```txt
|
|
12
|
+
* <prefix><base64url(JSON { ...claims, exp })>.<base64url(HMAC-SHA256(secret, payloadPart))>
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* - The secret is an **arbitrary string**, fed to the HMAC as raw UTF-8 bytes.
|
|
16
|
+
* An empty secret is rejected (it would let anyone mint tokens).
|
|
17
|
+
* - The signature is checked first, in constant time; claims are never
|
|
18
|
+
* interpreted before it passes.
|
|
19
|
+
* - `exp` is unix epoch milliseconds.
|
|
20
|
+
* - **Rotation:** `verify` accepts a list of secrets. Mint with the new secret
|
|
21
|
+
* first in the list and keep the old one until its tokens have expired. The
|
|
22
|
+
* wire format has no key id, so tokens minted by older releases keep
|
|
23
|
+
* verifying.
|
|
24
|
+
*
|
|
25
|
+
* Zero dependencies (Web Crypto only), so it runs on Workers and in browsers.
|
|
26
|
+
*
|
|
27
|
+
* @module
|
|
28
|
+
*/
|
|
29
|
+
/** Base class of every scoped-token error. Maps to HTTP 401 at the API layer. */
|
|
30
|
+
var TokenError = class extends Error {
|
|
31
|
+
constructor(message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "TokenError";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
const encoder = new TextEncoder();
|
|
37
|
+
const base64urlEncode = (bytes) => {
|
|
38
|
+
let binary = "";
|
|
39
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
40
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
41
|
+
};
|
|
42
|
+
const base64urlDecode = (value) => {
|
|
43
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new TypeError("not base64url");
|
|
44
|
+
const padded = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
45
|
+
const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
46
|
+
const bytes = new Uint8Array(binary.length);
|
|
47
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
48
|
+
return bytes;
|
|
49
|
+
};
|
|
50
|
+
/** HMAC-SHA256 keyed by the raw UTF-8 bytes of the (arbitrary-string) secret. */
|
|
51
|
+
async function hmac(secret, content) {
|
|
52
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
53
|
+
name: "HMAC",
|
|
54
|
+
hash: "SHA-256"
|
|
55
|
+
}, false, ["sign"]);
|
|
56
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(content)));
|
|
57
|
+
}
|
|
58
|
+
/** Constant-time byte comparison (XOR accumulate — no early exit on content). */
|
|
59
|
+
function timingSafeEqual(a, b) {
|
|
60
|
+
if (a.length !== b.length) return false;
|
|
61
|
+
let diff = 0;
|
|
62
|
+
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
|
63
|
+
return diff === 0;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Create a product's scoped-token codec.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* import { createScopedTokens } from "@xtandard/kit/tokens";
|
|
71
|
+
*
|
|
72
|
+
* const portal = createScopedTokens({
|
|
73
|
+
* prefix: "whpt_",
|
|
74
|
+
* ttl: "7d",
|
|
75
|
+
* label: "portal token",
|
|
76
|
+
* errorName: "PortalTokenError",
|
|
77
|
+
* validateClaims: (p) => {
|
|
78
|
+
* if (typeof p.app !== "string" || !p.app) throw new Error("missing application");
|
|
79
|
+
* return { app: p.app };
|
|
80
|
+
* },
|
|
81
|
+
* });
|
|
82
|
+
* const token = await portal.create(secret, { app: "acme" });
|
|
83
|
+
* const { claims } = await portal.verify(secret, token); // { app: "acme" }
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
function createScopedTokens(options) {
|
|
87
|
+
const { prefix } = options;
|
|
88
|
+
if (!prefix) throw new TypeError("createScopedTokens: a prefix is required");
|
|
89
|
+
const label = options.label ?? "token";
|
|
90
|
+
const errorName = options.errorName ?? "TokenError";
|
|
91
|
+
const clock = options.now ?? Date.now;
|
|
92
|
+
const defaultTtl = durationToMs(options.ttl);
|
|
93
|
+
class ScopedTokenError extends TokenError {
|
|
94
|
+
constructor(message) {
|
|
95
|
+
super(message);
|
|
96
|
+
this.name = errorName;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const secretsOf = (secret) => {
|
|
100
|
+
const list = typeof secret === "string" ? [secret] : [...secret];
|
|
101
|
+
if (list.length === 0 || list.some((s) => typeof s !== "string" || s.length === 0)) throw new ScopedTokenError(`A ${label} secret is required`);
|
|
102
|
+
return list;
|
|
103
|
+
};
|
|
104
|
+
const validate = (payload) => {
|
|
105
|
+
try {
|
|
106
|
+
return options.validateClaims(payload);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (error instanceof TokenError) throw error;
|
|
109
|
+
throw new ScopedTokenError(`Invalid ${label}: ${error instanceof Error ? error.message : String(error)}`);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
prefix,
|
|
114
|
+
TokenError: ScopedTokenError,
|
|
115
|
+
matches: (value) => value.startsWith(prefix),
|
|
116
|
+
async create(secret, claims, createOptions = {}) {
|
|
117
|
+
const [signing] = secretsOf(secret);
|
|
118
|
+
const { exp: _ignored, ...rest } = claims;
|
|
119
|
+
validate(rest);
|
|
120
|
+
const ttl = createOptions.expiresIn === void 0 ? defaultTtl : durationToMs(createOptions.expiresIn);
|
|
121
|
+
const payload = {
|
|
122
|
+
...rest,
|
|
123
|
+
exp: (createOptions.now ?? clock()) + ttl
|
|
124
|
+
};
|
|
125
|
+
const payloadPart = base64urlEncode(encoder.encode(JSON.stringify(payload)));
|
|
126
|
+
return `${prefix}${payloadPart}.${base64urlEncode(await hmac(signing, payloadPart))}`;
|
|
127
|
+
},
|
|
128
|
+
async verify(secret, token, verifyOptions = {}) {
|
|
129
|
+
const secrets = secretsOf(secret);
|
|
130
|
+
if (typeof token !== "string" || !token.startsWith(prefix)) throw new ScopedTokenError(`Invalid ${label}: missing ${prefix} prefix`);
|
|
131
|
+
const parts = token.slice(prefix.length).split(".");
|
|
132
|
+
if (parts.length !== 2 || !parts[0] || !parts[1]) throw new ScopedTokenError(`Invalid ${label}: malformed`);
|
|
133
|
+
const [payloadPart, signaturePart] = parts;
|
|
134
|
+
let candidate;
|
|
135
|
+
try {
|
|
136
|
+
candidate = base64urlDecode(signaturePart);
|
|
137
|
+
} catch {
|
|
138
|
+
throw new ScopedTokenError(`Invalid ${label}: malformed signature`);
|
|
139
|
+
}
|
|
140
|
+
let signed = false;
|
|
141
|
+
for (const s of secrets) if (timingSafeEqual(await hmac(s, payloadPart), candidate)) signed = true;
|
|
142
|
+
if (!signed) throw new ScopedTokenError(`Invalid ${label}: signature mismatch`);
|
|
143
|
+
let payload;
|
|
144
|
+
try {
|
|
145
|
+
payload = JSON.parse(new TextDecoder().decode(base64urlDecode(payloadPart)));
|
|
146
|
+
} catch {
|
|
147
|
+
throw new ScopedTokenError(`Invalid ${label}: malformed payload`);
|
|
148
|
+
}
|
|
149
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) throw new ScopedTokenError(`Invalid ${label}: malformed payload`);
|
|
150
|
+
const { exp, ...rest } = payload;
|
|
151
|
+
if (typeof exp !== "number" || !Number.isFinite(exp)) throw new ScopedTokenError(`Invalid ${label}: missing expiry`);
|
|
152
|
+
const claims = validate(rest);
|
|
153
|
+
if ((verifyOptions.now ?? clock()) >= exp) throw new ScopedTokenError(`${label[0]?.toUpperCase()}${label.slice(1)} has expired`);
|
|
154
|
+
return {
|
|
155
|
+
claims,
|
|
156
|
+
expiresAt: exp
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
export { createScopedTokens as n, TokenError as t };
|
|
163
|
+
|
|
164
|
+
//# sourceMappingURL=scoped-cFBbotCh.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scoped-cFBbotCh.mjs","names":[],"sources":["../src/tokens/scoped.ts"],"sourcesContent":["/**\n * Scoped tokens: compact HMAC-signed grants that scope their bearer to a\n * subset of a panel (one tenant, one customer, a few actions) for a limited\n * time. The products call them portal tokens (`whpt_`, `audpt_`, `entpt_`) or\n * viewer tokens (`lvt_`); the mechanics are the same, the claims differ.\n *\n * Wire format:\n *\n * ```txt\n * <prefix><base64url(JSON { ...claims, exp })>.<base64url(HMAC-SHA256(secret, payloadPart))>\n * ```\n *\n * - The secret is an **arbitrary string**, fed to the HMAC as raw UTF-8 bytes.\n * An empty secret is rejected (it would let anyone mint tokens).\n * - The signature is checked first, in constant time; claims are never\n * interpreted before it passes.\n * - `exp` is unix epoch milliseconds.\n * - **Rotation:** `verify` accepts a list of secrets. Mint with the new secret\n * first in the list and keep the old one until its tokens have expired. The\n * wire format has no key id, so tokens minted by older releases keep\n * verifying.\n *\n * Zero dependencies (Web Crypto only), so it runs on Workers and in browsers.\n *\n * @module\n */\n\nimport { durationToMs, type Duration } from \"../util/duration.ts\";\n\n/** Base class of every scoped-token error. Maps to HTTP 401 at the API layer. */\nexport class TokenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TokenError\";\n }\n}\n\n/** One secret, or a rotation list (the first one signs, all of them verify). */\nexport type TokenSecret = string | readonly string[];\n\n/** Options for {@link createScopedTokens}. */\nexport interface ScopedTokensOptions<Claims extends object> {\n /** Token prefix, e.g. `\"whpt_\"`. A product's tokens depend on it, so it never changes. */\n prefix: string;\n /** Default lifetime when `create` gets no `expiresIn`. */\n ttl: Duration;\n /**\n * Check the decoded payload and return the typed claims (without `exp`), or\n * throw. Runs on `create` too, so a bad grant can't be minted. A thrown\n * non-{@link TokenError} becomes `Invalid <label>: <message>`.\n */\n validateClaims: (payload: Record<string, unknown>) => Claims;\n /** Clock (unix ms). Default `Date.now`. */\n now?: () => number;\n /** How errors name the token: `\"portal token\"`, `\"viewer token\"`. Default `\"token\"`. */\n label?: string;\n /**\n * The `name` of the errors this instance throws (the products map\n * `PortalTokenError` / `ViewerTokenError` to 401 by name). Default\n * `\"TokenError\"`.\n */\n errorName?: string;\n}\n\n/** Per-call options for {@link ScopedTokens.create}. */\nexport interface CreateTokenOptions {\n /** Lifetime. Default: the instance `ttl`. */\n expiresIn?: Duration;\n /** Clock override (unix ms) for this call. */\n now?: number;\n}\n\n/** A verified token: its claims and expiry. */\nexport interface VerifiedToken<Claims> {\n claims: Claims;\n /** Expiry, unix epoch milliseconds. */\n expiresAt: number;\n}\n\n/** What {@link createScopedTokens} returns. */\nexport interface ScopedTokens<Claims extends object> {\n /** The token prefix. */\n readonly prefix: string;\n /** Mint a token for `claims`. Call it server-side, after your own authentication. */\n create(secret: TokenSecret, claims: Claims, options?: CreateTokenOptions): Promise<string>;\n /** Verify format, signature, claims and expiry; throws {@link ScopedTokens.TokenError}. */\n verify(\n secret: TokenSecret,\n token: string,\n options?: { now?: number },\n ): Promise<VerifiedToken<Claims>>;\n /** True when `value` looks like one of these tokens (prefix only, no verification). */\n matches(value: string): boolean;\n /** The error class this instance throws (a {@link TokenError} subclass named `errorName`). */\n readonly TokenError: new (message: string) => TokenError;\n}\n\nconst encoder = new TextEncoder();\n\nconst base64urlEncode = (bytes: Uint8Array): string => {\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\n\nconst base64urlDecode = (value: string): Uint8Array => {\n if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new TypeError(\"not base64url\");\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const binary = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n};\n\n/** HMAC-SHA256 keyed by the raw UTF-8 bytes of the (arbitrary-string) secret. */\nasync function hmac(secret: string, content: string): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret) as BufferSource,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(content)));\n}\n\n/** Constant-time byte comparison (XOR accumulate — no early exit on content). */\nfunction timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number);\n return diff === 0;\n}\n\n/**\n * Create a product's scoped-token codec.\n *\n * @example\n * ```ts\n * import { createScopedTokens } from \"@xtandard/kit/tokens\";\n *\n * const portal = createScopedTokens({\n * prefix: \"whpt_\",\n * ttl: \"7d\",\n * label: \"portal token\",\n * errorName: \"PortalTokenError\",\n * validateClaims: (p) => {\n * if (typeof p.app !== \"string\" || !p.app) throw new Error(\"missing application\");\n * return { app: p.app };\n * },\n * });\n * const token = await portal.create(secret, { app: \"acme\" });\n * const { claims } = await portal.verify(secret, token); // { app: \"acme\" }\n * ```\n */\nexport function createScopedTokens<Claims extends object>(\n options: ScopedTokensOptions<Claims>,\n): ScopedTokens<Claims> {\n const { prefix } = options;\n if (!prefix) throw new TypeError(\"createScopedTokens: a prefix is required\");\n const label = options.label ?? \"token\";\n const errorName = options.errorName ?? \"TokenError\";\n const clock = options.now ?? Date.now;\n const defaultTtl = durationToMs(options.ttl);\n\n class ScopedTokenError extends TokenError {\n constructor(message: string) {\n super(message);\n this.name = errorName;\n }\n }\n\n const secretsOf = (secret: TokenSecret): string[] => {\n const list = typeof secret === \"string\" ? [secret] : [...secret];\n if (list.length === 0 || list.some((s) => typeof s !== \"string\" || s.length === 0)) {\n throw new ScopedTokenError(`A ${label} secret is required`);\n }\n return list;\n };\n\n const validate = (payload: Record<string, unknown>): Claims => {\n try {\n return options.validateClaims(payload);\n } catch (error) {\n if (error instanceof TokenError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n throw new ScopedTokenError(`Invalid ${label}: ${message}`);\n }\n };\n\n return {\n prefix,\n TokenError: ScopedTokenError,\n matches: (value) => value.startsWith(prefix),\n\n async create(secret, claims, createOptions = {}) {\n const [signing] = secretsOf(secret) as [string];\n const { exp: _ignored, ...rest } = claims as Record<string, unknown>;\n validate(rest);\n const ttl =\n createOptions.expiresIn === undefined ? defaultTtl : durationToMs(createOptions.expiresIn);\n const payload = { ...rest, exp: (createOptions.now ?? clock()) + ttl };\n const payloadPart = base64urlEncode(encoder.encode(JSON.stringify(payload)));\n const signature = base64urlEncode(await hmac(signing, payloadPart));\n return `${prefix}${payloadPart}.${signature}`;\n },\n\n async verify(secret, token, verifyOptions = {}) {\n const secrets = secretsOf(secret);\n if (typeof token !== \"string\" || !token.startsWith(prefix)) {\n throw new ScopedTokenError(`Invalid ${label}: missing ${prefix} prefix`);\n }\n const parts = token.slice(prefix.length).split(\".\");\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new ScopedTokenError(`Invalid ${label}: malformed`);\n }\n const [payloadPart, signaturePart] = parts as [string, string];\n\n // Signature first: never interpret unauthenticated claims.\n let candidate: Uint8Array;\n try {\n candidate = base64urlDecode(signaturePart);\n } catch {\n throw new ScopedTokenError(`Invalid ${label}: malformed signature`);\n }\n let signed = false;\n for (const s of secrets) {\n // Check every secret (no early exit), so timing doesn't reveal which one matched.\n if (timingSafeEqual(await hmac(s, payloadPart), candidate)) signed = true;\n }\n if (!signed) throw new ScopedTokenError(`Invalid ${label}: signature mismatch`);\n\n let payload: unknown;\n try {\n payload = JSON.parse(new TextDecoder().decode(base64urlDecode(payloadPart)));\n } catch {\n throw new ScopedTokenError(`Invalid ${label}: malformed payload`);\n }\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n throw new ScopedTokenError(`Invalid ${label}: malformed payload`);\n }\n const { exp, ...rest } = payload as Record<string, unknown>;\n if (typeof exp !== \"number\" || !Number.isFinite(exp)) {\n throw new ScopedTokenError(`Invalid ${label}: missing expiry`);\n }\n const claims = validate(rest);\n if ((verifyOptions.now ?? clock()) >= exp) {\n throw new ScopedTokenError(`${label[0]?.toUpperCase()}${label.slice(1)} has expired`);\n }\n return { claims, expiresAt: exp };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AA8DA,MAAM,UAAU,IAAI,YAAY;AAEhC,MAAM,mBAAmB,UAA8B;CACrD,IAAI,SAAS;CACb,KAAK,MAAM,KAAK,OAAO,UAAU,OAAO,aAAa,CAAC;CACtD,OAAO,KAAK,MAAM,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE;AAC/E;AAEA,MAAM,mBAAmB,UAA8B;CACrD,IAAI,CAAC,mBAAmB,KAAK,KAAK,GAAG,MAAM,IAAI,UAAU,eAAe;CACxE,MAAM,SAAS,MAAM,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG;CACzD,MAAM,SAAS,KAAK,SAAS,IAAI,QAAQ,IAAK,OAAO,SAAS,KAAM,CAAC,CAAC;CACtE,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO;AACT;;AAGA,eAAe,KAAK,QAAgB,SAAsC;CACxE,MAAM,MAAM,MAAM,OAAO,OAAO,UAC9B,OACA,QAAQ,OAAO,MAAM,GACrB;EAAE,MAAM;EAAQ,MAAM;CAAU,GAChC,OACA,CAAC,MAAM,CACT;CACA,OAAO,IAAI,WAAW,MAAM,OAAO,OAAO,KAAK,QAAQ,KAAK,QAAQ,OAAO,OAAO,CAAC,CAAC;AACtF;;AAGA,SAAS,gBAAgB,GAAe,GAAwB;CAC9D,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;C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,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,SAAS,GAAG,GACjD,MAAM,IAAI,iBAAiB,WAAW,MAAM,iBAAiB;GAE/D,MAAM,SAAS,SAAS,IAAI;GAC5B,KAAK,cAAc,OAAO,MAAM,MAAM,KACpC,MAAM,IAAI,iBAAiB,GAAG,MAAM,IAAI,YAAY,IAAI,MAAM,MAAM,CAAC,EAAE,aAAa;GAEtF,OAAO;IAAE;IAAQ,WAAW;GAAI;EAClC;CACF;AACF"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { n as CompareAndSwapKvStorage } from "./contract-BvgtswLX.cjs";
|
|
2
|
+
import { t as SqliteExecutor } from "./kv-sqlite-B6iTLOx2.cjs";
|
|
3
|
+
import { Database } from "bun:sqlite";
|
|
4
|
+
|
|
5
|
+
//#region src/storage/sqlite.d.ts
|
|
6
|
+
/** Options for {@link createSqliteStorage}. */
|
|
7
|
+
interface SqliteStorageOptions {
|
|
8
|
+
/** Database file path. Default `":memory:"`. Ignored when `database` is given. */
|
|
9
|
+
path?: string;
|
|
10
|
+
/** An existing `bun:sqlite` `Database` to use instead of opening one. Never closed. */
|
|
11
|
+
database?: Database;
|
|
12
|
+
/** Table name (default `"xtandard_kv"`; products pass theirs). Validated as a safe identifier. */
|
|
13
|
+
table?: string;
|
|
14
|
+
}
|
|
15
|
+
/** A compare-and-swap capable storage backed by SQLite, plus `close()`. */
|
|
16
|
+
interface SqliteKvStorage extends CompareAndSwapKvStorage {
|
|
17
|
+
/** Close the database if this driver opened it; no-op for a borrowed one. */
|
|
18
|
+
close(): void;
|
|
19
|
+
}
|
|
20
|
+
/** A lazily opened `bun:sqlite` database whose DDL runs once (semi-public, ADR 0004). */
|
|
21
|
+
interface SqliteConnection {
|
|
22
|
+
/** Resolve the database, opening it and running the DDL on first use (retried after a failure). */
|
|
23
|
+
get(): Promise<Database>;
|
|
24
|
+
/** Close the database if this connection opened it. */
|
|
25
|
+
close(): void;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Build a {@link SqliteConnection} that opens `path` (or borrows `database`) and runs `ddl` once.
|
|
29
|
+
* Products add their own tables by passing extra statements.
|
|
30
|
+
*/
|
|
31
|
+
declare function sqliteConnection(options: Pick<SqliteStorageOptions, "path" | "database">, ddl: string[]): SqliteConnection;
|
|
32
|
+
/** Adapt a `bun:sqlite` database to the positional-args {@link SqliteExecutor}. */
|
|
33
|
+
declare function bunSqliteExecutor(db: Database): SqliteExecutor;
|
|
34
|
+
/**
|
|
35
|
+
* Create a SQLite-backed storage. Requires the Bun runtime once used.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* import { createSqliteStorage } from "@xtandard/kit/storage/sqlite";
|
|
40
|
+
*
|
|
41
|
+
* const storage = createSqliteStorage({ path: "./data.sqlite", table: "xtandard_kv" });
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
declare function createSqliteStorage(options?: SqliteStorageOptions): SqliteKvStorage;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { createSqliteStorage as a, bunSqliteExecutor as i, SqliteKvStorage as n, sqliteConnection as o, SqliteStorageOptions as r, SqliteConnection as t };
|
|
47
|
+
//# sourceMappingURL=sqlite-B2g1JJz1.d.cts.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { n as CompareAndSwapKvStorage } from "./contract-BvgtswLX.mjs";
|
|
2
|
+
import { t as SqliteExecutor } from "./kv-sqlite-Tx4UedJs.mjs";
|
|
3
|
+
import { Database } from "bun:sqlite";
|
|
4
|
+
|
|
5
|
+
//#region src/storage/sqlite.d.ts
|
|
6
|
+
/** Options for {@link createSqliteStorage}. */
|
|
7
|
+
interface SqliteStorageOptions {
|
|
8
|
+
/** Database file path. Default `":memory:"`. Ignored when `database` is given. */
|
|
9
|
+
path?: string;
|
|
10
|
+
/** An existing `bun:sqlite` `Database` to use instead of opening one. Never closed. */
|
|
11
|
+
database?: Database;
|
|
12
|
+
/** Table name (default `"xtandard_kv"`; products pass theirs). Validated as a safe identifier. */
|
|
13
|
+
table?: string;
|
|
14
|
+
}
|
|
15
|
+
/** A compare-and-swap capable storage backed by SQLite, plus `close()`. */
|
|
16
|
+
interface SqliteKvStorage extends CompareAndSwapKvStorage {
|
|
17
|
+
/** Close the database if this driver opened it; no-op for a borrowed one. */
|
|
18
|
+
close(): void;
|
|
19
|
+
}
|
|
20
|
+
/** A lazily opened `bun:sqlite` database whose DDL runs once (semi-public, ADR 0004). */
|
|
21
|
+
interface SqliteConnection {
|
|
22
|
+
/** Resolve the database, opening it and running the DDL on first use (retried after a failure). */
|
|
23
|
+
get(): Promise<Database>;
|
|
24
|
+
/** Close the database if this connection opened it. */
|
|
25
|
+
close(): void;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Build a {@link SqliteConnection} that opens `path` (or borrows `database`) and runs `ddl` once.
|
|
29
|
+
* Products add their own tables by passing extra statements.
|
|
30
|
+
*/
|
|
31
|
+
declare function sqliteConnection(options: Pick<SqliteStorageOptions, "path" | "database">, ddl: string[]): SqliteConnection;
|
|
32
|
+
/** Adapt a `bun:sqlite` database to the positional-args {@link SqliteExecutor}. */
|
|
33
|
+
declare function bunSqliteExecutor(db: Database): SqliteExecutor;
|
|
34
|
+
/**
|
|
35
|
+
* Create a SQLite-backed storage. Requires the Bun runtime once used.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* import { createSqliteStorage } from "@xtandard/kit/storage/sqlite";
|
|
40
|
+
*
|
|
41
|
+
* const storage = createSqliteStorage({ path: "./data.sqlite", table: "xtandard_kv" });
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
declare function createSqliteStorage(options?: SqliteStorageOptions): SqliteKvStorage;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { createSqliteStorage as a, bunSqliteExecutor as i, SqliteKvStorage as n, sqliteConnection as o, SqliteStorageOptions as r, SqliteConnection as t };
|
|
47
|
+
//# sourceMappingURL=sqlite-BIPIlxfj.d.mts.map
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
const require_peer = require("./peer-BIjBFzwQ.cjs");
|
|
2
|
+
const require_util = require("./util-dAnTK9x-.cjs");
|
|
3
|
+
const require_kv_sqlite = require("./kv-sqlite-CHOdIMJ-.cjs");
|
|
4
|
+
//#region src/storage/sqlite.ts
|
|
5
|
+
const SUBPATH = "@xtandard/kit/storage/sqlite";
|
|
6
|
+
/**
|
|
7
|
+
* Build a {@link SqliteConnection} that opens `path` (or borrows `database`) and runs `ddl` once.
|
|
8
|
+
* Products add their own tables by passing extra statements.
|
|
9
|
+
*/
|
|
10
|
+
function sqliteConnection(options, ddl) {
|
|
11
|
+
let db = options.database;
|
|
12
|
+
const ownsDb = !options.database;
|
|
13
|
+
let ready;
|
|
14
|
+
return {
|
|
15
|
+
get() {
|
|
16
|
+
ready ??= (async () => {
|
|
17
|
+
if (!db) {
|
|
18
|
+
if (typeof globalThis.Bun === "undefined") throw new Error(`${SUBPATH} requires the Bun runtime (bun:sqlite)`);
|
|
19
|
+
const { Database: Ctor } = await require_peer.importPeer("bun:sqlite", SUBPATH, () => import("bun:sqlite"));
|
|
20
|
+
db = new Ctor(options.path ?? ":memory:");
|
|
21
|
+
}
|
|
22
|
+
for (const statement of ddl) db.run(statement);
|
|
23
|
+
return db;
|
|
24
|
+
})().catch((error) => {
|
|
25
|
+
ready = void 0;
|
|
26
|
+
throw error;
|
|
27
|
+
});
|
|
28
|
+
return ready;
|
|
29
|
+
},
|
|
30
|
+
close() {
|
|
31
|
+
if (ownsDb) db?.close();
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Adapt a `bun:sqlite` database to the positional-args {@link SqliteExecutor}. */
|
|
36
|
+
function bunSqliteExecutor(db) {
|
|
37
|
+
return { async all(sql, args) {
|
|
38
|
+
return db.query(sql).all(...args);
|
|
39
|
+
} };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create a SQLite-backed storage. Requires the Bun runtime once used.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* import { createSqliteStorage } from "@xtandard/kit/storage/sqlite";
|
|
47
|
+
*
|
|
48
|
+
* const storage = createSqliteStorage({ path: "./data.sqlite", table: "xtandard_kv" });
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
function createSqliteStorage(options = {}) {
|
|
52
|
+
const table = require_util.assertIdentifier(options.table ?? "xtandard_kv");
|
|
53
|
+
const connection = sqliteConnection(options, [require_kv_sqlite.sqliteKvSchema(table)]);
|
|
54
|
+
return {
|
|
55
|
+
...require_kv_sqlite.sqliteKvStorage(table, async () => bunSqliteExecutor(await connection.get())),
|
|
56
|
+
close: connection.close
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
Object.defineProperty(exports, "bunSqliteExecutor", {
|
|
61
|
+
enumerable: true,
|
|
62
|
+
get: function() {
|
|
63
|
+
return bunSqliteExecutor;
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
Object.defineProperty(exports, "createSqliteStorage", {
|
|
67
|
+
enumerable: true,
|
|
68
|
+
get: function() {
|
|
69
|
+
return createSqliteStorage;
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
Object.defineProperty(exports, "sqliteConnection", {
|
|
73
|
+
enumerable: true,
|
|
74
|
+
get: function() {
|
|
75
|
+
return sqliteConnection;
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
//# sourceMappingURL=sqlite-BntoYaXZ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sqlite-BntoYaXZ.cjs","names":["importPeer","assertIdentifier","sqliteKvSchema","sqliteKvStorage"],"sources":["../src/storage/sqlite.ts"],"sourcesContent":["/**\n * SQLite storage driver on `bun:sqlite`: **Bun only**, zero npm dependencies. Durable, fast and\n * file-backed (or in-memory) for single-node deployments and local persistence.\n *\n * `bun:sqlite` is loaded lazily on first use, so importing this module works under any runtime\n * (only opening a database needs Bun). Values are canonical JSON, so `compareAndSwap` is one\n * conditional `UPDATE` (atomic across processes sharing the file); see `kv-sqlite.ts`.\n *\n * @module\n */\n\nimport type { Database } from \"bun:sqlite\";\nimport { importPeer } from \"../internal/peer.ts\";\nimport type { CompareAndSwapKvStorage } from \"./contract.ts\";\nimport { sqliteKvSchema, sqliteKvStorage, type SqliteExecutor } from \"./kv-sqlite.ts\";\nimport { assertIdentifier } from \"./util.ts\";\n\nconst SUBPATH = \"@xtandard/kit/storage/sqlite\";\n\n/** Options for {@link createSqliteStorage}. */\nexport interface SqliteStorageOptions {\n /** Database file path. Default `\":memory:\"`. Ignored when `database` is given. */\n path?: string;\n /** An existing `bun:sqlite` `Database` to use instead of opening one. Never closed. */\n database?: Database;\n /** Table name (default `\"xtandard_kv\"`; products pass theirs). Validated as a safe identifier. */\n table?: string;\n}\n\n/** A compare-and-swap capable storage backed by SQLite, plus `close()`. */\nexport interface SqliteKvStorage extends CompareAndSwapKvStorage {\n /** Close the database if this driver opened it; no-op for a borrowed one. */\n close(): void;\n}\n\n/** A lazily opened `bun:sqlite` database whose DDL runs once (semi-public, ADR 0004). */\nexport interface SqliteConnection {\n /** Resolve the database, opening it and running the DDL on first use (retried after a failure). */\n get(): Promise<Database>;\n /** Close the database if this connection opened it. */\n close(): void;\n}\n\n/**\n * Build a {@link SqliteConnection} that opens `path` (or borrows `database`) and runs `ddl` once.\n * Products add their own tables by passing extra statements.\n */\nexport function sqliteConnection(\n options: Pick<SqliteStorageOptions, \"path\" | \"database\">,\n ddl: string[],\n): SqliteConnection {\n let db: Database | undefined = options.database;\n const ownsDb = !options.database;\n let ready: Promise<Database> | undefined;\n return {\n get(): Promise<Database> {\n ready ??= (async () => {\n if (!db) {\n if (typeof (globalThis as { Bun?: unknown }).Bun === \"undefined\") {\n throw new Error(`${SUBPATH} requires the Bun runtime (bun:sqlite)`);\n }\n const { Database: Ctor } = await importPeer(\n \"bun:sqlite\",\n SUBPATH,\n () => import(\"bun:sqlite\"),\n );\n db = new Ctor(options.path ?? \":memory:\");\n }\n for (const statement of ddl) db.run(statement);\n return db;\n })().catch((error: unknown) => {\n ready = undefined;\n throw error;\n });\n return ready;\n },\n close(): void {\n if (ownsDb) db?.close();\n },\n };\n}\n\n/** Adapt a `bun:sqlite` database to the positional-args {@link SqliteExecutor}. */\nexport function bunSqliteExecutor(db: Database): SqliteExecutor {\n return {\n async all(sql, args) {\n return db.query(sql).all(...(args as never[])) as Array<Record<string, unknown>>;\n },\n };\n}\n\n/**\n * Create a SQLite-backed storage. Requires the Bun runtime once used.\n *\n * @example\n * ```ts\n * import { createSqliteStorage } from \"@xtandard/kit/storage/sqlite\";\n *\n * const storage = createSqliteStorage({ path: \"./data.sqlite\", table: \"xtandard_kv\" });\n * ```\n */\nexport function createSqliteStorage(options: SqliteStorageOptions = {}): SqliteKvStorage {\n const table = assertIdentifier(options.table ?? \"xtandard_kv\");\n const connection = sqliteConnection(options, [sqliteKvSchema(table)]);\n return {\n ...sqliteKvStorage(table, async () => bunSqliteExecutor(await connection.get())),\n close: connection.close,\n };\n}\n"],"mappings":";;;;AAiBA,MAAM,UAAU;;;;;AA8BhB,SAAgB,iBACd,SACA,KACkB;CAClB,IAAI,KAA2B,QAAQ;CACvC,MAAM,SAAS,CAAC,QAAQ;CACxB,IAAI;CACJ,OAAO;EACL,MAAyB;GACvB,WAAW,YAAY;IACrB,IAAI,CAAC,IAAI;KACP,IAAI,OAAQ,WAAiC,QAAQ,aACnD,MAAM,IAAI,MAAM,GAAG,QAAQ,uCAAuC;KAEpE,MAAM,EAAE,UAAU,SAAS,MAAMA,aAAAA,WAC/B,cACA,eACM,OAAO,aACf;KACA,KAAK,IAAI,KAAK,QAAQ,QAAQ,UAAU;IAC1C;IACA,KAAK,MAAM,aAAa,KAAK,GAAG,IAAI,SAAS;IAC7C,OAAO;GACT,GAAG,EAAE,OAAO,UAAmB;IAC7B,QAAQ,KAAA;IACR,MAAM;GACR,CAAC;GACD,OAAO;EACT;EACA,QAAc;GACZ,IAAI,QAAQ,IAAI,MAAM;EACxB;CACF;AACF;;AAGA,SAAgB,kBAAkB,IAA8B;CAC9D,OAAO,EACL,MAAM,IAAI,KAAK,MAAM;EACnB,OAAO,GAAG,MAAM,GAAG,EAAE,IAAI,GAAI,IAAgB;CAC/C,EACF;AACF;;;;;;;;;;;AAYA,SAAgB,oBAAoB,UAAgC,CAAC,GAAoB;CACvF,MAAM,QAAQC,aAAAA,iBAAiB,QAAQ,SAAS,aAAa;CAC7D,MAAM,aAAa,iBAAiB,SAAS,CAACC,kBAAAA,eAAe,KAAK,CAAC,CAAC;CACpE,OAAO;EACL,GAAGC,kBAAAA,gBAAgB,OAAO,YAAY,kBAAkB,MAAM,WAAW,IAAI,CAAC,CAAC;EAC/E,OAAO,WAAW;CACpB;AACF"}
|