gemi 0.129.0 → 0.130.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/{chunk-wmkrb1qv.js → chunk-13agap7z.js} +1 -1
- package/dist/{chunk-zw5z1k84.js → chunk-7ynnce4b.js} +1 -1
- package/dist/{chunk-sbdm4enk.js → chunk-xtqhagxz.js} +2 -2
- package/dist/{chunk-sbdm4enk.js.map → chunk-xtqhagxz.js.map} +1 -1
- package/dist/chunks/MutationError-DuKqBW8o.js +199 -0
- package/dist/chunks/MutationError-DuKqBW8o.js.map +1 -0
- package/dist/chunks/{RealtimeClient-CqGve6h8.js → RealtimeClient-DsWbFRC7.js} +11 -3
- package/dist/chunks/RealtimeClient-DsWbFRC7.js.map +1 -0
- package/dist/chunks/{ThemeProvider-DaX0eyqs.js → ThemeProvider-gWqXjGh-.js} +70 -91
- package/dist/chunks/ThemeProvider-gWqXjGh-.js.map +1 -0
- package/dist/chunks/channelKey-CIhHpX6x.js +10 -0
- package/dist/chunks/channelKey-CIhHpX6x.js.map +1 -0
- package/dist/chunks/fetchFileRequest-BSrgYnAy.js +57 -0
- package/dist/chunks/fetchFileRequest-BSrgYnAy.js.map +1 -0
- package/dist/chunks/{live-DIUDdLrA.js → live-CUdMhXHL.js} +22 -3
- package/dist/chunks/live-CUdMhXHL.js.map +1 -0
- package/dist/chunks/mutationExtras-CtY-X9m7.js +115 -0
- package/dist/chunks/mutationExtras-CtY-X9m7.js.map +1 -0
- package/dist/client/MutationError.d.ts +7 -9
- package/dist/client/MutationError.d.ts.map +1 -1
- package/dist/client/QueryResource.d.ts +3 -11
- package/dist/client/QueryResource.d.ts.map +1 -1
- package/dist/client/fetchFile.d.ts +4 -7
- package/dist/client/fetchFile.d.ts.map +1 -1
- package/dist/client/fetchFileRequest.d.ts +14 -0
- package/dist/client/fetchFileRequest.d.ts.map +1 -0
- package/dist/client/index.js +88 -339
- package/dist/client/index.js.map +1 -1
- package/dist/client/lazyModule.d.ts +32 -0
- package/dist/client/lazyModule.d.ts.map +1 -0
- package/dist/client/mutationErrorHelpers.d.ts +11 -0
- package/dist/client/mutationErrorHelpers.d.ts.map +1 -0
- package/dist/client/mutationExtras.d.ts +3 -0
- package/dist/client/mutationExtras.d.ts.map +1 -0
- package/dist/client/mutationModules.d.ts +17 -0
- package/dist/client/mutationModules.d.ts.map +1 -0
- package/dist/client/queryUpdates.d.ts +22 -0
- package/dist/client/queryUpdates.d.ts.map +1 -0
- package/dist/client/realtime/RealtimeClient.d.ts +5 -0
- package/dist/client/realtime/RealtimeClient.d.ts.map +1 -1
- package/dist/client/realtime/channelKey.d.ts +4 -0
- package/dist/client/realtime/channelKey.d.ts.map +1 -0
- package/dist/client/realtime/live.d.ts +6 -0
- package/dist/client/realtime/live.d.ts.map +1 -1
- package/dist/client/realtime/loader.d.ts +20 -23
- package/dist/client/realtime/loader.d.ts.map +1 -1
- package/dist/client/realtime/useChannelSubscription.d.ts.map +1 -1
- package/dist/client/useMutation.d.ts +1 -1
- package/dist/client/useMutation.d.ts.map +1 -1
- package/dist/client/useSetQueryData.d.ts +4 -17
- package/dist/client/useSetQueryData.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/testing/index.js +4 -3
- package/dist/testing/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/RealtimeClient-CqGve6h8.js.map +0 -1
- package/dist/chunks/ThemeProvider-DaX0eyqs.js.map +0 -1
- package/dist/chunks/live-DIUDdLrA.js.map +0 -1
- /package/dist/{chunk-wmkrb1qv.js.map → chunk-13agap7z.js.map} +0 -0
- /package/dist/{chunk-zw5z1k84.js.map → chunk-7ynnce4b.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{S as R,T as VJ,U as zJ}from"./chunk-
|
|
2
|
+
import{S as R,T as VJ,U as zJ}from"./chunk-xtqhagxz.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-
|
|
2
|
+
import{R as S,T as h,U as u}from"./chunk-xtqhagxz.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`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ba as y}from"./chunk-kk18xqgc.js";import{createElement as q}from"react";function z(i,n){let p=Object.keys(n).sort((s,g)=>g.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),b=new RegExp(p.join("|"),"g");return i.replace(b,(s)=>n[s])}async function L(i,n,p=[],b){let s=[...p.map((t)=>`${i}/views/${t}.tsx`),b?`${i}/views/${b}.tsx`:`${i}/views/RootLayout.tsx`],g=new Set;for(let t of s){let u=n.moduleGraph.getModulesByFile(t);if(u)for(let x of u)g.add(x)}let e=[],l=[],r={};for(let t of g)if(t)for(let u of t.importedModules){if(u.file.includes("module.css"))r[u.file]=u.ssrTransformResult.map.sourcesContent.join("");if(u.file.includes(".css"))l.push(u.file)}for(let t of l){let u=await n.transformRequest(t+"?direct"),x=t.includes("module.css"),k="";if(x)k=z(r[t],u.default);e.push({isDev:!0,id:t,content:x?k:u.code})}return e.map((t,u)=>{return q("style",{key:u,type:"text/css","data-vite-dev-id":t.id,dangerouslySetInnerHTML:{__html:t.content}})})}async function _(i=[]){return i.map((n,p)=>{return q("style",{key:p,id:n?.id,type:"text/css",dangerouslySetInnerHTML:{__html:n.content}})})}import{existsSync as J}from"fs";import{basename as N}from"path";import{networkInterfaces as O}from"os";var v={name:"gemi",version:"0.
|
|
2
|
+
import{Ba as y}from"./chunk-kk18xqgc.js";import{createElement as q}from"react";function z(i,n){let p=Object.keys(n).sort((s,g)=>g.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),b=new RegExp(p.join("|"),"g");return i.replace(b,(s)=>n[s])}async function L(i,n,p=[],b){let s=[...p.map((t)=>`${i}/views/${t}.tsx`),b?`${i}/views/${b}.tsx`:`${i}/views/RootLayout.tsx`],g=new Set;for(let t of s){let u=n.moduleGraph.getModulesByFile(t);if(u)for(let x of u)g.add(x)}let e=[],l=[],r={};for(let t of g)if(t)for(let u of t.importedModules){if(u.file.includes("module.css"))r[u.file]=u.ssrTransformResult.map.sourcesContent.join("");if(u.file.includes(".css"))l.push(u.file)}for(let t of l){let u=await n.transformRequest(t+"?direct"),x=t.includes("module.css"),k="";if(x)k=z(r[t],u.default);e.push({isDev:!0,id:t,content:x?k:u.code})}return e.map((t,u)=>{return q("style",{key:u,type:"text/css","data-vite-dev-id":t.id,dangerouslySetInnerHTML:{__html:t.content}})})}async function _(i=[]){return i.map((n,p)=>{return q("style",{key:p,id:n?.id,type:"text/css",dangerouslySetInnerHTML:{__html:n.content}})})}import{existsSync as J}from"fs";import{basename as N}from"path";import{networkInterfaces as O}from"os";var v={name:"gemi",version:"0.130.0",private:!1,license:"MIT",author:"Enes Tufekci <enes@gemijs.dev>",repository:{type:"git",url:"git+https://github.com/nstfkc/gemi.git",directory:"packages/gemi"},bin:{gemi:"./dist/bin/gemi.js","gemi-orm-generator":"./dist/bin/orm-generator.js"},files:["dist/**/*","ide/typescript-plugin/package.json","skills/**/*"],module:!0,exports:{"./http":"./http/index.ts","./client":"./client/index.ts","./ai":"./ai/index.ts","./ai/client":"./ai/client/index.ts","./testing":"./testing/index.ts","./app":"./app/index.ts","./facades":"./facades/index.ts","./email":"./email/index.ts","./vite":"./dist/vite/index.mjs","./kernel":"./kernel/index.ts","./services":"./services/index.ts","./i18n":"./i18n/index.ts","./dictionary":"./i18n/dictionaryRuntime.ts","./server":"./server/index.ts","./config":"./config/index.ts","./container":"./container/index.ts","./foundation":"./foundation/index.ts","./database":"./database/index.ts","./orm":"./orm/index.ts","./support":"./support/index.ts","./console/run":"./console/run.ts","./queue/work":"./services/queue/work.ts","./stats/route-table":"./stats/route-table.ts","./ide/typescript-plugin":"./ide/typescript-plugin/index.ts","./bun/preload":"./bun/preload.ts","./bun/plugin":"./bun/plugin.ts","./vitest":"./vitest/index.ts"},scripts:{lint:"oxlint",typecheck:"tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.browser.json && tsc --noEmit -p ide/typescript-plugin/tsconfig.json",build:"NODE_ENV=production bun run build:core && bun run build:bin && bun run build:types && bun run build:client && bun run build:plugin && bun run build:ts-plugin && bun run build:client-types && bun run build:augmentation","build:core":"bun ./scripts/build.ts","build:bin":"bun build --outdir=./dist/bin --target=bun --external=vite --external=react-dom --external=react/jsx-runtime --external=bun --external=sharp --external=@azure/storage-blob --external=typescript --sourcemap ./bin/gemi.ts ./bin/orm-generator.ts && bun ./scripts/prepare-bin.ts","build:client":"rm -rf dist/client dist/testing dist/ai/client dist/chunks && vite build -c vite.client.config.mts","build:plugin":"vite build -c vite.plugin.config.mts","build:ts-plugin":"bun ./scripts/build-ts-plugin.ts","build:types":"tsc -p tsconfig.build.json","build:client-types":"tsc -p tsconfig.browser.json",test:"bun --bun x vitest","test:types":"vitest run --typecheck.only","test:live":"bun --bun x vitest run ai/live","test:packaging":"bun --bun x vitest run --config vitest.packaging.config.ts","build:publish":"bun scripts/build-publish.ts",prepublishOnly:"echo 'Do not publish from this directory \u2014 its exports point at TS source. Run: bun run build:publish, then publish from .publish/' && exit 1","build:augmentation":"bun ./scripts/wire-augmentation.ts"},dependencies:{"@aws-sdk/client-s3":"^3.629.0","@aws-sdk/s3-request-presigner":"^3.629.0","ast-types":"^0.14.2",commander:"^12.1.0",history:"^5.3.0","jsx-email":"2.0.0-rc2.1","magic-string":"^0.30.17",open:"^10.1.0","react-error-boundary":"^6.0.0",recast:"^0.23.9",resend:"^6.12.3",satori:"^0.12.2","temporal-polyfill":"^0.2.5","twitter-api-v2":"^1.20.2","urlpattern-polyfill":"^10.0.0",uuid:"^9.0.1"},devDependencies:{"@babel/parser":"^7.25.4","@prisma/generator-helper":"^6.5.0","@repo/typescript-config":"*","@testing-library/react":"^16.3.2","@types/bun":"^1.3.14","@types/eslint":"^8.56.5","@types/node":"^20.11.24","@types/react":"^19.0.2","@types/react-dom":"^19.0.2",eslint:"^8.57.0",jsdom:"^30.0.1",oxlint:"^1.39.0",postgres:"^3.4.5",react:"19.2.3","react-dom":"19.2.3",typescript:"^5.7.3",vitest:"^4.0.0"},peerDependencies:{"@azure/storage-blob":"^12.28.0",react:">=19","react-dom":">=19",sharp:"^0.34.2",typescript:">=5",vite:"^8.0.0",postgres:"^3.4.0"},peerDependenciesMeta:{"@azure/storage-blob":{optional:!0},typescript:{optional:!0},postgres:{optional:!0}}};var Q=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D"],W=Boolean(process.stdout.isTTY)&&!process.env.NO_COLOR,c=(i,n)=>W?`\x1B[${i}m${n}\x1B[0m`:n,X=(i)=>c("1",i),d=(i)=>c("2",i),j=(i)=>c("36",i),Y=(i)=>c("32",i),Z=(i)=>c("35",i);function $(){return v.version??"?"}function f(i){for(let n of Object.values(O()))for(let p of n??[])if((p.family==="IPv4"||p.family===4)&&!p.internal)return`http://${p.address}:${i}`;return null}function H(i){return y(i).filter((n)=>J(n)).map((n)=>N(n))}function T(i){let{port:n,rootDir:p}=i,b=`http://localhost:${n}`,s=f(n),g=H(p),e=(r,t)=>` ${Y("\u279C")} ${X(r.padEnd(9))}${t}`,l=["",...Q.map((r)=>Z(r)),"",` ${d("gemi")} ${j(`v${$()}`)}`,"",e("Local:",j(b)),e("Network:",s?j(s):d("unavailable")),e("Env:",g.length?g.join(", "):d("none")),""];console.log(l.join(`
|
|
3
3
|
`))}function I(i=process.env.SERVER_IDLE_TIMEOUT){if(i===void 0||i.trim()==="")return 10;let n=Number(i.trim());if(!Number.isInteger(n)||n<0||n>255)throw Error(`SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 (0 disables the timeout), got ${JSON.stringify(i)}.`);return n}
|
|
4
4
|
export{L as R,_ as S,T,I as U};
|
|
5
5
|
|
|
6
|
-
//# debugId=
|
|
6
|
+
//# debugId=1F5F6DD3E5726AE964756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"/**\n * Bun's default, and what both servers use when `SERVER_IDLE_TIMEOUT` is unset.\n */\nexport const DEFAULT_SERVER_IDLE_TIMEOUT = 10;\n\n/**\n * The `idleTimeout` (seconds) both `gemi dev` and `gemi start` pass to\n * `Bun.serve`, from `SERVER_IDLE_TIMEOUT` (#787).\n *\n * One reader for both servers, so a long-poll that works under `gemi start`\n * also works under `gemi dev`. Before this, only `httpProd` read the variable\n * and the dev server always ran at Bun's 10 seconds.\n *\n * It is the time a connection may stay silent, a response that has not started\n * included, before Bun closes it; `0` disables it. It does not apply to an\n * upgraded websocket (the HMR relay included), which has its own\n * `websocket.idleTimeout`.\n *\n * Unset or blank means the default. Anything that is not a whole number from 0\n * to 255 (Bun's own limits) fails the boot with the variable's name, instead\n * of Bun's \"expects idleTimeout to be an integer\", which does not say where the\n * value came from.\n */\nexport function serverIdleTimeout(raw: string | undefined = process.env.SERVER_IDLE_TIMEOUT): number {\n if (raw === undefined || raw.trim() === \"\") return DEFAULT_SERVER_IDLE_TIMEOUT;\n\n const seconds = Number(raw.trim());\n if (!Number.isInteger(seconds) || seconds < 0 || seconds > 255) {\n throw new Error(\n `SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 ` +\n `(0 disables the timeout), got ${JSON.stringify(raw)}.`,\n );\n }\n return seconds;\n}\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";yCAAA,wBAAS,cAGT,SAAS,CAAc,CAAC,EAAc,EAAwC,CAC5E,IAAM,EAAc,OAAO,KAAK,CAAM,EACnC,KAAK,CAAC,EAAG,IAAM,EAAE,OAAS,EAAE,MAAM,EAClC,IAAI,CAAC,IAAQ,EAAI,QAAQ,sBAAuB,MAAM,CAAC,EAGpD,EAAQ,IAAI,OAAO,EAAY,KAAK,GAAG,EAAG,GAAG,EAEnD,OAAO,EAAK,QAAQ,EAAO,CAAC,IAAU,EAAO,EAAM,EAGrD,eAAsB,CAAe,CACnC,EACA,EACA,EAAyB,CAAC,EAE1B,EACA,CACA,IAAM,EAAQ,CACZ,GAAG,EAAa,IAAI,CAAC,IAAS,GAAG,WAAgB,OAAU,EAC3D,EAAS,GAAG,WAAgB,QAAe,GAAG,wBAChD,EAEM,EAAU,IAAI,IACpB,QAAW,KAAQ,EAAO,CACxB,IAAM,EAAM,EAAK,YAAY,iBAAiB,CAAI,EAClD,GAAI,EACF,QAAW,KAAK,EAAK,EAAQ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AAI,KAAK,IAAM,GAAI,MArBH,IAuBzC,IAAM,EAAU,OAAO,EAAI,KAAK,CAAC,EACjC,GAAI,CAAC,OAAO,UAAU,CAAO,GAAK,EAAU,GAAK,EAAU,IACzD,MAAU,MACR,qGACmC,KAAK,UAAU,CAAG,IACvD,EAEF,OAAO",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "1F5F6DD3E5726AE964756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
//#region http/refusal.ts
|
|
2
|
+
/**
|
|
3
|
+
* The kind a status stands for, for a refusal that does not name one: an app's
|
|
4
|
+
* own `RequestBreakerError`, or an older server's `{ message }`. Any other 4xx
|
|
5
|
+
* is a `form_error`, a message about this request for `<FormError>` to show.
|
|
6
|
+
*/
|
|
7
|
+
function refusalKindForStatus(status) {
|
|
8
|
+
if (status === 401) return "authentication";
|
|
9
|
+
if (status === 403) return "permission";
|
|
10
|
+
if (status === 404) return "not_found";
|
|
11
|
+
if (status === 416) return "range_not_satisfiable";
|
|
12
|
+
if (status === 429) return "rate_limit";
|
|
13
|
+
if (status >= 500) return "server_error";
|
|
14
|
+
return "form_error";
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region client/MutationError.ts
|
|
18
|
+
var LEGACY_MESSAGES = {
|
|
19
|
+
"Authentication error": "authentication",
|
|
20
|
+
"Not authorized": "authorization",
|
|
21
|
+
"Insufficient permissions": "permission",
|
|
22
|
+
"Invalid CSRF token": "csrf",
|
|
23
|
+
"Internal Server Error": "server_error",
|
|
24
|
+
Forbidden: "permission",
|
|
25
|
+
"Not found": "not_found",
|
|
26
|
+
"Rate limit exceeded": "rate_limit"
|
|
27
|
+
};
|
|
28
|
+
/** @internal */
|
|
29
|
+
function isObject(error) {
|
|
30
|
+
return typeof error === "object" && error !== null;
|
|
31
|
+
}
|
|
32
|
+
function legacyKind(message, status) {
|
|
33
|
+
return LEGACY_MESSAGES[message] ?? (status === 401 ? "authorization" : refusalKindForStatus(status));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The `MutationError` a non-2xx response's parsed body stands for.
|
|
37
|
+
*
|
|
38
|
+
* gemi's own error bodies are `{ error }`, and the value under `error` is what
|
|
39
|
+
* is handed over. An app's body without one —
|
|
40
|
+
* `HttpResponse.json({ message: "Taken" }, { status: 409 })` — is handed over
|
|
41
|
+
* whole. A body with no content (`null`) becomes a refusal naming the status.
|
|
42
|
+
*
|
|
43
|
+
* What is handed over carries `status`, and a `kind` when it has a `message`:
|
|
44
|
+
* a bare string, which servers before 0.88 sent for most refusals, becomes
|
|
45
|
+
* `{ kind, message, status }`, and so does a `{ message }` without a kind.
|
|
46
|
+
*
|
|
47
|
+
* @internal
|
|
48
|
+
*/
|
|
49
|
+
function mutationErrorFromBody(body, status) {
|
|
50
|
+
const error = isObject(body) && "error" in body && body.error != null ? body.error : body;
|
|
51
|
+
if (error == null) return {
|
|
52
|
+
kind: refusalKindForStatus(status),
|
|
53
|
+
message: `Request failed with status ${status}`,
|
|
54
|
+
status
|
|
55
|
+
};
|
|
56
|
+
if (typeof error === "string") return {
|
|
57
|
+
kind: legacyKind(error, status),
|
|
58
|
+
message: error,
|
|
59
|
+
status
|
|
60
|
+
};
|
|
61
|
+
if (!isObject(error) || error instanceof Error) return error;
|
|
62
|
+
const withStatus = {
|
|
63
|
+
...error,
|
|
64
|
+
status: typeof error.status === "number" ? error.status : status
|
|
65
|
+
};
|
|
66
|
+
if (typeof error.kind !== "string" && typeof error.message === "string") return {
|
|
67
|
+
...withStatus,
|
|
68
|
+
kind: refusalKindForStatus(withStatus.status)
|
|
69
|
+
};
|
|
70
|
+
return withStatus;
|
|
71
|
+
}
|
|
72
|
+
function kindOf(error) {
|
|
73
|
+
if (typeof error === "string") return LEGACY_MESSAGES[error];
|
|
74
|
+
if (!isObject(error) || error instanceof Error) return void 0;
|
|
75
|
+
if (typeof error.kind === "string") return error.kind;
|
|
76
|
+
if (typeof error.status === "number") return refusalKindForStatus(error.status);
|
|
77
|
+
return typeof error.message === "string" ? LEGACY_MESSAGES[error.message] : void 0;
|
|
78
|
+
}
|
|
79
|
+
/** Field messages, as `<ValidationErrors>` renders them. */
|
|
80
|
+
function isValidationError(error) {
|
|
81
|
+
return isObject(error) && error.kind === "validation_error";
|
|
82
|
+
}
|
|
83
|
+
/** A form-level message, as `<FormError>` renders it. */
|
|
84
|
+
function isFormError(error) {
|
|
85
|
+
return isObject(error) && error.kind === "form_error";
|
|
86
|
+
}
|
|
87
|
+
/** No signed-in user: `AuthenticationError` (401). */
|
|
88
|
+
function isAuthenticationError(error) {
|
|
89
|
+
return kindOf(error) === "authentication";
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A signed-in user who may not do this: `InsufficientPermissionsError` (403),
|
|
93
|
+
* `AuthorizationError` (401) or a policy denial (403), whatever message it was
|
|
94
|
+
* thrown with.
|
|
95
|
+
*/
|
|
96
|
+
function isPermissionError(error) {
|
|
97
|
+
const kind = kindOf(error);
|
|
98
|
+
return kind === "permission" || kind === "authorization";
|
|
99
|
+
}
|
|
100
|
+
/** The CSRF cookie is missing or stale (403). A reload fixes it. */
|
|
101
|
+
function isCsrfError(error) {
|
|
102
|
+
return kindOf(error) === "csrf";
|
|
103
|
+
}
|
|
104
|
+
/** A missing record, file or route (404). */
|
|
105
|
+
function isNotFoundError(error) {
|
|
106
|
+
return kindOf(error) === "not_found";
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* `RateLimitMiddleware` or `RateLimiter.enforce` refused the request (429).
|
|
110
|
+
* `retryAfter` (ms) says when to try again, when the server sent it.
|
|
111
|
+
*/
|
|
112
|
+
function isRateLimitError(error) {
|
|
113
|
+
return kindOf(error) === "rate_limit";
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The server failed (a 500, under `gemi dev` too), or answered something that
|
|
117
|
+
* is not JSON.
|
|
118
|
+
*/
|
|
119
|
+
function isServerError(error) {
|
|
120
|
+
return kindOf(error) === "server_error" || error instanceof SyntaxError;
|
|
121
|
+
}
|
|
122
|
+
/** The request got no answer: offline, DNS, CORS, a dropped connection. */
|
|
123
|
+
function isNetworkError(error) {
|
|
124
|
+
return error instanceof TypeError;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Which of the guards above `error` passes, for a `switch` over all of them.
|
|
128
|
+
* `"unknown"` is everything else: a 416, an error body of the app's own shape.
|
|
129
|
+
*/
|
|
130
|
+
function mutationErrorKind(error) {
|
|
131
|
+
if (isValidationError(error)) return "validation";
|
|
132
|
+
if (isFormError(error)) return "form";
|
|
133
|
+
if (isAuthenticationError(error)) return "authentication";
|
|
134
|
+
if (isPermissionError(error)) return "permission";
|
|
135
|
+
if (isCsrfError(error)) return "csrf";
|
|
136
|
+
if (isNotFoundError(error)) return "not_found";
|
|
137
|
+
if (isRateLimitError(error)) return "rate_limit";
|
|
138
|
+
if (isServerError(error)) return "server";
|
|
139
|
+
if (isNetworkError(error)) return "network";
|
|
140
|
+
return "unknown";
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* An error answered with `status`: a route's typed error from
|
|
144
|
+
* `HttpResponse.error(status, body)` / `httpError`, narrowed to the members
|
|
145
|
+
* of `error`'s type with that status.
|
|
146
|
+
*
|
|
147
|
+
* ```ts
|
|
148
|
+
* onError: (error) => {
|
|
149
|
+
* if (isHttpError(error, 410)) toast(error.message);
|
|
150
|
+
* }
|
|
151
|
+
* ```
|
|
152
|
+
*
|
|
153
|
+
* At run time it checks the status alone, so gemi's own refusals with the
|
|
154
|
+
* same status (a 404 `not_found`, a 429 `rate_limit`) pass it too; pick a
|
|
155
|
+
* status gemi does not use for its own errors, or check `kind` after it.
|
|
156
|
+
*/
|
|
157
|
+
function isHttpError(error, status) {
|
|
158
|
+
return isObject(error) && !(error instanceof Error) && error.status === status;
|
|
159
|
+
}
|
|
160
|
+
var FALLBACK_MESSAGE = "Something went wrong. Try again.";
|
|
161
|
+
function unwrapQueryError(error) {
|
|
162
|
+
if (error instanceof Error && error.name === "QueryError" && "body" in error) {
|
|
163
|
+
const { body, status } = error;
|
|
164
|
+
return body == null ? error : mutationErrorFromBody(body, status);
|
|
165
|
+
}
|
|
166
|
+
return error;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* `error.list(fallback)` for any value: an error kept from a mutation, a
|
|
170
|
+
* `useQuery` `QueryError` (its body is read), or anything else.
|
|
171
|
+
*
|
|
172
|
+
* Kept in step with `list` in `./mutationErrorHelpers`, which the mutation
|
|
173
|
+
* hooks load on first use (#915) and so cannot share this code: an app's
|
|
174
|
+
* bundler would put it back in the entry chunk. `MutationError.helpers.test`
|
|
175
|
+
* runs the same cases through both.
|
|
176
|
+
*/
|
|
177
|
+
function mutationErrorList(error, fallback = FALLBACK_MESSAGE) {
|
|
178
|
+
const value = unwrapQueryError(error);
|
|
179
|
+
if (isValidationError(value)) {
|
|
180
|
+
const messages = Object.values(value.messages ?? {}).flat().filter((message) => typeof message === "string" && message !== "");
|
|
181
|
+
return messages.length > 0 ? messages : [fallback];
|
|
182
|
+
}
|
|
183
|
+
if (isObject(value) && !(value instanceof Error) && value.kind !== "server_error" && typeof value.message === "string" && value.message !== "") return [value.message];
|
|
184
|
+
return [fallback];
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* `error.field(name)` for any value: a validation error's messages for
|
|
188
|
+
* `name` (a `QueryError`'s body is read), `[]` for anything else.
|
|
189
|
+
*/
|
|
190
|
+
function mutationErrorField(error, name) {
|
|
191
|
+
const value = unwrapQueryError(error);
|
|
192
|
+
if (!isValidationError(value)) return [];
|
|
193
|
+
const messages = value.messages?.[name];
|
|
194
|
+
return Array.isArray(messages) ? [...messages] : [];
|
|
195
|
+
}
|
|
196
|
+
//#endregion
|
|
197
|
+
export { isNetworkError as a, isPermissionError as c, isValidationError as d, mutationErrorField as f, mutationErrorList as h, isHttpError as i, isRateLimitError as l, mutationErrorKind as m, isCsrfError as n, isNotFoundError as o, mutationErrorFromBody as p, isFormError as r, isObject as s, isAuthenticationError as t, isServerError as u };
|
|
198
|
+
|
|
199
|
+
//# sourceMappingURL=MutationError-DuKqBW8o.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MutationError-DuKqBW8o.js","names":[],"sources":["../../http/refusal.ts","../../client/MutationError.ts"],"sourcesContent":["/**\n * The shape of a refusal on the wire: the `error` field of a non-2xx `/api`\n * answer, for every refusal gemi sends.\n *\n * It was a bare string for most of them (`\"Not authorized\"`, `\"Invalid CSRF\n * token\"`, a 500's message) and `{ message }` for the rest. A string carries no\n * status, so a client could only classify the framework's default messages: an\n * `AuthorizationError` thrown with a message of its own, the rule the skill\n * teaches, was `\"unknown\"`, and apps compared strings (issue #673).\n *\n * Shared by the server, which builds it, and the client, which reads it and\n * wraps an older server's bare strings into it, so this module imports nothing.\n */\n\n/**\n * Which refusal this is. `validation_error` and `form_error` predate the rest\n * and keep their spelling, and `server_error` is the kind `useUpload` already\n * reported for a failed upload, so a 500 has one name wherever it comes from.\n */\nexport type RefusalKind =\n /** No signed-in user: `AuthenticationError` (401). */\n | \"authentication\"\n /** `AuthorizationError` (401): a known user refused this action. */\n | \"authorization\"\n /** `InsufficientPermissionsError` (403) or a policy denial (403). */\n | \"permission\"\n /** `InvalidCSRFTokenError` (403): the CSRF cookie is missing or stale. */\n | \"csrf\"\n /** A missing record, file or route (404). */\n | \"not_found\"\n /** A `Range` the object cannot satisfy (416). */\n | \"range_not_satisfiable\"\n /** `RateLimitMiddleware` or `RateLimiter.enforce` refused the request (429). */\n | \"rate_limit\"\n /** An unhandled exception (500). */\n | \"server_error\"\n /** A single form-level message, which `<FormError>` renders. */\n | \"form_error\"\n /** `ValidationError` (400). Carries `messages` instead of `message`. */\n | \"validation_error\";\n\n/** A refusal's `error`, apart from `validation_error`, which has `messages`. */\nexport type Refusal<K extends RefusalKind = Exclude<RefusalKind, \"validation_error\">> = {\n kind: K;\n message: string;\n status: number;\n /**\n * `rate_limit` only: milliseconds until a retry can succeed, when the\n * limiter knew (the `rate-limit` middleware, `RateLimiter.enforce`).\n */\n retryAfter?: number;\n};\n\n/**\n * The kind a status stands for, for a refusal that does not name one: an app's\n * own `RequestBreakerError`, or an older server's `{ message }`. Any other 4xx\n * is a `form_error`, a message about this request for `<FormError>` to show.\n */\nexport function refusalKindForStatus(status: number): Exclude<RefusalKind, \"validation_error\"> {\n if (status === 401) return \"authentication\";\n if (status === 403) return \"permission\";\n if (status === 404) return \"not_found\";\n if (status === 416) return \"range_not_satisfiable\";\n if (status === 429) return \"rate_limit\";\n if (status >= 500) return \"server_error\";\n return \"form_error\";\n}\n","import { refusalKindForStatus, type RefusalKind } from \"../http/refusal\";\n\n/**\n * What a failed mutation hands `onError` and puts in `error` — `useMutation`\n * and its `usePost`/`usePut`/`usePatch`/`useDelete` shorthands, `useUpload`,\n * and `<Form onError>`.\n *\n * It was typed `any` on `<Form>` and on the hooks' `error`, and as a union of\n * `kind`s the server never sent (`not_authorized`, `insufficient_permissions`)\n * on the hooks' `onError`. Apps sniffed the shape themselves, and got it wrong\n * as easily as right. This is the shape the framework actually produces,\n * member by member, read off the server's error payloads and the client's\n * fetch code (issue #626).\n *\n * Since 0.88 every refusal is an object with a `kind`, its `message` and the\n * `status` it came with (issue #673). Most refusals were a bare string before,\n * which carried no status, so a refusal thrown with a message of its own could\n * not be told apart from any other string. A server older than 0.85 still sends\n * those strings; the client wraps them into the same object, so the guards and\n * `error.message` work against either.\n */\n\n/** A server-side `ValidationError` (400): messages keyed by field. */\nexport interface MutationValidationError {\n kind: \"validation_error\";\n messages: Record<string, string[]>;\n status?: number;\n}\n\n/**\n * A single form-level message, which `<FormError>` renders: a\n * `RequestBreakerError` of the app's own, or any other 4xx that answered a\n * message without a kind of its own.\n */\nexport interface MutationFormError {\n kind: \"form_error\";\n message: string;\n status?: number;\n}\n\n/**\n * The server failed: an unhandled exception (500; under `gemi dev` the message\n * is the exception's), or a failed `useUpload` whose body was not JSON.\n */\nexport interface MutationServerError {\n kind: \"server_error\";\n message: string;\n status?: number;\n}\n\n/** The refusals other than the three above. */\nexport type MutationRefusalKind = Exclude<\n RefusalKind,\n \"validation_error\" | \"form_error\" | \"server_error\"\n>;\n\n/**\n * A refusal: `authentication` (401), `authorization` (`AuthorizationError`,\n * 401), `permission` (`InsufficientPermissionsError` or a policy, 403), `csrf`\n * (403), `not_found` (404), `range_not_satisfiable` (416) or `rate_limit`\n * (429). `message` is the one it was thrown with.\n */\nexport interface MutationRefusal<K extends MutationRefusalKind = MutationRefusalKind> {\n kind: K;\n message: string;\n status: number;\n /**\n * `rate_limit` only: milliseconds until a retry can succeed, when the\n * server's limiter knew (the `rate-limit` middleware, `RateLimiter.enforce`).\n */\n retryAfter?: number;\n}\n\n/**\n * @deprecated A `{ message }` body is wrapped into a `MutationRefusal` or\n * `MutationFormError` since 0.88, and `MutationError` no longer includes this.\n */\nexport interface MutationMessageError {\n kind?: undefined;\n message: string;\n}\n\n/**\n * Every value `onError` receives and `error` holds for a request gemi's server\n * answered, or failed to reach:\n *\n * - `MutationValidationError`, `MutationFormError`, `MutationServerError`,\n * `MutationRefusal` — tagged with `kind`, and (from the server) `status`.\n * - `Error` — raised in the browser: a `TypeError` when the request never got\n * an answer (offline, DNS, CORS), a `SyntaxError` when the answer was not\n * JSON (a proxy's HTML error page, say). A throw from an `onSuccess` of\n * yours is reported through `onError` as well, as whatever it threw.\n *\n * Never a string since 0.88. A cancelled request is not an error: `onCanceled`\n * runs and `error` stays `null`. A route's typed errors — the bodies its\n * handler answers with `HttpResponse.error(status, body)` / `httpError` — are\n * added to this union on its hooks and `<Form>` (`MutationError | E`). Any\n * other error body of the route's own shape is outside this type: a body with an `error` field\n * (`HttpResponse.json({ error }, { status: 409 })`) hands over that field, as\n * gemi's own errors do, and any other body is handed over whole. Either is\n * given a `kind` (from the status) and the `status` when it is an object with\n * a string `message` and no `kind`, and becomes one when it is a string.\n */\nexport type MutationError =\n | MutationValidationError\n | MutationFormError\n | MutationServerError\n | MutationRefusal\n | Error;\n\n/** What `mutationErrorKind` answers, one per guard below. */\nexport type MutationErrorKind =\n | \"validation\"\n | \"form\"\n | \"authentication\"\n | \"permission\"\n | \"csrf\"\n | \"not_found\"\n | \"rate_limit\"\n | \"server\"\n | \"network\"\n | \"unknown\";\n\n// What a server before 0.88 sent: the framework's own messages, as bare\n// strings, or as `{ message }`. Read so a client on 0.85 classifies an older\n// server's refusals during a rolling deploy. Remove in 0.86.\nconst LEGACY_MESSAGES: Record<string, RefusalKind> = {\n \"Authentication error\": \"authentication\",\n \"Not authorized\": \"authorization\",\n \"Insufficient permissions\": \"permission\",\n \"Invalid CSRF token\": \"csrf\",\n \"Internal Server Error\": \"server_error\",\n Forbidden: \"permission\",\n \"Not found\": \"not_found\",\n \"Rate limit exceeded\": \"rate_limit\",\n};\n\n/** @internal */\nexport function isObject(error: unknown): error is Record<string, unknown> {\n return typeof error === \"object\" && error !== null;\n}\n\n// A bare string from a server before 0.88. Its own message names the kind when\n// it is one of the framework's; otherwise the status does, and a 401 with a\n// message of its own can only be an `AuthorizationError` — an\n// `AuthenticationError` always says \"Authentication error\".\nfunction legacyKind(message: string, status: number): RefusalKind {\n return (\n LEGACY_MESSAGES[message] ?? (status === 401 ? \"authorization\" : refusalKindForStatus(status))\n );\n}\n\n/**\n * The `MutationError` a non-2xx response's parsed body stands for.\n *\n * gemi's own error bodies are `{ error }`, and the value under `error` is what\n * is handed over. An app's body without one —\n * `HttpResponse.json({ message: \"Taken\" }, { status: 409 })` — is handed over\n * whole. A body with no content (`null`) becomes a refusal naming the status.\n *\n * What is handed over carries `status`, and a `kind` when it has a `message`:\n * a bare string, which servers before 0.88 sent for most refusals, becomes\n * `{ kind, message, status }`, and so does a `{ message }` without a kind.\n *\n * @internal\n */\nexport function mutationErrorFromBody(body: unknown, status: number): MutationError {\n const error = isObject(body) && \"error\" in body && body.error != null ? body.error : body;\n if (error == null) {\n return {\n kind: refusalKindForStatus(status),\n message: `Request failed with status ${status}`,\n status,\n } as MutationError;\n }\n if (typeof error === \"string\") {\n return { kind: legacyKind(error, status), message: error, status } as MutationError;\n }\n if (!isObject(error) || error instanceof Error) {\n return error as MutationError;\n }\n const withStatus = { ...error, status: typeof error.status === \"number\" ? error.status : status };\n if (typeof error.kind !== \"string\" && typeof error.message === \"string\") {\n return {\n ...withStatus,\n // The status alone places an older server's `{ message }` bodies (403\n // \"Forbidden\", 404, 429), and it is what an app's own body means.\n kind: refusalKindForStatus(withStatus.status),\n } as MutationError;\n }\n return withStatus as MutationError;\n}\n\n// The kind a value stands for: its `kind`; else, for an object that has none,\n// its `status`; else one of the framework's old messages, as a bare string or\n// `{ message }`, for a body handed to a guard straight off an older server.\nfunction kindOf(error: unknown): string | undefined {\n if (typeof error === \"string\") return LEGACY_MESSAGES[error];\n if (!isObject(error) || error instanceof Error) return undefined;\n if (typeof error.kind === \"string\") return error.kind;\n if (typeof error.status === \"number\") return refusalKindForStatus(error.status);\n return typeof error.message === \"string\" ? LEGACY_MESSAGES[error.message] : undefined;\n}\n\n// The guards read `kind`, falling back to `status`, and accept the bare\n// strings and `{ message }` bodies of a server before 0.88 for one minor. What\n// the hooks hand over is already wrapped, so those fallbacks only matter for a\n// body passed in by hand.\n\n/** Field messages, as `<ValidationErrors>` renders them. */\nexport function isValidationError(\n error: unknown,\n): error is MutationValidationError {\n return isObject(error) && error.kind === \"validation_error\";\n}\n\n/** A form-level message, as `<FormError>` renders it. */\nexport function isFormError(error: unknown): error is MutationFormError {\n return isObject(error) && error.kind === \"form_error\";\n}\n\n/** No signed-in user: `AuthenticationError` (401). */\nexport function isAuthenticationError(\n error: unknown,\n): error is MutationRefusal<\"authentication\"> {\n return kindOf(error) === \"authentication\";\n}\n\n/**\n * A signed-in user who may not do this: `InsufficientPermissionsError` (403),\n * `AuthorizationError` (401) or a policy denial (403), whatever message it was\n * thrown with.\n */\nexport function isPermissionError(\n error: unknown,\n): error is MutationRefusal<\"permission\" | \"authorization\"> {\n const kind = kindOf(error);\n return kind === \"permission\" || kind === \"authorization\";\n}\n\n/** The CSRF cookie is missing or stale (403). A reload fixes it. */\nexport function isCsrfError(error: unknown): error is MutationRefusal<\"csrf\"> {\n return kindOf(error) === \"csrf\";\n}\n\n/** A missing record, file or route (404). */\nexport function isNotFoundError(\n error: unknown,\n): error is MutationRefusal<\"not_found\"> {\n return kindOf(error) === \"not_found\";\n}\n\n/**\n * `RateLimitMiddleware` or `RateLimiter.enforce` refused the request (429).\n * `retryAfter` (ms) says when to try again, when the server sent it.\n */\nexport function isRateLimitError(\n error: unknown,\n): error is MutationRefusal<\"rate_limit\"> {\n return kindOf(error) === \"rate_limit\";\n}\n\n/**\n * The server failed (a 500, under `gemi dev` too), or answered something that\n * is not JSON.\n */\nexport function isServerError(\n error: unknown,\n): error is MutationServerError | SyntaxError {\n return kindOf(error) === \"server_error\" || error instanceof SyntaxError;\n}\n\n/** The request got no answer: offline, DNS, CORS, a dropped connection. */\nexport function isNetworkError(error: unknown): error is TypeError {\n return error instanceof TypeError;\n}\n\n/**\n * Which of the guards above `error` passes, for a `switch` over all of them.\n * `\"unknown\"` is everything else: a 416, an error body of the app's own shape.\n */\nexport function mutationErrorKind(error: unknown): MutationErrorKind {\n if (isValidationError(error)) return \"validation\";\n if (isFormError(error)) return \"form\";\n if (isAuthenticationError(error)) return \"authentication\";\n if (isPermissionError(error)) return \"permission\";\n if (isCsrfError(error)) return \"csrf\";\n if (isNotFoundError(error)) return \"not_found\";\n if (isRateLimitError(error)) return \"rate_limit\";\n if (isServerError(error)) return \"server\";\n if (isNetworkError(error)) return \"network\";\n return \"unknown\";\n}\n\n/**\n * The members of `E` answered with status `S`. When none of them names it — an\n * `unknown`, or a `MutationError` alone — `E` with that status, rather than\n * `never`.\n */\nexport type HttpErrorWithStatus<E, S extends number> = [Extract<E, { status: S }>] extends [never]\n ? E & { status: S }\n : Extract<E, { status: S }>;\n\n/**\n * An error answered with `status`: a route's typed error from\n * `HttpResponse.error(status, body)` / `httpError`, narrowed to the members\n * of `error`'s type with that status.\n *\n * ```ts\n * onError: (error) => {\n * if (isHttpError(error, 410)) toast(error.message);\n * }\n * ```\n *\n * At run time it checks the status alone, so gemi's own refusals with the\n * same status (a 404 `not_found`, a 429 `rate_limit`) pass it too; pick a\n * status gemi does not use for its own errors, or check `kind` after it.\n */\nexport function isHttpError<E, S extends number>(\n error: E,\n status: S,\n): error is HttpErrorWithStatus<E, S> {\n return isObject(error) && !(error instanceof Error) && error.status === status;\n}\n\n/**\n * What every error the mutation hooks hand over carries (issue #890): the\n * messages to show a person, without flattening `messages` by hand.\n */\nexport interface MutationErrorHelpers {\n /**\n * The failure in words, as a flat list that is never empty: a validation\n * error's messages, every field's in the order the server sent them; the\n * `message` of any other error the server meant for a person (a form error,\n * a refusal, a route's typed error); else `[fallback]` — for a server error,\n * whose message is an exception's under `gemi dev`, and for the browser's\n * own errors (no answer, an answer that was not JSON).\n *\n * `fallback` defaults to `\"Something went wrong. Try again.\"`.\n */\n list(fallback?: string): string[];\n /** A validation error's messages for the field `name`; `[]` otherwise. */\n field(name: string): string[];\n}\n\n/**\n * `T` with the helpers, member by member. A member that has a `list` or\n * `field` of its own — a route's typed error body with a `field` key — keeps\n * it, and does not get that helper.\n */\nexport type WithMutationErrorHelpers<T> = T extends object\n ? T & Omit<MutationErrorHelpers, keyof T>\n : T;\n\nconst FALLBACK_MESSAGE = \"Something went wrong. Try again.\";\n\n// A `QueryError`'s refusal, read as the mutation hooks read a body. Read by\n// shape, not `instanceof`, so a copy of the class from another bundle works.\nfunction unwrapQueryError(error: unknown): unknown {\n if (error instanceof Error && error.name === \"QueryError\" && \"body\" in error) {\n const { body, status } = error as Error & { body: unknown; status: number };\n return body == null ? error : mutationErrorFromBody(body, status);\n }\n return error;\n}\n\n/**\n * `error.list(fallback)` for any value: an error kept from a mutation, a\n * `useQuery` `QueryError` (its body is read), or anything else.\n *\n * Kept in step with `list` in `./mutationErrorHelpers`, which the mutation\n * hooks load on first use (#915) and so cannot share this code: an app's\n * bundler would put it back in the entry chunk. `MutationError.helpers.test`\n * runs the same cases through both.\n */\nexport function mutationErrorList(\n error: unknown,\n fallback: string = FALLBACK_MESSAGE,\n): string[] {\n const value = unwrapQueryError(error);\n if (isValidationError(value)) {\n const messages = Object.values(value.messages ?? {})\n .flat()\n .filter((message) => typeof message === \"string\" && message !== \"\");\n return messages.length > 0 ? messages : [fallback];\n }\n if (\n isObject(value) &&\n !(value instanceof Error) &&\n value.kind !== \"server_error\" &&\n typeof value.message === \"string\" &&\n value.message !== \"\"\n ) {\n return [value.message];\n }\n return [fallback];\n}\n\n/**\n * `error.field(name)` for any value: a validation error's messages for\n * `name` (a `QueryError`'s body is read), `[]` for anything else.\n */\nexport function mutationErrorField(error: unknown, name: string): string[] {\n const value = unwrapQueryError(error);\n if (!isValidationError(value)) return [];\n const messages = value.messages?.[name];\n return Array.isArray(messages) ? [...messages] : [];\n}\n"],"mappings":";;;;;;AA0DA,SAAgB,qBAAqB,QAA0D;CAC7F,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,UAAU,KAAK,OAAO;CAC1B,OAAO;AACT;;;AC4DA,IAAM,kBAA+C;CACnD,wBAAwB;CACxB,kBAAkB;CAClB,4BAA4B;CAC5B,sBAAsB;CACtB,yBAAyB;CACzB,WAAW;CACX,aAAa;CACb,uBAAuB;AACzB;;AAGA,SAAgB,SAAS,OAAkD;CACzE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAMA,SAAS,WAAW,SAAiB,QAA6B;CAChE,OACE,gBAAgB,aAAa,WAAW,MAAM,kBAAkB,qBAAqB,MAAM;AAE/F;;;;;;;;;;;;;;;AAgBA,SAAgB,sBAAsB,MAAe,QAA+B;CAClF,MAAM,QAAQ,SAAS,IAAI,KAA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AI,WAAW,CAAC,QAAQ;CACnD;CACA,IACE,SAAS,KAAK,KACd,EAAE,iBAAiB,UACnB,MAAM,SAAS,kBACf,OAAO,MAAM,YAAY,YACzB,MAAM,YAAY,IAElB,OAAO,CAAC,MAAM,OAAO;CAEvB,OAAO,CAAC,QAAQ;AAClB;;;;;AAMA,SAAgB,mBAAmB,OAAgB,MAAwB;CACzE,MAAM,QAAQ,iBAAiB,KAAK;CACpC,IAAI,CAAC,kBAAkB,KAAK,GAAG,OAAO,CAAC;CACvC,MAAM,WAAW,MAAM,WAAW;CAClC,OAAO,MAAM,QAAQ,QAAQ,IAAI,CAAC,GAAG,QAAQ,IAAI,CAAC;AACpD"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { H as realtime } from "./ThemeProvider-gWqXjGh-.js";
|
|
2
|
+
import { t as channelKey } from "./channelKey-CIhHpX6x.js";
|
|
2
3
|
//#region services/broadcast/protocol.ts
|
|
3
4
|
/**
|
|
4
5
|
* The `gemi.v1` WebSocket protocol, shared by the server transport
|
|
@@ -539,7 +540,14 @@ function reportListenerError(error) {
|
|
|
539
540
|
throw error;
|
|
540
541
|
});
|
|
541
542
|
}
|
|
543
|
+
/**
|
|
544
|
+
* The tab's client, created on first use with the options `configureRealtime`
|
|
545
|
+
* set. `loadRealtimeClient` in `./loader` calls it once this module is loaded.
|
|
546
|
+
*/
|
|
547
|
+
function tabClient() {
|
|
548
|
+
return realtime.client ??= new RealtimeClient(realtime.options);
|
|
549
|
+
}
|
|
542
550
|
//#endregion
|
|
543
|
-
export { IDLE_CLOSE_MS, MAX_LIMIT_RETRIES, RELEASE_LINGER_MS, RESYNC_COALESCE_MS, RealtimeClient, backoffDelay };
|
|
551
|
+
export { IDLE_CLOSE_MS, MAX_LIMIT_RETRIES, RELEASE_LINGER_MS, RESYNC_COALESCE_MS, RealtimeClient, backoffDelay, tabClient };
|
|
544
552
|
|
|
545
|
-
//# sourceMappingURL=RealtimeClient-
|
|
553
|
+
//# sourceMappingURL=RealtimeClient-DsWbFRC7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RealtimeClient-DsWbFRC7.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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