gemi 0.179.0 → 0.181.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 +51 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +76 -1
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/index.d.ts +3 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +34 -34
- package/dist/ai/index.js.map +3 -3
- package/dist/ai/types.d.ts +5 -1
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/usageLimits.d.ts +138 -0
- package/dist/ai/usageLimits.d.ts.map +1 -0
- package/dist/app/index.js +1 -1
- package/dist/auth/AuthController.d.ts +4 -0
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/AuthManager.d.ts +5 -4
- package/dist/auth/AuthManager.d.ts.map +1 -1
- package/dist/auth/UserProvider.d.ts +1 -1
- package/dist/auth/UserProvider.d.ts.map +1 -1
- package/dist/auth/config.d.ts +40 -6
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/auth/oneTimeCode.d.ts +24 -1
- package/dist/auth/oneTimeCode.d.ts.map +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-nv2ecda9.js → chunk-07ttfngb.js} +2 -2
- package/dist/{chunk-nv2ecda9.js.map → chunk-07ttfngb.js.map} +1 -1
- package/dist/{chunk-w6br58a9.js → chunk-0jery7ys.js} +4 -4
- package/dist/{chunk-w6br58a9.js.map → chunk-0jery7ys.js.map} +1 -1
- package/dist/{chunk-xzzdywf6.js → chunk-1863jd18.js} +2 -2
- package/dist/{chunk-pw6ssy3a.js.map → chunk-1863jd18.js.map} +1 -1
- package/dist/{chunk-6nrd3djs.js → chunk-1kcv4dyh.js} +2 -2
- package/dist/{chunk-6nrd3djs.js.map → chunk-1kcv4dyh.js.map} +1 -1
- package/dist/{chunk-q30ryk1a.js → chunk-1mz16fsz.js} +2 -2
- package/dist/{chunk-q30ryk1a.js.map → chunk-1mz16fsz.js.map} +1 -1
- package/dist/{chunk-f5mhc5eh.js → chunk-28mrg70g.js} +2 -2
- package/dist/{chunk-f5mhc5eh.js.map → chunk-28mrg70g.js.map} +1 -1
- package/dist/{chunk-wtjfjh0x.js → chunk-3jnnma7m.js} +2 -2
- package/dist/{chunk-wtjfjh0x.js.map → chunk-3jnnma7m.js.map} +1 -1
- package/dist/{chunk-b53n5696.js → chunk-3m791vwf.js} +2 -2
- package/dist/{chunk-b53n5696.js.map → chunk-3m791vwf.js.map} +1 -1
- package/dist/{chunk-mby1wdny.js → chunk-4b5rpya9.js} +2 -2
- package/dist/{chunk-mby1wdny.js.map → chunk-4b5rpya9.js.map} +1 -1
- package/dist/{chunk-v8qzdvpj.js → chunk-5467avf1.js} +2 -2
- package/dist/{chunk-v8qzdvpj.js.map → chunk-5467avf1.js.map} +1 -1
- package/dist/{chunk-tjmw2z5z.js → chunk-5d6h1znx.js} +2 -2
- package/dist/{chunk-tjmw2z5z.js.map → chunk-5d6h1znx.js.map} +1 -1
- package/dist/{chunk-9mcweetq.js → chunk-5f4k3n9x.js} +2 -2
- package/dist/{chunk-9mcweetq.js.map → chunk-5f4k3n9x.js.map} +1 -1
- package/dist/chunk-5nqwxjf1.js +15 -0
- package/dist/{chunk-c0qq5t8a.js.map → chunk-5nqwxjf1.js.map} +5 -4
- package/dist/{chunk-rv0r5fde.js → chunk-5sjteb6f.js} +3 -3
- package/dist/{chunk-rv0r5fde.js.map → chunk-5sjteb6f.js.map} +1 -1
- package/dist/{chunk-4hj0q8fs.js → chunk-62v0y132.js} +2 -2
- package/dist/{chunk-4hj0q8fs.js.map → chunk-62v0y132.js.map} +1 -1
- package/dist/{chunk-sr1gv50s.js → chunk-6bf04rk5.js} +2 -2
- package/dist/{chunk-sr1gv50s.js.map → chunk-6bf04rk5.js.map} +1 -1
- package/dist/{chunk-xgmc7cp5.js → chunk-6dzm2pv7.js} +2 -2
- package/dist/{chunk-xgmc7cp5.js.map → chunk-6dzm2pv7.js.map} +1 -1
- package/dist/{chunk-7jxf0kys.js → chunk-6s7bb50m.js} +3 -3
- package/dist/{chunk-7jxf0kys.js.map → chunk-6s7bb50m.js.map} +1 -1
- package/dist/{chunk-nwg70wza.js → chunk-73svx8gr.js} +3 -3
- package/dist/{chunk-nwg70wza.js.map → chunk-73svx8gr.js.map} +1 -1
- package/dist/{chunk-jpq74abh.js → chunk-7fzwgvyg.js} +1 -1
- package/dist/{chunk-vv1na1vj.js → chunk-7g90w0t6.js} +1 -1
- package/dist/{chunk-520hnb9j.js → chunk-7n6vnmtv.js} +2 -2
- package/dist/{chunk-520hnb9j.js.map → chunk-7n6vnmtv.js.map} +1 -1
- package/dist/{chunk-gjb7cfr4.js → chunk-7pbwmt7j.js} +2 -2
- package/dist/{chunk-gjb7cfr4.js.map → chunk-7pbwmt7j.js.map} +1 -1
- package/dist/{chunk-ht0atvyc.js → chunk-7rmsc511.js} +3 -3
- package/dist/{chunk-ht0atvyc.js.map → chunk-7rmsc511.js.map} +1 -1
- package/dist/{chunk-zpshgset.js → chunk-7stvx6x7.js} +2 -2
- package/dist/{chunk-zpshgset.js.map → chunk-7stvx6x7.js.map} +1 -1
- package/dist/{chunk-zm4fdsq5.js → chunk-8z1z4zbq.js} +2 -2
- package/dist/{chunk-zm4fdsq5.js.map → chunk-8z1z4zbq.js.map} +1 -1
- package/dist/chunk-91vxf94n.js +41 -0
- package/dist/{chunk-51yv7x03.js.map → chunk-91vxf94n.js.map} +5 -4
- package/dist/{chunk-5cf61bb5.js → chunk-9beqhac6.js} +2 -2
- package/dist/{chunk-5cf61bb5.js.map → chunk-9beqhac6.js.map} +1 -1
- package/dist/{chunk-sen7c0e6.js → chunk-9brq77q6.js} +3 -3
- package/dist/{chunk-sen7c0e6.js.map → chunk-9brq77q6.js.map} +1 -1
- package/dist/{chunk-wjkcqe8w.js → chunk-adsbv4rm.js} +2 -2
- package/dist/{chunk-wjkcqe8w.js.map → chunk-adsbv4rm.js.map} +1 -1
- package/dist/{chunk-yef8dvmg.js → chunk-am9gmm5a.js} +2 -2
- package/dist/{chunk-yef8dvmg.js.map → chunk-am9gmm5a.js.map} +1 -1
- package/dist/{chunk-6t9zjhm6.js → chunk-ambptjfh.js} +2 -2
- package/dist/{chunk-6t9zjhm6.js.map → chunk-ambptjfh.js.map} +1 -1
- package/dist/{chunk-6vdvhj14.js → chunk-btt706nx.js} +2 -2
- package/dist/{chunk-6vdvhj14.js.map → chunk-btt706nx.js.map} +1 -1
- package/dist/{chunk-dp5ha6qy.js → chunk-cxh9qe1c.js} +2 -2
- package/dist/{chunk-dp5ha6qy.js.map → chunk-cxh9qe1c.js.map} +1 -1
- package/dist/{chunk-8v95cjc5.js → chunk-dcwsya9e.js} +2 -2
- package/dist/{chunk-8v95cjc5.js.map → chunk-dcwsya9e.js.map} +1 -1
- package/dist/{chunk-6wwk0psy.js → chunk-f3s8pz3m.js} +2 -2
- package/dist/{chunk-6wwk0psy.js.map → chunk-f3s8pz3m.js.map} +1 -1
- package/dist/{chunk-yx26j5vk.js → chunk-fagkv8sm.js} +2 -2
- package/dist/{chunk-yx26j5vk.js.map → chunk-fagkv8sm.js.map} +1 -1
- package/dist/{chunk-s0m717j8.js → chunk-fzwaybhd.js} +3 -3
- package/dist/{chunk-s0m717j8.js.map → chunk-fzwaybhd.js.map} +1 -1
- package/dist/{chunk-93s13x3v.js → chunk-g09qz75d.js} +2 -2
- package/dist/{chunk-93s13x3v.js.map → chunk-g09qz75d.js.map} +1 -1
- package/dist/{chunk-bptarxbq.js → chunk-g0ps09h7.js} +2 -2
- package/dist/{chunk-bptarxbq.js.map → chunk-g0ps09h7.js.map} +1 -1
- package/dist/{chunk-xvaryyd0.js → chunk-g57cg31m.js} +2 -2
- package/dist/{chunk-xvaryyd0.js.map → chunk-g57cg31m.js.map} +1 -1
- package/dist/{chunk-5db4v8gv.js → chunk-gprc53rf.js} +1 -1
- package/dist/{chunk-q3g4xs1z.js → chunk-h5s56wzw.js} +2 -2
- package/dist/{chunk-q3g4xs1z.js.map → chunk-h5s56wzw.js.map} +1 -1
- package/dist/{chunk-vhk6735r.js → chunk-j1j0438r.js} +2 -2
- package/dist/{chunk-vhk6735r.js.map → chunk-j1j0438r.js.map} +1 -1
- package/dist/{chunk-hbjatkm9.js → chunk-jc48hhha.js} +2 -2
- package/dist/{chunk-hbjatkm9.js.map → chunk-jc48hhha.js.map} +1 -1
- package/dist/{chunk-zx5tp1c6.js → chunk-k1v0xgwe.js} +2 -2
- package/dist/{chunk-zx5tp1c6.js.map → chunk-k1v0xgwe.js.map} +1 -1
- package/dist/{chunk-sx6jmyaf.js → chunk-k6x35rn5.js} +1 -1
- package/dist/{chunk-ssmq5r41.js → chunk-m3ncxcw8.js} +2 -2
- package/dist/{chunk-ssmq5r41.js.map → chunk-m3ncxcw8.js.map} +1 -1
- package/dist/{chunk-8zwm5n7d.js → chunk-n31hppcx.js} +2 -2
- package/dist/{chunk-8zwm5n7d.js.map → chunk-n31hppcx.js.map} +1 -1
- package/dist/{chunk-xf8f9tbf.js → chunk-n5gvv25q.js} +2 -2
- package/dist/{chunk-xf8f9tbf.js.map → chunk-n5gvv25q.js.map} +1 -1
- package/dist/{chunk-e14fgtk1.js → chunk-n6hd9swg.js} +2 -2
- package/dist/{chunk-e14fgtk1.js.map → chunk-n6hd9swg.js.map} +1 -1
- package/dist/{chunk-5v07y14d.js → chunk-njrnn5dw.js} +2 -2
- package/dist/{chunk-5v07y14d.js.map → chunk-njrnn5dw.js.map} +1 -1
- package/dist/{chunk-jwvwve00.js → chunk-p9avgpzd.js} +2 -2
- package/dist/{chunk-jwvwve00.js.map → chunk-p9avgpzd.js.map} +1 -1
- package/dist/{chunk-tefb1nz7.js → chunk-pt159v3n.js} +2 -2
- package/dist/{chunk-tefb1nz7.js.map → chunk-pt159v3n.js.map} +1 -1
- package/dist/chunk-px7yzba8.js +117 -0
- package/dist/{chunk-66xyz4m3.js.map → chunk-px7yzba8.js.map} +7 -7
- package/dist/{chunk-me14hs9k.js → chunk-q9xsgn2s.js} +2 -2
- package/dist/{chunk-me14hs9k.js.map → chunk-q9xsgn2s.js.map} +1 -1
- package/dist/{chunk-e7hb47yy.js → chunk-r1sjx2q9.js} +2 -2
- package/dist/{chunk-e7hb47yy.js.map → chunk-r1sjx2q9.js.map} +1 -1
- package/dist/{chunk-r36kq8x1.js → chunk-ry9jard2.js} +3 -3
- package/dist/{chunk-r36kq8x1.js.map → chunk-ry9jard2.js.map} +1 -1
- package/dist/{chunk-47cjayhh.js → chunk-rz6npg3r.js} +3 -3
- package/dist/{chunk-47cjayhh.js.map → chunk-rz6npg3r.js.map} +1 -1
- package/dist/{chunk-cv496s8h.js → chunk-s9etcqcq.js} +2 -2
- package/dist/{chunk-cv496s8h.js.map → chunk-s9etcqcq.js.map} +1 -1
- package/dist/{chunk-9aj6eavs.js → chunk-skyt9hyg.js} +2 -2
- package/dist/{chunk-9aj6eavs.js.map → chunk-skyt9hyg.js.map} +1 -1
- package/dist/{chunk-tv13vbcm.js → chunk-syqvk994.js} +2 -2
- package/dist/{chunk-tv13vbcm.js.map → chunk-syqvk994.js.map} +1 -1
- package/dist/{chunk-y3pnwpvp.js → chunk-t797crcj.js} +3 -3
- package/dist/{chunk-y3pnwpvp.js.map → chunk-t797crcj.js.map} +1 -1
- package/dist/{chunk-r7j4c5t2.js → chunk-tr8s1z7k.js} +3 -3
- package/dist/{chunk-r7j4c5t2.js.map → chunk-tr8s1z7k.js.map} +1 -1
- package/dist/{chunk-ks99tx7f.js → chunk-tvvqhwa3.js} +2 -2
- package/dist/{chunk-ks99tx7f.js.map → chunk-tvvqhwa3.js.map} +1 -1
- package/dist/{chunk-czzyrw7d.js → chunk-vfaen5tf.js} +2 -2
- package/dist/{chunk-czzyrw7d.js.map → chunk-vfaen5tf.js.map} +1 -1
- package/dist/{chunk-bm2zz2j1.js → chunk-vgmmftm2.js} +2 -2
- package/dist/{chunk-bm2zz2j1.js.map → chunk-vgmmftm2.js.map} +1 -1
- package/dist/{chunk-9522w4e4.js → chunk-vm3ayd1b.js} +3 -3
- package/dist/{chunk-9522w4e4.js.map → chunk-vm3ayd1b.js.map} +1 -1
- package/dist/{chunk-mpv431ga.js → chunk-wa7rtfkk.js} +1 -1
- package/dist/{chunk-pw6ssy3a.js → chunk-xh3qqmbk.js} +2 -2
- package/dist/{chunk-xzzdywf6.js.map → chunk-xh3qqmbk.js.map} +1 -1
- package/dist/{chunk-zrrpab1x.js → chunk-xnfkz18n.js} +3 -3
- package/dist/{chunk-zrrpab1x.js.map → chunk-xnfkz18n.js.map} +1 -1
- package/dist/{chunk-s208599z.js → chunk-xwvm54dx.js} +2 -2
- package/dist/{chunk-s208599z.js.map → chunk-xwvm54dx.js.map} +1 -1
- package/dist/{chunk-zqptpk90.js → chunk-y16jhwrv.js} +2 -2
- package/dist/{chunk-zqptpk90.js.map → chunk-y16jhwrv.js.map} +1 -1
- package/dist/chunk-y82d4w0m.js +5 -0
- package/dist/{chunk-vq2a7qd8.js.map → chunk-y82d4w0m.js.map} +1 -1
- package/dist/{chunk-znrk326r.js → chunk-yrd14jjt.js} +1 -1
- package/dist/{chunk-hm1xy515.js → chunk-zscd52sv.js} +3 -3
- package/dist/{chunk-hm1xy515.js.map → chunk-zscd52sv.js.map} +1 -1
- package/dist/{chunk-z8mq4g46.js → chunk-ztvewkks.js} +3 -3
- package/dist/{chunk-z8mq4g46.js.map → chunk-ztvewkks.js.map} +1 -1
- package/dist/chunks/{RealtimeClient-DpAJYcF5.js → RealtimeClient-CHNbqDr7.js} +2 -2
- package/dist/chunks/{RealtimeClient-DpAJYcF5.js.map → RealtimeClient-CHNbqDr7.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-DAbL-cqC.js → ThemeProvider-Bkc6A9Nn.js} +240 -9
- package/dist/chunks/ThemeProvider-Bkc6A9Nn.js.map +1 -0
- package/dist/chunks/{fetchFileRequest-yAKa_pKx.js → fetchFileRequest-BGEW4Wd7.js} +2 -2
- package/dist/chunks/{fetchFileRequest-yAKa_pKx.js.map → fetchFileRequest-BGEW4Wd7.js.map} +1 -1
- package/dist/chunks/{live-BvhWo-yY.js → live-l4vtaqXd.js} +3 -3
- package/dist/chunks/{live-BvhWo-yY.js.map → live-l4vtaqXd.js.map} +1 -1
- package/dist/chunks/{mutationExtras-_hbHxr6-.js → mutationExtras-C7UPW9XP.js} +2 -2
- package/dist/chunks/{mutationExtras-_hbHxr6-.js.map → mutationExtras-C7UPW9XP.js.map} +1 -1
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/QueryResource.d.ts.map +1 -1
- package/dist/client/authenticationErrors.d.ts +116 -0
- package/dist/client/authenticationErrors.d.ts.map +1 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +41 -53
- package/dist/client/index.js.map +1 -1
- package/dist/client/init.d.ts +15 -0
- package/dist/client/init.d.ts.map +1 -1
- package/dist/client/retryPolicy.d.ts +14 -3
- package/dist/client/retryPolicy.d.ts.map +1 -1
- package/dist/client/useMutation.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- 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/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/errors.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/http/signInHeader.d.ts +14 -0
- package/dist/http/signInHeader.d.ts.map +1 -0
- 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/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.d.ts +2 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.js +2 -2
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-51yv7x03.js +0 -41
- package/dist/chunk-66xyz4m3.js +0 -117
- package/dist/chunk-c0qq5t8a.js +0 -15
- package/dist/chunk-vq2a7qd8.js +0 -5
- package/dist/chunks/ThemeProvider-DAbL-cqC.js.map +0 -1
- /package/dist/{chunk-jpq74abh.js.map → chunk-7fzwgvyg.js.map} +0 -0
- /package/dist/{chunk-vv1na1vj.js.map → chunk-7g90w0t6.js.map} +0 -0
- /package/dist/{chunk-5db4v8gv.js.map → chunk-gprc53rf.js.map} +0 -0
- /package/dist/{chunk-sx6jmyaf.js.map → chunk-k6x35rn5.js.map} +0 -0
- /package/dist/{chunk-mpv431ga.js.map → chunk-wa7rtfkk.js.map} +0 -0
- /package/dist/{chunk-znrk326r.js.map → chunk-yrd14jjt.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RealtimeClient-DpAJYcF5.js","names":[],"sources":["../../services/broadcast/protocol.ts","../../client/realtime/RealtimeClient.ts"],"sourcesContent":["/**\n * The `gemi.v1` WebSocket protocol, shared by the server transport\n * (`SocketHub`) and the browser client (`gemi/client`'s connection manager).\n * Types and constants only: this module is imported by the browser bundle, so\n * it must never import a server module.\n *\n * Every frame is a JSON text frame. Binary frames are refused.\n *\n * From the client:\n *\n * - `{op:\"sub\", id, ch, p?}`: subscribe `id` (chosen by the client, unique per\n * socket) to the channel pattern `ch` with params `p`. The server builds\n * the topic and authorizes it.\n * - `{op:\"unsub\", id}`\n * - `{op:\"ping\"}`: answered with `pong`. The client sends one every\n * `heartbeatMs` and reconnects when it hears nothing for twice that.\n *\n * From the server:\n *\n * - `{op:\"hello\", socketId, tag, heartbeatMs}`: the first frame. `socketId`\n * goes in the `X-Gemi-Socket` header of the client's own requests (for\n * `Broadcast.toOthers`); it is never shown to anyone else. `tag` is what\n * an event frame's `x` carries when it skips this socket.\n * - `{op:\"subscribed\", id, t}`: `id` joined topic `t`. Sent only once this\n * process receives the topic's events, so the resync the client runs on it\n * cannot miss one.\n * - `{op:\"denied\", id, code}`: `id` was refused, or later revoked.\n * - `{op:\"ev\", t, ev, d?, x?}`: an event on topic `t`. Dropped by the socket\n * whose `tag` is `x`.\n * - `{op:\"gap\"}`: events may have been lost for this socket; resync all.\n * - `{op:\"pong\"}`\n * - `{op:\"bye\", code, retryAfter}`: the server is going away (a restart).\n * Reconnect after `retryAfter` ms.\n */\n\n/** The WebSocket subprotocol. */\nexport const BROADCAST_PROTOCOL = \"gemi.v1\";\n\n/** The default endpoint, `defineBroadcastConfig({ path })`. */\nexport const DEFAULT_SOCKET_PATH = \"/__gemi/socket\";\n\nexport { SOCKET_ID_HEADER } from \"./socketHeader\";\n\n/** What a subscription id may look like. */\nexport const SUBSCRIPTION_ID = /^[A-Za-z0-9_-]{1,32}$/;\n\n/**\n * Close codes the server uses. 1012 and 1013 are the standard \"restart\" and\n * \"try again later\"; the 4xxx ones are gemi's own.\n */\nexport const CloseCode = {\n /** The client went away (tab closed, socket released). */\n Normal: 1000,\n /** A frame that was not JSON text, or not a known op. */\n UnsupportedData: 1003,\n /** Too many frames, or a frame over the size limit. */\n PolicyViolation: 1008,\n /** The server is restarting; `bye` said when to come back. */\n Restart: 1012,\n /** The socket fell too far behind; reconnect and resync. */\n TryAgainLater: 1013,\n /** The socket's user was signed out or its access revoked. */\n Revoked: 4001,\n} as const;\n\n/** Why a subscription was refused. */\nexport type DeniedCode =\n /** No channel with that pattern. Permanent. */\n | \"unknown_channel\"\n /** Missing, extra or malformed params. Permanent. */\n | \"invalid_params\"\n /** The channel's authorization said no. */\n | \"denied\"\n /** Authorization failed (a session store outage, a bug). Retryable. */\n | \"error\"\n /** The socket has `maxChannelsPerSocket` subscriptions already. */\n | \"limit\"\n /** Too many `sub`/`unsub` frames; retry later. */\n | \"rate_limited\"\n /** The subscription was revoked by `Broadcast.revoke`. */\n | \"revoked\"\n /** The frame was malformed, or the id is already in use. */\n | \"invalid\";\n\nexport type ClientFrame =\n | { op: \"sub\"; id: string; ch: string; p?: Record<string, string | number> }\n | { op: \"unsub\"; id: string }\n | { op: \"ping\" };\n\nexport type ServerFrame =\n | { op: \"hello\"; socketId: string; tag: string; heartbeatMs: number }\n | { op: \"subscribed\"; id: string; t: string }\n | { op: \"denied\"; id: string; code: DeniedCode }\n | { op: \"ev\"; t: string; ev: string; d?: unknown; x?: string }\n | { op: \"gap\" }\n | { op: \"pong\" }\n | { op: \"bye\"; code: number; retryAfter: number };\n\n/**\n * Whether a refusal is final for this socket's session: resubscribing will\n * get the same answer, so the client does not retry it on its own.\n */\nexport function isPermanentDenial(code: DeniedCode): boolean {\n return code === \"unknown_channel\" || code === \"invalid_params\" || code === \"invalid\";\n}\n","import {\n BROADCAST_PROTOCOL,\n CloseCode,\n DEFAULT_SOCKET_PATH,\n isPermanentDenial,\n type ClientFrame,\n type DeniedCode,\n type ServerFrame,\n} from \"../../services/broadcast/protocol\";\nimport { channelKey } from \"./channelKey\";\nimport { realtime } from \"./loader\";\n\n/**\n * Where a channel subscription stands, as the hooks report it.\n *\n * - `idle`: the hook is disabled (`enabled: false`).\n * - `connecting`: the socket is opening, or the `sub` awaits its answer.\n * - `open`: subscribed; events arrive.\n * - `denied`: the server refused (or revoked) it; `code` says why.\n * - `closed`: no socket, on the server, before the first effect, or while\n * waiting to reconnect.\n */\nexport type ChannelStatus = \"idle\" | \"connecting\" | \"open\" | \"denied\" | \"closed\";\n\nexport type ChannelParamValues = Record<string, string | number>;\n\n/** What a hook hands the socket for one channel. */\nexport interface ChannelListener {\n onEvent?(event: string, data: unknown): void;\n /** Events may have been missed: refetch what the channel describes. */\n onResync?(): void;\n onStatus?(status: ChannelStatus, code: DeniedCode | null): void;\n}\n\n/**\n * What the hooks subscribe through: the tab's `RealtimeClient`, or a\n * `FakeSocket` in tests. Returns the release function.\n */\nexport interface RealtimeSocket {\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void;\n}\n\nexport interface RealtimeOptions {\n /** The socket endpoint, `defineBroadcastConfig({ path })`. Default `/__gemi/socket`. */\n path?: string;\n /**\n * How long a hidden tab keeps its socket, in ms, before disconnecting. On\n * becoming visible again it reconnects and resyncs. Default 60 000.\n */\n hiddenDisconnectMs?: number;\n}\n\ninterface ClientInternals {\n /** Test seam: the WebSocket class. */\n WebSocket?: typeof WebSocket;\n /** Test seam: the full URL, instead of the page's origin + `path`. */\n url?: string;\n random?: () => number;\n}\n\n/** The minimum gap between two resyncs of one subscription. */\nexport const RESYNC_COALESCE_MS = 2_000;\n/** How long the socket stays open after its last subscription goes. */\nexport const IDLE_CLOSE_MS = 5_000;\n/**\n * How long a subscription outlives its last listener. A hook that remounts\n * within it (StrictMode's double mount, a route change back, a list that\n * re-renders its rows) picks the same subscription up again: no `unsub`, no\n * new `sub`, nothing counted against the server's rate limit.\n */\nexport const RELEASE_LINGER_MS = 1_500;\n/** The least wait before resending a `sub` denied with `rate_limited`. */\nconst RATE_LIMITED_RETRY_MS = 5_000;\n/**\n * How often a `sub` denied with `limit` is resent on one socket. The socket\n * holds as many channels as the server allows, so only a released one makes\n * room: worth a few tries with backoff, not a retry for as long as the socket\n * lives. Past it the subscription waits for the next connection.\n */\nexport const MAX_LIMIT_RETRIES = 5;\nconst MIN_BACKOFF_MS = 1_000;\nconst MAX_BACKOFF_MS = 30_000;\nconst DEFAULT_HEARTBEAT_MS = 25_000;\nconst DEFAULT_HIDDEN_DISCONNECT_MS = 60_000;\n\ninterface Entry {\n key: string;\n id: string;\n pattern: string;\n params: ChannelParamValues;\n listeners: Set<ChannelListener>;\n status: ChannelStatus;\n code: DeniedCode | null;\n /** Refused for good: not resent on a reconnect. */\n permanent: boolean;\n topic: string | null;\n lastResyncAt: number;\n resyncTimer: ReturnType<typeof setTimeout> | null;\n /** Set while the entry outlives its last listener; see `RELEASE_LINGER_MS`. */\n lingerTimer: ReturnType<typeof setTimeout> | null;\n /** A transient denial's resend, on the same socket. */\n retryTimer: ReturnType<typeof setTimeout> | null;\n retries: number;\n}\n\n/**\n * The tab's one WebSocket to the app (`gemi.v1`), multiplexing every channel\n * the mounted hooks subscribe to.\n *\n * Opened by the first subscription and closed a few seconds after the last\n * one goes. Reconnects with full-jitter backoff (1 to 30 s), or after the\n * server's `bye.retryAfter`, at once on `online`; resubscribes everything\n * then. A tab hidden for `hiddenDisconnectMs` disconnects, and reconnects\n * when shown. Every `subscribed` ack and every `gap` resyncs the\n * subscription (coalesced to one per 2 s), because events are volatile: a\n * client that may have missed one refetches over HTTP.\n *\n * Loaded on first use (#891): import this module as a type only, and reach\n * the tab's instance through `./loader`, or it lands in every route's entry\n * chunk.\n */\nexport class RealtimeClient implements RealtimeSocket {\n private options: Required<RealtimeOptions>;\n private readonly internals: ClientInternals;\n private ws: WebSocket | null = null;\n private entries = new Map<string, Entry>();\n private byId = new Map<string, Entry>();\n private topics = new Map<string, Set<string>>();\n private nextId = 1;\n private attempt = 0;\n private tag: string | null = null;\n private socketIdValue: string | null = null;\n private heartbeatMs = DEFAULT_HEARTBEAT_MS;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private hiddenTimer: ReturnType<typeof setTimeout> | null = null;\n private pingTimer: ReturnType<typeof setInterval> | null = null;\n private livenessTimer: ReturnType<typeof setTimeout> | null = null;\n private retryAfter: number | null = null;\n private revoked = false;\n private pausedWhileHidden = false;\n private listening = false;\n\n constructor(options: RealtimeOptions = {}, internals: ClientInternals = {}) {\n this.options = withDefaults(options);\n this.internals = internals;\n }\n\n configure(options: RealtimeOptions) {\n this.options = withDefaults({ ...this.options, ...options });\n }\n\n /** The id to send as `X-Gemi-Socket`, while the socket is open. */\n get socketId(): string | null {\n return this.socketIdValue;\n }\n\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void {\n const key = channelKey(pattern, params);\n let entry = this.entries.get(key);\n if (!entry) {\n entry = {\n key,\n id: String(this.nextId++),\n pattern,\n params: { ...params },\n listeners: new Set(),\n status: \"closed\",\n code: null,\n permanent: false,\n topic: null,\n lastResyncAt: 0,\n resyncTimer: null,\n lingerTimer: null,\n retryTimer: null,\n retries: 0,\n };\n this.entries.set(key, entry);\n this.byId.set(entry.id, entry);\n if (this.isOpen()) {\n this.sendSub(entry);\n }\n }\n if (entry.lingerTimer) {\n clearTimeout(entry.lingerTimer);\n entry.lingerTimer = null;\n }\n entry.listeners.add(listener);\n listener.onStatus?.(entry.status, entry.code);\n this.cancelIdleClose();\n this.listen();\n if (!this.ws && !this.reconnectTimer && !this.pausedWhileHidden) {\n this.connect();\n }\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.release(entry!, listener);\n };\n }\n\n private release(entry: Entry, listener: ChannelListener) {\n entry.listeners.delete(listener);\n if (entry.listeners.size > 0 || entry.lingerTimer) return;\n entry.lingerTimer = setTimeout(() => {\n entry.lingerTimer = null;\n if (entry.listeners.size === 0) this.drop(entry);\n }, RELEASE_LINGER_MS);\n }\n\n private drop(entry: Entry) {\n if (entry.resyncTimer) clearTimeout(entry.resyncTimer);\n this.clearRetry(entry);\n this.entries.delete(entry.key);\n this.byId.delete(entry.id);\n this.dropTopic(entry);\n if (this.isOpen() && (entry.status === \"open\" || entry.status === \"connecting\")) {\n this.send({ op: \"unsub\", id: entry.id });\n }\n if (this.entries.size === 0) this.scheduleIdleClose();\n }\n\n private isOpen() {\n return this.ws !== null && this.ws.readyState === 1;\n }\n\n private connect() {\n if (typeof window === \"undefined\") return;\n if (this.entries.size === 0) return;\n const Impl = this.internals.WebSocket ?? globalThis.WebSocket;\n if (!Impl) return;\n this.clearReconnect();\n let ws: WebSocket;\n try {\n ws = new Impl(this.url(), [BROADCAST_PROTOCOL]);\n } catch {\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n for (const entry of this.entries.values()) {\n if (!entry.permanent) this.setStatus(entry, \"connecting\", null);\n }\n ws.onopen = () => {\n if (this.ws !== ws) return;\n this.touch();\n for (const entry of this.entries.values()) {\n if (entry.permanent) continue;\n // A new socket starts every transient denial's count over.\n entry.retries = 0;\n this.sendSub(entry);\n }\n };\n ws.onmessage = (event: MessageEvent) => {\n if (this.ws !== ws) return;\n this.touch();\n let frame: ServerFrame;\n try {\n frame = JSON.parse(String(event.data));\n } catch {\n return;\n }\n this.handle(frame);\n };\n ws.onclose = (event: CloseEvent) => {\n if (this.ws !== ws) return;\n this.onClosed(event.code);\n };\n ws.onerror = () => {\n // A `close` follows.\n };\n }\n\n private url(): string {\n if (this.internals.url) return this.internals.url;\n const { protocol, host } = window.location;\n return `${protocol === \"https:\" ? \"wss:\" : \"ws:\"}//${host}${this.options.path}`;\n }\n\n private sendSub(entry: Entry) {\n this.setStatus(entry, \"connecting\", null);\n const frame: ClientFrame = { op: \"sub\", id: entry.id, ch: entry.pattern };\n if (Object.keys(entry.params).length > 0) frame.p = entry.params;\n this.send(frame);\n }\n\n private send(frame: ClientFrame) {\n if (!this.isOpen()) return;\n try {\n this.ws!.send(JSON.stringify(frame));\n } catch {\n // The close handler takes over.\n }\n }\n\n private handle(frame: ServerFrame) {\n switch (frame.op) {\n case \"hello\":\n this.socketIdValue = frame.socketId;\n this.tag = frame.tag;\n this.attempt = 0;\n this.revoked = false;\n if (frame.heartbeatMs > 0) {\n this.heartbeatMs = frame.heartbeatMs;\n }\n this.startHeartbeat();\n return;\n case \"subscribed\": {\n const entry = this.byId.get(frame.id);\n if (!entry) return;\n this.dropTopic(entry);\n entry.topic = frame.t;\n let ids = this.topics.get(frame.t);\n if (!ids) this.topics.set(frame.t, (ids = new Set()));\n ids.add(entry.id);\n this.clearRetry(entry);\n entry.retries = 0;\n this.setStatus(entry, \"open\", null);\n // The window between the view rendering and this ack, or the time\n // the socket was down, may have carried events this tab missed.\n this.resync(entry);\n return;\n }\n case \"denied\": {\n const entry = this.byId.get(frame.id);\n if (!entry) return;\n this.dropTopic(entry);\n entry.permanent = isPermanentDenial(frame.code);\n this.setStatus(entry, \"denied\", frame.code);\n this.scheduleRetry(entry, frame.code);\n return;\n }\n case \"ev\": {\n if (frame.x !== undefined && frame.x === this.tag) return;\n const ids = this.topics.get(frame.t);\n if (!ids) return;\n for (const id of Array.from(ids)) {\n const entry = this.byId.get(id);\n if (!entry) continue;\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onEvent?.(frame.ev, frame.d);\n } catch (error) {\n reportListenerError(error);\n }\n }\n }\n return;\n }\n case \"gap\":\n for (const entry of this.entries.values()) {\n if (entry.status === \"open\") this.resync(entry);\n }\n return;\n case \"bye\":\n this.retryAfter = Math.max(0, Number(frame.retryAfter) || 0);\n return;\n case \"pong\":\n return;\n }\n }\n\n private onClosed(code: number) {\n this.ws = null;\n this.socketIdValue = null;\n this.tag = null;\n this.stopHeartbeat();\n this.topics.clear();\n for (const entry of this.entries.values()) {\n entry.topic = null;\n // The reconnect resends it.\n this.clearRetry(entry);\n if (!entry.permanent) this.setStatus(entry, \"closed\", null);\n }\n if (code === CloseCode.Revoked) this.revoked = true;\n if (this.entries.size > 0 && !this.pausedWhileHidden) this.scheduleReconnect();\n }\n\n private scheduleReconnect() {\n this.clearReconnect();\n let delay: number;\n if (this.retryAfter !== null) {\n delay = this.retryAfter;\n this.retryAfter = null;\n } else if (this.revoked) {\n // Signed out or access revoked: come back promptly, as whoever we are now.\n this.revoked = false;\n delay = Math.floor(this.random() * 500);\n } else {\n delay = backoffDelay(this.attempt, this.random());\n }\n this.attempt++;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.connect();\n }, delay);\n }\n\n private clearReconnect() {\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n private random() {\n return (this.internals.random ?? Math.random)();\n }\n\n private startHeartbeat() {\n this.stopHeartbeat();\n this.pingTimer = setInterval(() => this.send({ op: \"ping\" }), this.heartbeatMs);\n this.touch();\n }\n\n private stopHeartbeat() {\n if (this.pingTimer) clearInterval(this.pingTimer);\n if (this.livenessTimer) clearTimeout(this.livenessTimer);\n this.pingTimer = null;\n this.livenessTimer = null;\n }\n\n /** Anything from the server proves the socket alive. */\n private touch() {\n if (this.livenessTimer) clearTimeout(this.livenessTimer);\n const ws = this.ws;\n this.livenessTimer = setTimeout(() => {\n if (this.ws !== ws || !ws) return;\n // Silent for two heartbeats: a dead connection a proxy never closed.\n try {\n ws.close();\n } catch {}\n this.onClosed(1006);\n }, this.heartbeatMs * 2);\n }\n\n private setStatus(entry: Entry, status: ChannelStatus, code: DeniedCode | null) {\n if (entry.status === status && entry.code === code) return;\n entry.status = status;\n entry.code = code;\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onStatus?.(status, code);\n } catch (error) {\n reportListenerError(error);\n }\n }\n }\n\n /** At most one resync per subscription per 2 s; a later one is deferred, not dropped. */\n private resync(entry: Entry) {\n if (entry.resyncTimer) return;\n const now = Date.now();\n const wait = entry.lastResyncAt + RESYNC_COALESCE_MS - now;\n const fire = () => {\n entry.resyncTimer = null;\n entry.lastResyncAt = Date.now();\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onResync?.();\n } catch (error) {\n reportListenerError(error);\n }\n }\n };\n if (entry.lastResyncAt === 0 || wait <= 0) fire();\n else entry.resyncTimer = setTimeout(fire, wait);\n }\n\n /**\n * A transient denial (`rate_limited`, `error`, `limit`) is retried on the\n * same socket, with backoff: a healthy socket may never reconnect. `denied`\n * and `revoked` are the channel's answer for this session, so they wait for\n * the next connection (a sign-in reconnects), and a permanent one is never\n * resent. `limit` gives up after `MAX_LIMIT_RETRIES` on one socket.\n */\n private scheduleRetry(entry: Entry, code: DeniedCode) {\n if (code !== \"rate_limited\" && code !== \"error\" && code !== \"limit\") return;\n if (code === \"limit\" && entry.retries >= MAX_LIMIT_RETRIES) return;\n this.clearRetry(entry);\n const floor = code === \"rate_limited\" ? RATE_LIMITED_RETRY_MS : MIN_BACKOFF_MS;\n const delay = Math.max(floor, backoffDelay(entry.retries, this.random()));\n entry.retries++;\n entry.retryTimer = setTimeout(() => {\n entry.retryTimer = null;\n if (this.entries.get(entry.key) !== entry || entry.status !== \"denied\") return;\n if (this.isOpen()) this.sendSub(entry);\n }, delay);\n }\n\n private clearRetry(entry: Entry) {\n if (entry.retryTimer) clearTimeout(entry.retryTimer);\n entry.retryTimer = null;\n }\n\n private dropTopic(entry: Entry) {\n if (!entry.topic) return;\n const ids = this.topics.get(entry.topic);\n ids?.delete(entry.id);\n if (ids && ids.size === 0) this.topics.delete(entry.topic);\n entry.topic = null;\n }\n\n private scheduleIdleClose() {\n this.cancelIdleClose();\n this.idleTimer = setTimeout(() => {\n this.idleTimer = null;\n if (this.entries.size > 0) return;\n this.clearReconnect();\n this.close();\n }, IDLE_CLOSE_MS);\n }\n\n private cancelIdleClose() {\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n\n /** Closes the socket without reconnecting. */\n private close() {\n const ws = this.ws;\n if (!ws) return;\n this.ws = null;\n try {\n ws.close(CloseCode.Normal);\n } catch {}\n this.onClosed(CloseCode.Normal);\n }\n\n private listen() {\n if (this.listening || typeof window === \"undefined\") return;\n this.listening = true;\n window.addEventListener(\"online\", this.onOnline);\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n }\n }\n\n private onOnline = () => {\n if (this.entries.size === 0 || this.ws || this.pausedWhileHidden) return;\n this.attempt = 0;\n this.connect();\n };\n\n private onVisibility = () => {\n if (document.visibilityState === \"hidden\") {\n if (this.hiddenTimer) return;\n this.hiddenTimer = setTimeout(() => {\n this.hiddenTimer = null;\n if (document.visibilityState !== \"hidden\") return;\n this.pausedWhileHidden = true;\n this.clearReconnect();\n this.close();\n }, this.options.hiddenDisconnectMs);\n return;\n }\n if (this.hiddenTimer) clearTimeout(this.hiddenTimer);\n this.hiddenTimer = null;\n if (this.pausedWhileHidden) {\n this.pausedWhileHidden = false;\n this.attempt = 0;\n // The `subscribed` acks resync every subscription.\n this.connect();\n }\n };\n\n /**\n * Drops the socket and opens a new one at once, when anything is\n * subscribed. A socket keeps the session it was opened with (the upgrade's\n * cookies), so signing in or out in this tab reconnects it: every channel\n * is then authorized as the new session, and the acks resync.\n */\n reconnect() {\n this.close();\n this.clearReconnect();\n this.attempt = 0;\n if (this.entries.size > 0 && !this.pausedWhileHidden) this.connect();\n }\n\n /** For tests: drops the socket, timers and listeners. */\n dispose() {\n this.clearReconnect();\n this.cancelIdleClose();\n if (this.hiddenTimer) clearTimeout(this.hiddenTimer);\n for (const entry of this.entries.values()) {\n if (entry.resyncTimer) clearTimeout(entry.resyncTimer);\n if (entry.lingerTimer) clearTimeout(entry.lingerTimer);\n this.clearRetry(entry);\n }\n this.entries.clear();\n this.byId.clear();\n this.close();\n if (this.listening && typeof window !== \"undefined\") {\n window.removeEventListener(\"online\", this.onOnline);\n document?.removeEventListener(\"visibilitychange\", this.onVisibility);\n this.listening = false;\n }\n }\n}\n\n/** Full jitter, 1 to 30 s: `max(1 s, random × min(30 s, 1 s × 2^attempt))`. */\nexport function backoffDelay(attempt: number, random: number): number {\n const cap = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** Math.min(attempt, 10));\n return Math.max(MIN_BACKOFF_MS, Math.floor(random * cap));\n}\n\nfunction withDefaults(options: RealtimeOptions): Required<RealtimeOptions> {\n return {\n path: options.path ?? DEFAULT_SOCKET_PATH,\n hiddenDisconnectMs: options.hiddenDisconnectMs ?? DEFAULT_HIDDEN_DISCONNECT_MS,\n };\n}\n\nfunction reportListenerError(error: unknown) {\n setTimeout(() => {\n throw error;\n });\n}\n\n/**\n * The tab's client, created on first use with the options `configureRealtime`\n * set. `loadRealtimeClient` in `./loader` calls it once this module is loaded.\n */\nexport function tabClient(): RealtimeClient {\n return (realtime.client ??= new RealtimeClient(realtime.options));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,qBAAqB;;;;;AAclC,IAAa,YAAY;;CAEvB,QAAQ;;CAER,iBAAiB;;CAEjB,iBAAiB;;CAEjB,SAAS;;CAET,eAAe;;CAEf,SAAS;AACX;;;;;AAuCA,SAAgB,kBAAkB,MAA2B;CAC3D,OAAO,SAAS,qBAAqB,SAAS,oBAAoB,SAAS;AAC7E;;;;AC3CA,IAAa,qBAAqB;;AAElC,IAAa,gBAAgB;;;;;;;AAO7B,IAAa,oBAAoB;;AAEjC,IAAM,wBAAwB;;;;;;;AAO9B,IAAa,oBAAoB;AACjC,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,uBAAuB;AAC7B,IAAM,+BAA+B;;;;;;;;;;;;;;;;;AAsCrC,IAAa,iBAAb,MAAsD;CACpD;CACA;CACA,KAA+B;CAC/B,0BAAkB,IAAI,IAAmB;CACzC,uBAAe,IAAI,IAAmB;CACtC,yBAAiB,IAAI,IAAyB;CAC9C,SAAiB;CACjB,UAAkB;CAClB,MAA6B;CAC7B,gBAAuC;CACvC,cAAsB;CACtB,iBAA+D;CAC/D,YAA0D;CAC1D,cAA4D;CAC5D,YAA2D;CAC3D,gBAA8D;CAC9D,aAAoC;CACpC,UAAkB;CAClB,oBAA4B;CAC5B,YAAoB;CAEpB,YAAY,UAA2B,CAAC,GAAG,YAA6B,CAAC,GAAG;EAC1E,KAAK,UAAU,aAAa,OAAO;EACnC,KAAK,YAAY;CACnB;CAEA,UAAU,SAA0B;E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UAAU;GAEf,KAAK,QAAQ;EACf;CACF;;;;;;;CAQA,YAAY;EACV,KAAK,MAAM;EACX,KAAK,eAAe;EACpB,KAAK,UAAU;EACf,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC,KAAK,mBAAmB,KAAK,QAAQ;CACrE;;CAGA,UAAU;EACR,KAAK,eAAe;EACpB,KAAK,gBAAgB;EACrB,IAAI,KAAK,aAAa,aAAa,KAAK,WAAW;EACnD,KAAK,MAAM,SAAS,KAAK,QAAQ,OAAO,GAAG;GACzC,IAAI,MAAM,aAAa,aAAa,MAAM,WAAW;GACrD,IAAI,MAAM,aAAa,aAAa,MAAM,WAAW;GACrD,KAAK,WAAW,KAAK;EACvB;EACA,KAAK,QAAQ,MAAM;EACnB,KAAK,KAAK,MAAM;EAChB,KAAK,MAAM;EACX,IAAI,KAAK,aAAa,OAAO,WAAW,aAAa;GACnD,OAAO,oBAAoB,UAAU,KAAK,QAAQ;GAClD,UAAU,oBAAoB,oBAAoB,KAAK,YAAY;GACnE,KAAK,YAAY;EACnB;CACF;AACF;;AAGA,SAAgB,aAAa,SAAiB,QAAwB;CACpE,MAAM,MAAM,KAAK,IAAI,gBAAgB,iBAAiB,KAAK,KAAK,IAAI,SAAS,EAAE,CAAC;CAChF,OAAO,KAAK,IAAI,gBAAgB,KAAK,MAAM,SAAS,GAAG,CAAC;AAC1D;AAEA,SAAS,aAAa,SAAqD;CACzE,OAAO;EACL,MAAM,QAAQ,QAAA;EACd,oBAAoB,QAAQ,sBAAsB;CACpD;AACF;AAEA,SAAS,oBAAoB,OAAgB;CAC3C,iBAAiB;EACf,MAAM;CACR,CAAC;AACH;;;;;AAMA,SAAgB,YAA4B;CAC1C,OAAQ,SAAS,WAAW,IAAI,eAAe,SAAS,OAAO;AACjE"}
|
|
1
|
+
{"version":3,"file":"RealtimeClient-CHNbqDr7.js","names":[],"sources":["../../services/broadcast/protocol.ts","../../client/realtime/RealtimeClient.ts"],"sourcesContent":["/**\n * The `gemi.v1` WebSocket protocol, shared by the server transport\n * (`SocketHub`) and the browser client (`gemi/client`'s connection manager).\n * Types and constants only: this module is imported by the browser bundle, so\n * it must never import a server module.\n *\n * Every frame is a JSON text frame. Binary frames are refused.\n *\n * From the client:\n *\n * - `{op:\"sub\", id, ch, p?}`: subscribe `id` (chosen by the client, unique per\n * socket) to the channel pattern `ch` with params `p`. The server builds\n * the topic and authorizes it.\n * - `{op:\"unsub\", id}`\n * - `{op:\"ping\"}`: answered with `pong`. The client sends one every\n * `heartbeatMs` and reconnects when it hears nothing for twice that.\n *\n * From the server:\n *\n * - `{op:\"hello\", socketId, tag, heartbeatMs}`: the first frame. `socketId`\n * goes in the `X-Gemi-Socket` header of the client's own requests (for\n * `Broadcast.toOthers`); it is never shown to anyone else. `tag` is what\n * an event frame's `x` carries when it skips this socket.\n * - `{op:\"subscribed\", id, t}`: `id` joined topic `t`. Sent only once this\n * process receives the topic's events, so the resync the client runs on it\n * cannot miss one.\n * - `{op:\"denied\", id, code}`: `id` was refused, or later revoked.\n * - `{op:\"ev\", t, ev, d?, x?}`: an event on topic `t`. Dropped by the socket\n * whose `tag` is `x`.\n * - `{op:\"gap\"}`: events may have been lost for this socket; resync all.\n * - `{op:\"pong\"}`\n * - `{op:\"bye\", code, retryAfter}`: the server is going away (a restart).\n * Reconnect after `retryAfter` ms.\n */\n\n/** The WebSocket subprotocol. */\nexport const BROADCAST_PROTOCOL = \"gemi.v1\";\n\n/** The default endpoint, `defineBroadcastConfig({ path })`. */\nexport const DEFAULT_SOCKET_PATH = \"/__gemi/socket\";\n\nexport { SOCKET_ID_HEADER } from \"./socketHeader\";\n\n/** What a subscription id may look like. */\nexport const SUBSCRIPTION_ID = /^[A-Za-z0-9_-]{1,32}$/;\n\n/**\n * Close codes the server uses. 1012 and 1013 are the standard \"restart\" and\n * \"try again later\"; the 4xxx ones are gemi's own.\n */\nexport const CloseCode = {\n /** The client went away (tab closed, socket released). */\n Normal: 1000,\n /** A frame that was not JSON text, or not a known op. */\n UnsupportedData: 1003,\n /** Too many frames, or a frame over the size limit. */\n PolicyViolation: 1008,\n /** The server is restarting; `bye` said when to come back. */\n Restart: 1012,\n /** The socket fell too far behind; reconnect and resync. */\n TryAgainLater: 1013,\n /** The socket's user was signed out or its access revoked. */\n Revoked: 4001,\n} as const;\n\n/** Why a subscription was refused. */\nexport type DeniedCode =\n /** No channel with that pattern. Permanent. */\n | \"unknown_channel\"\n /** Missing, extra or malformed params. Permanent. */\n | \"invalid_params\"\n /** The channel's authorization said no. */\n | \"denied\"\n /** Authorization failed (a session store outage, a bug). Retryable. */\n | \"error\"\n /** The socket has `maxChannelsPerSocket` subscriptions already. */\n | \"limit\"\n /** Too many `sub`/`unsub` frames; retry later. */\n | \"rate_limited\"\n /** The subscription was revoked by `Broadcast.revoke`. */\n | \"revoked\"\n /** The frame was malformed, or the id is already in use. */\n | \"invalid\";\n\nexport type ClientFrame =\n | { op: \"sub\"; id: string; ch: string; p?: Record<string, string | number> }\n | { op: \"unsub\"; id: string }\n | { op: \"ping\" };\n\nexport type ServerFrame =\n | { op: \"hello\"; socketId: string; tag: string; heartbeatMs: number }\n | { op: \"subscribed\"; id: string; t: string }\n | { op: \"denied\"; id: string; code: DeniedCode }\n | { op: \"ev\"; t: string; ev: string; d?: unknown; x?: string }\n | { op: \"gap\" }\n | { op: \"pong\" }\n | { op: \"bye\"; code: number; retryAfter: number };\n\n/**\n * Whether a refusal is final for this socket's session: resubscribing will\n * get the same answer, so the client does not retry it on its own.\n */\nexport function isPermanentDenial(code: DeniedCode): boolean {\n return code === \"unknown_channel\" || code === \"invalid_params\" || code === \"invalid\";\n}\n","import {\n BROADCAST_PROTOCOL,\n CloseCode,\n DEFAULT_SOCKET_PATH,\n isPermanentDenial,\n type ClientFrame,\n type DeniedCode,\n type ServerFrame,\n} from \"../../services/broadcast/protocol\";\nimport { channelKey } from \"./channelKey\";\nimport { realtime } from \"./loader\";\n\n/**\n * Where a channel subscription stands, as the hooks report it.\n *\n * - `idle`: the hook is disabled (`enabled: false`).\n * - `connecting`: the socket is opening, or the `sub` awaits its answer.\n * - `open`: subscribed; events arrive.\n * - `denied`: the server refused (or revoked) it; `code` says why.\n * - `closed`: no socket, on the server, before the first effect, or while\n * waiting to reconnect.\n */\nexport type ChannelStatus = \"idle\" | \"connecting\" | \"open\" | \"denied\" | \"closed\";\n\nexport type ChannelParamValues = Record<string, string | number>;\n\n/** What a hook hands the socket for one channel. */\nexport interface ChannelListener {\n onEvent?(event: string, data: unknown): void;\n /** Events may have been missed: refetch what the channel describes. */\n onResync?(): void;\n onStatus?(status: ChannelStatus, code: DeniedCode | null): void;\n}\n\n/**\n * What the hooks subscribe through: the tab's `RealtimeClient`, or a\n * `FakeSocket` in tests. Returns the release function.\n */\nexport interface RealtimeSocket {\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void;\n}\n\nexport interface RealtimeOptions {\n /** The socket endpoint, `defineBroadcastConfig({ path })`. Default `/__gemi/socket`. */\n path?: string;\n /**\n * How long a hidden tab keeps its socket, in ms, before disconnecting. On\n * becoming visible again it reconnects and resyncs. Default 60 000.\n */\n hiddenDisconnectMs?: number;\n}\n\ninterface ClientInternals {\n /** Test seam: the WebSocket class. */\n WebSocket?: typeof WebSocket;\n /** Test seam: the full URL, instead of the page's origin + `path`. */\n url?: string;\n random?: () => number;\n}\n\n/** The minimum gap between two resyncs of one subscription. */\nexport const RESYNC_COALESCE_MS = 2_000;\n/** How long the socket stays open after its last subscription goes. */\nexport const IDLE_CLOSE_MS = 5_000;\n/**\n * How long a subscription outlives its last listener. A hook that remounts\n * within it (StrictMode's double mount, a route change back, a list that\n * re-renders its rows) picks the same subscription up again: no `unsub`, no\n * new `sub`, nothing counted against the server's rate limit.\n */\nexport const RELEASE_LINGER_MS = 1_500;\n/** The least wait before resending a `sub` denied with `rate_limited`. */\nconst RATE_LIMITED_RETRY_MS = 5_000;\n/**\n * How often a `sub` denied with `limit` is resent on one socket. The socket\n * holds as many channels as the server allows, so only a released one makes\n * room: worth a few tries with backoff, not a retry for as long as the socket\n * lives. Past it the subscription waits for the next connection.\n */\nexport const MAX_LIMIT_RETRIES = 5;\nconst MIN_BACKOFF_MS = 1_000;\nconst MAX_BACKOFF_MS = 30_000;\nconst DEFAULT_HEARTBEAT_MS = 25_000;\nconst DEFAULT_HIDDEN_DISCONNECT_MS = 60_000;\n\ninterface Entry {\n key: string;\n id: string;\n pattern: string;\n params: ChannelParamValues;\n listeners: Set<ChannelListener>;\n status: ChannelStatus;\n code: DeniedCode | null;\n /** Refused for good: not resent on a reconnect. */\n permanent: boolean;\n topic: string | null;\n lastResyncAt: number;\n resyncTimer: ReturnType<typeof setTimeout> | null;\n /** Set while the entry outlives its last listener; see `RELEASE_LINGER_MS`. */\n lingerTimer: ReturnType<typeof setTimeout> | null;\n /** A transient denial's resend, on the same socket. */\n retryTimer: ReturnType<typeof setTimeout> | null;\n retries: number;\n}\n\n/**\n * The tab's one WebSocket to the app (`gemi.v1`), multiplexing every channel\n * the mounted hooks subscribe to.\n *\n * Opened by the first subscription and closed a few seconds after the last\n * one goes. Reconnects with full-jitter backoff (1 to 30 s), or after the\n * server's `bye.retryAfter`, at once on `online`; resubscribes everything\n * then. A tab hidden for `hiddenDisconnectMs` disconnects, and reconnects\n * when shown. Every `subscribed` ack and every `gap` resyncs the\n * subscription (coalesced to one per 2 s), because events are volatile: a\n * client that may have missed one refetches over HTTP.\n *\n * Loaded on first use (#891): import this module as a type only, and reach\n * the tab's instance through `./loader`, or it lands in every route's entry\n * chunk.\n */\nexport class RealtimeClient implements RealtimeSocket {\n private options: Required<RealtimeOptions>;\n private readonly internals: ClientInternals;\n private ws: WebSocket | null = null;\n private entries = new Map<string, Entry>();\n private byId = new Map<string, Entry>();\n private topics = new Map<string, Set<string>>();\n private nextId = 1;\n private attempt = 0;\n private tag: string | null = null;\n private socketIdValue: string | null = null;\n private heartbeatMs = DEFAULT_HEARTBEAT_MS;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private hiddenTimer: ReturnType<typeof setTimeout> | null = null;\n private pingTimer: ReturnType<typeof setInterval> | null = null;\n private livenessTimer: ReturnType<typeof setTimeout> | null = null;\n private retryAfter: number | null = null;\n private revoked = false;\n private pausedWhileHidden = false;\n private listening = false;\n\n constructor(options: RealtimeOptions = {}, internals: ClientInternals = {}) {\n this.options = withDefaults(options);\n this.internals = internals;\n }\n\n configure(options: RealtimeOptions) {\n this.options = withDefaults({ ...this.options, ...options });\n }\n\n /** The id to send as `X-Gemi-Socket`, while the socket is open. */\n get socketId(): string | null {\n return this.socketIdValue;\n }\n\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void {\n const key = channelKey(pattern, params);\n let entry = this.entries.get(key);\n if (!entry) {\n entry = {\n key,\n id: String(this.nextId++),\n pattern,\n params: { ...params },\n listeners: new Set(),\n status: \"closed\",\n code: null,\n permanent: false,\n topic: null,\n lastResyncAt: 0,\n resyncTimer: null,\n lingerTimer: null,\n retryTimer: null,\n retries: 0,\n };\n this.entries.set(key, entry);\n this.byId.set(entry.id, entry);\n if (this.isOpen()) {\n this.sendSub(entry);\n }\n }\n if (entry.lingerTimer) {\n clearTimeout(entry.lingerTimer);\n entry.lingerTimer = null;\n }\n entry.listeners.add(listener);\n listener.onStatus?.(entry.status, entry.code);\n this.cancelIdleClose();\n this.listen();\n if (!this.ws && !this.reconnectTimer && !this.pausedWhileHidden) {\n this.connect();\n }\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.release(entry!, listener);\n };\n }\n\n private release(entry: Entry, listener: ChannelListener) {\n entry.listeners.delete(listener);\n if (entry.listeners.size > 0 || entry.lingerTimer) return;\n entry.lingerTimer = setTimeout(() => {\n entry.lingerTimer = null;\n if (entry.listeners.size === 0) this.drop(entry);\n }, RELEASE_LINGER_MS);\n }\n\n private drop(entry: Entry) {\n if (entry.resyncTimer) clearTimeout(entry.resyncTimer);\n this.clearRetry(entry);\n this.entries.delete(entry.key);\n this.byId.delete(entry.id);\n this.dropTopic(entry);\n if (this.isOpen() && (entry.status === \"open\" || entry.status === \"connecting\")) {\n this.send({ op: \"unsub\", id: entry.id });\n }\n if (this.entries.size === 0) this.scheduleIdleClose();\n }\n\n private isOpen() {\n return this.ws !== null && this.ws.readyState === 1;\n }\n\n private connect() {\n if (typeof window === \"undefined\") return;\n if (this.entries.size === 0) return;\n const Impl = this.internals.WebSocket ?? globalThis.WebSocket;\n if (!Impl) return;\n this.clearReconnect();\n let ws: WebSocket;\n try {\n ws = new Impl(this.url(), [BROADCAST_PROTOCOL]);\n } catch {\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n for (const entry of this.entries.values()) {\n if (!entry.permanent) this.setStatus(entry, \"connecting\", null);\n }\n ws.onopen = () => {\n if (this.ws !== ws) return;\n this.touch();\n for (const entry of this.entries.values()) {\n if (entry.permanent) continue;\n // A new socket starts every transient denial's count over.\n entry.retries = 0;\n this.sendSub(entry);\n }\n };\n ws.onmessage = (event: MessageEvent) => {\n if (this.ws !== ws) return;\n this.touch();\n let frame: ServerFrame;\n try {\n frame = JSON.parse(String(event.data));\n } catch {\n return;\n }\n this.handle(frame);\n };\n ws.onclose = (event: CloseEvent) => {\n if (this.ws !== ws) return;\n this.onClosed(event.code);\n };\n ws.onerror = () => {\n // A `close` follows.\n };\n }\n\n private url(): string {\n if (this.internals.url) return this.internals.url;\n const { protocol, host } = window.location;\n return `${protocol === \"https:\" ? \"wss:\" : \"ws:\"}//${host}${this.options.path}`;\n }\n\n private sendSub(entry: Entry) {\n this.setStatus(entry, \"connecting\", null);\n const frame: ClientFrame = { op: \"sub\", id: entry.id, ch: entry.pattern };\n if (Object.keys(entry.params).length > 0) frame.p = entry.params;\n this.send(frame);\n }\n\n private send(frame: ClientFrame) {\n if (!this.isOpen()) return;\n try {\n this.ws!.send(JSON.stringify(frame));\n } catch {\n // The close handler takes over.\n }\n }\n\n private handle(frame: ServerFrame) {\n switch (frame.op) {\n case \"hello\":\n this.socketIdValue = frame.socketId;\n this.tag = frame.tag;\n this.attempt = 0;\n this.revoked = false;\n if (frame.heartbeatMs > 0) {\n this.heartbeatMs = frame.heartbeatMs;\n }\n this.startHeartbeat();\n return;\n case \"subscribed\": {\n const entry = this.byId.get(frame.id);\n if (!entry) return;\n this.dropTopic(entry);\n entry.topic = frame.t;\n let ids = this.topics.get(frame.t);\n if (!ids) this.topics.set(frame.t, (ids = new Set()));\n ids.add(entry.id);\n this.clearRetry(entry);\n entry.retries = 0;\n this.setStatus(entry, \"open\", null);\n // The window between the view rendering and this ack, or the time\n // the socket was down, may have carried events this tab missed.\n this.resync(entry);\n return;\n }\n case \"denied\": {\n const entry = this.byId.get(frame.id);\n if (!entry) return;\n this.dropTopic(entry);\n entry.permanent = isPermanentDenial(frame.code);\n this.setStatus(entry, \"denied\", frame.code);\n this.scheduleRetry(entry, frame.code);\n return;\n }\n case \"ev\": {\n if (frame.x !== undefined && frame.x === this.tag) return;\n const ids = this.topics.get(frame.t);\n if (!ids) return;\n for (const id of Array.from(ids)) {\n const entry = this.byId.get(id);\n if (!entry) continue;\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onEvent?.(frame.ev, frame.d);\n } catch (error) {\n reportListenerError(error);\n }\n }\n }\n return;\n }\n case \"gap\":\n for (const entry of this.entries.values()) {\n if (entry.status === \"open\") this.resync(entry);\n }\n return;\n case \"bye\":\n this.retryAfter = Math.max(0, Number(frame.retryAfter) || 0);\n return;\n case \"pong\":\n return;\n }\n }\n\n private onClosed(code: number) {\n this.ws = null;\n this.socketIdValue = null;\n this.tag = null;\n this.stopHeartbeat();\n this.topics.clear();\n for (const entry of this.entries.values()) {\n entry.topic = null;\n // The reconnect resends it.\n this.clearRetry(entry);\n if (!entry.permanent) this.setStatus(entry, \"closed\", null);\n }\n if (code === CloseCode.Revoked) this.revoked = true;\n if (this.entries.size > 0 && !this.pausedWhileHidden) this.scheduleReconnect();\n }\n\n private scheduleReconnect() {\n this.clearReconnect();\n let delay: number;\n if (this.retryAfter !== null) {\n delay = this.retryAfter;\n this.retryAfter = null;\n } else if (this.revoked) {\n // Signed out or access revoked: come back promptly, as whoever we are now.\n this.revoked = false;\n delay = Math.floor(this.random() * 500);\n } else {\n delay = backoffDelay(this.attempt, this.random());\n }\n this.attempt++;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.connect();\n }, delay);\n }\n\n private clearReconnect() {\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n private random() {\n return (this.internals.random ?? Math.random)();\n }\n\n private startHeartbeat() {\n this.stopHeartbeat();\n this.pingTimer = setInterval(() => this.send({ op: \"ping\" }), this.heartbeatMs);\n this.touch();\n }\n\n private stopHeartbeat() {\n if (this.pingTimer) clearInterval(this.pingTimer);\n if (this.livenessTimer) clearTimeout(this.livenessTimer);\n this.pingTimer = null;\n this.livenessTimer = null;\n }\n\n /** Anything from the server proves the socket alive. */\n private touch() {\n if (this.livenessTimer) clearTimeout(this.livenessTimer);\n const ws = this.ws;\n this.livenessTimer = setTimeout(() => {\n if (this.ws !== ws || !ws) return;\n // Silent for two heartbeats: a dead connection a proxy never closed.\n try {\n ws.close();\n } catch {}\n this.onClosed(1006);\n }, this.heartbeatMs * 2);\n }\n\n private setStatus(entry: Entry, status: ChannelStatus, code: DeniedCode | null) {\n if (entry.status === status && entry.code === code) return;\n entry.status = status;\n entry.code = code;\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onStatus?.(status, code);\n } catch (error) {\n reportListenerError(error);\n }\n }\n }\n\n /** At most one resync per subscription per 2 s; a later one is deferred, not dropped. */\n private resync(entry: Entry) {\n if (entry.resyncTimer) return;\n const now = Date.now();\n const wait = entry.lastResyncAt + RESYNC_COALESCE_MS - now;\n const fire = () => {\n entry.resyncTimer = null;\n entry.lastResyncAt = Date.now();\n for (const listener of Array.from(entry.listeners)) {\n try {\n listener.onResync?.();\n } catch (error) {\n reportListenerError(error);\n }\n }\n };\n if (entry.lastResyncAt === 0 || wait <= 0) fire();\n else entry.resyncTimer = setTimeout(fire, wait);\n }\n\n /**\n * A transient denial (`rate_limited`, `error`, `limit`) is retried on the\n * same socket, with backoff: a healthy socket may never reconnect. `denied`\n * and `revoked` are the channel's answer for this session, so they wait for\n * the next connection (a sign-in reconnects), and a permanent one is never\n * resent. `limit` gives up after `MAX_LIMIT_RETRIES` on one socket.\n */\n private scheduleRetry(entry: Entry, code: DeniedCode) {\n if (code !== \"rate_limited\" && code !== \"error\" && code !== \"limit\") return;\n if (code === \"limit\" && entry.retries >= MAX_LIMIT_RETRIES) return;\n this.clearRetry(entry);\n const floor = code === \"rate_limited\" ? RATE_LIMITED_RETRY_MS : MIN_BACKOFF_MS;\n const delay = Math.max(floor, backoffDelay(entry.retries, this.random()));\n entry.retries++;\n entry.retryTimer = setTimeout(() => {\n entry.retryTimer = null;\n if (this.entries.get(entry.key) !== entry || entry.status !== \"denied\") return;\n if (this.isOpen()) this.sendSub(entry);\n }, delay);\n }\n\n private clearRetry(entry: Entry) {\n if (entry.retryTimer) clearTimeout(entry.retryTimer);\n entry.retryTimer = null;\n }\n\n private dropTopic(entry: Entry) {\n if (!entry.topic) return;\n const ids = this.topics.get(entry.topic);\n ids?.delete(entry.id);\n if (ids && ids.size === 0) this.topics.delete(entry.topic);\n entry.topic = null;\n }\n\n private scheduleIdleClose() {\n this.cancelIdleClose();\n this.idleTimer = setTimeout(() => {\n this.idleTimer = null;\n if (this.entries.size > 0) return;\n this.clearReconnect();\n this.close();\n }, IDLE_CLOSE_MS);\n }\n\n private cancelIdleClose() {\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n\n /** Closes the socket without reconnecting. */\n private close() {\n const ws = this.ws;\n if (!ws) return;\n this.ws = null;\n try {\n ws.close(CloseCode.Normal);\n } catch {}\n this.onClosed(CloseCode.Normal);\n }\n\n private listen() {\n if (this.listening || typeof window === \"undefined\") return;\n this.listening = true;\n window.addEventListener(\"online\", this.onOnline);\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", this.onVisibility);\n }\n }\n\n private onOnline = () => {\n if (this.entries.size === 0 || this.ws || this.pausedWhileHidden) return;\n this.attempt = 0;\n this.connect();\n };\n\n private onVisibility = () => {\n if (document.visibilityState === \"hidden\") {\n if (this.hiddenTimer) return;\n this.hiddenTimer = setTimeout(() => {\n this.hiddenTimer = null;\n if (document.visibilityState !== \"hidden\") return;\n this.pausedWhileHidden = true;\n this.clearReconnect();\n this.close();\n }, this.options.hiddenDisconnectMs);\n return;\n }\n if (this.hiddenTimer) clearTimeout(this.hiddenTimer);\n this.hiddenTimer = null;\n if (this.pausedWhileHidden) {\n this.pausedWhileHidden = false;\n this.attempt = 0;\n // The `subscribed` acks resync every subscription.\n this.connect();\n }\n };\n\n /**\n * Drops the socket and opens a new one at once, when anything is\n * subscribed. A socket keeps the session it was opened with (the upgrade's\n * cookies), so signing in or out in this tab reconnects it: every channel\n * is then authorized as the new session, and the acks resync.\n */\n reconnect() {\n this.close();\n this.clearReconnect();\n this.attempt = 0;\n if (this.entries.size > 0 && !this.pausedWhileHidden) this.connect();\n }\n\n /** For tests: drops the socket, timers and listeners. */\n dispose() {\n this.clearReconnect();\n this.cancelIdleClose();\n if (this.hiddenTimer) clearTimeout(this.hiddenTimer);\n for (const entry of this.entries.values()) {\n if (entry.resyncTimer) clearTimeout(entry.resyncTimer);\n if (entry.lingerTimer) clearTimeout(entry.lingerTimer);\n this.clearRetry(entry);\n }\n this.entries.clear();\n this.byId.clear();\n this.close();\n if (this.listening && typeof window !== \"undefined\") {\n window.removeEventListener(\"online\", this.onOnline);\n document?.removeEventListener(\"visibilitychange\", this.onVisibility);\n this.listening = false;\n }\n }\n}\n\n/** Full jitter, 1 to 30 s: `max(1 s, random × min(30 s, 1 s × 2^attempt))`. */\nexport function backoffDelay(attempt: number, random: number): number {\n const cap = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** Math.min(attempt, 10));\n return Math.max(MIN_BACKOFF_MS, Math.floor(random * cap));\n}\n\nfunction withDefaults(options: RealtimeOptions): Required<RealtimeOptions> {\n return {\n path: options.path ?? DEFAULT_SOCKET_PATH,\n hiddenDisconnectMs: options.hiddenDisconnectMs ?? DEFAULT_HIDDEN_DISCONNECT_MS,\n };\n}\n\nfunction reportListenerError(error: unknown) {\n setTimeout(() => {\n throw error;\n });\n}\n\n/**\n * The tab's client, created on first use with the options `configureRealtime`\n * set. `loadRealtimeClient` in `./loader` calls it once this module is loaded.\n */\nexport function tabClient(): RealtimeClient {\n return (realtime.client ??= new RealtimeClient(realtime.options));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,qBAAqB;;;;;AAclC,IAAa,YAAY;;CAEvB,QAAQ;;CAER,iBAAiB;;CAEjB,iBAAiB;;CAEjB,SAAS;;CAET,eAAe;;CAEf,SAAS;AACX;;;;;AAuCA,SAAgB,kBAAkB,MAA2B;CAC3D,OAAO,SAAS,qBAAqB,SAAS,oBAAoB,SAAS;AAC7E;;;;AC3CA,IAAa,qBAAqB;;AAElC,IAAa,gBAAgB;;;;;;;AAO7B,IAAa,oBAAoB;;AAEjC,IAAM,wBAAwB;;;;;;;AAO9B,IAAa,oBAAoB;AACjC,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,uBAAuB;AAC7B,IAAM,+BAA+B;;;;;;;;;;;;;;;;;AAsCrC,IAAa,iBAAb,MAAsD;CACpD;CACA;CACA,KAA+B;CAC/B,0BAAkB,IAAI,IAAmB;CACzC,uBAAe,IAAI,IAAmB;CACtC,yBAAiB,IAAI,IAAyB;CAC9C,SAAiB;CACjB,UAAkB;CAClB,MAA6B;CAC7B,gBAAuC;CACvC,cAAsB;CACtB,iBAA+D;CAC/D,YAA0D;CAC1D,cAA4D;CAC5D,YAA2D;CAC3D,gBAA8D;CAC9D,aAAoC;CACpC,UAAkB;CAClB,oBAA4B;CAC5B,YAAoB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
|
@@ -72,14 +72,26 @@ function shouldRetryQuery(failureCount, error, retry = 3) {
|
|
|
72
72
|
return failureCount <= retry;
|
|
73
73
|
}
|
|
74
74
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
75
|
+
* The wait before a retry. The default is exponential backoff with "equal
|
|
76
|
+
* jitter": the step `baseDelay * 2^(failureCount - 1)`, capped at 30s, of
|
|
77
|
+
* which half is fixed and half random — 0.5–1s, 1–2s, 2–4s, … by default.
|
|
78
|
+
*
|
|
79
|
+
* The jitter is there for failures many clients see at once. A database blip
|
|
80
|
+
* fails every open tab's queries in the same second, and an exact schedule
|
|
81
|
+
* would bring them all back in the same second, retry after retry. The fixed
|
|
82
|
+
* half keeps a floor, so a retry never lands right on top of the failure.
|
|
83
|
+
*
|
|
84
|
+
* Only the default is jittered. A `retryDelay` the caller set (a number or a
|
|
85
|
+
* function) and a `Retry-After` the server sent are honoured exactly.
|
|
86
|
+
*
|
|
87
|
+
* `random` is `Math.random` unless a test passes its own.
|
|
77
88
|
*/
|
|
78
|
-
function retryDelayFor(failureCount, error, retryDelay, baseDelay = DEFAULT_RETRY_BASE_DELAY) {
|
|
89
|
+
function retryDelayFor(failureCount, error, retryDelay, baseDelay = DEFAULT_RETRY_BASE_DELAY, random = Math.random) {
|
|
79
90
|
if (error instanceof QueryError && error.retryAfter !== void 0) return error.retryAfter;
|
|
80
91
|
if (typeof retryDelay === "function") return retryDelay(failureCount, error);
|
|
81
92
|
if (typeof retryDelay === "number") return retryDelay;
|
|
82
|
-
|
|
93
|
+
const step = Math.min(baseDelay * 2 ** Math.max(0, failureCount - 1), Math.max(MAX_RETRY_DELAY, baseDelay));
|
|
94
|
+
return Math.round(step / 2 + step / 2 * random());
|
|
83
95
|
}
|
|
84
96
|
/**
|
|
85
97
|
* A `Retry-After` header value in ms: delta-seconds or an HTTP date.
|
|
@@ -112,6 +124,213 @@ function readResponseBody(response) {
|
|
|
112
124
|
return response.json();
|
|
113
125
|
}
|
|
114
126
|
//#endregion
|
|
127
|
+
//#region http/signInHeader.ts
|
|
128
|
+
/**
|
|
129
|
+
* The response header an `authentication` refusal to an `/api` request
|
|
130
|
+
* carries: the sign-in page the request would have been sent to as a page —
|
|
131
|
+
* `auth.signInPath`, or the route's own from `"auth:/admin/sign-in"` — without
|
|
132
|
+
* an intended-URL parameter, since an API request is not a page to return to.
|
|
133
|
+
* The web client reads it to build the sign-in URL it hands
|
|
134
|
+
* `onAuthenticationError`, so the path is never hardcoded there (#1119).
|
|
135
|
+
*
|
|
136
|
+
* A module of its own, importing nothing: the client's copy lands in the
|
|
137
|
+
* entry chunk, and sharing a module with `MutationError` would pull the two
|
|
138
|
+
* chunks together ("needs no chunk besides the entry" in `packaging.test.ts`).
|
|
139
|
+
*/
|
|
140
|
+
var SIGN_IN_HEADER = "x-gemi-sign-in";
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region utils/intendedUrl.ts
|
|
143
|
+
/**
|
|
144
|
+
* The search parameter carrying the page a signed-out visitor was trying to
|
|
145
|
+
* reach. `AuthenticationMiddleware` writes it onto the sign-in redirect —
|
|
146
|
+
* `/auth/sign-in?redirect=%2Finvoices%3Fpage%3D2` — and `Auth.intendedUrl()` /
|
|
147
|
+
* `useIntendedUrl()` read it back after sign-in.
|
|
148
|
+
*/
|
|
149
|
+
var INTENDED_URL_PARAM = "redirect";
|
|
150
|
+
var PROBE_ORIGIN = "http://gemi.invalid";
|
|
151
|
+
/**
|
|
152
|
+
* `value` if it is a path on this origin, `fallback` otherwise.
|
|
153
|
+
*
|
|
154
|
+
* The intended URL arrives in a query string anybody can write, so reading it
|
|
155
|
+
* back unchecked is an open redirect: `?redirect=https://evil.example` signs
|
|
156
|
+
* the user in and hands them to a look-alike. Only a same-origin path passes:
|
|
157
|
+
* `//evil.example` and `/\evil.example` are protocol-relative to a browser and
|
|
158
|
+
* are refused, as is anything a browser would strip control characters out of
|
|
159
|
+
* before resolving.
|
|
160
|
+
*
|
|
161
|
+
* Returns path, search and hash — never an origin — so the result is safe to
|
|
162
|
+
* hand to `push`, `Redirect.to` or a `Location` header alike.
|
|
163
|
+
*/
|
|
164
|
+
function safeRedirectPath(value, fallback = "/") {
|
|
165
|
+
if (typeof value !== "string" || !value.startsWith("/")) return fallback;
|
|
166
|
+
if (/[\u0000-\u001f\u007f\\]/.test(value) || value.startsWith("//")) return fallback;
|
|
167
|
+
try {
|
|
168
|
+
const url = new URL(value, PROBE_ORIGIN);
|
|
169
|
+
if (url.origin !== PROBE_ORIGIN) return fallback;
|
|
170
|
+
const tail = `${url.search}${url.hash}`.replaceAll("/", "%2F");
|
|
171
|
+
const path = `${url.pathname}${tail}`.replaceAll(":", "%3A");
|
|
172
|
+
return path.startsWith("//") ? fallback : path;
|
|
173
|
+
} catch {
|
|
174
|
+
return fallback;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Whether a `Redirect` directive names somewhere outside the router — an
|
|
179
|
+
* absolute http(s) URL or a protocol-relative one — and so has to leave the
|
|
180
|
+
* page rather than be looked up as a route.
|
|
181
|
+
*
|
|
182
|
+
* Only those two shapes. The value goes to `location.replace`, and *any*
|
|
183
|
+
* scheme that parses would include `javascript:`, which runs in this document
|
|
184
|
+
* rather than navigating away from it: an app passing a user-influenced value
|
|
185
|
+
* to `Redirect.external` would be handing out same-origin script execution.
|
|
186
|
+
* Anything else falls through to the router, which cannot leave the origin.
|
|
187
|
+
*/
|
|
188
|
+
function isExternalRedirect(path) {
|
|
189
|
+
return /^(https?:\/\/|\/\/)/i.test(path ?? "");
|
|
190
|
+
}
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region client/authenticationErrors.ts
|
|
193
|
+
/** Where an older server, which sends no sign-in header, would have sent pages. */
|
|
194
|
+
var DEFAULT_SIGN_IN_PATH = "/auth/sign-in";
|
|
195
|
+
/** How long after the refusal `/auth/me` is asked. */
|
|
196
|
+
var AUTHENTICATION_RECHECK_DELAY_MS = 1e3;
|
|
197
|
+
var handler;
|
|
198
|
+
var navigator$1 = null;
|
|
199
|
+
var state$1 = "idle";
|
|
200
|
+
var rechecks = 0;
|
|
201
|
+
var refetches = [];
|
|
202
|
+
/** Called by `init()`. `undefined` turns it off, which is the default. */
|
|
203
|
+
function configureAuthenticationErrors(option) {
|
|
204
|
+
handler = option;
|
|
205
|
+
}
|
|
206
|
+
/** Called by the client router; returns the unregister function. */
|
|
207
|
+
function setAuthenticationNavigator(next) {
|
|
208
|
+
navigator$1 = next;
|
|
209
|
+
return () => {
|
|
210
|
+
if (navigator$1 === next) navigator$1 = null;
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* The page changed: a new incident may start. A check under way finishes on
|
|
215
|
+
* its own, since its answer is still about this session.
|
|
216
|
+
*/
|
|
217
|
+
function resetAuthenticationIncident() {
|
|
218
|
+
if (state$1 === "handled") state$1 = "idle";
|
|
219
|
+
rechecks = 0;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Whether a response is an `authentication` refusal: a 401 whose `error` is
|
|
223
|
+
* `{ kind: "authentication" }`, or the bare `"Authentication error"` a server
|
|
224
|
+
* under `RequestBreakerError.legacyStringPayload` sends. An `AuthorizationError`
|
|
225
|
+
* is a 401 too, and is told apart by its kind (or, as a string, by its
|
|
226
|
+
* message: an `AuthenticationError` always says "Authentication error").
|
|
227
|
+
*/
|
|
228
|
+
function isAuthenticationRefusal(status, body) {
|
|
229
|
+
if (status !== 401) return false;
|
|
230
|
+
const error = body && typeof body === "object" ? body.error : void 0;
|
|
231
|
+
if (typeof error === "string") return error === "Authentication error";
|
|
232
|
+
return !!error && typeof error === "object" && error.kind === "authentication";
|
|
233
|
+
}
|
|
234
|
+
function signInPathFrom(headers) {
|
|
235
|
+
const value = headers?.get?.(SIGN_IN_HEADER);
|
|
236
|
+
if (typeof value !== "string" || value === "") return DEFAULT_SIGN_IN_PATH;
|
|
237
|
+
if (/^https?:\/\//i.test(value)) return value;
|
|
238
|
+
if (value.startsWith("/") && !value.startsWith("//") && !value.includes("\\")) return value;
|
|
239
|
+
return DEFAULT_SIGN_IN_PATH;
|
|
240
|
+
}
|
|
241
|
+
function currentPage() {
|
|
242
|
+
const fromRouter = navigator$1?.current();
|
|
243
|
+
if (fromRouter) return fromRouter;
|
|
244
|
+
if (typeof window === "undefined") return null;
|
|
245
|
+
return {
|
|
246
|
+
pathname: window.location.pathname,
|
|
247
|
+
search: window.location.search
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
var trim = (path) => path.replace(/\/+$/, "") || "/";
|
|
251
|
+
/**
|
|
252
|
+
* The sign-in URL for the page on screen, or `null` when that page is the
|
|
253
|
+
* sign-in page itself — sending it back to itself would only be a loop.
|
|
254
|
+
*/
|
|
255
|
+
function signInUrlFor(signInPath, page) {
|
|
256
|
+
const external = isExternalRedirect(signInPath);
|
|
257
|
+
const target = new URL(signInPath, "http://gemi.invalid");
|
|
258
|
+
if (!external && trim(target.pathname) === trim(page.pathname)) return null;
|
|
259
|
+
target.searchParams.set(INTENDED_URL_PARAM, external ? page.pathname : `${page.pathname}${page.search}`);
|
|
260
|
+
return external ? target.href : `${target.pathname}${target.search}`;
|
|
261
|
+
}
|
|
262
|
+
function go(url) {
|
|
263
|
+
if (!isExternalRedirect(url) && navigator$1) navigator$1.replace(url);
|
|
264
|
+
else window.location.replace(url);
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Reports a refused `/api` request. Returns at once; the check and the hook
|
|
268
|
+
* run later. A no-op unless `onAuthenticationError` is set, outside a browser,
|
|
269
|
+
* and for anything but an `authentication` refusal.
|
|
270
|
+
*
|
|
271
|
+
* `refetch` (queries) runs when the check finds the session alive.
|
|
272
|
+
*/
|
|
273
|
+
function reportAuthenticationRefusal(report) {
|
|
274
|
+
if (!handler || typeof window === "undefined") return;
|
|
275
|
+
if (!isAuthenticationRefusal(report.status, report.body)) return;
|
|
276
|
+
if (report.path.split("?")[0] === "/auth/me") return;
|
|
277
|
+
if (state$1 === "handled") return;
|
|
278
|
+
if (state$1 === "idle" && rechecks >= 2) return;
|
|
279
|
+
if (report.refetch) refetches.push(report.refetch);
|
|
280
|
+
if (state$1 === "checking") return;
|
|
281
|
+
state$1 = "checking";
|
|
282
|
+
rechecks++;
|
|
283
|
+
const first = report;
|
|
284
|
+
setTimeout(() => {
|
|
285
|
+
confirm(first);
|
|
286
|
+
}, AUTHENTICATION_RECHECK_DELAY_MS);
|
|
287
|
+
}
|
|
288
|
+
async function confirm(first) {
|
|
289
|
+
let signedOut = false;
|
|
290
|
+
let headers = first.headers?.get?.("x-gemi-sign-in") ? first.headers : null;
|
|
291
|
+
try {
|
|
292
|
+
const response = await fetch("/api/auth/me", {
|
|
293
|
+
cache: "no-store",
|
|
294
|
+
headers: { Accept: "application/json" }
|
|
295
|
+
});
|
|
296
|
+
let body = null;
|
|
297
|
+
try {
|
|
298
|
+
body = await response.json();
|
|
299
|
+
} catch {}
|
|
300
|
+
signedOut = isAuthenticationRefusal(response.status, body);
|
|
301
|
+
if (signedOut && !headers) headers = response.headers;
|
|
302
|
+
} catch {}
|
|
303
|
+
const pending = refetches;
|
|
304
|
+
refetches = [];
|
|
305
|
+
if (!signedOut) {
|
|
306
|
+
state$1 = "idle";
|
|
307
|
+
for (const refetch of pending) try {
|
|
308
|
+
refetch();
|
|
309
|
+
} catch (error) {
|
|
310
|
+
console.error(error);
|
|
311
|
+
}
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
state$1 = "handled";
|
|
315
|
+
const page = currentPage();
|
|
316
|
+
if (!page) return;
|
|
317
|
+
const signInUrl = signInUrlFor(signInPathFrom(headers), page);
|
|
318
|
+
if (!signInUrl) return;
|
|
319
|
+
const context = {
|
|
320
|
+
source: first.source,
|
|
321
|
+
path: first.path,
|
|
322
|
+
error: first.error,
|
|
323
|
+
signInUrl,
|
|
324
|
+
redirect: () => go(signInUrl)
|
|
325
|
+
};
|
|
326
|
+
try {
|
|
327
|
+
if (handler === "redirect") context.redirect();
|
|
328
|
+
else handler?.(context);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
console.error(error);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
//#endregion
|
|
115
334
|
//#region client/QueryResource.ts
|
|
116
335
|
var DEFAULT_STALE_TIME = 5e3;
|
|
117
336
|
var MAX_TIMEOUT = 2 ** 31 - 1;
|
|
@@ -586,7 +805,19 @@ var QueryResource = class {
|
|
|
586
805
|
this.staleVariants.delete(variantKey);
|
|
587
806
|
this.lastFetchRecord.set(variantKey, Date.now());
|
|
588
807
|
this.failures.delete(variantKey);
|
|
589
|
-
} else
|
|
808
|
+
} else {
|
|
809
|
+
const error = new QueryError(this.key, variantKey, response.status, data, parseRetryAfter(response.headers?.get?.("retry-after")));
|
|
810
|
+
writeError(error);
|
|
811
|
+
if (isLatest()) reportAuthenticationRefusal({
|
|
812
|
+
source: "query",
|
|
813
|
+
path: this.key,
|
|
814
|
+
status: response.status,
|
|
815
|
+
body: data,
|
|
816
|
+
headers: response.headers,
|
|
817
|
+
error,
|
|
818
|
+
refetch: () => this.resolveVariant(variantKey, true, false)
|
|
819
|
+
});
|
|
820
|
+
}
|
|
590
821
|
} finally {
|
|
591
822
|
if (controller) {
|
|
592
823
|
const set = this.controllers.get(variantKey);
|
|
@@ -796,7 +1027,7 @@ function loadedRealtimeClient() {
|
|
|
796
1027
|
}
|
|
797
1028
|
var loading = null;
|
|
798
1029
|
/** The lazily loaded client. Replaceable in tests, to simulate a failed load. */
|
|
799
|
-
var lazyModules = { client: () => import("./RealtimeClient-
|
|
1030
|
+
var lazyModules = { client: () => import("./RealtimeClient-CHNbqDr7.js") };
|
|
800
1031
|
/**
|
|
801
1032
|
* `./live`, loaded by the first live query. `<Page>` in `gemi/testing` sets
|
|
802
1033
|
* `current` up front, so a live query on a provided socket subscribes during
|
|
@@ -804,7 +1035,7 @@ var lazyModules = { client: () => import("./RealtimeClient-DpAJYcF5.js") };
|
|
|
804
1035
|
*/
|
|
805
1036
|
var liveModule = {
|
|
806
1037
|
current: null,
|
|
807
|
-
load: () => import("./live-
|
|
1038
|
+
load: () => import("./live-l4vtaqXd.js").then((n) => n.n)
|
|
808
1039
|
};
|
|
809
1040
|
/**
|
|
810
1041
|
* The tab's client, loading its module and creating it on first use. `null`
|
|
@@ -3790,6 +4021,6 @@ function useTheme() {
|
|
|
3790
4021
|
return useContext(ThemeContext);
|
|
3791
4022
|
}
|
|
3792
4023
|
//#endregion
|
|
3793
|
-
export { QueryManagerProvider as $, useNavigate as A, createMemoryHistory as B, loadDictionaryForRender as C, routeDataUrl as D, readRoutePayload as E, useLocation as F, realtime as G, configureRealtime as H, domainUrl as I, loadedModule as J, reconnectRealtime as K, isAbsoluteUrl as L, I18nProvider as M, ServerDataContext as N, useRoute as O, ServerDataProvider as P, QueryManagerContext as Q, ProgressManager as R, loadDictionary as S, setActiveLocale as T, followLive as U, RealtimeContext as V, liveModule as W, applyParams as X, toVariantKey as Y, QueryConfigContext as Z, isChunkLoadError as _, useRouteTransition as a,
|
|
4024
|
+
export { QueryManagerProvider as $, useNavigate as A, createMemoryHistory as B, loadDictionaryForRender as C, routeDataUrl as D, readRoutePayload as E, useLocation as F, realtime as G, configureRealtime as H, domainUrl as I, loadedModule as J, reconnectRealtime as K, isAbsoluteUrl as L, I18nProvider as M, ServerDataContext as N, useRoute as O, ServerDataProvider as P, QueryManagerContext as Q, ProgressManager as R, loadDictionary as S, setActiveLocale as T, followLive as U, RealtimeContext as V, liveModule as W, applyParams as X, toVariantKey as Y, QueryConfigContext as Z, isChunkLoadError as _, useRouteTransition as a, resetAuthenticationIncident as at, recoverFromBuildMismatch as b, ClientRouterContext as c, isExternalRedirect as ct, ComponentsProvider as d, isRetryableQueryError as dt, USER_QUERY_CONFIG_KEYS as et, initialViewModulesReady as f, parseRetryAfter as ft, configureChunkLoadRecovery as g, Subject as gt, CHUNK_RELOAD_MARKER as h, QueryError as ht, RouteTransitionProvider as i, reportAuthenticationRefusal as it, I18nContext as j, useSearchParams as k, ClientRouterProvider as l, safeRedirectPath as lt, subscribeViewModules as m, shouldRetryQuery as mt, useTheme as n, DEFAULT_STALE_TIME as nt, useChannelSubscription as o, setAuthenticationNavigator as ot, loadViewModule as p, retryDelayFor as pt, loadLazy as q, m as r, configureAuthenticationErrors as rt, useCoalesced as s, INTENDED_URL_PARAM as st, ThemeProvider as t, pickDefined as tt, ComponentsContext as u, readResponseBody as ut, navigationStarted as v, registerDictionary as w, recoverFromChunkLoadError as x, otherBuild as y, Action as z };
|
|
3794
4025
|
|
|
3795
|
-
//# sourceMappingURL=ThemeProvider-
|
|
4026
|
+
//# sourceMappingURL=ThemeProvider-Bkc6A9Nn.js.map
|