gemi 0.109.0 → 0.111.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/dist/ai/Agent.d.ts +11 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +7 -0
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/index.js +11 -11
- package/dist/ai/index.js.map +4 -4
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/bin/gemi.js +485 -63
- package/dist/bin/gemi.js.map +12 -8
- package/dist/bun/plugin.js +2 -2
- package/dist/bun/plugin.js.map +1 -1
- package/dist/bun/preload.js +2 -2
- package/dist/bun/preload.js.map +1 -1
- package/dist/{chunk-hgz8sx40.js → chunk-09ypnhjv.js} +3 -3
- package/dist/{chunk-hgz8sx40.js.map → chunk-09ypnhjv.js.map} +1 -1
- package/dist/{chunk-qnq110tw.js → chunk-0d9qsmx2.js} +3 -3
- package/dist/{chunk-qnq110tw.js.map → chunk-0d9qsmx2.js.map} +1 -1
- package/dist/{chunk-m9609t1y.js → chunk-0sjh5v1n.js} +1 -1
- package/dist/{chunk-g5a3ptsa.js → chunk-11fsn5mr.js} +3 -3
- package/dist/{chunk-g5a3ptsa.js.map → chunk-11fsn5mr.js.map} +1 -1
- package/dist/chunk-1bkr5wnt.js +58 -0
- package/dist/chunk-1bkr5wnt.js.map +14 -0
- package/dist/{chunk-whe0x70j.js → chunk-1c1d0e60.js} +3 -3
- package/dist/{chunk-whe0x70j.js.map → chunk-1c1d0e60.js.map} +1 -1
- package/dist/{chunk-rgfzqwpg.js → chunk-1kr25rcg.js} +3 -3
- package/dist/{chunk-rgfzqwpg.js.map → chunk-1kr25rcg.js.map} +1 -1
- package/dist/{chunk-vee4j6ft.js → chunk-1pem26zc.js} +3 -3
- package/dist/{chunk-vee4j6ft.js.map → chunk-1pem26zc.js.map} +1 -1
- package/dist/{chunk-nxxx0m1a.js → chunk-1va15sfq.js} +2 -2
- package/dist/{chunk-nxxx0m1a.js.map → chunk-1va15sfq.js.map} +2 -2
- package/dist/{chunk-wvwee7dn.js → chunk-1yx2e0bh.js} +2 -2
- package/dist/{chunk-wvwee7dn.js.map → chunk-1yx2e0bh.js.map} +1 -1
- package/dist/{chunk-9r3znmqq.js → chunk-303mprnv.js} +2 -2
- package/dist/{chunk-9r3znmqq.js.map → chunk-303mprnv.js.map} +1 -1
- package/dist/{chunk-grs8dnkd.js → chunk-30xjcyzh.js} +2 -2
- package/dist/{chunk-grs8dnkd.js.map → chunk-30xjcyzh.js.map} +1 -1
- package/dist/{chunk-h15eae7g.js → chunk-358sdcx9.js} +3 -3
- package/dist/{chunk-h15eae7g.js.map → chunk-358sdcx9.js.map} +1 -1
- package/dist/{chunk-367kyrdx.js → chunk-3cg7y62b.js} +2 -2
- package/dist/{chunk-367kyrdx.js.map → chunk-3cg7y62b.js.map} +1 -1
- package/dist/{chunk-t26n9vzw.js → chunk-3y8q8x11.js} +2 -2
- package/dist/{chunk-t26n9vzw.js.map → chunk-3y8q8x11.js.map} +1 -1
- package/dist/chunk-4mfrgd5m.js +34 -0
- package/dist/chunk-4mfrgd5m.js.map +10 -0
- package/dist/chunk-5cygrbxv.js +4 -0
- package/dist/{chunk-9qw9fa6z.js.map → chunk-5cygrbxv.js.map} +2 -2
- package/dist/{chunk-tvy2fqza.js → chunk-5stgtwqw.js} +2 -2
- package/dist/{chunk-tvy2fqza.js.map → chunk-5stgtwqw.js.map} +1 -1
- package/dist/chunk-6chz1ktz.js +9 -0
- package/dist/chunk-6chz1ktz.js.map +13 -0
- package/dist/{chunk-wqsdjweb.js → chunk-6vr7f5fq.js} +4 -4
- package/dist/{chunk-wqsdjweb.js.map → chunk-6vr7f5fq.js.map} +1 -1
- package/dist/{chunk-g74qwhvf.js → chunk-7tx5y712.js} +2 -2
- package/dist/{chunk-g74qwhvf.js.map → chunk-7tx5y712.js.map} +1 -1
- package/dist/{chunk-g7fr2cy2.js → chunk-8afxrmdc.js} +3 -3
- package/dist/{chunk-g7fr2cy2.js.map → chunk-8afxrmdc.js.map} +1 -1
- package/dist/{chunk-vwkdfngg.js → chunk-8b2tw2yp.js} +1 -1
- package/dist/{chunk-t3qw9syt.js → chunk-9rchedr4.js} +2 -2
- package/dist/{chunk-t3qw9syt.js.map → chunk-9rchedr4.js.map} +1 -1
- package/dist/{chunk-jm4jn28j.js → chunk-9s851qz8.js} +2 -2
- package/dist/{chunk-jm4jn28j.js.map → chunk-9s851qz8.js.map} +1 -1
- package/dist/{chunk-jc4j61xb.js → chunk-a6453d9s.js} +3 -3
- package/dist/{chunk-jc4j61xb.js.map → chunk-a6453d9s.js.map} +1 -1
- package/dist/{chunk-9m18pknp.js → chunk-bn5yn731.js} +2 -2
- package/dist/{chunk-9m18pknp.js.map → chunk-bn5yn731.js.map} +1 -1
- package/dist/{chunk-t85rca2p.js → chunk-c098fzvk.js} +2 -2
- package/dist/{chunk-t85rca2p.js.map → chunk-c098fzvk.js.map} +1 -1
- package/dist/{chunk-mp5krm14.js → chunk-cttmy1jp.js} +4 -4
- package/dist/{chunk-mp5krm14.js.map → chunk-cttmy1jp.js.map} +2 -2
- package/dist/{chunk-eyg88bgv.js → chunk-cy5qp6mz.js} +3 -3
- package/dist/{chunk-eyg88bgv.js.map → chunk-cy5qp6mz.js.map} +1 -1
- package/dist/{chunk-zys7kecf.js → chunk-ddr4qvvt.js} +3 -3
- package/dist/{chunk-zys7kecf.js.map → chunk-ddr4qvvt.js.map} +1 -1
- package/dist/{chunk-r9gzbjc5.js → chunk-et4pv1b1.js} +1 -1
- package/dist/{chunk-a1g0bahx.js → chunk-frerzsxq.js} +2 -2
- package/dist/{chunk-a1g0bahx.js.map → chunk-frerzsxq.js.map} +1 -1
- package/dist/{chunk-qz9aaw5x.js → chunk-gb37722w.js} +3 -3
- package/dist/{chunk-qz9aaw5x.js.map → chunk-gb37722w.js.map} +1 -1
- package/dist/chunk-h3864a8z.js +17 -0
- package/dist/{chunk-s5aa4hty.js.map → chunk-h3864a8z.js.map} +13 -12
- package/dist/{chunk-zhm3qvrc.js → chunk-h4sw6nt3.js} +3 -3
- package/dist/{chunk-zhm3qvrc.js.map → chunk-h4sw6nt3.js.map} +1 -1
- package/dist/{chunk-5d6eaxab.js → chunk-he7z7y9j.js} +2 -2
- package/dist/{chunk-5d6eaxab.js.map → chunk-he7z7y9j.js.map} +1 -1
- package/dist/{chunk-d2tngs73.js → chunk-hf7a51s3.js} +2 -2
- package/dist/{chunk-d2tngs73.js.map → chunk-hf7a51s3.js.map} +1 -1
- package/dist/chunk-hn67spz6.js +5 -0
- package/dist/{chunk-z9x8x3wq.js.map → chunk-hn67spz6.js.map} +1 -1
- package/dist/{chunk-f7jhkg8x.js → chunk-jbrwt3cs.js} +4 -4
- package/dist/{chunk-f7jhkg8x.js.map → chunk-jbrwt3cs.js.map} +1 -1
- package/dist/{chunk-k1ezptt8.js → chunk-k1vw22t2.js} +2 -2
- package/dist/{chunk-k1ezptt8.js.map → chunk-k1vw22t2.js.map} +1 -1
- package/dist/chunk-k1xt2tw7.js +4 -0
- package/dist/{chunk-rjcsdazt.js.map → chunk-k1xt2tw7.js.map} +2 -2
- package/dist/{chunk-7mc5e61r.js → chunk-kf71mjxa.js} +3 -3
- package/dist/{chunk-7mc5e61r.js.map → chunk-kf71mjxa.js.map} +1 -1
- package/dist/{chunk-vna85rdq.js → chunk-m6ystvtk.js} +2 -2
- package/dist/{chunk-vna85rdq.js.map → chunk-m6ystvtk.js.map} +1 -1
- package/dist/{chunk-qyyxzy04.js → chunk-mb7q7s0a.js} +3 -3
- package/dist/{chunk-qyyxzy04.js.map → chunk-mb7q7s0a.js.map} +1 -1
- package/dist/{chunk-sp2v357a.js → chunk-mn5xw79b.js} +3 -3
- package/dist/{chunk-sp2v357a.js.map → chunk-mn5xw79b.js.map} +1 -1
- package/dist/{chunk-q8k7f11z.js → chunk-mwqg079k.js} +2 -2
- package/dist/{chunk-q8k7f11z.js.map → chunk-mwqg079k.js.map} +1 -1
- package/dist/{chunk-ga533cpz.js → chunk-nncz308h.js} +3 -3
- package/dist/{chunk-ga533cpz.js.map → chunk-nncz308h.js.map} +1 -1
- package/dist/{chunk-hf32yq23.js → chunk-nsvktvp4.js} +2 -2
- package/dist/{chunk-hf32yq23.js.map → chunk-nsvktvp4.js.map} +1 -1
- package/dist/{chunk-3x86bhfn.js → chunk-nvv9wej6.js} +3 -3
- package/dist/{chunk-3x86bhfn.js.map → chunk-nvv9wej6.js.map} +1 -1
- package/dist/chunk-p1aqq0ga.js +16 -0
- package/dist/{chunk-d5sbnzng.js.map → chunk-p1aqq0ga.js.map} +5 -9
- package/dist/chunk-p7r2w4qw.js +5 -0
- package/dist/{chunk-ehasw3qm.js.map → chunk-p7r2w4qw.js.map} +2 -2
- package/dist/{chunk-zz7h6tdr.js → chunk-pwmgqq7z.js} +2 -2
- package/dist/{chunk-zz7h6tdr.js.map → chunk-pwmgqq7z.js.map} +1 -1
- package/dist/chunk-pyj7cd9t.js +4 -0
- package/dist/{chunk-gdsby5jh.js.map → chunk-pyj7cd9t.js.map} +2 -2
- package/dist/{chunk-h6g9g8qc.js → chunk-q9s7kwgt.js} +3 -3
- package/dist/{chunk-h6g9g8qc.js.map → chunk-q9s7kwgt.js.map} +1 -1
- package/dist/{chunk-9hbwvcxn.js → chunk-qd2v93y4.js} +2 -2
- package/dist/{chunk-9hbwvcxn.js.map → chunk-qd2v93y4.js.map} +1 -1
- package/dist/{chunk-tr9mxdth.js → chunk-rfcygmf5.js} +3 -3
- package/dist/{chunk-tr9mxdth.js.map → chunk-rfcygmf5.js.map} +1 -1
- package/dist/{chunk-vsnmdtrs.js → chunk-s6jjy4y9.js} +2 -2
- package/dist/{chunk-vsnmdtrs.js.map → chunk-s6jjy4y9.js.map} +1 -1
- package/dist/{chunk-6zekebzt.js → chunk-sq2wkynk.js} +2 -2
- package/dist/{chunk-6zekebzt.js.map → chunk-sq2wkynk.js.map} +1 -1
- package/dist/{chunk-52vsdnny.js → chunk-td8tha3j.js} +3 -3
- package/dist/{chunk-52vsdnny.js.map → chunk-td8tha3j.js.map} +1 -1
- package/dist/chunk-tdsfke9q.js +6 -0
- package/dist/{chunk-fe1pcnw6.js.map → chunk-tdsfke9q.js.map} +5 -4
- package/dist/{chunk-t0bp8nrc.js → chunk-tk5q8hkv.js} +4 -4
- package/dist/{chunk-t0bp8nrc.js.map → chunk-tk5q8hkv.js.map} +2 -2
- package/dist/{chunk-dpy08xw4.js → chunk-tq85n8zh.js} +2 -2
- package/dist/{chunk-dpy08xw4.js.map → chunk-tq85n8zh.js.map} +1 -1
- package/dist/{chunk-wdpdqjr1.js → chunk-twnn7r66.js} +2 -2
- package/dist/{chunk-wdpdqjr1.js.map → chunk-twnn7r66.js.map} +1 -1
- package/dist/chunk-w7jsh3xd.js +5 -0
- package/dist/{chunk-1es50p4k.js.map → chunk-w7jsh3xd.js.map} +2 -2
- package/dist/chunk-wqvvjd5r.js +24 -0
- package/dist/{chunk-w3j53r0a.js.map → chunk-wqvvjd5r.js.map} +4 -4
- package/dist/{chunk-zh1t33nq.js → chunk-wsttx9rg.js} +2 -2
- package/dist/{chunk-zh1t33nq.js.map → chunk-wsttx9rg.js.map} +1 -1
- package/dist/{chunk-7ssjzp87.js → chunk-wvsv1jgg.js} +2 -2
- package/dist/{chunk-7ssjzp87.js.map → chunk-wvsv1jgg.js.map} +1 -1
- package/dist/chunk-x78jrs4y.js +4 -0
- package/dist/{chunk-y66ntxbg.js.map → chunk-x78jrs4y.js.map} +2 -2
- package/dist/chunk-xk930yaw.js +5 -0
- package/dist/{chunk-pa3khk46.js.map → chunk-xk930yaw.js.map} +2 -2
- package/dist/chunk-xkc7ftnq.js +9 -0
- package/dist/chunk-xkc7ftnq.js.map +10 -0
- package/dist/{chunk-564zfdd1.js → chunk-yer1r3t3.js} +2 -2
- package/dist/{chunk-564zfdd1.js.map → chunk-yer1r3t3.js.map} +1 -1
- package/dist/{chunk-c8dhvdrs.js → chunk-yqavgpwd.js} +3 -3
- package/dist/{chunk-c8dhvdrs.js.map → chunk-yqavgpwd.js.map} +1 -1
- package/dist/{chunk-hyfzw1fk.js → chunk-z10cas5r.js} +2 -2
- package/dist/{chunk-hyfzw1fk.js.map → chunk-z10cas5r.js.map} +1 -1
- package/dist/{chunk-jgtean4t.js → chunk-zhs1r1z0.js} +3 -3
- package/dist/{chunk-jgtean4t.js.map → chunk-zhs1r1z0.js.map} +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +106 -52
- package/dist/client/index.js.map +1 -1
- package/dist/client/islands.d.ts +99 -56
- package/dist/client/islands.d.ts.map +1 -1
- package/dist/config/index.d.ts +8 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/config/index.js.map +2 -2
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/Lang.d.ts +7 -1
- package/dist/facades/Lang.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/CorsMiddleware.d.ts +13 -0
- package/dist/http/CorsMiddleware.d.ts.map +1 -1
- package/dist/http/Middleware.d.ts +11 -0
- package/dist/http/Middleware.d.ts.map +1 -1
- package/dist/http/ViewRouter.d.ts +29 -0
- package/dist/http/ViewRouter.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/internal/islandRuntime.d.ts +45 -0
- package/dist/internal/islandRuntime.d.ts.map +1 -0
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/context.d.ts +24 -0
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/index.d.ts +1 -1
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +2 -2
- package/dist/server/devFetch.d.ts.map +1 -1
- package/dist/server/httpDev.d.ts.map +1 -1
- package/dist/server/httpProd.d.ts.map +1 -1
- package/dist/server/idleTimeout.d.ts +24 -0
- package/dist/server/idleTimeout.d.ts.map +1 -0
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/modulePreloads.d.ts +7 -6
- package/dist/server/modulePreloads.d.ts.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/middleware/MiddlewareRegistry.d.ts +13 -2
- package/dist/services/middleware/MiddlewareRegistry.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/DomainRouter.d.ts +10 -0
- package/dist/services/router/DomainRouter.d.ts.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +3 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/staticCache.d.ts +23 -0
- package/dist/services/router/staticCache.d.ts.map +1 -0
- package/dist/services/router/staticDocument.d.ts +39 -17
- package/dist/services/router/staticDocument.d.ts.map +1 -1
- package/dist/stats/bundleStats.d.ts +104 -0
- package/dist/stats/bundleStats.d.ts.map +1 -0
- package/dist/stats/route-table.d.ts +2 -0
- package/dist/stats/route-table.d.ts.map +1 -0
- package/dist/stats/route-table.js +4 -0
- package/dist/stats/route-table.js.map +11 -0
- package/dist/stats/routeTable.d.ts +25 -0
- package/dist/stats/routeTable.d.ts.map +1 -0
- package/dist/stats/run.d.ts +43 -0
- package/dist/stats/run.d.ts.map +1 -0
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vite/index.mjs +125 -23
- package/dist/vitest/index.d.ts +18 -0
- package/dist/vitest/index.d.ts.map +1 -1
- package/dist/vitest/index.js +2 -2
- package/dist/vitest/index.js.map +3 -3
- package/package.json +2 -1
- package/dist/chunk-1es50p4k.js +0 -5
- package/dist/chunk-9qw9fa6z.js +0 -4
- package/dist/chunk-d5sbnzng.js +0 -18
- package/dist/chunk-ehasw3qm.js +0 -5
- package/dist/chunk-fe1pcnw6.js +0 -6
- package/dist/chunk-fj6yftm7.js +0 -58
- package/dist/chunk-fj6yftm7.js.map +0 -14
- package/dist/chunk-gdsby5jh.js +0 -4
- package/dist/chunk-ngw4xzrt.js +0 -9
- package/dist/chunk-ngw4xzrt.js.map +0 -10
- package/dist/chunk-pa3khk46.js +0 -5
- package/dist/chunk-rjcsdazt.js +0 -4
- package/dist/chunk-s5aa4hty.js +0 -17
- package/dist/chunk-w3j53r0a.js +0 -24
- package/dist/chunk-y66ntxbg.js +0 -4
- package/dist/chunk-z9x8x3wq.js +0 -5
- /package/dist/{chunk-m9609t1y.js.map → chunk-0sjh5v1n.js.map} +0 -0
- /package/dist/{chunk-vwkdfngg.js.map → chunk-8b2tw2yp.js.map} +0 -0
- /package/dist/{chunk-r9gzbjc5.js.map → chunk-et4pv1b1.js.map} +0 -0
package/dist/vitest/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ea as B,fa as D}from"../chunk-6vr7f5fq.js";import"../chunk-cy5qp6mz.js";import"../chunk-yqavgpwd.js";import{za as J}from"../chunk-p1aqq0ga.js";import"../chunk-4mfrgd5m.js";import"../chunk-1yx2e0bh.js";function N(){return{name:"gemi-custom-request",enforce:"pre",async transform(G,H){let j=H.split("?",1)[0];if(j.includes("/node_modules/")||!B.test(j))return null;return{code:await D(G),map:null}}}}export{N as gemiRequestPlugin,J as gemiIslandPlugin};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=69032BE0B0AA208664756E2164756E21
|
package/dist/vitest/index.js.map
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../vitest/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type { Plugin } from \"vite\";\nimport {\n CUSTOM_REQUEST_FILTER,\n customRequestParser,\n} from \"../bun/customRequestParser\";\n\n/**\n * The request-param rewrite, as a Vite plugin, for running an app's routes\n * under vitest.\n *\n * gemi calls a route handler and a controller method with no arguments, and a\n * handler written `async (req: HttpRequest<…>) => …` only gets its request\n * because the build rewrites it to `async (req = new HttpRequest()) => …`, which\n * reads the current request from the request context. The app's build and dev\n * server get that rewrite from `gemi/bun/plugin`. Vitest loads modules through\n * Vite instead, even under `bun --bun vitest`, so without this plugin a route\n * dispatched with `App.fetch` in a test sees `req === undefined`.\n *\n * Same transform, same files (`/http/controllers/` and `/http/routes/`) as the\n * Bun plugin. `enforce: \"pre\"` so it sees the TypeScript annotations before\n * Vite strips them.\n *\n * ```ts\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { gemiRequestPlugin } from \"gemi/vitest\";\n *\n * export default defineConfig({ plugins: [gemiRequestPlugin()] });\n * ```\n */\nexport function gemiRequestPlugin(): Plugin {\n return {\n name: \"gemi-custom-request\",\n enforce: \"pre\",\n async transform(code, id) {\n const path = id.split(\"?\", 1)[0];\n if (path.includes(\"/node_modules/\") || !CUSTOM_REQUEST_FILTER.test(path)) {\n return null;\n }\n return { code: await customRequestParser(code), map: null };\n },\n };\n}\n"
|
|
5
|
+
"import type { Plugin } from \"vite\";\nimport {\n CUSTOM_REQUEST_FILTER,\n customRequestParser,\n} from \"../bun/customRequestParser\";\n\n/**\n * The request-param rewrite, as a Vite plugin, for running an app's routes\n * under vitest.\n *\n * gemi calls a route handler and a controller method with no arguments, and a\n * handler written `async (req: HttpRequest<…>) => …` only gets its request\n * because the build rewrites it to `async (req = new HttpRequest()) => …`, which\n * reads the current request from the request context. The app's build and dev\n * server get that rewrite from `gemi/bun/plugin`. Vitest loads modules through\n * Vite instead, even under `bun --bun vitest`, so without this plugin a route\n * dispatched with `App.fetch` in a test sees `req === undefined`.\n *\n * Same transform, same files (`/http/controllers/` and `/http/routes/`) as the\n * Bun plugin. `enforce: \"pre\"` so it sees the TypeScript annotations before\n * Vite strips them.\n *\n * ```ts\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { gemiRequestPlugin } from \"gemi/vitest\";\n *\n * export default defineConfig({ plugins: [gemiRequestPlugin()] });\n * ```\n */\nexport function gemiRequestPlugin(): Plugin {\n return {\n name: \"gemi-custom-request\",\n enforce: \"pre\",\n async transform(code, id) {\n const path = id.split(\"?\", 1)[0];\n if (path.includes(\"/node_modules/\") || !CUSTOM_REQUEST_FILTER.test(path)) {\n return null;\n }\n return { code: await customRequestParser(code), map: null };\n },\n };\n}\n\n/**\n * gemi's island transform, for an app's `vitest.config.ts`: with it, a test\n * that renders a static view through `App.fetch` sees each\n * `island(() => import(\"./Counter\"))` with the same module key as the build,\n * and a hydrated view renders the component in place instead of lazily.\n *\n * Without it islands still render (the component is loaded with the\n * `import()`), but their keys are unknown.\n *\n * ```ts\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { gemiIslandPlugin, gemiRequestPlugin } from \"gemi/vitest\";\n *\n * export default defineConfig({ plugins: [gemiRequestPlugin(), gemiIslandPlugin()] });\n * ```\n */\nexport { gemiIslandPlugin } from \"../vite/islandPlugin\";\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": ";
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": ";yOA8BO,IAAS,JAAiB,HAAW,JAC1C,CAAO,CACL,KAAM,sBACN,QAAS,WACH,UAAS,CAAC,EAAM,EAAI,CACxB,IAAM,EAAO,EAAG,MAAM,IAAK,CAAC,EAAE,GAC9B,GAAI,EAAK,SAAS,gBAAgB,GAAK,CAAC,EAAsB,KAAK,CAAI,EACrE,OAAO,KAET,MAAO,CAAE,KAAM,MAAM,EAAoB,CAAI,EAAG,IAAK,IAAK,EAE9D",
|
|
8
|
+
"debugId": "69032BE0B0AA208664756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gemi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.111.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Enes Tufekci <enes@gemijs.dev>",
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
"./support": "./dist/support/index.js",
|
|
43
43
|
"./console/run": "./dist/console/run.js",
|
|
44
44
|
"./queue/work": "./dist/services/queue/work.js",
|
|
45
|
+
"./stats/route-table": "./dist/stats/route-table.js",
|
|
45
46
|
"./ide/typescript-plugin": "./dist/ide/typescript-plugin/index.js",
|
|
46
47
|
"./bun/preload": "./dist/bun/preload.js",
|
|
47
48
|
"./bun/plugin": "./dist/bun/plugin.js",
|
package/dist/chunk-1es50p4k.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{H as C}from"./chunk-zys7kecf.js";import{V as ne}from"./chunk-qz9aaw5x.js";import"./chunk-g7fr2cy2.js";import{$ as _}from"./chunk-jc4j61xb.js";import{rh as c,vh as F}from"./chunk-wvwee7dn.js";var x=c(_(),1),T=c(C(),1);var q=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var D=c(ne(),1);var u=c(_(),1),m=c(C(),1);var W=300000,h="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var j=async(e,o={},r)=>{let{SSOOIDCClient:t}=await import("./chunk-zh1t33nq.js").then((m)=>c(m.default,1)),n=(f)=>o.clientConfig?.[f]??o.parentClientConfig?.[f]??r?.[f];return new t(Object.assign({},o.clientConfig??{},{region:e??o.clientConfig?.region,logger:n("logger"),userAgentAppId:n("userAgentAppId")}))};var X=async(e,o,r={},t)=>{let{CreateTokenCommand:n}=await import("./chunk-zh1t33nq.js").then((m)=>c(m.default,1));return(await j(o,r,t)).send(new n({clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken,grantType:"refresh_token"}))};var z=c(_(),1);var P=(e)=>{if(e.expiration&&e.expiration.getTime()<Date.now())throw new z.TokenProviderError(`Token is expired. ${h}`,!1)};var J=c(_(),1);var g=(e,o,r=!1)=>{if(typeof o>"u")throw new J.TokenProviderError(`Value not present for '${e}' in SSO Token${r?". Cannot refresh":""}. ${h}`,!1)};var V=c(C(),1);import{promises as re}from"fs";var{writeFile:te}=re,Y=(e,o)=>{let r=V.getSSOTokenFilepath(e),t=JSON.stringify(o,null,2);return te(r,t)};var B=new Date(0),Q=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/token-providers - fromSso");let r=await m.parseKnownFiles(e),t=m.getProfileName({profile:e.profile??o?.profile}),n=r[t];if(!n)throw new u.TokenProviderError(`Profile '${t}' could not be found in shared credentials file.`,!1);else if(!n.sso_session)throw new u.TokenProviderError(`Profile '${t}' is missing required property 'sso_session'.`);let a=n.sso_session,p=(await m.loadSsoSessionData(e))[a];if(!p)throw new u.TokenProviderError(`Sso session '${a}' could not be found in shared credentials file.`,!1);for(let i of["sso_start_url","sso_region"])if(!p[i])throw new u.TokenProviderError(`Sso session '${a}' is missing required property '${i}'.`,!1);let{sso_start_url:S,sso_region:I}=p,s;try{s=await m.getSSOTokenFromFile(a)}catch(i){throw new u.TokenProviderError(`The SSO session token associated with profile=${t} was not found or is invalid. ${h}`,!1)}g("accessToken",s.accessToken),g("expiresAt",s.expiresAt);let{accessToken:y,expiresAt:E}=s,l={token:y,expiration:new Date(E)};if(l.expiration.getTime()-Date.now()>W)return l;if(Date.now()-B.getTime()<30000)return P(l),l;g("clientId",s.clientId,!0),g("clientSecret",s.clientSecret,!0),g("refreshToken",s.refreshToken,!0);try{B.setTime(Date.now());let i=await X(s,I,e,o);g("accessToken",i.accessToken),g("expiresIn",i.expiresIn);let O=new Date(Date.now()+i.expiresIn*1000);try{await Y(a,{...s,accessToken:i.accessToken,expiresAt:O.toISOString(),refreshToken:i.refreshToken})}catch(R){}return{token:i.accessToken,expiration:O}}catch(i){return P(l),l}};var k=c(_(),1),Z=c(C(),1),A=!1,$=async({ssoStartUrl:e,ssoSession:o,ssoAccountId:r,ssoRegion:t,ssoRoleName:n,ssoClient:a,clientConfig:f,parentClientConfig:p,callerClientConfig:S,profile:I,filepath:s,configFilepath:y,ignoreCache:E,logger:l})=>{let i,O="To refresh this SSO session run aws sso login with the corresponding profile.";if(o)try{let w=await Q({profile:I,filepath:s,configFilepath:y,ignoreCache:E})();i={accessToken:w.token,expiresAt:new Date(w.expiration).toISOString()}}catch(w){throw new k.CredentialsProviderError(w.message,{tryNextLink:A,logger:l})}else try{i=await Z.getSSOTokenFromFile(e)}catch(w){throw new k.CredentialsProviderError("The SSO session associated with this profile is invalid. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:A,logger:l})}if(new Date(i.expiresAt).getTime()-Date.now()<=0)throw new k.CredentialsProviderError("The SSO session associated with this profile has expired. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:A,logger:l});let{accessToken:R}=i,{SSOClient:d,GetRoleCredentialsCommand:N}=await import("./chunk-d2tngs73.js"),se=a||new d(Object.assign({},f??{},{logger:f?.logger??S?.logger??p?.logger,region:f?.region??t,userAgentAppId:f?.userAgentAppId??S?.userAgentAppId??p?.userAgentAppId})),L;try{L=await se.send(new N({accountId:r,roleName:n,accessToken:R}))}catch(w){throw new k.CredentialsProviderError(w,{tryNextLink:A,logger:l})}let{roleCredentials:{accessKeyId:M,secretAccessKey:G,sessionToken:K,expiration:b,credentialScope:H,accountId:U}={}}=L;if(!M||!G||!K||!b)throw new k.CredentialsProviderError("SSO returns an invalid temporary credential.",{tryNextLink:A,logger:l});let v={accessKeyId:M,secretAccessKey:G,sessionToken:K,expiration:new Date(b),...H&&{credentialScope:H},...U&&{accountId:U}};if(o)D.setCredentialFeature(v,"CREDENTIALS_SSO","s");else D.setCredentialFeature(v,"CREDENTIALS_SSO_LEGACY","u");return v};var ee=c(_(),1),oe=(e,o)=>{let{sso_start_url:r,sso_account_id:t,sso_region:n,sso_role_name:a}=e;if(!r||!t||!n||!a)throw new ee.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(e).join(", ")}
|
|
3
|
-
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:o});return e};var Ce=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");let{ssoStartUrl:r,ssoAccountId:t,ssoRegion:n,ssoRoleName:a,ssoSession:f}=e,{ssoClient:p}=e,S=T.getProfileName({profile:e.profile??o?.profile});if(!r&&!t&&!n&&!a&&!f){let s=(await T.parseKnownFiles(e))[S];if(!s)throw new x.CredentialsProviderError(`Profile ${S} was not found.`,{logger:e.logger});if(!q(s))throw new x.CredentialsProviderError(`Profile ${S} is not configured with SSO credentials.`,{logger:e.logger});if(s?.sso_session){let d=(await T.loadSsoSessionData(e))[s.sso_session],N=` configurations in profile ${S} and sso-session ${s.sso_session}`;if(n&&n!==d.sso_region)throw new x.CredentialsProviderError("Conflicting SSO region"+N,{tryNextLink:!1,logger:e.logger});if(r&&r!==d.sso_start_url)throw new x.CredentialsProviderError("Conflicting SSO start_url"+N,{tryNextLink:!1,logger:e.logger});s.sso_region=d.sso_region,s.sso_start_url=d.sso_start_url}let{sso_start_url:y,sso_account_id:E,sso_region:l,sso_role_name:i,sso_session:O}=oe(s,e.logger);return $({ssoStartUrl:y,ssoSession:O,ssoAccountId:E,ssoRegion:l,ssoRoleName:i,ssoClient:p,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:S,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})}else if(!r||!t||!n||!a)throw new x.CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',{tryNextLink:!1,logger:e.logger});else return $({ssoStartUrl:r,ssoSession:f,ssoAccountId:t,ssoRegion:n,ssoRoleName:a,ssoClient:p,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:S,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})};export{oe as validateSsoProfile,q as isSsoProfile,Ce as fromSSO};
|
|
4
|
-
|
|
5
|
-
//# debugId=B31BEE4BFEC76B8464756E2164756E21
|
package/dist/chunk-9qw9fa6z.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{V as C}from"./chunk-qz9aaw5x.js";import{$ as A}from"./chunk-jc4j61xb.js";import{rh as _}from"./chunk-wvwee7dn.js";var S=_(C(),1),p=_(A(),1),N="AWS_ACCESS_KEY_ID",a="AWS_SECRET_ACCESS_KEY",i="AWS_SESSION_TOKEN",I="AWS_CREDENTIAL_EXPIRATION",d="AWS_CREDENTIAL_SCOPE",v="AWS_ACCOUNT_ID",T=(e)=>async()=>{e?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");let o=process.env[N],r=process.env[a],n=process.env[i],s=process.env[I],t=process.env[d],E=process.env[v];if(o&&r){let c={accessKeyId:o,secretAccessKey:r,...n&&{sessionToken:n},...s&&{expiration:new Date(s)},...t&&{credentialScope:t},...E&&{accountId:E}};return S.setCredentialFeature(c,"CREDENTIALS_ENV_VARS","g"),c}throw new p.CredentialsProviderError("Unable to find environment variable credentials.",{logger:e?.logger})};export{N as a,a as b,i as c,I as d,d as e,v as f,T as g};
|
|
3
|
-
|
|
4
|
-
//# debugId=019F9C8D14D87CBB64756E2164756E21
|
package/dist/chunk-d5sbnzng.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ma as p,na as h,oa as l,pa as o}from"./chunk-a1g0bahx.js";import{sa as I,ta as x,ua as k,va as m}from"./chunk-564zfdd1.js";import{wa as a}from"./chunk-9r3znmqq.js";var EQ=["gemi","gemi/client","gemi/http","gemi/app","gemi/facades","gemi/email","gemi/kernel","gemi/services","gemi/i18n","gemi/dictionary"];function M(Q){return Q==="gemi"||Q.startsWith("gemi/")}var i=44,r=59,T="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b=new Uint8Array(64),t=new Uint8Array(128);for(let Q=0;Q<T.length;Q++){let Z=T.charCodeAt(Q);b[Q]=Z,t[Z]=Q}function _(Q,Z,$){let z=Z-$;z=z<0?-z<<1|1:z<<1;do{let J=z&31;if(z>>>=5,z>0)J|=32;Q.write(b[J])}while(z>0);return Z}var R=16384,y=typeof TextDecoder<"u"?new TextDecoder:typeof Buffer<"u"?{decode(Q){return Buffer.from(Q.buffer,Q.byteOffset,Q.byteLength).toString()}}:{decode(Q){let Z="";for(let $=0;$<Q.length;$++)Z+=String.fromCharCode(Q[$]);return Z}},n=class{constructor(){this.pos=0,this.out="",this.buffer=new Uint8Array(R)}write(Q){let{buffer:Z}=this;if(Z[this.pos++]=Q,this.pos===R)this.out+=y.decode(Z),this.pos=0}flush(){let{buffer:Q,out:Z,pos:$}=this;return $>0?Z+y.decode(Q.subarray(0,$)):Z}};function L(Q){let Z=new n,$=0,z=0,J=0,W=0;for(let H=0;H<Q.length;H++){let Y=Q[H];if(H>0)Z.write(r);if(Y.length===0)continue;let X=0;for(let G=0;G<Y.length;G++){let F=Y[G];if(G>0)Z.write(i);if(X=_(Z,F[0],X),F.length===1)continue;if($=_(Z,F[1],$),z=_(Z,F[2],z),J=_(Z,F[3],J),F.length===4)continue;W=_(Z,F[4],W)}}return Z.flush()}class P{constructor(Q){this.bits=Q instanceof P?Q.bits.slice():[]}add(Q){this.bits[Q>>5]|=1<<(Q&31)}has(Q){return!!(this.bits[Q>>5]&1<<(Q&31))}}class B{constructor(Q,Z,$){this.start=Q,this.end=Z,this.original=$,this.intro="",this.outro="",this.content=$,this.storeName=!1,this.edited=!1,this.previous=null,this.next=null}appendLeft(Q){this.outro+=Q}appendRight(Q){this.intro=this.intro+Q}clone(){let Q=new B(this.start,this.end,this.original);return Q.intro=this.intro,Q.outro=this.outro,Q.content=this.content,Q.storeName=this.storeName,Q.edited=this.edited,Q}contains(Q){return this.start<Q&&Q<this.end}eachNext(Q){let Z=this;while(Z)Q(Z),Z=Z.next}eachPrevious(Q){let Z=this;while(Z)Q(Z),Z=Z.previous}edit(Q,Z,$){if(this.content=Q,!$)this.intro="",this.outro="";return this.storeName=Z,this.edited=!0,this}prependLeft(Q){this.outro=Q+this.outro}prependRight(Q){this.intro=Q+this.intro}reset(){if(this.intro="",this.outro="",this.edited)this.content=this.original,this.storeName=!1,this.edited=!1}split(Q){let Z=Q-this.start,$=this.original.slice(0,Z),z=this.original.slice(Z);this.original=$;let J=new B(Q,this.end,z);if(J.outro=this.outro,this.outro="",this.end=Q,this.edited)J.edit("",!1),this.content="";else this.content=$;if(J.next=this.next,J.next)J.next.previous=J;return J.previous=this,this.next=J,J}toString(){return this.intro+this.content+this.outro}trimEnd(Q){if(this.outro=this.outro.replace(Q,""),this.outro.length)return!0;let Z=this.content.replace(Q,"");if(Z.length){if(Z!==this.content){if(this.split(this.start+Z.length).edit("",void 0,!0),this.edited)this.edit(Z,this.storeName,!0)}return!0}else if(this.edit("",void 0,!0),this.intro=this.intro.replace(Q,""),this.intro.length)return!0}trimStart(Q){if(this.intro=this.intro.replace(Q,""),this.intro.length)return!0;let Z=this.content.replace(Q,"");if(Z.length){if(Z!==this.content){let $=this.split(this.end-Z.length);if(this.edited)$.edit(Z,this.storeName,!0);this.edit("",void 0,!0)}return!0}else if(this.edit("",void 0,!0),this.outro=this.outro.replace(Q,""),this.outro.length)return!0}}function e(){if(typeof globalThis<"u"&&typeof globalThis.btoa==="function")return(Q)=>globalThis.btoa(unescape(encodeURIComponent(Q)));else if(typeof Buffer==="function")return(Q)=>Buffer.from(Q,"utf-8").toString("base64");else return()=>{throw Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.")}}var QQ=e();class C{constructor(Q){if(this.version=3,this.file=Q.file,this.sources=Q.sources,this.sourcesContent=Q.sourcesContent,this.names=Q.names,this.mappings=L(Q.mappings),typeof Q.x_google_ignoreList<"u")this.x_google_ignoreList=Q.x_google_ignoreList;if(typeof Q.debugId<"u")this.debugId=Q.debugId}toString(){return JSON.stringify(this)}toUrl(){return"data:application/json;charset=utf-8;base64,"+QQ(this.toString())}}function ZQ(Q){let Z=Q.split(`
|
|
3
|
-
`),$=Z.filter((W)=>/^\t+/.test(W)),z=Z.filter((W)=>/^ {2,}/.test(W));if($.length===0&&z.length===0)return null;if($.length>=z.length)return"\t";let J=z.reduce((W,H)=>{let Y=/^ +/.exec(H)[0].length;return Math.min(Y,W)},1/0);return Array(J+1).join(" ")}function $Q(Q,Z){let $=Q.split(/[/\\]/),z=Z.split(/[/\\]/);$.pop();while($[0]===z[0])$.shift(),z.shift();if($.length){let J=$.length;while(J--)$[J]=".."}return $.concat(z).join("/")}var zQ=Object.prototype.toString;function JQ(Q){return zQ.call(Q)==="[object Object]"}function v(Q){let Z=Q.split(`
|
|
4
|
-
`),$=[];for(let z=0,J=0;z<Z.length;z++)$.push(J),J+=Z[z].length+1;return function(J){let W=0,H=$.length;while(W<H){let G=W+H>>1;if(J<$[G])H=G;else W=G+1}let Y=W-1,X=J-$[Y];return{line:Y,column:X}}}var WQ=/\w/;class f{constructor(Q){this.hires=Q,this.generatedCodeLine=0,this.generatedCodeColumn=0,this.raw=[],this.rawSegments=this.raw[this.generatedCodeLine]=[],this.pending=null}addEdit(Q,Z,$,z){if(Z.length){let J=Z.length-1,W=Z.indexOf(`
|
|
5
|
-
`,0),H=-1;while(W>=0&&J>W){let X=[this.generatedCodeColumn,Q,$.line,$.column];if(z>=0)X.push(z);this.rawSegments.push(X),this.generatedCodeLine+=1,this.raw[this.generatedCodeLine]=this.rawSegments=[],this.generatedCodeColumn=0,H=W,W=Z.indexOf(`
|
|
6
|
-
`,W+1)}let Y=[this.generatedCodeColumn,Q,$.line,$.column];if(z>=0)Y.push(z);this.rawSegments.push(Y),this.advance(Z.slice(H+1))}else if(this.pending)this.rawSegments.push(this.pending),this.advance(Z);this.pending=null}addUneditedChunk(Q,Z,$,z,J){let W=Z.start,H=!0,Y=!1;while(W<Z.end){if($[W]===`
|
|
7
|
-
`)z.line+=1,z.column=0,this.generatedCodeLine+=1,this.raw[this.generatedCodeLine]=this.rawSegments=[],this.generatedCodeColumn=0,H=!0,Y=!1;else{if(this.hires||H||J.has(W)){let X=[this.generatedCodeColumn,Q,z.line,z.column];if(this.hires==="boundary")if(WQ.test($[W])){if(!Y)this.rawSegments.push(X),Y=!0}else this.rawSegments.push(X),Y=!1;else this.rawSegments.push(X)}z.column+=1,this.generatedCodeColumn+=1,H=!1}W+=1}this.pending=null}advance(Q){if(!Q)return;let Z=Q.split(`
|
|
8
|
-
`);if(Z.length>1){for(let $=0;$<Z.length-1;$++)this.generatedCodeLine++,this.raw[this.generatedCodeLine]=this.rawSegments=[];this.generatedCodeColumn=0}this.generatedCodeColumn+=Z[Z.length-1].length}}var O=`
|
|
9
|
-
`,U={insertLeft:!1,insertRight:!1,storeName:!1};class q{constructor(Q,Z={}){let $=new B(0,Q.length,Q);Object.defineProperties(this,{original:{writable:!0,value:Q},outro:{writable:!0,value:""},intro:{writable:!0,value:""},firstChunk:{writable:!0,value:$},lastChunk:{writable:!0,value:$},lastSearchedChunk:{writable:!0,value:$},byStart:{writable:!0,value:{}},byEnd:{writable:!0,value:{}},filename:{writable:!0,value:Z.filename},indentExclusionRanges:{writable:!0,value:Z.indentExclusionRanges},sourcemapLocations:{writable:!0,value:new P},storedNames:{writable:!0,value:{}},indentStr:{writable:!0,value:void 0},ignoreList:{writable:!0,value:Z.ignoreList},offset:{writable:!0,value:Z.offset||0}}),this.byStart[0]=$,this.byEnd[Q.length]=$}addSourcemapLocation(Q){this.sourcemapLocations.add(Q)}append(Q){if(typeof Q!=="string")throw TypeError("outro content must be a string");return this.outro+=Q,this}appendLeft(Q,Z){if(Q=Q+this.offset,typeof Z!=="string")throw TypeError("inserted content must be a string");this._split(Q);let $=this.byEnd[Q];if($)$.appendLeft(Z);else this.intro+=Z;return this}appendRight(Q,Z){if(Q=Q+this.offset,typeof Z!=="string")throw TypeError("inserted content must be a string");this._split(Q);let $=this.byStart[Q];if($)$.appendRight(Z);else this.outro+=Z;return this}clone(){let Q=new q(this.original,{filename:this.filename,offset:this.offset}),Z=this.firstChunk,$=Q.firstChunk=Q.lastSearchedChunk=Z.clone();while(Z){Q.byStart[$.start]=$,Q.byEnd[$.end]=$;let z=Z.next,J=z&&z.clone();if(J)$.next=J,J.previous=$,$=J;Z=z}if(Q.lastChunk=$,this.indentExclusionRanges)Q.indentExclusionRanges=this.indentExclusionRanges.slice();return Q.sourcemapLocations=new P(this.sourcemapLocations),Q.intro=this.intro,Q.outro=this.outro,Q}generateDecodedMap(Q){Q=Q||{};let Z=0,$=Object.keys(this.storedNames),z=new f(Q.hires),J=v(this.original);if(this.intro)z.advance(this.intro);if(this.firstChunk.eachNext((W)=>{let H=J(W.start);if(W.intro.length)z.advance(W.intro);if(W.edited)z.addEdit(Z,W.content,H,W.storeName?$.indexOf(W.original):-1);else z.addUneditedChunk(Z,W,this.original,H,this.sourcemapLocations);if(W.outro.length)z.advance(W.outro)}),this.outro)z.advance(this.outro);return{file:Q.file?Q.file.split(/[/\\]/).pop():void 0,sources:[Q.source?$Q(Q.file||"",Q.source):Q.file||""],sourcesContent:Q.includeContent?[this.original]:void 0,names:$,mappings:z.raw,x_google_ignoreList:this.ignoreList?[Z]:void 0}}generateMap(Q){return new C(this.generateDecodedMap(Q))}_ensureindentStr(){if(this.indentStr===void 0)this.indentStr=ZQ(this.original)}_getRawIndentString(){return this._ensureindentStr(),this.indentStr}getIndentString(){return this._ensureindentStr(),this.indentStr===null?"\t":this.indentStr}indent(Q,Z){let $=/^[^\r\n]/gm;if(JQ(Q))Z=Q,Q=void 0;if(Q===void 0)this._ensureindentStr(),Q=this.indentStr||"\t";if(Q==="")return this;Z=Z||{};let z={};if(Z.exclude)(typeof Z.exclude[0]==="number"?[Z.exclude]:Z.exclude).forEach((G)=>{for(let F=G[0];F<G[1];F+=1)z[F]=!0});let J=Z.indentStart!==!1,W=(X)=>{if(J)return`${Q}${X}`;return J=!0,X};this.intro=this.intro.replace($,W);let H=0,Y=this.firstChunk;while(Y){let X=Y.end;if(Y.edited){if(!z[H]){if(Y.content=Y.content.replace($,W),Y.content.length)J=Y.content[Y.content.length-1]===`
|
|
10
|
-
`}}else{H=Y.start;while(H<X){if(!z[H]){let G=this.original[H];if(G===`
|
|
11
|
-
`)J=!0;else if(G!=="\r"&&J)if(J=!1,H===Y.start)Y.prependRight(Q);else this._splitChunk(Y,H),Y=Y.next,Y.prependRight(Q)}H+=1}}H=Y.end,Y=Y.next}return this.outro=this.outro.replace($,W),this}insert(){throw Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)")}insertLeft(Q,Z){if(!U.insertLeft)console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"),U.insertLeft=!0;return this.appendLeft(Q,Z)}insertRight(Q,Z){if(!U.insertRight)console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"),U.insertRight=!0;return this.prependRight(Q,Z)}move(Q,Z,$){if(Q=Q+this.offset,Z=Z+this.offset,$=$+this.offset,$>=Q&&$<=Z)throw Error("Cannot move a selection inside itself");this._split(Q),this._split(Z),this._split($);let z=this.byStart[Q],J=this.byEnd[Z],W=z.previous,H=J.next,Y=this.byStart[$];if(!Y&&J===this.lastChunk)return this;let X=Y?Y.previous:this.lastChunk;if(W)W.next=H;if(H)H.previous=W;if(X)X.next=z;if(Y)Y.previous=J;if(!z.previous)this.firstChunk=J.next;if(!J.next)this.lastChunk=z.previous,this.lastChunk.next=null;if(z.previous=X,J.next=Y||null,!X)this.firstChunk=z;if(!Y)this.lastChunk=J;return this}overwrite(Q,Z,$,z){return z=z||{},this.update(Q,Z,$,{...z,overwrite:!z.contentOnly})}update(Q,Z,$,z){if(Q=Q+this.offset,Z=Z+this.offset,typeof $!=="string")throw TypeError("replacement content must be a string");if(this.original.length!==0){while(Q<0)Q+=this.original.length;while(Z<0)Z+=this.original.length}if(Z>this.original.length)throw Error("end is out of bounds");if(Q===Z)throw Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");if(this._split(Q),this._split(Z),z===!0){if(!U.storeName)console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"),U.storeName=!0;z={storeName:!0}}let J=z!==void 0?z.storeName:!1,W=z!==void 0?z.overwrite:!1;if(J){let X=this.original.slice(Q,Z);Object.defineProperty(this.storedNames,X,{writable:!0,value:!0,enumerable:!0})}let H=this.byStart[Q],Y=this.byEnd[Z];if(H){let X=H;while(X!==Y){if(X.next!==this.byStart[X.end])throw Error("Cannot overwrite across a split point");X=X.next,X.edit("",!1)}H.edit($,J,!W)}else{let X=new B(Q,Z,"").edit($,J);Y.next=X,X.previous=Y}return this}prepend(Q){if(typeof Q!=="string")throw TypeError("outro content must be a string");return this.intro=Q+this.intro,this}prependLeft(Q,Z){if(Q=Q+this.offset,typeof Z!=="string")throw TypeError("inserted content must be a string");this._split(Q);let $=this.byEnd[Q];if($)$.prependLeft(Z);else this.intro=Z+this.intro;return this}prependRight(Q,Z){if(Q=Q+this.offset,typeof Z!=="string")throw TypeError("inserted content must be a string");this._split(Q);let $=this.byStart[Q];if($)$.prependRight(Z);else this.outro=Z+this.outro;return this}remove(Q,Z){if(Q=Q+this.offset,Z=Z+this.offset,this.original.length!==0){while(Q<0)Q+=this.original.length;while(Z<0)Z+=this.original.length}if(Q===Z)return this;if(Q<0||Z>this.original.length)throw Error("Character is out of bounds");if(Q>Z)throw Error("end must be greater than start");this._split(Q),this._split(Z);let $=this.byStart[Q];while($)$.intro="",$.outro="",$.edit(""),$=Z>$.end?this.byStart[$.end]:null;return this}reset(Q,Z){if(Q=Q+this.offset,Z=Z+this.offset,this.original.length!==0){while(Q<0)Q+=this.original.length;while(Z<0)Z+=this.original.length}if(Q===Z)return this;if(Q<0||Z>this.original.length)throw Error("Character is out of bounds");if(Q>Z)throw Error("end must be greater than start");this._split(Q),this._split(Z);let $=this.byStart[Q];while($)$.reset(),$=Z>$.end?this.byStart[$.end]:null;return this}lastChar(){if(this.outro.length)return this.outro[this.outro.length-1];let Q=this.lastChunk;do{if(Q.outro.length)return Q.outro[Q.outro.length-1];if(Q.content.length)return Q.content[Q.content.length-1];if(Q.intro.length)return Q.intro[Q.intro.length-1]}while(Q=Q.previous);if(this.intro.length)return this.intro[this.intro.length-1];return""}lastLine(){let Q=this.outro.lastIndexOf(O);if(Q!==-1)return this.outro.substr(Q+1);let Z=this.outro,$=this.lastChunk;do{if($.outro.length>0){if(Q=$.outro.lastIndexOf(O),Q!==-1)return $.outro.substr(Q+1)+Z;Z=$.outro+Z}if($.content.length>0){if(Q=$.content.lastIndexOf(O),Q!==-1)return $.content.substr(Q+1)+Z;Z=$.content+Z}if($.intro.length>0){if(Q=$.intro.lastIndexOf(O),Q!==-1)return $.intro.substr(Q+1)+Z;Z=$.intro+Z}}while($=$.previous);if(Q=this.intro.lastIndexOf(O),Q!==-1)return this.intro.substr(Q+1)+Z;return this.intro+Z}slice(Q=0,Z=this.original.length-this.offset){if(Q=Q+this.offset,Z=Z+this.offset,this.original.length!==0){while(Q<0)Q+=this.original.length;while(Z<0)Z+=this.original.length}let $="",z=this.firstChunk;while(z&&(z.start>Q||z.end<=Q)){if(z.start<Z&&z.end>=Z)return $;z=z.next}if(z&&z.edited&&z.start!==Q)throw Error(`Cannot use replaced character ${Q} as slice start anchor.`);let J=z;while(z){if(z.intro&&(J!==z||z.start===Q))$+=z.intro;let W=z.start<Z&&z.end>=Z;if(W&&z.edited&&z.end!==Z)throw Error(`Cannot use replaced character ${Z} as slice end anchor.`);let H=J===z?Q-z.start:0,Y=W?z.content.length+Z-z.end:z.content.length;if($+=z.content.slice(H,Y),z.outro&&(!W||z.end===Z))$+=z.outro;if(W)break;z=z.next}return $}snip(Q,Z){let $=this.clone();return $.remove(0,Q),$.remove(Z,$.original.length),$}_split(Q){if(this.byStart[Q]||this.byEnd[Q])return;let Z=this.lastSearchedChunk,$=Z,z=Q>Z.end;while(Z){if(Z.contains(Q))return this._splitChunk(Z,Q);if(Z=z?this.byStart[Z.end]:this.byEnd[Z.start],Z===$)return;$=Z}}_splitChunk(Q,Z){if(Q.edited&&Q.content.length){let z=v(this.original)(Z);throw Error(`Cannot split a chunk that has already been edited (${z.line}:${z.column} \u2013 "${Q.original}")`)}let $=Q.split(Z);if(this.byEnd[Z]=Q,this.byStart[Z]=$,this.byEnd[$.end]=$,Q===this.lastChunk)this.lastChunk=$;return this.lastSearchedChunk=Q,!0}toString(){let Q=this.intro,Z=this.firstChunk;while(Z)Q+=Z.toString(),Z=Z.next;return Q+this.outro}isEmpty(){let Q=this.firstChunk;do if(Q.intro.length&&Q.intro.trim()||Q.content.length&&Q.content.trim()||Q.outro.length&&Q.outro.trim())return!1;while(Q=Q.next);return!0}length(){let Q=this.firstChunk,Z=0;do Z+=Q.intro.length+Q.content.length+Q.outro.length;while(Q=Q.next);return Z}trimLines(){return this.trim("[\\r\\n]")}trim(Q){return this.trimStart(Q).trimEnd(Q)}trimEndAborted(Q){let Z=new RegExp((Q||"\\s")+"+$");if(this.outro=this.outro.replace(Z,""),this.outro.length)return!0;let $=this.lastChunk;do{let z=$.end,J=$.trimEnd(Z);if($.end!==z){if(this.lastChunk===$)this.lastChunk=$.next;this.byEnd[$.end]=$,this.byStart[$.next.start]=$.next,this.byEnd[$.next.end]=$.next}if(J)return!0;$=$.previous}while($);return!1}trimEnd(Q){return this.trimEndAborted(Q),this}trimStartAborted(Q){let Z=new RegExp("^"+(Q||"\\s")+"+");if(this.intro=this.intro.replace(Z,""),this.intro.length)return!0;let $=this.firstChunk;do{let z=$.end,J=$.trimStart(Z);if($.end!==z){if($===this.lastChunk)this.lastChunk=$.next;this.byEnd[$.end]=$,this.byStart[$.next.start]=$.next,this.byEnd[$.next.end]=$.next}if(J)return!0;$=$.next}while($);return!1}trimStart(Q){return this.trimStartAborted(Q),this}hasChanged(){return this.original!==this.toString()}_replaceRegexp(Q,Z){function $(J,W){if(typeof Z==="string")return Z.replace(/\$(\$|&|\d+)/g,(H,Y)=>{if(Y==="$")return"$";if(Y==="&")return J[0];if(+Y<J.length)return J[+Y];return`$${Y}`});else return Z(...J,J.index,W,J.groups)}function z(J,W){let H,Y=[];while(H=J.exec(W))Y.push(H);return Y}if(Q.global)z(Q,this.original).forEach((W)=>{if(W.index!=null){let H=$(W,this.original);if(H!==W[0])this.overwrite(W.index,W.index+W[0].length,H)}});else{let J=this.original.match(Q);if(J&&J.index!=null){let W=$(J,this.original);if(W!==J[0])this.overwrite(J.index,J.index+J[0].length,W)}}return this}_replaceString(Q,Z){let{original:$}=this,z=$.indexOf(Q);if(z!==-1){if(typeof Z==="function")Z=Z(Q,z,$);if(Q!==Z)this.overwrite(z,z+Q.length,Z)}return this}replace(Q,Z){if(typeof Q==="string")return this._replaceString(Q,Z);return this._replaceRegexp(Q,Z)}_replaceAllString(Q,Z){let{original:$}=this,z=Q.length;for(let J=$.indexOf(Q);J!==-1;J=$.indexOf(Q,J+z)){let W=$.slice(J,J+z),H=Z;if(typeof Z==="function")H=Z(W,J,$);if(W!==H)this.overwrite(J,J+z,H)}return this}replaceAll(Q,Z){if(typeof Q==="string")return this._replaceAllString(Q,Z);if(!Q.global)throw TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");return this._replaceRegexp(Q,Z)}}import{parseAstAsync as YQ}from"vite";var w="virtual:gemi-dict/",S="\x00virtual:gemi-dict/",HQ=new Set(["gemi/dictionary","gemi/client","gemi/i18n"]),XQ="gemi/dictionary";function g(){let Q=new Map;return{name:"gemi-plugin-dictionary",enforce:"post",resolveId(Z){if(Z.startsWith(w))return`\x00${Z}`;return null},async load(Z){if(!Z.startsWith(S))return null;let $=Z.slice(S.length),z=$.lastIndexOf("/"),J=$.slice(0,z),W=$.slice(z+1),H=Q.get(J);if(!H){let X=GQ(J);if(X){try{await this.load({id:X})}catch{}H=Q.get(J)}}if(!H)return this.error(`No dictionary registered for "${J}". If this persists, restart the dev server.`),null;let Y=x(H.translations,W,H.locales);return`export default ${JSON.stringify(Y)};
|
|
12
|
-
`},async transform(Z,$){if(!Z.includes("defineDictionary"))return null;if($.startsWith("\x00")||$.includes("/node_modules/"))return null;let z=await YQ(Z),J=new Set;for(let G of z.body){if(G.type!=="ImportDeclaration")continue;if(!HQ.has(G.source?.value))continue;for(let F of G.specifiers??[])if(F.type==="ImportSpecifier"&&F.imported?.name==="defineDictionary")J.add(F.local.name)}let W=[],H=0;if(V(z,(G)=>{if(G.type!=="CallExpression")return;let F=G.callee;if(F?.type==="Identifier"&&J.has(F.name)){W.push(G);return}if((F?.type==="Identifier"?F.name:F?.type==="MemberExpression"&&!F.computed?F.property?.name:void 0)==="defineDictionary")H++}),H>0&&KQ(z,"defineDictionary"))H=0;if(H>0)this.warn(`${$}: ${H} defineDictionary() call(s) could not be traced to an import of "gemi/dictionary", "gemi/client" or "gemi/i18n", so their locales were left inline and will all ship to the browser. Import defineDictionary directly by name rather than through a namespace import or a local re-export.`);if(W.length===0)return null;let Y=new q(Z),X=!1;for(let G of W){if(G.arguments?.length<1||G.arguments?.length>2)this.error({message:"defineDictionary() takes an object literal and an optional options object.",pos:G.start});let F=FQ(G.arguments[0],(D)=>this.error({message:D,pos:G.arguments[0]?.start??G.start})),K=DQ(G.arguments[1],(D)=>this.error({message:D,pos:G.arguments[1]?.start??G.start})),j=m(F),A=`${Buffer.from($).toString("base64url")}/${j}`,N=I(F,K);if(N.length===0)this.error({message:'defineDictionary() declares no locales \u2014 every key needs at least one "<locale>": "<string>" entry.',pos:G.start});if(!K){let D=k(F);if(D)this.error({message:`defineDictionary() cannot infer a source language. Key "${D.againstKey}" lists "${D.againstFirst}" first but "${D.key}" lists "${D.first}" first, so the locale every key falls back to depends on the order `+"they are written in \u2014 moving one key would change what language a reader sees. "+'Pass { sourceLocale: "<locale>" } as the second argument to pin it.',pos:G.start})}Q.set(A,{id:j,locales:N,translations:F});let s=N.map((D)=>`${JSON.stringify(D)}:()=>import(${JSON.stringify(`${w}${A}/${D}`)})`).join(",");Y.overwrite(G.start,G.end,`__gemi_dict__(${JSON.stringify(j)},{${s}})`),X=!0}if(!X)return null;return Y.append(`
|
|
13
|
-
import { __gemi_dict__ } from ${JSON.stringify(XQ)};
|
|
14
|
-
`),{code:Y.toString(),map:Y.generateMap({hires:!0})}}}}function GQ(Q){let Z=Q.indexOf("/");if(Z===-1)return null;try{return Buffer.from(Q.slice(0,Z),"base64url").toString("utf8")}catch{return null}}function FQ(Q,Z){if(Q?.type!=="ObjectExpression")Z("defineDictionary() needs an inline object literal \u2014 it is read at build time, so a variable or spread cannot be resolved.");let $={};for(let z of Q.properties){let J=E(z);if(J===null)Z("defineDictionary() keys must be plain string keys \u2014 computed keys and spreads cannot be read at build time.");if(z.value?.type!=="ObjectExpression")Z(`defineDictionary() entry "${J}" must be an object of "<locale>": "<string>" pairs.`);let W={};for(let H of z.value.properties){let Y=E(H);if(Y===null)Z(`defineDictionary() entry "${J}" has a locale key that cannot be read at build time.`);let X=H.value;if(X?.type!=="Literal"||typeof X.value!=="string")Z(`defineDictionary() entry "${J}" locale "${Y}" must be a string literal. Use {{param}} interpolation instead of a template literal or a function.`);W[Y]=X.value}$[J]=W}return $}function DQ(Q,Z){if(Q===void 0)return;if(Q.type!=="ObjectExpression")Z("defineDictionary() options must be an inline object literal \u2014 it is read at build time.");for(let $ of Q.properties){if(E($)!=="sourceLocale")continue;let z=$.value;if(z?.type!=="Literal"||typeof z.value!=="string")Z("defineDictionary() sourceLocale must be a string literal.");return z.value}return}function KQ(Q,Z){let $=!1;return V(Q,(z)=>{if($)return;if(z.type==="FunctionDeclaration"&&z.id?.name===Z)$=!0;if(z.type==="VariableDeclarator"&&z.id?.name===Z)$=!0}),$}function E(Q){if(Q?.type!=="Property"||Q.computed)return null;if(Q.key?.type==="Identifier")return Q.key.name;if(Q.key?.type==="Literal"&&typeof Q.key.value==="string")return Q.key.value;return null}function V(Q,Z){if(Q===null||typeof Q!=="object")return;if(Array.isArray(Q)){for(let $ of Q)V($,Z);return}if(typeof Q.type==="string")Z(Q);for(let $ of Object.keys(Q)){if($==="parent")continue;let z=Q[$];if(z&&typeof z==="object")V(z,Z)}}import{mkdir as UQ,writeFile as qQ}from"fs/promises";import{dirname as jQ,join as AQ}from"path";function u(Q){let Z;return{name:"gemi-plugin-asset-base",config:($,z)=>z.command==="build"&&Q?{base:Q}:void 0,configResolved($){Z=$},async writeBundle($){if(!Z||Z.command!=="build"||Z.build.ssr||!$.dir)return;let z=AQ($.dir,h);await UQ(jQ(z),{recursive:!0}),await qQ(z,`${JSON.stringify({assetBase:NQ(Z.base)})}
|
|
15
|
-
`)}}}function NQ(Q){return Q.startsWith("/")||/^[a-z][a-z\d+.-]*:\/\//i.test(Q)?l(Q):p}import{realpathSync as _Q}from"fs";import{relative as OQ,sep as BQ}from"path";var PQ=/\(\s*\)\s*=>\s*import\(\s*(["'])([^"'\n]+?\.island(?:\.[cm]?[jt]sx?)?)\1\s*\)/g;function d(Q){try{return _Q(Q)}catch{return Q}}function c(){let Q=process.cwd();return{name:"gemi-plugin-islands",enforce:"pre",configResolved(Z){Q=d(Z.root)},async transform(Z,$,z){if($.includes("/node_modules/")||$.startsWith("\x00"))return null;if(!/\.[cm]?[jt]sx?$/.test($.split("?")[0]))return null;if(!Z.includes(".island"))return null;let J=Boolean(z?.ssr)||this.environment?.config?.consumer==="server",W=new q(Z),H=!1;for(let Y of Z.matchAll(PQ)){let[X,G,F]=Y,K=await this.resolve(F,$);if(!K||K.external)continue;let j=d(K.id.split("?")[0]),A=OQ(Q,j).split(BQ).join("/");if(A.startsWith(".."))continue;let N=J?'() => Promise.reject(new Error("Island modules load in the browser."))':`() => import(${G}${F}${G})`;W.overwrite(Y.index,Y.index+X.length,`Object.assign(${N}, { gemiIsland: ${JSON.stringify(A)} })`),H=!0}if(!H)return null;return{code:W.toString(),map:W.generateMap({hires:!0})}}}}var VQ=async()=>{let Q=await a(process.cwd()),{plugins:Z=[],...$}=Q.vite??{},z=o(Q.assetBase);return[{name:"gemi-plugin-config",enforce:"pre",config:async(J,W)=>{let H=`${process.cwd()}/app`;return{assetsInclude:["/public"],build:{manifest:!0,ssrEmitAssets:!0,sourcemap:!0,rollupOptions:{input:Array.from(JSON.parse(process.env.GEMI_INPUT??"[]")).filter((Y)=>!(W.isSsrBuild&&/\.island\.[cm]?[jt]sx?$/.test(Y))),preserveEntrySignatures:"strict",...W.isSsrBuild?{external:M}:{}}},resolve:{alias:{"@/app":H}}}}},{name:"gemi-plugin-user-config",config:()=>$},u(z),c(),{name:"gemi-plugin-hot-reload",handleHotUpdate({server:J,modules:W}){if(W?.[0]?.id?.includes("/app/http/"))return[]}},...Z,g()]},sQ=VQ;
|
|
16
|
-
export{EQ as ka,sQ as la};
|
|
17
|
-
|
|
18
|
-
//# debugId=1C8F07075029D6C564756E2164756E21
|
package/dist/chunk-ehasw3qm.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{H as F}from"./chunk-zys7kecf.js";import{$ as w}from"./chunk-jc4j61xb.js";import{sh as h}from"./chunk-wvwee7dn.js";var P=h((p)=>{var t=w(),l=F();function d(e){try{let o=new Set(Array.from(e.match(/([A-Z_]){3,}/g)??[]));return o.delete("CONFIG"),o.delete("CONFIG_PREFIX_SEPARATOR"),o.delete("ENV"),[...o].join(", ")}catch(o){return e}}var u=(e,o)=>async()=>{try{let r=e(process.env,o);if(r===void 0)throw Error();return r}catch(r){throw new t.CredentialsProviderError(r.message||`Not found in ENV: ${d(e.toString())}`,{logger:o?.logger})}},C=(e,{preferredFile:o="config",...r}={})=>async()=>{let n=l.getProfileName(r),{configFile:i,credentialsFile:c}=await l.loadSharedConfigFiles(r),s=c[n]||{},g=i[n]||{},m=o==="config"?{...s,...g}:{...g,...s};try{let f=e(m,o==="config"?i:c);if(f===void 0)throw Error();return f}catch(a){throw new t.CredentialsProviderError(a.message||`Not found in config files w/ profile [${n}]: ${d(e.toString())}`,{logger:r.logger})}},y=(e)=>typeof e==="function",E=(e)=>y(e)?async()=>await e():t.fromStatic(e),N=({environmentVariableSelector:e,configFileSelector:o,default:r},n={})=>{let{signingName:i,logger:c}=n,s={signingName:i,logger:c};return t.memoize(t.chain(u(e,s),C(o,n),E(r)))};p.loadConfig=N});
|
|
3
|
-
export{P as G};
|
|
4
|
-
|
|
5
|
-
//# debugId=033C30EEC084045664756E2164756E21
|
package/dist/chunk-fe1pcnw6.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{xa as y}from"./chunk-tvy2fqza.js";import{createElement as j}from"react";function h(i,n){let s=Object.keys(n).sort((u,b)=>b.length-u.length).map((u)=>u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),r=new RegExp(s.join("|"),"g");return i.replace(r,(u)=>n[u])}async function L(i,n,s=[],r){let u=[...s.map((t)=>`${i}/views/${t}.tsx`),r?`${i}/views/${r}.tsx`:`${i}/views/RootLayout.tsx`],b=new Set;for(let t of u){let e=n.moduleGraph.getModulesByFile(t);if(e)for(let l of e)b.add(l)}let p=[],d=[],c={};for(let t of b)if(t)for(let e of t.importedModules){if(e.file.includes("module.css"))c[e.file]=e.ssrTransformResult.map.sourcesContent.join("");if(e.file.includes(".css"))d.push(e.file)}for(let t of d){let e=await n.transformRequest(t+"?direct"),l=t.includes("module.css"),x="";if(l)x=h(c[t],e.default);p.push({isDev:!0,id:t,content:l?x:e.code})}return p.map((t,e)=>{return j("style",{key:e,type:"text/css","data-vite-dev-id":t.id,dangerouslySetInnerHTML:{__html:t.content}})})}async function N(i=[]){return i.map((n,s)=>{return j("style",{key:s,id:n?.id,type:"text/css",dangerouslySetInnerHTML:{__html:n.content}})})}import{existsSync as f}from"fs";import{basename as k}from"path";import{networkInterfaces as q}from"os";var v={name:"gemi",version:"0.109.0",private:!1,license:"MIT",author:"Enes Tufekci <enes@gemijs.dev>",repository:{type:"git",url:"git+https://github.com/nstfkc/gemi.git",directory:"packages/gemi"},bin:{gemi:"./dist/bin/gemi.js","gemi-orm-generator":"./dist/bin/orm-generator.js"},files:["dist/**/*","ide/typescript-plugin/package.json","skills/**/*"],module:!0,exports:{"./http":"./http/index.ts","./client":"./client/index.ts","./ai":"./ai/index.ts","./ai/client":"./ai/client/index.ts","./testing":"./testing/index.ts","./app":"./app/index.ts","./facades":"./facades/index.ts","./email":"./email/index.ts","./vite":"./dist/vite/index.mjs","./kernel":"./kernel/index.ts","./services":"./services/index.ts","./i18n":"./i18n/index.ts","./dictionary":"./i18n/dictionaryRuntime.ts","./server":"./server/index.ts","./config":"./config/index.ts","./container":"./container/index.ts","./foundation":"./foundation/index.ts","./database":"./database/index.ts","./orm":"./orm/index.ts","./support":"./support/index.ts","./console/run":"./console/run.ts","./queue/work":"./services/queue/work.ts","./ide/typescript-plugin":"./ide/typescript-plugin/index.ts","./bun/preload":"./bun/preload.ts","./bun/plugin":"./bun/plugin.ts","./vitest":"./vitest/index.ts"},scripts:{lint:"oxlint",typecheck:"tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.browser.json && tsc --noEmit -p ide/typescript-plugin/tsconfig.json",build:"NODE_ENV=production bun run build:core && bun run build:bin && bun run build:types && bun run build:client && bun run build:plugin && bun run build:ts-plugin && bun run build:client-types && bun run build:augmentation","build:core":"bun ./scripts/build.ts","build:bin":"bun build --outdir=./dist/bin --target=bun --external=vite --external=react-dom --external=react/jsx-runtime --external=bun --external=sharp --external=@azure/storage-blob --external=typescript --sourcemap ./bin/gemi.ts ./bin/orm-generator.ts && bun ./scripts/prepare-bin.ts","build:client":"rm -rf dist/client dist/testing dist/ai/client dist/chunks && vite build -c vite.client.config.mts","build:plugin":"vite build -c vite.plugin.config.mts","build:ts-plugin":"bun ./scripts/build-ts-plugin.ts","build:types":"tsc -p tsconfig.build.json","build:client-types":"tsc -p tsconfig.browser.json",test:"bun --bun vitest","test:types":"vitest run --typecheck.only","test:live":"bun --bun vitest run ai/live","test:packaging":"bun --bun vitest run --config vitest.packaging.config.ts","build:publish":"bun scripts/build-publish.ts",prepublishOnly:"echo 'Do not publish from this directory \u2014 its exports point at TS source. Run: bun run build:publish, then publish from .publish/' && exit 1","build:augmentation":"bun ./scripts/wire-augmentation.ts"},dependencies:{"@aws-sdk/client-s3":"^3.629.0","@aws-sdk/s3-request-presigner":"^3.629.0","ast-types":"^0.14.2",commander:"^12.1.0",history:"^5.3.0","jsx-email":"2.0.0-rc2.1","magic-string":"^0.30.17",open:"^10.1.0","react-error-boundary":"^6.0.0",recast:"^0.23.9",resend:"^6.12.3",satori:"^0.12.2","temporal-polyfill":"^0.2.5","twitter-api-v2":"^1.20.2","urlpattern-polyfill":"^10.0.0",uuid:"^9.0.1"},devDependencies:{"@babel/parser":"^7.25.4","@prisma/generator-helper":"^6.5.0","@repo/typescript-config":"*","@testing-library/react":"^16.3.2","@types/bun":"^1.3.14","@types/eslint":"^8.56.5","@types/node":"^20.11.24","@types/react":"^19.0.2","@types/react-dom":"^19.0.2",eslint:"^8.57.0",jsdom:"^30.0.1",oxlint:"^1.39.0",react:"19.2.3","react-dom":"19.2.3",typescript:"^5.7.3",vitest:"^4.0.0"},peerDependencies:{"@azure/storage-blob":"^12.28.0",react:">=19","react-dom":">=19",sharp:"^0.34.2",typescript:">=5",vite:"^8.0.0"},peerDependenciesMeta:{"@azure/storage-blob":{optional:!0},typescript:{optional:!0}}};var z=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D"],E=Boolean(process.stdout.isTTY)&&!process.env.NO_COLOR,g=(i,n)=>E?`\x1B[${i}m${n}\x1B[0m`:n,O=(i)=>g("1",i),o=(i)=>g("2",i),a=(i)=>g("36",i),T=(i)=>g("32",i),R=(i)=>g("35",i);function _(){return v.version??"?"}function G(i){for(let n of Object.values(q()))for(let s of n??[])if((s.family==="IPv4"||s.family===4)&&!s.internal)return`http://${s.address}:${i}`;return null}function H(i){return y(i).filter((n)=>f(n)).map((n)=>k(n))}function B(i){let{port:n,rootDir:s}=i,r=`http://localhost:${n}`,u=G(n),b=H(s),p=(c,t)=>` ${T("\u279C")} ${O(c.padEnd(9))}${t}`,d=["",...z.map((c)=>R(c)),"",` ${o("gemi")} ${a(`v${_()}`)}`,"",p("Local:",a(r)),p("Network:",u?a(u):o("unavailable")),p("Env:",b.length?b.join(", "):o("none")),""];console.log(d.join(`
|
|
3
|
-
`))}
|
|
4
|
-
export{L as h,N as i,B as j};
|
|
5
|
-
|
|
6
|
-
//# debugId=0084180CD93381AF64756E2164756E21
|
package/dist/chunk-fj6yftm7.js
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{h as y,j as q}from"./chunk-fe1pcnw6.js";import{ka as E,la as w}from"./chunk-d5sbnzng.js";import"./chunk-a1g0bahx.js";import"./chunk-564zfdd1.js";import"./chunk-9r3znmqq.js";import"./chunk-tvy2fqza.js";import"./chunk-q8k7f11z.js";import{Vf as _}from"./chunk-zz7h6tdr.js";import{ph as N}from"./chunk-hf32yq23.js";import"./chunk-wvwee7dn.js";import{join as QJ}from"path";import{createServer as WJ}from"vite";import{join as u}from"path";import{IncomingMessage as v,ServerResponse as l}from"http";import{Socket as d}from"net";function c(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
|
|
3
|
-
`).split(`
|
|
4
|
-
`).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).join(`
|
|
5
|
-
`).trim()}function F(J){return`
|
|
6
|
-
<!DOCTYPE html>
|
|
7
|
-
<html lang="en">
|
|
8
|
-
<head>
|
|
9
|
-
<meta charset="UTF-8" />
|
|
10
|
-
<meta
|
|
11
|
-
name="viewport"
|
|
12
|
-
content="width=device-width, initial-scale=1.0"
|
|
13
|
-
/>
|
|
14
|
-
|
|
15
|
-
<title>Error</title>
|
|
16
|
-
<style>
|
|
17
|
-
body {
|
|
18
|
-
font-family: Arial, sans-serif;
|
|
19
|
-
padding: 20px;
|
|
20
|
-
}
|
|
21
|
-
h1 {
|
|
22
|
-
color: red;
|
|
23
|
-
}
|
|
24
|
-
</style>
|
|
25
|
-
</head>
|
|
26
|
-
<body>
|
|
27
|
-
<div id="overlay"></div>
|
|
28
|
-
<script type="module" src="/refresh.js"></script>
|
|
29
|
-
<script type="module" src="/@vite/client"></script>
|
|
30
|
-
<script>
|
|
31
|
-
${c.toString()}
|
|
32
|
-
const err = ${JSON.stringify(J,Object.getOwnPropertyNames(J),2)}
|
|
33
|
-
|
|
34
|
-
window.addEventListener('load', () => {
|
|
35
|
-
const container = document.getElementById('overlay')
|
|
36
|
-
const ErrorOverlay = customElements.get('vite-error-overlay')
|
|
37
|
-
if (ErrorOverlay) {
|
|
38
|
-
const overlay = new ErrorOverlay({ ...err, message: cleanupTerminalText(err.message) });
|
|
39
|
-
container.appendChild(overlay)
|
|
40
|
-
}
|
|
41
|
-
})
|
|
42
|
-
</script>
|
|
43
|
-
</body>
|
|
44
|
-
</html>
|
|
45
|
-
`}function i(J,Q){let W=new URL(Q.url),Z=new v(new d);Z.url=W.pathname+W.search,Z.method=Q.method,Z.headers=Object.fromEntries(Q.headers);let z=new l(Z),X=[];return new Promise((L)=>{z.write=(G)=>{if(G)X.push(Buffer.from(G));return!0},z.end=(G)=>{if(G&&typeof G!=="function")X.push(Buffer.from(G));let $=new Headers;for(let[U,Y]of Object.entries(z.getHeaders())){if(Y==null)continue;for(let B of Array.isArray(Y)?Y:[Y])$.append(U,String(B))}return L(new Response(X.length?Buffer.concat(X):null,{status:z.statusCode,headers:$})),z},J.middlewares(Z,z,()=>L(null))})}function p(J,Q,W){let Z=String(Q),z=" ".repeat(Z.length),X=" ".repeat(Math.max(0,W-1))+"^";return`${Z} | ${J}
|
|
46
|
-
${z} | ${X}
|
|
47
|
-
`}function I(J){if(J&&typeof J==="object"){let Q=J.position;if(Q&&typeof Q==="object"&&typeof Q.file==="string")return{message:typeof J.message==="string"?J.message:String(J),stack:"",frame:typeof Q.lineText==="string"?p(Q.lineText,Q.line,Q.column):void 0,loc:{file:Q.file,line:Q.line,column:Q.column}};return{message:typeof J.message==="string"?J.message:String(J),stack:typeof J.stack==="string"?J.stack:""}}return{message:String(J),stack:""}}function O(J){let Q=globalThis.__gemiVite;if(!Q)return;Q.ws.send({type:"error",err:I(J)}),globalThis.__gemiErrorActive=!0}function H(J){let Q=J.environments.ssr;if(typeof Q?.runner?.import!=="function")throw Error("gemi dev requires a runnable Vite SSR environment.");return Q.runner}var S="/@gemi/dev-entry.js",n=`const report = (error) => console.error(error);
|
|
48
|
-
await import("/refresh.js").catch(report);
|
|
49
|
-
await import("/@vite/client").catch(report);
|
|
50
|
-
await import("/app/client.tsx");
|
|
51
|
-
`,o=`import RefreshRuntime from "/@react-refresh";
|
|
52
|
-
RefreshRuntime.injectIntoGlobalHook(window);
|
|
53
|
-
window.$RefreshReg$ = () => {};
|
|
54
|
-
window.$RefreshSig$ = () => (type) => type;
|
|
55
|
-
window.__vite_plugin_react_preamble_installed__ = true;
|
|
56
|
-
`;function s(J){let{pathname:Q}=new URL(J.url),W=(Z)=>new Response(Z,{headers:{"Content-Type":"application/javascript"}});if(Q===S)return W(n);if(Q.startsWith("/render-error.js"))return W("window.render_error = true");if(Q.startsWith("/refresh.js"))return W(o);return null}function C(J,Q,W){let Z=u(process.cwd(),"app");return async(z)=>{let{pathname:X}=new URL(z.url),L=($)=>{if(console.error($),W.ssrFixStacktrace?.($),O($),N(X))return new Response(JSON.stringify({error:_("server_error",$?.message??String($),500)}),{status:500,headers:{"Content-Type":"application/json"}});return globalThis.__gemiErrorPageServed=!0,new Response(F(I($)),{status:500,headers:{"Content-Type":"text/html"}})},G=async($)=>{let U=s($);if(U)return U;try{let Y=J.fetch.bind(J),B=await i(W,$)??await Y($);if(B instanceof Response)return B;let A={},b={},M={},h=(K,j)=>`"${K}": () => import("${j}")`,D=[];for(let K of["404",...J.getFlatComponentTree.call(J)]){if(Bun.env.NODE_ENV==="test")break;let j=`${process.env.APP_DIR}`,x=await H(W).import(`${j}/views/${K}.tsx`);A[K]=x.default,b[K]=x?.OpenGraph,M[K]=x,D.push(h(K,`/app/views/${K}.tsx`))}let m=`{${D.join(",")}}`;return await B({getStyles:async(K,j)=>await y(Z,W,K,j?.layout),resolveIsland:(K)=>({src:`/${K}`,preload:[]}),bootstrapModules:[S],viewImportMap:A,viewModules:M,ogMap:b,loaders:m,cssManifest:{}})}catch(Y){return L(Y)}};return await Q(z,($)=>J.withGlobalMiddleware($,G,L))}}function a(J){try{return Bun.listen({hostname:"0.0.0.0",port:J,socket:{data(){}}}).stop(!0),!0}catch(Q){return Q?.code!=="EADDRINUSE"}}function T(J,Q=a){let W=24678+(J-5173);if(W>65471)W=24678;for(let Z=W;Z<W+64;Z++)if(Q(Z))return Z;throw Error(`Could not find a free port for Vite's HMR websocket: tried ${W}-${W+64-1}. Set one explicitly in gemi.config.ts as \`vite: { server: { ws: { port } } }\`.`)}import{createServer as t}from"http";var r=new Set(["vite-hmr","vite-ping"]);async function k(J){let Q=t((W,Z)=>{Z.writeHead(426,{"Content-Type":"text/plain"}),Z.end("Upgrade Required")});return await new Promise((W,Z)=>{Q.once("error",Z),Q.listen(J,"127.0.0.1",()=>{Q.off("error",Z),W()})}),Q}function P(J){if(!J||typeof J!=="object")return null;let W=J.server?.address?.();if(W&&typeof W==="object"&&"port"in W)return Number(W.port)||null;return null}function f(J){if(J.headers.get("upgrade")?.toLowerCase()!=="websocket")return!1;return r.has(J.headers.get("sec-websocket-protocol")??"")}var e=(J)=>typeof J==="string"?J:new Uint8Array(J);async function R(J,Q,W){let Z=new URL(J.url),z=J.headers.get("sec-websocket-protocol")??"vite-hmr",X={host:J.headers.get("host")??Z.host},L=J.headers.get("origin");if(L)X.origin=L;let G=new WebSocket(`ws://127.0.0.1:${W}${Z.pathname}${Z.search}`,{protocols:[z],headers:X});G.binaryType="arraybuffer";let $={upstream:G,early:[]};if(G.onmessage=(B)=>{let A=e(B.data);if($.browser)$.browser.send(A);else $.early.push(A)},G.onclose=(B)=>{$.browser?.close(JJ(B.code),B.reason)},G.onerror=()=>{},!await new Promise((B)=>{G.addEventListener("open",()=>B(!0),{once:!0}),G.addEventListener("close",()=>B(!1),{once:!0})}))return new Response("Vite refused the HMR websocket",{status:403});if(!Q.upgrade(J,{headers:{"Sec-WebSocket-Protocol":z},data:$}))return G.close(),new Response("WebSocket upgrade failed",{status:400});return}function JJ(J){if(J===1000||J>=1001&&J<=1003||J>=1007&&J<=1014)return J;if(J>=3000&&J<=4999)return J;return 1000}var g={open(J){let Q=J.data;for(let W of Q.early)J.send(W);if(Q.early=[],Q.browser=J,Q.upstream.readyState!==WebSocket.OPEN)J.close(1000)},message(J,Q){if(J.data.upstream.readyState===WebSocket.OPEN)J.data.upstream.send(Q)},close(J){let{upstream:Q}=J.data;if(Q.readyState<=WebSocket.OPEN)Q.close()}};var V=process.cwd(),ZJ=QJ(V,"app");if(!globalThis.__gemiErrorHooked)globalThis.__gemiErrorHooked=!0,process.on("unhandledRejection",(J)=>{console.error(J),O(J)}),process.on("uncaughtException",(J)=>{console.error(J),O(J)});async function _J(J,Q){let W=Number(process.env.PORT)||5173,Z=Boolean(globalThis.__gemiVite),z=globalThis.__gemiVite??=await WJ({configFile:!1,plugins:[w()],server:{middlewareMode:!0,port:W,ws:{server:await k(T(W))},allowedHosts:J.devAllowedHosts.call(J),watch:{ignored:($)=>{let U=$.split(/[/\\]/).pop()??"";return U===".env"||U.startsWith(".env.")}}},appType:"custom",resolve:{dedupe:["react","react-dom"]},optimizeDeps:{include:["react","react-dom","react-dom/client"]},ssr:{external:[...E]}});process.env.ROOT_DIR=V,process.env.APP_DIR=ZJ;let X=C(J,Q,z),L=P(z.config?.server?.ws),G=Bun.serve({port:W,fetch:($,U)=>{if(L!==null&&f($))return R($,U,L);return X($)},websocket:g});if(Z)H(z).clearCache();if(Z)if(globalThis.__gemiErrorActive&&globalThis.__gemiErrorPageServed)globalThis.__gemiErrorActive=!1,globalThis.__gemiErrorPageServed=!1,z.ws.send({type:"full-reload"});else globalThis.__gemiErrorActive=!1,z.ws.send({type:"custom",event:"http-reload"});else q({port:G.port,rootDir:V});return G}export{I as viteErrorPayload,_J as httpDev};
|
|
57
|
-
|
|
58
|
-
//# debugId=BDE7E65D52E6D0DE64756E2164756E21
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../server/httpDev.ts", "../server/devFetch.ts", "../server/renderErrorPage.ts", "../server/hmrPort.ts", "../server/hmrRelay.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import { join } from \"node:path\";\n\nimport { createServer } from \"vite\";\n\nimport { App } from \"../app\";\nimport gemiVite from \"../vite\";\nimport { Instrumentation } from \"./types\";\nimport { printStartupBanner } from \"./banner\";\nimport { GEMI_EXTERNAL_SPECIFIERS } from \"../internal/gemiExternals\";\nimport { createDevFetch, sendErrorToClient, ssrRunner } from \"./devFetch\";\nimport { resolveHmrPort } from \"./hmrPort\";\nimport {\n type HmrRelayData,\n hmrRelayHandler,\n hmrRelayPort,\n isHmrUpgrade,\n listenHmrServer,\n upgradeHmr,\n} from \"./hmrRelay\";\n\nexport { viteErrorPayload } from \"./devFetch\";\n\nconst rootDir = process.cwd();\nconst appDir = join(rootDir, \"app\");\n\n// `bun --hot` re-evaluates the module graph on every server-code change. A\n// syntax error or top-level throw in app code therefore fails during *module\n// load* — outside any request, and before `httpDev` re-runs — so Bun only\n// prints it to the console. Bun surfaces these as `unhandledRejection` (the\n// reload re-imports the entry and the failing dynamic import rejects), so hook\n// that here and forward it to the client. Registered once; process listeners\n// persist across reloads.\nif (!globalThis.__gemiErrorHooked) {\n globalThis.__gemiErrorHooked = true;\n process.on(\"unhandledRejection\", (reason) => {\n console.error(reason);\n sendErrorToClient(reason);\n });\n process.on(\"uncaughtException\", (err) => {\n console.error(err);\n sendErrorToClient(err);\n });\n}\n\nexport async function httpDev(app: App, instrumentation: Instrumentation) {\n // Same override the prod server honors (`httpProd.ts`). Read here rather than\n // inline at `Bun.serve` because the HMR port is derived from it.\n const httpPort = Number(process.env.PORT) || 5173;\n\n // `bun --hot` re-runs this module on every server-code change, so keep a\n // single Vite server on `globalThis` instead of spawning a new one (and a new\n // HMR socket) on each reload.\n const isReload = Boolean(globalThis.__gemiVite);\n const vite = (globalThis.__gemiVite ??= await createServer({\n // gemi owns the Vite setup — the app has no `vite.config.mjs` to discover.\n // Register the gemi plugin explicitly instead; it loads `gemi.config.ts` and\n // appends the app's Vite plugins (e.g. `@vitejs/plugin-react`, which serves\n // `/@react-refresh` and the HMR preamble referenced below).\n configFile: false,\n plugins: [gemiVite()],\n server: {\n middlewareMode: true,\n // The page's own port, so the HMR client's fallback (\"direct\") socket\n // also targets this server rather than Vite's default 5173.\n port: httpPort,\n // In middleware mode Vite would stand up a second HTTP server for the HMR\n // websocket on a fixed port — so two `gemi dev` processes fought over one\n // socket, and a proxy or tunnel, which carries only the page's port,\n // could not reach it at all. Hand Vite a loopback server instead, on a\n // port of this process's own (see `hmrPort.ts` for how it is chosen):\n // given a server, Vite tells the browser to connect to the page's origin,\n // and `Bun.serve` below relays that socket to it (see `hmrRelay.ts`).\n // `ws` and not the older `hmr`: `server.hmr.{port,host,…}` is\n // deprecated in Vite 8 and warns. An app overriding either one in\n // `gemi.config.ts` still wins — plugin config (where `gemi.config.ts`'s\n // `vite` block is applied) is merged over this inline config, and Vite's\n // own `hmr`→`ws` compat shim forwards the deprecated spelling here.\n ws: { server: await listenHmrServer(resolveHmrPort(httpPort)) },\n // Vite answers any host other than `localhost` and `*.localhost` with a\n // 403, which would block a `route.domains` root such as `lvh.me` and\n // every custom domain pointed here from `/etc/hosts`.\n allowedHosts: app.devAllowedHosts.call(app),\n // gemi reloads `.env` into process.env itself (see `watchEnv`). Stop Vite\n // from *also* watching env files: Vite's env-change handler restarts the\n // dev server, which closes the SSR module runner — but gemi keeps a single\n // Vite instance across `bun --hot` reloads, so an in-flight view import\n // hits the closed runner (\"Vite module runner has been closed\"). Ignoring\n // env files here only disables the restart; env *loading* at startup (and\n // `import.meta.env`) is unaffected.\n watch: {\n ignored: (file: string) => {\n const base = file.split(/[/\\\\]/).pop() ?? \"\";\n return base === \".env\" || base.startsWith(\".env.\");\n },\n },\n },\n appType: \"custom\",\n // Views are loaded through this SSR graph while the renderer\n // (react-dom/server in ViewRouteDispatcher) is imported by Bun.\n // Dedupe so Vite can never resolve a second React copy — a mismatch makes\n // the SSR dispatcher null (\"Invalid hook call\") after an HMR reload.\n resolve: { dedupe: [\"react\", \"react-dom\"] },\n // Pre-bundle the whole React surface the client uses in one pass. The client\n // imports `react-dom/client` (`init.tsx`) and `react-dom` (`createPortal` in\n // `HttpReload.tsx`); if only the first is discovered at startup, the first\n // request to a module using the second triggers a *second* optimize pass,\n // and the already-served page ends up importing a now-stale dep — surfacing\n // as \"does not provide an export named 't'\". Listing them up front bundles\n // them together so no re-optimization (and no version skew) happens.\n optimizeDeps: { include: [\"react\", \"react-dom\", \"react-dom/client\"] },\n // `gemi` is a linked package, so Vite would otherwise compile its own copy\n // into this graph — giving views a *different* `RouteStateContext` (and\n // other module-level singletons) than the Bun-loaded renderer's `Root`\n // provider, so `useRouteData()` reads the empty default (`i18n` undefined).\n // Externalizing makes view imports of `gemi/*` resolve to the one Bun\n // instance. Vite's `ssr.external` matches exact specifiers (subpaths are NOT\n // covered by the bare name, and regexes are ignored here), so every subpath\n // a view might import must be listed — see `internal/gemiExternals`, the\n // shared source of truth this and the SSR build (`vite/index.ts`) both use.\n ssr: {\n external: [...GEMI_EXTERNAL_SPECIFIERS],\n },\n }));\n\n process.env.ROOT_DIR = rootDir;\n process.env.APP_DIR = appDir;\n\n const devFetch = createDevFetch(app, instrumentation, vite);\n // `null` when an app's own `server.ws` in `gemi.config.ts` sent Vite's\n // websocket elsewhere; the browser then connects there directly.\n const relayPort = hmrRelayPort(vite.config?.server?.ws);\n const server = Bun.serve<HmrRelayData>({\n port: httpPort,\n fetch: (req, server) => {\n if (relayPort !== null && isHmrUpgrade(req)) {\n return upgradeHmr(req, server, relayPort);\n }\n return devFetch(req);\n },\n websocket: hmrRelayHandler,\n });\n\n // `bun --hot` re-evaluates its *whole* module graph on a server-code change —\n // node_modules included — so after a reload `react`, `react-dom/server` and the\n // Bun-loaded `gemi` are all fresh instances. This Vite server is not reloaded\n // with them (it is deliberately kept on `globalThis` above), and its SSR runner\n // still holds every view module it has evaluated — each bound, through the\n // externalized `gemi/*` imports, to the *previous* `gemi` and therefore the\n // previous `react`. The next render then sets the dispatcher on the new React\n // while a cached view calls hooks on the old one: \"Invalid hook call\", a null\n // `dispatcher.useContext` thrown from `useRouteData` inside a view nobody\n // touched. Editing a *view* never showed it — Vite's own watcher invalidates\n // that module, so it re-evaluates against the new instances. Editing a\n // server-only file (`app/config/*`, a feature declaration, a controller) is\n // the case with nothing to invalidate the views, so drop the evaluated\n // modules here, once per reload.\n //\n // Here and not before `Bun.serve`, with nothing awaited in between, because\n // both sides of the swap have to see a consistent pair. Until that call\n // returns the *previous* fetch handler is still serving — old dispatcher, old\n // `react-dom/server` — and a request landing there after an early clear would\n // re-evaluate its views against the *new* `gemi`: the same mismatch, reversed.\n // After it, the new handler is live and must not be given the stale ones. The\n // two statements are synchronous neighbours, so no request can be dispatched\n // between them.\n //\n // Only the *evaluated* modules go: the server-side transform cache is\n // untouched, so this costs a re-evaluation and not a re-transform. Clearing\n // the module graph as well would not have been enough anyway — externalized\n // deps (`gemi`, and React through it) are cached in the runner by URL and\n // carry no invalidation flag, which is exactly where the stale React hides.\n if (isReload) {\n ssrRunner(vite).clearCache();\n }\n\n // On a reload `app` has already been rebuilt with the new code and Bun.serve\n // above has swapped in the new fetch handler, so the updated controllers are\n // live *now*. Tell the client to re-run its queries only at this point —\n // firing it from Vite's file watcher instead races Bun's reload and leaves\n // the UI one change behind.\n if (isReload) {\n // We got here, so the reload succeeded. Recover from any error that was\n // showing: a standalone error page must be fully reloaded to get the app\n // back, whereas an overlay pushed onto a live page is cleared by the\n // client's `http-reload` handler (no jarring full-page reload). A normal\n // reload just re-runs client queries against the now-live controllers.\n if (globalThis.__gemiErrorActive && globalThis.__gemiErrorPageServed) {\n globalThis.__gemiErrorActive = false;\n globalThis.__gemiErrorPageServed = false;\n vite.ws.send({ type: \"full-reload\" });\n } else {\n globalThis.__gemiErrorActive = false;\n vite.ws.send({ type: \"custom\", event: \"http-reload\" });\n }\n } else {\n // First start (not a `bun --hot` reload) — print the startup banner once.\n printStartupBanner({ port: server.port, rootDir });\n }\n\n return server;\n}\n",
|
|
6
|
-
"import { stringEraRefusal } from \"../http/Error\";\nimport { join } from \"node:path\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nimport type { RunnableDevEnvironment, ViteDevServer } from \"vite\";\n\nimport type { App } from \"../app\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport { renderErrorPage } from \"./renderErrorPage\";\nimport { createDevStyles } from \"./styles\";\nimport type { Instrumentation } from \"./types\";\n\n// Run a Web `Request` through Vite's Connect middleware.\n// Resolves to a `Response` when Vite handles the request (module transforms,\n// assets, the HMR client, ...), or `null` when it calls `next()` — which, with\n// `appType: \"custom\"`, it does for everything it doesn't own.\nfunction viteMiddleware(vite: ViteDevServer, request: Request): Promise<Response | null> {\n const url = new URL(request.url);\n\n const req = new IncomingMessage(new Socket());\n req.url = url.pathname + url.search;\n req.method = request.method;\n req.headers = Object.fromEntries(request.headers);\n\n const res = new ServerResponse(req);\n const chunks: Buffer[] = [];\n\n return new Promise((resolve) => {\n res.write = ((chunk: any) => {\n if (chunk) chunks.push(Buffer.from(chunk));\n return true;\n }) as typeof res.write;\n\n res.end = ((chunk?: any) => {\n if (chunk && typeof chunk !== \"function\") chunks.push(Buffer.from(chunk));\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(res.getHeaders())) {\n if (value == null) continue;\n for (const v of Array.isArray(value) ? value : [value]) {\n headers.append(key, String(v));\n }\n }\n\n resolve(\n new Response(chunks.length ? Buffer.concat(chunks) : null, {\n status: res.statusCode,\n headers,\n }),\n );\n return res;\n }) as typeof res.end;\n\n vite.middlewares(req, res, () => resolve(null));\n });\n}\n\ndeclare global {\n // Created once and reused across `bun --hot` reloads (see below).\n var __gemiVite: ViteDevServer | undefined;\n // Guards one-time registration of the process error hooks across reloads.\n var __gemiErrorHooked: boolean | undefined;\n // An error overlay is currently showing on the client (clear it on recovery).\n var __gemiErrorActive: boolean | undefined;\n // We served a standalone error *page* (not just a pushed overlay), so the\n // visible document has no live app — recovery needs a full page reload.\n var __gemiErrorPageServed: boolean | undefined;\n}\n\n// Build the `> 1 | ...\\n | ^` codeframe Vite's overlay renders — must\n// match its `codeframeRE` (a `<line> | <text>` line followed by a `| ^` line,\n// each ending in a newline).\nfunction codeFrame(lineText: string, line: number, column: number) {\n const gutter = String(line);\n const pad = \" \".repeat(gutter.length);\n const caret = \" \".repeat(Math.max(0, column - 1)) + \"^\";\n return `${gutter} | ${lineText}\\n${pad} | ${caret}\\n`;\n}\n\n// Normalize whatever Bun/JS throws into the { message, stack, frame, loc }\n// shape Vite's error overlay consumes. Two cases matter:\n// - a real `Error` (runtime top-level throw) carries a proper `.stack`;\n// - a Bun `BuildMessage` (syntax error) has NO `.stack`, only a `.position`\n// ({ file, line, column, lineText }) — so synthesize a codeframe + loc from\n// it, otherwise the overlay shows a bare message with no location.\n// (An `Error` instance also JSON-stringifies to `{}`, so fields are copied by\n// hand either way.)\nexport function viteErrorPayload(err: any) {\n if (err && typeof err === \"object\") {\n const pos = err.position;\n if (pos && typeof pos === \"object\" && typeof pos.file === \"string\") {\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: \"\",\n frame:\n typeof pos.lineText === \"string\"\n ? codeFrame(pos.lineText, pos.line, pos.column)\n : undefined,\n loc: { file: pos.file, line: pos.line, column: pos.column },\n };\n }\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: typeof err.stack === \"string\" ? err.stack : \"\",\n };\n }\n return { message: String(err), stack: \"\" };\n}\n\n// Push an error into the browser via Vite's HMR socket. `__gemiVite` persists\n// across `bun --hot` reloads, so this works even when the reload that produced\n// the error never got far enough to (re)run `httpDev`.\nexport function sendErrorToClient(err: any) {\n const vite = globalThis.__gemiVite;\n if (!vite) return;\n vite.ws.send({ type: \"error\", err: viteErrorPayload(err) as any });\n globalThis.__gemiErrorActive = true;\n}\n\n/**\n * The SSR environment's module runner — what `vite.ssrLoadModule` is a thin\n * (and, in Vite 8, deprecated) wrapper over. Going through it directly is what\n * gives `httpDev` a handle on the evaluated-module cache it has to drop after a\n * `bun --hot` reload; `ssrLoadModule` keeps its own runner private.\n *\n * Duck-typed rather than `isRunnableDevEnvironment(environment)`: this server\n * outlives the module instance that created it, and after a reload the freshly\n * evaluated `vite` brings a *new* `RunnableDevEnvironment` class object, so the\n * `instanceof` that predicate performs is false for a perfectly runnable\n * environment. (The same one-copy-per-reload rule this whole dance is about.)\n */\nexport function ssrRunner(vite: ViteDevServer) {\n const environment = vite.environments.ssr as RunnableDevEnvironment;\n if (typeof environment?.runner?.import !== \"function\") {\n throw new Error(\"gemi dev requires a runnable Vite SSR environment.\");\n }\n return environment.runner;\n}\n\n/**\n * The dev document's single bootstrap module. It loads, in this order:\n *\n * 1. `/refresh.js` — the React Refresh preamble;\n * 2. `/@vite/client` — the HMR client;\n * 3. `/app/client.tsx` — the app.\n *\n * One module, because React emits every `bootstrapModules` entry as\n * `<script type=\"module\" async>`, and async module scripts run in whatever\n * order they finish loading. The preamble has to have installed\n * `window.$RefreshReg$` before any component module evaluates, or\n * `@vitejs/plugin-react`'s transform throws \"can't detect preamble\" and the\n * app never hydrates. Awaiting each `import()` is what makes the order a\n * guarantee rather than a race.\n *\n * The preamble and the HMR client are each caught: an app without\n * `@vitejs/plugin-react` has no `/@react-refresh` and needs no preamble, and a\n * broken HMR client must not stop the app from booting. The app's own import\n * is not caught, so its errors surface as they would from a script tag.\n */\nexport const DEV_ENTRY_PATH = \"/@gemi/dev-entry.js\";\n\nexport const DEV_ENTRY_SOURCE = `const report = (error) => console.error(error);\nawait import(\"/refresh.js\").catch(report);\nawait import(\"/@vite/client\").catch(report);\nawait import(\"/app/client.tsx\");\n`;\n\n/**\n * Installs the React Refresh preamble, as `@vitejs/plugin-react`'s own\n * `index.html` transform would.\n *\n * The runtime is imported by an origin-relative URL. An absolute one, built\n * from the request URL the server sees, breaks behind a TLS-terminating proxy\n * or tunnel: the browser is on `https://<tunnel>` while the server sees\n * `http://localhost:5173`, so the import is blocked as mixed content or points\n * at a host the browser cannot reach.\n */\nexport const REFRESH_PREAMBLE_SOURCE = `import RefreshRuntime from \"/@react-refresh\";\nRefreshRuntime.injectIntoGlobalHook(window);\nwindow.$RefreshReg$ = () => {};\nwindow.$RefreshSig$ = () => (type) => type;\nwindow.__vite_plugin_react_preamble_installed__ = true;\n`;\n\n/**\n * The scripts the dev document loads that nothing on disk backs: the\n * bootstrap entry above, `/refresh.js` with the React Refresh preamble, and\n * `/render-error.js`, which the dev error page loads. `null` for any other\n * path.\n *\n * Answered inside the global middleware, not in front of it as they were. They\n * have no production counterpart, but a gate that must hold in dev as well,\n * one that refuses traffic without a header, is only complete if nothing the\n * dev server answers goes around it.\n */\nfunction devScript(req: Request): Response | null {\n const { pathname } = new URL(req.url);\n const script = (source: string) =>\n new Response(source, {\n headers: {\n \"Content-Type\": \"application/javascript\",\n },\n });\n if (pathname === DEV_ENTRY_PATH) {\n return script(DEV_ENTRY_SOURCE);\n }\n if (pathname.startsWith(\"/render-error.js\")) {\n return script(\"window.render_error = true\");\n }\n if (pathname.startsWith(\"/refresh.js\")) {\n return script(REFRESH_PREAMBLE_SOURCE);\n }\n return null;\n}\n\n/**\n * The dev server's `fetch` handler, apart from `Bun.serve` and from creating\n * Vite, so a test can hand it a stub Vite server and drive it with plain\n * `Request`s. `httpDev` is the only other caller. This module has no import\n * side effects, unlike `httpDev.ts`, which installs process-wide error hooks.\n */\nexport function createDevFetch(\n app: App,\n instrumentation: Instrumentation,\n vite: ViteDevServer,\n): (req: Request) => Promise<Response> {\n const appDir = join(process.cwd(), \"app\");\n\n return async (req) => {\n const { pathname } = new URL(req.url);\n const errorResponse = (err: any): Response => {\n // Errors thrown *while handling a request* (a controller throwing, a\n // failing view import, ...) never hit `httpDev`'s module-load hooks,\n // so surface them here: forward to the overlay for any already-open\n // page, and render an error page for this response so a fresh load\n // (which has no live HMR socket yet) still shows the failure.\n console.error(err);\n vite.ssrFixStacktrace?.(err);\n sendErrorToClient(err);\n\n if (isApiPath(pathname)) {\n return new Response(\n JSON.stringify({\n error: stringEraRefusal(\"server_error\", err?.message ?? String(err), 500),\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n // This document has no live app (so no HttpReload listener to clear the\n // overlay) — remember that, so recovery forces a full page reload.\n globalThis.__gemiErrorPageServed = true;\n return new Response(renderErrorPage(viteErrorPayload(err)), {\n status: 500,\n headers: { \"Content-Type\": \"text/html\" },\n });\n };\n const requestHandler = async (req: Request): Promise<Response> => {\n const script = devScript(req);\n if (script) {\n return script;\n }\n try {\n const handler = app.fetch.bind(app);\n const result = (await viteMiddleware(vite, req)) ?? (await handler(req));\n if (result instanceof Response) {\n return result;\n }\n\n const viewImportMap = {};\n const ogMap = {};\n const viewModules = {};\n const template = (viewName: string, path: string) =>\n `\"${viewName}\": () => import(\"${path}\")`;\n const templates = [];\n\n for (const fileName of [\"404\", ...app.getFlatComponentTree.call(app)]) {\n if (process.env.NODE_ENV === \"test\") {\n break;\n }\n const appDir = `${process.env.APP_DIR}`;\n const mod = await ssrRunner(vite).import(`${appDir}/views/${fileName}.tsx`);\n\n viewImportMap[fileName] = mod.default;\n ogMap[fileName] = mod?.OpenGraph;\n // The whole module, so a streaming render can put the view's\n // `Loading`/`Error` exports into the shell it sends.\n viewModules[fileName] = mod;\n // Emit a root-relative URL (`/app/views/Foo.tsx`), NOT the absolute\n // filesystem path the runner import above uses. The browser's\n // `window.loaders` preload and `client.tsx`'s `import.meta.glob` map\n // must import the exact same URL — otherwise Vite serves the module\n // under two URLs (`/app/views/Foo.tsx` vs `/Users/.../app/views/Foo.tsx`)\n // and loads/instantiates the view twice.\n templates.push(template(fileName, `/app/views/${fileName}.tsx`));\n }\n\n const loaders = `{${templates.join(\",\")}}`;\n\n return await result({\n getStyles: async (currentViews: string[], options?: { static?: boolean; layout?: string }) =>\n await createDevStyles(appDir, vite, currentViews, options?.layout),\n // Vite serves app files by their root-relative path.\n resolveIsland: (moduleKey: string) => ({ src: `/${moduleKey}`, preload: [] }),\n bootstrapModules: [DEV_ENTRY_PATH],\n viewImportMap,\n viewModules,\n ogMap,\n loaders,\n cssManifest: {},\n });\n } catch (err: any) {\n return errorResponse(err);\n }\n };\n\n // In front of Vite's middleware, the dev scripts and the app, as\n // `httpProd` puts the global middleware in front of its static files, so a\n // check that passes here passes there. A throw from it is answered like\n // one from a route. Vite's HMR websocket is the one thing it cannot cover:\n // its upgrade is relayed to Vite by `Bun.serve` (see `hmrRelay.ts`) before\n // this handler runs, and Vite checks the token and host itself.\n return await instrumentation(req, (req) =>\n app.withGlobalMiddleware(req, requestHandler, errorResponse),\n );\n };\n}\n",
|
|
7
|
-
"function cleanupTerminalText(text) {\n return (\n text\n // Remove ANSI escape sequences (colors, formatting)\n .replace(/\\x1b\\[[0-9;]*m/g, \"\")\n // Remove ANSI escape sequences with different format\n .replace(/\\[[0-9;]*m/g, \"\")\n // Remove excessive whitespace and normalize line breaks\n .replace(/\\n\\s*\\n/g, \"\\n\")\n // Trim each line\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .join(\"\\n\")\n .trim()\n );\n}\n\nexport function renderErrorPage(err: any) {\n return `\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1.0\"\n />\n\n <title>Error</title>\n <style>\n body {\n font-family: Arial, sans-serif;\n padding: 20px;\n }\n h1 {\n color: red;\n }\n </style>\n </head>\n <body>\n <div id=\"overlay\"></div>\n <script type=\"module\" src=\"/refresh.js\"></script>\n <script type=\"module\" src=\"/@vite/client\"></script>\n <script>\n ${cleanupTerminalText.toString()}\n const err = ${JSON.stringify(err, Object.getOwnPropertyNames(err), 2)}\n\n window.addEventListener('load', () => {\n const container = document.getElementById('overlay')\n const ErrorOverlay = customElements.get('vite-error-overlay')\n if (ErrorOverlay) {\n const overlay = new ErrorOverlay({ ...err, message: cleanupTerminalText(err.message) });\n container.appendChild(overlay)\n }\n })\n </script>\n </body>\n</html>\n`;\n}\n",
|
|
8
|
-
"// Vite's HMR websocket needs a port of its own, and in middleware mode Vite\n// always picks the same one.\n//\n// `httpDev` runs Vite with `middlewareMode: true`, so Vite has no HTTP server of\n// its own to hang the websocket off — it stands up a second HTTP server just for\n// the upgrade. When nothing names a port, that server binds Vite's default 24678\n// in *every* `gemi dev` process. `PORT` moves the Bun server and nothing else, so\n// a second dev server logs\n//\n// WebSocket server error: Port undefined is already in use\n//\n// and carries on with a dead socket. (Vite logs that failure rather than throwing\n// — which is why the symptom is not a crash but pages that hot-reload on the\n// *other* checkout's edits: their `/@vite/client` was told 24678, and 24678 is\n// the first server's.) So gemi names the port instead of letting Vite default it.\n//\n// Why derive from the HTTP port rather than just scan for a free one: two dev\n// servers must already differ in `PORT` to run at all, so deriving makes their\n// HMR ports differ *before* either one binds anything. A scan alone would hand\n// both the same port when they start at the same moment, each having probed\n// before the other bound. The scan is still here, for the port being taken by\n// something that is not a gemi dev server.\n\nconst VITE_DEFAULT_HTTP_PORT = 5173;\nconst VITE_DEFAULT_HMR_PORT = 24678;\n\n// A port is 16 bits.\nconst MAX_PORT = 65535;\n\n// How far to walk up from the derived port before giving up. Large enough that\n// only a pathological machine exhausts it, small enough to fail in well under a\n// second rather than appearing to hang.\nconst SEARCH_WINDOW = 64;\n\n/**\n * Bind-test a port the same way Vite will.\n *\n * Vite calls `wsHttpServer.listen(port, host)` with no host unless one is\n * configured, so its websocket server takes the wildcard address — which is what\n * this binds too. The match matters: a wildcard bind collides with a wildcard\n * *or* a loopback holder, while a loopback bind only collides with loopback. A\n * process holding `127.0.0.1:P` alone therefore reads as free here, correctly —\n * Vite would fail to bind `*:P` against it, but nothing in gemi makes Vite bind\n * loopback-only, so that case cannot arise from a second `gemi dev`.\n *\n * Only `EADDRINUSE` counts as taken. Any other failure — a permission error, an\n * unroutable address — is not something a different port would fix, so it is\n * reported free and left for Vite to surface.\n */\nfunction isPortFree(port: number): boolean {\n try {\n const listener = Bun.listen({\n hostname: \"0.0.0.0\",\n port,\n socket: { data() {} },\n });\n // `true` closes active connections too. There are none — nothing has been\n // told this port exists yet — but it also makes the close synchronous, so\n // the port is released before the next probe or before Vite binds it.\n listener.stop(true);\n return true;\n } catch (error) {\n return (error as { code?: string })?.code !== \"EADDRINUSE\";\n }\n}\n\n/**\n * Pick the port for Vite's HMR websocket, given the port the dev server's HTTP\n * side is on.\n *\n * `5173` returns `24678` — Vite's two defaults stay paired, so a single dev\n * server behaves exactly as it did before, and anything pointed at 24678 (a\n * firewall rule, a container port mapping, a note in a README) keeps working.\n * Every other HTTP port is offset by the same distance, so distinct `PORT`s\n * always yield distinct HMR ports.\n *\n * @param isFree Injected for tests. Production callers use the bind test above.\n */\nexport function resolveHmrPort(\n httpPort: number,\n isFree: (port: number) => boolean = isPortFree,\n): number {\n let start = VITE_DEFAULT_HMR_PORT + (httpPort - VITE_DEFAULT_HTTP_PORT);\n\n // A high `PORT` can push the derived port past the top of the range — or so\n // close to it that the walk would run off the end. Fall back to the default\n // and let the scan sort it out; being *adjacent* to another server's port is\n // fine, landing *on* it is what has to be avoided, and the scan does that.\n //\n // There is deliberately no matching floor. The offset is only -5173, so the\n // lowest a real HTTP port can derive is 19505 (from `PORT=0`) — a guard for\n // the bottom of the range would be a branch no input can take.\n if (start > MAX_PORT - SEARCH_WINDOW) {\n start = VITE_DEFAULT_HMR_PORT;\n }\n\n for (let port = start; port < start + SEARCH_WINDOW; port++) {\n if (isFree(port)) return port;\n }\n\n throw new Error(\n `Could not find a free port for Vite's HMR websocket: tried ${start}-${\n start + SEARCH_WINDOW - 1\n }. Set one explicitly in gemi.config.ts as \\`vite: { server: { ws: { port } } }\\`.`,\n );\n}\n",
|
|
9
|
-
"import { createServer, type Server as NodeServer } from \"node:http\";\n\nimport type { Server, ServerWebSocket, WebSocketHandler } from \"bun\";\n\n// Vite's HMR websocket, carried on the dev server's own port.\n//\n// In middleware mode Vite has no HTTP server of its own, so by default it\n// stands up a second one for the websocket, on a second port (see\n// `hmrPort.ts`), and tells the browser to connect to `<page host>:<that port>`.\n// A reverse proxy or tunnel (ngrok, a container port mapping, a phone on the\n// LAN through https) only carries the port the page came from, so HMR could\n// not connect there, and the client logged connection failures forever.\n//\n// Vite can attach its websocket to a server it is handed (`server.ws.server`)\n// instead, and then tells the browser to connect to the page's own origin. That\n// server has to be a Node `http.Server`; the dev server is `Bun.serve`. So:\n//\n// - the Node server Vite is handed listens on loopback only, on the port\n// `resolveHmrPort` picked, and answers nothing but websocket upgrades;\n// - `Bun.serve` accepts the browser's upgrade on the page's origin and relays\n// frames both ways to that loopback server.\n//\n// The relay forwards the browser's `Host` and `Origin` and the request's query\n// (the `token`), so Vite still runs its own host and token checks against what\n// the browser actually sent.\n\n/** The subprotocols Vite's client opens its sockets with. */\nconst VITE_PROTOCOLS = new Set([\"vite-hmr\", \"vite-ping\"]);\n\n/**\n * Start the loopback Node server Vite attaches its HMR websocket to.\n * Everything but an upgrade gets `426 Upgrade Required`, as Vite's own\n * websocket server answers.\n */\nexport async function listenHmrServer(port: number): Promise<NodeServer> {\n const server = createServer((_req, res) => {\n res.writeHead(426, { \"Content-Type\": \"text/plain\" });\n res.end(\"Upgrade Required\");\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n return server;\n}\n\n/**\n * The loopback port to relay to, read from the config Vite actually resolved,\n * so an app that set its own `server.ws` in `gemi.config.ts` is relayed to\n * where Vite really is, or not relayed at all. `null` when Vite was not given\n * a server (its websocket is then on a port of its own, and the client goes\n * there directly) or when HMR is off.\n */\nexport function hmrRelayPort(wsConfig: unknown): number | null {\n if (!wsConfig || typeof wsConfig !== \"object\") return null;\n const server = (wsConfig as { server?: { address?: () => unknown } }).server;\n const address = server?.address?.();\n if (address && typeof address === \"object\" && \"port\" in address) {\n return Number((address as { port: number }).port) || null;\n }\n return null;\n}\n\n/** Whether a request is the Vite client opening its HMR (or ping) socket. */\nexport function isHmrUpgrade(req: Request): boolean {\n if (req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") return false;\n return VITE_PROTOCOLS.has(req.headers.get(\"sec-websocket-protocol\") ?? \"\");\n}\n\nexport type HmrRelayData = {\n /** The socket to Vite, already open when the browser's is accepted. */\n upstream: WebSocket;\n /** Frames Vite sent before the browser's socket opened (its `connected`). */\n early: (string | Uint8Array)[];\n browser?: ServerWebSocket<HmrRelayData>;\n};\n\ntype Frame = string | Uint8Array;\n\nconst frameOf = (data: unknown): Frame =>\n typeof data === \"string\" ? data : new Uint8Array(data as ArrayBuffer);\n\n/**\n * Open the socket to Vite first, and accept the browser's upgrade only once\n * Vite has accepted it. Returns `undefined` once Bun has taken the request\n * over, or a refusal.\n *\n * The order matters. Vite refuses a socket whose host is not in\n * `allowedHosts`, or a cross-origin one without its token. Had the browser's\n * socket been accepted first and closed when Vite refused, the client would\n * read that as \"server connection lost\", ping (which Vite always answers),\n * and reload the page, forever. Refused before it opens, the client logs one\n * \"failed to connect to websocket\" and the page keeps working.\n */\nexport async function upgradeHmr(\n req: Request,\n server: Server<HmrRelayData>,\n port: number,\n): Promise<Response | undefined> {\n const url = new URL(req.url);\n const protocol = req.headers.get(\"sec-websocket-protocol\") ?? \"vite-hmr\";\n // `Host` is what Vite's `allowedHosts` check reads; the URL's host is the\n // same value `Bun.serve` derived it from.\n const headers: Record<string, string> = {\n host: req.headers.get(\"host\") ?? url.host,\n };\n const origin = req.headers.get(\"origin\");\n if (origin) headers.origin = origin;\n\n const upstream = new WebSocket(\n `ws://127.0.0.1:${port}${url.pathname}${url.search}`,\n {\n protocols: [protocol],\n headers,\n } as any,\n );\n upstream.binaryType = \"arraybuffer\";\n const data: HmrRelayData = { upstream, early: [] };\n\n upstream.onmessage = (event) => {\n const frame = frameOf(event.data);\n if (data.browser) data.browser.send(frame);\n else data.early.push(frame);\n };\n upstream.onclose = (event) => {\n data.browser?.close(sendableCloseCode(event.code), event.reason);\n };\n upstream.onerror = () => {\n // A `close` follows; it ends the browser's socket if there is one.\n };\n\n const opened = await new Promise<boolean>((resolve) => {\n upstream.addEventListener(\"open\", () => resolve(true), { once: true });\n upstream.addEventListener(\"close\", () => resolve(false), { once: true });\n });\n if (!opened) {\n return new Response(\"Vite refused the HMR websocket\", { status: 403 });\n }\n\n const upgraded = server.upgrade(req, {\n // The browser fails a connection whose response does not echo the\n // subprotocol it asked for.\n headers: { \"Sec-WebSocket-Protocol\": protocol },\n data,\n });\n if (!upgraded) {\n upstream.close();\n return new Response(\"WebSocket upgrade failed\", { status: 400 });\n }\n return undefined;\n}\n\n// A close code that may be sent in a close frame. 1005, 1006 and 1015 are\n// reported locally and never sent.\nfunction sendableCloseCode(code: number): number {\n if (\n code === 1000 ||\n (code >= 1001 && code <= 1003) ||\n (code >= 1007 && code <= 1014)\n ) {\n return code;\n }\n if (code >= 3000 && code <= 4999) return code;\n return 1000;\n}\n\n/** `Bun.serve`'s `websocket` option: relays frames to and from Vite. */\nexport const hmrRelayHandler: WebSocketHandler<HmrRelayData> = {\n open(ws: ServerWebSocket<HmrRelayData>) {\n const data = ws.data;\n for (const frame of data.early) ws.send(frame);\n data.early = [];\n data.browser = ws;\n // Vite may have hung up while the upgrade was in flight.\n if (data.upstream.readyState !== WebSocket.OPEN) ws.close(1000);\n },\n message(ws: ServerWebSocket<HmrRelayData>, message) {\n if (ws.data.upstream.readyState === WebSocket.OPEN) {\n ws.data.upstream.send(message);\n }\n },\n close(ws: ServerWebSocket<HmrRelayData>) {\n const { upstream } = ws.data;\n if (upstream.readyState <= WebSocket.OPEN) upstream.close();\n },\n};\n"
|
|
10
|
-
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L,QAAS,CAAC,IAAiB,CACzB,IAAM,EAAO,EAAK,MAAM,OAAO,EAAE,IAAI,GAAK,GAC1C,OAAO,IAAS,QAAU,EAAK,WAAW,OAAO,EAErD,CACF,EACA,QAAS,SAKT,QAAS,CAAE,OAAQ,CAAC,QAAS,WAAW,CAAE,EAQ1C,aAAc,CAAE,QAAS,CAAC,QAAS,YAAa,kBAAkB,CAAE,EAUpE,IAAK,CACH,SAAU,CAAC,GAAG,CAAwB,CACxC,CACF,CAAC,EAED,QAAQ,IAAI,SAAW,EACvB,QAAQ,IAAI,QAAU,GAEtB,IAAM,EAAW,EAAe,EAAK,EAAiB,CAAI,EAGpD,EAAY,EAAa,EAAK,QAAQ,QAAQ,EAAE,EAChD,EAAS,IAAI,MAAoB,CACrC,KAAM,EACN,MAAO,CAAC,EAAK,IAAW,CACtB,GAAI,IAAc,MAAQ,EAAa,CAAG,EACxC,OAAO,EAAW,EAAK,EAAQ,CAAS,EAE1C,OAAO,EAAS,CAAG,GAErB,UAAW,CACb,CAAC,EA+BD,GAAI,EACF,EAAU,CAAI,EAAE,WAAW,EAQ7B,GAAI,EAMF,GAAI,WAAW,mBAAqB,WAAW,sBAC7C,WAAW,kBAAoB,GAC/B,WAAW,sBAAwB,GACnC,EAAK,GAAG,KAAK,CAAE,KAAM,aAAc,CAAC,EAEpC,gBAAW,kBAAoB,GAC/B,EAAK,GAAG,KAAK,CAAE,KAAM,SAAU,MAAO,aAAc,CAAC,EAIvD,OAAmB,CAAE,KAAM,EAAO,KAAM,SAAQ,CAAC,EAGnD,OAAO",
|
|
12
|
-
"debugId": "BDE7E65D52E6D0DE64756E2164756E21",
|
|
13
|
-
"names": []
|
|
14
|
-
}
|
package/dist/chunk-gdsby5jh.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{H as A}from"./chunk-zys7kecf.js";import{V as I}from"./chunk-qz9aaw5x.js";import"./chunk-g7fr2cy2.js";import{$ as f}from"./chunk-jc4j61xb.js";import{rh as t,vh as T}from"./chunk-wvwee7dn.js";var N=t(I(),1),a=t(f(),1),d=t(A(),1);import{readFileSync as g}from"fs";var c=(e)=>async(s)=>{e.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");let{roleArn:o,roleSessionName:r,webIdentityToken:i,providerId:n,policyArns:m,policy:S,durationSeconds:l}=e,{roleAssumerWithWebIdentity:E}=e;if(!E){let{getDefaultRoleAssumerWithWebIdentity:p}=await import("./chunk-t3qw9syt.js").then((m)=>t(m.default,1));E=p({...e.clientConfig,credentialProviderLogger:e.logger,parentClientConfig:{...s?.callerClientConfig,...e.parentClientConfig}},e.clientPlugins)}return E({RoleArn:o,RoleSessionName:r??`aws-sdk-js-session-${Date.now()}`,WebIdentityToken:i,ProviderId:n,PolicyArns:m,Policy:S,DurationSeconds:l})};var _="AWS_WEB_IDENTITY_TOKEN_FILE",O="AWS_ROLE_ARN",k="AWS_ROLE_SESSION_NAME",L=(e={})=>async(s)=>{e.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");let o=e?.webIdentityTokenFile??process.env[_],r=e?.roleArn??process.env[O],i=e?.roleSessionName??process.env[k];if(!o||!r)throw new a.CredentialsProviderError("Web identity configuration not specified",{logger:e.logger});let n=await c({...e,webIdentityToken:d.externalDataInterceptor?.getTokenRecord?.()[o]??g(o,{encoding:"ascii"}),roleArn:r,roleSessionName:i})(s);if(o===process.env[_])N.setCredentialFeature(n,"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN","h");return n};export{c as fromWebToken,L as fromTokenFile};
|
|
3
|
-
|
|
4
|
-
//# debugId=094C73B5ABC20B2664756E2164756E21
|
package/dist/chunk-ngw4xzrt.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Ag as K,Dg as W,tg as X}from"./chunk-vsnmdtrs.js";import{AsyncLocalStorage as U}from"async_hooks";var v=new U;function E(){return v.getStore()?.tx}function S(){return v.getStore()?.connection??K}function g(j,q){let B=v.getStore();if(S()===j)return q();return y(j),v.run({...B,depth:B?.depth??0,connection:j===K?void 0:j},q)}function y(j){let q=v.getStore();if(q?.tx===void 0)return;let B=q.connection??K;if(B===j)return;throw new W(B,j)}function k(j){let q=v.getStore();if(q?.tx===void 0||q.afterCommit===void 0)return!1;return q.afterCommit.push(j),!0}function O(j){let q=v.getStore();if(q?.tx===void 0||q.commitDependsOn===void 0)return!1;return q.commitDependsOn.push(j),!0}class F extends Error{constructor(j){super(`A statement this transaction depended on failed after being issued on it, so the transaction rolled back instead of committing: ${j instanceof Error?j.message:String(j)}`,{cause:j});this.name="TransactionDependencyError"}}async function R(j,q){if(j.length===q)return;let z=(await Promise.allSettled(j.slice(q))).find((G)=>G.status==="rejected");if(z)throw new F(z.reason)}function h(){let j=v.getStore();return j?.tx===void 0?null:j.depth}function N(){return v.getStore()?.system===!0}function T(j){let q=v.getStore();return v.run({...q,depth:q?.depth??0,system:!0},j)}function x(j){return v.getStore()?.trashed?.get(j)}function p(j,q,B){let z=v.getStore(),G=new Map(z?.trashed);return G.set(j,q),v.run({...z,depth:z?.depth??0,trashed:G},B)}function l(){return v.getStore()?.actor}function f(j,q){let B=v.getStore();return v.run({...B,depth:B?.depth??0,system:!1,actor:{user:j??null}},q)}function L(j){if(Bun.env.NODE_ENV!=="development")return null;if(j===!1)return null;if(j===void 0)return X;if(!Number.isFinite(j)||j<=0)return X;return j}function _(j){let q=L(j);if(q===null)return()=>{};let B=Error("transaction opened here"),z=setTimeout(()=>{let G=B.stack?.split(`
|
|
3
|
-
`).slice(1).join(`
|
|
4
|
-
`)??"";console.warn(`[gemi] A database transaction has not settled after ${q}ms. It `+"reserves a pooled connection until it does \u2014 check for network or "+`filesystem I/O inside the callback, and move it outside the transaction if you find any.
|
|
5
|
-
${G}
|
|
6
|
-
(development only; set database.slowTransactionThreshold to change the threshold, or false to switch this off)`)},q);return z.unref?.(),()=>clearTimeout(z)}async function b(j,q){if(j.length===0)return;await v.run({...q,tx:void 0,afterCommit:void 0,commitDependsOn:void 0,depth:q?.depth??0},async()=>{for(let B of j)try{await B()}catch(z){console.error("An after-commit callback threw. The transaction it was waiting on had already committed and stays committed, and the callbacks after it still ran.",z)}})}function C(j,q,B){let z=v.getStore(),G=B?.connection??K;if(y(G),z?.tx){let J=z.afterCommit,Q=J?.length??0,P=z.commitDependsOn,M=P?.length??0;return z.tx.savepoint((V)=>{let H=V;return v.run({...z,tx:H,depth:z.depth+1},async()=>{let I=await q(H);if(P)await R(P,M);return I})}).catch((V)=>{if(J)J.length=Q;if(P)P.length=M;throw V})}let Y=_(B?.slowTransactionThreshold),Z=[],$=[];try{return j.begin((J)=>v.run({...z,tx:J,depth:0,connection:G===K?void 0:G,afterCommit:Z,commitDependsOn:$},async()=>{let Q=await q(J);return await R($,0),Q})).finally(Y).then(async(J)=>{return await b(Z,z),J})}catch(J){throw Y(),J}}
|
|
7
|
-
export{v as bg,E as cg,S as dg,g as eg,y as fg,k as gg,O as hg,F as ig,h as jg,N as kg,T as lg,x as mg,p as ng,l as og,f as pg,C as qg};
|
|
8
|
-
|
|
9
|
-
//# debugId=BBCAC2B67205EAFF64756E2164756E21
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../orm/context.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import type { SQL, TransactionSQL } from \"bun\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { SLOW_TRANSACTION_THRESHOLD } from \"../database/config\";\nimport {\n CrossConnectionTransactionError,\n DEFAULT_CONNECTION,\n} from \"../database/Connection\";\n\n/**\n * The ambient transaction: the ORM's own `AsyncLocalStorage`, holding nothing\n * but the open handle and how deep the nesting is.\n *\n * One store per scope with one owner, which is the pattern the framework\n * already follows — `kernel/context.ts` holds the Application,\n * `http/requestContext.ts` the request and its user. The reasoning for\n * not folding this into the kernel's is written up beside it, and the short\n * version is that a transaction scope has to *nest inside* an Application scope\n * without replacing it, and `foundation/app.ts` must keep reading exactly one\n * shape out of the kernel store or resolving a service becomes a transaction\n * concern.\n *\n * What makes an ALS the right home rather than a field somewhere: two concurrent\n * requests each in their own transaction must never see each other's handle.\n * Anything reachable from the Application — which is one object shared by every\n * in-flight request — fails that by construction, and fails it as silently\n * written data, not as an error. \"two concurrent transactions never see each\n * other's handle\" in `context.test.ts` is the test that would catch it.\n */\nexport interface OrmScope {\n /**\n * Bun's transaction handle. Every ORM statement in scope runs on it, which\n * means they all run on one reserved connection — so nothing here may issue\n * two statements concurrently. `Model.$exec` already runs its nested writes\n * and its relation reads sequentially, for exactly this reason.\n */\n tx?: TransactionSQL;\n /** 0 for the outermost transaction, 1+ for each savepoint inside it. */\n depth: number;\n /**\n * Which named connection this subtree's queries run on, and — when `tx` is\n * set — which connection the open transaction belongs to.\n *\n * Ambient rather than an argument threaded through `$exec`, for the same\n * reason the handle above is: a relation read resolves its target through the\n * registry and calls that class's `$exec`, so an argument would have to be\n * carried by every intermediate that has no interest in it, and the one that\n * forgot would silently read a nested `include` off the *other* pool. There\n * is no error that shape produces; there are just rows from the wrong place.\n *\n * `undefined` means the default connection. Kept as absent-rather-than-\n * `\"default\"` so that entering a scope on the default connection is\n * indistinguishable from not entering one, which is what makes the\n * cross-connection check below cost a comparison of two `undefined`s on every\n * application that never declares a second connection.\n */\n connection?: string;\n /**\n * Whether policies are suspended for this scope. Set only by\n * `Model.asSystem`, and never by anything ambient — the whole point is that\n * unscoped access is a decision visible at the call site, not the accidental\n * result of a missing user.\n */\n system?: boolean;\n /**\n * The user policies should scope to, when there is no request to read one\n * from. Set only by `Model.asUser`.\n *\n * A sentinel wrapper rather than the bare value, so that \"a scope was entered\n * with `null`\" stays distinguishable from \"no scope was entered\" — the two\n * mean different things under deny-by-default.\n */\n actor?: { user: unknown };\n /**\n * Work that must not happen unless this transaction commits — an event whose\n * `static afterCommit` is set, today, and nothing else.\n *\n * **Created by the outermost `withTransaction` and never by a savepoint.** A\n * savepoint's scope is a spread of its parent's (`{ ...current, tx: nested }`),\n * so the array arrives here already shared by reference with the transaction\n * that opened it — which is the behaviour wanted rather than a leak. A\n * dispatch made inside a savepoint that commits, in a transaction that then\n * rolls back, must not run: rolling back the outermost transaction discards\n * the list whole, savepoint entries included, because nothing ever drains it.\n *\n * The inverse — a savepoint that rolls back under a transaction that commits\n * — is the case sharing gets wrong on its own, and `withTransaction`'s\n * savepoint branch is where it is put right.\n *\n * Absent, rather than an empty array, on every scope that is not a\n * transaction: `runAsSystem`, `runAsUser` and `runOnConnection` spread\n * whatever they are given, so \"there is a list here\" and \"there is an open\n * transaction here\" have to stay the same question. `deferUntilCommit`\n * answers `false` when either half is missing and the caller runs the work\n * now, which is what keeps a hand-built scope carrying a `tx` — the shape\n * tests write — from swallowing a dispatch into a list nothing drains.\n */\n afterCommit?: AfterCommitCallback[];\n /**\n * Statements written on `tx` that the commit must wait for and must not\n * outlive — today, a job row the database queue driver wrote on the\n * transaction (#563), and nothing else. See `commitDependsOn`.\n *\n * Created and shared exactly as `afterCommit` is, and truncated with it\n * when a savepoint rolls back.\n */\n commitDependsOn?: Promise<unknown>[];\n /**\n * Models whose soft-delete scope (`static $softDeletes`) is lifted or\n * inverted for this async subtree, by name — set only by\n * `Model.withTrashed(fn)` / `Model.onlyTrashed(fn)`.\n *\n * Keyed by model name rather than class because a nested relation read\n * resolves its target through the registry by name, and the block has to\n * reach those reads too. A fresh map per block, never mutated, so an inner\n * block cannot leak its entry back into the enclosing one.\n */\n trashed?: ReadonlyMap<string, TrashedMode>;\n}\n\n/**\n * How a soft-deleted model's trashed rows are treated: `\"with\"` includes them,\n * `\"only\"` reads nothing else. Absent means the default — they are hidden.\n */\nexport type TrashedMode = \"with\" | \"only\";\n\n/**\n * Work deferred to a transaction's commit.\n *\n * Awaited when it is drained, and its rejection is caught there: a callback is\n * a side effect that the transaction is not waiting on and cannot be told\n * about, so the only thing left to do with a failure is report it.\n *\n * Not exported: a caller passes a lambda and never names this, and an export\n * nothing outside this file uses is what `orm/architecture.test.ts` is pointed\n * at. The declaration emit carries it along regardless, so `OrmScope` stays\n * readable from a `.d.ts`.\n */\ntype AfterCommitCallback = () => void | Promise<void>;\n\n/**\n * One ambient scope for the ORM, not one per feature.\n *\n * Transactions (iteration 5) and system access (iteration 6) are both\n * \"something is true for this async subtree and every query in it\", so they\n * share a store rather than minting a second `AsyncLocalStorage` each. The\n * inventory note in `kernel/context.ts` sets the bar for adding one; two\n * booleans-worth of ORM state does not clear it.\n */\nexport const ormContext = new AsyncLocalStorage<OrmScope>();\n\n/**\n * The open transaction, or `undefined` outside one. This is what `Model.$exec`\n * consults to decide which connection a statement runs on.\n *\n * Exported as the escape hatch for code that genuinely needs the handle — a raw\n * query that must join the surrounding transaction, say. **Do not store what it\n * returns.** Bun's handle stays callable after its `begin` resolves: queries on\n * it then run on the pooled connection, outside any transaction, and succeed.\n * Verified against both dialects, and it is the reason `Model.transaction`'s\n * callback takes no argument.\n */\nexport function currentTransaction(): TransactionSQL | undefined {\n return ormContext.getStore()?.tx;\n}\n\n/**\n * The connection every query in this scope runs on unless it names another.\n *\n * `\"default\"` outside any scope, so callers get a name rather than a\n * `string | undefined` to normalise themselves — the store keeps it absent,\n * which is not the same distinction and is nobody else's business.\n */\nexport function currentConnectionName(): string {\n return ormContext.getStore()?.connection ?? DEFAULT_CONNECTION;\n}\n\n/**\n * Run `fn` with `name` as the ambient connection.\n *\n * Merged into the current scope rather than replacing it, exactly as\n * `runAsSystem` and `runAsUser` are: naming a connection must not drop an open\n * transaction handle or re-enable policies underneath it.\n *\n * Deliberately absent from `orm/index.ts`, so it is not part of what an\n * application can reach — `Model.on(name)` and `DB.connection(name)` are the\n * two doors, and both funnel through here so that a nested relation read,\n * which resolves its own class out of the registry and calls its `$exec`,\n * inherits the connection without anything having to pass it along.\n */\nexport function runOnConnection<T>(\n name: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n if (currentConnectionName() === name) return fn();\n\n // ENTERING A CONNECTION IS WHERE THE CROSS-CONNECTION CHECK BELONGS, not at\n // each door — and it has to be *here*, before the scope is entered, because\n // entering it is what makes the check impossible afterwards.\n //\n // The scope carries `tx` and `connection` together, so overwriting the name\n // while an open handle stays in place produces a store that says \"a\n // transaction on analytics\" while holding the *default* connection's handle.\n // Every check downstream then agrees with itself and the statement runs on\n // the wrong connection's transaction. `Model.save` found this: it routes to\n // the row's own connection, so it is the one caller that switches connections\n // with a transaction already open.\n assertConnectionUsable(name);\n\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n },\n fn,\n );\n}\n\n/**\n * Refuse a statement that names one connection while a transaction is open on\n * another.\n *\n * The check `withTransaction`'s single-connection note asked for, and the\n * reasoning for refusing rather than routing is on\n * `CrossConnectionTransactionError`. Both doors call it — `Model.$exec` for\n * every model operation, `DB` for a raw fragment — because either one alone\n * leaves the other free to straddle the two connections, and a raw `DB.execute`\n * escaping a transaction is the more damaging of the two.\n *\n * Only ever fires on a query that *names* a connection: an unqualified one\n * resolves to the ambient name, which is the transaction's own.\n */\nexport function assertConnectionUsable(name: string): void {\n const store = ormContext.getStore();\n if (store?.tx === undefined) return;\n\n const open = store.connection ?? DEFAULT_CONNECTION;\n if (open === name) return;\n\n throw new CrossConnectionTransactionError(open, name);\n}\n\n/**\n * Hold `callback` until the open transaction commits, and say whether that\n * happened.\n *\n * `false` means there was nothing to wait for — no transaction is open, or the\n * scope was entered by hand rather than by `withTransaction` — and the caller\n * must run the work itself, now. That return value is the whole contract: a\n * caller that ignores it turns \"no transaction here\" into a side effect queued\n * on a list nothing will ever drain, which is a dispatch that silently never\n * happens.\n *\n * `true` means the callback is on the outermost scope's list and will run after\n * `begin` resolves, outside the transaction, whatever the caller does next. It\n * will not run at all if the transaction rolls back, or if a savepoint it was\n * registered inside rolls back — both of which are the point.\n *\n * Nothing here is ordered against anything but the other deferred callbacks:\n * they run in registration order, one at a time, after the commit round-trip.\n */\nexport function deferUntilCommit(callback: AfterCommitCallback): boolean {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.afterCommit === undefined) return false;\n\n store.afterCommit.push(callback);\n return true;\n}\n\n/**\n * Make the open transaction's commit depend on `write`, a statement issued on\n * its handle: the transaction does not commit until `write` settles, and\n * rolls back — rejecting with `TransactionDependencyError` — if it rejected.\n *\n * For a write the caller may not await. A queued listener's dispatch never is\n * (`EventManager` pushes it and moves on), and on Postgres a statement that\n * fails aborts the whole transaction: every statement after it is refused and\n * Bun's `COMMIT` quietly becomes a rollback. Without this, the callback's\n * promise resolved, `begin` resolved, and the rows the caller wrote were gone\n * with nothing to say so. MySQL does not abort on a failed statement, and is\n * failed here anyway, so that a joined write means the same thing on both:\n * it commits with the transaction or the transaction does not commit.\n *\n * `false` when there is no transaction to depend on, as for\n * `deferUntilCommit`.\n */\nexport function commitDependsOn(write: Promise<unknown>): boolean {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.commitDependsOn === undefined) {\n return false;\n }\n store.commitDependsOn.push(write);\n return true;\n}\n\n/**\n * A write the transaction's commit depended on failed, so the transaction —\n * or the savepoint the write was made in — rolled back. `cause` is the write's\n * own error.\n */\nexport class TransactionDependencyError extends Error {\n constructor(cause: unknown) {\n super(\n `A statement this transaction depended on failed after being issued on ` +\n `it, so the transaction rolled back instead of committing: ` +\n `${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.name = \"TransactionDependencyError\";\n }\n}\n\n/**\n * Wait for the writes registered from `mark` on, and throw if one failed.\n *\n * Called at the end of a transaction's or savepoint's callback, *inside*\n * `begin`/`savepoint`, so a throw is what makes Bun roll back rather than\n * commit — after `begin` has resolved it is too late to do anything but\n * report. Every write is settled before throwing, so none is still running on\n * the handle when the rollback is issued.\n */\nasync function awaitDependencies(\n writes: Promise<unknown>[],\n mark: number,\n): Promise<void> {\n if (writes.length === mark) return;\n const settled = await Promise.allSettled(writes.slice(mark));\n const failed = settled.find(\n (outcome): outcome is PromiseRejectedResult => outcome.status === \"rejected\",\n );\n if (failed) throw new TransactionDependencyError(failed.reason);\n}\n\n/** How deeply nested the current transaction is; `null` outside one. */\nexport function transactionDepth(): number | null {\n const store = ormContext.getStore();\n return store?.tx === undefined ? null : store.depth;\n}\n\n/** Whether policies are suspended for the current async scope. */\nexport function isSystemScope(): boolean {\n return ormContext.getStore()?.system === true;\n}\n\n/**\n * Run `fn` with policies suspended.\n *\n * The escape hatch the deny-by-default rule needs to be usable: a cron tick, a\n * queue worker or a seed script has no user, and under deny-by-default every\n * policied model would refuse it. This makes that intent explicit *at the call\n * site*, which is the property that matters — unscoped access must never be\n * what happens when a user simply fails to turn up.\n *\n * It nests inside a transaction and a transaction nests inside it: the scope is\n * merged rather than replaced, so `asSystem` does not silently drop an open\n * handle.\n */\nexport function runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n const current = ormContext.getStore();\n return ormContext.run({ ...current, depth: current?.depth ?? 0, system: true }, fn);\n}\n\n/**\n * How `model`'s trashed rows are treated in this async scope, or `undefined`\n * for the default (hidden). See `OrmScope.trashed`.\n */\nexport function trashedMode(model: string): TrashedMode | undefined {\n return ormContext.getStore()?.trashed?.get(model);\n}\n\n/**\n * Run `fn` with `model`'s soft-delete scope lifted (`\"with\"`) or inverted\n * (`\"only\"`). Merged into the current scope like `runAsSystem`, so it keeps an\n * open transaction, the system flag and the actor — and every other policy.\n */\nexport function runWithTrashed<T>(\n model: string,\n mode: TrashedMode,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n const trashed = new Map(current?.trashed);\n trashed.set(model, mode);\n return ormContext.run(\n { ...current, depth: current?.depth ?? 0, trashed },\n fn,\n );\n}\n\n/** The explicitly-set actor, or `undefined` when none was. */\nexport function currentActor(): { user: unknown } | undefined {\n return ormContext.getStore()?.actor;\n}\n\n/**\n * Run `fn` with policies scoped to `user`, for code with no request to read one\n * from.\n *\n * The counterpart to `runAsSystem`, and the reason that one is not the only\n * escape hatch. A queue worker processing \"send the invoice for organisation 7\"\n * genuinely acts *as somebody*; giving it `asSystem` would suspend policies\n * entirely and leave it hand-scoping every query — which is precisely the\n * unscoped-by-accident failure the deny-by-default rule exists to prevent. The\n * narrow tool should be the easy one.\n *\n * It is also what makes policies testable without reaching into\n * `RequestContext`'s internals.\n *\n * Takes precedence over the request store, so a job that says who it is acting\n * as is not quietly overridden by an ambient request that happens to enclose it.\n *\n * It also **clears `system`**, which is the more surprising half. Acting as a\n * user is strictly narrower than acting as the system, so naming one inside an\n * `asSystem` block has to narrow back — and the spread would otherwise carry\n * `system: true` forward, leaving `$exec` to skip policies entirely while\n * `currentUser()` cheerfully returned the actor. Silently unscoped, from the\n * realistic shape: a worker enters `asSystem` to read its job queue, then\n * narrows to the job's owner for the work itself. The reverse nesting —\n * `asSystem` inside `asUser` — suspends policies, which is what it should do.\n */\nexport function runAsUser<T>(user: unknown, fn: () => Promise<T>): Promise<T> {\n const current = ormContext.getStore();\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n system: false,\n actor: { user: user ?? null },\n },\n fn,\n );\n}\n\n/**\n * The warning threshold in milliseconds, or `null` when the warning is off.\n *\n * `configured` is `database.slowTransactionThreshold` — see `DatabaseConfig`.\n * It arrives as a value rather than being read from here so that this file\n * keeps knowing nothing about the container: `withTransaction` is reachable\n * with a bare pool, and its tests use one.\n *\n * Exported for its own tests. The behaviour worth pinning is the fallback —\n * that a malformed threshold lands on the default rather than disabling — and\n * that cannot be observed through `withTransaction`: \"no warning fired\" is what\n * a disabled warning looks like too, so a behavioural test of it passes just as\n * happily when the fallback is gone. Asserting the number directly is the only\n * form of that test that can fail.\n */\nexport function slowTransactionThreshold(\n configured?: number | false,\n): number | null {\n // Read per call, never cached at module scope. `scripts/build.ts` rewrites\n // `process.env.NODE_ENV` to `Bun.env.NODE_ENV` precisely so mode stays a\n // runtime question in the built framework; caching it here would undo that.\n if (process.env.NODE_ENV !== \"development\") return null;\n\n // The one way to switch it off, and it has to be spelled. Everything else\n // falls back, so the warning is never lost to a mistyped value — only to an\n // explicit `false`.\n if (configured === false) return null;\n\n if (configured === undefined) return SLOW_TRANSACTION_THRESHOLD;\n if (!Number.isFinite(configured) || configured <= 0) {\n return SLOW_TRANSACTION_THRESHOLD;\n }\n return configured;\n}\n\n/**\n * Warn, in development only, about a transaction that has been open too long.\n *\n * The risk is structural rather than occasional: an open transaction holds one\n * reserved connection for as long as its callback runs, and nothing about\n * `Model.transaction(async () => { ... })` stops that callback from awaiting a\n * `fetch`, an S3 upload or a slow queue push. Under concurrency that drains the\n * pool, and the symptom — every unrelated query in the process blocking on\n * connection acquisition — names neither the callback nor the I/O in it.\n *\n * A timer rather than measuring elapsed time on the way out, for one reason:\n * the worst case is the transaction that *never* settles (a hung request, a\n * lock wait, a deadlock). After-the-fact measurement is silent for exactly that\n * case; a timer fires while it is still open and still holding the connection.\n *\n * The `Error` is constructed up front and read only if the timer fires — V8\n * formats `.stack` lazily on first access, so an ordinary fast transaction pays\n * for an object allocation and nothing else.\n *\n * The clock starts at the `begin` call, not at the moment a connection is\n * acquired, and stops when `begin` settles rather than when the callback\n * returns — so it spans the pool wait and the commit round-trip as well as the\n * callback. That is deliberate: all three are time this transaction is in\n * flight, and a warning that only covered the callback would stay silent for a\n * transaction stuck waiting on an exhausted pool, which is the exact situation\n * a long transaction elsewhere creates. Hence \"not settled\" rather than \"open\n * for\" — the message must not claim a connection was held for the whole span.\n */\nfunction watchForSlowTransaction(configured?: number | false): () => void {\n const threshold = slowTransactionThreshold(configured);\n if (threshold === null) return () => {};\n\n const site = new Error(\"transaction opened here\");\n\n const timer = setTimeout(() => {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A database transaction has not settled after ${threshold}ms. It ` +\n `reserves a pooled connection until it does — check for network or ` +\n `filesystem I/O inside the callback, and move it outside the ` +\n `transaction if you find any.\\n${stack}\\n` +\n `(development only; set database.slowTransactionThreshold to change ` +\n `the threshold, or false to switch this off)`,\n );\n }, threshold);\n\n // Otherwise the warning timer is itself a reason the process stays alive,\n // which would turn a diagnostic into a hang in short-lived commands and\n // scripts.\n timer.unref?.();\n\n return () => clearTimeout(timer);\n}\n\n/**\n * Runs what a committed transaction deferred, outside the transaction it was\n * deferred by.\n *\n * `outside` is the scope that was ambient before `begin` — an `asSystem` block,\n * a named connection, or nothing at all — and re-entering it explicitly is the\n * guarantee rather than a tidy-up. The alternative is relying on where a `.then`\n * happens to have captured its context, and the failure that produces is the\n * one the whole feature is about: a listener that runs \"after commit\" while\n * still holding the closed transaction's handle joins nothing, because Bun's\n * handle stays callable and simply runs on the pool. So the scope is rebuilt\n * with `tx` and the drained list cleared, and a listener that opens its own\n * transaction gets a real one.\n *\n * Errors are caught per callback and the next one still runs, for the reason\n * the event subsystem catches per listener: these are independent side effects\n * whose order came from a filesystem walk. And the transaction is not failed by\n * one — it committed, the database kept the rows, and reporting a rejection to\n * the caller would have it roll back or retry work that is already durable.\n * stderr is all that is left, and it is enough: the caller has no decision to\n * make here.\n *\n * The transaction's own promise does not resolve until this has finished, which\n * is the one thing about `afterCommit` that a caller can feel. Deliberate: the\n * alternative is a floating promise whose rejection nobody sees and whose work\n * a short-lived process — a command, a seed — exits out from under.\n */\nasync function drainAfterCommit(\n callbacks: AfterCommitCallback[],\n outside: OrmScope | undefined,\n): Promise<void> {\n if (callbacks.length === 0) return;\n\n await ormContext.run(\n {\n ...outside,\n tx: undefined,\n afterCommit: undefined,\n commitDependsOn: undefined,\n depth: outside?.depth ?? 0,\n },\n async () => {\n for (const callback of callbacks) {\n try {\n await callback();\n } catch (error) {\n console.error(\n `An after-commit callback threw. The transaction it was waiting ` +\n `on had already committed and stays committed, and the ` +\n `callbacks after it still ran.`,\n error,\n );\n }\n }\n },\n );\n}\n\n/**\n * Run `fn` inside a transaction, entering the ambient scope for its whole async\n * subtree.\n *\n * The single implementation behind both `Model.transaction` and\n * `DB.transaction`, so the two cannot become transaction systems that ignore\n * each other: a `Model.create` inside a `DB.transaction` joins it, and a raw\n * `DB.sql` inside a `Model.transaction` can join it through\n * `currentTransaction()`.\n *\n * Nesting becomes a savepoint. Not a preference — Bun refuses the alternative\n * outright (`cannot call begin inside a transaction use savepoint() instead`),\n * and a savepoint is the semantics worth having anyway: an inner failure rolls\n * back to it and leaves the outer transaction usable, which a caller that\n * catches can rely on. Verified on SQLite and Postgres.\n *\n * Note Bun hands the savepoint callback the *same* handle object as the outer\n * transaction (`sp === tx`), so the depth counter is the only thing that\n * actually changes on the way in. The callback's argument is still what gets\n * stored, so this keeps working if that ever stops being true. The cast is\n * because Bun types a savepoint handle as plain `SQL` — without `savepoint` on\n * it — while the runtime object does carry the method, which is what makes\n * three levels of nesting work.\n *\n * Anything `deferUntilCommit` queued is drained once `begin` resolves, outside\n * the transaction and only on the outermost call — a savepoint has committed\n * nothing durable, so draining there would run work that a later rollback of\n * the enclosing transaction was meant to have prevented. See `drainAfterCommit`\n * for what that costs the caller.\n *\n * In development, an outermost transaction that stays open past\n * `options.slowTransactionThreshold` (2s by default, `false` to disable) warns\n * — see `watchForSlowTransaction`. Nothing here *prevents* a long transaction;\n * the warning exists because the cost of one is paid by unrelated queries\n * elsewhere in the process, which makes it hard to trace back.\n *\n * The threshold is passed in rather than read from `app(DatabaseManager)` here.\n * Every caller already holds the manager — it is where `pool` came from — and\n * taking it as an argument keeps this file free of the container, so a bare\n * `SQL` is still enough to call it. Its tests rely on that.\n *\n * `options.connection` is the name `pool` belongs to, and follows the same rule\n * for the same reason: the pool cannot be asked what it is called. Passing it\n * is what lets a nested `withTransaction` tell \"the same connection, so take a\n * savepoint\" from \"a different one, so refuse\" — omitting it means the default\n * connection, which is what a two-argument call always meant.\n *\n * The return type is asserted rather than inferred for one reason worth\n * knowing: Bun's `begin` unwraps a callback that resolves to an *array of\n * promises*, awaiting each. So `Model.transaction(async () => [a, b])` where\n * `a` and `b` are promises resolves to their values, not to the promises. That\n * is Bun's behaviour and is left alone; it is only surprising if unmentioned.\n */\nexport function withTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options?: { slowTransactionThreshold?: number | false; connection?: string },\n): Promise<T> {\n const current = ormContext.getStore();\n\n // THE SINGLE-CONNECTION ASSUMPTION, WHICH IS NOW CHECKED RATHER THAN PINNED.\n //\n // The savepoint branch below ignores `pool` entirely. That was correct while\n // there was one `DatabaseManager` and one `SQL` — the ambient handle and\n // whatever pool the caller passed were necessarily the same database — and\n // the note that stood here said what would happen when a second connection\n // became configurable (#327): a `DB.transaction` on B inside a\n // `Model.transaction` on A would savepoint on **A** and hand the callback A's\n // handle, so statements landed in the wrong database with no error at all.\n //\n // So the name is compared before the branch is taken, and a mismatch raises.\n // Refusing is the whole answer rather than half of one — there is no way to\n // make one transaction span two pools, and the alternatives are covered on\n // `CrossConnectionTransactionError`.\n //\n // A caller that passes no `connection` is treated as naming the default,\n // which is what `withTransaction(pool, fn)` meant before this argument\n // existed.\n const name = options?.connection ?? DEFAULT_CONNECTION;\n assertConnectionUsable(name);\n\n // `current?.tx` rather than `current`: since iteration 6 a scope can exist\n // with no open transaction — `Model.asSystem` enters one — and a savepoint\n // needs an actual handle, not merely a store.\n if (current?.tx) {\n // WHERE THE SHARED AFTER-COMMIT LIST IS PUT RIGHT.\n //\n // The savepoint's scope is a spread of this one, so it appends to the\n // transaction's list rather than to a list of its own — which is what makes\n // \"the outer transaction rolled back, so nothing runs\" free. The case that\n // is not free is this one: the savepoint rolls back and the transaction\n // goes on to commit. Its entries have to go, or a dispatch made inside a\n // block the database threw away runs anyway, which is the same wrong answer\n // as before with an extra step.\n //\n // A mark on the way in and a truncate on the way out, rather than tagging\n // each entry with its depth and dropping everything at or below the failing\n // one. Depth cannot tell two *siblings* apart: a savepoint that committed\n // and one that rolled back both left entries at the same depth, adjacent in\n // the list, and dropping by depth would discard the committed sibling's\n // work as well. The index is exact because the ORM issues one statement at\n // a time on a transaction handle — see `OrmScope.tx` — so nothing appends\n // between the mark and the failure but this savepoint's own subtree.\n const deferred = current.afterCommit;\n const mark = deferred?.length ?? 0;\n // The same mark for the writes the commit depends on. The savepoint waits\n // for its own before it releases, so one that failed rolls back only the\n // savepoint — which a caller that catches can survive, exactly as it\n // survives a statement that threw inside it — and is then forgotten\n // rather than failing the transaction a second time.\n const dependencies = current.commitDependsOn;\n const dependencyMark = dependencies?.length ?? 0;\n\n return current.tx\n .savepoint((sp) => {\n const nested = sp as TransactionSQL;\n return ormContext.run(\n { ...current, tx: nested, depth: current.depth + 1 },\n async () => {\n const result = await fn(nested);\n if (dependencies) {\n await awaitDependencies(dependencies, dependencyMark);\n }\n return result;\n },\n );\n })\n .catch((error: unknown) => {\n if (deferred) deferred.length = mark;\n if (dependencies) dependencies.length = dependencyMark;\n throw error;\n }) as Promise<T>;\n }\n\n // Only the outermost scope is watched. A savepoint reserves no connection of\n // its own — its lifetime is bounded by the transaction it sits in, which is\n // already being timed — so warning per depth would report one slow block as\n // several warnings and point at the innermost frame rather than the one\n // holding the connection.\n const stopWatching = watchForSlowTransaction(\n options?.slowTransactionThreshold,\n );\n\n // Built out here rather than inside the `begin` callback, because the drain\n // below needs it *after* that callback's scope is gone, and reading it off\n // the store then is exactly what is no longer possible.\n const deferred: AfterCommitCallback[] = [];\n const dependencies: Promise<unknown>[] = [];\n\n // The `try` covers a *synchronous* throw from `begin` — a closed pool, say.\n // `.finally` alone would not: it is only attached once `begin` has returned a\n // promise, so a synchronous throw escapes with the timer still armed and\n // eventually warns about a transaction that never opened. `unref` keeps that\n // from holding the process, which makes it cosmetic rather than a leak, but\n // it is the same gap the `.finally` below exists to close.\n try {\n // Spread rather than replace: a `Model.transaction` inside a\n // `Model.asSystem` must not silently re-enable policies for its subtree.\n //\n // The connection goes into the scope alongside the handle, and the pair is\n // what makes the check at the top of this function possible: \"which\n // connection is this transaction on\" has to be answerable from the store,\n // because the handle itself does not say. It is also what makes an\n // unqualified query inside `DB.connection(\"analytics\").transaction(...)`\n // *join* the transaction instead of being refused by it — the query\n // inherits the name rather than defaulting to the hot path.\n return (\n pool\n .begin((tx) =>\n ormContext.run(\n {\n ...current,\n tx,\n depth: 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n // A fresh list per outermost transaction, assigned rather than\n // left to the spread. `current` holds no list today — the drain\n // clears the field before it runs anything — and assigning is\n // what keeps that from being load-bearing: a transaction opened\n // by a callback during a drain gets its own list either way,\n // rather than appending to the array it is being run out of.\n afterCommit: deferred,\n commitDependsOn: dependencies,\n },\n async () => {\n const result = await fn(tx);\n await awaitDependencies(dependencies, 0);\n return result;\n },\n ),\n )\n // `finally` and not a `then`/`catch` pair: the connection is released on\n // rollback exactly as it is on commit, so a throwing callback must clear\n // the timer too or every failed transaction leaves a warning armed\n // against a connection that has already gone back to the pool.\n //\n // Before the drain, so that a slow after-commit listener is not\n // reported as a transaction that will not settle. The connection went\n // back to the pool at the commit; the warning is about holding it.\n .finally(stopWatching)\n // Only here, on the fulfilled path. A rejected `begin` rolled back, so\n // the scope and everything queued on it are discarded unread — which is\n // the whole of what `afterCommit` promises.\n .then(async (result) => {\n await drainAfterCommit(deferred, current);\n return result;\n }) as Promise<T>\n );\n } catch (error) {\n stopWatching();\n throw error;\n }\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";yDACA,4BAAS,oBAmJF,IAAM,EAAa,IAAI,EAavB,SAAS,CAAkB,EAA+B,CAC/D,OAAO,EAAW,SAAS,GAAG,GAUzB,SAAS,CAAqB,EAAW,CAC9C,OAAO,EAAW,SAAS,GAAG,YAAc,EAgBvC,SAAS,CAAkB,CAChC,EACA,EACY,CACZ,IAAM,EAAU,EAAW,SAAS,EACpC,GAAI,EAAsB,IAAM,EAAM,OAAO,EAAG,EAehD,OAFA,EAAuB,CAAI,EAEpB,EAAW,IAChB,IACK,EACH,MAAO,GAAS,OAAS,EACzB,WAAY,IAAS,EAAqB,OAAY,CACxD,EACA,CACF,EAiBK,SAAS,CAAsB,CAAC,EAAoB,CACzD,IAAM,EAAQ,EAAW,SAAS,EAClC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,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{G as r}from"./chunk-ehasw3qm.js";import"./chunk-zys7kecf.js";import{Z as mc}from"./chunk-whe0x70j.js";import"./chunk-g7fr2cy2.js";import{$ as _}from"./chunk-jc4j61xb.js";import{rh as u,uh as O}from"./chunk-wvwee7dn.js";import{Buffer as hc}from"buffer";import{request as Yc}from"http";function E(c){return new Promise((I,x)=>{let N=Yc({method:"GET",...c,hostname:c.hostname?.replace(/^\[(.+)\]$/,"$1")});N.on("error",(T)=>{x(Object.assign(new K.ProviderError("Unable to connect to instance metadata service"),T)),N.destroy()}),N.on("timeout",()=>{x(new K.ProviderError("TimeoutError from instance metadata service")),N.destroy()}),N.on("response",(T)=>{let{statusCode:y=400}=T;if(y<200||300<=y)x(Object.assign(new K.ProviderError("Error response received from instance metadata service"),{statusCode:y})),N.destroy();let $=[];T.on("data",(w)=>{$.push(w)}),T.on("end",()=>{I(hc.concat($)),N.destroy()})}),N.end()})}var K;var D=O(()=>{K=u(_(),1)});var G=(c)=>Boolean(c)&&typeof c==="object"&&typeof c.AccessKeyId==="string"&&typeof c.SecretAccessKey==="string"&&typeof c.Token==="string"&&typeof c.Expiration==="string",L=(c)=>({accessKeyId:c.AccessKeyId,secretAccessKey:c.SecretAccessKey,sessionToken:c.Token,expiration:new Date(c.Expiration),...c.AccountId&&{accountId:c.AccountId}});var W=()=>{};var Hc=1000,qc=0,Q=({maxRetries:c=0,timeout:I=1000})=>({maxRetries:c,timeout:I});var X=()=>{};var v=(c,I)=>{let x=c();for(let N=0;N<I;N++)x=x.catch(c);return x};var b=()=>{};import{parse as Sc}from"url";var z,H="AWS_CONTAINER_CREDENTIALS_FULL_URI",q="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",M="AWS_CONTAINER_AUTHORIZATION_TOKEN",kc=(c={})=>{let{timeout:I,maxRetries:x}=Q(c);return()=>v(async()=>{let N=await jc({logger:c.logger}),T=JSON.parse(await fc(I,N));if(!G(T))throw new z.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:c.logger});return L(T)},x)},fc=async(c,I)=>{if(process.env[M])I.headers={...I.headers,Authorization:process.env[M]};return(await E({...I,timeout:c})).toString()},uc="169.254.170.2",Ec,$c,jc=async({logger:c})=>{if(process.env[q])return{hostname:uc,path:process.env[q]};if(process.env[H]){let I=Sc(process.env[H]);if(!I.hostname||!(I.hostname in Ec))throw new z.CredentialsProviderError(`${I.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:c});if(!I.protocol||!(I.protocol in $c))throw new z.CredentialsProviderError(`${I.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:c});return{...I,port:I.port?parseInt(I.port,10):void 0}}throw new z.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${q} or ${H} environment variable is set`,{tryNextLink:!1,logger:c})};var p=O(()=>{D();W();X();b();z=u(_(),1),Ec={localhost:!0,"127.0.0.1":!0},$c={"http:":!0,"https:":!0}});var C,Z;var a=O(()=>{C=u(_(),1);Z=class Z extends C.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(c,I=!0){super(c,I);this.tryNextLink=I,Object.setPrototypeOf(this,Z.prototype)}}});var J;var B=O(()=>{(function(c){c.IPv4="http://169.254.169.254",c.IPv6="http://[fd00:ec2::254]"})(J||(J={}))});var n;var o=O(()=>{n={environmentVariableSelector:(c)=>c.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(c)=>c.ec2_metadata_service_endpoint,default:void 0}});var f;var t=O(()=>{(function(c){c.IPv4="IPv4",c.IPv6="IPv6"})(f||(f={}))});var Ac="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",Jc="ec2_metadata_service_endpoint_mode",s;var g=O(()=>{t();s={environmentVariableSelector:(c)=>c[Ac],configFileSelector:(c)=>c[Jc],default:f.IPv4}});var U,l,F=async()=>l.parseUrl(await vc()||await zc()),vc=async()=>U.loadConfig(n)(),zc=async()=>{let c=await U.loadConfig(s)();switch(c){case f.IPv4:return J.IPv4;case f.IPv6:return J.IPv6;default:throw Error(`Unsupported endpoint mode: ${c}. Select from ${Object.values(f)}`)}};var P=O(()=>{B();o();t();g();U=u(r(),1),l=u(mc(),1)});var V=(c,I)=>{let x=300+Math.floor(Math.random()*300),N=new Date(Date.now()+x*1000);I.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(N)}.
|
|
3
|
-
For more information, please visit: https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html`);let T=c.originalExpiration??c.expiration;return{...c,...T?{originalExpiration:T}:{},expiration:N}};var d=()=>{};var e=(c,I={})=>{let x=I?.logger||console,N;return async()=>{let T;try{if(T=await c(),T.expiration&&T.expiration.getTime()<Date.now())T=V(T,x)}catch(y){if(N)x.warn("Credential renew failed: ",y),T=V(N,x);else throw y}return N=T,T}};var i=O(()=>{d()});var Nc,k,Tc="/latest/meta-data/iam/security-credentials/",Kc="/latest/api/token",R="AWS_EC2_METADATA_V1_DISABLED",cc="ec2_metadata_v1_disabled",Ic="x-aws-ec2-metadata-token",YI=(c={})=>e(_c(c),{logger:c.logger}),_c=(c={})=>{let I=!1,{logger:x,profile:N}=c,{timeout:T,maxRetries:y}=Q(c),$=async(w,j)=>{if(I||j.headers?.[Ic]==null){let h=!1,Y=!1,wc=await Nc.loadConfig({environmentVariableSelector:(S)=>{let A=S[R];if(Y=!!A&&A!=="false",A===void 0)throw new k.CredentialsProviderError(`${R} not set in env, checking config file next.`,{logger:c.logger});return Y},configFileSelector:(S)=>{let A=S[cc];return h=!!A&&A!=="false",h},default:!1},{profile:N})();if(c.ec2MetadataV1Disabled||wc){let S=[];if(c.ec2MetadataV1Disabled)S.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");if(h)S.push(`config file profile (${cc})`);if(Y)S.push(`process environment variable (${R})`);throw new Z(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${S.join(", ")}].`)}}let yc=(await v(async()=>{let h;try{h=await Gc(j)}catch(Y){if(Y.statusCode===401)I=!1;throw Y}return h},w)).trim();return v(async()=>{let h;try{h=await Lc(yc,j,c)}catch(Y){if(Y.statusCode===401)I=!1;throw Y}return h},w)};return async()=>{let w=await F();if(I)return x?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),$(y,{...w,timeout:T});else{let j;try{j=(await Dc({...w,timeout:T})).toString()}catch(m){if(m?.statusCode===400)throw Object.assign(m,{message:"EC2 Metadata token request returned error"});else if(m.message==="TimeoutError"||[403,404,405].includes(m.statusCode))I=!0;return x?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),$(y,{...w,timeout:T})}return $(y,{...w,headers:{[Ic]:j},timeout:T})}}},Dc=async(c)=>E({...c,path:Kc,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),Gc=async(c)=>(await E({...c,path:Tc})).toString(),Lc=async(c,I,x)=>{let N=JSON.parse((await E({...I,path:Tc+c})).toString());if(!G(N))throw new k.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:x.logger});return L(N)};var xc=O(()=>{a();D();W();X();b();P();i();Nc=u(r(),1),k=u(_(),1)});var Oc=()=>{};var Qc=O(()=>{D();P();B();p();xc();X();Oc()});Qc();export{Q as providerConfigFromInit,E as httpRequest,F as getInstanceMetadataEndpoint,YI as fromInstanceMetadata,kc as fromContainerMetadata,J as Endpoint,q as ENV_CMDS_RELATIVE_URI,H as ENV_CMDS_FULL_URI,M as ENV_CMDS_AUTH_TOKEN,Hc as DEFAULT_TIMEOUT,qc as DEFAULT_MAX_RETRIES};
|
|
4
|
-
|
|
5
|
-
//# debugId=CE79E6C25A7E4E4564756E2164756E21
|
package/dist/chunk-rjcsdazt.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{H as A}from"./chunk-zys7kecf.js";import{V as T}from"./chunk-qz9aaw5x.js";import"./chunk-g7fr2cy2.js";import{$ as y}from"./chunk-jc4j61xb.js";import{rh as r}from"./chunk-wvwee7dn.js";var u=r(A(),1);var i=r(y(),1),E=r(A(),1);import{exec as d}from"child_process";import{promisify as I}from"util";var x=r(T(),1),_=(c,n,e)=>{if(n.Version!==1)throw Error(`Profile ${c} credential_process did not return Version 1.`);if(n.AccessKeyId===void 0||n.SecretAccessKey===void 0)throw Error(`Profile ${c} credential_process returned invalid credentials.`);if(n.Expiration){let w=new Date;if(new Date(n.Expiration)<w)throw Error(`Profile ${c} credential_process returned expired credentials.`)}let s=n.AccountId;if(!s&&e?.[c]?.aws_account_id)s=e[c].aws_account_id;let t={accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,...n.SessionToken&&{sessionToken:n.SessionToken},...n.Expiration&&{expiration:new Date(n.Expiration)},...n.CredentialScope&&{credentialScope:n.CredentialScope},...s&&{accountId:s}};return x.setCredentialFeature(t,"CREDENTIALS_PROCESS","w"),t};var K=async(c,n,e)=>{let s=n[c];if(n[c]){let t=s.credential_process;if(t!==void 0){let w=I(E.externalDataInterceptor?.getTokenRecord?.().exec??d);try{let{stdout:o}=await w(t),S;try{S=JSON.parse(o.trim())}catch{throw Error(`Profile ${c} credential_process returned invalid JSON.`)}return _(c,S,n)}catch(o){throw new i.CredentialsProviderError(o.message,{logger:e})}}else throw new i.CredentialsProviderError(`Profile ${c} did not contain credential_process.`,{logger:e})}else throw new i.CredentialsProviderError(`Profile ${c} could not be found in shared credentials file.`,{logger:e})};var R=(c={})=>async({callerClientConfig:n}={})=>{c.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");let e=await u.parseKnownFiles(c);return K(u.getProfileName({profile:c.profile??n?.profile}),e,c.logger)};export{R as fromProcess};
|
|
3
|
-
|
|
4
|
-
//# debugId=4831F73829DFFBEF64756E2164756E21
|