modelence 0.21.0-ml.dev.2 → 0.21.0-ml.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 (28) 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-T4G5RAOK.js → chunk-B5XMG3OE.js} +5 -5
  6. package/dist/{chunk-T4G5RAOK.js.map → chunk-B5XMG3OE.js.map} +1 -1
  7. package/dist/{chunk-7DT2YQTG.js → chunk-M24E3CAP.js} +3 -3
  8. package/dist/{chunk-7DT2YQTG.js.map → chunk-M24E3CAP.js.map} +1 -1
  9. package/dist/{chunk-GISIHWCC.js → chunk-RVUJ3U27.js} +2 -2
  10. package/dist/{chunk-GISIHWCC.js.map → chunk-RVUJ3U27.js.map} +1 -1
  11. package/dist/client.d.ts +10 -0
  12. package/dist/client.js +1 -1
  13. package/dist/{package-SYXH7HQF.js → package-PEWLDTN6.js} +2 -2
  14. package/dist/{package-SYXH7HQF.js.map → package-PEWLDTN6.js.map} +1 -1
  15. package/dist/{render-HDPCEI2O.js → render-UY7R4EKL.js} +2 -2
  16. package/dist/{render-HDPCEI2O.js.map → render-UY7R4EKL.js.map} +1 -1
  17. package/dist/renderApp-ZMIJGGAP.js +2 -0
  18. package/dist/{renderApp-Y3OJU4PO.js.map → renderApp-ZMIJGGAP.js.map} +1 -1
  19. package/dist/server-WW7YMRBB.js +2 -0
  20. package/dist/{server-WAXWRUOY.js.map → server-WW7YMRBB.js.map} +1 -1
  21. package/dist/server.js +1 -1
  22. package/dist/{transport-UBIBRQF5.js → transport-Q6Q42CSY.js} +2 -2
  23. package/dist/{transport-UBIBRQF5.js.map → transport-Q6Q42CSY.js.map} +1 -1
  24. package/package.json +1 -1
  25. package/dist/chunk-3RMUZGFT.js +0 -2
  26. package/dist/chunk-3RMUZGFT.js.map +0 -1
  27. package/dist/renderApp-Y3OJU4PO.js +0 -2
  28. package/dist/server-WAXWRUOY.js +0 -2
