modelence 0.21.0-ml.dev.2 → 0.21.0-ml.dev.4

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 (37) hide show
  1. package/dist/chunk-54MUUAZG.js +2 -0
  2. package/dist/chunk-54MUUAZG.js.map +1 -0
  3. package/dist/{chunk-5UXY2NRZ.js → chunk-76I5SXWM.js} +2 -2
  4. package/dist/{chunk-5UXY2NRZ.js.map → chunk-76I5SXWM.js.map} +1 -1
  5. package/dist/chunk-PSOK2GIU.js +37 -0
  6. package/dist/chunk-PSOK2GIU.js.map +1 -0
  7. package/dist/{chunk-GISIHWCC.js → chunk-RVUJ3U27.js} +2 -2
  8. package/dist/{chunk-GISIHWCC.js.map → chunk-RVUJ3U27.js.map} +1 -1
  9. package/dist/{chunk-7DT2YQTG.js → chunk-UESPWVXG.js} +3 -3
  10. package/dist/{chunk-7DT2YQTG.js.map → chunk-UESPWVXG.js.map} +1 -1
  11. package/dist/chunk-UP2DHNXI.js +4 -0
  12. package/dist/chunk-UP2DHNXI.js.map +1 -0
  13. package/dist/{chunk-P2W2XOKE.js → chunk-WN6LHVUX.js} +2 -2
  14. package/dist/{chunk-P2W2XOKE.js.map → chunk-WN6LHVUX.js.map} +1 -1
  15. package/dist/client.d.ts +10 -0
  16. package/dist/client.js +1 -1
  17. package/dist/{package-SYXH7HQF.js → package-FJDWEXEP.js} +2 -2
  18. package/dist/{package-SYXH7HQF.js.map → package-FJDWEXEP.js.map} +1 -1
  19. package/dist/{render-HDPCEI2O.js → render-E7KMOS4P.js} +2 -2
  20. package/dist/{render-HDPCEI2O.js.map → render-E7KMOS4P.js.map} +1 -1
  21. package/dist/renderApp-ZMIJGGAP.js +2 -0
  22. package/dist/{renderApp-Y3OJU4PO.js.map → renderApp-ZMIJGGAP.js.map} +1 -1
  23. package/dist/server-B47F2UA4.js +2 -0
  24. package/dist/{server-WAXWRUOY.js.map → server-B47F2UA4.js.map} +1 -1
  25. package/dist/server.js +1 -1
  26. package/dist/transport-VEYCPFOD.js +2 -0
  27. package/dist/{transport-UBIBRQF5.js.map → transport-VEYCPFOD.js.map} +1 -1
  28. package/package.json +1 -1
  29. package/dist/chunk-3RMUZGFT.js +0 -2
  30. package/dist/chunk-3RMUZGFT.js.map +0 -1
  31. package/dist/chunk-LVB7YU4P.js +0 -3
  32. package/dist/chunk-LVB7YU4P.js.map +0 -1
  33. package/dist/chunk-T4G5RAOK.js +0 -37
  34. package/dist/chunk-T4G5RAOK.js.map +0 -1
  35. package/dist/renderApp-Y3OJU4PO.js +0 -2
  36. package/dist/server-WAXWRUOY.js +0 -2
  37. package/dist/transport-UBIBRQF5.js +0 -2
