@codelitdev/platform-cli 0.1.0-alpha.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.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +43 -0
  4. package/dist/codemod-readme-title.d.ts +5 -0
  5. package/dist/codemod-readme-title.js +21 -0
  6. package/dist/create.d.ts +6 -0
  7. package/dist/create.js +124 -0
  8. package/dist/doctor.d.ts +12 -0
  9. package/dist/doctor.js +111 -0
  10. package/dist/fs.d.ts +5 -0
  11. package/dist/fs.js +42 -0
  12. package/dist/git.d.ts +1 -0
  13. package/dist/git.js +19 -0
  14. package/dist/hash.d.ts +2 -0
  15. package/dist/hash.js +8 -0
  16. package/dist/index.d.ts +4 -0
  17. package/dist/index.js +4 -0
  18. package/dist/manifest.d.ts +12 -0
  19. package/dist/manifest.js +31 -0
  20. package/dist/template.d.ts +2 -0
  21. package/dist/template.js +23 -0
  22. package/dist/upgrade.d.ts +13 -0
  23. package/dist/upgrade.js +97 -0
  24. package/package.json +41 -0
  25. package/template/.github/workflows/platform-conformance.yml +28 -0
  26. package/template/README.md +5 -0
  27. package/template/apps/api/.env.example +18 -0
  28. package/template/apps/api/README.md +3 -0
  29. package/template/apps/api/billing.config.ts +25 -0
  30. package/template/apps/api/drizzle.config.ts +7 -0
  31. package/template/apps/api/package.json +53 -0
  32. package/template/apps/api/scripts/generate-auth-schema.mjs +173 -0
  33. package/template/apps/api/scripts/migrate.mjs +15 -0
  34. package/template/apps/api/src/app.test.ts +479 -0
  35. package/template/apps/api/src/auth/api-keys.ts +131 -0
  36. package/template/apps/api/src/auth/authenticate.ts +166 -0
  37. package/template/apps/api/src/auth/better-auth.ts +38 -0
  38. package/template/apps/api/src/auth/oauth.ts +9 -0
  39. package/template/apps/api/src/auth/options.ts +69 -0
  40. package/template/apps/api/src/billing.ts +58 -0
  41. package/template/apps/api/src/conformance-adapter.ts +335 -0
  42. package/template/apps/api/src/db/migrate.ts +26 -0
  43. package/template/apps/api/src/db/migrations/0000_application.sql +72 -0
  44. package/template/apps/api/src/db/migrations/0000_auth.sql +178 -0
  45. package/template/apps/api/src/db/migrations/0001_billing.sql +234 -0
  46. package/template/apps/api/src/db/schema/auth.generated.ts +185 -0
  47. package/template/apps/api/src/db/schema/billing.generated.ts +447 -0
  48. package/template/apps/api/src/db/schema/index.ts +3 -0
  49. package/template/apps/api/src/db/schema/notes.ts +31 -0
  50. package/template/apps/api/src/db/schema/tenants.ts +83 -0
  51. package/template/apps/api/src/deps.ts +12 -0
  52. package/template/apps/api/src/dispatch.ts +476 -0
  53. package/template/apps/api/src/express-app.ts +161 -0
  54. package/template/apps/api/src/invitations.ts +217 -0
  55. package/template/apps/api/src/logger.ts +26 -0
  56. package/template/apps/api/src/main.ts +98 -0
  57. package/template/apps/api/src/mcp.ts +127 -0
  58. package/template/apps/api/src/notes.ts +251 -0
  59. package/template/apps/api/src/openapi.ts +12 -0
  60. package/template/apps/api/src/permissions.ts +35 -0
  61. package/template/apps/api/src/runtime.ts +167 -0
  62. package/template/apps/api/src/seed.ts +340 -0
  63. package/template/apps/api/src/tenancy.ts +116 -0
  64. package/template/apps/api/src/types.ts +20 -0
  65. package/template/apps/api/src/worker.ts +57 -0
  66. package/template/apps/api/tsconfig.json +14 -0
  67. package/template/apps/web/.env.example +7 -0
  68. package/template/apps/web/app/api/[...path]/route.ts +51 -0
  69. package/template/apps/web/app/globals.css +156 -0
  70. package/template/apps/web/app/layout.tsx +34 -0
  71. package/template/apps/web/app/login/page.tsx +127 -0
  72. package/template/apps/web/app/notes/page.tsx +93 -0
  73. package/template/apps/web/app/page.tsx +80 -0
  74. package/template/apps/web/components/auth-gate.tsx +34 -0
  75. package/template/apps/web/components/browser-observability.tsx +53 -0
  76. package/template/apps/web/components/tenant-switcher.tsx +51 -0
  77. package/template/apps/web/lib/observability-config.ts +15 -0
  78. package/template/apps/web/next-env.d.ts +2 -0
  79. package/template/apps/web/next.config.ts +7 -0
  80. package/template/apps/web/package.json +26 -0
  81. package/template/apps/web/tsconfig.json +21 -0
  82. package/template/biome.template.json +50 -0
  83. package/template/docker-compose.yml +14 -0
  84. package/template/package.json +40 -0
  85. package/template/packages/api-contract/package.json +23 -0
  86. package/template/packages/api-contract/src/index.ts +256 -0
  87. package/template/packages/api-contract/src/mcp-parity.ts +158 -0
  88. package/template/packages/api-contract/tsconfig.json +11 -0
  89. package/template/patches/@anatine__zod-openapi@1.14.2.patch +14 -0
  90. package/template/tooling/platform/config.ts +2 -0
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@codelitdev/platform-cli",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Create, doctor, and upgrade CodeLit Platform products",
5
+ "author": "CodeLit",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "bin": {
9
+ "codelit-platform": "./dist/bin.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "template"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json && bun -e \"import('node:fs').then(fs=>{fs.rmSync('template',{recursive:true,force:true});fs.cpSync('../../templates/saas-product','template',{recursive:true})})\"",
24
+ "test": "bun test --timeout 60000 src --path-ignore-patterns=**/template/**",
25
+ "test:packed": "bun scripts/packed-consumer.mjs",
26
+ "typecheck": "tsc -p tsconfig.test.json --noEmit",
27
+ "lint": "biome lint ."
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "tag": "latest"
32
+ },
33
+ "dependencies": {
34
+ "@codelitdev/platform-preset": "0.1.0-alpha.0"
35
+ },
36
+ "devDependencies": {
37
+ "@types/bun": "^1.4.1",
38
+ "@types/node": "^22.14.1",
39
+ "typescript": "^5.9.3"
40
+ }
41
+ }
@@ -0,0 +1,28 @@
1
+ name: Platform conformance
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches: [main]
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ verify:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
16
+ - uses: oven-sh/setup-bun@v2
17
+ with:
18
+ bun-version: 1.4.1
19
+ # `platform-cli create` intentionally does not resolve dependencies.
20
+ # Bootstrap the product lockfile on its first run; all subsequent CI
21
+ # installs are immutable and use the frozen lockfile below.
22
+ - run: bun install
23
+ if: ${{ !hashFiles('bun.lock') }}
24
+ - run: bun install --frozen-lockfile
25
+ - run: bun run --filter "*/api" check:drift
26
+ - run: bun run test
27
+ - run: bun run typecheck
28
+ - run: bun run build
@@ -0,0 +1,5 @@
1
+ # __PRODUCT_NAME__
2
+
3
+ Generated from CodeLit Platform `templates/saas-product`. Product-owned
4
+ application code lives in `apps/**` and `packages/api-contract/**`. Managed
5
+ Platform files live under `tooling/platform/**`.
@@ -0,0 +1,18 @@
1
+ # API runtime
2
+ PORT=4000
3
+ PUBLIC_API_URL=http://127.0.0.1:4000
4
+ WEB_ORIGIN=http://localhost:3000
5
+ NODE_ENV=development
6
+ DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/__PRODUCT_SLUG__
7
+
8
+ # Generate local random values; AUTH_SECRET must be at least 32 characters.
9
+ AUTH_SECRET=replace-with-a-random-secret-at-least-32-characters
10
+ API_KEY_PEPPER=replace-with-a-random-pepper-at-least-32-characters
11
+ SEED=1
12
+
13
+ # Optional observability integrations.
14
+ LOG_LEVEL=info
15
+ # POSTHOG_API_KEY=
16
+ # POSTHOG_HOST=https://app.posthog.com
17
+ # OTLP_LOGS_ENDPOINT=
18
+ # OTLP_LOGS_AUTHORIZATION=
@@ -0,0 +1,3 @@
1
+ # __PRODUCT_NAME__ API
2
+
3
+ Product-owned application services live here.
@@ -0,0 +1,25 @@
1
+ import { defineBillingConfig } from "@codelitdev/billing/config";
2
+
3
+ export default defineBillingConfig({
4
+ dialect: "postgresql",
5
+ adapter: "drizzle",
6
+ output: "./src/db/schema/billing.generated.ts",
7
+ billableEntity: {
8
+ modelName: "tenant",
9
+ tableImport: "./tenants",
10
+ tableExport: "tenants",
11
+ idColumn: "id",
12
+ idType: "uuid",
13
+ onDelete: "restrict",
14
+ },
15
+ payer: {
16
+ modelName: "user",
17
+ tableImport: "./auth.generated",
18
+ tableExport: "user",
19
+ idColumn: "id",
20
+ idType: "text",
21
+ onDelete: "restrict",
22
+ },
23
+ planIds: ["pro", "business"],
24
+ requiredOfferKeys: ["pro_month", "pro_year", "business_month", "business_year"],
25
+ });
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from "drizzle-kit";
2
+
3
+ export default defineConfig({
4
+ schema: "./src/db/schema/index.ts",
5
+ out: "./src/db/migrations",
6
+ dialect: "postgresql",
7
+ });
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@__PRODUCT_SLUG__/api",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "bun --watch src/main.ts",
8
+ "build": "tsc -p tsconfig.json --noEmit",
9
+ "typecheck": "tsc -p tsconfig.json --noEmit",
10
+ "test": "bun test --timeout 60000 src",
11
+ "lint": "biome lint .",
12
+ "start": "bun src/main.ts",
13
+ "worker": "bun src/worker.ts",
14
+ "generate:billing": "codelit-billing generate --config billing.config.ts",
15
+ "generate:auth-schema": "bun scripts/generate-auth-schema.mjs",
16
+ "check:billing-schema": "codelit-billing generate --check --config billing.config.ts",
17
+ "check:auth-schema": "bun scripts/generate-auth-schema.mjs --check",
18
+ "check:drift": "bun run check:billing-schema && bun run check:auth-schema",
19
+ "migrate": "bun scripts/migrate.mjs",
20
+ "pretest": "bun run check:auth-schema"
21
+ },
22
+ "dependencies": {
23
+ "@better-auth/core": "1.7.2",
24
+ "@codelitdev/billing": "workspace:*",
25
+ "@codelitdev/oauth-server-kit": "workspace:*",
26
+ "@codelitdev/mcp-server-kit": "workspace:*",
27
+ "@codelitdev/platform-conformance": "workspace:*",
28
+ "@codelitdev/observability": "workspace:*",
29
+ "@better-auth/oauth-provider": "1.7.2",
30
+ "@better-auth/utils": "0.4.2",
31
+ "@better-fetch/fetch": "1.3.1",
32
+ "@ts-rest/express": "3.52.1",
33
+ "@ts-rest/open-api": "^3.52.1",
34
+ "@codelitdev/platform": "workspace:*",
35
+ "@__PRODUCT_SLUG__/api-contract": "workspace:*",
36
+ "@types/pg": "^8.23.1",
37
+ "better-call": "1.4.0",
38
+ "better-auth": "1.7.2",
39
+ "drizzle-orm": "^0.45.2",
40
+ "express": "^4.21.2",
41
+ "pg": "^8.23.0",
42
+ "pino": "^9.6.0",
43
+ "zod": "^3.25.76"
44
+ },
45
+ "devDependencies": {
46
+ "@electric-sql/pglite": "^0.2.17",
47
+ "@types/express": "^4.17.21",
48
+ "@types/node": "^22.14.1",
49
+ "drizzle-kit": "0.31.4",
50
+ "typescript": "^5.9.3",
51
+ "@types/bun": "^1.4.1"
52
+ }
53
+ }
@@ -0,0 +1,173 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { oauthProvider } from "@better-auth/oauth-provider";
6
+ import { createOAuthProviderOptions } from "@codelitdev/oauth-server-kit/better-auth";
7
+ import { getSchema } from "better-auth/db";
8
+ import { emailOTP } from "better-auth/plugins/email-otp";
9
+ import { jwt } from "better-auth/plugins/jwt";
10
+
11
+ const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
12
+ const tsPath = path.join(root, "src/db/schema/auth.generated.ts");
13
+ const sqlPath = path.join(root, "src/db/migrations/0000_auth.sql");
14
+ const check = process.argv.includes("--check");
15
+
16
+ const publicApiUrl = "http://127.0.0.1:4000";
17
+ const options = {
18
+ appName: "__PRODUCT_NAME__",
19
+ baseURL: publicApiUrl,
20
+ basePath: "/api/auth",
21
+ secret: "schema-generation-secret-at-least-32-chars",
22
+ emailAndPassword: { enabled: true },
23
+ plugins: [
24
+ jwt(),
25
+ emailOTP({
26
+ async sendVerificationOTP() {},
27
+ }),
28
+ oauthProvider(
29
+ createOAuthProviderOptions({
30
+ loginPage: `${publicApiUrl}/oauth/login`,
31
+ consentPage: `${publicApiUrl}/oauth/consent`,
32
+ scopes: ["openid", "profile", "email", "offline_access", "data:read"],
33
+ validAudiences: [`${publicApiUrl}/api`, `${publicApiUrl}/mcp`],
34
+ clientRegistrationDefaultScopes: ["openid", "profile", "email"],
35
+ clientRegistrationAllowedScopes: ["offline_access", "data:read"],
36
+ }),
37
+ ),
38
+ ],
39
+ };
40
+
41
+ const schema = getSchema(options);
42
+
43
+ function snake(value) {
44
+ return value
45
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
46
+ .replace(/([a-z\d])([A-Z])/g, "$1_$2")
47
+ .replace(/-/g, "_")
48
+ .toLowerCase();
49
+ }
50
+
51
+ function toCamel(name) {
52
+ return name.replace(/[_-](\w)/g, (_, ch) => ch.toUpperCase());
53
+ }
54
+
55
+ function quoteIdent(name) {
56
+ return `"${name.replaceAll('"', '""')}"`;
57
+ }
58
+
59
+ function drizzleType(sqlCol, field) {
60
+ const type = field.type;
61
+ if (type === "boolean") return `boolean("${sqlCol}")`;
62
+ if (type === "number") return `integer("${sqlCol}")`;
63
+ if (type === "date") return `timestamp("${sqlCol}", { withTimezone: true })`;
64
+ if (type === "json") return `jsonb("${sqlCol}")`;
65
+ if (type === "string[]" || (Array.isArray(type) && type[0] === "string")) {
66
+ return `text("${sqlCol}").array()`;
67
+ }
68
+ return `text("${sqlCol}")`;
69
+ }
70
+
71
+ function sqlType(field) {
72
+ const type = field.type;
73
+ if (type === "boolean") return "boolean";
74
+ if (type === "number") return "integer";
75
+ if (type === "date") return "timestamptz";
76
+ if (type === "json") return "jsonb";
77
+ if (type === "string[]" || (Array.isArray(type) && type[0] === "string")) {
78
+ return "text[]";
79
+ }
80
+ return "text";
81
+ }
82
+
83
+ const tables = Object.entries(schema)
84
+ .filter(([, table]) => !table.disableMigrations)
85
+ .sort((a, b) => {
86
+ const order = (a[1].order ?? 1000) - (b[1].order ?? 1000);
87
+ return order !== 0 ? order : a[0].localeCompare(b[0]);
88
+ });
89
+
90
+ const ts = [
91
+ "/**",
92
+ " * AUTO-GENERATED FILE. DO NOT EDIT.",
93
+ " * Generated by Better Auth getSchema (better-auth/db) from the reference",
94
+ " * Better Auth options (jwt + oauth-server-kit oauthProvider).",
95
+ " * Importing this module performs no DDL.",
96
+ " */",
97
+ 'import { boolean, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";',
98
+ "",
99
+ ];
100
+ const sql = ["-- AUTO-GENERATED by scripts/generate-auth-schema.mjs. DO NOT EDIT."];
101
+
102
+ for (const [modelName, table] of tables) {
103
+ const exportName = toCamel(modelName);
104
+ const tableSql = snake(modelName);
105
+ ts.push(`export const ${exportName} = pgTable("${tableSql}", {`);
106
+ ts.push(' id: text("id").primaryKey(),');
107
+ if (sql.length > 1) sql.push("--> statement-breakpoint");
108
+ sql.push(`CREATE TABLE IF NOT EXISTS ${quoteIdent(tableSql)} (`);
109
+ const sqlCols = [` id text PRIMARY KEY`];
110
+ for (const [key, field] of Object.entries(table.fields)) {
111
+ const sqlCol = snake(field.fieldName || key);
112
+ let col = drizzleType(sqlCol, field);
113
+ let sqlDef = ` ${quoteIdent(sqlCol)} ${sqlType(field)}`;
114
+ if (field.required === true) {
115
+ col += ".notNull()";
116
+ sqlDef += " NOT NULL";
117
+ }
118
+ if (field.unique) {
119
+ col += ".unique()";
120
+ sqlDef += " UNIQUE";
121
+ }
122
+ if (field.references) {
123
+ const targetTable = snake(field.references.model);
124
+ const targetField = snake(field.references.field || "id");
125
+ const onDelete = field.references.onDelete ?? "cascade";
126
+ const targetExport = toCamel(field.references.model);
127
+ const targetProp = toCamel(field.references.field || "id");
128
+ col += `.references(() => ${targetExport}.${targetProp}, { onDelete: "${onDelete}" })`;
129
+ sqlDef += ` REFERENCES ${quoteIdent(targetTable)}(${quoteIdent(targetField)}) ON DELETE ${onDelete.toUpperCase()}`;
130
+ }
131
+ ts.push(` ${toCamel(key)}: ${col},`);
132
+ sqlCols.push(sqlDef);
133
+ }
134
+ ts.push("});");
135
+ ts.push("");
136
+ sql.push(`${sqlCols.join(",\n")}`);
137
+ sql.push(");");
138
+ }
139
+
140
+ const tsSource = `${ts.join("\n").trimEnd()}\n`;
141
+ const sqlSource = `${sql.join("\n")}\n`;
142
+
143
+ function writeOrCheck(filePath, source) {
144
+ let existing;
145
+ try {
146
+ existing = readFileSync(filePath, "utf8");
147
+ } catch {
148
+ // A missing generated file is reported as drift below.
149
+ }
150
+ if (check) {
151
+ if (existing !== source) {
152
+ const fp = (value) => createHash("sha256").update(value).digest("hex");
153
+ process.stderr.write(
154
+ `auth schema drift: ${filePath}\ncommitted=${existing ? fp(existing) : "missing"} generated=${fp(source)}\n`,
155
+ );
156
+ process.exitCode = 1;
157
+ return false;
158
+ }
159
+ process.stdout.write(`ok ${filePath}\n`);
160
+ return true;
161
+ }
162
+ if (existing !== source) {
163
+ writeFileSync(filePath, source);
164
+ process.stdout.write(`wrote ${filePath}\n`);
165
+ } else {
166
+ process.stdout.write(`unchanged ${filePath}\n`);
167
+ }
168
+ return true;
169
+ }
170
+
171
+ const tsOk = writeOrCheck(tsPath, tsSource);
172
+ const sqlOk = writeOrCheck(sqlPath, sqlSource);
173
+ if (check && (!tsOk || !sqlOk)) process.exit(1);
@@ -0,0 +1,15 @@
1
+ import { Client } from "pg";
2
+ import { applyMigrations } from "../src/db/migrate.ts";
3
+
4
+ const databaseUrl = process.env.DATABASE_URL;
5
+ if (!databaseUrl) throw new Error("DATABASE_URL_REQUIRED");
6
+ const client = new Client({ connectionString: databaseUrl });
7
+ await client.connect();
8
+ await applyMigrations((sql) => client.query(sql));
9
+ const tables = await client.query(
10
+ "select tablename from pg_tables where schemaname = 'public' order by tablename",
11
+ );
12
+ process.stdout.write(
13
+ `${JSON.stringify({ migrated: true, tables: tables.rows.map((row) => row.tablename) })}\n`,
14
+ );
15
+ await client.end();