modelence 0.23.0-setup.dev.1 → 0.23.0-setup.dev.3

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/bin/modelence.js +5 -4
  2. package/dist/bin/modelence.js.map +1 -1
  3. package/dist/{chunk-VW6ML4HX.js → chunk-5DF3HHWJ.js} +2 -2
  4. package/dist/{chunk-VW6ML4HX.js.map → chunk-5DF3HHWJ.js.map} +1 -1
  5. package/dist/{chunk-I25TKIJW.js → chunk-7XZDALJZ.js} +12 -12
  6. package/dist/chunk-7XZDALJZ.js.map +1 -0
  7. package/dist/chunk-JQ7HKLQZ.js +3 -0
  8. package/dist/chunk-JQ7HKLQZ.js.map +1 -0
  9. package/dist/chunk-NCJCE4XN.js +3 -0
  10. package/dist/chunk-NCJCE4XN.js.map +1 -0
  11. package/dist/chunk-QMKQ7DUD.js +4 -0
  12. package/dist/chunk-QMKQ7DUD.js.map +1 -0
  13. package/dist/{chunk-SIKRUWRN.js → chunk-UHER7BLC.js} +2 -2
  14. package/dist/{chunk-SIKRUWRN.js.map → chunk-UHER7BLC.js.map} +1 -1
  15. package/dist/client.js +1 -1
  16. package/dist/package-A4RGADVP.js +2 -0
  17. package/dist/{package-XAQYEUWG.js.map → package-A4RGADVP.js.map} +1 -1
  18. package/dist/{render-RN75WGWX.js → render-V4SWSKPW.js} +2 -2
  19. package/dist/{render-RN75WGWX.js.map → render-V4SWSKPW.js.map} +1 -1
  20. package/dist/renderApp-YNRUDPRK.js +2 -0
  21. package/dist/{renderApp-DDIZBBPN.js.map → renderApp-YNRUDPRK.js.map} +1 -1
  22. package/dist/server-D7FBXWTW.js +2 -0
  23. package/dist/{server-46L3FOLX.js.map → server-D7FBXWTW.js.map} +1 -1
  24. package/dist/server.js +1 -1
  25. package/dist/{transport-JPOZOWQ6.js → transport-OSL4EWWD.js} +2 -2
  26. package/dist/{transport-JPOZOWQ6.js.map → transport-OSL4EWWD.js.map} +1 -1
  27. package/package.json +4 -1
  28. package/dist/chunk-B7EXKTEZ.js +0 -3
  29. package/dist/chunk-B7EXKTEZ.js.map +0 -1
  30. package/dist/chunk-I25TKIJW.js.map +0 -1
  31. package/dist/chunk-PGNYB3ZP.js +0 -3
  32. package/dist/chunk-PGNYB3ZP.js.map +0 -1
  33. package/dist/chunk-WHC2SP5P.js +0 -4
  34. package/dist/chunk-WHC2SP5P.js.map +0 -1
  35. package/dist/package-XAQYEUWG.js +0 -2
  36. package/dist/renderApp-DDIZBBPN.js +0 -2
  37. package/dist/server-46L3FOLX.js +0 -2
package/dist/client.js CHANGED
@@ -1,2 +1,2 @@
1
- export{f as AppProvider,e as ClientChannel,a as createClientModule,d as renderApp,b as systemConfig}from'./chunk-VW6ML4HX.js';export{i as ModelenceQueryClient,n as ModelenceQueryProvider,f as connectModelenceQueryClient,m as createQueryKey,h as disconnectModelenceQueryClient,d as getWebsocketClientProvider,k as modelenceLiveQuery,l as modelenceMutation,j as modelenceQuery,c as setWebsocketClientProvider,e as startWebsockets,b as subscribeLiveQuery}from'./chunk-B7EXKTEZ.js';export{F as MethodError,I as callMethod,d as configureClient,b as getConfig,c as getLocalStorageSession,A as linkOAuthProvider,x as loginWithMagicLink,y as loginWithOneTimeCode,q as loginWithPassword,u as logout,t as resendEmailVerification,z as resetPassword,w as sendMagicLink,v as sendResetPasswordToken,p as signupWithPassword,B as unlinkOAuthProvider,r as updateProfile,o as useSession,s as verifyEmail}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=client.js.map
1
+ export{f as AppProvider,e as ClientChannel,a as createClientModule,d as renderApp,b as systemConfig}from'./chunk-5DF3HHWJ.js';export{i as ModelenceQueryClient,n as ModelenceQueryProvider,f as connectModelenceQueryClient,m as createQueryKey,h as disconnectModelenceQueryClient,d as getWebsocketClientProvider,k as modelenceLiveQuery,l as modelenceMutation,j as modelenceQuery,c as setWebsocketClientProvider,e as startWebsockets,b as subscribeLiveQuery}from'./chunk-NCJCE4XN.js';export{F as MethodError,I as callMethod,d as configureClient,b as getConfig,c as getLocalStorageSession,A as linkOAuthProvider,x as loginWithMagicLink,y as loginWithOneTimeCode,q as loginWithPassword,u as logout,t as resendEmailVerification,z as resetPassword,w as sendMagicLink,v as sendResetPasswordToken,p as signupWithPassword,B as unlinkOAuthProvider,r as updateProfile,o as useSession,s as verifyEmail}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=client.js.map
2
2
  //# sourceMappingURL=client.js.map
