@monorise/cli 4.0.0 → 4.2.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,11 +2,149 @@
2
2
 
3
3
  // cli.ts
4
4
  import "tsx";
5
- import "tsconfig-paths/register.js";
6
5
  import fs2 from "fs";
7
6
  import path2 from "path";
7
+ import { execSync } from "child_process";
8
8
  import chokidar from "chokidar";
9
9
 
10
+ // commands/utils/analytics-manifest.ts
11
+ import { createHash } from "crypto";
12
+ var lowerKebabCase = /^[a-z]+(?:-[a-z]+)*$/;
13
+ function normalizeSqlIdentifier(name) {
14
+ const normalized = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
15
+ return /^[a-z_]/.test(normalized) ? normalized : `_${normalized}`;
16
+ }
17
+ function athenaType(schema, path3) {
18
+ let current = schema;
19
+ while (current._def?.typeName === "ZodOptional" || current._def?.typeName === "ZodNullable" || current._def?.typeName === "ZodDefault") {
20
+ const innerType = current._def?.innerType;
21
+ if (!innerType) break;
22
+ current = innerType;
23
+ }
24
+ switch (current._def?.typeName) {
25
+ case "ZodString":
26
+ return current._def.checks?.some((check) => check.kind === "datetime") ? "timestamp" : "string";
27
+ case "ZodNumber":
28
+ return "double";
29
+ case "ZodBoolean":
30
+ return "boolean";
31
+ case "ZodDate":
32
+ return "timestamp";
33
+ case "ZodArray":
34
+ case "ZodObject":
35
+ return "json";
36
+ default:
37
+ throw new Error(
38
+ `Unsupported analytics schema field ${path3}. Supported types are string, number, boolean, datetime, arrays, and objects.`
39
+ );
40
+ }
41
+ }
42
+ function columns(schema, path3) {
43
+ if (!schema.shape) {
44
+ throw new Error(`Analytics schema ${path3} must be a Zod object.`);
45
+ }
46
+ const names = /* @__PURE__ */ new Map();
47
+ return Object.entries(schema.shape).map(([sourceName, field]) => {
48
+ const name = normalizeSqlIdentifier(sourceName);
49
+ const existing = names.get(name);
50
+ if (existing) {
51
+ throw new Error(
52
+ `Analytics column identifier collision in ${path3}: ${existing} and ${sourceName} both normalize to ${name}.`
53
+ );
54
+ }
55
+ names.set(name, sourceName);
56
+ return {
57
+ name,
58
+ sourceName,
59
+ type: athenaType(field, `${path3}.${sourceName}`)
60
+ };
61
+ });
62
+ }
63
+ function fingerprint(datasets) {
64
+ return createHash("sha256").update(JSON.stringify(datasets)).digest("hex");
65
+ }
66
+ function validateSchemaEvolution(previous, next) {
67
+ const nextDatasets = new Map(
68
+ next.datasets.map((dataset) => [dataset.identifier, dataset])
69
+ );
70
+ for (const previousDataset of previous.datasets) {
71
+ const nextDataset = nextDatasets.get(previousDataset.identifier);
72
+ if (!nextDataset) {
73
+ throw new Error(
74
+ `Analytics dataset ${previousDataset.name} was removed. Supply an explicit analytics migration.`
75
+ );
76
+ }
77
+ const nextColumns = new Map(
78
+ nextDataset.columns.map((column) => [column.name, column])
79
+ );
80
+ for (const previousColumn of previousDataset.columns) {
81
+ const nextColumn = nextColumns.get(previousColumn.name);
82
+ if (!nextColumn) {
83
+ throw new Error(
84
+ `Analytics field ${previousDataset.name}.${previousColumn.sourceName} was removed or renamed. Supply an explicit analytics migration.`
85
+ );
86
+ }
87
+ if (nextColumn.type !== previousColumn.type) {
88
+ throw new Error(
89
+ `Analytics field ${previousDataset.name}.${previousColumn.sourceName} changed from ${previousColumn.type} to ${nextColumn.type}. Supply an explicit analytics migration.`
90
+ );
91
+ }
92
+ }
93
+ }
94
+ }
95
+ function createAnalyticsManifest(configs) {
96
+ const datasets = [];
97
+ const unnamedMutuals = /* @__PURE__ */ new Set();
98
+ const identifiers = /* @__PURE__ */ new Map();
99
+ const mutuals = /* @__PURE__ */ new Set();
100
+ const addDataset = (kind, name, schema) => {
101
+ if (!lowerKebabCase.test(name)) {
102
+ throw new Error(
103
+ `Invalid analytics ${kind} name: ${name}. Must be lower-kebab-case.`
104
+ );
105
+ }
106
+ const identifier = normalizeSqlIdentifier(name);
107
+ const existing = identifiers.get(identifier);
108
+ if (existing) {
109
+ throw new Error(
110
+ `Analytics dataset identifier collision: ${existing} and ${name} both normalize to ${identifier}.`
111
+ );
112
+ }
113
+ identifiers.set(identifier, name);
114
+ datasets.push({
115
+ kind,
116
+ name,
117
+ identifier,
118
+ currentTable: `${identifier}_${kind === "entity" ? "entities" : "mutuals"}`,
119
+ historyTable: `${identifier}_${kind === "entity" ? "entity_changes" : "mutual_changes"}`,
120
+ columns: columns(schema, `${kind} ${name}`),
121
+ partition: { granularity: "day" }
122
+ });
123
+ };
124
+ for (const config of configs) {
125
+ addDataset("entity", config.name, config.finalSchema);
126
+ for (const field of Object.values(config.mutual?.mutualFields ?? {})) {
127
+ const mutual = field.mutual;
128
+ if (!mutual?.name) {
129
+ unnamedMutuals.add(`${config.name}.${field.entityType}`);
130
+ continue;
131
+ }
132
+ if (mutuals.has(mutual)) continue;
133
+ mutuals.add(mutual);
134
+ addDataset("mutual", mutual.name, mutual.mutualDataSchema);
135
+ }
136
+ }
137
+ return {
138
+ version: 1,
139
+ datasets,
140
+ unnamedMutuals: [...unnamedMutuals].sort(),
141
+ schemaFingerprint: fingerprint(datasets)
142
+ };
143
+ }
144
+
145
+ // cli.ts
146
+ import { fileURLToPath } from "url";
147
+
10
148
  // commands/utils/detect-package.ts
