modelence 0.4.7 → 0.4.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -117
- package/dist/bin/modelence.js +10 -3
- package/dist/bin/modelence.js.map +1 -1
- package/dist/{chunk-O2JTQHZP.js → chunk-DN5SVAO2.js} +2 -2
- package/dist/chunk-DN5SVAO2.js.map +1 -0
- package/dist/{chunk-D5LNOX64.js → chunk-EQLDF7OO.js} +2 -2
- package/dist/chunk-EQLDF7OO.js.map +1 -0
- package/dist/{chunk-GDI7FXAT.js → chunk-R7MPLJMA.js} +2 -2
- package/dist/chunk-R7MPLJMA.js.map +1 -0
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +7 -3
- package/dist/index.js +1 -1
- package/dist/mongo.js.map +1 -1
- package/dist/server.d.ts +8 -2
- package/dist/server.js +2 -2
- package/dist/server.js.map +1 -1
- package/package.json +2 -5
- package/dist/chunk-D5LNOX64.js.map +0 -1
- package/dist/chunk-GDI7FXAT.js.map +0 -1
- package/dist/chunk-O2JTQHZP.js.map +0 -1
- package/dist/index-5e-76duG.d.ts +0 -15
package/README.md
CHANGED
|
@@ -1,127 +1,19 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
<a href="https://modelence.com">
|
|
3
3
|
<picture>
|
|
4
|
-
<source media="(prefers-color-scheme: dark)" srcset="
|
|
5
|
-
<img alt="Modelence logo" src="
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="/packages/modelence/static/modelence.png">
|
|
5
|
+
<img alt="Modelence logo" src="/packages/modelence/static/modelence.png" height="128">
|
|
6
6
|
</picture>
|
|
7
7
|
</a>
|
|
8
8
|
<h1>Modelence</h1>
|
|
9
|
+
|
|
10
|
+
[Documentation](https://docs.modelence.com) | [API Reference](https://docs.modelence.com/docs/api-reference/intro)
|
|
9
11
|
|
|
10
|
-

|
|
11
|
-
<a href="https://www.npmjs.com/package/modelence"><img alt="NPM version" src="https://img.shields.io/npm/v/modelence.svg"></a>
|
|
12
|
-
|
|
12
|
+

|
|
13
|
+
<a href="https://www.npmjs.com/package/modelence"><img alt="NPM version" src="https://img.shields.io/npm/v/modelence.svg"></a>
|
|
13
14
|
</div>
|
|
14
15
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
## Dev Setup
|
|
18
|
-
Run `npm install` first to install packages.
|
|
19
|
-
|
|
20
|
-
Use `npm run dev` to keep rebuilding the package on every change for linking in local dev mode.
|
|
21
|
-
|
|
22
|
-
## App setup
|
|
23
|
-
|
|
24
|
-
- Create the following folder structure in your Node project:
|
|
25
|
-
|
|
26
|
-
```
|
|
27
|
-
src/
|
|
28
|
-
src/client/index.html
|
|
29
|
-
src/client/index.css
|
|
30
|
-
src/client/index.tsx
|
|
31
|
-
src/client/routes.ts
|
|
32
|
-
src/server/app.ts
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
- Install dependencies:
|
|
36
|
-
|
|
37
|
-
```
|
|
38
|
-
npm install --save modelence
|
|
39
|
-
npm install --save react react-dom react-router-dom
|
|
40
|
-
npm install --save-dev @types/react @types/react-dom
|
|
41
|
-
npm install --save-dev tsx nodemon
|
|
42
|
-
npm install --save-dev tailwindcss postcss autoprefixer
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
- Add the following scripts to your `package.json`:
|
|
46
|
-
|
|
47
|
-
```
|
|
48
|
-
"scripts": {
|
|
49
|
-
"dev": "nodemon --exec tsx src/server/app.ts"
|
|
50
|
-
}
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
- Create a `tsconfig.json` file in the root of your project with the following content:
|
|
54
|
-
```json
|
|
55
|
-
{
|
|
56
|
-
"compilerOptions": {
|
|
57
|
-
"outDir": "./.modelence/build/",
|
|
58
|
-
"baseUrl": ".",
|
|
59
|
-
"paths": {
|
|
60
|
-
"@/*": ["./src/*"]
|
|
61
|
-
},
|
|
62
|
-
"sourceMap": true,
|
|
63
|
-
"noImplicitAny": true,
|
|
64
|
-
"module": "NodeNext",
|
|
65
|
-
"esModuleInterop": true,
|
|
66
|
-
"skipLibCheck": true,
|
|
67
|
-
"target": "ES2020",
|
|
68
|
-
"lib": [
|
|
69
|
-
"ES2020",
|
|
70
|
-
"DOM",
|
|
71
|
-
"WebWorker"
|
|
72
|
-
],
|
|
73
|
-
"jsx": "react-jsx",
|
|
74
|
-
"allowJs": true,
|
|
75
|
-
"moduleResolution": "bundler",
|
|
76
|
-
"strict": false,
|
|
77
|
-
"noEmit": true,
|
|
78
|
-
"incremental": true,
|
|
79
|
-
"resolveJsonModule": true,
|
|
80
|
-
"isolatedModules": true,
|
|
81
|
-
"plugins": [
|
|
82
|
-
{
|
|
83
|
-
"name": "next"
|
|
84
|
-
}
|
|
85
|
-
]
|
|
86
|
-
},
|
|
87
|
-
"include": [
|
|
88
|
-
"**/*.ts",
|
|
89
|
-
"**/*.d.ts",
|
|
90
|
-
"**/*.tsx"
|
|
91
|
-
],
|
|
92
|
-
"exclude": [
|
|
93
|
-
"node_modules"
|
|
94
|
-
]
|
|
95
|
-
}
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
Create a `tailwind.config.js` file in the root of your project with the following content:
|
|
99
|
-
```js
|
|
100
|
-
/** @type {import('tailwindcss').Config} */
|
|
101
|
-
module.exports = {
|
|
102
|
-
content: [
|
|
103
|
-
"./src/client/**/*.{js,jsx,ts,tsx}",
|
|
104
|
-
],
|
|
105
|
-
theme: {
|
|
106
|
-
extend: {},
|
|
107
|
-
},
|
|
108
|
-
plugins: [],
|
|
109
|
-
darkMode: 'class',
|
|
110
|
-
}
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
Create a `postcss.config.js` file in the root of your project with the following content:
|
|
114
|
-
```js
|
|
115
|
-
/** @type {import('postcss-load-config').Config} */
|
|
116
|
-
export default {
|
|
117
|
-
plugins: {
|
|
118
|
-
tailwindcss: {},
|
|
119
|
-
},
|
|
120
|
-
};
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
## Documentation
|
|
124
|
-
|
|
125
|
-
[Documentation](https://docs.modelence.com) | [API Reference](https://docs.modelence.com/api-reference)
|
|
16
|
+
## Getting Started
|
|
17
|
+
Modelence is a full-stack TypeScript Framework for real-time MongoDB applications, with the mission to eliminate all boilerplate for most standard features that modern web applications need, like database access, authentication, AI integration and more.
|
|
126
18
|
|
|
127
|
-
|
|
19
|
+
- Visit our [Quick Start Guide](https://docs.modelence.com/docs/quick-start/intro) to get started with Modelence.
|
package/dist/bin/modelence.js
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import
|
|
3
|
-
`);await promises.writeFile(
|
|
4
|
-
`),console.log(`Successfully configured ${
|
|
2
|
+
import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import S,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import O from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import ce from'archiver';import oe from'open';import {Octokit}from'@octokit/rest';import c from'fs-extra';var v=".modelence.env";async function A(e,t){let o=await fetch(`${t}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!o.ok){let n=await o.text();throw new Error(n||`Request failed with status ${o.status}`)}return o.json()}async function R(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${v} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function U(e){return String(e).replace(/"/g,'\\"')}async function V(e){try{let t=e.replace(".env",".backup.env");await promises.copyFile(e,t),console.log(`Backup created at ${t}`);}catch(t){console.warn("Failed to create backup file:",t);}}async function $(e){try{let t=join(process.cwd(),v),o={};try{let a=await promises.readFile(t,"utf8");o=parse(a),await V(t),await R()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let n=await A(e.token,e.host),r={...o,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:n.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:n.serviceToken,MODELENCE_CONTAINER_ID:n.containerId},s=Object.entries(r).map(([a,i])=>`${a}="${U(i)}"`).join(`
|
|
3
|
+
`);await promises.writeFile(t,s.trim()+`
|
|
4
|
+
`),console.log(`Successfully configured ${v} file`);}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var C=null,b=null;function G(){if(!C)throw new Error("Environment variables not loaded");return C}function D(){if(!b)throw new Error("Configuration not loaded");return b}function p(e){let t=G().MODELENCE_SERVICE_ENDPOINT;if(!t)throw new Error("MODELENCE_SERVICE_ENDPOINT not found in environment variables");return `${t}${e}`}function g(){let{serverDir:e,serverEntry:t}=D();return join(e,t)}function T(){return D().postBuildCommand}function N(e){let t=x("build");return t}function u(e){return join(process.cwd(),e)}function x(e){let t=u(".modelence");return e?join(t,e):t}async function h(){try{let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");b=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()}).parse(o);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await O.readFile(join(process.cwd(),".modelence.env"),"utf-8");C=parse(e);}catch(e){if(e.code!=="ENOENT")throw e}}async function Q(){let e=T();if(e){console.log("Running post-build command..."),execSync(e);return}await ee();}async function ee(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:S.resolve(process.cwd(),".modelence/build/client"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function te(){return console.log("Building server with tsup..."),new Promise((e,t)=>{build({entry:[g()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,skipNodeModulesBundle:false,outExtension:({format:o})=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function E(){console.log("Building Modelence project...");try{let e=N();await O.rm(e,{recursive:!0,force:!0}),await te(),await Q(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await O.access(x());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function P(){let e=await fetch(p("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:t,verificationUrl:o}=await e.json();console.log(`Please visit ${o} to authenticate`),console.log(`Code: ${t}`),await oe(o);let n=await ie(t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:n})),{token:n}}async function ie(e){let n=Date.now()+6e5;for(;Date.now()<n;){try{let r=await ae(e);if(r)return r}catch(r){console.error("Error polling for CLI token:",r);}await new Promise(r=>setTimeout(r,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function ae(e){let t=await fetch(p(`/api/cli/token?code=${e}`),{method:"GET"});if(!t.ok)throw new Error(`CLI token polling failed: ${t.statusText}`);let{token:o}=await t.json();return o}async function M(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip");await E(),await le(n);let{token:r}=await P(),{bundleName:s}=await de(e.env,n,r);await promises.unlink(n),await pe(e.env,s,join(".modelence","build","app.mjs"),r);}async function le(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=ce("zip",{zlib:{level:9}});o.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),o.on("error",i=>{throw i});let n=new Promise((i,k)=>{t.on("close",i),t.on("error",k),o.on("error",k);});o.pipe(t);let r=["package.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server",join(".modelence","build"),".next"];for(let i of r)await promises.access(u(i)).then(()=>true).catch(()=>false)&&o.file(u(i),{name:i});for(let i of s)await promises.access(u(i)).then(()=>true).catch(()=>false)&&o.directory(u(i),i);await o.finalize(),await n;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function de(e,t,o){let n=await fetch(p(`/api/environments/${e}/upload`),{method:"POST",headers:{Authorization:`Bearer ${o}`}});if(!n.ok)throw console.error(await n.text()),new Error(`Failed to create upload URL: ${n.statusText}`);let{uploadUrl:r,bundleName:s}=await n.json(),a=await promises.readFile(t),i=await fetch(r,{method:"PUT",body:a,headers:{"Content-Type":"application/zip"}});if(!i.ok)throw new Error(`Failed to upload bundle: ${i.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${s}`),{bundleName:s}}async function pe(e,t,o,n){let r=await fetch(p(`/api/environments/${e}/deploy`),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({bundleName:t,entryPoint:o})});if(!r.ok)throw new Error(`Failed to trigger deployment: ${r.statusText}`);let{deploymentUrl:s}=await r.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${s}`);}function B(){console.log("Starting Modelence dev server...");let e=g(),t=S.resolve("./node_modules/.bin/tsx");execSync(`"${t}" watch "${e}"`,{stdio:"inherit",env:{...process.env,NODE_ENV:"development"}});}var ge="modelence/examples",he="empty-project";async function j(e,t={}){let o=t.template||he;if(console.log(`Creating new Modelence app: ${e}`),console.log(`Using template: ${o}`),!/^[a-zA-Z0-9-_]+$/.test(e))throw new Error("Project name can only contain letters, numbers, dashes and underscores");let n=S.resolve(process.cwd(),e);if(c.existsSync(n))throw new Error(`Directory ${e} already exists`);try{let r=new Octokit,s=await r.repos.getContent({owner:"modelence",repo:"examples",path:o});if(!Array.isArray(s.data))throw new Error("Invalid template structure");c.mkdirSync(n),await I(r,s.data,o,n);let a=S.join(n,"package.json"),i=await c.readJson(a);i.name=e,await c.writeJson(a,i,{spaces:2}),console.log("Installing dependencies..."),execSync("npm install",{cwd:n,stdio:"inherit"}),console.log(`
|
|
5
|
+
Successfully created ${e}!
|
|
6
|
+
|
|
7
|
+
Get started by typing:
|
|
8
|
+
|
|
9
|
+
cd ${e}
|
|
10
|
+
npm run dev
|
|
11
|
+
`);}catch(r){throw c.existsSync(n)&&c.removeSync(n),r.status===404?new Error(`Template "${o}" not found in ${ge}`):r}}async function I(e,t,o,n){for(let r of t){let s=S.join(n,r.name);if(r.type==="dir"){c.mkdirSync(s);let a=await e.repos.getContent({owner:"modelence",repo:"examples",path:`${o}/${r.name}`});Array.isArray(a.data)&&await I(e,a.data,`${o}/${r.name}`,s);}else {let a=await e.repos.getContent({owner:"modelence",repo:"examples",path:`${o}/${r.name}`});if("content"in a.data&&typeof a.data.content=="string"){let i=Buffer.from(a.data.content,"base64").toString();await c.writeFile(s,i);}}}}var m=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");m.command("create-app <project-name>").description("Create a new Modelence application").option("-t, --template <template-name>","Template to use (from examples repository)").action(async(e,t)=>{await j(e,{template:t.template});});m.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await $(e);});m.command("build").description("Build the application").action(async()=>{await h(),await E();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-e, --env <env>","Environment (deployment alias)").action(async e=>{await h(),await M(e);});m.command("dev").description("Start development server").action(async()=>{await h(),B();});m.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
5
12
|
//# sourceMappingURL=modelence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../bin/setup.ts","../../bin/config.ts","../../bin/build.ts","../../bin/auth.ts","../../bin/deploy.ts","../../bin/dev.ts","../../bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","studioBaseUrl","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","reject","tsupBuild","format","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","bundleFiles","bundleDirs","file","dir","stats","deploymentAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","program","Command"],"mappings":";wbAKA,IAAMA,CAAqB,CAAA,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAoBC,CAAAA,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAGD,EAAAA,CAAI,CAAc,UAAA,CAAA,CAAA,CAChD,MAAQ,CAAA,KAAA,CACR,OAAS,CAAA,CACP,yBAA2BD,CAAAA,CAC7B,CACF,CAAC,CAED,CAAA,GAAI,CAACE,CAAAA,CAAS,EAAI,CAAA,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAK,EAAA,CACtC,MAAM,IAAI,KAAMC,CAAAA,CAAAA,EAAa,CAA8BD,2BAAAA,EAAAA,CAAAA,CAAS,MAAM,CAAE,CAAA,CAC9E,CAEA,OAAOA,CAAS,CAAA,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAKC,CAAAA,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAQ,C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A,CAAK,IAAM,CACnBwD,CAAAA,CAAQ,MAAM,OAAQ,CAAA,IAAI,EAC5B,CAAC,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise((resolve) => {\n rl.question(`Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n });\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string, host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch (error) {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport { ModelenceConfig } from '../packages/types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT;\n if (!studioBaseUrl) {\n throw new Error('MODELENCE_SERVICE_ENDPOINT not found in environment variables');\n }\n\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n return join(serverDir, serverEntry);\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n return subPath ? join(buildDir, subPath) : buildDir;\n}\n\nexport function getProjectPath(subPath: string) {\n return join(process.cwd(), subPath);\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n return subPath ? join(modelenceDir, subPath) : modelenceDir;\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n \n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { env: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli();\n\n const { bundleName } = await uploadBundle(options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.env, bundleName, join('.modelence', 'build', 'app.mjs'), token);\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 } // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = [\n 'public',\n 'server',\n join('.modelence', 'build'),\n '.next',\n ];\n\n for (const file of bundleFiles) {\n if (await fs.access(getProjectPath(file)).then(() => true).catch(() => false)) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (await fs.access(getProjectPath(dir)).then(() => true).catch(() => false)) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(`Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);\n}\n\nasync function uploadBundle(deploymentAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/deployments/${deploymentAlias}/upload`), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`\n }\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: fileBuffer,\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(deploymentAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/deployments/${deploymentAlias}/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n \n const serverPath = getServerPath(); \n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" --no-cjs watch \"${serverPath}\"`, {\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'development' }\n }); \n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { loadEnv } from './config';\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version('0.2.1');\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-e, --env <env>', 'Environment (deployment alias)')\n .action(async (options) => {\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n dev();\n });\n\nloadEnv().then(() => {\n program.parse(process.argv);\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/create-app.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","studioBaseUrl","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","reject","tsupBuild","format","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","bundleFiles","bundleDirs","file","dir","stats","deploymentAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","EXAMPLES_REPO","DEFAULT_TEMPLATE","createApp","projectName","template","projectPath","octokit","Octokit","downloadTemplateFiles","packageJsonPath","packageJson","contents","templateName","targetPath","item","itemPath","dirContents","fileContent","content","program","Command"],"mappings":";8eAKA,IAAMA,CAAqB,CAAA,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAoBC,CAAAA,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAGD,EAAAA,CAAI,CAAc,UAAA,CAAA,CAAA,CAChD,MAAQ,CAAA,KAAA,CACR,OAAS,CAAA,CACP,yBAA2BD,CAAAA,CAC7B,CACF,CAAC,CAED,CAAA,GAAI,CAACE,CAAAA,CAAS,EAAI,CAAA,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAK,EAAA,CACtC,MAAM,IAAI,KAAMC,CAAAA,CAAAA,EAAa,CAA8BD,2BAAAA,EAAAA,CAAAA,CAAS,MAAM,CAAE,CAAA,CAC9E,CAEA,OAAOA,CAAS,CAAA,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAKC,CAAAA,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAQ,CAAA,KAAA,CACf,MAAQ,CAAA,OAAA,CAAQ,MAClB,CAAC,CAED,CAAA,OAAO,IAAI,OAAA,CAASC,CAAY,EAAA,CAC9BF,CAAG,CAAA,QAAA,CAAS,CAAYP,SAAAA,EAAAA,CAAkB,uDAAyDU,CAAW,EAAA,CAC5GH,CAAG,CAAA,KAAA,EACHE,CAAAA,CAAAA,CAAQC,CAAO,CAAA,WAAA,EAAkB,GAAA,GAAG,EACtC,CAAC,EACH,CAAC,CAC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,CACd,MAAMmB,CAAAA,GACR,CAAC,EAEHwD,CACG,CAAA,OAAA,CAAQ,QAAQ,CAAA,CAChB,WAAY,CAAA,2BAA2B,CACvC,CAAA,cAAA,CAAe,kBAAmB,gCAAgC,CAAA,CAClE,MAAO,CAAA,MAAOnG,CAAY,EAAA,CACzB,MAAMwB,CAAAA,EACN,CAAA,MAAM6B,CAAOrD,CAAAA,CAAO,EACtB,CAAC,CAEHmG,CAAAA,CAAAA,CACG,QAAQ,KAAK,CAAA,CACb,WAAY,CAAA,0BAA0B,CACtC,CAAA,MAAA,CAAO,SAAY,CAClB,MAAM3E,CAAQ,EAAA,CACdqD,CAAI,GACN,CAAC,CAAA,CAEHsB,CAAQ,CAAA,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise((resolve) => {\n rl.question(`Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n });\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string, host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch (error) {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT;\n if (!studioBaseUrl) {\n throw new Error('MODELENCE_SERVICE_ENDPOINT not found in environment variables');\n }\n\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n return join(serverDir, serverEntry);\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n return subPath ? join(buildDir, subPath) : buildDir;\n}\n\nexport function getProjectPath(subPath: string) {\n return join(process.cwd(), subPath);\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n return subPath ? join(modelenceDir, subPath) : modelenceDir;\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n \n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { env: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli();\n\n const { bundleName } = await uploadBundle(options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.env, bundleName, join('.modelence', 'build', 'app.mjs'), token);\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 } // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = [\n 'public',\n 'server',\n join('.modelence', 'build'),\n '.next',\n ];\n\n for (const file of bundleFiles) {\n if (await fs.access(getProjectPath(file)).then(() => true).catch(() => false)) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (await fs.access(getProjectPath(dir)).then(() => true).catch(() => false)) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(`Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);\n}\n\nasync function uploadBundle(deploymentAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/upload`), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`\n }\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: fileBuffer,\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(deploymentAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n \n const serverPath = getServerPath(); \n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'development' }\n }); \n}\n","import { Octokit } from '@octokit/rest';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nconst EXAMPLES_REPO = 'modelence/examples';\nconst DEFAULT_TEMPLATE = 'empty-project';\n\ninterface CreateAppOptions {\n template?: string;\n}\n\nexport async function createApp(projectName: string, options: CreateAppOptions = {}) {\n const template = options.template || DEFAULT_TEMPLATE;\n \n console.log(`Creating new Modelence app: ${projectName}`);\n console.log(`Using template: ${template}`);\n\n // Validate project name\n if (!/^[a-zA-Z0-9-_]+$/.test(projectName)) {\n throw new Error('Project name can only contain letters, numbers, dashes and underscores');\n }\n\n const projectPath = path.resolve(process.cwd(), projectName);\n\n // Check if directory already exists\n if (fs.existsSync(projectPath)) {\n throw new Error(`Directory ${projectName} already exists`);\n }\n\n try {\n // Initialize Octokit\n const octokit = new Octokit();\n\n // Get template contents from GitHub\n const response = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: template,\n });\n\n if (!Array.isArray(response.data)) {\n throw new Error('Invalid template structure');\n }\n\n // Create project directory\n fs.mkdirSync(projectPath);\n\n // Download and extract template files\n await downloadTemplateFiles(octokit, response.data, template, projectPath);\n\n // Update package.json\n const packageJsonPath = path.join(projectPath, 'package.json');\n const packageJson = await fs.readJson(packageJsonPath);\n packageJson.name = projectName;\n await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });\n\n // Install dependencies\n console.log('Installing dependencies...');\n execSync('npm install', { cwd: projectPath, stdio: 'inherit' });\n\n console.log(`\nSuccessfully created ${projectName}!\n\nGet started by typing:\n\n cd ${projectName}\n npm run dev\n `);\n\n } catch (error: any) {\n // Clean up on error\n if (fs.existsSync(projectPath)) {\n fs.removeSync(projectPath);\n }\n\n if (error.status === 404) {\n throw new Error(`Template \"${template}\" not found in ${EXAMPLES_REPO}`);\n }\n throw error;\n }\n}\n\nasync function downloadTemplateFiles(octokit: Octokit, contents: any[], templateName: string, targetPath: string) {\n for (const item of contents) {\n const itemPath = path.join(targetPath, item.name);\n\n if (item.type === 'dir') {\n fs.mkdirSync(itemPath);\n const dirContents = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: `${templateName}/${item.name}`,\n });\n if (Array.isArray(dirContents.data)) {\n await downloadTemplateFiles(octokit, dirContents.data, `${templateName}/${item.name}`, itemPath);\n }\n } else {\n const fileContent = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: `${templateName}/${item.name}`,\n });\n \n if ('content' in fileContent.data && typeof fileContent.data.content === 'string') {\n const content = Buffer.from(fileContent.data.content, 'base64').toString();\n await fs.writeFile(itemPath, content);\n }\n }\n }\n} ","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { createApp } from './create-app';\nimport { loadEnv } from './config';\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version('0.2.1');\n\n// Commands that don't need config\nprogram\n .command('create-app <project-name>')\n .description('Create a new Modelence application')\n .option('-t, --template <template-name>', 'Template to use (from examples repository)')\n .action(async (projectName, options) => {\n await createApp(projectName, {\n template: options.template\n });\n });\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-e, --env <env>', 'Environment (deployment alias)')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function s(n){if(n instanceof Date)return {type:"date"};if(Array.isArray(n)){let e={};for(let r=0;r<n.length;r++){let t=n[r],o=s(t);o&&(e[r]=o);}return Object.keys(e).length>0?{type:"array",elements:e}:null}if(typeof n=="object"&&n!==null){let e={};for(let[r,t]of Object.entries(n)){let o=s(t);o&&(e[r]=o);}return Object.keys(e).length>0?{type:"object",props:e}:null}return null}function i(n,e){return e?e.type==="date"?new Date(n):e.type==="array"?n.map((r,t)=>i(r,e.elements[t])):e.type==="object"?Object.fromEntries(Object.entries(n).map(([r,t])=>[r,i(t,e.props[r])])):n:n}export{s as a,i as b};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
function s(n){if(n instanceof Date)return {type:"date"};if(Array.isArray(n)){let e={};for(let r=0;r<n.length;r++){let t=n[r],o=s(t);o&&(e[r]=o);}return Object.keys(e).length>0?{type:"array",elements:e}:null}if(typeof n=="object"&&n!==null){let e={};for(let[r,t]of Object.entries(n)){let o=s(t);o&&(e[r]=o);}return Object.keys(e).length>0?{type:"object",props:e}:null}return null}function i(n,e){return e?e.type==="date"?new Date(n):e.type==="array"?n.map((r,t)=>i(r,e.elements[t])):e.type==="object"?Object.fromEntries(Object.entries(n).map(([r,t])=>[r,i(t,e.props[r])])):n:n}export{s as a,i as b};//# sourceMappingURL=chunk-DN5SVAO2.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-DN5SVAO2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/methods/serialize.ts"],"names":["getResponseTypeMap","result","elements","i","item","subTypeMap","props","key","value","reviveResponseTypes","data","typeMap","index"],"mappings":"AAAO,SAASA,EAAmBC,CAAa,CAAA,CAC9C,GAAIA,CAAAA,YAAkB,KACpB,OAAO,CAAE,IAAM,CAAA,MAAO,EAGxB,GAAI,KAAA,CAAM,QAAQA,CAAM,CAAA,CAAG,CACzB,IAAMC,CAAAA,CAAgC,EAAC,CACvC,QAASC,CAAI,CAAA,CAAA,CAAGA,CAAIF,CAAAA,CAAAA,CAAO,OAAQE,CAAK,EAAA,CAAA,CACtC,IAAMC,CAAAA,CAAOH,EAAOE,CAAC,CAAA,CACfE,EAAaL,CAAmBI,CAAAA,CAAI,EACtCC,CACFH,GAAAA,CAAAA,CAASC,CAAC,CAAA,CAAIE,GAElB,CACA,OAAO,MAAO,CAAA,IAAA,CAAKH,CAAQ,CAAE,CAAA,MAAA,CAAS,CAAI,CAAA,CACxC,KAAM,OACN,CAAA,QAAA,CAAAA,CACF,CAAI,CAAA,IACN,CAEA,GAAI,OAAOD,CAAW,EAAA,QAAA,EAAYA,IAAW,IAAM,CAAA,CACjD,IAAMK,CAA6B,CAAA,GACnC,IAAW,GAAA,CAACC,CAAKC,CAAAA,CAAK,IAAK,MAAO,CAAA,OAAA,CAAQP,CAAM,CAAG,CAAA,CACjD,IAAMI,CAAaL,CAAAA,CAAAA,CAAmBQ,CAAK,CAAA,CACvCH,IACFC,CAAMC,CAAAA,CAAG,CAAIF,CAAAA,CAAAA,EAEjB,CACA,OAAO,MAAA,CAAO,IAAKC,CAAAA,CAAK,EAAE,MAAS,CAAA,CAAA,CAAI,CACrC,IAAM,CAAA,QAAA,CACN,MAAAA,CACF,CAAA,CAAI,IACN,CAEA,OAAO,IACT,CAEO,SAASG,CAA6BC,CAAAA,CAAAA,CAAWC,EAAkC,CACxF,OAAKA,CAIDA,CAAAA,CAAAA,CAAQ,OAAS,MACZ,CAAA,IAAI,KAAKD,CAAI,CAAA,CAGlBC,EAAQ,IAAS,GAAA,OAAA,CACZD,CAAK,CAAA,GAAA,CAAI,CAACN,CAAWQ,CAAAA,CAAAA,GAAkBH,CAAoBL,CAAAA,CAAAA,CAAMO,EAAQ,QAASC,CAAAA,CAAK,CAAC,CAAC,EAG9FD,CAAQ,CAAA,IAAA,GAAS,SACZ,MAAO,CAAA,WAAA,CAAY,OAAO,OAAQD,CAAAA,CAAI,CAAE,CAAA,GAAA,CAAI,CAAC,CAACH,CAAAA,CAAKC,CAAK,CAAM,GAAA,CAACD,EAAKE,CAAoBD,CAAAA,CAAAA,CAAOG,CAAQ,CAAA,KAAA,CAAMJ,CAAG,CAAC,CAAC,CAAC,CAAC,CAAA,CAGtHG,EAfEA,CAgBX","file":"chunk-DN5SVAO2.js","sourcesContent":["export function getResponseTypeMap(result: any) {\n if (result instanceof Date) {\n return { type: 'date' };\n }\n\n if (Array.isArray(result)) {\n const elements: Record<string, any> = {};\n for (let i = 0; i < result.length; i++) {\n const item = result[i];\n const subTypeMap = getResponseTypeMap(item);\n if (subTypeMap) {\n elements[i] = subTypeMap;\n }\n }\n return Object.keys(elements).length > 0 ? {\n type: 'array',\n elements\n } : null;\n }\n\n if (typeof result === 'object' && result !== null) {\n const props: Record<string, any> = {};\n for (const [key, value] of Object.entries(result)) {\n const subTypeMap = getResponseTypeMap(value);\n if (subTypeMap) {\n props[key] = subTypeMap;\n }\n }\n return Object.keys(props).length > 0 ? {\n type: 'object',\n props\n } : null;\n }\n\n return null;\n}\n\nexport function reviveResponseTypes<T = any>(data: any, typeMap?: Record<string, any>): T {\n if (!typeMap) {\n return data;\n }\n\n if (typeMap.type === 'date') {\n return new Date(data) as T;\n }\n\n if (typeMap.type === 'array') {\n return data.map((item: any, index: number) => reviveResponseTypes(item, typeMap.elements[index]));\n }\n\n if (typeMap.type === 'object') {\n return Object.fromEntries(Object.entries(data).map(([key, value]) => [key, reviveResponseTypes(value, typeMap.props[key])])) as T;\n }\n\n return data;\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var t=class extends Error{constructor(s){super(s),this.name="AuthError",this.status=401;}},r=class extends Error{constructor(s){super(s),this.name="ValidationError",this.status=400;}};export{t as a,r as b};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var t=class extends Error{constructor(s){super(s),this.name="AuthError",this.status=401;}},r=class extends Error{constructor(s){super(s),this.name="ValidationError",this.status=400;}};export{t as a,r as b};//# sourceMappingURL=chunk-EQLDF7OO.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-EQLDF7OO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/error.ts"],"names":["AuthError","message","ValidationError"],"mappings":"AAAO,IAAMA,CAAN,CAAA,cAAwB,KAAM,CAGnC,YAAYC,CAAiB,CAAA,CAC3B,KAAMA,CAAAA,CAAO,EACb,IAAK,CAAA,IAAA,CAAO,WACZ,CAAA,IAAA,CAAK,OAAS,IAChB,CACF,CAEaC,CAAAA,CAAAA,CAAN,cAA8B,KAAM,CAGzC,WAAA,CAAYD,EAAiB,CAC3B,KAAA,CAAMA,CAAO,CAAA,CACb,KAAK,IAAO,CAAA,iBAAA,CACZ,IAAK,CAAA,MAAA,CAAS,IAChB,CACF","file":"chunk-EQLDF7OO.js","sourcesContent":["export class AuthError extends Error {\n status: number;\n\n constructor(message: string) {\n super(message);\n this.name = 'AuthError';\n this.status = 401;\n }\n}\n\nexport class ValidationError extends Error {\n status: number;\n\n constructor(message: string) {\n super(message);\n this.name = 'ValidationError';\n this.status = 400;\n }\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e={seconds:s=>s*1e3,minutes:s=>s*6e4,hours:s=>s*36e5,days:s=>s*864e5,weeks:s=>s*6048e5};export{e as a};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var e={seconds:s=>s*1e3,minutes:s=>s*6e4,hours:s=>s*36e5,days:s=>s*864e5,weeks:s=>s*6048e5};export{e as a};//# sourceMappingURL=chunk-R7MPLJMA.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-R7MPLJMA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/time.ts"],"names":["time","x"],"mappings":"AAMaA,IAAAA,CAAAA,CAAO,CAClB,OAAUC,CAAAA,CAAAA,EAAcA,EAAI,GAC5B,CAAA,OAAA,CAAUA,GAAcA,CAAI,CAAA,GAAA,CAC5B,MAAQA,CAAcA,EAAAA,CAAAA,CAAI,KAC1B,IAAOA,CAAAA,CAAAA,EAAcA,EAAI,KACzB,CAAA,KAAA,CAAQA,CAAcA,EAAAA,CAAAA,CAAI,MAC5B","file":"chunk-R7MPLJMA.js","sourcesContent":["const secondMs = 1000;\nconst minuteMs = 60 * secondMs;\nconst hourMs = 60 * minuteMs;\nconst dayMs = 24 * hourMs;\nconst weekMs = 7 * dayMs;\n\nexport const time = {\n seconds: (x: number) => x * secondMs,\n minutes: (x: number) => x * minuteMs,\n hours: (x: number) => x * hourMs,\n days: (x: number) => x * dayMs,\n weeks: (x: number) => x * weekMs,\n}\n"]}
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-
|
|
1
|
+
import {b as b$1}from'./chunk-DN5SVAO2.js';import {a}from'./chunk-R7MPLJMA.js';import L,{useState,useEffect,useMemo}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx,Fragment}from'react/jsx-runtime';import D from'react-dom/client';function w(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(r){return console.error("Error parsing session from localStorage",r),null}}function S(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var y=(e,r)=>{throw new Error(`Error calling method '${r}': ${e.toString()}`)};function E(e){y=e;}function A(e,r){return y(e,r)}async function i(e,r={}){try{return await _(`/api/_internal/method/${e}`,r)}catch(t){throw A(t,e),t}}async function _(e,r){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:w()?.authToken,clientInfo:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type}})});if(!t.ok){let s=await t.text();throw new Error(s)}let o=await t.text(),n=o?JSON.parse(o):void 0;if(!n)throw new Error("Invalid response from server");return b$1(n.data,n.typeMap)}function W(e,r={},t){let{result:o,triggerMethod:n}=T(e,r,{enabled:t?.enabled??true});return {...o,refetch:s=>n(s)}}function J(e,r={}){let{result:t,triggerMethod:o}=T(e,r,{enabled:false});return {...t,mutate:n=>o(n),mutateAsync:o}}function T(e,r={},t){let o=useMemo(()=>r,[JSON.stringify(r)]),n=useMemo(()=>t,[JSON.stringify(t)]),[s,l]=useState({isFetching:t.enabled,error:null,data:null}),f=async(N=o)=>{l({isFetching:true,error:null,data:s.data});try{let a=await i(e,N);return l({isFetching:!1,error:null,data:a}),a}catch(a){throw l({isFetching:false,error:a,data:null}),a}};return useEffect(()=>{t.enabled&&f();},[e,o,n]),{result:s,triggerMethod:f}}var c={};function F(e){if(!(e in c))throw new Error(`Unknown config: ${e}`);return c[e]?.value}function R(e){c=e;}var d=create(e=>({user:null,setUser:r=>e({user:r})})),M=false,z=a.seconds(30);async function P(){if(M)return;M=true;let{configs:e,session:r,user:t}=await i("_system.session.init");R(e),S(r);let o=t?Object.freeze(z$1.object({id:z$1.string(),handle:z$1.string()}).parse(t)):null;d.getState().setUser(o),await b();}async function b(){await i("_system.session.heartbeat"),setTimeout(b,z);}function g(e){d.getState().setUser(e);}function $(){return {user:d(r=>r.user)}}var v=false;function p({children:e,loadingElement:r}){let[t,o]=useState(true);return useEffect(()=>{async function n(){v||(v=true,await P(),o(false));}n();},[]),t?r??jsx("div",{children:"Loading..."}):jsx(Fragment,{children:e})}function V({loadingElement:e,routesElement:r,favicon:t,errorHandler:o}){if(o&&E(o),window.addEventListener("unload",()=>{}),D.createRoot(document.getElementById("root")).render(jsx(L.StrictMode,{children:jsx(U,{loadingElement:e,children:r})})),t){let n=document.querySelector("link[rel~='icon']");if(n)n.href=t;else {let s=document.createElement("link");s.rel="icon",s.href=t,document.head.appendChild(s);}}}async function G({email:e,password:r}){await i("_system.user.signupWithPassword",{email:e,password:r}),await k({email:e,password:r});}async function k({email:e,password:r}){let{user:t}=await i("_system.user.loginWithPassword",{email:e,password:r});return g(t),t}async function X(){await i("_system.user.logout"),g(null);}var U="useClient"in L?L.useClient(p):p;export{U as AppProvider,i as callMethod,F as getConfig,k as loginWithPassword,X as logout,V as renderApp,G as signupWithPassword,J as useMutation,W as useQuery,$ as useSession};//# sourceMappingURL=client.js.map
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../client/localStorage.ts","../client/errorHandler.ts","../client/method.ts","../config/client.ts","../client/session.ts","../client/AppProvider.tsx","../client/renderApp.tsx","../auth/client/index.ts","../client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","useQuery","options","triggerMethod","useMethod","useMutation","stableArgs","useMemo","stableOptions","setResult","useState","data","useEffect","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","initConfig","jsx","Fragment","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","logout"],"mappings":"qQAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,aAAa,OAAQ,CA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AAA,CAAK,KAAOH,CANH,CAAA,KAAA,CACT,IAAMI,CAAU,CAAA,QAAA,CAAS,cAAc,MAAM,CAAA,CAC7CA,EAAQ,GAAM,CAAA,MAAA,CACdA,EAAQ,IAAOJ,CAAAA,CAAAA,CACf,SAAS,IAAK,CAAA,WAAA,CAAYI,CAAO,EACnC,CAGF,CACF,CC/BA,eAAsBC,CAAAA,CAAmB,CAAE,KAAAC,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAA,CAAwC,CACjG,MAAMxD,CAAAA,CAAW,iCAAmC,CAAA,CAAE,KAAAuD,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAC,EAGvE,MAAMC,CAAAA,CAAkB,CAAE,KAAAF,CAAAA,CAAAA,CAAO,QAAAC,CAAAA,CAAS,CAAC,EAC7C,CAEA,eAAsBC,CAAAA,CAAkB,CAAE,KAAAF,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAA,CAAwC,CAChG,GAAM,CAAE,KAAA5B,CAAK,CAAA,CAAI,MAAM5B,CAA2B,CAAA,gCAAA,CAAkC,CAAE,KAAAuD,CAAAA,CAAAA,CAAO,QAAAC,CAAAA,CAAS,CAAC,CAAA,CACvG,OAAApB,CAAeR,CAAAA,CAAI,EACZA,CACT,CAEA,eAAsB8B,CAAS,EAAA,CAC7B,MAAM1D,CAAAA,CAAW,qBAAqB,CAAA,CACtCoC,EAAe,IAAI,EACrB,CClBaG,IAAAA,CAAAA,CAAc,cAAeY,CAEtCA,CAAAA,CAAAA,CAAM,SAAUZ,CAAAA,CAAmB,CACnCA,CAAAA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\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 { useState, useEffect, useMemo } from 'react';\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\ntype Args = Record<string, unknown>;\n\ntype MethodResult<T> = {\n isFetching: boolean;\n error: Error | null;\n data: T | null;\n};\n\nexport async function callMethod<T = unknown>(methodName: string, args: Args = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: Args): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\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\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\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\n/**\n * React hook for executing a query method.\n * \n * This hook automatically executes the query on mount and provides a refetch capability.\n * Similar to React Query's useQuery hook.\n * \n * @typeParam T - The expected return type of the query\n * @param methodName - The name of the method to query\n * @param args - Optional arguments to pass to the method\n * @param options - Optional options object\n * @param options.enabled - Boolean indicating if the query should be enabled\n * @returns {Object} An object containing the query state and a refetch function:\n * - `data` - The data returned by the query, or null if not yet loaded\n * - `isFetching` - Boolean indicating if the query is in progress\n * - `error` - Any error that occurred during the query, or null\n * - `refetch` - Function to manually trigger a refetch with optional new arguments\n * \n * @example\n * ```tsx\n * function MyComponent() {\n * // This is assuming you have a Module named \"todo\" with a query named \"getItem\"\n * const { data, isFetching, error } = useQuery<Todo>('todo.getItem', { id: '123' });\n * if (isFetching) {\n * return <div>Loading...</div>;\n * }\n * if (error) {\n * return <div>Error: {error.message}</div>;\n * }\n * return <div>{data?.name}</div>;\n * }\n * ```\n */\nexport function useQuery<T = unknown>(methodName: string, args: Args = {}, options?: { enabled?: boolean }): MethodResult<T> & {\n /** Function to manually trigger a refetch of the query with optional new arguments */\n refetch: (args?: Args) => void\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: options?.enabled ?? true });\n return {\n ...result,\n refetch: (args?: Args) => triggerMethod(args),\n };\n}\n\n/**\n * React hook for executing a mutation method.\n * \n * This hook provides functions to trigger the mutation manually and handles loading/error states.\n * Similar to React Query's useMutation hook.\n * \n * @typeParam T - The expected return type of the mutation\n * @param methodName - The name of the method to mutate\n * @param args - Optional default arguments to pass to the method\n * @returns {Object} An object containing the mutation state and trigger functions:\n * - `data` - The data returned by the last successful mutation, or null\n * - `isFetching` - Boolean indicating if the mutation is in progress\n * - `error` - Any error that occurred during the last mutation, or null\n * - `mutate` - Function to trigger the mutation with optional arguments\n * - `mutateAsync` - Promise-returning version of mutate, useful for awaiting the result\n * \n * @example\n * ```tsx\n * const { mutate: updateTodo, isFetching, error } = useMutation<User>('todos.update');\n * \n * // Later in your code:\n * updateTodo({ id: '123', name: 'New Name' });\n * ```\n */\nexport function useMutation<T = unknown>(methodName: string, args: Args = {}): MethodResult<T> & {\n /** Function to trigger the mutation with optional arguments */\n mutate: (args?: Args) => void,\n /** \n * Async version of mutate that returns a promise with the result.\n * Useful when you need to wait for the mutation to complete.\n */\n mutateAsync: (args?: Args) => Promise<T>\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: false });\n return {\n ...result,\n mutate: (args?: Args) => triggerMethod(args),\n mutateAsync: triggerMethod,\n };\n}\n\nexport function useMethod<T>(methodName: string, args: Args = {}, options: { enabled: boolean }): {\n result: MethodResult<T>,\n triggerMethod: (args?: Args) => Promise<T>\n} {\n // Memoize the args object to maintain reference stability and prevent infinite re-renders\n const stableArgs = useMemo(() => args, [JSON.stringify(args)]);\n const stableOptions = useMemo(() => options, [JSON.stringify(options)]);\n\n const [result, setResult] = useState<MethodResult<T>>({\n isFetching: options.enabled,\n error: null,\n data: null,\n });\n\n const triggerMethod = async (args: Args = stableArgs) => {\n setResult({ isFetching: true, error: null, data: result.data });\n try {\n const data = await callMethod<T>(methodName, args);\n setResult({ isFetching: false, error: null, data });\n return data;\n } catch (error) {\n setResult({ isFetching: false, error: error as Error, data: null });\n throw error;\n }\n };\n\n // TODO: switch to React Query (TanStack Query)\n useEffect(() => {\n if (!options.enabled) {\n return;\n }\n\n triggerMethod();\n }, [methodName, stableArgs, stableOptions]);\n\n return { result, triggerMethod };\n}\n","import { ConfigKey, AppConfig, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\nexport function getConfig(key: ConfigKey) {\n if (!(key in config)) {\n throw new Error(`Unknown config: ${key}`);\n }\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 { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return <>{children}</>;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\ntype User = {\n id: string;\n handle: string;\n};\n\nexport async function signupWithPassword({ email, password }: { email: string, password: string }) {\n await callMethod('_system.user.signupWithPassword', { email, password });\n\n // TODO: handle auto-login from the signup method itself to avoid a second method call\n await loginWithPassword({ email, password });\n}\n\nexport async function loginWithPassword({ email, password }: { email: string, password: string }) {\n const { user } = await callMethod<{ user: User }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = '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 { useQuery, useMutation, callMethod } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, logout } from './auth/client';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","useQuery","options","triggerMethod","useMethod","useMutation","stableArgs","useMemo","stableOptions","setResult","useState","data","useEffect","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","initConfig","jsx","Fragment","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","logout"],"mappings":"qQAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,aAAa,OAAQ,CAAA,mBAAmB,EAC5D,GAAI,CACF,OAAOA,CAAc,CAAA,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAASC,MAAAA,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAM,CAAA,yCAAA,CAA2CA,CAAC,CACnD,CAAA,IACT,CACF,CAEO,SAASC,EAAuBC,CAAiB,CAAA,CACtD,aAAa,OAAQ,CAAA,mBAAA,CAAqB,KAAK,SAAUA,CAAAA,CAAO,CAAC,EACnE,CCVA,IAAIC,CAA6B,CAAA,CAACC,CAAOC,CAAAA,CAAAA,GAAe,CACtD,MAAM,IAAI,KAAM,CAAA,CAAA,sBAAA,EAAyBA,CAAU,CAAMD,GAAAA,EAAAA,CAAAA,CAAM,UAAU,CAAA,CAAE,CAC7E,CAAA,CAEO,SAASE,CAAAA,CAAgBC,EAAuB,CACrDJ,CAAAA,CAAeI,EACjB,CAEO,SAASC,EAAYJ,CAAcC,CAAAA,CAAAA,CAAoB,CAC5D,OAAOF,CAAaC,CAAAA,CAAAA,CAAOC,CAAU,CACvC,CCUA,eAAsBI,CAAwBJ,CAAAA,CAAAA,CAAoBK,EAAa,EAAC,CAAe,CAC7F,GAAI,CACF,OAAO,MAAMC,CAAAA,CAAQ,yBAAyBN,CAAU,CAAA,CAAA,CAAIK,CAAI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7B,MAAM1D,CAAAA,CAAW,qBAAqB,CAAA,CACtCoC,EAAe,IAAI,EACrB,CClBaG,IAAAA,CAAAA,CAAc,cAAeY,CAEtCA,CAAAA,CAAAA,CAAM,SAAUZ,CAAAA,CAAmB,CACnCA,CAAAA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\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 { useState, useEffect, useMemo } from 'react';\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\ntype Args = Record<string, unknown>;\n\ntype MethodResult<T> = {\n isFetching: boolean;\n error: Error | null;\n data: T | null;\n};\n\nexport async function callMethod<T = unknown>(methodName: string, args: Args = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: Args): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\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\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\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\n/**\n * React hook for executing a query method.\n * \n * This hook automatically executes the query on mount and provides a refetch capability.\n * Similar to React Query's useQuery hook.\n * \n * @typeParam T - The expected return type of the query\n * @param methodName - The name of the method to query\n * @param args - Optional arguments to pass to the method\n * @param options - Optional options object\n * @param options.enabled - Boolean indicating if the query should be enabled\n * @returns {Object} An object containing the query state and a refetch function:\n * - `data` - The data returned by the query, or null if not yet loaded\n * - `isFetching` - Boolean indicating if the query is in progress\n * - `error` - Any error that occurred during the query, or null\n * - `refetch` - Function to manually trigger a refetch with optional new arguments\n * \n * @example\n * ```tsx\n * function MyComponent() {\n * // This is assuming you have a Module named \"todo\" with a query named \"getItem\"\n * const { data, isFetching, error } = useQuery<Todo>('todo.getItem', { id: '123' });\n * if (isFetching) {\n * return <div>Loading...</div>;\n * }\n * if (error) {\n * return <div>Error: {error.message}</div>;\n * }\n * return <div>{data?.name}</div>;\n * }\n * ```\n */\nexport function useQuery<T = unknown>(methodName: string, args: Args = {}, options?: { enabled?: boolean }): MethodResult<T> & {\n /** Function to manually trigger a refetch of the query with optional new arguments */\n refetch: (args?: Args) => void\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: options?.enabled ?? true });\n return {\n ...result,\n refetch: (args?: Args) => triggerMethod(args),\n };\n}\n\n/**\n * React hook for executing a mutation method.\n * \n * This hook provides functions to trigger the mutation manually and handles loading/error states.\n * Similar to React Query's useMutation hook.\n * \n * @typeParam T - The expected return type of the mutation\n * @param methodName - The name of the method to mutate\n * @param args - Optional default arguments to pass to the method\n * @returns {Object} An object containing the mutation state and trigger functions:\n * - `data` - The data returned by the last successful mutation, or null\n * - `isFetching` - Boolean indicating if the mutation is in progress\n * - `error` - Any error that occurred during the last mutation, or null\n * - `mutate` - Function to trigger the mutation with optional arguments\n * - `mutateAsync` - Promise-returning version of mutate, useful for awaiting the result\n * \n * @example\n * ```tsx\n * const { mutate: updateTodo, isFetching, error } = useMutation<User>('todos.update');\n * \n * // Later in your code:\n * updateTodo({ id: '123', name: 'New Name' });\n * ```\n */\nexport function useMutation<T = unknown>(methodName: string, args: Args = {}): MethodResult<T> & {\n /** Function to trigger the mutation with optional arguments */\n mutate: (args?: Args) => void,\n /** \n * Async version of mutate that returns a promise with the result.\n * Useful when you need to wait for the mutation to complete.\n */\n mutateAsync: (args?: Args) => Promise<T>\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: false });\n return {\n ...result,\n mutate: (args?: Args) => triggerMethod(args),\n mutateAsync: triggerMethod,\n };\n}\n\nexport function useMethod<T>(methodName: string, args: Args = {}, options: { enabled: boolean }): {\n result: MethodResult<T>,\n triggerMethod: (args?: Args) => Promise<T>\n} {\n // Memoize the args object to maintain reference stability and prevent infinite re-renders\n const stableArgs = useMemo(() => args, [JSON.stringify(args)]);\n const stableOptions = useMemo(() => options, [JSON.stringify(options)]);\n\n const [result, setResult] = useState<MethodResult<T>>({\n isFetching: options.enabled,\n error: null,\n data: null,\n });\n\n const triggerMethod = async (args: Args = stableArgs) => {\n setResult({ isFetching: true, error: null, data: result.data });\n try {\n const data = await callMethod<T>(methodName, args);\n setResult({ isFetching: false, error: null, data });\n return data;\n } catch (error) {\n setResult({ isFetching: false, error: error as Error, data: null });\n throw error;\n }\n };\n\n // TODO: switch to React Query (TanStack Query)\n useEffect(() => {\n if (!options.enabled) {\n return;\n }\n\n triggerMethod();\n }, [methodName, stableArgs, stableOptions]);\n\n return { result, triggerMethod };\n}\n","import { ConfigKey, AppConfig, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\nexport function getConfig(key: ConfigKey) {\n if (!(key in config)) {\n throw new Error(`Unknown config: ${key}`);\n }\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 { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return <>{children}</>;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\ntype User = {\n id: string;\n handle: string;\n};\n\nexport async function signupWithPassword({ email, password }: { email: string, password: string }) {\n await callMethod('_system.user.signupWithPassword', { email, password });\n\n // TODO: handle auto-login from the signup method itself to avoid a second method call\n await loginWithPassword({ email, password });\n}\n\nexport async function loginWithPassword({ email, password }: { email: string, password: string }) {\n const { user } = await callMethod<{ user: User }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = '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 { useQuery, useMutation, callMethod } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, logout } from './auth/client';\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
export { C as ConfigSchema } from './types-RXrmChkk.js';
|
|
2
|
-
export { M as ModelenceConfig } from './index-5e-76duG.js';
|
|
3
|
-
import 'express';
|
|
4
2
|
|
|
5
3
|
declare const time: {
|
|
6
4
|
seconds: (x: number) => number;
|
|
@@ -19,4 +17,10 @@ declare class ValidationError extends Error {
|
|
|
19
17
|
constructor(message: string);
|
|
20
18
|
}
|
|
21
19
|
|
|
22
|
-
|
|
20
|
+
interface ModelenceConfig {
|
|
21
|
+
serverDir: string;
|
|
22
|
+
serverEntry: string;
|
|
23
|
+
postBuildCommand?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export { AuthError, type ModelenceConfig, ValidationError, time };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as AuthError,b as ValidationError}from'./chunk-
|
|
1
|
+
export{a as AuthError,b as ValidationError}from'./chunk-EQLDF7OO.js';export{a as time}from'./chunk-R7MPLJMA.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/mongo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../mongo.ts"],"names":["mongo_default"],"mappings":"4CAEA,IAAOA,EAAQ","file":"mongo.js","sourcesContent":["export { ClientSession, ObjectId } from 'mongodb';\n\nexport default {};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/mongo.ts"],"names":["mongo_default"],"mappings":"4CAEA,IAAOA,EAAQ","file":"mongo.js","sourcesContent":["export { ClientSession, ObjectId } from 'mongodb';\n\nexport default {};\n"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -3,8 +3,7 @@ import { ObjectId as ObjectId$1, WithId, IndexDescription, MongoClient, Collecti
|
|
|
3
3
|
export { ObjectId } from 'mongodb';
|
|
4
4
|
import * as zod from 'zod';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
-
import { Request } from 'express';
|
|
7
|
-
import { A as AppServer } from './index-5e-76duG.js';
|
|
6
|
+
import { Request, Response, NextFunction } from 'express';
|
|
8
7
|
|
|
9
8
|
type CronJobHandler = () => Promise<void>;
|
|
10
9
|
type CronJobInputParams = {
|
|
@@ -343,6 +342,13 @@ type MigrationScript = {
|
|
|
343
342
|
handler: () => Promise<void>;
|
|
344
343
|
};
|
|
345
344
|
|
|
345
|
+
type ExpressMiddleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
|
|
346
|
+
interface AppServer {
|
|
347
|
+
init: () => Promise<void>;
|
|
348
|
+
handler: (req: Request, res: Response) => void;
|
|
349
|
+
middlewares?: () => ExpressMiddleware[];
|
|
350
|
+
}
|
|
351
|
+
|
|
346
352
|
type AppOptions = {
|
|
347
353
|
modules?: Module[];
|
|
348
354
|
server?: AppServer;
|