@@ -0,0 +1,2 @@
1
+ export{m as author,i as bin,o as bugs,t as default,r as dependencies,d as description,q as devDependencies,j as engines,g as exports,h as files,p as homepage,n as license,e as main,b as name,s as peerDependencies,l as repository,k as scripts,a as type,f as types,c as version}from'./chunk-JQ7HKLQZ.js';//# sourceMappingURL=package-A4RGADVP.js.map
2
+ //# sourceMappingURL=package-A4RGADVP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-XAQYEUWG.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-A4RGADVP.js"}
@@ -1,2 +1,2 @@
1
- import {a,b,c}from'./chunk-SIKRUWRN.js';import'./chunk-WHC2SP5P.js';import'./chunk-B5WLEHNH.js';import {a as a$1,n}from'./chunk-B7EXKTEZ.js';import {m,a as a$2,n as n$1}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';import {renderToPipeableStream}from'react-dom/server';import {Writable}from'stream';import {QueryClient,dehydrate}from'@tanstack/react-query';import {jsx}from'react/jsx-runtime';var J=()=>{let r=c();return r?n$1(r.session.user):null},M=r=>{let n=c();if(n)return n.session.configs[r]?.value};function D(){m(J),a$2(M);}async function X(r){let{callContext:n$1,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let l=await a("_system.session.init",{},n$1),i=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:i,children:O})}),a$2=null;await new Promise((s,m)=>{b({callContext:n$1,queryClient:i,session:{user:l.user,configs:l.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){a$2=e,E?.(),s(e);},onShellError(t){m(t);},onError(t){b$1?.(t);}});return e});});let d=null,_=s=>new Promise((m,e)=>{if(!a$2){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(o,c,I){s.write(o,N=>I(N??void 0));},final(o){try{let c=dehydrate(i);d=JSON.stringify(c);}finally{i.clear();}o(),m();}});t.on("error",o=>{s.destroy(o),e(o);}),s.on("error",e),a$2.pipe(t);});return {sessionState:JSON.stringify({session:l}),pipe:_,getQueryState:()=>{if(d===null)throw new Error("getQueryState() called before stream finished");return d}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-RN75WGWX.js.map
2
- //# sourceMappingURL=render-RN75WGWX.js.map
1
+ import {a,b,c}from'./chunk-UHER7BLC.js';import'./chunk-QMKQ7DUD.js';import'./chunk-B5WLEHNH.js';import {a as a$1,n}from'./chunk-NCJCE4XN.js';import {m,a as a$2,n as n$1}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';import {renderToPipeableStream}from'react-dom/server';import {Writable}from'stream';import {QueryClient,dehydrate}from'@tanstack/react-query';import {jsx}from'react/jsx-runtime';var J=()=>{let r=c();return r?n$1(r.session.user):null},M=r=>{let n=c();if(n)return n.session.configs[r]?.value};function D(){m(J),a$2(M);}async function X(r){let{callContext:n$1,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let l=await a("_system.session.init",{},n$1),i=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:i,children:O})}),a$2=null;await new Promise((s,m)=>{b({callContext:n$1,queryClient:i,session:{user:l.user,configs:l.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){a$2=e,E?.(),s(e);},onShellError(t){m(t);},onError(t){b$1?.(t);}});return e});});let d=null,_=s=>new Promise((m,e)=>{if(!a$2){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(o,c,I){s.write(o,N=>I(N??void 0));},final(o){try{let c=dehydrate(i);d=JSON.stringify(c);}finally{i.clear();}o(),m();}});t.on("error",o=>{s.destroy(o),e(o);}),s.on("error",e),a$2.pipe(t);});return {sessionState:JSON.stringify({session:l}),pipe:_,getQueryState:()=>{if(d===null)throw new Error("getQueryState() called before stream finished");return d}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-V4SWSKPW.js.map
2
+ //# sourceMappingURL=render-V4SWSKPW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ssr/render.tsx"],"names":["sessionResolver","ctx","getSsrContext","_parseSessionUser","configResolver","key","ensureSsrResolversInstalled","_setSsrSessionResolver","_setSsrConfigResolver","renderSsrTreeStream","options","callContext","loadingElement","routesElement","router","location","onShellReady","onError","sessionPayload","callInProcessMethod","queryClient","QueryClient","routedTree","tree","jsx","AppProvider","ModelenceQueryProvider","streamRef","resolve","reject","runWithSsrContext","stream","renderToPipeableStream","error","queryStateJson","pipe","destination","passthrough","Writable","chunk","_encoding","callback","err","dehydratedState","dehydrate"],"mappings":"6aAkBA,IAAMA,CAAAA,CAAkB,IAAM,CAC5B,IAAMC,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,OAAKD,EAGEE,GAAAA,CAAkBF,CAAAA,CAAI,OAAA,CAAQ,IAAI,EAFhC,IAGX,CAAA,CAEMG,EAAkBC,CAAAA,EAAmB,CACzC,IAAMJ,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,GAAKD,EAGL,OAAOA,CAAAA,CAAI,OAAA,CAAQ,OAAA,CAAQI,CAAG,CAAA,EAAG,KACnC,CAAA,CAEA,SAASC,GAA8B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IAAI,KAAA,CAAM,+CAA+C,EAEjE,OAAOA,CACT,CACF,CACF","file":"render-RN75WGWX.js","sourcesContent":["import React from 'react';\nimport { renderToPipeableStream, type PipeableStream } from 'react-dom/server';\nimport { Writable } from 'node:stream';\nimport { QueryClient, dehydrate, type DehydratedState } from '@tanstack/react-query';\nimport { AppProvider } from '../client/AppProvider';\nimport { ModelenceQueryProvider } from '../client/queryProvider';\nimport { getSsrContext, runWithSsrContext } from './context';\nimport { callInProcessMethod } from './callInProcess';\nimport type { Context } from '../methods/types';\nimport {\n _parseSessionUser,\n _setSsrSessionResolver,\n type SessionInitPayload,\n} from '../client/session';\nimport { _setSsrConfigResolver } from '../config/client';\nimport type { ConfigKey, Configs } from '../config/types';\nimport type { SsrRouter } from '../client/renderApp';\n\nconst sessionResolver = () => {\n const ctx = getSsrContext();\n if (!ctx) {\n return null;\n }\n return _parseSessionUser(ctx.session.user);\n};\n\nconst configResolver = (key: ConfigKey) => {\n const ctx = getSsrContext();\n if (!ctx) {\n return undefined;\n }\n return ctx.session.configs[key]?.value;\n};\n\nfunction ensureSsrResolversInstalled() {\n _setSsrSessionResolver(sessionResolver);\n _setSsrConfigResolver(configResolver);\n}\n\nexport type SsrRenderOptions = {\n callContext: Context;\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n router?: SsrRouter;\n location?: string;\n};\n\nexport type SsrStreamHandle = {\n /** Session bootstrap payload — inline before the shell flushes. */\n sessionState: string;\n /** Pipe React's HTML into `destination`. Resolves when streaming finishes. */\n pipe: (destination: Writable) => Promise<void>;\n /** Dehydrated query state. Only call after `pipe()` resolves. */\n getQueryState: () => string;\n};\n\nexport type SsrStreamOptions = SsrRenderOptions & {\n /** Fires when the shell is flushed; caller writes prelude + state here. */\n onShellReady?: () => void;\n /** Non-fatal SSR errors (Suspense fallbacks, etc.). */\n onError?: (error: unknown) => void;\n};\n\nexport async function renderSsrTreeStream(options: SsrStreamOptions): Promise<SsrStreamHandle> {\n const { callContext, loadingElement, routesElement, router, location, onShellReady, onError } =\n options;\n\n ensureSsrResolversInstalled();\n\n const sessionPayload = await callInProcessMethod<SessionInitPayload>(\n '_system.session.init',\n {},\n callContext\n );\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n gcTime: 0,\n },\n },\n });\n\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n const tree = (\n <AppProvider loadingElement={loadingElement}>\n <ModelenceQueryProvider client={queryClient}>{routedTree}</ModelenceQueryProvider>\n </AppProvider>\n );\n\n let streamRef: PipeableStream | null = null;\n // Resolves with the stream once React renders above-fallback content;\n // rejects on shell errors so the caller can fall back to a static response.\n const shellReady = new Promise<PipeableStream>((resolve, reject) => {\n // Run the render inside the SSR context so components can resolve\n // session/config/query state from the per-request scope.\n runWithSsrContext(\n {\n callContext,\n queryClient,\n session: {\n user: sessionPayload.user,\n configs: (sessionPayload.configs as Configs) ?? {},\n },\n },\n () => {\n const stream = renderToPipeableStream(tree, {\n onShellReady() {\n streamRef = stream;\n onShellReady?.();\n resolve(stream);\n },\n onShellError(error) {\n reject(error);\n },\n onError(error) {\n onError?.(error);\n },\n });\n return stream;\n }\n );\n });\n\n // Await so shell errors surface before the caller starts piping.\n await shellReady;\n\n let queryStateJson: string | null = null;\n\n const pipe = (destination: Writable): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (!streamRef) {\n reject(new Error('SSR stream was not initialized'));\n return;\n }\n\n // react-dom calls `destination.end()` when done. The caller still needs\n // to write the epilogue + query state, so wrap with a passthrough whose\n // `final()` resolves the pipe promise without closing the response.\n const passthrough = new Writable({\n write(chunk, _encoding, callback) {\n destination.write(chunk, (err) => callback(err ?? undefined));\n },\n final(callback) {\n try {\n const dehydratedState: DehydratedState = dehydrate(queryClient);\n queryStateJson = JSON.stringify(dehydratedState);\n } finally {\n queryClient.clear();\n }\n callback();\n resolve();\n },\n });\n\n passthrough.on('error', (err) => {\n destination.destroy(err);\n reject(err);\n });\n destination.on('error', reject);\n\n streamRef.pipe(passthrough);\n });\n };\n\n return {\n sessionState: JSON.stringify({ session: sessionPayload }),\n pipe,\n getQueryState: () => {\n if (queryStateJson === null) {\n throw new Error('getQueryState() called before stream finished');\n }\n return queryStateJson;\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/ssr/render.tsx"],"names":["sessionResolver","ctx","getSsrContext","_parseSessionUser","configResolver","key","ensureSsrResolversInstalled","_setSsrSessionResolver","_setSsrConfigResolver","renderSsrTreeStream","options","callContext","loadingElement","routesElement","router","location","onShellReady","onError","sessionPayload","callInProcessMethod","queryClient","QueryClient","routedTree","tree","jsx","AppProvider","ModelenceQueryProvider","streamRef","resolve","reject","runWithSsrContext","stream","renderToPipeableStream","error","queryStateJson","pipe","destination","passthrough","Writable","chunk","_encoding","callback","err","dehydratedState","dehydrate"],"mappings":"6aAkBA,IAAMA,CAAAA,CAAkB,IAAM,CAC5B,IAAMC,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,OAAKD,EAGEE,GAAAA,CAAkBF,CAAAA,CAAI,OAAA,CAAQ,IAAI,EAFhC,IAGX,CAAA,CAEMG,EAAkBC,CAAAA,EAAmB,CACzC,IAAMJ,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,GAAKD,EAGL,OAAOA,CAAAA,CAAI,OAAA,CAAQ,OAAA,CAAQI,CAAG,CAAA,EAAG,KACnC,CAAA,CAEA,SAASC,GAA8B,CACrCC,CAAAA,CAAuBP,CAAe,CAAA,CACtCQ,IAAsBJ,CAAc,EACtC,CA0BA,eAAsBK,EAAoBC,CAAAA,CAAqD,CAC7F,GAAM,CAAE,YAAAC,GAAAA,CAAa,cAAA,CAAAC,CAAAA,CAAgB,aAAA,CAAAC,EAAe,MAAA,CAAAC,CAAAA,CAAQ,SAAAC,CAAAA,CAAU,YAAA,CAAAC,EAAc,OAAA,CAAAC,GAAQ,CAAA,CAC1FP,CAAAA,CAEFJ,GAA4B,CAE5B,IAAMY,CAAAA,CAAiB,MAAMC,EAC3B,sBAAA,CAC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AAgC,CAAC,CAAA,CAClD,MACF,CAKA,IAAMQ,CAAAA,CAAc,IAAIC,QAAAA,CAAS,CAC/B,MAAMC,CAAAA,CAAOC,CAAAA,CAAWC,CAAAA,CAAU,CAChCL,EAAY,KAAA,CAAMG,CAAAA,CAAQG,GAAQD,CAAAA,CAASC,CAAAA,EAAO,MAAS,CAAC,EAC9D,CAAA,CACA,KAAA,CAAMD,EAAU,CACd,GAAI,CACF,IAAME,EAAmCC,SAAAA,CAAUxB,CAAW,CAAA,CAC9Dc,CAAAA,CAAiB,KAAK,SAAA,CAAUS,CAAe,EACjD,CAAA,OAAE,CACAvB,CAAAA,CAAY,KAAA,GACd,CACAqB,GAAS,CACTb,CAAAA,GACF,CACF,CAAC,CAAA,CAEDS,CAAAA,CAAY,EAAA,CAAG,OAAA,CAAUK,GAAQ,CAC/BN,CAAAA,CAAY,QAAQM,CAAG,CAAA,CACvBb,EAAOa,CAAG,EACZ,CAAC,CAAA,CACDN,EAAY,EAAA,CAAG,OAAA,CAASP,CAAM,CAAA,CAE9BF,IAAU,IAAA,CAAKU,CAAW,EAC5B,CAAC,EAGH,OAAO,CACL,YAAA,CAAc,IAAA,CAAK,UAAU,CAAE,OAAA,CAASnB,CAAe,CAAC,EACxD,IAAA,CAAAiB,CAAAA,CACA,aAAA,CAAe,IAAM,CACnB,GAAID,CAAAA,GAAmB,IAAA,CACrB,MAAM,IAAI,KAAA,CAAM,+CAA+C,EAEjE,OAAOA,CACT,CACF,CACF","file":"render-V4SWSKPW.js","sourcesContent":["import React from 'react';\nimport { renderToPipeableStream, type PipeableStream } from 'react-dom/server';\nimport { Writable } from 'node:stream';\nimport { QueryClient, dehydrate, type DehydratedState } from '@tanstack/react-query';\nimport { AppProvider } from '../client/AppProvider';\nimport { ModelenceQueryProvider } from '../client/queryProvider';\nimport { getSsrContext, runWithSsrContext } from './context';\nimport { callInProcessMethod } from './callInProcess';\nimport type { Context } from '../methods/types';\nimport {\n _parseSessionUser,\n _setSsrSessionResolver,\n type SessionInitPayload,\n} from '../client/session';\nimport { _setSsrConfigResolver } from '../config/client';\nimport type { ConfigKey, Configs } from '../config/types';\nimport type { SsrRouter } from '../client/renderApp';\n\nconst sessionResolver = () => {\n const ctx = getSsrContext();\n if (!ctx) {\n return null;\n }\n return _parseSessionUser(ctx.session.user);\n};\n\nconst configResolver = (key: ConfigKey) => {\n const ctx = getSsrContext();\n if (!ctx) {\n return undefined;\n }\n return ctx.session.configs[key]?.value;\n};\n\nfunction ensureSsrResolversInstalled() {\n _setSsrSessionResolver(sessionResolver);\n _setSsrConfigResolver(configResolver);\n}\n\nexport type SsrRenderOptions = {\n callContext: Context;\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n router?: SsrRouter;\n location?: string;\n};\n\nexport type SsrStreamHandle = {\n /** Session bootstrap payload — inline before the shell flushes. */\n sessionState: string;\n /** Pipe React's HTML into `destination`. Resolves when streaming finishes. */\n pipe: (destination: Writable) => Promise<void>;\n /** Dehydrated query state. Only call after `pipe()` resolves. */\n getQueryState: () => string;\n};\n\nexport type SsrStreamOptions = SsrRenderOptions & {\n /** Fires when the shell is flushed; caller writes prelude + state here. */\n onShellReady?: () => void;\n /** Non-fatal SSR errors (Suspense fallbacks, etc.). */\n onError?: (error: unknown) => void;\n};\n\nexport async function renderSsrTreeStream(options: SsrStreamOptions): Promise<SsrStreamHandle> {\n const { callContext, loadingElement, routesElement, router, location, onShellReady, onError } =\n options;\n\n ensureSsrResolversInstalled();\n\n const sessionPayload = await callInProcessMethod<SessionInitPayload>(\n '_system.session.init',\n {},\n callContext\n );\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n gcTime: 0,\n },\n },\n });\n\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n const tree = (\n <AppProvider loadingElement={loadingElement}>\n <ModelenceQueryProvider client={queryClient}>{routedTree}</ModelenceQueryProvider>\n </AppProvider>\n );\n\n let streamRef: PipeableStream | null = null;\n // Resolves with the stream once React renders above-fallback content;\n // rejects on shell errors so the caller can fall back to a static response.\n const shellReady = new Promise<PipeableStream>((resolve, reject) => {\n // Run the render inside the SSR context so components can resolve\n // session/config/query state from the per-request scope.\n runWithSsrContext(\n {\n callContext,\n queryClient,\n session: {\n user: sessionPayload.user,\n configs: (sessionPayload.configs as Configs) ?? {},\n },\n },\n () => {\n const stream = renderToPipeableStream(tree, {\n onShellReady() {\n streamRef = stream;\n onShellReady?.();\n resolve(stream);\n },\n onShellError(error) {\n reject(error);\n },\n onError(error) {\n onError?.(error);\n },\n });\n return stream;\n }\n );\n });\n\n // Await so shell errors surface before the caller starts piping.\n await shellReady;\n\n let queryStateJson: string | null = null;\n\n const pipe = (destination: Writable): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (!streamRef) {\n reject(new Error('SSR stream was not initialized'));\n return;\n }\n\n // react-dom calls `destination.end()` when done. The caller still needs\n // to write the epilogue + query state, so wrap with a passthrough whose\n // `final()` resolves the pipe promise without closing the response.\n const passthrough = new Writable({\n write(chunk, _encoding, callback) {\n destination.write(chunk, (err) => callback(err ?? undefined));\n },\n final(callback) {\n try {\n const dehydratedState: DehydratedState = dehydrate(queryClient);\n queryStateJson = JSON.stringify(dehydratedState);\n } finally {\n queryClient.clear();\n }\n callback();\n resolve();\n },\n });\n\n passthrough.on('error', (err) => {\n destination.destroy(err);\n reject(err);\n });\n destination.on('error', reject);\n\n streamRef.pipe(passthrough);\n });\n };\n\n return {\n sessionState: JSON.stringify({ session: sessionPayload }),\n pipe,\n getQueryState: () => {\n if (queryStateJson === null) {\n throw new Error('getQueryState() called before stream finished');\n }\n return queryStateJson;\n },\n };\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export{c as _getSsrSnapshot,d as renderApp}from'./chunk-5DF3HHWJ.js';import'./chunk-NCJCE4XN.js';import'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=renderApp-YNRUDPRK.js.map
2
+ //# sourceMappingURL=renderApp-YNRUDPRK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"renderApp-DDIZBBPN.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"renderApp-YNRUDPRK.js"}
@@ -0,0 +1,2 @@
1
+ export{g as getCallContext,f as startServer}from'./chunk-7XZDALJZ.js';import'./chunk-JQ7HKLQZ.js';import'./chunk-QMKQ7DUD.js';import'./chunk-VYR7VQMQ.js';import'./chunk-B5WLEHNH.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-D7FBXWTW.js.map
2
+ //# sourceMappingURL=server-D7FBXWTW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"server-46L3FOLX.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"server-D7FBXWTW.js"}
package/dist/server.js CHANGED
@@ -1,2 +1,2 @@
1
- export{m as ObjectId,k as ServerChannel,a as consumeRateLimit,c as deleteFile,j as deleteUser,i as disableUser,d as downloadFile,e as getFileUrl,b as getUploadUrl,l as sendEmail,h as startApp}from'./chunk-I25TKIJW.js';import'./chunk-PGNYB3ZP.js';export{y as LiveData,a as Module,c as Store,x as authenticate,k as clearSessionUser,A as createQuery,m as createSession,h as dbSessions,q as dbUsers,l as invalidateAllUserSessions,i as obtainSession,d as schema,n as setAuthTokenCookie,j as setSessionUser}from'./chunk-WHC2SP5P.js';import'./chunk-VYR7VQMQ.js';export{a as getConfig,h as getEnvironmentId}from'./chunk-B5WLEHNH.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server.js.map
1
+ export{m as ObjectId,k as ServerChannel,a as consumeRateLimit,c as deleteFile,j as deleteUser,i as disableUser,d as downloadFile,e as getFileUrl,b as getUploadUrl,l as sendEmail,h as startApp}from'./chunk-7XZDALJZ.js';import'./chunk-JQ7HKLQZ.js';export{y as LiveData,a as Module,c as Store,x as authenticate,k as clearSessionUser,A as createQuery,m as createSession,h as dbSessions,q as dbUsers,l as invalidateAllUserSessions,i as obtainSession,d as schema,n as setAuthTokenCookie,j as setSessionUser}from'./chunk-QMKQ7DUD.js';import'./chunk-VYR7VQMQ.js';export{a as getConfig,h as getEnvironmentId}from'./chunk-B5WLEHNH.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server.js.map
2
2
  //# sourceMappingURL=server.js.map