@@ -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 p(){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 h(e){R()&&globalThis.localStorage.setItem(b,JSON.stringify(e));}var _=null;function D(e){_=e;}function a(){return _}var P=(e,n)=>{console.error(`Error calling method '${n}':`,e);};function K(e){P=e;}function N(e,n){return P(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)},m="__modelence_call_method_transport__";function H(){return globalThis[m]??M}function B(e){let n=globalThis[m];return globalThis[m]=e,()=>{globalThis[m]=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",credentials:a()?.credentials??"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:n,authToken:w(),clientInfo:A()})});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 E={},k=null;function Q(e){k=e;}function Z(e){return typeof window>"u"&&k?k(e):E[e]?.value}function y(e){E=e;}var c=create(e=>({user:null,setUser:n=>e({user:n})})),g=false,T=false,$=a$1.seconds(30),O=null,j=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=j.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(g)return;g=true,y(e.configs);let t=p()?.authToken,r=e.session;if(t&&!e.user&&t!==r.authToken){T=true,c.getState().setUser(d(e.user));return}h(e.session),c.getState().setUser(d(e.user));}async function ue(){if(T){T=false;try{let{configs:e,session:n,user:t}=await s("_system.session.init");y(e),h(n),c.getState().setUser(d(t));}catch(e){console.error("Modelence: session reconciliation failed",e);}}}function ce(){return T}async function de(){if(g)return;g=true;let{configs:e,session:n,user:t}=await s("_system.session.init");y(e);let r=a();r?r.setAuthToken(n.authToken):h(n),c.getState().setUser(d(t)),await x();}async function fe(){typeof window>"u"||O!==null||await x();}async function x(){if(!(typeof window>"u")){try{await s("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}O=setTimeout(x,$);}}function f(e){let n=d(e);return c.getState().setUser(n),n}function ge(){return g}var C=null;function pe(e){C=e;}function he(e){return d(e)}function me(){return typeof window>"u"&&C?{user:C()}:{user:c(n=>n.user)}}async function Ce(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 xe(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),f(r)}async function Ue(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 f(i)}async function ve(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),f(null);}async function _e(e){let{email:n}=e;await s("_system.user.sendResetPasswordToken",{email:n});}async function Pe(e){let{email:n}=e;await s("_system.user.sendMagicLink",{email:n});}async function Ne(){let{user:e,session:n}=await s("_system.user.loginWithMagicLink"),t=a();return t&&t.setAuthToken(n.authToken),f(e)}async function Ae(e){let{email:n,code:t}=e,{user:r,session:o}=await s("_system.user.loginWithOneTimeCode",{email:n,code:t}),i=a();return i&&i.setAuthToken(o.authToken),f(r)}async function Ee(e){let{token:n,password:t}=e;await s("_system.user.resetPassword",{...n?{token:n}:{},password:t});}async function Oe(e){let{provider:n}=e,t=a(),r=t?.baseUrl??"";if(t?.openUrl){let o=w();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=w();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 Ie(e){let{provider:n}=e;await s("_system.user.unlinkOAuthProvider",{provider:n});}function w(){let e=a();return e?e.getAuthToken():p()?.authToken}function A(){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{ue as A,ce as B,de as C,fe as D,ge as E,pe as F,he as G,me as H,p as a,D as b,a as c,Ce as d,xe as e,Ue as f,ve as g,be as h,Re as i,_e as j,Pe as k,Ne as l,Ae as m,Ee as n,Oe as o,Ie as p,w as q,A as r,K as s,S as t,M as u,B as v,s as w,Q as x,Z as y,le as z};//# sourceMappingURL=chunk-54MUUAZG.js.map
2
+ //# sourceMappingURL=chunk-54MUUAZG.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","sendMagicLink","loginWithMagicLink","loginWithOneTimeCode","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,CAAAA,EAAyB,CACvC,GAAI,CAACD,CAAAA,EAAgB,CACnB,OAAO,IAAA,CAGT,IAAME,EAAc,UAAA,CAAW,YAAA,CAAa,QAAQH,CAAW,CAAA,CAC/D,GAAI,CACF,OAAOG,CAAAA,CAAc,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,MAAM,yCAAA,CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,CAAAA,CAAiB,CACjDL,CAAAA,EAAgB,EAIrB,WAAW,YAAA,CAAa,OAAA,CAAQD,EAAa,IAAA,CAAK,SAAA,CAAUM,CAAO,CAAC,EACtE,CCDA,IAAIC,EAA8B,IAAA,CAgC3B,SAASC,EAAgBC,CAAAA,CAA0B,CACxDF,CAAAA,CAASE,EACX,CAEO,SAASC,CAAAA,EAAuC,CACrD,OAAOH,CACT,CC7DA,IAAII,EAA6B,CAACC,CAAAA,CAAOC,CAAAA,GAAe,CACtD,QAAQ,KAAA,CAAM,CAAA,sBAAA,EAAyBA,CAAU,CAAA,EAAA,CAAA,CAAMD,CAAK,EAC9D,CAAA,CAEO,SAASE,CAAAA,CAA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GhE,CAAO,CAAA,oBAAA,EAAuByE,CAAQ,aAClE,CACF,CAUA,eAAsBI,EAAAA,CAAoBrE,CAAAA,CAAqD,CAC7F,GAAM,CAAE,QAAA,CAAAiE,CAAS,CAAA,CAAIjE,CAAAA,CACrB,MAAMD,CAAAA,CAAW,kCAAA,CAAoC,CAAE,QAAA,CAAAkE,CAAS,CAAC,EACnE,CAMO,SAAS9D,CAAAA,EAAmC,CACjD,IAAM3B,CAAAA,CAASG,CAAAA,EAAgB,CAC/B,OAAIH,CAAAA,CACKA,CAAAA,CAAO,cAAa,CAEtBL,CAAAA,IAA0B,SACnC,CAEO,SAASiC,CAAAA,EAA4B,CAC1C,IAAM5B,CAAAA,CAASG,GAAgB,CAC/B,OAAIH,EACKA,CAAAA,CAAO,aAAA,EAAc,CAG1B,OAAO,OAAW,GAAA,CACb,CACL,YAAa,CAAA,CACb,YAAA,CAAc,EACd,WAAA,CAAa,CAAA,CACb,YAAA,CAAc,CAAA,CACd,WAAY,CAAA,CACZ,WAAA,CAAa,IACf,CAAA,CAGK,CACL,YAAa,MAAA,CAAO,MAAA,CAAO,KAAA,CAC3B,YAAA,CAAc,OAAO,MAAA,CAAO,MAAA,CAC5B,YAAa,MAAA,CAAO,UAAA,CACpB,aAAc,MAAA,CAAO,WAAA,CACrB,UAAA,CAAY,MAAA,CAAO,iBACnB,WAAA,CAAa,MAAA,CAAO,OAAO,WAAA,EAAa,IAAA,EAAQ,IAClD,CACF","file":"chunk-54MUUAZG.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 * Credentials mode for method-call requests. Defaults to `'include'`, which\n * browser apps need for the cookie-based flows (password reset, magic link).\n *\n * Clients configured with token-in-body auth (React Native / Expo) never use\n * cookies, so set `'omit'` there — on Expo Web a credentialed cross-origin\n * request is otherwise blocked by any server answering\n * `Access-Control-Allow-Origin: *`, surfacing as \"TypeError: Failed to fetch\".\n */\n credentials?: RequestCredentials;\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 // Send cookies even when the SPA and API are on different origins. The\n // password-reset and magic-link flows rely on httpOnly cookies set by the\n // server landing routes; with the default `same-origin` policy the cookie\n // would be dropped on cross-origin POSTs and those flows would fail.\n // (Cross-origin use also requires the server to emit\n // `Access-Control-Allow-Credentials: true` and a non-wildcard origin.)\n // Token-in-body clients (React Native / Expo) don't use cookies and can\n // override this via `configureClient({ credentials: 'omit' })`.\n credentials: getClientConfig()?.credentials ?? 'include',\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 * Send a magic sign-in link to the given email address.\n *\n * Works for both existing and new users: clicking the emailed link signs the\n * user in, creating the account first if the email is unknown. A generic\n * response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await sendMagicLink({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to send the magic link to.\n */\nexport async function sendMagicLink(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendMagicLink', {\n email,\n });\n}\n\n/**\n * Complete a magic link sign-in.\n *\n * Call this from the page the magic link landing route redirects to. The\n * token is exchanged server-side via an httpOnly cookie, so no arguments are\n * needed. Signs the user in — creating the account first when the email is\n * not registered yet — and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithMagicLink();\n * ```\n */\nexport async function loginWithMagicLink() {\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithMagicLink'\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 * Complete a magic link sign-in by typing the one-time code from the email.\n *\n * Alternative to `loginWithMagicLink()` for contexts where clicking the link\n * can't reach the app — native apps without deep links, or when the email is\n * read on a different device. Signs the user in — creating the account first\n * when the email is not registered yet — and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithOneTimeCode({ email: 'user@example.com', code: '482193' });\n * ```\n * @param options.email - The email the magic link was sent to.\n * @param options.code - The one-time code from the email.\n */\nexport async function loginWithOneTimeCode(options: { email: string; code: string }) {\n const { email, code } = options;\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOneTimeCode',\n { email, code }\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 * Reset password.\n *\n * The token is normally exchanged server-side via an httpOnly cookie, so the\n * client only submits the new password. Pass `token` only for legacy flows\n * that still carry it client-side (deprecated).\n *\n * @param options.token - Reset token (optional; read from the httpOnly cookie when omitted).\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 ? { 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"]}
@@ -1,2 +1,2 @@
1
- import {E,r,q,w as w$1,B as B$1,A as A$1,C,c as c$1}from'./chunk-3RMUZGFT.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&&!E()&&!N());return useEffect(()=>{async function s(){if(!I){if(I=true,E()){B$1()&&await A$1();return}await C(),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=q(),n=r();for(let r of v.values())y?.emit("subscribeLiveQuery",{subscriptionId:r.subscriptionId,method:r.method,args:r.args,authToken:e,clientInfo:n});}function F(e){let n=c$1()?.baseUrl??"/";y=$(n,{transports:["websocket"],auth:{token:q()}}),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,r$1,t){let o=`sub-${++V}-${Date.now()}`,s=({subscriptionId:l,data:i,typeMap:f})=>{l===o&&r$1(c(i,f));},a=({subscriptionId:l,error:i})=>{l===o&&(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,{subscriptionId:o,method:e,args:n}),c$1.connected&&c$1.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:n,authToken:q(),clientInfo:r()}),()=>{v.delete(o),c$1.emit("unsubscribeLiveQuery",{subscriptionId:o}),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:()=>w$1(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={})=>w$1(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-5UXY2NRZ.js.map
2
- //# sourceMappingURL=chunk-5UXY2NRZ.js.map
1
+ import {E,r,q,w as w$1,B as B$1,A as A$1,C,c as c$1}from'./chunk-54MUUAZG.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&&!E()&&!N());return useEffect(()=>{async function s(){if(!I){if(I=true,E()){B$1()&&await A$1();return}await C(),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=q(),n=r();for(let r of v.values())y?.emit("subscribeLiveQuery",{subscriptionId:r.subscriptionId,method:r.method,args:r.args,authToken:e,clientInfo:n});}function F(e){let n=c$1()?.baseUrl??"/";y=$(n,{transports:["websocket"],auth:{token:q()}}),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,r$1,t){let o=`sub-${++V}-${Date.now()}`,s=({subscriptionId:l,data:i,typeMap:f})=>{l===o&&r$1(c(i,f));},a=({subscriptionId:l,error:i})=>{l===o&&(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,{subscriptionId:o,method:e,args:n}),c$1.connected&&c$1.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:n,authToken:q(),clientInfo:r()}),()=>{v.delete(o),c$1.emit("unsubscribeLiveQuery",{subscriptionId:o}),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:()=>w$1(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={})=>w$1(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-76I5SXWM.js.map
2
+ //# sourceMappingURL=chunk-76I5SXWM.js.map
@@ -1 +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":"2TAiBA,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,CAAAA,EAAqB,EAAK,CAACR,CAAAA,EACjD,CAAA,CAyBA,OAvBAS,SAAAA,CAAU,IAAM,CACd,eAAeC,CAAAA,EAAa,CAC1B,GAAI,CAAAX,CAAAA,CAMJ,CAAA,GAFAA,CAAAA,CAAgB,IAAA,CAEZS,CAAAA,EAAqB,CAAG,CAEtBG,GAAAA,EAAyB,EAC3B,MAAMC,GAAAA,EAAiB,CAEzB,MACF,CAEA,MAAMC,CAAAA,EAAY,CAClBP,CAAAA,CAAa,KAAK,EAAA,CACpB,CAEKI,CAAAA,GACP,CAAA,CAAG,EAAE,CAAA,CAEDL,CAAAA,CACKF,CAAAA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IAAMC,CAAAA,CAAO,QAAA,CAAS,cAAA,CAAeF,EAAyB,CAAA,CAC9D,GAAI,EAAA,CAACE,CAAAA,EAAQ,CAACA,CAAAA,CAAK,WAAA,CAAA,CAInB,GAAI,CACF,OAAO,IAAA,CAAK,KAAA,CAAMA,CAAAA,CAAK,WAAW,CACpC,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,CAAQ,KAAA,CAAM,4CAAA,CAA8CA,CAAC,CAAA,CAC7D,MACF,CACF,CAQO,SAASC,EAAAA,CAAuB,CACrC,QAAA,CAAA1F,CAAAA,CACA,MAAA,CAAA2F,CAAAA,CACA,eAAA,CAAAC,CACF,CAAA,CAAgC,CAC9B,GAAM,CAACC,CAAc,CAAA,CAAIxF,QAAAA,CAAS,IAAM,CACtC,IAAMyF,CAAAA,CACJH,CAAAA,EACA,IAAII,WAAAA,CAAY,CACd,cAAA,CAAgB,CACd,OAAA,CAAS,CACP,SAAA,CAAW,GACb,CACF,CACF,CAAC,CAAA,CACH,OAAI,OAAO,MAAA,CAAW,GAAA,EACpB/B,CAAAA,CAA4B8B,CAAE,CAAA,CAEzBA,CACT,CAAC,CAAA,CAEKE,CAAAA,CAAQJ,CAAAA,EAAmBL,EAAAA,EAAoB,CAErD,OACE3E,GAAAA,CAACqF,mBAAAA,CAAA,CAAoB,MAAA,CAAQJ,CAAAA,CAC3B,QAAA,CAAAjF,GAAAA,CAACsF,iBAAAA,CAAA,CAAkB,KAAA,CAAOF,CAAAA,CAAQ,QAAA,CAAAhG,CAAAA,CAAS,CAAA,CAC7C,CAEJ","file":"chunk-5UXY2NRZ.js","sourcesContent":["/*\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"]}
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":"2TAiBA,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,CAAAA,EAA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B,QAAA,CAAAjF,GAAAA,CAACsF,iBAAAA,CAAA,CAAkB,KAAA,CAAOF,CAAAA,CAAQ,QAAA,CAAAhG,CAAAA,CAAS,CAAA,CAC7C,CAEJ","file":"chunk-76I5SXWM.js","sourcesContent":["/*\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"]}
@@ -0,0 +1,37 @@
1
+ import {s as s$1}from'./chunk-UESPWVXG.js';import {a,b,c,o,p,q as q$1,r,s,k as k$1,l,x as x$1,j,i,m,h,n,t,y,z as z$2,A as A$1,B as B$1,d as d$1,C,v as v$1,u,e as e$1,F,D as D$1,E as E$1}from'./chunk-UP2DHNXI.js';import {b as b$1,d,a as a$4}from'./chunk-MIRF7FP3.js';import {a as a$2,f,e,g,c as c$1,h as h$1,l as l$1,k as k$2,d as d$2,j as j$2,m as m$1,i as i$1,n as n$1}from'./chunk-ENHGU3X4.js';import {a as a$3,b as b$2}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import rr from'dotenv';import Rn from'fs/promises';import zr from'os';import Y from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoServerError,MongoClient,MongoError,ObjectId}from'mongodb';export{ObjectId as m}from'mongodb';import Cr from'bcrypt';import $,{z as z$1}from'zod';import {randomBytes,randomInt,createHash,randomUUID}from'crypto';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import mn from'@vitejs/plugin-react';import Oe from'fs';import j$1,{Router}from'express';import ui from'cookie-parser';import mi from'http';var le=new a("_system",{configSchema:{mongodbUri:{type:"secret",isPublic:false,default:""},mongodbPoolSize:{type:"number",isPublic:false,default:10},"env.type":{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""},multiInstance:{type:"boolean",isPublic:false,default:false}}});var N=null;async function Ht(){if(N)return N;let e=V();if(!e)throw new Error("MongoDB URI is not set");let t=le.getConfig("mongodbPoolSize");N=new MongoClient(e,{driverInfo:{name:"Modelence",version:s$1.version},ignoreUndefined:true,maxPoolSize:t});try{return await N.connect(),await N.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),N}catch(o){throw console.error(o),N=null,o}}function V(){return le.getConfig("mongodbUri")||void 0}function be(){return N}var de=null,wr="_modelenceSocketio",Gt=60;async function yr({httpServer:e,channels:t}){let o=be(),r=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let n=null;if(r&&o){n=o.db().collection(wr);try{await n.createIndex({createdAt:1},{expireAfterSeconds:Gt,background:!0});}catch(i){if(i instanceof Error&&"code"in i&&i.code===85)try{await n.dropIndex("createdAt_1"),await n.createIndex({createdAt:1},{expireAfterSeconds:Gt,background:!0});}catch(s){console.error("Failed to recreate index on MongoDB collection for Socket.IO:",s);}else console.error("Failed to create index on MongoDB collection for Socket.IO:",i);}}de=new Server(e,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["websocket"],perMessageDeflate:false}),de.on("error",i=>{console.error("Socket.IO error:",i);}),de.use(async(i,s)=>{let a=i.handshake.auth.token;try{i.data=await v$1(a);}finally{s();}}),de.on("connection",i=>{i.on("disconnect",()=>{F(i);}),i.on("joinChannel",async s=>{let[a]=s.split(":"),c=false;for(let l of t)if(l.category===a){(!l.canAccessChannel||await l.canAccessChannel(i.data))&&(i.join(s),c=true,i.emit("joinedChannel",s));break}c||i.emit("joinError",{channel:s,error:"Access denied"});}),i.on("leaveChannel",s=>{i.leave(s),console.log(`User ${i.id} left channel ${s}`),i.emit("leftChannel",s);}),i.on("subscribeLiveQuery",s=>D$1(i,s)),i.on("unsubscribeLiveQuery",s=>E$1(i,s));}),console.log("Socket.IO server initialized");}function Er({category:e,id:t,data:o}){de?.to(`${e}:${t}`).emit(e,o);}var Ft={init:yr,broadcast:Er};async function ve(e){let t=e.toLowerCase().trim().split("@");if(t.length!==2)return false;let o=t[1];return !!await p.findOne({domain:o})}var Vt={interval:a$1.days(1),async handler(){let e=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let o=(await e.text()).split(`
2
+ `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),r=new Date,n=500;for(let i=0;i<o.length;i+=n){let s=o.slice(i,i+n);try{await p.insertMany(s.map(a=>({domain:a,addedAt:r})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var ke=3,B=50,Bt=8,qt=128,zt=254,Wt=e=>z$1.string().trim().min(e.min??1,{message:`must be at least ${e.min??1} characters`}).max(e.max,{message:`must be at most ${e.max} characters`}),He=e=>z$1.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),br=z$1.object({firstName:He({max:50}),lastName:He({max:50}),avatarUrl:He({max:400}),handle:Wt({min:ke,max:B})}).strict();function Ce(e){let t=br.partial().safeParse(e);if(!t.success){let o=t.error.issues[0],r=o.path.join("."),n=r?`${r}: ${o.message}`:o.message;throw new Error(n)}return t.data}function Se(e){return z$1.string().min(Bt,{message:`Password must contain at least ${Bt} characters`}).max(qt,{message:`Password must be at most ${qt} characters`}).parse(e)}function x(e){return z$1.string().max(zt,{message:`Email must be at most ${zt} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function Jt(e){return Wt({min:ke,max:B}).parse(e)}function Ae(e){return e instanceof MongoServerError&&e.code===11e3&&typeof e.keyPattern=="object"&&e.keyPattern!==null&&"emails.address"in e.keyPattern}function xe(e,t){return t?t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t.startsWith("/")?"":"/"}${t}`:e}function q(e){return {id:e._id,handle:e.handle,roles:e.roles||[],firstName:e.firstName??void 0,lastName:e.lastName??void 0,avatarUrl:e.avatarUrl??void 0}}async function Kt(e){let t=e.slice(0,B);try{if(!await o.findOne({handle:t},{collation:{locale:"en",strength:2}}))return t}catch(n){throw new Error(`Database error while checking handle availability: ${n}`)}let o$1=51;for(let n=2;n<=o$1;n++){let i=`_${n}`,s=`${t.slice(0,B-i.length)}${i}`;try{if(!await o.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}let r=10;for(let n=0;n<r;n++){let i=`_${randomBytes(3).toString("hex")}`,s=`${t.slice(0,B-i.length)}${i}`;try{if(!await o.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}throw new Error(`Could not generate a unique handle for base "${e}" after exhausting all attempts.`)}async function O(e,t,{throwOnConflict:o$1=true}={}){if(e!=null&&String(e).trim()!==""){let n=Jt(String(e).trim());if(o$1){if(await o.findOne({handle:n},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");return n}return Kt(n)}let r=t.split("@")[0].padEnd(ke,"_").slice(0,B);return Kt(r)}var Ge=Object.freeze({});function Fe(e){Ge=Object.freeze(Object.assign({},Ge,e));}function w(){return Ge}var Ve=Object.freeze({});function Yt(e){Ve=Object.freeze(Object.assign({},Ve,e));}function E(){return Ve}function Ar(){return w()?.provider?!!a$2("_system.user.auth.email.verification"):false}async function Xt(e,{user:t,session:o$1,connectionInfo:r,res:n}){try{if(!o$1)throw new Error("Session is not initialized");let i=r?.ip;i&&await k({bucket:"signin",type:"ip",value:i});let s=x(e.email),a=z$1.string().parse(e.password),c=await o.findOne({"emails.address":s,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l$1=c?.authMethods?.password?.hash;if(!l$1)throw Qt();if(!c.emails?.find(f=>f.address.toLowerCase()===s)?.verified&&Ar())throw new b$1("Your email address hasn't been verified yet. Please check your inbox for the verification email.","EMAIL_NOT_VERIFIED");if(!await Cr.compare(a,l$1))throw Qt();return await h(o$1.authToken,c._id),n&&l(n,o$1.authToken),E().onAfterLogin?.({provider:"email",user:c,session:o$1,connectionInfo:r}),E().login?.onSuccess?.(c),{user:q(c),session:{authToken:o$1.authToken}}}catch(i){throw i instanceof Error&&(E().onLoginError?.({provider:"email",error:i,session:o$1,connectionInfo:r}),E().login?.onError?.(i)),i}}async function Zt(e,{session:t,res:o}){if(!t)throw new Error("Session is not initialized");await i(t.authToken),o&&m(o);}function Qt(){return new Error("Incorrect email/password combination")}async function eo(e,{user:t}){if(!t)throw new Error("Not authenticated");let o$1=await o.requireById(t.id);return {handle:o$1.handle,emails:o$1.emails,authMethods:Object.keys(o$1.authMethods||{}),firstName:o$1.firstName??void 0,lastName:o$1.lastName??void 0,avatarUrl:o$1.avatarUrl??void 0}}async function to(e,{user:t}){if(!t)throw new Error("Not authenticated");let o$1=await o.requireById(t.id),r=Ce(e);if(await E().validateProfileUpdate?.(r),"handle"in r&&r.handle!==void 0&&await o.findOne({handle:r.handle,_id:{$ne:o$1._id}},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");if(Object.keys(r).length>0){let n={},i={};for(let[a,c]of Object.entries(r))c===void 0?i[a]="":n[a]=c;let s={};Object.keys(n).length>0&&(s.$set=n),Object.keys(i).length>0&&(s.$unset=i);try{await o.updateOne({_id:o$1._id},s);let a=Object.fromEntries(Object.keys(i).map(c=>[c,void 0]));o$1={...o$1,...n,...a};}catch(a){throw a instanceof Error&&"code"in a&&a.code===11e3?new Error("Handle already taken."):a}}return {user:q(o$1)}}var Be=["google","github"];async function oo({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!Be.includes(e))throw new Error(`Invalid provider. Supported providers are: ${Be.join(", ")}.`);let o$1=await o.requireById(t.id),r=o$1.authMethods??{};if(!r[e])throw new Error(`${e} is not linked to your account.`);if(Object.values(r).filter(Boolean).length<=1)throw new Error("Cannot unlink your only authentication method. Please add another method first.");let s=Object.keys(r).filter(l=>l!==e&&r[l]),a=s.length>0?{$or:s.map(l=>({[`authMethods.${l}`]:{$exists:true}}))}:{};if((await o.updateOne({_id:o$1._id,...a},{$unset:{[`authMethods.${e}`]:""}})).matchedCount===0)throw new Error("Cannot unlink your only authentication method. Please add another method first.")}var me=new b("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user","email"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var qe=[];function ro(e){if(qe.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");qe=e;}async function k(e){let{bucket:t,type:o,value:r,message:n}=e,i=qe.filter(a=>a.bucket===t&&a.type===o),s=n?()=>new d(n):void 0;for(let a of i)await xr(a,r,s);}async function xr(e,t,o){let r=()=>o?o():new d(`Rate limit exceeded for ${e.bucket}`),n=await me.findOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window}),i=Date.now(),s=Math.floor(i/e.window)*e.window,{count:a,modifier:c}=n?Rr(n,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+e.window+e.window)}}};if(a>=e.limit)throw r();await me.upsertOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window},c);}function Rr(e,t,o){let r=t-e.windowMs;if(e.windowStart.getTime()===t){let n=e.windowCount,i=e.prevWindowCount,s=1-(o-t)/e.windowMs;return {count:Math.round(n+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(t),prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}if(e.windowStart.getTime()===r){let n=1-(o-t)/e.windowMs;return {count:Math.round(e.windowCount*n),modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:e.windowCount,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}function no({name:e,email:t,verificationUrl:o}){return `
3
+ <p>Hi${e?` ${e}`:""},</p>
4
+ <p>Please verify your email address ${t} by clicking the link below:</p>
5
+ <p><a href="${o}">${o}</a></p>
6
+ <p>If you did not request this, please ignore this email.</p>
7
+ `}async function Lr(e){let t=await q$1.findOne({token:e,expiresAt:{$gt:new Date}});if(!t)throw new Error("Invalid or expired verification token");if(!await o.findOne({_id:t.userId,status:{$nin:["deleted","disabled"]}}))throw new Error("User not found");let r=t.email;if(!r)throw new Error("Email not found in token");let n=await o.findOneAndUpdate({_id:t.userId,status:{$nin:["deleted","disabled"]},"emails.address":r,"emails.verified":{$ne:true}},{$set:{"emails.$.verified":true}},{returnDocument:"after"});if(!n)throw await o.findOne({_id:t.userId,"emails.address":r})?new Error("Email is already verified"):new Error("Email address not found for this user");return await q$1.deleteOne({_id:t._id}),{userDoc:n,email:r}}async function io(e){let t=a$2("_system.site.url"),o=w().verification?.redirectUrl||w().emailVerifiedRedirectUrl||t||"/";try{let r=z$1.string().parse(e.query.token),{userDoc:n}=await Lr(r);E().onAfterEmailVerification?.({provider:"email",user:n,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}});let{authToken:s}=await k$1(n._id);return l(e.res,s),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=verified`}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return r instanceof Error&&(E().onEmailVerificationError?.({provider:"email",error:r,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}}),console.error("Error verifying email:",r)),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent(n)}`}}}async function We({userId:e,email:t,baseUrl:o}){let r=a$2("_system.site.url")||o;if(w().provider){let n=w().provider,i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a$1.hours(24));await q$1.insertOne({userId:e,email:t,token:i,createdAt:new Date,expiresAt:s});let a=`${r}/api/_internal/auth/verify-email?token=${i}`,l=(w()?.verification?.template||no)({name:"",email:t,verificationUrl:a}),d=x$1(l);await n?.sendEmail({to:t,from:w()?.from||"noreply@modelence.com",subject:w()?.verification?.subject||"Verify your email address",text:d,html:l});}}var ze={success:true,message:"If that email is registered and not yet verified, a verification email has been sent"};async function so(e,{connectionInfo:t}){let o$1=x(e.email),r=await o.findOne({"emails.address":o$1,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!r)return ze;let n=r.emails?.find(i=>i.address.toLowerCase()===o$1);if(!n||n.verified)return ze;if(!w().provider)throw new Error("Email provider is not configured");return await k({bucket:"verification",type:"user",value:r._id.toString(),message:"Please wait at least 60 seconds before requesting another verification email"}),await We({userId:r._id,email:o$1,baseUrl:t?.baseUrl}),ze}async function ao(e,{user:t,session:o$1,connectionInfo:r}){let n=E();try{let i=e,{firstName:s,lastName:a,avatarUrl:c,handle:l}=i,d=x(i.email),p=Se(i.password),f=r?.ip;if(f&&await k({bucket:"signupAttempt",type:"ip",value:f}),!n.allowDisposableEmails&&await ve(d))throw new Error("Please use a permanent email address");let y=await o.findOne({"emails.address":d},{collation:{locale:"en",strength:2}});if(y){let G=y.emails?.find(P=>P.address.toLowerCase()===d);throw y.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${G?.address}`)}await n.onBeforeSignup?.({email:d,firstName:s,lastName:a,handle:l,provider:"email",connectionInfo:r}),f&&await k({bucket:"signup",type:"ip",value:f});let h=Ce({firstName:s,lastName:a,avatarUrl:c,handle:l});await n.validateSignup?.({email:d,password:p,...h});let S;if(h.handle)S=await O(h.handle,d);else if(n.generateHandle){let G=await n.generateHandle({email:d,firstName:h.firstName,lastName:h.lastName});S=await O(G,d,{throwOnConflict:!1});}else S=await O(void 0,d);let ie=await Cr.hash(p,10),Q;try{Q=await o.insertOne({handle:S,status:"active",emails:[{address:d,verified:!1}],createdAt:new Date,authMethods:{password:{hash:ie}},...h.firstName!==void 0&&{firstName:h.firstName},...h.lastName!==void 0&&{lastName:h.lastName},...h.avatarUrl!==void 0&&{avatarUrl:h.avatarUrl}});}catch(G){throw Ae(G)?new Error(`User with email already exists: ${d}`):G}let H=await o.findOne({_id:Q.insertedId},{readPreference:"primary"});if(!H)throw new Error("User not found");return await We({userId:Q?.insertedId,email:d,baseUrl:r?.baseUrl}),n.onAfterSignup?.({provider:"email",user:H,session:o$1,connectionInfo:r}),n.signup?.onSuccess?.(H),Q.insertedId}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:"email",error:i,session:o$1,connectionInfo:r}),n.signup?.onError?.(i)),i}}function D(e){return createHash("sha256").update(e).digest("hex")}var Ke="resetPasswordToken",Ur="/api/_internal/",uo={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:Ur};async function mo(e){return r.findOne({token:D(e)})}async function co(e){return r.findOneAndDelete({_id:e})}function Nr({email:e,resetUrl:t}){return `
8
+ <p>Hi,</p>
9
+ <p>We received a request to reset your password for ${e}.</p>
10
+ <p>Click the link below to reset your password:</p>
11
+ <p><a href="${t}">${t}</a></p>
12
+ <p>This link will expire in 1 hour.</p>
13
+ <p>If you did not request this password reset, please ignore this email.</p>
14
+ `}var Je={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function po(e,{connectionInfo:t}){let o$1=x(e.email),r$1=t?.ip;r$1&&await k({bucket:"passwordReset",type:"ip",value:r$1}),await k({bucket:"passwordReset",type:"email",value:o$1});let n=await o.findOne({"emails.address":o$1,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return Je;let i=w().provider;if(!i)throw new Error("Email provider is not configured");let s=randomBytes(32).toString("hex"),a=Date.now(),c=new Date(a),l=new Date(a+a$1.hours(1));await r.insertOne({userId:n._id,email:o$1,token:D(s),createdAt:c,expiresAt:l});let d=a$2("_system.site.url")||t?.baseUrl;if(!d)throw new Error("Unable to build password reset link: set _system.site.url (MODELENCE_SITE_URL)");let p=`${d}/api/_internal/auth/reset-password?token=${s}`,y=(w()?.passwordReset?.template||Nr)({email:o$1,resetUrl:p,name:""}),h=x$1(y);return await i.sendEmail({to:o$1,from:w()?.from||"noreply@modelence.com",subject:w()?.passwordReset?.subject||"Reset your password",text:h,html:y}),Je}async function fo(e){let t=a$2("_system.site.url")||`${e.req.protocol}://${e.req.get("host")}`,o=xe(t,w().passwordReset?.redirectUrl);try{let r=z$1.string().parse(e.query.token),n=await mo(r);if(!n||n.expiresAt<new Date)throw new Error("This password reset link is invalid or has expired.");return e.res.cookie(Ke,r,{...uo,maxAge:a$1.hours(1)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling password reset landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This password reset link is invalid or has expired.")}`}}}async function go(e,t){let o$1=t.req?.cookies?.[Ke];!o$1&&e.token&&console.warn("[modelence] resetPassword received a token via request args instead of the httpOnly cookie. This path is deprecated and will be removed; ensure password reset emails link to /api/_internal/auth/reset-password so the token is exchanged server-side.");let r=z$1.string().parse(o$1??e.token),n=Se(e.password),i=()=>{t.res?.clearCookie(Ke,uo);},s=await mo(r);if(!s)throw i(),new Error("Invalid or expired reset token");if(s.expiresAt<new Date)throw await co(s._id),i(),new Error("Reset token has expired");let a=await o.findOne({_id:s.userId});if(!a)throw new Error("User not found");let c=await Cr.hash(n,10);if(!await co(s._id))throw i(),new Error("Invalid or expired reset token");return await o.updateOne({_id:a._id},{$set:{"authMethods.password.hash":c}}),s.email&&await o.updateOne({_id:a._id,"emails.address":s.email},{$set:{"emails.$.verified":true}}),await j(a._id),i(),{success:true,message:"Password has been reset successfully"}}function ho({name:e,email:t,magicLinkUrl:o,code:r}){return `
15
+ <p>Hi${e?` ${e}`:""},</p>
16
+ <p>Click the link below to sign in as ${t}:</p>
17
+ <p><a href="${o}">${o}</a></p>
18
+ <p>Or enter this one-time code in the app:</p>
19
+ <p><strong style="font-size: 24px; letter-spacing: 4px;">${r}</strong></p>
20
+ <p>The link and code can only be used once and will expire in 15 minutes.</p>
21
+ <p>If you did not request this, please ignore this email.</p>
22
+ `}var Ye="magicLinkToken",jr="/api/_internal/",Eo={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:jr},bo=15,wo=6,Hr=5;function Xe(){return !!E().magicLink?.enabled}async function vo(e){return s.findOne({token:D(e)})}async function pe(e){return s.findOneAndDelete({_id:e})}var yo={success:true,message:"If this email can be used to sign in, a link has been sent"};async function ko(e,{connectionInfo:t}){if(!Xe())throw new Error("Magic link authentication is not enabled");let o$1=x(e.email),r=t?.ip;r&&await k({bucket:"magicLink",type:"ip",value:r}),await k({bucket:"magicLink",type:"email",value:o$1});let n=w().provider;if(!n)throw new Error("Email provider is not configured");if(!E().allowDisposableEmails&&await ve(o$1))throw new Error("Please use a permanent email address");let i=await o.findOne({"emails.address":o$1},{collation:{locale:"en",strength:2}});if(i&&(i.status==="disabled"||i.status==="deleted"))return yo;let s$1=randomBytes(32).toString("hex"),a=randomInt(0,10**wo).toString().padStart(wo,"0"),c=Date.now(),l=new Date(c),d=new Date(c+a$1.minutes(bo));await s.insertOne({email:o$1,token:D(s$1),code:D(a),attempts:0,createdAt:l,expiresAt:d});let p=a$2("_system.site.url")||t?.baseUrl;if(!p)throw new Error("Unable to build magic link: set _system.site.url (MODELENCE_SITE_URL)");let f=`${p}/api/_internal/auth/magic-link?token=${s$1}`,h=(w()?.magicLink?.template||ho)({email:o$1,magicLinkUrl:f,code:a,name:""}),S=x$1(h);return await n.sendEmail({to:o$1,from:w()?.from||"noreply@modelence.com",subject:w()?.magicLink?.subject||"Your sign-in link",text:S,html:h}),yo}async function Co(e){let t=a$2("_system.site.url")||`${e.req.protocol}://${e.req.get("host")}`,o=xe(t,w().magicLink?.redirectUrl);try{let r=z$1.string().parse(e.query.token),n=await vo(r);if(!n||n.expiresAt<new Date)throw new Error("This sign-in link is invalid or has expired.");return e.res.cookie(Ye,r,{...Eo,maxAge:a$1.minutes(bo)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling magic link landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This sign-in link is invalid or has expired.")}`}}}async function So(e,t){let{tokenDoc:o$1,session:r,connectionInfo:n,res:i,clearCookie:s}=t,a=E(),l$1=!e.emails?.find(d=>d.address.toLowerCase()===o$1.email)?.verified;return await o.updateOne({_id:e._id,"emails.address":o$1.email},{$set:{"emails.$.verified":true}}),await h(r.authToken,e._id),i&&l(i,r.authToken),l$1&&a.onAfterEmailVerification?.({provider:"magicLink",user:e,session:r,connectionInfo:n}),a.onAfterLogin?.({provider:"magicLink",user:e,session:r,connectionInfo:n}),s(),{user:q(e),session:{authToken:r.authToken}}}async function Ao(e,t){let{tokenDoc:o,session:r,connectionInfo:n,clearCookie:i}=t,s=E();try{if(e.status==="disabled"||e.status==="deleted")throw await pe(o._id),i(),new Error("User account is not active");if(!await pe(o._id))throw i(),new Error("Invalid or expired magic link");return await So(e,t)}catch(a){throw a instanceof Error&&s.onLoginError?.({provider:"magicLink",error:a,session:r,connectionInfo:n}),a}}async function xo(e){let{tokenDoc:t,session:o$1,connectionInfo:r,res:n,clearCookie:i}=e,s=t.email,a=E();try{await a.onBeforeSignup?.({email:s,provider:"magicLink",connectionInfo:r});let c=r?.ip;c&&await k({bucket:"signup",type:"ip",value:c});let l$1;if(a.generateHandle){let y=await a.generateHandle({email:s});l$1=await O(y,s,{throwOnConflict:!1});}else l$1=await O(void 0,s);if(!await pe(t._id))throw i(),new Error("Invalid or expired magic link");let p;try{p=await o.insertOne({handle:l$1,status:"active",emails:[{address:s,verified:!0}],createdAt:new Date,authMethods:{}});}catch(y){if(!Ae(y))throw y;let h=await o.findOne({"emails.address":s},{collation:{locale:"en",strength:2},readPreference:"primary"});if(!h)throw new Error("User not found");if(h.status==="disabled"||h.status==="deleted")throw i(),new Error("User account is not active");return await So(h,e)}let f=await o.findOne({_id:p.insertedId},{readPreference:"primary"});if(!f)throw new Error("User not found");return await h(o$1.authToken,f._id),n&&l(n,o$1.authToken),a.onAfterSignup?.({provider:"magicLink",user:f,session:o$1,connectionInfo:r}),i(),{user:q(f),session:{authToken:o$1.authToken}}}catch(c){throw c instanceof Error&&a.onSignupError?.({provider:"magicLink",error:c,session:o$1,connectionInfo:r}),c}}async function Ro(e,t){let{session:o$1,connectionInfo:r,res:n,req:i}=t;if(!o$1)throw new Error("Session is not initialized");if(!Xe())throw new Error("Magic link authentication is not enabled");let s=z$1.string().parse(i?.cookies?.[Ye]),a=()=>{n?.clearCookie(Ye,Eo);},c=await vo(s);if(!c)throw a(),new Error("Invalid or expired magic link");if(c.expiresAt<new Date)throw await pe(c._id),a(),new Error("Magic link has expired");let l=await o.findOne({"emails.address":c.email},{collation:{locale:"en",strength:2}}),d={tokenDoc:{_id:c._id,email:c.email},session:o$1,connectionInfo:r,res:n,clearCookie:a};return l?Ao(l,d):xo(d)}async function Oo(e,t){let{session:o$1,connectionInfo:r,res:n}=t;if(!o$1)throw new Error("Session is not initialized");if(!Xe())throw new Error("Magic link authentication is not enabled");let i=x(e.email),s$1=z$1.string().parse(e.code).replace(/[\s-]/g,""),a=r?.ip;a&&await k({bucket:"oneTimeCode",type:"ip",value:a}),await k({bucket:"oneTimeCode",type:"email",value:i});let c=await s.findOne({email:i,code:D(s$1),attempts:{$lt:Hr}});if(!c)throw await s.updateMany({email:i},{$inc:{attempts:1}}),new Error("Invalid or expired code");if(c.expiresAt<new Date)throw await pe(c._id),new Error("Code has expired");let l=await o.findOne({"emails.address":i},{collation:{locale:"en",strength:2}}),d={tokenDoc:{_id:c._id,email:c.email},session:o$1,connectionInfo:r,res:n,clearCookie:()=>{}};return l?Ao(l,d):xo(d)}function _o(e){return `${e.bucket}
23
+ ${e.type}
24
+ ${e.window}`}function Gr(){return [{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.seconds(60),limit:1},{bucket:"verification",type:"user",window:a$1.days(1),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.days(1),limit:100},{bucket:"passwordReset",type:"email",window:a$1.hours(1),limit:5},{bucket:"passwordReset",type:"email",window:a$1.days(1),limit:10},{bucket:"magicLink",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"magicLink",type:"ip",window:a$1.days(1),limit:100},{bucket:"magicLink",type:"email",window:a$1.hours(1),limit:5},{bucket:"magicLink",type:"email",window:a$1.days(1),limit:10},{bucket:"oneTimeCode",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"oneTimeCode",type:"ip",window:a$1.days(1),limit:100},{bucket:"oneTimeCode",type:"email",window:a$1.hours(1),limit:10},{bucket:"oneTimeCode",type:"email",window:a$1.days(1),limit:20}]}function Fr(e){let t=[],o=["signup","signupAttempt","signin","verification","passwordReset","magicLink","oneTimeCode"];for(let r of o){let n=e[r];if(n!==void 0)for(let i of n)t.push({bucket:r,...i});}return t}function Ze(e={}){let t=Gr(),o=Fr(e),r=new Map;for(let s of o)r.set(_o(s),s);let n=[],i=new Set;for(let s of t){let a=_o(s),c=r.get(a);c!==void 0?(n.push(c),i.add(a)):n.push(s);}for(let[s,a]of r)i.has(s)||n.push(a);return n}var et=new a("_system.user",{stores:[o,p,q$1,r,s],queries:{getOwnProfile:eo},mutations:{signupWithPassword:ao,loginWithPassword:Xt,logout:Zt,resendEmailVerification:so,sendResetPasswordToken:po,resetPassword:go,sendMagicLink:ko,loginWithMagicLink:Ro,loginWithOneTimeCode:Oo,updateProfile:to,unlinkOAuthProvider:oo},cronJobs:{updateDisposableEmailList:Vt},rateLimits:Ze(),configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:true},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:io}},{path:"/api/_internal/auth/reset-password",handlers:{get:fo}},{path:"/api/_internal/auth/magic-link",handlers:{get:Co}}]});var Vr={withoutRemoteServer:{MONGODB_URI:"_system.mongodbUri",MONGODB_POOL_SIZE:"_system.mongodbPoolSize",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV_TYPE:"_system.env.type",MODELENCE_MULTI_INSTANCE:"_system.multiInstance",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"},withRemoteServer:{MODELENCE_SITE_URL:"_system.site.url"}};function Br(e,t){if(t==="number"){let o=Number(e);if(isNaN(o))throw new Error(`Invalid number value for config: ${e}`);return o}if(t==="boolean"){if(e.toLowerCase()==="true")return true;if(e.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${e}`)}return e}function qr(e,t){let o=[];for(let[r,n]of Object.entries(e)){let i=process.env[r],s=t[n];if(i){let a=s?.type??"string";o.push({key:n,type:a,value:Br(i,a)});}}return o}function Re(e,t="withoutRemoteServer"){let o=Vr[t];return qr(o,e)}async function Lo({configSchema:e,cronJobsMetadata:t,stores:o,roles:r}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=(o??[]).map(a=>({name:a.getName(),schema:a.getSerializedSchema(),collections:[a.getName()],version:2,indexes:a.getIndexes(),searchIndexes:a.getSearchIndexes(),indexCreationMode:a.getIndexCreationMode()})),s=await _("/api/connect","POST",{hostname:zr.hostname(),containerId:n,dataModels:i,configSchema:e,cronJobsMetadata:t,roles:r});if(s.status==="error")throw new Error(s.error);return console.log("Successfully connected to Modelence Cloud"),s}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Po(){return _("/api/configs","GET")}async function To(){return await _("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function _(e,t,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${r}${e}`,{method:t,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text(),a,c=s;try{a=JSON.parse(s);let d=a.error;if(typeof d=="string")c=d;else if(d&&typeof d=="object"){let p=d.message;typeof p=="string"&&(c=p);}}catch{}let l=new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${c}`);throw a!==void 0&&(l.responseBody=a),l.status=i.status,l}if(!(i.status===204||i.headers?.get("content-length")==="0"))return await i.json()}var tt=false,Wr=a$1.seconds(10);function Mo(){setInterval(async()=>{if(!tt){tt=true;try{await To();}catch(e){console.error("Error syncing status",e);}try{await Jr();}catch(e){console.error("Error syncing config",e);}tt=false;}},Wr);}function ot(e){c$1(e),c$1(Re(d$2(),"withRemoteServer"));}async function Jr(){let{configs:e}=await Po();ot(e);}var z=new b("_modelenceLocks",{schema:{_id:c.string(),instanceId:c.string(),acquiredAt:c.date(),resource:c.string()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}],indexCreationMode:"blocking"});var W={},Io=a$1.seconds(10),$o=randomBytes(32).toString("base64url"),Qr=a$1.seconds(30),te=new Map,rt=e=>e instanceof MongoError&&e.code===11e3,Uo=(e,t)=>typeof e.keyPattern=="object"&&e.keyPattern!==null&&Object.prototype.hasOwnProperty.call(e.keyPattern,t),Xr=async({error:e,resource:t})=>{if(Uo(e,"resource"))return true;if(Uo(e,"_id"))return false;let o=await z.findOne({resource:t});return !!o&&o._id!==t},No=async({resource:e,staleThresholdDate:t,instanceId:o})=>{let r=await z.upsertOne({_id:e,$or:[{instanceId:o},{acquiredAt:{$lt:t}}]},{$set:{resource:e,instanceId:o,acquiredAt:new Date},$setOnInsert:{_id:e}});return r.upsertedCount>0||r.modifiedCount>0},jo=async({resource:e,instanceId:t,staleThresholdDate:o})=>{let r=o?{resource:e,_id:{$ne:e},$or:[{instanceId:t},{acquiredAt:{$lt:o}}]}:{resource:e,instanceId:t};return (await z.deleteOne(r)).deletedCount>0},Zr=e=>{let t=e,o=te.get(t);o&&(o.stopRequested=true,o.timer&&(clearTimeout(o.timer),o.timer=null),te.delete(t));},Do=({resource:e,lockDuration:t,instanceId:o})=>{let r=Math.floor(t/3),n=e,i=te.get(n);if(i&&!i.stopRequested&&i.heartbeatInterval===r&&i.lockDuration===t)return;i&&(i.stopRequested=true,i.timer&&(clearTimeout(i.timer),i.timer=null),te.delete(n));let s={timer:null,stopRequested:false,lockDuration:t,heartbeatInterval:r},a=()=>{s.timer=setTimeout(()=>{J(e,{lockDuration:t,bypassCache:true,instanceId:o}).then(c=>{c||(s.stopRequested=true,j$2(`Lost lock while refreshing heartbeat: ${e}`,{source:"lock",resource:e,instanceId:o}));}).finally(()=>{if(s.stopRequested){te.delete(n);return}a();});},r);};te.set(n,s),a();};async function J(e,{lockDuration:t=Qr,successfulLockCacheDuration:o=Io,failedLockCacheDuration:r=Io,heartbeat:n,bypassCache:i,instanceId:s=$o}={}){let a=Date.now();if(!i&&W[e]&&a<W[e].expiresAt)return W[e].value&&n&&Do({resource:e,lockDuration:t,instanceId:s}),W[e].value;let c=new Date(a-t);j$2(`Attempting to acquire lock: ${e}`,{source:"lock",resource:e,instanceId:s});try{let l=await en({resource:e,staleThresholdDate:c,instanceId:s});return W[e]={value:l,expiresAt:a+(l?o:r)},l?(n&&Do({resource:e,lockDuration:t,instanceId:s}),j$2(`Lock acquired: ${e}`,{source:"lock",resource:e,instanceId:s})):j$2(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),l}catch{return W[e]={value:false,expiresAt:a+r},j$2(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),false}}var en=async({resource:e,staleThresholdDate:t,instanceId:o})=>{try{return await No({resource:e,staleThresholdDate:t,instanceId:o})}catch(r){if(rt(r)&&await Xr({error:r,resource:e})){if(!await jo({resource:e,staleThresholdDate:t,instanceId:o}))return false;try{return await No({resource:e,staleThresholdDate:t,instanceId:o})}catch(i){if(rt(i))return false;throw i}}if(rt(r))return false;throw r}};async function fe(e,{instanceId:t=$o}={}){Zr(e);try{let o=await z.deleteOne({_id:e,instanceId:t});return o.deletedCount===0?await jo({resource:e,instanceId:t}):o.deletedCount>0}catch{return false}finally{delete W[e];}}var K={},nt=null,it=new b("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Go(e,{description:t="",interval:o,timeout:r=Math.min(Math.max(o,a$1.minutes(1)),a$1.days(1)),handler:n}){if(K[e])throw new Error(`Duplicate cron job declaration: '${e}' already exists`);if(nt)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${e}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${e}]`);if(r>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${e}]`);K[e]={alias:e,params:{description:t,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function Fo(){if(nt)throw new Error("Cron jobs already started");let e=Object.keys(K);if(e.length>0){let t={alias:{$in:e}},o=await it.fetch(t),r=Date.now();o.forEach(n=>{let i=K[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:r);}),Object.values(K).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=r);}),nt=setInterval(tn,a$1.seconds(1));}}async function tn(){let e=Date.now();await J("cron",{successfulLockCacheDuration:a$1.seconds(10),failedLockCacheDuration:a$1.seconds(30)})&&Object.values(K).forEach(async o=>{let{params:r,state:n}=o;if(n.isRunning){n.startTs&&n.startTs+r.timeout<e&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=e&&await on(o);});}async function on(e){let{alias:t,params:o,handler:r,state:n}=e;n.isRunning=true,n.startTs=Date.now(),await it.updateOne({alias:t},{$set:{lastStartDate:new Date(n.startTs)}});let i=m$1("cron",`cron:${t}`);try{await r(),Ho(n,o),i.end("success");}catch(s){Ho(n,o);let a=s instanceof Error?s:new Error(String(s));n$1(a),i.end("error"),console.error(`Error in cron job '${t}':`,s);}}function Ho(e,t){e.scheduledRunTs=e.startTs?e.startTs+t.interval:Date.now(),e.startTs=void 0,e.isRunning=false;}function Vo(){return Object.values(K).map(({alias:e,params:t})=>({alias:e,description:t.description,interval:t.interval,timeout:t.timeout}))}var Bo=new a("_system.cron",{stores:[it]});function qo(e){let t=[...new Set(e)],o=new Map;for(let i of t){let s=i.getChainRoot();o.set(s,s.getChainTail());}let r=[...new Set(o.values())],n=new Map;for(let[i,s]of o){let a=s.getName(),c=n.get(a);if(c!==void 0&&c!==i)throw new Error(`Store collision: multiple unrelated stores use collection name '${a}'. Use .extend() to create a single extension chain instead of independent stores.`);n.set(a,i);}return {storesToInit:t,effectiveStores:r}}var st=new a("_system.lock",{stores:[z]});var ge=new b("_modelenceMigrations",{schema:{version:c.number(),status:c.enum(["completed","failed"]),description:c.string().optional(),output:c.string().optional(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function at(e,{lockMode:t="acquire"}={}){if(e.length!==0){if(t==="acquire"&&!await J("migrations")){k$2("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}try{let o=e.map(({version:s})=>s),r=await ge.fetch({version:{$in:o}}),n=new Set(r.map(({version:s})=>s)),i=e.filter(({version:s})=>!n.has(s));if(i.length===0)return;k$2(`Running migrations (${i.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i){k$2(`Running migration v${s}: ${a}`,{source:"migrations"});try{let d=(await c()||"").toString().trim(),p=15*1024*1024,f=d.length>p?d.slice(0,p)+`
25
+ [Output truncated - exceeded size limit]`:d;await ge.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:f,appliedAt:new Date}}),k$2(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await ge.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),k$2(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}}finally{t==="acquire"&&await fe("migrations");}}}function zo(e){setTimeout(()=>{at(e).catch(t=>{console.error("Error running migrations:",t);});},0);}var Wo=new a("_system.migration",{stores:[ge]});var Jo=new a("_system.rateLimit",{stores:[me]});async function rn({filePath:e,contentType:t,visibility:o}){return await _("/api/files/upload","POST",{filePath:e,contentType:t,visibility:o})}async function nn(e){await _("/api/files/delete","POST",{filePath:e});}async function sn(e){return await _("/api/files/download","POST",{filePath:e})}async function an(e){return await _("/api/files/url","POST",{filePath:e})}var Ko=new a("_system.files",{});function ct(e){return e.replace(/[<>&\u2028\u2029]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}var he="./.modelence/build/client".replace(/\\/g,"/"),Qo="./.modelence/build/ssr".replace(/\\/g,"/"),Xo="/index.tsx",pn=/(<div\b[^>]*\bid\s*=\s*["']root["'][^>]*>)\s*<\/div>/i,fn="</head>",lt=class{constructor(){this.ssrEnabled=false;this.ssrTransportInstalled=false;this.prodEntryLoaded=false;}enableSsr(){this.ssrEnabled=true;}async init({httpServer:t}){if(this.config=await vn(this.isDev()?t:void 0,{ssr:this.ssrEnabled}),this.isDev())console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config);else if(this.ssrEnabled){let o=Y.resolve(process.cwd(),Qo,"index.mjs");if(!Oe.existsSync(o))throw new Error(`Modelence: SSR is enabled (startApp({ ssr: true })) but the SSR bundle is missing at ${o}.
26
+
27
+ This usually means \`postBuildCommand\` is set in modelence.config.ts, which replaces the default Vite client build (and the SSR build along with it). Either:
28
+ \u2022 remove \`postBuildCommand\` so Modelence builds the SSR bundle, or
29
+ \u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:o}=await import('./transport-VEYCPFOD.js');o(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,o=[j$1.static(he,t)];return this.config?.publicDir&&o.push(j$1.static(this.config.publicDir,t)),o}async handler(t,o){if(this.ssrEnabled&&gn(t)){if(t.method==="HEAD"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200).end();return}try{await this.handleSsr(t,o);}catch(r){if(this.isDev()&&this.viteServer&&r instanceof Error&&this.viteServer.ssrFixStacktrace(r),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:r}),o.headersSent){o.end();return}this.serveStaticShell(o);}return}if(this.ssrEnabled){o.status(404).end();return}this.serveStaticShell(o);}async handleSsr(t,o){let r=await this.getTemplate(t.originalUrl),n=await this.captureSsrSnapshot();if(!n)throw new Error("Modelence SSR is enabled but no SSR snapshot was captured. Make sure 'src/client/index.tsx' calls renderApp(...) from 'modelence/client'.");let[{renderSsrTreeStream:i},{getCallContext:s},a]=await Promise.all([import('./render-E7KMOS4P.js'),import('./server-B47F2UA4.js'),import('./collectCss-4YETFI7P.js')]),c=await s(t,o),l=this.collectCssAssets(a);yn(o,a.buildEarlyHintsLink(l));let{sessionState:d,pipe:p,getQueryState:f}=await i({callContext:c,loadingElement:n.loadingElement,routesElement:n.routesElement,router:n.router,location:t.originalUrl}),{prelude:y,rootOpenTag:h,epilogue:S}=hn(r),ie=wn(y,a.renderStylesheetLinks(l));o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200),o.write(ie),o.write(`<script id="__MODELENCE_STATE__" type="application/json">${ct(d)}</script>`),o.write(h),await p(o),o.write("</div>"),o.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${ct(f())}</script>`),o.end(S);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,Xo):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(he)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let o=Y.resolve(process.cwd(),"src/client/index.html"),r=Oe.readFileSync(o,"utf-8");return this.viteServer&&(r=await this.viteServer.transformIndexHtml(t,r)),r}if(!this.prodTemplateCache){let o=Y.resolve(process.cwd(),he,"index.html");this.prodTemplateCache=Oe.readFileSync(o,"utf-8");}return this.prodTemplateCache}async captureSsrSnapshot(){let{_getSsrSnapshot:t}=await import('./renderApp-ZMIJGGAP.js');if(this.isDev()){if(!this.viteServer)throw new Error("Vite dev server not initialized");return await this.viteServer.ssrLoadModule(Xo),t()}return this.prodEntryLoaded||(await import(Y.resolve(process.cwd(),Qo,"index.mjs")),this.prodEntryLoaded=true),t()}serveStaticShell(t){if(this.isDev())try{t.setHeader("Cache-Control","no-store"),t.sendFile("index.html",{root:"./src/client"});}catch(o){console.error("Error serving index.html:",o),t.status(500).send("Internal Server Error");}else t.sendFile("index.html",{root:he});}isDev(){return process.env.NODE_ENV!=="production"}};function gn(e){if(e.method!=="GET"&&e.method!=="HEAD")return false;let t=e.get("accept")??"";if(t&&!t.includes("text/html")&&!t.includes("*/*"))return false;let o=(e.path??e.url??"").split("?")[0];if(o.startsWith("/api/"))return false;let r=o.split("/").pop()??"",n=r.lastIndexOf(".");if(n>0){let i=r.slice(n).toLowerCase();if(i!==".html"&&i!==".htm")return false}return true}function hn(e){let t=e.match(pn);if(!t||t.index===void 0)throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let o=e.slice(0,t.index),r=e.slice(t.index+t[0].length);return {prelude:o,rootOpenTag:t[1],epilogue:r}}function wn(e,t){if(!t)return e;let o=e.lastIndexOf(fn);return o===-1?t+e:e.slice(0,o)+t+e.slice(o)}function yn(e,t){if(t.length===0)return;let o=e;if(typeof o.writeEarlyHints=="function")try{o.writeEarlyHints({link:t});}catch(r){process.env.NODE_ENV!=="production"&&console.warn("Modelence SSR: writeEarlyHints failed",r);}}async function En(){let e=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,e))?.config||{}}catch(t){return console.warn("Could not load vite config:",t),{}}}function bn(e,t){let o=mergeConfig(e,t);if(o.plugins&&Array.isArray(o.plugins)){let r=new Set;o.plugins=o.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||r.has(i)?false:(r.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function vn(e,t={}){let o=process.cwd(),r=await En(),n=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>Oe.existsSync(Y.join(o,a))),i=[mn(),kn()];if(n){let a=(await import('vite-plugin-eslint')).default;i.push(a({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:o,overrideConfigFile:Y.resolve(o,n)}));}let s=defineConfig({plugins:i,build:{outDir:he,emptyOutDir:true},server:{middlewareMode:true,hmr:e?{server:e}:void 0},appType:t.ssr?"custom":"spa",root:"./src/client",resolve:{alias:{"@":Y.resolve(o,"src").replace(/\\/g,"/")}}});return bn(s,r)}function kn(){return {name:"modelence-asset-handler",async transform(e,t){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(t))return process.env.NODE_ENV==="development",e}}}var _e=new lt;function Cn(e){return e?e.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1]?.trim():void 0}function Sn(e){if(e)return Array.isArray(e)?e:[e]}function An(e){return {to:Array.isArray(e.to)?e.to:[e.to],subject:e.subject,html:e.html,text:e.text,fromName:Cn(e.from),replyTo:Sn(e.replyTo)}}function xn(e){if(!(e instanceof Error))return new Error("Managed email send failed");let t=e.responseBody,o=t?.error?.code,r=t?.error?.message;return o&&r?new Error(`Managed email rejected (${o}): ${r}`):e}var Zo={async sendEmail(e){if(e.cc||e.bcc||e.attachments||e.headers)throw new Error("Modelence managed email does not support cc, bcc, attachments, or custom headers in v1. Configure your own provider (Resend, SES, SMTP) to use these features. See https://docs.modelence.com/email/managed.");try{await _("/api/email/send","POST",An(e));}catch(t){throw xn(t)}}};var dt=Object.freeze({});function er(e){dt=Object.freeze(Object.assign({},dt,e));}function tr(){return dt}var ut=Object.freeze({});function or(e){ut=Object.freeze(Object.assign({},ut,e));}function Le(){return ut}async function Ln({modules:e$1=[],roles:t$1={},defaultRoles:o={},server:r=_e,migrations:n$1=[],email:i={},auth:s={},security:a={},websocket:c={},ssr:l=false}){l&&r===_e&&_e.enableSsr(),rr.config(),rr.config({path:".modelence.env"});let d=!!process.env.MODELENCE_SERVICE_ENDPOINT;Gn().then(()=>{}).catch(()=>{});for(let P of e$1)if(P.name.toLowerCase().startsWith("_system."))throw new Error(`Invalid module name: '${P.name}'
30
+
31
+ The '_system.' prefix is reserved for internal use and cannot be used in user-defined modules.
32
+
33
+ Rename your module to something that does not start with '_system.'`);let p=[et,n,Bo,Wo,Jo,le,st,Ko],f$1=[...p,...e$1];f(),Tn(p),Pn(e$1),t(t$1,o);let y=$n(f$1);e(y);let h=Mn(f$1),S=In(f$1);jn(f$1),et.rateLimits=Ze(s.rateLimits);let ie=Un(f$1);ro(ie);let{storesToInit:Q,effectiveStores:H}=qo(h);if(d){let{configs:P,environmentId:dr,appAlias:ur,environmentAlias:mr,telemetry:pr}=await Lo({configSchema:y,cronJobsMetadata:Vo(),stores:H,roles:t$1});ot(P),g({environmentId:dr,appAlias:ur,environmentAlias:mr,telemetry:pr});}else c$1(Re(y));if(d&&!i.provider?Fe({...i,provider:Zo}):Fe(i),Yt(s),er(a),or({...c,provider:c.provider||Ft}),V()){await Ht();let P=[...new Set([...Q,...H])];Hn(P),await Dn(H,n$1);}else zo(n$1);d&&(await h$1(),Mo()),Fo().catch(console.error),await nr(r,{combinedModules:f$1,channels:S});}function Pn(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))y(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))z$2(`${t.name}.${o}`,r);}}function Tn(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))A$1(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))B$1(`${t.name}.${o}`,r);}}function Mn(e){return e.flatMap(t=>t.stores)}function In(e){return e.flatMap(t=>t.channels)}function Un(e){return e.flatMap(t=>t.rateLimits)}function Nn(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var mt="migrations";async function Dn(e,t){if(!await J(mt,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let r,n;try{r=e.filter(a=>a.getIndexCreationMode()==="blocking"),n=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of r)await pt(a,"full");for(let a of n)await pt(a,"drop-only");}catch(a){throw await fe(mt),a}let i=(async()=>{for(let a of n)await pt(a,"create-only");})(),s=at(t,{lockMode:"skip"});Promise.allSettled([i,s]).then(([a,c])=>{a.status==="rejected"&&console.error("Error creating background indexes:",a.reason),c.status==="rejected"&&console.error("Error running migrations:",c.reason);}).finally(async()=>{await fe(mt);});}async function pt(e,t="full"){let o=e.getName();try{await e.createIndexes(t);}catch(r){Nn(o,r);}}function $n(e){let t={};for(let o of e)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in t)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);t[i]=n;}return t}function jn(e){for(let t of e)for(let[o,r]of Object.entries(t.cronJobs))Go(`${t.name}.${o}`,r);}function Hn(e){let t=be();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of e)o.init(t);}async function Gn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await Fn(),n=await import('./package-FJDWEXEP.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:zr.hostname(),environmentId:o})});}}async function Fn(){try{let e=Y.join(process.cwd(),"package.json"),t=await Rn.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function ir(e){await q$1.deleteMany({userId:e}),await r.deleteMany({userId:e});}async function Bn(e){await ir(e),await o.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function qn(e){await ir(e),await o.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var ft=class{constructor(t,o){this.category=t,this.canAccessChannel=o||null;}broadcast(t,o){let r=Le().provider;if(!r){l$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:t,data:o});}};function zn(e){if(!w().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return w().provider?.sendEmail(e)}async function Pe(e){return !e||typeof e!="string"?null:e$1(e)}function v(e,t,o){let r=E(),n=e.status(t);if(r.errorComponent)try{let i=r.errorComponent({error:o,statusCode:t});if(i)return n.send(i)}catch(i){console.error("Unhandled error in authConfig.errorComponent:",i);}return n.json({error:o})}async function gt(e,t){let{authToken:o}=await k$1(t);l(e,o),e.status(302),e.redirect("/");}async function Jn(e,t,o$1,r,n){let i=E();try{if(o$1.status==="disabled"||o$1.status==="deleted"){v(e,400,"User account is not active.");return}let s={};o$1.firstName===void 0&&t.firstName&&(s.firstName=t.firstName),o$1.lastName===void 0&&t.lastName&&(s.lastName=t.lastName),o$1.avatarUrl===void 0&&t.avatarUrl&&(s.avatarUrl=t.avatarUrl);let a=o$1;Object.keys(s).length>0&&(await o.updateOne({_id:o$1._id},{$set:s}),a={...o$1,...s}),await gt(e,o$1._id),i.onAfterLogin?.({provider:t.providerName,user:a,session:r,connectionInfo:n}),i.login?.onSuccess?.(a);}catch(s){throw s instanceof Error&&(i.login?.onError?.(s),i.onLoginError?.({provider:t.providerName,error:s,session:r,connectionInfo:n})),s}}async function Kn(e,t,o$1,r,n){let i=E();if((i.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(o$1.status==="disabled"||o$1.status==="deleted"){v(e,400,"User account is not active.");return}if(!o$1.emails?.find(c=>c.address.toLowerCase()===t.email.toLowerCase())?.verified){v(e,400,"User with this email already exists. Please log in instead.");return}try{let c={...o$1.firstName===void 0&&t.firstName&&{firstName:t.firstName},...o$1.lastName===void 0&&t.lastName&&{lastName:t.lastName},...o$1.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await o.updateOne({_id:o$1._id,status:{$nin:["deleted","disabled"]},$or:[{[`authMethods.${t.providerName}.id`]:{$exists:!1}},{[`authMethods.${t.providerName}.id`]:t.id}]},{$set:{[`authMethods.${t.providerName}.id`]:t.id,...c}})).matchedCount>0)){v(e,400,"User with this email already exists. Please log in instead.");return}await gt(e,o$1._id);let p={...o$1,...c,authMethods:{...o$1.authMethods,[t.providerName]:{id:t.id}}};i.onAfterLogin?.({provider:t.providerName,user:p,session:r,connectionInfo:n}),i.login?.onSuccess?.(p);return}catch(c){throw c instanceof Error&&(i.login?.onError?.(c),i.onLoginError?.({provider:t.providerName,error:c,session:r,connectionInfo:n})),c}}v(e,400,"User with this email already exists. Please log in instead.");}async function Yn(e,t,o$1,r){let n=E();try{let i;if(n.generateHandle){let l=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});i=await O(l,t.email,{throwOnConflict:!1});}else i=await O(void 0,t.email);let s={handle:i,status:"active",emails:[{address:t.email,verified:t.emailVerified}],createdAt:new Date,authMethods:{[t.providerName]:{id:t.id}},...t.firstName!==void 0&&{firstName:t.firstName},...t.lastName!==void 0&&{lastName:t.lastName},...t.avatarUrl!==void 0&&{avatarUrl:t.avatarUrl}},a=await o.insertOne(s);await gt(e,a.insertedId);let c=await o.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(n.onAfterSignup?.({provider:t.providerName,user:c,session:o$1,connectionInfo:r}),n.signup?.onSuccess?.(c));}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:i,session:o$1,connectionInfo:r}),n.signup?.onError?.(i)),i}}function re(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function Te(e,t,o$1){let r=await o.findOne({[`authMethods.${o$1.providerName}.id`]:o$1.id}),{session:n,connectionInfo:i}=await ne(e,t);if(r)return Jn(t,o$1,r,n,i);if(!o$1.email){v(t,400,`Email address is required for ${o$1.providerName} authentication.`);return}let s;try{s=await o.findOne({"emails.address":o$1.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(a){if(a instanceof Error){let c=E();c.onSignupError?.({provider:o$1.providerName,error:a,session:n,connectionInfo:i}),c.signup?.onError?.(a);}throw a}return s?Kn(t,o$1,s,n,i):Yn(t,o$1,n,i)}function A(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function oe(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function Me(e,t,o){let r=e.query.state,n=e.cookies[o],[i,s,a]=(n||"").split(":");return !r||!n||r!==i?(v(t,400,"Invalid OAuth state - possible CSRF attack"),null):(t.clearCookie(o),{mode:s||"login",...a?{linkedUserId:a}:{}})}async function Ie(e,t,o$1,r){let n=E(),{session:i,connectionInfo:s}=await ne(e,t),a=null;if(r){if(!ObjectId.isValid(r)){A(t),v(t,400,"Invalid OAuth linking state.");return}a=new ObjectId(r);}else a=i?.userId??null;if(!a){A(t),v(t,401,"You must be signed in to link a provider.");return}let c=a;try{let l=`authMethods.${o$1.providerName}.id`;if((await o.updateOne({_id:c,status:{$nin:["deleted","disabled"]},$or:[{[l]:{$exists:!1}},{[l]:o$1.id}]},{$set:{[l]:o$1.id}})).matchedCount===0){let f=await o.findOne({_id:c});if(!f||f.status==="deleted"||f.status==="disabled"){oe(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:new Error("User account not found or not active"),session:i,connectionInfo:s})),A(t),v(t,400,"User account is not active.");return}let y=f?.authMethods?.[o$1.providerName]?.id;if(y&&y!==o$1.id){oe(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:new Error(`User already has a different ${o$1.providerName} account linked`),session:i,connectionInfo:s})),A(t),v(t,400,`You have already linked a different ${o$1.providerName} account.`);return}oe(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:new Error(`Unexpected OAuth linking state for ${o$1.providerName}`),session:i,connectionInfo:s})),A(t),v(t,400,`Unable to link ${o$1.providerName} account.`);return}let p=await o.findOne({_id:c},{readPreference:"primary"});p&&oe(()=>n.onAfterOAuthLink?.({provider:o$1.providerName,user:p,session:i,connectionInfo:s})),A(t),t.status(302).redirect("/");}catch(l){if(l instanceof MongoServerError&&l.code===11e3){oe(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:l,session:i,connectionInfo:s})),A(t),v(t,400,`This ${o$1.providerName} account is already linked to a different user.`);return}if(l instanceof Error&&oe(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:l,session:i,connectionInfo:s})),A(t),!t.headersSent)throw l}}function Ue(e){return !e||typeof e!="string"?null:e}async function Zn(e,t,o,r){let n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:t,client_secret:o,redirect_uri:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function ei(e){let t=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function ti(e,t){let o=Ue(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Me(e,t,"authStateGoogle");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret")),c=re("google");try{let l=await Zn(o,s,a,c),d=await ei(l.access_token),p={id:d.id,email:d.email,emailVerified:d.verified_email,providerName:"google",firstName:d.given_name||void 0,lastName:d.family_name||void 0,avatarUrl:d.picture||void 0};n==="link"?await Ie(e,t,p,i):await Te(e,t,p);}catch(l){console.error("Google OAuth error:",l),n==="link"&&A(t),v(t,500,"Authentication failed");}}function oi(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.google.enabled"),s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret"));if(!i||!s||!a){v(r,503,"Google authentication is not configured");return}n();};return e.get("/api/_internal/auth/google",t,async(o,r)=>{let n=String(a$2("_system.user.auth.google.clientId")),i=re("google"),s=randomBytes(32).toString("hex"),a=o.query.mode==="link"?"link":"login",c=null;if(a==="link"&&o.query.linkNonce&&(c=await Pe(o.query.linkNonce),!c)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let l=c?`${s}:${a}:${c}`:`${s}:${a}`;r.cookie("authStateGoogle",l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let d=new URL("https://accounts.google.com/o/oauth2/v2/auth");d.searchParams.append("client_id",n),d.searchParams.append("redirect_uri",i),d.searchParams.append("response_type","code"),d.searchParams.append("scope","profile email"),d.searchParams.append("access_type","online"),d.searchParams.append("state",s),r.redirect(d.toString());}),e.get("/api/_internal/auth/google/callback",t,ti),e}var ar=oi;async function ii(e,t,o,r){let n=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,client_secret:o,code:e,redirect_uri:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function si(e){let t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function ai(e){let t=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user emails: ${t.statusText}`);return t.json()}async function ci(e,t){return e.email?e.email:(await ai(t)).find(r=>r.primary&&r.verified)?.email??null}async function li(e,t){let o=Ue(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Me(e,t,"authStateGithub");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret")),c=re("github");try{let l=await ii(o,s,a,c),d=await si(l.access_token),p=await ci(d,l.access_token);if(!p){n==="link"&&A(t),v(t,400,"Unable to retrieve a primary verified email from GitHub. Please ensure your GitHub account has a verified email set as primary.");return}let f=d.name?d.name.trim().split(/\s+/):[],y=f[0]||void 0,h=f.length>1?f.slice(1).join(" "):void 0,S={id:String(d.id),email:p,emailVerified:!0,providerName:"github",firstName:y,lastName:h,avatarUrl:d.avatar_url||void 0};n==="link"?await Ie(e,t,S,i):await Te(e,t,S);}catch(l){console.error("GitHub OAuth error:",l),n==="link"&&A(t),v(t,500,"Authentication failed");}}function di(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.github.enabled"),s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret"));if(!i||!s||!a){v(r,503,"GitHub authentication is not configured");return}n();};return e.get("/api/_internal/auth/github",t,async(o,r)=>{let n=String(a$2("_system.user.auth.github.clientId")),i=re("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(y=>y.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex"),l=o.query.mode==="link"?"link":"login",d=null;if(l==="link"&&o.query.linkNonce&&(d=await Pe(o.query.linkNonce),!d)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let p=d?`${c}:${l}:${d}`:`${c}:${l}`;r.cookie("authStateGithub",p,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let f=new URL("https://github.com/login/oauth/authorize");f.searchParams.append("client_id",n),f.searchParams.append("redirect_uri",i),f.searchParams.append("scope",a),f.searchParams.append("state",c),r.redirect(f.toString());}),e.get("/api/_internal/auth/github/callback",t,li),e}var cr=di;function lr(e,t,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&V())try{let{session:l,user:d}=await v$1(s);a={session:l,user:d};}catch{}let c=m$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:i$1(r.query),body:i$1(r.body),params:i$1(r.params)});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.headers&&Object.entries(l.headers).forEach(([d,p])=>{n.setHeader(d,p);}),l.redirect?n.redirect(l.redirect):n.send(l.data));}catch(l){c.end("error"),l instanceof a$4?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}function pi(e){let t=[];if(!e)return t.push(j$1.json({limit:"16mb"})),t.push(j$1.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let o=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(j$1.json(o));}if(e.urlencoded!==false){let o=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(j$1.urlencoded(o));}if(e.raw){let o=typeof e.raw=="object"?e.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};t.push(j$1.raw(r));}return t}function fi(e,t){for(let o of t)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=pi(s);Object.entries(i).forEach(([c,l])=>{e[c](n,...a,lr(c,n,l));});}}async function nr(e,{combinedModules:t,channels:o}){let r=j$1();r.use(ui()),r.use(wi()),fi(r,t),r.use(j$1.json({limit:"16mb"})),r.use(j$1.urlencoded({extended:true,limit:"16mb"})),r.use(ar()),r.use(cr()),r.post("/api/_internal/auth/set-link-cookie",async(a,c)=>{let{session:l}=await ne(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}c.cookie("oauthLinkToken",l.authToken,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/api/_internal/auth/",maxAge:10*60*1e3}),c.json({ok:true});}),r.post("/api/_internal/auth/issue-link-nonce",async(a,c)=>{let{session:l}=await ne(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}let d=await d$1(String(l.userId));c.json({nonce:d});}),r.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let l=a.params.methodName,d=await ne(a,c);try{let p=a$3(await C(l,a.body.args,d));c.json({data:p,typeMap:b$2(p)});}catch(p){gi(c,l,p);}});let n=mi.createServer(r);await e.init({httpServer:n}),e.middlewares&&r.use(e.middlewares()),r.all("*",(a,c,l)=>{Promise.resolve(e.handler(a,c)).catch(l);}),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let i=Le()?.provider;i&&i.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{k$2("Application started",{source:"app"});let a=a$2("_system.site.url")||`http://localhost:${s}`;console.log(`
34
+ Application started on ${a}
35
+ `);});}async function ne(e,t=null){let o=(e.path??e.url??"").split("?")[0],r=o.startsWith("/api/_internal/auth/")&&o.endsWith("/callback"),n=e.body??{},i=$.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(r?e.cookies.oauthLinkToken:null)||n.authToken),s=$.object({screenWidth:$.number(),screenHeight:$.number(),windowWidth:$.number(),windowHeight:$.number(),pixelRatio:$.number(),orientation:$.string().nullable()}).nullish().parse(n.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:Ei(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:yi(e)};if(!!V()){let{session:l,user:d,roles:p}=await v$1(i);return {clientInfo:s,connectionInfo:a,session:l,user:d,roles:p,req:e,res:t}}return {clientInfo:s,connectionInfo:a,session:null,user:null,roles:u(),req:e,res:t}}function gi(e,t,o){if(o instanceof a$4){o.status>=500&&o.status<600&&console.error(`Error calling ${t}:`,o),o.code&&e.setHeader("X-Modelence-Error-Code",o.code),e.status(o.status).send(o.message);return}if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r="";try{r=hi(o);}catch(n){console.error(`Error parsing Zod error in ${t}:`,n),r="Validation failed";}e.status(400).send(r);return}console.error(`Error calling ${t}:`,o),e.status(500).send(o instanceof Error?o.message:String(o));}function hi(e){let t=e.flatten(),o=Object.entries(t.fieldErrors).map(([i,s])=>`${i}: ${(s??[]).join(", ")}`),r=t.formErrors;return [...o,...r].filter(Boolean).join("; ")}function wi(){let{frameAncestors:e}=tr(),t=e&&e.length>0,o=t?["'self'",...e].join(" "):"'self'";return (r,n,i)=>{n.setHeader("Content-Security-Policy",`frame-ancestors ${o}`),t||n.setHeader("X-Frame-Options","SAMEORIGIN"),i();}}function yi(e){let t=e.headers["x-forwarded-host"],o=(Array.isArray(t)?t[0]:t?.split(",")[0])?.trim()||e.get("host"),r=e.headers["x-forwarded-proto"];return `${(Array.isArray(r)?r[0]:r?.split(",")[0])?.trim()||e.protocol}://${o}`}function Ei(e){let t=e.headers["x-forwarded-for"];if(t)return (Array.isArray(t)?t[0]:t.split(",")[0]).trim();let o=e.ip||e.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}
36
+ export{k as a,rn as b,nn as c,sn as d,an as e,nr as f,ne as g,Ln as h,Bn as i,qn as j,ft as k,zn as l};//# sourceMappingURL=chunk-PSOK2GIU.js.map
37
+ //# sourceMappingURL=chunk-PSOK2GIU.js.map