@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":"portal-container-Ca1NxrLE.cjs","names":["React","X","Monitor","Sun","Moon","Lock","QueryClient","QueryClientProvider","useBrowserLocation","React"],"sources":["../src/ui/theme.ts","../src/ui/theme-context.tsx","../src/ui/token.ts","../src/ui/lib/utils.ts","../src/ui/components/Toast.tsx","../src/ui/components/ThemeToggle.tsx","../src/ui/lib/nav-guard.ts","../src/ui/shell.tsx","../src/ui/boot.tsx","../src/ui/lib/portal-container.ts"],"sourcesContent":["/**\n * Theme preference: `system` (follows the OS), `light`, or `dark`. The preference is persisted in\n * localStorage under a product key (`xtandard-<product>:theme`, passed to {@link createThemeStore});\n * `system` live-updates when the OS scheme changes. The standalone SPA writes the resolved value to\n * `<html data-theme>` (see {@link ThemeStore.initTheme}); the React embed writes it to its own\n * wrapper instead, so it never touches the host document.\n *\n * Host detection ({@link detectHostTheme}, {@link subscribeHostTheme}) is key-free: it reads the\n * page, not a preference.\n *\n * @module\n */\n\n/** A theme preference: `system` follows the OS. */\nexport type ThemePref = \"system\" | \"light\" | \"dark\";\n\n/** A concrete theme — what every surface, text color and viewer resolves to. */\nexport type ResolvedTheme = \"light\" | \"dark\";\n\nconst DARK_QUERY = \"(prefers-color-scheme: dark)\";\n\nfunction darkQuery(): MediaQueryList | undefined {\n return typeof matchMedia !== \"undefined\" ? matchMedia(DARK_QUERY) : undefined;\n}\n\nfunction prefersDark(): boolean {\n return darkQuery()?.matches ?? false;\n}\n\n/** The OS colour scheme right now (`light` when it can't be read, e.g. on the server). */\nexport function systemTheme(): ResolvedTheme {\n return prefersDark() ? \"dark\" : \"light\";\n}\n\n/** Call `cb` when the OS colour scheme flips. Returns the unsubscribe function. */\nexport function subscribeSystemTheme(cb: () => void): () => void {\n const mq = darkQuery();\n mq?.addEventListener(\"change\", cb);\n return () => mq?.removeEventListener(\"change\", cb);\n}\n\n/** The concrete theme a preference resolves to right now. */\nexport function resolveTheme(pref: ThemePref): ResolvedTheme {\n return pref === \"system\" ? systemTheme() : pref;\n}\n\n/** A persisted theme preference, bound to one localStorage key. */\nexport interface ThemeStore {\n /** The localStorage key the preference lives under. */\n readonly storageKey: string;\n /** The stored preference (`system` when unset, invalid, or storage is unavailable). */\n getThemePref(): ThemePref;\n /** Persist `pref` and notify subscribers. */\n setThemePref(pref: ThemePref): void;\n /** The concrete theme the stored preference resolves to right now. */\n getResolvedTheme(): ResolvedTheme;\n /**\n * Subscribe to changes of the resolved preference theme — an explicit {@link setThemePref} or,\n * under `system`, the OS scheme flipping. Returns the unsubscribe function\n * (`useSyncExternalStore`-compatible).\n */\n subscribeThemePref(cb: () => void): () => void;\n /**\n * Standalone SPA only: apply the stored preference to `<html data-theme>` and keep it in sync\n * (toggle + OS changes). Call once at boot, before first paint. Returns the unsubscribe function.\n * The React embed does not call this — it themes its own wrapper.\n */\n initTheme(): () => void;\n}\n\n/**\n * Create the theme store for one product. `storageKey` is the product's localStorage key\n * (`\"xtandard-webhooks:theme\"`…); it is a stored-data contract, so products pass it explicitly.\n */\nexport function createThemeStore(storageKey: string): ThemeStore {\n const listeners = new Set<() => void>();\n\n const getThemePref = (): ThemePref => {\n try {\n const v = localStorage.getItem(storageKey);\n if (v === \"light\" || v === \"dark\" || v === \"system\") return v;\n } catch {\n /* storage unavailable (SSR, privacy mode) */\n }\n return \"system\";\n };\n\n const setThemePref = (pref: ThemePref): void => {\n try {\n localStorage.setItem(storageKey, pref);\n } catch {\n /* storage unavailable: the in-memory notification still applies it */\n }\n for (const cb of listeners) cb();\n };\n\n const getResolvedTheme = (): ResolvedTheme => resolveTheme(getThemePref());\n\n const subscribeThemePref = (cb: () => void): (() => void) => {\n listeners.add(cb);\n const mq = darkQuery();\n const onOs = () => {\n if (getThemePref() === \"system\") cb();\n };\n mq?.addEventListener(\"change\", onOs);\n return () => {\n listeners.delete(cb);\n mq?.removeEventListener(\"change\", onOs);\n };\n };\n\n const initTheme = (): (() => void) => {\n if (typeof document === \"undefined\") return () => {};\n const apply = () => {\n document.documentElement.dataset.theme = getResolvedTheme();\n };\n apply();\n return subscribeThemePref(apply);\n };\n\n return {\n storageKey,\n getThemePref,\n setThemePref,\n getResolvedTheme,\n subscribeThemePref,\n initTheme,\n };\n}\n\n/** The bits of an element {@link detectHostTheme} reads (keeps it testable without a DOM). */\nexport interface ThemeSignalSource {\n classList: { contains(token: string): boolean };\n getAttribute(name: string): string | null;\n style?: { colorScheme?: string };\n}\n\n/** The attributes {@link detectHostTheme} reads, in order. */\nconst THEME_ATTRIBUTES = [\"data-theme\", \"data-mode\", \"data-color-scheme\"] as const;\n\nfunction explicitTheme(el: ThemeSignalSource | null | undefined): ResolvedTheme | undefined {\n if (!el) return undefined;\n // Class strategy (Tailwind `darkMode: \"class\"`, next-themes `attribute=\"class\"`, …).\n if (el.classList.contains(\"dark\")) return \"dark\";\n if (el.classList.contains(\"light\")) return \"light\";\n // Attribute strategy (`data-theme`, also `data-mode` / `data-color-scheme`).\n for (const attr of THEME_ATTRIBUTES) {\n const v = el.getAttribute(attr);\n if (v === \"dark\" || v === \"light\") return v;\n }\n // An inline `color-scheme: dark` (next-themes sets it alongside the class).\n const cs = el.style?.colorScheme?.trim();\n if (cs === \"dark\" || cs === \"light\") return cs;\n return undefined;\n}\n\n/**\n * The host page's theme, for `theme=\"inherit\"`: an explicit signal on `<html>` (then `<body>`) — a\n * `dark`/`light` class, a `data-theme`/`data-mode`/`data-color-scheme` attribute, or an inline\n * `color-scheme` — and, only when the host sets none, the OS `prefers-color-scheme`.\n *\n * Pass `root`/`body` to read other elements (tests, iframes); they default to the document's.\n */\nexport function detectHostTheme(\n root: ThemeSignalSource | null | undefined = typeof document !== \"undefined\"\n ? document.documentElement\n : undefined,\n body: ThemeSignalSource | null | undefined = typeof document !== \"undefined\"\n ? document.body\n : undefined,\n): ResolvedTheme {\n return explicitTheme(root) ?? explicitTheme(body) ?? systemTheme();\n}\n\n/**\n * Watch the host page for theme switches: class/attribute/style changes on `<html>` and `<body>`,\n * plus the OS scheme. Returns the unsubscribe function. Without a DOM or `MutationObserver` (SSR,\n * old test environments) it only follows the OS scheme.\n */\nexport function subscribeHostTheme(cb: () => void): () => void {\n const offOs = subscribeSystemTheme(cb);\n if (typeof document === \"undefined\" || typeof MutationObserver === \"undefined\") return offOs;\n const observer = new MutationObserver(cb);\n const opts: MutationObserverInit = {\n attributes: true,\n attributeFilter: [\"class\", \"style\", ...THEME_ATTRIBUTES],\n };\n observer.observe(document.documentElement, opts);\n if (document.body) observer.observe(document.body, opts);\n return () => {\n observer.disconnect();\n offOs();\n };\n}\n","/**\n * React bindings for the theme store: {@link ThemeProvider} resolves a {@link ThemeMode} to one\n * concrete theme with `useSyncExternalStore`, and {@link useTheme} hands it (plus whether the\n * dashboard owns the toggle) to any component below, so the toggle never has to be prop-drilled.\n *\n * @module\n */\n\nimport * as React from \"react\";\nimport {\n detectHostTheme,\n subscribeHostTheme,\n subscribeSystemTheme,\n systemTheme,\n type ResolvedTheme,\n type ThemeStore,\n} from \"./theme.ts\";\n\n/**\n * How the dashboard's theme is decided:\n * - `\"auto\"` — its own system/light/dark preference (persisted), with the toggle.\n * - `\"inherit\"` — follow the host page (see {@link detectHostTheme}); no toggle.\n * - `\"light\"` / `\"dark\"` — fixed by the host (e.g. from its own theme state); no toggle.\n */\nexport type ThemeMode = \"auto\" | \"inherit\" | ResolvedTheme;\n\n/** What {@link useTheme} returns. */\nexport interface ThemeState {\n /** The single theme every surface, text color and viewer resolves to. */\n resolved: ResolvedTheme;\n /** Whether the dashboard owns the theme (shows its own toggle). */\n showToggle: boolean;\n /** The product's theme store, when a {@link ThemeProvider} supplied one. */\n store: ThemeStore | undefined;\n}\n\nconst ThemeContext = React.createContext<ThemeState | null>(null);\n\nconst serverLight = (): ResolvedTheme => \"light\";\nconst noopSubscribe = () => () => {};\nconst hostTheme = () => detectHostTheme();\n\n/** Resolve a {@link ThemeMode} against `store`, re-rendering on every relevant change. */\nexport function useResolvedTheme(store: ThemeStore, mode: ThemeMode): ResolvedTheme {\n // Both stores are always subscribed (hooks can't be conditional); only the one matching `mode`\n // is read.\n const fromPref = useSyncStore(\n mode === \"auto\" ? store.subscribeThemePref : noopSubscribe,\n store.getResolvedTheme,\n );\n const fromHost = useSyncStore(mode === \"inherit\" ? subscribeHostTheme : noopSubscribe, hostTheme);\n if (mode === \"auto\") return fromPref;\n if (mode === \"inherit\") return fromHost;\n return mode;\n}\n\nfunction useSyncStore(\n subscribe: (cb: () => void) => () => void,\n read: () => ResolvedTheme,\n): ResolvedTheme {\n return React.useSyncExternalStore(subscribe, read, serverLight);\n}\n\n/** Props for {@link ThemeProvider}. */\nexport interface ThemeProviderProps {\n /** The product's theme store ({@link createThemeStore}). */\n store: ThemeStore;\n /** How the theme is decided; defaults to `\"auto\"`. */\n mode?: ThemeMode;\n /** Render prop receiving the resolved theme (e.g. to set `data-theme` on a wrapper). */\n children: (resolved: ResolvedTheme) => React.ReactNode;\n}\n\n/** Provide the resolved theme (and the store, for {@link ThemeToggle}) to the subtree. */\nexport function ThemeProvider({\n store,\n mode = \"auto\",\n children,\n}: ThemeProviderProps): React.ReactElement {\n const resolved = useResolvedTheme(store, mode);\n const value = React.useMemo<ThemeState>(\n () => ({ resolved, showToggle: mode === \"auto\", store }),\n [resolved, mode, store],\n );\n return <ThemeContext.Provider value={value}>{children(resolved)}</ThemeContext.Provider>;\n}\n\n/**\n * The active theme. Outside a {@link ThemeProvider} it follows the OS scheme and reports no toggle\n * (there is no store to persist a choice in).\n */\nexport function useTheme(): ThemeState {\n const ctx = React.useContext(ThemeContext);\n const fromOs = React.useSyncExternalStore(\n ctx ? noopSubscribe : subscribeSystemTheme,\n systemTheme,\n serverLight,\n );\n return ctx ?? { resolved: fromOs, showToggle: false, store: undefined };\n}\n","/**\n * Portal-token hand-off for the standalone SPA: a host links its customer to\n * `https://app.example.com/panel/#token=…` (the fragment never reaches servers or access logs);\n * `?token=` works too. The token is removed from the address bar so it isn't bookmarked, shared or\n * sent in a `Referer` header.\n *\n * @module\n */\n\n/**\n * Read a portal token from `#token=` (preferred) or `?token=`, and strip it from the URL through\n * `replace` (e.g. `(url) => history.replaceState(null, \"\", url)`). Other query and hash parameters\n * are kept. Returns the token, or `null` when the URL carries none (nothing is replaced then).\n */\nexport function takeTokenFromUrl(\n location: Pick<Location, \"hash\" | \"search\" | \"pathname\">,\n replace: (url: string) => void,\n): string | null {\n const rawHash = location.hash.replace(/^#/, \"\");\n // A hash route (`#/events`) is not a parameter list: leave it alone.\n const hash = rawHash.startsWith(\"/\") ? undefined : new URLSearchParams(rawHash);\n const search = new URLSearchParams(location.search);\n const fromHash = hash?.get(\"token\");\n const token = fromHash || search.get(\"token\");\n if (!token) return null;\n // Only re-serialise the parts that carried a token, so the rest stays byte-identical.\n let s = location.search.replace(/^\\?/, \"\");\n if (search.has(\"token\")) {\n search.delete(\"token\");\n s = search.toString();\n }\n let h = rawHash;\n if (hash?.has(\"token\")) {\n hash.delete(\"token\");\n h = hash.toString();\n }\n replace(`${location.pathname}${s ? `?${s}` : \"\"}${h ? `#${h}` : \"\"}`);\n return token;\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\n/** Merge class names with Tailwind-aware de-duplication. */\nexport function cn(...inputs: ClassValue[]): string {\n return twMerge(clsx(inputs));\n}\n","import React, { createContext, useCallback, useContext, useEffect, useReducer } from \"react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"../lib/utils.ts\";\n\n/** The tone of a toast. */\nexport type ToastKind = \"success\" | \"error\" | \"info\" | \"warning\";\n\n/** One toast in the stack. */\nexport interface Toast {\n id: string;\n kind: ToastKind;\n message: string;\n detail?: string;\n}\n\ninterface ToastState {\n toasts: Toast[];\n}\n\ntype Action = { type: \"add\"; toast: Toast } | { type: \"remove\"; id: string };\n\nfunction reducer(state: ToastState, action: Action): ToastState {\n switch (action.type) {\n case \"add\":\n return { toasts: [...state.toasts, action.toast] };\n case \"remove\":\n return { toasts: state.toasts.filter((t) => t.id !== action.id) };\n default:\n return state;\n }\n}\n\ninterface ToastContextValue {\n add: (kind: ToastKind, message: string, detail?: string) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | null>(null);\n\n/** `add(kind, message, detail?)` for the nearest {@link ToastProvider}; throws outside one. */\nexport function useToast(): ToastContextValue {\n const ctx = useContext(ToastContext);\n if (!ctx) throw new Error(\"useToast must be used within ToastProvider\");\n return ctx;\n}\n\nconst kindAccent: Record<ToastKind, string> = {\n success: \"bg-success\",\n error: \"bg-destructive\",\n warning: \"bg-warning\",\n info: \"bg-accent\",\n};\n\nconst kindBorder: Record<ToastKind, string> = {\n success: \"border-l-[var(--success)]\",\n error: \"border-l-[var(--destructive)]\",\n warning: \"border-l-[var(--warning)]\",\n info: \"border-l-[var(--accent)]\",\n};\n\nfunction ToastItem({ toast, onRemove }: { toast: Toast; onRemove: (id: string) => void }) {\n useEffect(() => {\n const t = setTimeout(() => onRemove(toast.id), 4500);\n return () => clearTimeout(t);\n }, [toast.id, onRemove]);\n\n return (\n <div\n role=\"alert\"\n className={cn(\n \"flex min-w-[280px] max-w-sm items-start gap-2.5 rounded-lg border border-border bg-card px-3.5 py-3 shadow-lg\",\n \"border-l-[3px]\",\n kindBorder[toast.kind],\n )}\n style={{\n animation: \"toastIn 160ms ease-out\",\n }}\n >\n <span\n className={cn(\"mt-1 size-2 shrink-0 rounded-full\", kindAccent[toast.kind])}\n aria-hidden\n />\n <div className=\"flex-1 min-w-0\">\n <p className=\"m-0 text-[13px] font-medium text-foreground leading-snug\">{toast.message}</p>\n {toast.detail && (\n <p className=\"mt-1 text-xs text-muted-foreground leading-snug\">{toast.detail}</p>\n )}\n </div>\n <button\n aria-label=\"Dismiss\"\n onClick={() => onRemove(toast.id)}\n className=\"shrink-0 rounded-sm text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring outline-none\"\n >\n <X className=\"size-3.5\" />\n </button>\n\n <style>{`\n @keyframes toastIn {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n `}</style>\n </div>\n );\n}\n\n/** Hosts the toast stack (inside the embed wrapper, so it gets the scoped styles and theme). */\nexport function ToastProvider({ children }: { children: React.ReactNode }) {\n const [state, dispatch] = useReducer(reducer, { toasts: [] });\n\n const add = useCallback((kind: ToastKind, message: string, detail?: string) => {\n const id = `${Date.now()}-${Math.random()}`;\n dispatch({ type: \"add\", toast: { id, kind, message, detail } });\n }, []);\n\n const remove = useCallback((id: string) => {\n dispatch({ type: \"remove\", id });\n }, []);\n\n return (\n <ToastContext.Provider value={{ add }}>\n {children}\n <div\n aria-live=\"polite\"\n aria-atomic=\"false\"\n className=\"fixed bottom-6 right-6 z-[9999] flex flex-col gap-2\"\n >\n {state.toasts.map((t) => (\n <ToastItem key={t.id} toast={t} onRemove={remove} />\n ))}\n </div>\n </ToastContext.Provider>\n );\n}\n","import React, { useState } from \"react\";\nimport { Monitor, Sun, Moon } from \"lucide-react\";\nimport type { ThemePref, ThemeStore } from \"../theme.ts\";\nimport { useTheme } from \"../theme-context.tsx\";\nimport { cn } from \"../lib/utils.ts\";\n\nconst OPTIONS: { value: ThemePref; label: string; Icon: React.FC<{ className?: string }> }[] = [\n { value: \"system\", label: \"System theme\", Icon: Monitor },\n { value: \"light\", label: \"Light theme\", Icon: Sun },\n { value: \"dark\", label: \"Dark theme\", Icon: Moon },\n];\n\n/** Props for {@link ThemeToggle}. */\nexport interface ThemeToggleProps {\n /** The store to read and write; defaults to the enclosing {@link ThemeProvider}'s. */\n store?: ThemeStore;\n}\n\n/**\n * The system/light/dark switcher. It persists the choice in the product's theme store (the `store`\n * prop, else the enclosing `ThemeProvider`'s).\n */\nexport function ThemeToggle({ store: storeProp }: ThemeToggleProps = {}): React.ReactElement {\n const ctx = useTheme();\n const store = storeProp ?? ctx.store;\n if (!store) throw new Error(\"ThemeToggle needs a `store` prop or an enclosing <ThemeProvider>.\");\n const [pref, setPref] = useState<ThemePref>(() => store.getThemePref());\n\n const choose = (value: ThemePref) => {\n setPref(value);\n store.setThemePref(value);\n };\n\n return (\n <div\n role=\"group\"\n aria-label=\"Theme\"\n className=\"inline-flex gap-0.5 rounded-md border border-border bg-secondary/50 p-0.5\"\n >\n {OPTIONS.map(({ value, label, Icon }) => {\n const active = pref === value;\n return (\n <button\n key={value}\n type=\"button\"\n title={label}\n aria-label={label}\n aria-pressed={active}\n onClick={() => choose(value)}\n className={cn(\n \"inline-flex h-6 w-7 items-center justify-center rounded-[5px] outline-none transition-colors\",\n \"focus-visible:ring-2 focus-visible:ring-ring\",\n active\n ? \"bg-card text-foreground shadow-sm\"\n : \"text-muted-foreground hover:text-foreground\",\n )}\n >\n <Icon className=\"size-3.5\" />\n </button>\n );\n })}\n </div>\n );\n}\n","/**\n * A tiny process-wide navigation guard. A view with unsaved edits registers a\n * blocker; the app's in-app navigation (tabs, project/env switch, opening another\n * flag) calls {@link canLeave} first and aborts if the blocker says no.\n *\n * wouter has no built-in navigation blocker, so this bridges the dirty view to the\n * navigation entry points without prop-drilling. Single active blocker (only one\n * editor is open at a time).\n *\n * @module\n */\n\n/** Returns `true` if navigation is allowed, `false` to block it (e.g. user cancelled). */\ntype Blocker = () => boolean;\n\nlet active: Blocker | null = null;\n\n/** Register the current blocker (replaces any previous one). */\nexport function setNavBlocker(blocker: Blocker): void {\n active = blocker;\n}\n\n/** Clear `blocker` if it is still the active one (safe from stale cleanups). */\nexport function clearNavBlocker(blocker: Blocker): void {\n if (active === blocker) active = null;\n}\n\n/** Consult the active blocker. `true` when navigation may proceed. */\nexport function canLeave(): boolean {\n return active ? active() : true;\n}\n","/**\n * The admin shell shared by every product: {@link useShellConfig} (the `/config` query, portal and\n * readonly state), {@link useShellNav} (nav-guarded in-app navigation that keeps sticky query\n * params) and {@link ShellFrame} (header, brand, badges, theme toggle, tabs, a switcher slot and the\n * routed content). Views, tabs and switchers stay in the product.\n *\n * @module\n */\n\nimport * as React from \"react\";\nimport { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useLocation, useSearchParams } from \"wouter\";\nimport { Lock } from \"lucide-react\";\nimport { ThemeToggle } from \"./components/ThemeToggle.tsx\";\nimport { canLeave } from \"./lib/nav-guard.ts\";\nimport { cn } from \"./lib/utils.ts\";\nimport { useTheme } from \"./theme-context.tsx\";\n\n/** The `/config` fields the shell reads. Products extend it with their own. */\nexport interface ShellConfigBase {\n /** Navbar title (wordmark). */\n title?: string;\n /** Navbar logo image URL (replaces the wordmark). */\n logoUrl?: string;\n /** The panel is read-only: mutating actions are hidden or disabled. */\n readonly?: boolean;\n /** Portal principal (wh/au style). */\n portal?: boolean;\n /** `\"portal\"` for a portal principal (en style). */\n mode?: string;\n /** Mount path of the panel, from the bootstrap global. */\n basePath?: string;\n}\n\n/**\n * Read the bootstrap config the panel handler injects as `window[configGlobal]`\n * (`\"__WEBHOOKS_CONFIG__\"`…). `{}` when it is missing (dev server, embed, SSR).\n */\nexport function readConfigGlobal<C extends object = ShellConfigBase>(\n configGlobal: string,\n): Partial<C> {\n if (typeof window === \"undefined\") return {};\n const value = (window as unknown as Record<string, unknown>)[configGlobal];\n return value && typeof value === \"object\" ? (value as Partial<C>) : {};\n}\n\n/** Options for {@link useShellConfig}. */\nexport interface UseShellConfigOptions<C extends ShellConfigBase> {\n /** Fetch `/config` (the product's API function). */\n getConfig: () => Promise<C>;\n /** The bootstrap config (see {@link readConfigGlobal}); used until `/config` answers. */\n bootstrap?: Partial<C>;\n /** Query key; `[\"config\"]` by default. */\n queryKey?: readonly unknown[];\n /** Stale time in ms; 60 s by default. */\n staleTime?: number;\n /** Render the portal chrome regardless of `/config` (the token embed). */\n forcePortal?: boolean;\n /**\n * The portal/viewer token attached to the API client, if any. A token means portal even before\n * (or when) `/config` fails, so no admin request fires for a token holder.\n */\n token?: string | null;\n /** How a config says \"portal\"; default: `portal === true` or `mode === \"portal\"`. */\n isPortal?: (config: Partial<C>) => boolean;\n}\n\n/** What {@link useShellConfig} returns. */\nexport interface ShellConfigState<C extends ShellConfigBase> {\n /** `/config` once loaded, the bootstrap before that. */\n config: Partial<C>;\n /**\n * `/config` has answered. Gate the default route and admin queries on it: the bootstrap can't\n * know a portal principal, so rendering before it would fire requests a portal is denied.\n */\n ready: boolean;\n /** `/config` is still loading and there is no bootstrap title to render the chrome with. */\n loading: boolean;\n /** `/config` failed and there is no bootstrap to fall back on: show an error screen. */\n failed: boolean;\n /** Portal chrome (forced, a token, or `/config` says so). */\n portal: boolean;\n /** Read-only panel. */\n readonly: boolean;\n /** `ready && !portal`: the condition for admin-only queries (`enabled: adminReady`). */\n adminReady: boolean;\n /** The underlying query. */\n query: UseQueryResult<C>;\n}\n\nconst defaultIsPortal = (c: Partial<ShellConfigBase>) => c.portal === true || c.mode === \"portal\";\n\n/**\n * The `/config` query plus the shell's derived state, with both portal-race fixes: admin work waits\n * for `/config` (`ready`/`adminReady`), and a token means portal from the first render.\n */\nexport function useShellConfig<C extends ShellConfigBase>(\n options: UseShellConfigOptions<C>,\n): ShellConfigState<C> {\n const bootstrap: Partial<C> = options.bootstrap ?? {};\n const query = useQuery({\n queryKey: options.queryKey ?? [\"config\"],\n queryFn: options.getConfig,\n staleTime: options.staleTime ?? 60_000,\n });\n const config: Partial<C> = query.data ?? bootstrap;\n const isPortal = options.isPortal ?? defaultIsPortal;\n const portal = Boolean(options.forcePortal) || Boolean(options.token) || isPortal(config);\n const ready = query.isSuccess;\n const hasBootstrap = Boolean(bootstrap.title);\n return {\n config,\n ready,\n loading: query.isLoading && !hasBootstrap && !options.forcePortal,\n failed: query.isError && !hasBootstrap,\n portal,\n readonly: config.readonly ?? false,\n adminReady: ready && !portal,\n query,\n };\n}\n\n/** Options for {@link useShellNav}. */\nexport interface UseShellNavOptions {\n /** Query params that survive navigation (the scope, a portal token…): `[\"tenant\", \"token\"]`. */\n stickyParams?: readonly string[];\n}\n\n/**\n * In-app navigation for the shell: `go(path, params?)` consults the nav guard (a view with unsaved\n * edits can veto the move), carries the sticky params over, then applies `params` (`\"\"` removes\n * one).\n */\nexport function useShellNav(\n options: UseShellNavOptions = {},\n): (path: string, params?: Record<string, string>) => void {\n const [, navigate] = useLocation();\n const [searchParams] = useSearchParams();\n const sticky = options.stickyParams ?? [];\n return (path, params = {}) => {\n if (!canLeave()) return;\n const next = new URLSearchParams();\n for (const key of sticky) {\n const value = searchParams.get(key);\n if (value) next.set(key, value);\n }\n for (const [key, value] of Object.entries(params)) {\n if (value) next.set(key, value);\n else next.delete(key);\n }\n const search = next.toString();\n navigate(search ? `${path}?${search}` : path);\n };\n}\n\n/** One navigation tab. */\nexport interface ShellTab {\n path: string;\n label: React.ReactNode;\n /** Whether the tab is active for `location`; default: exact for `/`, prefix otherwise. */\n match?: (location: string) => boolean;\n}\n\n/** Props for {@link ShellFrame}. */\nexport interface ShellFrameProps {\n /** Wordmark next to the mark (and the logo's alt text). */\n title: string;\n /** Logo image URL; replaces the mark and the wordmark. */\n logoUrl?: string;\n /** The product mark (e.g. `<BrandMark light={…} />`), shown before the title. */\n brandMark?: React.ReactNode;\n /** Brand click handler (e.g. go home); the brand is not a link without it. */\n onBrandClick?: () => void;\n /** Scope switcher (app, project/env, tenant) or a pinned scope label, after the brand. */\n switcher?: React.ReactNode;\n /** Show the read-only badge. */\n readonly?: boolean;\n /** Show the portal badge. */\n portal?: boolean;\n /** Portal badge text; `\"Portal\"` by default. */\n portalLabel?: React.ReactNode;\n /** Extra header content, before the badges. */\n headerExtra?: React.ReactNode;\n /** Show the theme toggle; defaults to whether the theme provider owns the theme. */\n showThemeToggle?: boolean;\n /** Navigation tabs; the bar is hidden when there is at most one. */\n tabs?: readonly ShellTab[];\n /** Navigate to a tab (usually `useShellNav()`'s `go`). */\n onNavigate?: (path: string) => void;\n /** Render this full-screen instead of the shell (e.g. a config error). */\n fallback?: React.ReactNode;\n /** The routed content (`<Switch>…</Switch>`). */\n children?: React.ReactNode;\n className?: string;\n}\n\nconst defaultMatch = (path: string) => (location: string) =>\n path === \"/\" ? location === \"/\" : location === path || location.startsWith(`${path}/`);\n\n/** The shared admin chrome: sticky header (brand, switcher, badges, toggle), tabs and content. */\nexport function ShellFrame({\n title,\n logoUrl,\n brandMark,\n onBrandClick,\n switcher,\n readonly,\n portal,\n portalLabel = \"Portal\",\n headerExtra,\n showThemeToggle,\n tabs = [],\n onNavigate,\n fallback,\n children,\n className,\n}: ShellFrameProps): React.ReactElement {\n const [location] = useLocation();\n const theme = useTheme();\n const toggle = showThemeToggle ?? theme.showToggle;\n\n if (fallback !== undefined && fallback !== null && fallback !== false) {\n return (\n <div className=\"flex h-screen items-center justify-center bg-background px-4 text-center\">\n {fallback}\n </div>\n );\n }\n\n const brand = logoUrl ? (\n <img src={logoUrl} alt={title} className=\"h-7 max-w-[320px] object-contain\" />\n ) : (\n <>\n {brandMark}\n <span className=\"text-sm font-semibold tracking-tight\">{title}</span>\n </>\n );\n\n return (\n <div\n className={cn(\n \"flex h-screen flex-col overflow-hidden bg-background text-foreground\",\n className,\n )}\n >\n <header className=\"sticky top-0 z-40 border-b border-border bg-background/80 backdrop-blur\">\n <div className=\"mx-auto flex h-14 max-w-6xl items-center gap-3 px-4 sm:px-6\">\n {onBrandClick ? (\n <a\n href=\"#\"\n data-testid=\"shell-brand\"\n onClick={(e) => {\n e.preventDefault();\n onBrandClick();\n }}\n className=\"flex shrink-0 items-center gap-2 rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n {brand}\n </a>\n ) : (\n <div data-testid=\"shell-brand\" className=\"flex shrink-0 items-center gap-2\">\n {brand}\n </div>\n )}\n\n {switcher ? (\n <>\n <span className=\"select-none text-border\">/</span>\n {switcher}\n </>\n ) : null}\n\n <div className=\"ml-auto flex items-center gap-2\">\n {headerExtra}\n {readonly && (\n <span className=\"flex items-center gap-1 rounded-md border border-warning/30 bg-warning/10 px-2 py-0.5 text-xs font-medium text-warning\">\n <Lock className=\"size-3\" />\n Read-only\n </span>\n )}\n {portal && (\n <span className=\"rounded-md border border-accent/30 bg-accent/10 px-2 py-0.5 text-xs font-medium text-accent\">\n {portalLabel}\n </span>\n )}\n {toggle && <ThemeToggle />}\n </div>\n </div>\n\n {tabs.length > 1 && (\n <nav\n className=\"mx-auto flex max-w-6xl items-center gap-1 overflow-x-auto px-2 sm:px-4\"\n aria-label=\"Main navigation\"\n >\n {tabs.map(({ path, label, match }) => {\n const active = (match ?? defaultMatch(path))(location);\n return (\n <button\n key={path}\n type=\"button\"\n onClick={() => onNavigate?.(path)}\n aria-current={active ? \"page\" : undefined}\n className={cn(\n \"whitespace-nowrap px-3 py-2.5 text-[13px] font-medium outline-none transition-colors focus-visible:text-foreground\",\n active\n ? \"relative text-foreground after:absolute after:inset-x-3 after:-bottom-px after:h-0.5 after:rounded-full after:bg-accent\"\n : \"text-muted-foreground hover:text-foreground\",\n )}\n >\n {label}\n </button>\n );\n })}\n </nav>\n )}\n </header>\n\n <main className=\"flex-1 overflow-y-auto overflow-x-hidden\">{children}</main>\n </div>\n );\n}\n\n/** The default message for a `/config` failure (pass it as {@link ShellFrameProps.fallback}). */\nexport function ConfigError(): React.ReactElement {\n return (\n <p className=\"text-[13px] text-muted-foreground\">\n Could not load the panel configuration. Check that the API is reachable and that you are\n signed in.\n </p>\n );\n}\n","/**\n * The standalone SPA bootstrap (`src/ui/main.tsx` in every product): apply the theme before first\n * paint, take a portal token from the URL, create the QueryClient, read the base path from the\n * config global, and render the product's `App` with browser-history routing.\n *\n * @module\n */\n\nimport * as React from \"react\";\nimport { createRoot, type Root } from \"react-dom/client\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport type { BaseLocationHook } from \"wouter\";\nimport { useBrowserLocation } from \"wouter/use-browser-location\";\nimport type { ApiClient } from \"./api-client.ts\";\nimport { ToastProvider } from \"./components/Toast.tsx\";\nimport { readConfigGlobal } from \"./shell.tsx\";\nimport { createThemeStore, type ThemeStore } from \"./theme.ts\";\nimport { ThemeProvider } from \"./theme-context.tsx\";\nimport { takeTokenFromUrl } from \"./token.ts\";\n\n/** The props `bootSpa` (and `createEmbed`) pass to the product's `App`. */\nexport interface ShellAppProps {\n /** wouter location hook (browser history in the SPA; hash/browser/memory/custom in the embed). */\n locationHook?: BaseLocationHook;\n /** wouter search hook (the memory router's, so the query string survives `routing: \"memory\"`). */\n searchHook?: () => string;\n /** Router base path. */\n base?: string;\n /** Navbar logo override. */\n logoUrl?: string;\n /** Whether the shell shows its own theme toggle. */\n showThemeToggle?: boolean;\n /** Render the portal chrome regardless of `/config` (the token embed). */\n forcePortal?: boolean;\n}\n\n/** A `QueryClient` with the shell's defaults: one retry, no refetch on window focus. */\nexport function createShellQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: { queries: { retry: 1, refetchOnWindowFocus: false } },\n });\n}\n\n/** Options for {@link bootSpa}. */\nexport interface BootSpaOptions<P extends object = object> {\n /** The product's root component. */\n App: React.ComponentType<ShellAppProps & P>;\n /** The global the panel handler injects (`\"__WEBHOOKS_CONFIG__\"`); its `basePath` is the router base. */\n configGlobal: string;\n /** The theme storage key (`\"xtandard-webhooks:theme\"`), or an existing store. */\n themeKey: string | ThemeStore;\n /**\n * Take a portal token from `#token=`/`?token=`, strip it from the address bar, and attach it to\n * `api`. Needs `api`. Default `false` (products without a portal).\n */\n tokenFromUrl?: boolean;\n /** The product's API client (for the token). */\n api?: Pick<ApiClient, \"setApiToken\">;\n /** Extra props for `App`. */\n appProps?: P;\n /** The mount element or its id; `\"root\"` by default. */\n root?: HTMLElement | string;\n /** Bring your own QueryClient. */\n queryClient?: QueryClient;\n /** Wrap in `React.StrictMode`; default `true`. */\n strictMode?: boolean;\n}\n\n/** What {@link bootSpa} returns. */\nexport interface BootedSpa {\n root: Root;\n queryClient: QueryClient;\n themeStore: ThemeStore;\n /** The token taken from the URL, if any. */\n token: string | null;\n}\n\n/** Boot the standalone admin SPA. Call once from the product's `main.tsx`. */\nexport function bootSpa<P extends object = object>(options: BootSpaOptions<P>): BootedSpa {\n const themeStore =\n typeof options.themeKey === \"string\" ? createThemeStore(options.themeKey) : options.themeKey;\n // Apply the persisted theme before first paint.\n themeStore.initTheme();\n\n let token: string | null = null;\n if (options.tokenFromUrl) {\n if (!options.api) throw new Error(\"bootSpa: `tokenFromUrl` needs the product's `api` client.\");\n token = takeTokenFromUrl(window.location, (url) => window.history.replaceState(null, \"\", url));\n if (token) options.api.setApiToken(token);\n }\n\n const queryClient = options.queryClient ?? createShellQueryClient();\n const el =\n typeof options.root === \"object\"\n ? options.root\n : document.getElementById(options.root ?? \"root\");\n if (!el) throw new Error(\"Root element not found\");\n\n // The bundled SPA owns its URL, and the panel handler serves a SPA catch-all under the basePath,\n // so it uses real browser-history routing for clean, deep-linkable paths.\n const basePath = (\n readConfigGlobal<{ basePath?: string }>(options.configGlobal).basePath ?? \"\"\n ).replace(/\\/$/, \"\");\n\n const { App } = options;\n const appProps = (options.appProps ?? {}) as P;\n const tree = (\n <QueryClientProvider client={queryClient}>\n <ThemeProvider store={themeStore} mode=\"auto\">\n {() => (\n <ToastProvider>\n <App {...appProps} locationHook={useBrowserLocation} base={basePath} />\n </ToastProvider>\n )}\n </ThemeProvider>\n </QueryClientProvider>\n );\n const root = createRoot(el);\n root.render(options.strictMode === false ? tree : <React.StrictMode>{tree}</React.StrictMode>);\n return { root, queryClient, themeStore, token };\n}\n","/**\n * Where Base UI portals (Select/Combobox popups, Dialogs) render.\n *\n * In the **standalone SPA** the stylesheet is global, so portals default to\n * `document.body` and look right. In the **React embed** the stylesheet is\n * scoped under the product's `.xtandard-<product>` class (`xtandard-kit scope-embed-css`), so\n * anything portaled to `document.body` would fall outside the scope and render\n * unstyled. The embed therefore points portals at its own wrapper element via\n * {@link setPortalContainerRef}, keeping popups inside the scoped subtree.\n *\n * Module-level singleton (same trade-off as `setApiBase`/`setApiToken`): one\n * embed per page. Unset → portals default to `document.body`.\n *\n * @module\n */\n\nimport type { RefObject } from \"react\";\n\nlet sharedRef: RefObject<HTMLElement | null> | undefined;\n\n/** Point portals at `ref` (the embed wrapper). Pass `undefined` to reset to the body default. */\nexport function setPortalContainerRef(ref: RefObject<HTMLElement | null> | undefined): void {\n sharedRef = ref;\n}\n\n/**\n * The current portal container ref, or `undefined` when none is set (Base UI\n * then defaults to `document.body`). Pass the result to a Base UI\n * `*.Portal container={…}` prop.\n */\nexport function portalContainerRef(): RefObject<HTMLElement | null> | undefined {\n return sharedRef;\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,MAAM,aAAa;AAEnB,SAAS,YAAwC;CAC/C,OAAO,OAAO,eAAe,cAAc,WAAW,UAAU,IAAI,KAAA;AACtE;AAEA,SAAS,cAAuB;CAC9B,OAAO,UAAU,GAAG,WAAW;AACjC;;AAGA,SAAgB,cAA6B;CAC3C,OAAO,YAAY,IAAI,SAAS;AAClC;;AAGA,SAAgB,qBAAqB,IAA4B;CAC/D,MAAM,KAAK,UAAU;CACrB,IAAI,iBAAiB,UAAU,EAAE;CACjC,aAAa,IAAI,oBAAoB,UAAU,EAAE;AACnD;;AAGA,SAAgB,aAAa,MAAgC;CAC3D,OAAO,SAAS,WAAW,YAAY,IAAI;AAC7C;;;;;AA8BA,SAAgB,iBAAiB,YAAgC;CAC/D,MAAM,4BAAY,IAAI,IAAgB;CAEtC,MAAM,qBAAgC;EACpC,IAAI;GACF,MAAM,IAAI,aAAa,QAAQ,UAAU;GACzC,IAAI,MAAM,WAAW,MAAM,UAAU,MAAM,UAAU,OAAO;EAC9D,QAAQ,CAER;EACA,OAAO;CACT;CAEA,MAAM,gBAAgB,SAA0B;EAC9C,IAAI;GACF,aAAa,QAAQ,YAAY,IAA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,sBAAAA,qBAAD;EAAqB,QAAQ;YAC3B,iBAAA,GAAA,kBAAA,KAAC,eAAD;GAAe,OAAO;GAAY,MAAK;mBAEnC,iBAAA,GAAA,kBAAA,KAAC,eAAD,EAAA,UACE,iBAAA,GAAA,kBAAA,KAAC,KAAD;IAAK,GAAI;IAAU,cAAcC,4BAAAA;IAAoB,MAAM;GAAW,CAAA,EACzD,CAAA;EAEJ,CAAA;CACI,CAAA;CAEvB,MAAM,QAAA,GAAA,iBAAA,YAAkB,EAAE;CAC1B,KAAK,OAAO,QAAQ,eAAe,QAAQ,OAAO,iBAAA,GAAA,kBAAA,KAACC,MAAM,YAAP,EAAA,UAAmB,KAAuB,CAAA,CAAC;CAC7F,OAAO;EAAE;EAAM;EAAa;EAAY;CAAM;AAChD;;;ACtGA,IAAI;;AAGJ,SAAgB,sBAAsB,KAAsD;CAC1F,YAAY;AACd;;;;;;AAOA,SAAgB,qBAAgE;CAC9E,OAAO;AACT"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { n as CompareAndSwapKvStorage } from "./contract-BvgtswLX.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/storage/postgres.d.ts
|
|
4
|
+
/** Minimal structural view of a SQL client: `pg` `Pool`/`Client` and `PGlite` satisfy it. */
|
|
5
|
+
interface SqlClient {
|
|
6
|
+
/** Run one parameterized statement (`$1`, `$2`, …). */
|
|
7
|
+
query(text: string, params?: unknown[]): Promise<{
|
|
8
|
+
rows: Array<Record<string, unknown>>;
|
|
9
|
+
}>;
|
|
10
|
+
}
|
|
11
|
+
/** A client the driver can also shut down (e.g. a `pg` `Pool`). */
|
|
12
|
+
interface ClosableSqlClient extends SqlClient {
|
|
13
|
+
/** End the client. */
|
|
14
|
+
end?(): Promise<unknown>;
|
|
15
|
+
}
|
|
16
|
+
/** Options for {@link createPostgresStorage}. */
|
|
17
|
+
interface PostgresStorageOptions {
|
|
18
|
+
/** A pre-built client (`pg` `Pool`/`Client`, `PGlite`, …). Never closed by the driver. */
|
|
19
|
+
client?: SqlClient;
|
|
20
|
+
/** Connection string used to create a `pg` `Pool` lazily when no `client` is given. */
|
|
21
|
+
connectionString?: string;
|
|
22
|
+
/** Alias for {@link PostgresStorageOptions.connectionString}. */
|
|
23
|
+
url?: string;
|
|
24
|
+
/** Table name (default `"xtandard_kv"`; products pass theirs). Must be a safe SQL identifier. */
|
|
25
|
+
table?: string;
|
|
26
|
+
}
|
|
27
|
+
/** A compare-and-swap capable storage backed by Postgres, plus `close()`. */
|
|
28
|
+
interface PostgresKvStorage extends CompareAndSwapKvStorage {
|
|
29
|
+
/** End the pool if this driver created it; no-op for a borrowed client. */
|
|
30
|
+
close(): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/** A lazily created `pg` client (semi-public, ADR 0004). */
|
|
33
|
+
interface PgConnection {
|
|
34
|
+
/** Resolve the client, creating a `pg` `Pool` on first use when needed (retried after a failure). */
|
|
35
|
+
get(): Promise<ClosableSqlClient>;
|
|
36
|
+
/** End the pool if this connection created it. */
|
|
37
|
+
close(): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** Build a {@link PgConnection} from a borrowed `client` or a `connectionString`. */
|
|
40
|
+
declare function pgConnection(client: SqlClient | undefined, connectionString: string | undefined, subpath?: string): PgConnection;
|
|
41
|
+
/**
|
|
42
|
+
* Memoize "get the client and run these statements once" (semi-public, ADR 0004). The returned
|
|
43
|
+
* function resolves the client after the DDL has run; a failed DDL is retried on the next call.
|
|
44
|
+
* Products pass extra statements for their own tables (au's event log).
|
|
45
|
+
*/
|
|
46
|
+
declare function pgReady(connection: PgConnection, ddl: string[]): () => Promise<ClosableSqlClient>;
|
|
47
|
+
/**
|
|
48
|
+
* The DDL {@link createPostgresStorage} runs on first use, for migrations when the runtime role may
|
|
49
|
+
* not create tables. Products pass their table name.
|
|
50
|
+
*/
|
|
51
|
+
declare function postgresStorageSchema(table?: string): string;
|
|
52
|
+
/**
|
|
53
|
+
* The KV operations over a table that already exists (semi-public, ADR 0004): `exec` resolves a
|
|
54
|
+
* ready client before every operation. {@link createPostgresStorage} is this plus
|
|
55
|
+
* {@link pgConnection} and {@link pgReady}.
|
|
56
|
+
*/
|
|
57
|
+
declare function postgresKvStorage(table: string, exec: () => Promise<SqlClient>): CompareAndSwapKvStorage;
|
|
58
|
+
/**
|
|
59
|
+
* Create a Postgres-backed {@link PostgresKvStorage}. Connection and table creation are lazy.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* import { createPostgresStorage } from "@xtandard/kit/storage/postgres";
|
|
64
|
+
*
|
|
65
|
+
* const storage = createPostgresStorage({ connectionString: process.env.DATABASE_URL, table: "xtandard_kv" });
|
|
66
|
+
* // or: createPostgresStorage({ client: new PGlite() })
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
declare function createPostgresStorage(options?: PostgresStorageOptions): PostgresKvStorage;
|
|
70
|
+
//#endregion
|
|
71
|
+
export { SqlClient as a, pgReady as c, PostgresStorageOptions as i, postgresKvStorage as l, PgConnection as n, createPostgresStorage as o, PostgresKvStorage as r, pgConnection as s, ClosableSqlClient as t, postgresStorageSchema as u };
|
|
72
|
+
//# sourceMappingURL=postgres-BJzxKBk0.d.cts.map
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
const require_peer = require("./peer-BIjBFzwQ.cjs");
|
|
2
|
+
const require_util = require("./util-dAnTK9x-.cjs");
|
|
3
|
+
const require_json = require("./json-CM7TwYQ7.cjs");
|
|
4
|
+
//#region src/storage/postgres.ts
|
|
5
|
+
/**
|
|
6
|
+
* Postgres storage driver: one key/value table (`key text COLLATE "C" PRIMARY KEY, value jsonb`)
|
|
7
|
+
* over any client exposing `query(text, params?) → { rows }`: [`pg`](https://node-postgres.com)
|
|
8
|
+
* (`Pool`/`Client`) and the in-process [`@electric-sql/pglite`](https://pglite.dev) alike. Pass a
|
|
9
|
+
* `client`, or a `connectionString`/`url` to create a `pg` `Pool` lazily on first use.
|
|
10
|
+
*
|
|
11
|
+
* - The table is created on first use (`CREATE TABLE IF NOT EXISTS`, once); a failed DDL is
|
|
12
|
+
* retried on the next call, not cached.
|
|
13
|
+
* - The `"C"` collation (new tables only) makes ordering and `LIKE` prefixes bytewise. Existing
|
|
14
|
+
* tables keep working: prefixes are matched with `LIKE … ESCAPE '!'` plus an exact `startsWith`.
|
|
15
|
+
* - `compareAndSwap` is one statement (`UPDATE … WHERE value = $::jsonb`, or `INSERT … ON CONFLICT
|
|
16
|
+
* DO NOTHING` for an absent key). `jsonb` equality is structural, so rows written before
|
|
17
|
+
* canonicalisation swap too.
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
const SUBPATH = "@xtandard/kit/storage/postgres";
|
|
22
|
+
/** Build a {@link PgConnection} from a borrowed `client` or a `connectionString`. */
|
|
23
|
+
function pgConnection(client, connectionString, subpath = SUBPATH) {
|
|
24
|
+
const ownsClient = !client;
|
|
25
|
+
let current = client;
|
|
26
|
+
let connecting;
|
|
27
|
+
return {
|
|
28
|
+
async get() {
|
|
29
|
+
if (current) return current;
|
|
30
|
+
connecting ??= (async () => {
|
|
31
|
+
const mod = await require_peer.importPeer("pg", subpath, () => import("pg"));
|
|
32
|
+
current = new (mod.Pool ?? mod.default?.Pool)({ connectionString });
|
|
33
|
+
return current;
|
|
34
|
+
})();
|
|
35
|
+
try {
|
|
36
|
+
return await connecting;
|
|
37
|
+
} finally {
|
|
38
|
+
connecting = void 0;
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
async close() {
|
|
42
|
+
if (ownsClient && current?.end) await current.end();
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Memoize "get the client and run these statements once" (semi-public, ADR 0004). The returned
|
|
48
|
+
* function resolves the client after the DDL has run; a failed DDL is retried on the next call.
|
|
49
|
+
* Products pass extra statements for their own tables (au's event log).
|
|
50
|
+
*/
|
|
51
|
+
function pgReady(connection, ddl) {
|
|
52
|
+
let ensured;
|
|
53
|
+
return async () => {
|
|
54
|
+
const client = await connection.get();
|
|
55
|
+
ensured ??= (async () => {
|
|
56
|
+
for (const statement of ddl) await client.query(statement);
|
|
57
|
+
})();
|
|
58
|
+
try {
|
|
59
|
+
await ensured;
|
|
60
|
+
} catch (error) {
|
|
61
|
+
ensured = void 0;
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
return client;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The DDL {@link createPostgresStorage} runs on first use, for migrations when the runtime role may
|
|
69
|
+
* not create tables. Products pass their table name.
|
|
70
|
+
*/
|
|
71
|
+
function postgresStorageSchema(table = "xtandard_kv") {
|
|
72
|
+
require_util.assertIdentifier(table);
|
|
73
|
+
return `CREATE TABLE IF NOT EXISTS ${table} (key text COLLATE "C" PRIMARY KEY, value jsonb NOT NULL)`;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The KV operations over a table that already exists (semi-public, ADR 0004): `exec` resolves a
|
|
77
|
+
* ready client before every operation. {@link createPostgresStorage} is this plus
|
|
78
|
+
* {@link pgConnection} and {@link pgReady}.
|
|
79
|
+
*/
|
|
80
|
+
function postgresKvStorage(table, exec) {
|
|
81
|
+
require_util.assertIdentifier(table);
|
|
82
|
+
return {
|
|
83
|
+
async getItem(key) {
|
|
84
|
+
const { rows } = await (await exec()).query(`SELECT value::text AS value FROM ${table} WHERE key = $1`, [key]);
|
|
85
|
+
const value = rows[0]?.value;
|
|
86
|
+
return typeof value === "string" ? JSON.parse(value) : null;
|
|
87
|
+
},
|
|
88
|
+
async setItem(key, value) {
|
|
89
|
+
await (await exec()).query(`INSERT INTO ${table} (key, value) VALUES ($1, $2::jsonb)
|
|
90
|
+
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`, [key, require_json.canonicalJson(value)]);
|
|
91
|
+
},
|
|
92
|
+
async removeItem(key) {
|
|
93
|
+
await (await exec()).query(`DELETE FROM ${table} WHERE key = $1`, [key]);
|
|
94
|
+
},
|
|
95
|
+
async getKeys(prefix) {
|
|
96
|
+
const { rows } = await (await exec()).query(`SELECT key FROM ${table} WHERE key LIKE $1 ESCAPE '!'`, [`${require_util.escapeLike(prefix)}%`]);
|
|
97
|
+
return rows.map((row) => String(row.key)).filter((key) => key.startsWith(prefix));
|
|
98
|
+
},
|
|
99
|
+
async compareAndSwap(input) {
|
|
100
|
+
const c = await exec();
|
|
101
|
+
const next = require_json.canonicalJson(input.next);
|
|
102
|
+
const { rows } = input.expected === null ? await c.query(`INSERT INTO ${table} (key, value) VALUES ($1, $2::jsonb)
|
|
103
|
+
ON CONFLICT (key) DO NOTHING RETURNING key`, [input.key, next]) : await c.query(`UPDATE ${table} SET value = $3::jsonb
|
|
104
|
+
WHERE key = $1 AND value = $2::jsonb RETURNING key`, [
|
|
105
|
+
input.key,
|
|
106
|
+
require_json.canonicalJson(input.expected),
|
|
107
|
+
next
|
|
108
|
+
]);
|
|
109
|
+
return rows.length === 1;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Create a Postgres-backed {@link PostgresKvStorage}. Connection and table creation are lazy.
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* ```ts
|
|
118
|
+
* import { createPostgresStorage } from "@xtandard/kit/storage/postgres";
|
|
119
|
+
*
|
|
120
|
+
* const storage = createPostgresStorage({ connectionString: process.env.DATABASE_URL, table: "xtandard_kv" });
|
|
121
|
+
* // or: createPostgresStorage({ client: new PGlite() })
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
function createPostgresStorage(options = {}) {
|
|
125
|
+
const table = options.table ?? "xtandard_kv";
|
|
126
|
+
const connection = pgConnection(options.client, options.connectionString ?? options.url);
|
|
127
|
+
return {
|
|
128
|
+
...postgresKvStorage(table, pgReady(connection, [postgresStorageSchema(table)])),
|
|
129
|
+
close: connection.close
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
Object.defineProperty(exports, "createPostgresStorage", {
|
|
134
|
+
enumerable: true,
|
|
135
|
+
get: function() {
|
|
136
|
+
return createPostgresStorage;
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
Object.defineProperty(exports, "pgConnection", {
|
|
140
|
+
enumerable: true,
|
|
141
|
+
get: function() {
|
|
142
|
+
return pgConnection;
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
Object.defineProperty(exports, "pgReady", {
|
|
146
|
+
enumerable: true,
|
|
147
|
+
get: function() {
|
|
148
|
+
return pgReady;
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
Object.defineProperty(exports, "postgresKvStorage", {
|
|
152
|
+
enumerable: true,
|
|
153
|
+
get: function() {
|
|
154
|
+
return postgresKvStorage;
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
Object.defineProperty(exports, "postgresStorageSchema", {
|
|
158
|
+
enumerable: true,
|
|
159
|
+
get: function() {
|
|
160
|
+
return postgresStorageSchema;
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
//# sourceMappingURL=postgres-CA8_XcAE.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-CA8_XcAE.cjs","names":["importPeer","canonicalJson","escapeLike"],"sources":["../src/storage/postgres.ts"],"sourcesContent":["/**\n * Postgres storage driver: one key/value table (`key text COLLATE \"C\" PRIMARY KEY, value jsonb`)\n * over any client exposing `query(text, params?) → { rows }`: [`pg`](https://node-postgres.com)\n * (`Pool`/`Client`) and the in-process [`@electric-sql/pglite`](https://pglite.dev) alike. Pass a\n * `client`, or a `connectionString`/`url` to create a `pg` `Pool` lazily on first use.\n *\n * - The table is created on first use (`CREATE TABLE IF NOT EXISTS`, once); a failed DDL is\n * retried on the next call, not cached.\n * - The `\"C\"` collation (new tables only) makes ordering and `LIKE` prefixes bytewise. Existing\n * tables keep working: prefixes are matched with `LIKE … ESCAPE '!'` plus an exact `startsWith`.\n * - `compareAndSwap` is one statement (`UPDATE … WHERE value = $::jsonb`, or `INSERT … ON CONFLICT\n * DO NOTHING` for an absent key). `jsonb` equality is structural, so rows written before\n * canonicalisation swap too.\n *\n * @module\n */\n\nimport { canonicalJson } from \"../internal/json.ts\";\nimport { importPeer } from \"../internal/peer.ts\";\nimport type { CompareAndSwapInput, CompareAndSwapKvStorage } from \"./contract.ts\";\nimport { assertIdentifier, escapeLike } from \"./util.ts\";\n\nconst SUBPATH = \"@xtandard/kit/storage/postgres\";\n\n/** Minimal structural view of a SQL client: `pg` `Pool`/`Client` and `PGlite` satisfy it. */\nexport interface SqlClient {\n /** Run one parameterized statement (`$1`, `$2`, …). */\n query(text: string, params?: unknown[]): Promise<{ rows: Array<Record<string, unknown>> }>;\n}\n\n/** A client the driver can also shut down (e.g. a `pg` `Pool`). */\nexport interface ClosableSqlClient extends SqlClient {\n /** End the client. */\n end?(): Promise<unknown>;\n}\n\n/** Options for {@link createPostgresStorage}. */\nexport interface PostgresStorageOptions {\n /** A pre-built client (`pg` `Pool`/`Client`, `PGlite`, …). Never closed by the driver. */\n client?: SqlClient;\n /** Connection string used to create a `pg` `Pool` lazily when no `client` is given. */\n connectionString?: string;\n /** Alias for {@link PostgresStorageOptions.connectionString}. */\n url?: string;\n /** Table name (default `\"xtandard_kv\"`; products pass theirs). Must be a safe SQL identifier. */\n table?: string;\n}\n\n/** A compare-and-swap capable storage backed by Postgres, plus `close()`. */\nexport interface PostgresKvStorage extends CompareAndSwapKvStorage {\n /** End the pool if this driver created it; no-op for a borrowed client. */\n close(): Promise<void>;\n}\n\n/** A lazily created `pg` client (semi-public, ADR 0004). */\nexport interface PgConnection {\n /** Resolve the client, creating a `pg` `Pool` on first use when needed (retried after a failure). */\n get(): Promise<ClosableSqlClient>;\n /** End the pool if this connection created it. */\n close(): Promise<void>;\n}\n\n/** Build a {@link PgConnection} from a borrowed `client` or a `connectionString`. */\nexport function pgConnection(\n client: SqlClient | undefined,\n connectionString: string | undefined,\n subpath = SUBPATH,\n): PgConnection {\n const ownsClient = !client;\n let current: ClosableSqlClient | undefined = client;\n let connecting: Promise<ClosableSqlClient> | undefined;\n return {\n async get(): Promise<ClosableSqlClient> {\n if (current) return current;\n connecting ??= (async () => {\n type PoolCtor = new (config: { connectionString?: string }) => ClosableSqlClient;\n const mod = await importPeer(\n \"pg\",\n subpath,\n () =>\n import(\"pg\") as unknown as Promise<{ Pool?: PoolCtor; default?: { Pool: PoolCtor } }>,\n );\n const Pool = (mod.Pool ?? mod.default?.Pool) as PoolCtor;\n current = new Pool({ connectionString });\n return current;\n })();\n try {\n return await connecting;\n } finally {\n connecting = undefined;\n }\n },\n async close(): Promise<void> {\n if (ownsClient && current?.end) await current.end();\n },\n };\n}\n\n/**\n * Memoize \"get the client and run these statements once\" (semi-public, ADR 0004). The returned\n * function resolves the client after the DDL has run; a failed DDL is retried on the next call.\n * Products pass extra statements for their own tables (au's event log).\n */\nexport function pgReady(connection: PgConnection, ddl: string[]): () => Promise<ClosableSqlClient> {\n let ensured: Promise<void> | undefined;\n return async () => {\n const client = await connection.get();\n ensured ??= (async () => {\n for (const statement of ddl) await client.query(statement);\n })();\n try {\n await ensured;\n } catch (error) {\n ensured = undefined; // let a later call retry the DDL\n throw error;\n }\n return client;\n };\n}\n\n/**\n * The DDL {@link createPostgresStorage} runs on first use, for migrations when the runtime role may\n * not create tables. Products pass their table name.\n */\nexport function postgresStorageSchema(table = \"xtandard_kv\"): string {\n assertIdentifier(table);\n return `CREATE TABLE IF NOT EXISTS ${table} (key text COLLATE \"C\" PRIMARY KEY, value jsonb NOT NULL)`;\n}\n\n/**\n * The KV operations over a table that already exists (semi-public, ADR 0004): `exec` resolves a\n * ready client before every operation. {@link createPostgresStorage} is this plus\n * {@link pgConnection} and {@link pgReady}.\n */\nexport function postgresKvStorage(\n table: string,\n exec: () => Promise<SqlClient>,\n): CompareAndSwapKvStorage {\n assertIdentifier(table);\n return {\n async getItem<T>(key: string): Promise<T | null> {\n // `value::text`, parsed once: a driver that already parsed `jsonb` would otherwise hand back\n // the string \"123\" for a stored JSON string, and a second parse would turn it into 123.\n const { rows } = await (\n await exec()\n ).query(`SELECT value::text AS value FROM ${table} WHERE key = $1`, [key]);\n const value = rows[0]?.value;\n return typeof value === \"string\" ? (JSON.parse(value) as T) : null;\n },\n\n async setItem<T>(key: string, value: T): Promise<void> {\n await (\n await exec()\n ).query(\n `INSERT INTO ${table} (key, value) VALUES ($1, $2::jsonb)\n ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,\n [key, canonicalJson(value)],\n );\n },\n\n async removeItem(key: string): Promise<void> {\n await (await exec()).query(`DELETE FROM ${table} WHERE key = $1`, [key]);\n },\n\n async getKeys(prefix: string): Promise<string[]> {\n const { rows } = await (\n await exec()\n ).query(`SELECT key FROM ${table} WHERE key LIKE $1 ESCAPE '!'`, [`${escapeLike(prefix)}%`]);\n // Keep only exact (bytewise) prefix matches whatever the column's collation.\n return rows.map((row) => String(row.key)).filter((key) => key.startsWith(prefix));\n },\n\n async compareAndSwap<T>(input: CompareAndSwapInput<T>): Promise<boolean> {\n const c = await exec();\n const next = canonicalJson(input.next);\n const { rows } =\n input.expected === null\n ? await c.query(\n `INSERT INTO ${table} (key, value) VALUES ($1, $2::jsonb)\n ON CONFLICT (key) DO NOTHING RETURNING key`,\n [input.key, next],\n )\n : await c.query(\n `UPDATE ${table} SET value = $3::jsonb\n WHERE key = $1 AND value = $2::jsonb RETURNING key`,\n [input.key, canonicalJson(input.expected), next],\n );\n return rows.length === 1;\n },\n };\n}\n\n/**\n * Create a Postgres-backed {@link PostgresKvStorage}. Connection and table creation are lazy.\n *\n * @example\n * ```ts\n * import { createPostgresStorage } from \"@xtandard/kit/storage/postgres\";\n *\n * const storage = createPostgresStorage({ connectionString: process.env.DATABASE_URL, table: \"xtandard_kv\" });\n * // or: createPostgresStorage({ client: new PGlite() })\n * ```\n */\nexport function createPostgresStorage(options: PostgresStorageOptions = {}): PostgresKvStorage {\n const table = options.table ?? \"xtandard_kv\";\n const connection = pgConnection(options.client, options.connectionString ?? options.url);\n return {\n ...postgresKvStorage(table, pgReady(connection, [postgresStorageSchema(table)])),\n close: connection.close,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,MAAM,UAAU;;AAyChB,SAAgB,aACd,QACA,kBACA,UAAU,SACI;CACd,MAAM,aAAa,CAAC;CACpB,IAAI,UAAyC;CAC7C,IAAI;CACJ,OAAO;EACL,MAAM,MAAkC;GACtC,IAAI,SAAS,OAAO;GACpB,gBAAgB,YAAY;IAE1B,MAAM,MAAM,MAAMA,aAAAA,WAChB,MACA,eAEE,OAAO,KACX;IAEA,UAAU,KADI,IAAI,QAAQ,IAAI,SAAS,MACpB,EAAE,iBAAiB,CAAC;IACvC,OAAO;GACT,GAAG;GACH,IAAI;IACF,OAAO,MAAM;GACf,UAAU;IACR,aAAa,KAAA;GACf;EACF;EACA,MAAM,QAAuB;GAC3B,IAAI,cAAc,SAAS,KAAK,MAAM,QAAQ,IAAI;EACpD;CACF;AACF;;;;;;AAOA,SAAgB,QAAQ,YAA0B,KAAiD;CACjG,IAAI;CACJ,OAAO,YAAY;EACjB,MAAM,SAAS,MAAM,WAAW,IAAI;EACpC,aAAa,YAAY;GACvB,KAAK,MAAM,aAAa,KAAK,MAAM,OAAO,MAAM,SAAS;EAC3D,GAAG;EACH,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GACd,UAAU,KAAA;GACV,MAAM;EACR;EACA,OAAO;CACT;AACF;;;;;AAMA,SAAgB,sBAAsB,QAAQ,eAAuB;CACnE,aAAA,iBAAiB,KAAK;CACtB,OAAO,8BAA8B,MAAM;AAC7C;;;;;;AAOA,SAAgB,kBACd,OACA,MACyB;CACzB,aAAA,iBAAiB,KAAK;CACtB,OAAO;EACL,MAAM,QAAW,KAAgC;GAG/C,MAAM,EAAE,SAAS,OACf,MAAM,KAAK,GACX,M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AC;EAC/E,OAAO,WAAW;CACpB;AACF"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { n as CompareAndSwapKvStorage } from "./contract-BvgtswLX.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/storage/postgres.d.ts
|
|
4
|
+
/** Minimal structural view of a SQL client: `pg` `Pool`/`Client` and `PGlite` satisfy it. */
|
|
5
|
+
interface SqlClient {
|
|
6
|
+
/** Run one parameterized statement (`$1`, `$2`, …). */
|
|
7
|
+
query(text: string, params?: unknown[]): Promise<{
|
|
8
|
+
rows: Array<Record<string, unknown>>;
|
|
9
|
+
}>;
|
|
10
|
+
}
|
|
11
|
+
/** A client the driver can also shut down (e.g. a `pg` `Pool`). */
|
|
12
|
+
interface ClosableSqlClient extends SqlClient {
|
|
13
|
+
/** End the client. */
|
|
14
|
+
end?(): Promise<unknown>;
|
|
15
|
+
}
|
|
16
|
+
/** Options for {@link createPostgresStorage}. */
|
|
17
|
+
interface PostgresStorageOptions {
|
|
18
|
+
/** A pre-built client (`pg` `Pool`/`Client`, `PGlite`, …). Never closed by the driver. */
|
|
19
|
+
client?: SqlClient;
|
|
20
|
+
/** Connection string used to create a `pg` `Pool` lazily when no `client` is given. */
|
|
21
|
+
connectionString?: string;
|
|
22
|
+
/** Alias for {@link PostgresStorageOptions.connectionString}. */
|
|
23
|
+
url?: string;
|
|
24
|
+
/** Table name (default `"xtandard_kv"`; products pass theirs). Must be a safe SQL identifier. */
|
|
25
|
+
table?: string;
|
|
26
|
+
}
|
|
27
|
+
/** A compare-and-swap capable storage backed by Postgres, plus `close()`. */
|
|
28
|
+
interface PostgresKvStorage extends CompareAndSwapKvStorage {
|
|
29
|
+
/** End the pool if this driver created it; no-op for a borrowed client. */
|
|
30
|
+
close(): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/** A lazily created `pg` client (semi-public, ADR 0004). */
|
|
33
|
+
interface PgConnection {
|
|
34
|
+
/** Resolve the client, creating a `pg` `Pool` on first use when needed (retried after a failure). */
|
|
35
|
+
get(): Promise<ClosableSqlClient>;
|
|
36
|
+
/** End the pool if this connection created it. */
|
|
37
|
+
close(): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** Build a {@link PgConnection} from a borrowed `client` or a `connectionString`. */
|
|
40
|
+
declare function pgConnection(client: SqlClient | undefined, connectionString: string | undefined, subpath?: string): PgConnection;
|
|
41
|
+
/**
|
|
42
|
+
* Memoize "get the client and run these statements once" (semi-public, ADR 0004). The returned
|
|
43
|
+
* function resolves the client after the DDL has run; a failed DDL is retried on the next call.
|
|
44
|
+
* Products pass extra statements for their own tables (au's event log).
|
|
45
|
+
*/
|
|
46
|
+
declare function pgReady(connection: PgConnection, ddl: string[]): () => Promise<ClosableSqlClient>;
|
|
47
|
+
/**
|
|
48
|
+
* The DDL {@link createPostgresStorage} runs on first use, for migrations when the runtime role may
|
|
49
|
+
* not create tables. Products pass their table name.
|
|
50
|
+
*/
|
|
51
|
+
declare function postgresStorageSchema(table?: string): string;
|
|
52
|
+
/**
|
|
53
|
+
* The KV operations over a table that already exists (semi-public, ADR 0004): `exec` resolves a
|
|
54
|
+
* ready client before every operation. {@link createPostgresStorage} is this plus
|
|
55
|
+
* {@link pgConnection} and {@link pgReady}.
|
|
56
|
+
*/
|
|
57
|
+
declare function postgresKvStorage(table: string, exec: () => Promise<SqlClient>): CompareAndSwapKvStorage;
|
|
58
|
+
/**
|
|
59
|
+
* Create a Postgres-backed {@link PostgresKvStorage}. Connection and table creation are lazy.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* import { createPostgresStorage } from "@xtandard/kit/storage/postgres";
|
|
64
|
+
*
|
|
65
|
+
* const storage = createPostgresStorage({ connectionString: process.env.DATABASE_URL, table: "xtandard_kv" });
|
|
66
|
+
* // or: createPostgresStorage({ client: new PGlite() })
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
declare function createPostgresStorage(options?: PostgresStorageOptions): PostgresKvStorage;
|
|
70
|
+
//#endregion
|
|
71
|
+
export { SqlClient as a, pgReady as c, PostgresStorageOptions as i, postgresKvStorage as l, PgConnection as n, createPostgresStorage as o, PostgresKvStorage as r, pgConnection as s, ClosableSqlClient as t, postgresStorageSchema as u };
|
|
72
|
+
//# sourceMappingURL=postgres-RfQMgAsj.d.mts.map
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { t as importPeer } from "./peer-CTHMzOdn.mjs";
|
|
2
|
+
import { i as escapeLike, n as assertIdentifier } from "./util-Dnj5T-yw.mjs";
|
|
3
|
+
import { n as canonicalJson } from "./json-CmM1M5Kz.mjs";
|
|
4
|
+
//#region src/storage/postgres.ts
|
|
5
|
+
/**
|
|
6
|
+
* Postgres storage driver: one key/value table (`key text COLLATE "C" PRIMARY KEY, value jsonb`)
|
|
7
|
+
* over any client exposing `query(text, params?) → { rows }`: [`pg`](https://node-postgres.com)
|
|
8
|
+
* (`Pool`/`Client`) and the in-process [`@electric-sql/pglite`](https://pglite.dev) alike. Pass a
|
|
9
|
+
* `client`, or a `connectionString`/`url` to create a `pg` `Pool` lazily on first use.
|
|
10
|
+
*
|
|
11
|
+
* - The table is created on first use (`CREATE TABLE IF NOT EXISTS`, once); a failed DDL is
|
|
12
|
+
* retried on the next call, not cached.
|
|
13
|
+
* - The `"C"` collation (new tables only) makes ordering and `LIKE` prefixes bytewise. Existing
|
|
14
|
+
* tables keep working: prefixes are matched with `LIKE … ESCAPE '!'` plus an exact `startsWith`.
|
|
15
|
+
* - `compareAndSwap` is one statement (`UPDATE … WHERE value = $::jsonb`, or `INSERT … ON CONFLICT
|
|
16
|
+
* DO NOTHING` for an absent key). `jsonb` equality is structural, so rows written before
|
|
17
|
+
* canonicalisation swap too.
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
const SUBPATH = "@xtandard/kit/storage/postgres";
|
|
22
|
+
/** Build a {@link PgConnection} from a borrowed `client` or a `connectionString`. */
|
|
23
|
+
function pgConnection(client, connectionString, subpath = SUBPATH) {
|
|
24
|
+
const ownsClient = !client;
|
|
25
|
+
let current = client;
|
|
26
|
+
let connecting;
|
|
27
|
+
return {
|
|
28
|
+
async get() {
|
|
29
|
+
if (current) return current;
|
|
30
|
+
connecting ??= (async () => {
|
|
31
|
+
const mod = await importPeer("pg", subpath, () => import("pg"));
|
|
32
|
+
current = new (mod.Pool ?? mod.default?.Pool)({ connectionString });
|
|
33
|
+
return current;
|
|
34
|
+
})();
|
|
35
|
+
try {
|
|
36
|
+
return await connecting;
|
|
37
|
+
} finally {
|
|
38
|
+
connecting = void 0;
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
async close() {
|
|
42
|
+
if (ownsClient && current?.end) await current.end();
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Memoize "get the client and run these statements once" (semi-public, ADR 0004). The returned
|
|
48
|
+
* function resolves the client after the DDL has run; a failed DDL is retried on the next call.
|
|
49
|
+
* Products pass extra statements for their own tables (au's event log).
|
|
50
|
+
*/
|
|
51
|
+
function pgReady(connection, ddl) {
|
|
52
|
+
let ensured;
|
|
53
|
+
return async () => {
|
|
54
|
+
const client = await connection.get();
|
|
55
|
+
ensured ??= (async () => {
|
|
56
|
+
for (const statement of ddl) await client.query(statement);
|
|
57
|
+
})();
|
|
58
|
+
try {
|
|
59
|
+
await ensured;
|
|
60
|
+
} catch (error) {
|
|
61
|
+
ensured = void 0;
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
return client;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The DDL {@link createPostgresStorage} runs on first use, for migrations when the runtime role may
|
|
69
|
+
* not create tables. Products pass their table name.
|
|
70
|
+
*/
|
|
71
|
+
function postgresStorageSchema(table = "xtandard_kv") {
|
|
72
|
+
assertIdentifier(table);
|
|
73
|
+
return `CREATE TABLE IF NOT EXISTS ${table} (key text COLLATE "C" PRIMARY KEY, value jsonb NOT NULL)`;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The KV operations over a table that already exists (semi-public, ADR 0004): `exec` resolves a
|
|
77
|
+
* ready client before every operation. {@link createPostgresStorage} is this plus
|
|
78
|
+
* {@link pgConnection} and {@link pgReady}.
|
|
79
|
+
*/
|
|
80
|
+
function postgresKvStorage(table, exec) {
|
|
81
|
+
assertIdentifier(table);
|
|
82
|
+
return {
|
|
83
|
+
async getItem(key) {
|
|
84
|
+
const { rows } = await (await exec()).query(`SELECT value::text AS value FROM ${table} WHERE key = $1`, [key]);
|
|
85
|
+
const value = rows[0]?.value;
|
|
86
|
+
return typeof value === "string" ? JSON.parse(value) : null;
|
|
87
|
+
},
|
|
88
|
+
async setItem(key, value) {
|
|
89
|
+
await (await exec()).query(`INSERT INTO ${table} (key, value) VALUES ($1, $2::jsonb)
|
|
90
|
+
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`, [key, canonicalJson(value)]);
|
|
91
|
+
},
|
|
92
|
+
async removeItem(key) {
|
|
93
|
+
await (await exec()).query(`DELETE FROM ${table} WHERE key = $1`, [key]);
|
|
94
|
+
},
|
|
95
|
+
async getKeys(prefix) {
|
|
96
|
+
const { rows } = await (await exec()).query(`SELECT key FROM ${table} WHERE key LIKE $1 ESCAPE '!'`, [`${escapeLike(prefix)}%`]);
|
|
97
|
+
return rows.map((row) => String(row.key)).filter((key) => key.startsWith(prefix));
|
|
98
|
+
},
|
|
99
|
+
async compareAndSwap(input) {
|
|
100
|
+
const c = await exec();
|
|
101
|
+
const next = canonicalJson(input.next);
|
|
102
|
+
const { rows } = input.expected === null ? await c.query(`INSERT INTO ${table} (key, value) VALUES ($1, $2::jsonb)
|
|
103
|
+
ON CONFLICT (key) DO NOTHING RETURNING key`, [input.key, next]) : await c.query(`UPDATE ${table} SET value = $3::jsonb
|
|
104
|
+
WHERE key = $1 AND value = $2::jsonb RETURNING key`, [
|
|
105
|
+
input.key,
|
|
106
|
+
canonicalJson(input.expected),
|
|
107
|
+
next
|
|
108
|
+
]);
|
|
109
|
+
return rows.length === 1;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Create a Postgres-backed {@link PostgresKvStorage}. Connection and table creation are lazy.
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* ```ts
|
|
118
|
+
* import { createPostgresStorage } from "@xtandard/kit/storage/postgres";
|
|
119
|
+
*
|
|
120
|
+
* const storage = createPostgresStorage({ connectionString: process.env.DATABASE_URL, table: "xtandard_kv" });
|
|
121
|
+
* // or: createPostgresStorage({ client: new PGlite() })
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
function createPostgresStorage(options = {}) {
|
|
125
|
+
const table = options.table ?? "xtandard_kv";
|
|
126
|
+
const connection = pgConnection(options.client, options.connectionString ?? options.url);
|
|
127
|
+
return {
|
|
128
|
+
...postgresKvStorage(table, pgReady(connection, [postgresStorageSchema(table)])),
|
|
129
|
+
close: connection.close
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
export { postgresStorageSchema as a, postgresKvStorage as i, pgConnection as n, pgReady as r, createPostgresStorage as t };
|
|
134
|
+
|
|
135
|
+
//# sourceMappingURL=postgres-aDiBmNzr.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-aDiBmNzr.mjs","names":[],"sources":["../src/storage/postgres.ts"],"sourcesContent":["/**\n * Postgres storage driver: one key/value table (`key text COLLATE \"C\" PRIMARY KEY, value jsonb`)\n * over any client exposing `query(text, params?) → { rows }`: [`pg`](https://node-postgres.com)\n * (`Pool`/`Client`) and the in-process [`@electric-sql/pglite`](https://pglite.dev) alike. Pass a\n * `client`, or a `connectionString`/`url` to create a `pg` `Pool` lazily on first use.\n *\n * - The table is created on first use (`CREATE TABLE IF NOT EXISTS`, once); a failed DDL is\n * retried on the next call, not cached.\n * - The `\"C\"` collation (new tables only) makes ordering and `LIKE` prefixes bytewise. Existing\n * tables keep working: prefixes are matched with `LIKE … ESCAPE '!'` plus an exact `startsWith`.\n * - `compareAndSwap` is one statement (`UPDATE … WHERE value = $::jsonb`, or `INSERT … ON CONFLICT\n * DO NOTHING` for an absent key). `jsonb` equality is structural, so rows written before\n * canonicalisation swap too.\n *\n * @module\n */\n\nimport { canonicalJson } from \"../internal/json.ts\";\nimport { importPeer } from \"../internal/peer.ts\";\nimport type { CompareAndSwapInput, CompareAndSwapKvStorage } from \"./contract.ts\";\nimport { assertIdentifier, escapeLike } from \"./util.ts\";\n\nconst SUBPATH = \"@xtandard/kit/storage/postgres\";\n\n/** Minimal structural view of a SQL client: `pg` `Pool`/`Client` and `PGlite` satisfy it. */\nexport interface SqlClient {\n /** Run one parameterized statement (`$1`, `$2`, …). */\n query(text: string, params?: unknown[]): Promise<{ rows: Array<Record<string, unknown>> }>;\n}\n\n/** A client the driver can also shut down (e.g. a `pg` `Pool`). */\nexport interface ClosableSqlClient extends SqlClient {\n /** End the client. */\n end?(): Promise<unknown>;\n}\n\n/** Options for {@link createPostgresStorage}. */\nexport interface PostgresStorageOptions {\n /** A pre-built client (`pg` `Pool`/`Client`, `PGlite`, …). Never closed by the driver. */\n client?: SqlClient;\n /** Connection string used to create a `pg` `Pool` lazily when no `client` is given. */\n connectionString?: string;\n /** Alias for {@link PostgresStorageOptions.connectionString}. */\n url?: string;\n /** Table name (default `\"xtandard_kv\"`; products pass theirs). Must be a safe SQL identifier. */\n table?: string;\n}\n\n/** A compare-and-swap capable storage backed by Postgres, plus `close()`. */\nexport interface PostgresKvStorage extends CompareAndSwapKvStorage {\n /** End the pool if this driver created it; no-op for a borrowed client. */\n close(): Promise<void>;\n}\n\n/** A lazily created `pg` client (semi-public, ADR 0004). */\nexport interface PgConnection {\n /** Resolve the client, creating a `pg` `Pool` on first use when needed (retried after a failure). */\n get(): Promise<ClosableSqlClient>;\n /** End the pool if this connection created it. */\n close(): Promise<void>;\n}\n\n/** Build a {@link PgConnection} from a borrowed `client` or a `connectionString`. */\nexport function pgConnection(\n client: SqlClient | undefined,\n connectionString: string | undefined,\n subpath = SUBPATH,\n): PgConnection {\n const ownsClient = !client;\n let current: ClosableSqlClient | undefined = client;\n let connecting: Promise<ClosableSqlClient> | undefined;\n return {\n async get(): Promise<ClosableSqlClient> {\n if (current) return current;\n connecting ??= (async () => {\n type PoolCtor = new (config: { connectionString?: string }) => ClosableSqlClient;\n const mod = await importPeer(\n \"pg\",\n subpath,\n () =>\n import(\"pg\") as unknown as Promise<{ Pool?: PoolCtor; default?: { Pool: PoolCtor } }>,\n );\n const Pool = (mod.Pool ?? mod.default?.Pool) as PoolCtor;\n current = new Pool({ connectionString });\n return current;\n })();\n try {\n return await connecting;\n } finally {\n connecting = undefined;\n }\n },\n async close(): Promise<void> {\n if (ownsClient && current?.end) await current.end();\n },\n };\n}\n\n/**\n * Memoize \"get the client and run these statements once\" (semi-public, ADR 0004). The returned\n * function resolves the client after the DDL has run; a failed DDL is retried on the next call.\n * Products pass extra statements for their own tables (au's event log).\n */\nexport function pgReady(connection: PgConnection, ddl: string[]): () => Promise<ClosableSqlClient> {\n let ensured: Promise<void> | undefined;\n return async () => {\n const client = await connection.get();\n ensured ??= (async () => {\n for (const statement of ddl) await client.query(statement);\n })();\n try {\n await ensured;\n } catch (error) {\n ensured = undefined; // let a later call retry the DDL\n throw error;\n }\n return client;\n };\n}\n\n/**\n * The DDL {@link createPostgresStorage} runs on first use, for migrations when the runtime role may\n * not create tables. Products pass their table name.\n */\nexport function postgresStorageSchema(table = \"xtandard_kv\"): string {\n assertIdentifier(table);\n return `CREATE TABLE IF NOT EXISTS ${table} (key text COLLATE \"C\" PRIMARY KEY, value jsonb NOT NULL)`;\n}\n\n/**\n * The KV operations over a table that already exists (semi-public, ADR 0004): `exec` resolves a\n * ready client before every operation. {@link createPostgresStorage} is this plus\n * {@link pgConnection} and {@link pgReady}.\n */\nexport function postgresKvStorage(\n table: string,\n exec: () => Promise<SqlClient>,\n): CompareAndSwapKvStorage {\n assertIdentifier(table);\n return {\n async getItem<T>(key: string): Promise<T | null> {\n // `value::text`, parsed once: a driver that already parsed `jsonb` would otherwise hand back\n // the string \"123\" for a stored JSON string, and a second parse would turn it into 123.\n const { rows } = await (\n await exec()\n ).query(`SELECT value::text AS value FROM ${table} WHERE key = $1`, [key]);\n const value = rows[0]?.value;\n return typeof value === \"string\" ? (JSON.parse(value) as T) : null;\n },\n\n async setItem<T>(key: string, value: T): Promise<void> {\n await (\n await exec()\n ).query(\n `INSERT INTO ${table} (key, value) VALUES ($1, $2::jsonb)\n ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,\n [key, canonicalJson(value)],\n );\n },\n\n async removeItem(key: string): Promise<void> {\n await (await exec()).query(`DELETE FROM ${table} WHERE key = $1`, [key]);\n },\n\n async getKeys(prefix: string): Promise<string[]> {\n const { rows } = await (\n await exec()\n ).query(`SELECT key FROM ${table} WHERE key LIKE $1 ESCAPE '!'`, [`${escapeLike(prefix)}%`]);\n // Keep only exact (bytewise) prefix matches whatever the column's collation.\n return rows.map((row) => String(row.key)).filter((key) => key.startsWith(prefix));\n },\n\n async compareAndSwap<T>(input: CompareAndSwapInput<T>): Promise<boolean> {\n const c = await exec();\n const next = canonicalJson(input.next);\n const { rows } =\n input.expected === null\n ? await c.query(\n `INSERT INTO ${table} (key, value) VALUES ($1, $2::jsonb)\n ON CONFLICT (key) DO NOTHING RETURNING key`,\n [input.key, next],\n )\n : await c.query(\n `UPDATE ${table} SET value = $3::jsonb\n WHERE key = $1 AND value = $2::jsonb RETURNING key`,\n [input.key, canonicalJson(input.expected), next],\n );\n return rows.length === 1;\n },\n };\n}\n\n/**\n * Create a Postgres-backed {@link PostgresKvStorage}. Connection and table creation are lazy.\n *\n * @example\n * ```ts\n * import { createPostgresStorage } from \"@xtandard/kit/storage/postgres\";\n *\n * const storage = createPostgresStorage({ connectionString: process.env.DATABASE_URL, table: \"xtandard_kv\" });\n * // or: createPostgresStorage({ client: new PGlite() })\n * ```\n */\nexport function createPostgresStorage(options: PostgresStorageOptions = {}): PostgresKvStorage {\n const table = options.table ?? \"xtandard_kv\";\n const connection = pgConnection(options.client, options.connectionString ?? options.url);\n return {\n ...postgresKvStorage(table, pgReady(connection, [postgresStorageSchema(table)])),\n close: connection.close,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,MAAM,UAAU;;AAyChB,SAAgB,aACd,QACA,kBACA,UAAU,SACI;CACd,MAAM,aAAa,CAAC;CACpB,IAAI,UAAyC;CAC7C,IAAI;CACJ,OAAO;EACL,MAAM,MAAkC;GACtC,IAAI,SAAS,OAAO;GACpB,gBAAgB,YAAY;IAE1B,MAAM,MAAM,MAAM,WAChB,MACA,eAEE,OAAO,KACX;IAEA,UAAU,KADI,IAAI,QAAQ,IAAI,SAAS,MACpB,EAAE,iBAAiB,CAAC;IACvC,OAAO;GACT,GAAG;GACH,IAAI;IACF,OAAO,MAAM;GACf,UAAU;IACR,aAAa,KAAA;GACf;EACF;EACA,MAAM,QAAuB;GAC3B,IAAI,cAAc,SAAS,KAAK,MAAM,QAAQ,IAAI;EACpD;CACF;AACF;;;;;;AAOA,SAAgB,QAAQ,YAA0B,KAAiD;CACjG,IAAI;CACJ,OAAO,YAAY;EACjB,MAAM,SAAS,MAAM,WAAW,IAAI;EACpC,aAAa,YAAY;GACvB,KAAK,MAAM,aAAa,KAAK,MAAM,OAAO,MAAM,SAAS;EAC3D,GAAG;EACH,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GACd,UAAU,KAAA;GACV,MAAM;EACR;EACA,OAAO;CACT;AACF;;;;;AAMA,SAAgB,sBAAsB,QAAQ,eAAuB;CACnE,iBAAiB,KAAK;CACtB,OAAO,8BAA8B,MAAM;AAC7C;;;;;;AAOA,SAAgB,kBACd,OACA,MACyB;CACzB,iBAAiB,KAAK;CACtB,OAAO;EACL,MAAM,QAAW,KAAgC;GAG/C,MAAM,EAAE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