11
149
  import fs from "fs";
12
150
  import path from "path";
@@ -23,13 +161,43 @@ function detectCombinedPackage(startDir) {
23
161
  return false;
24
162
  }
25
163
 
164
+ // templates/root-tsconfig.ts
165
+ var ROOT_TSCONFIG_TEMPLATE = {
166
+ compilerOptions: {
167
+ target: "ES2022",
168
+ module: "ESNext",
169
+ moduleResolution: "bundler",
170
+ esModuleInterop: true,
171
+ strict: true,
172
+ skipLibCheck: true,
173
+ jsx: "preserve",
174
+ paths: {
175
+ "#/shared/*": ["./shared/*"],
176
+ "#/monorise/*": ["./.monorise/*"],
177
+ "#/monorise": ["./.monorise/index"]
178
+ }
179
+ },
180
+ include: ["**/*.ts", ".monorise/**/*.ts"],
181
+ exclude: ["node_modules", "apps"]
182
+ };
183
+
26
184
  // cli.ts
185
+ var __filename = fileURLToPath(import.meta.url);
186
+ var __dirname = path2.dirname(__filename);
187
+ var TEMPLATES_DIR = path2.join(__dirname, "templates", "files");
188
+ function readTemplate(filename) {
189
+ return fs2.readFileSync(path2.join(TEMPLATES_DIR, filename), "utf-8");
190
+ }
27
191
  function kebabToCamel(str) {
28
192
  return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
29
193
  }
30
194
  function kebabToPascal(kebab) {
31
195
  return kebab.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
32
196
  }
