modelence 0.19.0-email.dev.0 → 0.19.1-ssr.dev.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 (43) hide show
  1. package/dist/bin/modelence.js +2 -2
  2. package/dist/bin/modelence.js.map +1 -1
  3. package/dist/chunk-6CHWWK3O.js +3 -0
  4. package/dist/chunk-6CHWWK3O.js.map +1 -0
  5. package/dist/chunk-L36OLCF3.js +2 -0
  6. package/dist/chunk-L36OLCF3.js.map +1 -0
  7. package/dist/chunk-N7XT2ULQ.js +2 -0
  8. package/dist/chunk-N7XT2ULQ.js.map +1 -0
  9. package/dist/chunk-SI5I2VMN.js +25 -0
  10. package/dist/chunk-SI5I2VMN.js.map +1 -0
  11. package/dist/chunk-TNXGVFSU.js +3 -0
  12. package/dist/chunk-TNXGVFSU.js.map +1 -0
  13. package/dist/chunk-YLLX26A4.js +2 -0
  14. package/dist/chunk-YLLX26A4.js.map +1 -0
  15. package/dist/chunk-YRR32LTF.js +2 -0
  16. package/dist/chunk-YRR32LTF.js.map +1 -0
  17. package/dist/client.d.ts +67 -5
  18. package/dist/client.js +1 -1
  19. package/dist/client.js.map +1 -1
  20. package/dist/collectCss-4YETFI7P.js +2 -0
  21. package/dist/collectCss-4YETFI7P.js.map +1 -0
  22. package/dist/{index-CLpVWWuj.d.ts → index-CgNFVSg6.d.ts} +1 -1
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +1 -1
  25. package/dist/{package-HWYPZMTL.js → package-AGSLW64J.js} +2 -2
  26. package/dist/{package-HWYPZMTL.js.map → package-AGSLW64J.js.map} +1 -1
  27. package/dist/render-CHI3Y7PZ.js +2 -0
  28. package/dist/render-CHI3Y7PZ.js.map +1 -0
  29. package/dist/renderApp-ZDNATNY6.js +2 -0
  30. package/dist/renderApp-ZDNATNY6.js.map +1 -0
  31. package/dist/server-NZQGNLQF.js +2 -0
  32. package/dist/server-NZQGNLQF.js.map +1 -0
  33. package/dist/server.d.ts +8 -18
  34. package/dist/server.js +1 -20
  35. package/dist/server.js.map +1 -1
  36. package/dist/transport-4MGQHPZB.js +2 -0
  37. package/dist/transport-4MGQHPZB.js.map +1 -0
  38. package/dist/{types-CzGfkwti.d.ts → types-BHRPqQrN.d.ts} +6 -6
  39. package/dist/{types-JMIT4IDG.d.ts → types-cQjl1CfF.d.ts} +2 -2
  40. package/dist/types.d.ts +3 -3
  41. package/package.json +3 -1
  42. package/dist/chunk-TRKYSUXZ.js +0 -3
  43. package/dist/chunk-TRKYSUXZ.js.map +0 -1
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",r="0.19.1-ssr.dev.0",c="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",o="dist/global.d.ts",p={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],a={modelence:"./dist/bin/modelence.js"},l={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",bench:"tsx src/bench/index.ts",test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage",postversion:"git push && git push --tags",prepare:"cd ../.. && git config core.hooksPath .husky"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",v={"@tanstack/react-query":"^5.100.7","@types/archiver":"^6.0.3","@types/bcrypt":"^6.0.0","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-node":"^10.9.2",vitest:"^2.1.8","@vitest/coverage-v8":"^2.1.8","vite-tsconfig-paths":"^5.1.4"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^6.0.0",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.15.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={"@tanstack/react-query":">=5.0.0",react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:r,description:c,main:n,types:o,exports:p,files:d,bin:a,scripts:l,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:v,dependencies:x,peerDependencies:j};
2
+ export{s as a,i as b,r as c,c as d,n as e,o as f,p as g,d as h,a as i,l as j,m as k,y as l,u as m,g as n,h as o,v as p,x as q,j as r,b as s};//# sourceMappingURL=chunk-TNXGVFSU.js.map
3
+ //# sourceMappingURL=chunk-TNXGVFSU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,kBAAA,CACXC,CAAAA,C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C1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAwBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAKF","file":"chunk-TNXGVFSU.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.19.1-ssr.dev.0\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"bench\": \"tsx src/bench/index.ts\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"postversion\": \"git push && git push --tags\",\n \"prepare\": \"cd ../.. && git config core.hooksPath .husky\"\n },\n \"lint-staged\": {\n \"src/**/*.{ts,tsx,js,jsx,json,css,md}\": \"prettier --write\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@tanstack/react-query\": \"^5.100.7\",\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^6.0.0\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"husky\": \"^9.1.7\",\n \"lint-staged\": \"^16.2.7\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-node\": \"^10.9.2\",\n \"vitest\": \"^2.1.8\",\n \"@vitest/coverage-v8\": \"^2.1.8\",\n \"vite-tsconfig-paths\": \"^5.1.4\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^6.0.0\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.15.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"@tanstack/react-query\": \">=5.0.0\",\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {c as c$1}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import {create}from'zustand';import {z}from'zod';var b="modelence.session";function R(){return typeof globalThis<"u"&&typeof globalThis.localStorage<"u"}function g(){if(!R())return null;let e=globalThis.localStorage.getItem(b);try{return e?JSON.parse(e):null}catch(n){return console.error("Error parsing session from localStorage",n),null}}function p(e){R()&&globalThis.localStorage.setItem(b,JSON.stringify(e));}var P=null;function J(e){P=e;}function a(){return P}var _=(e,n)=>{console.error(`Error calling method '${n}':`,e);};function D(e){_=e;}function N(e,n){return _(e,n)}var S=class extends Error{constructor(n,t,r){super(n),this.name="MethodError",this.status=t,this.code=r;}},M=async(e,n)=>{let t=a()?.baseUrl??"";return W(`${t}/api/_internal/method/${e}`,n)},h="__modelence_call_method_transport__";function H(){return globalThis[h]??M}function B(e){let n=globalThis[h];return globalThis[h]=e,()=>{globalThis[h]=n;}}async function s(e,n,t){n=n??{},t=t??{};try{return await H()(e,n)}catch(r){throw (t.errorHandler??N)(r,e),r}}async function W(e,n){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:n,authToken:m(),clientInfo:E()})});if(!t.ok){let i=await t.text(),l=t.headers?.get("X-Modelence-Error-Code")??void 0;throw new S(i,t.status,l)}let r=await t.text(),o=r?JSON.parse(r):void 0;if(!o)throw new Error("Invalid response from server");return c$1(o.data,o.typeMap)}var A={},C=null;function Q(e){C=e;}function Z(e){return typeof window>"u"&&C?C(e):A[e]?.value}function w(e){A=e;}var c=create(e=>({user:null,setUser:n=>e({user:n})})),f=false,y=false,j=a$1.seconds(30),O=null,L=z.object({id:z.string(),handle:z.string(),roles:z.array(z.string()),firstName:z.string().optional(),lastName:z.string().optional(),avatarUrl:z.string().optional()});function d(e){if(!e)return null;let n=L.safeParse(e);if(!n.success)return console.error("Session Error: Invalid user payload",n.error),null;let t=n.data;return Object.freeze({...t,firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0,hasRole:r=>t.roles.includes(r),requireRole:r=>{if(!t.roles.includes(r))throw new Error(`Access denied - role '${r}' required`)}})}function le(e){if(f)return;f=true,w(e.configs);let t=g()?.authToken,r=e.session;if(t&&!e.user&&t!==r.authToken){y=true,c.getState().setUser(d(e.user));return}p(e.session),c.getState().setUser(d(e.user));}async function ue(){if(y){y=false;try{let{configs:e,session:n,user:t}=await s("_system.session.init");w(e),p(n),c.getState().setUser(d(t));}catch(e){console.error("Modelence: session reconciliation failed",e);}}}function ce(){return y}async function de(){if(f)return;f=true;let{configs:e,session:n,user:t}=await s("_system.session.init");w(e);let r=a();r?r.setAuthToken(n.authToken):p(n),c.getState().setUser(d(t)),await k();}async function fe(){typeof window>"u"||O!==null||await k();}async function k(){if(!(typeof window>"u")){try{await s("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}O=setTimeout(k,j);}}function T(e){let n=d(e);return c.getState().setUser(n),n}function ge(){return f}var x=null;function pe(e){x=e;}function he(e){return d(e)}function me(){return typeof window>"u"&&x?{user:x()}:{user:c(n=>n.user)}}async function xe(e){let{email:n,password:t,handle:r,firstName:o,lastName:i,avatarUrl:l}=e;await s("_system.user.signupWithPassword",{email:n,password:t,...r!==void 0?{handle:r}:{},...o!==void 0?{firstName:o}:{},...i!==void 0?{lastName:i}:{},...l!==void 0?{avatarUrl:l}:{}});}async function ke(e){let{email:n,password:t}=e,{user:r,session:o}=await s("_system.user.loginWithPassword",{email:n,password:t}),i=a();return i&&i.setAuthToken(o.authToken),T(r)}async function ve(e){let{firstName:n,lastName:t,avatarUrl:r,handle:o}=e,{user:i}=await s("_system.user.updateProfile",{...n!==void 0?{firstName:n}:{},...t!==void 0?{lastName:t}:{},...r!==void 0?{avatarUrl:r}:{},...o!==void 0?{handle:o}:{}});return T(i)}async function Ue(e){let{token:n}=e;await s("_system.user.verifyEmail",{token:n});}async function be(e){let{email:n}=e;await s("_system.user.resendEmailVerification",{email:n});}async function Re(){await s("_system.user.logout");let e=a();e&&e.setAuthToken(null),T(null);}async function Pe(e){let{email:n}=e;await s("_system.user.sendResetPasswordToken",{email:n});}async function _e(e){let{token:n,password:t}=e;await s("_system.user.resetPassword",{token:n,password:t});}async function Ne(e){let{provider:n}=e,t=a(),r=t?.baseUrl??"";if(t?.openUrl){let o=m();if(!o)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let i=await fetch(`${r}/api/_internal/auth/issue-link-nonce`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:o})});if(!i.ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let{nonce:l}=await i.json(),I=`${r}/api/_internal/auth/${n}?mode=link&linkNonce=${encodeURIComponent(l)}`;t.openUrl(I);}else {let o=m();if(o&&!(await fetch(`${r}/api/_internal/auth/set-link-cookie`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:o}),credentials:"include"})).ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");window.location.href=`${r}/api/_internal/auth/${n}?mode=link`;}}async function Ee(e){let{provider:n}=e;await s("_system.user.unlinkOAuthProvider",{provider:n});}function m(){let e=a();return e?e.getAuthToken():g()?.authToken}function E(){let e=a();return e?e.getClientInfo():typeof window>"u"?{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null}:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}export{fe as A,ge as B,pe as C,he as D,me as E,g as a,J as b,a as c,xe as d,ke as e,ve as f,Ue as g,be as h,Re as i,Pe as j,_e as k,Ne as l,Ee as m,m as n,E as o,D as p,S as q,M as r,B as s,s as t,Q as u,Z as v,le as w,ue as x,ce as y,de as z};//# sourceMappingURL=chunk-YLLX26A4.js.map
2
+ //# sourceMappingURL=chunk-YLLX26A4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/localStorage.ts","../src/client/clientConfig.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/auth/client/index.ts"],"names":["SESSION_KEY","hasLocalStorage","getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","config","configureClient","userConfig","getClientConfig","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","code","defaultCallMethodTransport","args","baseUrl","call","TRANSPORT_KEY","getTransport","setCallMethodTransport","next","previous","callMethod","options","endpoint","response","getAuthToken","getClientInfo","text","result","reviveResponseTypes","ssrConfigResolver","_setSsrConfigResolver","resolver","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","pendingReconciliation","SESSION_HEARTBEAT_INTERVAL","time","heartbeatTimer","userSchema","z","parseUser","parsedData","role","hydrateSession","payload","existingToken","ssrSession","reconcileSession","_isReconciliationPending","initSession","loopSessionHeartbeat","startSessionHeartbeat","setCurrentUser","enrichedUser","isSessionInitialized","ssrSessionResolver","_setSsrSessionResolver","_parseSessionUser","useSession","state","signupWithPassword","email","password","handle","firstName","lastName","avatarUrl","loginWithPassword","updateProfile","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","resetPassword","linkOAuthProvider","provider","nonceResponse","nonce","url","unlinkOAuthProvider"],"mappings":"uIAAA,IAAMA,EAAc,mBAAA,CAEpB,SAASC,CAAAA,EAA2B,CAClC,OAAO,OAAO,UAAA,CAAe,GAAA,EAAe,OAAO,WAAW,YAAA,CAAiB,GACjF,CAEO,SAASC,GAAyB,CACvC,GAAI,CAACD,CAAAA,GACH,OAAO,IAAA,CAG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BAAA,EAAuBsE,CAAQ,aAClE,CACF,CAUA,eAAsBI,EAAAA,CAAoBlE,EAAqD,CAC7F,GAAM,CAAE,QAAA,CAAA8D,CAAS,CAAA,CAAI9D,CAAAA,CACrB,MAAMD,CAAAA,CAAW,mCAAoC,CAAE,QAAA,CAAA+D,CAAS,CAAC,EACnE,CAMO,SAAS3D,CAAAA,EAAmC,CACjD,IAAM3B,CAAAA,CAASG,CAAAA,EAAgB,CAC/B,OAAIH,EACKA,CAAAA,CAAO,YAAA,EAAa,CAEtBL,CAAAA,IAA0B,SACnC,CAEO,SAASiC,CAAAA,EAA4B,CAC1C,IAAM5B,CAAAA,CAASG,CAAAA,EAAgB,CAC/B,OAAIH,CAAAA,CACKA,CAAAA,CAAO,aAAA,EAAc,CAG1B,OAAO,MAAA,CAAW,GAAA,CACb,CACL,WAAA,CAAa,EACb,YAAA,CAAc,CAAA,CACd,WAAA,CAAa,CAAA,CACb,aAAc,CAAA,CACd,UAAA,CAAY,CAAA,CACZ,WAAA,CAAa,IACf,CAAA,CAGK,CACL,WAAA,CAAa,MAAA,CAAO,OAAO,KAAA,CAC3B,YAAA,CAAc,MAAA,CAAO,MAAA,CAAO,OAC5B,WAAA,CAAa,MAAA,CAAO,UAAA,CACpB,YAAA,CAAc,OAAO,WAAA,CACrB,UAAA,CAAY,MAAA,CAAO,gBAAA,CACnB,YAAa,MAAA,CAAO,MAAA,CAAO,WAAA,EAAa,IAAA,EAAQ,IAClD,CACF","file":"chunk-YLLX26A4.js","sourcesContent":["const SESSION_KEY = 'modelence.session';\n\nfunction hasLocalStorage(): boolean {\n return typeof globalThis !== 'undefined' && typeof globalThis.localStorage !== 'undefined';\n}\n\nexport function getLocalStorageSession() {\n if (!hasLocalStorage()) {\n return null;\n }\n\n const sessionJson = globalThis.localStorage.getItem(SESSION_KEY);\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n if (!hasLocalStorage()) {\n return;\n }\n\n globalThis.localStorage.setItem(SESSION_KEY, JSON.stringify(session));\n}\n","import type { ClientInfo } from '@/methods/types';\n\nexport interface ClientConfig {\n baseUrl: string;\n getAuthToken: () => string | undefined;\n setAuthToken: (token: string | null) => void;\n getClientInfo: () => ClientInfo;\n /**\n * Opens a URL for OAuth redirects. React Native must use\n * `(url) => Linking.openURL(url)` — WebView is not supported.\n * Defaults to `window.location.href` when not provided.\n */\n openUrl?: (url: string) => void;\n}\n\nlet config: ClientConfig | null = null;\n\n/**\n * Configure the Modelence client for non-browser environments like React Native.\n *\n * When configured, the client uses the provided functions for auth-token\n * storage, client-info collection, and URL resolution instead of the\n * default browser APIs (localStorage, window.screen, relative URLs).\n *\n * @example\n * ```ts\n * import { configureClient } from 'modelence/client';\n * import { Linking } from 'react-native';\n *\n * let authToken: string | undefined;\n *\n * configureClient({\n * baseUrl: 'https://myapp.com',\n * getAuthToken: () => authToken,\n * setAuthToken: (token) => { authToken = token ?? undefined; },\n * getClientInfo: () => ({\n * screenWidth: Dimensions.get('screen').width,\n * screenHeight: Dimensions.get('screen').height,\n * windowWidth: Dimensions.get('window').width,\n * windowHeight: Dimensions.get('window').height,\n * pixelRatio: PixelRatio.get(),\n * orientation: null,\n * }),\n * openUrl: (url) => Linking.openURL(url),\n * });\n * ```\n */\nexport function configureClient(userConfig: ClientConfig) {\n config = userConfig;\n}\n\nexport function getClientConfig(): ClientConfig | null {\n return config;\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n /**\n * Machine-readable error code set by the server (when available), so callers\n * can branch on the error kind without matching the human-readable message.\n * For example, a login attempt with an unverified email yields\n * `code === 'EMAIL_NOT_VERIFIED'`.\n */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n this.code = code;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\n// Default: fetch HTTP. SSR swaps in an in-process transport via globalThis\n// so Vite's ssrLoadModule (separate module graph) shares the same instance.\nexport type CallMethodTransport = <T = unknown>(methodName: string, args: MethodArgs) => Promise<T>;\n\n/**\n * The default HTTP transport. Exported so alternative transports (e.g. the SSR\n * in-process transport) can delegate to it when they don't apply.\n * @internal\n */\nexport const defaultCallMethodTransport: CallMethodTransport = async <T>(\n methodName: string,\n args: MethodArgs\n) => {\n const baseUrl = getClientConfig()?.baseUrl ?? '';\n return call<T>(`${baseUrl}/api/_internal/method/${methodName}`, args);\n};\n\nconst TRANSPORT_KEY = '__modelence_call_method_transport__';\n\ntype GlobalWithTransport = typeof globalThis & {\n [TRANSPORT_KEY]?: CallMethodTransport;\n};\n\nfunction getTransport(): CallMethodTransport {\n return (globalThis as GlobalWithTransport)[TRANSPORT_KEY] ?? defaultCallMethodTransport;\n}\n\n/** Returns a disposer that restores the previous transport. */\nexport function setCallMethodTransport(next: CallMethodTransport): () => void {\n const previous = (globalThis as GlobalWithTransport)[TRANSPORT_KEY];\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = next;\n return () => {\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = previous;\n };\n}\n\n/**\n * Calls a server-side method (query or mutation) defined on a Modelence module.\n *\n * Both `args` and `options` are optional. Use the type parameter `T` to type the return value.\n *\n * @example\n * ```typescript\n * import { callMethod } from 'modelence/client';\n *\n * // No arguments\n * const todos = await callMethod<Todo[]>('todo.getAll');\n *\n * // With arguments\n * const todo = await callMethod<Todo>('todo.getOne', { id: '123' });\n *\n * // With a custom error handler\n * const created = await callMethod<Todo>(\n * 'todo.create',\n * { title: 'Buy groceries' },\n * { errorHandler: (error, methodName) => console.error(methodName, error) }\n * );\n * ```\n *\n * @param methodName - Fully qualified method name, e.g. `'todo.getAll'`.\n * @param args - Arguments passed to the server-side method. Defaults to `{}`.\n * @param options - Call-site options such as a custom {@link CallMethodOptions.errorHandler}. Defaults to `{}`.\n * @returns A promise that resolves to the method's return value.\n */\nexport async function callMethod<T = unknown>(\n methodName: string,\n args?: MethodArgs,\n options?: CallMethodOptions\n): Promise<T> {\n args = args ?? {};\n options = options ?? {};\n try {\n return await getTransport()<T>(methodName, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n const code = response.headers?.get('X-Modelence-Error-Code') ?? undefined;\n throw new MethodError(error, response.status, code);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\ntype SsrConfigResolver = (key: ConfigKey) => string | number | boolean | undefined;\nlet ssrConfigResolver: SsrConfigResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrConfigResolver(resolver: SsrConfigResolver | null) {\n ssrConfigResolver = resolver;\n}\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n if (typeof window === 'undefined' && ssrConfigResolver) {\n return ssrConfigResolver(key);\n }\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { getLocalStorageSession, setLocalStorageSession } from './localStorage';\nimport { getClientConfig } from './clientConfig';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\n// Set when SSR rendered anonymously but localStorage holds a token (no\n// cookie yet). `reconcileSession()` then re-auths via the body and refreshes\n// the cookie for subsequent SSR requests.\nlet pendingReconciliation = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const result = userSchema.safeParse(user);\n\n if (!result.success) {\n console.error('Session Error: Invalid user payload', result.error);\n return null;\n }\n\n const parsedData = result.data;\n\n return Object.freeze({\n ...parsedData,\n firstName: parsedData.firstName ?? undefined,\n lastName: parsedData.lastName ?? undefined,\n avatarUrl: parsedData.avatarUrl ?? undefined,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport type SessionInitPayload = {\n configs: Configs;\n session: object & { authToken: string };\n user: object;\n};\n\n/** Hydrate session state from the SSR payload, skipping the network round-trip. */\nexport function hydrateSession(payload: SessionInitPayload) {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n _setConfig(payload.configs);\n\n // localStorage token + anonymous SSR payload = server couldn't read the\n // token (no cookie yet). Preserve the localStorage token and defer to\n // `reconcileSession()`; overwriting here would log the user out permanently.\n const existingLocalSession = getLocalStorageSession() as { authToken?: string } | null;\n const existingToken = existingLocalSession?.authToken;\n const ssrSession = payload.session as { authToken?: string };\n\n if (existingToken && !payload.user && existingToken !== ssrSession.authToken) {\n pendingReconciliation = true;\n // First render must match the server (anonymous); reconcile swaps later.\n useSessionStore.getState().setUser(parseUser(payload.user));\n return;\n }\n\n setLocalStorageSession(payload.session);\n useSessionStore.getState().setUser(parseUser(payload.user));\n}\n\n/** Re-auth via the body token when SSR couldn't read it from a cookie. */\nexport async function reconcileSession() {\n if (!pendingReconciliation) {\n return;\n }\n pendingReconciliation = false;\n\n try {\n const { configs, session, user } = await callMethod<SessionInitPayload>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n useSessionStore.getState().setUser(parseUser(user));\n } catch (error) {\n console.error('Modelence: session reconciliation failed', error);\n }\n}\n\n/** @internal */\nexport function _isReconciliationPending(): boolean {\n return pendingReconciliation;\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<SessionInitPayload>('_system.session.init');\n _setConfig(configs);\n\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n } else {\n setLocalStorageSession(session);\n }\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\n/** Idempotent, client-only. Auto-started by `initSession`; call explicitly after `hydrateSession`. */\nexport async function startSessionHeartbeat() {\n if (typeof window === 'undefined' || heartbeatTimer !== null) {\n return;\n }\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function isSessionInitialized() {\n return isInitialized;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\ntype SsrSessionResolver = () => User | null;\nlet ssrSessionResolver: SsrSessionResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrSessionResolver(resolver: SsrSessionResolver | null) {\n ssrSessionResolver = resolver;\n}\n\n/** @internal */\nexport function _parseSessionUser(user: unknown): User | null {\n return parseUser(user);\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n if (typeof window === 'undefined' && ssrSessionResolver) {\n return { user: ssrSessionResolver() };\n }\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport { getLocalStorageSession } from '@/client/localStorage';\nimport { getClientConfig } from '@/client/clientConfig';\nimport type { ClientInfo } from '@/methods/types';\nimport { OAuthProvider } from '../types';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n * @param options.handle - Optional custom handle. If omitted, one is derived from the email.\n * @param options.firstName - Optional first name.\n * @param options.lastName - Optional last name.\n * @param options.avatarUrl - Optional avatar URL.\n */\nexport async function signupWithPassword(options: {\n email: string;\n password: string;\n handle?: string;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n}) {\n const { email, password, handle, firstName, lastName, avatarUrl } = options;\n await callMethod('_system.user.signupWithPassword', {\n email,\n password,\n ...(handle !== undefined ? { handle } : {}),\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithPassword',\n {\n email,\n password,\n }\n );\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n }\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Update the current user's profile.\n *\n * @example\n * ```ts\n * await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });\n * ```\n * @param options.firstName - The first name of the user.\n * @param options.lastName - The last name of the user.\n * @param options.avatarUrl - The avatar URL of the user.\n * @param options.handle - The handle of the user.\n */\nexport async function updateProfile(options: {\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n handle?: string;\n}) {\n const { firstName, lastName, avatarUrl, handle } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.updateProfile', {\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n ...(handle !== undefined ? { handle } : {}),\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(null);\n }\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Reset password.\n * @param options.token - The password reset token.\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n token,\n password,\n });\n}\n\n/**\n * Link an OAuth provider to the currently signed-in user's account.\n * Redirects the browser to the OAuth provider's authorization page.\n * The provider will redirect back and the account will be linked.\n *\n * @example\n * ```ts\n * linkOAuthProvider({ provider: 'google' });\n * ```\n * @param options.provider - The OAuth provider to link ('google' or 'github').\n */\nexport async function linkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n if (config?.openUrl) {\n // React Native: exchange authToken for a single-use nonce via an authenticated\n // request, then put the nonce in the URL. A crafted external link can't work\n // because the nonce is bound to this session and consumed on first use.\n const token = getAuthToken();\n if (!token) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const nonceResponse = await fetch(`${baseUrl}/api/_internal/auth/issue-link-nonce`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n });\n if (!nonceResponse.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const { nonce } = await nonceResponse.json();\n const url = `${baseUrl}/api/_internal/auth/${provider}?mode=link&linkNonce=${encodeURIComponent(nonce)}`;\n config.openUrl(url);\n } else {\n // Browser: set httpOnly cookie via same-origin fetch (keeps token out of redirect params).\n const token = getAuthToken();\n if (token) {\n const response = await fetch(`${baseUrl}/api/_internal/auth/set-link-cookie`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n credentials: 'include',\n });\n if (!response.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n }\n window.location.href = `${baseUrl}/api/_internal/auth/${provider}?mode=link`;\n }\n}\n/**\n * Unlink an OAuth provider from the currently signed-in user's account.\n *\n * @example\n * ```ts\n * await unlinkOAuthProvider({ provider: 'github' });\n * ```\n * @param options.provider - The OAuth provider to unlink ('google' or 'github').\n */\nexport async function unlinkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n await callMethod('_system.user.unlinkOAuthProvider', { provider });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n const config = getClientConfig();\n if (config) {\n return config.getAuthToken();\n }\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n const config = getClientConfig();\n if (config) {\n return config.getClientInfo();\n }\n\n if (typeof window === 'undefined') {\n return {\n screenWidth: 0,\n screenHeight: 0,\n windowWidth: 0,\n windowHeight: 0,\n pixelRatio: 1,\n orientation: null,\n };\n }\n\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {B as B$1,o,n,t,y as y$1,x,z,c as c$1}from'./chunk-YLLX26A4.js';import {c}from'./chunk-5M6FUMUK.js';import {useState,useEffect}from'react';import {jsx}from'react/jsx-runtime';import $ from'socket.io-client';import {hashKey,QueryClient,QueryClientProvider,HydrationBoundary}from'@tanstack/react-query';var K="__MODELENCE_STATE__",I=false;function N(){return typeof document<"u"&&document.getElementById(K)!==null}function de({children:e,loadingElement:n}){let r=typeof window>"u",[t,o]=useState(()=>!r&&!B$1()&&!N());return useEffect(()=>{async function s(){if(!I){if(I=true,B$1()){y$1()&&await x();return}await z(),o(false);}}s();},[]),t?n??jsx("div",{children:"Loading..."}):e}var y=null,v=new Map;function p(){if(!y)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return y}function B(){let e=n(),n$1=o();for(let r of v.values())y?.emit("subscribeLiveQuery",{subscriptionId:r.subscriptionId,method:r.method,args:r.args,authToken:e,clientInfo:n$1});}function F(e){let n$1=c$1()?.baseUrl??"/";y=$(n$1,{transports:["websocket"],auth:{token:n()}}),y.on("connect",()=>{v.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${v.size} live queries`),B());}),e.channels?.forEach(r=>r.init());}function j({category:e,listener:n}){p().on(e,n);}function H({category:e,listener:n}){p().once(e,n);}function Y({category:e,listener:n}){p().off(e,n);}function k({eventName:e,category:n,id:r}){p().emit(e,`${n}:${r}`);}function J({category:e,id:n}){k({eventName:"joinChannel",category:e,id:n});}function G({category:e,id:n}){k({eventName:"leaveChannel",category:e,id:n});}var V=0;function S(e,n$1,r,t){let o$1=`sub-${++V}-${Date.now()}`,s=({subscriptionId:l,data:i,typeMap:f})=>{l===o$1&&r(c(i,f));},a=({subscriptionId:l,error:i})=>{l===o$1&&(console.error(`[Modelence] Live query error for ${e}:`,i),t?.(i));},c$1=p();return c$1.on("liveQueryData",s),c$1.on("liveQueryError",a),v.set(o$1,{subscriptionId:o$1,method:e,args:n$1}),c$1.connected&&c$1.emit("subscribeLiveQuery",{subscriptionId:o$1,method:e,args:n$1,authToken:n(),clientInfo:o()}),()=>{v.delete(o$1),c$1.emit("unsubscribeLiveQuery",{subscriptionId:o$1}),c$1.off("liveQueryData",s),c$1.off("liveQueryError",a);}}var X={init:F,on:j,once:H,off:Y,emit:k,joinChannel:J,leaveChannel:G},A=X;var w=null;function _(e){w=e;}function he(){return w}function L(e){if(w){console.warn("WebSocket already initialized. Skipping initialization.");return}let n=e?.provider||A;_(n);try{n.init({channels:e?.channels});}catch(r){throw _(null),r}}var d=null,g=null,Q=false,u=new Map;function T(e){d!==e&&(d&&Z(),d=e,g=e.getQueryCache().subscribe(n=>{if(n.type==="removed"){let r=hashKey(n.query.queryKey),t=u.get(r);if(t){if(t.resolvers.size>0){let o=new Error("Query was removed from cache");t.resolvers.forEach(s=>s.reject(o)),t.resolvers.clear();}t.unsubscribe(),u.delete(r);}}}));}function Ee(){return d!==null}function Z(){g&&(g(),g=null),u.forEach(e=>e.unsubscribe()),u.clear(),d=null,Q=false;}var W=class{connect(n){T(n);}};function Pe(e,n={}){return {queryKey:[e,n],queryFn:()=>t(e,n)}}function Me(e,n={}){let r=["live",e,n],t=hashKey(r);return {queryKey:r,queryFn:()=>new Promise((o,s)=>{if(typeof window>"u")return;if(!d){let c=new Error("Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().");console.error("[Modelence]",c.message),s(c);return}Q||(L(),Q=true);let a=u.get(t);a||(a={unsubscribe:S(e,n,l=>{let i=u.get(t);i?.resolvers.size&&(i.resolvers.forEach(f=>f.resolve(l)),i.resolvers.clear()),d&&d.setQueryData(r,l);},l=>{let i=u.get(t);i&&(i.resolvers.size&&(i.resolvers.forEach(f=>f.reject(new Error(l))),i.resolvers.clear()),i.unsubscribe(),u.delete(t));}),resolvers:new Set},u.set(t,a)),a.resolvers.add({resolve:o,reject:s});}),staleTime:1/0,refetchOnWindowFocus:false,refetchOnMount:false,refetchOnReconnect:false,gcTime:0}}function Re(e,n={}){return {mutationFn:(r={})=>t(e,{...n,...r})}}function xe(e,n={}){return [e,n]}var oe="__MODELENCE_QUERY_STATE__";function ie(){if(typeof document>"u")return;let e=document.getElementById(oe);if(!(!e||!e.textContent))try{return JSON.parse(e.textContent)}catch(n){console.error("Modelence: failed to parse SSR query state",n);return}}function De({children:e,client:n,dehydratedState:r}){let[t]=useState(()=>{let s=n??new QueryClient({defaultOptions:{queries:{staleTime:6e4}}});return typeof window<"u"&&T(s),s}),o=r??ie();return jsx(QueryClientProvider,{client:t,children:jsx(HydrationBoundary,{state:o,children:e})})}export{de as a,S as b,_ as c,he as d,L as e,T as f,Ee as g,Z as h,W as i,Pe as j,Me as k,Re as l,xe as m,De as n};//# sourceMappingURL=chunk-YRR32LTF.js.map
2
+ //# sourceMappingURL=chunk-YRR32LTF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/AppProvider.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/client/query.ts","../src/client/queryProvider.tsx"],"names":["SSR_STATE_SCRIPT_ID","isInitialized","hasServerRenderedMarkup","AppProvider","children","loadingElement","isServer","isLoading","setIsLoading","useState","isSessionInitialized","useEffect","initConfig","_isReconciliationPending","reconcileSession","initSession","jsx","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","getAuthToken","clientInfo","getClientInfo","sub","init","props","baseUrl","getClientConfig","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","args","onData","onError","subscriptionId","handleData","sid","data","typeMap","reviveResponseTypes","handleError","error","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","queryClientRef","cacheUnsubscribe","websocketsStarted","subscriptions","connectModelenceQueryClient","queryClient","disconnectModelenceQueryClient","event","subscriptionKey","hashKey","cancelError","r","hasConnectedQueryClient","ModelenceQueryClient","modelenceQuery","methodName","callMethod","modelenceLiveQuery","queryKey","resolve","reject","currentSub","modelenceMutation","defaultArgs","variables","createQueryKey","SSR_QUERY_STATE_SCRIPT_ID","readDehydratedState","node","e","ModelenceQueryProvider","client","dehydratedState","internalClient","qc","QueryClient","state","QueryClientProvider","HydrationBoundary"],"mappings":"oTAiBA,IAAMA,CAAAA,CAAsB,qBAAA,CAOxBC,CAAAA,CAAgB,KAAA,CAKpB,SAASC,CAAAA,EAAmC,CAC1C,OAAO,OAAO,QAAA,CAAa,GAAA,EAAe,QAAA,CAAS,cAAA,CAAeF,CAAmB,CAAA,GAAM,IAC7F,CAEO,SAASG,EAAAA,CAAY,CAAE,QAAA,CAAAC,CAAAA,CAAU,cAAA,CAAAC,CAAe,CAAA,CAAqB,CAC1E,IAAMC,CAAAA,CAAW,OAAO,MAAA,CAAW,GAAA,CAC7B,CAACC,CAAAA,CAAWC,CAAY,CAAA,CAAIC,QAAAA,CAChC,IAAM,CAACH,CAAAA,EAAY,CAACI,GAAAA,EAAqB,EAAK,CAACR,CAAAA,EACjD,CAAA,CAyBA,OAvBAS,SAAAA,CAAU,IAAM,CACd,eAAeC,CAAAA,EAAa,CAC1B,GAAI,CAAAX,CAAAA,CAMJ,CAAA,GAFAA,CAAAA,CAA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Content":["/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n\n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport {\n _isReconciliationPending,\n initSession,\n isSessionInitialized,\n reconcileSession,\n} from './session';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\n// Presence of the state script signals server-rendered markup in the DOM,\n// even if `hydrateSession` failed to parse it. Hiding under a loading shell\n// here would cause a hydration mismatch and a flash-of-spinner.\nfunction hasServerRenderedMarkup(): boolean {\n return typeof document !== 'undefined' && document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const isServer = typeof window === 'undefined';\n const [isLoading, setIsLoading] = useState(\n () => !isServer && !isSessionInitialized() && !hasServerRenderedMarkup()\n );\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n if (isSessionInitialized()) {\n // SSR couldn't authenticate via cookie; reconcile via body token now.\n if (_isReconciliationPending()) {\n await reconcileSession();\n }\n return;\n }\n\n await initSession();\n setIsLoading(false);\n }\n\n void initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n const baseUrl = getClientConfig()?.baseUrl ?? '/';\n socketClient = io(baseUrl, {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider | null) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n setWebsocketClientProvider(provider);\n try {\n provider.init({\n channels: props?.channels,\n });\n } catch (error) {\n setWebsocketClientProvider(null);\n throw error;\n }\n}\n","'use client';\n\nimport { QueryClient, hashKey } from '@tanstack/react-query';\nimport { callMethod } from './method';\nimport { startWebsockets, subscribeLiveQuery } from '../websocket/client';\n\ntype Args = Record<string, unknown>;\n\ninterface Subscription {\n unsubscribe: () => void;\n resolvers: Set<{\n resolve: (data: unknown) => void;\n reject: (error: Error) => void;\n }>;\n}\n\nlet queryClientRef: QueryClient | null = null;\nlet cacheUnsubscribe: (() => void) | null = null;\nlet websocketsStarted = false;\nconst subscriptions = new Map<string, Subscription>();\n\n/**\n * Connects a `QueryClient` to Modelence's live-query layer. Auto-called by\n * `<ModelenceQueryProvider>`; only call manually if you mount your own\n * `<QueryClientProvider>`.\n *\n * Note: WebSocket setup is deferred until the first `modelenceLiveQuery`\n * call, so apps that only use `modelenceQuery`/`modelenceMutation` never\n * open a socket.\n */\nexport function connectModelenceQueryClient(queryClient: QueryClient) {\n if (queryClientRef === queryClient) {\n return;\n }\n\n if (queryClientRef) {\n disconnectModelenceQueryClient();\n }\n\n queryClientRef = queryClient;\n\n cacheUnsubscribe = queryClient.getQueryCache().subscribe((event) => {\n if (event.type === 'removed') {\n const subscriptionKey = hashKey(event.query.queryKey);\n const sub = subscriptions.get(subscriptionKey);\n if (sub) {\n if (sub.resolvers.size > 0) {\n const cancelError = new Error('Query was removed from cache');\n sub.resolvers.forEach((r) => r.reject(cancelError));\n sub.resolvers.clear();\n }\n sub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n });\n}\n\n/**\n * Whether a `QueryClient` is already connected to the live-query layer.\n * `renderApp` uses this to avoid injecting its own `<ModelenceQueryProvider>`\n * when the app already mounts its own provider and connects it beforehand.\n */\nexport function hasConnectedQueryClient(): boolean {\n return queryClientRef !== null;\n}\n\nexport function disconnectModelenceQueryClient() {\n if (cacheUnsubscribe) {\n cacheUnsubscribe();\n cacheUnsubscribe = null;\n }\n subscriptions.forEach((sub) => sub.unsubscribe());\n subscriptions.clear();\n queryClientRef = null;\n websocketsStarted = false;\n}\n\n/** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */\nexport class ModelenceQueryClient {\n connect(queryClient: QueryClient) {\n connectModelenceQueryClient(queryClient);\n }\n}\n\n/**\n * @example\n * ```tsx\n * const { data } = useQuery(modelenceQuery('todo.getAll'));\n * ```\n */\nexport function modelenceQuery<T = unknown>(methodName: string, args: Args = {}) {\n return {\n queryKey: [methodName, args],\n queryFn: () => callMethod<T>(methodName, args),\n };\n}\n\n/**\n * Live query — data updates in real time as the underlying collection changes.\n * Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or\n * `connectModelenceQueryClient(...)`.\n */\nexport function modelenceLiveQuery<T = unknown>(methodName: string, args: Args = {}) {\n const queryKey = ['live', methodName, args] as const;\n const subscriptionKey = hashKey(queryKey);\n\n return {\n queryKey,\n queryFn: () =>\n new Promise<T>((resolve, reject) => {\n // Live queries are WebSocket subscriptions — no server snapshot. Stay\n // pending on the server so Suspense renders; client re-runs after hydration.\n if (typeof window === 'undefined') {\n return;\n }\n\n if (!queryClientRef) {\n const error = new Error(\n 'Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().'\n );\n console.error('[Modelence]', error.message);\n reject(error);\n return;\n }\n\n if (!websocketsStarted) {\n startWebsockets();\n websocketsStarted = true;\n }\n\n let sub = subscriptions.get(subscriptionKey);\n\n if (!sub) {\n const unsubscribe = subscribeLiveQuery<T>(\n methodName,\n args,\n (data) => {\n const currentSub = subscriptions.get(subscriptionKey);\n\n if (currentSub?.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.resolve(data));\n currentSub.resolvers.clear();\n }\n\n if (queryClientRef) {\n queryClientRef.setQueryData(queryKey, data);\n }\n },\n (error) => {\n const currentSub = subscriptions.get(subscriptionKey);\n if (currentSub) {\n if (currentSub.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.reject(new Error(error)));\n currentSub.resolvers.clear();\n }\n currentSub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n );\n\n sub = { unsubscribe, resolvers: new Set() };\n subscriptions.set(subscriptionKey, sub);\n }\n\n // Shared map stores resolvers across `T` instantiations; erase the union.\n sub.resolvers.add({\n resolve: resolve as (data: unknown) => void,\n reject,\n });\n }),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n refetchOnReconnect: false,\n gcTime: 0,\n };\n}\n\nexport function modelenceMutation<T = unknown>(methodName: string, defaultArgs: Args = {}) {\n return {\n mutationFn: (variables: Args = {}) =>\n callMethod<T>(methodName, { ...defaultArgs, ...variables }),\n };\n}\n\nexport type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];\n\n/** Builds a query key matching `modelenceQuery(...)` for cache operations. */\nexport function createQueryKey<T extends string, U extends Args = Args>(\n methodName: T,\n args: U = {} as U\n): ModelenceQueryKey<T, U> {\n return [methodName, args] as const;\n}\n","'use client';\n\nimport React, { useState, type ReactNode } from 'react';\nimport {\n QueryClient,\n QueryClientProvider,\n HydrationBoundary,\n type DehydratedState,\n} from '@tanstack/react-query';\nimport { connectModelenceQueryClient } from './query';\n\nconst SSR_QUERY_STATE_SCRIPT_ID = '__MODELENCE_QUERY_STATE__';\n\nfunction readDehydratedState(): DehydratedState | undefined {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const node = document.getElementById(SSR_QUERY_STATE_SCRIPT_ID);\n if (!node || !node.textContent) {\n return undefined;\n }\n\n try {\n return JSON.parse(node.textContent) as DehydratedState;\n } catch (e) {\n console.error('Modelence: failed to parse SSR query state', e);\n return undefined;\n }\n}\n\ninterface ModelenceQueryProviderProps {\n children: ReactNode;\n client?: QueryClient;\n dehydratedState?: DehydratedState;\n}\n\nexport function ModelenceQueryProvider({\n children,\n client,\n dehydratedState,\n}: ModelenceQueryProviderProps) {\n const [internalClient] = useState(() => {\n const qc =\n client ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000,\n },\n },\n });\n if (typeof window !== 'undefined') {\n connectModelenceQueryClient(qc);\n }\n return qc;\n });\n\n const state = dehydratedState ?? readDehydratedState();\n\n return (\n <QueryClientProvider client={internalClient}>\n <HydrationBoundary state={state}>{children}</HydrationBoundary>\n </QueryClientProvider>\n );\n}\n"]}
package/dist/client.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { b as ClientInfo, c as ConfigKey, d as ConfigParams, A as AnyMethodShape, V as ValueType, e as ConfigType, O as OAuthProvider, W as WebsocketClientProvider, f as ClientChannel } from './types-CzGfkwti.js';
1
+ import { b as ClientInfo, c as ConfigKey, d as ConfigParams, A as AnyMethodShape, V as ValueType, e as ConfigType, O as OAuthProvider, W as WebsocketClientProvider, f as ClientChannel } from './types-BHRPqQrN.js';
2
2
  import { ObjectId } from 'mongodb';
3
- import React from 'react';
3
+ import React, { ReactNode } from 'react';
4
+ import * as react_jsx_runtime from 'react/jsx-runtime';
5
+ import { QueryClient, DehydratedState } from '@tanstack/react-query';
4
6
  import { F as FileVisibility } from './types-DLDzAym7.js';
5
7
  import 'http';
6
8
  import 'express';
@@ -207,12 +209,72 @@ declare const systemConfig: {
207
209
 
208
210
  type ErrorHandler = (error: Error, methodName: string) => void;
209
211
 
210
- declare function renderApp({ loadingElement, routesElement, favicon, errorHandler, }: {
212
+ type SsrRouter = (props: {
213
+ children: React.ReactNode;
214
+ location?: string;
215
+ }) => React.ReactElement;
216
+ interface RenderAppOptions {
211
217
  loadingElement: React.ReactNode;
212
218
  routesElement: React.ReactNode;
213
219
  favicon?: string;
214
220
  errorHandler?: ErrorHandler;
215
- }): void;
221
+ router?: SsrRouter;
222
+ }
223
+ declare function renderApp(options: RenderAppOptions): void;
224
+
225
+ interface ModelenceQueryProviderProps {
226
+ children: ReactNode;
227
+ client?: QueryClient;
228
+ dehydratedState?: DehydratedState;
229
+ }
230
+ declare function ModelenceQueryProvider({ children, client, dehydratedState, }: ModelenceQueryProviderProps): react_jsx_runtime.JSX.Element;
231
+
232
+ type Args = Record<string, unknown>;
233
+ /**
234
+ * Connects a `QueryClient` to Modelence's live-query layer. Auto-called by
235
+ * `<ModelenceQueryProvider>`; only call manually if you mount your own
236
+ * `<QueryClientProvider>`.
237
+ *
238
+ * Note: WebSocket setup is deferred until the first `modelenceLiveQuery`
239
+ * call, so apps that only use `modelenceQuery`/`modelenceMutation` never
240
+ * open a socket.
241
+ */
242
+ declare function connectModelenceQueryClient(queryClient: QueryClient): void;
243
+ declare function disconnectModelenceQueryClient(): void;
244
+ /** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */
245
+ declare class ModelenceQueryClient {
246
+ connect(queryClient: QueryClient): void;
247
+ }
248
+ /**
249
+ * @example
250
+ * ```tsx
251
+ * const { data } = useQuery(modelenceQuery('todo.getAll'));
252
+ * ```
253
+ */
254
+ declare function modelenceQuery<T = unknown>(methodName: string, args?: Args): {
255
+ queryKey: (string | Args)[];
256
+ queryFn: () => Promise<T>;
257
+ };
258
+ /**
259
+ * Live query — data updates in real time as the underlying collection changes.
260
+ * Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or
261
+ * `connectModelenceQueryClient(...)`.
262
+ */
263
+ declare function modelenceLiveQuery<T = unknown>(methodName: string, args?: Args): {
264
+ queryKey: readonly ["live", string, Args];
265
+ queryFn: () => Promise<T>;
266
+ staleTime: number;
267
+ refetchOnWindowFocus: boolean;
268
+ refetchOnMount: boolean;
269
+ refetchOnReconnect: boolean;
270
+ gcTime: number;
271
+ };
272
+ declare function modelenceMutation<T = unknown>(methodName: string, defaultArgs?: Args): {
273
+ mutationFn: (variables?: Args) => Promise<T>;
274
+ };
275
+ type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];
276
+ /** Builds a query key matching `modelenceQuery(...)` for cache operations. */
277
+ declare function createQueryKey<T extends string, U extends Args = Args>(methodName: T, args?: U): ModelenceQueryKey<T, U>;
216
278
 
217
279
  type User = {
218
280
  id: string;
@@ -428,4 +490,4 @@ declare function getFileUrl(filePath: string): Promise<{
428
490
 
429
491
  declare const AppProvider: any;
430
492
 
431
- export { AppProvider, type CallMethodOptions, ClientChannel, type ClientConfig, type MethodArgs, MethodError, type UserInfo, ValueType, callMethod, configureClient, createClientModule, deleteFile, downloadFile, getConfig, getFileUrl, getLocalStorageSession, getWebsocketClientProvider, linkOAuthProvider, loginWithPassword, logout, renderApp, resendEmailVerification, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, systemConfig, unlinkOAuthProvider, updateProfile, uploadFile, useSession, verifyEmail };
493
+ export { AppProvider, type CallMethodOptions, ClientChannel, type ClientConfig, type MethodArgs, MethodError, ModelenceQueryClient, type ModelenceQueryKey, ModelenceQueryProvider, type UserInfo, ValueType, callMethod, configureClient, connectModelenceQueryClient, createClientModule, createQueryKey, deleteFile, disconnectModelenceQueryClient, downloadFile, getConfig, getFileUrl, getLocalStorageSession, getWebsocketClientProvider, linkOAuthProvider, loginWithPassword, logout, modelenceLiveQuery, modelenceMutation, modelenceQuery, renderApp, resendEmailVerification, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, systemConfig, unlinkOAuthProvider, updateProfile, uploadFile, useSession, verifyEmail };
package/dist/client.js CHANGED
@@ -1,2 +1,2 @@
1
- import {c as c$1}from'./chunk-5M6FUMUK.js';import {a}from'./chunk-DO5TZLF5.js';import B,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx}from'react/jsx-runtime';import we from'react-dom/client';import ke from'socket.io-client';function x(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(t){return console.error("Error parsing session from localStorage",t),null}}function K(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var O=null;function G(e){O=e;}function d(){return O}async function X(e){let{email:t,password:r,handle:n,firstName:o,lastName:s,avatarUrl:a}=e;await i("_system.user.signupWithPassword",{email:t,password:r,...n!==void 0?{handle:n}:{},...o!==void 0?{firstName:o}:{},...s!==void 0?{lastName:s}:{},...a!==void 0?{avatarUrl:a}:{}});}async function Y(e){let{email:t,password:r}=e,{user:n,session:o}=await i("_system.user.loginWithPassword",{email:t,password:r}),s=d();return s&&s.setAuthToken(o.authToken),k(n)}async function Z(e){let{firstName:t,lastName:r,avatarUrl:n,handle:o}=e,{user:s}=await i("_system.user.updateProfile",{...t!==void 0?{firstName:t}:{},...r!==void 0?{lastName:r}:{},...n!==void 0?{avatarUrl:n}:{},...o!==void 0?{handle:o}:{}});return k(s)}async function ee(e){let{token:t}=e;await i("_system.user.verifyEmail",{token:t});}async function te(e){let{email:t}=e;await i("_system.user.resendEmailVerification",{email:t});}async function re(){await i("_system.user.logout");let e=d();e&&e.setAuthToken(null),k(null);}async function ne(e){let{email:t}=e;await i("_system.user.sendResetPasswordToken",{email:t});}async function oe(e){let{token:t,password:r}=e;await i("_system.user.resetPassword",{token:t,password:r});}async function ie(e){let{provider:t}=e,r=d(),n=r?.baseUrl??"";if(r?.openUrl){let o=c();if(!o)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let s=await fetch(`${n}/api/_internal/auth/issue-link-nonce`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:o})});if(!s.ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let{nonce:a}=await s.json(),l=`${n}/api/_internal/auth/${t}?mode=link&linkNonce=${encodeURIComponent(a)}`;r.openUrl(l);}else {let o=c();if(o&&!(await fetch(`${n}/api/_internal/auth/set-link-cookie`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:o}),credentials:"include"})).ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");window.location.href=`${n}/api/_internal/auth/${t}?mode=link`;}}async function se(e){let{provider:t}=e;await i("_system.user.unlinkOAuthProvider",{provider:t});}function c(){let e=d();return e?e.getAuthToken():x()?.authToken}function p(){let e=d();return e?e.getClientInfo():{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}var N=(e,t)=>{console.error(`Error calling method '${t}':`,e);};function F(e){N=e;}function W(e,t){return N(e,t)}var C=class extends Error{constructor(t,r,n){super(t),this.name="MethodError",this.status=r,this.code=n;}};async function i(e,t,r){t=t??{},r=r??{};try{let n=d()?.baseUrl??"";return await ae(`${n}/api/_internal/method/${e}`,t)}catch(n){throw (r.errorHandler??W)(n,e),n}}async function ae(e,t){let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:t,authToken:c(),clientInfo:p()})});if(!r.ok){let s=await r.text(),a=r.headers?.get("X-Modelence-Error-Code")??void 0;throw new C(s,r.status,a)}let n=await r.text(),o=n?JSON.parse(n):void 0;if(!o)throw new Error("Invalid response from server");return c$1(o.data,o.typeMap)}var _={};function P(e){return _[e]?.value}function $(e){_=e;}var b=create(e=>({user:null,setUser:t=>e({user:t})})),q=false,de=a.seconds(30),ue=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string()),firstName:z$1.string().optional(),lastName:z$1.string().optional(),avatarUrl:z$1.string().optional()});function L(e){if(!e)return null;let t=ue.safeParse(e);if(!t.success)return console.error("Session Error: Invalid user payload",t.error),null;let r=t.data;return Object.freeze({...r,firstName:r.firstName??void 0,lastName:r.lastName??void 0,avatarUrl:r.avatarUrl??void 0,hasRole:n=>r.roles.includes(n),requireRole:n=>{if(!r.roles.includes(n))throw new Error(`Access denied - role '${n}' required`)}})}async function H(){if(q)return;q=true;let{configs:e,session:t,user:r}=await i("_system.session.init");$(e);let n=d();n?n.setAuthToken(t.authToken):K(t),b.getState().setUser(L(r)),await z();}async function z(){try{await i("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}setTimeout(z,de);}function k(e){let t=L(e);return b.getState().setUser(t),t}function fe(){return {user:b(t=>t.user)}}var j=false;function S({children:e,loadingElement:t}){let[r,n]=useState(true);return useEffect(()=>{async function o(){j||(j=true,await H(),n(false));}o();},[]),r?t??jsx("div",{children:"Loading..."}):e}function M(e){return {getConfig(t){return P(`${e}.${t}`)},query(t,...r){let n=r[0]??{};return {queryKey:[e,t,n],queryFn:()=>i(`${e}.${t}`,n)}},mutation(t){return {mutationFn:r=>i(`${e}.${t}`,r)}},infiniteQuery(t,r){return {queryKey:[e,t,"infinite",r(void 0)],initialPageParam:void 0,queryFn:({pageParam:n})=>i(`${e}.${t}`,r(n))}}}}var he=M("_system");function ve({loadingElement:e,routesElement:t,favicon:r,errorHandler:n}){if(n&&F(n),window.addEventListener("unload",()=>{}),we.createRoot(document.getElementById("root")).render(jsx(B.StrictMode,{children:jsx(Q,{loadingElement:e,children:t})})),r){let o=document.querySelector("link[rel~='icon']");if(o)o.href=r;else {let s=document.createElement("link");s.rel="icon",s.href=r,document.head.appendChild(s);}}}var m=null,h=new Map;function y(){if(!m)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return m}function Ce(){let e=c(),t=p();for(let r of h.values())m?.emit("subscribeLiveQuery",{subscriptionId:r.subscriptionId,method:r.method,args:r.args,authToken:e,clientInfo:t});}function Te(e){let t=d()?.baseUrl??"/";m=ke(t,{transports:["websocket"],auth:{token:c()}}),m.on("connect",()=>{h.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${h.size} live queries`),Ce());}),e.channels?.forEach(r=>r.init());}function xe({category:e,listener:t}){y().on(e,t);}function Pe({category:e,listener:t}){y().once(e,t);}function be({category:e,listener:t}){y().off(e,t);}function A({eventName:e,category:t,id:r}){y().emit(e,`${t}:${r}`);}function Se({category:e,id:t}){A({eventName:"joinChannel",category:e,id:t});}function Me({category:e,id:t}){A({eventName:"leaveChannel",category:e,id:t});}var Ae=0;function V(e,t,r,n){let o=`sub-${++Ae}-${Date.now()}`,s=({subscriptionId:f,data:g,typeMap:T})=>{f===o&&r(c$1(g,T));},a=({subscriptionId:f,error:g})=>{f===o&&(console.error(`[Modelence] Live query error for ${e}:`,g),n?.(g));},l=y();return l.on("liveQueryData",s),l.on("liveQueryError",a),h.set(o,{subscriptionId:o,method:e,args:t}),l.connected&&l.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:t,authToken:c(),clientInfo:p()}),()=>{h.delete(o),l.emit("unsubscribeLiveQuery",{subscriptionId:o}),l.off("liveQueryData",s),l.off("liveQueryError",a);}}var Ee={init:Te,on:xe,once:Pe,off:be,emit:A,joinChannel:Se,leaveChannel:Me},J=Ee;var R=null;function E(e){R=e;}function w(){return R}function Re(e){if(R){console.warn("WebSocket already initialized. Skipping initialization.");return}let t=e?.provider||J;E(t);try{t.init({channels:e?.channels});}catch(r){throw E(null),r}}var U=class{constructor(t,r){this.category=t,this.onMessage=r;}init(){w()?.on({category:this.category,listener:this.onMessage});}joinChannel(t){w()?.joinChannel({category:this.category,id:t});}leaveChannel(t){w()?.leaveChannel({category:this.category,id:t});}};async function Ue(e,{filePath:t,contentType:r,visibility:n}){let{url:o,fields:s,filePath:a}=await i("_system.files.getUploadUrl",{filePath:t,contentType:r,visibility:n}),l=new FormData;for(let[g,T]of Object.entries(s))l.append(g,T);l.append("file",e);let f=await fetch(o,{method:"POST",body:l});if(!f.ok)throw new Error(`Failed to upload file: HTTP status: ${f.status}`);return {filePath:a}}async function Ie(e){await i("_system.files.deleteFile",{filePath:e});}async function Ke(e){return i("_system.files.downloadFile",{filePath:e})}async function Oe(e){return i("_system.files.getFileUrl",{filePath:e})}var Q="useClient"in B?B.useClient(S):S;export{Q as AppProvider,U as ClientChannel,C as MethodError,i as callMethod,G as configureClient,M as createClientModule,Ie as deleteFile,Ke as downloadFile,P as getConfig,Oe as getFileUrl,x as getLocalStorageSession,w as getWebsocketClientProvider,ie as linkOAuthProvider,Y as loginWithPassword,re as logout,ve as renderApp,te as resendEmailVerification,oe as resetPassword,ne as sendResetPasswordToken,E as setWebsocketClientProvider,X as signupWithPassword,Re as startWebsockets,V as subscribeLiveQuery,he as systemConfig,se as unlinkOAuthProvider,Z as updateProfile,Ue as uploadFile,fe as useSession,ee as verifyEmail};//# sourceMappingURL=client.js.map
1
+ export{j as AppProvider,e as ClientChannel,a as createClientModule,g as deleteFile,h as downloadFile,i as getFileUrl,d as renderApp,b as systemConfig,f as uploadFile}from'./chunk-N7XT2ULQ.js';export{i as ModelenceQueryClient,n as ModelenceQueryProvider,f as connectModelenceQueryClient,m as createQueryKey,h as disconnectModelenceQueryClient,d as getWebsocketClientProvider,k as modelenceLiveQuery,l as modelenceMutation,j as modelenceQuery,c as setWebsocketClientProvider,e as startWebsockets,b as subscribeLiveQuery}from'./chunk-YRR32LTF.js';export{q as MethodError,t as callMethod,b as configureClient,v as getConfig,a as getLocalStorageSession,l as linkOAuthProvider,e as loginWithPassword,i as logout,h as resendEmailVerification,k as resetPassword,j as sendResetPasswordToken,d as signupWithPassword,m as unlinkOAuthProvider,f as updateProfile,E as useSession,g as verifyEmail}from'./chunk-YLLX26A4.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=client.js.map
2
2
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/localStorage.ts","../src/client/clientConfig.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/module.ts","../src/system/client.ts","../src/client/renderApp.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/websocket/clientChannel.ts","../src/files/client.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","config","configureClient","userConfig","getClientConfig","signupWithPassword","options","email","password","handle","firstName","lastName","avatarUrl","callMethod","loginWithPassword","user","setCurrentUser","updateProfile","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","resetPassword","linkOAuthProvider","provider","baseUrl","getAuthToken","nonceResponse","nonce","url","unlinkOAuthProvider","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","code","args","call","endpoint","response","text","result","reviveResponseTypes","getConfig","key","_setConfig","configs","useSessionStore","create","set","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","userSchema","z","parseUser","parsedData","role","initSession","loopSessionHeartbeat","enrichedUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","createClientModule","moduleName","name","rest","getArgs","pageParam","systemConfig","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","clientInfo","sub","init","props","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","onData","onError","subscriptionId","handleData","sid","data","typeMap","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","getWebsocketClientProvider","startWebsockets","ClientChannel","onMessage","uploadFile","file","filePath","contentType","visibility","fields","resolvedFilePath","formData","value","uploadResponse","deleteFile","downloadFile","getFileUrl"],"mappings":"sRAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,OAAA,CAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,IAAA,CAAK,KAAA,CAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,CAAAA,CAAiB,CACtD,YAAA,CAAa,OAAA,CAAQ,mBAAA,CAAqB,IAAA,CAAK,SAAA,CAAUA,CAAO,CAAC,EACnE,CCGA,IAAIC,CAAAA,CAA8B,IAAA,CAgC3B,SAASC,CAAAA,CAAgBC,CAAAA,CAA0B,CACxDF,CAAAA,CAASE,EACX,CAEO,SAASC,CAAAA,EAAuC,CACrD,OAAOH,CACT,CCXA,eAAsBI,CAAAA,CAAmBC,CAAAA,CAOtC,CACD,GAAM,CAAE,KAAA,CAAAC,CAAAA,C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OAAA,CAAQH,CAAM,CAAA,CAC9CE,CAAAA,CAAS,MAAA,CAAOzF,CAAAA,CAAK0F,CAAK,CAAA,CAE5BD,CAAAA,CAAS,MAAA,CAAO,MAAA,CAAQN,CAAI,CAAA,CAE5B,IAAMQ,CAAAA,CAAiB,MAAM,MAAMhH,CAAAA,CAAK,CACtC,MAAA,CAAQ,MAAA,CACR,IAAA,CAAM8G,CACR,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAe,EAAA,CAClB,MAAM,IAAI,MAAM,CAAA,oCAAA,EAAuCA,CAAAA,CAAe,MAAM,CAAA,CAAE,CAAA,CAGhF,OAAO,CAAE,QAAA,CAAUH,CAAiB,CACtC,CAEA,eAAsBI,EAAAA,CAAWR,CAAAA,CAAiC,CAChE,MAAM1H,CAAAA,CAAW,0BAAA,CAA4B,CAAE,QAAA,CAAA0H,CAAS,CAAC,EAC3D,CAEA,eAAsBS,EAAAA,CAAaT,CAAAA,CAAoD,CACrF,OAAO1H,EAAW,4BAAA,CAA8B,CAAE,QAAA,CAAA0H,CAAS,CAAC,CAC9D,CAEA,eAAsBU,EAAAA,CAAWV,CAAAA,CAA4C,CAC3E,OAAO1H,CAAAA,CAAW,0BAAA,CAA4B,CAAE,QAAA,CAAA0H,CAAS,CAAC,CAC5D,CC7CO,IAAMjE,CAAAA,CACX,WAAA,GAAeoB,CAAAA,CAEXA,CAAAA,CAAM,SAAA,CAAUpB,CAAmB,CAAA,CACnCA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","import type { ClientInfo } from '@/methods/types';\n\nexport interface ClientConfig {\n baseUrl: string;\n getAuthToken: () => string | undefined;\n setAuthToken: (token: string | null) => void;\n getClientInfo: () => ClientInfo;\n /**\n * Opens a URL for OAuth redirects. React Native must use\n * `(url) => Linking.openURL(url)` — WebView is not supported.\n * Defaults to `window.location.href` when not provided.\n */\n openUrl?: (url: string) => void;\n}\n\nlet config: ClientConfig | null = null;\n\n/**\n * Configure the Modelence client for non-browser environments like React Native.\n *\n * When configured, the client uses the provided functions for auth-token\n * storage, client-info collection, and URL resolution instead of the\n * default browser APIs (localStorage, window.screen, relative URLs).\n *\n * @example\n * ```ts\n * import { configureClient } from 'modelence/client';\n * import { Linking } from 'react-native';\n *\n * let authToken: string | undefined;\n *\n * configureClient({\n * baseUrl: 'https://myapp.com',\n * getAuthToken: () => authToken,\n * setAuthToken: (token) => { authToken = token ?? undefined; },\n * getClientInfo: () => ({\n * screenWidth: Dimensions.get('screen').width,\n * screenHeight: Dimensions.get('screen').height,\n * windowWidth: Dimensions.get('window').width,\n * windowHeight: Dimensions.get('window').height,\n * pixelRatio: PixelRatio.get(),\n * orientation: null,\n * }),\n * openUrl: (url) => Linking.openURL(url),\n * });\n * ```\n */\nexport function configureClient(userConfig: ClientConfig) {\n config = userConfig;\n}\n\nexport function getClientConfig(): ClientConfig | null {\n return config;\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport { getLocalStorageSession } from '@/client/localStorage';\nimport { getClientConfig } from '@/client/clientConfig';\nimport type { ClientInfo } from '@/methods/types';\nimport { OAuthProvider } from '../types';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n * @param options.handle - Optional custom handle. If omitted, one is derived from the email.\n * @param options.firstName - Optional first name.\n * @param options.lastName - Optional last name.\n * @param options.avatarUrl - Optional avatar URL.\n */\nexport async function signupWithPassword(options: {\n email: string;\n password: string;\n handle?: string;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n}) {\n const { email, password, handle, firstName, lastName, avatarUrl } = options;\n await callMethod('_system.user.signupWithPassword', {\n email,\n password,\n ...(handle !== undefined ? { handle } : {}),\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithPassword',\n {\n email,\n password,\n }\n );\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n }\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Update the current user's profile.\n *\n * @example\n * ```ts\n * await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });\n * ```\n * @param options.firstName - The first name of the user.\n * @param options.lastName - The last name of the user.\n * @param options.avatarUrl - The avatar URL of the user.\n * @param options.handle - The handle of the user.\n */\nexport async function updateProfile(options: {\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n handle?: string;\n}) {\n const { firstName, lastName, avatarUrl, handle } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.updateProfile', {\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n ...(handle !== undefined ? { handle } : {}),\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(null);\n }\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Reset password.\n * @param options.token - The password reset token.\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n token,\n password,\n });\n}\n\n/**\n * Link an OAuth provider to the currently signed-in user's account.\n * Redirects the browser to the OAuth provider's authorization page.\n * The provider will redirect back and the account will be linked.\n *\n * @example\n * ```ts\n * linkOAuthProvider({ provider: 'google' });\n * ```\n * @param options.provider - The OAuth provider to link ('google' or 'github').\n */\nexport async function linkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n if (config?.openUrl) {\n // React Native: exchange authToken for a single-use nonce via an authenticated\n // request, then put the nonce in the URL. A crafted external link can't work\n // because the nonce is bound to this session and consumed on first use.\n const token = getAuthToken();\n if (!token) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const nonceResponse = await fetch(`${baseUrl}/api/_internal/auth/issue-link-nonce`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n });\n if (!nonceResponse.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const { nonce } = await nonceResponse.json();\n const url = `${baseUrl}/api/_internal/auth/${provider}?mode=link&linkNonce=${encodeURIComponent(nonce)}`;\n config.openUrl(url);\n } else {\n // Browser: set httpOnly cookie via same-origin fetch (keeps token out of redirect params).\n const token = getAuthToken();\n if (token) {\n const response = await fetch(`${baseUrl}/api/_internal/auth/set-link-cookie`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n credentials: 'include',\n });\n if (!response.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n }\n window.location.href = `${baseUrl}/api/_internal/auth/${provider}?mode=link`;\n }\n}\n/**\n * Unlink an OAuth provider from the currently signed-in user's account.\n *\n * @example\n * ```ts\n * await unlinkOAuthProvider({ provider: 'github' });\n * ```\n * @param options.provider - The OAuth provider to unlink ('google' or 'github').\n */\nexport async function unlinkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n await callMethod('_system.user.unlinkOAuthProvider', { provider });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n const config = getClientConfig();\n if (config) {\n return config.getAuthToken();\n }\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n const config = getClientConfig();\n if (config) {\n return config.getClientInfo();\n }\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n /**\n * Machine-readable error code set by the server (when available), so callers\n * can branch on the error kind without matching the human-readable message.\n * For example, a login attempt with an unverified email yields\n * `code === 'EMAIL_NOT_VERIFIED'`.\n */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n this.code = code;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\n/**\n * Calls a server-side method (query or mutation) defined on a Modelence module.\n *\n * Both `args` and `options` are optional. Use the type parameter `T` to type the return value.\n *\n * @example\n * ```typescript\n * import { callMethod } from 'modelence/client';\n *\n * // No arguments\n * const todos = await callMethod<Todo[]>('todo.getAll');\n *\n * // With arguments\n * const todo = await callMethod<Todo>('todo.getOne', { id: '123' });\n *\n * // With a custom error handler\n * const created = await callMethod<Todo>(\n * 'todo.create',\n * { title: 'Buy groceries' },\n * { errorHandler: (error, methodName) => console.error(methodName, error) }\n * );\n * ```\n *\n * @param methodName - Fully qualified method name, e.g. `'todo.getAll'`.\n * @param args - Arguments passed to the server-side method. Defaults to `{}`.\n * @param options - Call-site options such as a custom {@link CallMethodOptions.errorHandler}. Defaults to `{}`.\n * @returns A promise that resolves to the method's return value.\n */\nexport async function callMethod<T = unknown>(\n methodName: string,\n args?: MethodArgs,\n options?: CallMethodOptions\n): Promise<T> {\n args = args ?? {};\n options = options ?? {};\n try {\n const baseUrl = getClientConfig()?.baseUrl ?? '';\n return await call<T>(`${baseUrl}/api/_internal/method/${methodName}`, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n const code = response.headers?.get('X-Modelence-Error-Code') ?? undefined;\n throw new MethodError(error, response.status, code);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { getClientConfig } from './clientConfig';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const result = userSchema.safeParse(user);\n\n if (!result.success) {\n console.error('Session Error: Invalid user payload', result.error);\n return null;\n }\n\n const parsedData = result.data;\n\n return Object.freeze({\n ...parsedData,\n firstName: parsedData.firstName ?? undefined,\n lastName: parsedData.lastName ?? undefined,\n avatarUrl: parsedData.avatarUrl ?? undefined,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{\n configs: Configs;\n session: object & { authToken: string };\n user: object;\n }>('_system.session.init');\n _setConfig(configs);\n\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n } else {\n setLocalStorageSession(session);\n }\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n void initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({\n loadingElement,\n routesElement,\n favicon,\n errorHandler,\n}: {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{routesElement}</AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n const baseUrl = getClientConfig()?.baseUrl ?? '/';\n socketClient = io(baseUrl, {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider | null) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n setWebsocketClientProvider(provider);\n try {\n provider.init({\n channels: props?.channels,\n });\n } catch (error) {\n setWebsocketClientProvider(null);\n throw error;\n }\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import { callMethod } from '../client/method';\nimport type { FileVisibility, GetUploadUrlResult } from './types';\n\ntype UploadFileParams = {\n filePath: string;\n contentType: string;\n visibility: FileVisibility;\n};\n\ntype UploadFileResult = {\n filePath: string;\n};\n\nexport async function uploadFile(\n file: File | Blob,\n { filePath, contentType, visibility }: UploadFileParams\n): Promise<UploadFileResult> {\n const {\n url,\n fields,\n filePath: resolvedFilePath,\n } = await callMethod<GetUploadUrlResult>('_system.files.getUploadUrl', {\n filePath,\n contentType,\n visibility,\n });\n\n const formData = new FormData();\n for (const [key, value] of Object.entries(fields)) {\n formData.append(key, value);\n }\n formData.append('file', file);\n\n const uploadResponse = await fetch(url, {\n method: 'POST',\n body: formData,\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload file: HTTP status: ${uploadResponse.status}`);\n }\n\n return { filePath: resolvedFilePath };\n}\n\nexport async function deleteFile(filePath: string): Promise<void> {\n await callMethod('_system.files.deleteFile', { filePath });\n}\n\nexport async function downloadFile(filePath: string): Promise<{ downloadUrl: string }> {\n return callMethod('_system.files.downloadFile', { filePath });\n}\n\nexport async function getFileUrl(filePath: string): Promise<{ url: string }> {\n return callMethod('_system.files.getFileUrl', { filePath });\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\nexport { uploadFile, deleteFile, downloadFile, getFileUrl } from './files/client';\n"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"client.js"}
@@ -0,0 +1,2 @@
1
+ import a from'path';import u from'fs';var l=/\.(css|scss|sass|less|styl|stylus|pcss|postcss)(\?|$)/,p=Object.freeze({hrefs:[],source:"dev"});function y(s,e){let t=s.moduleGraph.getModuleById(d(s,e));if(!t)return p;let i=new Set,o=[],n=new Set,c=r=>{if(!i.has(r)){i.add(r),r.url&&l.test(r.url)&&!n.has(r.url)&&(n.add(r.url),o.push(r.url));for(let f of r.importedModules)c(f);for(let f of r.ssrImportedModules)c(f);}};return c(t),{hrefs:o,source:"dev"}}function d(s,e){let t=s.config.root;return a.join(t,e).replace(/\\/g,"/")}function A(s){let e=a.resolve(process.cwd(),s,".vite","ssr-manifest.json");if(!u.existsSync(e))return {hrefs:[],source:"prod"};let t;try{t=JSON.parse(u.readFileSync(e,"utf-8"));}catch(o){return console.warn("Modelence SSR: failed to parse ssr-manifest.json",o),{hrefs:[],source:"prod"}}let i=new Set;for(let o of Object.values(t))if(Array.isArray(o))for(let n of o)typeof n=="string"&&l.test(n)&&i.add(n);return {hrefs:Array.from(i),source:"prod"}}function v(s){return s.hrefs.length===0?"":s.hrefs.map(e=>`<link rel="stylesheet" href="${S(e)}">`).join("")}function C(s){return s.hrefs.map(e=>`<${e}>; rel=preload; as=style`)}function S(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;")}export{C as buildEarlyHintsLink,y as collectDevCssAssets,A as loadProdCssAssets,v as renderStylesheetLinks};//# sourceMappingURL=collectCss-4YETFI7P.js.map
2
+ //# sourceMappingURL=collectCss-4YETFI7P.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ssr/collectCss.ts"],"names":["CSS_EXTENSION_REGEX","EMPTY_ASSETS","collectDevCssAssets","viteServer","entryVirtualPath","ssrModule","resolveEntryId","seen","hrefs","hrefSet","walk","mod","imported","root","path","loadProdCssAssets","clientBuildDir","manifestPath","fs","manifest","error","assets","asset","renderStylesheetLinks","href","escapeAttribute","buildEarlyHintsLink","value"],"mappings":"sCAIA,IAAMA,CAAAA,CAAsB,uDAAA,CAUtBC,CAAAA,CAA0B,MAAA,CAAO,MAAA,CAAO,CAAE,MAAO,EAAC,CAAG,MAAA,CAAQ,KAAM,CAAC,CAAA,CAInE,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACW,CACX,IAAMC,CAAAA,CAAYF,CAAAA,CAAW,WAAA,CAAY,aAAA,CACvCG,CAAAA,CAAeH,EAAYC,CAAgB,CAC7C,CAAA,CACA,GAAI,CAACC,CAAAA,CACH,OAAOJ,CAAAA,CAGT,IAAMM,CAAAA,CAAO,IAAI,GAAA,CACXC,CAAAA,CAAkB,EAAC,CACnBC,CAAAA,CAAU,IAAI,IAEdC,CAAAA,CAAQC,CAAAA,EAAoB,CAChC,GAAI,CAAAJ,CAAAA,CAAK,GAAA,CAAII,CAAG,EAGhB,CAAAJ,CAAAA,CAAK,GAAA,CAAII,CAAG,CAAA,CAERA,CAAAA,CAAI,GAAA,EAAOX,CAAAA,CAAoB,KAAKW,CAAAA,CAAI,GAAG,CAAA,EAAK,CAACF,CAAAA,CAAQ,GAAA,CAAIE,CAAAA,CAAI,GAAG,IACtEF,CAAAA,CAAQ,GAAA,CAAIE,CAAAA,CAAI,GAAG,CAAA,CACnBH,CAAAA,CAAM,IAAA,CAAKG,CAAAA,CAAI,GAAG,CAAA,CAAA,CAGpB,IAAA,IAAWC,CAAAA,IAAYD,CAAAA,CAAI,eAAA,CACzBD,CAAAA,CAAKE,C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,CAAoB,IAAA,CAAKsB,CAAK,CAAA,EAC7Db,CAAAA,CAAQ,GAAA,CAAIa,CAAK,CAAA,CAKvB,OAAO,CAAE,KAAA,CAAO,KAAA,CAAM,IAAA,CAAKb,CAAO,CAAA,CAAG,OAAQ,MAAO,CACtD,CAEO,SAASc,CAAAA,CAAsBF,CAAAA,CAA2B,CAC/D,OAAIA,EAAO,KAAA,CAAM,MAAA,GAAW,CAAA,CACnB,EAAA,CAEFA,CAAAA,CAAO,KAAA,CACX,GAAA,CAAKG,CAAAA,EAAS,gCAAgCC,CAAAA,CAAgBD,CAAI,CAAC,CAAA,EAAA,CAAI,CAAA,CACvE,IAAA,CAAK,EAAE,CACZ,CAGO,SAASE,CAAAA,CAAoBL,CAAAA,CAA6B,CAC/D,OAAOA,CAAAA,CAAO,KAAA,CAAM,GAAA,CAAKG,GAAS,CAAA,CAAA,EAAIA,CAAI,CAAA,wBAAA,CAA0B,CACtE,CAEA,SAASC,CAAAA,CAAgBE,CAAAA,CAAuB,CAC9C,OAAOA,CAAAA,CAAM,OAAA,CAAQ,IAAA,CAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,CAAM,QAAQ,CAC5D","file":"collectCss-4YETFI7P.js","sourcesContent":["import path from 'path';\nimport fs from 'fs';\nimport type { ViteDevServer, ModuleNode } from 'vite';\n\nconst CSS_EXTENSION_REGEX = /\\.(css|scss|sass|less|styl|stylus|pcss|postcss)(\\?|$)/;\n\nexport type CssAssetSource = 'dev' | 'prod';\n\nexport interface CssAssets {\n /** URLs for `<link rel=\"stylesheet\">`. Dev: Vite transform; prod: built asset. */\n hrefs: string[];\n source: CssAssetSource;\n}\n\nconst EMPTY_ASSETS: CssAssets = Object.freeze({ hrefs: [], source: 'dev' }) as CssAssets;\n\n// Walks the dev module graph from the SSR entry to gather CSS hrefs the\n// browser can fetch directly, killing FOUC in dev.\nexport function collectDevCssAssets(\n viteServer: ViteDevServer,\n entryVirtualPath: string\n): CssAssets {\n const ssrModule = viteServer.moduleGraph.getModuleById(\n resolveEntryId(viteServer, entryVirtualPath)\n );\n if (!ssrModule) {\n return EMPTY_ASSETS;\n }\n\n const seen = new Set<ModuleNode>();\n const hrefs: string[] = [];\n const hrefSet = new Set<string>();\n\n const walk = (mod: ModuleNode) => {\n if (seen.has(mod)) {\n return;\n }\n seen.add(mod);\n\n if (mod.url && CSS_EXTENSION_REGEX.test(mod.url) && !hrefSet.has(mod.url)) {\n hrefSet.add(mod.url);\n hrefs.push(mod.url);\n }\n\n for (const imported of mod.importedModules) {\n walk(imported);\n }\n for (const imported of mod.ssrImportedModules) {\n walk(imported);\n }\n };\n\n walk(ssrModule);\n\n return { hrefs, source: 'dev' };\n}\n\nfunction resolveEntryId(viteServer: ViteDevServer, entryVirtualPath: string): string {\n const root = viteServer.config.root;\n return path.join(root, entryVirtualPath).replace(/\\\\/g, '/');\n}\n\ntype SsrManifest = Record<string, string[]>;\n\n// Flatten all CSS hrefs from the SSR manifest. Per-request filtering would\n// be ideal but we don't have the rendered module list at boot, so emit all.\nexport function loadProdCssAssets(clientBuildDir: string): CssAssets {\n const manifestPath = path.resolve(process.cwd(), clientBuildDir, '.vite', 'ssr-manifest.json');\n\n if (!fs.existsSync(manifestPath)) {\n return { hrefs: [], source: 'prod' };\n }\n\n let manifest: SsrManifest;\n try {\n manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as SsrManifest;\n } catch (error) {\n console.warn('Modelence SSR: failed to parse ssr-manifest.json', error);\n return { hrefs: [], source: 'prod' };\n }\n\n const hrefSet = new Set<string>();\n for (const assets of Object.values(manifest)) {\n if (!Array.isArray(assets)) {\n continue;\n }\n for (const asset of assets) {\n if (typeof asset === 'string' && CSS_EXTENSION_REGEX.test(asset)) {\n hrefSet.add(asset);\n }\n }\n }\n\n return { hrefs: Array.from(hrefSet), source: 'prod' };\n}\n\nexport function renderStylesheetLinks(assets: CssAssets): string {\n if (assets.hrefs.length === 0) {\n return '';\n }\n return assets.hrefs\n .map((href) => `<link rel=\"stylesheet\" href=\"${escapeAttribute(href)}\">`)\n .join('');\n}\n\n// Link header values for 103 Early Hints (preload CSS before render starts).\nexport function buildEarlyHintsLink(assets: CssAssets): string[] {\n return assets.hrefs.map((href) => `<${href}>; rel=preload; as=style`);\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;');\n}\n"]}
@@ -12,7 +12,7 @@ interface AppServerInitOptions {
12
12
  }
13
13
  interface AppServer {
14
14
  init: (options: AppServerInitOptions) => Promise<void>;
15
- handler: (req: Request, res: Response) => void;
15
+ handler: (req: Request, res: Response) => void | Promise<void>;
16
16
  middlewares?: () => ExpressMiddleware[];
17
17
  }
18
18
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { C as ConfigSchema, W as WebsocketClientProvider, a as WebsocketServerProvider } from './types-CzGfkwti.js';
2
- export { M as ModelenceConfig } from './index-CLpVWWuj.js';
1
+ export { C as ConfigSchema, W as WebsocketClientProvider, a as WebsocketServerProvider } from './types-BHRPqQrN.js';
2
+ export { M as ModelenceConfig } from './index-CgNFVSg6.js';
3
3
  import 'http';
4
4
  import 'mongodb';
5
5
  import 'express';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export{b as AuthError,a as ModelenceError,d as RateLimitError,c as ValidationError}from'./chunk-MIRF7FP3.js';export{a as time}from'./chunk-DO5TZLF5.js';import'./chunk-55J6XMHW.js';//# sourceMappingURL=index.js.map
1
+ export{b as AuthError,a as ModelenceError,d as RateLimitError,c as ValidationError}from'./chunk-MIRF7FP3.js';import'./chunk-55J6XMHW.js';export{a as time}from'./chunk-DO5TZLF5.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-TRKYSUXZ.js';//# sourceMappingURL=package-HWYPZMTL.js.map
2
- //# sourceMappingURL=package-HWYPZMTL.js.map
1
+ export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-TNXGVFSU.js';//# sourceMappingURL=package-AGSLW64J.js.map
2
+ //# sourceMappingURL=package-AGSLW64J.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-HWYPZMTL.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-AGSLW64J.js"}
@@ -0,0 +1,2 @@
1
+ import {a,b,c}from'./chunk-L36OLCF3.js';import'./chunk-6CHWWK3O.js';import'./chunk-7LPSX5A6.js';import {a as a$1,n}from'./chunk-YRR32LTF.js';import {C,u,D as D$1}from'./chunk-YLLX26A4.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';import {renderToPipeableStream}from'react-dom/server';import {Writable}from'stream';import {QueryClient,dehydrate}from'@tanstack/react-query';import {jsx}from'react/jsx-runtime';var J=()=>{let r=c();return r?D$1(r.session.user):null},M=r=>{let o=c();if(o)return o.session.configs[r]?.value};function D(){C(J),u(M);}async function X(r){let{callContext:o,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let i=await a("_system.session.init",{},o),n$1=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:n$1,children:O})}),l=null;await new Promise((s,d)=>{b({callContext:o,queryClient:n$1,session:{user:i.user,configs:i.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){l=e,E?.(),s(e);},onShellError(t){d(t);},onError(t){b$1?.(t);}});return e});});let a$2=null,_=s=>new Promise((d,e)=>{if(!l){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(m,c,I){s.write(m,N=>I(N??void 0));},final(m){try{let c=dehydrate(n$1);a$2=JSON.stringify(c);}finally{n$1.clear();}m(),d();}});t.on("error",e),s.on("error",e),l.pipe(t);});return {sessionState:JSON.stringify({session:i}),pipe:_,getQueryState:()=>{if(a$2===null)throw new Error("getQueryState() called before stream finished");return a$2}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-CHI3Y7PZ.js.map
2
+ //# sourceMappingURL=render-CHI3Y7PZ.js.map