@@ -1,2 +1,2 @@
1
- import {c,a}from'./chunk-SIKRUWRN.js';import'./chunk-WHC2SP5P.js';import'./chunk-B5WLEHNH.js';import {H,G}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';function d(){return H(async(t,r)=>{let o=c();return o?a(t,r,o.callContext):G(t,r)})}export{d as installSsrCallMethodTransport};//# sourceMappingURL=transport-JPOZOWQ6.js.map
2
- //# sourceMappingURL=transport-JPOZOWQ6.js.map
1
+ import {c,a}from'./chunk-UHER7BLC.js';import'./chunk-QMKQ7DUD.js';import'./chunk-B5WLEHNH.js';import {H,G}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';function d(){return H(async(t,r)=>{let o=c();return o?a(t,r,o.callContext):G(t,r)})}export{d as installSsrCallMethodTransport};//# sourceMappingURL=transport-OSL4EWWD.js.map
2
+ //# sourceMappingURL=transport-OSL4EWWD.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ssr/transport.ts"],"names":["installSsrCallMethodTransport","setCallMethodTransport","methodName","args","ssrCtx","getSsrContext","callInProcessMethod","defaultCallMethodTransport"],"mappings":"4LAcO,SAASA,CAAAA,EAA4C,CAC1D,OAAOC,CAAAA,CAAuB,MAAUC,EAAoBC,CAAAA,GAAqB,CAC/E,IAAMC,CAAAA,CAASC,CAAAA,EAAc,CAC7B,OAAKD,CAAAA,CAIEE,CAAAA,CAAuBJ,CAAAA,CAAYC,CAAAA,CAAMC,CAAAA,CAAO,WAAW,CAAA,CAHzDG,CAAAA,CAA8BL,CAAAA,CAAYC,CAAI,CAIzD,CAAC,CACH","file":"transport-JPOZOWQ6.js","sourcesContent":["import {\n setCallMethodTransport,\n defaultCallMethodTransport,\n type MethodArgs,\n} from '../client/method';\nimport { callInProcessMethod } from './callInProcess';\nimport { getSsrContext } from './context';\n\n/**\n * Routes `callMethod` through `runMethod` in-process during an active SSR\n * render. Outside a render (e.g. server-side `callMethod` from jobs or other\n * non-render code) there is no request context, so it falls back to the\n * default HTTP transport — installing SSR must not break those call sites.\n */\nexport function installSsrCallMethodTransport(): () => void {\n return setCallMethodTransport(async <T>(methodName: string, args: MethodArgs) => {\n const ssrCtx = getSsrContext();\n if (!ssrCtx) {\n return defaultCallMethodTransport<T>(methodName, args);\n }\n\n return callInProcessMethod<T>(methodName, args, ssrCtx.callContext);\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/ssr/transport.ts"],"names":["installSsrCallMethodTransport","setCallMethodTransport","methodName","args","ssrCtx","getSsrContext","callInProcessMethod","defaultCallMethodTransport"],"mappings":"4LAcO,SAASA,CAAAA,EAA4C,CAC1D,OAAOC,CAAAA,CAAuB,MAAUC,EAAoBC,CAAAA,GAAqB,CAC/E,IAAMC,CAAAA,CAASC,CAAAA,EAAc,CAC7B,OAAKD,CAAAA,CAIEE,CAAAA,CAAuBJ,CAAAA,CAAYC,CAAAA,CAAMC,CAAAA,CAAO,WAAW,CAAA,CAHzDG,CAAAA,CAA8BL,CAAAA,CAAYC,CAAI,CAIzD,CAAC,CACH","file":"transport-OSL4EWWD.js","sourcesContent":["import {\n setCallMethodTransport,\n defaultCallMethodTransport,\n type MethodArgs,\n} from '../client/method';\nimport { callInProcessMethod } from './callInProcess';\nimport { getSsrContext } from './context';\n\n/**\n * Routes `callMethod` through `runMethod` in-process during an active SSR\n * render. Outside a render (e.g. server-side `callMethod` from jobs or other\n * non-render code) there is no request context, so it falls back to the\n * default HTTP transport — installing SSR must not break those call sites.\n */\nexport function installSsrCallMethodTransport(): () => void {\n return setCallMethodTransport(async <T>(methodName: string, args: MethodArgs) => {\n const ssrCtx = getSsrContext();\n if (!ssrCtx) {\n return defaultCallMethodTransport<T>(methodName, args);\n }\n\n return callInProcessMethod<T>(methodName, args, ssrCtx.callContext);\n });\n}\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "modelence",
4
- "version": "0.23.0-setup.dev.1",
4
+ "version": "0.23.0-setup.dev.3",
5
5
  "description": "The Node.js Framework for Real-Time MongoDB Apps",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/global.d.ts",