197
+ function execCommand(command, cwd, stdio = "inherit") {
198
+ console.log(`Running: ${command}`);
199
+ execSync(command, { cwd, stdio });
200
+ }
33
201
  async function generateConfigFile(configDir, monoriseOutputDir, projectRoot) {
34
202
  const configOutputPath = path2.join(monoriseOutputDir, "config.ts");
35
203
  const initialConfigContent = `
@@ -47,6 +215,7 @@ export enum Entity {}
47
215
  const schemaEntries = [];
48
216
  const allowedEntityEntries = [];
49
217
  const entityWithEmailAuthEntries = [];
218
+ const analyticsConfigs = [];
50
219
  const relativePathToConfigDir = path2.relative(monoriseOutputDir, configDir);
51
220
  const importPathPrefix = relativePathToConfigDir ? `${relativePathToConfigDir}/` : "./";
52
221
  for (const file of files) {
@@ -62,6 +231,7 @@ export enum Entity {}
62
231
  throw new Error(`Duplicate name found: ${config.name} in ${file}`);
63
232
  }
64
233
  names.add(config.name);
234
+ analyticsConfigs.push(config);
65
235
  const fileName = file.replace(/\.ts$/, "");
66
236
  const variableName = kebabToCamel(fileName);
67
237
  imports.push(
@@ -144,7 +314,28 @@ export default config;
144
314
  ${moduleAugmentations}
145
315
  `;
146
316
  fs2.writeFileSync(configOutputPath, configOutputContent);
317
+ const analyticsManifestPath = path2.join(
318
+ monoriseOutputDir,
319
+ "analytics-manifest.json"
320
+ );
321
+ const manifest = createAnalyticsManifest(analyticsConfigs);
322
+ if (fs2.existsSync(analyticsManifestPath)) {
323
+ validateSchemaEvolution(
324
+ JSON.parse(fs2.readFileSync(analyticsManifestPath, "utf8")),
325
+ manifest
326
+ );
327
+ }
328
+ fs2.writeFileSync(analyticsManifestPath, `${JSON.stringify(manifest, null, 2)}
329
+ `);
147
330
  console.log("Successfully generated config.ts!");
331
+ const indexOutputPath = path2.join(monoriseOutputDir, "index.ts");
332
+ fs2.writeFileSync(
333
+ indexOutputPath,
334
+ `export * from './config';
335
+ export { default } from './config';
336
+ `
337
+ );
338
+ console.log("Successfully generated index.ts!");
148
339
  return configOutputPath;
149
340
  }
