gemi 0.128.0 → 0.129.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.
Files changed (58) hide show
  1. package/dist/{chunk-0mp9tck6.js → chunk-0ryswty9.js} +20 -20
  2. package/dist/{chunk-0mp9tck6.js.map → chunk-0ryswty9.js.map} +5 -4
  3. package/dist/{chunk-wzfvwvz0.js → chunk-jj1ppnnk.js} +2 -2
  4. package/dist/{chunk-wzfvwvz0.js.map → chunk-jj1ppnnk.js.map} +1 -1
  5. package/dist/{chunk-tchte4dv.js → chunk-sbdm4enk.js} +2 -2
  6. package/dist/{chunk-tchte4dv.js.map → chunk-sbdm4enk.js.map} +1 -1
  7. package/dist/{chunk-df0mekds.js → chunk-wmkrb1qv.js} +1 -1
  8. package/dist/{chunk-qz0da20r.js → chunk-zw5z1k84.js} +1 -1
  9. package/dist/chunks/RealtimeClient-CqGve6h8.js +545 -0
  10. package/dist/chunks/RealtimeClient-CqGve6h8.js.map +1 -0
  11. package/dist/chunks/{ThemeProvider-BIrCSrFY.js → ThemeProvider-DaX0eyqs.js} +155 -539
  12. package/dist/chunks/ThemeProvider-DaX0eyqs.js.map +1 -0
  13. package/dist/chunks/live-DIUDdLrA.js +69 -0
  14. package/dist/chunks/live-DIUDdLrA.js.map +1 -0
  15. package/dist/chunks/subscriptionStream-CULcRbx0.js +166 -0
  16. package/dist/chunks/subscriptionStream-CULcRbx0.js.map +1 -0
  17. package/dist/client/index.d.ts +1 -1
  18. package/dist/client/index.d.ts.map +1 -1
  19. package/dist/client/index.js +118 -330
  20. package/dist/client/index.js.map +1 -1
  21. package/dist/client/init.d.ts +1 -1
  22. package/dist/client/init.d.ts.map +1 -1
  23. package/dist/client/realtime/FakeSocket.d.ts +1 -1
  24. package/dist/client/realtime/FakeSocket.d.ts.map +1 -1
  25. package/dist/client/realtime/RealtimeClient.d.ts +4 -20
  26. package/dist/client/realtime/RealtimeClient.d.ts.map +1 -1
  27. package/dist/client/realtime/live.d.ts +25 -0
  28. package/dist/client/realtime/live.d.ts.map +1 -0
  29. package/dist/client/realtime/loader.d.ts +59 -0
  30. package/dist/client/realtime/loader.d.ts.map +1 -0
  31. package/dist/client/realtime/useChannelSubscription.d.ts +1 -1
  32. package/dist/client/realtime/useChannelSubscription.d.ts.map +1 -1
  33. package/dist/client/subscriptionStream.d.ts +36 -0
  34. package/dist/client/subscriptionStream.d.ts.map +1 -0
  35. package/dist/client/useChannel.d.ts +1 -13
  36. package/dist/client/useChannel.d.ts.map +1 -1
  37. package/dist/client/useQuery.d.ts +1 -1
  38. package/dist/client/useQuery.d.ts.map +1 -1
  39. package/dist/client/useSubscription.d.ts +5 -10
  40. package/dist/client/useSubscription.d.ts.map +1 -1
  41. package/dist/facades/index.js +1 -1
  42. package/dist/http/index.js +1 -1
  43. package/dist/i18n/index.js +1 -1
  44. package/dist/kernel/index.js +1 -1
  45. package/dist/server/index.js +1 -1
  46. package/dist/services/broadcast/protocol.d.ts +1 -2
  47. package/dist/services/broadcast/protocol.d.ts.map +1 -1
  48. package/dist/services/broadcast/socketHeader.d.ts +9 -0
  49. package/dist/services/broadcast/socketHeader.d.ts.map +1 -0
  50. package/dist/services/index.js +2 -2
  51. package/dist/services/index.js.map +1 -1
  52. package/dist/testing/Page.d.ts.map +1 -1
  53. package/dist/testing/index.js +3 -1
  54. package/dist/testing/index.js.map +1 -1
  55. package/package.json +1 -1
  56. package/dist/chunks/ThemeProvider-BIrCSrFY.js.map +0 -1
  57. /package/dist/{chunk-df0mekds.js.map → chunk-wmkrb1qv.js.map} +0 -0
  58. /package/dist/{chunk-qz0da20r.js.map → chunk-zw5z1k84.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{S as R,T as VJ,U as zJ}from"./chunk-tchte4dv.js";import{oa as M,sa as L,ta as OJ}from"./chunk-a22h5cby.js";import"./chunk-kk18xqgc.js";import{$f as HJ,Pd as r,ag as N}from"./chunk-0mp9tck6.js";import"./chunk-2869cbhd.js";import"./chunk-vjpby5sf.js";import{mh as i,nh as a,qh as t}from"./chunk-2bmk0fzm.js";import{ri as GJ}from"./chunk-fezaxj28.js";import"./chunk-gzaaspe7.js";import"./chunk-wv3nnq8c.js";import"./chunk-v09w6pr2.js";import"./chunk-mc8mxx2a.js";import"./chunk-pgh7gsag.js";import"./chunk-2z1gd231.js";import"./chunk-4yp84g2y.js";import"./chunk-peng31np.js";import"./chunk-1yttk239.js";import"./chunk-p528pvmm.js";import"./chunk-b7wmssj5.js";import"./chunk-cp84b0ev.js";import"./chunk-njaxnv6c.js";import{Jk as $J}from"./chunk-f8ce6e9c.js";import"./chunk-np73p641.js";import{Xk as KJ}from"./chunk-ty5sp1ym.js";import{Yk as D}from"./chunk-0vxwrc4t.js";import"./chunk-xtnbcbkf.js";import{createHash as Q2}from"crypto";import{join as E,resolve as xJ,sep as LJ}from"path";import{Duplex as qJ}from"stream";import{constants as _,createBrotliCompress as bJ,createGzip as SJ}from"zlib";var kJ=["br","gzip"],wJ=1024,vJ=5,EJ=19,yJ=6;function gJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function fJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[X,...Q]=Z.split(";"),H=X.trim().toLowerCase();if(H==="")continue;let j=1;for(let Y of Q){let K=Y.indexOf("=");if(K===-1)continue;if(Y.slice(0,K).trim().toLowerCase()==="q"){j=gJ(Y.slice(K+1));break}}$.set(H,j)}return $}function k(J,$=kJ){let Z=fJ(J);if(!Z)return null;let X=Z.get("*"),Q=null,H=0;for(let j of $){let Y=Z.get(j)??X??0;if(Y>H)Q=j,H=Y}return Q}function mJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function uJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let X=$.headers.get("Content-Encoding");if(X&&X.trim().toLowerCase()!=="identity")return!1;if(mJ($.headers.get("Cache-Control"),"no-transform"))return!1;let Q=$.headers.get("Content-Length");if(Q!==null&&Number(Q)<wJ)return!1;return!0}function hJ(J){let $=J==="br"?bJ({params:{[_.BROTLI_PARAM_QUALITY]:vJ,[_.BROTLI_PARAM_LGWIN]:EJ},flush:_.BROTLI_OPERATION_FLUSH}):SJ({level:yJ,flush:_.Z_SYNC_FLUSH});return qJ.toWeb($)}function cJ(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((X)=>X.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function d(J,$){if(!uJ(J.method,$))return $;let Z=new Headers($.headers);cJ(Z);let X=k(J.headers.get("Accept-Encoding"));if(!X)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let Q;try{Q=hJ(X)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",X),Z.delete("Content-Length"),new Response($.body.pipeThrough(Q),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as aJ,stat as s}from"fs/promises";import{join as tJ}from"path";import{mkdir as V2,readFile as pJ,stat as z2,writeFile as x2}from"fs/promises";import{dirname as C2,join as dJ}from"path";import{promisify as l}from"util";import{brotliCompress as lJ,constants as P2,gzip as oJ}from"zlib";var nJ=".vite/static-assets.json";var o={br:".br",gzip:".gz"},iJ=["br","gzip"],_2=l(lJ),B2=l(oJ);async function n(J){let $;try{$=await pJ(dJ(J,nJ),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let X={files:{}};for(let[Q,H]of Object.entries(Z)){if(!Array.isArray(H))continue;X.files[Q]=iJ.filter((j)=>H.includes(j))}return X}function w(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function e(J){let $=new Set;async function Z(X,Q){let H;try{H=await aJ(X,{withFileTypes:!0})}catch{return}for(let j of H){if(j.name.startsWith("."))continue;if(Q&&j.name==="assets")continue;let Y=tJ(X,j.name),K=j.isDirectory(),V=j.isFile();if(j.isSymbolicLink())try{let I=await s(Y);K=I.isDirectory(),V=I.isFile()}catch{continue}if(V)$.add(Y);else if(K&&!j.isSymbolicLink())await Z(Y,!1)}}return await Z(J,!0),$}var rJ="public, max-age=31536000, must-revalidate",sJ="public, max-age=31536000, immutable";async function eJ(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let X=k(J.headers.get("Accept-Encoding"),Z);if(!X)return null;let Q=$+o[X];try{let H=await s(Q);return H.isFile()?{encoding:X,path:Q,size:H.size}:null}catch{return null}}async function JJ(J,$,Z={}){let X=Bun.file($),Q=Z.encodings??[],H={"Content-Type":X.type||"application/octet-stream","Cache-Control":Z.immutable?sJ:rJ,"Accept-Ranges":"bytes"};if(Q.length>0)H.Vary="Accept-Encoding";let j=await eJ(J,$,Q);if(j){let V=Bun.file(j.path);return new Response(V.stream(),{headers:{...H,"Content-Encoding":j.encoding,"Content-Length":String(j.size),ETag:`${w(V.lastModified)}-${j.encoding}`}})}let Y=X.size;H.ETag=w(X.lastModified);let K=i(J.headers.get("Range"));if(K){let V=a(K,Y);if(!V)return r(Y);return new Response(X.slice(V.start,V.end+1).stream(),{status:206,headers:{...H,"Content-Range":t(V.start,V.end,Y),"Content-Length":String(V.length)}})}return new Response(X.stream(),{headers:{...H,"Content-Length":String(Y)}})}import{stat as W2}from"fs/promises";var B="app/client.tsx";function ZJ(J,$=M){let Z=J[B]?.file;if(!Z)return;return{module:L(Z,$),preload:A(J,B,$)}}function A(J,$,Z=M){let X=[],Q=new Set,H=(j)=>{if(Q.has(j))return;Q.add(j);let Y=J[j];if(!Y?.file)return;X.push(L(Y.file,Z));for(let K of Y.imports??[])H(K)};return H($),X}function XJ(J,$){let Z=[],X=new Set,Q=new Set,H=(j)=>{if(Q.has(j))return;Q.add(j);let Y=J[j];if(!Y)return;for(let K of Y.imports??[])H(K);for(let K of Y.css??[])if(!X.has(K))X.add(K),Z.push(K)};return H($),Z}function QJ(J,$=M){let Z=new Map;return(X)=>{if(!Z.has(X)){let Q=`${X}${$J}`,H=J[Q]?.file;Z.set(X,H?{src:L(H,$),preload:A(J,Q,$)}:void 0)}return Z.get(X)}}function WJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),X=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var r=!1;try{var s=window.sessionStorage,m=JSON.parse(s.getItem(${Z})||"null");var d=m?Date.now()-m.at:NaN;if(navigator.onLine!==!1&&!(d>=0&&d<${$})){s.setItem(${Z},JSON.stringify({url:window.location.href,at:Date.now()}));r=!0}}catch(e){}if(r)window.location.reload();else throw new Error(${X});export {}`}var J2=new RegExp(`^${HJ}/.+\\.m?js$`);function $2(J){return J2.test(J)}function jJ(J){if($2(J))return new Response(WJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(N(J))return new Response("Not found",{status:404});return}var Z2=`<!DOCTYPE html>
2
+ import{S as R,T as VJ,U as zJ}from"./chunk-sbdm4enk.js";import{oa as M,sa as L,ta as OJ}from"./chunk-a22h5cby.js";import"./chunk-kk18xqgc.js";import{$f as HJ,Pd as r,ag as N}from"./chunk-0ryswty9.js";import"./chunk-2869cbhd.js";import"./chunk-vjpby5sf.js";import{mh as i,nh as a,qh as t}from"./chunk-2bmk0fzm.js";import{ri as GJ}from"./chunk-fezaxj28.js";import"./chunk-gzaaspe7.js";import"./chunk-wv3nnq8c.js";import"./chunk-v09w6pr2.js";import"./chunk-mc8mxx2a.js";import"./chunk-pgh7gsag.js";import"./chunk-2z1gd231.js";import"./chunk-4yp84g2y.js";import"./chunk-peng31np.js";import"./chunk-1yttk239.js";import"./chunk-p528pvmm.js";import"./chunk-b7wmssj5.js";import"./chunk-cp84b0ev.js";import"./chunk-njaxnv6c.js";import{Jk as $J}from"./chunk-f8ce6e9c.js";import"./chunk-np73p641.js";import{Xk as KJ}from"./chunk-ty5sp1ym.js";import{Yk as D}from"./chunk-0vxwrc4t.js";import"./chunk-xtnbcbkf.js";import{createHash as Q2}from"crypto";import{join as E,resolve as xJ,sep as LJ}from"path";import{Duplex as qJ}from"stream";import{constants as _,createBrotliCompress as bJ,createGzip as SJ}from"zlib";var kJ=["br","gzip"],wJ=1024,vJ=5,EJ=19,yJ=6;function gJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function fJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[X,...Q]=Z.split(";"),H=X.trim().toLowerCase();if(H==="")continue;let j=1;for(let Y of Q){let K=Y.indexOf("=");if(K===-1)continue;if(Y.slice(0,K).trim().toLowerCase()==="q"){j=gJ(Y.slice(K+1));break}}$.set(H,j)}return $}function k(J,$=kJ){let Z=fJ(J);if(!Z)return null;let X=Z.get("*"),Q=null,H=0;for(let j of $){let Y=Z.get(j)??X??0;if(Y>H)Q=j,H=Y}return Q}function mJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function uJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let X=$.headers.get("Content-Encoding");if(X&&X.trim().toLowerCase()!=="identity")return!1;if(mJ($.headers.get("Cache-Control"),"no-transform"))return!1;let Q=$.headers.get("Content-Length");if(Q!==null&&Number(Q)<wJ)return!1;return!0}function hJ(J){let $=J==="br"?bJ({params:{[_.BROTLI_PARAM_QUALITY]:vJ,[_.BROTLI_PARAM_LGWIN]:EJ},flush:_.BROTLI_OPERATION_FLUSH}):SJ({level:yJ,flush:_.Z_SYNC_FLUSH});return qJ.toWeb($)}function cJ(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((X)=>X.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function d(J,$){if(!uJ(J.method,$))return $;let Z=new Headers($.headers);cJ(Z);let X=k(J.headers.get("Accept-Encoding"));if(!X)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let Q;try{Q=hJ(X)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",X),Z.delete("Content-Length"),new Response($.body.pipeThrough(Q),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as aJ,stat as s}from"fs/promises";import{join as tJ}from"path";import{mkdir as V2,readFile as pJ,stat as z2,writeFile as x2}from"fs/promises";import{dirname as C2,join as dJ}from"path";import{promisify as l}from"util";import{brotliCompress as lJ,constants as P2,gzip as oJ}from"zlib";var nJ=".vite/static-assets.json";var o={br:".br",gzip:".gz"},iJ=["br","gzip"],_2=l(lJ),B2=l(oJ);async function n(J){let $;try{$=await pJ(dJ(J,nJ),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let X={files:{}};for(let[Q,H]of Object.entries(Z)){if(!Array.isArray(H))continue;X.files[Q]=iJ.filter((j)=>H.includes(j))}return X}function w(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function e(J){let $=new Set;async function Z(X,Q){let H;try{H=await aJ(X,{withFileTypes:!0})}catch{return}for(let j of H){if(j.name.startsWith("."))continue;if(Q&&j.name==="assets")continue;let Y=tJ(X,j.name),K=j.isDirectory(),V=j.isFile();if(j.isSymbolicLink())try{let I=await s(Y);K=I.isDirectory(),V=I.isFile()}catch{continue}if(V)$.add(Y);else if(K&&!j.isSymbolicLink())await Z(Y,!1)}}return await Z(J,!0),$}var rJ="public, max-age=31536000, must-revalidate",sJ="public, max-age=31536000, immutable";async function eJ(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let X=k(J.headers.get("Accept-Encoding"),Z);if(!X)return null;let Q=$+o[X];try{let H=await s(Q);return H.isFile()?{encoding:X,path:Q,size:H.size}:null}catch{return null}}async function JJ(J,$,Z={}){let X=Bun.file($),Q=Z.encodings??[],H={"Content-Type":X.type||"application/octet-stream","Cache-Control":Z.immutable?sJ:rJ,"Accept-Ranges":"bytes"};if(Q.length>0)H.Vary="Accept-Encoding";let j=await eJ(J,$,Q);if(j){let V=Bun.file(j.path);return new Response(V.stream(),{headers:{...H,"Content-Encoding":j.encoding,"Content-Length":String(j.size),ETag:`${w(V.lastModified)}-${j.encoding}`}})}let Y=X.size;H.ETag=w(X.lastModified);let K=i(J.headers.get("Range"));if(K){let V=a(K,Y);if(!V)return r(Y);return new Response(X.slice(V.start,V.end+1).stream(),{status:206,headers:{...H,"Content-Range":t(V.start,V.end,Y),"Content-Length":String(V.length)}})}return new Response(X.stream(),{headers:{...H,"Content-Length":String(Y)}})}import{stat as W2}from"fs/promises";var B="app/client.tsx";function ZJ(J,$=M){let Z=J[B]?.file;if(!Z)return;return{module:L(Z,$),preload:A(J,B,$)}}function A(J,$,Z=M){let X=[],Q=new Set,H=(j)=>{if(Q.has(j))return;Q.add(j);let Y=J[j];if(!Y?.file)return;X.push(L(Y.file,Z));for(let K of Y.imports??[])H(K)};return H($),X}function XJ(J,$){let Z=[],X=new Set,Q=new Set,H=(j)=>{if(Q.has(j))return;Q.add(j);let Y=J[j];if(!Y)return;for(let K of Y.imports??[])H(K);for(let K of Y.css??[])if(!X.has(K))X.add(K),Z.push(K)};return H($),Z}function QJ(J,$=M){let Z=new Map;return(X)=>{if(!Z.has(X)){let Q=`${X}${$J}`,H=J[Q]?.file;Z.set(X,H?{src:L(H,$),preload:A(J,Q,$)}:void 0)}return Z.get(X)}}function WJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),X=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var r=!1;try{var s=window.sessionStorage,m=JSON.parse(s.getItem(${Z})||"null");var d=m?Date.now()-m.at:NaN;if(navigator.onLine!==!1&&!(d>=0&&d<${$})){s.setItem(${Z},JSON.stringify({url:window.location.href,at:Date.now()}));r=!0}}catch(e){}if(r)window.location.reload();else throw new Error(${X});export {}`}var J2=new RegExp(`^${HJ}/.+\\.m?js$`);function $2(J){return J2.test(J)}function jJ(J){if($2(J))return new Response(WJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(N(J))return new Response("Not found",{status:404});return}var Z2=`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8" />
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{R as S,T as h,U as u}from"./chunk-tchte4dv.js";import{ma as q,na as w}from"./chunk-03wc6em7.js";import"./chunk-a22h5cby.js";import"./chunk-epvpmakp.js";import"./chunk-r3v2cnrj.js";import"./chunk-qv8sj2z3.js";import"./chunk-kk18xqgc.js";import"./chunk-bnp6wpzd.js";import{ri as N}from"./chunk-fezaxj28.js";import{Jk as y}from"./chunk-f8ce6e9c.js";import{Yk as C}from"./chunk-0vxwrc4t.js";import"./chunk-xtnbcbkf.js";import{join as $J}from"path";import{createServer as zJ}from"vite";import{join as l}from"path";import{IncomingMessage as d,ServerResponse as p}from"http";import{Socket as i}from"net";function c(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
2
+ import{R as S,T as h,U as u}from"./chunk-sbdm4enk.js";import{ma as q,na as w}from"./chunk-03wc6em7.js";import"./chunk-a22h5cby.js";import"./chunk-epvpmakp.js";import"./chunk-r3v2cnrj.js";import"./chunk-qv8sj2z3.js";import"./chunk-kk18xqgc.js";import"./chunk-bnp6wpzd.js";import{ri as N}from"./chunk-fezaxj28.js";import{Jk as y}from"./chunk-f8ce6e9c.js";import{Yk as C}from"./chunk-0vxwrc4t.js";import"./chunk-xtnbcbkf.js";import{join as $J}from"path";import{createServer as zJ}from"vite";import{join as l}from"path";import{IncomingMessage as d,ServerResponse as p}from"http";import{Socket as i}from"net";function c(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
3
3
  `).split(`
4
4
  `).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
5
5
  `).trim()}function _(J){return`
@@ -0,0 +1,545 @@
1
+ import { z as channelKey } from "./ThemeProvider-DaX0eyqs.js";
2
+ //#region services/broadcast/protocol.ts
3
+ /**
4
+ * The `gemi.v1` WebSocket protocol, shared by the server transport
5
+ * (`SocketHub`) and the browser client (`gemi/client`'s connection manager).
6
+ * Types and constants only: this module is imported by the browser bundle, so
7
+ * it must never import a server module.
8
+ *
9
+ * Every frame is a JSON text frame. Binary frames are refused.
10
+ *
11
+ * From the client:
12
+ *
13
+ * - `{op:"sub", id, ch, p?}`: subscribe `id` (chosen by the client, unique per
14
+ * socket) to the channel pattern `ch` with params `p`. The server builds
15
+ * the topic and authorizes it.
16
+ * - `{op:"unsub", id}`
17
+ * - `{op:"ping"}`: answered with `pong`. The client sends one every
18
+ * `heartbeatMs` and reconnects when it hears nothing for twice that.
19
+ *
20
+ * From the server:
21
+ *
22
+ * - `{op:"hello", socketId, tag, heartbeatMs}`: the first frame. `socketId`
23
+ * goes in the `X-Gemi-Socket` header of the client's own requests (for
24
+ * `Broadcast.toOthers`); it is never shown to anyone else. `tag` is what
25
+ * an event frame's `x` carries when it skips this socket.
26
+ * - `{op:"subscribed", id, t}`: `id` joined topic `t`. Sent only once this
27
+ * process receives the topic's events, so the resync the client runs on it
28
+ * cannot miss one.
29
+ * - `{op:"denied", id, code}`: `id` was refused, or later revoked.
30
+ * - `{op:"ev", t, ev, d?, x?}`: an event on topic `t`. Dropped by the socket
31
+ * whose `tag` is `x`.
32
+ * - `{op:"gap"}`: events may have been lost for this socket; resync all.
33
+ * - `{op:"pong"}`
34
+ * - `{op:"bye", code, retryAfter}`: the server is going away (a restart).
35
+ * Reconnect after `retryAfter` ms.
36
+ */
37
+ /** The WebSocket subprotocol. */
38
+ var BROADCAST_PROTOCOL = "gemi.v1";
39
+ /**
40
+ * Close codes the server uses. 1012 and 1013 are the standard "restart" and
41
+ * "try again later"; the 4xxx ones are gemi's own.
42
+ */
43
+ var CloseCode = {
44
+ /** The client went away (tab closed, socket released). */
45
+ Normal: 1e3,
46
+ /** A frame that was not JSON text, or not a known op. */
47
+ UnsupportedData: 1003,
48
+ /** Too many frames, or a frame over the size limit. */
49
+ PolicyViolation: 1008,
50
+ /** The server is restarting; `bye` said when to come back. */
51
+ Restart: 1012,
52
+ /** The socket fell too far behind; reconnect and resync. */
53
+ TryAgainLater: 1013,
54
+ /** The socket's user was signed out or its access revoked. */
55
+ Revoked: 4001
56
+ };
57
+ /**
58
+ * Whether a refusal is final for this socket's session: resubscribing will
59
+ * get the same answer, so the client does not retry it on its own.
60
+ */
61
+ function isPermanentDenial(code) {
62
+ return code === "unknown_channel" || code === "invalid_params" || code === "invalid";
63
+ }
64
+ //#endregion
65
+ //#region client/realtime/RealtimeClient.ts
66
+ /** The minimum gap between two resyncs of one subscription. */
67
+ var RESYNC_COALESCE_MS = 2e3;
68
+ /** How long the socket stays open after its last subscription goes. */
69
+ var IDLE_CLOSE_MS = 5e3;
70
+ /**
71
+ * How long a subscription outlives its last listener. A hook that remounts
72
+ * within it (StrictMode's double mount, a route change back, a list that
73
+ * re-renders its rows) picks the same subscription up again: no `unsub`, no
74
+ * new `sub`, nothing counted against the server's rate limit.
75
+ */
76
+ var RELEASE_LINGER_MS = 1500;
77
+ /** The least wait before resending a `sub` denied with `rate_limited`. */
78
+ var RATE_LIMITED_RETRY_MS = 5e3;
79
+ /**
80
+ * How often a `sub` denied with `limit` is resent on one socket. The socket
81
+ * holds as many channels as the server allows, so only a released one makes
82
+ * room: worth a few tries with backoff, not a retry for as long as the socket
83
+ * lives. Past it the subscription waits for the next connection.
84
+ */
85
+ var MAX_LIMIT_RETRIES = 5;
86
+ var MIN_BACKOFF_MS = 1e3;
87
+ var MAX_BACKOFF_MS = 3e4;
88
+ var DEFAULT_HEARTBEAT_MS = 25e3;
89
+ var DEFAULT_HIDDEN_DISCONNECT_MS = 6e4;
90
+ /**
91
+ * The tab's one WebSocket to the app (`gemi.v1`), multiplexing every channel
92
+ * the mounted hooks subscribe to.
93
+ *
94
+ * Opened by the first subscription and closed a few seconds after the last
95
+ * one goes. Reconnects with full-jitter backoff (1 to 30 s), or after the
96
+ * server's `bye.retryAfter`, at once on `online`; resubscribes everything
97
+ * then. A tab hidden for `hiddenDisconnectMs` disconnects, and reconnects
98
+ * when shown. Every `subscribed` ack and every `gap` resyncs the
99
+ * subscription (coalesced to one per 2 s), because events are volatile: a
100
+ * client that may have missed one refetches over HTTP.
101
+ *
102
+ * Loaded on first use (#891): import this module as a type only, and reach
103
+ * the tab's instance through `./loader`, or it lands in every route's entry
104
+ * chunk.
105
+ */
106
+ var RealtimeClient = class {
107
+ options;
108
+ internals;
109
+ ws = null;
110
+ entries = /* @__PURE__ */ new Map();
111
+ byId = /* @__PURE__ */ new Map();
112
+ topics = /* @__PURE__ */ new Map();
113
+ nextId = 1;
114
+ attempt = 0;
115
+ tag = null;
116
+ socketIdValue = null;
117
+ heartbeatMs = DEFAULT_HEARTBEAT_MS;
118
+ reconnectTimer = null;
119
+ idleTimer = null;
120
+ hiddenTimer = null;
121
+ pingTimer = null;
122
+ livenessTimer = null;
123
+ retryAfter = null;
124
+ revoked = false;
125
+ pausedWhileHidden = false;
126
+ listening = false;
127
+ constructor(options = {}, internals = {}) {
128
+ this.options = withDefaults(options);
129
+ this.internals = internals;
130
+ }
131
+ configure(options) {
132
+ this.options = withDefaults({
133
+ ...this.options,
134
+ ...options
135
+ });
136
+ }
137
+ /** The id to send as `X-Gemi-Socket`, while the socket is open. */
138
+ get socketId() {
139
+ return this.socketIdValue;
140
+ }
141
+ subscribe(pattern, params, listener) {
142
+ const key = channelKey(pattern, params);
143
+ let entry = this.entries.get(key);
144
+ if (!entry) {
145
+ entry = {
146
+ key,
147
+ id: String(this.nextId++),
148
+ pattern,
149
+ params: { ...params },
150
+ listeners: /* @__PURE__ */ new Set(),
151
+ status: "closed",
152
+ code: null,
153
+ permanent: false,
154
+ topic: null,
155
+ lastResyncAt: 0,
156
+ resyncTimer: null,
157
+ lingerTimer: null,
158
+ retryTimer: null,
159
+ retries: 0
160
+ };
161
+ this.entries.set(key, entry);
162
+ this.byId.set(entry.id, entry);
163
+ if (this.isOpen()) this.sendSub(entry);
164
+ }
165
+ if (entry.lingerTimer) {
166
+ clearTimeout(entry.lingerTimer);
167
+ entry.lingerTimer = null;
168
+ }
169
+ entry.listeners.add(listener);
170
+ listener.onStatus?.(entry.status, entry.code);
171
+ this.cancelIdleClose();
172
+ this.listen();
173
+ if (!this.ws && !this.reconnectTimer && !this.pausedWhileHidden) this.connect();
174
+ let released = false;
175
+ return () => {
176
+ if (released) return;
177
+ released = true;
178
+ this.release(entry, listener);
179
+ };
180
+ }
181
+ release(entry, listener) {
182
+ entry.listeners.delete(listener);
183
+ if (entry.listeners.size > 0 || entry.lingerTimer) return;
184
+ entry.lingerTimer = setTimeout(() => {
185
+ entry.lingerTimer = null;
186
+ if (entry.listeners.size === 0) this.drop(entry);
187
+ }, RELEASE_LINGER_MS);
188
+ }
189
+ drop(entry) {
190
+ if (entry.resyncTimer) clearTimeout(entry.resyncTimer);
191
+ this.clearRetry(entry);
192
+ this.entries.delete(entry.key);
193
+ this.byId.delete(entry.id);
194
+ this.dropTopic(entry);
195
+ if (this.isOpen() && (entry.status === "open" || entry.status === "connecting")) this.send({
196
+ op: "unsub",
197
+ id: entry.id
198
+ });
199
+ if (this.entries.size === 0) this.scheduleIdleClose();
200
+ }
201
+ isOpen() {
202
+ return this.ws !== null && this.ws.readyState === 1;
203
+ }
204
+ connect() {
205
+ if (typeof window === "undefined") return;
206
+ if (this.entries.size === 0) return;
207
+ const Impl = this.internals.WebSocket ?? globalThis.WebSocket;
208
+ if (!Impl) return;
209
+ this.clearReconnect();
210
+ let ws;
211
+ try {
212
+ ws = new Impl(this.url(), [BROADCAST_PROTOCOL]);
213
+ } catch {
214
+ this.scheduleReconnect();
215
+ return;
216
+ }
217
+ this.ws = ws;
218
+ for (const entry of this.entries.values()) if (!entry.permanent) this.setStatus(entry, "connecting", null);
219
+ ws.onopen = () => {
220
+ if (this.ws !== ws) return;
221
+ this.touch();
222
+ for (const entry of this.entries.values()) {
223
+ if (entry.permanent) continue;
224
+ entry.retries = 0;
225
+ this.sendSub(entry);
226
+ }
227
+ };
228
+ ws.onmessage = (event) => {
229
+ if (this.ws !== ws) return;
230
+ this.touch();
231
+ let frame;
232
+ try {
233
+ frame = JSON.parse(String(event.data));
234
+ } catch {
235
+ return;
236
+ }
237
+ this.handle(frame);
238
+ };
239
+ ws.onclose = (event) => {
240
+ if (this.ws !== ws) return;
241
+ this.onClosed(event.code);
242
+ };
243
+ ws.onerror = () => {};
244
+ }
245
+ url() {
246
+ if (this.internals.url) return this.internals.url;
247
+ const { protocol, host } = window.location;
248
+ return `${protocol === "https:" ? "wss:" : "ws:"}//${host}${this.options.path}`;
249
+ }
250
+ sendSub(entry) {
251
+ this.setStatus(entry, "connecting", null);
252
+ const frame = {
253
+ op: "sub",
254
+ id: entry.id,
255
+ ch: entry.pattern
256
+ };
257
+ if (Object.keys(entry.params).length > 0) frame.p = entry.params;
258
+ this.send(frame);
259
+ }
260
+ send(frame) {
261
+ if (!this.isOpen()) return;
262
+ try {
263
+ this.ws.send(JSON.stringify(frame));
264
+ } catch {}
265
+ }
266
+ handle(frame) {
267
+ switch (frame.op) {
268
+ case "hello":
269
+ this.socketIdValue = frame.socketId;
270
+ this.tag = frame.tag;
271
+ this.attempt = 0;
272
+ this.revoked = false;
273
+ if (frame.heartbeatMs > 0) this.heartbeatMs = frame.heartbeatMs;
274
+ this.startHeartbeat();
275
+ return;
276
+ case "subscribed": {
277
+ const entry = this.byId.get(frame.id);
278
+ if (!entry) return;
279
+ this.dropTopic(entry);
280
+ entry.topic = frame.t;
281
+ let ids = this.topics.get(frame.t);
282
+ if (!ids) this.topics.set(frame.t, ids = /* @__PURE__ */ new Set());
283
+ ids.add(entry.id);
284
+ this.clearRetry(entry);
285
+ entry.retries = 0;
286
+ this.setStatus(entry, "open", null);
287
+ this.resync(entry);
288
+ return;
289
+ }
290
+ case "denied": {
291
+ const entry = this.byId.get(frame.id);
292
+ if (!entry) return;
293
+ this.dropTopic(entry);
294
+ entry.permanent = isPermanentDenial(frame.code);
295
+ this.setStatus(entry, "denied", frame.code);
296
+ this.scheduleRetry(entry, frame.code);
297
+ return;
298
+ }
299
+ case "ev": {
300
+ if (frame.x !== void 0 && frame.x === this.tag) return;
301
+ const ids = this.topics.get(frame.t);
302
+ if (!ids) return;
303
+ for (const id of Array.from(ids)) {
304
+ const entry = this.byId.get(id);
305
+ if (!entry) continue;
306
+ for (const listener of Array.from(entry.listeners)) try {
307
+ listener.onEvent?.(frame.ev, frame.d);
308
+ } catch (error) {
309
+ reportListenerError(error);
310
+ }
311
+ }
312
+ return;
313
+ }
314
+ case "gap":
315
+ for (const entry of this.entries.values()) if (entry.status === "open") this.resync(entry);
316
+ return;
317
+ case "bye":
318
+ this.retryAfter = Math.max(0, Number(frame.retryAfter) || 0);
319
+ return;
320
+ case "pong": return;
321
+ }
322
+ }
323
+ onClosed(code) {
324
+ this.ws = null;
325
+ this.socketIdValue = null;
326
+ this.tag = null;
327
+ this.stopHeartbeat();
328
+ this.topics.clear();
329
+ for (const entry of this.entries.values()) {
330
+ entry.topic = null;
331
+ this.clearRetry(entry);
332
+ if (!entry.permanent) this.setStatus(entry, "closed", null);
333
+ }
334
+ if (code === CloseCode.Revoked) this.revoked = true;
335
+ if (this.entries.size > 0 && !this.pausedWhileHidden) this.scheduleReconnect();
336
+ }
337
+ scheduleReconnect() {
338
+ this.clearReconnect();
339
+ let delay;
340
+ if (this.retryAfter !== null) {
341
+ delay = this.retryAfter;
342
+ this.retryAfter = null;
343
+ } else if (this.revoked) {
344
+ this.revoked = false;
345
+ delay = Math.floor(this.random() * 500);
346
+ } else delay = backoffDelay(this.attempt, this.random());
347
+ this.attempt++;
348
+ this.reconnectTimer = setTimeout(() => {
349
+ this.reconnectTimer = null;
350
+ this.connect();
351
+ }, delay);
352
+ }
353
+ clearReconnect() {
354
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
355
+ this.reconnectTimer = null;
356
+ }
357
+ random() {
358
+ return (this.internals.random ?? Math.random)();
359
+ }
360
+ startHeartbeat() {
361
+ this.stopHeartbeat();
362
+ this.pingTimer = setInterval(() => this.send({ op: "ping" }), this.heartbeatMs);
363
+ this.touch();
364
+ }
365
+ stopHeartbeat() {
366
+ if (this.pingTimer) clearInterval(this.pingTimer);
367
+ if (this.livenessTimer) clearTimeout(this.livenessTimer);
368
+ this.pingTimer = null;
369
+ this.livenessTimer = null;
370
+ }
371
+ /** Anything from the server proves the socket alive. */
372
+ touch() {
373
+ if (this.livenessTimer) clearTimeout(this.livenessTimer);
374
+ const ws = this.ws;
375
+ this.livenessTimer = setTimeout(() => {
376
+ if (this.ws !== ws || !ws) return;
377
+ try {
378
+ ws.close();
379
+ } catch {}
380
+ this.onClosed(1006);
381
+ }, this.heartbeatMs * 2);
382
+ }
383
+ setStatus(entry, status, code) {
384
+ if (entry.status === status && entry.code === code) return;
385
+ entry.status = status;
386
+ entry.code = code;
387
+ for (const listener of Array.from(entry.listeners)) try {
388
+ listener.onStatus?.(status, code);
389
+ } catch (error) {
390
+ reportListenerError(error);
391
+ }
392
+ }
393
+ /** At most one resync per subscription per 2 s; a later one is deferred, not dropped. */
394
+ resync(entry) {
395
+ if (entry.resyncTimer) return;
396
+ const now = Date.now();
397
+ const wait = entry.lastResyncAt + RESYNC_COALESCE_MS - now;
398
+ const fire = () => {
399
+ entry.resyncTimer = null;
400
+ entry.lastResyncAt = Date.now();
401
+ for (const listener of Array.from(entry.listeners)) try {
402
+ listener.onResync?.();
403
+ } catch (error) {
404
+ reportListenerError(error);
405
+ }
406
+ };
407
+ if (entry.lastResyncAt === 0 || wait <= 0) fire();
408
+ else entry.resyncTimer = setTimeout(fire, wait);
409
+ }
410
+ /**
411
+ * A transient denial (`rate_limited`, `error`, `limit`) is retried on the
412
+ * same socket, with backoff: a healthy socket may never reconnect. `denied`
413
+ * and `revoked` are the channel's answer for this session, so they wait for
414
+ * the next connection (a sign-in reconnects), and a permanent one is never
415
+ * resent. `limit` gives up after `MAX_LIMIT_RETRIES` on one socket.
416
+ */
417
+ scheduleRetry(entry, code) {
418
+ if (code !== "rate_limited" && code !== "error" && code !== "limit") return;
419
+ if (code === "limit" && entry.retries >= 5) return;
420
+ this.clearRetry(entry);
421
+ const delay = Math.max(code === "rate_limited" ? RATE_LIMITED_RETRY_MS : MIN_BACKOFF_MS, backoffDelay(entry.retries, this.random()));
422
+ entry.retries++;
423
+ entry.retryTimer = setTimeout(() => {
424
+ entry.retryTimer = null;
425
+ if (this.entries.get(entry.key) !== entry || entry.status !== "denied") return;
426
+ if (this.isOpen()) this.sendSub(entry);
427
+ }, delay);
428
+ }
429
+ clearRetry(entry) {
430
+ if (entry.retryTimer) clearTimeout(entry.retryTimer);
431
+ entry.retryTimer = null;
432
+ }
433
+ dropTopic(entry) {
434
+ if (!entry.topic) return;
435
+ const ids = this.topics.get(entry.topic);
436
+ ids?.delete(entry.id);
437
+ if (ids && ids.size === 0) this.topics.delete(entry.topic);
438
+ entry.topic = null;
439
+ }
440
+ scheduleIdleClose() {
441
+ this.cancelIdleClose();
442
+ this.idleTimer = setTimeout(() => {
443
+ this.idleTimer = null;
444
+ if (this.entries.size > 0) return;
445
+ this.clearReconnect();
446
+ this.close();
447
+ }, IDLE_CLOSE_MS);
448
+ }
449
+ cancelIdleClose() {
450
+ if (this.idleTimer) clearTimeout(this.idleTimer);
451
+ this.idleTimer = null;
452
+ }
453
+ /** Closes the socket without reconnecting. */
454
+ close() {
455
+ const ws = this.ws;
456
+ if (!ws) return;
457
+ this.ws = null;
458
+ try {
459
+ ws.close(CloseCode.Normal);
460
+ } catch {}
461
+ this.onClosed(CloseCode.Normal);
462
+ }
463
+ listen() {
464
+ if (this.listening || typeof window === "undefined") return;
465
+ this.listening = true;
466
+ window.addEventListener("online", this.onOnline);
467
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", this.onVisibility);
468
+ }
469
+ onOnline = () => {
470
+ if (this.entries.size === 0 || this.ws || this.pausedWhileHidden) return;
471
+ this.attempt = 0;
472
+ this.connect();
473
+ };
474
+ onVisibility = () => {
475
+ if (document.visibilityState === "hidden") {
476
+ if (this.hiddenTimer) return;
477
+ this.hiddenTimer = setTimeout(() => {
478
+ this.hiddenTimer = null;
479
+ if (document.visibilityState !== "hidden") return;
480
+ this.pausedWhileHidden = true;
481
+ this.clearReconnect();
482
+ this.close();
483
+ }, this.options.hiddenDisconnectMs);
484
+ return;
485
+ }
486
+ if (this.hiddenTimer) clearTimeout(this.hiddenTimer);
487
+ this.hiddenTimer = null;
488
+ if (this.pausedWhileHidden) {
489
+ this.pausedWhileHidden = false;
490
+ this.attempt = 0;
491
+ this.connect();
492
+ }
493
+ };
494
+ /**
495
+ * Drops the socket and opens a new one at once, when anything is
496
+ * subscribed. A socket keeps the session it was opened with (the upgrade's
497
+ * cookies), so signing in or out in this tab reconnects it: every channel
498
+ * is then authorized as the new session, and the acks resync.
499
+ */
500
+ reconnect() {
501
+ this.close();
502
+ this.clearReconnect();
503
+ this.attempt = 0;
504
+ if (this.entries.size > 0 && !this.pausedWhileHidden) this.connect();
505
+ }
506
+ /** For tests: drops the socket, timers and listeners. */
507
+ dispose() {
508
+ this.clearReconnect();
509
+ this.cancelIdleClose();
510
+ if (this.hiddenTimer) clearTimeout(this.hiddenTimer);
511
+ for (const entry of this.entries.values()) {
512
+ if (entry.resyncTimer) clearTimeout(entry.resyncTimer);
513
+ if (entry.lingerTimer) clearTimeout(entry.lingerTimer);
514
+ this.clearRetry(entry);
515
+ }
516
+ this.entries.clear();
517
+ this.byId.clear();
518
+ this.close();
519
+ if (this.listening && typeof window !== "undefined") {
520
+ window.removeEventListener("online", this.onOnline);
521
+ document?.removeEventListener("visibilitychange", this.onVisibility);
522
+ this.listening = false;
523
+ }
524
+ }
525
+ };
526
+ /** Full jitter, 1 to 30 s: `max(1 s, random × min(30 s, 1 s × 2^attempt))`. */
527
+ function backoffDelay(attempt, random) {
528
+ const cap = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** Math.min(attempt, 10));
529
+ return Math.max(MIN_BACKOFF_MS, Math.floor(random * cap));
530
+ }
531
+ function withDefaults(options) {
532
+ return {
533
+ path: options.path ?? "/__gemi/socket",
534
+ hiddenDisconnectMs: options.hiddenDisconnectMs ?? DEFAULT_HIDDEN_DISCONNECT_MS
535
+ };
536
+ }
537
+ function reportListenerError(error) {
538
+ setTimeout(() => {
539
+ throw error;
540
+ });
541
+ }
542
+ //#endregion
543
+ export { IDLE_CLOSE_MS, MAX_LIMIT_RETRIES, RELEASE_LINGER_MS, RESYNC_COALESCE_MS, RealtimeClient, backoffDelay };
544
+
545
+ //# sourceMappingURL=RealtimeClient-CqGve6h8.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RealtimeClient-CqGve6h8.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 \"./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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,qBAAqB;;;;;AAclC,I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