@@ -23,6 +23,9 @@
23
23
  "bin": {
24
24
  "modelence": "./dist/bin/modelence.js"
25
25
  },
26
+ "engines": {
27
+ "node": ">=22"
28
+ },
26
29
  "scripts": {
27
30
  "build": "tsup",
28
31
  "dev": "tsup --watch",
@@ -1,3 +0,0 @@
1
- import {l,f as f$1,I as I$1,D,C as C$1,i,h as h$1,j as j$1,e}from'./chunk-MTG3OZWX.js';import {c}from'./chunk-5M6FUMUK.js';import {useState,useEffect}from'react';import {jsx,jsxs}from'react/jsx-runtime';import Y from'socket.io-client';import {hashKey,QueryClient,QueryClientProvider,HydrationBoundary}from'@tanstack/react-query';var a={page:{minHeight:"100vh",backgroundColor:"#f3f4f6",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 16px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",color:"#111827"},container:{maxWidth:"576px",width:"100%"},logoWrap:{display:"flex",justifyContent:"center",marginBottom:"32px"},title:{fontSize:"30px",lineHeight:"36px",fontWeight:700,textAlign:"center",margin:0},subtitle:{marginTop:"16px",color:"#4b5563",textAlign:"center"},steps:{marginTop:"32px",listStyle:"none",padding:0,display:"flex",flexDirection:"column",gap:"16px"},step:{display:"flex",gap:"16px",alignItems:"flex-start",backgroundColor:"#ffffff",borderRadius:"8px",border:"1px solid #e5e7eb",padding:"16px"},stepNumber:{flex:"none",width:"28px",height:"28px",borderRadius:"9999px",backgroundColor:"#111827",color:"#ffffff",fontSize:"14px",fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},stepText:{color:"#374151",lineHeight:"28px"},code:{fontSize:"14px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace",backgroundColor:"#e5e7eb",borderRadius:"4px",padding:"2px 4px"},footer:{marginTop:"32px",fontSize:"14px",color:"#6b7280",textAlign:"center"}};function Q(){return jsx("div",{style:a.page,children:jsxs("div",{style:a.container,children:[jsx("div",{style:a.logoWrap,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"80",height:"80",viewBox:"0 0 48 48",fill:"none","aria-label":"Modelence Logo",children:jsx("path",{fill:"#5509D9",d:"M45 22.788V12L24 0l-9.437 5.392L45 22.788ZM25.152 35.24l10.589 6.052 8.107-4.632-10.589-6.052-8.107 4.632Zm9.26-15.872v9.264L45 34.684V25.42l-10.589-6.052ZM3 25.212V36l21 12 9.441-5.392L3 25.212ZM22.848 12.76 12.26 6.708 4.152 11.34l10.589 6.052 8.107-4.632Zm-9.26 15.872v-9.264L3 13.316v9.264l10.589 6.052Z"})})}),jsx("h1",{style:a.title,children:"Connect this project to Modelence Cloud"}),jsx("p",{style:a.subtitle,children:"One quick step before you can use this app locally."}),jsxs("ol",{style:a.steps,children:[jsxs(T,{number:1,children:["Run ",jsx("code",{style:a.code,children:"npx modelence setup"})," in the project folder."]}),jsx(T,{number:2,children:"Your browser opens \u2014 log in and choose your environment."}),jsxs(T,{number:3,children:["Restart the dev server (",jsx("code",{style:a.code,children:"npm run dev"}),")."]})]}),jsx("p",{style:a.footer,children:"This page refreshes automatically once the project is connected."})]})})}function T({number:e,children:t}){return jsxs("li",{style:a.step,children:[jsx("span",{style:a.stepNumber,children:e}),jsx("span",{style:a.stepText,children:t})]})}var Z="__MODELENCE_STATE__",$=3e3,z=false;function V(){return typeof document<"u"&&document.getElementById(Z)!==null}function Se({children:e,loadingElement:t,setupElement:n}){let r=typeof window>"u",[i$1,c]=useState(()=>!r&&!l()&&!V()),[d,s]=useState(()=>!r&&l()&&f$1());return useEffect(()=>{async function l$1(){if(!z){if(z=true,l()){i()&&await h$1();return}await j$1(),s(f$1()),c(false);}}l$1();},[]),useEffect(()=>{if(!d)return;let l=setInterval(async()=>{try{let{setupRequired:o}=await I$1("_system.setupStatus",{},{errorHandler:()=>{}});o||window.location.reload();}catch{}},$);return ()=>clearInterval(l)},[d]),i$1?t??jsx("div",{children:"Loading..."}):d&&n!==null?n??jsx(Q,{}):e}var b=null,m=new Map;function h(){if(!b)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return b}function J(){let e=C$1(),t=D();for(let n of m.values())b?.emit("subscribeLiveQuery",{subscriptionId:n.subscriptionId,method:n.method,args:n.args,authToken:e,clientInfo:t});}function G(e$1){let t=e()?.baseUrl??"/";b=Y(t,{transports:["websocket"],auth:{token:C$1()}}),b.on("connect",()=>{m.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${m.size} live queries`),J());}),e$1.channels?.forEach(n=>n.init());}function X({category:e,listener:t}){h().on(e,t);}function ee({category:e,listener:t}){h().once(e,t);}function te({category:e,listener:t}){h().off(e,t);}function R({eventName:e,category:t,id:n}){h().emit(e,`${t}:${n}`);}function ne({category:e,id:t}){R({eventName:"joinChannel",category:e,id:t});}function re({category:e,id:t}){R({eventName:"leaveChannel",category:e,id:t});}var oe=0;function M(e,t,n,r){let i=`sub-${++oe}-${Date.now()}`,c$1=({subscriptionId:l,data:o,typeMap:y})=>{l===i&&n(c(o,y));},d=({subscriptionId:l,error:o})=>{l===i&&(console.error(`[Modelence] Live query error for ${e}:`,o),r?.(o));},s=h();return s.on("liveQueryData",c$1),s.on("liveQueryError",d),m.set(i,{subscriptionId:i,method:e,args:t}),s.connected&&s.emit("subscribeLiveQuery",{subscriptionId:i,method:e,args:t,authToken:C$1(),clientInfo:D()}),()=>{m.delete(i),s.emit("unsubscribeLiveQuery",{subscriptionId:i}),s.off("liveQueryData",c$1),s.off("liveQueryError",d);}}var ie={init:G,on:X,once:ee,off:te,emit:R,joinChannel:ne,leaveChannel:re},K=ie;var E=null;function O(e){E=e;}function Pe(){return E}function F(e){if(E){console.warn("WebSocket already initialized. Skipping initialization.");return}let t=e?.provider||K;O(t);try{t.init({channels:e?.channels});}catch(n){throw O(null),n}}var p=null,C=null,P=false,f=new Map;function I(e){p!==e&&(p&&se(),p=e,C=e.getQueryCache().subscribe(t=>{if(t.type==="removed"){let n=hashKey(t.query.queryKey),r=f.get(n);if(r){if(r.resolvers.size>0){let i=new Error("Query was removed from cache");r.resolvers.forEach(c=>c.reject(i)),r.resolvers.clear();}r.unsubscribe(),f.delete(n);}}}));}function Ne(){return p!==null}function se(){C&&(C(),C=null),f.forEach(e=>e.unsubscribe()),f.clear(),p=null,P=false;}var j=class{connect(t){I(t);}};function De(e,t={}){return {queryKey:[e,t],queryFn:()=>I$1(e,t)}}function qe(e,t={}){let n=["live",e,t],r=hashKey(n);return {queryKey:n,queryFn:()=>new Promise((i,c)=>{if(typeof window>"u")return;if(!p){let s=new Error("Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().");console.error("[Modelence]",s.message),c(s);return}P||(F(),P=true);let d=f.get(r);d||(d={unsubscribe:M(e,t,l=>{let o=f.get(r);o?.resolvers.size&&(o.resolvers.forEach(y=>y.resolve(l)),o.resolvers.clear()),p&&p.setQueryData(n,l);},l=>{let o=f.get(r);o&&(o.resolvers.size&&(o.resolvers.forEach(y=>y.reject(new Error(l))),o.resolvers.clear()),o.unsubscribe(),f.delete(r));}),resolvers:new Set},f.set(r,d)),d.resolvers.add({resolve:i,reject:c});}),staleTime:1/0,refetchOnWindowFocus:false,refetchOnMount:false,refetchOnReconnect:false,gcTime:0}}function ze(e,t={}){return {mutationFn:(n={})=>I$1(e,{...t,...n})}}function Ue(e,t={}){return [e,t]}var de="__MODELENCE_QUERY_STATE__";function fe(){if(typeof document>"u")return;let e=document.getElementById(de);if(!(!e||!e.textContent))try{return JSON.parse(e.textContent)}catch(t){console.error("Modelence: failed to parse SSR query state",t);return}}function Be({children:e,client:t,dehydratedState:n}){let[r]=useState(()=>{let c=t??new QueryClient({defaultOptions:{queries:{staleTime:6e4}}});return typeof window<"u"&&I(c),c}),i=n??fe();return jsx(QueryClientProvider,{client:r,children:jsx(HydrationBoundary,{state:i,children:e})})}
2
- export{Se as a,M as b,O as c,Pe as d,F as e,I as f,Ne as g,se as h,j as i,De as j,qe as k,ze as l,Ue as m,Be as n};//# sourceMappingURL=chunk-B7EXKTEZ.js.map
3
- //# sourceMappingURL=chunk-B7EXKTEZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/client/SetupScreen.tsx","../src/client/AppProvider.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/client/query.ts","../src/client/queryProvider.tsx"],"names":["styles","SetupScreen","jsx","jsxs","Step","number","children","SSR_STATE_SCRIPT_ID","SETUP_POLL_INTERVAL","isInitialized","hasServerRenderedMarkup","AppProvider","loadingElement","setupElement","isServer","isLoading","setIsLoading","useState","isSessionInitialized","needsSetup","setNeedsSetup","_isSetupRequired","useEffect","initConfig","_isReconciliationPending","reconcileSession","initSession","timer","setupRequired","callMethod","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","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":"yUAeA,IAAMA,CAAAA,CAA8C,CAClD,KAAM,CACJ,SAAA,CAAW,QACX,eAAA,CAAiB,SAAA,CACjB,OAAA,CAAS,MAAA,CACT,WAAY,QAAA,CACZ,cAAA,CAAgB,SAChB,OAAA,CAAS,QAAA,CACT,WACE,4FAAA,CACF,KAAA,CAAO,SACT,CAAA,CACA,UAAW,CACT,QAAA,CAAU,QACV,KAAA,CAAO,MACT,EACA,QAAA,CAAU,CACR,OAAA,CAAS,MAAA,CACT,eAAgB,QAAA,CAChB,YAAA,CAAc,MAChB,CAAA,CACA,KAAA,CAAO,CACL,QAAA,CAAU,MAAA,CACV,UAAA,CAAY,MAAA,CACZ,WAAY,GAAA,CACZ,SAAA,CAAW,SACX,MAAA,CAAQ,CACV,EACA,QAAA,CAAU,CACR,SAAA,CAAW,MAAA,CACX,MAAO,SAAA,CACP,SAAA,CAAW,QACb,CAAA,CACA,KAAA,CAAO,CACL,SAAA,CAAW,MAAA,CACX,SAAA,CAAW,MAAA,CACX,QAAS,CAAA,CACT,OAAA,CAAS,OACT,aAAA,CAAe,QAAA,CACf,IAAK,MACP,CAAA,CACA,IAAA,CAAM,CACJ,QAAS,MAAA,CACT,GAAA,CAAK,OACL,UAAA,CAAY,YAAA,CACZ,gBAAiB,SAAA,CACjB,YAAA,CAAc,KAAA,CACd,MAAA,CAAQ,oBACR,OAAA,CAAS,MACX,EACA,UAAA,CAAY,CACV,KAAM,MAAA,CACN,KAAA,CAAO,MAAA,CACP,MAAA,CAAQ,OACR,YAAA,CAAc,QAAA,CACd,gBAAiB,SAAA,CACjB,KAAA,CAAO,UACP,QAAA,CAAU,MAAA,CACV,UAA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AA,CAA4B,4BAElC,SAASC,EAAAA,EAAmD,CAC1D,GAAI,OAAO,QAAA,CAAa,GAAA,CACtB,OAGF,IAAMC,CAAAA,CAAO,SAAS,cAAA,CAAeF,EAAyB,EAC9D,GAAI,EAAA,CAACE,CAAAA,EAAQ,CAACA,EAAK,WAAA,CAAA,CAInB,GAAI,CACF,OAAO,IAAA,CAAK,MAAMA,CAAAA,CAAK,WAAW,CACpC,CAAA,MAASC,EAAG,CACV,OAAA,CAAQ,MAAM,4CAAA,CAA8CA,CAAC,EAC7D,MACF,CACF,CAQO,SAASC,GAAuB,CACrC,QAAA,CAAApG,EACA,MAAA,CAAAqG,CAAAA,CACA,gBAAAC,CACF,CAAA,CAAgC,CAC9B,GAAM,CAACC,CAAc,CAAA,CAAI5F,SAAS,IAAM,CACtC,IAAM6F,CAAAA,CACJH,CAAAA,EACA,IAAII,WAAAA,CAAY,CACd,cAAA,CAAgB,CACd,QAAS,CACP,SAAA,CAAW,GACb,CACF,CACF,CAAC,CAAA,CACH,OAAI,OAAO,MAAA,CAAW,KACpB9B,CAAAA,CAA4B6B,CAAE,EAEzBA,CACT,CAAC,CAAA,CAEKE,CAAAA,CAAQJ,GAAmBL,EAAAA,EAAoB,CAErD,OACErG,GAAAA,CAAC+G,mBAAAA,CAAA,CAAoB,MAAA,CAAQJ,CAAAA,CAC3B,QAAA,CAAA3G,GAAAA,CAACgH,kBAAA,CAAkB,KAAA,CAAOF,EAAQ,QAAA,CAAA1G,CAAAA,CAAS,EAC7C,CAEJ","file":"chunk-B7EXKTEZ.js","sourcesContent":["'use client';\n\nimport { ReactNode } from 'react';\n\n/*\n Shown by AppProvider instead of the app when a development server reports it\n has no backend at all — no Modelence Cloud connection and no local database\n (see server-side isSetupRequired). This is the state of every fresh clone:\n .modelence.env holds the environment's credentials and is gitignored, so it\n never travels with the repo.\n\n Styled inline: this renders inside arbitrary user apps, so it can't rely on\n any CSS framework being present.\n*/\n\nconst styles: Record<string, React.CSSProperties> = {\n page: {\n minHeight: '100vh',\n backgroundColor: '#f3f4f6',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: '0 16px',\n fontFamily:\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif\",\n color: '#111827',\n },\n container: {\n maxWidth: '576px',\n width: '100%',\n },\n logoWrap: {\n display: 'flex',\n justifyContent: 'center',\n marginBottom: '32px',\n },\n title: {\n fontSize: '30px',\n lineHeight: '36px',\n fontWeight: 700,\n textAlign: 'center',\n margin: 0,\n },\n subtitle: {\n marginTop: '16px',\n color: '#4b5563',\n textAlign: 'center',\n },\n steps: {\n marginTop: '32px',\n listStyle: 'none',\n padding: 0,\n display: 'flex',\n flexDirection: 'column',\n gap: '16px',\n },\n step: {\n display: 'flex',\n gap: '16px',\n alignItems: 'flex-start',\n backgroundColor: '#ffffff',\n borderRadius: '8px',\n border: '1px solid #e5e7eb',\n padding: '16px',\n },\n stepNumber: {\n flex: 'none',\n width: '28px',\n height: '28px',\n borderRadius: '9999px',\n backgroundColor: '#111827',\n color: '#ffffff',\n fontSize: '14px',\n fontWeight: 600,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n },\n stepText: {\n color: '#374151',\n lineHeight: '28px',\n },\n code: {\n fontSize: '14px',\n fontFamily: \"ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace\",\n backgroundColor: '#e5e7eb',\n borderRadius: '4px',\n padding: '2px 4px',\n },\n footer: {\n marginTop: '32px',\n fontSize: '14px',\n color: '#6b7280',\n textAlign: 'center',\n },\n};\n\nexport default function SetupScreen() {\n return (\n <div style={styles.page}>\n <div style={styles.container}>\n <div style={styles.logoWrap}>\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"80\"\n height=\"80\"\n viewBox=\"0 0 48 48\"\n fill=\"none\"\n aria-label=\"Modelence Logo\"\n >\n <path\n fill=\"#5509D9\"\n d=\"M45 22.788V12L24 0l-9.437 5.392L45 22.788ZM25.152 35.24l10.589 6.052 8.107-4.632-10.589-6.052-8.107 4.632Zm9.26-15.872v9.264L45 34.684V25.42l-10.589-6.052ZM3 25.212V36l21 12 9.441-5.392L3 25.212ZM22.848 12.76 12.26 6.708 4.152 11.34l10.589 6.052 8.107-4.632Zm-9.26 15.872v-9.264L3 13.316v9.264l10.589 6.052Z\"\n />\n </svg>\n </div>\n <h1 style={styles.title}>Connect this project to Modelence Cloud</h1>\n <p style={styles.subtitle}>One quick step before you can use this app locally.</p>\n\n <ol style={styles.steps}>\n <Step number={1}>\n Run <code style={styles.code}>npx modelence setup</code> in the project folder.\n </Step>\n <Step number={2}>Your browser opens &mdash; log in and choose your environment.</Step>\n <Step number={3}>\n Restart the dev server (<code style={styles.code}>npm run dev</code>).\n </Step>\n </ol>\n\n <p style={styles.footer}>\n This page refreshes automatically once the project is connected.\n </p>\n </div>\n </div>\n );\n}\n\nfunction Step({ number, children }: { number: number; children: ReactNode }) {\n return (\n <li style={styles.step}>\n <span style={styles.stepNumber}>{number}</span>\n <span style={styles.stepText}>{children}</span>\n </li>\n );\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 { useState, useEffect, ReactNode } from 'react';\nimport { callMethod } from './method';\nimport SetupScreen from './SetupScreen';\nimport {\n _isReconciliationPending,\n _isSetupRequired,\n initSession,\n isSessionInitialized,\n reconcileSession,\n} from './session';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\nconst SETUP_POLL_INTERVAL = 3000;\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n /*\n Replaces the built-in setup screen shown when a development server has no\n backend yet (see SetupScreen). Pass `null` to disable the screen entirely\n and render the app regardless.\n */\n setupElement?: 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, setupElement }: AppProviderProps) {\n const isServer = typeof window === 'undefined';\n const [isLoading, setIsLoading] = useState(\n () => !isServer && !isSessionInitialized() && !hasServerRenderedMarkup()\n );\n const [needsSetup, setNeedsSetup] = useState(\n () => !isServer && isSessionInitialized() && _isSetupRequired()\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 setNeedsSetup(_isSetupRequired());\n setIsLoading(false);\n }\n\n void initConfig();\n }, []);\n\n // While the setup screen is up, watch for the project getting connected\n // (setup writes .modelence.env and the user restarts the dev server) and\n // reload for a clean boot. Poll errors are expected mid-restart.\n useEffect(() => {\n if (!needsSetup) {\n return;\n }\n\n const timer = setInterval(async () => {\n try {\n const { setupRequired } = await callMethod<{ setupRequired: boolean }>(\n '_system.setupStatus',\n {},\n { errorHandler: () => {} }\n );\n if (!setupRequired) {\n window.location.reload();\n }\n } catch {\n // Dev server restarting — keep polling.\n }\n }, SETUP_POLL_INTERVAL);\n\n return () => clearInterval(timer);\n }, [needsSetup]);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n if (needsSetup && setupElement !== null) {\n return setupElement ?? <SetupScreen />;\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 { 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"]}