150
341
  async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir) {
@@ -196,6 +387,9 @@ ${routesImportLine ? `${routesImportLine}
196
387
  ` : ""}const coreFactory = new CoreFactory(config);
197
388
 
198
389
  export const replicationHandler = coreFactory.replicationProcessor;
390
+ export const analyticsHandler = coreFactory.analyticsProcessor;
391
+ export const analyticsBackfillHandler = coreFactory.analyticsBackfillProcessor;
392
+ export { analyticsMaterializationProcessor as analyticsMaterializationHandler } from '${coreImportPath}';
199
393
  export const mutualHandler = coreFactory.mutualProcessor;
200
394
  export const tagHandler = coreFactory.tagProcessor;
201
395
  export const treeHandler = coreFactory.prejoinProcessor;
@@ -278,123 +472,277 @@ var MONORISE_LOGO = `
278
472
 
279
473
  `;
280
474
  async function runInitCommand(rootPath) {
281
- const projectRoot = rootPath ? path2.resolve(rootPath) : process.cwd();
282
475
  console.log(MONORISE_LOGO);
283
- console.log(`Initializing Monorise project in ${projectRoot}...`);
284
- const monoriseConfigTsPath = path2.join(projectRoot, "monorise.config.ts");
285
- const monoriseConfigContent = `
286
- const config = {
287
- configDir: './monorise/entities',
288
- // custom route file should export default an Hono object.
289
- // customRoutes: './path/to/custom/routes.ts'
290
- };
291
-
292
- export default config;
293
- `;
294
- if (!fs2.existsSync(monoriseConfigTsPath)) {
295
- fs2.writeFileSync(monoriseConfigTsPath, monoriseConfigContent.trimStart());
296
- console.log(`Created ${path2.relative(projectRoot, monoriseConfigTsPath)}`);
476
+ let projectName = "my-app";
477
+ let projectRoot;
478
+ if (rootPath) {
479
+ projectRoot = path2.resolve(rootPath);
480
+ projectName = path2.basename(projectRoot);
297
481
  } else {
298
- console.log(
299
- `${path2.relative(projectRoot, monoriseConfigTsPath)} already exists. Skipping.`
300
- );
482
+ const args = process.argv.slice(2);
483
+ const nameIndex = args.indexOf("--name");
484
+ if (nameIndex > -1 && args[nameIndex + 1]) {
485
+ projectName = args[nameIndex + 1];
486
+ }
487
+ projectRoot = path2.resolve(projectName);
301
488
  }
302
- const monoriseEntitiesDir = path2.join(projectRoot, "monorise", "entities");
303
- fs2.mkdirSync(monoriseEntitiesDir, { recursive: true });
304
- const userEntityTsPath = path2.join(monoriseEntitiesDir, "user.ts");
305
- const userEntityContent = `
306
- import { createEntityConfig } from 'monorise/base';
307
- import { z } from 'zod';
308
-
309
- const baseSchema = z
310
- .object({
311
- displayName: z
312
- .string()
313
- .min(1, 'Please provide a name for this user account'),
314
- firstName: z.string().min(1, 'Please provide first name'),
315
- lastName: z.string().min(1, 'Please provide last name'),
316
- jobTitle: z.string(),
317
- })
318
- .partial();
319
-
320
- const config = createEntityConfig({
321
- name: 'user',
322
- baseSchema,
323
- });
324
-
325
- export default config;
326
- `;
327
- if (!fs2.existsSync(userEntityTsPath)) {
328
- fs2.writeFileSync(userEntityTsPath, userEntityContent.trimStart());
329
- console.log(`Created ${path2.relative(projectRoot, userEntityTsPath)}`);
330
- } else {
331
- console.log(
332
- `${path2.relative(projectRoot, userEntityTsPath)} already exists. Skipping.`
489
+ console.log(`
490
+ \u{1F680} Creating Monorise project: ${projectName}
491
+ `);
492
+ if (fs2.existsSync(projectRoot)) {
493
+ console.error(`Error: Directory ${projectName} already exists.`);
494
+ process.exit(1);
495
+ }
496
+ console.log("\u{1F4C1} Creating project structure...");
497
+ fs2.mkdirSync(projectRoot, { recursive: true });
498
+ fs2.mkdirSync(path2.join(projectRoot, "apps"), { recursive: true });
499
+ fs2.mkdirSync(path2.join(projectRoot, "services", "core"), { recursive: true });
500
+ fs2.mkdirSync(path2.join(projectRoot, "monorise", "configs"), { recursive: true });
501
+ fs2.mkdirSync(path2.join(projectRoot, "monorise", "mutuals"), { recursive: true });
502
+ console.log("\u{1F4E6} Initializing root package.json...");
503
+ const rootPackageJson = {
504
+ name: projectName,
505
+ version: "0.0.0",
506
+ type: "module",
507
+ private: true,
508
+ workspaces: ["apps/*", "services/*"]
509
+ };
510
+ fs2.writeFileSync(
511
+ path2.join(projectRoot, "package.json"),
512
+ JSON.stringify(rootPackageJson, null, 2)
513
+ );
514
+ console.log("\u2699\uFE0F Creating root tsconfig.json...");
515
+ fs2.writeFileSync(
516
+ path2.join(projectRoot, "tsconfig.json"),
517
+ JSON.stringify(ROOT_TSCONFIG_TEMPLATE, null, 2)
518
+ );
519
+ console.log("\n\u{1F4F1} Creating Next.js app in apps/web...");
520
+ const nextAppDir = path2.join(projectRoot, "apps", "web");
521
+ try {
522
+ execCommand(
523
+ `npx create-next-app@latest web --typescript --tailwind --eslint --app --no-src-dir --import-alias "#/*" --no-turbopack --yes`,
524
+ path2.join(projectRoot, "apps")
333
525
  );
526
+ } catch (error) {
527
+ console.error("Failed to create Next.js app:", error);
528
+ process.exit(1);
334
529
  }
335
- const packageJsonPath = path2.join(projectRoot, "package.json");
336
- if (fs2.existsSync(packageJsonPath)) {
530
+ console.log("\n\u2601\uFE0F Installing SST v4...");
531
+ try {
532
+ execCommand("npm install sst@^4 --save-dev", projectRoot);
533
+ } catch (error) {
534
+ console.error("Failed to install SST:", error);
535
+ process.exit(1);
536
+ }
537
+ console.log("\n\u{1F4E6} Installing dependencies (monorise, hono, zod, shadcn utilities)...");
538
+ try {
539
+ execCommand("npm install monorise hono zod clsx class-variance-authority radix-ui lucide-react tailwind-merge react-hook-form @hookform/resolvers", projectRoot);
540
+ } catch (error) {
541
+ console.error("Failed to install dependencies:", error);
542
+ process.exit(1);
543
+ }
544
+ console.log("\u2699\uFE0F Creating monorise.config.ts...");
545
+ fs2.writeFileSync(
546
+ path2.join(projectRoot, "monorise.config.ts"),
547
+ readTemplate("monorise.config.ts")
548
+ );
549
+ console.log("\u{1F517} Creating team-membership mutual config...");
550
+ fs2.writeFileSync(
551
+ path2.join(projectRoot, "monorise", "mutuals", "team-membership.ts"),
552
+ readTemplate("team-membership.mutual.ts")
553
+ );
554
+ console.log("\u{1F464} Creating starter User entity...");
555
+ fs2.writeFileSync(
556
+ path2.join(projectRoot, "monorise", "configs", "user.ts"),
557
+ readTemplate("user-entity.ts")
558
+ );
559
+ console.log("\u{1F465} Creating starter Team entity...");
560
+ fs2.writeFileSync(
561
+ path2.join(projectRoot, "monorise", "configs", "team.ts"),
562
+ readTemplate("team-entity.ts")
563
+ );
564
+ console.log("\u{1F527} Creating services/core/routes.ts...");
565
+ fs2.writeFileSync(
566
+ path2.join(projectRoot, "services", "core", "routes.ts"),
567
+ readTemplate("core-routes.ts")
568
+ );
569
+ const servicesPackageJson = {
570
+ name: "@my-app/services",
571
+ version: "0.0.0",
572
+ type: "module"
573
+ };
574
+ fs2.writeFileSync(
575
+ path2.join(projectRoot, "services", "core", "package.json"),
576
+ JSON.stringify(servicesPackageJson, null, 2)
577
+ );
578
+ console.log("\u2699\uFE0F Creating sst.config.ts with Monorise...");
579
+ const sstConfigPath = path2.join(projectRoot, "sst.config.ts");
580
+ fs2.writeFileSync(sstConfigPath, readTemplate("sst.config.ts").replace("{{PROJECT_NAME}}", projectName));
581
+ console.log("\n\u2601\uFE0F Installing SST providers...");
582
+ try {
583
+ execCommand("npx sst install", projectRoot);
584
+ } catch (error) {
585
+ console.warn("Warning: SST install failed, continuing anyway...");
586
+ }
587
+ console.log("\u{1F4C4} Creating example page in apps/web...");
588
+ const webSrcAppDir = path2.join(projectRoot, "apps", "web", "src", "app");
589
+ const webAppDir = path2.join(projectRoot, "apps", "web", "app");
590
+ const pagePath = fs2.existsSync(webSrcAppDir) ? path2.join(webSrcAppDir, "page.tsx") : fs2.existsSync(webAppDir) ? path2.join(webAppDir, "page.tsx") : null;
591
+ if (pagePath) {
337
592
  try {
338
- const packageJsonContent = fs2.readFileSync(packageJsonPath, "utf8");
339
- const packageJson = JSON.parse(packageJsonContent);
340
- if (packageJson.type !== "module") {
341
- packageJson.type = "module";
342
- fs2.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
343
- console.log(
344
- `Updated 'type' to 'module' in ${path2.relative(projectRoot, packageJsonPath)}`
345
- );
346
- } else {
347
- console.log(
348
- `'type: "module"' already set in ${path2.relative(projectRoot, packageJsonPath)}. Skipping.`
593
+ fs2.writeFileSync(pagePath, readTemplate("example-page.tsx"));
594
+ console.log(`Created example page at ${path2.relative(projectRoot, pagePath)}`);
595
+ } catch (error) {
596
+ console.warn("Warning: Could not create example page:", error);
597
+ }
598
+ } else {
599
+ console.warn("Warning: Could not find apps/web/src/app or apps/web/app directory");
600
+ }
601
+ const webRoot = fs2.existsSync(webSrcAppDir) ? path2.join(projectRoot, "apps", "web", "src") : fs2.existsSync(webAppDir) ? path2.join(projectRoot, "apps", "web") : null;
602
+ if (webRoot) {
603
+ const appDir = fs2.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;
604
+ fs2.mkdirSync(path2.join(webRoot, "components", "ui"), { recursive: true });
605
+ fs2.mkdirSync(path2.join(webRoot, "lib"), { recursive: true });
606
+ console.log("\u{1F310} Creating global components...");
607
+ fs2.writeFileSync(
608
+ path2.join(webRoot, "components", "global-initializer.tsx"),
609
+ readTemplate("global-initializer.tsx")
610
+ );
611
+ fs2.writeFileSync(
612
+ path2.join(webRoot, "components", "global-loader.tsx"),
613
+ readTemplate("global-loader.tsx")
614
+ );
615
+ console.log("\u{1F527} Creating lib/utils.ts...");
616
+ fs2.writeFileSync(
617
+ path2.join(webRoot, "lib", "utils.ts"),
618
+ readTemplate("lib-utils.ts")
619
+ );
620
+ console.log("\u{1F3A8} Creating shadcn UI components...");
621
+ fs2.writeFileSync(
622
+ path2.join(webRoot, "components", "ui", "button.tsx"),
623
+ readTemplate("ui-button.tsx")
624
+ );
625
+ fs2.writeFileSync(
626
+ path2.join(webRoot, "components", "ui", "card.tsx"),
627
+ readTemplate("ui-card.tsx")
628
+ );
629
+ fs2.writeFileSync(
630
+ path2.join(webRoot, "components", "ui", "input.tsx"),
631
+ readTemplate("ui-input.tsx")
632
+ );
633
+ fs2.writeFileSync(
634
+ path2.join(webRoot, "components", "ui", "label.tsx"),
635
+ readTemplate("ui-label.tsx")
636
+ );
637
+ console.log("\u{1F3A8} Setting up shadcn globals.css...");
638
+ const globalsCssPath = path2.join(appDir, "globals.css");
639
+ fs2.writeFileSync(globalsCssPath, readTemplate("globals.css"));
640
+ console.log("\u{1F4D0} Updating layout.tsx with global components...");
641
+ const layoutPath = path2.join(appDir, "layout.tsx");
642
+ if (fs2.existsSync(layoutPath)) {
643
+ try {
644
+ let layoutContent = fs2.readFileSync(layoutPath, "utf8");
645
+ const globalImports = `import GlobalInitializer from '#/components/global-initializer';
646
+ import GlobalLoader from '#/components/global-loader';`;
647
+ const lastImportIndex = layoutContent.lastIndexOf("import ");
648
+ const lineEnd = layoutContent.indexOf("\n", lastImportIndex);
649
+ layoutContent = layoutContent.slice(0, lineEnd + 1) + globalImports + "\n" + layoutContent.slice(lineEnd + 1);
650
+ layoutContent = layoutContent.replace(
651
+ /(<body[^>]*>)/,
652
+ `$1
653
+ <div id="loader-portal" />
654
+ <GlobalInitializer />
655
+ <GlobalLoader />`
349
656
  );
657
+ fs2.writeFileSync(layoutPath, layoutContent);
658
+ } catch (error) {
659
+ console.warn("Warning: Could not update layout.tsx:", error);
350
660
  }
351
- } catch (error) {
352
- console.error(
353
- `Error reading or parsing ${path2.relative(projectRoot, packageJsonPath)}:`,
354
- error
661
+ }
662
+ const postcssPath = path2.join(projectRoot, "apps", "web", "postcss.config.mjs");
663
+ if (fs2.existsSync(postcssPath)) {
664
+ fs2.writeFileSync(
665
+ postcssPath,
666
+ `const config = {
667
+ plugins: {
668
+ '@tailwindcss/postcss': {},
669
+ },
670
+ };
671
+
672
+ export default config;
673
+ `
355
674
  );
356
675
  }
357
- } else {
358
- console.warn(
359
- `Warning: ${path2.relative(projectRoot, packageJsonPath)} not found. Cannot update 'type'.`
676
+ console.log("\u{1F500} Creating API proxy routes...");
677
+ const apiDir = path2.join(appDir, "api");
678
+ const catchAllDir = path2.join(apiDir, "[...proxy]");
679
+ fs2.mkdirSync(catchAllDir, { recursive: true });
680
+ fs2.writeFileSync(
681
+ path2.join(apiDir, "proxy-request.ts"),
682
+ readTemplate("proxy-request.ts")
683
+ );
684
+ fs2.writeFileSync(
685
+ path2.join(catchAllDir, "route.ts"),
686
+ readTemplate("proxy-route.ts")
360
687
  );
361
688
  }
362
- const tsconfigPath = path2.join(projectRoot, "tsconfig.json");
363
- if (fs2.existsSync(tsconfigPath)) {
689
+ console.log("\u2699\uFE0F Updating apps/web tsconfig.json...");
690
+ const webTsconfigPath = path2.join(projectRoot, "apps", "web", "tsconfig.json");
691
+ if (fs2.existsSync(webTsconfigPath)) {
364
692
  try {
365
- const tsconfigContent = fs2.readFileSync(tsconfigPath, "utf8");
366
- const tsconfig = JSON.parse(tsconfigContent);
367
- if (!tsconfig.compilerOptions) {
368
- tsconfig.compilerOptions = {};
693
+ const webTsconfigContent = fs2.readFileSync(webTsconfigPath, "utf8");
694
+ const webTsconfig = JSON.parse(webTsconfigContent);
695
+ if (!webTsconfig.compilerOptions) {
696
+ webTsconfig.compilerOptions = {};
369
697
  }
370
- if (!tsconfig.compilerOptions.paths) {
371
- tsconfig.compilerOptions.paths = {};
372
- }
373
- const pathKey = "#/monorise/*";
374
- const pathValue = ["./.monorise/*"];
375
- if (!tsconfig.compilerOptions.paths[pathKey]) {
376
- tsconfig.compilerOptions.paths[pathKey] = pathValue;
377
- fs2.writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2));
378
- console.log(
379
- `Added '${pathKey}' path alias in ${path2.relative(projectRoot, tsconfigPath)}`
380
- );
381
- } else {
382
- console.log(
383
- `'${pathKey}' path alias already set in ${path2.relative(projectRoot, tsconfigPath)}. Skipping.`
384
- );
698
+ if (!webTsconfig.compilerOptions.paths) {
699
+ webTsconfig.compilerOptions.paths = {};
385
700
  }
701
+ webTsconfig.compilerOptions.paths["#/shared/*"] = ["../../shared/*"];
702
+ webTsconfig.compilerOptions.paths["#/monorise/*"] = ["../../.monorise/*"];
703
+ webTsconfig.compilerOptions.paths["#/monorise"] = ["../../.monorise/index"];
704
+ const hasSrcDir = fs2.existsSync(path2.join(projectRoot, "apps", "web", "src"));
705
+ webTsconfig.compilerOptions.paths["#/*"] = [hasSrcDir ? "./src/*" : "./*"];
706
+ fs2.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));
386
707
  } catch (error) {
387
- console.error(
388
- `Error updating ${path2.relative(projectRoot, tsconfigPath)}:`,
389
- error
390
- );
708
+ console.warn("Warning: Could not update apps/web tsconfig.json:", error);
391
709
  }
392
- } else {
393
- console.warn(
394
- `Warning: ${path2.relative(projectRoot, tsconfigPath)} not found. Cannot add path alias.`
395
- );
396
710
  }
397
- console.log("Monorise initialization complete!");
711
+ console.log("\n\u{1F528} Running initial Monorise build...");
712
+ try {
713
+ execCommand("npx monorise build", projectRoot);
714
+ } catch (error) {
715
+ console.warn("Warning: Initial monorise build failed. You can run it manually later.");
716
+ }
717
+ console.log("\n" + "=".repeat(60));
718
+ console.log("\u2705 Monorise project created successfully!");
719
+ console.log("=".repeat(60));
720
+ console.log(`
721
+ \u{1F4C1} Project structure:`);
722
+ console.log(` ${projectName}/`);
723
+ console.log(` \u251C\u2500\u2500 apps/web/ # Next.js frontend`);
724
+ console.log(` \u251C\u2500\u2500 services/core/ # Backend routes (Hono)`);
725
+ console.log(` \u251C\u2500\u2500 monorise/configs/ # Entity definitions (User, Team)`);
726
+ console.log(` \u251C\u2500\u2500 monorise/mutuals/ # Shared mutual relationship configs`);
727
+ console.log(` \u2514\u2500\u2500 .monorise/ # Generated files`);
728
+ console.log(`
729
+ \u{1F4C2} Where to start coding:`);
730
+ console.log(` \u2022 Edit your data model \u2192 monorise/configs/user.ts`);
731
+ console.log(` (Add fields like phone, role, status to the User entity)`);
732
+ console.log(
733
+ ` \u2022 Build your UI \u2192 ${pagePath ? path2.relative(projectRoot, pagePath) : "apps/web/app/page.tsx"}`
734
+ );
735
+ console.log(` (React components using useEntities and createEntity)`);
736
+ console.log(` \u2022 Add backend logic \u2192 services/core/routes.ts`);
737
+ console.log(` (Custom API endpoints with Hono)`);
738
+ console.log(` \u2022 See the User <-> Team relationship \u2192 monorise/mutuals/team-membership.ts`);
739
+ console.log(` (createMutualConfig \u2014 shared schema, referenced from both entity configs)`);
740
+ console.log(`
741
+ \u{1F680} Next steps:`);
742
+ console.log(` cd ${projectName}`);
743
+ console.log(` npx sst dev`);
744
+ console.log("\n\u{1F4DA} Documentation: https://monorise.dev");
745
+ console.log("");
398
746
  }
399
747
  async function runDevCommand(configDir, rootPath) {
400
748
  console.log(MONORISE_LOGO);
@@ -465,10 +813,10 @@ async function main() {
465
813
  } else if (command === "build") {
466
814
  await runBuildCommand(rootPath);
467
815
  } else if (command === "init") {
468
- await runInitCommand(rootPath);
816
+ await runInitCommand();
469
817
  } else {
470
818
  console.error(
471
- "Unknown command. Usage: monorise [dev|build|init] [--config-root <path>]"
819
+ "Unknown command. Usage:\n monorise dev [--config-root <path>]\n monorise build [--config-root <path>]\n monorise init [--name <project-name>]"
472
820
  );
473
821
  process.exit(1);
474
822
  }