@@ -1,3 +1,3 @@
1
- var s="module",i="modelence",r="0.21.0-ml.dev.2",c="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",o="dist/global.d.ts",p={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],a={modelence:"./dist/bin/modelence.js"},l={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",bench:"tsx src/bench/index.ts",test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage",postversion:"git push && git push --tags",prepare:"cd ../.. && git config core.hooksPath .husky"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",v={"@tanstack/react-query":"^5.100.7","@types/archiver":"^6.0.3","@types/bcrypt":"^6.0.0","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-node":"^10.9.2",vitest:"^2.1.8","@vitest/coverage-v8":"^2.1.8","vite-tsconfig-paths":"^5.1.4"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^6.0.0",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.15.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={"@tanstack/react-query":">=5.0.0",react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:r,description:c,main:n,types:o,exports:p,files:d,bin:a,scripts:l,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:v,dependencies:x,peerDependencies:j};
2
- export{s as a,i as b,r as c,c as d,n as e,o as f,p as g,d as h,a as i,l as j,m as k,y as l,u as m,g as n,h as o,v as p,x as q,j as r,b as s};//# sourceMappingURL=chunk-7DT2YQTG.js.map
3
- //# sourceMappingURL=chunk-7DT2YQTG.js.map
1
+ var s="module",i="modelence",r="0.21.0-ml.dev.3",c="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",o="dist/global.d.ts",p={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],a={modelence:"./dist/bin/modelence.js"},l={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",bench:"tsx src/bench/index.ts",test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage",postversion:"git push && git push --tags",prepare:"cd ../.. && git config core.hooksPath .husky"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",v={"@tanstack/react-query":"^5.100.7","@types/archiver":"^6.0.3","@types/bcrypt":"^6.0.0","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-node":"^10.9.2",vitest:"^2.1.8","@vitest/coverage-v8":"^2.1.8","vite-tsconfig-paths":"^5.1.4"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^6.0.0",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.15.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={"@tanstack/react-query":">=5.0.0",react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:r,description:c,main:n,types:o,exports:p,files:d,bin:a,scripts:l,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:v,dependencies:x,peerDependencies:j};
2
+ export{s as a,i as b,r as c,c as d,n as e,o as f,p as g,d as h,a as i,l as j,m as k,y as l,u as m,g as n,h as o,v as p,x as q,j as r,b as s};//# sourceMappingURL=chunk-M24E3CAP.js.map
3
+ //# sourceMappingURL=chunk-M24E3CAP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,iBAAA,CACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,KAAA,CAAS,mBAAA,CACT,QAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,IAAA,CAAQ,iCAAA,CACR,YAAA,CAAc,2BAAA,CACd,cAAA,CAAkB,eAAA,CAClB,MAAS,wBAAA,CACT,IAAA,CAAQ,YAAA,CACR,YAAA,CAAc,QAAA,CACd,eAAA,CAAiB,uBAAA,CACjB,WAAA,CAAe,6BAAA,CACf,OAAA,CAAW,8CACb,CAAA,CAIAC,CAAAA,CAAc,CACZ,KAAQ,KAAA,CACR,GAAA,CAAO,gDACT,CAAA,CACAC,CAAAA,CAAU,WAAA,CACVC,CAAAA,CAAW,w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A,CACAC,CAAAA,CAAoB,CAClB,uBAAA,CAAyB,SAAA,CACzB,KAAA,CAAS,UAAA,CACT,WAAA,CAAa,UACf,CAAA,CA3GFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAeA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAwBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAKF","file":"chunk-7DT2YQTG.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.21.0-ml.dev.2\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"bench\": \"tsx src/bench/index.ts\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"postversion\": \"git push && git push --tags\",\n \"prepare\": \"cd ../.. && git config core.hooksPath .husky\"\n },\n \"lint-staged\": {\n \"src/**/*.{ts,tsx,js,jsx,json,css,md}\": \"prettier --write\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@tanstack/react-query\": \"^5.100.7\",\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^6.0.0\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"husky\": \"^9.1.7\",\n \"lint-staged\": \"^16.2.7\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-node\": \"^10.9.2\",\n \"vitest\": \"^2.1.8\",\n \"@vitest/coverage-v8\": \"^2.1.8\",\n \"vite-tsconfig-paths\": \"^5.1.4\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^6.0.0\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.15.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"@tanstack/react-query\": \">=5.0.0\",\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
1
+ {"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,iBAAA,CACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,KAAA,CAAS,mBAAA,CACT,QAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CA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ACb,eAAA,CAAiB,SACjB,MAAA,CAAU,SAAA,CACV,kBAAA,CAAoB,SAAA,CACpB,OAAA,CAAW,SAAA,CACX,UAAA,CAAY,SAAA,CACZ,IAAA,CAAQ,QAAA,CACR,OAAA,CAAW,QAAA,CACX,IAAA,CAAQ,SAAA,CACR,YAAa,QAAA,CACb,kBAAA,CAAoB,QAAA,CACpB,IAAA,CAAQ,QAAA,CACR,GAAA,CAAO,SAAA,CACP,UAAA,CAAc,QAAA,CACd,IAAA,CAAQ,QAAA,CACR,oBAAA,CAAsB,QAAA,CACtB,OAAA,CAAW,UACX,uBAAA,CAAyB,SAAA,CACzB,GAAA,CAAO,SAAA,CACP,OAAA,CAAW,QACb,CAAA,CACAC,CAAAA,CAAoB,CAClB,uBAAA,CAAyB,SAAA,CACzB,KAAA,CAAS,UAAA,CACT,WAAA,CAAa,UACf,CAAA,CA3GFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAeA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAwBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAKF","file":"chunk-M24E3CAP.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.21.0-ml.dev.3\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"bench\": \"tsx src/bench/index.ts\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"postversion\": \"git push && git push --tags\",\n \"prepare\": \"cd ../.. && git config core.hooksPath .husky\"\n },\n \"lint-staged\": {\n \"src/**/*.{ts,tsx,js,jsx,json,css,md}\": \"prettier --write\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@tanstack/react-query\": \"^5.100.7\",\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^6.0.0\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"husky\": \"^9.1.7\",\n \"lint-staged\": \"^16.2.7\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-node\": \"^10.9.2\",\n \"vitest\": \"^2.1.8\",\n \"@vitest/coverage-v8\": \"^2.1.8\",\n \"vite-tsconfig-paths\": \"^5.1.4\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^6.0.0\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.15.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"@tanstack/react-query\": \">=5.0.0\",\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- import {a,d,g,n}from'./chunk-5UXY2NRZ.js';import {w,y,s,z,D}from'./chunk-3RMUZGFT.js';import A from'react';import E from'react-dom/client';import {jsx}from'react/jsx-runtime';function c(t){return {getConfig(e){return y(`${t}.${e}`)},query(e,...r){let o=r[0]??{};return {queryKey:[t,e,o],queryFn:()=>w(`${t}.${e}`,o)}},mutation(e){return {mutationFn:r=>w(`${t}.${e}`,r)}},infiniteQuery(e,r){return {queryKey:[t,e,"infinite",r(void 0)],initialPageParam:void 0,queryFn:({pageParam:o})=>w(`${t}.${e}`,r(o))}}}}var _=c("_system");var u=class{constructor(e,r){this.category=e,this.onMessage=r;}init(){d()?.on({category:this.category,listener:this.onMessage});}joinChannel(e){d()?.joinChannel({category:this.category,id:e});}leaveChannel(e){d()?.leaveChannel({category:this.category,id:e});}};var C="useClient"in A?A.useClient(a):a;var K="__MODELENCE_STATE__";function Q(){return typeof document>"u"?false:document.getElementById(K)!==null}function W(){if(typeof document>"u")return null;let t=document.getElementById(K);if(!t)return null;try{return JSON.parse(t.textContent??"")}catch(e){return console.error("Modelence: failed to parse SSR state",e),null}}var v="__modelence_ssr_snapshot__";function H(t){globalThis[v]=t;}function De(){return globalThis[v]??null}function q(t){if(typeof window>"u"){H(t);return}let{loadingElement:e,routesElement:r,favicon:o,errorHandler:f,router:y}=t;f&&s(f),window.addEventListener("unload",()=>{});let k=Q(),g$1=W();g$1?.session&&(z(g$1.session),D());let m=document.getElementById("root"),b=window.location.pathname+window.location.search,h=y?y({children:r,location:b}):r,O=g()?h:jsx(n,{children:h}),M=jsx(A.StrictMode,{children:jsx(C,{loadingElement:e,children:O})});if(k?E.hydrateRoot(m,M):E.createRoot(m).render(M),o){let T=document.querySelector("link[rel~='icon']");if(T)T.href=o;else {let s=document.createElement("link");s.rel="icon",s.href=o,document.head.appendChild(s);}}}export{c as a,_ as b,De as c,q as d,u as e,C as f};//# sourceMappingURL=chunk-GISIHWCC.js.map
2
- //# sourceMappingURL=chunk-GISIHWCC.js.map
1
+ import {a,d,g,n}from'./chunk-76I5SXWM.js';import {w,y,s,z,D}from'./chunk-54MUUAZG.js';import A from'react';import E from'react-dom/client';import {jsx}from'react/jsx-runtime';function c(t){return {getConfig(e){return y(`${t}.${e}`)},query(e,...r){let o=r[0]??{};return {queryKey:[t,e,o],queryFn:()=>w(`${t}.${e}`,o)}},mutation(e){return {mutationFn:r=>w(`${t}.${e}`,r)}},infiniteQuery(e,r){return {queryKey:[t,e,"infinite",r(void 0)],initialPageParam:void 0,queryFn:({pageParam:o})=>w(`${t}.${e}`,r(o))}}}}var _=c("_system");var u=class{constructor(e,r){this.category=e,this.onMessage=r;}init(){d()?.on({category:this.category,listener:this.onMessage});}joinChannel(e){d()?.joinChannel({category:this.category,id:e});}leaveChannel(e){d()?.leaveChannel({category:this.category,id:e});}};var C="useClient"in A?A.useClient(a):a;var K="__MODELENCE_STATE__";function Q(){return typeof document>"u"?false:document.getElementById(K)!==null}function W(){if(typeof document>"u")return null;let t=document.getElementById(K);if(!t)return null;try{return JSON.parse(t.textContent??"")}catch(e){return console.error("Modelence: failed to parse SSR state",e),null}}var v="__modelence_ssr_snapshot__";function H(t){globalThis[v]=t;}function De(){return globalThis[v]??null}function q(t){if(typeof window>"u"){H(t);return}let{loadingElement:e,routesElement:r,favicon:o,errorHandler:f,router:y}=t;f&&s(f),window.addEventListener("unload",()=>{});let k=Q(),g$1=W();g$1?.session&&(z(g$1.session),D());let m=document.getElementById("root"),b=window.location.pathname+window.location.search,h=y?y({children:r,location:b}):r,O=g()?h:jsx(n,{children:h}),M=jsx(A.StrictMode,{children:jsx(C,{loadingElement:e,children:O})});if(k?E.hydrateRoot(m,M):E.createRoot(m).render(M),o){let T=document.querySelector("link[rel~='icon']");if(T)T.href=o;else {let s=document.createElement("link");s.rel="icon",s.href=o,document.head.appendChild(s);}}}export{c as a,_ as b,De as c,q as d,u as e,C as f};//# sourceMappingURL=chunk-RVUJ3U27.js.map
2
+ //# sourceMappingURL=chunk-RVUJ3U27.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/module.ts","../src/system/client.ts","../src/websocket/clientChannel.ts","../src/client.ts","../src/client/renderApp.tsx"],"names":["createClientModule","moduleName","key","getConfig","name","rest","args","callMethod","getArgs","pageParam","systemConfig","ClientChannel","category","onMessage","getWebsocketClientProvider","id","AppProvider","React","SSR_STATE_SCRIPT_ID","hasSsrMarker","readSsrState","node","SNAPSHOT_KEY","setSnapshot","snapshot","_getSsrSnapshot","renderApp","options","loadingElement","routesElement","favicon","errorHandler","router","setErrorHandler","isHydrating","ssrState","hydrateSession","startSessionHeartbeat","container","location","routedTree","appTree","hasConnectedQueryClient","jsx","ModelenceQueryProvider","tree","ReactDOM","link","newLink"],"mappings":"+KAuFO,SAASA,CAAAA,CAA8CC,CAAAA,CAAoB,CAChF,OAAO,CACL,UACEC,CAAAA,CACqD,CAErD,OAAOC,CAAAA,CAAiB,CAAA,EAAGF,CAAU,CAAA,CAAA,EAAIC,CAAG,CAAA,CAAE,CAChD,CAAA,CAEA,KAAA,CACEE,KACGC,CAAAA,CAGH,CACA,IAAMC,CAAAA,CAAQD,CAAAA,CAAK,CAAC,CAAA,EAAK,EAAC,CAC1B,OAAO,CACL,QAAA,CAAU,CAACJ,CAAAA,CAAYG,CAAAA,CAAME,CAAI,CAAA,CACjC,OAAA,CAAS,IACPC,CAAAA,CACE,CAAA,EAAGN,CAAU,IAAIG,CAAI,CAAA,CAAA,CACrBE,CACF,CACJ,CACF,EAEA,QAAA,CAAwDF,CAAAA,CAAS,CAC/D,OAAO,CACL,UAAA,CACEE,GAEAC,CAAAA,CACE,CAAA,EAAGN,CAAU,CAAA,CAAA,EAAIG,CAAI,GACrBE,CACF,CACJ,CACF,CAAA,CAUA,aAAA,CACEF,CAAAA,CACAI,EACA,CACA,OAAO,CACL,QAAA,CAAU,CAACP,EAAYG,CAAAA,CAAM,UAAA,CAAYI,CAAAA,CAAQ,MAAS,CAAC,CAAA,CAE3D,iBAAkB,MAAA,CAClB,OAAA,CAAS,CAAC,CACR,SAAA,CAAAC,CACF,IAGEF,CAAAA,CACE,CAAA,EAAGN,CAAU,CAAA,CAAA,EAAIG,CAAI,CAAA,CAAA,CACrBI,EAAQC,C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AA,CAAQ,EACxD,CAAA,CASF,GANIP,EACFY,CAAAA,CAAS,WAAA,CAAYR,CAAAA,CAAWO,CAAI,CAAA,CAEpCC,CAAAA,CAAS,WAAWR,CAAS,CAAA,CAAE,OAAOO,CAAI,CAAA,CAGxCf,EAAS,CACX,IAAMiB,CAAAA,CAAO,QAAA,CAAS,aAAA,CAAc,mBAAmB,EACvD,GAAKA,CAAAA,CAMHA,EAAK,IAAA,CAAOjB,CAAAA,CAAAA,KANH,CACT,IAAMkB,CAAAA,CAAU,QAAA,CAAS,aAAA,CAAc,MAAM,CAAA,CAC7CA,EAAQ,GAAA,CAAM,MAAA,CACdA,CAAAA,CAAQ,IAAA,CAAOlB,CAAAA,CACf,QAAA,CAAS,KAAK,WAAA,CAAYkB,CAAO,EACnC,CAGF,CACF","file":"chunk-GISIHWCC.js","sourcesContent":["'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { ModelenceQueryProvider } from './client/queryProvider';\nexport {\n modelenceQuery,\n modelenceLiveQuery,\n modelenceMutation,\n createQueryKey,\n connectModelenceQueryClient,\n disconnectModelenceQueryClient,\n ModelenceQueryClient,\n type ModelenceQueryKey,\n} from './client/query';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n sendMagicLink,\n loginWithMagicLink,\n loginWithOneTimeCode,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\nimport { hydrateSession, startSessionHeartbeat, type SessionInitPayload } from './session';\nimport { ModelenceQueryProvider } from './queryProvider';\nimport { hasConnectedQueryClient } from './query';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ntype SsrState = {\n session?: SessionInitPayload;\n};\n\nfunction hasSsrMarker(): boolean {\n if (typeof document === 'undefined') {\n return false;\n }\n return document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nfunction readSsrState(): SsrState | null {\n if (typeof document === 'undefined') {\n return null;\n }\n\n const node = document.getElementById(SSR_STATE_SCRIPT_ID);\n if (!node) {\n return null;\n }\n\n try {\n return JSON.parse(node.textContent ?? '') as SsrState;\n } catch (e) {\n // Caller must still hydrate (marker presence drives that, not parsed payload).\n console.error('Modelence: failed to parse SSR state', e);\n return null;\n }\n}\n\nexport type SsrRouter = (props: {\n children: React.ReactNode;\n location?: string;\n}) => React.ReactElement;\n\nexport interface RenderAppOptions {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n router?: SsrRouter;\n}\n\n// Shared via globalThis: ssrLoadModule loads the user's entry in a separate\n// module graph from the framework runtime.\nconst SNAPSHOT_KEY = '__modelence_ssr_snapshot__';\n\ntype GlobalWithSnapshot = typeof globalThis & {\n [SNAPSHOT_KEY]?: RenderAppOptions | null;\n};\n\nfunction setSnapshot(snapshot: RenderAppOptions | null) {\n (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] = snapshot;\n}\n\n/** @internal Used by the SSR runtime after evaluating the user's entry. */\nexport function _getSsrSnapshot(): RenderAppOptions | null {\n return (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] ?? null;\n}\n\nexport function renderApp(options: RenderAppOptions) {\n if (typeof window === 'undefined') {\n setSnapshot(options);\n return;\n }\n\n const { loadingElement, routesElement, favicon, errorHandler, router } = options;\n\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n // Empty 'unload' handler prevents bfcache in most browsers.\n window.addEventListener('unload', () => {});\n\n // Hydrate session BEFORE building the tree so `isSessionInitialized()` is\n // true on the first render and matches the server output. Hydration mode\n // tracks marker presence (not parse success): a parse failure still leaves\n // server-rendered DOM that must be hydrated, not replaced.\n const isHydrating = hasSsrMarker();\n const ssrState = readSsrState();\n if (ssrState?.session) {\n hydrateSession(ssrState.session);\n // Fire-and-forget: the heartbeat loop runs in the background.\n void startSessionHeartbeat();\n }\n\n const container = document.getElementById('root')!;\n // Pass the same location the server used (req.originalUrl == path + search;\n // the hash is never sent to the server) so a location-driven router (e.g. a\n // static router) resolves the same route on hydration as it did during SSR,\n // avoiding hydration mismatches.\n const location = window.location.pathname + window.location.search;\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n\n // If the app already connected its own QueryClient (the documented\n // bring-your-own-provider pattern connects before calling renderApp), don't\n // inject ours. A second provider would shadow the user's client: useQuery\n // would read the inner client while live-query updates write to the outer\n // one, so real-time queries would never update.\n const appTree = hasConnectedQueryClient() ? (\n routedTree\n ) : (\n <ModelenceQueryProvider>{routedTree}</ModelenceQueryProvider>\n );\n\n const tree = (\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{appTree}</AppProvider>\n </React.StrictMode>\n );\n\n if (isHydrating) {\n ReactDOM.hydrateRoot(container, tree);\n } else {\n ReactDOM.createRoot(container).render(tree);\n }\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/client/module.ts","../src/system/client.ts","../src/websocket/clientChannel.ts","../src/client.ts","../src/client/renderApp.tsx"],"names":["createClientModule","moduleName","key","getConfig","name","rest","args","callMethod","getArgs","pageParam","systemConfig","ClientChannel","category","onMessage","getWebsocketClientProvider","id","AppProvider","React","SSR_STATE_SCRIPT_ID","hasSsrMarker","readSsrState","node","SNAPSHOT_KEY","setSnapshot","snapshot","_getSsrSnapshot","renderApp","options","loadingElement","routesElement","favicon","errorHandler","router","setErrorHandler","isHydrating","ssrState","hydrateSession","startSessionHeartbeat","container","location","routedTree","appTree","hasConnectedQueryClient","jsx","ModelenceQueryProvider","tree","ReactDOM","link","newLink"],"mappings":"+KAuFO,SAASA,CAAAA,CAA8CC,CAAAA,CAAoB,CAChF,OAAO,CACL,UACEC,CAAAA,CACqD,CAErD,OAAOC,CAAAA,CAAiB,CAAA,EAAGF,CAAU,CAAA,CAAA,EAAIC,CAAG,CAAA,CAAE,CAChD,CAAA,CAEA,KAAA,CACEE,KACGC,CAAAA,CAGH,CACA,IAAMC,CAAAA,CAAQD,CAAAA,CAAK,CAAC,CAAA,EAAK,EAAC,CAC1B,OAAO,CACL,QAAA,CAAU,CAACJ,CAAAA,CAAYG,CAAAA,CAAME,CAAI,CAAA,CACjC,OAAA,CAAS,IACPC,CAAAA,CACE,CAAA,EAAGN,CAAU,IAAIG,CAAI,CAAA,CAAA,CACrBE,CACF,CACJ,CACF,EAEA,QAAA,CAAwDF,CAAAA,CAAS,CAC/D,OAAO,CACL,UAAA,CACEE,GAEAC,CAAAA,CACE,CAAA,EAAGN,CAAU,CAAA,CAAA,EAAIG,CAAI,GACrBE,CACF,CACJ,CACF,CAAA,CAUA,aAAA,CACEF,CAAAA,CACAI,EACA,CACA,OAAO,CACL,QAAA,CAAU,CAACP,EAAYG,CAAAA,CAAM,UAAA,CAAYI,CAAAA,CAAQ,MAAS,CAAC,CAAA,CAE3D,iBAAkB,MAAA,CAClB,OAAA,CAAS,CAAC,CACR,SAAA,CAAAC,CACF,IAGEF,CAAAA,CACE,CAAA,EAAGN,CAAU,CAAA,CAAA,EAAIG,CAAI,CAAA,CAAA,CACrBI,EAAQC,CAAS,CACnB,CACJ,CACF,CACF,CACF,CCtJO,IAAMC,CAAAA,CAAeV,CAAAA,CAAwC,SAAS,MCDhEW,CAAAA,CAAN,KAAiC,CAItC,WAAA,CAAYC,CAAAA,CAAkBC,EAA8B,CAC1D,IAAA,CAAK,QAAA,CAAWD,CAAAA,CAChB,IAAA,CAAK,SAAA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AA,CAAc,mBAAmB,EACvD,GAAKA,CAAAA,CAMHA,EAAK,IAAA,CAAOjB,CAAAA,CAAAA,KANH,CACT,IAAMkB,CAAAA,CAAU,QAAA,CAAS,aAAA,CAAc,MAAM,CAAA,CAC7CA,EAAQ,GAAA,CAAM,MAAA,CACdA,CAAAA,CAAQ,IAAA,CAAOlB,CAAAA,CACf,QAAA,CAAS,KAAK,WAAA,CAAYkB,CAAO,EACnC,CAGF,CACF","file":"chunk-RVUJ3U27.js","sourcesContent":["'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { ModelenceQueryProvider } from './client/queryProvider';\nexport {\n modelenceQuery,\n modelenceLiveQuery,\n modelenceMutation,\n createQueryKey,\n connectModelenceQueryClient,\n disconnectModelenceQueryClient,\n ModelenceQueryClient,\n type ModelenceQueryKey,\n} from './client/query';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n sendMagicLink,\n loginWithMagicLink,\n loginWithOneTimeCode,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\nimport { hydrateSession, startSessionHeartbeat, type SessionInitPayload } from './session';\nimport { ModelenceQueryProvider } from './queryProvider';\nimport { hasConnectedQueryClient } from './query';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ntype SsrState = {\n session?: SessionInitPayload;\n};\n\nfunction hasSsrMarker(): boolean {\n if (typeof document === 'undefined') {\n return false;\n }\n return document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nfunction readSsrState(): SsrState | null {\n if (typeof document === 'undefined') {\n return null;\n }\n\n const node = document.getElementById(SSR_STATE_SCRIPT_ID);\n if (!node) {\n return null;\n }\n\n try {\n return JSON.parse(node.textContent ?? '') as SsrState;\n } catch (e) {\n // Caller must still hydrate (marker presence drives that, not parsed payload).\n console.error('Modelence: failed to parse SSR state', e);\n return null;\n }\n}\n\nexport type SsrRouter = (props: {\n children: React.ReactNode;\n location?: string;\n}) => React.ReactElement;\n\nexport interface RenderAppOptions {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n router?: SsrRouter;\n}\n\n// Shared via globalThis: ssrLoadModule loads the user's entry in a separate\n// module graph from the framework runtime.\nconst SNAPSHOT_KEY = '__modelence_ssr_snapshot__';\n\ntype GlobalWithSnapshot = typeof globalThis & {\n [SNAPSHOT_KEY]?: RenderAppOptions | null;\n};\n\nfunction setSnapshot(snapshot: RenderAppOptions | null) {\n (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] = snapshot;\n}\n\n/** @internal Used by the SSR runtime after evaluating the user's entry. */\nexport function _getSsrSnapshot(): RenderAppOptions | null {\n return (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] ?? null;\n}\n\nexport function renderApp(options: RenderAppOptions) {\n if (typeof window === 'undefined') {\n setSnapshot(options);\n return;\n }\n\n const { loadingElement, routesElement, favicon, errorHandler, router } = options;\n\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n // Empty 'unload' handler prevents bfcache in most browsers.\n window.addEventListener('unload', () => {});\n\n // Hydrate session BEFORE building the tree so `isSessionInitialized()` is\n // true on the first render and matches the server output. Hydration mode\n // tracks marker presence (not parse success): a parse failure still leaves\n // server-rendered DOM that must be hydrated, not replaced.\n const isHydrating = hasSsrMarker();\n const ssrState = readSsrState();\n if (ssrState?.session) {\n hydrateSession(ssrState.session);\n // Fire-and-forget: the heartbeat loop runs in the background.\n void startSessionHeartbeat();\n }\n\n const container = document.getElementById('root')!;\n // Pass the same location the server used (req.originalUrl == path + search;\n // the hash is never sent to the server) so a location-driven router (e.g. a\n // static router) resolves the same route on hydration as it did during SSR,\n // avoiding hydration mismatches.\n const location = window.location.pathname + window.location.search;\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n\n // If the app already connected its own QueryClient (the documented\n // bring-your-own-provider pattern connects before calling renderApp), don't\n // inject ours. A second provider would shadow the user's client: useQuery\n // would read the inner client while live-query updates write to the outer\n // one, so real-time queries would never update.\n const appTree = hasConnectedQueryClient() ? (\n routedTree\n ) : (\n <ModelenceQueryProvider>{routedTree}</ModelenceQueryProvider>\n );\n\n const tree = (\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{appTree}</AppProvider>\n </React.StrictMode>\n );\n\n if (isHydrating) {\n ReactDOM.hydrateRoot(container, tree);\n } else {\n ReactDOM.createRoot(container).render(tree);\n }\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n"]}
package/dist/client.d.ts CHANGED
@@ -17,6 +17,16 @@ interface ClientConfig {
17
17
  * Defaults to `window.location.href` when not provided.
18
18
  */
19
19
  openUrl?: (url: string) => void;
20
+ /**
21
+ * Credentials mode for method-call requests. Defaults to `'include'`, which
22
+ * browser apps need for the cookie-based flows (password reset, magic link).
23
+ *
24
+ * Clients configured with token-in-body auth (React Native / Expo) never use
25
+ * cookies, so set `'omit'` there — on Expo Web a credentialed cross-origin
26
+ * request is otherwise blocked by any server answering
27
+ * `Access-Control-Allow-Origin: *`, surfacing as "TypeError: Failed to fetch".
28
+ */
29
+ credentials?: RequestCredentials;
20
30
  }
21
31
  /**
22
32
  * Configure the Modelence client for non-browser environments like React Native.
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-GISIHWCC.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-5UXY2NRZ.js';export{t as MethodError,w as callMethod,b as configureClient,y as getConfig,a as getLocalStorageSession,o as linkOAuthProvider,l as loginWithMagicLink,m as loginWithOneTimeCode,e as loginWithPassword,i as logout,h as resendEmailVerification,n as resetPassword,k as sendMagicLink,j as sendResetPasswordToken,d as signupWithPassword,p as unlinkOAuthProvider,f as updateProfile,H as useSession,g as verifyEmail}from'./chunk-3RMUZGFT.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-RVUJ3U27.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-76I5SXWM.js';export{t as MethodError,w as callMethod,b as configureClient,y as getConfig,a as getLocalStorageSession,o as linkOAuthProvider,l as loginWithMagicLink,m as loginWithOneTimeCode,e as loginWithPassword,i as logout,h as resendEmailVerification,n as resetPassword,k as sendMagicLink,j as sendResetPasswordToken,d as signupWithPassword,p as unlinkOAuthProvider,f as updateProfile,H as useSession,g as verifyEmail}from'./chunk-54MUUAZG.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=client.js.map
2
2
  //# sourceMappingURL=client.js.map
@@ -1,2 +1,2 @@
1
- export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-7DT2YQTG.js';//# sourceMappingURL=package-SYXH7HQF.js.map
2
- //# sourceMappingURL=package-SYXH7HQF.js.map
1
+ export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-M24E3CAP.js';//# sourceMappingURL=package-PEWLDTN6.js.map
2
+ //# sourceMappingURL=package-PEWLDTN6.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-SYXH7HQF.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-PEWLDTN6.js"}
@@ -1,2 +1,2 @@
1
- import {a,b,c}from'./chunk-P2W2XOKE.js';import'./chunk-LVB7YU4P.js';import'./chunk-ENHGU3X4.js';import {a as a$1,n}from'./chunk-5UXY2NRZ.js';import {F,x,G}from'./chunk-3RMUZGFT.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?G(r.session.user):null},M=r=>{let o=c();if(o)return o.session.configs[r]?.value};function D(){F(J),x(M);}async function X(r){let{callContext:o,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let i=await a("_system.session.init",{},o),n$1=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:n$1,children:O})}),l=null;await new Promise((s,d)=>{b({callContext:o,queryClient:n$1,session:{user:i.user,configs:i.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){l=e,E?.(),s(e);},onShellError(t){d(t);},onError(t){b$1?.(t);}});return e});});let a$2=null,_=s=>new Promise((d,e)=>{if(!l){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(m,c,I){s.write(m,N=>I(N??void 0));},final(m){try{let c=dehydrate(n$1);a$2=JSON.stringify(c);}finally{n$1.clear();}m(),d();}});t.on("error",e),s.on("error",e),l.pipe(t);});return {sessionState:JSON.stringify({session:i}),pipe:_,getQueryState:()=>{if(a$2===null)throw new Error("getQueryState() called before stream finished");return a$2}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-HDPCEI2O.js.map
2
- //# sourceMappingURL=render-HDPCEI2O.js.map
1
+ import {a,b,c}from'./chunk-P2W2XOKE.js';import'./chunk-LVB7YU4P.js';import'./chunk-ENHGU3X4.js';import {a as a$1,n}from'./chunk-76I5SXWM.js';import {F,x,G}from'./chunk-54MUUAZG.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?G(r.session.user):null},M=r=>{let o=c();if(o)return o.session.configs[r]?.value};function D(){F(J),x(M);}async function X(r){let{callContext:o,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let i=await a("_system.session.init",{},o),n$1=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:n$1,children:O})}),l=null;await new Promise((s,d)=>{b({callContext:o,queryClient:n$1,session:{user:i.user,configs:i.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){l=e,E?.(),s(e);},onShellError(t){d(t);},onError(t){b$1?.(t);}});return e});});let a$2=null,_=s=>new Promise((d,e)=>{if(!l){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(m,c,I){s.write(m,N=>I(N??void 0));},final(m){try{let c=dehydrate(n$1);a$2=JSON.stringify(c);}finally{n$1.clear();}m(),d();}});t.on("error",e),s.on("error",e),l.pipe(t);});return {sessionState:JSON.stringify({session:i}),pipe:_,getQueryState:()=>{if(a$2===null)throw new Error("getQueryState() called before stream finished");return a$2}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-UY7R4EKL.js.map
2
+ //# sourceMappingURL=render-UY7R4EKL.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":"+ZAkBA,IAAMA,CAAAA,CAAkB,IAAM,CAC5B,IAAMC,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,OAAKD,CAAAA,CAGEE,CAAAA,CAAkBF,CAAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,CAFhC,IAGX,CAAA,CAEMG,CAAAA,CAAkBC,GAAmB,CACzC,IAAMJ,CAAAA,CAAMC,CAAAA,GACZ,GAAKD,CAAAA,CAGL,OAAOA,CAAAA,CAAI,QAAQ,OAAA,CAAQI,CAAG,CAAA,EAAG,KACnC,EAEA,SAASC,CAAAA,EAA8B,CACrCC,CAAAA,CAAuBP,CAAe,CAAA,CACtCQ,CAAAA,CAAsBJ,CAAc,EACtC,CA0BA,eAAsBK,CAAAA,CAAoBC,CAAAA,CAAqD,CAC7F,GAAM,CAAE,WAAA,CAAAC,CAAAA,CAAa,cAAA,CAAAC,EAAgB,aAAA,CAAAC,CAAAA,CAAe,MAAA,CAAAC,CAAAA,CAAQ,SAAAC,CAAAA,CAAU,YAAA,CAAAC,CAAAA,CAAc,OAAA,CAAAC,GAAQ,CAAA,CAC1FP,CA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AAI,OAAA,CAAQ,CAACR,CAAAA,CAASC,CAAAA,GAAW,CACtC,GAAI,CAACF,CAAAA,CAAW,CACdE,CAAAA,CAAO,IAAI,MAAM,gCAAgC,CAAC,CAAA,CAClD,MACF,CAKA,IAAMQ,CAAAA,CAAc,IAAIC,QAAAA,CAAS,CAC/B,KAAA,CAAMC,CAAAA,CAAOC,CAAAA,CAAWC,CAAAA,CAAU,CAChCL,CAAAA,CAAY,KAAA,CAAMG,CAAAA,CAAQG,CAAAA,EAAQD,EAASC,CAAAA,EAAO,MAAS,CAAC,EAC9D,EACA,KAAA,CAAMD,CAAAA,CAAU,CACd,GAAI,CACF,IAAME,CAAAA,CAAmCC,SAAAA,CAAUxB,GAAW,EAC9Dc,GAAAA,CAAiB,IAAA,CAAK,SAAA,CAAUS,CAAe,EACjD,CAAA,OAAE,CACAvB,GAAAA,CAAY,KAAA,GACd,CACAqB,CAAAA,EAAS,CACTb,CAAAA,GACF,CACF,CAAC,CAAA,CAEDS,CAAAA,CAAY,GAAG,OAAA,CAASR,CAAM,CAAA,CAC9BO,CAAAA,CAAY,GAAG,OAAA,CAASP,CAAM,CAAA,CAE9BF,CAAAA,CAAU,KAAKU,CAAW,EAC5B,CAAC,CAAA,CAGH,OAAO,CACL,YAAA,CAAc,IAAA,CAAK,SAAA,CAAU,CAAE,OAAA,CAASnB,CAAe,CAAC,CAAA,CACxD,KAAAiB,CAAAA,CACA,aAAA,CAAe,IAAM,CACnB,GAAID,GAAAA,GAAmB,IAAA,CACrB,MAAM,IAAI,MAAM,+CAA+C,CAAA,CAEjE,OAAOA,GACT,CACF,CACF","file":"render-HDPCEI2O.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', reject);\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":"+ZAkBA,IAAMA,CAAAA,CAAkB,IAAM,CAC5B,IAAMC,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,OAAKD,CAAAA,CAGEE,CAAAA,CAAkBF,CAAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,CAFhC,IAGX,CAAA,CAEMG,CAAAA,CAAkBC,GAAmB,CACzC,IAAMJ,CAAAA,CAAMC,CAAAA,GACZ,GAAKD,CAAAA,CAGL,OAAOA,CAAAA,CAAI,QAAQ,OAAA,CAAQI,CAAG,CAAA,EAAG,KACnC,EAEA,SAASC,CAAAA,EAA8B,CACrCC,CAAAA,CAAuBP,CAAe,CAAA,CACtCQ,CAAAA,CAAsBJ,CAAc,EACtC,CA0BA,eAAsBK,CAAAA,CAAoBC,CAAAA,CAAqD,CAC7F,GAAM,CAAE,WAAA,CAAAC,CAAAA,CAAa,cAAA,CAAAC,EAAgB,aAAA,CAAAC,CAAAA,CAAe,MAAA,CAAAC,CAAAA,CAAQ,SAAAC,CAAAA,CAAU,YAAA,CAAAC,CAAAA,CAAc,OAAA,CAAAC,GAAQ,CAAA,CAC1FP,CAAAA,CAEFJ,CAAAA,EAA4B,CAE5B,IAAMY,CAAAA,CAAiB,MAAMC,CAAAA,CAC3B,sBAAA,CACA,EAAC,CACDR,CACF,CAAA,CAEMS,GAAAA,CAAc,IAAIC,WAAAA,CAAY,CAClC,cAAA,CAAgB,CACd,QAAS,CACP,KAAA,CAAO,KAAA,CACP,MAAA,CAAQ,CACV,CACF,CACF,CAAC,CAAA,CAEKC,EAAaR,CAAAA,CAASA,CAAAA,CAAO,CAAE,QAAA,CAAUD,EAAe,QAAA,CAAAE,CAAS,CAAC,CAAA,CAA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9D,EACA,KAAA,CAAMD,CAAAA,CAAU,CACd,GAAI,CACF,IAAME,CAAAA,CAAmCC,SAAAA,CAAUxB,GAAW,EAC9Dc,GAAAA,CAAiB,IAAA,CAAK,SAAA,CAAUS,CAAe,EACjD,CAAA,OAAE,CACAvB,GAAAA,CAAY,KAAA,GACd,CACAqB,CAAAA,EAAS,CACTb,CAAAA,GACF,CACF,CAAC,CAAA,CAEDS,CAAAA,CAAY,GAAG,OAAA,CAASR,CAAM,CAAA,CAC9BO,CAAAA,CAAY,GAAG,OAAA,CAASP,CAAM,CAAA,CAE9BF,CAAAA,CAAU,KAAKU,CAAW,EAC5B,CAAC,CAAA,CAGH,OAAO,CACL,YAAA,CAAc,IAAA,CAAK,SAAA,CAAU,CAAE,OAAA,CAASnB,CAAe,CAAC,CAAA,CACxD,KAAAiB,CAAAA,CACA,aAAA,CAAe,IAAM,CACnB,GAAID,GAAAA,GAAmB,IAAA,CACrB,MAAM,IAAI,MAAM,+CAA+C,CAAA,CAEjE,OAAOA,GACT,CACF,CACF","file":"render-UY7R4EKL.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', reject);\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-RVUJ3U27.js';import'./chunk-76I5SXWM.js';import'./chunk-54MUUAZG.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=renderApp-ZMIJGGAP.js.map
2
+ //# sourceMappingURL=renderApp-ZMIJGGAP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"renderApp-Y3OJU4PO.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"renderApp-ZMIJGGAP.js"}
@@ -0,0 +1,2 @@
1
+ export{g as getCallContext,f as startServer}from'./chunk-B5XMG3OE.js';import'./chunk-M24E3CAP.js';import'./chunk-LVB7YU4P.js';import'./chunk-MIRF7FP3.js';import'./chunk-ENHGU3X4.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-WW7YMRBB.js.map
2
+ //# sourceMappingURL=server-WW7YMRBB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"server-WAXWRUOY.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"server-WW7YMRBB.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-T4G5RAOK.js';import'./chunk-7DT2YQTG.js';export{w as LiveData,a as Module,b as Store,v as authenticate,i as clearSessionUser,y as createQuery,k as createSession,f as dbSessions,o as dbUsers,j as invalidateAllUserSessions,g as obtainSession,c as schema,l as setAuthTokenCookie,h as setSessionUser}from'./chunk-LVB7YU4P.js';import'./chunk-MIRF7FP3.js';export{a as getConfig}from'./chunk-ENHGU3X4.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-B5XMG3OE.js';import'./chunk-M24E3CAP.js';export{w as LiveData,a as Module,b as Store,v as authenticate,i as clearSessionUser,y as createQuery,k as createSession,f as dbSessions,o as dbUsers,j as invalidateAllUserSessions,g as obtainSession,c as schema,l as setAuthTokenCookie,h as setSessionUser}from'./chunk-LVB7YU4P.js';import'./chunk-MIRF7FP3.js';export{a as getConfig}from'./chunk-ENHGU3X4.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-P2W2XOKE.js';import'./chunk-LVB7YU4P.js';import'./chunk-ENHGU3X4.js';import {v,u}from'./chunk-3RMUZGFT.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';function d(){return v(async(t,r)=>{let o=c();return o?a(t,r,o.callContext):u(t,r)})}export{d as installSsrCallMethodTransport};//# sourceMappingURL=transport-UBIBRQF5.js.map
2
- //# sourceMappingURL=transport-UBIBRQF5.js.map
1
+ import {c,a}from'./chunk-P2W2XOKE.js';import'./chunk-LVB7YU4P.js';import'./chunk-ENHGU3X4.js';import {v,u}from'./chunk-54MUUAZG.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';function d(){return v(async(t,r)=>{let o=c();return o?a(t,r,o.callContext):u(t,r)})}export{d as installSsrCallMethodTransport};//# sourceMappingURL=transport-Q6Q42CSY.js.map
2
+ //# sourceMappingURL=transport-Q6Q42CSY.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-UBIBRQF5.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-Q6Q42CSY.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.21.0-ml.dev.2",
4
+ "version": "0.21.0-ml.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",
@@ -1,2 +0,0 @@
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:"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-3RMUZGFT.js.map
2
- //# sourceMappingURL=chunk-3RMUZGFT.js.map
@@ -1 +0,0 @@
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,CACl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G1B,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-3RMUZGFT.js","sourcesContent":["const SESSION_KEY = 'modelence.session';\n\nfunction hasLocalStorage(): boolean {\n return typeof globalThis !== 'undefined' && typeof globalThis.localStorage !== 'undefined';\n}\n\nexport function getLocalStorageSession() {\n if (!hasLocalStorage()) {\n return null;\n }\n\n const sessionJson = globalThis.localStorage.getItem(SESSION_KEY);\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n if (!hasLocalStorage()) {\n return;\n }\n\n globalThis.localStorage.setItem(SESSION_KEY, JSON.stringify(session));\n}\n","import type { ClientInfo } from '@/methods/types';\n\nexport interface ClientConfig {\n baseUrl: string;\n getAuthToken: () => string | undefined;\n setAuthToken: (token: string | null) => void;\n getClientInfo: () => ClientInfo;\n /**\n * Opens a URL for OAuth redirects. React Native must use\n * `(url) => Linking.openURL(url)` — WebView is not supported.\n * Defaults to `window.location.href` when not provided.\n */\n openUrl?: (url: string) => void;\n}\n\nlet config: ClientConfig | null = null;\n\n/**\n * Configure the Modelence client for non-browser environments like React Native.\n *\n * When configured, the client uses the provided functions for auth-token\n * storage, client-info collection, and URL resolution instead of the\n * default browser APIs (localStorage, window.screen, relative URLs).\n *\n * @example\n * ```ts\n * import { configureClient } from 'modelence/client';\n * import { Linking } from 'react-native';\n *\n * let authToken: string | undefined;\n *\n * configureClient({\n * baseUrl: 'https://myapp.com',\n * getAuthToken: () => authToken,\n * setAuthToken: (token) => { authToken = token ?? undefined; },\n * getClientInfo: () => ({\n * screenWidth: Dimensions.get('screen').width,\n * screenHeight: Dimensions.get('screen').height,\n * windowWidth: Dimensions.get('window').width,\n * windowHeight: Dimensions.get('window').height,\n * pixelRatio: PixelRatio.get(),\n * orientation: null,\n * }),\n * openUrl: (url) => Linking.openURL(url),\n * });\n * ```\n */\nexport function configureClient(userConfig: ClientConfig) {\n config = userConfig;\n}\n\nexport function getClientConfig(): ClientConfig | null {\n return config;\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n /**\n * Machine-readable error code set by the server (when available), so callers\n * can branch on the error kind without matching the human-readable message.\n * For example, a login attempt with an unverified email yields\n * `code === 'EMAIL_NOT_VERIFIED'`.\n */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n this.code = code;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\n// Default: fetch HTTP. SSR swaps in an in-process transport via globalThis\n// so Vite's ssrLoadModule (separate module graph) shares the same instance.\nexport type CallMethodTransport = <T = unknown>(methodName: string, args: MethodArgs) => Promise<T>;\n\n/**\n * The default HTTP transport. Exported so alternative transports (e.g. the SSR\n * in-process transport) can delegate to it when they don't apply.\n * @internal\n */\nexport const defaultCallMethodTransport: CallMethodTransport = async <T>(\n methodName: string,\n args: MethodArgs\n) => {\n const baseUrl = getClientConfig()?.baseUrl ?? '';\n return call<T>(`${baseUrl}/api/_internal/method/${methodName}`, args);\n};\n\nconst TRANSPORT_KEY = '__modelence_call_method_transport__';\n\ntype GlobalWithTransport = typeof globalThis & {\n [TRANSPORT_KEY]?: CallMethodTransport;\n};\n\nfunction getTransport(): CallMethodTransport {\n return (globalThis as GlobalWithTransport)[TRANSPORT_KEY] ?? defaultCallMethodTransport;\n}\n\n/** Returns a disposer that restores the previous transport. */\nexport function setCallMethodTransport(next: CallMethodTransport): () => void {\n const previous = (globalThis as GlobalWithTransport)[TRANSPORT_KEY];\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = next;\n return () => {\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = previous;\n };\n}\n\n/**\n * Calls a server-side method (query or mutation) defined on a Modelence module.\n *\n * Both `args` and `options` are optional. Use the type parameter `T` to type the return value.\n *\n * @example\n * ```typescript\n * import { callMethod } from 'modelence/client';\n *\n * // No arguments\n * const todos = await callMethod<Todo[]>('todo.getAll');\n *\n * // With arguments\n * const todo = await callMethod<Todo>('todo.getOne', { id: '123' });\n *\n * // With a custom error handler\n * const created = await callMethod<Todo>(\n * 'todo.create',\n * { title: 'Buy groceries' },\n * { errorHandler: (error, methodName) => console.error(methodName, error) }\n * );\n * ```\n *\n * @param methodName - Fully qualified method name, e.g. `'todo.getAll'`.\n * @param args - Arguments passed to the server-side method. Defaults to `{}`.\n * @param options - Call-site options such as a custom {@link CallMethodOptions.errorHandler}. Defaults to `{}`.\n * @returns A promise that resolves to the method's return value.\n */\nexport async function callMethod<T = unknown>(\n methodName: string,\n args?: MethodArgs,\n options?: CallMethodOptions\n): Promise<T> {\n args = args ?? {};\n options = options ?? {};\n try {\n return await getTransport()<T>(methodName, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // Send cookies even when the SPA and API are on different origins. The\n // password-reset flow relies on the httpOnly `resetPasswordToken` cookie\n // set by the server landing route; with the default `same-origin` policy\n // the cookie would be dropped on cross-origin POSTs and the reset would\n // fail. (Cross-origin use also requires the server to emit\n // `Access-Control-Allow-Credentials: true` and a non-wildcard origin.)\n 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 +0,0 @@
1
- export{c as _getSsrSnapshot,d as renderApp}from'./chunk-GISIHWCC.js';import'./chunk-5UXY2NRZ.js';import'./chunk-3RMUZGFT.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=renderApp-Y3OJU4PO.js.map
2
- //# sourceMappingURL=renderApp-Y3OJU4PO.js.map
@@ -1,2 +0,0 @@
1
- export{g as getCallContext,f as startServer}from'./chunk-T4G5RAOK.js';import'./chunk-7DT2YQTG.js';import'./chunk-LVB7YU4P.js';import'./chunk-MIRF7FP3.js';import'./chunk-ENHGU3X4.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-WAXWRUOY.js.map
2
- //# sourceMappingURL=server-WAXWRUOY.js.map